-
Notifications
You must be signed in to change notification settings - Fork 47
/
CommonAwsFunc.go
359 lines (305 loc) · 10.6 KB
/
CommonAwsFunc.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
// 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 CB-Spider Team, 2019.06.
package resources
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
irs "github.com/cloud-barista/cb-spider/cloud-control-manager/cloud-driver/interfaces/resources"
)
const CBDefaultVNetName string = "CB-VNet" // CB Default Virtual Network Name
const CBDefaultSubnetName string = "CB-VNet-Subnet" // CB Default Subnet Name
const CBDefaultCidrBlock string = "192.168.0.0/16" // CB Default CidrBlock
type AwsCBNetworkInfo struct {
VpcName string
VpcId string
CidrBlock string
IsDefault bool
State string
SubnetName string
SubnetId string
}
const CUSTOM_ERR_CODE_TOOMANY string = "600" //awserr.New("600", "n개 이상의 xxxx 정보가 존재합니다.", nil)
const CUSTOM_ERR_CODE_NOTFOUND string = "404" //awserr.New("404", "XXX 정보가 존재하지 않습니다.", nil)
//VPC
func GetCBDefaultVNetName() string {
return CBDefaultVNetName
}
//Subnet
func GetCBDefaultSubnetName() string {
return CBDefaultSubnetName
}
func GetCBDefaultCidrBlock() string {
return CBDefaultCidrBlock
}
/*
//이 함수는 VPC & Subnet이 존재하는 곳에서만 사용됨.
//VPC & Subnet이 존재하는 경우 정보를 리턴하고 없는 경우 Default VPC & Subnet을 생성 후 정보를 리턴 함.
func (VPCHandler *AwsVPCHandler) GetAutoCBNetworkInfo() (AwsCBNetworkInfo, error) {
return AwsCBNetworkInfo{}, errors.New("인터페이스 변경해야 함!!!!")
var awsCBNetworkInfo AwsCBNetworkInfo
subNetId := VPCHandler.GetMcloudBaristaDefaultSubnetId()
if subNetId == "" {
//내부에서 VPC를 자동으로 생성후 Subnet을 생성함.
_, err := VPCHandler.CreateVNetwork(irs.VNetworkReqInfo{})
if err != nil {
cblogger.Error("Default VNetwork(VPC & Subnet) 자동 생성 실패")
cblogger.Error(err)
return AwsCBNetworkInfo{}, err
}
}
//VPC & Subnet을 생성했으므로 예외처리 없이 조회만 처리함.
awsVpcInfo, _ := VPCHandler.GetVpc(GetCBDefaultVNetName())
spew.Dump(awsVpcInfo)
awsCBNetworkInfo.VpcId = awsVpcInfo.Id
awsCBNetworkInfo.VpcName = awsVpcInfo.Name
awsSubnetInfo, _ := VPCHandler.GetVNetwork(irs.IID{})
spew.Dump(awsSubnetInfo)
//awsCBNetworkInfo.SubnetId = awsSubnetInfo.Id
//awsCBNetworkInfo.SubnetName = awsSubnetInfo.Name
awsCBNetworkInfo.SubnetId = awsSubnetInfo.IId.SystemId
awsCBNetworkInfo.SubnetName = awsSubnetInfo.IId.NameId
spew.Dump(awsCBNetworkInfo)
return awsCBNetworkInfo, nil
}
*/
/*
func (VPCHandler *AwsVPCHandler) GetMcloudBaristaDefaultVpcId() string {
return ""
awsVpcInfo, err := VPCHandler.GetVpc(GetCBDefaultVNetName())
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
}
} else {
cblogger.Error(err.Error())
}
return ""
}
//기존 정보가 존재하면...
if awsVpcInfo.Id != "" {
return awsVpcInfo.Id
} else {
return ""
}
}
*/
/*
//@TODO : awsSubnetInfo.IId.SystemId를 리턴해야 하는지 NameId를 리턴해야 하는지 체크해야 함. -> 생성된 정보가 있는지만 체크 하므로 상관 없음.
func (VPCHandler *AwsVPCHandler) GetMcloudBaristaDefaultSubnetId() string {
awsSubnetInfo, err := VPCHandler.GetVNetwork(irs.IID{})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
cblogger.Error(aerr.Error())
}
} else {
cblogger.Error(err.Error())
}
return ""
}
//기존 정보가 존재하면...
//if awsSubnetInfo.Id != "" {
// return awsSubnetInfo.Id
if awsSubnetInfo.IId.SystemId != "" {
return awsSubnetInfo.IId.SystemId
} else {
return ""
}
}
//@TODO : ListVNetwork()에서 호출되는 경우도 있기 때문에 필요하면 VPC조회와 생성을 별도의 Func으로 분리해야함.(일단은 큰 문제는 없어서 놔둠)
//CB Default Virtual Network가 존재하지 않으면 생성하며, 존재하는 경우 Vpc ID를 리턴 함.
func (VPCHandler *AwsVPCHandler) FindOrCreateMcloudBaristaDefaultVPC(vNetworkReqInfo irs.VNetworkReqInfo) (string, error) {
cblogger.Info(vNetworkReqInfo)
awsVpcInfo, err := VPCHandler.GetVpc(GetCBDefaultVNetName())
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
}
//기존 정보가 존재하면...
if awsVpcInfo.Id != "" {
return awsVpcInfo.Id, nil
} else {
//@TODO : Subnet과 VPC모두 CSP별 고정된 값으로 드라이버가 내부적으로 자동으로 생성하도록 CB규약이 바뀌어서 서브넷 정보 기반의 로직은 모두 잠시 죽여 놓음 - 리스트 요청시에도 내부적으로 자동 생성하도록 변경 중
/ *
cblogger.Infof("기본 VPC[%s]가 없어서 Subnet 요청 정보를 기반으로 /16 범위의 VPC를 생성합니다.", GetCBDefaultVNetName())
cblogger.Info("Subnet CIDR 요청 정보 : ", vNetworkReqInfo.CidrBlock)
if vNetworkReqInfo.CidrBlock == "" {
//VPC가 없는 최초 상태에서 List()에서 호출되었을 수 있기 때문에 에러 처리는 하지 않고 nil을 전달함.
cblogger.Infof("요청 정보에 CIDR 정보가 없어서 Default VPC[%s]를 생성하지 않음", GetCBDefaultVNetName())
return "", nil
}
reqCidr := strings.Split(vNetworkReqInfo.CidrBlock, ".")
//cblogger.Info("CIDR 추출 정보 : ", reqCidr[0])
VpcCidrBlock := reqCidr[0] + "." + reqCidr[1] + ".0.0/16"
cblogger.Info("신규 VPC에 사용할 CIDR 정보 : ", VpcCidrBlock)
* /
cblogger.Infof("기본 VPC[%s]가 없어서 CIDR[%s] 범위의 VPC를 자동으로 생성합니다.", GetCBDefaultVNetName(), GetCBDefaultCidrBlock())
awsVpcReqInfo := AwsVpcReqInfo{
Name: GetCBDefaultVNetName(),
//CidrBlock: VpcCidrBlock,
CidrBlock: GetCBDefaultCidrBlock(),
}
result, errVpc := VPCHandler.CreateVpc(awsVpcReqInfo)
if errVpc != nil {
cblogger.Error(errVpc)
return "", errVpc
}
cblogger.Infof("CB Default VPC[%s] 생성 완료 - CIDR : [%s]", GetCBDefaultVNetName(), result.CidrBlock)
cblogger.Info(result)
spew.Dump(result)
return result.Id, nil
}
}
//자동으로 생성된 VPC & Subnet을 삭제해도 되는가?
//명시적으로 Subnet 삭제의 호출이 없기 때문에 시큐리티 그룹이나 vNic이 삭제되는 시점에 호출됨.
func (VPCHandler *AwsVPCHandler) IsAvailableAutoCBNet() bool {
return false
}
*/
//Name Tag 설정
func SetNameTag(Client *ec2.EC2, Id string, value string) bool {
// Tag에 Name 설정
cblogger.Infof("Name Tage 설정 - ResourceId : [%s] Value : [%s] ", Id, value)
_, errtag := Client.CreateTags(&ec2.CreateTagsInput{
Resources: []*string{&Id},
Tags: []*ec2.Tag{
{
Key: aws.String("Name"),
Value: aws.String(value),
},
},
})
if errtag != nil {
cblogger.Error("Name Tag 설정 실패 : ")
cblogger.Error(errtag)
return false
}
return true
}
func JSONMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}
//Cloud Object를 JSON String 타입으로 변환
func ConvertJsonStringNoEscape(v interface{}) (string, error) {
//jsonBytes, errJson := json.Marshal(v)
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
errJson := encoder.Encode(v)
if errJson != nil {
cblogger.Error("JSON 변환 실패")
cblogger.Error(errJson)
return "", errJson
}
//fmt.Println("After marshal", string(buffer.Bytes()))
//spew.Dump(string(buffer.Bytes()))
//spew.Dump("\"TEST")
jsonString := string(buffer.Bytes())
//jsonString = strings.Replace(jsonString, "\n", "", -1)
jsonString = strings.Replace(jsonString, "\"", "", -1)
return jsonString, nil
}
//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.Debugf("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)
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
}