controller.go 32 KB

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