sandbox_dns_unix.go 8.7 KB

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