-
Notifications
You must be signed in to change notification settings - Fork 1
/
resource_host_info.go
460 lines (400 loc) · 13.7 KB
/
resource_host_info.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package plugin
import (
"context"
"fmt"
"sync"
"time"
"github.com/hashicorp/terraform-plugin-go/tfprotov6"
"github.com/hashicorp/terraform-plugin-go/tftypes"
"github.com/hashicorp-forge/terraform-provider-enos/internal/diags"
"github.com/hashicorp-forge/terraform-provider-enos/internal/remoteflight"
"github.com/hashicorp-forge/terraform-provider-enos/internal/retry"
resource "github.com/hashicorp-forge/terraform-provider-enos/internal/server/resourcerouter"
"github.com/hashicorp-forge/terraform-provider-enos/internal/server/state"
)
type hostInfo struct {
providerConfig *config
mu sync.Mutex
}
var _ resource.Resource = (*hostInfo)(nil)
type hostInfoStateV1 struct {
ID *tfString
Arch *tfString
Distro *tfString
DistroVersion *tfString
Hostname *tfString
Pid1 *tfString
Platform *tfString
PlatformVersion *tfString
Transport *embeddedTransportV1
failureHandlers
}
var _ state.State = (*hostInfoStateV1)(nil)
func newHostInfo() *hostInfo {
return &hostInfo{
providerConfig: newProviderConfig(),
mu: sync.Mutex{},
}
}
func newHostInfoStateV1() *hostInfoStateV1 {
transport := newEmbeddedTransport()
fh := failureHandlers{TransportDebugFailureHandler(transport)}
return &hostInfoStateV1{
ID: newTfString(),
Arch: newTfString(),
Distro: newTfString(),
DistroVersion: newTfString(),
Hostname: newTfString(),
Pid1: newTfString(),
Platform: newTfString(),
PlatformVersion: newTfString(),
// TODO: Add support for determining the default package manager if there is one?
Transport: transport,
failureHandlers: fh,
}
}
func (f *hostInfo) Name() string {
return "enos_host_info"
}
func (f *hostInfo) Schema() *tfprotov6.Schema {
return newHostInfoStateV1().Schema()
}
func (f *hostInfo) SetProviderConfig(providerConfig tftypes.Value) error {
f.mu.Lock()
defer f.mu.Unlock()
return f.providerConfig.FromTerraform5Value(providerConfig)
}
func (f *hostInfo) GetProviderConfig() (*config, error) {
f.mu.Lock()
defer f.mu.Unlock()
return f.providerConfig.Copy()
}
// ValidateResourceConfig is the request Terraform sends when it wants to
// validate the resource's configuration.
func (f *hostInfo) ValidateResourceConfig(ctx context.Context, req tfprotov6.ValidateResourceConfigRequest, res *tfprotov6.ValidateResourceConfigResponse) {
newState := newHostInfoStateV1()
transportUtil.ValidateResourceConfig(ctx, newState, req, res)
}
// UpgradeResourceState is the request Terraform sends when it wants to
// upgrade the resource's state to a new version.
func (f *hostInfo) UpgradeResourceState(ctx context.Context, req tfprotov6.UpgradeResourceStateRequest, res *tfprotov6.UpgradeResourceStateResponse) {
newState := newHostInfoStateV1()
transportUtil.UpgradeResourceState(ctx, newState, req, res)
}
// ReadResource is the request Terraform sends when it wants to get the latest state for the resource.
// We'll exit gracefully if we're unable to read the resource since it's possible that it does not
// yet exist.
func (f *hostInfo) ReadResource(ctx context.Context, req tfprotov6.ReadResourceRequest, res *tfprotov6.ReadResourceResponse) {
select {
case <-ctx.Done():
res.Diagnostics = append(res.Diagnostics, ctxToDiagnostic(ctx))
return
default:
}
currentState := newHostInfoStateV1()
// Make sure we marshal our new state when we return
defer func() {
var err error
res.NewState, err = state.Marshal(currentState)
if err != nil {
res.Diagnostics = append(res.Diagnostics, diags.ErrToDiagnostic("Serialization Error", err))
}
}()
// Try and build a client to read the resource. If we encounter missing preconditions or errors
// then we'll return our state unmodified, eg: whatever was passed in and Unknown values for our
// optional and computed attributes.
transport := transportUtil.ReadUnmarshalAndBuildTransport(ctx, currentState, f, req, res)
if transport == nil {
return
}
client, err := transport.Client(ctx)
if err != nil {
return
}
defer client.Close()
// We actually have a valid transport and hostInfo name. Try and find the hostInfo.
hostInfo, _ := remoteflight.TargetHostInfo(ctx, client, remoteflight.NewTargetRequest(
remoteflight.WithTargetRequestRetryOpts(
retry.WithIntervalFunc(retry.IntervalExponential(2*time.Second)),
retry.WithMaxRetries(3),
),
))
if hostInfo == nil {
// We couldn't find our HostInfo. Set all of our current state attrs to Unknown since we can't read
// it and need to Apply.
currentState.Arch.Unknown = true
currentState.Distro.Unknown = true
currentState.DistroVersion.Unknown = true
currentState.Hostname.Unknown = true
currentState.Pid1.Unknown = true
currentState.Platform.Unknown = true
currentState.PlatformVersion.Unknown = true
return
}
// Update the current state with our hostInfo attrs.
currentState.SetInfo(hostInfo)
}
// ImportResourceState is the request Terraform sends when it wants the provider
// to import one or more resources specified by an ID.
//
// Importing a hostInfo doesn't make a lot of sense but we have to support the
// function regardless. As our only interface is a string ID, supporting this
// without provider level transport configuration would be absurdly difficult.
// Until then this will simply be a no-op. If/When we implement that behavior
// we could probably create use an identier that combines the source and
// destination to import a hostInfo.
func (f *hostInfo) ImportResourceState(ctx context.Context, req tfprotov6.ImportResourceStateRequest, res *tfprotov6.ImportResourceStateResponse) {
newState := newHostInfoStateV1()
transportUtil.ImportResourceState(ctx, newState, req, res)
}
// PlanResourceChange is the request Terraform sends when it is generating a plan
// for the resource and wants the provider's input on what the planned state should be.
func (f *hostInfo) PlanResourceChange(ctx context.Context, req resource.PlanResourceChangeRequest, res *resource.PlanResourceChangeResponse) {
priorState := newHostInfoStateV1()
proposedState := newHostInfoStateV1()
res.PlannedState = proposedState
transportUtil.PlanUnmarshalVerifyAndBuildTransport(ctx, priorState, proposedState, f, req, res)
if diags.HasErrors(res.Diagnostics) {
return
}
// Plan for all unknown computed attributes to be Unknown until after apply.
if _, ok := priorState.ID.Get(); !ok {
proposedState.ID.Unknown = true
}
if _, ok := proposedState.Arch.Get(); !ok {
proposedState.Arch.Unknown = true
}
if _, ok := proposedState.Distro.Get(); !ok {
proposedState.Distro.Unknown = true
}
if _, ok := proposedState.DistroVersion.Get(); !ok {
proposedState.DistroVersion.Unknown = true
}
if _, ok := proposedState.Hostname.Get(); !ok {
proposedState.Hostname.Unknown = true
}
if _, ok := proposedState.Pid1.Get(); !ok {
proposedState.Pid1.Unknown = true
}
if _, ok := proposedState.Platform.Get(); !ok {
proposedState.Platform.Unknown = true
}
if _, ok := proposedState.PlatformVersion.Get(); !ok {
proposedState.PlatformVersion.Unknown = true
}
}
// ApplyResourceChange is the request Terraform sends when it needs to apply a planned set of
// changes to the resource.
func (f *hostInfo) ApplyResourceChange(ctx context.Context, req resource.ApplyResourceChangeRequest, res *resource.ApplyResourceChangeResponse) {
priorState := newHostInfoStateV1()
plannedState := newHostInfoStateV1()
res.NewState = plannedState
transportUtil.ApplyUnmarshalState(ctx, priorState, plannedState, req, res)
if diags.HasErrors(res.Diagnostics) {
return
}
if req.IsDelete() || (!req.IsCreate() && !req.IsUpdate()) {
// nothing to do on delete or when we're not creating or updating.
return
}
transport := transportUtil.ApplyValidatePlannedAndBuildTransport(ctx, plannedState, f, res)
if diags.HasErrors(res.Diagnostics) {
return
}
plannedState.ID.Set("static")
client, err := transport.Client(ctx)
if err != nil {
res.Diagnostics = append(res.Diagnostics, diags.ErrToDiagnostic("Transport Error", err))
return
}
defer client.Close()
hostInfo, err := remoteflight.TargetHostInfo(ctx, client, remoteflight.NewTargetRequest(
remoteflight.WithTargetRequestRetryOpts(
retry.WithIntervalFunc(retry.IntervalExponential(2*time.Second)),
retry.WithMaxRetries(3),
),
))
// Not all platforms can be expected to have all host info. If we get an error return a warning
// diagnostic for now.
if err != nil {
res.Diagnostics = append(res.Diagnostics, diags.ErrToDiagnosticWarn(
"getting target host info",
AttributePathError(
fmt.Errorf("failed to determine host information, due to: %w", err),
"transport",
),
))
}
// Update the current state with our hostInfo attrs.
plannedState.SetInfo(hostInfo)
}
func (s *hostInfoStateV1) SetInfo(i *remoteflight.HostInfo) {
if i == nil {
return
}
// Update the current state with our hostInfo attrs.
if i.Arch != nil {
s.Arch.Set(*i.Arch)
} else {
s.Arch.Set("")
}
if i.Distro != nil {
s.Distro.Set(*i.Distro)
} else {
s.Distro.Set("")
}
if i.DistroVersion != nil {
s.DistroVersion.Set(*i.DistroVersion)
} else {
s.DistroVersion.Set("")
}
if i.Hostname != nil {
s.Hostname.Set(*i.Hostname)
} else {
s.Hostname.Set("")
}
if i.Pid1 != nil {
s.Pid1.Set(*i.Pid1)
} else {
s.Pid1.Set("")
}
if i.Platform != nil {
s.Platform.Set(*i.Platform)
} else {
s.Platform.Set("")
}
if i.PlatformVersion != nil {
s.PlatformVersion.Set(*i.PlatformVersion)
} else {
s.PlatformVersion.Set("")
}
}
// Schema is the hostInfo states Terraform schema.
func (s *hostInfoStateV1) Schema() *tfprotov6.Schema {
return &tfprotov6.Schema{
Version: 1,
Block: &tfprotov6.SchemaBlock{
DescriptionKind: tfprotov6.StringKindMarkdown,
Description: docCaretToBacktick(`
The ^enos_host_info^ resource can be used to determine information about a target host. While it is intended
to be used against SSH targets, if the required utilities are present in a container other transports ought
to work as well.
`),
Attributes: []*tfprotov6.SchemaAttribute{
{
Name: "id",
Type: tftypes.String,
Computed: true,
Description: resourceStaticIDDescription,
},
{
Name: "arch",
Type: tftypes.String,
Computed: true,
Description: "The machine architecture of the target. Equivalent of uname -m",
},
{
Name: "distro",
Type: tftypes.String,
Computed: true,
Description: "The software distribution of the target. Equivalent of /etc/os-release or lsb_release",
},
{
Name: "distro_version",
Type: tftypes.String,
Computed: true,
Description: "The software distribution version of the target. Equivalent of /etc/os-release or lsb_release",
},
{
Name: "hostname",
Type: tftypes.String,
Computed: true,
Description: "The local hostname of the target. Equivalent of uname -n",
},
{
Name: "pid1",
Type: tftypes.String,
Computed: true,
Description: "The process manager of the target. Equivalent of ps -p 1 -c -o command=",
},
{
Name: "platform",
Type: tftypes.String,
Computed: true,
Description: "The platform of the target. Equivalent of uname -s",
},
{
Name: "platform_version",
Type: tftypes.String,
Computed: true,
Description: "The platform version of the target. Equivalent of uname -r",
},
s.Transport.SchemaAttributeTransport(supportsSSH),
},
},
}
}
// Validate validates the configuration. This will validate the source hostInfo
// exists and that the transport configuration is valid.
func (s *hostInfoStateV1) Validate(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
return nil
}
// FromTerraform5Value is a callback to unmarshal from the tftypes.Vault with As().
func (s *hostInfoStateV1) FromTerraform5Value(val tftypes.Value) error {
vals, err := mapAttributesTo(val, map[string]interface{}{
"id": s.ID,
"arch": s.Arch,
"distro": s.Distro,
"distro_version": s.DistroVersion,
"hostname": s.Hostname,
"pid1": s.Pid1,
"platform": s.Platform,
"platform_version": s.PlatformVersion,
})
if err != nil {
return err
}
if vals["transport"].IsKnown() {
return s.Transport.FromTerraform5Value(vals["transport"])
}
return nil
}
// Terraform5Type is the hostInfo state tftypes.Type.
func (s *hostInfoStateV1) Terraform5Type() tftypes.Type {
return tftypes.Object{AttributeTypes: map[string]tftypes.Type{
"id": s.ID.TFType(),
"arch": s.Arch.TFType(),
"distro": s.Distro.TFType(),
"distro_version": s.DistroVersion.TFType(),
"hostname": s.Hostname.TFType(),
"pid1": s.Pid1.TFType(),
"platform": s.Platform.TFType(),
"platform_version": s.PlatformVersion.TFType(),
"transport": s.Transport.Terraform5Type(),
}}
}
// Terraform5Value is the hostInfo state tftypes.Value.
func (s *hostInfoStateV1) Terraform5Value() tftypes.Value {
return tftypes.NewValue(s.Terraform5Type(), map[string]tftypes.Value{
"id": s.ID.TFValue(),
"arch": s.Arch.TFValue(),
"distro": s.Distro.TFValue(),
"distro_version": s.DistroVersion.TFValue(),
"hostname": s.Hostname.TFValue(),
"pid1": s.Pid1.TFValue(),
"platform": s.Platform.TFValue(),
"platform_version": s.PlatformVersion.TFValue(),
"transport": s.Transport.Terraform5Value(),
})
}
// EmbeddedTransport is a pointer to the state's embedded transport.
func (s *hostInfoStateV1) EmbeddedTransport() *embeddedTransportV1 {
return s.Transport
}