controller.go 34 KB

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