controller.go 25 KB

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