controller.go 25 KB

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