controller.go 31 KB

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