controller.go 28 KB

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