-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathresource_cloudstack_autoscale_vm_profile.go
More file actions
519 lines (427 loc) · 14.5 KB
/
Copy pathresource_cloudstack_autoscale_vm_profile.go
File metadata and controls
519 lines (427 loc) · 14.5 KB
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 cloudstack
import (
"fmt"
"log"
"strings"
"time"
"github.com/apache/cloudstack-go/v2/cloudstack"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceCloudStackAutoScaleVMProfile() *schema.Resource {
return &schema.Resource{
Create: resourceCloudStackAutoScaleVMProfileCreate,
Read: resourceCloudStackAutoScaleVMProfileRead,
Update: resourceCloudStackAutoScaleVMProfileUpdate,
Delete: resourceCloudStackAutoScaleVMProfileDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"service_offering": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "the service offering of the auto deployed virtual machine",
},
"template": {
Type: schema.TypeString,
Required: true,
Description: "the template of the auto deployed virtual machine",
},
"zone": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "availability zone for the auto deployed virtual machine",
},
"destroy_vm_grace_period": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "the time allowed for existing connections to get closed before a vm is expunged",
},
"other_deploy_params": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
ForceNew: true,
Description: "parameters other than zoneId/serviceOfferringId/templateId of the auto deployed virtual machine",
},
"counter_param_list": {
Type: schema.TypeMap,
Optional: true,
Description: "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161",
},
"user_data": {
Type: schema.TypeString,
Optional: true,
Description: "an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request.",
},
"user_data_id": {
Type: schema.TypeString,
Optional: true,
Description: "the ID of the Userdata",
},
"user_data_details": {
Type: schema.TypeMap,
Optional: true,
Description: "used to specify the parameters values for the variables in userdata",
},
"autoscale_user_id": {
Type: schema.TypeString,
Optional: true,
Description: "the ID of the user used to launch and destroy the VMs",
},
"display": {
Type: schema.TypeBool,
Optional: true,
Description: "an optional field, whether to the display the profile to the end user or not",
},
"account_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "account that will own the autoscale VM profile",
},
"project_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "an optional project for the autoscale VM profile",
},
"domain_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "domain ID of the account owning a autoscale VM profile",
},
"metadata": metadataSchema(),
},
}
}
func resourceCloudStackAutoScaleVMProfileCreate(d *schema.ResourceData, meta interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
serviceofferingid, e := retrieveID(cs, "service_offering", d.Get("service_offering").(string))
if e != nil {
return e.Error()
}
zoneid, e := retrieveID(cs, "zone", d.Get("zone").(string))
if e != nil {
return e.Error()
}
templateid, e := retrieveTemplateID(cs, zoneid, d.Get("template").(string))
if e != nil {
return e.Error()
}
p := cs.AutoScale.NewCreateAutoScaleVmProfileParams(serviceofferingid, templateid, zoneid)
if v, ok := d.GetOk("destroy_vm_grace_period"); ok {
duration, err := time.ParseDuration(v.(string))
if err != nil {
return err
}
p.SetExpungevmgraceperiod(int(duration.Seconds()))
}
if v, ok := d.GetOk("other_deploy_params"); ok {
nv := make(map[string]string)
for k, v := range v.(map[string]interface{}) {
nv[k] = v.(string)
}
p.SetOtherdeployparams(nv)
}
if v, ok := d.GetOk("counter_param_list"); ok {
nv := make(map[string]string)
for k, v := range v.(map[string]interface{}) {
nv[k] = v.(string)
}
p.SetCounterparam(nv)
}
if v, ok := d.GetOk("user_data"); ok {
p.SetUserdata(v.(string))
}
if v, ok := d.GetOk("user_data_id"); ok {
p.SetUserdataid(v.(string))
}
if v, ok := d.GetOk("user_data_details"); ok {
nv := make(map[string]string)
for k, v := range v.(map[string]interface{}) {
nv[k] = v.(string)
}
p.SetUserdatadetails(nv)
}
if v, ok := d.GetOk("autoscale_user_id"); ok {
p.SetAutoscaleuserid(v.(string))
}
if v, ok := d.GetOk("display"); ok {
p.SetFordisplay(v.(bool))
}
if v, ok := d.GetOk("account_name"); ok {
p.SetAccount(v.(string))
}
if v, ok := d.GetOk("project_id"); ok {
p.SetProjectid(v.(string))
}
if v, ok := d.GetOk("domain_id"); ok {
p.SetDomainid(v.(string))
}
r, err := cs.AutoScale.CreateAutoScaleVmProfile(p)
if err != nil {
return fmt.Errorf("Error creating AutoScaleVmProfile %s: %s", d.Id(), err)
}
d.SetId(r.Id)
if err = setMetadata(cs, d, "AutoScaleVmProfile"); err != nil {
return fmt.Errorf("Error setting metadata on the AutoScaleVmProfile %s: %s", d.Id(), err)
}
return resourceCloudStackAutoScaleVMProfileRead(d, meta)
}
func resourceCloudStackAutoScaleVMProfileRead(d *schema.ResourceData, meta interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
p, count, err := cs.AutoScale.GetAutoScaleVmProfileByID(d.Id())
if err != nil {
if count == 0 {
log.Printf(
"[DEBUG] AutoScaleVmProfile %s no longer exists", d.Id())
d.SetId("")
return nil
}
return err
}
zone, _, err := cs.Zone.GetZoneByID(p.Zoneid)
if err != nil {
return err
}
offering, _, err := cs.ServiceOffering.GetServiceOfferingByID(p.Serviceofferingid)
if err != nil {
return err
}
template, _, err := cs.Template.GetTemplateByID(p.Templateid, "executable", cloudstack.WithZone(p.Zoneid))
if err != nil {
return err
}
setValueOrID(d, "service_offering", offering.Name, p.Serviceofferingid)
setValueOrID(d, "template", template.Name, p.Templateid)
setValueOrID(d, "zone", zone.Name, p.Zoneid)
d.Set("destroy_vm_grace_period", (time.Duration(p.Expungevmgraceperiod) * time.Second).String())
if p.Otherdeployparams != nil {
d.Set("other_deploy_params", p.Otherdeployparams)
}
if p.Userdata != "" {
d.Set("user_data", p.Userdata)
}
if p.Userdataid != "" {
d.Set("user_data_id", p.Userdataid)
}
if p.Userdatadetails != "" {
if _, ok := d.GetOk("user_data_details"); !ok {
d.Set("user_data_details", map[string]interface{}{})
}
}
if p.Autoscaleuserid != "" {
d.Set("autoscale_user_id", p.Autoscaleuserid)
}
d.Set("display", p.Fordisplay)
if p.Account != "" {
d.Set("account_name", p.Account)
}
if p.Projectid != "" {
d.Set("project_id", p.Projectid)
}
if p.Domainid != "" {
d.Set("domain_id", p.Domainid)
}
metadata, err := getMetadata(cs, d, "AutoScaleVmProfile")
if err != nil {
return err
}
d.Set("metadata", metadata)
return nil
}
// waitForVMGroupsState waits for the specified VM groups to reach the desired state
func waitForVMGroupsState(cs *cloudstack.CloudStackClient, groupIDs []string, desiredState string) error {
maxRetries := 30 // 30 * 2 seconds = 60 seconds max wait
for i := 0; i < maxRetries; i++ {
allInDesiredState := true
for _, groupID := range groupIDs {
group, _, err := cs.AutoScale.GetAutoScaleVmGroupByID(groupID)
if err != nil {
return fmt.Errorf("Error checking state of VM group %s: %s", groupID, err)
}
groupInDesiredState := false
if desiredState == "disabled" {
groupInDesiredState = (group.State == "disabled")
} else if desiredState == "enabled" {
groupInDesiredState = (group.State == "enabled")
} else {
groupInDesiredState = (group.State == desiredState)
}
if !groupInDesiredState {
allInDesiredState = false
log.Printf("[DEBUG] VM group %s is in state '%s', waiting for '%s'", groupID, group.State, desiredState)
break
}
}
if allInDesiredState {
log.Printf("[INFO] All VM groups have reached desired state: %s", desiredState)
return nil
}
if i < maxRetries-1 {
log.Printf("[INFO] Waiting for VM groups to reach state '%s' (attempt %d/%d)", desiredState, i+1, maxRetries)
time.Sleep(2 * time.Second)
}
}
return fmt.Errorf("Timeout waiting for VM groups to reach state '%s' after %d seconds", desiredState, maxRetries*2)
}
func waitForVMGroupsToBeDisabled(cs *cloudstack.CloudStackClient, profileID string) error {
log.Printf("[DEBUG] Waiting for VM groups using profile %s to be disabled", profileID)
listParams := cs.AutoScale.NewListAutoScaleVmGroupsParams()
listParams.SetVmprofileid(profileID)
groups, err := cs.AutoScale.ListAutoScaleVmGroups(listParams)
if err != nil {
log.Printf("[ERROR] Failed to list VM groups for profile %s: %s", profileID, err)
return fmt.Errorf("Error listing autoscale VM groups: %s", err)
}
log.Printf("[DEBUG] Found %d VM groups using profile %s", len(groups.AutoScaleVmGroups), profileID)
var groupIDs []string
for _, group := range groups.AutoScaleVmGroups {
log.Printf("[DEBUG] VM group %s (%s) current state: %s", group.Name, group.Id, group.State)
groupIDs = append(groupIDs, group.Id)
}
if len(groupIDs) == 0 {
log.Printf("[DEBUG] No VM groups found using profile %s", profileID)
return nil
}
log.Printf("[INFO] Waiting for %d VM groups to be disabled for profile update", len(groupIDs))
if err := waitForVMGroupsState(cs, groupIDs, "disabled"); err != nil {
return fmt.Errorf("Autoscale VM groups must be disabled before updating profile: %s", err)
}
log.Printf("[DEBUG] All VM groups are now disabled for profile %s", profileID)
return nil
}
func resourceCloudStackAutoScaleVMProfileUpdate(d *schema.ResourceData, meta interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
log.Printf("[DEBUG] Profile update requested for ID: %s", d.Id())
for _, key := range []string{"template", "destroy_vm_grace_period", "counter_param_list", "user_data", "user_data_id", "user_data_details", "autoscale_user_id", "display", "metadata"} {
if d.HasChange(key) {
old, new := d.GetChange(key)
log.Printf("[DEBUG] Field '%s' changed from %v to %v", key, old, new)
}
}
// Check if we only have metadata changes (which don't require CloudStack API update)
onlyMetadataChanges := d.HasChange("metadata") &&
!d.HasChange("template") &&
!d.HasChange("destroy_vm_grace_period") &&
!d.HasChange("counter_param_list") &&
!d.HasChange("user_data") &&
!d.HasChange("user_data_id") &&
!d.HasChange("user_data_details") &&
!d.HasChange("autoscale_user_id") &&
!d.HasChange("display")
if !onlyMetadataChanges {
if err := waitForVMGroupsToBeDisabled(cs, d.Id()); err != nil {
return fmt.Errorf("Autoscale VM groups must be disabled before updating profile: %s", err)
}
p := cs.AutoScale.NewUpdateAutoScaleVmProfileParams(d.Id())
if d.HasChange("template") {
zoneid, e := retrieveID(cs, "zone", d.Get("zone").(string))
if e != nil {
return e.Error()
}
templateid, e := retrieveTemplateID(cs, zoneid, d.Get("template").(string))
if e != nil {
return e.Error()
}
p.SetTemplateid(templateid)
}
if d.HasChange("destroy_vm_grace_period") {
if v, ok := d.GetOk("destroy_vm_grace_period"); ok {
duration, err := time.ParseDuration(v.(string))
if err != nil {
return err
}
p.SetExpungevmgraceperiod(int(duration.Seconds()))
}
}
if d.HasChange("counter_param_list") {
if v, ok := d.GetOk("counter_param_list"); ok {
nv := make(map[string]string)
for k, v := range v.(map[string]interface{}) {
nv[k] = v.(string)
}
p.SetCounterparam(nv)
}
}
if d.HasChange("user_data") {
if v, ok := d.GetOk("user_data"); ok {
p.SetUserdata(v.(string))
}
}
if d.HasChange("user_data_id") {
if v, ok := d.GetOk("user_data_id"); ok {
p.SetUserdataid(v.(string))
}
}
if d.HasChange("user_data_details") {
if v, ok := d.GetOk("user_data_details"); ok {
nv := make(map[string]string)
for k, v := range v.(map[string]interface{}) {
nv[k] = v.(string)
}
p.SetUserdatadetails(nv)
}
}
if d.HasChange("autoscale_user_id") {
if v, ok := d.GetOk("autoscale_user_id"); ok {
p.SetAutoscaleuserid(v.(string))
}
}
if d.HasChange("display") {
if v, ok := d.GetOk("display"); ok {
p.SetFordisplay(v.(bool))
}
}
log.Printf("[DEBUG] Performing CloudStack API update for profile %s", d.Id())
_, updateErr := cs.AutoScale.UpdateAutoScaleVmProfile(p)
if updateErr != nil {
return fmt.Errorf("Error updating AutoScaleVmProfile %s: %s", d.Id(), updateErr)
}
}
if d.HasChange("metadata") {
if metadataErr := updateMetadata(cs, d, "AutoScaleVmProfile"); metadataErr != nil {
return fmt.Errorf("Error updating tags on AutoScaleVmProfile %s: %s", d.Id(), metadataErr)
}
}
return resourceCloudStackAutoScaleVMProfileRead(d, meta)
}
func resourceCloudStackAutoScaleVMProfileDelete(d *schema.ResourceData, meta interface{}) error {
cs := meta.(*cloudstack.CloudStackClient)
p := cs.AutoScale.NewDeleteAutoScaleVmProfileParams(d.Id())
log.Printf("[INFO] Deleting AutoScaleVmProfile: %s", d.Id())
_, err := cs.AutoScale.DeleteAutoScaleVmProfile(p)
if err != nil {
// This is a very poor way to be told the ID does no longer exist :(
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", d.Id())) {
return nil
}
return fmt.Errorf("Error deleting AutoScaleVmProfile %s: %s", d.Id(), err)
}
return nil
}