forked from scaleway/scaleway-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_server.go
999 lines (902 loc) · 28.1 KB
/
custom_server.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
package instance
import (
"bytes"
"context"
"fmt"
"net"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/scaleway/scaleway-cli/internal/core"
"github.com/scaleway/scaleway-cli/internal/human"
"github.com/scaleway/scaleway-cli/internal/interactive"
"github.com/scaleway/scaleway-sdk-go/api/instance/v1"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/scaleway/scaleway-sdk-go/scw"
)
const (
serverActionTimeout = 10 * time.Minute
)
//
// Marshalers
//
// serverStateMarshalSpecs allows to override the displayed instance.ServerState.
var (
serverStateMarshalSpecs = human.EnumMarshalSpecs{
instance.ServerStateRunning: &human.EnumMarshalSpec{Attribute: color.FgGreen},
instance.ServerStateStopped: &human.EnumMarshalSpec{Attribute: color.Faint, Value: "archived"},
instance.ServerStateStoppedInPlace: &human.EnumMarshalSpec{Attribute: color.Faint},
instance.ServerStateStarting: &human.EnumMarshalSpec{Attribute: color.FgBlue},
instance.ServerStateStopping: &human.EnumMarshalSpec{Attribute: color.FgBlue},
instance.ServerStateLocked: &human.EnumMarshalSpec{Attribute: color.FgRed},
}
)
// serverLocationMarshalerFunc marshals a instance.ServerLocation.
func serverLocationMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
location := i.(instance.ServerLocation)
zone, err := scw.ParseZone(location.ZoneID)
if err != nil {
return "", err
}
return string(zone), nil
}
// serversMarshalerFunc marshals a Server.
func serversMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
// humanServerInList is the custom Server type used for list view.
type humanServerInList struct {
ID string
Name string
Type string
State instance.ServerState
Zone scw.Zone
PublicIP net.IP
PrivateIP *string
Tags []string
ImageName string
PlacementGroup *instance.PlacementGroup
ModificationDate time.Time
CreationDate time.Time
Volumes int
Protected bool
SecurityGroupName string
SecurityGroupID string
StateDetail string
Arch instance.Arch
ImageID string
}
servers := i.([]*instance.Server)
humanServers := make([]*humanServerInList, 0)
for _, server := range servers {
publicIPAddress := net.IP(nil)
if server.PublicIP != nil {
publicIPAddress = server.PublicIP.Address
}
serverImageID := ""
serverImageName := ""
if server.Image != nil {
serverImageID = server.Image.ID
serverImageName = server.Image.Name
}
humanServers = append(humanServers, &humanServerInList{
ID: server.ID,
Name: server.Name,
Type: server.CommercialType,
State: server.State,
Zone: server.Zone,
PublicIP: publicIPAddress,
PrivateIP: server.PrivateIP,
Tags: server.Tags,
ImageName: serverImageName,
PlacementGroup: server.PlacementGroup,
ModificationDate: server.ModificationDate,
CreationDate: server.CreationDate,
Volumes: len(server.Volumes),
Protected: server.Protected,
SecurityGroupName: server.SecurityGroup.Name,
SecurityGroupID: server.SecurityGroup.ID,
StateDetail: server.StateDetail,
Arch: server.Arch,
ImageID: serverImageID,
})
}
return human.Marshal(humanServers, opt)
}
func getServerResponseMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
serverResponse := i.(instance.GetServerResponse)
// Sections
opt.Sections = []*human.MarshalSection{
{
FieldName: "server",
Title: "Server",
},
{
FieldName: "server.image",
Title: "Server Image",
}, {
FieldName: "server.allowed-actions",
}, {
FieldName: "volumes",
Title: "Volumes",
},
}
customServer := &struct {
Server *instance.Server
Volumes []*instance.Volume
}{
serverResponse.Server,
orderVolumes(serverResponse.Server.Volumes),
}
str, err := human.Marshal(customServer, opt)
if err != nil {
return "", err
}
return str, nil
}
// orderVolumes return an ordered slice based on the volume map key "0", "1", "2",...
func orderVolumes(v map[string]*instance.Volume) []*instance.Volume {
indexes := []string(nil)
for index := range v {
indexes = append(indexes, index)
}
sort.Strings(indexes)
var orderedVolumes []*instance.Volume
for _, index := range indexes {
orderedVolumes = append(orderedVolumes, v[index])
}
return orderedVolumes
}
// serversMarshalerFunc marshals a BootscriptID.
func bootscriptMarshalerFunc(i interface{}, opt *human.MarshalOpt) (string, error) {
bootscript := i.(instance.Bootscript)
return bootscript.Title, nil
}
//
// Builders
//
func serverListBuilder(c *core.Command) *core.Command {
type customListServersRequest struct {
*instance.ListServersRequest
OrganizationID *string
}
renameOrganizationIDArgSpec(c.ArgSpecs)
c.ArgsType = reflect.TypeOf(customListServersRequest{})
c.AddInterceptors(func(ctx context.Context, argsI interface{}, runner core.CommandRunner) (i interface{}, err error) {
args := argsI.(*customListServersRequest)
if args.ListServersRequest == nil {
args.ListServersRequest = &instance.ListServersRequest{}
}
request := args.ListServersRequest
request.Organization = args.OrganizationID
return runner(ctx, request)
})
return c
}
func serverUpdateBuilder(c *core.Command) *core.Command {
type instanceUpdateServerRequestCustom struct {
*instance.UpdateServerRequest
IP *instance.NullableStringValue
PlacementGroupID *instance.NullableStringValue
SecurityGroupID *string
VolumeIDs *[]string
CloudInit string
}
c.ArgsType = reflect.TypeOf(instanceUpdateServerRequestCustom{})
// Rename modified arg specs.
c.ArgSpecs.GetByName("placement-group").Name = "placement-group-id"
c.ArgSpecs.GetByName("security-group.id").Name = "security-group-id"
// Delete unused arg specs.
c.ArgSpecs.DeleteByName("security-group.name")
c.ArgSpecs.DeleteByName("volumes.{key}.name")
c.ArgSpecs.DeleteByName("volumes.{key}.size")
c.ArgSpecs.DeleteByName("volumes.{key}.id")
c.ArgSpecs.DeleteByName("volumes.{key}.volume-type")
c.ArgSpecs.DeleteByName("volumes.{key}.organization")
// Add new arg specs.
c.ArgSpecs.AddBefore("placement-group-id", &core.ArgSpec{
Name: "volume-ids.{index}",
Short: "Will update ALL volume IDs at once, including the root volume of the server (use volume-ids=none to detach all volumes)",
})
c.ArgSpecs.AddBefore("boot-type", &core.ArgSpec{
Name: "ip",
Short: `IP that should be attached to the server (use ip=none to detach)`,
})
c.ArgSpecs.AddBefore("boot-type", &core.ArgSpec{
Name: "cloud-init",
Short: "The cloud-init script to use",
})
c.Run = func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
customRequest := argsI.(*instanceUpdateServerRequestCustom)
updateServerRequest := customRequest.UpdateServerRequest
updateServerRequest.PlacementGroup = customRequest.PlacementGroupID
if customRequest.SecurityGroupID != nil {
updateServerRequest.SecurityGroup = &instance.SecurityGroupTemplate{
ID: *customRequest.SecurityGroupID,
}
}
attachIPRequest := (*instance.UpdateIPRequest)(nil)
detachIP := false
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
getServerResponse, err := api.GetServer(&instance.GetServerRequest{
Zone: updateServerRequest.Zone,
ServerID: customRequest.ServerID,
})
if err != nil {
return nil, err
}
switch {
case customRequest.IP == nil:
// ip is not set
// do nothing
case customRequest.IP.Null:
// ip=none
// detach IP from the server, only if it was attached.
if getServerResponse.Server.PublicIP != nil {
detachIP = true
}
default:
// ip=<anything>
// update ip
if getServerResponse.Server.PublicIP != nil {
detachIP = true
}
attachIPRequest = &instance.UpdateIPRequest{
IP: customRequest.IP.Value,
Server: &instance.NullableStringValue{
Value: customRequest.ServerID,
},
}
}
// Instance API does not support detaching the existing IP and then attaching a new one to the same server
// in 1 call only.
// We need to do it manually in 2 calls.
if detachIP {
_, err = api.UpdateIP(&instance.UpdateIPRequest{
IP: getServerResponse.Server.PublicIP.ID,
Server: &instance.NullableStringValue{
Null: true,
},
})
if err != nil {
return nil, err
}
}
if attachIPRequest != nil {
_, err = api.UpdateIP(attachIPRequest)
if err != nil {
return nil, err
}
}
// Update all volume IDs at once.
if customRequest.VolumeIDs != nil {
volumes := make(map[string]*instance.VolumeTemplate)
for i, volumeID := range *customRequest.VolumeIDs {
index := strconv.Itoa(i)
volumes[index] = &instance.VolumeTemplate{ID: volumeID, Name: getServerResponse.Server.Name + "-" + index}
}
customRequest.Volumes = &volumes
}
// Set cloud-init
if customRequest.CloudInit != "" {
err := api.SetServerUserData(&instance.SetServerUserDataRequest{
Zone: updateServerRequest.Zone,
ServerID: customRequest.ServerID,
Key: "cloud-init",
Content: bytes.NewBufferString(customRequest.CloudInit),
})
if err != nil {
return nil, err
}
}
updateServerResponse, err := api.UpdateServer(updateServerRequest)
if err != nil {
return nil, err
}
return updateServerResponse, nil
}
return c
}
func serverGetBuilder(c *core.Command) *core.Command {
// This method is here as a proof of concept before we find the correct way to implement it at larger scale
c.ArgSpecs.GetPositionalArg().AutoCompleteFunc = func(ctx context.Context, prefix string) core.AutocompleteSuggestions {
api := instance.NewAPI(core.ExtractClient(ctx))
resp, err := api.ListServers(&instance.ListServersRequest{}, scw.WithAllPages())
if err != nil {
return nil
}
suggestion := core.AutocompleteSuggestions{}
for _, s := range resp.Servers {
if strings.HasPrefix(s.ID, prefix) {
suggestion = append(suggestion, s.ID)
}
}
return suggestion
}
return c
}
//
// Commands
//
func serverAttachVolumeCommand() *core.Command {
return &core.Command{
Short: `Attach a volume to a server`,
Namespace: "instance",
Resource: "server",
Verb: "attach-volume",
ArgsType: reflect.TypeOf(instance.AttachVolumeRequest{}),
ArgSpecs: core.ArgSpecs{
{
Name: "server-id",
Short: `ID of the server`,
Required: true,
},
{
Name: "volume-id",
Short: `ID of the volume to attach`,
Required: true,
},
core.ZoneArgSpec(),
},
Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) {
request := argsI.(*instance.AttachVolumeRequest)
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
return api.AttachVolume(request)
},
Examples: []*core.Example{
{
Short: "Attach a volume to a server",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111","volume_id": "22222222-1111-5555-2222-666666111111"}`,
},
},
}
}
func serverDetachVolumeCommand() *core.Command {
return &core.Command{
Short: `Detach a volume from its server`,
Namespace: "instance",
Resource: "server",
Verb: "detach-volume",
ArgsType: reflect.TypeOf(instance.DetachVolumeRequest{}),
ArgSpecs: core.ArgSpecs{
{
Name: "volume-id",
Short: `ID of the volume to detach`,
Required: true,
},
core.ZoneArgSpec(),
},
Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) {
request := argsI.(*instance.DetachVolumeRequest)
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
return api.DetachVolume(request)
},
Examples: []*core.Example{
{
Short: "Detach a volume from its server",
ArgsJSON: `{"volume_id": "22222222-1111-5555-2222-666666111111"}`,
},
},
}
}
type instanceActionRequest struct {
Zone scw.Zone
ServerID string
}
var serverActionArgSpecs = core.ArgSpecs{
{
Name: "server-id",
Short: `ID of the server affected by the action.`,
Required: true,
Positional: true,
},
core.ZoneArgSpec(),
}
func serverStartCommand() *core.Command {
return &core.Command{
Short: `Power on server`,
Namespace: "instance",
Resource: "server",
Verb: "start",
ArgsType: reflect.TypeOf(instanceActionRequest{}),
Run: getRunServerAction(instance.ServerActionPoweron),
WaitFunc: waitForServerFunc(),
ArgSpecs: serverActionArgSpecs,
Examples: []*core.Example{
{
Short: "Start a server in the default zone with a given id",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Start a server in fr-par-1 zone with a given id",
ArgsJSON: `{"zone":"fr-par-1", "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
func serverStopCommand() *core.Command {
return &core.Command{
Short: `Power off server`,
Namespace: "instance",
Resource: "server",
Verb: "stop",
ArgsType: reflect.TypeOf(instanceActionRequest{}),
Run: getRunServerAction(instance.ServerActionPoweroff),
WaitFunc: waitForServerFunc(),
ArgSpecs: serverActionArgSpecs,
Examples: []*core.Example{
{
Short: "Stop a server in the default zone with a given id",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Stop a server in fr-par-1 zone with a given id",
ArgsJSON: `{"zone":"fr-par-1", "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
func serverStandbyCommand() *core.Command {
return &core.Command{
Short: `Put server in standby mode`,
Namespace: "instance",
Resource: "server",
Verb: "standby",
ArgsType: reflect.TypeOf(instanceActionRequest{}),
Run: getRunServerAction(instance.ServerActionStopInPlace),
WaitFunc: waitForServerFunc(),
ArgSpecs: serverActionArgSpecs,
Examples: []*core.Example{
{
Short: "Put in standby a server in the default zone with a given id",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Put in standby a server in fr-par-1 zone with a given id",
ArgsJSON: `{"zone":"fr-par-1", "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
func serverRebootCommand() *core.Command {
return &core.Command{
Short: `Reboot server`,
Namespace: "instance",
Resource: "server",
Verb: "reboot",
ArgsType: reflect.TypeOf(instanceActionRequest{}),
Run: getRunServerAction(instance.ServerActionReboot),
WaitFunc: waitForServerFunc(),
ArgSpecs: serverActionArgSpecs,
Examples: []*core.Example{
{
Short: "Reboot a server in the default zone with a given id",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Reboot a server in fr-par-1 zone with a given id",
ArgsJSON: `{"zone":"fr-par-1", "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
func serverBackupCommand() *core.Command {
type instanceBackupRequest struct {
Zone scw.Zone
ServerID string
Name string
}
return &core.Command{
Short: `Backup server`,
Long: `Create a new image based on the server.
This command:
- creates a snapshot of all attached volumes.
- creates an image based on all these snapshots.
Once your image is ready you will be able to create a new server based on this image.
`,
Namespace: "instance",
Resource: "server",
Verb: "backup",
ArgsType: reflect.TypeOf(instanceBackupRequest{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) {
args := argsI.(*instanceBackupRequest)
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
res, err := api.ServerAction(&instance.ServerActionRequest{
Zone: args.Zone,
ServerID: args.ServerID,
Action: instance.ServerActionBackup,
Name: &args.Name,
})
if err != nil {
return nil, err
}
tmp := strings.Split(res.Task.HrefResult, "/")
if len(tmp) != 3 {
return nil, fmt.Errorf("cannot extract image id from task")
}
return api.GetImage(&instance.GetImageRequest{ImageID: tmp[2]})
},
WaitFunc: func(ctx context.Context, argsI, respI interface{}) (i interface{}, err error) {
resp := respI.(*instance.GetImageResponse)
api := instance.NewAPI(core.ExtractClient(ctx))
return api.WaitForImage(&instance.WaitForImageRequest{
ImageID: resp.Image.ID,
Zone: resp.Image.Zone,
Timeout: scw.TimeDurationPtr(serverActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
},
ArgSpecs: core.ArgSpecs{
{
Name: "server-id",
Short: `ID of the server to backup.`,
Required: true,
Positional: true,
},
{
Name: "name",
Short: `Name of your backup.`,
Default: core.RandomValueGenerator("backup"),
},
core.ZoneArgSpec(),
},
Examples: []*core.Example{
{
Short: "Create a new image based on a server",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
func serverWaitCommand() *core.Command {
return &core.Command{
Short: `Wait for server to reach a stable state`,
Long: `Wait for server to reach a stable state. This is similar to using --wait flag on other action commands, but without requiring a new action on the server.`,
Namespace: "instance",
Resource: "server",
Verb: "wait",
ArgsType: reflect.TypeOf(instanceActionRequest{}),
Run: func(ctx context.Context, argsI interface{}) (i interface{}, err error) {
return waitForServerFunc()(ctx, argsI, nil)
},
ArgSpecs: serverActionArgSpecs,
Examples: []*core.Example{
{
Short: "Wait for a server to reach a stable state",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
}
}
func waitForServerFunc() core.WaitFunc {
return func(ctx context.Context, argsI, _ interface{}) (interface{}, error) {
return instance.NewAPI(core.ExtractClient(ctx)).WaitForServer(&instance.WaitForServerRequest{
Zone: argsI.(*instanceActionRequest).Zone,
ServerID: argsI.(*instanceActionRequest).ServerID,
Timeout: scw.TimeDurationPtr(serverActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
}
}
func getRunServerAction(action instance.ServerAction) core.CommandRunner {
return func(ctx context.Context, argsI interface{}) (i interface{}, e error) {
args := argsI.(*instanceActionRequest)
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
_, err := api.ServerAction(&instance.ServerActionRequest{
Zone: args.Zone,
ServerID: args.ServerID,
Action: action,
})
return &core.SuccessResult{Message: fmt.Sprintf("%s successful for the server", action)}, err
}
}
type customDeleteServerRequest struct {
Zone scw.Zone
ServerID string
WithVolumes withVolumes
WithIP bool
ForceShutdown bool
}
type withVolumes string
const (
withVolumesNone = withVolumes("none")
withVolumesLocal = withVolumes("local")
withVolumesBlock = withVolumes("block")
withVolumesRoot = withVolumes("root")
withVolumesAll = withVolumes("all")
)
func serverDeleteCommand() *core.Command {
return &core.Command{
Short: `Delete server`,
Long: `Delete a server with the given ID.`,
Namespace: "instance",
Verb: "delete",
Resource: "server",
ArgsType: reflect.TypeOf(customDeleteServerRequest{}),
ArgSpecs: core.ArgSpecs{
{
Name: "server-id",
Required: true,
Positional: true,
},
{
Name: "with-volumes",
Short: "Delete the volumes attached to the server",
Default: core.DefaultValueSetter("none"),
EnumValues: []string{
string(withVolumesNone),
string(withVolumesLocal),
string(withVolumesBlock),
string(withVolumesRoot),
string(withVolumesAll),
},
},
{
Name: "with-ip",
Short: "Delete the IP attached to the server",
},
{
Name: "force-shutdown",
Short: "Force shutdown of the instance server before deleting it",
},
core.ZoneArgSpec(),
},
Examples: []*core.Example{
{
Short: "Delete a server in the default zone with a given id",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Delete a server in fr-par-1 zone with a given id",
ArgsJSON: `{"zone":"fr-par-1", "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
SeeAlsos: []*core.SeeAlso{
{
Command: "scw instance server terminate",
Short: "Terminate a running server",
},
{
Command: "scw instance server stop",
Short: "Stop a running server",
},
},
Run: func(ctx context.Context, argsI interface{}) (interface{}, error) {
deleteServerArgs := argsI.(*customDeleteServerRequest)
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
server, err := api.GetServer(&instance.GetServerRequest{
Zone: deleteServerArgs.Zone,
ServerID: deleteServerArgs.ServerID,
})
if err != nil {
return nil, err
}
if deleteServerArgs.ForceShutdown {
finalStateServer, err := api.WaitForServer(&instance.WaitForServerRequest{
Zone: deleteServerArgs.Zone,
ServerID: deleteServerArgs.ServerID,
Timeout: scw.TimeDurationPtr(serverActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
if err != nil {
return nil, err
}
if finalStateServer.State != instance.ServerStateStopped {
err = api.ServerActionAndWait(&instance.ServerActionAndWaitRequest{
Zone: deleteServerArgs.Zone,
ServerID: deleteServerArgs.ServerID,
Action: instance.ServerActionPoweroff,
Timeout: scw.TimeDurationPtr(serverActionTimeout),
RetryInterval: core.DefaultRetryInterval,
})
if err != nil {
return nil, err
}
}
}
err = api.DeleteServer(&instance.DeleteServerRequest{
Zone: deleteServerArgs.Zone,
ServerID: deleteServerArgs.ServerID,
})
if err != nil {
return nil, err
}
if deleteServerArgs.WithIP && server.Server.PublicIP != nil && !server.Server.PublicIP.Dynamic {
err = api.DeleteIP(&instance.DeleteIPRequest{
Zone: deleteServerArgs.Zone,
IP: server.Server.PublicIP.ID,
})
if err != nil {
return nil, err
}
_, _ = interactive.Printf("successfully deleted ip %s\n", server.Server.PublicIP.Address.String())
}
deletedVolumeMessages := [][2]string(nil)
for index, volume := range server.Server.Volumes {
switch {
case deleteServerArgs.WithVolumes == withVolumesNone:
break
case deleteServerArgs.WithVolumes == withVolumesRoot && index != "0":
continue
case deleteServerArgs.WithVolumes == withVolumesLocal && volume.VolumeType != instance.VolumeVolumeTypeLSSD:
continue
case deleteServerArgs.WithVolumes == withVolumesBlock && volume.VolumeType != instance.VolumeVolumeTypeBSSD:
continue
}
err = api.DeleteVolume(&instance.DeleteVolumeRequest{
Zone: deleteServerArgs.Zone,
VolumeID: volume.ID,
})
if err != nil {
return nil, &core.CliError{
Err: err,
Hint: "Make sure this resource have been deleted or try to delete it manually.",
}
}
humanSize, err := human.Marshal(volume.Size, nil)
if err != nil {
logger.Debugf("cannot marshal human size %v", volume.Size)
}
deletedVolumeMessages = append(deletedVolumeMessages, [2]string{
index,
fmt.Sprintf("successfully deleted volume %s (%s %s)", volume.Name, humanSize, volume.VolumeType),
})
}
// Sort and print deleted volume messages
sort.Slice(deletedVolumeMessages, func(i, j int) bool {
return deletedVolumeMessages[i][0] < deletedVolumeMessages[j][0]
})
for _, message := range deletedVolumeMessages {
_, _ = interactive.Println(message[1])
}
return &core.SuccessResult{}, nil
},
}
}
type customTerminateServerRequest struct {
Zone scw.Zone
ServerID string
WithIP bool
WithBlock withBlock
}
type withBlock string
const (
withBlockPrompt = withBlock("prompt")
withBlockTrue = withBlock("true")
withBlockFalse = withBlock("false")
)
func serverTerminateCommand() *core.Command {
return &core.Command{
Short: `Terminate server`,
Long: `Terminates a server with the given ID and all of its volumes.`,
Namespace: "instance",
Verb: "terminate",
Resource: "server",
ArgsType: reflect.TypeOf(customTerminateServerRequest{}),
ArgSpecs: core.ArgSpecs{
{
Name: "server-id",
Required: true,
Positional: true,
},
{
Name: "with-ip",
Short: "Delete the IP attached to the server",
},
{
Name: "with-block",
Short: "Delete the Block Storage volumes attached to the server",
Default: core.DefaultValueSetter("prompt"),
EnumValues: []string{
string(withBlockPrompt),
string(withBlockTrue),
string(withBlockFalse),
},
},
core.ZoneArgSpec(),
},
Examples: []*core.Example{
{
Short: "Terminate a server in the default zone with a given id",
ArgsJSON: `{"server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Terminate a server in fr-par-1 zone with a given id",
ArgsJSON: `{"zone":"fr-par-1", "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
{
Short: "Terminate a server and also delete its flexible IPs",
ArgsJSON: `{"with_ip":true, "server_id": "11111111-1111-1111-1111-111111111111"}`,
},
},
SeeAlsos: []*core.SeeAlso{
{
Command: "scw instance server delete",
Short: "delete a running server",
},
{
Command: "scw instance server stop",
Short: "Stop a running server",
},
},
Run: func(ctx context.Context, argsI interface{}) (interface{}, error) {
terminateServerArgs := argsI.(*customTerminateServerRequest)
client := core.ExtractClient(ctx)
api := instance.NewAPI(client)
server, err := api.GetServer(&instance.GetServerRequest{
Zone: terminateServerArgs.Zone,
ServerID: terminateServerArgs.ServerID,
})
if err != nil {
return nil, err
}
deleteBlockVolumes, err := shouldDeleteBlockVolumes(ctx, server, terminateServerArgs.WithBlock)
if err != nil {
return nil, err
}
if !deleteBlockVolumes {
// detach block storage volumes before terminating the instance to preserve them
for _, volume := range server.Server.Volumes {
if volume.VolumeType != instance.VolumeVolumeTypeBSSD {
continue
}
if _, err := api.DetachVolume(&instance.DetachVolumeRequest{
Zone: terminateServerArgs.Zone,
VolumeID: volume.ID,
}); err != nil {
return nil, err
}
_, _ = interactive.Printf("successfully detached volume %s\n", volume.Name)
}
}
if _, err := api.ServerAction(&instance.ServerActionRequest{
Zone: terminateServerArgs.Zone,
ServerID: terminateServerArgs.ServerID,
Action: instance.ServerActionTerminate,
}); err != nil {
return nil, err
}
if terminateServerArgs.WithIP && server.Server.PublicIP != nil && !server.Server.PublicIP.Dynamic {
err = api.DeleteIP(&instance.DeleteIPRequest{
Zone: terminateServerArgs.Zone,
IP: server.Server.PublicIP.ID,
})
if err != nil {
return nil, err
}
_, _ = interactive.Printf("successfully deleted ip %s\n", server.Server.PublicIP.Address.String())
}
return &core.SuccessResult{}, err
},
}
}
func shouldDeleteBlockVolumes(ctx context.Context, server *instance.GetServerResponse, terminateWithBlock withBlock) (bool, error) {
switch terminateWithBlock {
case withBlockTrue:
return true, nil
case withBlockFalse:
return false, nil
case withBlockPrompt:
// Only prompt user if at least one block volume is attached to the instance
for _, volume := range server.Server.Volumes {
if volume.VolumeType != instance.VolumeVolumeTypeBSSD {
continue
}
return interactive.PromptBoolWithConfig(&interactive.PromptBoolConfig{
Prompt: "Do you also want to delete block volumes attached to this instance ?",
DefaultValue: false,
Ctx: ctx,
})
}
return false, nil
default:
return false, fmt.Errorf("unsupported with-block value %v", terminateWithBlock)
}
}