controller.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /*
  2. Package libnetwork provides the basic functionality and extension points to
  3. create network namespaces and allocate interfaces for containers to use.
  4. networkType := "bridge"
  5. // Create a new controller instance
  6. driverOptions := options.Generic{}
  7. genericOption := make(map[string]interface{})
  8. genericOption[netlabel.GenericData] = driverOptions
  9. controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
  10. if err != nil {
  11. return
  12. }
  13. // Create a network for containers to join.
  14. // NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can make use of
  15. network, err := controller.NewNetwork(networkType, "network1", "")
  16. if err != nil {
  17. return
  18. }
  19. // For each new container: allocate IP and interfaces. The returned network
  20. // settings will be used for container infos (inspect and such), as well as
  21. // iptables rules for port publishing. This info is contained or accessible
  22. // from the returned endpoint.
  23. ep, err := network.CreateEndpoint("Endpoint1")
  24. if err != nil {
  25. return
  26. }
  27. // Create the sandbox for the container.
  28. // NewSandbox accepts Variadic optional arguments which libnetwork can use.
  29. sbx, err := controller.NewSandbox("container1",
  30. libnetwork.OptionHostname("test"),
  31. libnetwork.OptionDomainname("example.com"))
  32. // A sandbox can join the endpoint via the join api.
  33. err = ep.Join(sbx)
  34. if err != nil {
  35. return
  36. }
  37. */
  38. package libnetwork
  39. import (
  40. "context"
  41. "fmt"
  42. "net"
  43. "path/filepath"
  44. "runtime"
  45. "strings"
  46. "sync"
  47. "time"
  48. "github.com/containerd/log"
  49. "github.com/docker/docker/libnetwork/cluster"
  50. "github.com/docker/docker/libnetwork/config"
  51. "github.com/docker/docker/libnetwork/datastore"
  52. "github.com/docker/docker/libnetwork/diagnostic"
  53. "github.com/docker/docker/libnetwork/discoverapi"
  54. "github.com/docker/docker/libnetwork/driverapi"
  55. remotedriver "github.com/docker/docker/libnetwork/drivers/remote"
  56. "github.com/docker/docker/libnetwork/drvregistry"
  57. "github.com/docker/docker/libnetwork/ipamapi"
  58. "github.com/docker/docker/libnetwork/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. svcRecords map[string]*svcInfo
  81. serviceBindings map[serviceKey]*service
  82. ingressSandbox *Sandbox
  83. agent *nwAgent
  84. networkLocker *locker.Locker
  85. agentInitDone chan struct{}
  86. agentStopDone chan struct{}
  87. keys []*types.EncryptionKey
  88. DiagnosticServer *diagnostic.Server
  89. mu sync.Mutex
  90. // FIXME(thaJeztah): defOsSbox is always nil on non-Linux: move these fields to Linux-only files.
  91. defOsSboxOnce sync.Once
  92. defOsSbox *osl.Namespace
  93. }
  94. // New creates a new instance of network controller.
  95. func New(cfgOptions ...config.Option) (*Controller, error) {
  96. c := &Controller{
  97. id: stringid.GenerateRandomID(),
  98. cfg: config.New(cfgOptions...),
  99. sandboxes: map[string]*Sandbox{},
  100. svcRecords: make(map[string]*svcInfo),
  101. serviceBindings: make(map[serviceKey]*service),
  102. agentInitDone: make(chan struct{}),
  103. networkLocker: locker.New(),
  104. DiagnosticServer: diagnostic.New(),
  105. }
  106. c.DiagnosticServer.Init()
  107. if err := c.initStores(); err != nil {
  108. return nil, err
  109. }
  110. c.drvRegistry.Notify = c
  111. // External plugins don't need config passed through daemon. They can
  112. // bootstrap themselves.
  113. if err := remotedriver.Register(&c.drvRegistry, c.cfg.PluginGetter); err != nil {
  114. return nil, err
  115. }
  116. if err := registerNetworkDrivers(&c.drvRegistry, c.makeDriverConfig); err != nil {
  117. return nil, err
  118. }
  119. if err := initIPAMDrivers(&c.ipamRegistry, c.cfg.PluginGetter, c.cfg.DefaultAddressPool); err != nil {
  120. return nil, err
  121. }
  122. c.WalkNetworks(func(nw *Network) bool {
  123. if n := nw; n.hasSpecialDriver() && !n.ConfigOnly() {
  124. if err := n.getController().addNetwork(n); err != nil {
  125. log.G(context.TODO()).Warnf("Failed to populate network %q with driver %q", nw.Name(), nw.Type())
  126. }
  127. }
  128. return false
  129. })
  130. // Reserve pools first before doing cleanup. Otherwise the
  131. // cleanups of endpoint/network and sandbox below will
  132. // generate many unnecessary warnings
  133. c.reservePools()
  134. // Cleanup resources
  135. if err := c.sandboxCleanup(c.cfg.ActiveSandboxes); err != nil {
  136. log.G(context.TODO()).WithError(err).Error("error during sandbox cleanup")
  137. }
  138. if err := c.cleanupLocalEndpoints(); err != nil {
  139. log.G(context.TODO()).WithError(err).Warnf("error during endpoint cleanup")
  140. }
  141. c.networkCleanup()
  142. if err := c.startExternalKeyListener(); err != nil {
  143. return nil, err
  144. }
  145. setupArrangeUserFilterRule(c)
  146. return c, nil
  147. }
  148. // SetClusterProvider sets the cluster provider.
  149. func (c *Controller) SetClusterProvider(provider cluster.Provider) {
  150. var sameProvider bool
  151. c.mu.Lock()
  152. // Avoids to spawn multiple goroutine for the same cluster provider
  153. if c.cfg.ClusterProvider == provider {
  154. // If the cluster provider is already set, there is already a go routine spawned
  155. // that is listening for events, so nothing to do here
  156. sameProvider = true
  157. } else {
  158. c.cfg.ClusterProvider = provider
  159. }
  160. c.mu.Unlock()
  161. if provider == nil || sameProvider {
  162. return
  163. }
  164. // We don't want to spawn a new go routine if the previous one did not exit yet
  165. c.AgentStopWait()
  166. go c.clusterAgentInit()
  167. }
  168. // SetKeys configures the encryption key for gossip and overlay data path.
  169. func (c *Controller) SetKeys(keys []*types.EncryptionKey) error {
  170. // libnetwork side of agent depends on the keys. On the first receipt of
  171. // keys setup the agent. For subsequent key set handle the key change
  172. subsysKeys := make(map[string]int)
  173. for _, key := range keys {
  174. if key.Subsystem != subsysGossip &&
  175. key.Subsystem != subsysIPSec {
  176. return fmt.Errorf("key received for unrecognized subsystem")
  177. }
  178. subsysKeys[key.Subsystem]++
  179. }
  180. for s, count := range subsysKeys {
  181. if count != keyringSize {
  182. return fmt.Errorf("incorrect number of keys for subsystem %v", s)
  183. }
  184. }
  185. if c.getAgent() == nil {
  186. c.mu.Lock()
  187. c.keys = keys
  188. c.mu.Unlock()
  189. return nil
  190. }
  191. return c.handleKeyChange(keys)
  192. }
  193. func (c *Controller) getAgent() *nwAgent {
  194. c.mu.Lock()
  195. defer c.mu.Unlock()
  196. return c.agent
  197. }
  198. func (c *Controller) clusterAgentInit() {
  199. clusterProvider := c.cfg.ClusterProvider
  200. var keysAvailable bool
  201. for {
  202. eventType := <-clusterProvider.ListenClusterEvents()
  203. // The events: EventSocketChange, EventNodeReady and EventNetworkKeysAvailable are not ordered
  204. // when all the condition for the agent initialization are met then proceed with it
  205. switch eventType {
  206. case cluster.EventNetworkKeysAvailable:
  207. // Validates that the keys are actually available before starting the initialization
  208. // This will handle old spurious messages left on the channel
  209. c.mu.Lock()
  210. keysAvailable = c.keys != nil
  211. c.mu.Unlock()
  212. fallthrough
  213. case cluster.EventSocketChange, cluster.EventNodeReady:
  214. if keysAvailable && c.isSwarmNode() {
  215. c.agentOperationStart()
  216. if err := c.agentSetup(clusterProvider); err != nil {
  217. c.agentStopComplete()
  218. } else {
  219. c.agentInitComplete()
  220. }
  221. }
  222. case cluster.EventNodeLeave:
  223. c.agentOperationStart()
  224. c.mu.Lock()
  225. c.keys = nil
  226. c.mu.Unlock()
  227. // We are leaving the cluster. Make sure we
  228. // close the gossip so that we stop all
  229. // incoming gossip updates before cleaning up
  230. // any remaining service bindings. But before
  231. // deleting the networks since the networks
  232. // should still be present when cleaning up
  233. // service bindings
  234. c.agentClose()
  235. c.cleanupServiceDiscovery("")
  236. c.cleanupServiceBindings("")
  237. c.agentStopComplete()
  238. return
  239. }
  240. }
  241. }
  242. // AgentInitWait waits for agent initialization to be completed in the controller.
  243. func (c *Controller) AgentInitWait() {
  244. c.mu.Lock()
  245. agentInitDone := c.agentInitDone
  246. c.mu.Unlock()
  247. if agentInitDone != nil {
  248. <-agentInitDone
  249. }
  250. }
  251. // AgentStopWait waits for the Agent stop to be completed in the controller.
  252. func (c *Controller) AgentStopWait() {
  253. c.mu.Lock()
  254. agentStopDone := c.agentStopDone
  255. c.mu.Unlock()
  256. if agentStopDone != nil {
  257. <-agentStopDone
  258. }
  259. }
  260. // agentOperationStart marks the start of an Agent Init or Agent Stop
  261. func (c *Controller) agentOperationStart() {
  262. c.mu.Lock()
  263. if c.agentInitDone == nil {
  264. c.agentInitDone = make(chan struct{})
  265. }
  266. if c.agentStopDone == nil {
  267. c.agentStopDone = make(chan struct{})
  268. }
  269. c.mu.Unlock()
  270. }
  271. // agentInitComplete notifies the successful completion of the Agent initialization
  272. func (c *Controller) agentInitComplete() {
  273. c.mu.Lock()
  274. if c.agentInitDone != nil {
  275. close(c.agentInitDone)
  276. c.agentInitDone = nil
  277. }
  278. c.mu.Unlock()
  279. }
  280. // agentStopComplete notifies the successful completion of the Agent stop
  281. func (c *Controller) agentStopComplete() {
  282. c.mu.Lock()
  283. if c.agentStopDone != nil {
  284. close(c.agentStopDone)
  285. c.agentStopDone = nil
  286. }
  287. c.mu.Unlock()
  288. }
  289. func (c *Controller) makeDriverConfig(ntype string) map[string]interface{} {
  290. if c.cfg == nil {
  291. return nil
  292. }
  293. cfg := map[string]interface{}{}
  294. for _, label := range c.cfg.Labels {
  295. key, val, _ := strings.Cut(label, "=")
  296. if !strings.HasPrefix(key, netlabel.DriverPrefix+"."+ntype) {
  297. continue
  298. }
  299. cfg[key] = val
  300. }
  301. // Merge in the existing config for this driver.
  302. for k, v := range c.cfg.DriverConfig(ntype) {
  303. cfg[k] = v
  304. }
  305. if c.cfg.Scope.IsValid() {
  306. // FIXME: every driver instance constructs a new DataStore
  307. // instance against the same database. Yikes!
  308. cfg[netlabel.LocalKVClient] = discoverapi.DatastoreConfigData{
  309. Scope: scope.Local,
  310. Provider: c.cfg.Scope.Client.Provider,
  311. Address: c.cfg.Scope.Client.Address,
  312. Config: c.cfg.Scope.Client.Config,
  313. }
  314. }
  315. return cfg
  316. }
  317. // ID returns the controller's unique identity.
  318. func (c *Controller) ID() string {
  319. return c.id
  320. }
  321. // BuiltinDrivers returns the list of builtin network drivers.
  322. func (c *Controller) BuiltinDrivers() []string {
  323. drivers := []string{}
  324. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  325. if driver.IsBuiltIn() {
  326. drivers = append(drivers, name)
  327. }
  328. return false
  329. })
  330. return drivers
  331. }
  332. // BuiltinIPAMDrivers returns the list of builtin ipam drivers.
  333. func (c *Controller) BuiltinIPAMDrivers() []string {
  334. drivers := []string{}
  335. c.ipamRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, _ *ipamapi.Capability) bool {
  336. if driver.IsBuiltIn() {
  337. drivers = append(drivers, name)
  338. }
  339. return false
  340. })
  341. return drivers
  342. }
  343. func (c *Controller) processNodeDiscovery(nodes []net.IP, add bool) {
  344. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  345. if d, ok := driver.(discoverapi.Discover); ok {
  346. c.pushNodeDiscovery(d, capability, nodes, add)
  347. }
  348. return false
  349. })
  350. }
  351. func (c *Controller) pushNodeDiscovery(d discoverapi.Discover, capability driverapi.Capability, nodes []net.IP, add bool) {
  352. var self net.IP
  353. // try swarm-mode config
  354. if agent := c.getAgent(); agent != nil {
  355. self = net.ParseIP(agent.advertiseAddr)
  356. }
  357. if d == nil || capability.ConnectivityScope != scope.Global || nodes == nil {
  358. return
  359. }
  360. for _, node := range nodes {
  361. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  362. var err error
  363. if add {
  364. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  365. } else {
  366. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  367. }
  368. if err != nil {
  369. log.G(context.TODO()).Debugf("discovery notification error: %v", err)
  370. }
  371. }
  372. }
  373. // Config returns the bootup configuration for the controller.
  374. func (c *Controller) Config() config.Config {
  375. c.mu.Lock()
  376. defer c.mu.Unlock()
  377. if c.cfg == nil {
  378. return config.Config{}
  379. }
  380. return *c.cfg
  381. }
  382. func (c *Controller) isManager() 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.IsManager()
  389. }
  390. func (c *Controller) isAgent() bool {
  391. c.mu.Lock()
  392. defer c.mu.Unlock()
  393. if c.cfg == nil || c.cfg.ClusterProvider == nil {
  394. return false
  395. }
  396. return c.cfg.ClusterProvider.IsAgent()
  397. }
  398. func (c *Controller) isSwarmNode() bool {
  399. return c.isManager() || c.isAgent()
  400. }
  401. func (c *Controller) GetPluginGetter() plugingetter.PluginGetter {
  402. return c.cfg.PluginGetter
  403. }
  404. func (c *Controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  405. if d, ok := driver.(discoverapi.Discover); ok {
  406. c.agentDriverNotify(d)
  407. }
  408. return nil
  409. }
  410. // XXX This should be made driver agnostic. See comment below.
  411. const overlayDSROptionString = "dsr"
  412. // NewNetwork creates a new network of the specified network type. The options
  413. // are network specific and modeled in a generic way.
  414. func (c *Controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (_ *Network, retErr error) {
  415. if id != "" {
  416. c.networkLocker.Lock(id)
  417. defer c.networkLocker.Unlock(id) //nolint:errcheck
  418. if _, err := c.NetworkByID(id); err == nil {
  419. return nil, NetworkNameError(id)
  420. }
  421. }
  422. if strings.TrimSpace(name) == "" {
  423. return nil, ErrInvalidName(name)
  424. }
  425. // Make sure two concurrent calls to this method won't create conflicting
  426. // networks, otherwise libnetwork will end up in an invalid state.
  427. if name != "" {
  428. c.networkLocker.Lock(name)
  429. defer c.networkLocker.Unlock(name)
  430. if _, err := c.NetworkByName(name); err == nil {
  431. return nil, NetworkNameError(name)
  432. }
  433. }
  434. if id == "" {
  435. id = stringid.GenerateRandomID()
  436. }
  437. defaultIpam := defaultIpamForNetworkType(networkType)
  438. // Construct the network object
  439. nw := &Network{
  440. name: name,
  441. networkType: networkType,
  442. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  443. ipamType: defaultIpam,
  444. id: id,
  445. created: time.Now(),
  446. ctrlr: c,
  447. persist: true,
  448. drvOnce: &sync.Once{},
  449. loadBalancerMode: loadBalancerModeDefault,
  450. }
  451. nw.processOptions(options...)
  452. if err := nw.validateConfiguration(); err != nil {
  453. return nil, err
  454. }
  455. // These variables must be defined here, as declaration would otherwise
  456. // be skipped by the "goto addToStore"
  457. var (
  458. caps driverapi.Capability
  459. err error
  460. skipCfgEpCount bool
  461. )
  462. // Reset network types, force local scope and skip allocation and
  463. // plumbing for configuration networks. Reset of the config-only
  464. // network drivers is needed so that this special network is not
  465. // usable by old engine versions.
  466. if nw.configOnly {
  467. nw.scope = scope.Local
  468. nw.networkType = "null"
  469. goto addToStore
  470. }
  471. _, caps, err = nw.resolveDriver(nw.networkType, true)
  472. if err != nil {
  473. return nil, err
  474. }
  475. if nw.scope == scope.Local && caps.DataScope == scope.Global {
  476. return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
  477. }
  478. if nw.ingress && caps.DataScope != scope.Global {
  479. return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
  480. }
  481. // At this point the network scope is still unknown if not set by user
  482. if (caps.DataScope == scope.Global || nw.scope == scope.Swarm) &&
  483. c.isSwarmNode() && !nw.dynamic {
  484. if c.isManager() {
  485. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  486. return nil, ManagerRedirectError(name)
  487. }
  488. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  489. }
  490. if nw.scope == scope.Swarm && !c.isSwarmNode() {
  491. return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active")
  492. }
  493. // Make sure we have a driver available for this network type
  494. // before we allocate anything.
  495. if _, err := nw.driver(true); err != nil {
  496. return nil, err
  497. }
  498. // From this point on, we need the network specific configuration,
  499. // which may come from a configuration-only network
  500. if nw.configFrom != "" {
  501. configNetwork, err := c.getConfigNetwork(nw.configFrom)
  502. if err != nil {
  503. return nil, types.NotFoundErrorf("configuration network %q does not exist", nw.configFrom)
  504. }
  505. if err := configNetwork.applyConfigurationTo(nw); err != nil {
  506. return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
  507. }
  508. nw.generic[netlabel.Internal] = nw.internal
  509. defer func() {
  510. if retErr == nil && !skipCfgEpCount {
  511. if err := configNetwork.getEpCnt().IncEndpointCnt(); err != nil {
  512. 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)
  513. }
  514. }
  515. }()
  516. }
  517. if err := nw.ipamAllocate(); err != nil {
  518. return nil, err
  519. }
  520. defer func() {
  521. if retErr != nil {
  522. nw.ipamRelease()
  523. }
  524. }()
  525. // Note from thaJeztah to future code visitors, or "future self".
  526. //
  527. // This code was previously assigning the error to the global "err"
  528. // variable (before it was renamed to "retErr"), but in case of a
  529. // "MaskableError" did not *return* the error:
  530. // https://github.com/moby/moby/blob/b325dcbff60a04cedbe40eb627465fc7379d05bf/libnetwork/controller.go#L566-L573
  531. //
  532. // Depending on code paths further down, that meant that this error
  533. // was either overwritten by other errors (and thus not handled in
  534. // defer statements) or handled (if no other code was overwriting it.
  535. //
  536. // I suspect this was a bug (but possible without effect), but it could
  537. // have been intentional. This logic is confusing at least, and even
  538. // more so combined with the handling in defer statements that check for
  539. // both the "err" return AND "skipCfgEpCount":
  540. // https://github.com/moby/moby/blob/b325dcbff60a04cedbe40eb627465fc7379d05bf/libnetwork/controller.go#L586-L602
  541. //
  542. // To save future visitors some time to dig up history:
  543. //
  544. // - config-only networks were added in 25082206df465d1c11dd1276a65b4a1dc701bd43
  545. // - the special error-handling and "skipCfgEpcoung" was added in ddd22a819867faa0cd7d12b0c3fad1099ac3eb26
  546. // - and updated in 87b082f3659f9ec245ab15d781e6bfffced0af83 to don't use string-matching
  547. //
  548. // To cut a long story short: if this broke anything, you know who to blame :)
  549. if err := c.addNetwork(nw); err != nil {
  550. if _, ok := err.(types.MaskableError); ok { //nolint:gosimple
  551. // This error can be ignored and set this boolean
  552. // value to skip a refcount increment for configOnly networks
  553. skipCfgEpCount = true
  554. } else {
  555. return nil, err
  556. }
  557. }
  558. defer func() {
  559. if retErr != nil {
  560. if err := nw.deleteNetwork(); err != nil {
  561. log.G(context.TODO()).Warnf("couldn't roll back driver network on network %s creation failure: %v", nw.name, retErr)
  562. }
  563. }
  564. }()
  565. // XXX If the driver type is "overlay" check the options for DSR
  566. // being set. If so, set the network's load balancing mode to DSR.
  567. // This should really be done in a network option, but due to
  568. // time pressure to get this in without adding changes to moby,
  569. // swarm and CLI, it is being implemented as a driver-specific
  570. // option. Unfortunately, drivers can't influence the core
  571. // "libnetwork.Network" data type. Hence we need this hack code
  572. // to implement in this manner.
  573. if gval, ok := nw.generic[netlabel.GenericData]; ok && nw.networkType == "overlay" {
  574. optMap := gval.(map[string]string)
  575. if _, ok := optMap[overlayDSROptionString]; ok {
  576. nw.loadBalancerMode = loadBalancerModeDSR
  577. }
  578. }
  579. addToStore:
  580. // First store the endpoint count, then the network. To avoid to
  581. // end up with a datastore containing a network and not an epCnt,
  582. // in case of an ungraceful shutdown during this function call.
  583. epCnt := &endpointCnt{n: nw}
  584. if err := c.updateToStore(epCnt); err != nil {
  585. return nil, err
  586. }
  587. defer func() {
  588. if retErr != nil {
  589. if err := c.deleteFromStore(epCnt); err != nil {
  590. log.G(context.TODO()).Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, retErr, err)
  591. }
  592. }
  593. }()
  594. nw.epCnt = epCnt
  595. if err := c.updateToStore(nw); err != nil {
  596. return nil, err
  597. }
  598. defer func() {
  599. if retErr != nil {
  600. if err := c.deleteFromStore(nw); err != nil {
  601. log.G(context.TODO()).Warnf("could not rollback from store, network %v on failure (%v): %v", nw, retErr, err)
  602. }
  603. }
  604. }()
  605. if nw.configOnly {
  606. return nw, nil
  607. }
  608. joinCluster(nw)
  609. defer func() {
  610. if retErr != nil {
  611. nw.cancelDriverWatches()
  612. if err := nw.leaveCluster(); err != nil {
  613. log.G(context.TODO()).Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", nw.name, retErr, err)
  614. }
  615. }
  616. }()
  617. if nw.hasLoadBalancerEndpoint() {
  618. if err := nw.createLoadBalancerSandbox(); err != nil {
  619. return nil, err
  620. }
  621. }
  622. if c.isSwarmNode() {
  623. c.mu.Lock()
  624. arrangeIngressFilterRule()
  625. c.mu.Unlock()
  626. }
  627. // Sets up the DOCKER-USER chain for each iptables version (IPv4, IPv6)
  628. // that's enabled in the controller's configuration.
  629. for _, ipVersion := range c.enabledIptablesVersions() {
  630. if err := setupUserChain(ipVersion); err != nil {
  631. log.G(context.TODO()).WithError(err).Warnf("Controller.NewNetwork %s:", name)
  632. }
  633. }
  634. return nw, nil
  635. }
  636. var joinCluster NetworkWalker = func(nw *Network) bool {
  637. if nw.configOnly {
  638. return false
  639. }
  640. if err := nw.joinCluster(); err != nil {
  641. log.G(context.TODO()).Errorf("Failed to join network %s (%s) into agent cluster: %v", nw.Name(), nw.ID(), err)
  642. }
  643. nw.addDriverWatches()
  644. return false
  645. }
  646. func (c *Controller) reservePools() {
  647. networks, err := c.getNetworks()
  648. if err != nil {
  649. log.G(context.TODO()).Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  650. return
  651. }
  652. for _, n := range networks {
  653. if n.configOnly {
  654. continue
  655. }
  656. if !doReplayPoolReserve(n) {
  657. continue
  658. }
  659. // Construct pseudo configs for the auto IP case
  660. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  661. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  662. if autoIPv4 {
  663. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  664. }
  665. if n.enableIPv6 && autoIPv6 {
  666. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  667. }
  668. // Account current network gateways
  669. for i, cfg := range n.ipamV4Config {
  670. if cfg.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  671. cfg.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  672. }
  673. }
  674. if n.enableIPv6 {
  675. for i, cfg := range n.ipamV6Config {
  676. if cfg.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  677. cfg.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  678. }
  679. }
  680. }
  681. // Reserve pools
  682. if err := n.ipamAllocate(); err != nil {
  683. log.G(context.TODO()).Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  684. }
  685. // Reserve existing endpoints' addresses
  686. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  687. if err != nil {
  688. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  689. continue
  690. }
  691. epl, err := n.getEndpointsFromStore()
  692. if err != nil {
  693. log.G(context.TODO()).Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  694. continue
  695. }
  696. for _, ep := range epl {
  697. if ep.Iface() == nil {
  698. log.G(context.TODO()).Warnf("endpoint interface is empty for %q (%s)", ep.Name(), ep.ID())
  699. continue
  700. }
  701. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  702. log.G(context.TODO()).Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  703. ep.Name(), ep.ID(), n.Name(), n.ID())
  704. }
  705. }
  706. }
  707. }
  708. func doReplayPoolReserve(n *Network) bool {
  709. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  710. if err != nil {
  711. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  712. return false
  713. }
  714. return caps.RequiresRequestReplay
  715. }
  716. func (c *Controller) addNetwork(n *Network) error {
  717. d, err := n.driver(true)
  718. if err != nil {
  719. return err
  720. }
  721. // Create the network
  722. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  723. return err
  724. }
  725. n.startResolver()
  726. return nil
  727. }
  728. // Networks returns the list of Network(s) managed by this controller.
  729. func (c *Controller) Networks(ctx context.Context) []*Network {
  730. var list []*Network
  731. for _, n := range c.getNetworksFromStore(ctx) {
  732. if n.inDelete {
  733. continue
  734. }
  735. list = append(list, n)
  736. }
  737. return list
  738. }
  739. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  740. func (c *Controller) WalkNetworks(walker NetworkWalker) {
  741. for _, n := range c.Networks(context.TODO()) {
  742. if walker(n) {
  743. return
  744. }
  745. }
  746. }
  747. // NetworkByName returns the Network which has the passed name.
  748. // If not found, the error [ErrNoSuchNetwork] is returned.
  749. func (c *Controller) NetworkByName(name string) (*Network, error) {
  750. if name == "" {
  751. return nil, ErrInvalidName(name)
  752. }
  753. var n *Network
  754. c.WalkNetworks(func(current *Network) bool {
  755. if current.Name() == name {
  756. n = current
  757. return true
  758. }
  759. return false
  760. })
  761. if n == nil {
  762. return nil, ErrNoSuchNetwork(name)
  763. }
  764. return n, nil
  765. }
  766. // NetworkByID returns the Network which has the passed id.
  767. // If not found, the error [ErrNoSuchNetwork] is returned.
  768. func (c *Controller) NetworkByID(id string) (*Network, error) {
  769. if id == "" {
  770. return nil, ErrInvalidID(id)
  771. }
  772. return c.getNetworkFromStore(id)
  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. }