Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

region zone keyvalue and drvCapabilityInfo GCP #931

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (GCPDriver) GetDriverCapability() idrv.DriverCapabilityInfo {
drvCapabilityInfo.VPCHandler = true
drvCapabilityInfo.DiskHandler = false
drvCapabilityInfo.MyImageHandler = false
drvCapabilityInfo.RegionZoneHandler = false
drvCapabilityInfo.RegionZoneHandler = true
drvCapabilityInfo.ClusterHandler = true

return drvCapabilityInfo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1808,6 +1808,7 @@ func handleRegionZone() {
fmt.Println("1. RegionZone List")
fmt.Println("2. OrgRegion List")
fmt.Println("3. OrgZone List")
fmt.Println("4. GetRegionZone List")

var commandNum int
inputCnt, err := fmt.Scan(&commandNum)
Expand Down Expand Up @@ -1854,6 +1855,16 @@ func handleRegionZone() {
cblogger.Infof("[%s] ListOrgZone 조회 성공 : ", result)
spew.Dump(result)
}
case 4:
regionName := "us-central1"
result, err := handler.GetRegionZone(regionName)
if err != nil {
cblogger.Infof("[%s] GetRegionZone 조회 실패 : ", err)
} else {
cblogger.Infof("[%s] GetRegionZone 조회 성공 : ", result)
spew.Dump(result)
}

}
}
}
Expand All @@ -1866,7 +1877,7 @@ func main() {
//handleImage() //AMI
//handleKeyPair()
//handleSecurity()
//handleVM()
// handleVM()
//handleLoadBalancer()
//handleDisk()
//handleMyImage()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ package resources

import (
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
Expand All @@ -42,6 +45,7 @@ const (

const CBDefaultVNetName string = "cb-vnet" // CB Default Virtual Network Name
const CBDefaultSubnetName string = "cb-vnet" // CB Default Subnet Name
const KEY_VALUE_CONVERT_DEBUG_INFO bool = false

const OperationGlobal = 1
const OperationRegion = 2
Expand Down Expand Up @@ -101,6 +105,7 @@ func GetCBDefaultSubnetName() string {
return CBDefaultSubnetName
}

// KeyValue gen func
func GetKeyValueList(i map[string]interface{}) []irs.KeyValue {
var keyValueList []irs.KeyValue
for k, v := range i {
Expand All @@ -121,6 +126,88 @@ func GetKeyValueList(i map[string]interface{}) []irs.KeyValue {
return keyValueList
}

// Cloud Object를 CB-KeyValue 형식으로 변환이 필요할 경우 이용
func ConvertKeyValueList(v interface{}) ([]irs.KeyValue, error) {
//spew.Dump(v)
var keyValueList []irs.KeyValue
var i map[string]interface{}

jsonBytes, errJson := json.Marshal(v)
if errJson != nil {
cblogger.Error("KeyValue 변환 실패")
cblogger.Error(errJson)
return nil, errJson
}

json.Unmarshal(jsonBytes, &i)

for k, v := range i {
if KEY_VALUE_CONVERT_DEBUG_INFO {
cblogger.Debugf("K:[%s]====>", k)
}
/*
cblogger.Infof("v:[%s]====>", reflect.ValueOf(v))

vv := reflect.ValueOf(v)
cblogger.Infof("value ====>[%s]", vv.String())
s := fmt.Sprint(v)
cblogger.Infof("value2 ====>[%s]", s)
*/
//value := fmt.Sprint(v)
value, errString := ConvertToString(v)
if errString != nil {
//cblogger.Debugf("Key[%s]의 값은 변환 불가 - [%s]", k, errString) //요구에 의해서 Error에서 Warn으로 낮춤
continue
}
keyValueList = append(keyValueList, irs.KeyValue{k, value})

/*
_, ok := v.(string)
if !ok {
cblogger.Errorf("Key[%s]의 값은 변환 불가", k)
continue
}
keyValueList = append(keyValueList, irs.KeyValue{k, v.(string)})
*/
}
cblogger.Debug("getKeyValueList : ", keyValueList)
//keyValueList = append(keyValueList, irs.KeyValue{"test", typeToString([]float32{3.14, 1.53, 2.0000000000000})})

return keyValueList, nil
}

// CB-KeyValue 등을 위해 String 타입으로 변환
func ConvertToString(value interface{}) (string, error) {
if value == nil {
if KEY_VALUE_CONVERT_DEBUG_INFO {
cblogger.Debugf("Nil Value")
}
return "", errors.New("Nil. Value")
}

var result string
t := reflect.ValueOf(value)
if KEY_VALUE_CONVERT_DEBUG_INFO {
cblogger.Debug("==>ValueOf : ", t)
}

switch value.(type) {
case float32:
result = strconv.FormatFloat(t.Float(), 'f', -1, 32) // f, fmt, prec, bitSize
case float64:
result = strconv.FormatFloat(t.Float(), 'f', -1, 64) // f, fmt, prec, bitSize
//strconv.FormatFloat(instanceTypeInfo.MemorySize, 'f', 0, 64)

default:
if KEY_VALUE_CONVERT_DEBUG_INFO {
cblogger.Debug("--> default type:", reflect.ValueOf(value).Type())
}
result = fmt.Sprint(value)
}

return result, nil
}

// KeyPair 해시 생성 함수
func CreateHashString(credentialInfo idrv.CredentialInfo) (string, error) {
keyString := credentialInfo.ClientId + credentialInfo.ClientSecret + credentialInfo.TenantId + credentialInfo.SubscriptionId
Expand Down Expand Up @@ -512,38 +599,103 @@ func WaitContainerOperationDone(client *container.Service, project string, regio
return nil
}

// region에 해당하는 zone 목록 조회
func GetZoneListByRegion(client *compute.Service, regionUrl string) (*compute.ZoneList, error) {
projectId := ""
regionName := ""
// 리전 목록 조회
func ListRegion(client *compute.Service, projectId string) (*compute.RegionList, error) {

arrLink := strings.Split(regionUrl, "/")
if len(arrLink) > 0 {
regionName = arrLink[len(arrLink)-1]
for pos, item := range arrLink {
if strings.EqualFold(item, "projects") {
projectId = arrLink[pos+1]
break
}
}
if projectId == "" {
return nil, errors.New("ProjectId not found.")
}

callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: "",
ResourceType: call.REGIONZONE,
ResourceName: "",
CloudOSAPI: "List()",
ElapsedTime: "",
ErrorMSG: "",
}
cblogger.Infof("projectId : [%s] / imageName : [%s]", projectId, regionName)
callLogStart := call.Start()
resp, err := client.Regions.List(projectId).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)

if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return nil, err
}
return resp, nil
}

// region 조회
// GCP에서 region은 regionName과 regionUri로 구분 됨. regionName으로 찾는 function임.
func GetRegion(client *compute.Service, projectId string, regionName string) (*compute.Region, error) {

if projectId == "" {
return nil, errors.New("ProjectId information not found in URL.")
return nil, errors.New("ProjectId not found.")
}

if regionName == "" {
return nil, errors.New("Region Name not found.")
}

resp, err := client.Zones.List(projectId).Do()
callogger := call.GetLogger("HISCALL")
callLogInfo := call.CLOUDLOGSCHEMA{
CloudOS: call.GCP,
RegionZone: regionName,
ResourceType: call.REGIONZONE,
ResourceName: "",
CloudOSAPI: "Get()",
ElapsedTime: "",
ErrorMSG: "",
}
callLogStart := call.Start()
resp, err := client.Regions.Get(projectId, regionName).Do()
callLogInfo.ElapsedTime = call.Elapsed(callLogStart)

if err != nil {
callLogInfo.ErrorMSG = err.Error()
callogger.Info(call.String(callLogInfo))
cblogger.Error(err)
return nil, err
}
return resp, nil

}

// region에 해당하는 zone 목록 조회
// filter조건으로 사용하는 region조건은 regionUrl로 넘겨야 함.
// filter조건 자체가 string이며 regionUrl에 특수문자가 있고 따옴표로 감싸야만 결과가 정상적으로 나옴
// region="xxx/xxx/xxx" 형태로 보내야하며
// ` ` 로 감싸야 함.
// filter := "region=https://www.googleapis.com/compute/v1/projects/xxx/regions/us-east1" -> error return.
// filter := `region="https://www.googleapis.com/compute/v1/projects/xxx/regions/us-east1"` -> 조회결과 옴
// filter := `region="us-east1"`// -> 조회결과 없음
func GetZoneListByRegion(client *compute.Service, projectId string, regionUrl string) (*compute.ZoneList, error) {

if projectId == "" {
return nil, errors.New("Project information not found")
}
if regionUrl == "" {
return nil, errors.New("Region information not found")
}

filter := `region="` + regionUrl + `"`

resp, err := client.Zones.List(projectId).Filter(filter).Do()

if err != nil {
cblogger.Error(err)
return nil, err
}
// spew.Dump(resp)
return resp, nil
}

// Available or Unavailable 로 return
// Status of the zone, either UP or DOWN.
// Status of the zone, either UP or DOWN. (지원하지 않는 경우 NotSupported)
func GetZoneStatus(status string) irs.ZoneStatus {
if status == "UP" {
return irs.ZoneAvailable
Expand Down
Loading