controller.go 32 KB

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