controller.go 25 KB

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