controller.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. /*
  2. Package libnetwork provides the basic functionality and extension points to
  3. create network namespaces and allocate interfaces for containers to use.
  4. networkType := "bridge"
  5. // Create a new controller instance
  6. driverOptions := options.Generic{}
  7. genericOption := make(map[string]interface{})
  8. genericOption[netlabel.GenericData] = driverOptions
  9. controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
  10. if err != nil {
  11. return
  12. }
  13. // Create a network for containers to join.
  14. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make use of
  15. network, err := controller.NewNetwork(networkType, "network1", "")
  16. if err != nil {
  17. return
  18. }
  19. // For each new container: allocate IP and interfaces. The returned network
  20. // settings will be used for container infos (inspect and such), as well as
  21. // iptables rules for port publishing. This info is contained or accessible
  22. // from the returned endpoint.
  23. ep, err := network.CreateEndpoint("Endpoint1")
  24. if err != nil {
  25. return
  26. }
  27. // Create the sandbox for the container.
  28. // NewSandbox accepts Variadic optional arguments which libnetwork can use.
  29. sbx, err := controller.NewSandbox("container1",
  30. libnetwork.OptionHostname("test"),
  31. libnetwork.OptionDomainname("docker.io"))
  32. // A sandbox can join the endpoint via the join api.
  33. err = ep.Join(sbx)
  34. if err != nil {
  35. return
  36. }
  37. */
  38. package libnetwork
  39. import (
  40. "container/heap"
  41. "fmt"
  42. "net"
  43. "strings"
  44. "sync"
  45. log "github.com/Sirupsen/logrus"
  46. "github.com/docker/docker/pkg/discovery"
  47. "github.com/docker/docker/pkg/plugins"
  48. "github.com/docker/docker/pkg/stringid"
  49. "github.com/docker/libnetwork/config"
  50. "github.com/docker/libnetwork/datastore"
  51. "github.com/docker/libnetwork/discoverapi"
  52. "github.com/docker/libnetwork/driverapi"
  53. "github.com/docker/libnetwork/drvregistry"
  54. "github.com/docker/libnetwork/hostdiscovery"
  55. "github.com/docker/libnetwork/ipamapi"
  56. "github.com/docker/libnetwork/netlabel"
  57. "github.com/docker/libnetwork/osl"
  58. "github.com/docker/libnetwork/types"
  59. )
  60. // NetworkController provides the interface for controller instance which manages
  61. // networks.
  62. type NetworkController interface {
  63. // ID provides an unique identity for the controller
  64. ID() string
  65. // Config method returns the bootup configuration for the controller
  66. Config() config.Config
  67. // Create a new network. The options parameter carries network specific options.
  68. NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
  69. // Networks returns the list of Network(s) managed by this controller.
  70. Networks() []Network
  71. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  72. WalkNetworks(walker NetworkWalker)
  73. // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
  74. NetworkByName(name string) (Network, error)
  75. // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
  76. NetworkByID(id string) (Network, error)
  77. // NewSandbox cretes a new network sandbox for the passed container id
  78. NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
  79. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  80. Sandboxes() []Sandbox
  81. // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  82. WalkSandboxes(walker SandboxWalker)
  83. // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
  84. SandboxByID(id string) (Sandbox, error)
  85. // SandboxDestroy destroys a sandbox given a container ID
  86. SandboxDestroy(id string) error
  87. // Stop network controller
  88. Stop()
  89. // ReloadCondfiguration updates the controller configuration
  90. ReloadConfiguration(cfgOptions ...config.Option) error
  91. }
  92. // NetworkWalker is a client provided function which will be used to walk the Networks.
  93. // When the function returns true, the walk will stop.
  94. type NetworkWalker func(nw Network) bool
  95. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  96. // When the function returns true, the walk will stop.
  97. type SandboxWalker func(sb Sandbox) bool
  98. type sandboxTable map[string]*sandbox
  99. type controller struct {
  100. id string
  101. drvRegistry *drvregistry.DrvRegistry
  102. sandboxes sandboxTable
  103. cfg *config.Config
  104. stores []datastore.DataStore
  105. discovery hostdiscovery.HostDiscovery
  106. extKeyListener net.Listener
  107. watchCh chan *endpoint
  108. unWatchCh chan *endpoint
  109. svcDb map[string]svcInfo
  110. nmap map[string]*netWatch
  111. defOsSbox osl.Sandbox
  112. sboxOnce sync.Once
  113. sync.Mutex
  114. }
  115. type initializer struct {
  116. fn drvregistry.InitFunc
  117. ntype string
  118. }
  119. // New creates a new instance of network controller.
  120. func New(cfgOptions ...config.Option) (NetworkController, error) {
  121. c := &controller{
  122. id: stringid.GenerateRandomID(),
  123. cfg: config.ParseConfigOptions(cfgOptions...),
  124. sandboxes: sandboxTable{},
  125. svcDb: make(map[string]svcInfo),
  126. }
  127. if err := c.initStores(); err != nil {
  128. return nil, err
  129. }
  130. drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil)
  131. if err != nil {
  132. return nil, err
  133. }
  134. for _, i := range getInitializers() {
  135. var dcfg map[string]interface{}
  136. // External plugins don't need config passed through daemon. They can
  137. // bootstrap themselves
  138. if i.ntype != "remote" {
  139. dcfg = c.makeDriverConfig(i.ntype)
  140. }
  141. if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil {
  142. return nil, err
  143. }
  144. }
  145. c.drvRegistry = drvRegistry
  146. if c.cfg != nil && c.cfg.Cluster.Watcher != nil {
  147. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  148. // Failing to initialize discovery is a bad situation to be in.
  149. // But it cannot fail creating the Controller
  150. log.Errorf("Failed to Initialize Discovery : %v", err)
  151. }
  152. }
  153. c.sandboxCleanup()
  154. c.cleanupLocalEndpoints()
  155. c.networkCleanup()
  156. if err := c.startExternalKeyListener(); err != nil {
  157. return nil, err
  158. }
  159. return c, nil
  160. }
  161. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  162. if c.cfg == nil {
  163. return nil
  164. }
  165. config := make(map[string]interface{})
  166. for _, label := range c.cfg.Daemon.Labels {
  167. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  168. continue
  169. }
  170. config[netlabel.Key(label)] = netlabel.Value(label)
  171. }
  172. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  173. if ok {
  174. for k, v := range drvCfg.(map[string]interface{}) {
  175. config[k] = v
  176. }
  177. }
  178. for k, v := range c.cfg.Scopes {
  179. if !v.IsValid() {
  180. continue
  181. }
  182. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  183. Scope: k,
  184. Provider: v.Client.Provider,
  185. Address: v.Client.Address,
  186. Config: v.Client.Config,
  187. }
  188. }
  189. return config
  190. }
  191. var procReloadConfig = make(chan (bool), 1)
  192. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  193. procReloadConfig <- true
  194. defer func() { <-procReloadConfig }()
  195. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  196. // Refuse the configuration if it alters an existing datastore client configuration.
  197. update := false
  198. cfg := config.ParseConfigOptions(cfgOptions...)
  199. for s := range c.cfg.Scopes {
  200. if _, ok := cfg.Scopes[s]; !ok {
  201. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  202. }
  203. }
  204. for s, nSCfg := range cfg.Scopes {
  205. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  206. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  207. eSCfg.Client.Address != nSCfg.Client.Address {
  208. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  209. }
  210. } else {
  211. if err := c.initScopedStore(s, nSCfg); err != nil {
  212. return err
  213. }
  214. update = true
  215. }
  216. }
  217. if !update {
  218. return nil
  219. }
  220. c.Lock()
  221. c.cfg = cfg
  222. c.Unlock()
  223. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  224. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  225. log.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  226. }
  227. }
  228. var dsConfig *discoverapi.DatastoreConfigData
  229. for scope, sCfg := range cfg.Scopes {
  230. if scope == datastore.LocalScope || !sCfg.IsValid() {
  231. continue
  232. }
  233. dsConfig = &discoverapi.DatastoreConfigData{
  234. Scope: scope,
  235. Provider: sCfg.Client.Provider,
  236. Address: sCfg.Client.Address,
  237. Config: sCfg.Client.Config,
  238. }
  239. break
  240. }
  241. if dsConfig == nil {
  242. return nil
  243. }
  244. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  245. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  246. if err != nil {
  247. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  248. }
  249. return false
  250. })
  251. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  252. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  253. if err != nil {
  254. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  255. }
  256. return false
  257. })
  258. return nil
  259. }
  260. func (c *controller) ID() string {
  261. return c.id
  262. }
  263. func (c *controller) validateHostDiscoveryConfig() bool {
  264. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  265. return false
  266. }
  267. return true
  268. }
  269. func (c *controller) clusterHostID() string {
  270. c.Lock()
  271. defer c.Unlock()
  272. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  273. return ""
  274. }
  275. addr := strings.Split(c.cfg.Cluster.Address, ":")
  276. return addr[0]
  277. }
  278. func (c *controller) isNodeAlive(node string) bool {
  279. if c.discovery == nil {
  280. return false
  281. }
  282. nodes := c.discovery.Fetch()
  283. for _, n := range nodes {
  284. if n.String() == node {
  285. return true
  286. }
  287. }
  288. return false
  289. }
  290. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  291. if c.cfg == nil {
  292. return fmt.Errorf("discovery initialization requires a valid configuration")
  293. }
  294. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  295. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  296. }
  297. func (c *controller) activeCallback() {
  298. ds := c.getStore(datastore.GlobalScope)
  299. if ds != nil && !ds.Active() {
  300. ds.RestartWatch()
  301. }
  302. }
  303. func (c *controller) hostJoinCallback(nodes []net.IP) {
  304. c.processNodeDiscovery(nodes, true)
  305. }
  306. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  307. c.processNodeDiscovery(nodes, false)
  308. }
  309. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  310. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  311. c.pushNodeDiscovery(driver, capability, nodes, add)
  312. return false
  313. })
  314. }
  315. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  316. var self net.IP
  317. if c.cfg != nil {
  318. addr := strings.Split(c.cfg.Cluster.Address, ":")
  319. self = net.ParseIP(addr[0])
  320. }
  321. if d == nil || cap.DataScope != datastore.GlobalScope || nodes == nil {
  322. return
  323. }
  324. for _, node := range nodes {
  325. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  326. var err error
  327. if add {
  328. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  329. } else {
  330. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  331. }
  332. if err != nil {
  333. log.Debugf("discovery notification error : %v", err)
  334. }
  335. }
  336. }
  337. func (c *controller) Config() config.Config {
  338. c.Lock()
  339. defer c.Unlock()
  340. if c.cfg == nil {
  341. return config.Config{}
  342. }
  343. return *c.cfg
  344. }
  345. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  346. c.Lock()
  347. hd := c.discovery
  348. c.Unlock()
  349. if hd != nil {
  350. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  351. }
  352. return nil
  353. }
  354. // NewNetwork creates a new network of the specified network type. The options
  355. // are network specific and modeled in a generic way.
  356. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  357. if !config.IsValidName(name) {
  358. return nil, ErrInvalidName(name)
  359. }
  360. if id == "" {
  361. id = stringid.GenerateRandomID()
  362. }
  363. // Construct the network object
  364. network := &network{
  365. name: name,
  366. networkType: networkType,
  367. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  368. ipamType: ipamapi.DefaultIPAM,
  369. id: id,
  370. ctrlr: c,
  371. persist: true,
  372. drvOnce: &sync.Once{},
  373. }
  374. network.processOptions(options...)
  375. // Make sure we have a driver available for this network type
  376. // before we allocate anything.
  377. if _, err := network.driver(true); err != nil {
  378. return nil, err
  379. }
  380. err := network.ipamAllocate()
  381. if err != nil {
  382. return nil, err
  383. }
  384. defer func() {
  385. if err != nil {
  386. network.ipamRelease()
  387. }
  388. }()
  389. if err = c.addNetwork(network); err != nil {
  390. return nil, err
  391. }
  392. defer func() {
  393. if err != nil {
  394. if e := network.deleteNetwork(); e != nil {
  395. log.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  396. }
  397. }
  398. }()
  399. // First store the endpoint count, then the network. To avoid to
  400. // end up with a datastore containing a network and not an epCnt,
  401. // in case of an ungraceful shutdown during this function call.
  402. epCnt := &endpointCnt{n: network}
  403. if err = c.updateToStore(epCnt); err != nil {
  404. return nil, err
  405. }
  406. defer func() {
  407. if err != nil {
  408. if e := c.deleteFromStore(epCnt); e != nil {
  409. log.Warnf("couldnt rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  410. }
  411. }
  412. }()
  413. network.epCnt = epCnt
  414. if err = c.updateToStore(network); err != nil {
  415. return nil, err
  416. }
  417. return network, nil
  418. }
  419. func (c *controller) addNetwork(n *network) error {
  420. d, err := n.driver(true)
  421. if err != nil {
  422. return err
  423. }
  424. // Create the network
  425. if err := d.CreateNetwork(n.id, n.generic, n.getIPData(4), n.getIPData(6)); err != nil {
  426. return err
  427. }
  428. return nil
  429. }
  430. func (c *controller) Networks() []Network {
  431. var list []Network
  432. networks, err := c.getNetworksFromStore()
  433. if err != nil {
  434. log.Error(err)
  435. }
  436. for _, n := range networks {
  437. if n.inDelete {
  438. continue
  439. }
  440. list = append(list, n)
  441. }
  442. return list
  443. }
  444. func (c *controller) WalkNetworks(walker NetworkWalker) {
  445. for _, n := range c.Networks() {
  446. if walker(n) {
  447. return
  448. }
  449. }
  450. }
  451. func (c *controller) NetworkByName(name string) (Network, error) {
  452. if name == "" {
  453. return nil, ErrInvalidName(name)
  454. }
  455. var n Network
  456. s := func(current Network) bool {
  457. if current.Name() == name {
  458. n = current
  459. return true
  460. }
  461. return false
  462. }
  463. c.WalkNetworks(s)
  464. if n == nil {
  465. return nil, ErrNoSuchNetwork(name)
  466. }
  467. return n, nil
  468. }
  469. func (c *controller) NetworkByID(id string) (Network, error) {
  470. if id == "" {
  471. return nil, ErrInvalidID(id)
  472. }
  473. n, err := c.getNetworkFromStore(id)
  474. if err != nil {
  475. return nil, ErrNoSuchNetwork(id)
  476. }
  477. return n, nil
  478. }
  479. // NewSandbox creates a new sandbox for the passed container id
  480. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  481. var err error
  482. if containerID == "" {
  483. return nil, types.BadRequestErrorf("invalid container ID")
  484. }
  485. var sb *sandbox
  486. c.Lock()
  487. for _, s := range c.sandboxes {
  488. if s.containerID == containerID {
  489. // If not a stub, then we already have a complete sandbox.
  490. if !s.isStub {
  491. c.Unlock()
  492. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, s)
  493. }
  494. // We already have a stub sandbox from the
  495. // store. Make use of it so that we don't lose
  496. // the endpoints from store but reset the
  497. // isStub flag.
  498. sb = s
  499. sb.isStub = false
  500. break
  501. }
  502. }
  503. c.Unlock()
  504. // Create sandbox and process options first. Key generation depends on an option
  505. if sb == nil {
  506. sb = &sandbox{
  507. id: stringid.GenerateRandomID(),
  508. containerID: containerID,
  509. endpoints: epHeap{},
  510. epPriority: map[string]int{},
  511. config: containerConfig{},
  512. controller: c,
  513. }
  514. }
  515. heap.Init(&sb.endpoints)
  516. sb.processOptions(options...)
  517. if err = sb.setupResolutionFiles(); err != nil {
  518. return nil, err
  519. }
  520. if sb.config.useDefaultSandBox {
  521. c.sboxOnce.Do(func() {
  522. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false)
  523. })
  524. if err != nil {
  525. c.sboxOnce = sync.Once{}
  526. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  527. }
  528. sb.osSbox = c.defOsSbox
  529. }
  530. if sb.osSbox == nil && !sb.config.useExternalKey {
  531. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  532. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  533. }
  534. }
  535. c.Lock()
  536. c.sandboxes[sb.id] = sb
  537. c.Unlock()
  538. defer func() {
  539. if err != nil {
  540. c.Lock()
  541. delete(c.sandboxes, sb.id)
  542. c.Unlock()
  543. }
  544. }()
  545. err = sb.storeUpdate()
  546. if err != nil {
  547. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  548. }
  549. return sb, nil
  550. }
  551. func (c *controller) Sandboxes() []Sandbox {
  552. c.Lock()
  553. defer c.Unlock()
  554. list := make([]Sandbox, 0, len(c.sandboxes))
  555. for _, s := range c.sandboxes {
  556. // Hide stub sandboxes from libnetwork users
  557. if s.isStub {
  558. continue
  559. }
  560. list = append(list, s)
  561. }
  562. return list
  563. }
  564. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  565. for _, sb := range c.Sandboxes() {
  566. if walker(sb) {
  567. return
  568. }
  569. }
  570. }
  571. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  572. if id == "" {
  573. return nil, ErrInvalidID(id)
  574. }
  575. c.Lock()
  576. s, ok := c.sandboxes[id]
  577. c.Unlock()
  578. if !ok {
  579. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  580. }
  581. return s, nil
  582. }
  583. // SandboxDestroy destroys a sandbox given a container ID
  584. func (c *controller) SandboxDestroy(id string) error {
  585. var sb *sandbox
  586. c.Lock()
  587. for _, s := range c.sandboxes {
  588. if s.containerID == id {
  589. sb = s
  590. break
  591. }
  592. }
  593. c.Unlock()
  594. // It is not an error if sandbox is not available
  595. if sb == nil {
  596. return nil
  597. }
  598. return sb.Delete()
  599. }
  600. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  601. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  602. return func(sb Sandbox) bool {
  603. if sb.ContainerID() == containerID {
  604. *out = sb
  605. return true
  606. }
  607. return false
  608. }
  609. }
  610. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  611. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  612. return func(sb Sandbox) bool {
  613. if sb.Key() == key {
  614. *out = sb
  615. return true
  616. }
  617. return false
  618. }
  619. }
  620. func (c *controller) loadDriver(networkType string) error {
  621. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  622. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  623. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  624. if err != nil {
  625. if err == plugins.ErrNotFound {
  626. return types.NotFoundErrorf(err.Error())
  627. }
  628. return err
  629. }
  630. return nil
  631. }
  632. func (c *controller) loadIPAMDriver(name string) error {
  633. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  634. if err == plugins.ErrNotFound {
  635. return types.NotFoundErrorf(err.Error())
  636. }
  637. return err
  638. }
  639. return nil
  640. }
  641. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  642. id, cap := c.drvRegistry.IPAM(name)
  643. if id == nil {
  644. // Might be a plugin name. Try loading it
  645. if err := c.loadIPAMDriver(name); err != nil {
  646. return nil, nil, err
  647. }
  648. // Now that we resolved the plugin, try again looking up the registry
  649. id, cap = c.drvRegistry.IPAM(name)
  650. if id == nil {
  651. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  652. }
  653. }
  654. return id, cap, nil
  655. }
  656. func (c *controller) Stop() {
  657. c.closeStores()
  658. c.stopExternalKeyListener()
  659. osl.GC()
  660. }