sandbox.go 25 KB

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