controller.go 33 KB

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