controller.go 24 KB

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