-
Notifications
You must be signed in to change notification settings - Fork 19
/
hostname.go
88 lines (78 loc) · 1.96 KB
/
hostname.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package plugins
import (
"bufio"
"fmt"
"math/rand"
"strings"
"syscall"
"time"
"github.com/denisbrodbeck/machineid"
"github.com/hashicorp/go-multierror"
"github.com/mudler/yip/pkg/logger"
"github.com/mudler/yip/pkg/schema"
"github.com/mudler/yip/pkg/utils"
uuid "github.com/satori/go.uuid"
"github.com/twpayne/go-vfs/v4"
)
const localHost = "127.0.0.1"
func Hostname(l logger.Interface, s schema.Stage, fs vfs.FS, console Console) error {
var errs error
hostname := s.Hostname
if hostname == "" {
return nil
}
// Template the input string with random generated strings and UUID.
// Those can be used to e.g. generate random node names based on patterns "foo-{{.UUID}}"
rand.Seed(time.Now().UnixNano())
id, _ := machineid.ID()
myuuid, err := uuid.NewV4()
if err != nil {
return err
}
tmpl, err := utils.TemplatedString(hostname,
struct {
UUID string
Random string
MachineID string
}{
UUID: myuuid.String(),
MachineID: id,
Random: utils.RandomString(32),
},
)
if err != nil {
return err
}
if err := syscall.Sethostname([]byte(tmpl)); err != nil {
errs = multierror.Append(errs, err)
}
if err := SystemHostname(tmpl, fs); err != nil {
errs = multierror.Append(errs, err)
}
if err := UpdateHostsFile(tmpl, fs); err != nil {
errs = multierror.Append(errs, err)
}
return errs
}
func UpdateHostsFile(hostname string, fs vfs.FS) error {
hosts, err := fs.Open("/etc/hosts")
if err != nil {
return err
}
defer hosts.Close()
lines := bufio.NewScanner(hosts)
content := ""
for lines.Scan() {
line := strings.TrimSpace(lines.Text())
fields := strings.Fields(line)
if len(fields) > 0 && fields[0] == localHost {
content += fmt.Sprintf("%s localhost %s\n", localHost, hostname)
continue
}
content += line + "\n"
}
return fs.WriteFile("/etc/hosts", []byte(content), 0600)
}
func SystemHostname(hostname string, fs vfs.FS) error {
return fs.WriteFile("/etc/hostname", []byte(hostname+"\n"), 0644)
}