-
Notifications
You must be signed in to change notification settings - Fork 47
/
CommonAlibabaFunc.go
276 lines (233 loc) · 6.79 KB
/
CommonAlibabaFunc.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
// Cloud Driver 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, 2019.09.
package resources
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"sync"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
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/sirupsen/logrus"
)
const (
// default Resource GROUP Name
CBResourceGroupName = "CB-GROUP"
// default VPC Name
CBVirutalNetworkName = "CB-VNet"
// default CIDR Block
CBVnetDefaultCidr = "130.0.0.0/16"
// default VM User Name
CBDefaultVmUserName = "cb-user"
// default Subnet Name
CBSubnetName = "CB-VNet-Sub"
// default Bandwidth is 5 Mbit/s
CBBandwidth = "5"
// default InstanceChargeType
CBInstanceChargeType = "PostPaid"
// default InternetChargeType
CBInternetChargeType = "PayByTraffic"
// default Tag Name
CBMetaDefaultTagName = "cbCate"
// default Tag Value
CBMetaDefaultTagValue = "cbAlibaba"
CBPageOn = true
// page number for control pages
CBPageNumber = 1 // 페이지 시작은 1부터 시작되기 때문에 삭제 예정
// page size for control pages
CBPageSize = 100 //오브젝트(예: 이미지 / 키페어 / ...) 마다 지정 개수가 달라서 삭제 예정
CBKeyPairPath = "/meta_db/.ssh-aliyun/"
//CBCloudInitFilePath = "/cloud-driver-libs/.cloud-init-aliyun/cloud-init"
CBCloudInitFilePath = "/cloud-driver-libs/.cloud-init-common/cloud-init"
)
type AlibabaCBNetworkInfo struct {
VpcName string
VpcId string
CidrBlock string
IsDefault bool
State string
SubnetName string
SubnetId string
}
var once sync.Once
var cblogger *logrus.Logger
var calllogger *logrus.Logger
func InitLog() {
once.Do(func() {
// cblog is a global variable.
cblogger = cblog.GetLogger("CB-SPIDER")
calllogger = call.GetLogger("HISCALL")
})
}
func LoggingError(hiscallInfo call.CLOUDLOGSCHEMA, err error) {
hiscallInfo.ErrorMSG = err.Error()
calllogger.Error(call.String(hiscallInfo))
}
func LoggingInfo(hiscallInfo call.CLOUDLOGSCHEMA, start time.Time) {
hiscallInfo.ElapsedTime = call.Elapsed(start)
calllogger.Info(call.String(hiscallInfo))
}
func GetCallLogScheme(region idrv.RegionInfo, resourceType call.RES_TYPE, resourceName string, apiName string) call.CLOUDLOGSCHEMA {
cblogger.Info(fmt.Sprintf("Call %s %s", call.ALIBABA, apiName))
return call.CLOUDLOGSCHEMA{
CloudOS: call.ALIBABA,
RegionZone: region.Region,
ResourceType: resourceType,
ResourceName: resourceName,
CloudOSAPI: apiName,
}
}
func GetCBResourceGroupName() string {
return CBResourceGroupName
}
// VPC
func GetCBVirutalNetworkName() string {
return CBVirutalNetworkName
}
// Subnet
func GetCBSubnetName() string {
return CBSubnetName
}
func GetCBVnetDefaultCidr() string {
return CBVnetDefaultCidr
}
func SetNameTag(Client *ecs.Client, resourceId string, resourceType string, value string) bool {
// Tag에 Name 설정
cblogger.Infof("Name Tage 설정 - ResourceId : [%s] Value : [%s] ", resourceId, value)
request := ecs.CreateAddTagsRequest()
request.Scheme = "https"
request.ResourceType = resourceType // "disk", "instance", "image", "securitygroup", "snapshot"
request.ResourceId = resourceId // "i-t4n4qtfwa4w5aavx588v"
request.Tag = &[]ecs.AddTagsTag{
{
Key: "Name",
Value: value, // "cbVal",
},
{
Key: "cbCate",
Value: "cbAlibaba",
},
{
Key: "cbName",
Value: value, // "cbVal",
},
// Resources: []*string{&Id},
}
_, errtag := Client.AddTags(request)
if errtag != nil {
cblogger.Error("Name Tag 설정 실패 : ")
cblogger.Error(errtag)
return false
}
return true
}
// Cloud Object를 JSON String 타입으로 변환
func ConvertJsonString(v interface{}) (string, error) {
jsonBytes, errJson := json.Marshal(v)
if errJson != nil {
cblogger.Error("JSON 변환 실패")
cblogger.Error(errJson)
return "", errJson
}
jsonString := string(jsonBytes)
return jsonString, nil
}
// CB-KeyValue 등을 위해 String 타입으로 변환
func ConvertToString(value interface{}) (string, error) {
if value == nil {
cblogger.Error("Nil Value")
return "", errors.New("NIL Value")
}
var result string
t := reflect.ValueOf(value)
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:
cblogger.Debug("--> default type:", reflect.ValueOf(value).Type())
result = fmt.Sprint(value)
}
return result, nil
}
// 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 {
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.Errorf("Key[%s]의 값은 변환 불가 - [%s]", k, errString)
continue
}
keyValueList = append(keyValueList, irs.KeyValue{k, value})
}
cblogger.Debug("getKeyValueList : ", keyValueList)
//keyValueList = append(keyValueList, irs.KeyValue{"test", typeToString([]float32{3.14, 1.53, 2.0000000000000})})
return keyValueList, nil
}
// array에 주어진 string이 있는지 체크
func ContainString(s []string, str string) bool {
for _, v := range s {
cblogger.Info(v + " : " + str)
cblogger.Info(v == str)
if v == str {
return true
}
}
return false
}
/*
*
json 형태로 출력
*/
func printToJson(class interface{}) {
e, err := json.Marshal(class)
if err != nil {
cblogger.Info(err)
}
cblogger.Info(string(e))
}
// irs.KeyValue 배열에서 특정 키를 가진 KeyValue 가 있는지 검사
func HasKey(key string, keyValueList []irs.KeyValue) bool {
for _, kv := range keyValueList {
if kv.Key == key {
return true
}
}
return false
}