controller.go 20 KB

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