sandbox.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. package libnetwork
  2. import (
  3. "container/heap"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "sync"
  11. log "github.com/Sirupsen/logrus"
  12. "github.com/docker/libnetwork/etchosts"
  13. "github.com/docker/libnetwork/osl"
  14. "github.com/docker/libnetwork/resolvconf"
  15. "github.com/docker/libnetwork/types"
  16. )
  17. // Sandbox provides the control over the network container entity. It is a one to one mapping with the container.
  18. type Sandbox interface {
  19. // ID returns the ID of the sandbox
  20. ID() string
  21. // Key returns the sandbox's key
  22. Key() string
  23. // ContainerID returns the container id associated to this sandbox
  24. ContainerID() string
  25. // Labels returns the sandbox's labels
  26. Labels() map[string]interface{}
  27. // Statistics retrieves the interfaces' statistics for the sandbox
  28. Statistics() (map[string]*types.InterfaceStatistics, error)
  29. // Refresh leaves all the endpoints, resets and re-apply the options,
  30. // re-joins all the endpoints without destroying the osl sandbox
  31. Refresh(options ...SandboxOption) error
  32. // SetKey updates the Sandbox Key
  33. SetKey(key string) error
  34. // Delete destroys this container after detaching it from all connected endpoints.
  35. Delete() error
  36. }
  37. // SandboxOption is a option setter function type used to pass varios options to
  38. // NewNetContainer method. The various setter functions of type SandboxOption are
  39. // provided by libnetwork, they look like ContainerOptionXXXX(...)
  40. type SandboxOption func(sb *sandbox)
  41. func (sb *sandbox) processOptions(options ...SandboxOption) {
  42. for _, opt := range options {
  43. if opt != nil {
  44. opt(sb)
  45. }
  46. }
  47. }
  48. type epHeap []*endpoint
  49. type sandbox struct {
  50. id string
  51. containerID string
  52. config containerConfig
  53. osSbox osl.Sandbox
  54. controller *controller
  55. refCnt int
  56. hostsOnce sync.Once
  57. endpoints epHeap
  58. epPriority map[string]int
  59. joinLeaveDone chan struct{}
  60. dbIndex uint64
  61. dbExists bool
  62. sync.Mutex
  63. }
  64. // These are the container configs used to customize container /etc/hosts file.
  65. type hostsPathConfig struct {
  66. hostName string
  67. domainName string
  68. hostsPath string
  69. originHostsPath string
  70. extraHosts []extraHost
  71. parentUpdates []parentUpdate
  72. }
  73. type parentUpdate struct {
  74. cid string
  75. name string
  76. ip string
  77. }
  78. type extraHost struct {
  79. name string
  80. IP string
  81. }
  82. // These are the container configs used to customize container /etc/resolv.conf file.
  83. type resolvConfPathConfig struct {
  84. resolvConfPath string
  85. originResolvConfPath string
  86. resolvConfHashFile string
  87. dnsList []string
  88. dnsSearchList []string
  89. dnsOptionsList []string
  90. }
  91. type containerConfig struct {
  92. hostsPathConfig
  93. resolvConfPathConfig
  94. generic map[string]interface{}
  95. useDefaultSandBox bool
  96. useExternalKey bool
  97. prio int // higher the value, more the priority
  98. }
  99. func (sb *sandbox) ID() string {
  100. return sb.id
  101. }
  102. func (sb *sandbox) ContainerID() string {
  103. return sb.containerID
  104. }
  105. func (sb *sandbox) Key() string {
  106. if sb.config.useDefaultSandBox {
  107. return osl.GenerateKey("default")
  108. }
  109. return osl.GenerateKey(sb.id)
  110. }
  111. func (sb *sandbox) Labels() map[string]interface{} {
  112. return sb.config.generic
  113. }
  114. func (sb *sandbox) Statistics() (map[string]*types.InterfaceStatistics, error) {
  115. m := make(map[string]*types.InterfaceStatistics)
  116. if sb.osSbox == nil {
  117. return m, nil
  118. }
  119. var err error
  120. for _, i := range sb.osSbox.Info().Interfaces() {
  121. if m[i.DstName()], err = i.Statistics(); err != nil {
  122. return m, err
  123. }
  124. }
  125. return m, nil
  126. }
  127. func (sb *sandbox) Delete() error {
  128. c := sb.controller
  129. // Detach from all endpoints
  130. for _, ep := range sb.getConnectedEndpoints() {
  131. // endpoint in the Gateway network will be cleaned up
  132. // when when sandbox no longer needs external connectivity
  133. if ep.endpointInGWNetwork() {
  134. continue
  135. }
  136. if err := ep.Leave(sb); err != nil {
  137. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  138. }
  139. if err := ep.Delete(); err != nil {
  140. log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
  141. }
  142. }
  143. if sb.osSbox != nil {
  144. sb.osSbox.Destroy()
  145. }
  146. if err := sb.storeDelete(); err != nil {
  147. log.Warnf("Failed to delete sandbox %s from store: %v", sb.ID(), err)
  148. }
  149. c.Lock()
  150. delete(c.sandboxes, sb.ID())
  151. c.Unlock()
  152. return nil
  153. }
  154. func (sb *sandbox) Refresh(options ...SandboxOption) error {
  155. // Store connected endpoints
  156. epList := sb.getConnectedEndpoints()
  157. // Detach from all endpoints
  158. for _, ep := range epList {
  159. if err := ep.Leave(sb); err != nil {
  160. log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  161. }
  162. }
  163. // Re-apply options
  164. sb.config = containerConfig{}
  165. sb.processOptions(options...)
  166. // Setup discovery files
  167. if err := sb.setupResolutionFiles(); err != nil {
  168. return err
  169. }
  170. // Re -connect to all endpoints
  171. for _, ep := range epList {
  172. if err := ep.Join(sb); err != nil {
  173. log.Warnf("Failed attach sandbox %s to endpoint %s: %v\n", sb.ID(), ep.ID(), err)
  174. }
  175. }
  176. return nil
  177. }
  178. func (sb *sandbox) MarshalJSON() ([]byte, error) {
  179. sb.Lock()
  180. defer sb.Unlock()
  181. // We are just interested in the container ID. This can be expanded to include all of containerInfo if there is a need
  182. return json.Marshal(sb.id)
  183. }
  184. func (sb *sandbox) UnmarshalJSON(b []byte) (err error) {
  185. sb.Lock()
  186. defer sb.Unlock()
  187. var id string
  188. if err := json.Unmarshal(b, &id); err != nil {
  189. return err
  190. }
  191. sb.id = id
  192. return nil
  193. }
  194. func (sb *sandbox) setupResolutionFiles() error {
  195. if err := sb.buildHostsFile(); err != nil {
  196. return err
  197. }
  198. if err := sb.updateParentHosts(); err != nil {
  199. return err
  200. }
  201. if err := sb.setupDNS(); err != nil {
  202. return err
  203. }
  204. return nil
  205. }
  206. func (sb *sandbox) getConnectedEndpoints() []*endpoint {
  207. sb.Lock()
  208. defer sb.Unlock()
  209. eps := make([]*endpoint, len(sb.endpoints))
  210. for i, ep := range sb.endpoints {
  211. eps[i] = ep
  212. }
  213. return eps
  214. }
  215. func (sb *sandbox) getEndpoint(id string) *endpoint {
  216. sb.Lock()
  217. defer sb.Unlock()
  218. for _, ep := range sb.endpoints {
  219. if ep.id == id {
  220. return ep
  221. }
  222. }
  223. return nil
  224. }
  225. func (sb *sandbox) updateGateway(ep *endpoint) error {
  226. sb.Lock()
  227. osSbox := sb.osSbox
  228. sb.Unlock()
  229. if osSbox == nil {
  230. return nil
  231. }
  232. osSbox.UnsetGateway()
  233. osSbox.UnsetGatewayIPv6()
  234. if ep == nil {
  235. return nil
  236. }
  237. ep.Lock()
  238. joinInfo := ep.joinInfo
  239. ep.Unlock()
  240. if err := osSbox.SetGateway(joinInfo.gw); err != nil {
  241. return fmt.Errorf("failed to set gateway while updating gateway: %v", err)
  242. }
  243. if err := osSbox.SetGatewayIPv6(joinInfo.gw6); err != nil {
  244. return fmt.Errorf("failed to set IPv6 gateway while updating gateway: %v", err)
  245. }
  246. return nil
  247. }
  248. func (sb *sandbox) SetKey(basePath string) error {
  249. var err error
  250. if basePath == "" {
  251. return types.BadRequestErrorf("invalid sandbox key")
  252. }
  253. sb.Lock()
  254. osSbox := sb.osSbox
  255. sb.Unlock()
  256. if osSbox != nil {
  257. // If we already have an OS sandbox, release the network resources from that
  258. // and destroy the OS snab. We are moving into a new home further down. Note that none
  259. // of the network resources gets destroyed during the move.
  260. sb.releaseOSSbox()
  261. }
  262. osSbox, err = osl.GetSandboxForExternalKey(basePath, sb.Key())
  263. if err != nil {
  264. return err
  265. }
  266. sb.Lock()
  267. sb.osSbox = osSbox
  268. sb.Unlock()
  269. defer func() {
  270. if err != nil {
  271. sb.Lock()
  272. sb.osSbox = nil
  273. sb.Unlock()
  274. }
  275. }()
  276. for _, ep := range sb.getConnectedEndpoints() {
  277. if err = sb.populateNetworkResources(ep); err != nil {
  278. return err
  279. }
  280. }
  281. return nil
  282. }
  283. func releaseOSSboxResources(osSbox osl.Sandbox, ep *endpoint) {
  284. for _, i := range osSbox.Info().Interfaces() {
  285. // Only remove the interfaces owned by this endpoint from the sandbox.
  286. if ep.hasInterface(i.SrcName()) {
  287. if err := i.Remove(); err != nil {
  288. log.Debugf("Remove interface failed: %v", err)
  289. }
  290. }
  291. }
  292. ep.Lock()
  293. joinInfo := ep.joinInfo
  294. ep.Unlock()
  295. // Remove non-interface routes.
  296. for _, r := range joinInfo.StaticRoutes {
  297. if err := osSbox.RemoveStaticRoute(r); err != nil {
  298. log.Debugf("Remove route failed: %v", err)
  299. }
  300. }
  301. }
  302. func (sb *sandbox) releaseOSSbox() {
  303. sb.Lock()
  304. osSbox := sb.osSbox
  305. sb.osSbox = nil
  306. sb.Unlock()
  307. if osSbox == nil {
  308. return
  309. }
  310. for _, ep := range sb.getConnectedEndpoints() {
  311. releaseOSSboxResources(osSbox, ep)
  312. }
  313. osSbox.Destroy()
  314. }
  315. func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
  316. sb.Lock()
  317. if sb.osSbox == nil {
  318. sb.Unlock()
  319. return nil
  320. }
  321. sb.Unlock()
  322. ep.Lock()
  323. joinInfo := ep.joinInfo
  324. i := ep.iface
  325. ep.Unlock()
  326. if i.srcName != "" {
  327. var ifaceOptions []osl.IfaceOption
  328. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
  329. if i.addrv6 != nil && i.addrv6.IP.To16() != nil {
  330. ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().AddressIPv6(i.addrv6))
  331. }
  332. if err := sb.osSbox.AddInterface(i.srcName, i.dstPrefix, ifaceOptions...); err != nil {
  333. return fmt.Errorf("failed to add interface %s to sandbox: %v", i.srcName, err)
  334. }
  335. }
  336. if joinInfo != nil {
  337. // Set up non-interface routes.
  338. for _, r := range joinInfo.StaticRoutes {
  339. if err := sb.osSbox.AddStaticRoute(r); err != nil {
  340. return fmt.Errorf("failed to add static route %s: %v", r.Destination.String(), err)
  341. }
  342. }
  343. }
  344. for _, gwep := range sb.getConnectedEndpoints() {
  345. if len(gwep.Gateway()) > 0 {
  346. if gwep != ep {
  347. return nil
  348. }
  349. if err := sb.updateGateway(gwep); err != nil {
  350. return err
  351. }
  352. }
  353. }
  354. return sb.storeUpdate()
  355. }
  356. func (sb *sandbox) clearNetworkResources(origEp *endpoint) error {
  357. ep := sb.getEndpoint(origEp.id)
  358. if ep == nil {
  359. return fmt.Errorf("could not find the sandbox endpoint data for endpoint %s",
  360. ep.name)
  361. }
  362. sb.Lock()
  363. osSbox := sb.osSbox
  364. sb.Unlock()
  365. if osSbox != nil {
  366. releaseOSSboxResources(osSbox, ep)
  367. }
  368. sb.Lock()
  369. if len(sb.endpoints) == 0 {
  370. // sb.endpoints should never be empty and this is unexpected error condition
  371. // We log an error message to note this down for debugging purposes.
  372. log.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name())
  373. sb.Unlock()
  374. return nil
  375. }
  376. var (
  377. gwepBefore, gwepAfter *endpoint
  378. index = -1
  379. )
  380. for i, e := range sb.endpoints {
  381. if e == ep {
  382. index = i
  383. }
  384. if len(e.Gateway()) > 0 && gwepBefore == nil {
  385. gwepBefore = e
  386. }
  387. if index != -1 && gwepBefore != nil {
  388. break
  389. }
  390. }
  391. heap.Remove(&sb.endpoints, index)
  392. for _, e := range sb.endpoints {
  393. if len(e.Gateway()) > 0 {
  394. gwepAfter = e
  395. break
  396. }
  397. }
  398. delete(sb.epPriority, ep.ID())
  399. sb.Unlock()
  400. if gwepAfter != nil && gwepBefore != gwepAfter {
  401. sb.updateGateway(gwepAfter)
  402. }
  403. return sb.storeUpdate()
  404. }
  405. const (
  406. defaultPrefix = "/var/lib/docker/network/files"
  407. dirPerm = 0755
  408. filePerm = 0644
  409. )
  410. func (sb *sandbox) buildHostsFile() error {
  411. if sb.config.hostsPath == "" {
  412. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  413. }
  414. dir, _ := filepath.Split(sb.config.hostsPath)
  415. if err := createBasePath(dir); err != nil {
  416. return err
  417. }
  418. // This is for the host mode networking
  419. if sb.config.originHostsPath != "" {
  420. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  421. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  422. }
  423. return nil
  424. }
  425. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  426. for _, extraHost := range sb.config.extraHosts {
  427. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  428. }
  429. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  430. }
  431. func (sb *sandbox) updateHostsFile(ifaceIP string, svcRecords []etchosts.Record) error {
  432. var err error
  433. if sb.config.originHostsPath != "" {
  434. return nil
  435. }
  436. max := func(a, b int) int {
  437. if a < b {
  438. return b
  439. }
  440. return a
  441. }
  442. extraContent := make([]etchosts.Record, 0,
  443. max(len(sb.config.extraHosts), len(svcRecords)))
  444. sb.hostsOnce.Do(func() {
  445. // Rebuild the hosts file accounting for the passed
  446. // interface IP and service records
  447. for _, extraHost := range sb.config.extraHosts {
  448. extraContent = append(extraContent,
  449. etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  450. }
  451. err = etchosts.Build(sb.config.hostsPath, ifaceIP,
  452. sb.config.hostName, sb.config.domainName, extraContent)
  453. })
  454. if err != nil {
  455. return err
  456. }
  457. extraContent = extraContent[:0]
  458. for _, svc := range svcRecords {
  459. extraContent = append(extraContent, svc)
  460. }
  461. sb.addHostsEntries(extraContent)
  462. return nil
  463. }
  464. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  465. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  466. log.Warnf("Failed adding service host entries to the running container: %v", err)
  467. }
  468. }
  469. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  470. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  471. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  472. }
  473. }
  474. func (sb *sandbox) updateParentHosts() error {
  475. var pSb Sandbox
  476. for _, update := range sb.config.parentUpdates {
  477. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  478. if pSb == nil {
  479. continue
  480. }
  481. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  482. return err
  483. }
  484. }
  485. return nil
  486. }
  487. func (sb *sandbox) setupDNS() error {
  488. var newRC *resolvconf.File
  489. if sb.config.resolvConfPath == "" {
  490. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  491. }
  492. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  493. dir, _ := filepath.Split(sb.config.resolvConfPath)
  494. if err := createBasePath(dir); err != nil {
  495. return err
  496. }
  497. // This is for the host mode networking
  498. if sb.config.originResolvConfPath != "" {
  499. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  500. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  501. }
  502. return nil
  503. }
  504. currRC, err := resolvconf.Get()
  505. if err != nil {
  506. return err
  507. }
  508. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  509. var (
  510. err error
  511. dnsList = resolvconf.GetNameservers(currRC.Content)
  512. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  513. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  514. )
  515. if len(sb.config.dnsList) > 0 {
  516. dnsList = sb.config.dnsList
  517. }
  518. if len(sb.config.dnsSearchList) > 0 {
  519. dnsSearchList = sb.config.dnsSearchList
  520. }
  521. if len(sb.config.dnsOptionsList) > 0 {
  522. dnsOptionsList = sb.config.dnsOptionsList
  523. }
  524. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  525. if err != nil {
  526. return err
  527. }
  528. } else {
  529. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  530. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  531. return err
  532. }
  533. // No contention on container resolv.conf file at sandbox creation
  534. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  535. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  536. }
  537. }
  538. // Write hash
  539. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  540. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  541. }
  542. return nil
  543. }
  544. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  545. var (
  546. currHash string
  547. hashFile = sb.config.resolvConfHashFile
  548. )
  549. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  550. return nil
  551. }
  552. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  553. if err != nil {
  554. if !os.IsNotExist(err) {
  555. return err
  556. }
  557. } else {
  558. h, err := ioutil.ReadFile(hashFile)
  559. if err != nil {
  560. if !os.IsNotExist(err) {
  561. return err
  562. }
  563. } else {
  564. currHash = string(h)
  565. }
  566. }
  567. if currHash != "" && currHash != currRC.Hash {
  568. // Seems the user has changed the container resolv.conf since the last time
  569. // we checked so return without doing anything.
  570. log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  571. return nil
  572. }
  573. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  574. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  575. if err != nil {
  576. return err
  577. }
  578. // for atomic updates to these files, use temporary files with os.Rename:
  579. dir := path.Dir(sb.config.resolvConfPath)
  580. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  581. if err != nil {
  582. return err
  583. }
  584. tmpResolvFile, err := ioutil.TempFile(dir, "resolv")
  585. if err != nil {
  586. return err
  587. }
  588. // Change the perms to filePerm (0644) since ioutil.TempFile creates it by default as 0600
  589. if err := os.Chmod(tmpResolvFile.Name(), filePerm); err != nil {
  590. return err
  591. }
  592. // write the updates to the temp files
  593. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
  594. return err
  595. }
  596. if err = ioutil.WriteFile(tmpResolvFile.Name(), newRC.Content, filePerm); err != nil {
  597. return err
  598. }
  599. // rename the temp files for atomic replace
  600. if err = os.Rename(tmpHashFile.Name(), hashFile); err != nil {
  601. return err
  602. }
  603. return os.Rename(tmpResolvFile.Name(), sb.config.resolvConfPath)
  604. }
  605. // joinLeaveStart waits to ensure there are no joins or leaves in progress and
  606. // marks this join/leave in progress without race
  607. func (sb *sandbox) joinLeaveStart() {
  608. sb.Lock()
  609. defer sb.Unlock()
  610. for sb.joinLeaveDone != nil {
  611. joinLeaveDone := sb.joinLeaveDone
  612. sb.Unlock()
  613. select {
  614. case <-joinLeaveDone:
  615. }
  616. sb.Lock()
  617. }
  618. sb.joinLeaveDone = make(chan struct{})
  619. }
  620. // joinLeaveEnd marks the end of this join/leave operation and
  621. // signals the same without race to other join and leave waiters
  622. func (sb *sandbox) joinLeaveEnd() {
  623. sb.Lock()
  624. defer sb.Unlock()
  625. if sb.joinLeaveDone != nil {
  626. close(sb.joinLeaveDone)
  627. sb.joinLeaveDone = nil
  628. }
  629. }
  630. // OptionHostname function returns an option setter for hostname option to
  631. // be passed to NewSandbox method.
  632. func OptionHostname(name string) SandboxOption {
  633. return func(sb *sandbox) {
  634. sb.config.hostName = name
  635. }
  636. }
  637. // OptionDomainname function returns an option setter for domainname option to
  638. // be passed to NewSandbox method.
  639. func OptionDomainname(name string) SandboxOption {
  640. return func(sb *sandbox) {
  641. sb.config.domainName = name
  642. }
  643. }
  644. // OptionHostsPath function returns an option setter for hostspath option to
  645. // be passed to NewSandbox method.
  646. func OptionHostsPath(path string) SandboxOption {
  647. return func(sb *sandbox) {
  648. sb.config.hostsPath = path
  649. }
  650. }
  651. // OptionOriginHostsPath function returns an option setter for origin hosts file path
  652. // tbeo passed to NewSandbox method.
  653. func OptionOriginHostsPath(path string) SandboxOption {
  654. return func(sb *sandbox) {
  655. sb.config.originHostsPath = path
  656. }
  657. }
  658. // OptionExtraHost function returns an option setter for extra /etc/hosts options
  659. // which is a name and IP as strings.
  660. func OptionExtraHost(name string, IP string) SandboxOption {
  661. return func(sb *sandbox) {
  662. sb.config.extraHosts = append(sb.config.extraHosts, extraHost{name: name, IP: IP})
  663. }
  664. }
  665. // OptionParentUpdate function returns an option setter for parent container
  666. // which needs to update the IP address for the linked container.
  667. func OptionParentUpdate(cid string, name, ip string) SandboxOption {
  668. return func(sb *sandbox) {
  669. sb.config.parentUpdates = append(sb.config.parentUpdates, parentUpdate{cid: cid, name: name, ip: ip})
  670. }
  671. }
  672. // OptionResolvConfPath function returns an option setter for resolvconfpath option to
  673. // be passed to net container methods.
  674. func OptionResolvConfPath(path string) SandboxOption {
  675. return func(sb *sandbox) {
  676. sb.config.resolvConfPath = path
  677. }
  678. }
  679. // OptionOriginResolvConfPath function returns an option setter to set the path to the
  680. // origin resolv.conf file to be passed to net container methods.
  681. func OptionOriginResolvConfPath(path string) SandboxOption {
  682. return func(sb *sandbox) {
  683. sb.config.originResolvConfPath = path
  684. }
  685. }
  686. // OptionDNS function returns an option setter for dns entry option to
  687. // be passed to container Create method.
  688. func OptionDNS(dns string) SandboxOption {
  689. return func(sb *sandbox) {
  690. sb.config.dnsList = append(sb.config.dnsList, dns)
  691. }
  692. }
  693. // OptionDNSSearch function returns an option setter for dns search entry option to
  694. // be passed to container Create method.
  695. func OptionDNSSearch(search string) SandboxOption {
  696. return func(sb *sandbox) {
  697. sb.config.dnsSearchList = append(sb.config.dnsSearchList, search)
  698. }
  699. }
  700. // OptionDNSOptions function returns an option setter for dns options entry option to
  701. // be passed to container Create method.
  702. func OptionDNSOptions(options string) SandboxOption {
  703. return func(sb *sandbox) {
  704. sb.config.dnsOptionsList = append(sb.config.dnsOptionsList, options)
  705. }
  706. }
  707. // OptionUseDefaultSandbox function returns an option setter for using default sandbox to
  708. // be passed to container Create method.
  709. func OptionUseDefaultSandbox() SandboxOption {
  710. return func(sb *sandbox) {
  711. sb.config.useDefaultSandBox = true
  712. }
  713. }
  714. // OptionUseExternalKey function returns an option setter for using provided namespace
  715. // instead of creating one.
  716. func OptionUseExternalKey() SandboxOption {
  717. return func(sb *sandbox) {
  718. sb.config.useExternalKey = true
  719. }
  720. }
  721. // OptionGeneric function returns an option setter for Generic configuration
  722. // that is not managed by libNetwork but can be used by the Drivers during the call to
  723. // net container creation method. Container Labels are a good example.
  724. func OptionGeneric(generic map[string]interface{}) SandboxOption {
  725. return func(sb *sandbox) {
  726. sb.config.generic = generic
  727. }
  728. }
  729. func (eh epHeap) Len() int { return len(eh) }
  730. func (eh epHeap) Less(i, j int) bool {
  731. ci, _ := eh[i].getSandbox()
  732. cj, _ := eh[j].getSandbox()
  733. epi := eh[i]
  734. epj := eh[j]
  735. if epi.endpointInGWNetwork() {
  736. return false
  737. }
  738. if epj.endpointInGWNetwork() {
  739. return true
  740. }
  741. cip, ok := ci.epPriority[eh[i].ID()]
  742. if !ok {
  743. cip = 0
  744. }
  745. cjp, ok := cj.epPriority[eh[j].ID()]
  746. if !ok {
  747. cjp = 0
  748. }
  749. if cip == cjp {
  750. return eh[i].network.Name() < eh[j].network.Name()
  751. }
  752. return cip > cjp
  753. }
  754. func (eh epHeap) Swap(i, j int) { eh[i], eh[j] = eh[j], eh[i] }
  755. func (eh *epHeap) Push(x interface{}) {
  756. *eh = append(*eh, x.(*endpoint))
  757. }
  758. func (eh *epHeap) Pop() interface{} {
  759. old := *eh
  760. n := len(old)
  761. x := old[n-1]
  762. *eh = old[0 : n-1]
  763. return x
  764. }
  765. func createBasePath(dir string) error {
  766. return os.MkdirAll(dir, dirPerm)
  767. }
  768. func createFile(path string) error {
  769. var f *os.File
  770. dir, _ := filepath.Split(path)
  771. err := createBasePath(dir)
  772. if err != nil {
  773. return err
  774. }
  775. f, err = os.Create(path)
  776. if err == nil {
  777. f.Close()
  778. }
  779. return err
  780. }
  781. func copyFile(src, dst string) error {
  782. sBytes, err := ioutil.ReadFile(src)
  783. if err != nil {
  784. return err
  785. }
  786. return ioutil.WriteFile(dst, sBytes, filePerm)
  787. }