controller.go 31 KB

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