hostname.go 997 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package hostname
  2. import (
  3. "bufio"
  4. "io/ioutil"
  5. "os"
  6. "strings"
  7. "syscall"
  8. "github.com/rancher/os/config"
  9. )
  10. func SetHostnameFromCloudConfig(cc *config.CloudConfig) error {
  11. var hostname string
  12. if cc.Hostname == "" {
  13. hostname = cc.Rancher.Defaults.Hostname
  14. } else {
  15. hostname = cc.Hostname
  16. }
  17. if hostname == "" {
  18. return nil
  19. }
  20. // set hostname
  21. return syscall.Sethostname([]byte(hostname))
  22. }
  23. func SyncHostname() error {
  24. hostname, err := os.Hostname()
  25. if err != nil {
  26. return err
  27. }
  28. if hostname == "" {
  29. return nil
  30. }
  31. hosts, err := os.Open("/etc/hosts")
  32. defer hosts.Close()
  33. if err != nil {
  34. return err
  35. }
  36. lines := bufio.NewScanner(hosts)
  37. hostsContent := ""
  38. for lines.Scan() {
  39. line := strings.TrimSpace(lines.Text())
  40. fields := strings.Fields(line)
  41. if len(fields) > 0 && fields[0] == "127.0.1.1" {
  42. hostsContent += "127.0.1.1 " + hostname + "\n"
  43. continue
  44. }
  45. hostsContent += line + "\n"
  46. }
  47. return ioutil.WriteFile("/etc/hosts", []byte(hostsContent), 0600)
  48. }