controller.go 29 KB

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