sandbox_dns_unix.go 12 KB

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