forked from ucloud/ucloud-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuhost.go
More file actions
1620 lines (1515 loc) · 59.4 KB
/
Copy pathuhost.go
File metadata and controls
1620 lines (1515 loc) · 59.4 KB
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
// Copyright © 2018 NAME HERE tony.li@ucloud.cn
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"encoding/base64"
"fmt"
"io"
"regexp"
"strings"
"sync"
"time"
"github.com/spf13/cobra"
"github.com/ucloud/ucloud-sdk-go/services/uhost"
"github.com/ucloud/ucloud-sdk-go/services/unet"
sdk "github.com/ucloud/ucloud-sdk-go/ucloud"
"github.com/ucloud/ucloud-sdk-go/ucloud/request"
"github.com/ucloud/ucloud-cli/base"
"github.com/ucloud/ucloud-cli/model/cli"
"github.com/ucloud/ucloud-cli/model/status"
"github.com/ucloud/ucloud-cli/ux"
)
var uhostSpoller = base.NewSpoller(sdescribeUHostByID, base.Cxt.GetWriter())
//NewCmdUHost ucloud uhost
func NewCmdUHost() *cobra.Command {
cmd := &cobra.Command{
Use: "uhost",
Short: "List,create,delete,stop,restart,poweroff or resize UHost instance",
Long: `List,create,delete,stop,restart,poweroff or resize UHost instance`,
Args: cobra.NoArgs,
}
out := base.Cxt.GetWriter()
cmd.AddCommand(NewCmdUHostList(out))
cmd.AddCommand(NewCmdUHostCreate())
cmd.AddCommand(NewCmdUHostDelete(out))
cmd.AddCommand(NewCmdUHostStop(out))
cmd.AddCommand(NewCmdUHostStart(out))
cmd.AddCommand(NewCmdUHostReboot(out))
cmd.AddCommand(NewCmdUHostPoweroff(out))
cmd.AddCommand(NewCmdUHostResize(out))
cmd.AddCommand(NewCmdUHostClone(out))
cmd.AddCommand(NewCmdUhostResetPassword(out))
cmd.AddCommand(NewCmdUhostReinstallOS(out))
cmd.AddCommand(NewCmdUhostCreateImage(out))
cmd.AddCommand(NewCmdIsolation(out))
cmd.AddCommand(NewCmdUhostLeaveIsolationGroup(out))
return cmd
}
//UHostRow UHost表格行
type UHostRow struct {
UHostName string
Remark string
ResourceID string
Group string
PrivateIP string
PublicIP string
Config string
DiskSet string
Zone string
Image string
VPC string
Subnet string
Type string
State string
CreationTime string
}
func listUhost(uhosts []uhost.UHostInstanceSet, out io.Writer, output string) {
list := make([]UHostRow, 0)
for _, host := range uhosts {
row := UHostRow{}
row.UHostName = host.Name
row.Remark = host.Remark
row.ResourceID = host.UHostId
row.Group = host.Tag
for _, ip := range host.IPSet {
if row.PublicIP != "" {
row.PublicIP += " | "
}
if ip.Type == "Private" {
row.PrivateIP = ip.IP
row.VPC = ip.VPCId
row.Subnet = ip.SubnetId
} else {
row.PublicIP += fmt.Sprintf("%s", ip.IP)
}
}
cupCore := host.CPU
memorySize := host.Memory / 1024
diskSize := 0
var disks []string
for _, disk := range host.DiskSet {
if disk.Type == "Data" || disk.Type == "Udisk" {
diskSize += disk.Size
}
disks = append(disks, fmt.Sprintf("%s:%s:%dG", disk.Type, disk.DiskType, disk.Size))
}
row.Zone = host.Zone
row.DiskSet = strings.Join(disks, "|")
row.Config = fmt.Sprintf("cpu:%d memory:%dG disk:%dG", cupCore, memorySize, diskSize)
row.Image = fmt.Sprintf("%s|%s", host.BasicImageId, host.BasicImageName)
row.CreationTime = base.FormatDate(host.CreateTime)
row.State = host.State
row.Type = host.MachineType + "/" + host.HostType
if host.HotplugFeature {
row.Type += "/HotPlug"
}
list = append(list, row)
}
if global.JSON {
base.PrintJSON(list, out)
} else {
var cols []string
if output == "wide" {
cols = []string{"UHostName", "Remark", "ResourceID", "Group", "PrivateIP", "PublicIP", "Config", "DiskSet", "Zone", "Image", "VPC", "Subnet", "Type", "State", "CreationTime"}
} else {
cols = []string{"UHostName", "ResourceID", "Group", "PrivateIP", "PublicIP", "Config", "Image", "Type", "State", "CreationTime"}
}
base.PrintTable(list, cols)
}
}
func listUhostID(uhosts []uhost.UHostInstanceSet, out io.Writer) {
ids := make([]string, 0)
for _, u := range uhosts {
ids = append(ids, u.UHostId)
}
fmt.Fprintln(out, strings.Join(ids, ","))
}
func fetchUHosts(req *uhost.DescribeUHostInstanceRequest) ([]uhost.UHostInstanceSet, int, error) {
resp, err := base.BizClient.DescribeUHostInstance(req)
if err != nil {
return nil, 0, err
}
return resp.UHostSet, resp.TotalCount, nil
}
func fetchUHostsPageOff(req *uhost.DescribeUHostInstanceRequest) ([]uhost.UHostInstanceSet, error) {
_req := *req
result := make([]uhost.UHostInstanceSet, 0)
for limit, offset := 50, 0; ; offset += limit {
_req.Offset = sdk.Int(offset)
_req.Limit = sdk.Int(limit)
uhosts, total, err := fetchUHosts(&_req)
if err != nil {
return nil, err
}
result = append(result, uhosts...)
if offset+limit >= total {
break
}
}
return result, nil
}
func getAllUHosts(req *uhost.DescribeUHostInstanceRequest, pageOff bool, allRegion bool) ([]uhost.UHostInstanceSet, error) {
if allRegion {
result := make([]uhost.UHostInstanceSet, 0)
regions, err := getAllRegions()
if err != nil {
return nil, err
}
for _, region := range regions {
_req := *req
_req.Region = sdk.String(region)
//如果要获取所有region的主机,则不分页
uhosts, err := fetchUHostsPageOff(&_req)
if err != nil {
return nil, err
}
result = append(result, uhosts...)
}
return result, nil
}
if pageOff {
_req := *req
uhosts, err := fetchUHostsPageOff(&_req)
if err != nil {
return nil, err
}
return uhosts, nil
}
uhosts, _, err := fetchUHosts(req)
if err != nil {
return nil, err
}
return uhosts, nil
}
//NewCmdUHostList [ucloud uhost list]
func NewCmdUHostList(out io.Writer) *cobra.Command {
var allRegion, pageOff, idOnly bool
var output string
var uhostIds []string
req := base.BizClient.NewDescribeUHostInstanceRequest()
cmd := &cobra.Command{
Use: "list",
Short: "List all UHost Instances",
Long: `List all UHost Instances`,
Run: func(cmd *cobra.Command, args []string) {
*req.VPCId = base.PickResourceID(*req.VPCId)
*req.SubnetId = base.PickResourceID(*req.SubnetId)
*req.IsolationGroup = base.PickResourceID(*req.IsolationGroup)
for _, uhost := range uhostIds {
req.UHostIds = append(req.UHostIds, base.PickResourceID(uhost))
}
uhosts, err := getAllUHosts(req, pageOff, allRegion)
if err != nil {
base.HandleError(err)
return
}
if idOnly {
listUhostID(uhosts, out)
} else {
listUhost(uhosts, out, output)
}
},
}
cmd.Flags().SortFlags = false
req.ProjectId = cmd.Flags().String("project-id", base.ConfigIns.ProjectID, "Optional. Assign project-id")
req.Region = cmd.Flags().String("region", base.ConfigIns.Region, "Optional. Assign region.")
req.Zone = cmd.Flags().String("zone", "", "Optional. Assign availability zone")
req.Offset = cmd.Flags().Int("offset", 0, "Optional. Offset default 0")
req.Limit = cmd.Flags().Int("limit", 50, "Optional. Limit default 50, max value 100")
req.VPCId = cmd.Flags().String("vpc-id", "", "Optional. Resource ID of VPC. List uhost instances of the specified VPC")
req.SubnetId = cmd.Flags().String("subnet-id", "", "Optional. Resource ID of Subnet. List uhost instances of the specified Subnet")
req.IsolationGroup = cmd.Flags().String("isolation-group", "", "Optional. Resource ID of isolation group. List uhost instances of the specified isolation group")
cmd.Flags().StringSliceVar(&uhostIds, "uhost-id", make([]string, 0), "Optional. Resource ID of uhost instances, multiple values separated by comma(without space)")
cmd.Flags().BoolVar(&allRegion, "all-region", false, "Optional. Accpet values: true or false. List uhost instances of all regions when assigned true")
cmd.Flags().BoolVar(&pageOff, "page-off", false, "Optional. Paging or not. If all-region is specified this flag will be true. Accept values: true or false. If assigned, the limit flag will be disabled and list all uhost instances")
cmd.Flags().BoolVar(&idOnly, "uhost-id-only", false, "Optional. Just display resource id of uhost")
cmd.Flags().StringVarP(&output, "output", "o", "", "Optional. Accept values: wide. Display more information about uhost such as DiskSet and Zone")
bindGroup(req, cmd.Flags())
cmd.Flags().SetFlagValues("page-off", "true", "false")
cmd.Flags().SetFlagValues("uhost-id-only", "true", "false")
cmd.Flags().SetFlagValues("output", "wide")
cmd.Flags().SetFlagValuesFunc("project-id", getProjectList)
cmd.Flags().SetFlagValuesFunc("region", getRegionList)
cmd.Flags().SetFlagValuesFunc("zone", func() []string {
return getZoneList(req.GetRegion())
})
flags := cmd.Flags()
flags.SetFlagValuesFunc("vpc-id", func() []string {
return getAllVPCIdNames(*req.ProjectId, *req.Region)
})
flags.SetFlagValuesFunc("subnet-id", func() []string {
return getAllSubnetIDNames(*req.VPCId, *req.ProjectId, *req.Region)
})
flags.SetFlagValuesFunc("isolation-group", func() []string {
return getIsolationGroupList(*req.ProjectId, *req.Region)
})
flags.SetFlagValuesFunc("uhost-id", func() []string {
return getUhostList(nil, *req.ProjectId, *req.Region, *req.Zone)
})
return cmd
}
//NewCmdUHostCreate [ucloud uhost create]
func NewCmdUHostCreate() *cobra.Command {
var bindEipIDs []string
var hotPlug string
var async bool
var count int
var hotPlugImageFlag bool
req := base.BizClient.NewCreateUHostInstanceRequest()
eipReq := base.BizClient.NewAllocateEIPRequest()
cmd := &cobra.Command{
Use: "create",
Short: "Create UHost instance",
Long: "Create UHost instance",
Run: func(cmd *cobra.Command, args []string) {
*req.Memory *= 1024
req.LoginMode = sdk.String("Password")
req.ImageId = sdk.String(base.PickResourceID(*req.ImageId))
req.VPCId = sdk.String(base.PickResourceID(*req.VPCId))
req.SubnetId = sdk.String(base.PickResourceID(*req.SubnetId))
req.SecurityGroupId = sdk.String(base.PickResourceID(*req.SecurityGroupId))
req.IsolationGroup = sdk.String(base.PickResourceID(*req.IsolationGroup))
if hotPlug == "true" {
req.HotplugFeature = sdk.Bool(true)
any, err := describeImageByID(*req.ImageId, *req.ProjectId, *req.Region, *req.Zone)
if err != nil {
base.LogError(fmt.Sprintf("check image support hot-plug failed: %v", err))
} else {
image, ok := any.(*uhost.UHostImageSet)
if !ok {
base.LogError(fmt.Sprintf("check image support hot-plug failed, image %s may not exist", *req.ImageId))
}
for _, feature := range image.Features {
if feature == "HotPlug" {
hotPlugImageFlag = true
}
}
}
if !hotPlugImageFlag {
base.LogWarn(fmt.Sprintf("warning. image %s does not support hot-plug", *req.ImageId))
req.HotplugFeature = sdk.Bool(false)
}
}
wg := &sync.WaitGroup{}
tokens := make(chan struct{}, 20)
wg.Add(count)
if count <= 5 {
for i := 0; i < count; i++ {
bindEipID := ""
if len(bindEipIDs) > i {
bindEipID = bindEipIDs[i]
}
go createUhostWrapper(req, eipReq, bindEipID, async, make(chan bool, count), wg, tokens, i)
}
} else {
retCh := make(chan bool, count)
ux.Doc.Disable()
refresh := ux.NewRefresh()
go func() {
for i := 0; i < count; i++ {
bindEipID := ""
if len(bindEipIDs) > i {
bindEipID = bindEipIDs[i]
}
go createUhostWrapper(req, eipReq, bindEipID, async, retCh, wg, tokens, i)
}
}()
go func() {
var success, fail int
refresh.Do(fmt.Sprintf("uhost creating, total:%d, success:%d, fail:%d", count, success, fail))
for ret := range retCh {
if ret {
success++
} else {
fail++
}
refresh.Do(fmt.Sprintf("uhost creating, total:%d, success:%d, fail:%d", count, success, fail))
if count == success+fail && fail > 0 {
fmt.Printf("Check logs in %s\n", base.GetLogFilePath())
}
}
}()
}
wg.Wait()
},
}
req.Disks = make([]uhost.UHostDisk, 2)
req.Disks[0].IsBoot = sdk.String("True")
req.Disks[1].IsBoot = sdk.String("False")
flags := cmd.Flags()
flags.SortFlags = false
req.CPU = flags.Int("cpu", 4, "Required. The count of CPU cores. Optional parameters: {1, 2, 4, 8, 12, 16, 24, 32}")
req.Memory = flags.Int("memory-gb", 8, "Required. Memory size. Unit: GB. Range: [1, 128], multiple of 2")
req.Password = flags.String("password", "", "Required. Password of the uhost user(root/ubuntu)")
req.ImageId = flags.String("image-id", "", "Required. The ID of image. see 'ucloud image list'")
flags.BoolVar(&async, "async", false, "Optional. Do not wait for the long-running operation to finish.")
flags.IntVar(&count, "count", 1, "Optional. Number of uhost to create.")
req.VPCId = flags.String("vpc-id", "", "Optional. VPC ID. This field is required under VPC2.0. See 'ucloud vpc list'")
req.SubnetId = flags.String("subnet-id", "", "Optional. Subnet ID. This field is required under VPC2.0. See 'ucloud subnet list'")
req.Name = flags.String("name", "UHost", "Optional. UHost instance name")
flags.StringSliceVar(&bindEipIDs, "bind-eip", nil, "Optional. Resource ID or IP Address of eip that will be bound to the new created uhost")
eipReq.OperatorName = flags.String("create-eip-line", "", "Optional. BGP for regions in the chinese mainland and International for overseas regions")
eipReq.Bandwidth = flags.Int("create-eip-bandwidth-mb", 0, "Optional. Required if you want to create new EIP. Bandwidth(Unit:Mbps).The range of value related to network charge mode. By traffic [1, 300]; by bandwidth [1,800] (Unit: Mbps); it could be 0 if the eip belong to the shared bandwidth")
eipReq.PayMode = flags.String("create-eip-traffic-mode", "Bandwidth", "Optional. 'Traffic','Bandwidth' or 'ShareBandwidth'")
eipReq.ShareBandwidthId = flags.String("shared-bw-id", "", "Optional. Resource ID of shared bandwidth. It takes effect when create-eip-traffic-mode is ShareBandwidth ")
eipReq.Name = flags.String("create-eip-name", "", "Optional. Name of created eip to bind with the uhost")
eipReq.Remark = flags.String("create-eip-remark", "", "Optional.Remark of your EIP.")
req.ChargeType = flags.String("charge-type", "Month", "Optional.'Year',pay yearly;'Month',pay monthly;'Dynamic', pay hourly")
req.Quantity = flags.Int("quantity", 1, "Optional. The duration of the instance. N years/months.")
bindProjectID(req, flags)
bindRegion(req, flags)
bindZone(req, flags)
req.MachineType = flags.String("machine-type", "", "Optional. Accept values: N, C, G, O. Forward to https://docs.ucloud.cn/api/uhost-api/uhost_type for details")
req.MinimalCpuPlatform = flags.String("minimal-cpu-platform", "", "Optional. Accpet values: Intel/Auto, Intel/IvyBridge, Intel/Haswell, Intel/Broadwell, Intel/Skylake, Intel/Cascadelake")
req.UHostType = flags.String("type", "", "Optional. Accept values: N1, N2, N3, G1, G2, G3, I1, I2, C1. Forward to https://docs.ucloud.cn/api/uhost-api/uhost_type for details")
req.GPU = flags.Int("gpu", 0, "Optional. The count of GPU cores.")
req.NetCapability = flags.String("net-capability", "Normal", "Optional. Default is 'Normal', also support 'Super' which will enhance multiple times network capability as before")
flags.StringVar(&hotPlug, "hot-plug", "true", "Optional. Enable hot plug feature or not. Accept values: true or false")
req.Disks[0].Type = flags.String("os-disk-type", "CLOUD_SSD", "Optional. Enumeration value. 'LOCAL_NORMAL', Ordinary local disk; 'CLOUD_NORMAL', Ordinary cloud disk; 'LOCAL_SSD',local ssd disk; 'CLOUD_SSD',cloud ssd disk; 'EXCLUSIVE_LOCAL_DISK',big data. The disk only supports a limited combination.")
req.Disks[0].Size = flags.Int("os-disk-size-gb", 20, "Optional. Default 20G. Windows should be bigger than 40G Unit GB")
req.Disks[0].BackupType = flags.String("os-disk-backup-type", "NONE", "Optional. Enumeration value, 'NONE' or 'DATAARK'. DataArk supports real-time backup, which can restore the disk back to any moment within the last 12 hours. (Normal Local Disk and Normal Cloud Disk Only)")
req.Disks[1].Type = flags.String("data-disk-type", "CLOUD_SSD", "Optional. Enumeration value. 'LOCAL_NORMAL', Ordinary local disk; 'CLOUD_NORMAL', Ordinary cloud disk; 'LOCAL_SSD',local ssd disk; 'CLOUD_SSD',cloud ssd disk; 'EXCLUSIVE_LOCAL_DISK',big data. The disk only supports a limited combination.")
req.Disks[1].Size = flags.Int("data-disk-size-gb", 20, "Optional. Disk size. Unit GB")
req.Disks[1].BackupType = flags.String("data-disk-backup-type", "NONE", "Optional. Enumeration value, 'NONE' or 'DATAARK'. DataArk supports real-time backup, which can restore the disk back to any moment within the last 12 hours. (Normal Local Disk and Normal Cloud Disk Only)")
req.SecurityGroupId = flags.String("firewall-id", "", "Optional. Firewall Id, default: Web recommended firewall. see 'ucloud firewall list'.")
req.Tag = flags.String("group", "Default", "Optional. Business group")
req.IsolationGroup = flags.String("isolation-group", "", "Optional. Resource ID of isolation group. see 'ucloud uhost isolation-group list")
flags.MarkDeprecated("type", "please use --machine-type instead")
flags.SetFlagValues("charge-type", "Month", "Year", "Dynamic", "Trial")
flags.SetFlagValues("hot-plug", "true", "false")
flags.SetFlagValues("cpu", "1", "2", "4", "8", "12", "16", "24", "32")
flags.SetFlagValues("type", "N2", "N1", "N3", "I2", "I1", "C1", "G1", "G2", "G3")
flags.SetFlagValues("machine-type", "N", "C", "G", "O")
flags.SetFlagValues("minimal-cpu-platform", "Intel/Auto", "Intel/IvyBridge", "Intel/Haswell", "Intel/Broadwell", "Intel/Skylake", "Intel/Cascadelake")
flags.SetFlagValues("net-capability", "Normal", "Super")
flags.SetFlagValues("os-disk-type", "LOCAL_NORMAL", "CLOUD_NORMAL", "LOCAL_SSD", "CLOUD_SSD", "CLOUD_RSSD", "EXCLUSIVE_LOCAL_DISK")
flags.SetFlagValues("os-disk-backup-type", "NONE", "DATAARK")
flags.SetFlagValues("data-disk-type", "LOCAL_NORMAL", "CLOUD_NORMAL", "LOCAL_SSD", "CLOUD_SSD", "EXCLUSIVE_LOCAL_DISK")
flags.SetFlagValues("data-disk-backup-type", "NONE", "DATAARK")
flags.SetFlagValues("create-eip-line", "BGP", "International")
flags.SetFlagValues("create-eip-traffic-mode", "Bandwidth", "Traffic", "ShareBandwidth")
flags.SetFlagValuesFunc("image-id", func() []string {
return getImageList([]string{status.IMAGE_AVAILABLE}, cli.IMAGE_BASE, *req.ProjectId, *req.Region, *req.Zone)
})
flags.SetFlagValuesFunc("vpc-id", func() []string {
return getAllVPCIdNames(*req.ProjectId, *req.Region)
})
flags.SetFlagValuesFunc("bind-eip", func() []string {
return getAllEip(*req.ProjectId, *req.Region, []string{status.EIP_FREE}, nil)
})
flags.SetFlagValuesFunc("firewall-id", func() []string {
return getFirewallIDNames(*req.ProjectId, *req.Region)
})
flags.SetFlagValuesFunc("subnet-id", func() []string {
return getAllSubnetIDNames(*req.VPCId, *req.ProjectId, *req.Region)
})
flags.SetFlagValuesFunc("isolation-group", func() []string {
return getIsolationGroupList(*req.ProjectId, *req.Region)
})
cmd.MarkFlagRequired("cpu")
cmd.MarkFlagRequired("memory-gb")
cmd.MarkFlagRequired("password")
cmd.MarkFlagRequired("image-id")
return cmd
}
//createUhostWrapper 处理UI和并发控制
func createUhostWrapper(req *uhost.CreateUHostInstanceRequest, eipReq *unet.AllocateEIPRequest, bindEipID string, async bool, retCh chan<- bool, wg *sync.WaitGroup, tokens chan struct{}, idx int) {
//控制并发数量
tokens <- struct{}{}
defer func() {
<-tokens
//设置延时,使报错能渲染出来
time.Sleep(time.Second / 5)
wg.Done()
}()
success, logs := createUhost(req, eipReq, bindEipID, async)
retCh <- success
logs = append(logs, fmt.Sprintf("index:%d, result:%t", idx, success))
base.LogInfo(logs...)
}
func createUhost(req *uhost.CreateUHostInstanceRequest, eipReq *unet.AllocateEIPRequest, bindEipID string, async bool) (bool, []string) {
resp, err := base.BizClient.CreateUHostInstance(req)
block := ux.NewBlock()
ux.Doc.Append(block)
logs := []string{"=================================================="}
logs = append(logs, fmt.Sprintf("api:CreateUHostInstance, request:%v", base.ToQueryMap(req)))
if err != nil {
logs = append(logs, fmt.Sprintf("err:%v", err))
block.Append(base.ParseError(err))
return false, logs
}
logs = append(logs, fmt.Sprintf("resp:%#v", resp))
if len(resp.UHostIds) != 1 {
block.Append(fmt.Sprintf("expect uhost count 1 , accept %d", len(resp.UHostIds)))
return false, logs
}
text := fmt.Sprintf("uhost[%s] is initializing", resp.UHostIds[0])
if async {
block.Append(text)
} else {
uhostSpoller.Sspoll(resp.UHostIds[0], text, []string{status.HOST_RUNNING, status.HOST_FAIL}, block)
}
if bindEipID != "" {
eip := base.PickResourceID(bindEipID)
logs = append(logs, fmt.Sprintf("bind eip: %s", eip))
eipLogs, err := sbindEIP(sdk.String(resp.UHostIds[0]), sdk.String("uhost"), &eip, req.ProjectId, req.Region)
logs = append(logs, eipLogs...)
if err != nil {
block.Append(fmt.Sprintf("bind eip[%s] with uhost[%s] failed: %v", eip, resp.UHostIds[0], err))
return false, logs
}
block.Append(fmt.Sprintf("bind eip[%s] with uhost[%s] successfully", eip, resp.UHostIds[0]))
} else if *eipReq.Bandwidth != 0 {
eipReq.ChargeType = req.ChargeType
eipReq.Tag = req.Tag
eipReq.Quantity = req.Quantity
eipReq.Region = req.Region
eipReq.ProjectId = req.ProjectId
logs = append(logs, fmt.Sprintf("create eip request: %v", base.ToQueryMap(eipReq)))
if *eipReq.OperatorName == "" {
*eipReq.OperatorName = getEIPLine(*req.Region)
}
eipResp, err := base.BizClient.AllocateEIP(eipReq)
if err != nil {
logs = append(logs, fmt.Sprintf("create eip error: %#v", err))
block.Append(base.ParseError(err))
} else {
logs = append(logs, fmt.Sprintf("create eip resp: %#v", eipResp))
for _, eip := range eipResp.EIPSet {
block.Append(fmt.Sprintf("allocate EIP[%s] ", eip.EIPId))
for _, ip := range eip.EIPAddr {
block.Append(fmt.Sprintf("IP:%s Line:%s", ip.IP, ip.OperatorName))
}
if len(resp.UHostIds) == 1 {
eipLogs, err := sbindEIP(sdk.String(resp.UHostIds[0]), sdk.String("uhost"), sdk.String(eip.EIPId), req.ProjectId, req.Region)
logs = append(logs, eipLogs...)
if err != nil {
block.Append(fmt.Sprintf("bind eip[%s] with uhost[%s] failed: %v", eip, resp.UHostIds[0], err))
return false, logs
}
block.Append(fmt.Sprintf("bind eip[%s] with uhost[%s] successfully", eip, resp.UHostIds[0]))
}
}
}
}
return true, logs
}
//NewCmdUHostDelete ucloud uhost delete
func NewCmdUHostDelete(out io.Writer) *cobra.Command {
var uhostIDs *[]string
var isDestroy = sdk.Bool(false)
var yes *bool
req := base.BizClient.NewTerminateUHostInstanceRequest()
cmd := &cobra.Command{
Use: "delete",
Short: "Delete Uhost instance",
Long: "Delete Uhost instance",
Run: func(cmd *cobra.Command, args []string) {
if !*yes {
sure, err := ux.Prompt("Are you sure you want to delete the host(s)?")
if err != nil {
base.Cxt.Println(err)
return
}
if !sure {
return
}
}
if *isDestroy {
req.Destroy = sdk.Int(1)
} else {
req.Destroy = sdk.Int(0)
}
reqs := make([]request.Common, len(*uhostIDs))
for idx, id := range *uhostIDs {
_req := *req
id = base.PickResourceID(id)
_req.UHostId = sdk.String(id)
reqs[idx] = &_req
}
coAction := newConcurrentAction(reqs, 50, deleteUHost)
coAction.Do()
},
}
flags := cmd.Flags()
flags.SortFlags = false
uhostIDs = cmd.Flags().StringSlice("uhost-id", nil, "Requried. ResourceIDs(UhostIds) of the uhost instance")
bindRegion(req, flags)
bindProjectID(req, flags)
req.Zone = cmd.Flags().String("zone", "", "Optional. availability zone")
isDestroy = cmd.Flags().Bool("destroy", false, "Optional. false,the uhost instance will be thrown to UHost recycle if you have permission; true,the uhost instance will be deleted directly")
req.ReleaseEIP = cmd.Flags().Bool("release-eip", true, "Optional. false,Unbind EIP only; true, Unbind EIP and release it")
req.ReleaseUDisk = cmd.Flags().Bool("delete-cloud-disk", true, "Optional. false, detach cloud disk only; true, detach cloud disk and delete it")
yes = cmd.Flags().BoolP("yes", "y", false, "Optional. Do not prompt for confirmation.")
cmd.Flags().SetFlagValues("destroy", "true", "false")
cmd.Flags().SetFlagValues("release-eip", "true", "false")
cmd.Flags().SetFlagValues("delete-cloud-disk", "true", "false")
cmd.Flags().SetFlagValuesFunc("uhost-id", func() []string {
return getUhostList([]string{status.HOST_RUNNING, status.HOST_STOPPED, status.HOST_FAIL}, *req.ProjectId, *req.Region, *req.Zone)
})
cmd.MarkFlagRequired("uhost-id")
return cmd
}
func deleteUHost(creq request.Common) (bool, []string) {
req := creq.(*uhost.TerminateUHostInstanceRequest)
block := ux.NewBlock()
ux.Doc.Append(block)
logs := []string{}
hostIns, err := sdescribeUHostByID(*req.UHostId)
if err != nil {
logs = append(logs, fmt.Sprintf("describe uhost[%s] failed: %s", *req.UHostId, base.ParseError(err)))
return false, logs
}
if hostIns == nil {
logs = append(logs, fmt.Sprintf("uhost[%s] does not exist", *req.UHostId))
return false, logs
}
ins := hostIns.(*uhost.UHostInstanceSet)
if ins.State == "Running" {
_req := base.BizClient.NewStopUHostInstanceRequest()
_req.ProjectId = req.ProjectId
_req.Region = req.Region
_req.Zone = req.Zone
_req.UHostId = req.UHostId
stopUhostInsV2(_req, false, block)
}
logs = append(logs, fmt.Sprintf("api:TerminateUHostInstance, request:%v", base.ToQueryMap(req)))
resp, err := base.BizClient.TerminateUHostInstance(req)
if err != nil {
block.Append(base.ParseError(err))
logs = append(logs, fmt.Sprintf("delete uhost[%s] failed: %s", *req.UHostId, base.ParseError(err)))
return false, logs
}
text := fmt.Sprintf("uhost[%s] deleted", resp.UHostId)
logs = append(logs, text)
block.Append(text)
return true, logs
}
//NewCmdUHostStop ucloud uhost stop
func NewCmdUHostStop(out io.Writer) *cobra.Command {
var uhostIDs *[]string
var async *bool
req := base.BizClient.NewStopUHostInstanceRequest()
cmd := &cobra.Command{
Use: "stop",
Short: "Shut down uhost instance",
Long: "Shut down uhost instance",
Example: "ucloud uhost stop --uhost-id uhost-xxx1,uhost-xxx2",
Run: func(cmd *cobra.Command, args []string) {
for _, id := range *uhostIDs {
id = base.PickResourceID(id)
req.UHostId = &id
stopUhostIns(req, *async, out)
}
},
}
cmd.Flags().SortFlags = false
uhostIDs = cmd.Flags().StringSlice("uhost-id", nil, "Required. ResourceIDs(UHostIds) of the uhost instances")
req.ProjectId = cmd.Flags().String("project-id", base.ConfigIns.ProjectID, "Optional. Assign project-id")
req.Region = cmd.Flags().String("region", base.ConfigIns.Region, "Optional. Assign region")
req.Zone = cmd.Flags().String("zone", "", "Optional. Assign availability zone")
async = cmd.Flags().Bool("async", false, "Optional. Do not wait for the long-running operation to finish.")
cmd.Flags().SetFlagValuesFunc("uhost-id", func() []string {
return getUhostList([]string{status.HOST_RUNNING}, *req.ProjectId, *req.Region, *req.Zone)
})
cmd.MarkFlagRequired("uhost-id")
return cmd
}
func promptStopUhostIns(req *uhost.StopUHostInstanceRequest, yes, async bool, promptText string, out io.Writer) bool {
if !yes {
agreeClose, err := ux.Prompt(promptText)
if err != nil {
base.LogError(err.Error())
return false
}
if !agreeClose {
return false
}
}
return stopUhostIns(req, false, out)
}
func stopUhostIns(req *uhost.StopUHostInstanceRequest, async bool, out io.Writer) bool {
resp, err := base.BizClient.StopUHostInstance(req)
if err != nil {
base.HandleError(err)
return false
}
text := fmt.Sprintf("uhost [%v] is shutting down", resp.UhostId)
if async {
fmt.Fprintln(out, text)
return false
}
poller := base.NewPoller(describeUHostByID, out)
return poller.Poll(resp.UhostId, *req.ProjectId, *req.Region, *req.Zone, text, []string{status.HOST_STOPPED, status.HOST_FAIL})
}
//可并发调用版本
func stopUhostInsV2(req *uhost.StopUHostInstanceRequest, async bool, block *ux.Block) {
resp, err := base.BizClient.StopUHostInstance(req)
if err != nil {
block.Append(base.ParseError(err))
return
}
text := fmt.Sprintf("uhost[%v] is shutting down", resp.UhostId)
if async {
block.Append(text)
} else {
uhostSpoller.Sspoll(resp.UhostId, text, []string{status.HOST_STOPPED, status.HOST_FAIL}, block)
}
}
//NewCmdUHostStart ucloud uhost start
func NewCmdUHostStart(out io.Writer) *cobra.Command {
var async *bool
var uhostIDs *[]string
req := base.BizClient.NewStartUHostInstanceRequest()
cmd := &cobra.Command{
Use: "start",
Short: "Start Uhost instance",
Long: "Start Uhost instance",
Example: "ucloud uhost start --uhost-id uhost-xxx1,uhost-xxx2",
Run: func(cmd *cobra.Command, args []string) {
for _, id := range *uhostIDs {
id := base.PickResourceID(id)
req.UHostId = &id
resp, err := base.BizClient.StartUHostInstance(req)
if err != nil {
base.HandleError(err)
} else {
text := fmt.Sprintf("uhost[%v] is starting", resp.UhostId)
if *async {
fmt.Fprintln(out, text)
} else {
poller := base.NewPoller(describeUHostByID, out)
poller.Poll(resp.UhostId, *req.ProjectId, *req.Region, *req.Zone, text, []string{status.HOST_RUNNING, status.HOST_FAIL})
}
}
}
},
}
cmd.Flags().SortFlags = false
uhostIDs = cmd.Flags().StringSlice("uhost-id", nil, "Requried. ResourceIDs(UHostIds) of the uhost instance")
req.ProjectId = cmd.Flags().String("project-id", base.ConfigIns.ProjectID, "Optional. Assign project-id")
req.Region = cmd.Flags().String("region", base.ConfigIns.Region, "Optional. Assign region")
req.Zone = cmd.Flags().String("zone", "", "Optional. Assign availability zone")
async = cmd.Flags().Bool("async", false, "Optional. Do not wait for the long-running operation to finish.")
cmd.Flags().SetFlagValuesFunc("uhost-id", func() []string {
return getUhostList([]string{status.HOST_STOPPED}, *req.ProjectId, *req.Region, *req.Zone)
})
cmd.MarkFlagRequired("uhost-id")
return cmd
}
//NewCmdUHostReboot ucloud uhost restart
func NewCmdUHostReboot(out io.Writer) *cobra.Command {
var uhostIDs *[]string
var async *bool
req := base.BizClient.NewRebootUHostInstanceRequest()
cmd := &cobra.Command{
Use: "restart",
Short: "Restart uhost instance",
Long: "Restart uhost instance",
Example: "ucloud uhost restart --uhost-id uhost-xxx1,uhost-xxx2",
Run: func(cmd *cobra.Command, args []string) {
for _, id := range *uhostIDs {
id = base.PickResourceID(id)
req.UHostId = &id
resp, err := base.BizClient.RebootUHostInstance(req)
if err != nil {
base.HandleError(err)
} else {
text := fmt.Sprintf("uhost[%v] is restarting", resp.UhostId)
if *async {
fmt.Fprintln(out, text)
} else {
poller := base.NewPoller(describeUHostByID, out)
poller.Poll(resp.UhostId, *req.ProjectId, *req.Region, *req.Zone, text, []string{status.HOST_RUNNING, status.HOST_FAIL})
}
}
}
},
}
cmd.Flags().SortFlags = false
uhostIDs = cmd.Flags().StringSlice("uhost-id", nil, "Required. ResourceIDs(UHostIds) of the uhost instance")
req.ProjectId = cmd.Flags().String("project-id", base.ConfigIns.ProjectID, "Optional. Assign project-id")
req.Region = cmd.Flags().String("region", base.ConfigIns.Region, "Optional. Assign region")
req.Zone = cmd.Flags().String("zone", "", "Optional. Assign availability zone")
req.DiskPassword = cmd.Flags().String("disk-password", "", "Optional. Encrypted disk password")
async = cmd.Flags().Bool("async", false, "Optional. Do not wait for the long-running operation to finish.")
cmd.Flags().SetFlagValuesFunc("uhost-id", func() []string {
return getUhostList([]string{status.HOST_FAIL, status.HOST_RUNNING, status.HOST_STOPPED}, *req.ProjectId, *req.Region, *req.Zone)
})
cmd.MarkFlagRequired("uhost-id")
return cmd
}
//NewCmdUHostPoweroff ucloud uhost poweroff
func NewCmdUHostPoweroff(out io.Writer) *cobra.Command {
var yes *bool
var uhostIDs *[]string
req := base.BizClient.NewPoweroffUHostInstanceRequest()
cmd := &cobra.Command{
Use: "poweroff",
Short: "Analog power off Uhost instnace",
Long: "Analog power off Uhost instnace",
Example: "ucloud uhost poweroff --uhost-id uhost-xxx1,uhost-xxx2",
Run: func(cmd *cobra.Command, args []string) {
if !*yes {
confirmText := "Danger, it may affect data integrity. Are you sure you want to poweroff this uhost?"
if len(*uhostIDs) > 1 {
confirmText = "Danger, it may affect data integrity. Are you sure you want to poweroff those uhosts?"
}
sure, err := ux.Prompt(confirmText)
if err != nil {
fmt.Fprintln(out, err)
return
}
if !sure {
return
}
}
for _, id := range *uhostIDs {
id = base.PickResourceID(id)
req.UHostId = &id
resp, err := base.BizClient.PoweroffUHostInstance(req)
if err != nil {
base.HandleError(err)
} else {
fmt.Fprintf(out, "uhost[%v] is power off\n", resp.UhostId)
}
}
},
}
cmd.Flags().SortFlags = false
uhostIDs = cmd.Flags().StringSlice("uhost-id", nil, "ResourceIDs(UHostIds) of the uhost instance")
req.ProjectId = cmd.Flags().String("project-id", base.ConfigIns.ProjectID, "Assign project-id")
req.Region = cmd.Flags().String("region", base.ConfigIns.Region, "Assign region")
req.Zone = cmd.Flags().String("zone", "", "Assign availability zone")
yes = cmd.Flags().BoolP("yes", "y", false, "Optional. Do not prompt for confirmation.")
cmd.Flags().SetFlagValuesFunc("uhost-id", func() []string {
return getUhostList([]string{status.HOST_FAIL, status.HOST_RUNNING, status.HOST_STOPPED}, *req.ProjectId, *req.Region, *req.Zone)
})
cmd.MarkFlagRequired("uhost-id")
return cmd
}
func resizeAttachedDisk(out io.Writer, req *uhost.ResizeAttachedDiskRequest, host *uhost.UHostInstanceSet, yes, async bool, promptText string) error {
req.UHostId = &host.UHostId
if host.State == status.HOST_RUNNING {
err := tryStopUhost(req, host.UHostId, promptText, yes, async, out)
if err != nil {
return fmt.Errorf("try to stop uhost error :%w", err)
}
}
req.DryRun = sdk.Bool(false)
_, err := base.BizClient.ResizeAttachedDisk(req)
if err != nil {
return err
}
text := fmt.Sprintf("uhost [%s] disk [%s] resize", host.UHostId, *req.DiskId)
if async {
fmt.Fprintln(out, text)
} else {
poller := base.NewPoller(describeUHostByID, out)
poller.Poll(host.UHostId, *req.ProjectId, *req.Region, *req.Zone, text, []string{status.HOST_RUNNING, status.HOST_STOPPED, status.HOST_FAIL})
}
return nil
}
func tryStopUhost(req *uhost.ResizeAttachedDiskRequest, uhostID, promptText string, yes, async bool, out io.Writer) error {
req.DryRun = sdk.Bool(true)
resp, err := base.BizClient.ResizeAttachedDisk(req)
if err != nil {
return err
}
if resp.NeedRestart {
stopReq := base.BizClient.NewStopUHostInstanceRequest()
stopReq.UHostId = &uhostID
promptStopUhostIns(stopReq, yes, async, promptText, out)
}
return nil
}
//NewCmdUHostResize ucloud uhost resize
func NewCmdUHostResize(out io.Writer) *cobra.Command {
var yes, async *bool
var bootDiskSize, dataDiskSize int
var dataDiskID string
var uhostIDs *[]string
req := base.BizClient.NewResizeUHostInstanceRequest()
cmd := &cobra.Command{
Use: "resize",
Short: "Resize uhost instance,such as cpu core count, memory size and disk size",
Long: "Resize uhost instance,such as cpu core count, memory size and disk size",
Example: "ucloud uhost resize --uhost-id uhost-xxx1,uhost-xxx2 --cpu 4 --memory-gb 8",
Run: func(cmd *cobra.Command, args []string) {
if *req.CPU == 0 {
req.CPU = nil
}
if *req.Memory == 0 {
req.Memory = nil
} else {
*req.Memory *= 1024
}
for _, id := range *uhostIDs {
id = base.PickResourceID(id)
req.UHostId = &id
host, err := describeUHostByID(id, *req.ProjectId, *req.Region, *req.Zone)
if err != nil {
base.Cxt.Println(err)
return
}
inst := host.(*uhost.UHostInstanceSet)
stopReq := base.BizClient.NewStopUHostInstanceRequest()
stopReq.ProjectId = req.ProjectId
stopReq.Region = req.Region
stopReq.Zone = req.Zone
stopReq.UHostId = &id
confirmText := "Resize uhost must be done after the uhost is stopped. Do you want to stop this uhost?"
if req.CPU != nil || req.Memory != nil || *req.NetCapValue != 0 {
if inst.State == status.HOST_RUNNING {
ret := promptStopUhostIns(stopReq, *yes, *async, confirmText, out)
if ret {
inst.State = status.HOST_STOPPED
}
}
resp, err := base.BizClient.ResizeUHostInstance(req)
if err != nil {
base.HandleError(err)
} else {
text := fmt.Sprintf("uhost [%v] cpu, memory resize", resp.UhostId)
if *async {
fmt.Fprintln(out, text)
} else {
poller := base.NewPoller(describeUHostByID, out)
poller.Poll(resp.UhostId, *req.ProjectId, *req.Region, *req.Zone, text, []string{status.HOST_RUNNING, status.HOST_STOPPED, status.HOST_FAIL})
}
}
}
if dataDiskSize != 0 || bootDiskSize != 0 {
_req := base.BizClient.NewResizeAttachedDiskRequest()
var bootDisk uhost.UHostDiskSet
var dataDisks = map[string]uhost.UHostDiskSet{}
for _, disk := range inst.DiskSet {
if disk.IsBoot == "True" {
bootDisk = disk
} else if disk.IsBoot == "False" {
dataDisks[disk.DiskId] = disk
}
}
if bootDiskSize != 0 {
if bootDiskSize <= bootDisk.Size {
base.LogError(fmt.Sprintf("Error, disk does not support shrinkage. current system-disk-size %dg", bootDisk.Size))
continue
} else {
_req.DiskSpace = &bootDiskSize
_req.DiskId = &bootDisk.DiskId
}
err := resizeAttachedDisk(out, _req, inst, *yes, *async, confirmText)
if err != nil {
base.HandleError(err)
}
}
if dataDiskSize != 0 {
var dataDisk uhost.UHostDiskSet
if len(dataDisks) > 1 {
if dataDiskID == "" {
base.LogError(fmt.Sprintf("Error, the uhost %s have %d data disks. data-disk-id should be assigned", id, len(dataDisks)))
continue
}
var ok bool
dataDisk, ok = dataDisks[dataDiskID]
if !ok {
base.LogError(fmt.Sprintf("Error, the disk %s does not exist", dataDiskID))
continue
}
} else if len(dataDisks) == 1 {
for _, disk := range dataDisks {
dataDisk = disk
}