/
database_data_guard_association_resource.go
560 lines (487 loc) · 18.2 KB
/
database_data_guard_association_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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
package provider
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/terraform-providers/terraform-provider-oci/httpreplay"
oci_common "github.com/oracle/oci-go-sdk/common"
oci_database "github.com/oracle/oci-go-sdk/database"
)
func DatabaseDataGuardAssociationResource() *schema.Resource {
return &schema.Resource{
Timeouts: &schema.ResourceTimeout{
Create: &TwoHours,
Delete: &TwoHours,
Update: &TwoHours,
},
Create: createDatabaseDataGuardAssociation,
Read: readDatabaseDataGuardAssociation,
Update: updateDatabaseDataGuardAssociation,
Delete: deleteDatabaseDataGuardAssociation,
Schema: map[string]*schema.Schema{
// Required
"creation_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: EqualIgnoreCaseSuppressDiff,
ValidateFunc: validation.StringInSlice([]string{
"ExistingDbSystem",
"NewDbSystem",
}, true),
},
"database_admin_password": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Sensitive: true,
},
"database_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"delete_standby_db_home_on_delete": {
Type: schema.TypeString,
Required: true,
},
"protection_mode": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"transport_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
// Optional
"availability_domain": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
DiffSuppressFunc: EqualIgnoreCaseSuppressDiff,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"hostname": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"peer_db_system_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"subnet_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
// Computed
"apply_lag": {
Type: schema.TypeString,
Computed: true,
},
"apply_rate": {
Type: schema.TypeString,
Computed: true,
},
"lifecycle_details": {
Type: schema.TypeString,
Computed: true,
},
"peer_data_guard_association_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_database_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_db_home_id": {
Type: schema.TypeString,
Computed: true,
},
"peer_role": {
Type: schema.TypeString,
Computed: true,
},
"role": {
Type: schema.TypeString,
Computed: true,
},
"state": {
Type: schema.TypeString,
Computed: true,
},
"time_created": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func createDatabaseDataGuardAssociation(d *schema.ResourceData, m interface{}) error {
sync := &DatabaseDataGuardAssociationResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).databaseClient
return CreateResource(d, sync)
}
func readDatabaseDataGuardAssociation(d *schema.ResourceData, m interface{}) error {
sync := &DatabaseDataGuardAssociationResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).databaseClient
return ReadResource(sync)
}
func updateDatabaseDataGuardAssociation(d *schema.ResourceData, m interface{}) error {
sync := &DatabaseDataGuardAssociationResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).databaseClient
return UpdateResource(d, sync)
}
func deleteDatabaseDataGuardAssociation(d *schema.ResourceData, m interface{}) error {
sync := &DatabaseDataGuardAssociationResourceCrud{}
sync.D = d
sync.Client = m.(*OracleClients).databaseClient
return DeleteResource(d, sync)
}
type DatabaseDataGuardAssociationResourceCrud struct {
BaseCrud
Client *oci_database.DatabaseClient
Res *oci_database.DataGuardAssociation
DisableNotFoundRetries bool
}
//after deleting the dataguard we should wait a little bit of time because the dbSystem sometime goes from terminating to available if deleted right after the standby dbHome is deleted and the dataguard is deleted.
func (s *DatabaseDataGuardAssociationResourceCrud) ExtraWaitPostCreateDelete() time.Duration {
if httpreplay.ShouldRetryImmediately() {
return 10 * time.Millisecond
}
return time.Second * 30
}
func (s *DatabaseDataGuardAssociationResourceCrud) ID() string {
return *s.Res.Id
}
func (s *DatabaseDataGuardAssociationResourceCrud) CreatedPending() []string {
return []string{
string(oci_database.DataGuardAssociationLifecycleStateProvisioning),
}
}
func (s *DatabaseDataGuardAssociationResourceCrud) CreatedTarget() []string {
return []string{
string(oci_database.DataGuardAssociationLifecycleStateAvailable),
}
}
func (s *DatabaseDataGuardAssociationResourceCrud) DeletedPending() []string {
return []string{
string(oci_database.DataGuardAssociationLifecycleStateAvailable),
string(oci_database.DataGuardAssociationLifecycleStateTerminating),
}
}
func (s *DatabaseDataGuardAssociationResourceCrud) DeletedTarget() []string {
return []string{
string(oci_database.DataGuardAssociationLifecycleStateTerminated),
}
}
func (s *DatabaseDataGuardAssociationResourceCrud) Create() error {
request := oci_database.CreateDataGuardAssociationRequest{}
err := s.populateTopLevelPolymorphicCreateDataGuardAssociationRequest(&request)
if err != nil {
return err
}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "database")
response, err := s.Client.CreateDataGuardAssociation(context.Background(), request)
if err != nil {
return err
}
s.Res = &response.DataGuardAssociation
return nil
}
func (s *DatabaseDataGuardAssociationResourceCrud) Get() error {
request := oci_database.GetDataGuardAssociationRequest{}
tmp := s.D.Id()
request.DataGuardAssociationId = &tmp
if databaseId, ok := s.D.GetOkExists("database_id"); ok {
tmp := databaseId.(string)
request.DatabaseId = &tmp
}
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "database")
response, err := s.Client.GetDataGuardAssociation(context.Background(), request)
if err != nil {
return err
}
s.Res = &response.DataGuardAssociation
return nil
}
//We need to have an empty delete because otherwise the added delete_standby_db_home_on_delete would have to be marked as ForceNew, which is undesireable. This way the update will pass the new value for this property from the config to the statefile.
func (s *DatabaseDataGuardAssociationResourceCrud) Update() error {
return s.Get()
}
func (s *DatabaseDataGuardAssociationResourceCrud) Delete() error {
if deleteStandbyDbHomeOnDelete, ok := s.D.GetOkExists("delete_standby_db_home_on_delete"); ok {
tmp := deleteStandbyDbHomeOnDelete.(string)
if tmp != "true" {
return fmt.Errorf("we do not currently support deleting the dataguard association without deleting the standby dbHome. Please set delete_standby_db_home_on_delete to \"true\" if you want to continue with the destroy. Once you change the value of delete_standby_db_home_on_delete you must do a `terraform apply` before running a `terraform destroy` so that destroy operation would get the new value")
}
}
err := s.Get()
if err != nil {
return err
}
creationType, ok := s.D.GetOkExists("creation_type")
if !ok {
return fmt.Errorf("creation_type could not be established during the delete")
}
if strings.ToLower(creationType.(string)) == strings.ToLower("ExistingDbSystem") {
var standbyDbHomeId *string
if s.Res.PeerRole == oci_database.DataGuardAssociationPeerRoleStandby {
standbyDbHomeId = s.Res.PeerDbHomeId
} else if s.Res.Role == oci_database.DataGuardAssociationRoleStandby {
standbyDbHomeId, err = s.GetDbHomeIdFromDatabaseId(s.Res.DatabaseId)
if err != nil {
return fmt.Errorf("could not delete the dataguard association as the standby DB Home Id could not be obtained: %v", err)
}
} else {
return fmt.Errorf("could not delete the dataguard association as it is not possible to determine the standby DB home")
}
if standbyDbHomeId == nil {
return fmt.Errorf("could not delete the dataguard association as the standby DB Home Id could not be obtained")
}
request := oci_database.DeleteDbHomeRequest{}
request.DbHomeId = standbyDbHomeId
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "database")
_, err = s.Client.DeleteDbHome(context.Background(), request)
if err != nil {
return fmt.Errorf("could not delete standby DB Home to delete the data guard association: %v", err)
}
getDbHomeRequest := oci_database.GetDbHomeRequest{}
getDbHomeRequest.DbHomeId = standbyDbHomeId
getDbHomeRequest.RequestMetadata.RetryPolicy = waitForDbHomeToTerminateRetryPolicy(2 * time.Hour)
getDbHomeResponse, err := s.Client.GetDbHome(context.Background(), getDbHomeRequest)
//Sometimed the DB Home goes from a TERMINATING Lifecycle state into AVAILABLE, this is to catch that case and report it ot the user as a failure in deleting the database
if getDbHomeResponse.LifecycleState == oci_database.DbHomeLifecycleStateAvailable {
return fmt.Errorf("could not delete the dataguard association as the dbHome could not be deleted")
}
return err
} else if strings.ToLower(creationType.(string)) == strings.ToLower("NewDbSystem") {
var standbyDbSystemId *string
if s.Res.PeerRole == oci_database.DataGuardAssociationPeerRoleStandby {
standbyDbSystemId = s.Res.PeerDbSystemId
} else if s.Res.Role == oci_database.DataGuardAssociationRoleStandby {
standbyDbSystemId, err = s.GetDbSystemIdFromDatabaseId(s.Res.DatabaseId)
if err != nil {
return fmt.Errorf("could not delete the dataguard association as the standby DB System Id could not be obtained: %v", err)
}
} else {
return fmt.Errorf("could not delete the dataguard association as it is not possible to determine the standby DB System")
}
if standbyDbSystemId == nil {
return fmt.Errorf("could not delete the dataguard association as the standby DB System Id could not be obtained")
}
request := oci_database.TerminateDbSystemRequest{}
request.DbSystemId = standbyDbSystemId
request.RequestMetadata.RetryPolicy = getRetryPolicy(s.DisableNotFoundRetries, "database")
_, err := s.Client.TerminateDbSystem(context.Background(), request)
if err != nil {
return fmt.Errorf("could not delete standby DB System to delete the data guard association: %v", err)
}
getDbSystemRequest := oci_database.GetDbSystemRequest{}
getDbSystemRequest.DbSystemId = standbyDbSystemId
getDbSystemRequest.RequestMetadata.RetryPolicy = waitForDbSystemToTerminateRetryPolicy(2 * time.Hour)
getDbSystemResponse, err := s.Client.GetDbSystem(context.Background(), getDbSystemRequest)
//Sometimes the DB System goes from a TERMINATING Lifecycle state into AVAILABLE, this is to catch that case and report it ot the user as a failure in deleting the db System
if getDbSystemResponse.LifecycleState == oci_database.DbSystemLifecycleStateAvailable {
return fmt.Errorf("could not delete the dataguard association as the dbSystem could not be deleted")
}
return err
}
return fmt.Errorf("unrecognized creation_type during delete")
}
func (s *DatabaseDataGuardAssociationResourceCrud) SetData() error {
if s.Res.ApplyLag != nil {
s.D.Set("apply_lag", *s.Res.ApplyLag)
}
if s.Res.ApplyRate != nil {
s.D.Set("apply_rate", *s.Res.ApplyRate)
}
if s.Res.DatabaseId != nil {
s.D.Set("database_id", *s.Res.DatabaseId)
}
if s.Res.LifecycleDetails != nil {
s.D.Set("lifecycle_details", *s.Res.LifecycleDetails)
}
if s.Res.PeerDataGuardAssociationId != nil {
s.D.Set("peer_data_guard_association_id", *s.Res.PeerDataGuardAssociationId)
}
if s.Res.PeerDatabaseId != nil {
s.D.Set("peer_database_id", *s.Res.PeerDatabaseId)
}
if s.Res.PeerDbHomeId != nil {
s.D.Set("peer_db_home_id", *s.Res.PeerDbHomeId)
}
if s.Res.PeerDbSystemId != nil {
s.D.Set("peer_db_system_id", *s.Res.PeerDbSystemId)
}
s.D.Set("peer_role", s.Res.PeerRole)
s.D.Set("protection_mode", s.Res.ProtectionMode)
s.D.Set("role", s.Res.Role)
s.D.Set("state", s.Res.LifecycleState)
if s.Res.TimeCreated != nil {
s.D.Set("time_created", s.Res.TimeCreated.String())
}
s.D.Set("transport_type", s.Res.TransportType)
return nil
}
func (s *DatabaseDataGuardAssociationResourceCrud) populateTopLevelPolymorphicCreateDataGuardAssociationRequest(request *oci_database.CreateDataGuardAssociationRequest) error {
//discriminator
creationTypeRaw, ok := s.D.GetOkExists("creation_type")
var creationType string
if ok {
creationType = creationTypeRaw.(string)
} else {
creationType = "" // default value
}
switch strings.ToLower(creationType) {
case strings.ToLower("ExistingDbSystem"):
details := oci_database.CreateDataGuardAssociationToExistingDbSystemDetails{}
if peerDbSystemId, ok := s.D.GetOkExists("peer_db_system_id"); ok {
tmp := peerDbSystemId.(string)
details.PeerDbSystemId = &tmp
}
if databaseAdminPassword, ok := s.D.GetOkExists("database_admin_password"); ok {
tmp := databaseAdminPassword.(string)
details.DatabaseAdminPassword = &tmp
}
if databaseId, ok := s.D.GetOkExists("database_id"); ok {
tmp := databaseId.(string)
request.DatabaseId = &tmp
}
if protectionMode, ok := s.D.GetOkExists("protection_mode"); ok {
details.ProtectionMode = oci_database.CreateDataGuardAssociationDetailsProtectionModeEnum(protectionMode.(string))
}
if transportType, ok := s.D.GetOkExists("transport_type"); ok {
details.TransportType = oci_database.CreateDataGuardAssociationDetailsTransportTypeEnum(transportType.(string))
}
request.CreateDataGuardAssociationDetails = details
case strings.ToLower("NewDbSystem"):
details := oci_database.CreateDataGuardAssociationWithNewDbSystemDetails{}
if availabilityDomain, ok := s.D.GetOkExists("availability_domain"); ok {
tmp := availabilityDomain.(string)
details.AvailabilityDomain = &tmp
}
if displayName, ok := s.D.GetOkExists("display_name"); ok {
tmp := displayName.(string)
details.DisplayName = &tmp
}
if hostname, ok := s.D.GetOkExists("hostname"); ok {
tmp := hostname.(string)
details.Hostname = &tmp
}
if subnetId, ok := s.D.GetOkExists("subnet_id"); ok {
tmp := subnetId.(string)
details.SubnetId = &tmp
}
if databaseAdminPassword, ok := s.D.GetOkExists("database_admin_password"); ok {
tmp := databaseAdminPassword.(string)
details.DatabaseAdminPassword = &tmp
}
if databaseId, ok := s.D.GetOkExists("database_id"); ok {
tmp := databaseId.(string)
request.DatabaseId = &tmp
}
if protectionMode, ok := s.D.GetOkExists("protection_mode"); ok {
details.ProtectionMode = oci_database.CreateDataGuardAssociationDetailsProtectionModeEnum(protectionMode.(string))
}
if transportType, ok := s.D.GetOkExists("transport_type"); ok {
details.TransportType = oci_database.CreateDataGuardAssociationDetailsTransportTypeEnum(transportType.(string))
}
request.CreateDataGuardAssociationDetails = details
default:
return fmt.Errorf("unknown creation_type '%v' was specified", creationType)
}
return nil
}
func (s *DatabaseDataGuardAssociationResourceCrud) GetDbHomeIdFromDatabaseId(databaseId *string) (*string, error) {
request := oci_database.GetDatabaseRequest{}
request.DatabaseId = databaseId
request.RequestMetadata.RetryPolicy = getRetryPolicy(true, "database")
response, err := s.Client.GetDatabase(context.Background(), request)
if err != nil {
return nil, err
}
return response.DbHomeId, nil
}
func (s *DatabaseDataGuardAssociationResourceCrud) GetDbSystemIdFromDatabaseId(databaseId *string) (*string, error) {
dbHomeId, err := s.GetDbHomeIdFromDatabaseId(databaseId)
if err != nil {
return dbHomeId, err
}
return s.GetDbSystemIdFromDbHomeId(dbHomeId)
}
func (s *DatabaseDataGuardAssociationResourceCrud) GetDbSystemIdFromDbHomeId(dbHomeId *string) (*string, error) {
request := oci_database.GetDbHomeRequest{}
request.DbHomeId = dbHomeId
request.RequestMetadata.RetryPolicy = getRetryPolicy(true, "database")
response, err := s.Client.GetDbHome(context.Background(), request)
if err != nil {
return nil, err
}
return response.DbSystemId, nil
}
func waitForDbHomeToTerminateRetryPolicy(timeout time.Duration) *oci_common.RetryPolicy {
startTime := time.Now()
// wait for peering status to not be Pending
return &oci_common.RetryPolicy{
ShouldRetryOperation: func(response oci_common.OCIOperationResponse) bool {
if shouldRetry(response, false, "database", startTime) {
return true
}
if getDbHomeResponse, ok := response.Response.(oci_database.GetDbHomeResponse); ok {
if getDbHomeResponse.LifecycleState != oci_database.DbHomeLifecycleStateTerminated && getDbHomeResponse.LifecycleState != oci_database.DbHomeLifecycleStateAvailable {
timeWaited := getElapsedRetryDuration(startTime)
return timeWaited < timeout
}
}
return false
},
NextDuration: func(response oci_common.OCIOperationResponse) time.Duration {
return getRetryBackoffDuration(response, false, "database", startTime)
},
MaximumNumberAttempts: 0,
}
}
func waitForDbSystemToTerminateRetryPolicy(timeout time.Duration) *oci_common.RetryPolicy {
startTime := time.Now()
// wait for peering status to not be Pending
return &oci_common.RetryPolicy{
ShouldRetryOperation: func(response oci_common.OCIOperationResponse) bool {
if shouldRetry(response, false, "database", startTime) {
return true
}
if getDbSystemResponse, ok := response.Response.(oci_database.GetDbSystemResponse); ok {
if getDbSystemResponse.LifecycleState != oci_database.DbSystemLifecycleStateTerminated && getDbSystemResponse.LifecycleState != oci_database.DbSystemLifecycleStateAvailable {
timeWaited := getElapsedRetryDuration(startTime)
return timeWaited < timeout
}
}
return false
},
NextDuration: func(response oci_common.OCIOperationResponse) time.Duration {
return getRetryBackoffDuration(response, false, "database", startTime)
},
MaximumNumberAttempts: 0,
}
}