controller.go 28 KB

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