-
Notifications
You must be signed in to change notification settings - Fork 18
/
instances.go
1346 lines (1246 loc) · 36.4 KB
/
instances.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 instances
import (
"encoding/base64"
"fmt"
"os"
"sort"
"strings"
"github.com/G-Core/gcorelabscloud-go/client/instances/v1/client"
client2 "github.com/G-Core/gcorelabscloud-go/client/instances/v2/client"
"github.com/G-Core/gcorelabscloud-go/gcore/baremetal/v1/bminstances"
gcorecloud "github.com/G-Core/gcorelabscloud-go"
"github.com/urfave/cli/v2"
"github.com/G-Core/gcorelabscloud-go/client/flags"
"github.com/G-Core/gcorelabscloud-go/client/utils"
"github.com/G-Core/gcorelabscloud-go/gcore/instance/v1/instances"
"github.com/G-Core/gcorelabscloud-go/gcore/instance/v1/types"
"github.com/G-Core/gcorelabscloud-go/gcore/task/v1/tasks"
"github.com/G-Core/gcorelabscloud-go/gcore/volume/v1/volumes"
)
var (
instanceIDText = "instance_id is mandatory argument"
volumeSourceType = types.VolumeSource("").StringList()
volumeType = volumes.VolumeType("").StringList()
interfaceTypes = types.InterfaceType("").StringList()
interfaceFloatingIPSource = types.FloatingIPSource("").StringList()
bootableIndex = 0
)
var Commands = cli.Command{
Name: "instance",
Usage: "GCloud instances API",
Subcommands: []*cli.Command{
&instanceGetCommand,
&instanceListCommand,
&instanceCreateCommandV2,
&instanceRenameCommand,
&instanceDeleteCommand,
&instanceStartCommand,
&instanceStopCommand,
&instancePowerCycleCommand,
&instanceRebootCommand,
&instanceSuspendCommand,
&instanceResumeCommand,
&instanceResizeCommand,
&instanceCreateBaremetalCommand,
{
Name: "interface",
Usage: "Instance interfaces",
Subcommands: []*cli.Command{
&instanceListInterfacesCommand,
},
},
{
Name: "securitygroup",
Usage: "Instance security groups",
Subcommands: []*cli.Command{
&instanceListSecurityGroupsCommand,
&instanceAssignSecurityGroupsCommand,
&instanceUnAssignSecurityGroupsCommand,
},
},
{
Name: "metadata",
Usage: "Instance metadata",
Subcommands: []*cli.Command{
&metadataListCommand,
&metadataGetCommand,
&metadataCreateCommand,
&metadataUpdateCommand,
&metadataDeleteCommand,
},
},
},
}
func StringSliceToMetadataSetOpts(slice []string) (*instances.MetadataSetOpts, error) {
if len(slice) == 0 {
return nil, nil
}
var m instances.MetadataSetOpts
for _, s := range slice {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
return &m, fmt.Errorf("wrong label format: %s", s)
}
m.Metadata = append(m.Metadata, instances.MetadataOpts{Key: parts[0], Value: parts[1]})
}
return &m, nil
}
func StringSliceToAppConfigSetOpts(slice []string) (map[string]interface{}, error) {
if len(slice) == 0 {
return nil, nil
}
m := make(map[string]interface{}, len(slice))
for _, s := range slice {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
return m, fmt.Errorf("wrong label format: %s", s)
}
m[parts[0]] = parts[1]
}
return m, nil
}
func GetUserData(c *cli.Context) (string, error) {
userData := ""
userDataFile := c.String("user-data-file")
userDataContent := c.String("user-data")
if userDataFile != "" {
fileContent, err := os.ReadFile(userDataFile)
if err != nil {
return "", err
}
userData = base64.StdEncoding.EncodeToString(fileContent)
} else if userDataContent != "" {
userData = base64.StdEncoding.EncodeToString([]byte(userDataContent))
}
return userData, nil
}
func GetInstanceVolumes(c *cli.Context) ([]instances.CreateVolumeOpts, error) {
volumeSources := utils.GetEnumStringSliceValue(c, "volume-source")
volumeTypes := utils.GetEnumStringSliceValue(c, "volume-type")
volumeBootIndexes := c.IntSlice("volume-boot-index")
volumeSizes := c.IntSlice("volume-size")
volumeNames := c.StringSlice("volume-name")
volumeImageIDs := c.StringSlice("volume-image-id")
volumeVolumeIDs := c.StringSlice("volume-volume-id")
volumeSnapshotIDs := c.StringSlice("volume-snapshot-id")
res := make([]instances.CreateVolumeOpts, 0, len(volumeSources))
for idx, s := range volumeSources {
source := types.VolumeSource(s)
bootIndex := utils.IntFromIndex(volumeBootIndexes, idx, 0)
if !source.Bootable() {
bootIndex = -1
}
opts := instances.CreateVolumeOpts{
Source: source,
BootIndex: bootIndex,
Size: utils.IntFromIndex(volumeSizes, idx, 0),
TypeName: func(idx int) volumes.VolumeType {
if idx < len(volumeTypes) {
return volumes.VolumeType(volumeTypes[idx])
}
return volumes.Standard
}(idx),
Name: utils.StringFromIndex(volumeNames, idx, ""),
ImageID: utils.StringFromIndex(volumeImageIDs, idx, ""),
SnapshotID: utils.StringFromIndex(volumeSnapshotIDs, idx, ""),
VolumeID: utils.StringFromIndex(volumeVolumeIDs, idx, ""),
}
err := gcorecloud.TranslateValidationError(opts.Validate())
if err != nil {
return nil, err
}
res = append(res, opts)
}
// adjust boot order number so that they goes consistently
sort.Slice(res, func(i, j int) bool {
return res[i].BootIndex < res[j].BootIndex
})
minOrder := 0
bootableExists := false
for _, opts := range res {
if opts.BootIndex < 0 {
continue
}
if opts.BootIndex > minOrder {
opts.BootIndex = minOrder
}
minOrder++
if opts.BootIndex == bootableIndex {
bootableExists = true
}
}
if !bootableExists {
return res, fmt.Errorf("set bootable volume with source from next list: %s, %s", types.Image, types.Snapshot)
}
return res, nil
}
func GetInterfaces(c *cli.Context) ([]instances.InterfaceInstanceCreateOpts, error) {
interfaceTypes := utils.GetEnumStringSliceValue(c, "interface-type")
interfaceNetworkIDs := c.StringSlice("interface-network-id")
interfaceSubnetIDs := c.StringSlice("interface-subnet-id")
interfaceFloatingSources := utils.GetEnumStringSliceValue(c, "interface-floating-source")
interfaceFloatingIPs := c.StringSlice("interface-floating-ip")
res := make([]instances.InterfaceInstanceCreateOpts, 0, len(interfaceTypes))
for idx, t := range interfaceTypes {
interfaceType := types.InterfaceType(t)
var fIP *instances.CreateNewInterfaceFloatingIPOpts = nil
if interfaceType == types.SubnetInterfaceType {
source := types.FloatingIPSource(utils.StringFromIndex(interfaceFloatingSources, idx, ""))
if source != "" {
fIP = &instances.CreateNewInterfaceFloatingIPOpts{
Source: types.FloatingIPSource(utils.StringFromIndex(interfaceFloatingSources, idx, "")),
ExistingFloatingID: utils.StringFromIndex(interfaceFloatingIPs, idx, ""),
}
}
}
opts := instances.InterfaceOpts{
Type: interfaceType,
NetworkID: utils.StringFromIndex(interfaceNetworkIDs, idx, ""),
SubnetID: utils.StringFromIndex(interfaceSubnetIDs, idx, ""),
FloatingIP: fIP,
}
err := gcorecloud.TranslateValidationError(opts.Validate())
if err != nil {
return nil, err
}
res = append(res, instances.InterfaceInstanceCreateOpts{InterfaceOpts: opts})
}
return res, nil
}
func getBaremetalInterfaces(c *cli.Context) ([]bminstances.InterfaceOpts, error) {
interfaceTypes := utils.GetEnumStringSliceValue(c, "interface-type")
interfaceNetworkIDs := c.StringSlice("interface-network-id")
interfaceSubnetIDs := c.StringSlice("interface-subnet-id")
interfaceFloatingSources := utils.GetEnumStringSliceValue(c, "interface-floating-source")
interfaceFloatingIPs := c.StringSlice("interface-floating-ip")
res := make([]bminstances.InterfaceOpts, 0, len(interfaceTypes))
for idx, t := range interfaceTypes {
interfaceType := types.InterfaceType(t)
var fIP *bminstances.CreateNewInterfaceFloatingIPOpts = nil
if interfaceType == types.SubnetInterfaceType {
source := types.FloatingIPSource(utils.StringFromIndex(interfaceFloatingSources, idx, ""))
if source != "" {
fIP = &bminstances.CreateNewInterfaceFloatingIPOpts{
Source: types.FloatingIPSource(utils.StringFromIndex(interfaceFloatingSources, idx, "")),
ExistingFloatingID: utils.StringFromIndex(interfaceFloatingIPs, idx, ""),
}
}
}
opts := bminstances.InterfaceOpts{
Type: interfaceType,
NetworkID: utils.StringFromIndex(interfaceNetworkIDs, idx, ""),
SubnetID: utils.StringFromIndex(interfaceSubnetIDs, idx, ""),
FloatingIP: fIP,
}
err := gcorecloud.TranslateValidationError(opts.Validate())
if err != nil {
return nil, err
}
res = append(res, opts)
}
return res, nil
}
func GetSecurityGroups(c *cli.Context) []gcorecloud.ItemID {
securityGroups := c.StringSlice("security-group")
res := make([]gcorecloud.ItemID, len(securityGroups))
for i, s := range securityGroups {
res[i] = gcorecloud.ItemID{ID: s}
}
return res
}
var instanceListCommand = cli.Command{
Name: "list",
Usage: "List instances",
Category: "instance",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "exclude-security-group",
Aliases: []string{"e"},
Usage: "exclude instances with specified security group name",
Required: false,
},
&cli.BoolFlag{
Name: "available-floating",
Aliases: []string{"a"},
Usage: "show only instances which are able to handle floating address",
Required: false,
},
&cli.BoolFlag{
Name: "include-baremetal",
Aliases: []string{"bm"},
Usage: "include baremetal instances",
Required: false,
},
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "filter out instances by name",
Required: false,
},
&cli.StringFlag{
Name: "flavor_id",
Aliases: []string{"fid"},
Usage: "filter out instances by flavor id",
Required: false,
},
&cli.IntFlag{
Name: "limit",
Aliases: []string{"l"},
Usage: "limit the number of returned instances",
Required: false,
},
&cli.IntFlag{
Name: "offset",
Aliases: []string{"o"},
Usage: "offset value is used to exclude the first set of records from the result",
Required: false,
},
},
Action: func(c *cli.Context) error {
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
opts := instances.ListOpts{
ExcludeSecGroup: c.String("exclude-security-group"),
AvailableFloating: c.Bool("available-floating"),
IncludeBaremetal: c.Bool("include-baremetal"),
Name: c.String("name"),
FlavorID: c.String("flavor_id"),
Limit: c.Int("limit"),
Offset: c.Int("offset"),
}
results, err := instances.ListAll(client, opts)
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(results, c.String("format"))
return nil
},
}
var instanceListInterfacesCommand = cli.Command{
Name: "list",
Usage: "List instance interfaces",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "list")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
results, err := instances.ListInterfacesAll(client, instanceID)
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(results, c.String("format"))
return nil
},
}
var instanceListSecurityGroupsCommand = cli.Command{
Name: "list",
Usage: "List instance security groups",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "list")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
results, err := instances.ListSecurityGroupsAll(client, instanceID)
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(results, c.String("format"))
return nil
},
}
var instanceRenameCommand = cli.Command{
Name: "rename",
Usage: "Rename instance",
ArgsUsage: "<instance_id>",
Category: "instance",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "security group name",
Required: true,
},
},
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "rename")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
opts := instances.RenameInstanceOpts{Name: c.String("name")}
instance, err := instances.RenameInstance(client, instanceID, opts).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceAssignSecurityGroupsCommand = cli.Command{
Name: "add",
Usage: "Add instance security group",
ArgsUsage: "<instance_id>",
Category: "instance",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "security group name",
Required: true,
},
},
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "add")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
opts := instances.SecurityGroupOpts{Name: c.String("name")}
err = instances.AssignSecurityGroup(client, instanceID, opts).ExtractErr()
if err != nil {
return cli.NewExitError(err, 1)
}
return nil
},
}
var instanceUnAssignSecurityGroupsCommand = cli.Command{
Name: "delete",
Usage: "Add instance security group",
ArgsUsage: "<instance_id>",
Category: "instance",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "security group name",
Required: true,
},
},
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "delete")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
opts := instances.SecurityGroupOpts{Name: c.String("name")}
err = instances.UnAssignSecurityGroup(client, instanceID, opts).ExtractErr()
if err != nil {
return cli.NewExitError(err, 1)
}
return nil
},
}
var instanceCreateCommandV2 = cli.Command{
Name: "create",
Usage: `
Create instance.
Example: gcoreclient instance create --flavor g1-standard-1-2 --name test1 --keypair keypair --volume-source image --volume-type standard --volume-image-id --interface-type subnet --interface-network-id 95ea2073-c5eb-448a-aed5-78045f88f24a --interface-subnet-id b7fd6e0a-36a5-4f6a-9dc4-90a39eb9833f --volume-size 2 --metadata one=two -d -w`,
Category: "instance",
Flags: append([]cli.Flag{
&cli.StringSliceFlag{
Name: "name",
Aliases: []string{"n"},
Usage: "instance name",
Required: false,
},
&cli.StringSliceFlag{
Name: "name-template",
Usage: "instance name templates",
Required: false,
},
&cli.StringFlag{
Name: "flavor",
Usage: "instance flavor",
Required: true,
},
&cli.StringFlag{
Name: "keypair",
Aliases: []string{"k"},
Usage: "instance ssh keypair",
Required: false,
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"p"},
Usage: "instance password",
Required: false,
},
&cli.StringFlag{
Name: "username",
Aliases: []string{"u"},
Usage: "instance username",
Required: false,
},
&cli.StringFlag{
Name: "user-data",
Usage: "instance user data",
Required: false,
},
&cli.StringFlag{
Name: "user-data-file",
Usage: "instance user data file",
Required: false,
},
&cli.GenericFlag{
Name: "volume-source",
Aliases: []string{"vs"},
Value: &utils.EnumStringSliceValue{
Enum: volumeSourceType,
},
Usage: fmt.Sprintf("instance volume source. output in %s", strings.Join(volumeSourceType, ", ")),
Required: true,
},
&cli.IntSliceFlag{
Name: "volume-boot-index",
Usage: "instance volume boot index",
Required: false,
},
&cli.IntSliceFlag{
Name: "volume-size",
Usage: "instance volume size",
Required: false,
},
&cli.GenericFlag{
Name: "volume-type",
Aliases: []string{"vt"},
Value: &utils.EnumStringSliceValue{
Enum: volumeType,
},
Usage: fmt.Sprintf("instance volume types. output in %s", strings.Join(volumeType, ", ")),
Required: true,
},
&cli.StringSliceFlag{
Name: "volume-name",
Usage: "instance volume name",
Required: false,
},
&cli.StringSliceFlag{
Name: "volume-image-id",
Usage: "instance volume image id",
Required: false,
},
&cli.StringSliceFlag{
Name: "volume-snapshot-id",
Usage: "instance volume snapshot id",
Required: false,
},
&cli.StringSliceFlag{
Name: "volume-volume-id",
Usage: "instance volume volume id",
Required: false,
},
&cli.GenericFlag{
Name: "interface-type",
Aliases: []string{"it"},
Value: &utils.EnumStringSliceValue{
Enum: interfaceTypes,
},
Usage: fmt.Sprintf("instance interface type. output in %s", strings.Join(interfaceTypes, ", ")),
Required: true,
},
&cli.StringSliceFlag{
Name: "interface-network-id",
Usage: "instance interface network id",
Required: false,
},
&cli.StringSliceFlag{
Name: "interface-subnet-id",
Usage: "instance interface subnet id",
Required: false,
},
&cli.GenericFlag{
Name: "interface-floating-source",
Aliases: []string{"ifs"},
Value: &utils.EnumStringSliceValue{
Enum: interfaceFloatingIPSource,
},
Usage: fmt.Sprintf("instance floating ip source. output in %s", strings.Join(interfaceFloatingIPSource, ", ")),
Required: false,
},
&cli.StringSliceFlag{
Name: "interface-floating-ip",
Usage: "instance interface existing floating ip. Required when --interface-floating-source set as `existing`",
Required: false,
},
&cli.StringSliceFlag{
Name: "security-group",
Usage: "instance security group",
Required: false,
},
&cli.StringFlag{
Name: "server-group",
Usage: "instance server group",
},
&cli.StringSliceFlag{
Name: "metadata",
Usage: "instance metadata. Example: --metadata one=two --metadata three=four",
Required: false,
},
}, flags.WaitCommandFlags...),
Action: func(c *cli.Context) error {
clientV2, err := client2.NewInstanceClientV2(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
clientV1, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
userData, err := GetUserData(c)
if err != nil {
_ = cli.ShowCommandHelp(c, "create")
return cli.NewExitError(err, 1)
}
instanceVolumes, err := GetInstanceVolumes(c)
if err != nil {
_ = cli.ShowCommandHelp(c, "create")
return cli.NewExitError(err, 1)
}
// todo add security group mapping
instanceInterfaces, err := GetInterfaces(c)
if err != nil {
_ = cli.ShowCommandHelp(c, "create")
return cli.NewExitError(err, 1)
}
securityGroups := GetSecurityGroups(c)
metadata, err := StringSliceToMetadataSetOpts(c.StringSlice("metadata"))
if err != nil {
_ = cli.ShowCommandHelp(c, "create")
return cli.NewExitError(err, 1)
}
opts := instances.CreateOpts{
Flavor: c.String("flavor"),
Names: c.StringSlice("name"),
NameTemplates: c.StringSlice("name-template"),
Volumes: instanceVolumes,
Interfaces: instanceInterfaces,
SecurityGroups: securityGroups,
Keypair: c.String("keypair"),
Password: c.String("password"),
Username: c.String("username"),
UserData: userData,
Metadata: metadata,
ServerGroupID: c.String("server-group"),
}
err = gcorecloud.TranslateValidationError(opts.Validate())
if err != nil {
return cli.NewExitError(err, 1)
}
results, err := instances.Create(clientV2, opts).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
return utils.WaitTaskAndShowResult(c, clientV1, results, true, func(task tasks.TaskID) (interface{}, error) {
taskInfo, err := tasks.Get(clientV1, string(task)).Extract()
if err != nil {
return nil, fmt.Errorf("cannot get task with ID: %s. Error: %w", task, err)
}
instanceID, err := instances.ExtractInstanceIDFromTask(taskInfo)
if err != nil {
return nil, fmt.Errorf("cannot retrieve instance ID from task info: %w", err)
}
instance, err := instances.Get(clientV1, instanceID).Extract()
if err != nil {
return nil, fmt.Errorf("cannot get instance with ID: %s. Error: %w", instanceID, err)
}
return instance, nil
})
},
}
var instanceGetCommand = cli.Command{
Name: "show",
Usage: "Get instance information",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "show")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.Get(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceDeleteCommand = cli.Command{
Name: "delete",
Usage: "Delete instance",
Flags: append([]cli.Flag{
&cli.StringSliceFlag{
Name: "volume-id",
Usage: "instance volume id",
Required: false,
},
&cli.StringSliceFlag{
Name: "floating-ip",
Usage: "instance floating ip",
Required: false,
},
&cli.BoolFlag{
Name: "delete-floating-ips",
Usage: "delete all instance floating ips",
Required: false,
},
}, flags.WaitCommandFlags...),
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "show")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
opts := instances.DeleteOpts{
Volumes: c.StringSlice("volume-id"),
DeleteFloatings: c.Bool("delete-floating-ips"),
FloatingIPs: c.StringSlice("floating-ip"),
}
err = gcorecloud.TranslateValidationError(opts.Validate())
if err != nil {
return cli.NewExitError(err, 1)
}
results, err := instances.Delete(client, instanceID, opts).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
return utils.WaitTaskAndShowResult(c, client, results, false, func(task tasks.TaskID) (interface{}, error) {
_, err := instances.Get(client, instanceID).Extract()
if err == nil {
return nil, fmt.Errorf("cannot delete instance with ID: %s", instanceID)
}
switch err.(type) {
case gcorecloud.ErrDefault404:
return nil, nil
default:
return nil, err
}
})
},
}
var instanceStartCommand = cli.Command{
Name: "start",
Usage: "Start instance",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "start")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.Start(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceStopCommand = cli.Command{
Name: "stop",
Usage: "Stop instance",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "stop")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.Stop(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instancePowerCycleCommand = cli.Command{
Name: "powercycle",
Usage: "Stop and start instance. Aka hard reboot",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "powercycle")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.PowerCycle(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceRebootCommand = cli.Command{
Name: "reboot",
Usage: "Reboot instance",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "reboot")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.Reboot(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceSuspendCommand = cli.Command{
Name: "suspend",
Usage: "Suspend instance",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "suspend")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.Suspend(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceResumeCommand = cli.Command{
Name: "resume",
Usage: "Resume instance",
ArgsUsage: "<instance_id>",
Category: "instance",
Action: func(c *cli.Context) error {
instanceID, err := flags.GetFirstStringArg(c, instanceIDText)
if err != nil {
_ = cli.ShowCommandHelp(c, "resume")
return err
}
client, err := client.NewInstanceClientV1(c)
if err != nil {
_ = cli.ShowAppHelp(c)
return cli.NewExitError(err, 1)
}
instance, err := instances.Resume(client, instanceID).Extract()
if err != nil {
return cli.NewExitError(err, 1)
}
utils.ShowResults(instance, c.String("format"))
return nil
},
}
var instanceResizeCommand = cli.Command{