sandbox_dns_unix.go 10 KB

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