sandbox_dns_unix.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. // +build !windows
  2. package libnetwork
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. log "github.com/Sirupsen/logrus"
  10. "github.com/docker/libnetwork/etchosts"
  11. "github.com/docker/libnetwork/resolvconf"
  12. "github.com/docker/libnetwork/types"
  13. )
  14. const (
  15. defaultPrefix = "/var/lib/docker/network/files"
  16. dirPerm = 0755
  17. filePerm = 0644
  18. )
  19. func (sb *sandbox) startResolver() {
  20. sb.resolverOnce.Do(func() {
  21. var err error
  22. sb.resolver = NewResolver(sb)
  23. defer func() {
  24. if err != nil {
  25. sb.resolver = nil
  26. }
  27. }()
  28. err = sb.rebuildDNS()
  29. if err != nil {
  30. log.Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
  31. return
  32. }
  33. sb.resolver.SetExtServers(sb.extDNS)
  34. sb.osSbox.InvokeFunc(sb.resolver.SetupFunc())
  35. if err = sb.resolver.Start(); err != nil {
  36. log.Errorf("Resolver Setup/Start failed for container %s, %q", sb.ContainerID(), err)
  37. }
  38. })
  39. }
  40. func (sb *sandbox) setupResolutionFiles() error {
  41. if err := sb.buildHostsFile(); err != nil {
  42. return err
  43. }
  44. if err := sb.updateParentHosts(); err != nil {
  45. return err
  46. }
  47. if err := sb.setupDNS(); err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. func (sb *sandbox) buildHostsFile() error {
  53. if sb.config.hostsPath == "" {
  54. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  55. }
  56. dir, _ := filepath.Split(sb.config.hostsPath)
  57. if err := createBasePath(dir); err != nil {
  58. return err
  59. }
  60. // This is for the host mode networking
  61. if sb.config.originHostsPath != "" {
  62. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  63. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  64. }
  65. return nil
  66. }
  67. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  68. for _, extraHost := range sb.config.extraHosts {
  69. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  70. }
  71. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  72. }
  73. func (sb *sandbox) updateHostsFile(ifaceIP string) error {
  74. var mhost string
  75. if ifaceIP == "" {
  76. return nil
  77. }
  78. if sb.config.originHostsPath != "" {
  79. return nil
  80. }
  81. if sb.config.domainName != "" {
  82. mhost = fmt.Sprintf("%s.%s %s", sb.config.hostName, sb.config.domainName,
  83. sb.config.hostName)
  84. } else {
  85. mhost = sb.config.hostName
  86. }
  87. extraContent := []etchosts.Record{{Hosts: mhost, IP: ifaceIP}}
  88. sb.addHostsEntries(extraContent)
  89. return nil
  90. }
  91. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  92. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  93. log.Warnf("Failed adding service host entries to the running container: %v", err)
  94. }
  95. }
  96. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  97. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  98. log.Warnf("Failed deleting service host entries to the running container: %v", err)
  99. }
  100. }
  101. func (sb *sandbox) updateParentHosts() error {
  102. var pSb Sandbox
  103. for _, update := range sb.config.parentUpdates {
  104. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  105. if pSb == nil {
  106. continue
  107. }
  108. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  109. return err
  110. }
  111. }
  112. return nil
  113. }
  114. func (sb *sandbox) restorePath() {
  115. if sb.config.resolvConfPath == "" {
  116. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  117. }
  118. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  119. if sb.config.hostsPath == "" {
  120. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  121. }
  122. }
  123. func (sb *sandbox) setupDNS() error {
  124. var newRC *resolvconf.File
  125. if sb.config.resolvConfPath == "" {
  126. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  127. }
  128. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  129. dir, _ := filepath.Split(sb.config.resolvConfPath)
  130. if err := createBasePath(dir); err != nil {
  131. return err
  132. }
  133. // This is for the host mode networking
  134. if sb.config.originResolvConfPath != "" {
  135. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  136. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  137. }
  138. return nil
  139. }
  140. currRC, err := resolvconf.Get()
  141. if err != nil {
  142. return err
  143. }
  144. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  145. var (
  146. err error
  147. dnsList = resolvconf.GetNameservers(currRC.Content, types.IP)
  148. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  149. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  150. )
  151. if len(sb.config.dnsList) > 0 {
  152. dnsList = sb.config.dnsList
  153. }
  154. if len(sb.config.dnsSearchList) > 0 {
  155. dnsSearchList = sb.config.dnsSearchList
  156. }
  157. if len(sb.config.dnsOptionsList) > 0 {
  158. dnsOptionsList = sb.config.dnsOptionsList
  159. }
  160. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  161. if err != nil {
  162. return err
  163. }
  164. } else {
  165. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  166. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  167. return err
  168. }
  169. // No contention on container resolv.conf file at sandbox creation
  170. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  171. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  172. }
  173. }
  174. // Write hash
  175. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  176. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  177. }
  178. return nil
  179. }
  180. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  181. var (
  182. currHash string
  183. hashFile = sb.config.resolvConfHashFile
  184. )
  185. // This is for the host mode networking
  186. if sb.config.originResolvConfPath != "" {
  187. return nil
  188. }
  189. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  190. return nil
  191. }
  192. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  193. if err != nil {
  194. if !os.IsNotExist(err) {
  195. return err
  196. }
  197. } else {
  198. h, err := ioutil.ReadFile(hashFile)
  199. if err != nil {
  200. if !os.IsNotExist(err) {
  201. return err
  202. }
  203. } else {
  204. currHash = string(h)
  205. }
  206. }
  207. if currHash != "" && currHash != currRC.Hash {
  208. // Seems the user has changed the container resolv.conf since the last time
  209. // we checked so return without doing anything.
  210. //log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  211. return nil
  212. }
  213. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  214. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  215. if err != nil {
  216. return err
  217. }
  218. err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644)
  219. if err != nil {
  220. return err
  221. }
  222. // write the new hash in a temp file and rename it to make the update atomic
  223. dir := path.Dir(sb.config.resolvConfPath)
  224. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  225. if err != nil {
  226. return err
  227. }
  228. if err = ioutil.WriteFile(tmpHashFile.Name(), []byte(newRC.Hash), filePerm); err != nil {
  229. return err
  230. }
  231. return os.Rename(tmpHashFile.Name(), hashFile)
  232. }
  233. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
  234. // resolv.conf by doing the follwing
  235. // - Save the external name servers in resolv.conf in the sandbox
  236. // - Add only the embedded server's IP to container's resolv.conf
  237. // - If the embedded server needs any resolv.conf options add it to the current list
  238. func (sb *sandbox) rebuildDNS() error {
  239. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  240. if err != nil {
  241. return err
  242. }
  243. // localhost entries have already been filtered out from the list
  244. // retain only the v4 servers in sb for forwarding the DNS queries
  245. sb.extDNS = resolvconf.GetNameservers(currRC.Content, types.IPv4)
  246. var (
  247. dnsList = []string{sb.resolver.NameServer()}
  248. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  249. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  250. )
  251. // external v6 DNS servers has to be listed in resolv.conf
  252. dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...)
  253. // Resolver returns the options in the format resolv.conf expects
  254. dnsOptionsList = append(dnsOptionsList, sb.resolver.ResolverOptions()...)
  255. _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  256. return err
  257. }
  258. func createBasePath(dir string) error {
  259. return os.MkdirAll(dir, dirPerm)
  260. }
  261. func createFile(path string) error {
  262. var f *os.File
  263. dir, _ := filepath.Split(path)
  264. err := createBasePath(dir)
  265. if err != nil {
  266. return err
  267. }
  268. f, err = os.Create(path)
  269. if err == nil {
  270. f.Close()
  271. }
  272. return err
  273. }
  274. func copyFile(src, dst string) error {
  275. sBytes, err := ioutil.ReadFile(src)
  276. if err != nil {
  277. return err
  278. }
  279. return ioutil.WriteFile(dst, sBytes, filePerm)
  280. }