controller.go 31 KB

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