-
Notifications
You must be signed in to change notification settings - Fork 48
/
VPCHandler.go
1494 lines (1288 loc) · 44.3 KB
/
VPCHandler.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
// Cloud Driver Interface of CB-Spider.
// The CB-Spider is a sub-Framework of the Cloud-Barista Multi-Cloud Project.
// The CB-Spider Mission is to connect all the clouds with a single interface.
//
// * Cloud-Barista: https://github.com/cloud-barista
//
// This is Resouces interfaces of Cloud Driver.
//
// by devunet@mz.co.kr
package resources
import (
"errors"
"strconv"
call "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/call-log"
idrv "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces"
irs "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces/resources"
"github.com/davecgh/go-spew/spew"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
vpc "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/vpc/v20170312"
)
type TencentVPCHandler struct {
Region idrv.RegionInfo
Client *vpc.Client
}
func (VPCHandler *TencentVPCHandler) CreateVPC(vpcReqInfo irs.VPCReqInfo) (irs.VPCInfo, error) {
cblogger.Info(vpcReqInfo)
//=================================================
// 동일 이름 생성 방지 추가(cb-spider 요청 필수 기능)
//=================================================
isExist, errExist := VPCHandler.isExist(vpcReqInfo.IId.NameId)
if errExist != nil {
cblogger.Error(errExist)
return irs.VPCInfo{}, errExist
}
if isExist {
return irs.VPCInfo{}, errors.New("A VPC with the name " + vpcReqInfo.IId.NameId + " already exists.")
}
zoneId := VPCHandler.Region.Zone
cblogger.Infof("Zone : %s", zoneId)
if zoneId == "" {
cblogger.Error("Connection 정보에 Zone 정보가 없습니다.")
return irs.VPCInfo{}, errors.New("Connection 정보에 Zone 정보가 없습니다.")
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: vpcReqInfo.IId.NameId,
CloudOSAPI: "CreateVpc()",
ElapsedTime: "",
ErrorMSG: "",
}
//=========================
// VPC 생성
//=========================
request := vpc.NewCreateVpcRequest()
request.VpcName = common.StringPtr(vpcReqInfo.IId.NameId)
request.CidrBlock = common.StringPtr(vpcReqInfo.IPv4_CIDR)
callLogStart := call.Start()
response, err := VPCHandler.Client.CreateVpc(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
cblogger.Debug(response.ToJsonString())
//spew.Dump(result)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return irs.VPCInfo{}, err
}
callogger.Info(call.String(callLogInfo))
newVpcId := *response.Response.Vpc.VpcId // Subnet이 포함된 정보를 전달해야 하기 때문에 생성된 VPC Id를 보관함.
//=========================
// Subnet 생성
//========================
requestSubnet := vpc.NewCreateSubnetsRequest()
requestSubnet.VpcId = common.StringPtr(newVpcId)
requestSubnet.Subnets = []*vpc.SubnetInput{}
for _, curSubnet := range vpcReqInfo.SubnetInfoList {
cblogger.Infof("[%s] Subnet 처리", curSubnet.IId.NameId)
reqSubnet := &vpc.SubnetInput{
CidrBlock: common.StringPtr(curSubnet.IPv4_CIDR),
SubnetName: common.StringPtr(curSubnet.IId.NameId),
Zone: common.StringPtr(zoneId),
//RouteTableId: common.StringPtr("route"),
}
requestSubnet.Subnets = append(requestSubnet.Subnets, reqSubnet)
}
responseSubnet, errSubnet := VPCHandler.Client.CreateSubnets(requestSubnet)
cblogger.Debug(responseSubnet.ToJsonString())
spew.Dump(responseSubnet)
if errSubnet != nil {
cblogger.Error(errSubnet)
return irs.VPCInfo{}, errSubnet
}
//신규로 생성된 VPC와 Subnet 정보를 irs.VPCInfo{}로 치환해도 되지만 수정의 편의및 최신 정보 통일을 위해 GetVPC롤 호출함.
//생성된 Subnet을 포함한 VPC의 최신 정보를 조회함.
retVpcInfo, errVpc := VPCHandler.GetVPC(irs.IID{SystemId: newVpcId})
if errVpc != nil {
cblogger.Error(errVpc)
return irs.VPCInfo{}, errVpc
}
retVpcInfo.IId.NameId = vpcReqInfo.IId.NameId // 생성 시에는 NameId는 cb-spider를 위해 요청 받은 값을 그대로 리턴해야 함.
return retVpcInfo, nil
}
//VPC 정보를 추출함
func ExtractVpcDescribeInfo(vpcInfo *vpc.Vpc) irs.VPCInfo {
// cblogger.Debug("전달 받은 내용")
// spew.Dump(vpcInfo)
resVpcInfo := irs.VPCInfo{
//NameId는 사용되지 않기 때문에 전달할 필요가 없지만 Tencent는 Name도 필수로 들어가니 전달함.
IId: irs.IID{SystemId: *vpcInfo.VpcId, NameId: *vpcInfo.VpcName},
IPv4_CIDR: *vpcInfo.CidrBlock,
}
return resVpcInfo
}
func (VPCHandler *TencentVPCHandler) ListVPC() ([]*irs.VPCInfo, error) {
cblogger.Info("Start")
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: "ListVPC",
CloudOSAPI: "DescribeVpcs()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDescribeVpcsRequest()
callLogStart := call.Start()
response, err := VPCHandler.Client.DescribeVpcs(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
cblogger.Debug(response.ToJsonString())
//spew.Dump(result)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return nil, err
}
callogger.Info(call.String(callLogInfo))
cblogger.Info("VPC 개수 : ", *response.Response.TotalCount)
var vpcInfoList []*irs.VPCInfo
if *response.Response.TotalCount > 0 {
for _, curVpc := range response.Response.VpcSet {
cblogger.Debugf("[%s] VPC 정보 조회 - [%s]", *curVpc.VpcId, *curVpc.VpcName)
vpcInfo, vpcErr := VPCHandler.GetVPC(irs.IID{SystemId: *curVpc.VpcId})
// cblogger.Info("==>조회 결과")
// spew.Dump(vpcInfo)
if vpcErr != nil {
cblogger.Error(vpcErr)
return nil, vpcErr
}
vpcInfoList = append(vpcInfoList, &vpcInfo)
}
}
cblogger.Debugf("리턴 결과 목록 수 : [%d]", len(vpcInfoList))
// spew.Dump(vpcInfoList)
return vpcInfoList, nil
}
// cb-spider 정책상 이름 기반으로 중복 생성을 막아야 함.
func (VPCHandler *TencentVPCHandler) isExist(chkName string) (bool, error) {
cblogger.Debugf("chkName : %s", chkName)
request := vpc.NewDescribeVpcsRequest()
request.Filters = []*vpc.Filter{
&vpc.Filter{
Name: common.StringPtr("vpc-name"),
Values: common.StringPtrs([]string{chkName}),
},
}
response, err := VPCHandler.Client.DescribeVpcs(request)
if err != nil {
cblogger.Error(err)
return false, err
}
if *response.Response.TotalCount < 1 {
return false, nil
}
cblogger.Infof("VPC 정보 찾음 - VpcId:[%s] / VpcName:[%s]", *response.Response.VpcSet[0].VpcId, *response.Response.VpcSet[0].VpcName)
return true, nil
}
func (VPCHandler *TencentVPCHandler) GetVPC(vpcIID irs.IID) (irs.VPCInfo, error) {
cblogger.Info("VPC IID : ", vpcIID.SystemId)
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: "GetVPC",
CloudOSAPI: "DescribeVpcs()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDescribeVpcsRequest()
request.VpcIds = common.StringPtrs([]string{vpcIID.SystemId})
callLogStart := call.Start()
response, err := VPCHandler.Client.DescribeVpcs(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
cblogger.Errorf("An API error has returned: %s", err.Error())
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
return irs.VPCInfo{}, err
}
callogger.Info(call.String(callLogInfo))
cblogger.Debug("VPC 개수 : ", *response.Response.TotalCount)
if *response.Response.TotalCount < 1 {
return irs.VPCInfo{}, errors.New("Notfound: '" + vpcIID.SystemId + "' VPC Not found")
}
vpcInfo := ExtractVpcDescribeInfo(response.Response.VpcSet[0])
cblogger.Debug(vpcInfo)
//=======================
// Subnet 처리
//=======================
var errSubnet error
vpcInfo.SubnetInfoList, errSubnet = VPCHandler.ListSubnet(vpcIID.SystemId)
if errSubnet != nil {
callogger.Error(errSubnet)
return vpcInfo, errSubnet
}
return vpcInfo, nil
}
func (VPCHandler *TencentVPCHandler) DeleteVPC(vpcIID irs.IID) (bool, error) {
cblogger.Infof("Delete VPC : [%s]", vpcIID.SystemId)
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: vpcIID.SystemId,
CloudOSAPI: "DeleteVpc()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDeleteVpcRequest()
request.VpcId = common.StringPtr(vpcIID.SystemId)
callLogStart := call.Start()
_, err := VPCHandler.Client.DeleteVpc(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
cblogger.Errorf("An API error has returned: %s", err.Error())
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
return false, err
}
callogger.Info(call.String(callLogInfo))
return true, nil
}
func (VPCHandler *TencentVPCHandler) ListSubnet(reqVpcId string) ([]irs.SubnetInfo, error) {
cblogger.Infof("reqVpcId : [%s]", reqVpcId)
var arrSubnetInfoList []irs.SubnetInfo
/*
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: "ListSubnet - VpcId:" + reqVpcId,
CloudOSAPI: "DescribeSubnets()",
ElapsedTime: "",
ErrorMSG: "",
}
*/
request := vpc.NewDescribeSubnetsRequest()
request.Filters = []*vpc.Filter{
&vpc.Filter{
Name: common.StringPtr("vpc-id"),
Values: common.StringPtrs([]string{reqVpcId}),
},
}
// callLogStart := call.Start()
response, err := VPCHandler.Client.DescribeSubnets(request)
// callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
//cblogger.Debug(response.ToJsonString())
spew.Dump(response)
if err != nil {
// callLogInfo.ErrorMSG = err.Error()
// callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return nil, err
}
// callogger.Info(call.String(callLogInfo))
for _, curSubnet := range response.Response.SubnetSet {
cblogger.Infof("[%s] Subnet 정보 조회", *curSubnet.SubnetId)
resSubnetInfo := irs.SubnetInfo{
IId: irs.IID{SystemId: *curSubnet.SubnetId, NameId: *curSubnet.SubnetName},
IPv4_CIDR: *curSubnet.CidrBlock,
//Status: *subnetInfo.State,
}
keyValueList := []irs.KeyValue{
{Key: "VpcId", Value: *curSubnet.VpcId},
{Key: "IsDefault", Value: strconv.FormatBool(*curSubnet.IsDefault)},
{Key: "AvailabilityZone", Value: *curSubnet.Zone},
}
resSubnetInfo.KeyValueList = keyValueList
arrSubnetInfoList = append(arrSubnetInfoList, resSubnetInfo)
}
return arrSubnetInfoList, nil
}
// 동일 이름으로 생성되는 것을 막기 위해 중복 체크함.
// reqSubnetNameId : 서브넷 Name
func (VPCHandler *TencentVPCHandler) isExistSubnet(reqSubnetNameId string) (bool, error) {
cblogger.Infof("reqSubnetNameId : [%s]", reqSubnetNameId)
request := vpc.NewDescribeSubnetsRequest()
request.Filters = []*vpc.Filter{
&vpc.Filter{
Name: common.StringPtr("subnet-name"),
Values: common.StringPtrs([]string{reqSubnetNameId}),
},
}
//spew.Dump(request)
response, err := VPCHandler.Client.DescribeSubnets(request)
//cblogger.Debug("서브넷 실행 결과")
//spew.Dump(response)
if err != nil {
cblogger.Error(err)
return false, err
}
if *response.Response.TotalCount < 1 {
return false, nil
}
return true, nil
}
func (VPCHandler *TencentVPCHandler) AddSubnet(vpcIID irs.IID, subnetInfo irs.SubnetInfo) (irs.VPCInfo, error) {
cblogger.Infof("[%s] Subnet 추가 - CIDR : %s", subnetInfo.IId.NameId, subnetInfo.IPv4_CIDR)
zoneId := VPCHandler.Region.Zone
cblogger.Infof("Zone : %s", zoneId)
if zoneId == "" {
cblogger.Error("Connection 정보에 Zone 정보가 없습니다.")
return irs.VPCInfo{}, errors.New("Connection 정보에 Zone 정보가 없습니다.")
}
if subnetInfo.IId.NameId == "" {
return irs.VPCInfo{}, errors.New("생성할 SubnetId 정보가 없습니다.")
}
isExit, errSubnetInfo := VPCHandler.isExistSubnet(subnetInfo.IId.NameId)
if errSubnetInfo != nil {
cblogger.Error(errSubnetInfo)
return irs.VPCInfo{}, errSubnetInfo
}
cblogger.Info("Subnet 존재여부 : ")
cblogger.Info(isExit)
if isExit {
cblogger.Errorf("이미 [%S] Subnet이 존재하기 때문에 생성하지 않고 기존 정보와 함께 에러를 리턴함.", subnetInfo.IId.NameId)
return irs.VPCInfo{}, errors.New("InvalidVNetwork.Duplicate: The Subnet '" + subnetInfo.IId.NameId + "' already exists.")
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: vpcIID.SystemId,
CloudOSAPI: "CreateSubnet()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewCreateSubnetRequest()
request.VpcId = common.StringPtr(vpcIID.SystemId)
request.SubnetName = common.StringPtr(subnetInfo.IId.NameId)
request.CidrBlock = common.StringPtr(subnetInfo.IPv4_CIDR)
request.Zone = common.StringPtr(VPCHandler.Region.Zone)
callLogStart := call.Start()
response, err := VPCHandler.Client.CreateSubnet(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
cblogger.Debug(response.ToJsonString())
spew.Dump(response)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return irs.VPCInfo{}, err
}
callogger.Info(call.String(callLogInfo))
retVpcInfo, errVpcInfo := VPCHandler.GetVPC(vpcIID)
if errVpcInfo != nil {
cblogger.Error(errVpcInfo)
return irs.VPCInfo{}, err
}
//retVpcInfo.SubnetInfoList[0].IId.NameId = vpcReqInfo.IId.NameId // 생성 시에는 NameId는 요청 받은 값으로 리턴해야 함.
return retVpcInfo, nil
}
func (VPCHandler *TencentVPCHandler) RemoveSubnet(vpcIID irs.IID, subnetIID irs.IID) (bool, error) {
cblogger.Infof("[%s] VPC의 [%s] Subnet 삭제", vpcIID.SystemId, subnetIID.SystemId)
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.TENCENT,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: vpcIID.SystemId,
CloudOSAPI: "DeleteSubnet()",
ElapsedTime: "",
ErrorMSG: "",
}
request := vpc.NewDeleteSubnetRequest()
request.SubnetId = common.StringPtr(subnetIID.SystemId)
callLogStart := call.Start()
response, err := VPCHandler.Client.DeleteSubnet(request)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
cblogger.Debug(response.ToJsonString())
//spew.Dump(response)
if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Error(call.String(callLogInfo))
cblogger.Error(err)
return false, err
}
callogger.Info(call.String(callLogInfo))
return true, nil
}
/*
func (VPCHandler *TencentVPCHandler) CreateVPC(vpcReqInfo irs.VPCReqInfo) (irs.VPCInfo, error) {
cblogger.Info(vpcReqInfo)
zoneId := VPCHandler.Region.Zone
cblogger.Infof("Zone : %s", zoneId)
if zoneId == "" {
cblogger.Error("Connection 정보에 Zone 정보가 없습니다.")
return irs.VPCInfo{}, errors.New("Connection 정보에 Zone 정보가 없습니다.")
}
input := &ec2.CreateVpcInput{
CidrBlock: aws.String(vpcReqInfo.IPv4_CIDR),
}
spew.Dump(input)
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.AWS,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: vpcReqInfo.IId.NameId,
CloudOSAPI: "CreateVpc()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
result, err := VPCHandler.Client.CreateVpc(input)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
callLogInfo.ErrorMSG = aerr.Error()
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
callLogInfo.ErrorMSG = err.Error()
}
callogger.Info(call.String(callLogInfo))
return irs.VPCInfo{}, err
}
callogger.Info(call.String(callLogInfo))
cblogger.Info(result)
spew.Dump(result)
retVpcInfo := ExtractVpcDescribeInfo(result.Vpc)
retVpcInfo.IId.NameId = vpcReqInfo.IId.NameId // NameId는 요청 받은 값으로 리턴해야 함.
//IGW Name Tag 설정
if SetNameTag(VPCHandler.Client, *result.Vpc.VpcId, vpcReqInfo.IId.NameId) {
cblogger.Infof("VPC에 %s Name 설정 성공", vpcReqInfo.IId.NameId)
} else {
cblogger.Errorf("VPC에 %s Name 설정 실패", vpcReqInfo.IId.NameId)
}
//====================================
// PublicIP 할당을 위해 IGW 생성및 연결
//====================================
//IGW 생성
resultIGW, errIGW := VPCHandler.Client.CreateInternetGateway(&ec2.CreateInternetGatewayInput{})
if errIGW != nil {
if aerr, ok := errIGW.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(errIGW.Error())
}
return retVpcInfo, errIGW
}
cblogger.Info(resultIGW)
//IGW Name Tag 설정
if SetNameTag(VPCHandler.Client, *resultIGW.InternetGateway.InternetGatewayId, vpcReqInfo.IId.NameId) {
cblogger.Infof("IGW에 %s Name 설정 성공", vpcReqInfo.IId.NameId)
} else {
cblogger.Errorf("IGW에 %s Name 설정 실패", vpcReqInfo.IId.NameId)
}
// VPC에 IGW연결
inputIGW := &ec2.AttachInternetGatewayInput{
InternetGatewayId: aws.String(*resultIGW.InternetGateway.InternetGatewayId),
VpcId: aws.String(retVpcInfo.IId.SystemId),
}
resultIGWAttach, errIGWAttach := VPCHandler.Client.AttachInternetGateway(inputIGW)
if err != nil {
if aerr, ok := errIGWAttach.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(errIGWAttach.Error())
}
return retVpcInfo, errIGWAttach
}
cblogger.Info(resultIGWAttach)
// 생성된 VPC의 기본 라우팅 테이블에 IGW 라우팅 정보 추가
errRoute := VPCHandler.CreateRouteIGW(retVpcInfo.IId.SystemId, *resultIGW.InternetGateway.InternetGatewayId)
if errRoute != nil {
return retVpcInfo, errRoute
}
//==========================
// Subnet 생성
//==========================
//VPCHandler.CreateSubnet(retVpcInfo.IId.SystemId, vpcReqInfo.SubnetInfoList[0])
var resSubnetList []irs.SubnetInfo
for _, curSubnet := range vpcReqInfo.SubnetInfoList {
cblogger.Infof("[%s] Subnet 생성", curSubnet.IId.NameId)
cblogger.Infof("Reqt Subnet Info [%v]", curSubnet)
resSubnet, errSubnet := VPCHandler.CreateSubnet(retVpcInfo.IId.SystemId, curSubnet)
if errSubnet != nil {
return retVpcInfo, errSubnet
}
resSubnetList = append(resSubnetList, resSubnet)
}
retVpcInfo.SubnetInfoList = resSubnetList
return retVpcInfo, nil
}
// 생성된 VPC의 라우팅 테이블에 IGW(Internet Gateway) 라우팅 정보를 생성함 (AWS 콘솔의 라우팅 테이블의 [라우팅] Tab 처리)
func (VPCHandler *TencentVPCHandler) CreateRouteIGW(vpcId string, igwId string) error {
cblogger.Infof("VPC ID : [%s] / IGW ID : [%s]", vpcId, igwId)
routeTableId, errRoute := VPCHandler.GetDefaultRouteTable(vpcId)
if errRoute != nil {
return errRoute
}
cblogger.Infof("RouteTable[%s]에 IGW[%s]에 대한 라우팅(0.0.0.0/0) 정보를 추가 합니다.", routeTableId, igwId)
input := &ec2.CreateRouteInput{
DestinationCidrBlock: aws.String("0.0.0.0/0"),
GatewayId: aws.String(igwId),
RouteTableId: aws.String(routeTableId),
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.AWS,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: igwId,
CloudOSAPI: "CreateRoute()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
result, err := VPCHandler.Client.CreateRoute(input)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
cblogger.Errorf("RouteTable[%s]에 IGW[%s]에 대한 라우팅(0.0.0.0/0) 정보 추가 실패", routeTableId, igwId)
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
callLogInfo.ErrorMSG = aerr.Error()
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
callLogInfo.ErrorMSG = err.Error()
}
callogger.Info(call.String(callLogInfo))
return err
}
cblogger.Infof("RouteTable[%s]에 IGW[%s]에 대한 라우팅(0.0.0.0/0) 정보를 추가 완료", routeTableId, igwId)
callogger.Info(call.String(callLogInfo))
cblogger.Info(result)
spew.Dump(result)
return nil
}
//https://docs.aws.amazon.com/ko_kr/vpc/latest/userguide/VPC_Route_Tables.html
//https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeRouteTables.html
// 자동 생성된 VPC의 기본 라우팅 테이블 정보를 찾음
func (VPCHandler *TencentVPCHandler) GetDefaultRouteTable(vpcId string) (string, error) {
input := &ec2.DescribeRouteTablesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{
aws.String(vpcId),
},
},
},
}
result, err := VPCHandler.Client.DescribeRouteTables(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
}
return "", err
}
cblogger.Info(result)
spew.Dump(result)
if len(result.RouteTables) > 0 {
routeTableId := *result.RouteTables[0].RouteTableId
cblogger.Infof("라우팅 테이블 ID 찾음 : [%s]", routeTableId)
return routeTableId, nil
} else {
return "", errors.New("VPC에 할당된 라우팅 테이블 ID를 찾을 수 없습니다.")
}
}
func (VPCHandler *TencentVPCHandler) CreateSubnet(vpcId string, reqSubnetInfo irs.SubnetInfo) (irs.SubnetInfo, error) {
cblogger.Info(reqSubnetInfo)
zoneId := VPCHandler.Region.Zone
cblogger.Infof("Zone : %s", zoneId)
if zoneId == "" {
cblogger.Error("Connection 정보에 Zone 정보가 없습니다.")
return irs.SubnetInfo{}, errors.New("Connection 정보에 Zone 정보가 없습니다.")
}
if reqSubnetInfo.IId.SystemId != "" {
vpcInfo, errVpcInfo := VPCHandler.GetSubnet(reqSubnetInfo.IId.SystemId)
if errVpcInfo == nil {
cblogger.Errorf("이미 [%S] Subnet이 존재하기 때문에 생성하지 않고 기존 정보와 함께 에러를 리턴함.", reqSubnetInfo.IId.SystemId)
cblogger.Info(vpcInfo)
return vpcInfo, errors.New("InvalidVNetwork.Duplicate: The Subnet '" + reqSubnetInfo.IId.SystemId + "' already exists.")
}
}
//서브넷 생성
input := &ec2.CreateSubnetInput{
CidrBlock: aws.String(reqSubnetInfo.IPv4_CIDR),
VpcId: aws.String(vpcId),
//AvailabilityZoneId: aws.String(zoneId), //use1-az1, use1-az2, use1-az3, use1-az4, use1-az5, use1-az6
AvailabilityZone: aws.String(zoneId),
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.AWS,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: reqSubnetInfo.IId.NameId,
CloudOSAPI: "CreateSubnet()",
ElapsedTime: "",
ErrorMSG: "",
}
start := call.Start()
cblogger.Info(input)
result, err := VPCHandler.Client.CreateSubnet(input)
callLogInfo.ElapsedTime = call.Elapsed(start)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
callLogInfo.ErrorMSG = aerr.Error()
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
callLogInfo.ErrorMSG = err.Error()
}
callogger.Info(call.String(callLogInfo))
return irs.SubnetInfo{}, err
}
callogger.Info(call.String(callLogInfo))
cblogger.Info(result)
//spew.Dump(result)
//vNetworkInfo := irs.VNetworkInfo{}
vNetworkInfo := ExtractSubnetDescribeInfo(result.Subnet)
//Subnet Name 태깅
if SetNameTag(VPCHandler.Client, *result.Subnet.SubnetId, reqSubnetInfo.IId.NameId) {
cblogger.Infof("Subnet에 %s Name 설정 성공", reqSubnetInfo.IId.NameId)
} else {
cblogger.Errorf("Subnet에 %s Name 설정 실패", reqSubnetInfo.IId.NameId)
}
vNetworkInfo.IId.NameId = reqSubnetInfo.IId.NameId
// VPC의 라우팅 테이블에 생성된 Subnet 정보를 추가 함.
errSubnetRoute := VPCHandler.AssociateRouteTable(vpcId, vNetworkInfo.IId.SystemId)
if errSubnetRoute != nil {
} else {
return vNetworkInfo, errSubnetRoute
}
return vNetworkInfo, nil
}
// VPC의 라우팅 테이블에 생성된 Subnet을 연결 함.
func (VPCHandler *TencentVPCHandler) AssociateRouteTable(vpcId string, subnetId string) error {
routeTableId, errRoute := VPCHandler.GetDefaultRouteTable(vpcId)
if errRoute != nil {
return errRoute
}
input := &ec2.AssociateRouteTableInput{
RouteTableId: aws.String(routeTableId),
SubnetId: aws.String(subnetId),
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.AWS,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: subnetId,
CloudOSAPI: "AssociateRouteTable()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
result, err := VPCHandler.Client.AssociateRouteTable(input)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
callLogInfo.ErrorMSG = aerr.Error()
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
callLogInfo.ErrorMSG = err.Error()
}
callogger.Info(call.String(callLogInfo))
return err
}
callogger.Info(call.String(callLogInfo))
cblogger.Info(result)
//spew.Dump(result)
return nil
}
func (VPCHandler *TencentVPCHandler) ListVPC() ([]*irs.VPCInfo, error) {
cblogger.Debug("Start")
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.AWS,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: "ListVPC",
CloudOSAPI: "DescribeVpcs()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
result, err := VPCHandler.Client.DescribeVpcs(&ec2.DescribeVpcsInput{})
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
}
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
return nil, err
}
callogger.Info(call.String(callLogInfo))
var vNetworkInfoList []*irs.VPCInfo
for _, curVpc := range result.Vpcs {
cblogger.Infof("[%s] VPC 정보 조회", *curVpc.VpcId)
vNetworkInfo, vpcErr := VPCHandler.GetVPC(irs.IID{SystemId: *curVpc.VpcId})
if vpcErr != nil {
return nil, vpcErr
}
vNetworkInfoList = append(vNetworkInfoList, &vNetworkInfo)
}
spew.Dump(vNetworkInfoList)
return vNetworkInfoList, nil
}
func (VPCHandler *TencentVPCHandler) GetVPC(vpcIID irs.IID) (irs.VPCInfo, error) {
cblogger.Info("VPC IID : ", vpcIID.SystemId)
input := &ec2.DescribeVpcsInput{
VpcIds: []*string{
aws.String(vpcIID.SystemId),
},
}
// logger for HisCall
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.AWS,
RegionZone: VPCHandler.Region.Zone,
ResourceType: call.VPCSUBNET,
ResourceName: vpcIID.SystemId,
CloudOSAPI: "DescribeVpcs()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
result, err := VPCHandler.Client.DescribeVpcs(input)
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
callLogInfo.ErrorMSG = aerr.Error()
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
cblogger.Error(err.Error())
callLogInfo.ErrorMSG = err.Error()
}
callogger.Info(call.String(callLogInfo))
return irs.VPCInfo{}, err
}
callogger.Info(call.String(callLogInfo))
cblogger.Info(result)
//spew.Dump(result)
if reflect.ValueOf(result.Vpcs).IsNil() {
return irs.VPCInfo{}, nil
}
var errSubnet error
awsVpcInfo := ExtractVpcDescribeInfo(result.Vpcs[0])
awsVpcInfo.SubnetInfoList, errSubnet = VPCHandler.ListSubnet(vpcIID.SystemId)
if errSubnet != nil {
return awsVpcInfo, errSubnet
}
return awsVpcInfo, nil
}
//VPC 정보를 추출함
func ExtractVpcDescribeInfo(vpcInfo *ec2.Vpc) irs.VPCInfo {
awsVpcInfo := irs.VPCInfo{
IId: irs.IID{SystemId: *vpcInfo.VpcId},
IPv4_CIDR: *vpcInfo.CidrBlock,
//IsDefault: *vpcInfo.IsDefault,
//State: *vpcInfo.State,
}
//Name은 Tag의 "Name" 속성에만 저장됨
//NameId는 전달할 필요가 없음.
return awsVpcInfo
}
func (VPCHandler *TencentVPCHandler) DeleteSubnet(subnetIID irs.IID) (bool, error) {
input := &ec2.DeleteSubnetInput{
SubnetId: aws.String(subnetIID.SystemId),
}
cblogger.Info(input)
// logger for HisCall
callogger := call.GetLogger("HISCALL")