controller.go 31 KB

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