-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.go
383 lines (331 loc) · 9.51 KB
/
utils.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package utils
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"image"
"net"
"os"
"os/exec"
"os/signal"
"runtime"
"strings"
"gopkg.in/yaml.v3"
"github.com/denisbrodbeck/machineid"
"github.com/joho/godotenv"
"github.com/pterm/pterm"
"github.com/qeesung/image2ascii/convert"
)
const (
systemd = "systemd"
openrc = "openrc"
unknown = "unknown"
)
type KeyNotFoundErr struct {
Err error
}
func (err KeyNotFoundErr) Error() string {
return err.Err.Error()
}
func SH(c string) (string, error) {
cmd := exec.Command("/bin/sh", "-c", c)
cmd.Env = os.Environ()
o, err := cmd.CombinedOutput()
return string(o), err
}
func SHInDir(c, dir string, envs ...string) (string, error) {
cmd := exec.Command("/bin/sh", "-c", c)
cmd.Env = append(os.Environ(), envs...)
cmd.Dir = dir
o, err := cmd.CombinedOutput()
return string(o), err
}
func Exists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
// UUID TODO: move this into a machine submodule
func UUID() string {
if os.Getenv("UUID") != "" {
return os.Getenv("UUID")
}
id, _ := machineid.ID()
hostname, _ := os.Hostname()
return fmt.Sprintf("%s-%s", id, hostname)
}
// OSRelease finds the value of the specified key in the /etc/os-release file
// or, if a second argument is passed, on the file specified by the second argument.
// (optionally file argument is there for testing reasons).
func OSRelease(key string, file ...string) (string, error) {
var osReleaseFile string
if len(file) > 1 {
return "", errors.New("too many arguments passed")
}
if len(file) > 0 {
osReleaseFile = file[0]
} else {
osReleaseFile = "/etc/os-release"
}
release, err := godotenv.Read(osReleaseFile)
if err != nil {
return "", err
}
kairosKey := "KAIROS_" + key
v, exists := release[kairosKey]
if !exists {
// We try with the old naming without the prefix in case the key wasn't found
v, exists = release[key]
if !exists {
return "", KeyNotFoundErr{Err: fmt.Errorf("%s key not found", kairosKey)}
}
}
return v, nil
}
func FindCommand(def string, options []string) string {
for _, p := range options {
path, err := exec.LookPath(p)
if err == nil {
return path
}
}
// Otherwise return default
return def
}
func K3sBin() string {
for _, p := range []string{"/usr/bin/k3s", "/usr/local/bin/k3s"} {
if _, err := os.Stat(p); err == nil {
return p
}
}
return ""
}
func WriteEnv(envFile string, config map[string]string) error {
content, _ := os.ReadFile(envFile)
env, _ := godotenv.Unmarshal(string(content))
for key, val := range config {
env[key] = val
}
return godotenv.Write(env, envFile)
}
func Flavor() string {
v, err := OSRelease("FLAVOR")
if err != nil {
return ""
}
return v
}
// GetInit Return the init system used by the OS
func GetInit() string {
for _, file := range []string{"/run/systemd/system", "/sbin/systemctl", "/usr/bin/systemctl", "/usr/sbin/systemctl", "/usr/bin/systemctl"} {
_, err := os.Stat(file)
// Found systemd
if err == nil {
return systemd
}
}
for _, file := range []string{"/sbin/openrc", "/usr/sbin/openrc", "/bin/openrc", "/usr/bin/openrc"} {
_, err := os.Stat(file)
// Found openrc
if err == nil {
return openrc
}
}
return unknown
}
func Name() string {
v, err := OSRelease("NAME")
if err != nil {
return ""
}
return strings.ReplaceAll(v, "kairos-", "")
}
func IsOpenRCBased() bool {
return GetInit() == openrc
}
func ShellSTDIN(s, c string) (string, error) {
cmd := exec.Command("/bin/sh", "-c", c)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = bytes.NewBuffer([]byte(s))
o, err := cmd.CombinedOutput()
return string(o), err
}
func SetEnv(env []string) {
for _, e := range env {
pair := strings.SplitN(e, "=", 2)
if len(pair) >= 2 {
os.Setenv(pair[0], pair[1])
}
}
}
func OnSignal(fn func(), sig ...os.Signal) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, sig...)
go func() {
<-sigs
fn()
}()
}
func Shell() *exec.Cmd {
cmd := exec.Command("/bin/sh")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd
}
func Prompt(t string) (string, error) {
if t != "" {
pterm.Info.Println(t)
}
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(answer), nil
}
func PrintBanner(d []byte) {
img, _, _ := image.Decode(bytes.NewReader(d))
convertOptions := convert.DefaultOptions
convertOptions.FixedWidth = 100
convertOptions.FixedHeight = 40
// Create the image converter
converter := convert.NewImageConverter()
fmt.Print(converter.Image2ASCIIString(img, &convertOptions))
}
func Reboot() {
pterm.Info.Println("Rebooting node")
SH("reboot") //nolint:errcheck
}
func PowerOFF() {
pterm.Info.Println("Shutdown node")
if IsOpenRCBased() {
SH("poweroff") //nolint:errcheck
} else {
SH("shutdown") //nolint:errcheck
}
}
func Version() string {
v, err := OSRelease("VERSION")
if err != nil {
return ""
}
v = strings.ReplaceAll(v, "+k3s1-Kairos", "-")
v = strings.ReplaceAll(v, "+k3s-Kairos", "-")
return strings.ReplaceAll(v, "Kairos", "")
}
func ListToOutput(rels []string, output string) []string {
switch strings.ToLower(output) {
case "yaml":
d, _ := yaml.Marshal(rels)
return []string{string(d)}
case "json":
d, _ := json.Marshal(rels)
return []string{string(d)}
default:
return rels
}
}
func GetInterfaceIP(in string) string {
ifaces, err := net.Interfaces()
if err != nil {
fmt.Println("failed getting system interfaces")
return ""
}
for _, i := range ifaces {
if i.Name == in {
addrs, _ := i.Addrs()
// handle err
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip != nil {
return ip.String()
}
}
}
}
return ""
}
// GetCurrentPlatform returns the current platform in docker style `linux/amd64` for use with image utils
func GetCurrentPlatform() string {
return fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
}
// GetEfiGrubFiles Return possible paths for the grub.efi
// Used in enki and agent
func GetEfiGrubFiles(arch string) []string {
var modNames []string
switch arch {
case "arm64":
modNames = append(modNames, "/usr/share/efi/aarch64/grub.efi") // suse
modNames = append(modNames, "/usr/lib/grub/arm64-efi-signed/grubaa64.efi.signed") // ubuntu + debian
modNames = append(modNames, "/boot/efi/EFI/fedora/grubaa64.efi") // fedora
modNames = append(modNames, "/boot/efi/EFI/rocky/grubaa64.efi") // rocky
modNames = append(modNames, "/boot/efi/EFI/redhat/grubaa64.efi") // redhat
modNames = append(modNames, "/boot/efi/EFI/almalinux/grubaa64.efi") // almalinux
default:
modNames = append(modNames, "/usr/share/efi/x86_64/grub.efi") // suse
modNames = append(modNames, "/usr/lib/grub/x86_64-efi-signed/grubx64.efi.signed") // ubuntu + debian
modNames = append(modNames, "/boot/efi/EFI/fedora/grubx64.efi") // fedora
modNames = append(modNames, "/boot/efi/EFI/rocky/grubx64.efi") // rocky
modNames = append(modNames, "/boot/efi/EFI/redhat/grubx64.efi") // redhat
modNames = append(modNames, "/boot/efi/EFI/almalinux/grubx64.efi") // almalinux
}
return modNames
}
// GetEfiShimFiles Return possible paths for the shim.efi
// Used in enki and agent
func GetEfiShimFiles(arch string) []string {
var modNames []string
switch arch {
case "arm64":
modNames = append(modNames, "/usr/share/efi/aarch64/shim.efi") // suse
modNames = append(modNames, "/usr/lib/shim/shimaa64.efi.dualsigned") // ubuntu
modNames = append(modNames, "/usr/lib/shim/shimaa64.efi.signed.latest") // ubuntu
modNames = append(modNames, "/usr/lib/shim/shimaa64.efi.signed") // debian, maybe ubuntu but its a link so it can be broken
modNames = append(modNames, "/boot/efi/EFI/fedora/shim.efi") // fedora
modNames = append(modNames, "/boot/efi/EFI/rocky/shim.efi") // rocky
modNames = append(modNames, "/boot/efi/EFI/redhat/shim.efi") // redhat
modNames = append(modNames, "/boot/efi/EFI/almalinux/shim.efi") // almalinux
default:
modNames = append(modNames, "/usr/share/efi/x86_64/shim.efi") // suse
modNames = append(modNames, "/usr/lib/shim/shimx64.efi.dualsigned") // ubuntu
modNames = append(modNames, "/usr/lib/shim/shimx64.efi.signed.latest") // ubuntu
modNames = append(modNames, "/usr/lib/shim/shimx64.efi.signed") // debian, maybe ubuntu but its a link so it can be broken
modNames = append(modNames, "/boot/efi/EFI/fedora/shim.efi") // fedora
modNames = append(modNames, "/boot/efi/EFI/rocky/shim.efi") // rocky
modNames = append(modNames, "/boot/efi/EFI/redhat/shim.efi") // redhat
modNames = append(modNames, "/boot/efi/EFI/almalinux/shim.efi") // almalinux
}
return modNames
}
// SystemdBootConfReader reads a systemd-boot conf file and returns a map with the key/value pairs
func SystemdBootConfReader(filePath string) (map[string]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
result := make(map[string]string)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, " ", 2)
if len(parts) == 2 {
result[parts[0]] = parts[1]
}
if len(parts) == 1 {
result[parts[0]] = ""
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return result, nil
}