controller.go 27 KB

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