-
Notifications
You must be signed in to change notification settings - Fork 14
/
aliyun_publicip.go
381 lines (348 loc) · 14.8 KB
/
aliyun_publicip.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
/*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package aliyun
import (
"context"
ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v4/client"
"github.com/alibabacloud-go/tea/tea"
"github.com/chaosblade-io/chaosblade-exec-cloud/exec"
"github.com/chaosblade-io/chaosblade-exec-cloud/exec/category"
"github.com/chaosblade-io/chaosblade-spec-go/log"
"github.com/chaosblade-io/chaosblade-spec-go/spec"
"github.com/chaosblade-io/chaosblade-spec-go/util"
"os"
)
const PublicIpBin = "chaos_aliyun_publicip"
type PublicIpActionSpec struct {
spec.BaseExpActionCommandSpec
}
func NewPublicIpActionSpec() spec.ExpActionCommandSpec {
return &PublicIpActionSpec{
spec.BaseExpActionCommandSpec{
ActionFlags: []spec.ExpFlagSpec{
&spec.ExpFlag{
Name: "accessKeyId",
Desc: "the accessKeyId of aliyun, if not provided, get from env ACCESS_KEY_ID",
},
&spec.ExpFlag{
Name: "accessKeySecret",
Desc: "the accessKeySecret of aliyun, if not provided, get from env ACCESS_KEY_SECRET",
},
&spec.ExpFlag{
Name: "type",
Desc: "the operation of PublicIp, support release, unassociate, etc",
},
&spec.ExpFlag{
Name: "allocationId",
Desc: "the allocationId",
},
&spec.ExpFlag{
Name: "regionId",
Desc: "the regionId of aliyun",
},
&spec.ExpFlag{
Name: "publicIpAddress",
Desc: "the PublicIpAddress",
},
},
ActionExecutor: &PublicIpExecutor{},
ActionExample: `
# release publicIp which publicIpAddress is 1.1.1.1
blade create aliyun publicIp --accessKeyId xxx --accessKeySecret yyy --type release --publicIpAddress 1.1.1.1
# unassociate publicIp from instance i-x which allocationId id is a-x
blade create aliyun publicIp --accessKeyId xxx --accessKeySecret yyy --type unassociate --instanceId i-x --allocationId a-x`,
ActionPrograms: []string{PublicIpBin},
ActionCategories: []string{category.Cloud + "_" + category.Aliyun + "_" + category.PublicIp},
},
}
}
func (*PublicIpActionSpec) Name() string {
return "publicIp"
}
func (*PublicIpActionSpec) Aliases() []string {
return []string{}
}
func (*PublicIpActionSpec) ShortDesc() string {
return "do some aliyun publicIp Operations, like release, unassociate"
}
func (b *PublicIpActionSpec) LongDesc() string {
if b.ActionLongDesc != "" {
return b.ActionLongDesc
}
return "do some aliyun publicIp Operations, like release, unassociate"
}
type PublicIpExecutor struct {
channel spec.Channel
}
func (*PublicIpExecutor) Name() string {
return "publicIp"
}
func (be *PublicIpExecutor) Exec(uid string, ctx context.Context, model *spec.ExpModel) *spec.Response {
if be.channel == nil {
util.Errorf(uid, util.GetRunFuncName(), spec.ChannelNil.Msg)
return spec.ResponseFailWithFlags(spec.ChannelNil)
}
accessKeyId := model.ActionFlags["accessKeyId"]
accessKeySecret := model.ActionFlags["accessKeySecret"]
operationType := model.ActionFlags["type"]
regionId := model.ActionFlags["regionId"]
instanceId := model.ActionFlags["instanceId"]
allocationId := model.ActionFlags["allocationId"]
publicIpAddress := model.ActionFlags["publicIpAddress"]
if accessKeyId == "" {
val, ok := os.LookupEnv("ACCESS_KEY_ID")
if !ok {
log.Errorf(ctx, "could not get ACCESS_KEY_ID from env or parameter!")
return spec.ResponseFailWithFlags(spec.ParameterLess, "accessKeyId")
}
accessKeyId = val
}
if accessKeySecret == "" {
val, ok := os.LookupEnv("ACCESS_KEY_SECRET")
if !ok {
log.Errorf(ctx, "could not get ACCESS_KEY_SECRET from env or parameter!")
return spec.ResponseFailWithFlags(spec.ParameterLess, "accessKeySecret")
}
accessKeySecret = val
}
if regionId == "" {
log.Errorf(ctx, "regionId is required!")
return spec.ResponseFailWithFlags(spec.ParameterLess, "regionId")
}
if operationType == "release" && publicIpAddress == "" {
log.Errorf(ctx, "publicIpAddress is required when operationType is release!")
return spec.ResponseFailWithFlags(spec.ParameterLess, "publicIpAddress")
}
if operationType == "unassociate" && allocationId == "" {
log.Errorf(ctx, "allocationId is required when operationType is unassociate!")
return spec.ResponseFailWithFlags(spec.ParameterLess, "allocationId")
}
if operationType == "unassociate" && instanceId == "" {
log.Errorf(ctx, "instanceId is required when operationType is unassociate!")
return spec.ResponseFailWithFlags(spec.ParameterLess, "instanceId")
}
if operationType == "release" || operationType == "associate" {
ipStatusMap, _err := describeInstances(ctx, accessKeyId, accessKeySecret, regionId, instanceId)
if _err != nil {
return spec.ResponseFailWithFlags(spec.ParameterRequestFailed, "describe ip status failed")
}
isExist := false
for i := 0; i < len(ipStatusMap[instanceId]); i++ {
if ipStatusMap[instanceId][i] == publicIpAddress {
isExist = true
}
}
if (!isExist && operationType == "release") || (isExist && operationType == "associate") {
return be.stop(ctx, operationType, accessKeyId, accessKeySecret, regionId, allocationId, instanceId, publicIpAddress)
}
}
if operationType == "unassociateEip" || operationType == "associateEip" {
eipStatusMap, _err := describeEipAddresses(ctx, accessKeyId, accessKeySecret, regionId, allocationId, publicIpAddress)
if _err != nil {
return spec.ResponseFailWithFlags(spec.ParameterRequestFailed, "describe eip status failed")
}
if (eipStatusMap[publicIpAddress] != "InUse" && operationType == "unassociateEip") || (eipStatusMap[publicIpAddress] == "InUse" && operationType == "associateEip") {
return be.stop(ctx, operationType, accessKeyId, accessKeySecret, regionId, allocationId, instanceId, publicIpAddress)
}
}
return be.start(ctx, operationType, accessKeyId, accessKeySecret, regionId, allocationId, instanceId, publicIpAddress)
}
func (be *PublicIpExecutor) start(ctx context.Context, operationType, accessKeyId, accessKeySecret, regionId, allocationId, instanceId, publicIpAddress string) *spec.Response {
switch operationType {
case "release":
return releasePublicIpAddress(ctx, accessKeyId, accessKeySecret, regionId, publicIpAddress, instanceId)
case "associate":
return allocatePublicIpAddress(ctx, accessKeyId, accessKeySecret, regionId, publicIpAddress, instanceId)
case "unassociateEip":
return unassociateEipAddress(ctx, accessKeyId, accessKeySecret, regionId, allocationId, instanceId)
case "associateEip":
return associateEipAddress(ctx, accessKeyId, accessKeySecret, regionId, allocationId, instanceId)
default:
return spec.ResponseFailWithFlags(spec.ParameterInvalid, "type is not support(support release, associate, unassociateEip, associateEip)")
}
select {}
}
func (be *PublicIpExecutor) stop(ctx context.Context, operationType, accessKeyId, accessKeySecret, regionId, allocationId, instanceId, publicIpAddress string) *spec.Response {
switch operationType {
case "release":
return allocatePublicIpAddress(ctx, accessKeyId, accessKeySecret, regionId, publicIpAddress, instanceId)
case "associate":
return releasePublicIpAddress(ctx, accessKeyId, accessKeySecret, regionId, publicIpAddress, instanceId)
case "unassociateEip":
return associateEipAddress(ctx, accessKeyId, accessKeySecret, regionId, allocationId, instanceId)
case "associateEip":
return unassociateEipAddress(ctx, accessKeyId, accessKeySecret, regionId, allocationId, instanceId)
default:
return spec.ResponseFailWithFlags(spec.ParameterInvalid, "type is not support(support release, associate, unassociateEip, associateEip)")
}
ctx = context.WithValue(ctx, "bin", PublicIpBin)
return exec.Destroy(ctx, be.channel, "aliyun public Ip")
}
func (be *PublicIpExecutor) SetChannel(channel spec.Channel) {
be.channel = channel
}
// release Public Ip
func releasePublicIpAddress(ctx context.Context, accessKeyId, accessKeySecret, regionId, publicIpAddress, instanceId string) *spec.Response {
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret), regionId)
if _err != nil {
log.Errorf(ctx, "create aliyun client failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "create aliyun client failed")
}
if instanceId != "" {
releasePublicIpAddressRequest := &ecs20140526.ReleasePublicIpAddressRequest{
PublicIpAddress: tea.String(publicIpAddress),
InstanceId: tea.String(instanceId),
}
_, _err = client.ReleasePublicIpAddress(releasePublicIpAddressRequest)
} else {
releasePublicIpAddressRequest := &ecs20140526.ReleasePublicIpAddressRequest{
PublicIpAddress: tea.String(publicIpAddress),
}
_, _err = client.ReleasePublicIpAddress(releasePublicIpAddressRequest)
}
if _err != nil {
log.Errorf(ctx, "release aliyun public Ip failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "release aliyun public Ip failed")
}
return spec.Success()
}
// allocate Public Ip
func allocatePublicIpAddress(ctx context.Context, accessKeyId, accessKeySecret, regionId, publicIpAddress, instanceId string) *spec.Response {
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret), regionId)
if _err != nil {
log.Errorf(ctx, "create aliyun client failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "create aliyun client failed")
}
if instanceId != "" {
allocatePublicIpAddressRequest := &ecs20140526.AllocatePublicIpAddressRequest{
IpAddress: tea.String(publicIpAddress),
InstanceId: tea.String(instanceId),
}
_, _err = client.AllocatePublicIpAddress(allocatePublicIpAddressRequest)
}
if _err != nil {
log.Errorf(ctx, "allocate aliyun public Ip failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "allocate aliyun public Ip failed")
}
return spec.Success()
}
// unassociate Eip Address
func unassociateEipAddress(ctx context.Context, accessKeyId, accessKeySecret, regionId, allocationId, instanceId string) *spec.Response {
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret), regionId)
if _err != nil {
log.Errorf(ctx, "create aliyun client failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "create aliyun client failed")
}
if regionId != "" {
unassociateEipAddressRequest := &ecs20140526.UnassociateEipAddressRequest{
AllocationId: tea.String(allocationId),
InstanceId: tea.String(instanceId),
RegionId: tea.String(regionId),
}
_, _err = client.UnassociateEipAddress(unassociateEipAddressRequest)
} else {
unassociateEipAddressRequest := &ecs20140526.UnassociateEipAddressRequest{
AllocationId: tea.String(allocationId),
InstanceId: tea.String(instanceId),
}
_, _err = client.UnassociateEipAddress(unassociateEipAddressRequest)
}
if _err != nil {
log.Errorf(ctx, "unassociate aliyun Eip Address failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "unassociate aliyun Eip Address failed")
}
return spec.Success()
}
// associate Eip Address
func associateEipAddress(ctx context.Context, accessKeyId, accessKeySecret, regionId, allocationId, instanceId string) *spec.Response {
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret), regionId)
if _err != nil {
log.Errorf(ctx, "create aliyun client failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "create aliyun client failed")
}
if regionId != "" {
associateEipAddressRequest := &ecs20140526.AssociateEipAddressRequest{
AllocationId: tea.String(allocationId),
InstanceId: tea.String(instanceId),
RegionId: tea.String(regionId),
}
_, _err = client.AssociateEipAddress(associateEipAddressRequest)
} else {
associateEipAddressRequest := &ecs20140526.AssociateEipAddressRequest{
AllocationId: tea.String(allocationId),
InstanceId: tea.String(instanceId),
}
_, _err = client.AssociateEipAddress(associateEipAddressRequest)
}
if _err != nil {
log.Errorf(ctx, "associate aliyun Eip Address failed, err: %s", _err.Error())
return spec.ResponseFailWithFlags(spec.ContainerInContextNotFound, "associate aliyun Eip Address failed")
}
return spec.Success()
}
// describe eip addresses status
func describeEipAddresses(ctx context.Context, accessKeyId, accessKeySecret, regionId, allocationId, eipAddress string) (_result map[string]string, _err error) {
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret), regionId)
if _err != nil {
log.Errorf(ctx, "create aliyun client failed, err: %s", _err.Error())
return _result, _err
}
describeEipAddressesRequest := &ecs20140526.DescribeEipAddressesRequest{
AllocationId: tea.String(allocationId),
RegionId: tea.String(regionId),
EipAddress: tea.String(eipAddress),
}
response, _err := client.DescribeEipAddresses(describeEipAddressesRequest)
if _err != nil {
log.Errorf(ctx, "describe aliyun eip addresses status failed, err: %s", _err.Error())
return _result, _err
}
eipAddressStatusList := response.Body.EipAddresses.EipAddress
statusMap := map[string]string{}
for _, eipAddressStatus := range eipAddressStatusList {
statusMap[*eipAddressStatus.IpAddress] = *eipAddressStatus.Status
}
_result = statusMap
return _result, _err
}
// describe instances status
func describeInstances(ctx context.Context, accessKeyId, accessKeySecret, regionId, instanceId string) (_result map[string][]string, _err error) {
client, _err := CreateClient(tea.String(accessKeyId), tea.String(accessKeySecret), regionId)
if _err != nil {
log.Errorf(ctx, "create aliyun client failed, err: %s", _err.Error())
return _result, _err
}
describeInstancesRequest := &ecs20140526.DescribeInstancesRequest{
InstanceIds: tea.String("[\"" + instanceId + "\"]"),
RegionId: tea.String(regionId),
}
response, _err := client.DescribeInstances(describeInstancesRequest)
if _err != nil {
log.Errorf(ctx, "describe aliyun instances status failed, err: %s", _err.Error())
return _result, _err
}
instanceList := response.Body.Instances.Instance
statusMap := map[string][]string{}
for _, instanceStatus := range instanceList {
var ipList []string
for i := 0; i < len(instanceStatus.PublicIpAddress.IpAddress); i++ {
ipList = append(ipList, *instanceStatus.PublicIpAddress.IpAddress[i])
}
statusMap[*instanceStatus.InstanceId] = ipList
}
_result = statusMap
return _result, _err
}