controller.go 29 KB

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