controller.go 29 KB

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