Merge branch 'main' of https://github.com/svdavidson/warewulf into svdavidson-main

This commit is contained in:
Gregory Kurtzer
2020-12-22 21:28:21 -08:00
3 changed files with 55 additions and 6 deletions

View File

@@ -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)

View File

@@ -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