github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/internal/operator/nodeagent/dep/hostname/dep.go (about) 1 package hostname 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "os/exec" 8 "strings" 9 10 "github.com/caos/orbos/internal/operator/nodeagent/dep" 11 12 "github.com/caos/orbos/internal/operator/common" 13 "github.com/caos/orbos/internal/operator/nodeagent" 14 "github.com/caos/orbos/internal/operator/nodeagent/dep/middleware" 15 ) 16 17 type Installer interface { 18 isHostname() 19 nodeagent.Installer 20 } 21 22 type hostnameDep struct { 23 } 24 25 func New() Installer { 26 return &hostnameDep{} 27 } 28 29 func (hostnameDep) isHostname() {} 30 31 func (hostnameDep) Is(other nodeagent.Installer) bool { 32 _, ok := middleware.Unwrap(other).(Installer) 33 return ok 34 } 35 36 func (hostnameDep) String() string { return "Hostname" } 37 38 func (*hostnameDep) Equals(other nodeagent.Installer) bool { 39 _, ok := other.(*hostnameDep) 40 return ok 41 } 42 43 func (*hostnameDep) InstalledFilter() []string { return nil } 44 45 func (s *hostnameDep) Current() (pkg common.Package, err error) { 46 47 buf := new(bytes.Buffer) 48 defer buf.Reset() 49 50 cmd := exec.Command("hostname") 51 cmd.Stdout = buf 52 if err := cmd.Run(); err != nil { 53 return pkg, err 54 } 55 56 pkg.Config = map[string]string{"hostname": strings.TrimSuffix(buf.String(), "\n")} 57 return pkg, nil 58 } 59 60 func (s *hostnameDep) Ensure(_ common.Package, ensure common.Package, _ bool) error { 61 62 newHostname := ensure.Config["hostname"] 63 64 if newHostname == "" { 65 return errors.New("no hostname specified") 66 } 67 68 buf := new(bytes.Buffer) 69 defer buf.Reset() 70 71 cmd := exec.Command("hostnamectl", "set-hostname", newHostname) 72 cmd.Stdout = buf 73 if err := cmd.Run(); err != nil { 74 return err 75 } 76 77 comment := "# Added by node agent developed by CAOS AG" 78 return dep.ManipulateFile("/etc/hosts", []string{comment}, []string{fmt.Sprintf("127.0.0.1\t%s %s", newHostname, comment)}, nil) 79 }