controller.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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. c.Lock()
  200. c.cfg.Daemon.ClusterProvider = provider
  201. disableProviderCh := c.cfg.Daemon.DisableProvider
  202. c.Unlock()
  203. if provider != nil {
  204. go c.clusterAgentInit()
  205. } else {
  206. disableProviderCh <- struct{}{}
  207. }
  208. }
  209. func isValidClusteringIP(addr string) bool {
  210. return addr != "" && !net.ParseIP(addr).IsLoopback() && !net.ParseIP(addr).IsUnspecified()
  211. }
  212. // libnetwork side of agent depends on the keys. On the first receipt of
  213. // keys setup the agent. For subsequent key set handle the key change
  214. func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
  215. c.Lock()
  216. existingKeys := c.keys
  217. clusterConfigAvailable := c.clusterConfigAvailable
  218. agent := c.agent
  219. c.Unlock()
  220. subsysKeys := make(map[string]int)
  221. for _, key := range keys {
  222. if key.Subsystem != subsysGossip &&
  223. key.Subsystem != subsysIPSec {
  224. return fmt.Errorf("key received for unrecognized subsystem")
  225. }
  226. subsysKeys[key.Subsystem]++
  227. }
  228. for s, count := range subsysKeys {
  229. if count != keyringSize {
  230. return fmt.Errorf("incorrect number of keys for subsystem %v", s)
  231. }
  232. }
  233. if len(existingKeys) == 0 {
  234. c.Lock()
  235. c.keys = keys
  236. c.Unlock()
  237. if agent != nil {
  238. return (fmt.Errorf("libnetwork agent setup without keys"))
  239. }
  240. if clusterConfigAvailable {
  241. return c.agentSetup()
  242. }
  243. logrus.Debug("received encryption keys before cluster config")
  244. return nil
  245. }
  246. if agent == nil {
  247. c.Lock()
  248. c.keys = keys
  249. c.Unlock()
  250. return nil
  251. }
  252. return c.handleKeyChange(keys)
  253. }
  254. func (c *controller) getAgent() *agent {
  255. c.Lock()
  256. defer c.Unlock()
  257. return c.agent
  258. }
  259. func (c *controller) clusterAgentInit() {
  260. clusterProvider := c.cfg.Daemon.ClusterProvider
  261. for {
  262. select {
  263. case <-clusterProvider.ListenClusterEvents():
  264. if !c.isDistributedControl() {
  265. c.Lock()
  266. c.clusterConfigAvailable = true
  267. keys := c.keys
  268. c.Unlock()
  269. // agent initialization needs encryption keys and bind/remote IP which
  270. // comes from the daemon cluster events
  271. if len(keys) > 0 {
  272. c.agentSetup()
  273. }
  274. }
  275. case <-c.cfg.Daemon.DisableProvider:
  276. c.Lock()
  277. c.clusterConfigAvailable = false
  278. c.agentInitDone = make(chan struct{})
  279. c.keys = nil
  280. c.Unlock()
  281. // We are leaving the cluster. Make sure we
  282. // close the gossip so that we stop all
  283. // incoming gossip updates before cleaning up
  284. // any remaining service bindings. But before
  285. // deleting the networks since the networks
  286. // should still be present when cleaning up
  287. // service bindings
  288. c.agentClose()
  289. c.cleanupServiceBindings("")
  290. c.Lock()
  291. if c.agentStopDone != nil {
  292. close(c.agentStopDone)
  293. c.agentStopDone = nil
  294. }
  295. c.Unlock()
  296. return
  297. }
  298. }
  299. }
  300. // AgentInitWait waits for agent initialization to be completed in the
  301. // controller.
  302. func (c *controller) AgentInitWait() {
  303. c.Lock()
  304. agentInitDone := c.agentInitDone
  305. c.Unlock()
  306. if agentInitDone != nil {
  307. <-agentInitDone
  308. }
  309. }
  310. func (c *controller) AgentStopWait() {
  311. c.Lock()
  312. agentStopDone := c.agentStopDone
  313. c.Unlock()
  314. if agentStopDone != nil {
  315. <-agentStopDone
  316. }
  317. }
  318. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  319. if c.cfg == nil {
  320. return nil
  321. }
  322. config := make(map[string]interface{})
  323. for _, label := range c.cfg.Daemon.Labels {
  324. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  325. continue
  326. }
  327. config[netlabel.Key(label)] = netlabel.Value(label)
  328. }
  329. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  330. if ok {
  331. for k, v := range drvCfg.(map[string]interface{}) {
  332. config[k] = v
  333. }
  334. }
  335. for k, v := range c.cfg.Scopes {
  336. if !v.IsValid() {
  337. continue
  338. }
  339. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  340. Scope: k,
  341. Provider: v.Client.Provider,
  342. Address: v.Client.Address,
  343. Config: v.Client.Config,
  344. }
  345. }
  346. return config
  347. }
  348. var procReloadConfig = make(chan (bool), 1)
  349. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  350. procReloadConfig <- true
  351. defer func() { <-procReloadConfig }()
  352. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  353. // Refuse the configuration if it alters an existing datastore client configuration.
  354. update := false
  355. cfg := config.ParseConfigOptions(cfgOptions...)
  356. for s := range c.cfg.Scopes {
  357. if _, ok := cfg.Scopes[s]; !ok {
  358. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  359. }
  360. }
  361. for s, nSCfg := range cfg.Scopes {
  362. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  363. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  364. eSCfg.Client.Address != nSCfg.Client.Address {
  365. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  366. }
  367. } else {
  368. if err := c.initScopedStore(s, nSCfg); err != nil {
  369. return err
  370. }
  371. update = true
  372. }
  373. }
  374. if !update {
  375. return nil
  376. }
  377. c.Lock()
  378. c.cfg = cfg
  379. c.Unlock()
  380. var dsConfig *discoverapi.DatastoreConfigData
  381. for scope, sCfg := range cfg.Scopes {
  382. if scope == datastore.LocalScope || !sCfg.IsValid() {
  383. continue
  384. }
  385. dsConfig = &discoverapi.DatastoreConfigData{
  386. Scope: scope,
  387. Provider: sCfg.Client.Provider,
  388. Address: sCfg.Client.Address,
  389. Config: sCfg.Client.Config,
  390. }
  391. break
  392. }
  393. if dsConfig == nil {
  394. return nil
  395. }
  396. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  397. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  398. if err != nil {
  399. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  400. }
  401. return false
  402. })
  403. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  404. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  405. if err != nil {
  406. logrus.Errorf("Failed to set datastore in driver %s: %v", name, err)
  407. }
  408. return false
  409. })
  410. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  411. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  412. logrus.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  413. }
  414. }
  415. return nil
  416. }
  417. func (c *controller) ID() string {
  418. return c.id
  419. }
  420. func (c *controller) BuiltinDrivers() []string {
  421. drivers := []string{}
  422. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  423. if driver.IsBuiltIn() {
  424. drivers = append(drivers, name)
  425. }
  426. return false
  427. })
  428. return drivers
  429. }
  430. func (c *controller) BuiltinIPAMDrivers() []string {
  431. drivers := []string{}
  432. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  433. if driver.IsBuiltIn() {
  434. drivers = append(drivers, name)
  435. }
  436. return false
  437. })
  438. return drivers
  439. }
  440. func (c *controller) validateHostDiscoveryConfig() bool {
  441. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  442. return false
  443. }
  444. return true
  445. }
  446. func (c *controller) clusterHostID() string {
  447. c.Lock()
  448. defer c.Unlock()
  449. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  450. return ""
  451. }
  452. addr := strings.Split(c.cfg.Cluster.Address, ":")
  453. return addr[0]
  454. }
  455. func (c *controller) isNodeAlive(node string) bool {
  456. if c.discovery == nil {
  457. return false
  458. }
  459. nodes := c.discovery.Fetch()
  460. for _, n := range nodes {
  461. if n.String() == node {
  462. return true
  463. }
  464. }
  465. return false
  466. }
  467. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  468. if c.cfg == nil {
  469. return fmt.Errorf("discovery initialization requires a valid configuration")
  470. }
  471. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  472. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  473. }
  474. func (c *controller) activeCallback() {
  475. ds := c.getStore(datastore.GlobalScope)
  476. if ds != nil && !ds.Active() {
  477. ds.RestartWatch()
  478. }
  479. }
  480. func (c *controller) hostJoinCallback(nodes []net.IP) {
  481. c.processNodeDiscovery(nodes, true)
  482. }
  483. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  484. c.processNodeDiscovery(nodes, false)
  485. }
  486. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  487. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  488. c.pushNodeDiscovery(driver, capability, nodes, add)
  489. return false
  490. })
  491. }
  492. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  493. var self net.IP
  494. if c.cfg != nil {
  495. addr := strings.Split(c.cfg.Cluster.Address, ":")
  496. self = net.ParseIP(addr[0])
  497. // if external kvstore is not configured, try swarm-mode config
  498. if self == nil {
  499. if agent := c.getAgent(); agent != nil {
  500. self = net.ParseIP(agent.advertiseAddr)
  501. }
  502. }
  503. }
  504. if d == nil || cap.DataScope != datastore.GlobalScope || nodes == nil {
  505. return
  506. }
  507. for _, node := range nodes {
  508. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  509. var err error
  510. if add {
  511. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  512. } else {
  513. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  514. }
  515. if err != nil {
  516. logrus.Debugf("discovery notification error: %v", err)
  517. }
  518. }
  519. }
  520. func (c *controller) Config() config.Config {
  521. c.Lock()
  522. defer c.Unlock()
  523. if c.cfg == nil {
  524. return config.Config{}
  525. }
  526. return *c.cfg
  527. }
  528. func (c *controller) isManager() bool {
  529. c.Lock()
  530. defer c.Unlock()
  531. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  532. return false
  533. }
  534. return c.cfg.Daemon.ClusterProvider.IsManager()
  535. }
  536. func (c *controller) isAgent() bool {
  537. c.Lock()
  538. defer c.Unlock()
  539. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  540. return false
  541. }
  542. return c.cfg.Daemon.ClusterProvider.IsAgent()
  543. }
  544. func (c *controller) isDistributedControl() bool {
  545. return !c.isManager() && !c.isAgent()
  546. }
  547. func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
  548. return c.drvRegistry.GetPluginGetter()
  549. }
  550. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  551. c.Lock()
  552. hd := c.discovery
  553. c.Unlock()
  554. if hd != nil {
  555. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  556. }
  557. c.agentDriverNotify(driver)
  558. return nil
  559. }
  560. // NewNetwork creates a new network of the specified network type. The options
  561. // are network specific and modeled in a generic way.
  562. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  563. if id != "" {
  564. c.networkLocker.Lock(id)
  565. defer c.networkLocker.Unlock(id)
  566. if _, err := c.NetworkByID(id); err == nil {
  567. return nil, NetworkNameError(id)
  568. }
  569. }
  570. if !config.IsValidName(name) {
  571. return nil, ErrInvalidName(name)
  572. }
  573. if id == "" {
  574. id = stringid.GenerateRandomID()
  575. }
  576. defaultIpam := defaultIpamForNetworkType(networkType)
  577. // Construct the network object
  578. network := &network{
  579. name: name,
  580. networkType: networkType,
  581. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  582. ipamType: defaultIpam,
  583. id: id,
  584. created: time.Now(),
  585. ctrlr: c,
  586. persist: true,
  587. drvOnce: &sync.Once{},
  588. }
  589. network.processOptions(options...)
  590. _, cap, err := network.resolveDriver(networkType, true)
  591. if err != nil {
  592. return nil, err
  593. }
  594. if network.ingress && cap.DataScope != datastore.GlobalScope {
  595. return nil, types.ForbiddenErrorf("Ingress network can only be global scope network")
  596. }
  597. if cap.DataScope == datastore.GlobalScope && !c.isDistributedControl() && !network.dynamic {
  598. if c.isManager() {
  599. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  600. return nil, ManagerRedirectError(name)
  601. }
  602. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  603. }
  604. // Make sure we have a driver available for this network type
  605. // before we allocate anything.
  606. if _, err := network.driver(true); err != nil {
  607. return nil, err
  608. }
  609. err = network.ipamAllocate()
  610. if err != nil {
  611. return nil, err
  612. }
  613. defer func() {
  614. if err != nil {
  615. network.ipamRelease()
  616. }
  617. }()
  618. err = c.addNetwork(network)
  619. if err != nil {
  620. return nil, err
  621. }
  622. defer func() {
  623. if err != nil {
  624. if e := network.deleteNetwork(); e != nil {
  625. logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  626. }
  627. }
  628. }()
  629. // First store the endpoint count, then the network. To avoid to
  630. // end up with a datastore containing a network and not an epCnt,
  631. // in case of an ungraceful shutdown during this function call.
  632. epCnt := &endpointCnt{n: network}
  633. if err = c.updateToStore(epCnt); err != nil {
  634. return nil, err
  635. }
  636. defer func() {
  637. if err != nil {
  638. if e := c.deleteFromStore(epCnt); e != nil {
  639. logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  640. }
  641. }
  642. }()
  643. network.epCnt = epCnt
  644. if err = c.updateToStore(network); err != nil {
  645. return nil, err
  646. }
  647. joinCluster(network)
  648. if !c.isDistributedControl() {
  649. c.Lock()
  650. arrangeIngressFilterRule()
  651. c.Unlock()
  652. }
  653. return network, nil
  654. }
  655. var joinCluster NetworkWalker = func(nw Network) bool {
  656. n := nw.(*network)
  657. if err := n.joinCluster(); err != nil {
  658. logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  659. }
  660. n.addDriverWatches()
  661. return false
  662. }
  663. func (c *controller) reservePools() {
  664. networks, err := c.getNetworksForScope(datastore.LocalScope)
  665. if err != nil {
  666. logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  667. return
  668. }
  669. for _, n := range networks {
  670. if !doReplayPoolReserve(n) {
  671. continue
  672. }
  673. // Construct pseudo configs for the auto IP case
  674. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  675. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  676. if autoIPv4 {
  677. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  678. }
  679. if n.enableIPv6 && autoIPv6 {
  680. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  681. }
  682. // Account current network gateways
  683. for i, c := range n.ipamV4Config {
  684. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  685. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  686. }
  687. }
  688. if n.enableIPv6 {
  689. for i, c := range n.ipamV6Config {
  690. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  691. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  692. }
  693. }
  694. }
  695. // Reserve pools
  696. if err := n.ipamAllocate(); err != nil {
  697. logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  698. }
  699. // Reserve existing endpoints' addresses
  700. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  701. if err != nil {
  702. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  703. continue
  704. }
  705. epl, err := n.getEndpointsFromStore()
  706. if err != nil {
  707. logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  708. continue
  709. }
  710. for _, ep := range epl {
  711. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  712. logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  713. ep.Name(), ep.ID(), n.Name(), n.ID())
  714. }
  715. }
  716. }
  717. }
  718. func doReplayPoolReserve(n *network) bool {
  719. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  720. if err != nil {
  721. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  722. return false
  723. }
  724. return caps.RequiresRequestReplay
  725. }
  726. func (c *controller) addNetwork(n *network) error {
  727. d, err := n.driver(true)
  728. if err != nil {
  729. return err
  730. }
  731. // Create the network
  732. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  733. return err
  734. }
  735. n.startResolver()
  736. return nil
  737. }
  738. func (c *controller) Networks() []Network {
  739. var list []Network
  740. networks, err := c.getNetworksFromStore()
  741. if err != nil {
  742. logrus.Error(err)
  743. }
  744. for _, n := range networks {
  745. if n.inDelete {
  746. continue
  747. }
  748. list = append(list, n)
  749. }
  750. return list
  751. }
  752. func (c *controller) WalkNetworks(walker NetworkWalker) {
  753. for _, n := range c.Networks() {
  754. if walker(n) {
  755. return
  756. }
  757. }
  758. }
  759. func (c *controller) NetworkByName(name string) (Network, error) {
  760. if name == "" {
  761. return nil, ErrInvalidName(name)
  762. }
  763. var n Network
  764. s := func(current Network) bool {
  765. if current.Name() == name {
  766. n = current
  767. return true
  768. }
  769. return false
  770. }
  771. c.WalkNetworks(s)
  772. if n == nil {
  773. return nil, ErrNoSuchNetwork(name)
  774. }
  775. return n, nil
  776. }
  777. func (c *controller) NetworkByID(id string) (Network, error) {
  778. if id == "" {
  779. return nil, ErrInvalidID(id)
  780. }
  781. n, err := c.getNetworkFromStore(id)
  782. if err != nil {
  783. return nil, ErrNoSuchNetwork(id)
  784. }
  785. return n, nil
  786. }
  787. // NewSandbox creates a new sandbox for the passed container id
  788. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  789. if containerID == "" {
  790. return nil, types.BadRequestErrorf("invalid container ID")
  791. }
  792. var sb *sandbox
  793. c.Lock()
  794. for _, s := range c.sandboxes {
  795. if s.containerID == containerID {
  796. // If not a stub, then we already have a complete sandbox.
  797. if !s.isStub {
  798. sbID := s.ID()
  799. c.Unlock()
  800. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  801. }
  802. // We already have a stub sandbox from the
  803. // store. Make use of it so that we don't lose
  804. // the endpoints from store but reset the
  805. // isStub flag.
  806. sb = s
  807. sb.isStub = false
  808. break
  809. }
  810. }
  811. c.Unlock()
  812. // Create sandbox and process options first. Key generation depends on an option
  813. if sb == nil {
  814. sb = &sandbox{
  815. id: stringid.GenerateRandomID(),
  816. containerID: containerID,
  817. endpoints: epHeap{},
  818. epPriority: map[string]int{},
  819. populatedEndpoints: map[string]struct{}{},
  820. config: containerConfig{},
  821. controller: c,
  822. extDNS: []extDNSEntry{},
  823. }
  824. }
  825. sBox = sb
  826. heap.Init(&sb.endpoints)
  827. sb.processOptions(options...)
  828. c.Lock()
  829. if sb.ingress && c.ingressSandbox != nil {
  830. c.Unlock()
  831. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  832. }
  833. if sb.ingress {
  834. c.ingressSandbox = sb
  835. sb.config.hostsPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/hosts")
  836. sb.config.resolvConfPath = filepath.Join(c.cfg.Daemon.DataDir, "/network/files/resolv.conf")
  837. sb.id = "ingress_sbox"
  838. }
  839. c.Unlock()
  840. defer func() {
  841. if err != nil {
  842. c.Lock()
  843. if sb.ingress {
  844. c.ingressSandbox = nil
  845. }
  846. c.Unlock()
  847. }
  848. }()
  849. if err = sb.setupResolutionFiles(); err != nil {
  850. return nil, err
  851. }
  852. if sb.config.useDefaultSandBox {
  853. c.sboxOnce.Do(func() {
  854. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  855. })
  856. if err != nil {
  857. c.sboxOnce = sync.Once{}
  858. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  859. }
  860. sb.osSbox = c.defOsSbox
  861. }
  862. if sb.osSbox == nil && !sb.config.useExternalKey {
  863. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  864. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  865. }
  866. }
  867. c.Lock()
  868. c.sandboxes[sb.id] = sb
  869. c.Unlock()
  870. defer func() {
  871. if err != nil {
  872. c.Lock()
  873. delete(c.sandboxes, sb.id)
  874. c.Unlock()
  875. }
  876. }()
  877. err = sb.storeUpdate()
  878. if err != nil {
  879. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  880. }
  881. return sb, nil
  882. }
  883. func (c *controller) Sandboxes() []Sandbox {
  884. c.Lock()
  885. defer c.Unlock()
  886. list := make([]Sandbox, 0, len(c.sandboxes))
  887. for _, s := range c.sandboxes {
  888. // Hide stub sandboxes from libnetwork users
  889. if s.isStub {
  890. continue
  891. }
  892. list = append(list, s)
  893. }
  894. return list
  895. }
  896. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  897. for _, sb := range c.Sandboxes() {
  898. if walker(sb) {
  899. return
  900. }
  901. }
  902. }
  903. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  904. if id == "" {
  905. return nil, ErrInvalidID(id)
  906. }
  907. c.Lock()
  908. s, ok := c.sandboxes[id]
  909. c.Unlock()
  910. if !ok {
  911. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  912. }
  913. return s, nil
  914. }
  915. // SandboxDestroy destroys a sandbox given a container ID
  916. func (c *controller) SandboxDestroy(id string) error {
  917. var sb *sandbox
  918. c.Lock()
  919. for _, s := range c.sandboxes {
  920. if s.containerID == id {
  921. sb = s
  922. break
  923. }
  924. }
  925. c.Unlock()
  926. // It is not an error if sandbox is not available
  927. if sb == nil {
  928. return nil
  929. }
  930. return sb.Delete()
  931. }
  932. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  933. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  934. return func(sb Sandbox) bool {
  935. if sb.ContainerID() == containerID {
  936. *out = sb
  937. return true
  938. }
  939. return false
  940. }
  941. }
  942. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  943. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  944. return func(sb Sandbox) bool {
  945. if sb.Key() == key {
  946. *out = sb
  947. return true
  948. }
  949. return false
  950. }
  951. }
  952. func (c *controller) loadDriver(networkType string) error {
  953. var err error
  954. if pg := c.GetPluginGetter(); pg != nil {
  955. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  956. } else {
  957. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  958. }
  959. if err != nil {
  960. if err == plugins.ErrNotFound {
  961. return types.NotFoundErrorf(err.Error())
  962. }
  963. return err
  964. }
  965. return nil
  966. }
  967. func (c *controller) loadIPAMDriver(name string) error {
  968. var err error
  969. if pg := c.GetPluginGetter(); pg != nil {
  970. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  971. } else {
  972. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  973. }
  974. if err != nil {
  975. if err == plugins.ErrNotFound {
  976. return types.NotFoundErrorf(err.Error())
  977. }
  978. return err
  979. }
  980. return nil
  981. }
  982. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  983. id, cap := c.drvRegistry.IPAM(name)
  984. if id == nil {
  985. // Might be a plugin name. Try loading it
  986. if err := c.loadIPAMDriver(name); err != nil {
  987. return nil, nil, err
  988. }
  989. // Now that we resolved the plugin, try again looking up the registry
  990. id, cap = c.drvRegistry.IPAM(name)
  991. if id == nil {
  992. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  993. }
  994. }
  995. return id, cap, nil
  996. }
  997. func (c *controller) Stop() {
  998. c.closeStores()
  999. c.stopExternalKeyListener()
  1000. osl.GC()
  1001. }