generated from hashicorp/terraform-provider-scaffolding-framework
/
source_resource.go
275 lines (234 loc) · 7.74 KB
/
source_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
package provider
import (
"context"
"errors"
"fmt"
"os"
"reflect"
"strings"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/mezmo/terraform-provider-mezmo/internal/client"
. "github.com/mezmo/terraform-provider-mezmo/internal/client"
. "github.com/mezmo/terraform-provider-mezmo/internal/provider/models/modelutils"
. "github.com/mezmo/terraform-provider-mezmo/internal/provider/models/sources"
)
type SourceModel interface {
AgentSourceModel |
AzureEventHubSourceModel |
DatadogSourceModel |
DemoSourceModel |
FluentSourceModel |
HttpSourceModel |
KafkaSourceModel |
KinesisFirehoseSourceModel |
LogAnalysisSourceModel |
LogStashSourceModel |
OpenTelemetryTracesSourceModel |
PrometheusRemoteWriteSourceModel |
S3SourceModel |
SplunkHecSourceModel |
SQSSourceModel |
WebhookSourceModel
}
type SourceResource[T SourceModel] struct {
client Client
typeName string // The name to use as part of the terraform resource name: mezmo_{typeName}_source
nodeName string // the corresponding pipeline service node type
fromModelFunc sourceFromModelFunc[T]
toModelFunc sourceToModelFunc[T]
getIdFunc idGetterFunc[T]
getPipelineIdFunc idGetterFunc[T]
schema schema.Schema
}
func (r *SourceResource[T]) TypeName() string {
return fmt.Sprintf("%s_%s_source", PROVIDER_TYPE_NAME, r.typeName)
}
func (r *SourceResource[T]) NodeType() string {
// conversion to underscore and appending suffix
// disambiguates resources with similar node types
// example: http sink and http source
return strings.ReplaceAll(r.nodeName, "-", "_") + "_source"
}
func (r *SourceResource[T]) TerraformSchema() schema.Schema {
return r.schema
}
func (r *SourceResource[T]) ConvertToTerraformModel(component *reflect.Value) (*reflect.Value, error) {
if !component.CanInterface() {
return nil, errors.New("component Value does not contain an interfaceable type")
}
source, ok := component.Interface().(Source)
if !ok {
return nil, errors.New("component Value cannot be cast to Source")
}
var model T
r.toModelFunc(&model, &source)
res := reflect.ValueOf(model)
return &res, nil
}
// Configure implements resource.ResourceWithConfigure.
func (r *SourceResource[T]) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Data Source Configure Type",
fmt.Sprintf("Expected client.Client, got: %T. Please report this issue to Mezmo.", req.ProviderData),
)
return
}
r.client = client
}
// Create implements resource.Resource.
func (r *SourceResource[T]) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Retrieve values from plan
var plan T
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
component, dd := r.fromModelFunc(&plan, nil)
if setDiagnosticsHasError(dd, &resp.Diagnostics) {
return
}
if os.Getenv("DEBUG_SOURCE") == "1" {
PrintJSON("----- Destination TO Create api ---", component)
}
stored, err := r.client.CreateSource(r.getPipelineIdFunc(&plan).ValueString(), component)
if err != nil {
resp.Diagnostics.AddError(
"Error creating source",
"Could not create source, unexpected error: "+err.Error(),
)
return
}
if os.Getenv("DEBUG_SOURCE") == "1" {
PrintJSON("----- Destination FROM Create api ---", stored)
}
NullifyPlanFields(&plan, r.schema)
r.toModelFunc(&plan, stored)
diags = resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
}
// Delete implements resource.Resource.
func (r *SourceResource[T]) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state T
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Delete existing order
err := r.client.DeleteSource(r.getPipelineIdFunc(&state).ValueString(), r.getIdFunc(&state).ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Error Deleting Source",
"Could not source, unexpected error: "+err.Error(),
)
return
}
}
// Metadata implements resource.Resource.
func (r *SourceResource[T]) Metadata(_ context.Context, _ resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = r.TypeName()
}
// Read implements resource.Resource.
func (r *SourceResource[T]) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
// Get current state
var state T
if diags := req.State.Get(ctx, &state); setDiagnosticsHasError(diags, &resp.Diagnostics) {
return
}
component, err := r.client.Source(r.getPipelineIdFunc(&state).ValueString(), r.getIdFunc(&state).ValueString())
// force re-creation of manually deleted resources
if client.IsNotFoundError(err) {
resp.State.RemoveResource(ctx)
return
}
if err != nil {
resp.Diagnostics.AddError(
"Error Reading Source",
fmt.Sprintf("Could not read source with id %s and pipeline_id %s: %s",
r.getIdFunc(&state), r.getPipelineIdFunc(&state), err.Error()),
)
return
}
NullifyPlanFields(&state, r.schema)
r.toModelFunc(&state, component)
diags := resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
}
// Update implements resource.Resource.
func (r *SourceResource[T]) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Retrieve values from plan
var plan T
if diags := req.Plan.Get(ctx, &plan); setDiagnosticsHasError(diags, &resp.Diagnostics) {
return
}
var state T
if diags := req.State.Get(ctx, &state); setDiagnosticsHasError(diags, &resp.Diagnostics) {
return
}
component, dd := r.fromModelFunc(&plan, &state)
if setDiagnosticsHasError(dd, &resp.Diagnostics) {
return
}
if os.Getenv("DEBUG_SOURCE") == "1" {
PrintJSON("----- Destination TO Update api ---", component)
}
stored, err := r.client.UpdateSource(r.getPipelineIdFunc(&state).ValueString(), component)
if err != nil {
resp.Diagnostics.AddError(
"Error Updating Source",
"Could not updated source, unexpected error: "+err.Error(),
)
return
}
if os.Getenv("DEBUG_SOURCE") == "1" {
PrintJSON("----- Destination FROM Update api ---", stored)
}
NullifyPlanFields(&plan, r.schema)
r.toModelFunc(&plan, stored)
diags := resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
}
// Schema implements resource.Resource.
func (r *SourceResource[T]) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = r.schema
}
func (r *SourceResource[T]) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.Split(req.ID, "/")
if len(parts) != 2 {
resp.Diagnostics.AddError(
"Malformed Resource Import Id",
fmt.Sprintf(
"The source resource import id needs to be in the form of <pipeline id>/<source id>. The "+
"input \"%s\" did not contain two parts after parsing the id.",
req.ID,
),
)
return
}
pipelineId := strings.TrimSpace(parts[0])
if pipelineId == "" {
resp.Diagnostics.AddError(
"Resource Import Id Missing Pipeline Id Part",
"The pipeline id specified only contained whitespace.",
)
}
nodeId := strings.TrimSpace(parts[1])
if nodeId == "" {
resp.Diagnostics.AddError(
"Resource Import Id Missing Source Id Part",
"The source id specified only contained whitespace",
)
}
if !resp.Diagnostics.HasError() {
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), nodeId)...)
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("pipeline_id"), pipelineId)...)
}
}