controller.go 33 KB

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