controller.go 34 KB

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