controller.go 33 KB

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