controller.go 26 KB

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