sandbox.go 25 KB

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