controller.go 28 KB

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