controller.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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/cluster"
  50. "github.com/docker/libnetwork/config"
  51. "github.com/docker/libnetwork/datastore"
  52. "github.com/docker/libnetwork/discoverapi"
  53. "github.com/docker/libnetwork/driverapi"
  54. "github.com/docker/libnetwork/drvregistry"
  55. "github.com/docker/libnetwork/hostdiscovery"
  56. "github.com/docker/libnetwork/ipamapi"
  57. "github.com/docker/libnetwork/netlabel"
  58. "github.com/docker/libnetwork/osl"
  59. "github.com/docker/libnetwork/types"
  60. )
  61. // NetworkController provides the interface for controller instance which manages
  62. // networks.
  63. type NetworkController interface {
  64. // ID provides a unique identity for the controller
  65. ID() string
  66. // Config method returns the bootup configuration for the controller
  67. Config() config.Config
  68. // Create a new network. The options parameter carries network specific options.
  69. NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error)
  70. // Networks returns the list of Network(s) managed by this controller.
  71. Networks() []Network
  72. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  73. WalkNetworks(walker NetworkWalker)
  74. // NetworkByName returns the Network which has the passed name. If not found, the error ErrNoSuchNetwork is returned.
  75. NetworkByName(name string) (Network, error)
  76. // NetworkByID returns the Network which has the passed id. If not found, the error ErrNoSuchNetwork is returned.
  77. NetworkByID(id string) (Network, error)
  78. // NewSandbox creates a new network sandbox for the passed container id
  79. NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error)
  80. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  81. Sandboxes() []Sandbox
  82. // WlakSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  83. WalkSandboxes(walker SandboxWalker)
  84. // SandboxByID returns the Sandbox which has the passed id. If not found, a types.NotFoundError is returned.
  85. SandboxByID(id string) (Sandbox, error)
  86. // SandboxDestroy destroys a sandbox given a container ID
  87. SandboxDestroy(id string) error
  88. // Stop network controller
  89. Stop()
  90. // ReloadCondfiguration updates the controller configuration
  91. ReloadConfiguration(cfgOptions ...config.Option) error
  92. // SetClusterProvider sets cluster provider
  93. SetClusterProvider(provider cluster.Provider)
  94. // Wait for agent initialization complete in libnetwork controller
  95. AgentInitWait()
  96. // SetKeys configures the encryption key for gossip and overlay data path
  97. SetKeys(keys []*types.EncryptionKey) error
  98. }
  99. // NetworkWalker is a client provided function which will be used to walk the Networks.
  100. // When the function returns true, the walk will stop.
  101. type NetworkWalker func(nw Network) bool
  102. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  103. // When the function returns true, the walk will stop.
  104. type SandboxWalker func(sb Sandbox) bool
  105. type sandboxTable map[string]*sandbox
  106. type controller struct {
  107. id string
  108. drvRegistry *drvregistry.DrvRegistry
  109. sandboxes sandboxTable
  110. cfg *config.Config
  111. stores []datastore.DataStore
  112. discovery hostdiscovery.HostDiscovery
  113. extKeyListener net.Listener
  114. watchCh chan *endpoint
  115. unWatchCh chan *endpoint
  116. svcRecords map[string]svcInfo
  117. nmap map[string]*netWatch
  118. serviceBindings map[serviceKey]*service
  119. defOsSbox osl.Sandbox
  120. ingressSandbox *sandbox
  121. sboxOnce sync.Once
  122. agent *agent
  123. agentInitDone chan struct{}
  124. keys []*types.EncryptionKey
  125. clusterConfigAvailable bool
  126. sync.Mutex
  127. }
  128. type initializer struct {
  129. fn drvregistry.InitFunc
  130. ntype string
  131. }
  132. // New creates a new instance of network controller.
  133. func New(cfgOptions ...config.Option) (NetworkController, error) {
  134. c := &controller{
  135. id: stringid.GenerateRandomID(),
  136. cfg: config.ParseConfigOptions(cfgOptions...),
  137. sandboxes: sandboxTable{},
  138. svcRecords: make(map[string]svcInfo),
  139. serviceBindings: make(map[serviceKey]*service),
  140. agentInitDone: make(chan struct{}),
  141. }
  142. if err := c.initStores(); err != nil {
  143. return nil, err
  144. }
  145. drvRegistry, err := drvregistry.New(c.getStore(datastore.LocalScope), c.getStore(datastore.GlobalScope), c.RegisterDriver, nil)
  146. if err != nil {
  147. return nil, err
  148. }
  149. for _, i := range getInitializers() {
  150. var dcfg map[string]interface{}
  151. // External plugins don't need config passed through daemon. They can
  152. // bootstrap themselves
  153. if i.ntype != "remote" {
  154. dcfg = c.makeDriverConfig(i.ntype)
  155. }
  156. if err := drvRegistry.AddDriver(i.ntype, i.fn, dcfg); err != nil {
  157. return nil, err
  158. }
  159. }
  160. if err = initIPAMDrivers(drvRegistry, nil, c.getStore(datastore.GlobalScope)); err != nil {
  161. return nil, err
  162. }
  163. c.drvRegistry = drvRegistry
  164. if c.cfg != nil && c.cfg.Cluster.Watcher != nil {
  165. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  166. // Failing to initialize discovery is a bad situation to be in.
  167. // But it cannot fail creating the Controller
  168. log.Errorf("Failed to Initialize Discovery : %v", err)
  169. }
  170. }
  171. c.WalkNetworks(populateSpecial)
  172. // Reserve pools first before doing cleanup. Otherwise the
  173. // cleanups of endpoint/network and sandbox below will
  174. // generate many unnecessary warnings
  175. c.reservePools()
  176. // Cleanup resources
  177. c.sandboxCleanup(c.cfg.ActiveSandboxes)
  178. c.cleanupLocalEndpoints()
  179. c.networkCleanup()
  180. if err := c.startExternalKeyListener(); err != nil {
  181. return nil, err
  182. }
  183. return c, nil
  184. }
  185. func (c *controller) SetClusterProvider(provider cluster.Provider) {
  186. c.Lock()
  187. defer c.Unlock()
  188. c.cfg.Daemon.ClusterProvider = provider
  189. if provider != nil {
  190. go c.clusterAgentInit()
  191. } else {
  192. c.cfg.Daemon.DisableProvider <- struct{}{}
  193. }
  194. }
  195. func isValidClusteringIP(addr string) bool {
  196. return addr != "" && !net.ParseIP(addr).IsLoopback() && !net.ParseIP(addr).IsUnspecified()
  197. }
  198. // libnetwork side of agent depends on the keys. On the first receipt of
  199. // keys setup the agent. For subsequent key set handle the key change
  200. func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
  201. c.Lock()
  202. existingKeys := c.keys
  203. clusterConfigAvailable := c.clusterConfigAvailable
  204. agent := c.agent
  205. c.Unlock()
  206. if len(existingKeys) == 0 {
  207. c.Lock()
  208. c.keys = keys
  209. c.Unlock()
  210. if agent != nil {
  211. return (fmt.Errorf("libnetwork agent setup without keys"))
  212. }
  213. if clusterConfigAvailable {
  214. return c.agentSetup()
  215. }
  216. log.Debugf("received encryption keys before cluster config")
  217. return nil
  218. }
  219. if agent == nil {
  220. c.Lock()
  221. c.keys = keys
  222. c.Unlock()
  223. return nil
  224. }
  225. if len(keys) < keyringSize {
  226. return c.handleKeyChangeV1(keys)
  227. }
  228. return c.handleKeyChange(keys)
  229. }
  230. func (c *controller) clusterAgentInit() {
  231. clusterProvider := c.cfg.Daemon.ClusterProvider
  232. for {
  233. select {
  234. case <-clusterProvider.ListenClusterEvents():
  235. if !c.isDistributedControl() {
  236. c.Lock()
  237. c.clusterConfigAvailable = true
  238. keys := c.keys
  239. c.Unlock()
  240. // agent initialization needs encyrption keys and bind/remote IP which
  241. // comes from the daemon cluster events
  242. if len(keys) > 0 {
  243. c.agentSetup()
  244. }
  245. }
  246. case <-c.cfg.Daemon.DisableProvider:
  247. c.Lock()
  248. c.clusterConfigAvailable = false
  249. c.agentInitDone = make(chan struct{})
  250. c.Unlock()
  251. c.agentClose()
  252. return
  253. }
  254. }
  255. }
  256. // AgentInitWait waits for agent initialization to be completed in the
  257. // controller.
  258. func (c *controller) AgentInitWait() {
  259. <-c.agentInitDone
  260. }
  261. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  262. if c.cfg == nil {
  263. return nil
  264. }
  265. config := make(map[string]interface{})
  266. for _, label := range c.cfg.Daemon.Labels {
  267. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  268. continue
  269. }
  270. config[netlabel.Key(label)] = netlabel.Value(label)
  271. }
  272. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  273. if ok {
  274. for k, v := range drvCfg.(map[string]interface{}) {
  275. config[k] = v
  276. }
  277. }
  278. for k, v := range c.cfg.Scopes {
  279. if !v.IsValid() {
  280. continue
  281. }
  282. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  283. Scope: k,
  284. Provider: v.Client.Provider,
  285. Address: v.Client.Address,
  286. Config: v.Client.Config,
  287. }
  288. }
  289. return config
  290. }
  291. var procReloadConfig = make(chan (bool), 1)
  292. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  293. procReloadConfig <- true
  294. defer func() { <-procReloadConfig }()
  295. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  296. // Refuse the configuration if it alters an existing datastore client configuration.
  297. update := false
  298. cfg := config.ParseConfigOptions(cfgOptions...)
  299. for s := range c.cfg.Scopes {
  300. if _, ok := cfg.Scopes[s]; !ok {
  301. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  302. }
  303. }
  304. for s, nSCfg := range cfg.Scopes {
  305. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  306. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  307. eSCfg.Client.Address != nSCfg.Client.Address {
  308. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  309. }
  310. } else {
  311. if err := c.initScopedStore(s, nSCfg); err != nil {
  312. return err
  313. }
  314. update = true
  315. }
  316. }
  317. if !update {
  318. return nil
  319. }
  320. var dsConfig *discoverapi.DatastoreConfigData
  321. for scope, sCfg := range cfg.Scopes {
  322. if scope == datastore.LocalScope || !sCfg.IsValid() {
  323. continue
  324. }
  325. dsConfig = &discoverapi.DatastoreConfigData{
  326. Scope: scope,
  327. Provider: sCfg.Client.Provider,
  328. Address: sCfg.Client.Address,
  329. Config: sCfg.Client.Config,
  330. }
  331. break
  332. }
  333. if dsConfig == nil {
  334. return nil
  335. }
  336. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  337. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  338. if err != nil {
  339. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  340. }
  341. return false
  342. })
  343. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  344. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  345. if err != nil {
  346. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  347. }
  348. return false
  349. })
  350. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  351. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  352. log.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  353. }
  354. }
  355. return nil
  356. }
  357. func (c *controller) ID() string {
  358. return c.id
  359. }
  360. func (c *controller) validateHostDiscoveryConfig() bool {
  361. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  362. return false
  363. }
  364. return true
  365. }
  366. func (c *controller) clusterHostID() string {
  367. c.Lock()
  368. defer c.Unlock()
  369. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  370. return ""
  371. }
  372. addr := strings.Split(c.cfg.Cluster.Address, ":")
  373. return addr[0]
  374. }
  375. func (c *controller) isNodeAlive(node string) bool {
  376. if c.discovery == nil {
  377. return false
  378. }
  379. nodes := c.discovery.Fetch()
  380. for _, n := range nodes {
  381. if n.String() == node {
  382. return true
  383. }
  384. }
  385. return false
  386. }
  387. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  388. if c.cfg == nil {
  389. return fmt.Errorf("discovery initialization requires a valid configuration")
  390. }
  391. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  392. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  393. }
  394. func (c *controller) activeCallback() {
  395. ds := c.getStore(datastore.GlobalScope)
  396. if ds != nil && !ds.Active() {
  397. ds.RestartWatch()
  398. }
  399. }
  400. func (c *controller) hostJoinCallback(nodes []net.IP) {
  401. c.processNodeDiscovery(nodes, true)
  402. }
  403. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  404. c.processNodeDiscovery(nodes, false)
  405. }
  406. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  407. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  408. c.pushNodeDiscovery(driver, capability, nodes, add)
  409. return false
  410. })
  411. }
  412. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  413. var self net.IP
  414. if c.cfg != nil {
  415. addr := strings.Split(c.cfg.Cluster.Address, ":")
  416. self = net.ParseIP(addr[0])
  417. }
  418. if d == nil || cap.DataScope != datastore.GlobalScope || nodes == nil {
  419. return
  420. }
  421. for _, node := range nodes {
  422. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  423. var err error
  424. if add {
  425. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  426. } else {
  427. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  428. }
  429. if err != nil {
  430. log.Debugf("discovery notification error : %v", err)
  431. }
  432. }
  433. }
  434. func (c *controller) Config() config.Config {
  435. c.Lock()
  436. defer c.Unlock()
  437. if c.cfg == nil {
  438. return config.Config{}
  439. }
  440. return *c.cfg
  441. }
  442. func (c *controller) isManager() bool {
  443. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  444. return false
  445. }
  446. return c.cfg.Daemon.ClusterProvider.IsManager()
  447. }
  448. func (c *controller) isAgent() bool {
  449. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  450. return false
  451. }
  452. return c.cfg.Daemon.ClusterProvider.IsAgent()
  453. }
  454. func (c *controller) isDistributedControl() bool {
  455. return !c.isManager() && !c.isAgent()
  456. }
  457. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  458. c.Lock()
  459. hd := c.discovery
  460. c.Unlock()
  461. if hd != nil {
  462. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  463. }
  464. c.agentDriverNotify(driver)
  465. return nil
  466. }
  467. // NewNetwork creates a new network of the specified network type. The options
  468. // are network specific and modeled in a generic way.
  469. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  470. if !config.IsValidName(name) {
  471. return nil, ErrInvalidName(name)
  472. }
  473. if id == "" {
  474. id = stringid.GenerateRandomID()
  475. }
  476. // Construct the network object
  477. network := &network{
  478. name: name,
  479. networkType: networkType,
  480. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  481. ipamType: ipamapi.DefaultIPAM,
  482. id: id,
  483. ctrlr: c,
  484. persist: true,
  485. drvOnce: &sync.Once{},
  486. }
  487. network.processOptions(options...)
  488. _, cap, err := network.resolveDriver(networkType, true)
  489. if err != nil {
  490. return nil, err
  491. }
  492. if cap.DataScope == datastore.GlobalScope && !c.isDistributedControl() && !network.dynamic {
  493. if c.isManager() {
  494. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  495. return nil, ManagerRedirectError(name)
  496. }
  497. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  498. }
  499. // Make sure we have a driver available for this network type
  500. // before we allocate anything.
  501. if _, err := network.driver(true); err != nil {
  502. return nil, err
  503. }
  504. err = network.ipamAllocate()
  505. if err != nil {
  506. return nil, err
  507. }
  508. defer func() {
  509. if err != nil {
  510. network.ipamRelease()
  511. }
  512. }()
  513. err = c.addNetwork(network)
  514. if err != nil {
  515. return nil, err
  516. }
  517. defer func() {
  518. if err != nil {
  519. if e := network.deleteNetwork(); e != nil {
  520. log.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  521. }
  522. }
  523. }()
  524. // First store the endpoint count, then the network. To avoid to
  525. // end up with a datastore containing a network and not an epCnt,
  526. // in case of an ungraceful shutdown during this function call.
  527. epCnt := &endpointCnt{n: network}
  528. if err = c.updateToStore(epCnt); err != nil {
  529. return nil, err
  530. }
  531. defer func() {
  532. if err != nil {
  533. if e := c.deleteFromStore(epCnt); e != nil {
  534. log.Warnf("couldnt rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  535. }
  536. }
  537. }()
  538. network.epCnt = epCnt
  539. if err = c.updateToStore(network); err != nil {
  540. return nil, err
  541. }
  542. joinCluster(network)
  543. return network, nil
  544. }
  545. var joinCluster NetworkWalker = func(nw Network) bool {
  546. n := nw.(*network)
  547. if err := n.joinCluster(); err != nil {
  548. log.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  549. }
  550. n.addDriverWatches()
  551. return false
  552. }
  553. func (c *controller) reservePools() {
  554. networks, err := c.getNetworksForScope(datastore.LocalScope)
  555. if err != nil {
  556. log.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  557. return
  558. }
  559. for _, n := range networks {
  560. if !doReplayPoolReserve(n) {
  561. continue
  562. }
  563. // Construct pseudo configs for the auto IP case
  564. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  565. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  566. if autoIPv4 {
  567. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  568. }
  569. if n.enableIPv6 && autoIPv6 {
  570. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  571. }
  572. // Account current network gateways
  573. for i, c := range n.ipamV4Config {
  574. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  575. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  576. }
  577. }
  578. for i, c := range n.ipamV6Config {
  579. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  580. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  581. }
  582. }
  583. // Reserve pools
  584. if err := n.ipamAllocate(); err != nil {
  585. log.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  586. }
  587. // Reserve existing endpoints' addresses
  588. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  589. if err != nil {
  590. log.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  591. continue
  592. }
  593. epl, err := n.getEndpointsFromStore()
  594. if err != nil {
  595. log.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  596. continue
  597. }
  598. for _, ep := range epl {
  599. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  600. log.Warnf("Failed to reserve current adress for endpoint %q (%s) on network %q (%s)",
  601. ep.Name(), ep.ID(), n.Name(), n.ID())
  602. }
  603. }
  604. }
  605. }
  606. func doReplayPoolReserve(n *network) bool {
  607. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  608. if err != nil {
  609. log.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  610. return false
  611. }
  612. return caps.RequiresRequestReplay
  613. }
  614. func (c *controller) addNetwork(n *network) error {
  615. d, err := n.driver(true)
  616. if err != nil {
  617. return err
  618. }
  619. // Create the network
  620. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  621. return err
  622. }
  623. return nil
  624. }
  625. func (c *controller) Networks() []Network {
  626. var list []Network
  627. networks, err := c.getNetworksFromStore()
  628. if err != nil {
  629. log.Error(err)
  630. }
  631. for _, n := range networks {
  632. if n.inDelete {
  633. continue
  634. }
  635. list = append(list, n)
  636. }
  637. return list
  638. }
  639. func (c *controller) WalkNetworks(walker NetworkWalker) {
  640. for _, n := range c.Networks() {
  641. if walker(n) {
  642. return
  643. }
  644. }
  645. }
  646. func (c *controller) NetworkByName(name string) (Network, error) {
  647. if name == "" {
  648. return nil, ErrInvalidName(name)
  649. }
  650. var n Network
  651. s := func(current Network) bool {
  652. if current.Name() == name {
  653. n = current
  654. return true
  655. }
  656. return false
  657. }
  658. c.WalkNetworks(s)
  659. if n == nil {
  660. return nil, ErrNoSuchNetwork(name)
  661. }
  662. return n, nil
  663. }
  664. func (c *controller) NetworkByID(id string) (Network, error) {
  665. if id == "" {
  666. return nil, ErrInvalidID(id)
  667. }
  668. n, err := c.getNetworkFromStore(id)
  669. if err != nil {
  670. return nil, ErrNoSuchNetwork(id)
  671. }
  672. return n, nil
  673. }
  674. // NewSandbox creates a new sandbox for the passed container id
  675. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  676. if containerID == "" {
  677. return nil, types.BadRequestErrorf("invalid container ID")
  678. }
  679. var sb *sandbox
  680. c.Lock()
  681. for _, s := range c.sandboxes {
  682. if s.containerID == containerID {
  683. // If not a stub, then we already have a complete sandbox.
  684. if !s.isStub {
  685. c.Unlock()
  686. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, s)
  687. }
  688. // We already have a stub sandbox from the
  689. // store. Make use of it so that we don't lose
  690. // the endpoints from store but reset the
  691. // isStub flag.
  692. sb = s
  693. sb.isStub = false
  694. break
  695. }
  696. }
  697. c.Unlock()
  698. // Create sandbox and process options first. Key generation depends on an option
  699. if sb == nil {
  700. sb = &sandbox{
  701. id: stringid.GenerateRandomID(),
  702. containerID: containerID,
  703. endpoints: epHeap{},
  704. epPriority: map[string]int{},
  705. populatedEndpoints: map[string]struct{}{},
  706. config: containerConfig{},
  707. controller: c,
  708. }
  709. }
  710. sBox = sb
  711. heap.Init(&sb.endpoints)
  712. sb.processOptions(options...)
  713. c.Lock()
  714. if sb.ingress && c.ingressSandbox != nil {
  715. c.Unlock()
  716. return nil, fmt.Errorf("ingress sandbox already present")
  717. }
  718. if sb.ingress {
  719. c.ingressSandbox = sb
  720. }
  721. c.Unlock()
  722. defer func() {
  723. if err != nil {
  724. c.Lock()
  725. if sb.ingress {
  726. c.ingressSandbox = nil
  727. }
  728. c.Unlock()
  729. }
  730. }()
  731. if err = sb.setupResolutionFiles(); err != nil {
  732. return nil, err
  733. }
  734. if sb.config.useDefaultSandBox {
  735. c.sboxOnce.Do(func() {
  736. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  737. })
  738. if err != nil {
  739. c.sboxOnce = sync.Once{}
  740. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  741. }
  742. sb.osSbox = c.defOsSbox
  743. }
  744. if sb.osSbox == nil && !sb.config.useExternalKey {
  745. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  746. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  747. }
  748. }
  749. c.Lock()
  750. c.sandboxes[sb.id] = sb
  751. c.Unlock()
  752. defer func() {
  753. if err != nil {
  754. c.Lock()
  755. delete(c.sandboxes, sb.id)
  756. c.Unlock()
  757. }
  758. }()
  759. err = sb.storeUpdate()
  760. if err != nil {
  761. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  762. }
  763. return sb, nil
  764. }
  765. func (c *controller) Sandboxes() []Sandbox {
  766. c.Lock()
  767. defer c.Unlock()
  768. list := make([]Sandbox, 0, len(c.sandboxes))
  769. for _, s := range c.sandboxes {
  770. // Hide stub sandboxes from libnetwork users
  771. if s.isStub {
  772. continue
  773. }
  774. list = append(list, s)
  775. }
  776. return list
  777. }
  778. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  779. for _, sb := range c.Sandboxes() {
  780. if walker(sb) {
  781. return
  782. }
  783. }
  784. }
  785. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  786. if id == "" {
  787. return nil, ErrInvalidID(id)
  788. }
  789. c.Lock()
  790. s, ok := c.sandboxes[id]
  791. c.Unlock()
  792. if !ok {
  793. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  794. }
  795. return s, nil
  796. }
  797. // SandboxDestroy destroys a sandbox given a container ID
  798. func (c *controller) SandboxDestroy(id string) error {
  799. var sb *sandbox
  800. c.Lock()
  801. for _, s := range c.sandboxes {
  802. if s.containerID == id {
  803. sb = s
  804. break
  805. }
  806. }
  807. c.Unlock()
  808. // It is not an error if sandbox is not available
  809. if sb == nil {
  810. return nil
  811. }
  812. return sb.Delete()
  813. }
  814. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  815. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  816. return func(sb Sandbox) bool {
  817. if sb.ContainerID() == containerID {
  818. *out = sb
  819. return true
  820. }
  821. return false
  822. }
  823. }
  824. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  825. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  826. return func(sb Sandbox) bool {
  827. if sb.Key() == key {
  828. *out = sb
  829. return true
  830. }
  831. return false
  832. }
  833. }
  834. func (c *controller) loadDriver(networkType string) error {
  835. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  836. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  837. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  838. if err != nil {
  839. if err == plugins.ErrNotFound {
  840. return types.NotFoundErrorf(err.Error())
  841. }
  842. return err
  843. }
  844. return nil
  845. }
  846. func (c *controller) loadIPAMDriver(name string) error {
  847. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  848. if err == plugins.ErrNotFound {
  849. return types.NotFoundErrorf(err.Error())
  850. }
  851. return err
  852. }
  853. return nil
  854. }
  855. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  856. id, cap := c.drvRegistry.IPAM(name)
  857. if id == nil {
  858. // Might be a plugin name. Try loading it
  859. if err := c.loadIPAMDriver(name); err != nil {
  860. return nil, nil, err
  861. }
  862. // Now that we resolved the plugin, try again looking up the registry
  863. id, cap = c.drvRegistry.IPAM(name)
  864. if id == nil {
  865. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  866. }
  867. }
  868. return id, cap, nil
  869. }
  870. func (c *controller) Stop() {
  871. c.closeStores()
  872. c.stopExternalKeyListener()
  873. osl.GC()
  874. }