controller.go 28 KB

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