controller.go 31 KB

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