/
decode_args.go
344 lines (308 loc) · 10.9 KB
/
decode_args.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
package parse
import (
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/turbot/go-kit/helpers"
"github.com/turbot/pipe-fittings/hclhelpers"
"github.com/turbot/steampipe/pkg/steampipeconfig/modconfig"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/gocty"
)
func decodeArgs(attr *hcl.Attribute, evalCtx *hcl.EvalContext, resource modconfig.QueryProvider) (*modconfig.QueryArgs, []*modconfig.RuntimeDependency, hcl.Diagnostics) {
var runtimeDependencies []*modconfig.RuntimeDependency
var args = modconfig.NewQueryArgs()
var diags hcl.Diagnostics
v, valDiags := attr.Expr.Value(evalCtx)
ty := v.Type()
// determine which diags are runtime dependencies (which we allow) and which are not
if valDiags.HasErrors() {
for _, diag := range diags {
dependency := diagsToDependency(diag)
if dependency == nil || !dependency.IsRuntimeDependency() {
diags = append(diags, diag)
}
}
}
// now diags contains all diags which are NOT runtime dependencies
if diags.HasErrors() {
return nil, nil, diags
}
var err error
switch {
case ty.IsObjectType():
var argMap map[string]any
argMap, runtimeDependencies, err = ctyObjectToArgMap(attr, v, evalCtx)
if err == nil {
err = args.SetArgMap(argMap)
}
case ty.IsTupleType():
var argList []any
argList, runtimeDependencies, err = ctyTupleToArgArray(attr, v)
if err == nil {
err = args.SetArgList(argList)
}
default:
err = fmt.Errorf("'params' property must be either a map or an array")
}
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%s has invalid parameter config", resource.Name()),
Detail: err.Error(),
Subject: &attr.Range,
})
}
return args, runtimeDependencies, diags
}
func ctyTupleToArgArray(attr *hcl.Attribute, val cty.Value) ([]any, []*modconfig.RuntimeDependency, error) {
// convert the attribute to a slice
values := val.AsValueSlice()
// build output array
res := make([]any, len(values))
var runtimeDependencies []*modconfig.RuntimeDependency
for idx, v := range values {
// if the value is unknown, this is a runtime dependency
if !v.IsKnown() {
runtimeDependency, err := identifyRuntimeDependenciesFromArray(attr, idx, modconfig.AttributeArgs)
if err != nil {
return nil, nil, err
}
runtimeDependencies = append(runtimeDependencies, runtimeDependency)
} else {
// decode the value into a go type
val, err := hclhelpers.CtyToGo(v)
if err != nil {
err := fmt.Errorf("invalid value provided for arg #%d: %v", idx, err)
return nil, nil, err
}
res[idx] = val
}
}
return res, runtimeDependencies, nil
}
func ctyObjectToArgMap(attr *hcl.Attribute, val cty.Value, evalCtx *hcl.EvalContext) (map[string]any, []*modconfig.RuntimeDependency, error) {
res := make(map[string]any)
var runtimeDependencies []*modconfig.RuntimeDependency
it := val.ElementIterator()
for it.Next() {
k, v := it.Element()
// decode key
var key string
if err := gocty.FromCtyValue(k, &key); err != nil {
return nil, nil, err
}
// if the value is unknown, this is a runtime dependency
if !v.IsKnown() {
runtimeDependency, err := identifyRuntimeDependenciesFromObject(attr, key, modconfig.AttributeArgs, evalCtx)
if err != nil {
return nil, nil, err
}
runtimeDependencies = append(runtimeDependencies, runtimeDependency)
} else if getWrappedUnknownVal(v) {
runtimeDependency, err := identifyRuntimeDependenciesFromObject(attr, key, modconfig.AttributeArgs, evalCtx)
if err != nil {
return nil, nil, err
}
runtimeDependencies = append(runtimeDependencies, runtimeDependency)
} else {
// decode the value into a go type
val, err := hclhelpers.CtyToGo(v)
if err != nil {
err := fmt.Errorf("invalid value provided for param '%s': %v", key, err)
return nil, nil, err
}
res[key] = val
}
}
return res, runtimeDependencies, nil
}
// TACTICAL - is the cty value an array with a single unknown value
func getWrappedUnknownVal(v cty.Value) bool {
ty := v.Type()
switch {
case ty.IsTupleType():
values := v.AsValueSlice()
if len(values) == 1 && !values[0].IsKnown() {
return true
}
}
return false
}
func identifyRuntimeDependenciesFromObject(attr *hcl.Attribute, targetProperty, parentProperty string, evalCtx *hcl.EvalContext) (*modconfig.RuntimeDependency, error) {
// find the expression for this key
argsExpr, ok := attr.Expr.(*hclsyntax.ObjectConsExpr)
if !ok {
return nil, fmt.Errorf("could not extract runtime dependency for arg %s", targetProperty)
}
for _, item := range argsExpr.Items {
nameCty, valDiags := item.KeyExpr.Value(evalCtx)
if valDiags.HasErrors() {
return nil, fmt.Errorf("could not extract runtime dependency for arg %s", targetProperty)
}
var name string
if err := gocty.FromCtyValue(nameCty, &name); err != nil {
return nil, err
}
if name == targetProperty {
dep, err := getRuntimeDepFromExpression(item.ValueExpr, targetProperty, parentProperty)
if err != nil {
return nil, err
}
return dep, nil
}
}
return nil, fmt.Errorf("could not extract runtime dependency for arg %s - not found in attribute map", targetProperty)
}
func getRuntimeDepFromExpression(expr hcl.Expression, targetProperty, parentProperty string) (*modconfig.RuntimeDependency, error) {
isArray, propertyPath, err := propertyPathFromExpression(expr)
if err != nil {
return nil, err
}
if propertyPath.ItemType == modconfig.BlockTypeInput {
// tactical: validate input dependency
if err := validateInputRuntimeDependency(propertyPath); err != nil {
return nil, err
}
}
ret := &modconfig.RuntimeDependency{
PropertyPath: propertyPath,
ParentPropertyName: parentProperty,
TargetPropertyName: &targetProperty,
IsArray: isArray,
}
return ret, nil
}
func propertyPathFromExpression(expr hcl.Expression) (bool, *modconfig.ParsedPropertyPath, error) {
var propertyPathStr string
var isArray bool
dep_loop:
for {
switch e := expr.(type) {
case *hclsyntax.ScopeTraversalExpr:
propertyPathStr = hclhelpers.TraversalAsString(e.Traversal)
break dep_loop
case *hclsyntax.SplatExpr:
root := hclhelpers.TraversalAsString(e.Source.(*hclsyntax.ScopeTraversalExpr).Traversal)
var suffix string
// if there is a property path, add it
if each, ok := e.Each.(*hclsyntax.RelativeTraversalExpr); ok {
suffix = fmt.Sprintf(".%s", hclhelpers.TraversalAsString(each.Traversal))
}
propertyPathStr = fmt.Sprintf("%s.*%s", root, suffix)
break dep_loop
case *hclsyntax.TupleConsExpr:
// TACTICAL
// handle the case where an arg value is given as a runtime dependency inside an array, for example
// arns = [input.arn]
// this is a common pattern where a runtime depdency gives a scalar value, but an array is needed for the arg
// NOTE: this code only supports a SINGLE item in the array
if len(e.Exprs) != 1 {
return false, nil, fmt.Errorf("unsupported runtime dependency expression - only a single runtime depdency item may be wrapped in an array")
}
isArray = true
expr = e.Exprs[0]
// fall through to rerun loop with updated expr
default:
// unhandled expression type
return false, nil, fmt.Errorf("unexpected runtime dependency expression type")
}
}
propertyPath, err := modconfig.ParseResourcePropertyPath(propertyPathStr)
if err != nil {
return false, nil, err
}
return isArray, propertyPath, nil
}
func identifyRuntimeDependenciesFromArray(attr *hcl.Attribute, idx int, parentProperty string) (*modconfig.RuntimeDependency, error) {
// find the expression for this key
argsExpr, ok := attr.Expr.(*hclsyntax.TupleConsExpr)
if !ok {
return nil, fmt.Errorf("could not extract runtime dependency for arg #%d", idx)
}
for i, item := range argsExpr.Exprs {
if i == idx {
isArray, propertyPath, err := propertyPathFromExpression(item)
if err != nil {
return nil, err
}
// tactical: validate input dependency
if propertyPath.ItemType == modconfig.BlockTypeInput {
if err := validateInputRuntimeDependency(propertyPath); err != nil {
return nil, err
}
}
ret := &modconfig.RuntimeDependency{
PropertyPath: propertyPath,
ParentPropertyName: parentProperty,
TargetPropertyIndex: &idx,
IsArray: isArray,
}
return ret, nil
}
}
return nil, fmt.Errorf("could not extract runtime dependency for arg %d - not found in attribute list", idx)
}
// tactical - if runtime dependency is an input, validate it is of correct format
// TODO - include this with the main runtime dependency validation, when it is rewritten https://github.com/turbot/steampipe/issues/2925
func validateInputRuntimeDependency(propertyPath *modconfig.ParsedPropertyPath) error {
// input references must be of form self.input.<input_name>.value
if propertyPath.Scope != modconfig.RuntimeDependencyDashboardScope {
return fmt.Errorf("could not resolve runtime dependency resource %s", propertyPath.Original)
}
return nil
}
func decodeParam(block *hcl.Block, parseCtx *ModParseContext) (*modconfig.ParamDef, []*modconfig.RuntimeDependency, hcl.Diagnostics) {
def := modconfig.NewParamDef(block)
var runtimeDependencies []*modconfig.RuntimeDependency
content, diags := block.Body.Content(ParamDefBlockSchema)
if attr, exists := content.Attributes["description"]; exists {
moreDiags := gohcl.DecodeExpression(attr.Expr, parseCtx.EvalCtx, &def.Description)
diags = append(diags, moreDiags...)
}
if attr, exists := content.Attributes["default"]; exists {
defaultValue, deps, moreDiags := decodeParamDefault(attr, parseCtx, def.UnqualifiedName)
diags = append(diags, moreDiags...)
if !helpers.IsNil(defaultValue) {
def.SetDefault(defaultValue)
}
runtimeDependencies = deps
}
return def, runtimeDependencies, diags
}
func decodeParamDefault(attr *hcl.Attribute, parseCtx *ModParseContext, paramName string) (any, []*modconfig.RuntimeDependency, hcl.Diagnostics) {
v, diags := attr.Expr.Value(parseCtx.EvalCtx)
if v.IsKnown() {
// convert the raw default into a string representation
val, err := hclhelpers.CtyToGo(v)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%s has invalid default config", paramName),
Detail: err.Error(),
Subject: &attr.Range,
})
return nil, nil, diags
}
return val, nil, nil
}
// so value not known - is there a runtime dependency?
// check for a runtime dependency
runtimeDependency, err := getRuntimeDepFromExpression(attr.Expr, "default", paramName)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%s has invalid parameter default config", paramName),
Detail: err.Error(),
Subject: &attr.Range,
})
return nil, nil, diags
}
if runtimeDependency == nil {
// return the original diags
return nil, nil, diags
}
// so we have a runtime dependency
return nil, []*modconfig.RuntimeDependency{runtimeDependency}, nil
}