forked from lemoex/oci-help
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
2367 lines (2150 loc) · 73.5 KB
/
main.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
/*
甲骨文云API文档
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/
实例:
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/Instance/
VCN:
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/Vcn/
Subnet:
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/Subnet/
VNIC:
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/Vnic/
VnicAttachment:
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/VnicAttachment/
私有IP
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/PrivateIp/
公共IP
https://docs.oracle.com/en-us/iaas/api/#/en/iaas/20160918/PublicIp/
获取可用性域
https://docs.oracle.com/en-us/iaas/api/#/en/identity/20160918/AvailabilityDomain/ListAvailabilityDomains
*/
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"text/tabwriter"
"time"
"github.com/oracle/oci-go-sdk/v54/common"
"github.com/oracle/oci-go-sdk/v54/core"
"github.com/oracle/oci-go-sdk/v54/example/helpers"
"github.com/oracle/oci-go-sdk/v54/identity"
"gopkg.in/ini.v1"
)
const (
defConfigFilePath = "./oci-help.ini"
IPsFilePrefix = "IPs"
)
var (
configFilePath string
provider common.ConfigurationProvider
computeClient core.ComputeClient
networkClient core.VirtualNetworkClient
storageClient core.BlockstorageClient
identityClient identity.IdentityClient
ctx context.Context
oracleSections []*ini.Section
oracleSection *ini.Section
oracleSectionName string
oracle Oracle
instanceBaseSection *ini.Section
instance Instance
proxy string
token string
chat_id string
sendMessageUrl string
editMessageUrl string
EACH bool
availabilityDomains []identity.AvailabilityDomain
)
type Oracle struct {
User string `ini:"user"`
Fingerprint string `ini:"fingerprint"`
Tenancy string `ini:"tenancy"`
Region string `ini:"region"`
Key_file string `ini:"key_file"`
Key_password string `ini:"key_password"`
}
type Instance struct {
AvailabilityDomain string `ini:"availabilityDomain"`
SSH_Public_Key string `ini:"ssh_authorized_key"`
VcnDisplayName string `ini:"vcnDisplayName"`
SubnetDisplayName string `ini:"subnetDisplayName"`
Shape string `ini:"shape"`
OperatingSystem string `ini:"OperatingSystem"`
OperatingSystemVersion string `ini:"OperatingSystemVersion"`
InstanceDisplayName string `ini:"instanceDisplayName"`
Ocpus float32 `ini:"cpus"`
MemoryInGBs float32 `ini:"memoryInGBs"`
BootVolumeSizeInGBs int64 `ini:"bootVolumeSizeInGBs"`
Sum int32 `ini:"sum"`
Each int32 `ini:"each"`
Retry int32 `ini:"retry"`
CloudInit string `ini:"cloud-init"`
MinTime int32 `ini:"minTime"`
MaxTime int32 `ini:"maxTime"`
}
type Message struct {
OK bool `json:"ok"`
Result `json:"result"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
}
type Result struct {
MessageId int `json:"message_id"`
}
func main() {
flag.StringVar(&configFilePath, "config", defConfigFilePath, "配置文件路径")
flag.StringVar(&configFilePath, "c", defConfigFilePath, "配置文件路径")
flag.Parse()
cfg, err := ini.Load(configFilePath)
helpers.FatalIfError(err)
defSec := cfg.Section(ini.DefaultSection)
proxy = defSec.Key("proxy").Value()
token = defSec.Key("token").Value()
chat_id = defSec.Key("chat_id").Value()
if defSec.HasKey("EACH") {
EACH, _ = defSec.Key("EACH").Bool()
} else {
EACH = true
}
sendMessageUrl = "https://api.telegram.org/bot" + token + "/sendMessage"
editMessageUrl = "https://api.telegram.org/bot" + token + "/editMessageText"
rand.Seed(time.Now().UnixNano())
sections := cfg.Sections()
oracleSections = []*ini.Section{}
for _, sec := range sections {
if len(sec.ParentKeys()) == 0 {
user := sec.Key("user").Value()
fingerprint := sec.Key("fingerprint").Value()
tenancy := sec.Key("tenancy").Value()
region := sec.Key("region").Value()
key_file := sec.Key("key_file").Value()
if user != "" && fingerprint != "" && tenancy != "" && region != "" && key_file != "" {
oracleSections = append(oracleSections, sec)
}
}
}
if len(oracleSections) == 0 {
fmt.Printf("\033[1;31m未找到正确的配置信息, 请参考链接文档配置相关信息。链接: https://github.com/lemoex/oci-help\033[0m\n")
return
}
instanceBaseSection = cfg.Section("INSTANCE")
listOracleAccount()
}
func listOracleAccount() {
if len(oracleSections) == 1 {
oracleSection = oracleSections[0]
} else {
fmt.Printf("\n\033[1;32m%s\033[0m\n\n", "欢迎使用甲骨文实例管理工具")
w := new(tabwriter.Writer)
w.Init(os.Stdout, 4, 8, 1, '\t', 0)
fmt.Fprintf(w, "%s\t%s\t\n", "序号", "账号")
for i, section := range oracleSections {
fmt.Fprintf(w, "%d\t%s\t\n", i+1, section.Name())
}
w.Flush()
fmt.Printf("\n")
var input string
var index int
for {
fmt.Print("请输入账号对应的序号进入相关操作: ")
_, err := fmt.Scanln(&input)
if err != nil {
return
}
if strings.EqualFold(input, "oci") {
multiBatchLaunchInstances()
listOracleAccount()
return
} else if strings.EqualFold(input, "ip") {
multiBatchListInstancesIp()
listOracleAccount()
return
}
index, _ = strconv.Atoi(input)
if 0 < index && index <= len(oracleSections) {
break
} else {
index = 0
input = ""
fmt.Printf("\033[1;31m错误! 请输入正确的序号\033[0m\n")
}
}
oracleSection = oracleSections[index-1]
}
var err error
ctx = context.Background()
err = initVar(oracleSection)
if err != nil {
return
}
// 获取可用性域
fmt.Println("正在获取可用性域...")
availabilityDomains, err = ListAvailabilityDomains()
if err != nil {
printlnErr("获取可用性域失败", err.Error())
return
}
showMainMenu()
}
func initVar(oracleSec *ini.Section) (err error) {
oracleSectionName = oracleSec.Name()
oracle = Oracle{}
err = oracleSec.MapTo(&oracle)
if err != nil {
printlnErr("解析账号相关参数失败", err.Error())
return
}
provider, err = getProvider(oracle)
if err != nil {
printlnErr("获取 Provider 失败", err.Error())
return
}
computeClient, err = core.NewComputeClientWithConfigurationProvider(provider)
if err != nil {
printlnErr("创建 ComputeClient 失败", err.Error())
return
}
setProxyOrNot(&computeClient.BaseClient)
networkClient, err = core.NewVirtualNetworkClientWithConfigurationProvider(provider)
if err != nil {
printlnErr("创建 VirtualNetworkClient 失败", err.Error())
return
}
setProxyOrNot(&networkClient.BaseClient)
storageClient, err = core.NewBlockstorageClientWithConfigurationProvider(provider)
if err != nil {
printlnErr("创建 BlockstorageClient 失败", err.Error())
return
}
setProxyOrNot(&storageClient.BaseClient)
identityClient, err = identity.NewIdentityClientWithConfigurationProvider(provider)
if err != nil {
printlnErr("创建 IdentityClient 失败", err.Error())
return
}
setProxyOrNot(&identityClient.BaseClient)
return
}
func showMainMenu() {
fmt.Printf("\n\033[1;32m欢迎使用甲骨文实例管理工具\033[0m \n(当前账号: %s)\n\n", oracleSection.Name())
fmt.Printf("\033[1;36m%s\033[0m %s\n", "1.", "查看实例")
fmt.Printf("\033[1;36m%s\033[0m %s\n", "2.", "创建实例")
fmt.Printf("\033[1;36m%s\033[0m %s\n", "3.", "管理引导卷")
fmt.Print("\n请输入序号进入相关操作: ")
var input string
var num int
fmt.Scanln(&input)
if strings.EqualFold(input, "oci") {
batchLaunchInstances(oracleSection)
showMainMenu()
return
} else if strings.EqualFold(input, "ip") {
batchListInstancesIp(oracleSection)
showMainMenu()
return
}
num, _ = strconv.Atoi(input)
switch num {
case 1:
listInstances()
case 2:
listLaunchInstanceTemplates()
case 3:
listBootVolumes()
default:
if len(oracleSections) > 1 {
listOracleAccount()
}
}
}
func listInstances() {
fmt.Println("正在获取实例数据...")
instances, err := ListInstances(ctx, computeClient)
if err != nil {
printlnErr("获取失败, 回车返回上一级菜单.", err.Error())
fmt.Scanln()
showMainMenu()
return
}
if len(instances) == 0 {
fmt.Printf("\033[1;32m实例为空, 回车返回上一级菜单.\033[0m")
fmt.Scanln()
showMainMenu()
return
}
fmt.Printf("\n\033[1;32m实例信息\033[0m \n(当前账号: %s)\n\n", oracleSection.Name())
w := new(tabwriter.Writer)
w.Init(os.Stdout, 4, 8, 1, '\t', 0)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n", "序号", "名称", "状态 ", "配置")
//fmt.Printf("%-5s %-28s %-18s %-20s\n", "序号", "名称", "公共IP", "配置")
for i, ins := range instances {
// 获取实例公共IP
/*
var strIps string
ips, err := getInstancePublicIps(ctx, computeClient, networkClient, ins.Id)
if err != nil {
strIps = err.Error()
} else {
strIps = strings.Join(ips, ",")
}
*/
//fmt.Printf("%-7d %-30s %-20s %-20s\n", i+1, *ins.DisplayName, strIps, *ins.Shape)
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t\n", i+1, *ins.DisplayName, getInstanceState(ins.LifecycleState), *ins.Shape)
}
w.Flush()
fmt.Println("--------------------")
fmt.Printf("\n\033[1;32ma: %s b: %s c: %s d: %s\033[0m\n", "启动全部", "停止全部", "重启全部", "终止全部")
var input string
var index int
for {
fmt.Print("请输入序号查看实例详细信息: ")
_, err := fmt.Scanln(&input)
if err != nil {
showMainMenu()
return
}
switch input {
case "a":
fmt.Printf("确定启动全部实例?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
for _, ins := range instances {
_, err := instanceAction(ins.Id, core.InstanceActionActionStart)
if err != nil {
fmt.Printf("\033[1;31m实例 %s 启动失败.\033[0m %s\n", *ins.DisplayName, err.Error())
} else {
fmt.Printf("\033[1;32m实例 %s 启动成功.\033[0m\n", *ins.DisplayName)
}
}
} else {
continue
}
time.Sleep(1 * time.Second)
listInstances()
return
case "b":
fmt.Printf("确定停止全部实例?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
for _, ins := range instances {
_, err := instanceAction(ins.Id, core.InstanceActionActionSoftstop)
if err != nil {
fmt.Printf("\033[1;31m实例 %s 停止失败.\033[0m %s\n", *ins.DisplayName, err.Error())
} else {
fmt.Printf("\033[1;32m实例 %s 停止成功.\033[0m\n", *ins.DisplayName)
}
}
} else {
continue
}
time.Sleep(1 * time.Second)
listInstances()
return
case "c":
fmt.Printf("确定重启全部实例?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
for _, ins := range instances {
_, err := instanceAction(ins.Id, core.InstanceActionActionSoftreset)
if err != nil {
fmt.Printf("\033[1;31m实例 %s 重启失败.\033[0m %s\n", *ins.DisplayName, err.Error())
} else {
fmt.Printf("\033[1;32m实例 %s 重启成功.\033[0m\n", *ins.DisplayName)
}
}
} else {
continue
}
time.Sleep(1 * time.Second)
listInstances()
return
case "d":
fmt.Printf("确定终止全部实例?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
for _, ins := range instances {
err := terminateInstance(ins.Id)
if err != nil {
fmt.Printf("\033[1;31m实例 %s 终止失败.\033[0m %s\n", *ins.DisplayName, err.Error())
} else {
fmt.Printf("\033[1;32m实例 %s 终止成功.\033[0m\n", *ins.DisplayName)
}
}
} else {
continue
}
time.Sleep(1 * time.Second)
listInstances()
return
}
index, _ = strconv.Atoi(input)
if 0 < index && index <= len(instances) {
break
} else {
input = ""
index = 0
fmt.Printf("\033[1;31m错误! 请输入正确的序号\033[0m\n")
}
}
instanceDetails(instances[index-1].Id)
}
func instanceDetails(instanceId *string) {
for {
fmt.Println("正在获取实例详细信息...")
instance, err := getInstance(instanceId)
if err != nil {
fmt.Printf("\033[1;31m获取实例详细信息失败, 回车返回上一级菜单.\033[0m")
fmt.Scanln()
listInstances()
return
}
vnics, err := getInstanceVnics(instanceId)
if err != nil {
fmt.Printf("\033[1;31m获取实例VNIC失败, 回车返回上一级菜单.\033[0m")
fmt.Scanln()
listInstances()
return
}
var publicIps = make([]string, 0)
var strPublicIps string
if err != nil {
strPublicIps = err.Error()
} else {
for _, vnic := range vnics {
if vnic.PublicIp != nil {
publicIps = append(publicIps, *vnic.PublicIp)
}
}
strPublicIps = strings.Join(publicIps, ",")
}
fmt.Printf("\n\033[1;32m实例详细信息\033[0m \n(当前账号: %s)\n\n", oracleSection.Name())
fmt.Println("--------------------")
fmt.Printf("名称: %s\n", *instance.DisplayName)
fmt.Printf("状态: %s\n", getInstanceState(instance.LifecycleState))
fmt.Printf("公共IP: %s\n", strPublicIps)
fmt.Printf("可用性域: %s\n", *instance.AvailabilityDomain)
fmt.Printf("配置: %s\n", *instance.Shape)
fmt.Printf("OCPU计数: %g\n", *instance.ShapeConfig.Ocpus)
fmt.Printf("网络带宽(Gbps): %g\n", *instance.ShapeConfig.NetworkingBandwidthInGbps)
fmt.Printf("内存(GB): %g\n", *instance.ShapeConfig.MemoryInGBs)
fmt.Println("--------------------")
fmt.Printf("\n\033[1;32m1: %s 2: %s 3: %s 4: %s 5: %s\033[0m\n", "启动", "停止", "重启", "终止", "更换公共IP")
var input string
var num int
fmt.Print("\n请输入需要执行操作的序号: ")
fmt.Scanln(&input)
num, _ = strconv.Atoi(input)
switch num {
case 1:
_, err := instanceAction(instance.Id, core.InstanceActionActionStart)
if err != nil {
fmt.Printf("\033[1;31m启动实例失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m正在启动实例, 请稍后查看实例状态\033[0m\n")
}
time.Sleep(3 * time.Second)
case 2:
_, err := instanceAction(instance.Id, core.InstanceActionActionSoftstop)
if err != nil {
fmt.Printf("\033[1;31m停止实例失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m正在停止实例, 请稍后查看实例状态\033[0m\n")
}
time.Sleep(3 * time.Second)
case 3:
_, err := instanceAction(instance.Id, core.InstanceActionActionSoftreset)
if err != nil {
fmt.Printf("\033[1;31m重启实例失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m正在重启实例, 请稍后查看实例状态\033[0m\n")
}
time.Sleep(3 * time.Second)
case 4:
fmt.Printf("确定终止实例?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
err := terminateInstance(instance.Id)
if err != nil {
fmt.Printf("\033[1;31m终止实例失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m正在终止实例, 请稍后查看实例状态\033[0m\n")
}
time.Sleep(3 * time.Second)
}
case 5:
if len(vnics) == 0 {
fmt.Printf("\033[1;31m实例已终止或获取实例VNIC失败,请稍后重试.\033[0m\n")
break
}
fmt.Printf("将删除当前公共IP并创建一个新的公共IP。确定更换实例公共IP?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
publicIp, err := changePublicIp(vnics)
if err != nil {
fmt.Printf("\033[1;31m更换实例公共IP失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m更换实例公共IP成功, 实例公共IP: \033[0m%s\n", *publicIp.IpAddress)
}
time.Sleep(3 * time.Second)
}
default:
listInstances()
return
}
}
}
func listBootVolumes() {
var bootVolumes []core.BootVolume
var wg sync.WaitGroup
for _, ad := range availabilityDomains {
wg.Add(1)
go func(adName *string) {
defer wg.Done()
volumes, err := getBootVolumes(adName)
if err != nil {
printlnErr("获取引导卷失败", err.Error())
} else {
bootVolumes = append(bootVolumes, volumes...)
}
}(ad.Name)
}
wg.Wait()
fmt.Printf("\n\033[1;32m引导卷\033[0m \n(当前账号: %s)\n\n", oracleSection.Name())
w := new(tabwriter.Writer)
w.Init(os.Stdout, 4, 8, 1, '\t', 0)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n", "序号", "名称", "状态 ", "大小(GB)")
for i, volume := range bootVolumes {
fmt.Fprintf(w, "%d\t%s\t%s\t%d\t\n", i+1, *volume.DisplayName, getBootVolumeState(volume.LifecycleState), *volume.SizeInGBs)
}
w.Flush()
fmt.Printf("\n")
var input string
var index int
for {
fmt.Print("请输入序号查看引导卷详细信息: ")
_, err := fmt.Scanln(&input)
if err != nil {
showMainMenu()
return
}
index, _ = strconv.Atoi(input)
if 0 < index && index <= len(bootVolumes) {
break
} else {
input = ""
index = 0
fmt.Printf("\033[1;31m错误! 请输入正确的序号\033[0m\n")
}
}
bootvolumeDetails(bootVolumes[index-1].Id)
}
func bootvolumeDetails(bootVolumeId *string) {
for {
fmt.Println("正在获取引导卷详细信息...")
bootVolume, err := getBootVolume(bootVolumeId)
if err != nil {
fmt.Printf("\033[1;31m获取引导卷详细信息失败, 回车返回上一级菜单.\033[0m")
fmt.Scanln()
listBootVolumes()
return
}
attachments, err := listBootVolumeAttachments(bootVolume.AvailabilityDomain, bootVolume.CompartmentId, bootVolume.Id)
attachIns := make([]string, 0)
if err != nil {
attachIns = append(attachIns, err.Error())
} else {
for _, attachment := range attachments {
ins, err := getInstance(attachment.InstanceId)
if err != nil {
attachIns = append(attachIns, err.Error())
} else {
attachIns = append(attachIns, *ins.DisplayName)
}
}
}
var performance string
switch *bootVolume.VpusPerGB {
case 10:
performance = fmt.Sprintf("均衡 (VPU:%d)", *bootVolume.VpusPerGB)
case 20:
performance = fmt.Sprintf("性能较高 (VPU:%d)", *bootVolume.VpusPerGB)
default:
performance = fmt.Sprintf("UHP (VPU:%d)", *bootVolume.VpusPerGB)
}
fmt.Printf("\n\033[1;32m引导卷详细信息\033[0m \n(当前账号: %s)\n\n", oracleSection.Name())
fmt.Println("--------------------")
fmt.Printf("名称: %s\n", *bootVolume.DisplayName)
fmt.Printf("状态: %s\n", getBootVolumeState(bootVolume.LifecycleState))
fmt.Printf("可用性域: %s\n", *bootVolume.AvailabilityDomain)
fmt.Printf("大小(GB): %d\n", *bootVolume.SizeInGBs)
fmt.Printf("性能: %s\n", performance)
fmt.Printf("附加的实例: %s\n", strings.Join(attachIns, ","))
fmt.Println("--------------------")
fmt.Printf("\n\033[1;32m1: %s 2: %s 3: %s 4: %s\033[0m\n", "修改性能", "修改大小", "分离引导卷", "终止引导卷")
var input string
var num int
fmt.Print("\n请输入需要执行操作的序号: ")
fmt.Scanln(&input)
num, _ = strconv.Atoi(input)
switch num {
case 1:
fmt.Printf("修改引导卷性能, 请输入 (1: 均衡; 2: 性能较高): ")
var input string
fmt.Scanln(&input)
if input == "1" {
_, err := updateBootVolume(bootVolume.Id, nil, common.Int64(10))
if err != nil {
fmt.Printf("\033[1;31m修改引导卷性能失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m修改引导卷性能成功, 请稍后查看引导卷状态\033[0m\n")
}
} else if input == "2" {
_, err := updateBootVolume(bootVolume.Id, nil, common.Int64(20))
if err != nil {
fmt.Printf("\033[1;31m修改引导卷性能失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m修改引导卷性能成功, 请稍后查看引导卷信息\033[0m\n")
}
} else {
fmt.Printf("\033[1;31m输入错误.\033[0m\n")
}
time.Sleep(1 * time.Second)
case 2:
fmt.Printf("修改引导卷大小, 请输入 (例如修改为50GB, 输入50): ")
var input string
var sizeInGBs int64
fmt.Scanln(&input)
sizeInGBs, _ = strconv.ParseInt(input, 10, 64)
if sizeInGBs > 0 {
_, err := updateBootVolume(bootVolume.Id, &sizeInGBs, nil)
if err != nil {
fmt.Printf("\033[1;31m修改引导卷大小失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m修改引导卷大小成功, 请稍后查看引导卷信息\033[0m\n")
}
} else {
fmt.Printf("\033[1;31m输入错误.\033[0m\n")
}
time.Sleep(1 * time.Second)
case 3:
fmt.Printf("确定分离引导卷?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
for _, attachment := range attachments {
_, err := detachBootVolume(attachment.Id)
if err != nil {
fmt.Printf("\033[1;31m分离引导卷失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m分离引导卷成功, 请稍后查看引导卷信息\033[0m\n")
}
}
}
time.Sleep(1 * time.Second)
case 4:
fmt.Printf("确定终止引导卷?(输入 y 并回车): ")
var input string
fmt.Scanln(&input)
if strings.EqualFold(input, "y") {
_, err := deleteBootVolume(bootVolume.Id)
if err != nil {
fmt.Printf("\033[1;31m终止引导卷失败.\033[0m %s\n", err.Error())
} else {
fmt.Printf("\033[1;32m终止引导卷成功, 请稍后查看引导卷信息\033[0m\n")
}
}
time.Sleep(1 * time.Second)
default:
listBootVolumes()
return
}
}
}
func listLaunchInstanceTemplates() {
var instanceSections []*ini.Section
instanceSections = append(instanceSections, instanceBaseSection.ChildSections()...)
instanceSections = append(instanceSections, oracleSection.ChildSections()...)
if len(instanceSections) == 0 {
fmt.Printf("\033[1;31m未找到实例模版, 回车返回上一级菜单.\033[0m")
fmt.Scanln()
showMainMenu()
return
}
for {
fmt.Printf("\n\033[1;32m选择对应的实例模版开始创建实例\033[0m \n(当前账号: %s)\n\n", oracleSectionName)
w := new(tabwriter.Writer)
w.Init(os.Stdout, 4, 8, 1, '\t', 0)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t\n", "序号", "配置", "CPU个数", "内存(GB)")
for i, instanceSec := range instanceSections {
cpu := instanceSec.Key("cpus").Value()
if cpu == "" {
cpu = "-"
}
memory := instanceSec.Key("memoryInGBs").Value()
if memory == "" {
memory = "-"
}
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t\n", i+1, instanceSec.Key("shape").Value(), cpu, memory)
}
w.Flush()
fmt.Printf("\n")
var input string
var index int
for {
fmt.Print("请输入需要创建的实例的序号: ")
_, err := fmt.Scanln(&input)
if err != nil {
showMainMenu()
return
}
index, _ = strconv.Atoi(input)
if 0 < index && index <= len(instanceSections) {
break
} else {
input = ""
index = 0
fmt.Printf("\033[1;31m错误! 请输入正确的序号\033[0m\n")
}
}
instanceSection := instanceSections[index-1]
instance = Instance{}
err := instanceSection.MapTo(&instance)
if err != nil {
printlnErr("解析实例模版参数失败", err.Error())
continue
}
LaunchInstances(availabilityDomains)
}
}
func multiBatchLaunchInstances() {
for _, sec := range oracleSections {
var err error
err = initVar(sec)
if err != nil {
continue
}
// 获取可用性域
availabilityDomains, err = ListAvailabilityDomains()
if err != nil {
printlnErr("获取可用性域失败", err.Error())
continue
}
batchLaunchInstances(sec)
}
}
func batchLaunchInstances(oracleSec *ini.Section) {
var instanceSections []*ini.Section
instanceSections = append(instanceSections, instanceBaseSection.ChildSections()...)
instanceSections = append(instanceSections, oracleSec.ChildSections()...)
if len(instanceSections) == 0 {
return
}
printf("\033[1;36m[%s] 开始创建\033[0m\n", oracleSectionName)
var SUM, NUM int32 = 0, 0
sendMessage(fmt.Sprintf("[%s]", oracleSectionName), "开始创建")
for _, instanceSec := range instanceSections {
instance = Instance{}
err := instanceSec.MapTo(&instance)
if err != nil {
printlnErr("解析实例模版参数失败", err.Error())
continue
}
sum, num := LaunchInstances(availabilityDomains)
SUM = SUM + sum
NUM = NUM + num
}
printf("\033[1;36m[%s] 结束创建。创建实例总数: %d, 成功 %d , 失败 %d\033[0m\n", oracleSectionName, SUM, NUM, SUM-NUM)
text := fmt.Sprintf("结束创建。创建实例总数: %d, 成功 %d , 失败 %d", SUM, NUM, SUM-NUM)
sendMessage(fmt.Sprintf("[%s]", oracleSectionName), text)
}
func multiBatchListInstancesIp() {
IPsFilePath := IPsFilePrefix + "-" + time.Now().Format("2006-01-02-150405.txt")
_, err := os.Stat(IPsFilePath)
if err != nil && os.IsNotExist(err) {
os.Create(IPsFilePath)
}
fmt.Printf("正在导出实例公共IP地址...\n")
for _, sec := range oracleSections {
err := initVar(sec)
if err != nil {
continue
}
ListInstancesIPs(IPsFilePath, sec.Name())
}
fmt.Printf("导出实例公共IP地址完成,请查看文件 %s\n", IPsFilePath)
}
func batchListInstancesIp(sec *ini.Section) {
IPsFilePath := IPsFilePrefix + "-" + time.Now().Format("2006-01-02-150405.txt")
_, err := os.Stat(IPsFilePath)
if err != nil && os.IsNotExist(err) {
os.Create(IPsFilePath)
}
fmt.Printf("正在导出实例公共IP地址...\n")
ListInstancesIPs(IPsFilePath, sec.Name())
fmt.Printf("导出实例IP地址完成,请查看文件 %s\n", IPsFilePath)
}
func ListInstancesIPs(filePath string, sectionName string) {
vnicAttachments, err := ListVnicAttachments(ctx, computeClient, nil)
if err != nil {
fmt.Printf("ListVnicAttachments Error: %s\n", err.Error())
return
}
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
fmt.Printf("打开文件失败, Error: %s\n", err.Error())
return
}
_, err = io.WriteString(file, "["+sectionName+"]\n")
if err != nil {
fmt.Printf("%s\n", err.Error())
}
for _, vnicAttachment := range vnicAttachments {
vnic, err := GetVnic(ctx, networkClient, vnicAttachment.VnicId)
if err != nil {
fmt.Printf("IP地址获取失败, %s\n", err.Error())
continue
}
fmt.Printf("[%s] 实例: %s, IP: %s\n", sectionName, *vnic.DisplayName, *vnic.PublicIp)
_, err = io.WriteString(file, "实例: "+*vnic.DisplayName+", IP: "+*vnic.PublicIp+"\n")
if err != nil {
fmt.Printf("写入文件失败, Error: %s\n", err.Error())
}
}
_, err = io.WriteString(file, "\n")
if err != nil {
fmt.Printf("%s\n", err.Error())
}
}
// 返回值 sum: 创建实例总数; num: 创建成功的个数
func LaunchInstances(ads []identity.AvailabilityDomain) (sum, num int32) {
/* 创建实例的几种情况
* 1. 设置了 availabilityDomain 参数,即在设置的可用性域中创建 sum 个实例。
* 2. 没有设置 availabilityDomain 但是设置了 each 参数。即在获取的每个可用性域中创建 each 个实例,创建的实例总数 sum = each * adCount。
* 3. 没有设置 availabilityDomain 且没有设置 each 参数,即在获取到的可用性域中创建的实例总数为 sum。
*/
//可用性域数量
var adCount int32 = int32(len(ads))
adName := common.String(instance.AvailabilityDomain)
each := instance.Each
sum = instance.Sum
// 没有设置可用性域并且没有设置each时,才有用。
var usableAds = make([]identity.AvailabilityDomain, 0)
//可用性域不固定,即没有提供 availabilityDomain 参数
var AD_NOT_FIXED bool = false
var EACH_AD = false
if adName == nil || *adName == "" {
AD_NOT_FIXED = true
if each > 0 {
EACH_AD = true
sum = each * adCount
} else {
EACH_AD = false
usableAds = ads
}
}
name := instance.InstanceDisplayName
if name == "" {
name = time.Now().Format("instance-20060102-1504")
}
displayName := common.String(name)
if sum > 1 {
displayName = common.String(name + "-1")
}
// create the launch instance request
request := core.LaunchInstanceRequest{}
request.CompartmentId = common.String(oracle.Tenancy)
request.DisplayName = displayName
// Get a image.
fmt.Println("正在获取系统镜像...")
image, err := GetImage(ctx, computeClient)
if err != nil {
printlnErr("获取系统镜像失败", err.Error())
return
}
fmt.Println("系统镜像:", *image.DisplayName)
var shape core.Shape
if strings.Contains(strings.ToLower(instance.Shape), "flex") && instance.Ocpus > 0 && instance.MemoryInGBs > 0 {
shape.Shape = &instance.Shape
shape.Ocpus = &instance.Ocpus
shape.MemoryInGBs = &instance.MemoryInGBs
} else {
fmt.Println("正在获取Shape信息...")
shape, err = getShape(image.Id, instance.Shape)
if err != nil {
printlnErr("获取Shape信息失败", err.Error())
return
}
}
request.Shape = shape.Shape
if strings.Contains(strings.ToLower(*shape.Shape), "flex") {
request.ShapeConfig = &core.LaunchInstanceShapeConfigDetails{
Ocpus: shape.Ocpus,
MemoryInGBs: shape.MemoryInGBs,
}
}
// create a subnet or get the one already created
fmt.Println("正在获取子网...")
subnet, err := CreateOrGetNetworkInfrastructure(ctx, networkClient)
if err != nil {
printlnErr("获取子网失败", err.Error())
return
}
fmt.Println("子网:", *subnet.DisplayName)
request.CreateVnicDetails = &core.CreateVnicDetails{SubnetId: subnet.Id}
sd := core.InstanceSourceViaImageDetails{}
sd.ImageId = image.Id
if instance.BootVolumeSizeInGBs > 0 {
sd.BootVolumeSizeInGBs = common.Int64(instance.BootVolumeSizeInGBs)
}
request.SourceDetails = sd
request.IsPvEncryptionInTransitEnabled = common.Bool(true)
metaData := map[string]string{}
metaData["ssh_authorized_keys"] = instance.SSH_Public_Key
if instance.CloudInit != "" {
metaData["user_data"] = instance.CloudInit
}
request.Metadata = metaData
minTime := instance.MinTime
maxTime := instance.MaxTime
SKIP_RETRY_MAP := make(map[int32]bool)
var usableAdsTemp = make([]identity.AvailabilityDomain, 0)