sandbox_dns_unix.go 11 KB

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