controller.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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. keysAvailable = false
  287. c.agentOperationStart()
  288. c.Lock()
  289. c.keys = nil
  290. c.Unlock()
  291. // We are leaving the cluster. Make sure we
  292. // close the gossip so that we stop all
  293. // incoming gossip updates before cleaning up
  294. // any remaining service bindings. But before
  295. // deleting the networks since the networks
  296. // should still be present when cleaning up
  297. // service bindings
  298. c.agentClose()
  299. c.cleanupServiceDiscovery("")
  300. c.cleanupServiceBindings("")
  301. c.agentStopComplete()
  302. return
  303. }
  304. }
  305. }
  306. // AgentInitWait waits for agent initialization to be completed in the controller.
  307. func (c *controller) AgentInitWait() {
  308. c.Lock()
  309. agentInitDone := c.agentInitDone
  310. c.Unlock()
  311. if agentInitDone != nil {
  312. <-agentInitDone
  313. }
  314. }
  315. // AgentStopWait waits for the Agent stop to be completed in the controller
  316. func (c *controller) AgentStopWait() {
  317. c.Lock()
  318. agentStopDone := c.agentStopDone
  319. c.Unlock()
  320. if agentStopDone != nil {
  321. <-agentStopDone
  322. }
  323. }
  324. // agentOperationStart marks the start of an Agent Init or Agent Stop
  325. func (c *controller) agentOperationStart() {
  326. c.Lock()
  327. if c.agentInitDone == nil {
  328. c.agentInitDone = make(chan struct{})
  329. }
  330. if c.agentStopDone == nil {
  331. c.agentStopDone = make(chan struct{})
  332. }
  333. c.Unlock()
  334. }
  335. // agentInitComplete notifies the successful completion of the Agent initialization
  336. func (c *controller) agentInitComplete() {
  337. c.Lock()
  338. if c.agentInitDone != nil {
  339. close(c.agentInitDone)
  340. c.agentInitDone = nil
  341. }
  342. c.Unlock()
  343. }
  344. // agentStopComplete notifies the successful completion of the Agent stop
  345. func (c *controller) agentStopComplete() {
  346. c.Lock()
  347. if c.agentStopDone != nil {
  348. close(c.agentStopDone)
  349. c.agentStopDone = nil
  350. }
  351. c.Unlock()
  352. }
  353. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  354. if c.cfg == nil {
  355. return nil
  356. }
  357. config := make(map[string]interface{})
  358. for _, label := range c.cfg.Daemon.Labels {
  359. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  360. continue
  361. }
  362. config[netlabel.Key(label)] = netlabel.Value(label)
  363. }
  364. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  365. if ok {
  366. for k, v := range drvCfg.(map[string]interface{}) {
  367. config[k] = v
  368. }
  369. }
  370. for k, v := range c.cfg.Scopes {
  371. if !v.IsValid() {
  372. continue
  373. }
  374. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  375. Scope: k,
  376. Provider: v.Client.Provider,
  377. Address: v.Client.Address,
  378. Config: v.Client.Config,
  379. }
  380. }
  381. return config
  382. }
  383. var procReloadConfig = make(chan (bool), 1)
  384. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  385. procReloadConfig <- true
  386. defer func() { <-procReloadConfig }()
  387. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  388. // Refuse the configuration if it alters an existing datastore client configuration.
  389. update := false
  390. cfg := config.ParseConfigOptions(cfgOptions...)
  391. for s := range c.cfg.Scopes {
  392. if _, ok := cfg.Scopes[s]; !ok {
  393. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  394. }
  395. }
  396. for s, nSCfg := range cfg.Scopes {
  397. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  398. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  399. eSCfg.Client.Address != nSCfg.Client.Address {
  400. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  401. }
  402. } else {
  403. if err := c.initScopedStore(s, nSCfg); err != nil {
  404. return err
  405. }
  406. update = true
  407. }
  408. }
  409. if !update {
  410. return nil
  411. }
  412. c.Lock()
  413. c.cfg = cfg
  414. c.Unlock()
  415. var dsConfig *discoverapi.DatastoreConfigData
  416. for scope, sCfg := range cfg.Scopes {
  417. if scope == datastore.LocalScope || !sCfg.IsValid() {
  418. continue
  419. }
  420. dsConfig = &discoverapi.DatastoreConfigData{
  421. Scope: scope,
  422. Provider: sCfg.Client.Provider,
  423. Address: sCfg.Client.Address,
  424. Config: sCfg.Client.Config,
  425. }
  426. break
  427. }
  428. if dsConfig == nil {
  429. return nil
  430. }
  431. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  432. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  433. if err != nil {
  434. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  435. }
  436. return false
  437. })
  438. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  439. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  440. if err != nil {
  441. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  442. }
  443. return false
  444. })
  445. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  446. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  447. logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  448. }
  449. }
  450. return nil
  451. }
  452. func (c *controller) ID() string {
  453. return c.id
  454. }
  455. func (c *controller) BuiltinDrivers() []string {
  456. drivers := []string{}
  457. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  458. if driver.IsBuiltIn() {
  459. drivers = append(drivers, name)
  460. }
  461. return false
  462. })
  463. return drivers
  464. }
  465. func (c *controller) BuiltinIPAMDrivers() []string {
  466. drivers := []string{}
  467. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  468. if driver.IsBuiltIn() {
  469. drivers = append(drivers, name)
  470. }
  471. return false
  472. })
  473. return drivers
  474. }
  475. func (c *controller) validateHostDiscoveryConfig() bool {
  476. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  477. return false
  478. }
  479. return true
  480. }
  481. func (c *controller) clusterHostID() string {
  482. c.Lock()
  483. defer c.Unlock()
  484. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  485. return ""
  486. }
  487. addr := strings.Split(c.cfg.Cluster.Address, ":")
  488. return addr[0]
  489. }
  490. func (c *controller) isNodeAlive(node string) bool {
  491. if c.discovery == nil {
  492. return false
  493. }
  494. nodes := c.discovery.Fetch()
  495. for _, n := range nodes {
  496. if n.String() == node {
  497. return true
  498. }
  499. }
  500. return false
  501. }
  502. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  503. if c.cfg == nil {
  504. return fmt.Errorf("discovery initialization requires a valid configuration")
  505. }
  506. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  507. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  508. }
  509. func (c *controller) activeCallback() {
  510. ds := c.getStore(datastore.GlobalScope)
  511. if ds != nil && !ds.Active() {
  512. ds.RestartWatch()
  513. }
  514. }
  515. func (c *controller) hostJoinCallback(nodes []net.IP) {
  516. c.processNodeDiscovery(nodes, true)
  517. }
  518. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  519. c.processNodeDiscovery(nodes, false)
  520. }
  521. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  522. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  523. c.pushNodeDiscovery(driver, capability, nodes, add)
  524. return false
  525. })
  526. }
  527. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  528. var self net.IP
  529. if c.cfg != nil {
  530. addr := strings.Split(c.cfg.Cluster.Address, ":")
  531. self = net.ParseIP(addr[0])
  532. // if external kvstore is not configured, try swarm-mode config
  533. if self == nil {
  534. if agent := c.getAgent(); agent != nil {
  535. self = net.ParseIP(agent.advertiseAddr)
  536. }
  537. }
  538. }
  539. if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil {
  540. return
  541. }
  542. for _, node := range nodes {
  543. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  544. var err error
  545. if add {
  546. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  547. } else {
  548. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  549. }
  550. if err != nil {
  551. logrus.Debugf("discovery notification error: %v", err)
  552. }
  553. }
  554. }
  555. func (c *controller) Config() config.Config {
  556. c.Lock()
  557. defer c.Unlock()
  558. if c.cfg == nil {
  559. return config.Config{}
  560. }
  561. return *c.cfg
  562. }
  563. func (c *controller) isManager() bool {
  564. c.Lock()
  565. defer c.Unlock()
  566. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  567. return false
  568. }
  569. return c.cfg.Daemon.ClusterProvider.IsManager()
  570. }
  571. func (c *controller) isAgent() bool {
  572. c.Lock()
  573. defer c.Unlock()
  574. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  575. return false
  576. }
  577. return c.cfg.Daemon.ClusterProvider.IsAgent()
  578. }
  579. func (c *controller) isDistributedControl() bool {
  580. return !c.isManager() && !c.isAgent()
  581. }
  582. func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
  583. return c.drvRegistry.GetPluginGetter()
  584. }
  585. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  586. c.Lock()
  587. hd := c.discovery
  588. c.Unlock()
  589. if hd != nil {
  590. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  591. }
  592. c.agentDriverNotify(driver)
  593. return nil
  594. }
  595. // XXX This should be made driver agnostic. See comment below.
  596. const overlayDSROptionString = "dsr"
  597. // NewNetwork creates a new network of the specified network type. The options
  598. // are network specific and modeled in a generic way.
  599. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  600. if id != "" {
  601. c.networkLocker.Lock(id)
  602. defer c.networkLocker.Unlock(id)
  603. if _, err := c.NetworkByID(id); err == nil {
  604. return nil, NetworkNameError(id)
  605. }
  606. }
  607. if !config.IsValidName(name) {
  608. return nil, ErrInvalidName(name)
  609. }
  610. if id == "" {
  611. id = stringid.GenerateRandomID()
  612. }
  613. defaultIpam := defaultIpamForNetworkType(networkType)
  614. // Construct the network object
  615. network := &network{
  616. name: name,
  617. networkType: networkType,
  618. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  619. ipamType: defaultIpam,
  620. id: id,
  621. created: time.Now(),
  622. ctrlr: c,
  623. persist: true,
  624. drvOnce: &sync.Once{},
  625. loadBalancerMode: loadBalancerModeDefault,
  626. }
  627. network.processOptions(options...)
  628. if err := network.validateConfiguration(); err != nil {
  629. return nil, err
  630. }
  631. var (
  632. cap *driverapi.Capability
  633. err error
  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. defer func() {
  682. if err == nil {
  683. if err := t.getEpCnt().IncEndpointCnt(); err != nil {
  684. logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
  685. t.Name(), network.Name(), err)
  686. }
  687. }
  688. }()
  689. }
  690. err = network.ipamAllocate()
  691. if err != nil {
  692. return nil, err
  693. }
  694. defer func() {
  695. if err != nil {
  696. network.ipamRelease()
  697. }
  698. }()
  699. err = c.addNetwork(network)
  700. if err != nil {
  701. return nil, err
  702. }
  703. defer func() {
  704. if err != nil {
  705. if e := network.deleteNetwork(); e != nil {
  706. logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  707. }
  708. }
  709. }()
  710. // XXX If the driver type is "overlay" check the options for DSR
  711. // being set. If so, set the network's load balancing mode to DSR.
  712. // This should really be done in a network option, but due to
  713. // time pressure to get this in without adding changes to moby,
  714. // swarm and CLI, it is being implemented as a driver-specific
  715. // option. Unfortunately, drivers can't influence the core
  716. // "libnetwork.network" data type. Hence we need this hack code
  717. // to implement in this manner.
  718. if gval, ok := network.generic[netlabel.GenericData]; ok && network.networkType == "overlay" {
  719. optMap := gval.(map[string]string)
  720. if _, ok := optMap[overlayDSROptionString]; ok {
  721. network.loadBalancerMode = loadBalancerModeDSR
  722. }
  723. }
  724. addToStore:
  725. // First store the endpoint count, then the network. To avoid to
  726. // end up with a datastore containing a network and not an epCnt,
  727. // in case of an ungraceful shutdown during this function call.
  728. epCnt := &endpointCnt{n: network}
  729. if err = c.updateToStore(epCnt); err != nil {
  730. return nil, err
  731. }
  732. defer func() {
  733. if err != nil {
  734. if e := c.deleteFromStore(epCnt); e != nil {
  735. logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  736. }
  737. }
  738. }()
  739. network.epCnt = epCnt
  740. if err = c.updateToStore(network); err != nil {
  741. return nil, err
  742. }
  743. defer func() {
  744. if err != nil {
  745. if e := c.deleteFromStore(network); e != nil {
  746. logrus.Warnf("could not rollback from store, network %v on failure (%v): %v", network, err, e)
  747. }
  748. }
  749. }()
  750. if network.configOnly {
  751. return network, nil
  752. }
  753. joinCluster(network)
  754. defer func() {
  755. if err != nil {
  756. network.cancelDriverWatches()
  757. if e := network.leaveCluster(); e != nil {
  758. logrus.Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", network.name, err, e)
  759. }
  760. }
  761. }()
  762. if network.hasLoadBalancerEndpoint() {
  763. if err = network.createLoadBalancerSandbox(); err != nil {
  764. return nil, err
  765. }
  766. }
  767. if !c.isDistributedControl() {
  768. c.Lock()
  769. arrangeIngressFilterRule()
  770. c.Unlock()
  771. }
  772. c.arrangeUserFilterRule()
  773. return network, nil
  774. }
  775. var joinCluster NetworkWalker = func(nw Network) bool {
  776. n := nw.(*network)
  777. if n.configOnly {
  778. return false
  779. }
  780. if err := n.joinCluster(); err != nil {
  781. logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  782. }
  783. n.addDriverWatches()
  784. return false
  785. }
  786. func (c *controller) reservePools() {
  787. networks, err := c.getNetworksForScope(datastore.LocalScope)
  788. if err != nil {
  789. logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  790. return
  791. }
  792. for _, n := range networks {
  793. if n.configOnly {
  794. continue
  795. }
  796. if !doReplayPoolReserve(n) {
  797. continue
  798. }
  799. // Construct pseudo configs for the auto IP case
  800. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  801. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  802. if autoIPv4 {
  803. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  804. }
  805. if n.enableIPv6 && autoIPv6 {
  806. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  807. }
  808. // Account current network gateways
  809. for i, c := range n.ipamV4Config {
  810. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  811. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  812. }
  813. }
  814. if n.enableIPv6 {
  815. for i, c := range n.ipamV6Config {
  816. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  817. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  818. }
  819. }
  820. }
  821. // Reserve pools
  822. if err := n.ipamAllocate(); err != nil {
  823. logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  824. }
  825. // Reserve existing endpoints' addresses
  826. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  827. if err != nil {
  828. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  829. continue
  830. }
  831. epl, err := n.getEndpointsFromStore()
  832. if err != nil {
  833. logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  834. continue
  835. }
  836. for _, ep := range epl {
  837. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  838. logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  839. ep.Name(), ep.ID(), n.Name(), n.ID())
  840. }
  841. }
  842. }
  843. }
  844. func doReplayPoolReserve(n *network) bool {
  845. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  846. if err != nil {
  847. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  848. return false
  849. }
  850. return caps.RequiresRequestReplay
  851. }
  852. func (c *controller) addNetwork(n *network) error {
  853. d, err := n.driver(true)
  854. if err != nil {
  855. return err
  856. }
  857. // Create the network
  858. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  859. return err
  860. }
  861. n.startResolver()
  862. return nil
  863. }
  864. func (c *controller) Networks() []Network {
  865. var list []Network
  866. networks, err := c.getNetworksFromStore()
  867. if err != nil {
  868. logrus.Error(err)
  869. }
  870. for _, n := range networks {
  871. if n.inDelete {
  872. continue
  873. }
  874. list = append(list, n)
  875. }
  876. return list
  877. }
  878. func (c *controller) WalkNetworks(walker NetworkWalker) {
  879. for _, n := range c.Networks() {
  880. if walker(n) {
  881. return
  882. }
  883. }
  884. }
  885. func (c *controller) NetworkByName(name string) (Network, error) {
  886. if name == "" {
  887. return nil, ErrInvalidName(name)
  888. }
  889. var n Network
  890. s := func(current Network) bool {
  891. if current.Name() == name {
  892. n = current
  893. return true
  894. }
  895. return false
  896. }
  897. c.WalkNetworks(s)
  898. if n == nil {
  899. return nil, ErrNoSuchNetwork(name)
  900. }
  901. return n, nil
  902. }
  903. func (c *controller) NetworkByID(id string) (Network, error) {
  904. if id == "" {
  905. return nil, ErrInvalidID(id)
  906. }
  907. n, err := c.getNetworkFromStore(id)
  908. if err != nil {
  909. return nil, ErrNoSuchNetwork(id)
  910. }
  911. return n, nil
  912. }
  913. // NewSandbox creates a new sandbox for the passed container id
  914. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (Sandbox, error) {
  915. if containerID == "" {
  916. return nil, types.BadRequestErrorf("invalid container ID")
  917. }
  918. var sb *sandbox
  919. c.Lock()
  920. for _, s := range c.sandboxes {
  921. if s.containerID == containerID {
  922. // If not a stub, then we already have a complete sandbox.
  923. if !s.isStub {
  924. sbID := s.ID()
  925. c.Unlock()
  926. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  927. }
  928. // We already have a stub sandbox from the
  929. // store. Make use of it so that we don't lose
  930. // the endpoints from store but reset the
  931. // isStub flag.
  932. sb = s
  933. sb.isStub = false
  934. break
  935. }
  936. }
  937. c.Unlock()
  938. sandboxID := stringid.GenerateRandomID()
  939. if runtime.GOOS == "windows" {
  940. sandboxID = containerID
  941. }
  942. // Create sandbox and process options first. Key generation depends on an option
  943. if sb == nil {
  944. sb = &sandbox{
  945. id: sandboxID,
  946. containerID: containerID,
  947. endpoints: []*endpoint{},
  948. epPriority: map[string]int{},
  949. populatedEndpoints: map[string]struct{}{},
  950. config: containerConfig{},
  951. controller: c,
  952. extDNS: []extDNSEntry{},
  953. }
  954. }
  955. sb.processOptions(options...)
  956. c.Lock()
  957. if sb.ingress && c.ingressSandbox != nil {
  958. c.Unlock()
  959. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  960. }
  961. if sb.ingress {
  962. c.ingressSandbox = sb
  963. sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts")
  964. sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf")
  965. sb.id = "ingress_sbox"
  966. } else if sb.loadBalancerNID != "" {
  967. sb.id = "lb_" + sb.loadBalancerNID
  968. }
  969. c.Unlock()
  970. var err error
  971. defer func() {
  972. if err != nil {
  973. c.Lock()
  974. if sb.ingress {
  975. c.ingressSandbox = nil
  976. }
  977. c.Unlock()
  978. }
  979. }()
  980. if err = sb.setupResolutionFiles(); err != nil {
  981. return nil, err
  982. }
  983. if sb.config.useDefaultSandBox {
  984. c.sboxOnce.Do(func() {
  985. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  986. })
  987. if err != nil {
  988. c.sboxOnce = sync.Once{}
  989. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  990. }
  991. sb.osSbox = c.defOsSbox
  992. }
  993. if sb.osSbox == nil && !sb.config.useExternalKey {
  994. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  995. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  996. }
  997. }
  998. if sb.osSbox != nil {
  999. // Apply operating specific knobs on the load balancer sandbox
  1000. sb.osSbox.ApplyOSTweaks(sb.oslTypes)
  1001. }
  1002. c.Lock()
  1003. c.sandboxes[sb.id] = sb
  1004. c.Unlock()
  1005. defer func() {
  1006. if err != nil {
  1007. c.Lock()
  1008. delete(c.sandboxes, sb.id)
  1009. c.Unlock()
  1010. }
  1011. }()
  1012. err = sb.storeUpdate()
  1013. if err != nil {
  1014. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  1015. }
  1016. return sb, nil
  1017. }
  1018. func (c *controller) Sandboxes() []Sandbox {
  1019. c.Lock()
  1020. defer c.Unlock()
  1021. list := make([]Sandbox, 0, len(c.sandboxes))
  1022. for _, s := range c.sandboxes {
  1023. // Hide stub sandboxes from libnetwork users
  1024. if s.isStub {
  1025. continue
  1026. }
  1027. list = append(list, s)
  1028. }
  1029. return list
  1030. }
  1031. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  1032. for _, sb := range c.Sandboxes() {
  1033. if walker(sb) {
  1034. return
  1035. }
  1036. }
  1037. }
  1038. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  1039. if id == "" {
  1040. return nil, ErrInvalidID(id)
  1041. }
  1042. c.Lock()
  1043. s, ok := c.sandboxes[id]
  1044. c.Unlock()
  1045. if !ok {
  1046. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  1047. }
  1048. return s, nil
  1049. }
  1050. // SandboxDestroy destroys a sandbox given a container ID
  1051. func (c *controller) SandboxDestroy(id string) error {
  1052. var sb *sandbox
  1053. c.Lock()
  1054. for _, s := range c.sandboxes {
  1055. if s.containerID == id {
  1056. sb = s
  1057. break
  1058. }
  1059. }
  1060. c.Unlock()
  1061. // It is not an error if sandbox is not available
  1062. if sb == nil {
  1063. return nil
  1064. }
  1065. return sb.Delete()
  1066. }
  1067. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  1068. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  1069. return func(sb Sandbox) bool {
  1070. if sb.ContainerID() == containerID {
  1071. *out = sb
  1072. return true
  1073. }
  1074. return false
  1075. }
  1076. }
  1077. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  1078. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  1079. return func(sb Sandbox) bool {
  1080. if sb.Key() == key {
  1081. *out = sb
  1082. return true
  1083. }
  1084. return false
  1085. }
  1086. }
  1087. func (c *controller) loadDriver(networkType string) error {
  1088. var err error
  1089. if pg := c.GetPluginGetter(); pg != nil {
  1090. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  1091. } else {
  1092. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  1093. }
  1094. if err != nil {
  1095. if errors.Cause(err) == plugins.ErrNotFound {
  1096. return types.NotFoundErrorf(err.Error())
  1097. }
  1098. return err
  1099. }
  1100. return nil
  1101. }
  1102. func (c *controller) loadIPAMDriver(name string) error {
  1103. var err error
  1104. if pg := c.GetPluginGetter(); pg != nil {
  1105. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  1106. } else {
  1107. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  1108. }
  1109. if err != nil {
  1110. if err == plugins.ErrNotFound {
  1111. return types.NotFoundErrorf(err.Error())
  1112. }
  1113. return err
  1114. }
  1115. return nil
  1116. }
  1117. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  1118. id, cap := c.drvRegistry.IPAM(name)
  1119. if id == nil {
  1120. // Might be a plugin name. Try loading it
  1121. if err := c.loadIPAMDriver(name); err != nil {
  1122. return nil, nil, err
  1123. }
  1124. // Now that we resolved the plugin, try again looking up the registry
  1125. id, cap = c.drvRegistry.IPAM(name)
  1126. if id == nil {
  1127. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  1128. }
  1129. }
  1130. return id, cap, nil
  1131. }
  1132. func (c *controller) Stop() {
  1133. c.closeStores()
  1134. c.stopExternalKeyListener()
  1135. osl.GC()
  1136. }
  1137. // StartDiagnostic start the network dias mode
  1138. func (c *controller) StartDiagnostic(port int) {
  1139. c.Lock()
  1140. if !c.DiagnosticServer.IsDiagnosticEnabled() {
  1141. c.DiagnosticServer.EnableDiagnostic("127.0.0.1", port)
  1142. }
  1143. c.Unlock()
  1144. }
  1145. // StopDiagnostic start the network dias mode
  1146. func (c *controller) StopDiagnostic() {
  1147. c.Lock()
  1148. if c.DiagnosticServer.IsDiagnosticEnabled() {
  1149. c.DiagnosticServer.DisableDiagnostic()
  1150. }
  1151. c.Unlock()
  1152. }
  1153. // IsDiagnosticEnabled returns true if the dias is enabled
  1154. func (c *controller) IsDiagnosticEnabled() bool {
  1155. c.Lock()
  1156. defer c.Unlock()
  1157. return c.DiagnosticServer.IsDiagnosticEnabled()
  1158. }