hosts.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package glue
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path"
  7. "github.com/containernetworking/cni/pkg/types"
  8. "github.com/pkg/errors"
  9. )
  10. var (
  11. hostsFile = "/etc/hosts"
  12. defaultHosts = []byte(`127.0.0.1 localhost
  13. ::1 localhost ip6-localhost ip6-loopback
  14. fe00::0 ip6-localnet
  15. ff00::0 ip6-mcastprefix
  16. ff02::1 ip6-allnodes
  17. ff02::2 ip6-allrouters
  18. `)
  19. )
  20. func SetupHosts(state *DockerPluginState, cniResult *types.Result) error {
  21. targetFile := path.Join(state.Spec.Root.Path, hostsFile)
  22. mode := state.HostConfig.NetworkMode
  23. if !isZero(targetFile) {
  24. return nil
  25. }
  26. if mode.IsHost() {
  27. return copyToExistingFile(targetFile, hostsFile)
  28. } else if mode.IsNone() {
  29. return writeHosts(targetFile, "", "")
  30. } else if mode.IsContainer() {
  31. return nil
  32. }
  33. ip := ""
  34. if cniResult != nil && cniResult.IP4 != nil {
  35. ip = cniResult.IP4.IP.String()
  36. }
  37. return writeHosts(targetFile, ip, state.Config.Hostname)
  38. }
  39. func writeHosts(file, ip, hostname string) error {
  40. f, err := os.OpenFile(file, os.O_RDWR|os.O_TRUNC, 0666)
  41. if err != nil {
  42. return errors.Wrap(err, "opening "+file)
  43. }
  44. defer f.Close()
  45. if _, err := f.Write(defaultHosts); err != nil {
  46. return err
  47. }
  48. if ip != "" && hostname != "" {
  49. _, err := io.WriteString(f, fmt.Sprintf("%s %s\n", ip, hostname))
  50. if err != nil {
  51. return err
  52. }
  53. }
  54. return nil
  55. }