sandbox.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. package libnetwork
  2. import (
  3. "bytes"
  4. "container/heap"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "sync"
  12. log "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/pkg/ioutils"
  14. "github.com/docker/libnetwork/etchosts"
  15. "github.com/docker/libnetwork/osl"
  16. "github.com/docker/libnetwork/resolvconf"
  17. "github.com/docker/libnetwork/types"
  18. )
  19. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  20. type Sandbox interface {
  21. // ID returns the ID of the sandbox
  22. ID() string
  23. // Key returns the sandbox's key
  24. Key() string
  25. // ContainerID returns the container id associated to this sandbox
  26. ContainerID() string
  27. // Labels returns the sandbox's labels
  28. Labels() map[string]interface{}
  29. // Statistics retrieves the interfaces' statistics for the sandbox
  30. Statistics() (map[string]*osl.InterfaceStatistics, error)
  31. // Delete destroys this container after detaching it from all connected endpoints.
  32. Delete() error
  33. }
  34. // SandboxOption is a option setter function type used to pass varios options to
  35. // NewNetContainer method. The various setter functions of type SandboxOption are
  36. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  37. type SandboxOption func(sb *sandbox)
  38. func (sb *sandbox) processOptions(options ...SandboxOption) {
  39. for _, opt := range options {
  40. if opt != nil {
  41. opt(sb)
  42. }
  43. }
  44. }
  45. type epHeap []*endpoint
  46. type sandbox struct {
  47. id string
  48. containerID string
  49. config containerConfig
  50. osSbox osl.Sandbox
  51. controller *controller
  52. refCnt int
  53. endpoints epHeap
  54. epPriority map[string]int
  55. //hostsPath string
  56. //resolvConfPath string
  57. joinLeaveDone chan struct{}
  58. sync.Mutex
  59. }
  60. // These are the container configs used to customize container /etc/hosts file.
  61. type hostsPathConfig struct {
  62. hostName string
  63. domainName string
  64. hostsPath string
  65. originHostsPath string
  66. extraHosts []extraHost
  67. parentUpdates []parentUpdate
  68. }
  69. type parentUpdate struct {
  70. cid string
  71. name string
  72. ip string
  73. }
  74. type extraHost struct {
  75. name string
  76. IP string
  77. }
  78. // These are the container configs used to customize container /etc/resolv.conf file.
  79. type resolvConfPathConfig struct {
  80. resolvConfPath string
  81. originResolvConfPath string
  82. resolvConfHashFile string
  83. dnsList []string
  84. dnsSearchList []string
  85. }
  86. type containerConfig struct {
  87. hostsPathConfig
  88. resolvConfPathConfig
  89. generic map[string]interface{}
  90. useDefaultSandBox bool
  91. prio int // higher the value, more the priority
  92. }
  93. func (sb *sandbox) ID() string {
  94. return sb.id
  95. }
  96. func (sb *sandbox) ContainerID() string {
  97. return sb.containerID
  98. }
  99. func (sb *sandbox) Key() string {
  100. if sb.config.useDefaultSandBox {
  101. return osl.GenerateKey("default")
  102. }
  103. return osl.GenerateKey(sb.id)
  104. }
  105. func (sb *sandbox) Labels() map[string]interface{} {
  106. return sb.config.generic
  107. }
  108. func (sb *sandbox) Statistics() (map[string]*osl.InterfaceStatistics, error) {
  109. m := make(map[string]*osl.InterfaceStatistics)
  110. if sb.osSbox == nil {
  111. return m, nil
  112. }
  113. var err error
  114. for _, i := range sb.osSbox.Info().Interfaces() {
  115. if m[i.DstName()], err = i.Statistics(); err != nil {
  116. return m, err
  117. }
  118. }
  119. return m, nil
  120. }
  121. func (sb *sandbox) Delete() error {
  122. sb.Lock()
  123. c := sb.controller
  124. eps := make([]*endpoint, len(sb.endpoints))
  125. for i, ep := range sb.endpoints {
  126. eps[i] = ep
  127. }
  128. sb.Unlock()
  129. // Detach from all containers
  130. for _, ep := range eps {
  131. if err := ep.Leave(sb); err != nil {
  132. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  133. }
  134. }
  135. if sb.osSbox != nil {
  136. sb.osSbox.Destroy()
  137. }
  138. c.Lock()
  139. delete(c.sandboxes, sb.ID())
  140. c.Unlock()
  141. return nil
  142. }
  143. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  144. sb.Lock()
  145. defer sb.Unlock()
  146. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  147. return json.Marshal(sb.id)
  148. }
  149. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  150. sb.Lock()
  151. defer sb.Unlock()
  152. var id string
  153. if err := json.Unmarshal(b, &id); err != nil {
  154. return err
  155. }
  156. sb.id = id
  157. return nil
  158. }
  159. func (sb *sandbox) updateGateway(ep *endpoint) error {
  160. sb.osSbox.UnsetGateway()
  161. sb.osSbox.UnsetGatewayIPv6()
  162. if ep == nil {
  163. return nil
  164. }
  165. ep.Lock()
  166. joinInfo := ep.joinInfo
  167. ep.Unlock()
  168. if err := sb.osSbox.SetGateway(joinInfo.gw); err != nil {
  169. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  170. }
  171. if err := sb.osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  172. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  173. }
  174. return nil
  175. }
  176. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  177. ep.Lock()
  178. joinInfo := ep.joinInfo
  179. ifaces := ep.iFaces
  180. ep.Unlock()
  181. for _, i := range ifaces {
  182. var ifaceOptions []osl.IfaceOption
  183. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(&i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  184. if i.addrv6.IP.To16() != nil {
  185. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(&i.addrv6))
  186. }
  187. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  188. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  189. }
  190. }
  191. if joinInfo != nil {
  192. // Set up non-interface routes.
  193. for _, r := range joinInfo.StaticRoutes {
  194. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  195. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  196. }
  197. }
  198. }
  199. sb.Lock()
  200. heap.Push(&sb.endpoints, ep)
  201. highEp := sb.endpoints[0]
  202. sb.Unlock()
  203. if ep == highEp {
  204. if err := sb.updateGateway(ep); err != nil {
  205. return err
  206. }
  207. }
  208. return nil
  209. }
  210. func (sb *sandbox) clearNetworkResources(ep *endpoint) error {
  211. for _, i := range sb.osSbox.Info().Interfaces() {
  212. // Only remove the interfaces owned by this endpoint from the sandbox.
  213. if ep.hasInterface(i.SrcName()) {
  214. if err := i.Remove(); err != nil {
  215. log.Debugf("Remove interface failed: %v", err)
  216. }
  217. }
  218. }
  219. ep.Lock()
  220. joinInfo := ep.joinInfo
  221. ep.Unlock()
  222. // Remove non-interface routes.
  223. for _, r := range joinInfo.StaticRoutes {
  224. if err := sb.osSbox.RemoveStaticRoute(r); err != nil {
  225. log.Debugf("Remove route failed: %v", err)
  226. }
  227. }
  228. sb.Lock()
  229. if len(sb.endpoints) == 0 {
  230. // sb.endpoints should never be empty and this is unexpected error condition
  231. // We log an error message to note this down for debugging purposes.
  232. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  233. sb.Unlock()
  234. return nil
  235. }
  236. highEpBefore := sb.endpoints[0]
  237. var (
  238. i int
  239. e *endpoint
  240. )
  241. for i, e = range sb.endpoints {
  242. if e == ep {
  243. break
  244. }
  245. }
  246. heap.Remove(&sb.endpoints, i)
  247. var highEpAfter *endpoint
  248. if len(sb.endpoints) > 0 {
  249. highEpAfter = sb.endpoints[0]
  250. }
  251. delete(sb.epPriority, ep.ID())
  252. sb.Unlock()
  253. if highEpBefore != highEpAfter {
  254. sb.updateGateway(highEpAfter)
  255. }
  256. return nil
  257. }
  258. const (
  259. defaultPrefix = "/var/lib/docker/network/files"
  260. filePerm = 0644
  261. )
  262. func (sb *sandbox) buildHostsFile() error {
  263. if sb.config.hostsPath == "" {
  264. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  265. }
  266. dir, _ := filepath.Split(sb.config.hostsPath)
  267. if err := createBasePath(dir); err != nil {
  268. return err
  269. }
  270. // This is for the host mode networking
  271. if sb.config.originHostsPath != "" {
  272. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  273. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  274. }
  275. return nil
  276. }
  277. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  278. for _, extraHost := range sb.config.extraHosts {
  279. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  280. }
  281. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  282. }
  283. func (sb *sandbox) updateHostsFile(ifaceIP string, svcRecords []etchosts.Record) error {
  284. // Rebuild the hosts file accounting for the passed interface IP and service records
  285. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts)+len(svcRecords))
  286. for _, extraHost := range sb.config.extraHosts {
  287. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  288. }
  289. for _, svc := range svcRecords {
  290. extraContent = append(extraContent, svc)
  291. }
  292. return etchosts.Build(sb.config.hostsPath, ifaceIP, sb.config.hostName, sb.config.domainName, extraContent)
  293. }
  294. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  295. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  296. log.Warnf("Failed adding service host entries to the running container: %v", err)
  297. }
  298. }
  299. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  300. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  301. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  302. }
  303. }
  304. func (sb *sandbox) updateParentHosts() error {
  305. var pSb Sandbox
  306. for _, update := range sb.config.parentUpdates {
  307. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  308. if pSb == nil {
  309. continue
  310. }
  311. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  312. return err
  313. }
  314. }
  315. return nil
  316. }
  317. func (sb *sandbox) setupDNS() error {
  318. if sb.config.resolvConfPath == "" {
  319. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  320. }
  321. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  322. dir, _ := filepath.Split(sb.config.resolvConfPath)
  323. if err := createBasePath(dir); err != nil {
  324. return err
  325. }
  326. // This is for the host mode networking
  327. if sb.config.originResolvConfPath != "" {
  328. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  329. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  330. }
  331. return nil
  332. }
  333. resolvConf, err := resolvconf.Get()
  334. if err != nil {
  335. return err
  336. }
  337. dnsList := resolvconf.GetNameservers(resolvConf)
  338. dnsSearchList := resolvconf.GetSearchDomains(resolvConf)
  339. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 {
  340. if len(sb.config.dnsList) > 0 {
  341. dnsList = sb.config.dnsList
  342. }
  343. if len(sb.config.dnsSearchList) > 0 {
  344. dnsSearchList = sb.config.dnsSearchList
  345. }
  346. }
  347. hash, err := resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList)
  348. if err != nil {
  349. return err
  350. }
  351. // write hash
  352. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(hash), filePerm); err != nil {
  353. return types.InternalErrorf("failed to write resol.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  354. }
  355. return nil
  356. }
  357. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  358. var oldHash []byte
  359. hashFile := sb.config.resolvConfHashFile
  360. resolvConf, err := ioutil.ReadFile(sb.config.resolvConfPath)
  361. if err != nil {
  362. if !os.IsNotExist(err) {
  363. return err
  364. }
  365. } else {
  366. oldHash, err = ioutil.ReadFile(hashFile)
  367. if err != nil {
  368. if !os.IsNotExist(err) {
  369. return err
  370. }
  371. oldHash = []byte{}
  372. }
  373. }
  374. curHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
  375. if err != nil {
  376. return err
  377. }
  378. if string(oldHash) != "" && curHash != string(oldHash) {
  379. // Seems the user has changed the container resolv.conf since the last time
  380. // we checked so return without doing anything.
  381. log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  382. return nil
  383. }
  384. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  385. resolvConf, _ = resolvconf.FilterResolvDNS(resolvConf, ipv6Enabled)
  386. newHash, err := ioutils.HashData(bytes.NewReader(resolvConf))
  387. if err != nil {
  388. return err
  389. }
  390. // for atomic updates to these files, use temporary files with os.Rename:
  391. dir := path.Dir(sb.config.resolvConfPath)
  392. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  393. if err != nil {
  394. return err
  395. }
  396. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  397. if err != nil {
  398. return err
  399. }
  400. // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
  401. if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
  402. return err
  403. }
  404. // write the updates to the temp files
  405. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newHash), filePerm); err != nil {
  406. return err
  407. }
  408. if err = ioutil.WriteFile(tmpResolvFile.Name(), resolvConf, filePerm); err != nil {
  409. return err
  410. }
  411. // rename the temp files for atomic replace
  412. if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
  413. return err
  414. }
  415. return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
  416. }
  417. // OptionHostname function returns an option setter for hostname option to
  418. // be passed to NewSandbox method.
  419. func OptionHostname(name string) SandboxOption {
  420. return func(sb *sandbox) {
  421. sb.config.hostName = name
  422. }
  423. }
  424. // OptionDomainname function returns an option setter for domainname option to
  425. // be passed to NewSandbox method.
  426. func OptionDomainname(name string) SandboxOption {
  427. return func(sb *sandbox) {
  428. sb.config.domainName = name
  429. }
  430. }
  431. // OptionHostsPath function returns an option setter for hostspath option to
  432. // be passed to NewSandbox method.
  433. func OptionHostsPath(path string) SandboxOption {
  434. return func(sb *sandbox) {
  435. sb.config.hostsPath = path
  436. }
  437. }
  438. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  439. // tbeo passed to NewSandbox method.
  440. func OptionOriginHostsPath(path string) SandboxOption {
  441. return func(sb *sandbox) {
  442. sb.config.originHostsPath = path
  443. }
  444. }
  445. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  446. // which is a name and IP as strings.
  447. func OptionExtraHost(name string, IP string) SandboxOption {
  448. return func(sb *sandbox) {
  449. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  450. }
  451. }
  452. // OptionParentUpdate function returns an option setter for parent container
  453. // which needs to update the IP address for the linked container.
  454. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  455. return func(sb *sandbox) {
  456. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  457. }
  458. }
  459. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  460. // be passed to net container methods.
  461. func OptionResolvConfPath(path string) SandboxOption {
  462. return func(sb *sandbox) {
  463. sb.config.resolvConfPath = path
  464. }
  465. }
  466. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  467. // origin resolv.conf file to be passed to net container methods.
  468. func OptionOriginResolvConfPath(path string) SandboxOption {
  469. return func(sb *sandbox) {
  470. sb.config.originResolvConfPath = path
  471. }
  472. }
  473. // OptionDNS function returns an option setter for dns entry option to
  474. // be passed to container Create method.
  475. func OptionDNS(dns string) SandboxOption {
  476. return func(sb *sandbox) {
  477. sb.config.dnsList = append(sb.config.dnsList, dns)
  478. }
  479. }
  480. // OptionDNSSearch function returns an option setter for dns search entry option to
  481. // be passed to container Create method.
  482. func OptionDNSSearch(search string) SandboxOption {
  483. return func(sb *sandbox) {
  484. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  485. }
  486. }
  487. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  488. // be passed to container Create method.
  489. func OptionUseDefaultSandbox() SandboxOption {
  490. return func(sb *sandbox) {
  491. sb.config.useDefaultSandBox = true
  492. }
  493. }
  494. // OptionGeneric function returns an option setter for Generic configuration
  495. // that is not managed by libNetwork but can be used by the Drivers during the call to
  496. // net container creation method. Container Labels are a good example.
  497. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  498. return func(sb *sandbox) {
  499. sb.config.generic = generic
  500. }
  501. }
  502. func (eh epHeap) Len() int { return len(eh) }
  503. func (eh epHeap) Less(i, j int) bool {
  504. ci, _ := eh[i].getSandbox()
  505. cj, _ := eh[j].getSandbox()
  506. cip, ok := ci.epPriority[eh[i].ID()]
  507. if !ok {
  508. cip = 0
  509. }
  510. cjp, ok := cj.epPriority[eh[j].ID()]
  511. if !ok {
  512. cjp = 0
  513. }
  514. if cip == cjp {
  515. return eh[i].getNetwork().Name() < eh[j].getNetwork().Name()
  516. }
  517. return cip > cjp
  518. }
  519. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  520. func (eh *epHeap) Push(x interface{}) {
  521. *eh = append(*eh, x.(*endpoint))
  522. }
  523. func (eh *epHeap) Pop() interface{} {
  524. old := *eh
  525. n := len(old)
  526. x := old[n-1]
  527. *eh = old[0 : n-1]
  528. return x
  529. }
  530. func createBasePath(dir string) error {
  531. return os.MkdirAll(dir, filePerm)
  532. }
  533. func createFile(path string) error {
  534. var f *os.File
  535. dir, _ := filepath.Split(path)
  536. err := createBasePath(dir)
  537. if err != nil {
  538. return err
  539. }
  540. f, err = os.Create(path)
  541. if err == nil {
  542. f.Close()
  543. }
  544. return err
  545. }
  546. func copyFile(src, dst string) error {
  547. sBytes, err := ioutil.ReadFile(src)
  548. if err != nil {
  549. return err
  550. }
  551. return ioutil.WriteFile(dst, sBytes, filePerm)
  552. }