controller.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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. // if external kvstore is not configured, try swarm-mode config
  481. if self == nil {
  482. if agent := c.getAgent(); agent != nil {
  483. self = net.ParseIP(agent.advertiseAddr)
  484. }
  485. }
  486. }
  487. if d == nil || cap.DataScope != datastore.GlobalScope || nodes == nil {
  488. return
  489. }
  490. for _, node := range nodes {
  491. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  492. var err error
  493. if add {
  494. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  495. } else {
  496. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  497. }
  498. if err != nil {
  499. logrus.Debugf("discovery notification error: %v", err)
  500. }
  501. }
  502. }
  503. func (c *controller) Config() config.Config {
  504. c.Lock()
  505. defer c.Unlock()
  506. if c.cfg == nil {
  507. return config.Config{}
  508. }
  509. return *c.cfg
  510. }
  511. func (c *controller) isManager() bool {
  512. c.Lock()
  513. defer c.Unlock()
  514. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  515. return false
  516. }
  517. return c.cfg.Daemon.ClusterProvider.IsManager()
  518. }
  519. func (c *controller) isAgent() bool {
  520. c.Lock()
  521. defer c.Unlock()
  522. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  523. return false
  524. }
  525. return c.cfg.Daemon.ClusterProvider.IsAgent()
  526. }
  527. func (c *controller) isDistributedControl() bool {
  528. return !c.isManager() && !c.isAgent()
  529. }
  530. func (c *controller) GetPluginGetter() plugingetter.PluginGetter {
  531. return c.drvRegistry.GetPluginGetter()
  532. }
  533. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  534. c.Lock()
  535. hd := c.discovery
  536. c.Unlock()
  537. if hd != nil {
  538. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  539. }
  540. c.agentDriverNotify(driver)
  541. return nil
  542. }
  543. // NewNetwork creates a new network of the specified network type. The options
  544. // are network specific and modeled in a generic way.
  545. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  546. if id != "" {
  547. c.networkLocker.Lock(id)
  548. defer c.networkLocker.Unlock(id)
  549. if _, err := c.NetworkByID(id); err == nil {
  550. return nil, NetworkNameError(id)
  551. }
  552. }
  553. if err := config.ValidateName(name); err != nil {
  554. return nil, ErrInvalidName(err.Error())
  555. }
  556. if id == "" {
  557. id = stringid.GenerateRandomID()
  558. }
  559. defaultIpam := defaultIpamForNetworkType(networkType)
  560. // Construct the network object
  561. network := &network{
  562. name: name,
  563. networkType: networkType,
  564. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  565. ipamType: defaultIpam,
  566. id: id,
  567. created: time.Now(),
  568. ctrlr: c,
  569. persist: true,
  570. drvOnce: &sync.Once{},
  571. }
  572. network.processOptions(options...)
  573. _, cap, err := network.resolveDriver(networkType, true)
  574. if err != nil {
  575. return nil, err
  576. }
  577. if cap.DataScope == datastore.GlobalScope && !c.isDistributedControl() && !network.dynamic {
  578. if c.isManager() {
  579. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  580. return nil, ManagerRedirectError(name)
  581. }
  582. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  583. }
  584. // Make sure we have a driver available for this network type
  585. // before we allocate anything.
  586. if _, err := network.driver(true); err != nil {
  587. return nil, err
  588. }
  589. err = network.ipamAllocate()
  590. if err != nil {
  591. return nil, err
  592. }
  593. defer func() {
  594. if err != nil {
  595. network.ipamRelease()
  596. }
  597. }()
  598. err = c.addNetwork(network)
  599. if err != nil {
  600. return nil, err
  601. }
  602. defer func() {
  603. if err != nil {
  604. if e := network.deleteNetwork(); e != nil {
  605. logrus.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  606. }
  607. }
  608. }()
  609. // First store the endpoint count, then the network. To avoid to
  610. // end up with a datastore containing a network and not an epCnt,
  611. // in case of an ungraceful shutdown during this function call.
  612. epCnt := &endpointCnt{n: network}
  613. if err = c.updateToStore(epCnt); err != nil {
  614. return nil, err
  615. }
  616. defer func() {
  617. if err != nil {
  618. if e := c.deleteFromStore(epCnt); e != nil {
  619. logrus.Warnf("could not rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  620. }
  621. }
  622. }()
  623. network.epCnt = epCnt
  624. if err = c.updateToStore(network); err != nil {
  625. return nil, err
  626. }
  627. joinCluster(network)
  628. if !c.isDistributedControl() {
  629. arrangeIngressFilterRule()
  630. }
  631. return network, nil
  632. }
  633. var joinCluster NetworkWalker = func(nw Network) bool {
  634. n := nw.(*network)
  635. if err := n.joinCluster(); err != nil {
  636. logrus.Errorf("Failed to join network %s (%s) into agent cluster: %v", n.Name(), n.ID(), err)
  637. }
  638. n.addDriverWatches()
  639. return false
  640. }
  641. func (c *controller) reservePools() {
  642. networks, err := c.getNetworksForScope(datastore.LocalScope)
  643. if err != nil {
  644. logrus.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  645. return
  646. }
  647. for _, n := range networks {
  648. if !doReplayPoolReserve(n) {
  649. continue
  650. }
  651. // Construct pseudo configs for the auto IP case
  652. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  653. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  654. if autoIPv4 {
  655. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  656. }
  657. if n.enableIPv6 && autoIPv6 {
  658. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  659. }
  660. // Account current network gateways
  661. for i, c := range n.ipamV4Config {
  662. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  663. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  664. }
  665. }
  666. if n.enableIPv6 {
  667. for i, c := range n.ipamV6Config {
  668. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  669. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  670. }
  671. }
  672. }
  673. // Reserve pools
  674. if err := n.ipamAllocate(); err != nil {
  675. logrus.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  676. }
  677. // Reserve existing endpoints' addresses
  678. ipam, _, err := n.getController().getIPAMDriver(n.ipamType)
  679. if err != nil {
  680. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s) during address reservation", n.Name(), n.ID())
  681. continue
  682. }
  683. epl, err := n.getEndpointsFromStore()
  684. if err != nil {
  685. logrus.Warnf("Failed to retrieve list of current endpoints on network %q (%s)", n.Name(), n.ID())
  686. continue
  687. }
  688. for _, ep := range epl {
  689. if err := ep.assignAddress(ipam, true, ep.Iface().AddressIPv6() != nil); err != nil {
  690. logrus.Warnf("Failed to reserve current address for endpoint %q (%s) on network %q (%s)",
  691. ep.Name(), ep.ID(), n.Name(), n.ID())
  692. }
  693. }
  694. }
  695. }
  696. func doReplayPoolReserve(n *network) bool {
  697. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  698. if err != nil {
  699. logrus.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  700. return false
  701. }
  702. return caps.RequiresRequestReplay
  703. }
  704. func (c *controller) addNetwork(n *network) error {
  705. d, err := n.driver(true)
  706. if err != nil {
  707. return err
  708. }
  709. // Create the network
  710. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  711. return err
  712. }
  713. n.startResolver()
  714. return nil
  715. }
  716. func (c *controller) Networks() []Network {
  717. var list []Network
  718. networks, err := c.getNetworksFromStore()
  719. if err != nil {
  720. logrus.Error(err)
  721. }
  722. for _, n := range networks {
  723. if n.inDelete {
  724. continue
  725. }
  726. list = append(list, n)
  727. }
  728. return list
  729. }
  730. func (c *controller) WalkNetworks(walker NetworkWalker) {
  731. for _, n := range c.Networks() {
  732. if walker(n) {
  733. return
  734. }
  735. }
  736. }
  737. func (c *controller) NetworkByName(name string) (Network, error) {
  738. if name == "" {
  739. return nil, ErrInvalidName(name)
  740. }
  741. var n Network
  742. s := func(current Network) bool {
  743. if current.Name() == name {
  744. n = current
  745. return true
  746. }
  747. return false
  748. }
  749. c.WalkNetworks(s)
  750. if n == nil {
  751. return nil, ErrNoSuchNetwork(name)
  752. }
  753. return n, nil
  754. }
  755. func (c *controller) NetworkByID(id string) (Network, error) {
  756. if id == "" {
  757. return nil, ErrInvalidID(id)
  758. }
  759. n, err := c.getNetworkFromStore(id)
  760. if err != nil {
  761. return nil, ErrNoSuchNetwork(id)
  762. }
  763. return n, nil
  764. }
  765. // NewSandbox creates a new sandbox for the passed container id
  766. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  767. if containerID == "" {
  768. return nil, types.BadRequestErrorf("invalid container ID")
  769. }
  770. var sb *sandbox
  771. c.Lock()
  772. for _, s := range c.sandboxes {
  773. if s.containerID == containerID {
  774. // If not a stub, then we already have a complete sandbox.
  775. if !s.isStub {
  776. sbID := s.ID()
  777. c.Unlock()
  778. return nil, types.ForbiddenErrorf("container %s is already present in sandbox %s", containerID, sbID)
  779. }
  780. // We already have a stub sandbox from the
  781. // store. Make use of it so that we don't lose
  782. // the endpoints from store but reset the
  783. // isStub flag.
  784. sb = s
  785. sb.isStub = false
  786. break
  787. }
  788. }
  789. c.Unlock()
  790. // Create sandbox and process options first. Key generation depends on an option
  791. if sb == nil {
  792. sb = &sandbox{
  793. id: stringid.GenerateRandomID(),
  794. containerID: containerID,
  795. endpoints: epHeap{},
  796. epPriority: map[string]int{},
  797. populatedEndpoints: map[string]struct{}{},
  798. config: containerConfig{},
  799. controller: c,
  800. extDNS: []extDNSEntry{},
  801. }
  802. }
  803. sBox = sb
  804. heap.Init(&sb.endpoints)
  805. sb.processOptions(options...)
  806. c.Lock()
  807. if sb.ingress && c.ingressSandbox != nil {
  808. c.Unlock()
  809. return nil, types.ForbiddenErrorf("ingress sandbox already present")
  810. }
  811. if sb.ingress {
  812. c.ingressSandbox = sb
  813. sb.id = "ingress_sbox"
  814. }
  815. c.Unlock()
  816. defer func() {
  817. if err != nil {
  818. c.Lock()
  819. if sb.ingress {
  820. c.ingressSandbox = nil
  821. }
  822. c.Unlock()
  823. }
  824. }()
  825. if err = sb.setupResolutionFiles(); err != nil {
  826. return nil, err
  827. }
  828. if sb.config.useDefaultSandBox {
  829. c.sboxOnce.Do(func() {
  830. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false, false)
  831. })
  832. if err != nil {
  833. c.sboxOnce = sync.Once{}
  834. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  835. }
  836. sb.osSbox = c.defOsSbox
  837. }
  838. if sb.osSbox == nil && !sb.config.useExternalKey {
  839. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox, false); err != nil {
  840. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  841. }
  842. }
  843. c.Lock()
  844. c.sandboxes[sb.id] = sb
  845. c.Unlock()
  846. defer func() {
  847. if err != nil {
  848. c.Lock()
  849. delete(c.sandboxes, sb.id)
  850. c.Unlock()
  851. }
  852. }()
  853. err = sb.storeUpdate()
  854. if err != nil {
  855. return nil, fmt.Errorf("failed to update the store state of sandbox: %v", err)
  856. }
  857. return sb, nil
  858. }
  859. func (c *controller) Sandboxes() []Sandbox {
  860. c.Lock()
  861. defer c.Unlock()
  862. list := make([]Sandbox, 0, len(c.sandboxes))
  863. for _, s := range c.sandboxes {
  864. // Hide stub sandboxes from libnetwork users
  865. if s.isStub {
  866. continue
  867. }
  868. list = append(list, s)
  869. }
  870. return list
  871. }
  872. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  873. for _, sb := range c.Sandboxes() {
  874. if walker(sb) {
  875. return
  876. }
  877. }
  878. }
  879. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  880. if id == "" {
  881. return nil, ErrInvalidID(id)
  882. }
  883. c.Lock()
  884. s, ok := c.sandboxes[id]
  885. c.Unlock()
  886. if !ok {
  887. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  888. }
  889. return s, nil
  890. }
  891. // SandboxDestroy destroys a sandbox given a container ID
  892. func (c *controller) SandboxDestroy(id string) error {
  893. var sb *sandbox
  894. c.Lock()
  895. for _, s := range c.sandboxes {
  896. if s.containerID == id {
  897. sb = s
  898. break
  899. }
  900. }
  901. c.Unlock()
  902. // It is not an error if sandbox is not available
  903. if sb == nil {
  904. return nil
  905. }
  906. return sb.Delete()
  907. }
  908. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  909. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  910. return func(sb Sandbox) bool {
  911. if sb.ContainerID() == containerID {
  912. *out = sb
  913. return true
  914. }
  915. return false
  916. }
  917. }
  918. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  919. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  920. return func(sb Sandbox) bool {
  921. if sb.Key() == key {
  922. *out = sb
  923. return true
  924. }
  925. return false
  926. }
  927. }
  928. func (c *controller) loadDriver(networkType string) error {
  929. var err error
  930. if pg := c.GetPluginGetter(); pg != nil {
  931. _, err = pg.Get(networkType, driverapi.NetworkPluginEndpointType, plugingetter.Lookup)
  932. } else {
  933. _, err = plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  934. }
  935. if err != nil {
  936. if err == plugins.ErrNotFound {
  937. return types.NotFoundErrorf(err.Error())
  938. }
  939. return err
  940. }
  941. return nil
  942. }
  943. func (c *controller) loadIPAMDriver(name string) error {
  944. var err error
  945. if pg := c.GetPluginGetter(); pg != nil {
  946. _, err = pg.Get(name, ipamapi.PluginEndpointType, plugingetter.Lookup)
  947. } else {
  948. _, err = plugins.Get(name, ipamapi.PluginEndpointType)
  949. }
  950. if err != nil {
  951. if err == plugins.ErrNotFound {
  952. return types.NotFoundErrorf(err.Error())
  953. }
  954. return err
  955. }
  956. return nil
  957. }
  958. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  959. id, cap := c.drvRegistry.IPAM(name)
  960. if id == nil {
  961. // Might be a plugin name. Try loading it
  962. if err := c.loadIPAMDriver(name); err != nil {
  963. return nil, nil, err
  964. }
  965. // Now that we resolved the plugin, try again looking up the registry
  966. id, cap = c.drvRegistry.IPAM(name)
  967. if id == nil {
  968. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  969. }
  970. }
  971. return id, cap, nil
  972. }
  973. func (c *controller) Stop() {
  974. c.clearIngress(false)
  975. c.closeStores()
  976. c.stopExternalKeyListener()
  977. osl.GC()
  978. }
  979. func (c *controller) clearIngress(clusterLeave bool) {
  980. c.Lock()
  981. ingressSandbox := c.ingressSandbox
  982. c.ingressSandbox = nil
  983. c.Unlock()
  984. if ingressSandbox != nil {
  985. if err := ingressSandbox.Delete(); err != nil {
  986. logrus.Warnf("Could not delete ingress sandbox while leaving: %v", err)
  987. }
  988. }
  989. n, err := c.NetworkByName("ingress")
  990. if err != nil && clusterLeave {
  991. logrus.Warnf("Could not find ingress network while leaving: %v", err)
  992. }
  993. if n != nil {
  994. if err := n.Delete(); err != nil {
  995. logrus.Warnf("Could not delete ingress network while leaving: %v", err)
  996. }
  997. }
  998. }