-
Notifications
You must be signed in to change notification settings - Fork 8
/
install.go
388 lines (325 loc) · 9.57 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
386
387
388
package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"strings"
"syscall"
"time"
events "github.com/kairos-io/kairos-sdk/bus"
"github.com/kairos-io/kairos-sdk/machine"
"github.com/kairos-io/kairos-sdk/utils"
hook "github.com/kairos-io/kairos/v2/internal/agent/hooks"
"github.com/kairos-io/kairos/v2/internal/bus"
"github.com/kairos-io/kairos/v2/internal/cmd"
"github.com/kairos-io/kairos/v2/pkg/action"
"github.com/kairos-io/kairos/v2/pkg/config"
"github.com/kairos-io/kairos/v2/pkg/config/collector"
"github.com/kairos-io/kairos/v2/pkg/elementalConfig"
v1 "github.com/kairos-io/kairos/v2/pkg/types/v1"
qr "github.com/mudler/go-nodepair/qrcode"
"github.com/mudler/go-pluggable"
"github.com/pterm/pterm"
"gopkg.in/yaml.v2"
)
func optsToArgs(options map[string]string) (res []string) {
for k, v := range options {
if k != "device" && k != "cc" && k != "reboot" && k != "poweroff" {
res = append(res, fmt.Sprintf("--%s", k))
if v != "" {
res = append(res, v)
}
}
}
return
}
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 mergeOption(cloudConfig string, r map[string]string) {
c := &config.Config{}
yaml.Unmarshal([]byte(cloudConfig), c) //nolint:errcheck
for k, v := range c.Options {
if k == "cc" {
continue
}
r[k] = v
}
}
func ManualInstall(c string, options map[string]string, strictValidations bool) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
source, err := prepareConfiguration(ctx, c)
if err != nil {
return err
}
cc, err := config.Scan(collector.Directories(source), collector.MergeBootLine, collector.StrictValidation(strictValidations))
if err != nil {
return err
}
configStr, err := cc.String()
if err != nil {
return err
}
options["cc"] = configStr
// unlike Install device is already set
// options["device"] = cc.Install.Device
mergeOption(configStr, options)
if options["device"] == "" {
options["device"] = cc.Install.Device
}
return RunInstall(options)
}
func Install(dir ...string) error {
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)
}
})
ensureDataSourceReady()
// Reads config, and if present and offline is defined,
// runs the installation
cc, err := config.Scan(collector.Directories(dir...), collector.MergeBootLine, collector.NoLogs)
if err == nil && cc.Install != nil && cc.Install.Auto {
configStr, err := cc.String()
if err != nil {
return err
}
r["cc"] = configStr
r["device"] = cc.Install.Device
mergeOption(configStr, r)
err = RunInstall(r)
if err != nil {
return err
}
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 {
return errors.New("no configuration, stopping installation")
}
// we receive a cloud config at this point
cloudConfig, exists := r["cc"]
// merge any options defined in it
mergeOption(cloudConfig, r)
// now merge cloud config from system and
// the one received from the agent-provider
ccData := map[string]interface{}{}
// make sure the config we write has at least the #cloud-config header,
// if any other was defined beforeahead
header := "#cloud-config"
if hasHeader, head := config.HasHeader(configStr, ""); hasHeader {
header = head
}
// What we receive take precedence over the one in the system. best-effort
yaml.Unmarshal([]byte(configStr), &ccData) //nolint:errcheck
if exists {
yaml.Unmarshal([]byte(cloudConfig), &ccData) //nolint:errcheck
if hasHeader, head := config.HasHeader(cloudConfig, ""); hasHeader {
header = head
}
}
out, err := yaml.Marshal(ccData)
if err != nil {
return fmt.Errorf("failed marshalling cc: %w", err)
}
r["cc"] = config.AddHeader(header, string(out))
pterm.Info.Println("Starting installation")
if err := RunInstall(r); err != nil {
return err
}
pterm.Info.Println("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(options map[string]string) error {
// TODO: run yip directly
utils.SH("elemental run-stage kairos-install.pre") //nolint:errcheck
events.RunHookScript("/usr/bin/kairos-agent.install.pre.hook") //nolint:errcheck
f, _ := os.CreateTemp("", "xxxx")
defer os.RemoveAll(f.Name())
cloudInit, ok := options["cc"]
if !ok {
fmt.Println("cloudInit must be specified among options")
os.Exit(1)
}
// TODO: Drop this and make a more straighforward way of getting the cloud-init and options?
c := &config.Config{}
yaml.Unmarshal([]byte(cloudInit), c) //nolint:errcheck
if c.Install == nil {
c.Install = &config.Install{}
}
// TODO: Im guessing this was used to try to override elemental values from env vars
// Does it make sense anymore? We can now expose the whole options of elemental directly
env := append(c.Install.Env, c.Env...)
utils.SetEnv(env)
err := os.WriteFile(f.Name(), []byte(cloudInit), os.ModePerm)
if err != nil {
fmt.Printf("could not write cloud init: %s\n", err.Error())
os.Exit(1)
}
// Load the installation Config from the system
// TODO: This uses the default mounter, logger, fs, etc...
// Make it configurable?
installConfig, err := elementalConfig.ReadConfigRun("/etc/elemental")
if err != nil {
return err
}
_, reboot := options["reboot"]
_, poweroff := options["poweroff"]
installConfig.Reboot = reboot
installConfig.PowerOff = poweroff
// Generate the installation spec
installSpec, err := elementalConfig.ReadInstallSpec(installConfig)
if err != nil {
return err
}
// Set our cloud-init to the file we just created
installSpec.CloudInit = append(installSpec.CloudInit, f.Name())
// Get the source of the installation if we are overriding it
if c.Install.Image != "" {
imgSource, err := v1.NewSrcFromURI(c.Install.Image)
if err != nil {
return err
}
installSpec.Active.Source = imgSource
}
// Set the target device
device, ok := options["device"]
if !ok {
fmt.Println("device must be specified among options")
os.Exit(1)
}
if device == "auto" {
device = detectDevice()
}
installSpec.Target = device
// Check if values are correct
err = installSpec.Sanitize()
if err != nil {
return err
}
// Create the action
installAction := action.NewInstallAction(installConfig, installSpec)
// Run it
if err := installAction.Run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
return hook.Run(*c, hook.AfterInstall...)
}
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
}