controller.go 35 KB

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