network.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package network
  2. import (
  3. "golang.org/x/net/context"
  4. "github.com/rancher/os/docker"
  5. "github.com/rancher/os/log"
  6. "io/ioutil"
  7. "github.com/docker/libnetwork/resolvconf"
  8. "github.com/rancher/os/config"
  9. "github.com/rancher/os/hostname"
  10. "github.com/rancher/os/netconf"
  11. )
  12. func Main() {
  13. log.InitLogger()
  14. cfg := config.LoadConfig()
  15. ApplyNetworkConfig(cfg)
  16. log.Infof("Restart syslog")
  17. client, err := docker.NewSystemClient()
  18. if err != nil {
  19. log.Error(err)
  20. }
  21. if err := client.ContainerRestart(context.Background(), "syslog", 10); err != nil {
  22. log.Error(err)
  23. }
  24. select {}
  25. }
  26. func ApplyNetworkConfig(cfg *config.CloudConfig) {
  27. log.Infof("Apply Network Config")
  28. userSetDNS := len(cfg.Rancher.Network.DNS.Nameservers) > 0 || len(cfg.Rancher.Network.DNS.Search) > 0
  29. if err := hostname.SetHostnameFromCloudConfig(cfg); err != nil {
  30. log.Errorf("Failed to set hostname from cloud config: %v", err)
  31. }
  32. userSetHostname := cfg.Hostname != ""
  33. dhcpSetDNS, err := netconf.ApplyNetworkConfigs(&cfg.Rancher.Network, userSetHostname, userSetDNS)
  34. if err != nil {
  35. log.Errorf("Failed to apply network configs(by netconf): %v", err)
  36. }
  37. if dhcpSetDNS {
  38. log.Infof("DNS set by DHCP")
  39. }
  40. if !userSetDNS && !dhcpSetDNS {
  41. // only write 8.8.8.8,8.8.4.4 as a last resort
  42. log.Infof("Writing default resolv.conf - no user setting, and no DHCP setting")
  43. if _, err := resolvconf.Build("/etc/resolv.conf",
  44. cfg.Rancher.Defaults.Network.DNS.Nameservers,
  45. cfg.Rancher.Defaults.Network.DNS.Search,
  46. nil); err != nil {
  47. log.Errorf("Failed to write resolv.conf (!userSetDNS and !dhcpSetDNS): %v", err)
  48. }
  49. }
  50. if userSetDNS {
  51. if _, err := resolvconf.Build("/etc/resolv.conf", cfg.Rancher.Network.DNS.Nameservers, cfg.Rancher.Network.DNS.Search, nil); err != nil {
  52. log.Errorf("Failed to write resolv.conf (userSetDNS): %v", err)
  53. } else {
  54. log.Infof("writing to /etc/resolv.conf: nameservers: %v, search: %v", cfg.Rancher.Network.DNS.Nameservers, cfg.Rancher.Network.DNS.Search)
  55. }
  56. }
  57. resolve, err := ioutil.ReadFile("/etc/resolv.conf")
  58. log.Debugf("Resolve.conf == [%s], %v", resolve, err)
  59. log.Infof("Apply Network Config SyncHostname")
  60. if err := hostname.SyncHostname(); err != nil {
  61. log.Errorf("Failed to sync hostname: %v", err)
  62. }
  63. }