forked from aliyun/terraform-provider-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
484 lines (393 loc) · 10.2 KB
/
common.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
package alicloud
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
"strconv"
"strings"
"github.com/mitchellh/go-homedir"
"gopkg.in/yaml.v2"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/denverdino/aliyungo/common"
"github.com/google/uuid"
)
type InstanceNetWork string
const (
ClassicNet = InstanceNetWork("classic")
VpcNet = InstanceNetWork("vpc")
)
type PayType string
const (
PrePaid = PayType("PrePaid")
PostPaid = PayType("PostPaid")
Prepaid = PayType("Prepaid")
Postpaid = PayType("Postpaid")
)
type NetType string
const (
Internet = NetType("Internet")
Intranet = NetType("Intranet")
)
type NetworkType string
const (
Classic = NetworkType("Classic")
Vpc = NetworkType("Vpc")
)
type TimeType string
const (
Hour = TimeType("Hour")
Day = TimeType("Day")
Week = TimeType("Week")
Month = TimeType("Month")
Year = TimeType("Year")
)
type Status string
const (
Pending = Status("Pending")
Creating = Status("Creating")
Running = Status("Running")
Available = Status("Available")
Unavailable = Status("Unavailable")
Modifying = Status("Modifying")
Deleting = Status("Deleting")
Starting = Status("Starting")
Stopping = Status("Stopping")
Stopped = Status("Stopped")
Normal = Status("Normal")
Changing = Status("Changing")
Associating = Status("Associating")
Unassociating = Status("Unassociating")
InUse = Status("InUse")
DiskInUse = Status("In_use")
Active = Status("Active")
Inactive = Status("Inactive")
Idle = Status("Idle")
SoldOut = Status("SoldOut")
InService = Status("InService")
Removing = Status("Removing")
DisabledStatus = Status("Disabled")
Init = Status("Init")
Provisioning = Status("Provisioning")
Updating = Status("Updating")
FinancialLocked = Status("FinancialLocked")
PUBLISHED = Status("Published")
NOPUBLISHED = Status("NonPublished")
)
type IPType string
const (
Inner = IPType("Inner")
Private = IPType("Private")
Public = IPType("Public")
)
type ResourceType string
const (
ResourceTypeInstance = ResourceType("Instance")
ResourceTypeDisk = ResourceType("Disk")
ResourceTypeVSwitch = ResourceType("VSwitch")
ResourceTypeRds = ResourceType("Rds")
IoOptimized = ResourceType("IoOptimized")
ResourceTypeRkv = ResourceType("KVStore")
)
type InternetChargeType string
const (
PayByBandwidth = InternetChargeType("PayByBandwidth")
PayByTraffic = InternetChargeType("PayByTraffic")
)
// timeout for common product, ecs e.g.
const DefaultTimeout = 120
const DefaultTimeoutMedium = 500
// timeout for long time progerss product, rds e.g.
const DefaultLongTimeout = 1000
const DefaultIntervalShort = 5
const DefaultIntervalMedium = 10
const DefaultIntervalLong = 20
const (
PageSizeSmall = 10
PageSizeMedium = 20
PageSizeLarge = 50
)
// Protocol represents network protocol
type Protocol string
// Constants of protocol definition
const (
Http = Protocol("http")
Https = Protocol("https")
Tcp = Protocol("tcp")
Udp = Protocol("udp")
All = Protocol("all")
Icmp = Protocol("icmp")
Gre = Protocol("gre")
)
// ValidProtocols network protocol list
var ValidProtocols = []Protocol{Http, Https, Tcp, Udp}
// simple array value check method, support string type only
func isProtocolValid(value string) bool {
res := false
for _, v := range ValidProtocols {
if string(v) == value {
res = true
}
}
return res
}
// default region for all resource
const DEFAULT_REGION = "cn-beijing"
const INT_MAX = 2147483647
// symbol of multiIZ
const MULTI_IZ_SYMBOL = "MAZ"
// default connect port of db
const DB_DEFAULT_CONNECT_PORT = "3306"
const COMMA_SEPARATED = ","
const COLON_SEPARATED = ":"
const LOCAL_HOST_IP = "127.0.0.1"
// Takes the result of flatmap.Expand for an array of strings
// and returns a []string
func expandStringList(configured []interface{}) []string {
vs := make([]string, 0, len(configured))
for _, v := range configured {
vs = append(vs, v.(string))
}
return vs
}
// Takes list of string to strings. Expand to an array
// of raw strings and returns a []interface{}
func flattenStringList(list []string) []interface{} {
vs := make([]interface{}, 0, len(list))
for _, v := range list {
vs = append(vs, v)
}
return vs
}
func expandIntList(configured []interface{}) []int {
vs := make([]int, 0, len(configured))
for _, v := range configured {
vs = append(vs, v.(int))
}
return vs
}
// Convert the result for an array and returns a Json string
func convertListToJsonString(configured []interface{}) string {
if len(configured) < 1 {
return ""
}
result := "["
for i, v := range configured {
result += "\"" + v.(string) + "\""
if i < len(configured)-1 {
result += ","
}
}
result += "]"
return result
}
func StringPointer(s string) *string {
return &s
}
func BoolPointer(b bool) *bool {
return &b
}
func Int32Pointer(i int32) *int32 {
return &i
}
const ServerSideEncryptionAes256 = "AES256"
type OptimizedType string
const (
IOOptimized = OptimizedType("optimized")
NoneOptimized = OptimizedType("none")
)
type TagResourceType string
const (
TagResourceImage = TagResourceType("image")
TagResourceInstance = TagResourceType("instance")
TagResourceSnapshot = TagResourceType("snapshot")
TagResourceDisk = TagResourceType("disk")
TagResourceSecurityGroup = TagResourceType("securitygroup")
)
func getPagination(pageNumber, pageSize int) (pagination common.Pagination) {
pagination.PageSize = pageSize
pagination.PageNumber = pageNumber
return
}
const CharityPageUrl = "http://promotion.alicdn.com/help/oss/error.html"
func userDataHashSum(user_data string) string {
// Check whether the user_data is not Base64 encoded.
// Always calculate hash of base64 decoded value since we
// check against double-encoding when setting it
v, base64DecodeError := base64.StdEncoding.DecodeString(user_data)
if base64DecodeError != nil {
v = []byte(user_data)
}
return string(v)
}
// Remove useless blank in the string.
func Trim(v string) string {
if len(v) < 1 {
return v
}
return strings.Trim(v, " ")
}
func ConvertIntegerToInt(value requests.Integer) (v int, err error) {
if strings.TrimSpace(string(value)) == "" {
return
}
v, err = strconv.Atoi(string(value))
if err != nil {
return v, fmt.Errorf("Converting integer %s to int got an error: %#v.", value, err)
}
return
}
func GetUserHomeDir() (string, error) {
usr, err := user.Current()
if err != nil {
return "", fmt.Errorf("Get current user got an error: %#v.", err)
}
return usr.HomeDir, nil
}
func writeToFile(filePath string, data interface{}) error {
if strings.HasPrefix(filePath, "~") {
home, err := GetUserHomeDir()
if err != nil {
return err
}
if home != "" {
filePath = strings.Replace(filePath, "~", home, 1)
}
}
os.Remove(filePath)
var out string
switch data.(type) {
case string:
out = data.(string)
break
case nil:
return nil
default:
bs, err := json.MarshalIndent(data, "", "\t")
if err != nil {
return fmt.Errorf("MarshalIndent data %#v got an error: %#v", data, err)
}
out = string(bs)
}
ioutil.WriteFile(filePath, []byte(out), 422)
return nil
}
type Invoker struct {
catchers []*Catcher
}
type Catcher struct {
Reason string
RetryCount int
RetryWaitSeconds int
}
var ClientErrorCatcher = Catcher{AliyunGoClientFailure, 10, 5}
var ServiceBusyCatcher = Catcher{"ServiceUnavailable", 10, 5}
var ThrottlingCatcher = Catcher{Throttling, 10, 10}
func NewInvoker() Invoker {
i := Invoker{}
i.AddCatcher(ClientErrorCatcher)
i.AddCatcher(ServiceBusyCatcher)
i.AddCatcher(ThrottlingCatcher)
return i
}
func (a *Invoker) AddCatcher(catcher Catcher) {
a.catchers = append(a.catchers, &catcher)
}
func (a *Invoker) Run(f func() error) error {
err := f()
if err == nil {
return nil
}
for _, catcher := range a.catchers {
if IsExceptedErrors(err, []string{catcher.Reason}) {
catcher.RetryCount--
if catcher.RetryCount <= 0 {
return fmt.Errorf("Retry timeout and got an error: %#v.", err)
} else {
time.Sleep(time.Duration(catcher.RetryWaitSeconds) * time.Second)
return a.Run(f)
}
}
}
return err
}
func buildClientToken(prefix string) string {
token := strings.Replace(fmt.Sprintf("%s-%d-%s", prefix, time.Now().Unix(), uuid.New().String()), " ", "", -1)
if len(token) > 64 {
token = token[0:64]
}
return token
}
func getNextpageNumber(number requests.Integer) (requests.Integer, error) {
page, err := strconv.Atoi(string(number))
if err != nil {
return "", err
}
return requests.NewInteger(page + 1), nil
}
func terraformToAPI(field string) string {
var result string
for _, v := range strings.Split(field, "_") {
if len(v) > 0 {
result = fmt.Sprintf("%s%s%s", result, strings.ToUpper(string(v[0])), v[1:])
}
}
return result
}
func compareJsonTemplateAreEquivalent(tem1, tem2 string) (bool, error) {
var obj1 interface{}
err := json.Unmarshal([]byte(tem1), &obj1)
if err != nil {
return false, err
}
canonicalJson1, _ := json.Marshal(obj1)
var obj2 interface{}
err = json.Unmarshal([]byte(tem2), &obj2)
if err != nil {
return false, err
}
canonicalJson2, _ := json.Marshal(obj2)
equal := bytes.Compare(canonicalJson1, canonicalJson2) == 0
if !equal {
log.Printf("[DEBUG] Canonical template are not equal.\nFirst: %s\nSecond: %s\n",
canonicalJson1, canonicalJson2)
}
return equal, nil
}
func compareYamlTemplateAreEquivalent(tem1, tem2 string) (bool, error) {
var obj1 interface{}
err := yaml.Unmarshal([]byte(tem1), &obj1)
if err != nil {
return false, err
}
canonicalYaml1, _ := yaml.Marshal(obj1)
var obj2 interface{}
err = yaml.Unmarshal([]byte(tem2), &obj2)
if err != nil {
return false, err
}
canonicalYaml2, _ := yaml.Marshal(obj2)
equal := bytes.Compare(canonicalYaml1, canonicalYaml2) == 0
if !equal {
log.Printf("[DEBUG] Canonical template are not equal.\nFirst: %s\nSecond: %s\n",
canonicalYaml1, canonicalYaml2)
}
return equal, nil
}
// loadFileContent returns contents of a file in a given path
func loadFileContent(v string) ([]byte, error) {
filename, err := homedir.Expand(v)
if err != nil {
return nil, err
}
fileContent, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return fileContent, nil
}