/
resource_hcs_elb_pool.go
357 lines (302 loc) · 9.76 KB
/
resource_hcs_elb_pool.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
package elb
import (
"context"
"fmt"
"log"
"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/sdk/huaweicloud"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/sdk/huaweicloud/openstack/elb/v3/pools"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/common"
"github.com/huaweicloud/terraform-provider-hcs/huaweicloudstack/config"
)
func ResourcePoolV3() *schema.Resource {
return &schema.Resource{
CreateContext: resourcePoolV3Create,
ReadContext: resourcePoolV3Read,
UpdateContext: resourcePoolV3Update,
DeleteContext: resourcePoolV3Delete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"protocol": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"TCP", "UDP", "HTTP", "HTTPS", "QUIC",
}, false),
},
// One of loadbalancer_id or listener_id must be provided
"loadbalancer_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
AtLeastOneOf: []string{"loadbalancer_id", "listener_id"},
},
// One of loadbalancer_id or listener_id must be provided
"listener_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
AtLeastOneOf: []string{"loadbalancer_id", "listener_id"},
},
"lb_method": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"ROUND_ROBIN", "LEAST_CONNECTIONS", "SOURCE_IP", "QUIC_CID",
}, false),
},
"persistence": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"SOURCE_IP", "HTTP_COOKIE", "APP_COOKIE",
}, false),
},
"cookie_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"timeout": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
Computed: true,
},
},
},
},
},
}
}
func resourcePoolV3Create(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
elbClient, err := cfg.ElbV3Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating ELB client: %s", err)
}
var persistence pools.SessionPersistence
if p, ok := d.GetOk("persistence"); ok {
persistence, err = buildPersistence(p)
if err != nil {
return diag.FromErr(err)
}
}
createOpts := pools.CreateOpts{
Name: d.Get("name").(string),
Description: d.Get("description").(string),
Protocol: d.Get("protocol").(string),
LoadbalancerID: d.Get("loadbalancer_id").(string),
ListenerID: d.Get("listener_id").(string),
LBMethod: d.Get("lb_method").(string),
}
// Must omit if not set
if persistence != (pools.SessionPersistence{}) {
createOpts.Persistence = &persistence
}
log.Printf("[DEBUG] Create Options: %#v", createOpts)
pool, err := pools.Create(elbClient, createOpts).Extract()
if err != nil {
return diag.Errorf("error creating pool: %s", err)
}
d.SetId(pool.ID)
timeout := d.Timeout(schema.TimeoutCreate)
err = waitForElbV3Pool(ctx, elbClient, d.Id(), "ACTIVE", nil, timeout)
if err != nil {
return diag.FromErr(err)
}
return resourcePoolV3Read(ctx, d, meta)
}
func resourcePoolV3Read(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
elbClient, err := cfg.ElbV3Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating ELB client: %s", err)
}
pool, err := pools.Get(elbClient, d.Id()).Extract()
if err != nil {
return common.CheckDeletedDiag(d, err, "pool")
}
log.Printf("[DEBUG] Retrieved pool %s: %#v", d.Id(), pool)
mErr := multierror.Append(nil,
d.Set("lb_method", pool.LBMethod),
d.Set("protocol", pool.Protocol),
d.Set("description", pool.Description),
d.Set("name", pool.Name),
d.Set("region", cfg.GetRegion(d)),
)
if len(pool.Loadbalancers) != 0 {
mErr = multierror.Append(mErr, d.Set("loadbalancer_id", pool.Loadbalancers[0].ID))
}
if len(pool.Listeners) != 0 {
mErr = multierror.Append(mErr, d.Set("listener_id", pool.Listeners[0].ID))
}
if len(pool.Loadbalancers) != 0 {
d.Set("loadbalancer_id", pool.Loadbalancers[0].ID)
}
if len(pool.Listeners) != 0 {
d.Set("listener_id", pool.Listeners[0].ID)
}
if pool.Persistence.Type != "" {
var persistence = make([]map[string]interface{}, 1)
params := make(map[string]interface{})
params["cookie_name"] = pool.Persistence.CookieName
params["type"] = pool.Persistence.Type
params["timeout"] = pool.Persistence.PersistenceTimeout
persistence[0] = params
mErr = multierror.Append(mErr, d.Set("persistence", persistence))
}
if err := mErr.ErrorOrNil(); err != nil {
return diag.Errorf("error setting Dedicated ELB pool fields: %s", err)
}
return nil
}
func resourcePoolV3Update(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
elbClient, err := cfg.ElbV3Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating ELB client: %s", err)
}
var updateOpts pools.UpdateOpts
if d.HasChange("lb_method") {
updateOpts.LBMethod = d.Get("lb_method").(string)
}
if d.HasChange("name") {
name := d.Get("name").(string)
updateOpts.Name = &name
}
if d.HasChange("description") {
description := d.Get("description").(string)
updateOpts.Description = &description
}
if d.HasChange("persistence") {
persistence, err := buildPersistence(d.Get("persistence"))
if err != nil {
return diag.FromErr(err)
}
updateOpts.Persistence = &persistence
}
log.Printf("[DEBUG] Updating pool %s with options: %#v", d.Id(), updateOpts)
_, err = pools.Update(elbClient, d.Id(), updateOpts).Extract()
if err != nil {
return diag.Errorf("unable to update pool %s: %s", d.Id(), err)
}
timeout := d.Timeout(schema.TimeoutUpdate)
err = waitForElbV3Pool(ctx, elbClient, d.Id(), "ACTIVE", nil, timeout)
if err != nil {
return diag.FromErr(err)
}
return resourcePoolV3Read(ctx, d, meta)
}
func resourcePoolV3Delete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := config.GetHcsConfig(meta)
elbClient, err := cfg.ElbV3Client(cfg.GetRegion(d))
if err != nil {
return diag.Errorf("error creating ELB client: %s", err)
}
log.Printf("[DEBUG] Attempting to delete pool %s", d.Id())
err = pools.Delete(elbClient, d.Id()).ExtractErr()
if err != nil {
return diag.Errorf("unable to delete pool %s: %s", d.Id(), err)
}
// Wait for Pool to delete
timeout := d.Timeout(schema.TimeoutDelete)
err = waitForElbV3Pool(ctx, elbClient, d.Id(), "DELETED", nil, timeout)
if err != nil {
return diag.FromErr(err)
}
return nil
}
func waitForElbV3Pool(ctx context.Context, elbClient *golangsdk.ServiceClient, id string, target string, pending []string,
timeout time.Duration) error {
log.Printf("[DEBUG] Waiting for pool %s to become %s.", id, target)
stateConf := &resource.StateChangeConf{
Target: []string{target},
Pending: pending,
Refresh: resourceElbV3PoolRefreshFunc(elbClient, id),
Timeout: timeout,
Delay: 5 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err := stateConf.WaitForStateContext(ctx)
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
switch target {
case "DELETED":
return nil
default:
return fmt.Errorf("error: pool %s not found: %s", id, err)
}
}
return fmt.Errorf("error waiting for pool %s to become %s: %s", id, target, err)
}
return nil
}
func resourceElbV3PoolRefreshFunc(elbClient *golangsdk.ServiceClient, poolID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pool, err := pools.Get(elbClient, poolID).Extract()
if err != nil {
return nil, "", err
}
// The pool resource has no Status attribute, so a successful Get is the best we can do
return pool, "ACTIVE", nil
}
}
func buildPersistence(p interface{}) (pools.SessionPersistence, error) {
pV := (p.([]interface{}))[0].(map[string]interface{})
persistence := pools.SessionPersistence{
Type: pV["type"].(string),
}
if persistence.Type == "APP_COOKIE" {
if pV["cookie_name"].(string) == "" {
return persistence, fmt.Errorf(
"persistence cookie_name needs to be set if using 'APP_COOKIE' persistence type")
}
persistence.CookieName = pV["cookie_name"].(string)
if pV["timeout"].(int) != 0 {
return persistence, fmt.Errorf(
"persistence timeout is invalid when type is set to 'APP_COOKIE'")
}
} else if pV["cookie_name"].(string) != "" {
return persistence, fmt.Errorf(
"persistence cookie_name can only be set if using 'APP_COOKIE' persistence type")
}
persistence.PersistenceTimeout = pV["timeout"].(int)
return persistence, nil
}