/
backup.go
519 lines (455 loc) · 16.8 KB
/
backup.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
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
package resources
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/couchbasecloud/terraform-provider-couchbase-capella/internal/api"
backupapi "github.com/couchbasecloud/terraform-provider-couchbase-capella/internal/api/backup"
"github.com/couchbasecloud/terraform-provider-couchbase-capella/internal/errors"
providerschema "github.com/couchbasecloud/terraform-provider-couchbase-capella/internal/schema"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &Backup{}
_ resource.ResourceWithConfigure = &Backup{}
_ resource.ResourceWithImportState = &Backup{}
)
const errorMessageWhileBackupCreation = "There is an error during backup creation. Please check in Capella to see if any hanging resources" +
" have been created, unexpected error: "
// Backup is the Backup resource implementation.
type Backup struct {
*providerschema.Data
}
// NewBackup is a helper function to simplify the provider implementation.
func NewBackup() resource.Resource {
return &Backup{}
}
// Metadata returns the Backup resource type name.
func (b *Backup) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_backup"
}
// Schema defines the schema for the Backup resource.
func (b *Backup) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = BackupSchema()
}
// Create creates a new Backup.
func (b *Backup) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan providerschema.Backup
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
err := b.validateCreateBackupRequest(plan)
if err != nil {
resp.Diagnostics.AddError(
"Error parsing create backup request",
"Could not create backup "+err.Error(),
)
return
}
BackupRequest := backupapi.CreateBackupRequest{}
var organizationId = plan.OrganizationId.ValueString()
var projectId = plan.ProjectId.ValueString()
var clusterId = plan.ClusterId.ValueString()
var bucketId = plan.BucketId.ValueString()
latestBackup, err := b.getLatestBackup(ctx, organizationId, projectId, clusterId, bucketId)
if err != nil {
resp.Diagnostics.AddError(
"Error getting latest bucket backup in a cluster",
"Could not get the latest bucket backup : unexpected error "+api.ParseError(err),
)
return
}
var backupFound bool
if latestBackup != nil {
backupFound = true
}
url := fmt.Sprintf("%s/v4/organizations/%s/projects/%s/clusters/%s/buckets/%s/backups", b.HostURL, organizationId, projectId, clusterId, bucketId)
cfg := api.EndpointCfg{Url: url, Method: http.MethodPost, SuccessStatus: http.StatusAccepted}
_, err = b.Client.ExecuteWithRetry(
ctx,
cfg,
BackupRequest,
b.Token,
nil,
)
if err != nil {
resp.Diagnostics.AddError(
"Error executing create backup request",
errorMessageWhileBackupCreation+api.ParseError(err),
)
return
}
backupResponse, err := b.checkLatestBackupStatus(ctx, organizationId, projectId, clusterId, bucketId, backupFound, latestBackup)
if err != nil {
resp.Diagnostics.AddError(
"Error while checking latest backup status",
fmt.Sprintf("Could not read check latest backup status."+
"Please check in Capella to see if any hanging resources have "+
"been created, unexpected error: "+api.ParseError(err)),
)
return
}
backupStats := providerschema.NewBackupStats(*backupResponse.BackupStats)
backupStatsObj, diags := types.ObjectValueFrom(ctx, backupStats.AttributeTypes(), backupStats)
if diags.HasError() {
resp.Diagnostics.AddError(
"Error Reading Backup Stats",
fmt.Sprintf("Could not read backup stats data in a backup record, "+
"please check in Capella to see if any hanging resources have been created, "+
"unexpected error: %s", fmt.Errorf("error while backup stats conversion")),
)
return
}
scheduleInfo := providerschema.NewScheduleInfo(*backupResponse.ScheduleInfo)
scheduleInfoObj, diags := types.ObjectValueFrom(ctx, scheduleInfo.AttributeTypes(), scheduleInfo)
if diags.HasError() {
resp.Diagnostics.AddError(
"Error Error Reading Backup Schedule Info",
fmt.Sprintf("Could not read backup schedule info in a backup record, "+
"please check in Capella to see if any hanging resources have been created, "+
"unexpected error: %s", fmt.Errorf("error while backup schedule info conversion")),
)
return
}
refreshedState := providerschema.NewBackup(backupResponse, organizationId, projectId, backupStatsObj, scheduleInfoObj)
// Set state to fully populated data
diags = resp.State.Set(ctx, refreshedState)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Read reads backup information.
func (b *Backup) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state providerschema.Backup
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
IDs, err := state.Validate()
if err != nil {
resp.Diagnostics.AddError(
"Error Reading Backup in Capella",
"Could not read Capella Backup with ID "+state.Id.String()+": "+err.Error(),
)
return
}
var (
organizationId = IDs[providerschema.OrganizationId]
projectId = IDs[providerschema.ProjectId]
clusterId = IDs[providerschema.ClusterId]
backupId = IDs[providerschema.Id]
)
refreshedState, err := b.retrieveBackup(ctx, organizationId, projectId, clusterId, backupId)
if err != nil {
resourceNotFound, errString := api.CheckResourceNotFoundError(err)
if resourceNotFound {
tflog.Info(ctx, "resource doesn't exist in remote server removing resource from state file")
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Error reading backup",
"Could not read backup id "+state.Id.String()+": "+errString,
)
return
}
refreshedState.Restore = state.Restore
refreshedState.RestoreTimes = state.RestoreTimes
diags = resp.State.Set(ctx, &refreshedState)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Update updates the Backup record.
func (b *Backup) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var state, plan providerschema.Backup
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
diags = req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
IDs, err := plan.Validate()
if err != nil {
resp.Diagnostics.AddError(
"Error Reading Backup in Capella",
"Could not read Capella Backup with ID "+state.Id.String()+": "+err.Error(),
)
return
}
var (
organizationId = IDs[providerschema.OrganizationId]
projectId = IDs[providerschema.ProjectId]
clusterId = IDs[providerschema.ClusterId]
backupId = IDs[providerschema.Id]
)
var restore *providerschema.Restore
diags.Append(req.Config.GetAttribute(ctx, path.Root("restore"), &restore)...)
if plan.RestoreTimes.IsNull() || plan.RestoreTimes.IsUnknown() {
resp.Diagnostics.AddError(
"Error restoring backup",
"Could not restore backup id "+state.Id.String()+": plan restore times value is not set",
)
return
}
if !state.RestoreTimes.IsNull() && !state.RestoreTimes.IsUnknown() {
planRestoreTimes := *plan.RestoreTimes.ValueBigFloat()
stateRestoreTimes := *state.RestoreTimes.ValueBigFloat()
if planRestoreTimes.Cmp(&stateRestoreTimes) != 1 {
resp.Diagnostics.AddError(
"Error restoring backup",
"Could not restore backup id "+state.Id.String()+": plan restore times value is not greater than state restore times value",
)
return
}
}
var newServices []backupapi.Service
for _, service := range restore.Services {
newService := service.ValueString()
newServices = append(newServices, backupapi.Service(newService))
}
restoreRequest := backupapi.CreateRestoreRequest{
TargetClusterId: restore.TargetClusterId.ValueString(),
SourceClusterId: restore.SourceClusterId.ValueString(),
BackupId: backupId,
Services: &newServices,
ForceUpdates: restore.ForceUpdates.ValueBool(),
AutoRemoveCollections: restore.AutoRemoveCollections.ValueBool(),
FilterKeys: restore.FilterKeys.ValueString(),
FilterValues: restore.FilterValues.ValueString(),
IncludeData: restore.IncludeData.ValueString(),
ExcludeData: restore.ExcludeData.ValueString(),
MapData: restore.MapData.ValueString(),
ReplaceTTL: restore.ReplaceTTL.ValueString(),
ReplaceTTLWith: restore.ReplaceTTLWith.ValueString(),
}
url := fmt.Sprintf("%s/v4/organizations/%s/projects/%s/clusters/%s/backups/%s/restore", b.HostURL, organizationId, projectId, clusterId, backupId)
cfg := api.EndpointCfg{Url: url, Method: http.MethodPost, SuccessStatus: http.StatusAccepted}
_, err = b.Client.ExecuteWithRetry(
ctx,
cfg,
restoreRequest,
b.Token,
nil,
)
if err != nil {
resp.Diagnostics.AddError(
"Error restoring backup",
"Could not restore backup id "+state.Id.String()+": plan restore times value is not greater than state restore times value",
)
return
}
if !plan.Restore.IsUnknown() && !plan.Restore.IsNull() {
restore.Status = types.StringValue("RESTORE INITIATED")
restoreObj, diags := types.ObjectValueFrom(ctx, restore.AttributeTypes(), restore)
if diags.HasError() {
resp.Diagnostics.Append(diags...)
return
}
plan.Restore = restoreObj
}
diags = resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Delete deletes the backup.
func (b *Backup) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Retrieve values from state
var state providerschema.Backup
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resourceIDs, err := state.Validate()
if err != nil {
resp.Diagnostics.AddError(
"Error deleting backup",
"Could not delete backup id "+state.Id.String()+" unexpected error: "+err.Error(),
)
return
}
var (
organizationId = resourceIDs[providerschema.OrganizationId]
projectId = resourceIDs[providerschema.ProjectId]
clusterId = resourceIDs[providerschema.ClusterId]
backupId = resourceIDs[providerschema.Id]
)
// Delete existing Backup
url := fmt.Sprintf("%s/v4/organizations/%s/projects/%s/clusters/%s/backups/%s", b.HostURL, organizationId, projectId, clusterId, backupId)
cfg := api.EndpointCfg{Url: url, Method: http.MethodDelete, SuccessStatus: http.StatusAccepted}
_, err = b.Client.ExecuteWithRetry(
ctx,
cfg,
nil,
b.Token,
nil,
)
if err != nil {
resourceNotFound, errString := api.CheckResourceNotFoundError(err)
if resourceNotFound {
tflog.Info(ctx, "resource doesn't exist in remote server removing resource from state file")
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError(
"Error deleting backup",
"Could not delete backup id "+state.Id.String()+": "+errString,
)
return
}
}
// ImportState imports a remote backup that is not created by Terraform.
func (b *Backup) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
// Retrieve import ID and save to id attribute
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// Configure adds the provider configured api to the backup resource.
func (b *Backup) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*providerschema.Data)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *ProviderSourceData, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
b.Data = data
}
func (a *Backup) validateCreateBackupRequest(plan providerschema.Backup) error {
if plan.OrganizationId.IsNull() {
return errors.ErrOrganizationIdCannotBeEmpty
}
if plan.ProjectId.IsNull() {
return errors.ErrProjectIdCannotBeEmpty
}
if plan.ClusterId.IsNull() {
return errors.ErrClusterIdCannotBeEmpty
}
if plan.BucketId.IsNull() {
return errors.ErrBucketIdCannotBeEmpty
}
if !plan.RestoreTimes.IsNull() && !plan.RestoreTimes.IsUnknown() {
return errors.ErrRestoreTimesMustNotBeSetWhileCreateBackup
}
return nil
}
// checkLatestBackupStatus monitors the status of a backup creation operation for a specified
// organization, project, and cluster ID. It periodically fetches the backup job status using the `getLatestBackup`
// function and waits until the backup reaches a final state or until a specified timeout is reached.
// The function returns an error if the operation times out or encounters an error during status retrieval.
func (b *Backup) checkLatestBackupStatus(ctx context.Context, organizationId, projectId, clusterId, bucketId string, backupFound bool, latestBackup *backupapi.GetBackupResponse) (*backupapi.GetBackupResponse, error) {
var (
backupResp *backupapi.GetBackupResponse
err error
)
// Assuming 60 minutes is the max time backup completion takes, can change after discussion
const timeout = time.Minute * 60
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, timeout)
defer cancel()
const sleep = time.Second * 1
timer := time.NewTimer(1 * time.Second)
for {
select {
case <-ctx.Done():
const msg = "bucket backup creation status transition timed out after initiation"
return nil, fmt.Errorf(msg)
case <-timer.C:
backupResp, err = b.getLatestBackup(ctx, organizationId, projectId, clusterId, bucketId)
switch err {
case nil:
// If there is no existing backup for a bucket, check for a new backup record to be created.
// If a backup record exists already, wait for a backup record with a new ID to be created.
if !backupFound && backupResp != nil && backupapi.IsFinalState(backupResp.Status) {
return backupResp, nil
} else if backupFound && backupResp != nil && latestBackup.Id != backupResp.Id && backupapi.IsFinalState(backupResp.Status) {
return backupResp, nil
}
const msg = "waiting for backup to complete the execution"
tflog.Info(ctx, msg)
default:
return nil, err
}
timer.Reset(sleep)
}
}
}
// retrieveBackup retrieves backup information from the specified organization and project
// using the provided backup ID by open-api call.
func (b *Backup) retrieveBackup(ctx context.Context, organizationId, projectId, clusterId, backupId string) (*providerschema.Backup, error) {
url := fmt.Sprintf("%s/v4/organizations/%s/projects/%s/clusters/%s/backups/%s", b.HostURL, organizationId, projectId, clusterId, backupId)
cfg := api.EndpointCfg{Url: url, Method: http.MethodGet, SuccessStatus: http.StatusOK}
response, err := b.Client.ExecuteWithRetry(
ctx,
cfg,
nil,
b.Token,
nil,
)
if err != nil {
return nil, err
}
backupResp := backupapi.GetBackupResponse{}
err = json.Unmarshal(response.Body, &backupResp)
if err != nil {
return nil, err
}
bStats := providerschema.NewBackupStats(*backupResp.BackupStats)
bStatsObj, diags := types.ObjectValueFrom(ctx, bStats.AttributeTypes(), bStats)
if diags.HasError() {
return nil, errors.ErrUnableToConvertAuditData
}
sInfo := providerschema.NewScheduleInfo(*backupResp.ScheduleInfo)
sInfoObj, diags := types.ObjectValueFrom(ctx, sInfo.AttributeTypes(), sInfo)
if diags.HasError() {
return nil, errors.ErrUnableToConvertAuditData
}
refreshedState := providerschema.NewBackup(&backupResp, organizationId, projectId, bStatsObj, sInfoObj)
return refreshedState, nil
}
// getLatestBackup retrieves the latest backup information for a specified bucket in a cluster
// from the specified organization, project and cluster using the provided bucket ID by open-api call.
func (b *Backup) getLatestBackup(ctx context.Context, organizationId, projectId, clusterId, bucketId string) (*backupapi.GetBackupResponse, error) {
url := fmt.Sprintf("%s/v4/organizations/%s/projects/%s/clusters/%s/backups", b.HostURL, organizationId, projectId, clusterId)
cfg := api.EndpointCfg{Url: url, Method: http.MethodGet, SuccessStatus: http.StatusOK}
response, err := b.Client.ExecuteWithRetry(
ctx,
cfg,
nil,
b.Token,
nil,
)
if err != nil {
return nil, err
}
clusterResp := backupapi.GetBackupsResponse{}
err = json.Unmarshal(response.Body, &clusterResp)
if err != nil {
return nil, err
}
// check for a backup record of the specified bucket
for _, backup := range clusterResp.Data {
if backup.BucketId == bucketId {
return &backup, nil
}
}
return nil, nil
}