diff --git a/etc/hosts.tmpl b/etc/hosts.tmpl index 12f61397..1bdabf71 100644 --- a/etc/hosts.tmpl +++ b/etc/hosts.tmpl @@ -1,6 +1,4 @@ -127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 -::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 - +{{$.PrevHostFile}}# Do not edit after this line - these host entries are maintained by warewulf {{range $node := $.AllNodes}} # Entry for {{$node.Id.Get}} @@ -12,3 +10,4 @@ {{- end}} {{- end}} {{end}} + diff --git a/internal/app/wwctl/configure/hosts/main.go b/internal/app/wwctl/configure/hosts/main.go index 03c8fd0a..4cab1e2b 100644 --- a/internal/app/wwctl/configure/hosts/main.go +++ b/internal/app/wwctl/configure/hosts/main.go @@ -7,12 +7,14 @@ import ( "github.com/hpcng/warewulf/internal/pkg/wwlog" "github.com/spf13/cobra" "os" + "bytes" "text/template" ) type TemplateStruct struct { - Ipaddr string - Fqdn string + PrevHostFile string + Ipaddr string + Fqdn string AllNodes []node.NodeInfo } @@ -42,7 +44,40 @@ func CobraRunE(cmd *cobra.Command, args []string) error { os.Exit(1) } - w, err := os.OpenFile("/etc/hosts", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + replace.PrevHostFile = "" + w, err := os.Open("/etc/hosts") + if err != nil { + wwlog.Printf(wwlog.WARN, "%s\n", err) + } else { + // if /etc/hosts.ww does not exist, backup /etc/hosts to /etc/hosts.wwbackup + if ! util.IsFile("/etc/hosts.wwbackup") { + err = util.CopyFile("/etc/hosts", "/etc/hosts.wwbackup") + if err != nil { + wwlog.Printf(wwlog.ERROR, "%s\n", err) + } + } + + // read all lines before the # warewulf comment and put into PrevHostFile template variable + lines, _ := util.ReadFile("/etc/hosts") + if lines != nil { + var buffer bytes.Buffer + for _, line := range lines { + //wwlog.Printf(wwlog.INFO, "Reading line: %s\n", line) + if util.ValidString(line, "^#.*maintained by warewulf") { + break + } + buffer.WriteString(line) + buffer.WriteString("\n") + } + replace.PrevHostFile = buffer.String() + } + } + + //wwlog.Printf(wwlog.INFO, "PrevHostFile is %s\n", replace.PrevHostFile) + + w.Close() + + w, err = os.OpenFile("/etc/hosts", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { wwlog.Printf(wwlog.ERROR, "%s\n", err) os.Exit(1) diff --git a/internal/pkg/util/util.go b/internal/pkg/util/util.go index c342afd2..2366696e 100644 --- a/internal/pkg/util/util.go +++ b/internal/pkg/util/util.go @@ -11,6 +11,7 @@ import ( "path/filepath" "regexp" "time" + "bufio" // "strings" ) @@ -114,6 +115,20 @@ func IsFile(path string) bool { return false } +func ReadFile(path string) ([]string, error) { + lines := []string{} + f, err := os.Open(path) + if err != nil { + return nil, err + } + scanner := bufio.NewScanner(f) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + f.Close() + return lines, nil +} + func ValidString(pattern string, expr string) bool { if b, _ := regexp.MatchString(expr, pattern); b == true { return true