controller.go 31 KB

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