sandbox_dns_unix.go 10 KB

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