controller.go 30 KB

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