/
edenConfig.go
448 lines (433 loc) · 14.2 KB
/
edenConfig.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package cmd
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/lf-edge/eden/pkg/defaults"
"github.com/lf-edge/eden/pkg/models"
"github.com/lf-edge/eden/pkg/utils"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
qemuFileToSave string
qemuCpus int
qemuMemory int
qemuFirmware []string
qemuConfigPath string
eveImageFile string
qemuDTBPath string
hostFwd map[string]string
qemuSocketPath string
qemuUsbSerials int
qemuUsbTablets int
contextFile string
contextKeySet string
contextValueSet string
contextKeyGet string
contextAllGet bool
ssid string
password string
)
var configCmd = &cobra.Command{
Use: "config",
Short: "work with config",
Long: `Work with config.`,
}
func reloadConfigDetails() {
viperLoaded, err := utils.LoadConfigFile(configFile)
if err != nil {
log.Fatalf("error reading config: %s", err)
}
if viperLoaded {
qemuFirmware = viper.GetStringSlice("eve.firmware")
qemuConfigPath = utils.ResolveAbsPath(viper.GetString("eve.config-part"))
qemuDTBPath = utils.ResolveAbsPath(viper.GetString("eve.dtb-part"))
eveImageFile = utils.ResolveAbsPath(viper.GetString("eve.image-file"))
hostFwd = viper.GetStringMapString("eve.hostfwd")
qemuFileToSave = utils.ResolveAbsPath(viper.GetString("eve.qemu-config"))
devModel = viper.GetString("eve.devmodel")
eveRemote = viper.GetBool("eve.remote")
modelFile = viper.GetString("eve.devmodelfile")
if modelFile != "" {
filePath, err := filepath.Abs(modelFile)
if err != nil {
log.Fatalf("cannot get absolute path for devmodelfile (%s): %v", modelFile, err)
}
if _, err := os.Stat(filePath); err != nil {
log.Fatalf("cannot parse devmodelfile (%s): %v", modelFile, err)
}
}
}
}
var configAddCmd = &cobra.Command{
Use: "add [name]",
Long: "Generate config context for eden with defined name ('default' by default)",
Short: `Generate config context for eden with defined name ('default' by default).`,
Args: cobra.MaximumNArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
var err error
if configFile == "" {
configFile, err = utils.DefaultConfigPath()
if err != nil {
log.Fatalf("fail in DefaultConfigPath: %s", err)
}
}
if _, err := os.Stat(configFile); !os.IsNotExist(err) {
if force {
if err := os.Remove(configFile); err != nil {
log.Fatal(err)
}
} else {
log.Debugf("current config already exists: %s", configFile)
}
}
assignCobraToViper(cmd)
if _, err = os.Stat(configFile); os.IsNotExist(err) {
if err = utils.GenerateConfigFile(configFile); err != nil {
log.Fatalf("fail in generate yaml: %s", err.Error())
}
log.Infof("Config file generated: %s", configFile)
}
reloadConfigDetails()
return nil
},
Run: func(cmd *cobra.Command, args []string) {
model, err := models.GetDevModelByName(devModel)
if err != nil {
log.Fatalf("GetDevModelByName: %s", err)
}
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
currentContextName := context.Current
if len(args) > 0 {
context.Current = args[0]
} else {
context.Current = "default"
}
configFile = context.GetCurrentConfig()
if contextFile != "" {
if err := utils.CopyFile(contextFile, configFile); err != nil {
log.Fatalf("Cannot copy file: %s", err)
}
log.Infof("Context file generated: %s", contextFile)
} else {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
if err = utils.GenerateConfigFileDiff(configFile, context); err != nil {
log.Fatalf("error generate config: %s", err)
}
log.Infof("Context file generated: %s", configFile)
} else {
log.Infof("Config file already exists %s", configFile)
}
}
context.SetContext(context.Current)
reloadConfigDetails()
if eveArch != "" {
viper.Set("eve.arch", eveArch)
imageDist := fmt.Sprintf("%s-%s", context.Current, defaults.DefaultImageDist)
switch eveArch {
case "amd64":
viper.Set("eve.firmware", fmt.Sprintf("[%s %s]",
filepath.Join(imageDist, "eve", "OVMF_CODE.fd"),
filepath.Join(imageDist, "eve", "OVMF_VARS.fd")))
case "arm64":
viper.Set("eve.firmware", fmt.Sprintf("[%s]", filepath.Join(imageDist, "eve", "OVMF.fd")))
}
}
if ssid != "" {
viper.Set("eve.ssid", ssid)
}
for k, v := range model.Config() {
viper.Set(k, v)
}
if err = utils.GenerateConfigFileFromViper(); err != nil {
log.Fatalf("error writing config: %s", err)
}
context.SetContext(currentContextName)
},
}
var configListCmd = &cobra.Command{
Use: "list",
Short: "List config contexts",
PreRunE: func(cmd *cobra.Command, args []string) error {
assignCobraToViper(cmd)
_, err := utils.LoadConfigFile(configFile)
if err != nil {
return fmt.Errorf("error reading config: %s", err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
currentContext := context.Current
contexts := context.ListContexts()
for _, el := range contexts {
if el == currentContext {
fmt.Println("* " + el)
} else {
fmt.Println(el)
}
}
},
}
var configSetCmd = &cobra.Command{
Use: "set <name>",
Short: "Set current context to name",
Long: "Set current context to name \n\t will only modify key for name context if --key not empty",
Args: cobra.ExactValidArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
assignCobraToViper(cmd)
_, err := utils.LoadConfigFile(configFile)
if err != nil {
return fmt.Errorf("error reading config: %s", err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
oldContext := context.Current
if contextKeySet != "" {
defer context.SetContext(oldContext) //restore context after modifications
}
contexts := context.ListContexts()
for _, el := range contexts {
if el == args[0] {
context.SetContext(el)
if contextKeySet != "" {
_, err := utils.LoadConfigFileContext(context.GetCurrentConfig())
if err != nil {
log.Fatalf("error reading config: %s", err.Error())
}
viper.Set(contextKeySet, contextValueSet)
if err = utils.GenerateConfigFileFromViper(); err != nil {
log.Fatalf("error writing config: %s", err)
}
}
log.Infof("Current context is: %s", el)
return
}
}
log.Fatalf("context not found %s", args[0])
},
}
var configEditCmd = &cobra.Command{
Use: "edit [name]",
Short: "Edit current or context with defined name with $EDITOR",
Args: cobra.RangeArgs(0, 1),
PreRunE: func(cmd *cobra.Command, args []string) error {
assignCobraToViper(cmd)
_, err := utils.LoadConfigFile(configFile)
if err != nil {
return fmt.Errorf("error reading config: %s", err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
editor := os.Getenv("EDITOR")
if editor == "" {
log.Fatal("$EDITOR environment not set")
}
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
contextNameEdit := context.Current
if len(args) == 1 {
contextNameEdit = args[0]
}
contexts := context.ListContexts()
for _, el := range contexts {
if el == contextNameEdit {
context.Current = contextNameEdit
if err = utils.RunCommandForeground(editor, context.GetCurrentConfig()); err != nil {
log.Fatal(err)
}
return
}
}
log.Fatalf("context not found %s", contextNameEdit)
},
}
var configResetCmd = &cobra.Command{
Use: "reset [name]",
Short: "Reset current or context with defined name to defaults",
Args: cobra.RangeArgs(0, 1),
PreRunE: func(cmd *cobra.Command, args []string) error {
assignCobraToViper(cmd)
_, err := utils.LoadConfigFile(configFile)
if err != nil {
return fmt.Errorf("error reading config: %s", err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
oldContext := context.Current
defer context.SetContext(oldContext) //restore context after modifications
contextNameReset := context.Current
if len(args) == 1 {
contextNameReset = args[0]
}
contexts := context.ListContexts()
for _, el := range contexts {
if el == contextNameReset {
context.SetContext(el)
if err = os.Remove(context.GetCurrentConfig()); err != nil {
log.Fatalf("cannot delete old config file: %s", err)
}
_, err := utils.LoadConfigFile(context.GetCurrentConfig())
if err != nil {
log.Fatalf("error reading config: %s", err.Error())
}
return
}
}
log.Fatalf("context not found %s", contextNameReset)
},
}
var configGetCmd = &cobra.Command{
Use: "get [name]",
Short: "get config context for current or defined name",
Long: "Get config context for current or defined name. \n\tif --key set will show selected key only\n\tif --all set will return complete config",
Args: cobra.RangeArgs(0, 1),
PreRunE: func(cmd *cobra.Command, args []string) error {
assignCobraToViper(cmd)
_, err := utils.LoadConfigFile(configFile)
if err != nil {
return fmt.Errorf("error reading config: %s", err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
contextNameGet := ""
if len(args) == 1 {
contextNameGet = args[0]
}
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
oldContext := context.Current
defer context.SetContext(oldContext) //restore context after modifications
if contextNameGet != "" {
found := false
contexts := context.ListContexts()
for _, el := range contexts {
if el == contextNameGet {
context.SetContext(el)
found = true
break
}
}
if !found {
log.Fatalf("context not found %s", contextNameGet)
}
_, err := utils.LoadConfigFile(context.GetCurrentConfig())
if err != nil {
log.Fatalf("error reading config: %s", err.Error())
}
}
if contextKeyGet == "" && !contextAllGet {
fmt.Println(context.Current)
} else if contextKeyGet != "" {
fmt.Println(viper.Get(contextKeyGet))
} else if contextAllGet {
if err = viper.WriteConfigAs(defaults.DefaultConfigHidden); err != nil {
log.Fatal(err)
}
data, err := ioutil.ReadFile(defaults.DefaultConfigHidden)
if err != nil {
log.Fatalf("cannot read context config file %s: %s", configFile, err)
return
}
fmt.Print(string(data))
}
},
}
var configDeleteCmd = &cobra.Command{
Use: "delete <name>",
Short: "delete config context",
Args: cobra.ExactArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error {
assignCobraToViper(cmd)
_, err := utils.LoadConfigFile(configFile)
if err != nil {
return fmt.Errorf("error reading config: %s", err.Error())
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
contextNameDel := args[0]
context, err := utils.ContextLoad()
if err != nil {
log.Fatalf("Load context error: %s", err)
}
currentContext := context.Current
log.Infof("currentContext %s", currentContext)
log.Infof("contextName %s", contextNameDel)
if (contextNameDel == "" || contextNameDel == defaults.DefaultContext) && defaults.DefaultContext == currentContext {
log.Fatal("Cannot delete default context. Use 'eden clean' instead.")
}
if contextNameDel == currentContext {
contextNameDel = context.Current
context.SetContext(defaults.DefaultContext)
log.Infof("Move to %s context", defaults.DefaultContext)
}
context.Current = contextNameDel
configFile = context.GetCurrentConfig()
reloadConfigDetails()
if _, err := os.Stat(qemuFileToSave); !os.IsNotExist(err) {
if err := os.Remove(qemuFileToSave); err == nil {
log.Infof("deleted qemu config %s", qemuFileToSave)
}
}
log.Infof("currentContextFile %s", configFile)
if err := os.Remove(configFile); err != nil {
log.Fatalf("Cannot delete context %s: %s", contextNameDel, err)
}
},
}
func configInit() {
configCmd.AddCommand(configDeleteCmd)
configCmd.AddCommand(configGetCmd)
configGetCmd.Flags().StringVar(&contextKeyGet, "key", "", "will return value of key from current config context")
configGetCmd.Flags().BoolVar(&contextAllGet, "all", false, "will return config context")
configCmd.AddCommand(configSetCmd)
configSetCmd.Flags().StringVar(&contextKeySet, "key", "", "will set value of key from current config context")
configSetCmd.Flags().StringVar(&contextValueSet, "value", "", "will set value of key from current config context")
configCmd.AddCommand(configListCmd)
configCmd.AddCommand(configAddCmd)
configAddCmd.Flags().StringVar(&devModel, "devmodel", defaults.DefaultQemuModel,
fmt.Sprintf("device model (%s/%s/%s/%s)",
defaults.DefaultQemuModel, defaults.DefaultRPIModel, defaults.DefaultGCPModel, defaults.DefaultGeneralModel))
configAddCmd.Flags().StringVar(&contextFile, "file", "", "file with config to add")
configAddCmd.Flags().StringVarP(&qemuFileToSave, "qemu-config", "", defaults.DefaultQemuFileToSave, "file to save config")
configAddCmd.Flags().IntVarP(&qemuCpus, "cpus", "", defaults.DefaultCpus, "cpus")
configAddCmd.Flags().IntVarP(&qemuMemory, "memory", "", defaults.DefaultMemory, "memory (MB)")
configAddCmd.Flags().IntVarP(&qemuUsbSerials, "usbserials", "", 0, "number of USB serial adapters")
configAddCmd.Flags().IntVarP(&qemuUsbTablets, "usbtablets", "", 0, "number of USB tablet controllers")
configAddCmd.Flags().StringSliceVarP(&qemuFirmware, "eve-firmware", "", nil, "firmware path")
configAddCmd.Flags().StringVarP(&qemuConfigPath, "config-part", "", "", "path for config drive")
configAddCmd.Flags().StringVarP(&qemuDTBPath, "dtb-part", "", "", "path for device tree drive (for arm)")
configAddCmd.Flags().StringToStringVarP(&hostFwd, "eve-hostfwd", "", defaults.DefaultQemuHostFwd, "port forward map")
configAddCmd.Flags().StringVarP(&qemuSocketPath, "qmp", "", "", "use qmp socket with path")
configAddCmd.Flags().StringVar(&ssid, "ssid", "", "set ssid of wifi for rpi")
configAddCmd.Flags().StringVar(&eveArch, "arch", "", "arch of EVE (amd64 or arm64)")
configAddCmd.Flags().StringVar(&modelFile, "devmodel-file", "", "File to use for overwrite of model defaults")
configCmd.AddCommand(configResetCmd)
configCmd.AddCommand(configEditCmd)
}