-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathinstall.go
385 lines (322 loc) · 10.2 KB
/
install.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
package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"strings"
"syscall"
"time"
"github.com/kairos-io/kairos-agent/v2/pkg/uki"
internalutils "github.com/kairos-io/kairos-agent/v2/pkg/utils"
fsutils "github.com/kairos-io/kairos-agent/v2/pkg/utils/fs"
"github.com/sanity-io/litter"
"github.com/kairos-io/kairos-agent/v2/internal/bus"
"github.com/kairos-io/kairos-agent/v2/internal/cmd"
"github.com/kairos-io/kairos-agent/v2/pkg/action"
"github.com/kairos-io/kairos-agent/v2/pkg/config"
events "github.com/kairos-io/kairos-sdk/bus"
"github.com/kairos-io/kairos-sdk/collector"
"github.com/kairos-io/kairos-sdk/machine"
"github.com/kairos-io/kairos-sdk/utils"
qr "github.com/mudler/go-nodepair/qrcode"
"github.com/mudler/go-pluggable"
"github.com/pterm/pterm"
"gopkg.in/yaml.v2"
)
func displayInfo(agentConfig *Config) {
fmt.Println("--------------------------")
fmt.Println("No providers found, dropping to a shell. \n -- For instructions on how to install manually, see: https://kairos.io/docs/installation/manual/")
if !agentConfig.WebUI.Disable {
if !agentConfig.WebUI.HasAddress() {
ips := machine.LocalIPs()
if len(ips) > 0 {
fmt.Print("WebUI installer running at : ")
for _, ip := range ips {
fmt.Printf("%s%s ", ip, config.DefaultWebUIListenAddress)
}
fmt.Print("\n")
}
} else {
fmt.Printf("WebUI installer running at : %s\n", agentConfig.WebUI.ListenAddress)
}
ifaces := machine.Interfaces()
fmt.Printf("Network Interfaces: %s\n", strings.Join(ifaces, " "))
}
}
func ManualInstall(c, sourceImgURL, device string, reboot, poweroff, strictValidations bool) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
configSource, err := prepareConfiguration(ctx, c)
if err != nil {
return err
}
cliConf := generateInstallConfForCLIArgs(sourceImgURL)
cliConfManualArgs := generateInstallConfForManualCLIArgs(device, reboot, poweroff)
cc, err := config.Scan(collector.Directories(configSource),
collector.Readers(strings.NewReader(cliConf), strings.NewReader(cliConfManualArgs)),
collector.MergeBootLine,
collector.StrictValidation(strictValidations), collector.NoLogs)
if err != nil {
return err
}
return RunInstall(cc)
}
func Install(sourceImgURL string, dir ...string) error {
var cc *config.Config
var err error
bus.Manager.Initialize()
utils.OnSignal(func() {
svc, err := machine.Getty(1)
if err == nil {
svc.Start() //nolint:errcheck
}
}, syscall.SIGINT, syscall.SIGTERM)
tk := ""
r := map[string]string{}
bus.Manager.Response(events.EventChallenge, func(p *pluggable.Plugin, r *pluggable.EventResponse) {
tk = r.Data
})
bus.Manager.Response(events.EventInstall, func(p *pluggable.Plugin, resp *pluggable.EventResponse) {
err := json.Unmarshal([]byte(resp.Data), &r)
if err != nil {
fmt.Println(err)
}
cloudConfig, exists := r["cc"]
if exists {
// Re-read the full config and add the config coming from the event
cc, _ = config.Scan(collector.Directories(dir...), collector.Readers(strings.NewReader(cloudConfig)), collector.MergeBootLine, collector.NoLogs)
}
})
ensureDataSourceReady()
cliConf := generateInstallConfForCLIArgs(sourceImgURL)
// Reads config, and if present and offline is defined, runs the installation
cc, err = config.Scan(collector.Directories(dir...),
collector.Readers(strings.NewReader(cliConf)),
collector.MergeBootLine)
if err == nil && cc.Install != nil && cc.Install.Auto {
err = RunInstall(cc)
if err != nil {
return err
}
if cc.Install.Reboot == false && cc.Install.Poweroff == false {
pterm.DefaultInteractiveContinue.Show("Installation completed, press enter to go back to the shell.")
svc, err := machine.Getty(1)
if err == nil {
svc.Start() //nolint:errcheck
}
}
return nil
}
if err != nil {
fmt.Printf("- config not found in the system: %s", err.Error())
}
agentConfig, err := LoadConfig()
if err != nil {
return err
}
// try to clear screen
cmd.ClearScreen()
cmd.PrintBranding(DefaultBanner)
// If there are no providers registered, we enter a shell for manual installation
// and print information about the webUI
if !bus.Manager.HasRegisteredPlugins() {
displayInfo(agentConfig)
return utils.Shell().Run()
}
configStr, err := cc.String()
if err != nil {
return err
}
_, err = bus.Manager.Publish(events.EventChallenge, events.EventPayload{Config: configStr})
if err != nil {
return err
}
cmd.PrintText(agentConfig.Branding.Install, "Installation")
if !agentConfig.Fast {
time.Sleep(5 * time.Second)
}
if tk != "" {
qr.Print(tk)
}
if _, err := bus.Manager.Publish(events.EventInstall, events.InstallPayload{Token: tk, Config: configStr}); err != nil {
return err
}
if len(r) == 0 {
// This means there is no config in the system AND no config was obtained from events
return errors.New("no configuration, stopping installation")
}
pterm.Info.Println("Starting installation")
cc.Logger.Debugf("Runinstall with cc: %s\n", litter.Sdump(cc))
if err := RunInstall(cc); err != nil {
return err
}
if cc.Install.Reboot {
pterm.Info.Println("Installation completed, rebooting in 5 seconds.")
}
if cc.Install.Poweroff {
pterm.Info.Println("Installation completed, powering in 5 seconds.")
}
// If neither reboot and poweroff are enabled let the user insert enter to go back to a new shell
// This is helpful to see the installation messages instead of just cleaning the screen with a new tty
if cc.Install.Reboot == false && cc.Install.Poweroff == false {
pterm.DefaultInteractiveContinue.Show("Installation completed, press enter to go back to the shell.")
utils.Prompt("") //nolint:errcheck
// give tty1 back
svc, err := machine.Getty(1)
if err == nil {
svc.Start() //nolint: errcheck
}
}
return nil
}
func RunInstall(c *config.Config) error {
utils.SetEnv(c.Env)
utils.SetEnv(c.Install.Env)
if c.Install.Device == "" || c.Install.Device == "auto" {
c.Install.Device = detectDevice()
}
// UKI path. Check if we are on UKI AND if we are running off a cd, otherwise it makes no sense to run the install
// From the installed system
if internalutils.IsUkiWithFs(c.Fs) {
c.Logger.Debugf("UKI mode: %s\n", internalutils.UkiBootMode())
if internalutils.UkiBootMode() == internalutils.UkiRemovableMedia {
return runInstallUki(c)
}
c.Logger.Warnf("UKI boot mode is not removable media, skipping install")
return nil
} else { // Non-uki path
return runInstall(c)
}
}
// runInstallUki runs the UKI path install
func runInstallUki(c *config.Config) error {
// Load the spec from the config
installSpec, err := config.ReadUkiInstallSpecFromConfig(c)
if err != nil {
return err
}
// Set our cloud-init to the file we just created
f, err := dumpCCStringToFile(c)
if err == nil {
installSpec.CloudInit = append(installSpec.CloudInit, f)
}
// Check if values are correct
err = installSpec.Sanitize()
if err != nil {
return err
}
// Add user's cloud-config (to run user defined "before-install" stages)
c.CloudInitPaths = append(c.CloudInitPaths, installSpec.CloudInit...)
installAction := uki.NewInstallAction(c, installSpec)
return installAction.Run()
}
// runInstall runs the non-UKI path install
func runInstall(c *config.Config) error {
// Load the installation spec from the Config
installSpec, err := config.ReadInstallSpecFromConfig(c)
if err != nil {
return err
}
// TODO: This should not be neccessary
installSpec.NoFormat = c.Install.NoFormat
// Set our cloud-init to the file we just created
f, err := dumpCCStringToFile(c)
if err == nil {
installSpec.CloudInit = append(installSpec.CloudInit, f)
}
// Check if values are correct
err = installSpec.Sanitize()
if err != nil {
return err
}
// Add user's cloud-config (to run user defined "before-install" stages)
c.CloudInitPaths = append(c.CloudInitPaths, installSpec.CloudInit...)
installAction := action.NewInstallAction(c, installSpec)
return installAction.Run()
}
// dumpCCStringToFile dumps the cloud-init string to a file and returns the path of the file
func dumpCCStringToFile(c *config.Config) (string, error) {
f, err := fsutils.TempFile(c.Fs, "", "kairos-install-config-xxx.yaml")
if err != nil {
c.Logger.Error("Error creating temporary file for install config: %s\n", err.Error())
return "", err
}
defer func(f *os.File) {
_ = f.Close()
}(f)
ccstring, err := c.String()
if err != nil {
return "", err
}
err = os.WriteFile(f.Name(), []byte(ccstring), os.ModePerm)
if err != nil {
fmt.Printf("could not write cloud init to %s: %s\n", f.Name(), err.Error())
return "", err
}
return f.Name(), nil
}
func ensureDataSourceReady() {
timeout := time.NewTimer(5 * time.Minute)
ticker := time.NewTicker(500 * time.Millisecond)
defer timeout.Stop()
defer ticker.Stop()
for {
select {
case <-timeout.C:
fmt.Println("userdata configuration failed to load after 5m, ignoring.")
return
case <-ticker.C:
if _, err := os.Stat("/run/.userdata_load"); os.IsNotExist(err) {
return
}
fmt.Println("userdata configuration has not yet completed. (waiting for /run/.userdata_load to be deleted)")
}
}
}
func prepareConfiguration(ctx context.Context, source string) (string, error) {
// if the source is not an url it is already a configuration path
if u, err := url.Parse(source); err != nil || u.Scheme == "" {
return source, nil
}
// create a configuration file with the source referenced
f, err := os.CreateTemp(os.TempDir(), "kairos-install-*.yaml")
if err != nil {
return "", err
}
// defer cleanup until after parent is done
go func() {
<-ctx.Done()
_ = os.RemoveAll(f.Name())
}()
cfg := config.Config{
ConfigURL: source,
}
if err = yaml.NewEncoder(f).Encode(cfg); err != nil {
return "", err
}
return f.Name(), nil
}
func generateInstallConfForCLIArgs(sourceImageURL string) string {
if sourceImageURL == "" {
return ""
}
return fmt.Sprintf(`install:
source: %s
`, sourceImageURL)
}
// generateInstallConfForManualCLIArgs creates a kairos configuration for flags passed via manual install
func generateInstallConfForManualCLIArgs(device string, reboot, poweroff bool) string {
cfg := fmt.Sprintf(`install:
reboot: %t
poweroff: %t
`, reboot, poweroff)
if device != "" {
cfg += fmt.Sprintf(`
device: %s
`, device)
}
return cfg
}