controller.go 32 KB

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