-
Notifications
You must be signed in to change notification settings - Fork 7
/
resource_huaweicloud_as_bandwidth_policy.go
460 lines (414 loc) · 16 KB
/
resource_huaweicloud_as_bandwidth_policy.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
// ---------------------------------------------------------------
// *** AUTO GENERATED CODE ***
// @Product AS
// ---------------------------------------------------------------
package as
import (
"context"
"log"
"strings"
"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/utils"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/jmespath/go-jmespath"
)
func ResourceASBandWidthPolicy() *schema.Resource {
return &schema.Resource{
CreateContext: resourceASBandWidthPolicyCreate,
UpdateContext: resourceASBandWidthPolicyUpdate,
ReadContext: resourceASBandWidthPolicyRead,
DeleteContext: resourceASPolicyDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"scaling_policy_name": {
Type: schema.TypeString,
Required: true,
Description: `Specifies the AS policy name.`,
ValidateFunc: validation.StringLenBetween(1, 64),
},
"scaling_policy_type": {
Type: schema.TypeString,
Required: true,
Description: `Specifies the AS policy type.`,
ValidateFunc: validation.StringInSlice([]string{
"ALARM", "SCHEDULED", "RECURRENCE",
}, false),
},
"bandwidth_id": {
Type: schema.TypeString,
Required: true,
Description: `Specifies the scaling bandwidth ID.`,
},
"alarm_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the alarm rule ID.`,
ExactlyOneOf: []string{
"scheduled_policy",
},
},
"cool_down_time": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: `Specifies the cooldown period (in seconds).`,
ValidateFunc: validation.IntAtMost(86400),
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the description of the AS policy.`,
},
"scaling_policy_action": {
Type: schema.TypeList,
MaxItems: 1,
Elem: ASBandWidthPolicyActionSchema(),
Optional: true,
Computed: true,
},
"scheduled_policy": {
Type: schema.TypeList,
MaxItems: 1,
Elem: ASBandWidthScheduledPolicySchema(),
Optional: true,
Computed: true,
ExactlyOneOf: []string{
"alarm_id",
},
},
"scaling_resource_type": {
Type: schema.TypeString,
Computed: true,
Description: `the scaling resource type.`,
},
"status": {
Type: schema.TypeString,
Computed: true,
Description: `the AS policy status.`,
},
},
}
}
func ASBandWidthPolicyActionSchema() *schema.Resource {
sc := schema.Resource{
Schema: map[string]*schema.Schema{
"operation": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the operation to be performed. The default operation is ADD.`,
ValidateFunc: validation.StringInSlice([]string{
"ADD", "REDUCE", "SET",
}, false),
},
"size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: `Specifies the bandwidth (Mbit/s).`,
},
"limits": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: `Specifies the operation restrictions.`,
},
},
}
return &sc
}
func ASBandWidthScheduledPolicySchema() *schema.Resource {
sc := schema.Resource{
Schema: map[string]*schema.Schema{
"launch_time": {
Type: schema.TypeString,
Required: true,
Description: `Specifies the time when the scaling action is triggered. The time format complies with UTC.`,
},
"recurrence_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the periodic triggering type.`,
ValidateFunc: validation.StringInSlice([]string{
"Daily", "Weekly", "Monthly",
}, false),
},
"recurrence_value": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the day when a periodic scaling action is triggered.`,
},
"start_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the start time of the scaling action triggered periodically.`,
},
"end_time": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the end time of the scaling action triggered periodically.`,
},
},
}
return &sc
}
func resourceASBandWidthPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := config.GetHcsConfig(meta)
region := config.GetRegion(d)
// createBandwidthPolicy: create an AS bandwidth scaling policy
var (
createBandwidthPolicyHttpUrl = "autoscaling-api/v2/{project_id}/scaling_policy"
createBandwidthPolicyProduct = "autoscaling"
)
createBandwidthPolicyClient, err := config.NewServiceClient(createBandwidthPolicyProduct, region)
if err != nil {
return diag.Errorf("error creating ASBandWidthPolicy Client: %s", err)
}
createBandwidthPolicyPath := createBandwidthPolicyClient.Endpoint + createBandwidthPolicyHttpUrl
createBandwidthPolicyPath = strings.ReplaceAll(createBandwidthPolicyPath, "{project_id}", createBandwidthPolicyClient.ProjectID)
createBandwidthPolicyOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
}
createBandwidthPolicyOpt.JSONBody = utils.RemoveNil(buildCreateBandwidthPolicyBodyParams(d, config))
createBandwidthPolicyResp, err := createBandwidthPolicyClient.Request("POST", createBandwidthPolicyPath, &createBandwidthPolicyOpt)
if err != nil {
return diag.Errorf("error creating ASBandWidthPolicy: %s", err)
}
createBandwidthPolicyRespBody, err := utils.FlattenResponse(createBandwidthPolicyResp)
if err != nil {
return diag.FromErr(err)
}
id, err := jmespath.Search("scaling_policy_id", createBandwidthPolicyRespBody)
if err != nil {
return diag.Errorf("error creating ASBandWidthPolicy: ID is not found in API response")
}
d.SetId(id.(string))
return resourceASBandWidthPolicyRead(ctx, d, meta)
}
func buildCreateBandwidthPolicyBodyParams(d *schema.ResourceData, config *config.HcsConfig) map[string]interface{} {
bodyParams := map[string]interface{}{
"scaling_policy_name": utils.ValueIngoreEmpty(d.Get("scaling_policy_name")),
"scaling_policy_type": utils.ValueIngoreEmpty(d.Get("scaling_policy_type")),
"scaling_resource_id": utils.ValueIngoreEmpty(d.Get("bandwidth_id")),
"scaling_resource_type": "BANDWIDTH",
"alarm_id": utils.ValueIngoreEmpty(d.Get("alarm_id")),
"cool_down_time": utils.ValueIngoreEmpty(d.Get("cool_down_time")),
"description": utils.ValueIngoreEmpty(d.Get("description")),
"scaling_policy_action": buildCreateBandwidthPolicyScalingPolicyActionChildBody(d),
"scheduled_policy": buildCreateBandwidthPolicyScheduledPolicyChildBody(d),
}
return bodyParams
}
func buildCreateBandwidthPolicyScalingPolicyActionChildBody(d *schema.ResourceData) map[string]interface{} {
rawParams := d.Get("scaling_policy_action").([]interface{})
if len(rawParams) == 0 {
return nil
}
raw := rawParams[0].(map[string]interface{})
params := map[string]interface{}{
"operation": utils.ValueIngoreEmpty(raw["operation"]),
"size": utils.ValueIngoreEmpty(raw["size"]),
"limits": utils.ValueIngoreEmpty(raw["limits"]),
}
return params
}
func buildCreateBandwidthPolicyScheduledPolicyChildBody(d *schema.ResourceData) map[string]interface{} {
rawParams := d.Get("scheduled_policy").([]interface{})
if len(rawParams) == 0 {
return nil
}
raw := rawParams[0].(map[string]interface{})
params := map[string]interface{}{
"launch_time": utils.ValueIngoreEmpty(raw["launch_time"]),
"recurrence_type": utils.ValueIngoreEmpty(raw["recurrence_type"]),
"recurrence_value": utils.ValueIngoreEmpty(raw["recurrence_value"]),
"start_time": utils.ValueIngoreEmpty(raw["start_time"]),
"end_time": utils.ValueIngoreEmpty(raw["end_time"]),
}
return params
}
func resourceASBandWidthPolicyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := config.GetHcsConfig(meta)
region := config.GetRegion(d)
var mErr *multierror.Error
// getBandwidthPolicy: Query the AS bandwidth scaling policy
var (
getBandwidthPolicyHttpUrl = "autoscaling-api/v2/{project_id}/scaling_policy/{id}"
getBandwidthPolicyProduct = "autoscaling"
)
getBandwidthPolicyClient, err := config.NewServiceClient(getBandwidthPolicyProduct, region)
if err != nil {
return diag.Errorf("error creating ASBandWidthPolicy Client: %s", err)
}
getBandwidthPolicyPath := getBandwidthPolicyClient.Endpoint + getBandwidthPolicyHttpUrl
getBandwidthPolicyPath = strings.ReplaceAll(getBandwidthPolicyPath, "{project_id}", getBandwidthPolicyClient.ProjectID)
getBandwidthPolicyPath = strings.ReplaceAll(getBandwidthPolicyPath, "{id}", d.Id())
getBandwidthPolicyOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
}
getBandwidthPolicyResp, err := getBandwidthPolicyClient.Request("GET", getBandwidthPolicyPath, &getBandwidthPolicyOpt)
if err != nil {
return common.CheckDeletedDiag(d, err, "error retrieving ASBandWidthPolicy")
}
getBandwidthPolicyRespBody, err := utils.FlattenResponse(getBandwidthPolicyResp)
if err != nil {
return diag.FromErr(err)
}
mErr = multierror.Append(
mErr,
d.Set("region", region),
d.Set("scaling_policy_name", utils.PathSearch("scaling_policy.scaling_policy_name", getBandwidthPolicyRespBody, nil)),
d.Set("scaling_policy_type", utils.PathSearch("scaling_policy.scaling_policy_type", getBandwidthPolicyRespBody, nil)),
d.Set("bandwidth_id", utils.PathSearch("scaling_policy.scaling_resource_id", getBandwidthPolicyRespBody, nil)),
d.Set("scaling_resource_type", utils.PathSearch("scaling_policy.scaling_resource_type", getBandwidthPolicyRespBody, nil)),
d.Set("alarm_id", utils.PathSearch("scaling_policy.alarm_id", getBandwidthPolicyRespBody, nil)),
d.Set("cool_down_time", utils.PathSearch("scaling_policy.cool_down_time", getBandwidthPolicyRespBody, nil)),
d.Set("description", utils.PathSearch("scaling_policy.description", getBandwidthPolicyRespBody, nil)),
d.Set("status", utils.PathSearch("scaling_policy.policy_status", getBandwidthPolicyRespBody, nil)),
d.Set("scaling_policy_action", flattenGetBandwidthPolicyResponseBodyScalingPolicyAction(getBandwidthPolicyRespBody)),
d.Set("scheduled_policy", flattenGetBandwidthPolicyResponseBodyScheduledPolicy(getBandwidthPolicyRespBody)),
)
return diag.FromErr(mErr.ErrorOrNil())
}
func flattenGetBandwidthPolicyResponseBodyScalingPolicyAction(resp interface{}) []interface{} {
var rst []interface{}
curJson, err := jmespath.Search("scaling_policy.scaling_policy_action", resp)
if err != nil {
log.Printf("[ERROR] error parsing scaling_policy_action from response= %#v", resp)
return rst
}
rst = []interface{}{
map[string]interface{}{
"operation": utils.PathSearch("operation", curJson, nil),
"size": utils.PathSearch("size", curJson, nil),
"limits": utils.PathSearch("limits", curJson, nil),
},
}
return rst
}
func flattenGetBandwidthPolicyResponseBodyScheduledPolicy(resp interface{}) []interface{} {
var rst []interface{}
curJson, err := jmespath.Search("scaling_policy.scheduled_policy", resp)
if err != nil {
log.Printf("[ERROR] error parsing scheduled_policy from response= %#v", resp)
return rst
}
rst = []interface{}{
map[string]interface{}{
"launch_time": utils.PathSearch("launch_time", curJson, nil),
"recurrence_type": utils.PathSearch("recurrence_type", curJson, nil),
"recurrence_value": utils.PathSearch("recurrence_value", curJson, nil),
"start_time": utils.PathSearch("start_time", curJson, nil),
"end_time": utils.PathSearch("end_time", curJson, nil),
},
}
return rst
}
func resourceASBandWidthPolicyUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
config := config.GetHcsConfig(meta)
region := config.GetRegion(d)
updateBandwidthPolicyhasChanges := []string{
"scaling_policy_name",
"scaling_policy_type",
"bandwidth_id",
"scaling_resource_type",
"alarm_id",
"cool_down_time",
"description",
"scaling_policy_action",
"scheduled_policy",
}
if d.HasChanges(updateBandwidthPolicyhasChanges...) {
// updateBandwidthPolicy: update the AS bandwidth scaling policy
var (
updateBandwidthPolicyHttpUrl = "autoscaling-api/v2/{project_id}/scaling_policy/{id}"
updateBandwidthPolicyProduct = "autoscaling"
)
updateBandwidthPolicyClient, err := config.NewServiceClient(updateBandwidthPolicyProduct, region)
if err != nil {
return diag.Errorf("error creating ASBandWidthPolicy Client: %s", err)
}
updateBandwidthPolicyPath := updateBandwidthPolicyClient.Endpoint + updateBandwidthPolicyHttpUrl
updateBandwidthPolicyPath = strings.ReplaceAll(updateBandwidthPolicyPath, "{project_id}", updateBandwidthPolicyClient.ProjectID)
updateBandwidthPolicyPath = strings.ReplaceAll(updateBandwidthPolicyPath, "{id}", d.Id())
updateBandwidthPolicyOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
200,
},
}
updateBandwidthPolicyOpt.JSONBody = utils.RemoveNil(buildUpdateBandwidthPolicyBodyParams(d, config))
_, err = updateBandwidthPolicyClient.Request("PUT", updateBandwidthPolicyPath, &updateBandwidthPolicyOpt)
if err != nil {
return diag.Errorf("error updating ASBandWidthPolicy: %s", err)
}
}
return resourceASBandWidthPolicyRead(ctx, d, meta)
}
func buildUpdateBandwidthPolicyBodyParams(d *schema.ResourceData, config *config.HcsConfig) map[string]interface{} {
bodyParams := map[string]interface{}{
"scaling_policy_name": utils.ValueIngoreEmpty(d.Get("scaling_policy_name")),
"scaling_policy_type": utils.ValueIngoreEmpty(d.Get("scaling_policy_type")),
"scaling_resource_id": utils.ValueIngoreEmpty(d.Get("bandwidth_id")),
"scaling_resource_type": utils.ValueIngoreEmpty(d.Get("scaling_resource_type")),
"alarm_id": utils.ValueIngoreEmpty(d.Get("alarm_id")),
"cool_down_time": utils.ValueIngoreEmpty(d.Get("cool_down_time")),
"description": utils.ValueIngoreEmpty(d.Get("description")),
"scaling_policy_action": buildUpdateBandwidthPolicyScalingPolicyActionChildBody(d),
"scheduled_policy": buildUpdateBandwidthPolicyScheduledPolicyChildBody(d),
}
return bodyParams
}
func buildUpdateBandwidthPolicyScalingPolicyActionChildBody(d *schema.ResourceData) map[string]interface{} {
rawParams := d.Get("scaling_policy_action").([]interface{})
if len(rawParams) == 0 {
return nil
}
raw := rawParams[0].(map[string]interface{})
params := map[string]interface{}{
"operation": utils.ValueIngoreEmpty(raw["operation"]),
"size": utils.ValueIngoreEmpty(raw["size"]),
"limits": utils.ValueIngoreEmpty(raw["limits"]),
}
return params
}
func buildUpdateBandwidthPolicyScheduledPolicyChildBody(d *schema.ResourceData) map[string]interface{} {
rawParams := d.Get("scheduled_policy").([]interface{})
if len(rawParams) == 0 {
return nil
}
raw := rawParams[0].(map[string]interface{})
params := map[string]interface{}{
"launch_time": utils.ValueIngoreEmpty(raw["launch_time"]),
"recurrence_type": utils.ValueIngoreEmpty(raw["recurrence_type"]),
"recurrence_value": utils.ValueIngoreEmpty(raw["recurrence_value"]),
"start_time": utils.ValueIngoreEmpty(raw["start_time"]),
"end_time": utils.ValueIngoreEmpty(raw["end_time"]),
}
return params
}