controller.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. 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. extDNS: []extDNSEntry{},
  795. }
  796. }
  797. sBox = sb
  798. heap.Init(&sb.endpoints)
  799. sb.processOptions(options...)
  800. c.Lock()
  801. if sb.ingress && c.ingressSandbox != nil {
  802. c.Unlock()
  803. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  804. }
  805. if sb.ingress {
  806. c.ingressSandbox = sb
  807. sb.id = "ingress_sbox"
  808. }
  809. c.Unlock()
  810. defer func() {
  811. if err != nil {
  812. c.Lock()
  813. if sb.ingress {
  814. c.ingressSandbox = nil
  815. }
  816. c.Unlock()
  817. }
  818. }()
  819. if err = sb.setupResolutionFiles(); err != nil {
  820. return nil, err
  821. }
  822. if sb.config.useDefaultSandBox {
  823. c.sboxOnce.Do(func() {
  824. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  825. })
  826. if err != nil {
  827. c.sboxOnce = sync.Once{}
  828. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  829. }
  830. sb.osSbox = c.defOsSbox
  831. }
  832. if sb.osSbox == nil && !sb.config.useExternalKey {
  833. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  834. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  835. }
  836. }
  837. c.Lock()
  838. c.sandboxes[sb.id] = sb
  839. c.Unlock()
  840. defer func() {
  841. if err != nil {
  842. c.Lock()
  843. delete(c.sandboxes, sb.id)
  844. c.Unlock()
  845. }
  846. }()
  847. err = sb.storeUpdate()
  848. if err != nil {
  849. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  850. }
  851. return sb, nil
  852. }
  853. func (c *controller) Sandboxes() []Sandbox {
  854. c.Lock()
  855. defer c.Unlock()
  856. list := make([]Sandbox, 0, len(c.sandboxes))
  857. for _, s := range c.sandboxes {
  858. // Hide stub sandboxes from libnetwork users
  859. if s.isStub {
  860. continue
  861. }
  862. list = append(list, s)
  863. }
  864. return list
  865. }
  866. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  867. for _, sb := range c.Sandboxes() {
  868. if walker(sb) {
  869. return
  870. }
  871. }
  872. }
  873. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  874. if id == "" {
  875. return nil, ErrInvalidID(id)
  876. }
  877. c.Lock()
  878. s, ok := c.sandboxes[id]
  879. c.Unlock()
  880. if !ok {
  881. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  882. }
  883. return s, nil
  884. }
  885. // SandboxDestroy destroys a sandbox given a container ID
  886. func (c *controller) SandboxDestroy(id string) error {
  887. var sb *sandbox
  888. c.Lock()
  889. for _, s := range c.sandboxes {
  890. if s.containerID == id {
  891. sb = s
  892. break
  893. }
  894. }
  895. c.Unlock()
  896. // It is not an error if sandbox is not available
  897. if sb == nil {
  898. return nil
  899. }
  900. return sb.Delete()
  901. }
  902. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  903. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  904. return func(sb Sandbox) bool {
  905. if sb.ContainerID() == containerID {
  906. *out = sb
  907. return true
  908. }
  909. return false
  910. }
  911. }
  912. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  913. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  914. return func(sb Sandbox) bool {
  915. if sb.Key() == key {
  916. *out = sb
  917. return true
  918. }
  919. return false
  920. }
  921. }
  922. func (c *controller) loadDriver(networkType string) error {
  923. var err error
  924. if pg := c.GetPluginGetter(); pg != nil {
  925. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  926. } else {
  927. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  928. }
  929. if err != nil {
  930. if err == plugins.ErrNotFound {
  931. return types.NotFoundErrorf(err.Error())
  932. }
  933. return err
  934. }
  935. return nil
  936. }
  937. func (c *controller) loadIPAMDriver(name string) error {
  938. var err error
  939. if pg := c.GetPluginGetter(); pg != nil {
  940. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  941. } else {
  942. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  943. }
  944. if err != nil {
  945. if err == plugins.ErrNotFound {
  946. return types.NotFoundErrorf(err.Error())
  947. }
  948. return err
  949. }
  950. return nil
  951. }
  952. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  953. id, cap := c.drvRegistry.IPAM(name)
  954. if id == nil {
  955. // Might be a plugin name. Try loading it
  956. if err := c.loadIPAMDriver(name); err != nil {
  957. return nil, nil, err
  958. }
  959. // Now that we resolved the plugin, try again looking up the registry
  960. id, cap = c.drvRegistry.IPAM(name)
  961. if id == nil {
  962. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  963. }
  964. }
  965. return id, cap, nil
  966. }
  967. func (c *controller) Stop() {
  968. c.clearIngress(false)
  969. c.closeStores()
  970. c.stopExternalKeyListener()
  971. osl.GC()
  972. }
  973. func (c *controller) clearIngress(clusterLeave bool) {
  974. c.Lock()
  975. ingressSandbox := c.ingressSandbox
  976. c.ingressSandbox = nil
  977. c.Unlock()
  978. if ingressSandbox != nil {
  979. if err := ingressSandbox.Delete(); err != nil {
  980. logrus.Warnf("Could not delete ingress sandbox while leaving: %v", err)
  981. }
  982. }
  983. n, err := c.NetworkByName("ingress")
  984. if err != nil && clusterLeave {
  985. logrus.Warnf("Could not find ingress network while leaving: %v", err)
  986. }
  987. if n != nil {
  988. if err := n.Delete(); err != nil {
  989. logrus.Warnf("Could not delete ingress network while leaving: %v", err)
  990. }
  991. }
  992. }