-
Notifications
You must be signed in to change notification settings - Fork 5
/
bootentries.go
396 lines (349 loc) · 12.2 KB
/
bootentries.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
384
385
386
387
388
389
390
391
392
393
394
395
396
package action
import (
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"syscall"
cnst "github.com/kairos-io/kairos-agent/v2/pkg/constants"
"github.com/kairos-io/kairos-agent/v2/pkg/elemental"
"github.com/erikgeiser/promptkit/confirmation"
"github.com/erikgeiser/promptkit/selection"
"github.com/kairos-io/kairos-agent/v2/pkg/config"
v1 "github.com/kairos-io/kairos-agent/v2/pkg/types/v1"
"github.com/kairos-io/kairos-agent/v2/pkg/utils"
fsutils "github.com/kairos-io/kairos-agent/v2/pkg/utils/fs"
"github.com/kairos-io/kairos-agent/v2/pkg/utils/partitions"
)
// SelectBootEntry sets the default boot entry to the selected entry
// This is the entrypoint for the bootentry action with --select flag
// also other actions can call this function to set the default boot entry
func SelectBootEntry(cfg *config.Config, entry string) error {
if utils.IsUkiWithFs(cfg.Fs) {
return selectBootEntrySystemd(cfg, entry)
} else {
return selectBootEntryGrub(cfg, entry)
}
}
// ListBootEntries lists the boot entries available in the system and prompts the user to select one
// then calls the underlying SelectBootEntry function to mange the entry writing and validation
func ListBootEntries(cfg *config.Config) error {
if utils.IsUkiWithFs(cfg.Fs) {
return listBootEntriesSystemd(cfg)
} else {
return listBootEntriesGrub(cfg)
}
}
// selectBootEntryGrub sets the default boot entry to the selected entry via `grub2-editenv /oem/grubenv set next_entry=entry`
// also validates that the entry exists in our list of entries
func selectBootEntryGrub(cfg *config.Config, entry string) error {
// Validate if entry exists
entries, err := listGrubEntries(cfg)
if err != nil {
return err
}
// Check that entry exists in the entries list
err = entryInList(cfg, entry, entries)
if err != nil {
return err
}
cfg.Logger.Infof("Setting default boot entry to %s", entry)
// Set the default entry to the selected entry via `grub2-editenv /oem/grubenv set next_entry=statereset`
out, err := cfg.Runner.Run("grub2-editenv", "/oem/grubenv", "set", fmt.Sprintf("next_entry=%s", entry))
if err != nil {
cfg.Logger.Errorf("could not set default boot entry: %s\noutput: %s", err, out)
return err
}
cfg.Logger.Infof("Default boot entry set to %s", entry)
return err
}
// selectBootEntrySystemd sets the default boot entry to the selected entry via modifying the loader.conf file
// also validates that the entry exists in our list of entries
func selectBootEntrySystemd(cfg *config.Config, entry string) error {
cfg.Logger.Infof("Setting default boot entry to %s", entry)
// Get EFI partition
efiPartition, err := partitions.GetEfiPartition()
if err != nil {
return err
}
// Validate entry exists
entries, err := listSystemdEntries(cfg, efiPartition)
if err != nil {
return err
}
originalEntries := entries
// when there are only 4 entries, we can assume they are either cos (which will be replaced eventually), fallback, recovery or statereset
if len(entries) == len(cnst.UkiDefaultMenuEntries()) {
entries = cnst.UkiDefaultMenuEntries()
}
// Check that entry exists in the entries list
err = entryInList(cfg, entry, entries)
// we also accept "active" as a selection so we can migrate eventually from cos
if err != nil && !strings.HasPrefix(entry, "active") {
return err
}
// Mount it RW
err = cfg.Syscall.Mount("", efiPartition.MountPoint, "", syscall.MS_REMOUNT, "")
if err != nil {
cfg.Logger.Errorf("could not remount EFI partition: %s", err)
return err
}
// Remount it RO when finished
defer func(source string, target string, fstype string, flags uintptr, data string) {
err = cfg.Syscall.Mount(source, target, fstype, flags, data)
if err != nil {
cfg.Logger.Errorf("could not remount EFI partition as RO: %s", err)
}
}("", efiPartition.MountPoint, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, "")
systemdConf, err := utils.SystemdBootConfReader(cfg.Fs, filepath.Join(efiPartition.MountPoint, "loader/loader.conf"))
if err != nil {
cfg.Logger.Errorf("could not read loader.conf: %s", err)
return err
}
originalEntry := entry
if !reflect.DeepEqual(originalEntries, entries) {
// since we temporarily allow also active, here we need to first set entry to "cos" so it will match with the originalEntries
if strings.HasPrefix(entry, "active") {
entry = "cos"
}
for _, e := range originalEntries {
if strings.HasPrefix(e, entry) {
entry = e
}
}
}
bootName, err := bootNameToSystemdConf(entry)
if err != nil {
return err
}
// Set the default entry to the selected entry
systemdConf["default"] = bootName
err = utils.SystemdBootConfWriter(cfg.Fs, filepath.Join(efiPartition.MountPoint, "loader/loader.conf"), systemdConf)
if err != nil {
cfg.Logger.Errorf("could not write loader.conf: %s", err)
return err
}
cfg.Logger.Infof("Default boot entry set to %s", originalEntry)
return err
}
// listBootEntriesGrub lists the boot entries available in the grub config files
// and prompts the user to select one
// then calls the underlying SelectBootEntry function to mange the entry writing and validation
func listBootEntriesGrub(cfg *config.Config) error {
entries, err := listGrubEntries(cfg)
if err != nil {
return err
}
// create a selector
selector := selection.New("Select Next Boot Entry", entries)
selector.Filter = nil // Remove the filter
selector.ResultTemplate = `` // Do not print the result as we are asking for confirmation afterwards
selected, _ := selector.RunPrompt()
c := confirmation.New("Are you sure you want to change the boot entry to "+selected, confirmation.Yes)
c.ResultTemplate = ``
confirm, err := c.RunPrompt()
if confirm {
return SelectBootEntry(cfg, selected)
}
return err
}
func systemdConfToBootName(conf string) (string, error) {
if !strings.HasSuffix(conf, ".conf") {
return "", fmt.Errorf("unknown systemd-boot conf: %s", conf)
}
fileName := strings.TrimSuffix(conf, ".conf")
if strings.HasPrefix(fileName, "active") {
bootName := "cos"
confName := strings.TrimPrefix(fileName, "active")
if confName != "" {
bootName = bootName + " " + strings.Trim(confName, "_")
}
return bootName, nil
}
if strings.HasPrefix(fileName, "passive") {
bootName := "fallback"
confName := strings.TrimPrefix(fileName, "passive")
if confName != "" {
bootName = bootName + " " + strings.Trim(confName, "_")
}
return bootName, nil
}
if strings.HasPrefix(conf, "recovery") {
bootName := "recovery"
confName := strings.TrimPrefix(fileName, "recovery")
if confName != "" {
bootName = bootName + " " + strings.Trim(confName, "_")
}
return bootName, nil
}
if strings.HasPrefix(conf, "statereset") {
bootName := "statereset"
confName := strings.TrimPrefix(fileName, "statereset")
if confName != "" {
bootName = bootName + " " + strings.Trim(confName, "_")
}
return bootName, nil
}
return "", fmt.Errorf("unknown systemd-boot conf: %s", conf)
}
func bootNameToSystemdConf(name string) (string, error) {
differenciator := ""
if strings.HasPrefix(name, "cos") {
if name != "cos" {
differenciator = "_" + strings.TrimPrefix(name, "cos ")
}
return "active" + differenciator + ".conf", nil
}
if strings.HasPrefix(name, "active") {
if name != "active" {
differenciator = "_" + strings.TrimPrefix(name, "active ")
}
return "active" + differenciator + ".conf", nil
}
if strings.HasPrefix(name, "fallback") {
if name != "fallback" {
differenciator = "_" + strings.TrimPrefix(name, "fallback ")
}
return "passive" + differenciator + ".conf", nil
}
if strings.HasPrefix(name, "recovery") {
if name != "recovery" {
differenciator = "_" + strings.TrimPrefix(name, "recovery ")
}
return "recovery" + differenciator + ".conf", nil
}
if strings.HasPrefix(name, "statereset") {
if name != "statereset" {
differenciator = "_" + strings.TrimPrefix(name, "statereset ")
}
return "statereset" + differenciator + ".conf", nil
}
return "", fmt.Errorf("unknown boot name: %s", name)
}
// listBootEntriesSystemd lists the boot entries available in the systemd-boot config files
// and prompts the user to select one
// then calls the underlying SelectBootEntry function to mange the entry writing and validation
func listBootEntriesSystemd(cfg *config.Config) error {
var err error
e := elemental.NewElemental(cfg)
cleanup := utils.NewCleanStack()
defer func() { err = cleanup.Cleanup(err) }()
// Get EFI partition
efiPartition, err := partitions.GetEfiPartition()
if err != nil {
return err
}
// mount if not mounted
if mounted, err := utils.IsMounted(cfg, efiPartition); !mounted && err == nil {
if efiPartition.MountPoint == "" {
efiPartition.MountPoint = cnst.EfiDir
}
err = e.MountPartition(efiPartition)
if err != nil {
cfg.Logger.Errorf("could not mount EFI partition: %s", err)
return err
}
cleanup.Push(func() error { return e.UnmountPartition(efiPartition) })
}
// Get default entry from loader.conf
loaderConf, err := utils.SystemdBootConfReader(cfg.Fs, filepath.Join(efiPartition.MountPoint, "loader/loader.conf"))
if err != nil {
return err
}
entries, err := listSystemdEntries(cfg, efiPartition)
if err != nil {
return err
}
currentlySelected, err := systemdConfToBootName(loaderConf["default"])
// create a selector
selector := selection.New(fmt.Sprintf("Select Boot Entry (current entry: %s)", currentlySelected), entries)
selector.Filter = nil // Remove the filter
selector.ResultTemplate = `` // Do not print the result as we are asking for confirmation afterwards
selected, _ := selector.RunPrompt()
c := confirmation.New("Are you sure you want to change the boot entry to "+selected, confirmation.Yes)
c.ResultTemplate = ``
confirm, err := c.RunPrompt()
if err != nil {
return err
}
if confirm {
return SelectBootEntry(cfg, selected)
}
return err
}
// ListSystemdEntries reads the systemd-boot entries and returns a list of entries found
func listSystemdEntries(cfg *config.Config, efiPartition *v1.Partition) ([]string, error) {
var entries []string
err := fsutils.WalkDirFs(cfg.Fs, filepath.Join(efiPartition.MountPoint, "loader/entries/"), func(path string, info os.DirEntry, err error) error {
cfg.Logger.Debugf("Checking file %s", path)
if info == nil {
return nil
}
if info.IsDir() {
return nil
}
if filepath.Ext(info.Name()) != ".conf" {
return nil
}
entry, err := systemdConfToBootName(info.Name())
if err != nil {
return err
}
entries = append(entries, entry)
return nil
})
return entries, err
}
// listGrubEntries reads the grub config files and returns a list of entries found
func listGrubEntries(cfg *config.Config) ([]string, error) {
// Read grub config from 4 places
// /etc/cos/grub.cfg
// /run/initramfs/cos-state/grub/grub.cfg
// /run/initramfs/cos-state/grub2/grub.cfg
// /etc/kairos/branding/grubmenu.cfg
// And grep the entries by checking the --id\s([A-z0-9]*)\s{ pattern
// TODO: Check how to run this from livecd as it requires mounting state and grub?
var entries []string
for _, file := range []string{"/etc/cos/grub.cfg", "/run/initramfs/cos-state/grub/grub.cfg", "/etc/kairos/branding/grubmenu.cfg", "/run/initramfs/cos-state/grub2/grub.cfg"} {
f, err := cfg.Fs.ReadFile(file)
if err != nil {
cfg.Logger.Errorf("could not read file %s: %s", file, err)
continue
}
re, _ := regexp.Compile(`--id\s([A-z0-9]*)\s{`)
matches := re.FindAllStringSubmatch(string(f), -1)
for _, match := range matches {
entries = append(entries, match[1])
}
}
entries = uniqueStringArray(entries)
return entries, nil
}
// I lost count on how many places I had to implement this function
// Is that difficult to provide a simple []string.Unique() method from the standard lib????
// Or at least a Set type?
func uniqueStringArray(arr []string) []string {
unique := make(map[string]bool)
var result []string
for _, s := range arr {
if !unique[s] {
unique[s] = true
result = append(result, s)
}
}
return result
}
// Another one. Seriously there is nothing to check if something is in a list?
func entryInList(cfg *config.Config, entry string, list []string) error {
// Check that entry exists in the entries list
for _, e := range list {
if e == entry {
return nil
}
}
cfg.Logger.Errorf("entry %s does not exist", entry)
cfg.Logger.Debugf("entries: %v", list)
return fmt.Errorf("entry %s does not exist", entry)
}