controller.go 29 KB

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