controller.go 29 KB

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