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