controller.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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. // WlakSandboxes 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[string]*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[string]*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. c.drvRegistry = drvRegistry
  161. if c.cfg != nil && c.cfg.Cluster.Watcher != nil {
  162. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  163. // Failing to initialize discovery is a bad situation to be in.
  164. // But it cannot fail creating the Controller
  165. log.Errorf("Failed to Initialize Discovery : %v", err)
  166. }
  167. }
  168. c.sandboxCleanup()
  169. c.cleanupLocalEndpoints()
  170. c.networkCleanup()
  171. c.reservePools()
  172. if err := c.startExternalKeyListener(); err != nil {
  173. return nil, err
  174. }
  175. return c, nil
  176. }
  177. func (c *controller) SetClusterProvider(provider cluster.Provider) {
  178. c.cfg.Daemon.ClusterProvider = provider
  179. go c.clusterAgentInit()
  180. }
  181. func isValidClusteringIP(addr string) bool {
  182. return addr != "" && !net.ParseIP(addr).IsLoopback() && !net.ParseIP(addr).IsUnspecified()
  183. }
  184. // libnetwork side of agent depends on the keys. On the first receipt of
  185. // keys setup the agent. For subsequent key set handle the key change
  186. func (c *controller) SetKeys(keys []*types.EncryptionKey) error {
  187. if len(c.keys) == 0 {
  188. c.keys = keys
  189. if c.agent != nil {
  190. return (fmt.Errorf("libnetwork agent setup without keys"))
  191. }
  192. if c.clusterConfigAvailable {
  193. return c.agentSetup()
  194. }
  195. log.Debugf("received encryption keys before cluster config")
  196. return nil
  197. }
  198. if c.agent == nil {
  199. c.keys = keys
  200. return nil
  201. }
  202. return c.handleKeyChange(keys)
  203. }
  204. func (c *controller) clusterAgentInit() {
  205. clusterProvider := c.cfg.Daemon.ClusterProvider
  206. for {
  207. select {
  208. case <-clusterProvider.ListenClusterEvents():
  209. c.clusterConfigAvailable = true
  210. if !c.isDistributedControl() {
  211. // agent initialization needs encyrption keys and bind/remote IP which
  212. // comes from the daemon cluster events
  213. if len(c.keys) > 0 {
  214. c.agentSetup()
  215. }
  216. } else {
  217. c.agentInitDone = make(chan struct{})
  218. c.agentClose()
  219. }
  220. }
  221. }
  222. }
  223. // AgentInitWait waits for agent initialization to be completed in the
  224. // controller.
  225. func (c *controller) AgentInitWait() {
  226. <-c.agentInitDone
  227. }
  228. func (c *controller) makeDriverConfig(ntype string) map[string]interface{} {
  229. if c.cfg == nil {
  230. return nil
  231. }
  232. config := make(map[string]interface{})
  233. for _, label := range c.cfg.Daemon.Labels {
  234. if !strings.HasPrefix(netlabel.Key(label), netlabel.DriverPrefix+"."+ntype) {
  235. continue
  236. }
  237. config[netlabel.Key(label)] = netlabel.Value(label)
  238. }
  239. drvCfg, ok := c.cfg.Daemon.DriverCfg[ntype]
  240. if ok {
  241. for k, v := range drvCfg.(map[string]interface{}) {
  242. config[k] = v
  243. }
  244. }
  245. for k, v := range c.cfg.Scopes {
  246. if !v.IsValid() {
  247. continue
  248. }
  249. config[netlabel.MakeKVClient(k)] = discoverapi.DatastoreConfigData{
  250. Scope: k,
  251. Provider: v.Client.Provider,
  252. Address: v.Client.Address,
  253. Config: v.Client.Config,
  254. }
  255. }
  256. return config
  257. }
  258. var procReloadConfig = make(chan (bool), 1)
  259. func (c *controller) ReloadConfiguration(cfgOptions ...config.Option) error {
  260. procReloadConfig <- true
  261. defer func() { <-procReloadConfig }()
  262. // For now we accept the configuration reload only as a mean to provide a global store config after boot.
  263. // Refuse the configuration if it alters an existing datastore client configuration.
  264. update := false
  265. cfg := config.ParseConfigOptions(cfgOptions...)
  266. for s := range c.cfg.Scopes {
  267. if _, ok := cfg.Scopes[s]; !ok {
  268. return types.ForbiddenErrorf("cannot accept new configuration because it removes an existing datastore client")
  269. }
  270. }
  271. for s, nSCfg := range cfg.Scopes {
  272. if eSCfg, ok := c.cfg.Scopes[s]; ok {
  273. if eSCfg.Client.Provider != nSCfg.Client.Provider ||
  274. eSCfg.Client.Address != nSCfg.Client.Address {
  275. return types.ForbiddenErrorf("cannot accept new configuration because it modifies an existing datastore client")
  276. }
  277. } else {
  278. if err := c.initScopedStore(s, nSCfg); err != nil {
  279. return err
  280. }
  281. update = true
  282. }
  283. }
  284. if !update {
  285. return nil
  286. }
  287. var dsConfig *discoverapi.DatastoreConfigData
  288. for scope, sCfg := range cfg.Scopes {
  289. if scope == datastore.LocalScope || !sCfg.IsValid() {
  290. continue
  291. }
  292. dsConfig = &discoverapi.DatastoreConfigData{
  293. Scope: scope,
  294. Provider: sCfg.Client.Provider,
  295. Address: sCfg.Client.Address,
  296. Config: sCfg.Client.Config,
  297. }
  298. break
  299. }
  300. if dsConfig == nil {
  301. return nil
  302. }
  303. c.drvRegistry.WalkIPAMs(func(name string, driver ipamapi.Ipam, cap *ipamapi.Capability) bool {
  304. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  305. if err != nil {
  306. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  307. }
  308. return false
  309. })
  310. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  311. err := driver.DiscoverNew(discoverapi.DatastoreConfig, *dsConfig)
  312. if err != nil {
  313. log.Errorf("Failed to set datastore in driver %s: %v", name, err)
  314. }
  315. return false
  316. })
  317. if c.discovery == nil && c.cfg.Cluster.Watcher != nil {
  318. if err := c.initDiscovery(c.cfg.Cluster.Watcher); err != nil {
  319. log.Errorf("Failed to Initialize Discovery after configuration update: %v", err)
  320. }
  321. }
  322. return nil
  323. }
  324. func (c *controller) ID() string {
  325. return c.id
  326. }
  327. func (c *controller) validateHostDiscoveryConfig() bool {
  328. if c.cfg == nil || c.cfg.Cluster.Discovery == "" || c.cfg.Cluster.Address == "" {
  329. return false
  330. }
  331. return true
  332. }
  333. func (c *controller) clusterHostID() string {
  334. c.Lock()
  335. defer c.Unlock()
  336. if c.cfg == nil || c.cfg.Cluster.Address == "" {
  337. return ""
  338. }
  339. addr := strings.Split(c.cfg.Cluster.Address, ":")
  340. return addr[0]
  341. }
  342. func (c *controller) isNodeAlive(node string) bool {
  343. if c.discovery == nil {
  344. return false
  345. }
  346. nodes := c.discovery.Fetch()
  347. for _, n := range nodes {
  348. if n.String() == node {
  349. return true
  350. }
  351. }
  352. return false
  353. }
  354. func (c *controller) initDiscovery(watcher discovery.Watcher) error {
  355. if c.cfg == nil {
  356. return fmt.Errorf("discovery initialization requires a valid configuration")
  357. }
  358. c.discovery = hostdiscovery.NewHostDiscovery(watcher)
  359. return c.discovery.Watch(c.activeCallback, c.hostJoinCallback, c.hostLeaveCallback)
  360. }
  361. func (c *controller) activeCallback() {
  362. ds := c.getStore(datastore.GlobalScope)
  363. if ds != nil && !ds.Active() {
  364. ds.RestartWatch()
  365. }
  366. }
  367. func (c *controller) hostJoinCallback(nodes []net.IP) {
  368. c.processNodeDiscovery(nodes, true)
  369. }
  370. func (c *controller) hostLeaveCallback(nodes []net.IP) {
  371. c.processNodeDiscovery(nodes, false)
  372. }
  373. func (c *controller) processNodeDiscovery(nodes []net.IP, add bool) {
  374. c.drvRegistry.WalkDrivers(func(name string, driver driverapi.Driver, capability driverapi.Capability) bool {
  375. c.pushNodeDiscovery(driver, capability, nodes, add)
  376. return false
  377. })
  378. }
  379. func (c *controller) pushNodeDiscovery(d driverapi.Driver, cap driverapi.Capability, nodes []net.IP, add bool) {
  380. var self net.IP
  381. if c.cfg != nil {
  382. addr := strings.Split(c.cfg.Cluster.Address, ":")
  383. self = net.ParseIP(addr[0])
  384. }
  385. if d == nil || cap.DataScope != datastore.GlobalScope || nodes == nil {
  386. return
  387. }
  388. for _, node := range nodes {
  389. nodeData := discoverapi.NodeDiscoveryData{Address: node.String(), Self: node.Equal(self)}
  390. var err error
  391. if add {
  392. err = d.DiscoverNew(discoverapi.NodeDiscovery, nodeData)
  393. } else {
  394. err = d.DiscoverDelete(discoverapi.NodeDiscovery, nodeData)
  395. }
  396. if err != nil {
  397. log.Debugf("discovery notification error : %v", err)
  398. }
  399. }
  400. }
  401. func (c *controller) Config() config.Config {
  402. c.Lock()
  403. defer c.Unlock()
  404. if c.cfg == nil {
  405. return config.Config{}
  406. }
  407. return *c.cfg
  408. }
  409. func (c *controller) isManager() bool {
  410. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  411. return false
  412. }
  413. return c.cfg.Daemon.ClusterProvider.IsManager()
  414. }
  415. func (c *controller) isAgent() bool {
  416. if c.cfg == nil || c.cfg.Daemon.ClusterProvider == nil {
  417. return false
  418. }
  419. return c.cfg.Daemon.ClusterProvider.IsAgent()
  420. }
  421. func (c *controller) isDistributedControl() bool {
  422. return !c.isManager() && !c.isAgent()
  423. }
  424. func (c *controller) RegisterDriver(networkType string, driver driverapi.Driver, capability driverapi.Capability) error {
  425. c.Lock()
  426. hd := c.discovery
  427. c.Unlock()
  428. if hd != nil {
  429. c.pushNodeDiscovery(driver, capability, hd.Fetch(), true)
  430. }
  431. c.agentDriverNotify(driver)
  432. return nil
  433. }
  434. // NewNetwork creates a new network of the specified network type. The options
  435. // are network specific and modeled in a generic way.
  436. func (c *controller) NewNetwork(networkType, name string, id string, options ...NetworkOption) (Network, error) {
  437. if !config.IsValidName(name) {
  438. return nil, ErrInvalidName(name)
  439. }
  440. if id == "" {
  441. id = stringid.GenerateRandomID()
  442. }
  443. // Construct the network object
  444. network := &network{
  445. name: name,
  446. networkType: networkType,
  447. generic: map[string]interface{}{netlabel.GenericData: make(map[string]string)},
  448. ipamType: ipamapi.DefaultIPAM,
  449. id: id,
  450. ctrlr: c,
  451. persist: true,
  452. drvOnce: &sync.Once{},
  453. }
  454. network.processOptions(options...)
  455. _, cap, err := network.resolveDriver(networkType, true)
  456. if err != nil {
  457. return nil, err
  458. }
  459. if cap.DataScope == datastore.GlobalScope && !c.isDistributedControl() && !network.dynamic {
  460. if c.isManager() {
  461. // For non-distributed controlled environment, globalscoped non-dynamic networks are redirected to Manager
  462. return nil, ManagerRedirectError(name)
  463. }
  464. return nil, types.ForbiddenErrorf("Cannot create a multi-host network from a worker node. Please create the network from a manager node.")
  465. }
  466. // Make sure we have a driver available for this network type
  467. // before we allocate anything.
  468. if _, err := network.driver(true); err != nil {
  469. return nil, err
  470. }
  471. err = network.ipamAllocate()
  472. if err != nil {
  473. return nil, err
  474. }
  475. defer func() {
  476. if err != nil {
  477. network.ipamRelease()
  478. }
  479. }()
  480. err = c.addNetwork(network)
  481. if err != nil {
  482. return nil, err
  483. }
  484. defer func() {
  485. if err != nil {
  486. if e := network.deleteNetwork(); e != nil {
  487. log.Warnf("couldn't roll back driver network on network %s creation failure: %v", network.name, err)
  488. }
  489. }
  490. }()
  491. // First store the endpoint count, then the network. To avoid to
  492. // end up with a datastore containing a network and not an epCnt,
  493. // in case of an ungraceful shutdown during this function call.
  494. epCnt := &endpointCnt{n: network}
  495. if err = c.updateToStore(epCnt); err != nil {
  496. return nil, err
  497. }
  498. defer func() {
  499. if err != nil {
  500. if e := c.deleteFromStore(epCnt); e != nil {
  501. log.Warnf("couldnt rollback from store, epCnt %v on failure (%v): %v", epCnt, err, e)
  502. }
  503. }
  504. }()
  505. network.epCnt = epCnt
  506. if err = c.updateToStore(network); err != nil {
  507. return nil, err
  508. }
  509. if err = network.joinCluster(); err != nil {
  510. log.Errorf("Failed to join network %s into agent cluster: %v", name, err)
  511. }
  512. network.addDriverWatches()
  513. return network, nil
  514. }
  515. func (c *controller) reservePools() {
  516. networks, err := c.getNetworksForScope(datastore.LocalScope)
  517. if err != nil {
  518. log.Warnf("Could not retrieve networks from local store during ipam allocation for existing networks: %v", err)
  519. return
  520. }
  521. for _, n := range networks {
  522. if !doReplayPoolReserve(n) {
  523. continue
  524. }
  525. // Construct pseudo configs for the auto IP case
  526. autoIPv4 := (len(n.ipamV4Config) == 0 || (len(n.ipamV4Config) == 1 && n.ipamV4Config[0].PreferredPool == "")) && len(n.ipamV4Info) > 0
  527. autoIPv6 := (len(n.ipamV6Config) == 0 || (len(n.ipamV6Config) == 1 && n.ipamV6Config[0].PreferredPool == "")) && len(n.ipamV6Info) > 0
  528. if autoIPv4 {
  529. n.ipamV4Config = []*IpamConf{{PreferredPool: n.ipamV4Info[0].Pool.String()}}
  530. }
  531. if n.enableIPv6 && autoIPv6 {
  532. n.ipamV6Config = []*IpamConf{{PreferredPool: n.ipamV6Info[0].Pool.String()}}
  533. }
  534. // Account current network gateways
  535. for i, c := range n.ipamV4Config {
  536. if c.Gateway == "" && n.ipamV4Info[i].Gateway != nil {
  537. c.Gateway = n.ipamV4Info[i].Gateway.IP.String()
  538. }
  539. }
  540. for i, c := range n.ipamV6Config {
  541. if c.Gateway == "" && n.ipamV6Info[i].Gateway != nil {
  542. c.Gateway = n.ipamV6Info[i].Gateway.IP.String()
  543. }
  544. }
  545. if err := n.ipamAllocate(); err != nil {
  546. log.Warnf("Failed to allocate ipam pool(s) for network %q (%s): %v", n.Name(), n.ID(), err)
  547. }
  548. }
  549. }
  550. func doReplayPoolReserve(n *network) bool {
  551. _, caps, err := n.getController().getIPAMDriver(n.ipamType)
  552. if err != nil {
  553. log.Warnf("Failed to retrieve ipam driver for network %q (%s): %v", n.Name(), n.ID(), err)
  554. return false
  555. }
  556. return caps.RequiresRequestReplay
  557. }
  558. func (c *controller) addNetwork(n *network) error {
  559. d, err := n.driver(true)
  560. if err != nil {
  561. return err
  562. }
  563. // Create the network
  564. if err := d.CreateNetwork(n.id, n.generic, n, n.getIPData(4), n.getIPData(6)); err != nil {
  565. return err
  566. }
  567. return nil
  568. }
  569. func (c *controller) Networks() []Network {
  570. var list []Network
  571. networks, err := c.getNetworksFromStore()
  572. if err != nil {
  573. log.Error(err)
  574. }
  575. for _, n := range networks {
  576. if n.inDelete {
  577. continue
  578. }
  579. list = append(list, n)
  580. }
  581. return list
  582. }
  583. func (c *controller) WalkNetworks(walker NetworkWalker) {
  584. for _, n := range c.Networks() {
  585. if walker(n) {
  586. return
  587. }
  588. }
  589. }
  590. func (c *controller) NetworkByName(name string) (Network, error) {
  591. if name == "" {
  592. return nil, ErrInvalidName(name)
  593. }
  594. var n Network
  595. s := func(current Network) bool {
  596. if current.Name() == name {
  597. n = current
  598. return true
  599. }
  600. return false
  601. }
  602. c.WalkNetworks(s)
  603. if n == nil {
  604. return nil, ErrNoSuchNetwork(name)
  605. }
  606. return n, nil
  607. }
  608. func (c *controller) NetworkByID(id string) (Network, error) {
  609. if id == "" {
  610. return nil, ErrInvalidID(id)
  611. }
  612. n, err := c.getNetworkFromStore(id)
  613. if err != nil {
  614. return nil, ErrNoSuchNetwork(id)
  615. }
  616. return n, nil
  617. }
  618. // NewSandbox creates a new sandbox for the passed container id
  619. func (c *controller) NewSandbox(containerID string, options ...SandboxOption) (sBox Sandbox, err error) {
  620. if containerID == "" {
  621. return nil, types.BadRequestErrorf("invalid container ID")
  622. }
  623. var sb *sandbox
  624. c.Lock()
  625. for _, s := range c.sandboxes {
  626. if s.containerID == containerID {
  627. // If not a stub, then we already have a complete sandbox.
  628. if !s.isStub {
  629. c.Unlock()
  630. return nil, types.BadRequestErrorf("container %s is already present: %v", containerID, s)
  631. }
  632. // We already have a stub sandbox from the
  633. // store. Make use of it so that we don't lose
  634. // the endpoints from store but reset the
  635. // isStub flag.
  636. sb = s
  637. sb.isStub = false
  638. break
  639. }
  640. }
  641. c.Unlock()
  642. // Create sandbox and process options first. Key generation depends on an option
  643. if sb == nil {
  644. sb = &sandbox{
  645. id: stringid.GenerateRandomID(),
  646. containerID: containerID,
  647. endpoints: epHeap{},
  648. epPriority: map[string]int{},
  649. config: containerConfig{},
  650. controller: c,
  651. }
  652. }
  653. sBox = sb
  654. heap.Init(&sb.endpoints)
  655. sb.processOptions(options...)
  656. c.Lock()
  657. if sb.ingress && c.ingressSandbox != nil {
  658. c.Unlock()
  659. return nil, fmt.Errorf("ingress sandbox already present")
  660. }
  661. c.ingressSandbox = sb
  662. c.Unlock()
  663. defer func() {
  664. if err != nil {
  665. c.Lock()
  666. if sb.ingress {
  667. c.ingressSandbox = nil
  668. }
  669. c.Unlock()
  670. }
  671. }()
  672. if err = sb.setupResolutionFiles(); err != nil {
  673. return nil, err
  674. }
  675. if sb.config.useDefaultSandBox {
  676. c.sboxOnce.Do(func() {
  677. c.defOsSbox, err = osl.NewSandbox(sb.Key(), false)
  678. })
  679. if err != nil {
  680. c.sboxOnce = sync.Once{}
  681. return nil, fmt.Errorf("failed to create default sandbox: %v", err)
  682. }
  683. sb.osSbox = c.defOsSbox
  684. }
  685. if sb.osSbox == nil && !sb.config.useExternalKey {
  686. if sb.osSbox, err = osl.NewSandbox(sb.Key(), !sb.config.useDefaultSandBox); err != nil {
  687. return nil, fmt.Errorf("failed to create new osl sandbox: %v", err)
  688. }
  689. }
  690. c.Lock()
  691. c.sandboxes[sb.id] = sb
  692. c.Unlock()
  693. defer func() {
  694. if err != nil {
  695. c.Lock()
  696. delete(c.sandboxes, sb.id)
  697. c.Unlock()
  698. }
  699. }()
  700. err = sb.storeUpdate()
  701. if err != nil {
  702. return nil, fmt.Errorf("updating the store state of sandbox failed: %v", err)
  703. }
  704. return sb, nil
  705. }
  706. func (c *controller) Sandboxes() []Sandbox {
  707. c.Lock()
  708. defer c.Unlock()
  709. list := make([]Sandbox, 0, len(c.sandboxes))
  710. for _, s := range c.sandboxes {
  711. // Hide stub sandboxes from libnetwork users
  712. if s.isStub {
  713. continue
  714. }
  715. list = append(list, s)
  716. }
  717. return list
  718. }
  719. func (c *controller) WalkSandboxes(walker SandboxWalker) {
  720. for _, sb := range c.Sandboxes() {
  721. if walker(sb) {
  722. return
  723. }
  724. }
  725. }
  726. func (c *controller) SandboxByID(id string) (Sandbox, error) {
  727. if id == "" {
  728. return nil, ErrInvalidID(id)
  729. }
  730. c.Lock()
  731. s, ok := c.sandboxes[id]
  732. c.Unlock()
  733. if !ok {
  734. return nil, types.NotFoundErrorf("sandbox %s not found", id)
  735. }
  736. return s, nil
  737. }
  738. // SandboxDestroy destroys a sandbox given a container ID
  739. func (c *controller) SandboxDestroy(id string) error {
  740. var sb *sandbox
  741. c.Lock()
  742. for _, s := range c.sandboxes {
  743. if s.containerID == id {
  744. sb = s
  745. break
  746. }
  747. }
  748. c.Unlock()
  749. // It is not an error if sandbox is not available
  750. if sb == nil {
  751. return nil
  752. }
  753. return sb.Delete()
  754. }
  755. // SandboxContainerWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed containerID
  756. func SandboxContainerWalker(out *Sandbox, containerID string) SandboxWalker {
  757. return func(sb Sandbox) bool {
  758. if sb.ContainerID() == containerID {
  759. *out = sb
  760. return true
  761. }
  762. return false
  763. }
  764. }
  765. // SandboxKeyWalker returns a Sandbox Walker function which looks for an existing Sandbox with the passed key
  766. func SandboxKeyWalker(out *Sandbox, key string) SandboxWalker {
  767. return func(sb Sandbox) bool {
  768. if sb.Key() == key {
  769. *out = sb
  770. return true
  771. }
  772. return false
  773. }
  774. }
  775. func (c *controller) loadDriver(networkType string) error {
  776. // Plugins pkg performs lazy loading of plugins that acts as remote drivers.
  777. // As per the design, this Get call will result in remote driver discovery if there is a corresponding plugin available.
  778. _, err := plugins.Get(networkType, driverapi.NetworkPluginEndpointType)
  779. if err != nil {
  780. if err == plugins.ErrNotFound {
  781. return types.NotFoundErrorf(err.Error())
  782. }
  783. return err
  784. }
  785. return nil
  786. }
  787. func (c *controller) loadIPAMDriver(name string) error {
  788. if _, err := plugins.Get(name, ipamapi.PluginEndpointType); err != nil {
  789. if err == plugins.ErrNotFound {
  790. return types.NotFoundErrorf(err.Error())
  791. }
  792. return err
  793. }
  794. return nil
  795. }
  796. func (c *controller) getIPAMDriver(name string) (ipamapi.Ipam, *ipamapi.Capability, error) {
  797. id, cap := c.drvRegistry.IPAM(name)
  798. if id == nil {
  799. // Might be a plugin name. Try loading it
  800. if err := c.loadIPAMDriver(name); err != nil {
  801. return nil, nil, err
  802. }
  803. // Now that we resolved the plugin, try again looking up the registry
  804. id, cap = c.drvRegistry.IPAM(name)
  805. if id == nil {
  806. return nil, nil, types.BadRequestErrorf("invalid ipam driver: %q", name)
  807. }
  808. }
  809. return id, cap, nil
  810. }
  811. func (c *controller) Stop() {
  812. c.closeStores()
  813. c.stopExternalKeyListener()
  814. osl.GC()
  815. }