controller.go 21 KB

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