controller.go 29 KB

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