/
vdc_resource.go
434 lines (361 loc) · 14.5 KB
/
vdc_resource.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
// Package vdc provides a resource to manage VDCs.
package vdc
import (
"context"
"errors"
"fmt"
"time"
"github.com/vmware/go-vcloud-director/v2/govcd"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/orange-cloudavenue/cloudavenue-sdk-go/v1/infrapi"
"github.com/orange-cloudavenue/cloudavenue-sdk-go/v1/infrapi/rules"
"github.com/orange-cloudavenue/terraform-provider-cloudavenue/internal/client"
"github.com/orange-cloudavenue/terraform-provider-cloudavenue/internal/metrics"
"github.com/orange-cloudavenue/terraform-provider-cloudavenue/internal/provider/common/cloudavenue"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &vdcResource{}
_ resource.ResourceWithConfigure = &vdcResource{}
_ resource.ResourceWithImportState = &vdcResource{}
_ resource.ResourceWithValidateConfig = &vdcResource{}
_ resource.ResourceWithModifyPlan = &vdcResource{}
)
// NewVDCResource is a helper function to simplify the provider implementation.
func NewVDCResource() resource.Resource {
return &vdcResource{}
}
// vdcResource is the resource implementation.
type vdcResource struct {
client *client.CloudAvenue
}
// Metadata returns the resource type name.
func (r *vdcResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_" + categoryName
}
// Schema defines the schema for the resource.
func (r *vdcResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = vdcSchema().GetResource(ctx)
}
// Configure configures the resource.
func (r *vdcResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*client.CloudAvenue)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *client.CloudAvenue, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
}
func (r *vdcResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
config := new(vdcResourceModel)
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
StorageProfiles, d := config.StorageProfiles.Get(ctx)
resp.Diagnostics.Append(d...)
if resp.Diagnostics.HasError() {
return
}
if err := rules.Validate(rules.ValidateData{
ServiceClass: rules.ServiceClass(config.ServiceClass.Get()),
DisponibilityClass: rules.DisponibilityClass(config.DisponibilityClass.Get()),
BillingModel: rules.BillingModel(config.BillingModel.Get()),
VCPUInMhz: config.VCPUInMhz.GetInt(),
CPUAllocated: config.CPUAllocated.GetInt(),
MemoryAllocated: config.MemoryAllocated.GetInt(),
StorageBillingModel: rules.BillingModel(config.StorageBillingModel.Get()),
StorageProfiles: func() map[rules.StorageProfileClass]struct {
Limit int
Default bool
} {
storageProfiles := make(map[rules.StorageProfileClass]struct {
Limit int
Default bool
})
for _, sP := range StorageProfiles {
storageProfiles[rules.StorageProfileClass(sP.Class.Get())] = struct {
Limit int
Default bool
}{Limit: sP.Limit.GetInt(), Default: sP.Default.Get()}
}
return storageProfiles
}(),
}, false); err != nil {
switch {
case errors.Is(err, rules.ErrBillingModelNotAvailable):
resp.Diagnostics.AddAttributeError(path.Root("billing_model"), "Billing model attribute is not valid", err.Error())
case errors.Is(err, rules.ErrServiceClassNotFound):
resp.Diagnostics.AddAttributeError(path.Root("service_class"), "Service class attribute is not valid", err.Error())
case errors.Is(err, rules.ErrDisponibilityClassNotFound):
resp.Diagnostics.AddAttributeError(path.Root("disponibility_class"), "Disponibility class attribute is not valid", err.Error())
case errors.Is(err, rules.ErrStorageBillingModelNotFound):
resp.Diagnostics.AddAttributeError(path.Root("storage_billing_model"), "Storage billing model attribute is not valid", err.Error())
case errors.Is(err, rules.ErrStorageProfileClassNotFound):
resp.Diagnostics.AddAttributeError(path.Root("storage_profiles"), "Storage profile class attribute is not valid", err.Error())
case errors.Is(err, rules.ErrCPUAllocatedInvalid):
resp.Diagnostics.AddAttributeError(path.Root("cpu_allocated"), "CPU allocated attribute is not valid", err.Error())
case errors.Is(err, rules.ErrMemoryAllocatedInvalid):
resp.Diagnostics.AddAttributeError(path.Root("memory_allocated"), "Memory allocated attribute is not valid", err.Error())
case errors.Is(err, rules.ErrVCPUInMhzInvalid):
resp.Diagnostics.AddAttributeError(path.Root("cpu_speed_in_mhz"), "CPU speed in MHz attribute is not valid", err.Error())
case errors.Is(err, rules.ErrStorageProfileLimitInvalid) || errors.Is(err, rules.ErrStorageProfileLimitNotIntegrer):
resp.Diagnostics.AddAttributeError(path.Root("storage_profiles").AtName("limit"), "Storage profile limit attribute is not valid", err.Error())
case errors.Is(err, rules.ErrStorageProfileDefault):
resp.Diagnostics.AddAttributeError(path.Root("storage_profiles").AtName("default"), "Storage profile default attribute is not valid", err.Error())
default:
resp.Diagnostics.AddError("Error validating VDC", err.Error())
}
}
}
func (r *vdcResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, resp *resource.ModifyPlanResponse) {
var (
plan = new(vdcResourceModel)
state = new(vdcResourceModel)
)
// Retrieve values from plan
d := req.Plan.Get(ctx, plan)
if d.HasError() {
// If there is an error in the plan, we don't need to continue
return
}
d = req.State.Get(ctx, state)
// If error in state will be is in create mode
if !d.HasError() {
return
}
// If there is no error in the state, we are in update mode
// "Force replacement attributes, however you can change the `cpu_speed_in_mhz` attribute only if the `billing_model` is set to **RESERVED**."
if plan.VCPUInMhz.Equal(state.VCPUInMhz) && plan.BillingModel.Get() != string(rules.BillingModelReserved) {
resp.RequiresReplace = append(resp.RequiresReplace, path.Root("cpu_speed_in_mhz"))
resp.Diagnostics.AddAttributeWarning(path.Root("cpu_speed_in_mhz"), "CPU speed in MHz attribute require replacement", "You can change the `cpu_speed_in_mhz` attribute only if the `billing_model` is set to **RESERVED**.")
}
}
// Create creates the resource and sets the initial Terraform state.
func (r *vdcResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
defer metrics.New("cloudavenue_vdc", r.client.GetOrgName(), metrics.Create)()
// Retrieve values from plan
plan := new(vdcResourceModel)
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
cloudavenue.Lock(ctx)
defer cloudavenue.Unlock(ctx)
// Create() is passed a default timeout to use if no value
// has been supplied in the Terraform configuration.
createTimeout, errTO := plan.Timeouts.Create(ctx, 8*time.Minute)
if errTO != nil {
resp.Diagnostics.AddError(
"Error creating timeout",
"Could not create timeout, unexpected error",
)
return
}
ctx, cancel := context.WithTimeout(ctx, createTimeout)
defer cancel()
body, d := plan.ToCAVVirtualDataCenter(ctx)
resp.Diagnostics.Append(d...)
if resp.Diagnostics.HasError() {
return
}
_, err := r.client.CAVSDK.V1.VDC().New(body)
if err != nil {
resp.Diagnostics.AddError("Error creating VDC", err.Error())
return
}
stateRefreshed, found, d := r.read(ctx, plan)
if !found {
resp.State.RemoveResource(ctx)
resp.Diagnostics.AddWarning("Resource not found", fmt.Sprintf("Unable to find resource %s after creation", plan.Name.Get()))
return
}
resp.Diagnostics.Append(d...)
if resp.Diagnostics.HasError() {
return
}
// Save plan into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, stateRefreshed)...)
}
// Read refreshes the Terraform state with the latest data.
func (r *vdcResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
defer metrics.New("cloudavenue_vdc", r.client.GetOrgName(), metrics.Read)()
// Get current state
state := new(vdcResourceModel)
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
// Call API to read the resource and test for errors.
readTimeout, errTO := state.Timeouts.Read(ctx, 8*time.Minute)
if errTO != nil {
resp.Diagnostics.AddError(
"Error creating timeout",
"Could not create timeout, unexpected error",
)
return
}
ctx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
stateRefreshed, found, d := r.read(ctx, state)
if !found {
resp.State.RemoveResource(ctx)
resp.Diagnostics.AddWarning("Resource not found", fmt.Sprintf("Unable to find resource %s", state.Name.Get()))
return
}
resp.Diagnostics.Append(d...)
if resp.Diagnostics.HasError() {
return
}
// Save updated state into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, stateRefreshed)...)
}
// Update updates the resource and sets the updated Terraform state on success.
func (r *vdcResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
defer metrics.New("cloudavenue_vdc", r.client.GetOrgName(), metrics.Update)()
var (
plan = new(vdcResourceModel)
state = new(vdcResourceModel)
)
cloudavenue.Lock(ctx)
defer cloudavenue.Unlock(ctx)
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
// Update() is passed a default timeout to use if no value
// has been supplied in the Terraform configuration.
updateTimeout, errTO := plan.Timeouts.Update(ctx, 8*time.Minute)
if errTO != nil {
resp.Diagnostics.AddError(
"Error creating timeout",
"Could not create timeout, unexpected error",
)
return
}
ctx, cancel := context.WithTimeout(ctx, updateTimeout)
defer cancel()
vdc, err := r.client.CAVSDK.V1.VDC().GetVDC(plan.Name.Get())
if err != nil {
resp.Diagnostics.AddError("Error reading VDC", err.Error())
return
}
// Update the VDC
if !plan.Description.Equal(state.Description) {
vdc.SetDescription(plan.Description.Get())
}
if !plan.VCPUInMhz.Equal(state.VCPUInMhz) {
vdc.SetVCPUInMhz(plan.VCPUInMhz.GetInt())
}
if !plan.CPUAllocated.Equal(state.CPUAllocated) {
vdc.SetCPUAllocated(plan.CPUAllocated.GetInt())
}
if !plan.MemoryAllocated.Equal(state.MemoryAllocated) {
vdc.SetMemoryAllocated(plan.MemoryAllocated.GetInt())
}
if !plan.StorageProfiles.Equal(state.StorageProfiles) {
vdcStorageProfiles := make([]infrapi.StorageProfile, 0)
storageProfiles, d := plan.StorageProfiles.Get(ctx)
resp.Diagnostics.Append(d...)
if resp.Diagnostics.HasError() {
return
}
for _, storageProfile := range storageProfiles {
vdcStorageProfiles = append(vdcStorageProfiles, infrapi.StorageProfile{
Class: infrapi.StorageProfileClass(storageProfile.Class.Get()),
Limit: storageProfile.Limit.GetInt(),
Default: storageProfile.Default.Get(),
})
}
vdc.SetStorageProfiles(vdcStorageProfiles)
}
if err := vdc.Update(); err != nil {
resp.Diagnostics.AddError("Error updating VDC", err.Error())
return
}
stateRefreshed, _, d := r.read(ctx, state)
resp.Diagnostics.Append(d...)
if resp.Diagnostics.HasError() {
return
}
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, stateRefreshed)...)
}
// Delete deletes the resource and removes the Terraform state on success.
func (r *vdcResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
defer metrics.New("cloudavenue_vdc", r.client.GetOrgName(), metrics.Delete)()
state := new(vdcResourceModel)
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
cloudavenue.Lock(ctx)
defer cloudavenue.Unlock(ctx)
vdc, err := r.client.CAVSDK.V1.VDC().GetVDC(state.Name.Get())
if err != nil {
resp.Diagnostics.AddError("Error reading VDC", err.Error())
return
}
job, err := vdc.Delete()
if err != nil {
resp.Diagnostics.AddError("Error deleting VDC", err.Error())
return
}
if err := job.Wait(1, 600); err != nil {
resp.Diagnostics.AddError("Error deleting VDC", err.Error())
return
}
}
func (r *vdcResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
defer metrics.New("cloudavenue_vdc", r.client.GetOrgName(), metrics.Import)()
// Retrieve import ID and save to id attribute
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
// * Custom Functions.
// read is a generic function to read a resource.
func (r *vdcResource) read(ctx context.Context, planOrState *vdcResourceModel) (stateRefreshed *vdcResourceModel, found bool, diags diag.Diagnostics) {
stateRefreshed = planOrState.Copy()
vdc, err := r.client.CAVSDK.V1.VDC().GetVDC(planOrState.Name.Get())
if err != nil {
if govcd.IsNotFound(err) {
return nil, false, nil
}
diags.AddError("Error reading VDC", err.Error())
return nil, true, diags
}
stateRefreshed.ID.Set(vdc.GetID())
stateRefreshed.Name.Set(vdc.GetName())
stateRefreshed.Description.Set(vdc.GetDescription())
stateRefreshed.ServiceClass.Set(string(vdc.GetServiceClass()))
stateRefreshed.StorageBillingModel.Set(string(vdc.GetStorageBillingModel()))
stateRefreshed.DisponibilityClass.Set(string(vdc.GetDisponibilityClass()))
stateRefreshed.BillingModel.Set(string(vdc.GetBillingModel()))
stateRefreshed.VCPUInMhz.SetInt(vdc.GetVCPUInMhz())
stateRefreshed.CPUAllocated.SetInt(vdc.GetCPUAllocated())
stateRefreshed.MemoryAllocated.SetInt(vdc.GetMemoryAllocated())
storageProfiles := make([]*vdcResourceModelVDCStorageProfile, 0)
for _, storageProfile := range vdc.GetStorageProfiles() {
p := new(vdcResourceModelVDCStorageProfile)
p.Class.Set(string(storageProfile.Class))
p.Limit.SetInt(storageProfile.Limit)
p.Default.Set(storageProfile.Default)
storageProfiles = append(storageProfiles, p)
}
diags.Append(stateRefreshed.StorageProfiles.Set(ctx, storageProfiles)...)
if diags.HasError() {
return
}
return stateRefreshed, true, diags
}