controller.go 29 KB

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