controller.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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/Sirupsen/logrus"
  48. "github.com/docker/docker/pkg/discovery"
  49. "github.com/docker/docker/pkg/locker"
  50. "github.com/docker/docker/pkg/plugingetter"
  51. "github.com/docker/docker/pkg/plugins"
  52. "github.com/docker/docker/pkg/stringid"
  53. "github.com/docker/libnetwork/cluster"
  54. "github.com/docker/libnetwork/config"
  55. "github.com/docker/libnetwork/datastore"
  56. "github.com/docker/libnetwork/discoverapi"
  57. "github.com/docker/libnetwork/driverapi"
  58. "github.com/docker/libnetwork/drvregistry"
  59. "github.com/docker/libnetwork/hostdiscovery"
  60. "github.com/docker/libnetwork/ipamapi"
  61. "github.com/docker/libnetwork/netlabel"
  62. "github.com/docker/libnetwork/osl"
  63. "github.com/docker/libnetwork/types"
  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.cleanupServiceBindings("")
  289. c.agentStopComplete()
  290. return
  291. }
  292. }
  293. }
  294. // AgentInitWait waits for agent initialization to be completed in the controller.
  295. func (c *controller) AgentInitWait() {
  296. c.Lock()
  297. agentInitDone := c.agentInitDone
  298. c.Unlock()
  299. if agentInitDone != nil {
  300. <-agentInitDone
  301. }
  302. }
  303. // AgentStopWait waits for the Agent stop to be completed in the controller
  304. func (c *controller) AgentStopWait() {
  305. c.Lock()
  306. agentStopDone := c.agentStopDone
  307. c.Unlock()
  308. if agentStopDone != nil {
  309. <-agentStopDone
  310. }
  311. }
  312. // agentOperationStart marks the start of an Agent Init or Agent Stop
  313. func (c *controller) agentOperationStart() {
  314. c.Lock()
  315. if c.agentInitDone == nil {
  316. c.agentInitDone = make(chan struct{})
  317. }
  318. if c.agentStopDone == nil {
  319. c.agentStopDone = make(chan struct{})
  320. }
  321. c.Unlock()
  322. }
  323. // agentInitComplete notifies the successful completion of the Agent initialization
  324. func (c *controller) agentInitComplete() {
  325. c.Lock()
  326. if c.agentInitDone != nil {
  327. close(c.agentInitDone)
  328. c.agentInitDone = nil
  329. }
  330. c.Unlock()
  331. }
  332. // agentStopComplete notifies the successful completion of the Agent stop
  333. func (c *controller) agentStopComplete() {
  334. c.Lock()
  335. if c.agentStopDone != nil {
  336. close(c.agentStopDone)
  337. c.agentStopDone = nil
  338. }
  339. c.Unlock()
  340. }
  341. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  342. if c.cfg == nil {
  343. return nil
  344. }
  345. config := make(map[string]interface{})
  346. for _, label := range c.cfg.Daemon.Labels {
  347. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  348. continue
  349. }
  350. config[netlabel.Key(label)] = netlabel.Value(label)
  351. }
  352. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  353. if ok {
  354. for k, v := range drvCfg.(map[string]interface{}) {
  355. config[k] = v
  356. }
  357. }
  358. for k, v := range c.cfg.Scopes {
  359. if !v.IsValid() {
  360. continue
  361. }
  362. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  363. Scope: k,
  364. Provider: v.Client.Provider,
  365. Address: v.Client.Address,
  366. Config: v.Client.Config,
  367. }
  368. }
  369. return config
  370. }
  371. var procReloadConfig = make(chan (bool), 1)
  372. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  373. procReloadConfig <- true
  374. defer func() { <-procReloadConfig }()
  375. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  376. // Refuse the configuration if it alters an existing datastore client configuration.
  377. update := false
  378. cfg := config.ParseConfigOptions(cfgOptions...)
  379. for s := range c.cfg.Scopes {
  380. if _, ok := cfg.Scopes[s]; !ok {
  381. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  382. }
  383. }
  384. for s, nSCfg := range cfg.Scopes {
  385. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  386. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  387. eSCfg.Client.Address != nSCfg.Client.Address {
  388. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  389. }
  390. } else {
  391. if err := c.initScopedStore(s, nSCfg); err != nil {
  392. return err
  393. }
  394. update = true
  395. }
  396. }
  397. if !update {
  398. return nil
  399. }
  400. c.Lock()
  401. c.cfg = cfg
  402. c.Unlock()
  403. var dsConfig *discoverapi.DatastoreConfigData
  404. for scope, sCfg := range cfg.Scopes {
  405. if scope == datastore.LocalScope || !sCfg.IsValid() {
  406. continue
  407. }
  408. dsConfig = &discoverapi.DatastoreConfigData{
  409. Scope: scope,
  410. Provider: sCfg.Client.Provider,
  411. Address: sCfg.Client.Address,
  412. Config: sCfg.Client.Config,
  413. }
  414. break
  415. }
  416. if dsConfig == nil {
  417. return nil
  418. }
  419. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  420. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  421. if err != nil {
  422. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  423. }
  424. return false
  425. })
  426. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  427. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  428. if err != nil {
  429. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  430. }
  431. return false
  432. })
  433. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  434. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  435. logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  436. }
  437. }
  438. return nil
  439. }
  440. func (c *controller) ID() string {
  441. return c.id
  442. }
  443. func (c *controller) BuiltinDrivers() []string {
  444. drivers := []string{}
  445. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  446. if driver.IsBuiltIn() {
  447. drivers = append(drivers, name)
  448. }
  449. return false
  450. })
  451. return drivers
  452. }
  453. func (c *controller) BuiltinIPAMDrivers() []string {
  454. drivers := []string{}
  455. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  456. if driver.IsBuiltIn() {
  457. drivers = append(drivers, name)
  458. }
  459. return false
  460. })
  461. return drivers
  462. }
  463. func (c *controller) validateHostDiscoveryConfig() bool {
  464. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  465. return false
  466. }
  467. return true
  468. }
  469. func (c *controller) clusterHostID() string {
  470. c.Lock()
  471. defer c.Unlock()
  472. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  473. return ""
  474. }
  475. addr := strings.Split(c.cfg.Cluster.Address, ":")
  476. return addr[0]
  477. }
  478. func (c *controller) isNodeAlive(node string) bool {
  479. if c.discovery == nil {
  480. return false
  481. }
  482. nodes := c.discovery.Fetch()
  483. for _, n := range nodes {
  484. if n.String() == node {
  485. return true
  486. }
  487. }
  488. return false
  489. }
  490. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  491. if c.cfg == nil {
  492. return fmt.Errorf("discovery initialization requires a valid configuration")
  493. }
  494. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  495. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  496. }
  497. func (c *controller) activeCallback() {
  498. ds := c.getStore(datastore.GlobalScope)
  499. if ds != nil && !ds.Active() {
  500. ds.RestartWatch()
  501. }
  502. }
  503. func (c *controller) hostJoinCallback(nodes []net.IP) {
  504. c.processNodeDiscovery(nodes, true)
  505. }
  506. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  507. c.processNodeDiscovery(nodes, false)
  508. }
  509. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  510. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  511. c.pushNodeDiscovery(driver, capability, nodes, add)
  512. return false
  513. })
  514. }
  515. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  516. var self net.IP
  517. if c.cfg != nil {
  518. addr := strings.Split(c.cfg.Cluster.Address, ":")
  519. self = net.ParseIP(addr[0])
  520. // if external kvstore is not configured, try swarm-mode config
  521. if self == nil {
  522. if agent := c.getAgent(); agent != nil {
  523. self = net.ParseIP(agent.advertiseAddr)
  524. }
  525. }
  526. }
  527. if d == nil || cap.ConnectivityScope != datastore.GlobalScope || nodes == nil {
  528. return
  529. }
  530. for _, node := range nodes {
  531. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  532. var err error
  533. if add {
  534. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  535. } else {
  536. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  537. }
  538. if err != nil {
  539. logrus.Debugf("discovery notification error: %v", err)
  540. }
  541. }
  542. }
  543. func (c *controller) Config() config.Config {
  544. c.Lock()
  545. defer c.Unlock()
  546. if c.cfg == nil {
  547. return config.Config{}
  548. }
  549. return *c.cfg
  550. }
  551. func (c *controller) isManager() bool {
  552. c.Lock()
  553. defer c.Unlock()
  554. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  555. return false
  556. }
  557. return c.cfg.Daemon.ClusterProvider.IsManager()
  558. }
  559. func (c *controller) isAgent() bool {
  560. c.Lock()
  561. defer c.Unlock()
  562. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  563. return false
  564. }
  565. return c.cfg.Daemon.ClusterProvider.IsAgent()
  566. }
  567. func (c *controller) isDistributedControl() bool {
  568. return !c.isManager() && !c.isAgent()
  569. }
  570. func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
  571. return c.drvRegistry.GetPluginGetter()
  572. }
  573. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  574. c.Lock()
  575. hd := c.discovery
  576. c.Unlock()
  577. if hd != nil {
  578. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  579. }
  580. c.agentDriverNotify(driver)
  581. return nil
  582. }
  583. // NewNetwork creates a new network of the specified network type. The options
  584. // are network specific and modeled in a generic way.
  585. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  586. if id != "" {
  587. c.networkLocker.Lock(id)
  588. defer c.networkLocker.Unlock(id)
  589. if _, err := c.NetworkByID(id); err == nil {
  590. return nil, NetworkNameError(id)
  591. }
  592. }
  593. if !config.IsValidName(name) {
  594. return nil, ErrInvalidName(name)
  595. }
  596. if id == "" {
  597. id = stringid.GenerateRandomID()
  598. }
  599. defaultIpam := defaultIpamForNetworkType(networkType)
  600. // Construct the network object
  601. network := &network{
  602. name: name,
  603. networkType: networkType,
  604. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  605. ipamType: defaultIpam,
  606. id: id,
  607. created: time.Now(),
  608. ctrlr: c,
  609. persist: true,
  610. drvOnce: &sync.Once{},
  611. }
  612. network.processOptions(options...)
  613. if err := network.validateConfiguration(); err != nil {
  614. return nil, err
  615. }
  616. var (
  617. cap *driverapi.Capability
  618. err error
  619. )
  620. // Reset network types, force local scope and skip allocation and
  621. // plumbing for configuration networks. Reset of the config-only
  622. // network drivers is needed so that this special network is not
  623. // usable by old engine versions.
  624. if network.configOnly {
  625. network.scope = datastore.LocalScope
  626. network.networkType = "null"
  627. network.ipamType = ""
  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. // Make sure we have a driver available for this network type
  650. // before we allocate anything.
  651. if _, err := network.driver(true); err != nil {
  652. return nil, err
  653. }
  654. // From this point on, we need the network specific configuration,
  655. // which may come from a configuration-only network
  656. if network.configFrom != "" {
  657. t, err := c.getConfigNetwork(network.configFrom)
  658. if err != nil {
  659. return nil, types.NotFoundErrorf("configuration network %q does not exist", network.configFrom)
  660. }
  661. if err := t.applyConfigurationTo(network); err != nil {
  662. return nil, types.InternalErrorf("Failed to apply configuration: %v", err)
  663. }
  664. defer func() {
  665. if err == nil {
  666. if err := t.getEpCnt().IncEndpointCnt(); err != nil {
  667. logrus.Warnf("Failed to update reference count for configuration network %q on creation of network %q: %v",
  668. t.Name(), network.Name(), err)
  669. }
  670. }
  671. }()
  672. }
  673. err = network.ipamAllocate()
  674. if err != nil {
  675. return nil, err
  676. }
  677. defer func() {
  678. if err != nil {
  679. network.ipamRelease()
  680. }
  681. }()
  682. err = c.addNetwork(network)
  683. if err != nil {
  684. return nil, err
  685. }
  686. defer func() {
  687. if err != nil {
  688. if e := network.deleteNetwork(); e != nil {
  689. logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  690. }
  691. }
  692. }()
  693. addToStore:
  694. // First store the endpoint count, then the network. To avoid to
  695. // end up with a datastore containing a network and not an epCnt,
  696. // in case of an ungraceful shutdown during this function call.
  697. epCnt := &endpointCnt{n: network}
  698. if err = c.updateToStore(epCnt); err != nil {
  699. return nil, err
  700. }
  701. defer func() {
  702. if err != nil {
  703. if e := c.deleteFromStore(epCnt); e != nil {
  704. logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  705. }
  706. }
  707. }()
  708. network.epCnt = epCnt
  709. if err = c.updateToStore(network); err != nil {
  710. return nil, err
  711. }
  712. if network.configOnly {
  713. return network, nil
  714. }
  715. joinCluster(network)
  716. if !c.isDistributedControl() {
  717. c.Lock()
  718. arrangeIngressFilterRule()
  719. c.Unlock()
  720. }
  721. return network, nil
  722. }
  723. var joinCluster NetworkWalker = func(nw Network) bool {
  724. n := nw.(*network)
  725. if n.configOnly {
  726. return false
  727. }
  728. if err := n.joinCluster(); err != nil {
  729. logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  730. }
  731. n.addDriverWatches()
  732. return false
  733. }
  734. func (c *controller) reservePools() {
  735. networks, err := c.getNetworksForScope(datastore.LocalScope)
  736. if err != nil {
  737. logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  738. return
  739. }
  740. for _, n := range networks {
  741. if n.configOnly {
  742. continue
  743. }
  744. if !doReplayPoolReserve(n) {
  745. continue
  746. }
  747. // Construct pseudo configs for the auto IP case
  748. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  749. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  750. if autoIPv4 {
  751. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  752. }
  753. if n.enableIPv6 && autoIPv6 {
  754. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  755. }
  756. // Account current network gateways
  757. for i, c := range n.ipamV4Config {
  758. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  759. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  760. }
  761. }
  762. if n.enableIPv6 {
  763. for i, c := range n.ipamV6Config {
  764. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  765. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  766. }
  767. }
  768. }
  769. // Reserve pools
  770. if err := n.ipamAllocate(); err != nil {
  771. logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  772. }
  773. // Reserve existing endpoints' addresses
  774. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  775. if err != nil {
  776. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  777. continue
  778. }
  779. epl, err := n.getEndpointsFromStore()
  780. if err != nil {
  781. logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  782. continue
  783. }
  784. for _, ep := range epl {
  785. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  786. logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  787. ep.Name(), ep.ID(), n.Name(), n.ID())
  788. }
  789. }
  790. }
  791. }
  792. func doReplayPoolReserve(n *network) bool {
  793. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  794. if err != nil {
  795. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  796. return false
  797. }
  798. return caps.RequiresRequestReplay
  799. }
  800. func (c *controller) addNetwork(n *network) error {
  801. d, err := n.driver(true)
  802. if err != nil {
  803. return err
  804. }
  805. // Create the network
  806. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  807. return err
  808. }
  809. n.startResolver()
  810. return nil
  811. }
  812. func (c *controller) Networks() []Network {
  813. var list []Network
  814. networks, err := c.getNetworksFromStore()
  815. if err != nil {
  816. logrus.Error(err)
  817. }
  818. for _, n := range networks {
  819. if n.inDelete {
  820. continue
  821. }
  822. list = append(list, n)
  823. }
  824. return list
  825. }
  826. func (c *controller) WalkNetworks(walker NetworkWalker) {
  827. for _, n := range c.Networks() {
  828. if walker(n) {
  829. return
  830. }
  831. }
  832. }
  833. func (c *controller) NetworkByName(name string) (Network, error) {
  834. if name == "" {
  835. return nil, ErrInvalidName(name)
  836. }
  837. var n Network
  838. s := func(current Network) bool {
  839. if current.Name() == name {
  840. n = current
  841. return true
  842. }
  843. return false
  844. }
  845. c.WalkNetworks(s)
  846. if n == nil {
  847. return nil, ErrNoSuchNetwork(name)
  848. }
  849. return n, nil
  850. }
  851. func (c *controller) NetworkByID(id string) (Network, error) {
  852. if id == "" {
  853. return nil, ErrInvalidID(id)
  854. }
  855. n, err := c.getNetworkFromStore(id)
  856. if err != nil {
  857. return nil, ErrNoSuchNetwork(id)
  858. }
  859. return n, nil
  860. }
  861. // NewSandbox creates a new sandbox for the passed container id
  862. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  863. if containerID == "" {
  864. return nil, types.BadRequestErrorf("invalid container ID")
  865. }
  866. var sb *sandbox
  867. c.Lock()
  868. for _, s := range c.sandboxes {
  869. if s.containerID == containerID {
  870. // If not a stub, then we already have a complete sandbox.
  871. if !s.isStub {
  872. sbID := s.ID()
  873. c.Unlock()
  874. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  875. }
  876. // We already have a stub sandbox from the
  877. // store. Make use of it so that we don't lose
  878. // the endpoints from store but reset the
  879. // isStub flag.
  880. sb = s
  881. sb.isStub = false
  882. break
  883. }
  884. }
  885. c.Unlock()
  886. // Create sandbox and process options first. Key generation depends on an option
  887. if sb == nil {
  888. sb = &sandbox{
  889. id: stringid.GenerateRandomID(),
  890. containerID: containerID,
  891. endpoints: epHeap{},
  892. epPriority: map[string]int{},
  893. populatedEndpoints: map[string]struct{}{},
  894. config: containerConfig{},
  895. controller: c,
  896. extDNS: []extDNSEntry{},
  897. }
  898. }
  899. sBox = sb
  900. heap.Init(&sb.endpoints)
  901. sb.processOptions(options...)
  902. c.Lock()
  903. if sb.ingress && c.ingressSandbox != nil {
  904. c.Unlock()
  905. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  906. }
  907. if sb.ingress {
  908. c.ingressSandbox = sb
  909. sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts")
  910. sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf")
  911. sb.id = "ingress_sbox"
  912. }
  913. c.Unlock()
  914. defer func() {
  915. if err != nil {
  916. c.Lock()
  917. if sb.ingress {
  918. c.ingressSandbox = nil
  919. }
  920. c.Unlock()
  921. }
  922. }()
  923. if err = sb.setupResolutionFiles(); err != nil {
  924. return nil, err
  925. }
  926. if sb.config.useDefaultSandBox {
  927. c.sboxOnce.Do(func() {
  928. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  929. })
  930. if err != nil {
  931. c.sboxOnce = sync.Once{}
  932. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  933. }
  934. sb.osSbox = c.defOsSbox
  935. }
  936. if sb.osSbox == nil && !sb.config.useExternalKey {
  937. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  938. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  939. }
  940. }
  941. c.Lock()
  942. c.sandboxes[sb.id] = sb
  943. c.Unlock()
  944. defer func() {
  945. if err != nil {
  946. c.Lock()
  947. delete(c.sandboxes, sb.id)
  948. c.Unlock()
  949. }
  950. }()
  951. err = sb.storeUpdate()
  952. if err != nil {
  953. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  954. }
  955. return sb, nil
  956. }
  957. func (c *controller) Sandboxes() []Sandbox {
  958. c.Lock()
  959. defer c.Unlock()
  960. list := make([]Sandbox, 0, len(c.sandboxes))
  961. for _, s := range c.sandboxes {
  962. // Hide stub sandboxes from libnetwork users
  963. if s.isStub {
  964. continue
  965. }
  966. list = append(list, s)
  967. }
  968. return list
  969. }
  970. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  971. for _, sb := range c.Sandboxes() {
  972. if walker(sb) {
  973. return
  974. }
  975. }
  976. }
  977. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  978. if id == "" {
  979. return nil, ErrInvalidID(id)
  980. }
  981. c.Lock()
  982. s, ok := c.sandboxes[id]
  983. c.Unlock()
  984. if !ok {
  985. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  986. }
  987. return s, nil
  988. }
  989. // SandboxDestroy destroys a sandbox given a container ID
  990. func (c *controller) SandboxDestroy(id string) error {
  991. var sb *sandbox
  992. c.Lock()
  993. for _, s := range c.sandboxes {
  994. if s.containerID == id {
  995. sb = s
  996. break
  997. }
  998. }
  999. c.Unlock()
  1000. // It is not an error if sandbox is not available
  1001. if sb == nil {
  1002. return nil
  1003. }
  1004. return sb.Delete()
  1005. }
  1006. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  1007. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  1008. return func(sb Sandbox) bool {
  1009. if sb.ContainerID() == containerID {
  1010. *out = sb
  1011. return true
  1012. }
  1013. return false
  1014. }
  1015. }
  1016. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  1017. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  1018. return func(sb Sandbox) bool {
  1019. if sb.Key() == key {
  1020. *out = sb
  1021. return true
  1022. }
  1023. return false
  1024. }
  1025. }
  1026. func (c *controller) loadDriver(networkType string) error {
  1027. var err error
  1028. if pg := c.GetPluginGetter(); pg != nil {
  1029. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  1030. } else {
  1031. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  1032. }
  1033. if err != nil {
  1034. if err == plugins.ErrNotFound {
  1035. return types.NotFoundErrorf(err.Error())
  1036. }
  1037. return err
  1038. }
  1039. return nil
  1040. }
  1041. func (c *controller) loadIPAMDriver(name string) error {
  1042. var err error
  1043. if pg := c.GetPluginGetter(); pg != nil {
  1044. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  1045. } else {
  1046. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  1047. }
  1048. if err != nil {
  1049. if err == plugins.ErrNotFound {
  1050. return types.NotFoundErrorf(err.Error())
  1051. }
  1052. return err
  1053. }
  1054. return nil
  1055. }
  1056. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  1057. id, cap := c.drvRegistry.IPAM(name)
  1058. if id == nil {
  1059. // Might be a plugin name. Try loading it
  1060. if err := c.loadIPAMDriver(name); err != nil {
  1061. return nil, nil, err
  1062. }
  1063. // Now that we resolved the plugin, try again looking up the registry
  1064. id, cap = c.drvRegistry.IPAM(name)
  1065. if id == nil {
  1066. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  1067. }
  1068. }
  1069. return id, cap, nil
  1070. }
  1071. func (c *controller) Stop() {
  1072. c.closeStores()
  1073. c.stopExternalKeyListener()
  1074. osl.GC()
  1075. }