-
Notifications
You must be signed in to change notification settings - Fork 7
/
resource_hcs_compute_eip_associate.go
449 lines (387 loc) · 12.6 KB
/
resource_hcs_compute_eip_associate.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
package ecs
import (
"context"
"fmt"
"log"
"net"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/common"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/config"
golangsdk "github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/ecs/v1/cloudservers"
bandwidthsv1 "github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/networking/v1/bandwidths"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/networking/v1/eips"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/networking/v2/bandwidths"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/utils"
)
const publicIPv6Type string = "5_dualStack"
func ResourceComputeEIPAssociate() *schema.Resource {
return &schema.Resource{
CreateContext: resourceComputeEIPAssociateCreate,
ReadContext: resourceComputeEIPAssociateRead,
DeleteContext: resourceComputeEIPAssociateDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceComputeEIPAssociateImportState,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"public_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IsIPv4Address,
ExactlyOneOf: []string{"bandwidth_id"},
},
"bandwidth_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
RequiredWith: []string{"fixed_ip"},
},
"fixed_ip": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ValidateFunc: validation.IsIPAddress,
},
"port_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func eipAssociateRefreshFunc(client *golangsdk.ServiceClient, serverId, publicIP string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
resp, err := cloudservers.Get(client, serverId).Extract()
if err != nil {
return nil, "ERROR", err
}
for _, addresses := range resp.Addresses {
for _, address := range addresses {
if address.Type == "floating" && address.Addr == publicIP {
return resp, "COMPLETED", nil
}
}
}
return resp, "STARTING", nil
}
}
func resourceComputeEIPAssociateCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
ecsClient, err := cfg.ComputeV1Client(region)
if err != nil {
return diag.Errorf("error creating compute client: %s", err)
}
var publicID string
instanceID := d.Get("instance_id").(string)
fixedIP := d.Get("fixed_ip").(string)
if _, ok := d.GetOk("bandwidth_id"); ok {
// fixed_ip must be a valid IPv6 address when combining with bandwidth_id
if utils.IsIPv4Address(fixedIP) {
return diag.Errorf("the fixed_ip must be a valid IPv6 address, got: %s", fixedIP)
}
}
// get port id
portID, privateIP, err := getComputeInstancePortIDbyFixedIP(ecsClient, cfg, instanceID, fixedIP)
if err != nil {
return diag.Errorf("error getting port id of compute instance: %s", err)
}
if v, ok := d.GetOk("public_ip"); ok {
vpcClient, err := cfg.NetworkingV1Client(region)
if err != nil {
return diag.Errorf("error creating VPC client: %s", err)
}
// get EIP id
eipAddr := v.(string)
publicID = eipAddr
epsID := "all_granted_eps"
eipID, err := common.GetEipIDbyAddress(vpcClient, eipAddr, epsID)
if err != nil {
return diag.Errorf("error getting EIP: %s", err)
}
err = bindPortToEIP(vpcClient, eipID, portID)
if err != nil {
return diag.Errorf("error associating port %s to EIP: %s", portID, err)
}
} else {
bwClient, err := cfg.NetworkingV2Client(region)
if err != nil {
return diag.Errorf("error creating bandwidth v2.0 client: %s", err)
}
bwID := d.Get("bandwidth_id").(string)
publicID = bwID
err = insertPortToBandwidth(bwClient, bwID, portID)
if err != nil {
return diag.Errorf("error associating IPv6 port %s to bandwidth: %s", portID, err)
}
}
id := fmt.Sprintf("%s/%s/%s", publicID, instanceID, privateIP)
d.SetId(id)
stateConf := &resource.StateChangeConf{
Pending: []string{"STARTING"},
Target: []string{"COMPLETED"},
Refresh: eipAssociateRefreshFunc(ecsClient, instanceID, publicID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 5 * time.Second,
PollInterval: 10 * time.Second,
}
_, err = stateConf.WaitForStateContext(ctx)
if err != nil {
return diag.Errorf("error waiting for EIP association to complete: %s", err)
}
return resourceComputeEIPAssociateRead(ctx, d, meta)
}
func resourceComputeEIPAssociateRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
vpcClient, err := cfg.NetworkingV1Client(region)
if err != nil {
return diag.Errorf("error creating VPC client: %s", err)
}
ecsClient, err := cfg.ComputeV1Client(region)
if err != nil {
return diag.Errorf("error creating compute client: %s", err)
}
var associated bool
var publicID string
instanceID := d.Get("instance_id").(string)
fixedIP := d.Get("fixed_ip").(string)
// get port id of compute instance
portID, privateIP, err := getComputeInstancePortIDbyFixedIP(ecsClient, cfg, instanceID, fixedIP)
if err != nil {
return common.CheckDeletedDiag(d, err, "eip associate")
}
if v, ok := d.GetOk("public_ip"); ok {
eipAddr := v.(string)
publicID = eipAddr
epsID := "all_granted_eps"
eipInfo, err := getFloatingIPbyAddress(vpcClient, eipAddr, epsID)
if err != nil {
if eipInfo != nil {
log.Printf("[WARN] can not find the EIP by %s", eipAddr)
d.SetId("")
return nil
}
return diag.FromErr(err)
}
if eipInfo.PortID == portID {
associated = true
}
} else {
bwID := d.Get("bandwidth_id").(string)
publicID = bwID
band, err := bandwidthsv1.Get(vpcClient, bwID).Extract()
if err != nil {
return common.CheckDeletedDiag(d, err, "bandwidth")
}
for _, ipInfo := range band.PublicipInfo {
if ipInfo.PublicipId == portID {
associated = true
break
}
}
}
if !associated {
log.Printf("[WARN] the resource is not associated with the specified EIP or bandwidth")
d.SetId("")
}
id := fmt.Sprintf("%s/%s/%s", publicID, instanceID, privateIP)
d.SetId(id)
mErr := multierror.Append(nil,
d.Set("region", region),
d.Set("instance_id", instanceID),
d.Set("fixed_ip", privateIP),
d.Set("port_id", portID),
)
return diag.FromErr(mErr.ErrorOrNil())
}
func resourceComputeEIPAssociateDelete(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
region := cfg.GetRegion(d)
ecsClient, err := cfg.ComputeV1Client(region)
if err != nil {
return diag.Errorf("error creating compute client: %s", err)
}
instanceID := d.Get("instance_id").(string)
fixedIP := d.Get("fixed_ip").(string)
// get port id of compute instance
portID, _, err := getComputeInstancePortIDbyFixedIP(ecsClient, cfg, instanceID, fixedIP)
if err != nil {
return common.CheckDeletedDiag(d, err, "eip associate")
}
if v, ok := d.GetOk("public_ip"); ok {
vpcClient, err := cfg.NetworkingV1Client(region)
if err != nil {
return diag.Errorf("error creating VPC client: %s", err)
}
eipAddr := v.(string)
epsID := "all_granted_eps"
eipID, err := common.GetEipIDbyAddress(vpcClient, eipAddr, epsID)
if err != nil {
return diag.Errorf("error getting EIP: %s", err)
}
err = unbindPortFromEIP(vpcClient, eipID, portID)
if err != nil {
return diag.Errorf("error disassociating Floating IP: %s", err)
}
} else {
bwClient, err := cfg.NetworkingV2Client(region)
if err != nil {
return diag.Errorf("error creating bandwidth v2.0 client: %s", err)
}
bwID := d.Get("bandwidth_id").(string)
err = removePortFromBandwidth(bwClient, bwID, portID)
if err != nil {
return diag.Errorf("error associating IPv6 port %s to bandwidth: %s", portID, err)
}
}
return nil
}
func getComputeInstancePortIDbyFixedIP(client *golangsdk.ServiceClient, _ *config.HcsConfig, instanceId,
fixedIP string) (portId, privateIp string, err error) {
var instance *cloudservers.CloudServer
instance, err = cloudservers.Get(client, instanceId).Extract()
if err != nil {
return
} else if instance.Status == "DELETED" || instance.Status == "SOFT_DELETED" {
err = golangsdk.ErrDefault404{
ErrUnexpectedResponseCode: golangsdk.ErrUnexpectedResponseCode{
Body: []byte("the ECS instance has been deleted"),
},
}
return
}
for _, networkAddresses := range instance.Addresses {
for _, address := range networkAddresses {
if address.Type == "fixed" {
if fixedIP == "" || address.Addr == fixedIP {
portId = address.PortID
privateIp = address.Addr
return
}
}
}
}
err = fmt.Errorf("the port ID does not exist")
return
}
func getFloatingIPbyAddress(client *golangsdk.ServiceClient, floatingIP, epsID string) (*eips.PublicIp, error) {
listOpts := &eips.ListOpts{
PublicIp: []string{floatingIP},
EnterpriseProjectId: epsID,
}
pages, err := eips.List(client, listOpts).AllPages()
if err != nil {
return nil, err
}
allEips, err := eips.ExtractPublicIPs(pages)
if err != nil {
return nil, fmt.Errorf("unable to retrieve eips: %s ", err)
}
if len(allEips) != 1 {
return &eips.PublicIp{}, fmt.Errorf("can not find the EIP by %s", floatingIP)
}
return &allEips[0], nil
}
func insertPortToBandwidth(client *golangsdk.ServiceClient, bwID, portID string) error {
insertOpts := bandwidths.BandWidthInsertOpts{
PublicipInfo: []bandwidths.PublicIpInfoID{
{
PublicIPID: portID,
PublicIPType: publicIPv6Type,
},
},
}
log.Printf("[DEBUG] Insert port %s to bandwidth %s", portID, bwID)
_, err := bandwidths.Insert(client, bwID, insertOpts).Extract()
if err != nil {
return fmt.Errorf("error inserting %s into bandwidth %s: %s", portID, bwID, err)
}
return nil
}
func removePortFromBandwidth(client *golangsdk.ServiceClient, bwID, portID string) error {
removalSize := 5
removeOpts := bandwidths.BandWidthRemoveOpts{
Size: &removalSize,
PublicipInfo: []bandwidths.PublicIpInfoID{
{
PublicIPID: portID,
PublicIPType: publicIPv6Type,
},
},
}
log.Printf("[DEBUG] Remove port %s from bandwidth %s", portID, bwID)
err := bandwidths.Remove(client, bwID, removeOpts).ExtractErr()
if err != nil {
return fmt.Errorf("error removing %s from bandwidth: %s", portID, err)
}
return nil
}
func bindPortToEIP(client *golangsdk.ServiceClient, eipID, portID string) error {
log.Printf("[DEBUG] Bind port %s to EIP %s", portID, eipID)
return actionOnPort(client, eipID, portID)
}
func unbindPortFromEIP(client *golangsdk.ServiceClient, eipID, portID string) error {
log.Printf("[DEBUG] Unbind port %s from EIP: %s", portID, eipID)
return actionOnPort(client, eipID, "")
}
func actionOnPort(client *golangsdk.ServiceClient, eipID, portID string) error {
updateOpts := eips.UpdateOpts{
PortID: portID,
}
_, err := eips.Update(client, eipID, updateOpts).Extract()
if err != nil {
return err
}
return nil
}
func parseComputeFloatingIPAssociateID(id string) (publicID, instanceID, fixedIP string, err error) {
idParts := strings.Split(id, "/")
if len(idParts) != 3 && len(idParts) != 2 {
err = fmt.Errorf("unable to parse the resource ID, must be <eip address or bandwidth_id>/<instance_id>/<fixed_ip> format")
return
}
publicID = idParts[0]
instanceID = idParts[1]
if len(idParts) == 3 {
fixedIP = idParts[2]
}
return
}
func resourceComputeEIPAssociateImportState(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) {
publicID, instanceID, fixedIP, err := parseComputeFloatingIPAssociateID(d.Id())
if err != nil {
return nil, err
}
d.Set("instance_id", instanceID)
d.Set("fixed_ip", fixedIP)
parsedIP := net.ParseIP(publicID)
if parsedIP != nil {
d.Set("public_ip", publicID)
} else {
d.Set("bandwidth_id", publicID)
}
return []*schema.ResourceData{d}, nil
}