sandbox_dns_unix.go 10 KB

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