controller.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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. // WalkSandboxes 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. c.Lock()
  321. c.cfg = cfg
  322. c.Unlock()
  323. var dsConfig *discoverapi.DatastoreConfigData
  324. for scope, sCfg := range cfg.Scopes {
  325. if scope == datastore.LocalScope || !sCfg.IsValid() {
  326. continue
  327. }
  328. dsConfig = &discoverapi.DatastoreConfigData{
  329. Scope: scope,
  330. Provider: sCfg.Client.Provider,
  331. Address: sCfg.Client.Address,
  332. Config: sCfg.Client.Config,
  333. }
  334. break
  335. }
  336. if dsConfig == nil {
  337. return nil
  338. }
  339. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  340. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  341. if err != nil {
  342. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  343. }
  344. return false
  345. })
  346. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  347. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  348. if err != nil {
  349. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  350. }
  351. return false
  352. })
  353. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  354. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  355. log.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  356. }
  357. }
  358. return nil
  359. }
  360. func (c *controller) ID() string {
  361. return c.id
  362. }
  363. func (c *controller) validateHostDiscoveryConfig() bool {
  364. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  365. return false
  366. }
  367. return true
  368. }
  369. func (c *controller) clusterHostID() string {
  370. c.Lock()
  371. defer c.Unlock()
  372. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  373. return ""
  374. }
  375. addr := strings.Split(c.cfg.Cluster.Address, ":")
  376. return addr[0]
  377. }
  378. func (c *controller) isNodeAlive(node string) bool {
  379. if c.discovery == nil {
  380. return false
  381. }
  382. nodes := c.discovery.Fetch()
  383. for _, n := range nodes {
  384. if n.String() == node {
  385. return true
  386. }
  387. }
  388. return false
  389. }
  390. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  391. if c.cfg == nil {
  392. return fmt.Errorf("discovery initialization requires a valid configuration")
  393. }
  394. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  395. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  396. }
  397. func (c *controller) activeCallback() {
  398. ds := c.getStore(datastore.GlobalScope)
  399. if ds != nil && !ds.Active() {
  400. ds.RestartWatch()
  401. }
  402. }
  403. func (c *controller) hostJoinCallback(nodes []net.IP) {
  404. c.processNodeDiscovery(nodes, true)
  405. }
  406. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  407. c.processNodeDiscovery(nodes, false)
  408. }
  409. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  410. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  411. c.pushNodeDiscovery(driver, capability, nodes, add)
  412. return false
  413. })
  414. }
  415. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  416. var self net.IP
  417. if c.cfg != nil {
  418. addr := strings.Split(c.cfg.Cluster.Address, ":")
  419. self = net.ParseIP(addr[0])
  420. }
  421. if d == nil || cap.DataScope != datastore.GlobalScope || nodes == nil {
  422. return
  423. }
  424. for _, node := range nodes {
  425. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  426. var err error
  427. if add {
  428. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  429. } else {
  430. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  431. }
  432. if err != nil {
  433. log.Debugf("discovery notification error : %v", err)
  434. }
  435. }
  436. }
  437. func (c *controller) Config() config.Config {
  438. c.Lock()
  439. defer c.Unlock()
  440. if c.cfg == nil {
  441. return config.Config{}
  442. }
  443. return *c.cfg
  444. }
  445. func (c *controller) isManager() bool {
  446. c.Lock()
  447. defer c.Unlock()
  448. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  449. return false
  450. }
  451. return c.cfg.Daemon.ClusterProvider.IsManager()
  452. }
  453. func (c *controller) isAgent() bool {
  454. c.Lock()
  455. defer c.Unlock()
  456. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  457. return false
  458. }
  459. return c.cfg.Daemon.ClusterProvider.IsAgent()
  460. }
  461. func (c *controller) isDistributedControl() bool {
  462. return !c.isManager() && !c.isAgent()
  463. }
  464. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  465. c.Lock()
  466. hd := c.discovery
  467. c.Unlock()
  468. if hd != nil {
  469. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  470. }
  471. c.agentDriverNotify(driver)
  472. return nil
  473. }
  474. // NewNetwork creates a new network of the specified network type. The options
  475. // are network specific and modeled in a generic way.
  476. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  477. if !config.IsValidName(name) {
  478. return nil, ErrInvalidName(name)
  479. }
  480. if id == "" {
  481. id = stringid.GenerateRandomID()
  482. }
  483. // Construct the network object
  484. network := &network{
  485. name: name,
  486. networkType: networkType,
  487. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  488. ipamType: ipamapi.DefaultIPAM,
  489. id: id,
  490. ctrlr: c,
  491. persist: true,
  492. drvOnce: &sync.Once{},
  493. }
  494. network.processOptions(options...)
  495. _, cap, err := network.resolveDriver(networkType, true)
  496. if err != nil {
  497. return nil, err
  498. }
  499. if cap.DataScope == datastore.GlobalScope && !c.isDistributedControl() && !network.dynamic {
  500. if c.isManager() {
  501. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  502. return nil, ManagerRedirectError(name)
  503. }
  504. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  505. }
  506. // Make sure we have a driver available for this network type
  507. // before we allocate anything.
  508. if _, err := network.driver(true); err != nil {
  509. return nil, err
  510. }
  511. err = network.ipamAllocate()
  512. if err != nil {
  513. return nil, err
  514. }
  515. defer func() {
  516. if err != nil {
  517. network.ipamRelease()
  518. }
  519. }()
  520. err = c.addNetwork(network)
  521. if err != nil {
  522. return nil, err
  523. }
  524. defer func() {
  525. if err != nil {
  526. if e := network.deleteNetwork(); e != nil {
  527. log.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  528. }
  529. }
  530. }()
  531. // First store the endpoint count, then the network. To avoid to
  532. // end up with a datastore containing a network and not an epCnt,
  533. // in case of an ungraceful shutdown during this function call.
  534. epCnt := &endpointCnt{n: network}
  535. if err = c.updateToStore(epCnt); err != nil {
  536. return nil, err
  537. }
  538. defer func() {
  539. if err != nil {
  540. if e := c.deleteFromStore(epCnt); e != nil {
  541. log.Warnf("couldnt rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  542. }
  543. }
  544. }()
  545. network.epCnt = epCnt
  546. if err = c.updateToStore(network); err != nil {
  547. return nil, err
  548. }
  549. joinCluster(network)
  550. return network, nil
  551. }
  552. var joinCluster NetworkWalker = func(nw Network) bool {
  553. n := nw.(*network)
  554. if err := n.joinCluster(); err != nil {
  555. log.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  556. }
  557. n.addDriverWatches()
  558. return false
  559. }
  560. func (c *controller) reservePools() {
  561. networks, err := c.getNetworksForScope(datastore.LocalScope)
  562. if err != nil {
  563. log.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  564. return
  565. }
  566. for _, n := range networks {
  567. if !doReplayPoolReserve(n) {
  568. continue
  569. }
  570. // Construct pseudo configs for the auto IP case
  571. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  572. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  573. if autoIPv4 {
  574. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  575. }
  576. if n.enableIPv6 && autoIPv6 {
  577. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  578. }
  579. // Account current network gateways
  580. for i, c := range n.ipamV4Config {
  581. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  582. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  583. }
  584. }
  585. for i, c := range n.ipamV6Config {
  586. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  587. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  588. }
  589. }
  590. // Reserve pools
  591. if err := n.ipamAllocate(); err != nil {
  592. log.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  593. }
  594. // Reserve existing endpoints' addresses
  595. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  596. if err != nil {
  597. log.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  598. continue
  599. }
  600. epl, err := n.getEndpointsFromStore()
  601. if err != nil {
  602. log.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  603. continue
  604. }
  605. for _, ep := range epl {
  606. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  607. log.Warnf("Failed to reserve current adress for endpoint %q (%s) on network %q (%s)",
  608. ep.Name(), ep.ID(), n.Name(), n.ID())
  609. }
  610. }
  611. }
  612. }
  613. func doReplayPoolReserve(n *network) bool {
  614. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  615. if err != nil {
  616. log.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  617. return false
  618. }
  619. return caps.RequiresRequestReplay
  620. }
  621. func (c *controller) addNetwork(n *network) error {
  622. d, err := n.driver(true)
  623. if err != nil {
  624. return err
  625. }
  626. // Create the network
  627. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  628. return err
  629. }
  630. return nil
  631. }
  632. func (c *controller) Networks() []Network {
  633. var list []Network
  634. networks, err := c.getNetworksFromStore()
  635. if err != nil {
  636. log.Error(err)
  637. }
  638. for _, n := range networks {
  639. if n.inDelete {
  640. continue
  641. }
  642. list = append(list, n)
  643. }
  644. return list
  645. }
  646. func (c *controller) WalkNetworks(walker NetworkWalker) {
  647. for _, n := range c.Networks() {
  648. if walker(n) {
  649. return
  650. }
  651. }
  652. }
  653. func (c *controller) NetworkByName(name string) (Network, error) {
  654. if name == "" {
  655. return nil, ErrInvalidName(name)
  656. }
  657. var n Network
  658. s := func(current Network) bool {
  659. if current.Name() == name {
  660. n = current
  661. return true
  662. }
  663. return false
  664. }
  665. c.WalkNetworks(s)
  666. if n == nil {
  667. return nil, ErrNoSuchNetwork(name)
  668. }
  669. return n, nil
  670. }
  671. func (c *controller) NetworkByID(id string) (Network, error) {
  672. if id == "" {
  673. return nil, ErrInvalidID(id)
  674. }
  675. n, err := c.getNetworkFromStore(id)
  676. if err != nil {
  677. return nil, ErrNoSuchNetwork(id)
  678. }
  679. return n, nil
  680. }
  681. // NewSandbox creates a new sandbox for the passed container id
  682. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  683. if containerID == "" {
  684. return nil, types.BadRequestErrorf("invalid container ID")
  685. }
  686. var sb *sandbox
  687. c.Lock()
  688. for _, s := range c.sandboxes {
  689. if s.containerID == containerID {
  690. // If not a stub, then we already have a complete sandbox.
  691. if !s.isStub {
  692. c.Unlock()
  693. return nil, types.ForbiddenErrorf("container %s is already present: %v", containerID, s)
  694. }
  695. // We already have a stub sandbox from the
  696. // store. Make use of it so that we don't lose
  697. // the endpoints from store but reset the
  698. // isStub flag.
  699. sb = s
  700. sb.isStub = false
  701. break
  702. }
  703. }
  704. c.Unlock()
  705. // Create sandbox and process options first. Key generation depends on an option
  706. if sb == nil {
  707. sb = &sandbox{
  708. id: stringid.GenerateRandomID(),
  709. containerID: containerID,
  710. endpoints: epHeap{},
  711. epPriority: map[string]int{},
  712. populatedEndpoints: map[string]struct{}{},
  713. config: containerConfig{},
  714. controller: c,
  715. }
  716. }
  717. sBox = sb
  718. heap.Init(&sb.endpoints)
  719. sb.processOptions(options...)
  720. c.Lock()
  721. if sb.ingress && c.ingressSandbox != nil {
  722. c.Unlock()
  723. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  724. }
  725. if sb.ingress {
  726. c.ingressSandbox = sb
  727. }
  728. c.Unlock()
  729. defer func() {
  730. if err != nil {
  731. c.Lock()
  732. if sb.ingress {
  733. c.ingressSandbox = nil
  734. }
  735. c.Unlock()
  736. }
  737. }()
  738. if err = sb.setupResolutionFiles(); err != nil {
  739. return nil, err
  740. }
  741. if sb.config.useDefaultSandBox {
  742. c.sboxOnce.Do(func() {
  743. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  744. })
  745. if err != nil {
  746. c.sboxOnce = sync.Once{}
  747. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  748. }
  749. sb.osSbox = c.defOsSbox
  750. }
  751. if sb.osSbox == nil && !sb.config.useExternalKey {
  752. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  753. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  754. }
  755. }
  756. c.Lock()
  757. c.sandboxes[sb.id] = sb
  758. c.Unlock()
  759. defer func() {
  760. if err != nil {
  761. c.Lock()
  762. delete(c.sandboxes, sb.id)
  763. c.Unlock()
  764. }
  765. }()
  766. err = sb.storeUpdate()
  767. if err != nil {
  768. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  769. }
  770. return sb, nil
  771. }
  772. func (c *controller) Sandboxes() []Sandbox {
  773. c.Lock()
  774. defer c.Unlock()
  775. list := make([]Sandbox, 0, len(c.sandboxes))
  776. for _, s := range c.sandboxes {
  777. // Hide stub sandboxes from libnetwork users
  778. if s.isStub {
  779. continue
  780. }
  781. list = append(list, s)
  782. }
  783. return list
  784. }
  785. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  786. for _, sb := range c.Sandboxes() {
  787. if walker(sb) {
  788. return
  789. }
  790. }
  791. }
  792. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  793. if id == "" {
  794. return nil, ErrInvalidID(id)
  795. }
  796. c.Lock()
  797. s, ok := c.sandboxes[id]
  798. c.Unlock()
  799. if !ok {
  800. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  801. }
  802. return s, nil
  803. }
  804. // SandboxDestroy destroys a sandbox given a container ID
  805. func (c *controller) SandboxDestroy(id string) error {
  806. var sb *sandbox
  807. c.Lock()
  808. for _, s := range c.sandboxes {
  809. if s.containerID == id {
  810. sb = s
  811. break
  812. }
  813. }
  814. c.Unlock()
  815. // It is not an error if sandbox is not available
  816. if sb == nil {
  817. return nil
  818. }
  819. return sb.Delete()
  820. }
  821. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  822. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  823. return func(sb Sandbox) bool {
  824. if sb.ContainerID() == containerID {
  825. *out = sb
  826. return true
  827. }
  828. return false
  829. }
  830. }
  831. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  832. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  833. return func(sb Sandbox) bool {
  834. if sb.Key() == key {
  835. *out = sb
  836. return true
  837. }
  838. return false
  839. }
  840. }
  841. func (c *controller) loadDriver(networkType string) error {
  842. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  843. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  844. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  845. if err != nil {
  846. if err == plugins.ErrNotFound {
  847. return types.NotFoundErrorf(err.Error())
  848. }
  849. return err
  850. }
  851. return nil
  852. }
  853. func (c *controller) loadIPAMDriver(name string) error {
  854. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  855. if err == plugins.ErrNotFound {
  856. return types.NotFoundErrorf(err.Error())
  857. }
  858. return err
  859. }
  860. return nil
  861. }
  862. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  863. id, cap := c.drvRegistry.IPAM(name)
  864. if id == nil {
  865. // Might be a plugin name. Try loading it
  866. if err := c.loadIPAMDriver(name); err != nil {
  867. return nil, nil, err
  868. }
  869. // Now that we resolved the plugin, try again looking up the registry
  870. id, cap = c.drvRegistry.IPAM(name)
  871. if id == nil {
  872. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  873. }
  874. }
  875. return id, cap, nil
  876. }
  877. func (c *controller) Stop() {
  878. c.closeStores()
  879. c.stopExternalKeyListener()
  880. osl.GC()
  881. }