-
Notifications
You must be signed in to change notification settings - Fork 1
/
log_binding_resource.go
346 lines (297 loc) · 10.6 KB
/
log_binding_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
package provider
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"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/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
openapiclient "github.com/impart-security/terraform-provider-impart/internal/client"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &logBindingResource{}
_ resource.ResourceWithConfigure = &logBindingResource{}
_ resource.ResourceWithImportState = &logBindingResource{}
)
// NewLogBindingResource creates log binding resource.
func NewLogBindingResource() resource.Resource {
return &logBindingResource{}
}
// logBindingResource is the resource implementation for log bindins.
type logBindingResource struct {
client *impartAPIClient
}
// logBindingResourceModel maps the resource schema data.
type logBindingResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
SpecID types.String `tfsdk:"spec_id"`
LogstreamID types.String `tfsdk:"logstream_id"`
Pattern types.String `tfsdk:"pattern"`
PatternType types.String `tfsdk:"pattern_type"`
}
// Configure adds the provider configured client to the resource.
func (r *logBindingResource) Configure(ctx context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*impartAPIClient)
if !ok {
tflog.Error(ctx, "Unable to prepare the client")
return
}
r.client = client
}
// Metadata returns the resource type name.
func (r *logBindingResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_log_binding"
}
// Schema defines the schema for the resource.
func (r *logBindingResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manage a log binding.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Identifier for this log binding.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
Description: "The name for this log binding.",
Required: true,
},
"spec_id": schema.StringAttribute{
Description: "The specification id.",
Required: true,
},
"pattern": schema.StringAttribute{
Description: "The grok/json pattern for this log binding.",
Required: true,
},
"pattern_type": schema.StringAttribute{
Description: "The pattern type for this log binding. Accepted values: grok, json",
Required: true,
},
"logstream_id": schema.StringAttribute{
Description: "The logstream id for this log binding.",
Optional: true,
},
},
}
}
func (r *logBindingResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// Create a new resource.
func (r *logBindingResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
tflog.Debug(ctx, "Preparing to create the log binding resource")
// Retrieve values from plan
var plan logBindingResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
logstreamID := plan.LogstreamID.ValueString()
bindingResponse, _, err := r.client.LogBindingsAPI.CreateLogBinding(ctx, r.client.OrgID).LogBindingPostBody(openapiclient.LogBindingPostBody{
Name: plan.Name.ValueString(),
SpecId: plan.SpecID.ValueString(),
Pattern: base64.StdEncoding.EncodeToString([]byte(plan.Pattern.ValueString())),
PatternType: plan.PatternType.ValueString(),
LogstreamId: &logstreamID,
}).Execute()
if err != nil {
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to create the log binding",
message,
)
return
}
// Map response body to model
plan.ID = types.StringValue(bindingResponse.Id)
plan.Name = types.StringValue(bindingResponse.Name)
plan.SpecID = types.StringValue(bindingResponse.SpecId)
pattern, err := base64.StdEncoding.DecodeString(bindingResponse.Pattern)
if err != nil {
resp.Diagnostics.AddError(
"Unable to base64 decode the pattern",
err.Error(),
)
}
plan.Pattern = types.StringValue(string(pattern))
if logstreamID != "" {
plan.LogstreamID = types.StringValue(bindingResponse.LogstreamId)
}
// Set state to fully populated data
diags = resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Created the log binding resource", map[string]any{"success": true})
}
// Read resource information.
func (r *logBindingResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
tflog.Debug(ctx, "Preparing to read the log binding resource")
// Get current state
var state logBindingResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
logstreamID := state.LogstreamID.ValueString()
bindingResponse, httpResp, err := r.client.LogBindingsAPI.GetLogBinding(ctx, r.client.OrgID, state.ID.ValueString()).Execute()
if err != nil {
// Treat HTTP 404 Not Found status as a signal to remove/recreate resource
if httpResp.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to read the log binding",
message,
)
return
}
// Map response body to model
state = logBindingResourceModel{
ID: types.StringValue(bindingResponse.Id),
Name: types.StringValue(bindingResponse.Name),
SpecID: types.StringValue(bindingResponse.SpecId),
PatternType: types.StringValue(bindingResponse.PatternType),
}
if logstreamID != "" {
state.LogstreamID = types.StringValue(bindingResponse.LogstreamId)
}
pattern, err := base64.StdEncoding.DecodeString(bindingResponse.Pattern)
if err != nil {
resp.Diagnostics.AddError(
"Unable to base64 decode the pattern",
err.Error(),
)
}
state.Pattern = types.StringValue(string(pattern))
// Set refreshed state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Finished reading the log binding resource", map[string]any{"success": true})
}
func (r *logBindingResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
tflog.Debug(ctx, "Preparing to update the log binding resource")
// Retrieve values from plan
var plan logBindingResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
logstreamId := plan.ID.ValueString()
if !plan.LogstreamID.IsNull() {
logstreamId = plan.LogstreamID.ValueString()
}
specRequest := r.client.LogBindingsAPI.UpdateLogBinding(ctx, r.client.OrgID, plan.ID.ValueString()).
LogBindingPutBody(openapiclient.LogBindingPutBody{
Name: plan.Name.ValueString(),
SpecId: plan.SpecID.ValueString(),
Pattern: base64.StdEncoding.EncodeToString([]byte(plan.Pattern.ValueString())),
LogstreamId: logstreamId,
PatternType: plan.PatternType.ValueString(),
})
// update the log binding
logBindingResponse, _, err := specRequest.Execute()
if err != nil {
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to update the log binding",
message,
)
return
}
// Overwrite the log binding with refreshed state
state := logBindingResourceModel{
ID: types.StringValue(logBindingResponse.Id),
Name: types.StringValue(logBindingResponse.Name),
Pattern: types.StringValue(logBindingResponse.Pattern),
SpecID: types.StringValue(logBindingResponse.SpecId),
PatternType: types.StringValue(logBindingResponse.PatternType),
}
pattern, err := base64.StdEncoding.DecodeString(logBindingResponse.Pattern)
if err != nil {
resp.Diagnostics.AddError(
"Unable to base64 decode the pattern",
err.Error(),
)
}
state.Pattern = types.StringValue(string(pattern))
// update state if logstream id was set
if !plan.LogstreamID.IsNull() {
state.LogstreamID = types.StringValue(logBindingResponse.LogstreamId)
}
// Set refreshed state
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Updated the log binding resource", map[string]any{"success": true})
}
func (r *logBindingResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
tflog.Debug(ctx, "Preparing to delete the log binding resource")
// Retrieve values from state
var state logBindingResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// delete the log binding
_, err := r.client.LogBindingsAPI.DeleteLogBinding(ctx, r.client.OrgID, state.ID.ValueString()).Execute()
if err != nil {
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to delete the log binding",
message,
)
return
}
tflog.Debug(ctx, "Deleted the log binding resource", map[string]any{"success": true})
}
func (r logBindingResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
var data logBindingResourceModel
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
if data.PatternType.ValueString() != "json" && data.PatternType.ValueString() != "grok" {
resp.Diagnostics.AddError(
"Invalid pattern_type",
"Accepted values: grok, json",
)
}
}