-
Notifications
You must be signed in to change notification settings - Fork 2
/
service_resource.go
702 lines (633 loc) · 26.4 KB
/
service_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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
package provider
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
tsClient "github.com/timescale/terraform-provider-timescale/internal/client"
multiplyvalidator "github.com/timescale/terraform-provider-timescale/internal/utils"
)
// Ensure provider defined types fully satisfy framework interfaces
var _ resource.Resource = &ServiceResource{}
var _ resource.ResourceWithImportState = &ServiceResource{}
const (
ErrCreateTimeout = "Error waiting for service creation"
ErrUpdateService = "Error updating service"
ErrInvalidAttribute = "Invalid Attribute Value"
errReplicaFromFork = "cannot create a read replica from a read replica or fork"
errReplicaWithHA = "cannot create a read replica with HA enabled"
errUpdateReplicaSource = "cannot update read replica source"
DefaultMilliCPU = 500
DefaultMemoryGB = 2
)
var (
memorySizes = []int64{2, 4, 8, 16, 32, 64, 128}
milliCPUSizes = []int64{500, 1000, 2000, 4000, 8000, 16000, 32000}
)
func NewServiceResource() resource.Resource {
return &ServiceResource{}
}
// ServiceResource defines the resource implementation.
type ServiceResource struct {
client *tsClient.Client
}
// serviceResourceModel maps the resource schema data.
type serviceResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Timeouts timeouts.Value `tfsdk:"timeouts"`
MilliCPU types.Int64 `tfsdk:"milli_cpu"`
StorageGB types.Int64 `tfsdk:"storage_gb"`
MemoryGB types.Int64 `tfsdk:"memory_gb"`
Password types.String `tfsdk:"password"`
Hostname types.String `tfsdk:"hostname"`
Port types.Int64 `tfsdk:"port"`
ReplicaHostname types.String `tfsdk:"replica_hostname"`
ReplicaPort types.Int64 `tfsdk:"replica_port"`
PoolerHostname types.String `tfsdk:"pooler_hostname"`
PoolerPort types.Int64 `tfsdk:"pooler_port"`
Username types.String `tfsdk:"username"`
RegionCode types.String `tfsdk:"region_code"`
EnableHAReplica types.Bool `tfsdk:"enable_ha_replica"`
Paused types.Bool `tfsdk:"paused"`
ReadReplicaSource types.String `tfsdk:"read_replica_source"`
VpcID types.Int64 `tfsdk:"vpc_id"`
ConnectionPoolerEnabled types.Bool `tfsdk:"connection_pooler_enabled"`
EnvironmentTag types.String `tfsdk:"environment_tag"`
}
func (r *ServiceResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
tflog.Trace(ctx, "ServiceResource.Metadata")
resp.TypeName = req.ProviderTypeName + "_service"
}
// Schema defines the schema for the service resource.
func (r *ServiceResource) Schema(ctx context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
tflog.Trace(ctx, "ServiceResource.Schema")
resp.Schema = schema.Schema{
// This description is used by the documentation generator and the language server.
MarkdownDescription: `A Service is a TimescaleDB instance.
Please note that when updating the vpc_id attribute, it is possible to encounter a "no Endpoint for that service id exists" error.
The change has been taken into account but must still be propagated. You can run "terraform refresh" shortly to get the updated data.`,
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
MarkdownDescription: "Service ID is the unique identifier for this service.",
Description: "service id",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
MarkdownDescription: "Service Name is the configurable name assigned to this resource. If none is provided, a default will be generated by the provider.",
Description: "service name",
Optional: true,
// If the name attribute is absent, the provider will generate a default.
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"milli_cpu": schema.Int64Attribute{
MarkdownDescription: "Milli CPU",
Description: "Milli CPU",
Optional: true,
Computed: true,
Default: int64default.StaticInt64(DefaultMilliCPU),
Validators: []validator.Int64{
int64validator.OneOf(milliCPUSizes...),
multiplyvalidator.EqualToMultipleOf(250, path.Expressions{
path.MatchRoot("memory_gb"),
}...),
},
},
"enable_ha_replica": schema.BoolAttribute{
MarkdownDescription: "Enable HA Replica",
Description: "Enable HA Replica",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
},
"read_replica_source": schema.StringAttribute{
MarkdownDescription: "If set, this database will be a read replica of the provided source database. The region must be the same as the source, or if omitted will be handled by the provider",
Description: "If set, this database will be a read replica of the provided source database. The region must be the same as the source, or if omitted will be handled by the provider",
Optional: true,
},
"storage_gb": schema.Int64Attribute{
MarkdownDescription: "Deprecated: Storage GB",
Description: "Deprecated: Storage GB",
Optional: true,
DeprecationMessage: "This field is ignored. With the new usage-based storage Timescale automatically allocates the disk space needed by your service and you only pay for the disk space you use.",
},
"memory_gb": schema.Int64Attribute{
MarkdownDescription: "Memory GB",
Description: "Memory GB",
Optional: true,
Computed: true,
Default: int64default.StaticInt64(DefaultMemoryGB),
Validators: []validator.Int64{int64validator.OneOf(memorySizes...)},
},
"timeouts": timeouts.Attributes(ctx, timeouts.Opts{
Create: true,
}),
"password": schema.StringAttribute{
Description: "The Postgres password for this service",
MarkdownDescription: "The Postgres password for this service",
Optional: true,
Computed: true,
Sensitive: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"hostname": schema.StringAttribute{
Description: "The hostname for this service",
MarkdownDescription: "The hostname for this service",
Computed: true,
},
"port": schema.Int64Attribute{
Description: "The port for this service",
MarkdownDescription: "The port for this service",
Computed: true,
},
"replica_hostname": schema.StringAttribute{
MarkdownDescription: "Hostname of the HA-Replica of this service.",
Description: "Hostname of the HA-Replica of this service.",
Computed: true,
},
"replica_port": schema.Int64Attribute{
MarkdownDescription: "Port of the HA-Replica of this service.",
Description: "Port of the HA-Replica of this service.",
Computed: true,
},
"pooler_hostname": schema.StringAttribute{
MarkdownDescription: "Hostname of the pooler of this service.",
Description: "Hostname of the pooler of this service.",
Computed: true,
},
"pooler_port": schema.Int64Attribute{
MarkdownDescription: "Port of the pooler of this service.",
Description: "Port of the pooler of this service.",
Computed: true,
},
"connection_pooler_enabled": schema.BoolAttribute{
MarkdownDescription: "Set connection pooler status for this service.",
Description: "Set connection pooler status for this service.",
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"environment_tag": schema.StringAttribute{
MarkdownDescription: "Set environment tag for this service.",
Description: "Set environment tag for this service.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Validators: []validator.String{stringvalidator.OneOf("DEV", "PROD")},
},
"username": schema.StringAttribute{
Description: "The Postgres user for this service",
MarkdownDescription: "The Postgres user for this service",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"region_code": schema.StringAttribute{
Description: `The region for this service`,
MarkdownDescription: "The region for this service.",
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"vpc_id": schema.Int64Attribute{
Description: `The VpcID this service is tied to.`,
MarkdownDescription: `The VpcID this service is tied to.`,
Optional: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"paused": schema.BoolAttribute{
Description: `Paused status of the service.`,
MarkdownDescription: `Paused status of the service.`,
Default: booldefault.StaticBool(false),
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
},
}
}
// Configure adds the provider configured client to the service resource.
func (r *ServiceResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
tflog.Trace(ctx, "ServiceResource.Configure")
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*tsClient.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *tsClient.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
}
func (r *ServiceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
tflog.Trace(ctx, "ServiceResource.Create")
var plan serviceResourceModel
// Read Terraform plan data into the model
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
// Enabling HA replica means one replica
var replicaCount int64
if plan.EnableHAReplica.ValueBool() {
replicaCount = 1
}
request := tsClient.CreateServiceRequest{
Name: plan.Name.ValueString(),
MilliCPU: strconv.FormatInt(plan.MilliCPU.ValueInt64(), 10),
MemoryGB: strconv.FormatInt(plan.MemoryGB.ValueInt64(), 10),
RegionCode: plan.RegionCode.ValueString(),
ReplicaCount: strconv.FormatInt(replicaCount, 10),
EnableConnectionPooler: plan.ConnectionPoolerEnabled.ValueBool(),
EnvironmentTag: plan.EnvironmentTag.ValueString(),
}
if !plan.VpcID.IsNull() {
request.VpcID = plan.VpcID.ValueInt64()
}
readReplicaSource := plan.ReadReplicaSource.ValueString()
if readReplicaSource != "" {
primary, err := r.client.GetService(ctx, readReplicaSource)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("unable to get primary service %s, got error: %s", readReplicaSource, err))
return
}
err = r.validateCreateReadReplicaRequest(ctx, primary, plan)
if err != nil {
resp.Diagnostics.AddError("read replica validation error", err.Error())
return
}
if request.Name == "" {
request.Name = "replica-" + primary.Name
}
if request.RegionCode == "" {
request.RegionCode = primary.RegionCode
}
request.ForkConfig = &tsClient.ForkConfig{
ProjectID: primary.ProjectID,
ServiceID: primary.ID,
IsStandby: true,
}
if len(primary.Resources) > 0 {
request.StorageGB = strconv.FormatInt(primary.Resources[0].Spec.StorageGB, 10)
}
}
response, err := r.client.CreateService(ctx, request)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create service, got error: %s", err))
return
}
// Set the password to the initial password if not provided by the user
if plan.Password.IsNull() || plan.Password.IsUnknown() {
plan.Password = types.StringValue(response.InitialPassword)
}
service, err := r.waitForServiceReadiness(ctx, response.Service.ID, plan.Timeouts)
if err != nil {
resp.Diagnostics.AddError(ErrCreateTimeout, fmt.Sprintf("error occurred while waiting for service deployment, got error: %s", err))
// If we receive an error, attempt to delete the service to avoid having an orphaned instance.
_, err = r.client.DeleteService(context.Background(), response.Service.ID)
if err != nil {
resp.Diagnostics.AddWarning("Error Deleting Resource", "error occurred attempting to delete the resource that timed out, please check your Timescale account to verify there is no unexpected service running from Terraform")
}
return
}
// Check if a user-specified password was provided and update it if so, but only if the service is not a read replica
if !plan.Password.IsNull() && plan.Password.ValueString() != response.InitialPassword && readReplicaSource == "" {
err = r.client.ResetServicePassword(ctx, service.ID, plan.Password.ValueString())
if err != nil {
resp.Diagnostics.AddError("Setting the password failed", fmt.Sprintf("Unable to set user configured password, got error: %s", err))
// Attempt to delete the service to avoid leaving an instance in an inconsistent state
_, deleteErr := r.client.DeleteService(context.Background(), service.ID)
if deleteErr != nil {
resp.Diagnostics.AddWarning("Error Deleting Resource", fmt.Sprintf("Failed to delete service after password setting error; Remove orphaned resources from your account manually. Error: %s", deleteErr))
}
return
}
}
resourceModel := serviceToResource(resp.Diagnostics, service, plan)
resp.Diagnostics.Append(resp.State.Set(ctx, resourceModel)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, fmt.Sprintf("error updating terraform state %v", resp.Diagnostics.Errors()))
return
}
}
func (r *ServiceResource) validateCreateReadReplicaRequest(ctx context.Context, primary *tsClient.Service, plan serviceResourceModel) error {
tflog.Trace(ctx, "validateCreateReadReplicaRequest")
if primary.ForkSpec != nil {
return errors.New(errReplicaFromFork)
}
if plan.EnableHAReplica.ValueBool() {
return errors.New(errReplicaWithHA)
}
return nil
}
func (r *ServiceResource) waitForServiceReadiness(ctx context.Context, id string, timeouts timeouts.Value) (*tsClient.Service, error) {
tflog.Trace(ctx, "ServiceResource.waitForServiceReadiness")
defaultTimeout := 45 * time.Minute
timeout, diags := timeouts.Create(ctx, defaultTimeout)
if diags != nil && diags.HasError() {
tflog.Error(ctx, fmt.Sprintf("found errs %v", diags.Errors()))
return nil, fmt.Errorf("unable to get timeout from config %v", diags.Errors())
}
conf := retry.StateChangeConf{
Pending: []string{"QUEUED", "CONFIGURING", "UNSTABLE", "PAUSING", "RESUMING"},
Target: []string{"READY", "PAUSED"},
Delay: 10 * time.Second,
Timeout: timeout,
PollInterval: 5 * time.Second,
ContinuousTargetOccurence: 1,
Refresh: func() (result interface{}, state string, err error) {
s, err := r.client.GetService(ctx, id)
if err != nil {
return nil, "", err
}
return s, s.Status, nil
},
}
result, err := conf.WaitForStateContext(ctx)
if err != nil {
return nil, err
}
s, ok := result.(*tsClient.Service)
if !ok {
return nil, fmt.Errorf("unexpected type found, expected Service but got %T", result)
}
return s, nil
}
func (r *ServiceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
tflog.Trace(ctx, "ServiceResource.Read")
var state serviceResourceModel
// Read Terraform prior state plan into the model
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Getting Service: "+state.ID.ValueString())
service, err := r.client.GetService(ctx, state.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to read service, got error: %s", err))
return
}
resourceModel := serviceToResource(resp.Diagnostics, service, state)
// Save updated plan into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, resourceModel)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, fmt.Sprintf("error updating terraform state %v", resp.Diagnostics.Errors()))
return
}
}
func (r *ServiceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
tflog.Trace(ctx, "ServiceResource.Update")
var plan, state serviceResourceModel
// 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
}
serviceID := state.ID.ValueString()
readReplicaSource := plan.ReadReplicaSource.ValueString()
if readReplicaSource != state.ReadReplicaSource.ValueString() {
resp.Diagnostics.AddError(ErrUpdateService, errUpdateReplicaSource)
return
}
if readReplicaSource != "" && plan.EnableHAReplica.ValueBool() {
resp.Diagnostics.AddError(ErrUpdateService, errReplicaWithHA)
return
}
if !plan.Hostname.IsUnknown() {
resp.Diagnostics.AddError(ErrUpdateService, "Do not support hostname change")
return
}
if plan.Username != state.Username {
resp.Diagnostics.AddError(ErrUpdateService, "Do not support username change")
return
}
if !plan.Port.IsUnknown() {
resp.Diagnostics.AddError(ErrUpdateService, "Do not support port change")
return
}
if plan.RegionCode != state.RegionCode {
resp.Diagnostics.AddError(ErrUpdateService, "Do not support region code change")
return
}
if plan.Paused != state.Paused {
status := "ACTIVE"
if plan.Paused.ValueBool() {
status = "INACTIVE"
}
if _, err := r.client.ToggleService(ctx, serviceID, status); err != nil {
resp.Diagnostics.AddError("Failed to toggle service", err.Error())
return
}
}
// Connection pooler ////////////////////////////////////////
if plan.ConnectionPoolerEnabled != state.ConnectionPoolerEnabled {
if err := r.client.ToggleConnectionPooler(ctx, serviceID, plan.ConnectionPoolerEnabled.ValueBool()); err != nil {
resp.Diagnostics.AddError("Failed to toggle connection pooler", err.Error())
return
}
}
if plan.EnvironmentTag != state.EnvironmentTag {
if err := r.client.SetEnvironmentTag(ctx, serviceID, plan.EnvironmentTag.ValueString()); err != nil {
resp.Diagnostics.AddError("Failed to set environment tag", err.Error())
return
}
}
if !plan.PoolerHostname.IsUnknown() {
resp.Diagnostics.AddError(ErrUpdateService, "Do not support pooler hostname change")
return
}
if !plan.PoolerPort.IsUnknown() {
resp.Diagnostics.AddError(ErrUpdateService, "Do not support pooler port change")
return
}
// HA Replica ////////////////////////////////////////
if plan.EnableHAReplica != state.EnableHAReplica {
if plan.EnableHAReplica.ValueBool() {
if err := r.client.SetReplicaCount(ctx, serviceID, 1); err != nil {
resp.Diagnostics.AddError("Failed to add a HA replica", err.Error())
return
}
} else {
if err := r.client.SetReplicaCount(ctx, serviceID, 0); err != nil {
resp.Diagnostics.AddError("Failed to remove a HA replica", err.Error())
return
}
}
}
// VPC ////////////////////////////////////////
if !plan.VpcID.Equal(state.VpcID) {
// if state.VpcId is known and different from plan.VpcId, we must detach first
if !state.VpcID.IsNull() && !state.VpcID.IsUnknown() {
if err := r.client.DetachServiceFromVPC(ctx, serviceID, state.VpcID.ValueInt64()); err != nil {
resp.Diagnostics.AddError("Failed to detach service from VPC", err.Error())
return
}
}
// if plan.VpcId is known, it must be attached
if !plan.VpcID.IsNull() && !plan.VpcID.IsUnknown() {
if err := r.client.AttachServiceToVPC(ctx, serviceID, plan.VpcID.ValueInt64()); err != nil {
resp.Diagnostics.AddError("Failed to attach service to VPC", err.Error())
return
}
}
}
if !plan.Name.Equal(state.Name) {
if err := r.client.RenameService(ctx, serviceID, plan.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("Failed to rename a service", err.Error())
return
}
}
{
isResizeRequested := false
const noop = "0" // Compute and storage could be resized separately. Setting value to 0 means a no-op.
resizeConfig := tsClient.ResourceConfig{
MilliCPU: noop,
MemoryGB: noop,
}
if !plan.MilliCPU.Equal(state.MilliCPU) || !plan.MemoryGB.Equal(state.MemoryGB) {
isResizeRequested = true
resizeConfig.MilliCPU = strconv.FormatInt(plan.MilliCPU.ValueInt64(), 10)
resizeConfig.MemoryGB = strconv.FormatInt(plan.MemoryGB.ValueInt64(), 10)
}
if isResizeRequested {
if err := r.client.ResizeInstance(ctx, serviceID, resizeConfig); err != nil {
resp.Diagnostics.AddError("Failed to resize an instance", err.Error())
return
}
}
}
service, err := r.waitForServiceReadiness(ctx, serviceID, plan.Timeouts)
if err != nil {
resp.Diagnostics.AddError(ErrCreateTimeout, fmt.Sprintf("error occurred while waiting for service reconfiguration, got error: %s", err))
return
}
// Update Password if it has changed and if it's not a read replica
if !plan.Password.Equal(state.Password) && !plan.Password.IsNull() && readReplicaSource == "" {
err := r.client.ResetServicePassword(ctx, serviceID, plan.Password.ValueString())
if err != nil {
resp.Diagnostics.AddError("Failed to update password", fmt.Sprintf("Unable to update password, got error: %s", err))
return
}
}
resources := serviceToResource(resp.Diagnostics, service, plan)
resp.Diagnostics.Append(resp.State.Set(ctx, resources)...)
if resp.Diagnostics.HasError() {
tflog.Error(ctx, fmt.Sprintf("error updating terraform state %v", resp.Diagnostics.Errors()))
return
}
}
func (r *ServiceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
tflog.Trace(ctx, "ServiceResource.Delete")
var data serviceResourceModel
// Read Terraform prior state data into the model
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
tflog.Info(ctx, "Deleting Service: "+data.ID.ValueString())
_, err := r.client.DeleteService(ctx, data.ID.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error Deleting Timescale Service",
"Could not delete order, unexpected error: "+err.Error(),
)
return
}
}
func (r *ServiceResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
func serviceToResource(diag diag.Diagnostics, s *tsClient.Service, state serviceResourceModel) serviceResourceModel {
hasHaReplica := (s.ReplicaStatus != "")
hasPooler := s.ServiceSpec.PoolerEnabled
model := serviceResourceModel{
ID: types.StringValue(s.ID),
Password: state.Password,
Name: types.StringValue(s.Name),
MilliCPU: types.Int64Value(s.Resources[0].Spec.MilliCPU),
MemoryGB: types.Int64Value(s.Resources[0].Spec.MemoryGB),
Username: types.StringValue(s.ServiceSpec.Username),
RegionCode: types.StringValue(s.RegionCode),
Timeouts: state.Timeouts,
EnableHAReplica: types.BoolValue(hasHaReplica),
Paused: types.BoolValue(s.Status == "PAUSED" || s.Status == "PAUSING"),
ReadReplicaSource: state.ReadReplicaSource,
ConnectionPoolerEnabled: types.BoolValue(hasPooler),
Hostname: types.StringNull(),
Port: types.Int64Null(),
ReplicaHostname: types.StringNull(),
ReplicaPort: types.Int64Null(),
PoolerHostname: types.StringNull(),
PoolerPort: types.Int64Null(),
}
if s.VPCEndpoint != nil {
if vpcID, err := strconv.ParseInt(s.VPCEndpoint.VPCId, 10, 64); err != nil {
diag.AddError("Parse Error", "could not parse vpcID")
} else {
model.VpcID = types.Int64Value(vpcID)
}
}
if s.Metadata != nil {
model.EnvironmentTag = types.StringValue(s.Metadata.Environment)
}
if s.ForkSpec != nil && s.ForkSpec.IsStandby {
model.ReadReplicaSource = types.StringValue(s.ForkSpec.ServiceID)
}
if s.Endpoints != nil {
if s.Endpoints.Primary != nil && s.Endpoints.Primary.Host != "" {
model.Hostname = types.StringValue(s.Endpoints.Primary.Host)
model.Port = types.Int64Value(int64(s.Endpoints.Primary.Port))
}
if hasHaReplica && s.Endpoints.Replica != nil && s.Endpoints.Replica.Host != "" {
model.ReplicaHostname = types.StringValue(s.Endpoints.Replica.Host)
model.ReplicaPort = types.Int64Value(int64(s.Endpoints.Replica.Port))
}
if hasPooler && s.Endpoints.Pooler != nil && s.Endpoints.Pooler.Host != "" {
model.PoolerHostname = types.StringValue(s.Endpoints.Pooler.Host)
model.PoolerPort = types.Int64Value(int64(s.Endpoints.Pooler.Port))
}
}
return model
}