controller.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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/types"
  61. "github.com/docker/docker/pkg/plugingetter"
  62. "github.com/docker/docker/pkg/plugins"
  63. "github.com/docker/docker/pkg/stringid"
  64. "github.com/moby/locker"
  65. "github.com/pkg/errors"
  66. )
  67. // NetworkWalker is a client provided function which will be used to walk the Networks.
  68. // When the function returns true, the walk will stop.
  69. type NetworkWalker func(nw Network) bool
  70. // SandboxWalker is a client provided function which will be used to walk the Sandboxes.
  71. // When the function returns true, the walk will stop.
  72. type SandboxWalker func(sb *Sandbox) bool
  73. type sandboxTable map[string]*Sandbox
  74. // Controller manages networks.
  75. type Controller struct {
  76. id string
  77. drvRegistry drvregistry.Networks
  78. ipamRegistry drvregistry.IPAMs
  79. sandboxes sandboxTable
  80. cfg *config.Config
  81. store datastore.DataStore
  82. extKeyListener net.Listener
  83. watchCh chan *Endpoint
  84. unWatchCh chan *Endpoint
  85. svcRecords map[string]*svcInfo
  86. nmap map[string]*netWatch
  87. serviceBindings map[serviceKey]*service
  88. defOsSbox osl.Sandbox
  89. ingressSandbox *Sandbox
  90. sboxOnce sync.Once
  91. agent *agent
  92. networkLocker *locker.Locker
  93. agentInitDone chan struct{}
  94. agentStopDone chan struct{}
  95. keys []*types.EncryptionKey
  96. DiagnosticServer *diagnostic.Server
  97. mu sync.Mutex
  98. }
  99. // New creates a new instance of network controller.
  100. func New(cfgOptions ...config.Option) (*Controller, error) {
  101. c := &Controller{
  102. id: stringid.GenerateRandomID(),
  103. cfg: config.New(cfgOptions...),
  104. sandboxes: sandboxTable{},
  105. svcRecords: make(map[string]*svcInfo),
  106. serviceBindings: make(map[serviceKey]*service),
  107. agentInitDone: make(chan struct{}),
  108. networkLocker: locker.New(),
  109. DiagnosticServer: diagnostic.New(),
  110. }
  111. c.DiagnosticServer.Init()
  112. if err := c.initStores(); err != nil {
  113. return nil, err
  114. }
  115. c.drvRegistry.Notify = c.RegisterDriver
  116. // External plugins don't need config passed through daemon. They can
  117. // bootstrap themselves.
  118. if err := remotedriver.Register(&c.drvRegistry, c.cfg.PluginGetter); err != nil {
  119. return nil, err
  120. }
  121. if err := registerNetworkDrivers(&c.drvRegistry, c.makeDriverConfig); err != nil {
  122. return nil, err
  123. }
  124. if err := initIPAMDrivers(&c.ipamRegistry, c.cfg.PluginGetter, c.cfg.DefaultAddressPool); err != nil {
  125. return nil, err
  126. }
  127. c.WalkNetworks(populateSpecial)
  128. // Reserve pools first before doing cleanup. Otherwise the
  129. // cleanups of endpoint/network and sandbox below will
  130. // generate many unnecessary warnings
  131. c.reservePools()
  132. // Cleanup resources
  133. c.sandboxCleanup(c.cfg.ActiveSandboxes)
  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() *agent {
  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: datastore.LocalScope,
  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, cap *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. c.pushNodeDiscovery(driver, capability, nodes, add)
  340. return false
  341. })
  342. }
  343. func (c *Controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  344. var self net.IP
  345. // try swarm-mode config
  346. if agent := c.getAgent(); agent != nil {
  347. self = net.ParseIP(agent.advertiseAddr)
  348. }
  349. if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil {
  350. return
  351. }
  352. for _, node := range nodes {
  353. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  354. var err error
  355. if add {
  356. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  357. } else {
  358. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  359. }
  360. if err != nil {
  361. log.G(context.TODO()).Debugf("discovery notification error: %v", err)
  362. }
  363. }
  364. }
  365. // Config returns the bootup configuration for the controller.
  366. func (c *Controller) Config() config.Config {
  367. c.mu.Lock()
  368. defer c.mu.Unlock()
  369. if c.cfg == nil {
  370. return config.Config{}
  371. }
  372. return *c.cfg
  373. }
  374. func (c *Controller) isManager() bool {
  375. c.mu.Lock()
  376. defer c.mu.Unlock()
  377. if c.cfg == nil || c.cfg.ClusterProvider == nil {
  378. return false
  379. }
  380. return c.cfg.ClusterProvider.IsManager()
  381. }
  382. func (c *Controller) isAgent() bool {
  383. c.mu.Lock()
  384. defer c.mu.Unlock()
  385. if c.cfg == nil || c.cfg.ClusterProvider == nil {
  386. return false
  387. }
  388. return c.cfg.ClusterProvider.IsAgent()
  389. }
  390. func (c *Controller) isDistributedControl() bool {
  391. return !c.isManager() && !c.isAgent()
  392. }
  393. func (c *Controller) GetPluginGetter() plugingetter.PluginGetter {
  394. return c.cfg.PluginGetter
  395. }
  396. func (c *Controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  397. c.agentDriverNotify(driver)
  398. return nil
  399. }
  400. // XXX This should be made driver agnostic. See comment below.
  401. const overlayDSROptionString = "dsr"
  402. // NewNetwork creates a new network of the specified network type. The options
  403. // are network specific and modeled in a generic way.
  404. func (c *Controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  405. var (
  406. caps driverapi.Capability
  407. err error
  408. t *network
  409. skipCfgEpCount bool
  410. )
  411. if id != "" {
  412. c.networkLocker.Lock(id)
  413. defer c.networkLocker.Unlock(id) //nolint:errcheck
  414. if _, err = c.NetworkByID(id); err == nil {
  415. return nil, NetworkNameError(id)
  416. }
  417. }
  418. if strings.TrimSpace(name) == "" {
  419. return nil, ErrInvalidName(name)
  420. }
  421. if id == "" {
  422. id = stringid.GenerateRandomID()
  423. }
  424. defaultIpam := defaultIpamForNetworkType(networkType)
  425. // Construct the network object
  426. nw := &network{
  427. name: name,
  428. networkType: networkType,
  429. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  430. ipamType: defaultIpam,
  431. id: id,
  432. created: time.Now(),
  433. ctrlr: c,
  434. persist: true,
  435. drvOnce: &sync.Once{},
  436. loadBalancerMode: loadBalancerModeDefault,
  437. }
  438. nw.processOptions(options...)
  439. if err = nw.validateConfiguration(); err != nil {
  440. return nil, err
  441. }
  442. // Reset network types, force local scope and skip allocation and
  443. // plumbing for configuration networks. Reset of the config-only
  444. // network drivers is needed so that this special network is not
  445. // usable by old engine versions.
  446. if nw.configOnly {
  447. nw.scope = datastore.LocalScope
  448. nw.networkType = "null"
  449. goto addToStore
  450. }
  451. _, caps, err = nw.resolveDriver(nw.networkType, true)
  452. if err != nil {
  453. return nil, err
  454. }
  455. if nw.scope == datastore.LocalScope && caps.DataScope == datastore.GlobalScope {
  456. return nil, types.ForbiddenErrorf("cannot downgrade network scope for %s networks", networkType)
  457. }
  458. if nw.ingress && caps.DataScope != datastore.GlobalScope {
  459. return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
  460. }
  461. // At this point the network scope is still unknown if not set by user
  462. if (caps.DataScope == datastore.GlobalScope || nw.scope == datastore.SwarmScope) &&
  463. !c.isDistributedControl() && !nw.dynamic {
  464. if c.isManager() {
  465. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  466. return nil, ManagerRedirectError(name)
  467. }
  468. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  469. }
  470. if nw.scope == datastore.SwarmScope && c.isDistributedControl() {
  471. return nil, types.ForbiddenErrorf("cannot create a swarm scoped network when swarm is not active")
  472. }
  473. // Make sure we have a driver available for this network type
  474. // before we allocate anything.
  475. if _, err := nw.driver(true); err != nil {
  476. return nil, err
  477. }
  478. // From this point on, we need the network specific configuration,
  479. // which may come from a configuration-only network
  480. if nw.configFrom != "" {
  481. t, err = c.getConfigNetwork(nw.configFrom)
  482. if err != nil {
  483. return nil, types.NotFoundErrorf("configuration network %q does not exist", nw.configFrom)
  484. }
  485. if err = t.applyConfigurationTo(nw); err != nil {
  486. return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
  487. }
  488. nw.generic[netlabel.Internal] = nw.internal
  489. defer func() {
  490. if err == nil && !skipCfgEpCount {
  491. if err := t.getEpCnt().IncEndpointCnt(); err != nil {
  492. log.G(context.TODO()).Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
  493. t.Name(), nw.Name(), err)
  494. }
  495. }
  496. }()
  497. }
  498. err = nw.ipamAllocate()
  499. if err != nil {
  500. return nil, err
  501. }
  502. defer func() {
  503. if err != nil {
  504. nw.ipamRelease()
  505. }
  506. }()
  507. err = c.addNetwork(nw)
  508. if err != nil {
  509. if _, ok := err.(types.MaskableError); ok { //nolint:gosimple
  510. // This error can be ignored and set this boolean
  511. // value to skip a refcount increment for configOnly networks
  512. skipCfgEpCount = true
  513. } else {
  514. return nil, err
  515. }
  516. }
  517. defer func() {
  518. if err != nil {
  519. if e := nw.deleteNetwork(); e != nil {
  520. log.G(context.TODO()).Warnf("couldn't roll back driver network on network %s creation failure: %v", nw.name, err)
  521. }
  522. }
  523. }()
  524. // XXX If the driver type is "overlay" check the options for DSR
  525. // being set. If so, set the network's load balancing mode to DSR.
  526. // This should really be done in a network option, but due to
  527. // time pressure to get this in without adding changes to moby,
  528. // swarm and CLI, it is being implemented as a driver-specific
  529. // option. Unfortunately, drivers can't influence the core
  530. // "libnetwork.network" data type. Hence we need this hack code
  531. // to implement in this manner.
  532. if gval, ok := nw.generic[netlabel.GenericData]; ok && nw.networkType == "overlay" {
  533. optMap := gval.(map[string]string)
  534. if _, ok := optMap[overlayDSROptionString]; ok {
  535. nw.loadBalancerMode = loadBalancerModeDSR
  536. }
  537. }
  538. addToStore:
  539. // First store the endpoint count, then the network. To avoid to
  540. // end up with a datastore containing a network and not an epCnt,
  541. // in case of an ungraceful shutdown during this function call.
  542. epCnt := &endpointCnt{n: nw}
  543. if err = c.updateToStore(epCnt); err != nil {
  544. return nil, err
  545. }
  546. defer func() {
  547. if err != nil {
  548. if e := c.deleteFromStore(epCnt); e != nil {
  549. log.G(context.TODO()).Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  550. }
  551. }
  552. }()
  553. nw.epCnt = epCnt
  554. if err = c.updateToStore(nw); err != nil {
  555. return nil, err
  556. }
  557. defer func() {
  558. if err != nil {
  559. if e := c.deleteFromStore(nw); e != nil {
  560. log.G(context.TODO()).Warnf("could not rollback from store, network %v on failure (%v): %v", nw, err, e)
  561. }
  562. }
  563. }()
  564. if nw.configOnly {
  565. return nw, nil
  566. }
  567. joinCluster(nw)
  568. defer func() {
  569. if err != nil {
  570. nw.cancelDriverWatches()
  571. if e := nw.leaveCluster(); e != nil {
  572. log.G(context.TODO()).Warnf("Failed to leave agent cluster on network %s on failure (%v): %v", nw.name, err, e)
  573. }
  574. }
  575. }()
  576. if nw.hasLoadBalancerEndpoint() {
  577. if err = nw.createLoadBalancerSandbox(); err != nil {
  578. return nil, err
  579. }
  580. }
  581. if !c.isDistributedControl() {
  582. c.mu.Lock()
  583. arrangeIngressFilterRule()
  584. c.mu.Unlock()
  585. }
  586. arrangeUserFilterRule()
  587. return nw, nil
  588. }
  589. var joinCluster NetworkWalker = func(nw Network) bool {
  590. n := nw.(*network)
  591. if n.configOnly {
  592. return false
  593. }
  594. if err := n.joinCluster(); err != nil {
  595. log.G(context.TODO()).Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  596. }
  597. n.addDriverWatches()
  598. return false
  599. }
  600. func (c *Controller) reservePools() {
  601. networks, err := c.getNetworks()
  602. if err != nil {
  603. log.G(context.TODO()).Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  604. return
  605. }
  606. for _, n := range networks {
  607. if n.configOnly {
  608. continue
  609. }
  610. if !doReplayPoolReserve(n) {
  611. continue
  612. }
  613. // Construct pseudo configs for the auto IP case
  614. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  615. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  616. if autoIPv4 {
  617. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  618. }
  619. if n.enableIPv6 && autoIPv6 {
  620. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  621. }
  622. // Account current network gateways
  623. for i, cfg := range n.ipamV4Config {
  624. if cfg.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  625. cfg.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  626. }
  627. }
  628. if n.enableIPv6 {
  629. for i, cfg := range n.ipamV6Config {
  630. if cfg.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  631. cfg.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  632. }
  633. }
  634. }
  635. // Reserve pools
  636. if err := n.ipamAllocate(); err != nil {
  637. log.G(context.TODO()).Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  638. }
  639. // Reserve existing endpoints' addresses
  640. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  641. if err != nil {
  642. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  643. continue
  644. }
  645. epl, err := n.getEndpointsFromStore()
  646. if err != nil {
  647. log.G(context.TODO()).Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  648. continue
  649. }
  650. for _, ep := range epl {
  651. if ep.Iface() == nil {
  652. log.G(context.TODO()).Warnf("endpoint interface is empty for %q (%s)", ep.Name(), ep.ID())
  653. continue
  654. }
  655. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  656. log.G(context.TODO()).Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  657. ep.Name(), ep.ID(), n.Name(), n.ID())
  658. }
  659. }
  660. }
  661. }
  662. func doReplayPoolReserve(n *network) bool {
  663. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  664. if err != nil {
  665. log.G(context.TODO()).Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  666. return false
  667. }
  668. return caps.RequiresRequestReplay
  669. }
  670. func (c *Controller) addNetwork(n *network) error {
  671. d, err := n.driver(true)
  672. if err != nil {
  673. return err
  674. }
  675. // Create the network
  676. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  677. return err
  678. }
  679. n.startResolver()
  680. return nil
  681. }
  682. // Networks returns the list of Network(s) managed by this controller.
  683. func (c *Controller) Networks() []Network {
  684. var list []Network
  685. for _, n := range c.getNetworksFromStore() {
  686. if n.inDelete {
  687. continue
  688. }
  689. list = append(list, n)
  690. }
  691. return list
  692. }
  693. // WalkNetworks uses the provided function to walk the Network(s) managed by this controller.
  694. func (c *Controller) WalkNetworks(walker NetworkWalker) {
  695. for _, n := range c.Networks() {
  696. if walker(n) {
  697. return
  698. }
  699. }
  700. }
  701. // NetworkByName returns the Network which has the passed name.
  702. // If not found, the error [ErrNoSuchNetwork] is returned.
  703. func (c *Controller) NetworkByName(name string) (Network, error) {
  704. if name == "" {
  705. return nil, ErrInvalidName(name)
  706. }
  707. var n Network
  708. s := func(current Network) bool {
  709. if current.Name() == name {
  710. n = current
  711. return true
  712. }
  713. return false
  714. }
  715. c.WalkNetworks(s)
  716. if n == nil {
  717. return nil, ErrNoSuchNetwork(name)
  718. }
  719. return n, nil
  720. }
  721. // NetworkByID returns the Network which has the passed id.
  722. // If not found, the error [ErrNoSuchNetwork] is returned.
  723. func (c *Controller) NetworkByID(id string) (Network, error) {
  724. if id == "" {
  725. return nil, ErrInvalidID(id)
  726. }
  727. n, err := c.getNetworkFromStore(id)
  728. if err != nil {
  729. return nil, ErrNoSuchNetwork(id)
  730. }
  731. return n, nil
  732. }
  733. // NewSandbox creates a new sandbox for containerID.
  734. func (c *Controller) NewSandbox(containerID string, options ...SandboxOption) (*Sandbox, error) {
  735. if containerID == "" {
  736. return nil, types.BadRequestErrorf("invalid container ID")
  737. }
  738. var sb *Sandbox
  739. c.mu.Lock()
  740. for _, s := range c.sandboxes {
  741. if s.containerID == containerID {
  742. // If not a stub, then we already have a complete sandbox.
  743. if !s.isStub {
  744. sbID := s.ID()
  745. c.mu.Unlock()
  746. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  747. }
  748. // We already have a stub sandbox from the
  749. // store. Make use of it so that we don't lose
  750. // the endpoints from store but reset the
  751. // isStub flag.
  752. sb = s
  753. sb.isStub = false
  754. break
  755. }
  756. }
  757. c.mu.Unlock()
  758. sandboxID := stringid.GenerateRandomID()
  759. if runtime.GOOS == "windows" {
  760. sandboxID = containerID
  761. }
  762. // Create sandbox and process options first. Key generation depends on an option
  763. if sb == nil {
  764. sb = &Sandbox{
  765. id: sandboxID,
  766. containerID: containerID,
  767. endpoints: []*Endpoint{},
  768. epPriority: map[string]int{},
  769. populatedEndpoints: map[string]struct{}{},
  770. config: containerConfig{},
  771. controller: c,
  772. extDNS: []extDNSEntry{},
  773. }
  774. }
  775. sb.processOptions(options...)
  776. c.mu.Lock()
  777. if sb.ingress && c.ingressSandbox != nil {
  778. c.mu.Unlock()
  779. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  780. }
  781. if sb.ingress {
  782. c.ingressSandbox = sb
  783. sb.config.hostsPath = filepath.Join(c.cfg.DataDir, "/network/files/hosts")
  784. sb.config.resolvConfPath = filepath.Join(c.cfg.DataDir, "/network/files/resolv.conf")
  785. sb.id = "ingress_sbox"
  786. } else if sb.loadBalancerNID != "" {
  787. sb.id = "lb_" + sb.loadBalancerNID
  788. }
  789. c.mu.Unlock()
  790. var err error
  791. defer func() {
  792. if err != nil {
  793. c.mu.Lock()
  794. if sb.ingress {
  795. c.ingressSandbox = nil
  796. }
  797. c.mu.Unlock()
  798. }
  799. }()
  800. if err = sb.setupResolutionFiles(); err != nil {
  801. return nil, err
  802. }
  803. if sb.config.useDefaultSandBox {
  804. c.sboxOnce.Do(func() {
  805. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  806. })
  807. if err != nil {
  808. c.sboxOnce = sync.Once{}
  809. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  810. }
  811. sb.osSbox = c.defOsSbox
  812. }
  813. if sb.osSbox == nil && !sb.config.useExternalKey {
  814. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  815. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  816. }
  817. }
  818. if sb.osSbox != nil {
  819. // Apply operating specific knobs on the load balancer sandbox
  820. err := sb.osSbox.InvokeFunc(func() {
  821. sb.osSbox.ApplyOSTweaks(sb.oslTypes)
  822. })
  823. if err != nil {
  824. log.G(context.TODO()).Errorf("Failed to apply performance tuning sysctls to the sandbox: %v", err)
  825. }
  826. // Keep this just so performance is not changed
  827. sb.osSbox.ApplyOSTweaks(sb.oslTypes)
  828. }
  829. c.mu.Lock()
  830. c.sandboxes[sb.id] = sb
  831. c.mu.Unlock()
  832. defer func() {
  833. if err != nil {
  834. c.mu.Lock()
  835. delete(c.sandboxes, sb.id)
  836. c.mu.Unlock()
  837. }
  838. }()
  839. err = sb.storeUpdate()
  840. if err != nil {
  841. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  842. }
  843. return sb, nil
  844. }
  845. // Sandboxes returns the list of Sandbox(s) managed by this controller.
  846. func (c *Controller) Sandboxes() []*Sandbox {
  847. c.mu.Lock()
  848. defer c.mu.Unlock()
  849. list := make([]*Sandbox, 0, len(c.sandboxes))
  850. for _, s := range c.sandboxes {
  851. // Hide stub sandboxes from libnetwork users
  852. if s.isStub {
  853. continue
  854. }
  855. list = append(list, s)
  856. }
  857. return list
  858. }
  859. // WalkSandboxes uses the provided function to walk the Sandbox(s) managed by this controller.
  860. func (c *Controller) WalkSandboxes(walker SandboxWalker) {
  861. for _, sb := range c.Sandboxes() {
  862. if walker(sb) {
  863. return
  864. }
  865. }
  866. }
  867. // SandboxByID returns the Sandbox which has the passed id.
  868. // If not found, a [types.NotFoundError] is returned.
  869. func (c *Controller) SandboxByID(id string) (*Sandbox, error) {
  870. if id == "" {
  871. return nil, ErrInvalidID(id)
  872. }
  873. c.mu.Lock()
  874. s, ok := c.sandboxes[id]
  875. c.mu.Unlock()
  876. if !ok {
  877. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  878. }
  879. return s, nil
  880. }
  881. // SandboxDestroy destroys a sandbox given a container ID.
  882. func (c *Controller) SandboxDestroy(id string) error {
  883. var sb *Sandbox
  884. c.mu.Lock()
  885. for _, s := range c.sandboxes {
  886. if s.containerID == id {
  887. sb = s
  888. break
  889. }
  890. }
  891. c.mu.Unlock()
  892. // It is not an error if sandbox is not available
  893. if sb == nil {
  894. return nil
  895. }
  896. return sb.Delete()
  897. }
  898. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  899. func SandboxContainerWalker(out **Sandbox, containerID string) SandboxWalker {
  900. return func(sb *Sandbox) bool {
  901. if sb.ContainerID() == containerID {
  902. *out = sb
  903. return true
  904. }
  905. return false
  906. }
  907. }
  908. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  909. func SandboxKeyWalker(out **Sandbox, key string) SandboxWalker {
  910. return func(sb *Sandbox) bool {
  911. if sb.Key() == key {
  912. *out = sb
  913. return true
  914. }
  915. return false
  916. }
  917. }
  918. func (c *Controller) loadDriver(networkType string) error {
  919. var err error
  920. if pg := c.GetPluginGetter(); pg != nil {
  921. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  922. } else {
  923. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  924. }
  925. if err != nil {
  926. if errors.Cause(err) == plugins.ErrNotFound {
  927. return types.NotFoundErrorf(err.Error())
  928. }
  929. return err
  930. }
  931. return nil
  932. }
  933. func (c *Controller) loadIPAMDriver(name string) error {
  934. var err error
  935. if pg := c.GetPluginGetter(); pg != nil {
  936. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  937. } else {
  938. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  939. }
  940. if err != nil {
  941. if errors.Cause(err) == plugins.ErrNotFound {
  942. return types.NotFoundErrorf(err.Error())
  943. }
  944. return err
  945. }
  946. return nil
  947. }
  948. func (c *Controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  949. id, cap := c.ipamRegistry.IPAM(name)
  950. if id == nil {
  951. // Might be a plugin name. Try loading it
  952. if err := c.loadIPAMDriver(name); err != nil {
  953. return nil, nil, err
  954. }
  955. // Now that we resolved the plugin, try again looking up the registry
  956. id, cap = c.ipamRegistry.IPAM(name)
  957. if id == nil {
  958. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  959. }
  960. }
  961. return id, cap, nil
  962. }
  963. // Stop stops the network controller.
  964. func (c *Controller) Stop() {
  965. c.closeStores()
  966. c.stopExternalKeyListener()
  967. osl.GC()
  968. }
  969. // StartDiagnostic starts the network diagnostic server listening on port.
  970. func (c *Controller) StartDiagnostic(port int) {
  971. c.mu.Lock()
  972. if !c.DiagnosticServer.IsDiagnosticEnabled() {
  973. c.DiagnosticServer.EnableDiagnostic("127.0.0.1", port)
  974. }
  975. c.mu.Unlock()
  976. }
  977. // StopDiagnostic stops the network diagnostic server.
  978. func (c *Controller) StopDiagnostic() {
  979. c.mu.Lock()
  980. if c.DiagnosticServer.IsDiagnosticEnabled() {
  981. c.DiagnosticServer.DisableDiagnostic()
  982. }
  983. c.mu.Unlock()
  984. }
  985. // IsDiagnosticEnabled returns true if the diagnostic server is running.
  986. func (c *Controller) IsDiagnosticEnabled() bool {
  987. c.mu.Lock()
  988. defer c.mu.Unlock()
  989. return c.DiagnosticServer.IsDiagnosticEnabled()
  990. }