-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecs.go
427 lines (378 loc) · 13.6 KB
/
ecs.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
package main
import (
"fmt"
"log"
"strings"
"time"
ecsMdl "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/model"
)
const (
InstanceDefaultTimeout = 900
DefaultWaitForInterval = 5
ECSInstanceStatusRunning = "ACTIVE"
)
func CreateEcs(client Client, config *Config, vpcId, networkId string, securityGroupIds []string) ([]*ecsMdl.ServerDetail, error) {
request := &ecsMdl.CreateServersRequest{Body: &ecsMdl.CreateServersRequestBody{Server: &ecsMdl.PrePaidServer{}}}
request.Body.Server.Name = config.ECSName
imageId, minDisk, err := GetImageIdAndDisk(config, client)
if err != nil {
return nil, err
}
request.Body.Server.ImageRef = imageId
request.Body.Server.FlavorRef = config.Flavor
request.Body.Server.Vpcid = vpcId
nics := make([]ecsMdl.PrePaidServerNic, 0)
nics = append(nics, ecsMdl.PrePaidServerNic{SubnetId: networkId})
request.Body.Server.Nics = nics
securityGroups := make([]ecsMdl.PrePaidServerSecurityGroup, 0)
for _, id := range securityGroupIds {
securityGroups = append(securityGroups, ecsMdl.PrePaidServerSecurityGroup{Id: &id})
}
request.Body.Server.SecurityGroups = &securityGroups
if config.PublicIp {
publicIp := ecsMdl.PrePaidServerPublicip{}
publicIp.Eip = &ecsMdl.PrePaidServerEip{
Iptype: getIpType(config.PublicIpSpec.IpType),
Bandwidth: &ecsMdl.PrePaidServerEipBandwidth{
Size: &config.PublicIpSpec.Size,
Sharetype: getPublicIpShareType(config.PublicIpSpec.ShareType),
Chargemode: &config.PublicIpSpec.ChargeMode,
},
}
request.Body.Server.Publicip = &publicIp
}
request.Body.Server.ServerTags = buildTagList(config)
if config.Userdata != "" {
request.Body.Server.UserData = &config.Userdata
}
request.Body.Server.RootVolume = getRootVolumeProperties(minDisk, config)
request.Body.Server.DataVolumes = getDataVolumeProperties(minDisk, config)
request.Body.Server.AvailabilityZone = &config.AvailabilityZone
request.Body.Server.BatchCreateInMultiAz = &config.BatchCreateInMultiAz
//use iso image
//metedata := make(map[string]string)
//metedata["virtual_env_type"] = "IsoImage"
//request.Body.Server.Metadata = metedata
request.Body.Server.Extendparam = getCharging(config)
diskPrior := "true"
request.Body.Server.Extendparam.DiskPrior = &diskPrior
request.Body.Server.Extendparam.RegionID = &config.RegionId
request.Body.Server.OsschedulerHints = getServerSchedulerHints(config)
response, err := client.CreateServers(request)
if err != nil {
return nil, err
}
// Sleep
time.Sleep(5 * time.Second)
instance, err := waitForInstancesStatus(client, config.PublicIp, *response.ServerIds, ECSInstanceStatusRunning, InstanceDefaultTimeout)
if err != nil {
return nil, err
}
fmt.Println("create ecs success")
return instance, nil
}
func getServerSchedulerHints(config *Config) *ecsMdl.PrePaidServerSchedulerHints {
if config.ServerSchedulerHints.Group == "" {
return nil
}
var serverSchedulerHints ecsMdl.PrePaidServerSchedulerHints
switch config.ServerSchedulerHints.Tenancy {
case "shared":
shared := ecsMdl.GetPrePaidServerSchedulerHintsTenancyEnum().SHARED
serverSchedulerHints.Tenancy = &shared
case "dedicated":
dedicated := ecsMdl.GetPrePaidServerSchedulerHintsTenancyEnum().DEDICATED
serverSchedulerHints.Tenancy = &dedicated
}
serverSchedulerHints.Group = &config.ServerSchedulerHints.Group
serverSchedulerHints.DedicatedHostId = &config.ServerSchedulerHints.DedicatedHostId
return &serverSchedulerHints
}
func getCharging(config *Config) *ecsMdl.PrePaidServerExtendParam {
var charging ecsMdl.PrePaidServerExtendParam
var chargingMode ecsMdl.PrePaidServerExtendParamChargingMode
var isAutoPay ecsMdl.PrePaidServerExtendParamIsAutoPay
var isAutoRenew ecsMdl.PrePaidServerExtendParamIsAutoRenew
switch config.Charging.ChargingMode {
case "prePaid":
chargingMode = ecsMdl.GetPrePaidServerExtendParamChargingModeEnum().PRE_PAID
periodType := config.Charging.PeriodType
periodNum := config.Charging.PeriodNum
switch periodType {
case "month":
month := ecsMdl.GetPrePaidServerExtendParamPeriodTypeEnum().MONTH
charging.PeriodType = &month
case "year":
year := ecsMdl.GetPrePaidServerExtendParamPeriodTypeEnum().YEAR
charging.PeriodType = &year
}
charging.PeriodNum = &periodNum
switch config.Charging.IsAutoPay {
case true:
isAutoPay = ecsMdl.GetPrePaidServerExtendParamIsAutoPayEnum().TRUE
case false:
isAutoPay = ecsMdl.GetPrePaidServerExtendParamIsAutoPayEnum().FALSE
}
switch config.Charging.IsAutoRenew {
case true:
isAutoRenew = ecsMdl.GetPrePaidServerExtendParamIsAutoRenewEnum().TRUE
case false:
isAutoRenew = ecsMdl.GetPrePaidServerExtendParamIsAutoRenewEnum().FALSE
}
case "PostPaid":
chargingMode = ecsMdl.GetPrePaidServerExtendParamChargingModeEnum().POST_PAID
default:
chargingMode = ecsMdl.GetPrePaidServerExtendParamChargingModeEnum().POST_PAID
}
charging.ChargingMode = &chargingMode
charging.IsAutoPay = &isAutoPay
charging.IsAutoRenew = &isAutoRenew
charging.EnterpriseProjectId = config.Charging.EnterpriseProjectId
return &charging
}
func getRootVolumeProperties(minDisk int32, config *Config) *ecsMdl.PrePaidServerRootVolume {
rootVolume := ecsMdl.PrePaidServerRootVolume{}
switch config.RootVolume.VolumeType {
case "SSD":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().SSD
case "GPSSD":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().GPSSD
case "SATA":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().SATA
case "SAS":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().SAS
case "GPSSD2":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().GPSSD2
rootVolume.Iops = &config.RootVolume.Iops
rootVolume.Throughput = &config.RootVolume.Throughput
case "ESSD":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().ESSD
case "ESSD2":
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().ESSD2
rootVolume.Iops = &config.RootVolume.Iops
default:
rootVolume.Volumetype = ecsMdl.GetPrePaidServerRootVolumeVolumetypeEnum().GPSSD
}
if config.RootVolume.Size > minDisk {
rootVolume.Size = &config.RootVolume.Size
}
rootVolume.Extendparam = &ecsMdl.PrePaidServerRootVolumeExtendParam{SnapshotId: &config.RootVolume.SnapshotId}
return &rootVolume
}
func getDataVolumeProperties(minDisk int32, config *Config) *[]ecsMdl.PrePaidServerDataVolume {
dataVolumes := make([]ecsMdl.PrePaidServerDataVolume, 0)
if len(config.DataVolumes) < 0 {
dataVolumes = append(dataVolumes, ecsMdl.PrePaidServerDataVolume{Volumetype: ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().GPSSD, Size: 40})
return &dataVolumes
}
for _, volume := range config.DataVolumes {
dataVolume := ecsMdl.PrePaidServerDataVolume{}
switch volume.VolumeType {
case "SSD":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().SSD
case "GPSSD":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().GPSSD
case "SATA":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().SATA
case "SAS":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().SAS
case "GPSSD2":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().GPSSD2
dataVolume.Iops = &volume.Iops
dataVolume.Throughput = &volume.Throughput
case "ESSD":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().ESSD
case "ESSD2":
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().ESSD2
dataVolume.Iops = &volume.Iops
default:
dataVolume.Volumetype = ecsMdl.GetPrePaidServerDataVolumeVolumetypeEnum().GPSSD
}
if volume.Size > minDisk {
dataVolume.Size = volume.Size
} else {
dataVolume.Size = minDisk
}
dataVolume.Extendparam = &ecsMdl.PrePaidServerDataVolumeExtendParam{SnapshotId: &volume.SnapshotId}
dataVolume.DataImageId = &volume.DataImageId
if volume.ClusterId != "" {
dataVolume.ClusterId = &volume.ClusterId
clusterType := ecsMdl.GetPrePaidServerDataVolumeClusterTypeEnum().DSS
dataVolume.ClusterType = &clusterType
}
dataVolume.Multiattach = &volume.Multiattach
dataVolume.Hwpassthrough = &volume.Passthrough
dataVolumes = append(dataVolumes, dataVolume)
}
return &dataVolumes
}
func buildTagList(config *Config) *[]ecsMdl.PrePaidServerTag {
rawTagList := make([]ecsMdl.PrePaidServerTag, 0)
for _, tag := range config.Tags {
rawTagList = append(rawTagList, ecsMdl.PrePaidServerTag{Key: tag.Name, Value: tag.Value})
}
return removeDuplicatedTags(rawTagList)
}
func removeDuplicatedTags(tags []ecsMdl.PrePaidServerTag) *[]ecsMdl.PrePaidServerTag {
m := make(map[string]bool)
result := make([]ecsMdl.PrePaidServerTag, 0)
for _, entry := range tags {
if _, value := m[entry.Key]; !value {
m[entry.Key] = true
result = append(result, entry)
}
}
return &result
}
func waitForInstancesStatus(client Client, publicIP bool, instanceIds []string, instanceStatus string, timeout int) ([]*ecsMdl.ServerDetail, error) {
if timeout <= 0 {
timeout = InstanceDefaultTimeout
}
result, err := WaitForResult(fmt.Sprintf("Wait for the instances %v state to change to %s ", instanceIds, instanceStatus), func() (stop bool, result interface{}, err error) {
instances, err := describeInstances(client, instanceIds)
if err != nil {
return false, nil, err
}
if len(instances) <= 0 {
return true, nil, fmt.Errorf("the instances %v not found. ", instanceIds)
}
idsLen := len(instanceIds)
needInstances := make([]*ecsMdl.ServerDetail, 0)
for _, instance := range instances {
if instance.Status == instanceStatus {
needInstances = append(needInstances, &instance)
}
if publicIP {
wait := true
for _, addresses := range instance.Addresses {
for _, address := range addresses {
if *address.OSEXTIPStype == ecsMdl.GetServerAddressOSEXTIPStypeEnum().FLOATING {
wait = false
}
}
}
if wait {
return false, nil, fmt.Errorf("wait for public ip ")
}
}
}
if len(needInstances) == idsLen {
return true, needInstances, nil
}
return false, nil, fmt.Errorf("the instances %v state are not the expected state %s ", instanceIds, instanceStatus)
}, false, DefaultWaitForInterval, timeout)
if err != nil {
return nil, err
}
if result == nil {
return nil, nil
}
return result.([]*ecsMdl.ServerDetail), nil
}
func WaitForResult(name string, predicate func() (bool, interface{}, error), returnWhenError bool, delay int, timeout int) (interface{}, error) {
endTime := time.Now().Add(time.Duration(timeout) * time.Second)
delaySecond := time.Duration(delay) * time.Second
for {
satisfied, result, err := predicate()
if err != nil {
log.Print(fmt.Sprintf("%s Invoke func: %++s error: %++v", name, "predicate func() (bool, error)", err))
if returnWhenError {
return result, err
}
}
if satisfied {
return result, nil
}
time.Sleep(delaySecond)
if timeout >= 0 && time.Now().After(endTime) {
return nil, fmt.Errorf("wait for %s timeout", name)
}
}
}
func StopEcs(client Client, instanceIds []string) error {
request := ecsMdl.BatchStopServersRequest{Body: &ecsMdl.BatchStopServersRequestBody{OsStop: &ecsMdl.BatchStopServersOption{}}}
ids := make([]ecsMdl.ServerId, 0)
for _, instanceId := range instanceIds {
ids = append(ids, ecsMdl.ServerId{Id: instanceId})
}
request.Body.OsStop.Servers = ids
_, err := client.BatchStopServers(&request)
if err != nil {
return err
}
fmt.Println("stop ecs success")
return nil
}
func DeleteEcs(client Client, instanceIds []string) error {
request := ecsMdl.DeleteServersRequest{}
ids := make([]ecsMdl.ServerId, 0)
for _, instanceId := range instanceIds {
ids = append(ids, ecsMdl.ServerId{Id: instanceId})
}
deletePublicIp := true
deleteVolume := true
request.Body = &ecsMdl.DeleteServersRequestBody{
Servers: ids,
DeletePublicip: &deletePublicIp,
DeleteVolume: &deleteVolume,
}
_, err := client.DeleteServers(&request)
if err != nil {
return err
}
fmt.Println("stop ecs success")
return nil
}
func GetInstanceById(client Client, instanceId string) (*ecsMdl.ServerDetail, error) {
if instanceId == "" {
return nil, fmt.Errorf("instanceId not specified")
}
request := &ecsMdl.ShowServerRequest{}
request.ServerId = instanceId
response, err := client.ShowServer(request)
if err != nil {
return nil, err
}
return response.Server, nil
}
func GetExistingInstances(client Client, huaweiTag HuaweiTag) ([]ecsMdl.ServerDetail, error) {
request := ecsMdl.ListServersDetailsRequest{}
tag := fmt.Sprintf("%s,%s", huaweiTag.Name, huaweiTag.Value)
request.Tags = &tag
response, err := client.ListServersDetails(&request)
if err != nil {
return nil, err
}
return *response.Servers, nil
}
func describeInstances(client Client, instanceIds []string) ([]ecsMdl.ServerDetail, error) {
if len(instanceIds) < 1 {
return nil, fmt.Errorf("instance-ids not specified")
}
request := ecsMdl.ListServersDetailsRequest{}
serverIds := strings.Join(instanceIds, ",")
request.ServerId = &serverIds
response, err := client.ListServersDetails(&request)
if err != nil {
return nil, err
}
return *response.Servers, nil
}
func getPublicIpShareType(shareType string) ecsMdl.PrePaidServerEipBandwidthSharetype {
var shareTypeEnum ecsMdl.PrePaidServerEipBandwidthSharetype
switch shareType {
case "per":
shareTypeEnum = ecsMdl.GetPrePaidServerEipBandwidthSharetypeEnum().PER
case "whole":
shareTypeEnum = ecsMdl.GetPrePaidServerEipBandwidthSharetypeEnum().WHOLE
default:
shareTypeEnum = ecsMdl.GetPrePaidServerEipBandwidthSharetypeEnum().PER
}
return shareTypeEnum
}
func getIpType(ipType string) string {
if ipType == "" {
return "5_bgp"
}
return ipType
}