controller.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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. if n.enableIPv6 {
  641. for i, c := range n.ipamV6Config {
  642. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  643. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  644. }
  645. }
  646. }
  647. // Reserve pools
  648. if err := n.ipamAllocate(); err != nil {
  649. log.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  650. }
  651. // Reserve existing endpoints' addresses
  652. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  653. if err != nil {
  654. log.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  655. continue
  656. }
  657. epl, err := n.getEndpointsFromStore()
  658. if err != nil {
  659. log.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  660. continue
  661. }
  662. for _, ep := range epl {
  663. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  664. log.Warnf("Failed to reserve current adress for endpoint %q (%s) on network %q (%s)",
  665. ep.Name(), ep.ID(), n.Name(), n.ID())
  666. }
  667. }
  668. }
  669. }
  670. func doReplayPoolReserve(n *network) bool {
  671. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  672. if err != nil {
  673. log.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  674. return false
  675. }
  676. return caps.RequiresRequestReplay
  677. }
  678. func (c *controller) addNetwork(n *network) error {
  679. d, err := n.driver(true)
  680. if err != nil {
  681. return err
  682. }
  683. // Create the network
  684. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  685. return err
  686. }
  687. return nil
  688. }
  689. func (c *controller) Networks() []Network {
  690. var list []Network
  691. networks, err := c.getNetworksFromStore()
  692. if err != nil {
  693. log.Error(err)
  694. }
  695. for _, n := range networks {
  696. if n.inDelete {
  697. continue
  698. }
  699. list = append(list, n)
  700. }
  701. return list
  702. }
  703. func (c *controller) WalkNetworks(walker NetworkWalker) {
  704. for _, n := range c.Networks() {
  705. if walker(n) {
  706. return
  707. }
  708. }
  709. }
  710. func (c *controller) NetworkByName(name string) (Network, error) {
  711. if name == "" {
  712. return nil, ErrInvalidName(name)
  713. }
  714. var n Network
  715. s := func(current Network) bool {
  716. if current.Name() == name {
  717. n = current
  718. return true
  719. }
  720. return false
  721. }
  722. c.WalkNetworks(s)
  723. if n == nil {
  724. return nil, ErrNoSuchNetwork(name)
  725. }
  726. return n, nil
  727. }
  728. func (c *controller) NetworkByID(id string) (Network, error) {
  729. if id == "" {
  730. return nil, ErrInvalidID(id)
  731. }
  732. n, err := c.getNetworkFromStore(id)
  733. if err != nil {
  734. return nil, ErrNoSuchNetwork(id)
  735. }
  736. return n, nil
  737. }
  738. // NewSandbox creates a new sandbox for the passed container id
  739. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  740. if containerID == "" {
  741. return nil, types.BadRequestErrorf("invalid container ID")
  742. }
  743. var sb *sandbox
  744. c.Lock()
  745. for _, s := range c.sandboxes {
  746. if s.containerID == containerID {
  747. // If not a stub, then we already have a complete sandbox.
  748. if !s.isStub {
  749. c.Unlock()
  750. return nil, types.ForbiddenErrorf("container %s is already present: %v", containerID, s)
  751. }
  752. // We already have a stub sandbox from the
  753. // store. Make use of it so that we don't lose
  754. // the endpoints from store but reset the
  755. // isStub flag.
  756. sb = s
  757. sb.isStub = false
  758. break
  759. }
  760. }
  761. c.Unlock()
  762. // Create sandbox and process options first. Key generation depends on an option
  763. if sb == nil {
  764. sb = &sandbox{
  765. id: stringid.GenerateRandomID(),
  766. containerID: containerID,
  767. endpoints: epHeap{},
  768. epPriority: map[string]int{},
  769. populatedEndpoints: map[string]struct{}{},
  770. config: containerConfig{},
  771. controller: c,
  772. }
  773. }
  774. sBox = sb
  775. heap.Init(&sb.endpoints)
  776. sb.processOptions(options...)
  777. c.Lock()
  778. if sb.ingress && c.ingressSandbox != nil {
  779. c.Unlock()
  780. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  781. }
  782. if sb.ingress {
  783. c.ingressSandbox = sb
  784. }
  785. c.Unlock()
  786. defer func() {
  787. if err != nil {
  788. c.Lock()
  789. if sb.ingress {
  790. c.ingressSandbox = nil
  791. }
  792. c.Unlock()
  793. }
  794. }()
  795. if err = sb.setupResolutionFiles(); err != nil {
  796. return nil, err
  797. }
  798. if sb.config.useDefaultSandBox {
  799. c.sboxOnce.Do(func() {
  800. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  801. })
  802. if err != nil {
  803. c.sboxOnce = sync.Once{}
  804. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  805. }
  806. sb.osSbox = c.defOsSbox
  807. }
  808. if sb.osSbox == nil && !sb.config.useExternalKey {
  809. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  810. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  811. }
  812. }
  813. c.Lock()
  814. c.sandboxes[sb.id] = sb
  815. c.Unlock()
  816. defer func() {
  817. if err != nil {
  818. c.Lock()
  819. delete(c.sandboxes, sb.id)
  820. c.Unlock()
  821. }
  822. }()
  823. err = sb.storeUpdate()
  824. if err != nil {
  825. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  826. }
  827. return sb, nil
  828. }
  829. func (c *controller) Sandboxes() []Sandbox {
  830. c.Lock()
  831. defer c.Unlock()
  832. list := make([]Sandbox, 0, len(c.sandboxes))
  833. for _, s := range c.sandboxes {
  834. // Hide stub sandboxes from libnetwork users
  835. if s.isStub {
  836. continue
  837. }
  838. list = append(list, s)
  839. }
  840. return list
  841. }
  842. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  843. for _, sb := range c.Sandboxes() {
  844. if walker(sb) {
  845. return
  846. }
  847. }
  848. }
  849. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  850. if id == "" {
  851. return nil, ErrInvalidID(id)
  852. }
  853. c.Lock()
  854. s, ok := c.sandboxes[id]
  855. c.Unlock()
  856. if !ok {
  857. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  858. }
  859. return s, nil
  860. }
  861. // SandboxDestroy destroys a sandbox given a container ID
  862. func (c *controller) SandboxDestroy(id string) error {
  863. var sb *sandbox
  864. c.Lock()
  865. for _, s := range c.sandboxes {
  866. if s.containerID == id {
  867. sb = s
  868. break
  869. }
  870. }
  871. c.Unlock()
  872. // It is not an error if sandbox is not available
  873. if sb == nil {
  874. return nil
  875. }
  876. return sb.Delete()
  877. }
  878. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  879. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  880. return func(sb Sandbox) bool {
  881. if sb.ContainerID() == containerID {
  882. *out = sb
  883. return true
  884. }
  885. return false
  886. }
  887. }
  888. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  889. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  890. return func(sb Sandbox) bool {
  891. if sb.Key() == key {
  892. *out = sb
  893. return true
  894. }
  895. return false
  896. }
  897. }
  898. func (c *controller) loadDriver(networkType string) error {
  899. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  900. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  901. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  902. if err != nil {
  903. if err == plugins.ErrNotFound {
  904. return types.NotFoundErrorf(err.Error())
  905. }
  906. return err
  907. }
  908. return nil
  909. }
  910. func (c *controller) loadIPAMDriver(name string) error {
  911. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  912. if err == plugins.ErrNotFound {
  913. return types.NotFoundErrorf(err.Error())
  914. }
  915. return err
  916. }
  917. return nil
  918. }
  919. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  920. id, cap := c.drvRegistry.IPAM(name)
  921. if id == nil {
  922. // Might be a plugin name. Try loading it
  923. if err := c.loadIPAMDriver(name); err != nil {
  924. return nil, nil, err
  925. }
  926. // Now that we resolved the plugin, try again looking up the registry
  927. id, cap = c.drvRegistry.IPAM(name)
  928. if id == nil {
  929. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  930. }
  931. }
  932. return id, cap, nil
  933. }
  934. func (c *controller) Stop() {
  935. c.closeStores()
  936. c.stopExternalKeyListener()
  937. osl.GC()
  938. }