From ae7d14e6476a267f3e33bd8902adc4a6b974475d Mon Sep 17 00:00:00 2001 From: SungWoongz Date: Wed, 28 Feb 2024 13:53:55 +0900 Subject: [PATCH 1/4] Check log level & Englishization --- .../tencent/resources/CommonHandler.go | 14 +++--- .../tencent/resources/CommonTencentFunc.go | 8 ++-- .../drivers/tencent/resources/DiskHandler.go | 2 +- .../drivers/tencent/resources/ImageHandler.go | 2 +- .../tencent/resources/MyImageHandler.go | 2 +- .../drivers/tencent/resources/NLBHandler.go | 43 +++++++++---------- .../tencent/resources/SecurityHandler.go | 34 ++++++--------- .../drivers/tencent/resources/VMHandler.go | 38 ++++++++-------- .../tencent/resources/VMSpecHandler.go | 10 ++--- .../drivers/tencent/resources/VPCHandler.go | 18 ++++---- 10 files changed, 81 insertions(+), 90 deletions(-) diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonHandler.go index 781e28bcd..2038c9007 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonHandler.go @@ -58,15 +58,15 @@ func WaitForDelete(client *cvm.Client, imageIID irs.IID) (bool, error) { } if len(imageList) == 0 { - cblogger.Info("Image의 삭제가 완료되어 대기를 중단합니다.") + cblogger.Info("Image deletion is complete and stops waiting.") break } curRetryCnt++ - cblogger.Info("Image의 삭제가 완료되지 않아 1초 대기후 조회합니다.") + cblogger.Info("Image deletion has not been completed, so we will look up the climate for 1 second.") time.Sleep(time.Second * 1) if curRetryCnt > maxRetryCnt { - cblogger.Errorf("장시간(%d 초) 대기해도 Image의 삭제가 완료되지 않아서 강제로 중단합니다.", maxRetryCnt) + cblogger.Errorf("If you wait for a long time (%d seconds), the deletion of the image does not complete, so forcefully stop.", maxRetryCnt) return false, errors.New("Failed to delete image") } } @@ -95,16 +95,16 @@ func WaitForDone(client *cbs.Client, diskIID irs.IID, status string) (string, er cblogger.Info("===>Disk Status : ", curStatus) if curStatus == waitStatus { - cblogger.Infof("===>Disk 상태가 [%s]라서 대기를 중단합니다.", curStatus) + cblogger.Infof("===>Suspends standby because disk state is [%s].", curStatus) break } curRetryCnt++ - cblogger.Infof("Disk 상태가 [%s]이 아니라서 1초 대기후 조회합니다.", waitStatus) + cblogger.Infof("Disk status is not [%s] and climate lookup is performed in 1 second.", waitStatus) time.Sleep(time.Second * 1) if curRetryCnt > maxRetryCnt { - cblogger.Errorf("장시간(%d 초) 대기해도 Disk Status 값이 [%s]으로 변경되지 않아서 강제로 중단합니다.", maxRetryCnt, waitStatus) - return "Failed", errors.New("장시간 기다렸으나 생성된 Disk의 상태가 [" + waitStatus + "]으로 바뀌지 않아서 중단 합니다.") + cblogger.Errorf("Waiting for a long time (%d seconds) does not change the disk status value to [%s] and forces it to stop.", maxRetryCnt, waitStatus) + return "Failed", errors.New("After waiting a long time, the status of the created disk does not change to [" + waitStatus + "] and it is interrupted.") } } diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonTencentFunc.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonTencentFunc.go index 16c7c831b..362fd491d 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonTencentFunc.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/CommonTencentFunc.go @@ -115,7 +115,7 @@ func ConvertJsonStringNoEscape(v interface{}) (string, error) { encoder.SetEscapeHTML(false) errJson := encoder.Encode(v) if errJson != nil { - cblogger.Error("JSON 변환 실패") + cblogger.Error("JSON conversion failed") cblogger.Error(errJson) return "", errJson } @@ -136,7 +136,7 @@ func ConvertJsonString(v interface{}) (string, error) { jsonBytes, errJson := json.Marshal(v) if errJson != nil { - cblogger.Error("JSON 변환 실패") + cblogger.Error("JSON conversion failed") cblogger.Error(errJson) return "", errJson } @@ -180,7 +180,7 @@ func ConvertKeyValueList(v interface{}) ([]irs.KeyValue, error) { jsonBytes, errJson := json.Marshal(v) if errJson != nil { - cblogger.Error("KeyValue 변환 실패") + cblogger.Error("KeyValue conversion failed") cblogger.Error(errJson) return nil, errJson } @@ -201,7 +201,7 @@ func ConvertKeyValueList(v interface{}) ([]irs.KeyValue, error) { value, errString := ConvertToString(v) if errString != nil { //cblogger.Errorf("Key[%s]의 값은 변환 불가 - [%s]", k, errString) - cblogger.Debugf("Key[%s]의 값은 변환 불가 - [%s]", k, errString) //요구에 의해서 Error에서 Warn으로 낮춤 + cblogger.Debugf("Key[%s] values are not convertible - [%s]", k, errString) //요구에 의해서 Error에서 Warn으로 낮춤 continue } keyValueList = append(keyValueList, irs.KeyValue{k, value}) diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/DiskHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/DiskHandler.go index 445975781..5821d9f32 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/DiskHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/DiskHandler.go @@ -427,6 +427,6 @@ func (DiskHandler *TencentDiskHandler) diskExist(chkName string) (bool, error) { return false, nil } - cblogger.Infof("Disk 정보 찾음 - DiskId:[%s] / DiskName:[%s]", *response.Response.DiskSet[0].DiskId, *response.Response.DiskSet[0].DiskName) + cblogger.Infof("Found disk information - DiskId:[%s] / DiskName:[%s]", *response.Response.DiskSet[0].DiskId, *response.Response.DiskSet[0].DiskName) return true, nil } diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/ImageHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/ImageHandler.go index a9cd6ec0a..c372552ea 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/ImageHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/ImageHandler.go @@ -144,7 +144,7 @@ func ExtractImageDescribeInfo(image *cvm.Image) irs.ImageInfo { //KeyValue 목록 처리 keyValueList, errKeyValue := ConvertKeyValueList(image) if errKeyValue != nil { - cblogger.Errorf("[%]의 KeyValue 추출 실패", *image.ImageId) + cblogger.Errorf("KeyValue extraction failed for [%]", *image.ImageId) cblogger.Error(errKeyValue) } diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/MyImageHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/MyImageHandler.go index c26a9d737..a3411196a 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/MyImageHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/MyImageHandler.go @@ -322,7 +322,7 @@ func (myImageHandler *TencentMyImageHandler) myImageExist(chkName string) (bool, return false, nil } - cblogger.Infof("MyImage 정보 찾음 - MyImageId:[%s] / MyImageName:[%s]", *response.Response.ImageSet[0].ImageId, *response.Response.ImageSet[0].ImageName) + cblogger.Infof("Found MyImage information - MyImageId:[%s] / MyImageName:[%s]", *response.Response.ImageSet[0].ImageId, *response.Response.ImageSet[0].ImageName) return true, nil } diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/NLBHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/NLBHandler.go index 87038c59d..e6ebf2d2c 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/NLBHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/NLBHandler.go @@ -50,8 +50,8 @@ const ( ) /* - NLB 생성 - vpc required +NLB 생성 +vpc required */ func (NLBHandler *TencentNLBHandler) CreateNLB(nlbReqInfo irs.NLBInfo) (irs.NLBInfo, error) { ////// validation check area ////// @@ -244,7 +244,7 @@ func (NLBHandler *TencentNLBHandler) CreateNLB(nlbReqInfo irs.NLBInfo) (irs.NLBI } /* - NLB 모든 목록 조회 : TCP/UDP +NLB 모든 목록 조회 : TCP/UDP */ func (NLBHandler *TencentNLBHandler) ListNLB() ([]*irs.NLBInfo, error) { cblogger.Info("Start") @@ -298,7 +298,7 @@ func (NLBHandler *TencentNLBHandler) ListNLB() ([]*irs.NLBInfo, error) { } /* - NLB 조회 +NLB 조회 */ func (NLBHandler *TencentNLBHandler) GetNLB(nlbIID irs.IID) (irs.NLBInfo, error) { cblogger.Info("NLB IID : ", nlbIID.SystemId) @@ -762,7 +762,7 @@ func (NLBHandler *TencentNLBHandler) ChangeHealthCheckerInfo(nlbIID irs.IID, hea } -//CLB instance status (creating, running) +// CLB instance status (creating, running) func (NLBHandler *TencentNLBHandler) WaitForRun(nlbIID irs.IID) (string, error) { waitStatus := "Running" @@ -783,23 +783,23 @@ func (NLBHandler *TencentNLBHandler) WaitForRun(nlbIID irs.IID) (string, error) cblogger.Info("===>NLB Status : ", curStatus) if curStatus == LoadBalancerSet_Status_Running { - cblogger.Infof("===>NLB 상태가 [%d]라서 대기를 중단합니다.", curStatus) + cblogger.Infof("===>The NLB state is [%d] so it stops waiting.", curStatus) break } curRetryCnt++ - cblogger.Infof("NLB 상태가 [%s]이 아니라서 1초 대기후 조회합니다.", waitStatus) + cblogger.Infof("NLB status is not [%s] so I'm checking the climate for a second.", waitStatus) time.Sleep(time.Second * 1) if curRetryCnt > maxRetryCnt { - cblogger.Errorf("장시간(%d 초) 대기해도 NLB Status 값이 [%s]으로 변경되지 않아서 강제로 중단합니다.", maxRetryCnt, waitStatus) - return "Failed", errors.New("장시간 기다렸으나 생성된 NLB의 상태가 [" + waitStatus + "]으로 바뀌지 않아서 중단 합니다.") + cblogger.Errorf("The NLB Status value does not change to [%s] even after waiting for a long time (%d seconds), so it is forced to stop.", maxRetryCnt, waitStatus) + return "Failed", errors.New("I waited for a long time, but the generated NLB status did not change to [" + waitStatus + "] so I will stop.") } } return waitStatus, nil } -//Current status of a task (succeeded==Done, failed, in progress) +// Current status of a task (succeeded==Done, failed, in progress) func (NLBHandler *TencentNLBHandler) WaitForDone(requestId string) (string, error) { waitStatus := "Done" @@ -821,16 +821,16 @@ func (NLBHandler *TencentNLBHandler) WaitForDone(requestId string) (string, erro cblogger.Info("===>request status : ", requestStatus) if requestStatus == Request_Status_Succeeded { - cblogger.Infof("===>request 상태가 [%s]라서 대기를 중단합니다.", waitStatus) + cblogger.Infof("===>The request state is [%s] and will stop waiting.", waitStatus) break } curRetryCnt++ - cblogger.Infof("request 상태가 [%s]이 아니라서 1초 대기후 조회합니다.", waitStatus) + cblogger.Infof("The request status is not [%s], so I'm checking the climate for a second.", waitStatus) time.Sleep(time.Second * 1) if curRetryCnt > maxRetryCnt { - cblogger.Errorf("장시간(%d 초) 대기해도 request Status 값이 [%s]으로 변경되지 않아서 강제로 중단합니다.", maxRetryCnt, waitStatus) - return "Failed", errors.New("장시간 기다렸으나 생성된 request 상태가 [" + waitStatus + "]으로 바뀌지 않아서 중단 합니다.") + cblogger.Errorf("Waiting for a long time (%d seconds) does not change the request status value to [%s] and forces it to stop.", maxRetryCnt, waitStatus) + return "Failed", errors.New("I waited for a long time, but the generated request status did not change to [" + waitStatus + "] so I will stop.") } } @@ -838,8 +838,8 @@ func (NLBHandler *TencentNLBHandler) WaitForDone(requestId string) (string, erro } /* - nlb가 존재하는지 check - 동일이름이 없으면 false, 있으면 true +nlb가 존재하는지 check +동일이름이 없으면 false, 있으면 true */ func (NLBHandler *TencentNLBHandler) nlbExist(chkName string) (bool, error) { cblogger.Debugf("chkName : %s", chkName) @@ -862,7 +862,7 @@ func (NLBHandler *TencentNLBHandler) nlbExist(chkName string) (bool, error) { } /* - 조회한 결과에서 Spider의 NLBInfo 값으로 변환 +조회한 결과에서 Spider의 NLBInfo 값으로 변환 */ func (NLBHandler *TencentNLBHandler) ExtractNLBDescribeInfo(nlbInfo *clb.LoadBalancer) (irs.NLBInfo, error) { @@ -908,10 +908,9 @@ func (NLBHandler *TencentNLBHandler) ExtractNLBDescribeInfo(nlbInfo *clb.LoadBal return resNLBInfo, nil } - /* - NLB Name으로 Listener를 조회하여 NLBInfo.Listener 값으로 변환 - NLB 를 조회하여 Listener에 사용할 IP인 VIP 추출 +NLB Name으로 Listener를 조회하여 NLBInfo.Listener 값으로 변환 +NLB 를 조회하여 Listener에 사용할 IP인 VIP 추출 */ func (NLBHandler *TencentNLBHandler) ExtractListenerInfo(nlbIID irs.IID) (irs.ListenerInfo, error) { cblogger.Info("NLB IID : ", nlbIID.SystemId) @@ -945,7 +944,7 @@ func (NLBHandler *TencentNLBHandler) ExtractListenerInfo(nlbIID irs.IID) (irs.Li } /* - VM Group 정보 조회 +VM Group 정보 조회 */ func (NLBHandler *TencentNLBHandler) ExtractVMGroupInfo(nlbIID irs.IID) (irs.VMGroupInfo, error) { cblogger.Info("NLB IID : ", nlbIID.SystemId) @@ -986,7 +985,7 @@ func (NLBHandler *TencentNLBHandler) ExtractVMGroupInfo(nlbIID irs.IID) (irs.VMG } /* - Health Checker 정보 조회 +Health Checker 정보 조회 */ func (NLBHandler *TencentNLBHandler) ExtractHealthCheckerInfo(nlbIID irs.IID) (irs.HealthCheckerInfo, error) { cblogger.Info("NLB IID : ", nlbIID.SystemId) diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/SecurityHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/SecurityHandler.go index a4d48f9cc..2e5d190f2 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/SecurityHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/SecurityHandler.go @@ -11,17 +11,17 @@ package resources import ( + "encoding/json" "errors" "strings" - "encoding/json" + cblog "github.com/cloud-barista/cb-log" 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" - cblog "github.com/cloud-barista/cb-log" ) type TencentSecurityHandler struct { @@ -32,7 +32,7 @@ type TencentSecurityHandler struct { type RuleAction string const ( - Add RuleAction = "Add" + Add RuleAction = "Add" Remove RuleAction = "Remove" ) @@ -102,12 +102,12 @@ func (securityHandler *TencentSecurityHandler) CreateSecurity(securityReqInfo ir spew.Dump(defaultEgressRequest) return irs.SecurityInfo{}, err } - + //spew.Dump(defaultEgressResponse) cblogger.Debug(defaultEgressResponse.ToJsonString()) callogger.Info(call.String(callLogInfo)) - cblogger.Debug("보안 정책 처리") + cblogger.Debug("Security Policy Processing") securityGroupPolicySet := &vpc.SecurityGroupPolicySet{} request := vpc.NewCreateSecurityGroupPoliciesRequest() request.SecurityGroupId = common.StringPtr(*defaultEgressResponse.Response.SecurityGroup.SecurityGroupId) @@ -135,9 +135,6 @@ func (securityHandler *TencentSecurityHandler) CreateSecurity(securityReqInfo ir } } - - - request.SecurityGroupPolicySet = securityGroupPolicySet //callLogStart := call.Start() @@ -235,7 +232,7 @@ func (securityHandler *TencentSecurityHandler) isExist(chkName string) (bool, er return false, nil } - cblogger.Infof("보안그룹 정보 찾음 - VpcId:[%s] / VpcName:[%s]", *response.Response.SecurityGroupSet[0].SecurityGroupId, *response.Response.SecurityGroupSet[0].SecurityGroupName) + cblogger.Infof("Security group information found - VpcId:[%s] / VpcName:[%s]", *response.Response.SecurityGroupSet[0].SecurityGroupId, *response.Response.SecurityGroupSet[0].SecurityGroupName) return true, nil } @@ -321,14 +318,14 @@ func (securityHandler *TencentSecurityHandler) GetSecurityRuleInfo(securityIID i return &securityRuleInfos, nil } -//@TODO Port에 콤머가 사용된 정책 처리해야 함. -//direction : inbound / outbound +// @TODO Port에 콤머가 사용된 정책 처리해야 함. +// direction : inbound / outbound func (securityHandler *TencentSecurityHandler) ExtractPolicyGroups(policyGroups []*vpc.SecurityGroupPolicy, direction string) ([]irs.SecurityRuleInfo, error) { var results []irs.SecurityRuleInfo var fromPort string var toPort string - + /* var newDirection string //ingress -> inbound @@ -448,7 +445,7 @@ func (securityHandler *TencentSecurityHandler) AddRules(securityIID irs.IID, req } errorMsg += string(jsonRule) } - return irs.SecurityInfo{}, errors.New("invalid value - "+ errorMsg +" already exists!") + return irs.SecurityInfo{}, errors.New("invalid value - " + errorMsg + " already exists!") } securityGroupPolicyIngressSet := &vpc.SecurityGroupPolicySet{} @@ -456,11 +453,10 @@ func (securityHandler *TencentSecurityHandler) AddRules(securityIID irs.IID, req // rule 생성 시에는 ingress와 egress가 동시에 생성되지 않기 때문에 ingress, egress 따로 호촐함 for _, curPolicy := range *reqSecurityRules { - + // if !strings.EqualFold(curPolicy.Direction, commonDirection) { // return irs.SecurityInfo{}, errors.New("invalid - The parameter `Egress and Ingress` cannot be imported at the same time in the request.") // } - securityGroupPolicy := new(vpc.SecurityGroupPolicy) securityGroupPolicy.Protocol = common.StringPtr(curPolicy.IPProtocol) @@ -484,7 +480,6 @@ func (securityHandler *TencentSecurityHandler) AddRules(securityIID irs.IID, req } } - // Ingress request if len(securityGroupPolicyIngressSet.Ingress) > 0 { ingressRequest := vpc.NewCreateSecurityGroupPoliciesRequest() @@ -537,7 +532,6 @@ func (securityHandler *TencentSecurityHandler) AddRules(securityIID irs.IID, req return securityInfo, errSecurity } - // DeleteSecurityGroupPolicies inbound, outbound 동시 호출 불가 > 각각 호출 func (securityHandler *TencentSecurityHandler) RemoveRules(securityIID irs.IID, reqSecurityRules *[]irs.SecurityRuleInfo) (bool, error) { //////// @@ -569,7 +563,7 @@ func (securityHandler *TencentSecurityHandler) RemoveRules(securityIID irs.IID, } errorMsg += string(jsonRule) } - return false, errors.New("invalid value - "+ errorMsg +" does not exist!") + return false, errors.New("invalid value - " + errorMsg + " does not exist!") } securityGroupPolicyIngressSet := &vpc.SecurityGroupPolicySet{} @@ -651,7 +645,7 @@ func (securityHandler *TencentSecurityHandler) RemoveRules(securityIID irs.IID, // 동일한 rule이 있는지 체크 // RuleAction이 Add면 중복인 rule 리턴, Remove면 없는 rule 리턴 -func sameRulesCheck(presentSecurityRules *[]irs.SecurityRuleInfo, reqSecurityRules *[]irs.SecurityRuleInfo, action RuleAction) (*[]irs.SecurityRuleInfo) { +func sameRulesCheck(presentSecurityRules *[]irs.SecurityRuleInfo, reqSecurityRules *[]irs.SecurityRuleInfo, action RuleAction) *[]irs.SecurityRuleInfo { var checkResult []irs.SecurityRuleInfo for _, reqRule := range *reqSecurityRules { hasFound := false @@ -711,5 +705,3 @@ func sameRulesCheck(presentSecurityRules *[]irs.SecurityRuleInfo, reqSecurityRul return nil } - - diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMHandler.go index a2e02e640..4a1f6b4a8 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMHandler.go @@ -90,7 +90,7 @@ func (vmHandler *TencentVMHandler) StartVM(vmReqInfo irs.VMReqInfo) (irs.VMInfo, // return irs.VMInfo{}, errors.New("A VM with the name " + vmReqInfo.IId.NameId + " already exists.") //} - cblogger.Error("imageInfo begin") + cblogger.Debug("imageInfo begin") // Image의 크기 -> rootdisk size, datadisk attach 확인 및 설정 imageTypes := []string{"PUBLIC_IMAGE", "SHARED_IMAGE", "PRIVATE_IMAGE"} imageInfo, err := DescribeImagesByID(vmHandler.Client, vmReqInfo.ImageIID, imageTypes) @@ -113,7 +113,7 @@ func (vmHandler *TencentVMHandler) StartVM(vmReqInfo irs.VMReqInfo) (irs.VMInfo, isWindow = true vmReqInfo.KeyPairIID = irs.IID{} vmReqInfo.VMUserId = "administrator" // window은 administrator로 set - cblogger.Error("Window 이므로 keyPair는 사용하지 않고 admin, pass만 사용", vmReqInfo.VMUserId, vmReqInfo.VMUserPasswd, vmReqInfo.KeyPairIID) + cblogger.Debug("Because it's Windows, use only admin, pass, not keyPair", vmReqInfo.VMUserId, vmReqInfo.VMUserPasswd, vmReqInfo.KeyPairIID) } /* 2021-10-26 이슈 #480에 의해 제거 @@ -343,7 +343,7 @@ func (vmHandler *TencentVMHandler) StartVM(vmReqInfo irs.VMReqInfo) (irs.VMInfo, cblogger.Debugf("cloud-init data : [%s]", userDataBase64) request.UserData = common.StringPtr(userDataBase64) - cblogger.Debug("===== 요청 객체====") + cblogger.Debug("===== Request object====") spew.Config.Dump(request) callLogStart := call.Start() response, err := vmHandler.Client.RunInstances(request) @@ -373,7 +373,7 @@ func (vmHandler *TencentVMHandler) StartVM(vmReqInfo irs.VMReqInfo) (irs.VMInfo, cblogger.Error(errStatus.Error()) return irs.VMInfo{}, nil } - cblogger.Info("==>생성된 VM[%s]의 현재 상태[%s]", newVmIID, curStatus) + cblogger.Info("==>Current status of created VM [%s]", newVmIID, curStatus) DiskHandler := TencentDiskHandler{ Region: vmHandler.Region, @@ -481,7 +481,7 @@ func (vmHandler *TencentVMHandler) ResumeVM(vmIID irs.IID) (irs.VMStatus, error) } cblogger.Debug(curStatus) if curStatus != "Suspended" { - return irs.VMStatus("Failed"), errors.New(string("vm 상태가 Suspended 가 아닙니다." + curStatus)) + return irs.VMStatus("Failed"), errors.New(string("vm state is not Suspended." + curStatus)) } request := cvm.NewStartInstancesRequest() @@ -552,7 +552,7 @@ func (vmHandler *TencentVMHandler) RebootVM(vmIID irs.IID) (irs.VMStatus, error) return irs.VMStatus("Failed"), err } } else { - return irs.VMStatus("Failed"), errors.New(string(curStatus + "상태인 경우에는 Reboot할 수 없습니다.")) + return irs.VMStatus("Failed"), errors.New(string(curStatus + "Reboot is not possible if it is in the state.")) } return irs.VMStatus("Rebooting"), nil @@ -627,7 +627,7 @@ func (vmHandler *TencentVMHandler) GetVM(vmIID irs.IID) (irs.VMInfo, error) { cblogger.Debug(response.ToJsonString()) if *response.Response.TotalCount < 1 { - return irs.VMInfo{}, errors.New("VM 정보를 찾을 수 없습니다") + return irs.VMInfo{}, errors.New("VM information not found") } vmInfo, errVmInfo := vmHandler.ExtractDescribeInstances(response.Response.InstanceSet[0]) @@ -667,15 +667,15 @@ func (vmHandler *TencentVMHandler) ExtractDescribeInstances(curVm *cvm.Instance) // vmInfo.StartTime = *curVm.CreatedTime vmStartTime := *curVm.CreatedTime timeLen := len(vmStartTime) - cblogger.Debug("서버 구동 시간 포멧 변환 처리") - cblogger.Debugf("======> 생성시간 길이 [%s]", timeLen) + cblogger.Debug("Server Running Time Format Conversion Processing") + cblogger.Debugf("======> Generation time length [%s]", timeLen) if timeLen > 7 { - cblogger.Debugf("======> 생성시간 마지막 문자열 [%s]", vmStartTime[timeLen-1:]) + cblogger.Debugf("======> Generation Time Last String [%s]", vmStartTime[timeLen-1:]) var NewStartTime string if vmStartTime[timeLen-1:] == "Z" && timeLen == 17 { //cblogger.Infof("======> 문자열 변환 : [%s]", StartTime[:timeLen-1]) NewStartTime = vmStartTime[:timeLen-1] + ":00Z" - cblogger.Debugf("======> 최종 문자열 변환 : [%s]", NewStartTime) + cblogger.Debugf("======> Final string conversion : [%s]", NewStartTime) } else { NewStartTime = vmStartTime } @@ -868,7 +868,7 @@ func (vmHandler *TencentVMHandler) GetVMStatus(vmIID irs.IID) (irs.VMStatus, err cblogger.Debug(response.ToJsonString()) if *response.Response.TotalCount < 1 { - return irs.VMStatus("Failed"), errors.New("상태 정보를 찾을 수 없습니다") + return irs.VMStatus("Failed"), errors.New("Status information not found") } vmStatus, errStatus := ConvertVMStatusString(*response.Response.InstanceStatusSet[0].InstanceState) @@ -954,7 +954,7 @@ func ConvertVMStatusString(vmStatus string) (irs.VMStatus, error) { resultStatus = "Terminated" } else { //resultStatus = "Failed" - cblogger.Errorf("vmStatus [%s]와 일치하는 맵핑 정보를 찾지 못 함.", vmStatus) + cblogger.Debugf("Mapping information matching vmStatus [%s] not found.", vmStatus) return irs.VMStatus("Failed"), errors.New(vmStatus + "와 일치하는 CB VM 상태정보를 찾을 수 없습니다.") } cblogger.Infof("VM 상태 치환 : [%s] ==> [%s]", vmStatus, resultStatus) @@ -983,17 +983,17 @@ func (vmHandler *TencentVMHandler) WaitForRun(vmIID irs.IID) (irs.VMStatus, erro cblogger.Info("===>VM Status : ", curStatus) if curStatus == irs.VMStatus(waitStatus) { //|| curStatus == irs.VMStatus("Running") { - cblogger.Infof("===>VM 상태가 [%s]라서 대기를 중단합니다.", curStatus) + cblogger.Infof("===>VM state is [%s] and quiesce.", curStatus) break } //if curStatus != irs.VMStatus(waitStatus) { curRetryCnt++ - cblogger.Infof("VM 상태가 [%s]이 아니라서 1초 대기후 조회합니다.", waitStatus) + cblogger.Infof("VM status is not [%s] so we're looking at climate in 1 second.", waitStatus) time.Sleep(time.Second * 1) if curRetryCnt > maxRetryCnt { - cblogger.Errorf("장시간(%d 초) 대기해도 VM의 Status 값이 [%s]으로 변경되지 않아서 강제로 중단합니다.", maxRetryCnt, waitStatus) - return irs.VMStatus("Failed"), errors.New("장시간 기다렸으나 생성된 VM의 상태가 [" + waitStatus + "]으로 바뀌지 않아서 중단 합니다.") + cblogger.Errorf("Waiting for a long time (%d seconds) does not change the VM's status value to [%s] and forces it to stop.", maxRetryCnt, waitStatus) + return irs.VMStatus("Failed"), errors.New("You waited a long time, but the status of the created VM did not change to [" + waitStatus + "] and it is interrupted.") } } @@ -1002,7 +1002,7 @@ func (vmHandler *TencentVMHandler) WaitForRun(vmIID irs.IID) (irs.VMStatus, erro // VM 이름으로 중복 생성을 막아야 해서 VM존재 여부를 체크함. func (vmHandler *TencentVMHandler) vmExist(vmName string) (bool, error) { - cblogger.Infof("VM조회(Name기반) : %s", vmName) + cblogger.Infof("VM Inquiry (Name-based)) : %s", vmName) request := cvm.NewDescribeInstancesRequest() request.Filters = []*cvm.Filter{ &cvm.Filter{ @@ -1021,7 +1021,7 @@ func (vmHandler *TencentVMHandler) vmExist(vmName string) (bool, error) { return false, nil } - cblogger.Infof("VM 정보 찾음 - VmId:[%s] / VmName:[%s]", *response.Response.InstanceSet[0].InstanceId, *response.Response.InstanceSet[0].InstanceName) + cblogger.Infof("Found VM Information - VmId:[%s] / VmName:[%s]", *response.Response.InstanceSet[0].InstanceId, *response.Response.InstanceSet[0].InstanceName) return true, nil } diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMSpecHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMSpecHandler.go index fa901ac51..03c04adfa 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMSpecHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/VMSpecHandler.go @@ -65,7 +65,7 @@ func (vmSpecHandler *TencentVmSpecHandler) ListVMSpec() ([]*irs.VMSpecInfo, erro var vmSpecInfoList []*irs.VMSpecInfo for _, curSpec := range response.Response.InstanceTypeConfigSet { - cblogger.Debugf("[%s] VM Spec 정보 처리", *curSpec.InstanceType) + cblogger.Debugf("[%s] VM Spec Information Processing", *curSpec.InstanceType) vmSpecInfo := ExtractVMSpecInfo(curSpec) vmSpecInfoList = append(vmSpecInfoList, &vmSpecInfo) } @@ -130,7 +130,7 @@ func (vmSpecHandler *TencentVmSpecHandler) GetVMSpec(Name string) (irs.VMSpecInf cblogger.Debug(vmSpecInfo) return vmSpecInfo, nil } else { - return irs.VMSpecInfo{}, errors.New("정보를 찾을 수 없습니다") + return irs.VMSpecInfo{}, errors.New("No information found") } } @@ -247,7 +247,7 @@ func (vmSpecHandler *TencentVmSpecHandler) GetOrgVMSpec(Name string) (string, er cblogger.Debug(jsonString) return jsonString, errJson } else { - return "", errors.New("정보를 찾을 수 없습니다") + return "", errors.New("No information found") } } @@ -285,8 +285,8 @@ func ExtractVMSpecInfo(instanceTypeInfo *cvm.InstanceTypeConfig) irs.VMSpecInfo //KeyValue 목록 처리 keyValueList, errKeyValue := ConvertKeyValueList(instanceTypeInfo) if errKeyValue != nil { - cblogger.Errorf("[%]의 KeyValue 추출 실패", *instanceTypeInfo.InstanceType) - cblogger.Error(errKeyValue) + cblogger.Debugf("[%]의 KeyValue 추출 실패", *instanceTypeInfo.InstanceType) + cblogger.Debug(errKeyValue) } vmSpecInfo.KeyValueList = keyValueList diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/VPCHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/VPCHandler.go index f9029671d..d089a2d8d 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/VPCHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/VPCHandler.go @@ -184,7 +184,7 @@ func (VPCHandler *TencentVPCHandler) ListVPC() ([]*irs.VPCInfo, error) { } } - cblogger.Debugf("리턴 결과 목록 수 : [%d]", len(vpcInfoList)) + cblogger.Debugf("Number of Return Results List : [%d]", len(vpcInfoList)) // spew.Dump(vpcInfoList) return vpcInfoList, nil } @@ -211,7 +211,7 @@ func (VPCHandler *TencentVPCHandler) isExist(chkName string) (bool, error) { return false, nil } - cblogger.Infof("VPC 정보 찾음 - VpcId:[%s] / VpcName:[%s]", *response.Response.VpcSet[0].VpcId, *response.Response.VpcSet[0].VpcName) + cblogger.Infof("VPC information found - VpcId:[%s] / VpcName:[%s]", *response.Response.VpcSet[0].VpcId, *response.Response.VpcSet[0].VpcName) return true, nil } @@ -245,7 +245,7 @@ func (VPCHandler *TencentVPCHandler) GetVPC(vpcIID irs.IID) (irs.VPCInfo, error) } callogger.Info(call.String(callLogInfo)) - cblogger.Debug("VPC 개수 : ", *response.Response.TotalCount) + cblogger.Debug("Number of VPCs : ", *response.Response.TotalCount) if *response.Response.TotalCount < 1 { return irs.VPCInfo{}, errors.New("Notfound: '" + vpcIID.SystemId + "' VPC Not found") } @@ -340,7 +340,7 @@ func (VPCHandler *TencentVPCHandler) ListSubnet(reqVpcId string) ([]irs.SubnetIn // callogger.Info(call.String(callLogInfo)) for _, curSubnet := range response.Response.SubnetSet { - cblogger.Infof("[%s] Subnet 정보 조회", *curSubnet.SubnetId) + cblogger.Infof("[%s] Check Subnet Information", *curSubnet.SubnetId) resSubnetInfo := irs.SubnetInfo{ IId: irs.IID{SystemId: *curSubnet.SubnetId, NameId: *curSubnet.SubnetName}, IPv4_CIDR: *curSubnet.CidrBlock, @@ -389,7 +389,7 @@ func (VPCHandler *TencentVPCHandler) isExistSubnet(reqSubnetNameId string) (bool } 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) + cblogger.Infof("[%s] Add Subnet - CIDR : %s", subnetInfo.IId.NameId, subnetInfo.IPv4_CIDR) zoneId := VPCHandler.Region.Zone cblogger.Infof("Zone : %s", zoneId) @@ -399,7 +399,7 @@ func (VPCHandler *TencentVPCHandler) AddSubnet(vpcIID irs.IID, subnetInfo irs.Su } if subnetInfo.IId.NameId == "" { - return irs.VPCInfo{}, errors.New("생성할 SubnetId 정보가 없습니다.") + return irs.VPCInfo{}, errors.New("No SubnetId information to create.") } isExit, errSubnetInfo := VPCHandler.isExistSubnet(subnetInfo.IId.NameId) @@ -408,11 +408,11 @@ func (VPCHandler *TencentVPCHandler) AddSubnet(vpcIID irs.IID, subnetInfo irs.Su return irs.VPCInfo{}, errSubnetInfo } - cblogger.Info("Subnet 존재여부 : ") + cblogger.Info("Subnet presence or absence : ") cblogger.Info(isExit) if isExit { - cblogger.Errorf("이미 [%S] Subnet이 존재하기 때문에 생성하지 않고 기존 정보와 함께 에러를 리턴함.", subnetInfo.IId.NameId) + cblogger.Errorf("[%S] returns an error with existing information without creating it because Subnet already exists.", subnetInfo.IId.NameId) return irs.VPCInfo{}, errors.New("InvalidVNetwork.Duplicate: The Subnet '" + subnetInfo.IId.NameId + "' already exists.") } @@ -461,7 +461,7 @@ func (VPCHandler *TencentVPCHandler) AddSubnet(vpcIID irs.IID, subnetInfo irs.Su } func (VPCHandler *TencentVPCHandler) RemoveSubnet(vpcIID irs.IID, subnetIID irs.IID) (bool, error) { - cblogger.Infof("[%s] VPC의 [%s] Subnet 삭제", vpcIID.SystemId, subnetIID.SystemId) + cblogger.Infof("[%s] Delete [%s] Subnet on VPC", vpcIID.SystemId, subnetIID.SystemId) // logger for HisCall callogger := call.GetLogger("HISCALL") From 6e9f14fb530939d8f60ad5d01be63338f891788b Mon Sep 17 00:00:00 2001 From: SungWoongz Date: Wed, 28 Feb 2024 13:57:27 +0900 Subject: [PATCH 2/4] Delete storage-related productinfo & Add Pricing Policies (SpotPaid) --- .../tencent/resources/PriceInfoHandler.go | 288 ++++-------------- 1 file changed, 51 insertions(+), 237 deletions(-) diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go index bbaac53f7..2075be843 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go @@ -3,7 +3,7 @@ package resources import ( "bytes" "encoding/json" - "hash/fnv" + "reflect" "strconv" "strings" @@ -66,7 +66,6 @@ func (t *TencentPriceInfoHandler) GetPriceInfo(productFamily string, regionName //Common Instance Price calculator standardInfo, err := describeZoneInstanceConfigInfos(t.Client, filterKeyValueMap) - if err != nil { return "", err } @@ -167,108 +166,51 @@ func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceMod // standardInfo if instanceModel.standardInfo != nil { for _, v := range instanceModel.standardInfo.Response.InstanceTypeQuotaSet { - productId := computeInstanceKeyGeneration(*v.Zone, *v.InstanceType, *v.CpuType, strconv.FormatInt(*v.Memory, 10)) + productId := computeInstanceKeyGeneration(*v.Zone, *v.InstanceType, *v.CpuType, strconv.FormatInt(*v.Memory, 10)) price, ok := priceMap[productId] if ok { // 있으면 // policies 추출 policy := mappingPricingPolicy(v.InstanceChargeType, v.Price) - if priceValidateFilter(&policy, filterMap) { + if priceFilter(&policy, filterMap) { continue } - // append policy - pricePicies := price.PriceInfo.PricingPolicies - pricePicies = append(pricePicies, policy) - + pricePolicies := price.PriceInfo.PricingPolicies + pricePolicies = append(pricePolicies, policy) + price.PriceInfo.PricingPolicies = pricePolicies priceMap[productId] = price // price 재할당 + + cblogger.Info("add policy ", price) } else { // 없으면 // product 추출 productInfo := mappingProductInfo(regionName, *v) - if validateFilter(filterMap, &productInfo) { + if productFilter(filterMap, &productInfo) { continue } - // pricePicies 추출 + // pricePolicies 추출 policy := mappingPricingPolicy(v.InstanceChargeType, *v.Price) - if priceValidateFilter(&policy, filterMap) { + if priceFilter(&policy, filterMap) { continue } aPrice := irs.Price{} priceInfo := irs.PriceInfo{} - pricePicies := []irs.PricingPolicies{} - pricePicies = append(pricePicies, policy) + pricePolicies := []irs.PricingPolicies{} + pricePolicies = append(pricePolicies, policy) - priceInfo.PricingPolicies = pricePicies + priceInfo.PricingPolicies = pricePolicies aPrice.ProductInfo = productInfo aPrice.PriceInfo = priceInfo priceMap[productId] = aPrice } - - } - } - // reservedInfo - if instanceModel.reservedInfo != nil { - for _, v := range instanceModel.reservedInfo.Response.ReservedInstanceConfigInfos { - for _, info := range v.InstanceFamilies { - for _, iType := range info.InstanceTypes { - for _, p := range iType.Prices { - productId := computeInstanceKeyGeneration(*p.Zone, *iType.InstanceType, *iType.CpuModelName, strconv.FormatUint(*iType.Memory, 10)) - - price, ok := priceMap[productId] - if ok { // 있으면 - // policies 추출 - policy := mappingPricingPolicy(common.StringPtr("RESERVED"), iType.Prices) - - if priceValidateFilter(&policy, filterMap) { - continue - } - - // append policy - pricePicies := price.PriceInfo.PricingPolicies - pricePicies = append(pricePicies, policy) - - priceMap[productId] = price // price 재할당 - } else { // 없으면 - // product 추출 - productInfo := mappingProductInfo(regionName, *iType) - if validateFilter(filterMap, &productInfo) { - continue - } - - // for _, val := range *v.price.Res { - - // pricePicies 추출 - policy := mappingPricingPolicy(common.StringPtr("RESERVED"), *p) - - if priceValidateFilter(&policy, filterMap) { - continue - } - aPrice := irs.Price{} - priceInfo := irs.PriceInfo{} - - pricePicies := []irs.PricingPolicies{} - pricePicies = append(pricePicies, policy) - - priceInfo.PricingPolicies = pricePicies - - aPrice.ProductInfo = productInfo - aPrice.PriceInfo = priceInfo - - priceMap[productId] = aPrice - // } - } - - } // end of itype.Prices for - } // end of itype for - } // end of instanceFamilies for - } // end of reservedInstanceConfigInfos for + } // end of for } priceList := make([]irs.Price, 0) @@ -294,145 +236,8 @@ func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceMod } -// Mapper Start Function -- X -// func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceModel, filterMap map[string]string) (*irs.CloudPriceData, error) { -// priceMap := make(map[string]*TencentInstanceInformation, 0) - -// if instanceModel.standardInfo != nil { -// for _, v := range instanceModel.standardInfo.Response.InstanceTypeQuotaSet { - -// //변수값이 충분한지 고려할 필요가 있음, reservedInstance ReturnValue와 비교하여, 최대한 고유하게 가져갈 수 있는 것들은 -// //가져가도록 수정 -// key := computeInstanceKeyGeneration(*v.Zone, *v.InstanceType, *v.CpuType, strconv.FormatInt(*v.Memory, 10)) - -// if pp, ok := priceMap[key]; !ok { -// productInfo := mappingProductInfo(regionName, *v) - -// if validateFilter(filterMap, &productInfo) { -// continue -// } -// sp := make([]TencentCommonInstancePrice, 0) -// sp = append(sp, TencentCommonInstancePrice{InstanceChargeType: v.InstanceChargeType, Price: v.Price}) - -// priceMap[key] = &TencentInstanceInformation{ -// PriceList: &irs.Price{ -// ProductInfo: productInfo, -// }, -// StandardPrices: &sp, -// } -// } else { -// newSlice := append(*pp.StandardPrices, TencentCommonInstancePrice{InstanceChargeType: v.InstanceChargeType, Price: v.Price}) -// pp.StandardPrices = &newSlice -// } -// } -// } - -// //TODO reserved Instance Info Mapping -// if instanceModel.reservedInfo != nil { -// for _, v := range instanceModel.reservedInfo.Response.ReservedInstanceConfigInfos { -// for _, info := range v.InstanceFamilies { -// for _, iType := range info.InstanceTypes { -// for _, p := range iType.Prices { -// key := computeInstanceKeyGeneration(*p.Zone, *iType.InstanceType, *iType.CpuModelName, strconv.FormatUint(*iType.Memory, 10)) -// if pp, ok := priceMap[key]; !ok { -// productInfo := mappingProductInfo(regionName, *iType) - -// if validateFilter(filterMap, &productInfo) { -// continue -// } - -// rp := make([]TencentReservedInstancePrice, 0) -// rp = append(rp, TencentReservedInstancePrice{Price: p}) - -// priceMap[key] = &TencentInstanceInformation{ -// PriceList: &irs.Price{ -// ProductInfo: productInfo, -// }, - -// ReservedPrices: &rp, -// } -// } else { -// newSlice := append(*pp.ReservedPrices, TencentReservedInstancePrice{Price: p}) -// pp.ReservedPrices = &newSlice -// } -// } - -// } -// } -// } -// } -// generatePriceInfo(priceMap, filterMap) - -// priceList := make([]irs.Price, 0) - -// if priceMap != nil && len(priceMap) > 0 { -// for _, v := range priceMap { -// priceList = append(priceList, *v.PriceList) -// } -// } - -// x := &irs.CloudPriceData{ -// Meta: irs.Meta{ -// Version: "v0.1", -// Description: "Multi-Cloud Price Info Api", -// }, -// CloudPriceList: []irs.CloudPrice{ -// { -// CloudName: "TENCENT", -// PriceList: priceList, -// }, -// }, -// } -// return x, nil -// } - -// TencentSDK VM Product & Pricing struct to irs Struct -func generatePriceInfo(priceMap map[string]*TencentInstanceInformation, filterMap map[string]string) { - if priceMap != nil && len(priceMap) > 0 { - for _, v := range priceMap { - pl := v.PriceList - policies := make([]irs.PricingPolicies, 0) - prices := make([]any, 0) - - if v.StandardPrices != nil && len(*v.StandardPrices) > 0 { - for _, val := range *v.StandardPrices { - - policy := mappingPricingPolicy(val.InstanceChargeType, *val.Price) - - if priceValidateFilter(&policy, filterMap) { - continue - } - prices = append(prices, val.Price) - policies = append(policies, policy) - } - } - - if v.ReservedPrices != nil && len(*v.ReservedPrices) > 0 { - for _, val := range *v.ReservedPrices { - policy := mappingPricingPolicy(common.StringPtr("RESERVED"), *val.Price) - - if priceValidateFilter(&policy, filterMap) { - continue - } - prices = append(prices, val.Price) - policies = append(policies, policy) - } - } - // //mar, err := json.Marshal(prices) - // mar, err := ConvertJsonStringNoEscape(prices) - - // if err != nil { - // continue - // } - - pl.PriceInfo = irs.PriceInfo{ - PricingPolicies: policies, - CSPPriceInfo: prices, - } - } - } -} -func validateFilter(filterMap map[string]string, productInfo *irs.ProductInfo) bool { +// product 항목에 대해 필터 맵에 값이 있으면 true반환 -> true면 해당 값 필터링 +func productFilter(filterMap map[string]string, productInfo *irs.ProductInfo) bool { if len(filterMap) <= 0 { return false } @@ -462,7 +267,8 @@ func validateFilter(filterMap map[string]string, productInfo *irs.ProductInfo) b return false } -func priceValidateFilter(policy *irs.PricingPolicies, filterMap map[string]string) bool { +// price 항목에 대해 필터 맵에 값이 있으면 true반환 -> true면 해당 값 필터링 +func priceFilter(policy *irs.PricingPolicies, filterMap map[string]string) bool { if len(filterMap) <= 0 { return false } @@ -496,6 +302,8 @@ func priceValidateFilter(policy *irs.PricingPolicies, filterMap map[string]strin } // TencentSDK VM Product & Pricing struct to irs ProductPolicies +// storage 출력 항목 삭제 +// compute infra 관련 정보만 매핑 func mappingProductInfo(regionName string, i interface{}) irs.ProductInfo { productInfo := irs.ProductInfo{ //ProductId: "NA", @@ -520,13 +328,7 @@ func mappingProductInfo(regionName string, i interface{}) irs.ProductInfo { productInfo.OperatingSystem = strPtrNilCheck(nil) productInfo.PreInstalledSw = strPtrNilCheck(nil) - // not suit for compute instance - productInfo.VolumeType = strPtrNilCheck(nil) - productInfo.StorageMedia = strPtrNilCheck(nil) - productInfo.MaxVolumeSize = strPtrNilCheck(nil) - productInfo.MaxIOPSVolume = strPtrNilCheck(nil) - productInfo.MaxThroughputVolume = strPtrNilCheck(nil) - + // storage 관련 정보 삭제 return productInfo case cvm.ReservedInstanceTypeItem: @@ -545,13 +347,7 @@ func mappingProductInfo(regionName string, i interface{}) irs.ProductInfo { productInfo.OperatingSystem = strPtrNilCheck(nil) productInfo.PreInstalledSw = strPtrNilCheck(nil) - // not suit for compute instance - productInfo.VolumeType = strPtrNilCheck(nil) - productInfo.StorageMedia = strPtrNilCheck(nil) - productInfo.MaxVolumeSize = strPtrNilCheck(nil) - productInfo.MaxIOPSVolume = strPtrNilCheck(nil) - productInfo.MaxThroughputVolume = strPtrNilCheck(nil) - + // storage 관련 정보 삭제 return productInfo default: spew.Dump(v) @@ -573,10 +369,23 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli Currency: "USD", PricingPolicyInfo: &policyInfo, } + // POSTPAID -> v20170312.ItemPrice 반환 / SPOTPAID -> *v20170312.ItemPrice 포인터 반환 + // 포인터가 가리키는 실제 타입을 확인하여 포인터와 비 포인터를 동일하게 처리하기 위함 + objType := reflect.TypeOf(price) + isPointer := false - switch v := price.(type) { - case cvm.ItemPrice: + if objType.Kind() == reflect.Ptr { + objType = objType.Elem() + isPointer = true + } + switch objType { + case reflect.TypeOf(cvm.ItemPrice{}): + // 포인터일 경우, 실제 값을 가져온다 + if isPointer { + price = reflect.ValueOf(price).Elem().Interface() + } p := price.(cvm.ItemPrice) + policy.Unit = strPtrNilCheck(p.ChargeUnit) policy.Price = floatPtrNilCheck(p.UnitPrice) @@ -587,8 +396,9 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli policyInfo.OfferingClass = strPtrNilCheck(nil) policyInfo.PurchaseOption = strPtrNilCheck(nil) - case cvm.ReservedInstancePriceItem: + case reflect.TypeOf(cvm.ReservedInstancePriceItem{}): p := price.(cvm.ReservedInstancePriceItem) + policy.PricingId = strPtrNilCheck(p.ReservedInstancesOfferingId) policy.Unit = strPtrNilCheck(common.StringPtr("Yrs")) policy.Price = floatPtrNilCheck(p.FixedPrice) @@ -608,7 +418,7 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli policyInfo.OfferingClass = strPtrNilCheck(nil) default: - spew.Dump(v) + spew.Dump(objType) } return policy @@ -616,17 +426,21 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli // Instance Type 별 고유 key 생성 func computeInstanceKeyGeneration(hashingKeys ...string) string { - h := fnv.New32a() + // h := fnv.New32a() + keys := "" for _, key := range hashingKeys { if len(strings.TrimSpace(key)) > 0 { - _, err := h.Write([]byte(key)) - if err != nil { - return "" - } + keys += strings.TrimSpace(key) + // _, err := h.Write([]byte(key)) + // if err != nil { + // return "" + // } } } - return strconv.FormatUint(uint64(h.Sum32()), 10) + return keys + + //return strconv.FormatUint(uint64(h.Sum32()), 10) } // function 에 대한 explain 추가 작성 From 9c698fdb6d2e284e14ce765b698ed0b1c1a2e1d1 Mon Sep 17 00:00:00 2001 From: SungWoongz Date: Wed, 28 Feb 2024 15:46:48 +0900 Subject: [PATCH 3/4] =?UTF-8?q?pr=EC=A0=84=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tencent/resources/PriceInfoHandler.go | 60 ++++++++++++++++++- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go index 2075be843..bf47136c4 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go @@ -182,7 +182,6 @@ func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceMod price.PriceInfo.PricingPolicies = pricePolicies priceMap[productId] = price // price 재할당 - cblogger.Info("add policy ", price) } else { // 없으면 // product 추출 productInfo := mappingProductInfo(regionName, *v) @@ -212,6 +211,63 @@ func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceMod } } // end of for } + // reservedInfo + if instanceModel.reservedInfo != nil { + for _, v := range instanceModel.reservedInfo.Response.ReservedInstanceConfigInfos { + for _, info := range v.InstanceFamilies { + for _, iType := range info.InstanceTypes { + for _, p := range iType.Prices { + productId := computeInstanceKeyGeneration(*p.Zone, *iType.InstanceType, *iType.CpuModelName, strconv.FormatUint(*iType.Memory, 10)) + + price, ok := priceMap[productId] + if ok { // 있으면 + // policies 추출 + policy := mappingPricingPolicy(common.StringPtr("RESERVED"), iType.Prices) + + if priceFilter(&policy, filterMap) { + continue + } + + // append policy + pricePolicies := price.PriceInfo.PricingPolicies + pricePolicies = append(pricePolicies, policy) + + priceMap[productId] = price // price 재할당 + } else { // 없으면 + // product 추출 + productInfo := mappingProductInfo(regionName, *iType) + if productFilter(filterMap, &productInfo) { + continue + } + + // for _, val := range *v.price.Res { + + // pricePolicies 추출 + policy := mappingPricingPolicy(common.StringPtr("RESERVED"), *p) + + if priceFilter(&policy, filterMap) { + continue + } + aPrice := irs.Price{} + priceInfo := irs.PriceInfo{} + + pricePolicies := []irs.PricingPolicies{} + pricePolicies = append(pricePolicies, policy) + + priceInfo.PricingPolicies = pricePolicies + + aPrice.ProductInfo = productInfo + aPrice.PriceInfo = priceInfo + + priceMap[productId] = aPrice + // } + } + + } // end of itype.Prices for + } // end of itype for + } // end of instanceFamilies for + } // end of reservedInstanceConfigInfos for + } priceList := make([]irs.Price, 0) if priceMap != nil && len(priceMap) > 0 { @@ -359,7 +415,6 @@ func mappingProductInfo(regionName string, i interface{}) irs.ProductInfo { // TencentSDK VM Product & Pricing struct to irs PricingPolicies func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPolicies { - // price info mapping policyInfo := irs.PricingPolicyInfo{} @@ -398,7 +453,6 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli case reflect.TypeOf(cvm.ReservedInstancePriceItem{}): p := price.(cvm.ReservedInstancePriceItem) - policy.PricingId = strPtrNilCheck(p.ReservedInstancesOfferingId) policy.Unit = strPtrNilCheck(common.StringPtr("Yrs")) policy.Price = floatPtrNilCheck(p.FixedPrice) From 83f2f2b6287c99599fd3d1531f6795021619c16c Mon Sep 17 00:00:00 2001 From: SungWoongz Date: Wed, 28 Feb 2024 16:27:24 +0900 Subject: [PATCH 4/4] Supplement Reserved policy mapping --- .../drivers/tencent/resources/PriceInfoHandler.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go b/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go index bf47136c4..fb812d493 100644 --- a/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go +++ b/cloud-control-manager/cloud-driver/drivers/tencent/resources/PriceInfoHandler.go @@ -222,7 +222,7 @@ func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceMod price, ok := priceMap[productId] if ok { // 있으면 // policies 추출 - policy := mappingPricingPolicy(common.StringPtr("RESERVED"), iType.Prices) + policy := mappingPricingPolicy(common.StringPtr("RESERVED"), p) if priceFilter(&policy, filterMap) { continue @@ -231,7 +231,7 @@ func mappingToComputeStruct(regionName string, instanceModel *TencentInstanceMod // append policy pricePolicies := price.PriceInfo.PricingPolicies pricePolicies = append(pricePolicies, policy) - + price.PriceInfo.PricingPolicies = pricePolicies priceMap[productId] = price // price 재할당 } else { // 없으면 // product 추출 @@ -452,7 +452,11 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli policyInfo.PurchaseOption = strPtrNilCheck(nil) case reflect.TypeOf(cvm.ReservedInstancePriceItem{}): + if isPointer { + price = reflect.ValueOf(price).Elem().Interface() + } p := price.(cvm.ReservedInstancePriceItem) + policy.PricingId = strPtrNilCheck(p.ReservedInstancesOfferingId) policy.Unit = strPtrNilCheck(common.StringPtr("Yrs")) policy.Price = floatPtrNilCheck(p.FixedPrice) @@ -472,7 +476,8 @@ func mappingPricingPolicy(instanceChargeType *string, price any) irs.PricingPoli policyInfo.OfferingClass = strPtrNilCheck(nil) default: - spew.Dump(objType) + //spew.Dump(objType) + cblogger.Info("Type doesn't match", reflect.TypeOf(price)) } return policy