sandbox_dns_unix.go 9.3 KB

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