/
utility.go
1234 lines (1049 loc) · 38.9 KB
/
utility.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
/*
Copyright 2019 The Cloud-Barista Authors.
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 mcis is to manage multi-cloud infra service
package mcis
import (
//"encoding/json"
//uuid "github.com/google/uuid"
"fmt"
"sort"
"strconv"
"strings"
"github.com/cloud-barista/cb-tumblebug/src/core/common"
"github.com/cloud-barista/cb-tumblebug/src/core/mcir"
"github.com/go-resty/resty/v2"
"math"
"reflect"
"sync"
"time"
validator "github.com/go-playground/validator/v10"
)
// CB-Store
//var cblog *logrus.Logger
//var store icbs.Store
//var SPIDER_REST_URL string
// use a single instance of Validate, it caches struct info
var validate *validator.Validate
func init() {
//cblog = config.Cblogger
//store = cbstore.GetStore()
//SPIDER_REST_URL = os.Getenv("SPIDER_REST_URL")
validate = validator.New()
// register function to get tag name from json tags.
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
if name == "-" {
return ""
}
return name
})
// register validation for 'Tb*Req'
// NOTE: only have to register a non-pointer type for 'Tb*Req', validator
// internally dereferences during it's type checks.
validate.RegisterStructValidation(TbMcisReqStructLevelValidation, TbMcisReq{})
validate.RegisterStructValidation(TbVmReqStructLevelValidation, TbVmReq{})
validate.RegisterStructValidation(TbMcisCmdReqStructLevelValidation, McisCmdReq{})
// validate.RegisterStructValidation(TbMcisRecommendReqStructLevelValidation, McisRecommendReq{})
// validate.RegisterStructValidation(TbVmRecommendReqStructLevelValidation, TbVmRecommendReq{})
// validate.RegisterStructValidation(TbBenchmarkReqStructLevelValidation, BenchmarkReq{})
// validate.RegisterStructValidation(TbMultihostBenchmarkReqStructLevelValidation, MultihostBenchmarkReq{})
validate.RegisterStructValidation(DFMonAgentInstallReqStructLevelValidation, MonAgentInstallReq{})
}
/*
func GenUid() string {
return uuid.New().String()
}
*/
/*
type mcirIds struct {
CspImageId string
CspImageName string
CspSshKeyName string
Name string // Spec
CspVNetId string
CspVNetName string
CspSecurityGroupId string
CspSecurityGroupName string
CspPublicIpId string
CspPublicIpName string
CspVNicId string
CspVNicName string
ConnectionName string
}
*/
func CheckMcis(nsId string, mcisId string) (bool, error) {
// Check parameters' emptiness
if nsId == "" {
err := fmt.Errorf("CheckMcis failed; nsId given is null.")
return false, err
} else if mcisId == "" {
err := fmt.Errorf("CheckMcis failed; mcisId given is null.")
return false, err
}
err := common.CheckString(nsId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
err = common.CheckString(mcisId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
fmt.Println("[Check mcis] " + mcisId)
key := common.GenMcisKey(nsId, mcisId, "")
keyValue, err := common.CBStore.Get(key)
if err != nil {
common.CBLog.Error(err)
err = fmt.Errorf("In CheckMcis(); CBStore.Get() returned an error.")
common.CBLog.Error(err)
// return nil, err
}
if keyValue != nil {
return true, nil
}
return false, nil
}
// CheckSubGroup func is to check given subGroupId is duplicated with existing
func CheckSubGroup(nsId string, mcisId string, subGroupId string) (bool, error) {
err := common.CheckString(nsId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
err = common.CheckString(mcisId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
subGroupList, err := ListSubGroupId(nsId, mcisId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
for _, v := range subGroupList {
if strings.EqualFold(v, subGroupId) {
return true, nil
}
}
return false, nil
}
func CheckVm(nsId string, mcisId string, vmId string) (bool, error) {
// Check parameters' emptiness
if nsId == "" {
err := fmt.Errorf("CheckVm failed; nsId given is null.")
return false, err
} else if mcisId == "" {
err := fmt.Errorf("CheckVm failed; mcisId given is null.")
return false, err
} else if vmId == "" {
err := fmt.Errorf("CheckVm failed; vmId given is null.")
return false, err
}
err := common.CheckString(nsId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
err = common.CheckString(mcisId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
err = common.CheckString(vmId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
fmt.Println("[Check vm] " + mcisId + ", " + vmId)
key := common.GenMcisKey(nsId, mcisId, vmId)
keyValue, err := common.CBStore.Get(key)
if err != nil {
common.CBLog.Error(err)
err = fmt.Errorf("In CheckVm(); CBStore.Get() returned an error.")
common.CBLog.Error(err)
// return nil, err
}
if keyValue != nil {
return true, nil
}
return false, nil
}
func CheckMcisPolicy(nsId string, mcisId string) (bool, error) {
// Check parameters' emptiness
if nsId == "" {
err := fmt.Errorf("CheckMcis failed; nsId given is null.")
return false, err
} else if mcisId == "" {
err := fmt.Errorf("CheckMcis failed; mcisId given is null.")
return false, err
}
err := common.CheckString(nsId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
err = common.CheckString(mcisId)
if err != nil {
common.CBLog.Error(err)
return false, err
}
fmt.Println("[Check McisPolicy] " + mcisId)
key := common.GenMcisPolicyKey(nsId, mcisId, "")
keyValue, err := common.CBStore.Get(key)
if err != nil {
common.CBLog.Error(err)
err = fmt.Errorf("In CheckMcisPolicy(); CBStore.Get() returned an error.")
common.CBLog.Error(err)
// return nil, err
}
if keyValue != nil {
return true, nil
}
return false, nil
}
func TrimIP(sshAccessPoint string) (string, error) {
splitted := strings.Split(sshAccessPoint, ":")
if len(splitted) != 2 {
err := fmt.Errorf("In TrimIP(), sshAccessPoint does not seem 8.8.8.8:22 form.")
return strconv.Itoa(0), err
}
portString := splitted[1]
port, err := strconv.Atoi(portString)
if err != nil {
err := fmt.Errorf("In TrimIP(), strconv.Atoi returned an error.")
return strconv.Itoa(0), err
}
if port >= 1 && port <= 65535 { // valid port number
return portString, nil
} else {
err := fmt.Errorf("In TrimIP(), detected port number seems wrong: " + portString)
return strconv.Itoa(0), err
}
}
type SpiderNameIdSystemId struct {
NameId string
SystemId string
}
type SpiderAllListWrapper struct {
AllList SpiderAllList
}
type SpiderAllList struct {
MappedList []SpiderNameIdSystemId
OnlySpiderList []SpiderNameIdSystemId
OnlyCSPList []SpiderNameIdSystemId
}
// TbInspectResourcesResponse is struct for response of InspectResources request
type TbInspectResourcesResponse struct {
InspectResources []InspectResource `json:"inspectResources"`
}
// InspectResource is struct for InspectResource per Cloud Connection
type InspectResource struct {
// ResourcesOnCsp interface{} `json:"resourcesOnCsp"`
// ResourcesOnSpider interface{} `json:"resourcesOnSpider"`
// ResourcesOnTumblebug interface{} `json:"resourcesOnTumblebug"`
ConnectionName string `json:"connectionName"`
ResourceType string `json:"resourceType"`
SystemMessage string `json:"systemMessage"`
ResourceOverview resourceCountOverview `json:"resourceOverview"`
Resources resourcesByManageType `json:"resources"`
}
type resourceCountOverview struct {
OnTumblebug int `json:"onTumblebug"`
OnSpider int `json:"onSpider"`
OnCspTotal int `json:"onCspTotal"`
OnCspOnly int `json:"onCspOnly"`
}
type resourcesByManageType struct {
OnTumblebug resourceOnTumblebug `json:"onTumblebug"`
OnSpider resourceOnSpider `json:"onSpider"`
OnCspTotal resourceOnCsp `json:"onCspTotal"`
OnCspOnly resourceOnCsp `json:"onCspOnly"`
}
type resourceOnSpider struct {
Count int `json:"count"`
Info []resourceOnSpiderInfo `json:"info"`
}
type resourceOnSpiderInfo struct {
IdBySp string `json:"idBySp"`
IdByCsp string `json:"idByCsp"`
}
type resourceOnCsp struct {
Count int `json:"count"`
Info []resourceOnCspInfo `json:"info"`
}
type resourceOnCspInfo struct {
IdByCsp string `json:"idByCsp"`
RefNameOrId string `json:"refNameOrId"`
}
type resourceOnTumblebug struct {
Count int `json:"count"`
Info []resourceOnTumblebugInfo `json:"info"`
}
type resourceOnTumblebugInfo struct {
IdByTb string `json:"idByTb"`
IdByCsp string `json:"idByCsp"`
NsId string `json:"nsId"`
McisId string `json:"mcisId,omitempty"`
ObjectKey string `json:"objectKey"`
}
// InspectResources returns the state list of TB MCIR objects of given connConfig and resourceType
func InspectResources(connConfig string, resourceType string) (InspectResource, error) {
nsList, err := common.ListNsId()
nullObj := InspectResource{}
if err != nil {
common.CBLog.Error(err)
err = fmt.Errorf("an error occurred while getting namespaces' list: " + err.Error())
return nullObj, err
}
TbResourceList := resourceOnTumblebug{}
for _, ns := range nsList {
// Bring TB resources
switch resourceType {
case common.StrNLB:
mcisListinNs, _ := ListMcisId(ns)
if mcisListinNs == nil {
continue
}
for _, mcis := range mcisListinNs {
nlbListInMcis, err := ListNLBId(ns, mcis)
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
if nlbListInMcis == nil {
continue
}
for _, nlbId := range nlbListInMcis {
nlb, err := GetNLB(ns, mcis, nlbId)
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
if nlb.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = nlb.Id
temp.IdByCsp = nlb.CspNLBId
temp.NsId = ns
temp.McisId = mcis
temp.ObjectKey = GenNLBKey(ns, mcis, nlb.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
}
case common.StrVM:
mcisListinNs, _ := ListMcisId(ns)
if mcisListinNs == nil {
continue
}
for _, mcis := range mcisListinNs {
vmListInMcis, err := ListVmId(ns, mcis)
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
if vmListInMcis == nil {
continue
}
for _, vmId := range vmListInMcis {
vm, err := GetVmObject(ns, mcis, vmId)
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
if vm.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = vm.Id
temp.IdByCsp = vm.CspViewVmDetail.IId.SystemId
temp.NsId = ns
temp.McisId = mcis
temp.ObjectKey = common.GenMcisKey(ns, mcis, vm.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
}
case common.StrVNet:
resourceListInNs, err := mcir.ListResource(ns, resourceType, "", "")
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
resourcesInNs := resourceListInNs.([]mcir.TbVNetInfo) // type assertion
if len(resourcesInNs) == 0 {
continue
}
for _, resource := range resourcesInNs {
if resource.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = resource.Id
temp.IdByCsp = resource.CspVNetId
temp.NsId = ns
temp.ObjectKey = common.GenResourceKey(ns, resourceType, resource.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
case common.StrSecurityGroup:
resourceListInNs, err := mcir.ListResource(ns, resourceType, "", "")
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
resourcesInNs := resourceListInNs.([]mcir.TbSecurityGroupInfo) // type assertion
if len(resourcesInNs) == 0 {
continue
}
for _, resource := range resourcesInNs {
if resource.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = resource.Id
temp.IdByCsp = resource.CspSecurityGroupId
temp.NsId = ns
temp.ObjectKey = common.GenResourceKey(ns, resourceType, resource.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
case common.StrSSHKey:
resourceListInNs, err := mcir.ListResource(ns, resourceType, "", "")
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
resourcesInNs := resourceListInNs.([]mcir.TbSshKeyInfo) // type assertion
if len(resourcesInNs) == 0 {
continue
}
for _, resource := range resourcesInNs {
if resource.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = resource.Id
temp.IdByCsp = resource.CspSshKeyId
temp.NsId = ns
temp.ObjectKey = common.GenResourceKey(ns, resourceType, resource.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
case common.StrDataDisk:
resourceListInNs, err := mcir.ListResource(ns, resourceType, "", "")
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
resourcesInNs := resourceListInNs.([]mcir.TbDataDiskInfo) // type assertion
if len(resourcesInNs) == 0 {
continue
}
for _, resource := range resourcesInNs {
if resource.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = resource.Id
temp.IdByCsp = resource.CspDataDiskId
temp.NsId = ns
temp.ObjectKey = common.GenResourceKey(ns, resourceType, resource.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
case common.StrCustomImage:
resourceListInNs, err := mcir.ListResource(ns, resourceType, "", "")
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while getting resource list")
return nullObj, err
}
resourcesInNs := resourceListInNs.([]mcir.TbCustomImageInfo) // type assertion
if len(resourcesInNs) == 0 {
continue
}
for _, resource := range resourcesInNs {
if resource.ConnectionName == connConfig { // filtering
temp := resourceOnTumblebugInfo{}
temp.IdByTb = resource.Id
temp.IdByCsp = resource.CspCustomImageId
temp.NsId = ns
temp.ObjectKey = common.GenResourceKey(ns, resourceType, resource.Id)
TbResourceList.Info = append(TbResourceList.Info, temp)
}
}
default:
err = fmt.Errorf("Invalid resourceType: " + resourceType)
return nullObj, err
}
}
client := resty.New().SetCloseConnection(true)
client.SetAllowGetMethodPayload(true)
// Create Req body
type JsonTemplate struct {
ConnectionName string
}
tempReq := JsonTemplate{}
tempReq.ConnectionName = connConfig
var spiderRequestURL string
switch resourceType {
case common.StrNLB:
spiderRequestURL = common.SpiderRestUrl + "/allnlb"
case common.StrVM:
spiderRequestURL = common.SpiderRestUrl + "/allvm"
case common.StrVNet:
spiderRequestURL = common.SpiderRestUrl + "/allvpc"
case common.StrSecurityGroup:
spiderRequestURL = common.SpiderRestUrl + "/allsecuritygroup"
case common.StrSSHKey:
spiderRequestURL = common.SpiderRestUrl + "/allkeypair"
case common.StrDataDisk:
spiderRequestURL = common.SpiderRestUrl + "/alldisk"
case common.StrCustomImage:
spiderRequestURL = common.SpiderRestUrl + "/allmyimage"
default:
err = fmt.Errorf("Invalid resourceType: " + resourceType)
return nullObj, err
}
resp, err := client.R().
SetHeader("Content-Type", "application/json").
SetBody(tempReq).
SetResult(&SpiderAllListWrapper{}). // or SetResult(AuthSuccess{}).
//SetError(&AuthError{}). // or SetError(AuthError{}).
Get(spiderRequestURL)
if err != nil {
common.CBLog.Error(err)
err := fmt.Errorf("an error occurred while requesting to CB-Spider")
return nullObj, err
}
fmt.Println("HTTP Status code: " + strconv.Itoa(resp.StatusCode()))
switch {
case resp.StatusCode() >= 400 || resp.StatusCode() < 200:
err := fmt.Errorf(string(resp.Body()))
common.CBLog.Error(err)
return nullObj, err
default:
}
temp, _ := resp.Result().(*SpiderAllListWrapper) // type assertion
result := InspectResource{}
/*
// Implementation style 1
if len(TbResourceList) > 0 {
result.ResourcesOnTumblebug = TbResourceList
} else {
result.ResourcesOnTumblebug = []resourceOnTumblebug{}
}
*/
// Implementation style 2
result.ConnectionName = connConfig
result.ResourceType = resourceType
result.Resources.OnTumblebug = TbResourceList
//result.ResourcesOnTumblebug.Info = append(result.ResourcesOnTumblebug.Info, TbResourceList...)
// result.ResourcesOnCsp = append((*temp).AllList.MappedList, (*temp).AllList.OnlyCSPList...)
// result.ResourcesOnSpider = append((*temp).AllList.MappedList, (*temp).AllList.OnlySpiderList...)
result.Resources.OnSpider = resourceOnSpider{}
result.Resources.OnCspTotal = resourceOnCsp{}
result.Resources.OnCspOnly = resourceOnCsp{}
tmpResourceOnSpider := resourceOnSpiderInfo{}
tmpResourceOnCsp := resourceOnCspInfo{}
for _, v := range (*temp).AllList.MappedList {
tmpResourceOnSpider.IdBySp = v.NameId
tmpResourceOnSpider.IdByCsp = v.SystemId
result.Resources.OnSpider.Info = append(result.Resources.OnSpider.Info, tmpResourceOnSpider)
tmpResourceOnCsp.IdByCsp = v.SystemId
tmpResourceOnCsp.RefNameOrId = v.NameId
result.Resources.OnCspTotal.Info = append(result.Resources.OnCspTotal.Info, tmpResourceOnCsp)
}
for _, v := range (*temp).AllList.OnlySpiderList {
tmpResourceOnSpider.IdBySp = v.NameId
tmpResourceOnSpider.IdByCsp = v.SystemId
result.Resources.OnSpider.Info = append(result.Resources.OnSpider.Info, tmpResourceOnSpider)
}
for _, v := range (*temp).AllList.OnlyCSPList {
tmpResourceOnCsp.IdByCsp = v.SystemId
tmpResourceOnCsp.RefNameOrId = v.NameId
result.Resources.OnCspTotal.Info = append(result.Resources.OnCspTotal.Info, tmpResourceOnCsp)
result.Resources.OnCspOnly.Info = append(result.Resources.OnCspOnly.Info, tmpResourceOnCsp)
}
// Count resources
result.Resources.OnTumblebug.Count = len(result.Resources.OnTumblebug.Info)
result.Resources.OnSpider.Count = len(result.Resources.OnSpider.Info)
result.Resources.OnCspTotal.Count = len(result.Resources.OnCspTotal.Info)
result.Resources.OnCspOnly.Count = len(result.Resources.OnCspOnly.Info)
result.ResourceOverview.OnTumblebug = result.Resources.OnTumblebug.Count
result.ResourceOverview.OnSpider = result.Resources.OnSpider.Count
result.ResourceOverview.OnCspTotal = result.Resources.OnCspTotal.Count
result.ResourceOverview.OnCspOnly = result.Resources.OnCspOnly.Count
return result, nil
}
// InspectResourceAllResult is struct for Inspect Resource Result for All Clouds
type InspectResourceAllResult struct {
ElapsedTime int `json:"elapsedTime"`
RegisteredConnection int `json:"registeredConnection"`
AvailableConnection int `json:"availableConnection"`
TumblebugOverview inspectOverview `json:"tumblebugOverview"`
CspOnlyOverview inspectOverview `json:"cspOnlyOverview"`
InspectResult []InspectResourceResult `json:"inspectResult"`
}
// InspectResourceResult is struct for Inspect Resource Result
type InspectResourceResult struct {
ConnectionName string `json:"connectionName"`
SystemMessage string `json:"systemMessage"`
ElapsedTime int `json:"elapsedTime"`
TumblebugOverview inspectOverview `json:"tumblebugOverview"`
CspOnlyOverview inspectOverview `json:"cspOnlyOverview"`
}
type inspectOverview struct {
VNet int `json:"vNet"`
SecurityGroup int `json:"securityGroup"`
SshKey int `json:"sshKey"`
DataDisk int `json:"dataDisk"`
CustomImage int `json:"customImage"`
Vm int `json:"vm"`
NLB int `json:"nlb"`
}
// InspectResourcesOverview func is to check all resources in CB-TB and CSPs
func InspectResourcesOverview() (InspectResourceAllResult, error) {
startTime := time.Now()
connectionConfigList, err := common.GetConnConfigList()
if err != nil {
err := fmt.Errorf("Cannot load ConnectionConfigList")
common.CBLog.Error(err)
return InspectResourceAllResult{}, err
}
output := InspectResourceAllResult{}
var wait sync.WaitGroup
for _, k := range connectionConfigList.Connectionconfig {
wait.Add(1)
go func(k common.ConnConfig) {
defer wait.Done()
common.RandomSleep(0, 60)
temp := InspectResourceResult{}
temp.ConnectionName = k.ConfigName
startTimeForConnection := time.Now()
inspectResult, err := InspectResources(k.ConfigName, common.StrVNet)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage = err.Error()
}
// retry if request rateLimitExceeded occurs. (GCP has ratelimiting)
rateLimitMessage := "limit"
maxTrials := 5
if strings.Contains(temp.SystemMessage, rateLimitMessage) {
for i := 0; i < maxTrials; i++ {
common.RandomSleep(40, 80)
inspectResult, err = InspectResources(k.ConfigName, common.StrVNet)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage = err.Error()
} else {
temp.SystemMessage = ""
break
}
}
}
temp.TumblebugOverview.VNet = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.VNet = inspectResult.ResourceOverview.OnCspOnly
inspectResult, err = InspectResources(k.ConfigName, common.StrSecurityGroup)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage += err.Error()
}
temp.TumblebugOverview.SecurityGroup = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.SecurityGroup = inspectResult.ResourceOverview.OnCspOnly
inspectResult, err = InspectResources(k.ConfigName, common.StrSSHKey)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage += err.Error()
}
temp.TumblebugOverview.SshKey = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.SshKey = inspectResult.ResourceOverview.OnCspOnly
inspectResult, err = InspectResources(k.ConfigName, common.StrDataDisk)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage += err.Error()
}
temp.TumblebugOverview.DataDisk = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.DataDisk = inspectResult.ResourceOverview.OnCspOnly
inspectResult, err = InspectResources(k.ConfigName, common.StrCustomImage)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage += err.Error()
}
temp.TumblebugOverview.CustomImage = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.CustomImage = inspectResult.ResourceOverview.OnCspOnly
inspectResult, err = InspectResources(k.ConfigName, common.StrVM)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage += err.Error()
}
temp.TumblebugOverview.Vm = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.Vm = inspectResult.ResourceOverview.OnCspOnly
inspectResult, err = InspectResources(k.ConfigName, common.StrNLB)
if err != nil {
common.CBLog.Error(err)
temp.SystemMessage += err.Error()
}
temp.TumblebugOverview.NLB = inspectResult.ResourceOverview.OnTumblebug
temp.CspOnlyOverview.NLB = inspectResult.ResourceOverview.OnCspOnly
temp.ElapsedTime = int(math.Round(time.Now().Sub(startTimeForConnection).Seconds()))
output.InspectResult = append(output.InspectResult, temp)
}(k)
}
wait.Wait()
errorConnectionCnt := 0
for _, k := range output.InspectResult {
output.TumblebugOverview.VNet += k.TumblebugOverview.VNet
output.TumblebugOverview.SecurityGroup += k.TumblebugOverview.SecurityGroup
output.TumblebugOverview.SshKey += k.TumblebugOverview.SshKey
output.TumblebugOverview.DataDisk += k.TumblebugOverview.DataDisk
output.TumblebugOverview.CustomImage += k.TumblebugOverview.CustomImage
output.TumblebugOverview.Vm += k.TumblebugOverview.Vm
output.TumblebugOverview.NLB += k.TumblebugOverview.NLB
output.CspOnlyOverview.VNet += k.CspOnlyOverview.VNet
output.CspOnlyOverview.SecurityGroup += k.CspOnlyOverview.SecurityGroup
output.CspOnlyOverview.SshKey += k.CspOnlyOverview.SshKey
output.CspOnlyOverview.DataDisk += k.CspOnlyOverview.DataDisk
output.CspOnlyOverview.CustomImage += k.CspOnlyOverview.CustomImage
output.CspOnlyOverview.Vm += k.CspOnlyOverview.Vm
output.CspOnlyOverview.NLB += k.CspOnlyOverview.NLB
if k.SystemMessage != "" {
errorConnectionCnt++
}
}
sort.SliceStable(output.InspectResult, func(i, j int) bool {
return output.InspectResult[i].ConnectionName < output.InspectResult[j].ConnectionName
})
output.ElapsedTime = int(math.Round(time.Now().Sub(startTime).Seconds()))
output.RegisteredConnection = len(connectionConfigList.Connectionconfig)
output.AvailableConnection = output.RegisteredConnection - errorConnectionCnt
return output, err
}
// RegisterResourceAllResult is struct for Register Csp Native Resource Result for All Clouds
type RegisterResourceAllResult struct {
ElapsedTime int `json:"elapsedTime"`
RegisteredConnection int `json:"registeredConnection"`
AvailableConnection int `json:"availableConnection"`
RegisterationOverview registerationOverview `json:"registerationOverview"`
RegisterationResult []RegisterResourceResult `json:"registerationResult"`
}
// RegisterResourceResult is struct for Register Csp Native Resource Result
type RegisterResourceResult struct {
ConnectionName string `json:"connectionName"`
SystemMessage string `json:"systemMessage"`
ElapsedTime int `json:"elapsedTime"`
RegisterationOverview registerationOverview `json:"registerationOverview"`
RegisterationOutputs common.IdList `json:"registerationOutputs"`
}
type registerationOverview struct {
VNet int `json:"vNet"`
SecurityGroup int `json:"securityGroup"`
SshKey int `json:"sshKey"`
DataDisk int `json:"dataDisk"`
CustomImage int `json:"customImage"`
Vm int `json:"vm"`
NLB int `json:"nlb"`
Failed int `json:"failed"`
}
// RegisterCspNativeResourcesAll func registers all CSP-native resources into CB-TB
func RegisterCspNativeResourcesAll(nsId string, mcisId string, option string, mcisFlag string) (RegisterResourceAllResult, error) {
startTime := time.Now()
connectionConfigList, err := common.GetConnConfigList()
if err != nil {
err := fmt.Errorf("Cannot load ConnectionConfigList")
common.CBLog.Error(err)
return RegisterResourceAllResult{}, err
}
output := RegisterResourceAllResult{}
var wait sync.WaitGroup
for _, k := range connectionConfigList.Connectionconfig {
wait.Add(1)
go func(k common.ConnConfig) {
defer wait.Done()
mcisNameForRegister := mcisId + "-" + k.ConfigName
// Assign RandomSleep range by clouds
// This code is temporal, CB-Spider needs to be enhnaced for locking mechanism.
// CB-SP v0.5.9 will not help with rate limit issue.
if option != "onlyVm" {
if strings.Contains(k.ConfigName, "alibaba") {
common.RandomSleep(100, 200)
} else if strings.Contains(k.ConfigName, "aws") {
common.RandomSleep(300, 500)
} else if strings.Contains(k.ConfigName, "gcp") {
common.RandomSleep(700, 900)
} else {
}
}
common.RandomSleep(0, 50)
registerResult, err := RegisterCspNativeResources(nsId, k.ConfigName, mcisNameForRegister, option, mcisFlag)
if err != nil {
common.CBLog.Error(err)
}
output.RegisterationResult = append(output.RegisterationResult, registerResult)
}(k)
}
wait.Wait()
errorConnectionCnt := 0
for _, k := range output.RegisterationResult {
output.RegisterationOverview.VNet += k.RegisterationOverview.VNet
output.RegisterationOverview.SecurityGroup += k.RegisterationOverview.SecurityGroup
output.RegisterationOverview.SshKey += k.RegisterationOverview.SshKey
output.RegisterationOverview.DataDisk += k.RegisterationOverview.DataDisk
output.RegisterationOverview.CustomImage += k.RegisterationOverview.CustomImage
output.RegisterationOverview.Vm += k.RegisterationOverview.Vm
output.RegisterationOverview.NLB += k.RegisterationOverview.NLB
output.RegisterationOverview.Failed += k.RegisterationOverview.Failed
if k.SystemMessage != "" {
errorConnectionCnt++
}
}
output.ElapsedTime = int(math.Round(time.Now().Sub(startTime).Seconds()))
output.RegisteredConnection = len(connectionConfigList.Connectionconfig)
output.AvailableConnection = output.RegisteredConnection - errorConnectionCnt
sort.SliceStable(output.RegisterationResult, func(i, j int) bool {
return output.RegisterationResult[i].ConnectionName < output.RegisterationResult[j].ConnectionName
})
return output, err
}
// RegisterCspNativeResources func registers all CSP-native resources into CB-TB
func RegisterCspNativeResources(nsId string, connConfig string, mcisId string, option string, mcisFlag string) (RegisterResourceResult, error) {
startTime := time.Now()
optionFlag := "register"
registeredStatus := ""
result := RegisterResourceResult{}
startTime01 := time.Now() //tmp
var err error
if option != "onlyVm" {
// bring vNet list and register all
inspectedResources, err := InspectResources(connConfig, common.StrVNet)
if err != nil {
common.CBLog.Error(err)
result.SystemMessage = err.Error()
}
for _, r := range inspectedResources.Resources.OnCspOnly.Info {
req := mcir.TbVNetReq{}
req.ConnectionName = connConfig
req.CspVNetId = r.IdByCsp
req.Description = "Ref name: " + r.RefNameOrId + ". CSP managed resource (registered to CB-TB)"
req.Name = req.ConnectionName + "-" + req.CspVNetId
req.Name = common.ChangeIdString(req.Name)
_, err = mcir.CreateVNet(nsId, &req, optionFlag)
registeredStatus = ""
if err != nil {
common.CBLog.Error(err)
registeredStatus = " [Failed] " + err.Error()
result.RegisterationOverview.VNet--
result.RegisterationOverview.Failed++
}
result.RegisterationOutputs.IdList = append(result.RegisterationOutputs.IdList, common.StrVNet+": "+req.Name+registeredStatus)
result.RegisterationOverview.VNet++
}
fmt.Printf("\n\n%s [Elapsed]%s %d \n\n", connConfig, common.StrVNet, int(math.Round(time.Now().Sub(startTime01).Seconds()))) //tmp
startTime02 := time.Now() //tmp
// bring SecurityGroup list and register all
inspectedResources, err = InspectResources(connConfig, common.StrSecurityGroup)
if err != nil {
common.CBLog.Error(err)
result.SystemMessage += "//" + err.Error()