controller.go 36 KB

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