resolvconf.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package glue
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path"
  9. "strings"
  10. )
  11. var resolvConf = "/etc/resolv.conf"
  12. func SetupResolvConf(state *DockerPluginState) error {
  13. root := state.Spec.Root.Path
  14. mode := state.HostConfig.NetworkMode
  15. targetFile := path.Join(root, resolvConf)
  16. if !isZero(targetFile) {
  17. return nil
  18. }
  19. if mode.IsHost() || mode.IsNone() {
  20. return copyToExistingFile(targetFile, resolvConf)
  21. }
  22. if mode.IsContainer() {
  23. return nil
  24. }
  25. f, err := os.OpenFile(resolvConf, os.O_RDONLY, 0666)
  26. if err != nil {
  27. return err
  28. }
  29. defer f.Close()
  30. ignoreNameserver := false
  31. buf := &bytes.Buffer{}
  32. s := bufio.NewScanner(f)
  33. for s.Scan() {
  34. line := s.Text()
  35. copyLine := true
  36. switch {
  37. case strings.HasPrefix(line, "nameserver"):
  38. copyLine = false
  39. if ignoreNameserver {
  40. break
  41. }
  42. for _, dns := range state.HostConfig.DNS {
  43. ignoreNameserver = true
  44. buf.WriteString(fmt.Sprintf("nameserver %s\n", dns))
  45. }
  46. if !ignoreNameserver && strings.Contains(line, "127.0.") {
  47. ignoreNameserver = true
  48. buf.WriteString(fmt.Sprintf("nameserver 8.8.8.8\n"))
  49. buf.WriteString(fmt.Sprintf("nameserver 8.8.4.4\n"))
  50. } else {
  51. copyLine = true
  52. }
  53. case strings.HasPrefix(line, "search"):
  54. if len(state.HostConfig.DNSSearch) > 0 {
  55. buf.WriteString(fmt.Sprintf("search %s\n", strings.Join(state.HostConfig.DNSSearch, " ")))
  56. }
  57. case strings.HasPrefix(line, "options"):
  58. if len(state.HostConfig.DNSOptions) > 0 {
  59. buf.WriteString(fmt.Sprintf("options %s\n", strings.Join(state.HostConfig.DNSOptions, " ")))
  60. }
  61. }
  62. if copyLine {
  63. buf.WriteString(line)
  64. buf.WriteRune('\n')
  65. }
  66. }
  67. if err := s.Err(); err != nil {
  68. return err
  69. }
  70. return ioutil.WriteFile(targetFile, buf.Bytes(), 0666)
  71. }