controller.go 33 KB

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