controller.go 20 KB

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