/
machine.go
1395 lines (1189 loc) · 45.3 KB
/
machine.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"encoding/base64"
"log"
"os"
"os/exec"
"strings"
"time"
"fmt"
"net/url"
"slices"
"github.com/metal-stack/metal-go/api/client/firmware"
"github.com/metal-stack/metal-go/api/client/machine"
"github.com/metal-stack/metal-go/api/models"
"github.com/metal-stack/metal-lib/pkg/genericcli"
"github.com/metal-stack/metal-lib/pkg/genericcli/printers"
"github.com/metal-stack/metal-lib/pkg/pointer"
"github.com/metal-stack/metalctl/cmd/sorters"
"github.com/metal-stack/metalctl/pkg/api"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
// Port open on our control-plane to connect via ssh to get machine console access.
bmcConsolePort = 5222
forceFlag = "yes-i-really-mean-it"
)
type machineCmd struct {
*config
}
func (c *machineCmd) listCmdFlags(cmd *cobra.Command, lastEventErrorThresholdDefault time.Duration) {
listFlagCompletions := []struct {
flagName string
f func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)
}{
{flagName: "partition", f: c.comp.PartitionListCompletion},
{flagName: "size", f: c.comp.SizeListCompletion},
{flagName: "project", f: c.comp.ProjectListCompletion},
{flagName: "id", f: c.comp.MachineListCompletion},
{flagName: "image", f: c.comp.ImageListCompletion},
{flagName: "state", f: cobra.FixedCompletions([]string{
// empty does not work:
// models.V1FirewallFindRequestStateValueEmpty,
models.V1FirewallFindRequestStateValueLOCKED,
models.V1MachineFindRequestStateValueRESERVED,
}, cobra.ShellCompDirectiveDefault)},
}
cmd.Flags().String("id", "", "ID to filter [optional]")
cmd.Flags().String("partition", "", "partition to filter [optional]")
cmd.Flags().String("size", "", "size to filter [optional]")
cmd.Flags().String("rack", "", "rack to filter [optional]")
cmd.Flags().String("state", "", "state to filter [optional]")
cmd.Flags().String("name", "", "allocation name to filter [optional]")
cmd.Flags().String("project", "", "allocation project to filter [optional]")
cmd.Flags().String("image", "", "allocation image to filter [optional]")
cmd.Flags().String("hostname", "", "allocation hostname to filter [optional]")
cmd.Flags().String("mac", "", "mac to filter [optional]")
cmd.Flags().StringSlice("tags", []string{}, "tags to filter, use it like: --tags \"tag1,tag2\" or --tags \"tag3\".")
cmd.Flags().Duration("last-event-error-threshold", lastEventErrorThresholdDefault, "the duration up to how long in the past a machine last event error will be counted as an issue [optional]")
for _, c := range listFlagCompletions {
c := c
must(cmd.RegisterFlagCompletionFunc(c.flagName, c.f))
}
cmd.Long = cmd.Short + "\n" + api.EmojiHelpText()
}
func newMachineCmd(c *config) *cobra.Command {
w := machineCmd{
config: c,
}
cmdsConfig := &genericcli.CmdsConfig[*models.V1MachineAllocateRequest, *models.V1MachineUpdateRequest, *models.V1MachineResponse]{
BinaryName: binaryName,
GenericCLI: genericcli.NewGenericCLI[*models.V1MachineAllocateRequest, *models.V1MachineUpdateRequest, *models.V1MachineResponse](w).WithFS(c.fs),
Singular: "machine",
Plural: "machines",
Description: "a machine is a bare metal server provisioned through metal-stack that is intended to run user workload.",
Aliases: []string{"ms"},
CreateRequestFromCLI: w.createRequestFromCLI,
UpdateRequestFromCLI: w.updateRequestFromCLI,
Sorter: sorters.MachineSorter(),
ValidArgsFn: c.comp.MachineListCompletion,
DescribePrinter: func() printers.Printer { return c.describePrinter },
ListPrinter: func() printers.Printer { return c.listPrinter },
CreateCmdMutateFn: func(cmd *cobra.Command) {
c.addMachineCreateFlags(cmd, "machine")
cmd.Aliases = []string{"allocate"}
cmd.Example = `machine create can be done in two different ways:
- default with automatic allocation:
metalctl machine create \
--hostname worker01 \
--name worker \
--image ubuntu-18.04 \ # query available with: metalctl image list
--size t1-small-x86 \ # query available with: metalctl size list
--partition test \ # query available with: metalctl partition list
--project cluster01 \
--sshpublickey "@~/.ssh/id_rsa.pub"
- for metal administration with reserved machines:
reserve a machine you want to allocate:
metalctl machine reserve 00000000-0000-0000-0000-0cc47ae54694 --description "blocked for maintenance"
allocate this machine:
metalctl machine create \
--hostname worker01 \
--name worker \
--image ubuntu-18.04 \ # query available with: metalctl image list
--project cluster01 \
--sshpublickey "@~/.ssh/id_rsa.pub" \
--id 00000000-0000-0000-0000-0cc47ae54694
after you do not want to use this machine exclusive, remove the reservation:
metalctl machine reserve 00000000-0000-0000-0000-0cc47ae54694 --remove
Once created the machine installation can not be modified anymore.
`
},
DeleteCmdMutateFn: func(cmd *cobra.Command) {
cmd.Long = `delete a machine and destroy all data stored on the local disks. Once destroyed it is back for usage by other projects. A destroyed machine can not restored anymore`
cmd.Flags().Bool("remove-from-database", false, "remove given machine from the database, is only required for maintenance reasons [optional] (admin only).")
},
ListCmdMutateFn: func(cmd *cobra.Command) {
w.listCmdFlags(cmd, 1*time.Hour)
},
UpdateCmdMutateFn: func(cmd *cobra.Command) {
cmd.Flags().String("description", "", "the description of the machine [optional]")
cmd.Flags().StringSlice("add-tags", []string{}, "tags to be added to the machine [optional]")
cmd.Flags().StringSlice("remove-tags", []string{}, "tags to be removed from the machine [optional]")
},
}
machineConsolePasswordCmd := &cobra.Command{
Use: "consolepassword <machine ID>",
Short: "fetch the consolepassword for a machine",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineConsolePassword(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machinePowerCmd := &cobra.Command{
Use: "power",
Short: "manage machine power",
}
machinePowerOnCmd := &cobra.Command{
Use: "on <machine ID>",
Short: "power on a machine",
Long: "set the machine to power on state, if the machine already was on nothing happens.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machinePowerOn(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machinePowerOffCmd := &cobra.Command{
Use: "off <machine ID>",
Short: "power off a machine",
Long: `set the machine to power off state, if the machine already was off nothing happens.
It will usually take some time to power off the machine, depending on the machine type.
Power on will therefore not work if the machine is in the powering off phase.`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machinePowerOff(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machinePowerResetCmd := &cobra.Command{
Use: "reset <machine ID>",
Short: "power reset a machine",
Long: "(hard) reset the machine power.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machinePowerReset(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machinePowerCycleCmd := &cobra.Command{
Use: "cycle <machine ID>",
Short: "power cycle a machine (graceful shutdown)",
Long: "(soft) cycle the machine power.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machinePowerCycle(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineUpdateFirmwareCmd := &cobra.Command{
Use: "update-firmware",
Aliases: []string{"firmware-update"},
Short: "update a machine firmware",
}
machineUpdateBiosCmd := &cobra.Command{
Use: "bios <machine ID>",
Short: "update a machine BIOS",
Long: "the machine BIOS will be updated to given revision. If revision flag is not specified an update plan will be printed instead.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineUpdateBios(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineUpdateBmcCmd := &cobra.Command{
Use: "bmc <machine ID>",
Short: "update a machine BMC",
Long: "the machine BMC will be updated to given revision. If revision flag is not specified an update plan will be printed instead.",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineUpdateBmc(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineBootBiosCmd := &cobra.Command{
Use: "bios <machine ID>",
Short: "boot a machine into BIOS",
Long: "the machine will boot into bios. (machine does not reboot automatically)",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineBootBios(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineBootPxeCmd := &cobra.Command{
Use: "pxe <machine ID>",
Short: "boot a machine from PXE",
Long: "the machine will boot from PXE. (machine does not reboot automatically)",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineBootPxe(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineBootDiskCmd := &cobra.Command{
Use: "disk <machine ID>",
Short: "boot a machine from disk",
Long: "the machine will boot from disk. (machine does not reboot automatically)",
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineBootDisk(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineIdentifyCmd := &cobra.Command{
Use: "identify",
Short: "manage machine chassis identify LED power",
}
machineIdentifyOnCmd := &cobra.Command{
Use: "on <machine ID>",
Short: "power on the machine chassis identify LED",
Long: `set the machine chassis identify LED to on state`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineIdentifyOn(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineIdentifyOffCmd := &cobra.Command{
Use: "off <machine ID>",
Short: "power off the machine chassis identify LED",
Long: `set the machine chassis identify LED to off state`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineIdentifyOff(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineReserveCmd := &cobra.Command{
Use: "reserve <machine ID>",
Short: "reserve a machine",
Long: `reserve a machine for exclusive usage, this machine will no longer be picked by other allocations.
This is useful for maintenance of the machine or testing. After the reservation is not needed anymore, the reservation
should be removed with --remove.`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineReserve(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineLockCmd := &cobra.Command{
Use: "lock <machine ID>",
Short: "lock a machine",
Long: `when a machine is locked, it can not be destroyed, to destroy a machine you must first remove the lock from that machine with --remove`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineLock(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineReinstallCmd := &cobra.Command{
Use: "reinstall <machine ID>",
Short: "reinstalls an already allocated machine",
Long: `reinstalls an already allocated machine. If it is not yet allocated, nothing happens, otherwise only the machine's primary disk
is wiped and the new image will subsequently be installed on that device`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineReinstall(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineConsoleCmd := &cobra.Command{
Use: "console <machine ID>",
Short: `console access to a machine`,
Long: `console access to a machine, machine must be created with a ssh public key, authentication is done with your private key.
In case the machine did not register properly a direct ipmi console access is available via the --ipmi flag. This is only for administrative access.`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineConsole(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineIpmiCmd := &cobra.Command{
Use: "ipmi [<machine ID>]",
Short: `display ipmi details of the machine, if no machine ID is given all ipmi addresses are returned.`,
Long: `display ipmi details of the machine, if no machine ID is given all ipmi addresses are returned.` + "\n" + api.EmojiHelpText(),
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineIpmi(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineIssuesCmd := &cobra.Command{
Use: "issues [<machine ID>]",
Short: `display machines which are in a potential bad state`,
Long: `display machines which are in a potential bad state` + "\n" + api.EmojiHelpText(),
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineIssues(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineLogsCmd := &cobra.Command{
Use: "logs <machine ID>",
Aliases: []string{"log"},
Short: `display machine provisioning logs`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineLogs(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
machineIpmiEventsCmd := &cobra.Command{
Use: "events <machine ID>",
Aliases: []string{"event"},
Short: `display machine hardware events`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.machineIpmiEvents(args)
},
ValidArgsFunction: c.comp.MachineListCompletion,
}
w.listCmdFlags(machineIpmiCmd, 1*time.Hour)
genericcli.AddSortFlag(machineIpmiCmd, sorters.MachineIPMISorter())
w.listCmdFlags(machineIssuesCmd, api.DefaultLastErrorThreshold())
genericcli.AddSortFlag(machineIssuesCmd, sorters.MachineIPMISorter())
machineIssuesCmd.Flags().StringSlice("only", []string{}, "issue types to include [optional]")
machineIssuesCmd.Flags().StringSlice("omit", []string{}, "issue types to omit [optional]")
machineIssuesCmd.Flags().String("severity", "", "issue severity to include [optional]")
var severities []string
for _, s := range api.AllSevereties() {
severities = append(severities, string(s))
}
must(machineIssuesCmd.RegisterFlagCompletionFunc("severity", cobra.FixedCompletions(severities, cobra.ShellCompDirectiveNoFileComp)))
must(machineIssuesCmd.RegisterFlagCompletionFunc("omit", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var shortNames []string
for _, i := range api.AllIssues() {
shortNames = append(shortNames, string(i.Type)+"\t"+i.Description)
}
return shortNames, cobra.ShellCompDirectiveNoFileComp
}))
must(machineIssuesCmd.RegisterFlagCompletionFunc("only", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var shortNames []string
for _, i := range api.AllIssues() {
shortNames = append(shortNames, string(i.Type)+"\t"+i.Description)
}
return shortNames, cobra.ShellCompDirectiveNoFileComp
}))
machineLogsCmd.Flags().Duration("last-event-error-threshold", api.DefaultLastErrorThreshold(), "the duration up to how long in the past a machine last event error will be counted as an issue [optional]")
machineConsolePasswordCmd.Flags().StringP("reason", "", "", "a short description why access to the consolepassword is required")
machineUpdateBiosCmd.Flags().StringP("revision", "", "", "the BIOS revision")
machineUpdateBiosCmd.Flags().StringP("description", "", "", "the reason why the BIOS should be updated")
must(machineUpdateBiosCmd.RegisterFlagCompletionFunc("revision", c.comp.FirmwareBiosRevisionCompletion))
machineUpdateFirmwareCmd.AddCommand(machineUpdateBiosCmd)
machineUpdateBmcCmd.Flags().StringP("revision", "", "", "the BMC revision")
machineUpdateBmcCmd.Flags().StringP("description", "", "", "the reason why the BMC should be updated")
must(machineUpdateBmcCmd.RegisterFlagCompletionFunc("revision", c.comp.FirmwareBmcRevisionCompletion))
machineUpdateFirmwareCmd.AddCommand(machineUpdateBmcCmd)
machinePowerCmd.AddCommand(machinePowerOnCmd)
machinePowerCmd.AddCommand(machinePowerOffCmd)
machinePowerCmd.AddCommand(machinePowerResetCmd)
machinePowerCmd.AddCommand(machinePowerCycleCmd)
machinePowerCmd.AddCommand(machineBootBiosCmd)
machinePowerCmd.AddCommand(machineBootDiskCmd)
machinePowerCmd.AddCommand(machineBootPxeCmd)
machineIdentifyOnCmd.Flags().StringP("description", "d", "", "description of the reason for chassis identify LED turn-on.")
machineIdentifyCmd.AddCommand(machineIdentifyOnCmd)
machineIdentifyOffCmd.Flags().StringP("description", "d", "Triggered by metalctl", "description of the reason for chassis identify LED turn-off.")
machineIdentifyCmd.AddCommand(machineIdentifyOffCmd)
machineReserveCmd.Flags().StringP("description", "d", "", "description of the reason for the reservation.")
machineReserveCmd.Flags().BoolP("remove", "r", false, "remove the reservation.")
machineLockCmd.Flags().StringP("description", "d", "", "description of the reason for the lock.")
machineLockCmd.Flags().BoolP("remove", "r", false, "remove the lock.")
machineReinstallCmd.Flags().StringP("image", "", "", "id of the image to get installed. [required]")
machineReinstallCmd.Flags().StringP("description", "d", "", "description of the reinstallation. [optional]")
must(machineReinstallCmd.MarkFlagRequired("image"))
machineConsoleCmd.Flags().StringP("sshidentity", "p", "", "SSH key file, if not given the default ssh key will be used if present [optional].")
machineConsoleCmd.Flags().BoolP("ipmi", "", false, "use ipmitool with direct network access (admin only).")
machineConsoleCmd.Flags().StringP("ipmiuser", "", "", "overwrite ipmi user (admin only).")
machineConsoleCmd.Flags().StringP("ipmipassword", "", "", "overwrite ipmi password (admin only).")
machineIpmiEventsCmd.Flags().StringP("ipmiuser", "", "", "overwrite ipmi user (admin only).")
machineIpmiEventsCmd.Flags().StringP("ipmipassword", "", "", "overwrite ipmi password (admin only).")
machineIpmiEventsCmd.Flags().StringP("last", "n", "10", "show last <n> log entries.")
machineIpmiCmd.AddCommand(machineIpmiEventsCmd)
return genericcli.NewCmds(
cmdsConfig,
machineConsolePasswordCmd,
machineConsoleCmd,
machineIpmiCmd,
machineIssuesCmd,
machineLogsCmd,
machineUpdateFirmwareCmd,
machinePowerCmd,
machineIdentifyCmd,
machineReserveCmd,
machineLockCmd,
machineReinstallCmd,
)
}
func (c *config) addMachineCreateFlags(cmd *cobra.Command, name string) {
cmd.Flags().StringP("description", "d", "", "Description of the "+name+" to create. [optional]")
cmd.Flags().StringP("partition", "S", "", "partition/datacenter where the "+name+" is created. [required, except for reserved machines]")
cmd.Flags().StringP("hostname", "H", "", "Hostname of the "+name+". [required]")
cmd.Flags().StringP("image", "i", "", "OS Image to install. [required]")
cmd.Flags().StringP("filesystemlayout", "", "", "Filesystemlayout to use during machine installation. [optional]")
cmd.Flags().StringP("name", "n", "", "Name of the "+name+". [optional]")
cmd.Flags().StringP("id", "I", "", "ID of a specific "+name+" to allocate, if given, size and partition are ignored. Need to be set to reserved (--reserve) state before.")
cmd.Flags().StringP("project", "P", "", "Project where the "+name+" should belong to. [required]")
cmd.Flags().StringP("size", "s", "", "Size of the "+name+". [required, except for reserved machines]")
cmd.Flags().StringP("sshpublickey", "p", "",
`SSH public key for access via ssh and console. [optional]
Can be either the public key as string, or pointing to the public key file to use e.g.: "@~/.ssh/id_rsa.pub".
If ~/.ssh/[id_ed25519.pub | id_rsa.pub | id_dsa.pub] is present it will be picked as default, matching the first one in this order.`)
cmd.Flags().StringSlice("tags", []string{}, "tags to add to the "+name+", use it like: --tags \"tag1,tag2\" or --tags \"tag3\".")
cmd.Flags().StringP("userdata", "", "", `cloud-init.io compatible userdata. [optional]
Can be either the userdata as string, or pointing to the userdata file to use e.g.: "@/tmp/userdata.cfg".`)
switch name {
case "machine":
cmd.Flags().StringSlice("ips", []string{},
`Sets the machine's IP address. Usage: [--ips[=IPV4-ADDRESS[,IPV4-ADDRESS]...]]...
IPV4-ADDRESS specifies the IPv4 address to add.
It can only be used in conjunction with --networks.`)
cmd.Flags().StringSlice("networks", []string{},
`Adds a network. Usage: [--networks NETWORK[:MODE][,NETWORK[:MODE]]...]...
NETWORK specifies the name or id of an existing network.
MODE cane be omitted or one of:
auto IP address is automatically acquired from the given network
noauto IP address for the given network must be provided via --ips`)
case "firewall":
cmd.Flags().StringSlice("ips", []string{},
`Sets the firewall's IP address. Usage: [--ips[=IPV4-ADDRESS[,IPV4-ADDRESS]...]]...
IPV4-ADDRESS specifies the IPv4 address to add.
It can only be used in conjunction with --networks.`)
cmd.Flags().StringSlice("networks", []string{},
`Adds network(s). Usage: --networks NETWORK[:MODE][,NETWORK[:MODE]]... [--networks NETWORK[:MODE][,
NETWORK[:MODE]]...]...
NETWORK specifies the id of an existing network.
MODE can be omitted or one of:
auto IP address is automatically acquired from the given network
noauto No automatic IP address acquisition`)
default:
log.Fatal(fmt.Errorf("illegal name: %s. Must be one of (machine, firewall)", name))
}
cmd.MarkFlagsMutuallyExclusive("file", "project")
cmd.MarkFlagsRequiredTogether("project", "networks", "hostname", "image")
cmd.MarkFlagsRequiredTogether("size", "partition")
// Completion for arguments
must(cmd.RegisterFlagCompletionFunc("networks", c.comp.NetworkListCompletion))
must(cmd.RegisterFlagCompletionFunc("ips", c.comp.IpListCompletion))
must(cmd.RegisterFlagCompletionFunc("partition", c.comp.PartitionListCompletion))
must(cmd.RegisterFlagCompletionFunc("size", c.comp.SizeListCompletion))
must(cmd.RegisterFlagCompletionFunc("project", c.comp.ProjectListCompletion))
must(cmd.RegisterFlagCompletionFunc("id", c.comp.MachineListCompletion))
must(cmd.RegisterFlagCompletionFunc("image", c.comp.ImageListCompletion))
must(cmd.RegisterFlagCompletionFunc("filesystemlayout", c.comp.FilesystemLayoutListCompletion))
}
func (c machineCmd) Get(id string) (*models.V1MachineResponse, error) {
resp, err := c.client.Machine().FindMachine(machine.NewFindMachineParams().WithID(id), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c machineCmd) List() ([]*models.V1MachineResponse, error) {
resp, err := c.client.Machine().FindMachines(machine.NewFindMachinesParams().WithBody(machineFindRequestFromCLI()), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func machineFindRequestFromCLI() *models.V1MachineFindRequest {
return &models.V1MachineFindRequest{
ID: viper.GetString("id"),
PartitionID: viper.GetString("partition"),
Sizeid: viper.GetString("size"),
Rackid: viper.GetString("rack"),
Name: viper.GetString("name"),
AllocationProject: viper.GetString("project"),
AllocationImageID: viper.GetString("image"),
AllocationHostname: viper.GetString("hostname"),
NicsMacAddresses: viper.GetStringSlice("mac"),
StateValue: viper.GetString("state"),
Tags: viper.GetStringSlice("tags"),
}
}
func (c machineCmd) Delete(id string) (*models.V1MachineResponse, error) {
if viper.GetBool("remove-from-database") {
if !viper.GetBool(forceFlag) {
return nil, fmt.Errorf("remove-from-database is set but you forgot to add --%s", forceFlag)
}
resp, err := c.client.Machine().DeleteMachine(machine.NewDeleteMachineParams().WithID(id), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
resp, err := c.client.Machine().FreeMachine(machine.NewFreeMachineParams().WithID(id), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c machineCmd) Create(rq *models.V1MachineAllocateRequest) (*models.V1MachineResponse, error) {
resp, err := c.client.Machine().AllocateMachine(machine.NewAllocateMachineParams().WithBody(rq), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c machineCmd) Update(rq *models.V1MachineUpdateRequest) (*models.V1MachineResponse, error) {
resp, err := c.client.Machine().UpdateMachine(machine.NewUpdateMachineParams().WithBody(rq), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c machineCmd) Convert(r *models.V1MachineResponse) (string, *models.V1MachineAllocateRequest, *models.V1MachineUpdateRequest, error) {
if r.ID == nil {
return "", nil, nil, fmt.Errorf("ipaddress is nil")
}
return *r.ID, machineResponseToCreate(r), machineResponseToUpdate(r), nil
}
func machineResponseToCreate(r *models.V1MachineResponse) *models.V1MachineAllocateRequest {
var (
ips []string
networks []*models.V1MachineAllocationNetwork
allocation = pointer.SafeDeref(r.Allocation)
)
for _, s := range allocation.Networks {
ips = append(ips, s.Ips...)
networks = append(networks, &models.V1MachineAllocationNetwork{
Autoacquire: pointer.Pointer(len(s.Ips) == 0),
Networkid: s.Networkid,
})
}
return &models.V1MachineAllocateRequest{
Description: allocation.Description,
Filesystemlayoutid: pointer.SafeDeref(pointer.SafeDeref(allocation.Filesystemlayout).ID),
Hostname: pointer.SafeDeref(allocation.Hostname),
Imageid: pointer.SafeDeref(allocation.Image).ID,
Ips: ips,
Name: r.Name,
Networks: networks,
Partitionid: pointer.SafeDeref(r.Partition).ID,
Projectid: allocation.Project,
Sizeid: pointer.SafeDeref(r.Size).ID,
SSHPubKeys: allocation.SSHPubKeys,
Tags: r.Tags,
UserData: base64.StdEncoding.EncodeToString([]byte(allocation.UserData)),
UUID: pointer.SafeDeref(r.ID),
}
}
func machineResponseToUpdate(r *models.V1MachineResponse) *models.V1MachineUpdateRequest {
// SSHPublicKeys should can not be updated by metalctl
// nolint:exhaustruct
return &models.V1MachineUpdateRequest{
Description: pointer.PointerOrNil(pointer.SafeDeref(r.Allocation).Description),
ID: r.ID,
Tags: r.Tags,
}
}
func (c *machineCmd) createRequestFromCLI() (*models.V1MachineAllocateRequest, error) {
mcr, err := machineCreateRequest()
if err != nil {
return nil, fmt.Errorf("machine create error:%w", err)
}
return mcr, nil
}
func machineCreateRequest() (*models.V1MachineAllocateRequest, error) {
sshPublicKeyArgument := viper.GetString("sshpublickey")
if strings.HasPrefix(sshPublicKeyArgument, "@") {
var err error
sshPublicKeyArgument, err = readFromFile(sshPublicKeyArgument[1:])
if err != nil {
return nil, err
}
}
if len(sshPublicKeyArgument) == 0 {
sshKey, err := searchSSHKey()
if err != nil {
return nil, err
}
sshPublicKey := sshKey + ".pub"
sshPublicKeyArgument, err = readFromFile(sshPublicKey)
if err != nil {
return nil, err
}
}
var keys []string
if sshPublicKeyArgument != "" {
keys = append(keys, sshPublicKeyArgument)
}
userDataArgument := viper.GetString("userdata")
if strings.HasPrefix(userDataArgument, "@") {
var err error
userDataArgument, err = readFromFile(userDataArgument[1:])
if err != nil {
return nil, err
}
}
if userDataArgument != "" {
userDataArgument = base64.StdEncoding.EncodeToString([]byte(userDataArgument))
}
possibleNetworks := viper.GetStringSlice("networks")
networks, err := parseNetworks(possibleNetworks)
if err != nil {
return nil, err
}
mcr := &models.V1MachineAllocateRequest{
Description: viper.GetString("description"),
Partitionid: pointer.Pointer(viper.GetString("partition")),
Hostname: viper.GetString("hostname"),
Imageid: pointer.Pointer(viper.GetString("image")),
Name: viper.GetString("name"),
UUID: viper.GetString("id"),
Projectid: pointer.Pointer(viper.GetString("project")),
Sizeid: pointer.Pointer(viper.GetString("size")),
SSHPubKeys: keys,
Tags: viper.GetStringSlice("tags"),
UserData: userDataArgument,
Networks: networks,
Ips: viper.GetStringSlice("ips"),
}
if viper.IsSet("filesystemlayout") {
mcr.Filesystemlayoutid = viper.GetString("filesystemlayout")
}
return mcr, nil
}
func (c *machineCmd) updateRequestFromCLI(args []string) (*models.V1MachineUpdateRequest, error) {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return nil, err
}
resp, err := c.Get(id)
if err != nil {
return nil, err
}
addTags := viper.GetStringSlice("add-tags")
removeTags := viper.GetStringSlice("remove-tags")
for _, removeTag := range removeTags {
if !slices.Contains(resp.Tags, removeTag) {
return nil, fmt.Errorf("cannot remove tag because it is currently not present: %s", removeTag)
}
}
newTags := addTags
for _, t := range resp.Tags {
if slices.Contains(removeTags, t) {
continue
}
newTags = append(newTags, t)
}
// SSHPublicKeys should can not be updated by metalctl
// nolint:exhaustruct
return &models.V1MachineUpdateRequest{
ID: pointer.Pointer(id),
Description: pointer.Pointer(viper.GetString("description")),
Tags: newTags,
}, nil
}
// non-generic command handling
func (c *machineCmd) machineConsolePassword(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().GetMachineConsolePassword(machine.NewGetMachineConsolePasswordParams().WithBody(&models.V1MachineConsolePasswordRequest{
ID: &id,
Reason: pointer.Pointer(viper.GetString("reason")),
}), nil)
if err != nil {
return err
}
fmt.Fprintf(c.out, "%s\n", pointer.SafeDeref(resp.Payload.ConsolePassword))
return nil
}
func (c *machineCmd) machinePowerOn(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().MachineOn(machine.NewMachineOnParams().WithID(id).WithBody(emptyBody), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machinePowerOff(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().MachineOff(machine.NewMachineOffParams().WithID(id).WithBody(emptyBody), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machinePowerReset(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().MachineReset(machine.NewMachineResetParams().WithID(id).WithBody(emptyBody), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machinePowerCycle(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().MachineCycle(machine.NewMachineCycleParams().WithID(id).WithBody(emptyBody), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machineUpdateBios(args []string) error {
m, vendor, board, err := c.firmwareData(args)
if err != nil {
return err
}
revision := viper.GetString("revision")
currentVersion := ""
if m.Bios != nil && m.Bios.Version != nil {
currentVersion = *m.Bios.Version
}
return c.machineUpdateFirmware(models.V1MachineUpdateFirmwareRequestKindBios, *m.ID, vendor, board, revision, currentVersion)
}
func (c *machineCmd) machineUpdateBmc(args []string) error {
m, vendor, board, err := c.firmwareData(args)
if err != nil {
return err
}
revision := viper.GetString("revision")
currentVersion := ""
if m.Ipmi != nil && m.Ipmi.Bmcversion != nil {
currentVersion = *m.Ipmi.Bmcversion
}
return c.machineUpdateFirmware(models.V1MachineUpdateFirmwareRequestKindBmc, *m.ID, vendor, board, revision, currentVersion)
}
func (c *machineCmd) firmwareData(args []string) (*models.V1MachineIPMIResponse, string, string, error) {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return nil, "", "", err
}
resp, err := c.client.Machine().FindIPMIMachine(machine.NewFindIPMIMachineParams().WithID(id), nil)
if err != nil {
return nil, "", "", err
}
m := resp.Payload
if m.Ipmi == nil {
return nil, "", "", fmt.Errorf("no ipmi data available of machine %s", id)
}
fru := *m.Ipmi.Fru
vendor := strings.ToLower(fru.BoardMfg)
board := strings.ToUpper(fru.BoardPartNumber)
return m, vendor, board, nil
}
func (c *machineCmd) machineUpdateFirmware(kind string, machineID, vendor, board, revision, currentVersion string) error {
firmwareResp, err := c.client.Firmware().ListFirmwares(firmware.NewListFirmwaresParams().WithKind(&kind), nil)
if err != nil {
return err
}
var rr []string
revisionAvailable, containsCurrentVersion := false, false
vv, ok := firmwareResp.Payload.Revisions[string(kind)]
if ok {
bb, ok := vv.VendorRevisions[vendor]
if ok {
rr, ok = bb.BoardRevisions[board]
if ok {
for _, rev := range rr {
if rev == revision {
revisionAvailable = true
}
if rev == currentVersion {
containsCurrentVersion = true
}
}
}
}
}
printPlan := revision == "" || !revisionAvailable
if printPlan {
fmt.Fprintln(c.out, "Available:")
for _, rev := range rr {
if rev == currentVersion {
fmt.Fprintf(c.out, "%s (current)\n", rev)
} else {
fmt.Fprintln(c.out, rev)
}
}
if !containsCurrentVersion {
fmt.Fprintf(c.out, "---\nCurrent %s version: %s\n", strings.ToUpper(string(kind)), currentVersion)
}
}
if revision == "" {
return nil
}
if !revisionAvailable {
return fmt.Errorf("specified revision %s not available", revision)
}
switch kind {
case models.V1MachineUpdateFirmwareRequestKindBios:
fmt.Fprintln(c.out, "It is recommended to power off the machine before updating the BIOS. This command will power on your machine automatically after the update or trigger a reboot.\n\nThe update may take a couple of minutes (up to ~10 minutes). Please wait until the machine powers on / reboots automatically as otherwise the update is still progressing or an error occurred during the update.")
case models.V1MachineUpdateFirmwareRequestKindBmc:
fmt.Fprintln(c.out, "The update may take a couple of minutes (up to ~10 minutes). You can look up the result through the server's BMC interface.")
default:
return fmt.Errorf("unsupported firmware kind: %s", kind)
}
if !viper.GetBool("yes-i-really-mean-it") {
err = genericcli.Prompt()
if err != nil {
return err
}
}
description := viper.GetString("description")
if description == "" {
description = "unknown"
}
kindString := string(kind)
resp, err := c.client.Machine().UpdateFirmware(machine.NewUpdateFirmwareParams().WithID(machineID).WithBody(&models.V1MachineUpdateFirmwareRequest{
Description: &description,
Kind: &kindString,
Revision: &revision,
}), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machineBootBios(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().MachineBios(machine.NewMachineBiosParams().WithID(id).WithBody(emptyBody), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machineBootDisk(args []string) error {
id, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
resp, err := c.client.Machine().MachineDisk(machine.NewMachineDiskParams().WithID(id).WithBody(emptyBody), nil)
if err != nil {
return err
}
return c.listPrinter.Print(resp.Payload)
}
func (c *machineCmd) machineBootPxe(args []string) error {