-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathparameter.go
606 lines (567 loc) · 18.5 KB
/
parameter.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
package provider
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"github.com/google/uuid"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/mitchellh/mapstructure"
"golang.org/x/xerrors"
)
type Option struct {
Name string
Description string
Value string
Icon string
}
type Validation struct {
Min int
MinDisabled bool `mapstructure:"min_disabled"`
Max int
MaxDisabled bool `mapstructure:"max_disabled"`
Monotonic string
Regex string
Error string
}
const (
ValidationMonotonicIncreasing = "increasing"
ValidationMonotonicDecreasing = "decreasing"
)
type Parameter struct {
Value string
Name string
DisplayName string `mapstructure:"display_name"`
Description string
Type OptionType
FormType ParameterFormType
Mutable bool
Default string
Icon string
Option []Option
Validation []Validation
Optional bool
Order int
Ephemeral bool
}
func parameterDataSource() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
Description: "Use this data source to configure editable options for workspaces.",
ReadContext: func(ctx context.Context, rd *schema.ResourceData, i interface{}) diag.Diagnostics {
rd.SetId(uuid.NewString())
fixedValidation, err := fixValidationResourceData(rd.GetRawConfig(), rd.Get("validation"))
if err != nil {
return diag.FromErr(err)
}
err = rd.Set("validation", fixedValidation)
if err != nil {
return diag.FromErr(err)
}
var parameter Parameter
err = mapstructure.Decode(struct {
Value interface{}
Name interface{}
DisplayName interface{}
Description interface{}
Type interface{}
FormType interface{}
Mutable interface{}
Default interface{}
Icon interface{}
Option interface{}
Validation interface{}
Optional interface{}
Order interface{}
Ephemeral interface{}
}{
Value: rd.Get("value"),
Name: rd.Get("name"),
DisplayName: rd.Get("display_name"),
Description: rd.Get("description"),
Type: rd.Get("type"),
FormType: rd.Get("form_type"),
Mutable: rd.Get("mutable"),
Default: rd.Get("default"),
Icon: rd.Get("icon"),
Option: rd.Get("option"),
Validation: fixedValidation,
Optional: func() bool {
// This hack allows for checking if the "default" field is present in the .tf file.
// If "default" is missing or is "null", then it means that this field is required,
// and user must provide a value for it.
val := !rd.GetRawConfig().AsValueMap()["default"].IsNull()
rd.Set("optional", val)
return val
}(),
Order: rd.Get("order"),
Ephemeral: rd.Get("ephemeral"),
}, ¶meter)
if err != nil {
return diag.Errorf("decode parameter: %s", err)
}
var value string
if parameter.Default != "" {
err := valueIsType(parameter.Type, parameter.Default, cty.Path{cty.GetAttrStep{Name: "default"}})
if err != nil {
return err
}
value = parameter.Default
}
envValue, ok := os.LookupEnv(ParameterEnvironmentVariable(parameter.Name))
if ok {
value = envValue
}
rd.Set("value", value)
if !parameter.Mutable && parameter.Ephemeral {
return diag.Errorf("parameter can't be immutable and ephemeral")
}
if !parameter.Optional && parameter.Ephemeral {
return diag.Errorf("ephemeral parameter requires the default property")
}
// TODO: Should we move this into the Valid() function on
// Parameter?
if len(parameter.Validation) == 1 {
validation := ¶meter.Validation[0]
err = validation.Valid(parameter.Type, value)
if err != nil {
return diag.FromErr(err)
}
}
// Validate options
_, parameter.FormType, err = ValidateFormType(parameter.Type, len(parameter.Option), parameter.FormType)
if err != nil {
return singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: "Invalid form_type for parameter",
Detail: err.Error(),
AttributePath: cty.Path{cty.GetAttrStep{Name: "form_type"}},
})
}
// Set the form_type back in case the value was changed.
// Eg via a default. If a user does not specify, a default value
// is used and saved.
rd.Set("form_type", parameter.FormType)
diags := parameter.Valid()
if diags.HasError() {
return diags
}
return nil
},
Schema: map[string]*schema.Schema{
"value": {
Type: schema.TypeString,
Computed: true,
Description: "The output value of the parameter.",
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the parameter. If this is changed, developers will be re-prompted for a new value.",
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: "The displayed name of the parameter as it will appear in the interface.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "Describe what this parameter does.",
},
"type": {
Type: schema.TypeString,
Default: "string",
Optional: true,
ValidateFunc: validation.StringInSlice(toStrings(OptionTypes()), false),
Description: "The type of this parameter. Must be one of: `\"number\"`, `\"string\"`, `\"bool\"`, or `\"list(string)\"`.",
},
"form_type": {
Type: schema.TypeString,
Default: ParameterFormTypeDefault,
Optional: true,
ValidateFunc: validation.StringInSlice(toStrings(ParameterFormTypes()), false),
Description: fmt.Sprintf("The type of this parameter. Must be one of: [%s].", strings.Join(toStrings(ParameterFormTypes()), ", ")),
},
"styling": {
Type: schema.TypeString,
Default: `{}`,
Description: "JSON encoded string containing the metadata for controlling the appearance of this parameter in the UI. " +
"This option is purely cosmetic and does not affect the function of the parameter in terraform.",
Optional: true,
},
"mutable": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether this value can be changed after workspace creation. This can be destructive for values like region, so use with caution!",
},
"default": {
Type: schema.TypeString,
Optional: true,
Description: "A default value for the parameter.",
},
"icon": {
Type: schema.TypeString,
Description: "A URL to an icon that will display in the dashboard. View built-in " +
"icons [here](https://github.com/coder/coder/tree/main/site/static/icon). Use a " +
"built-in icon with `\"${data.coder_workspace.me.access_url}/icon/<path>\"`.",
ForceNew: true,
Optional: true,
ValidateFunc: func(i interface{}, s string) ([]string, []error) {
_, err := url.Parse(s)
if err != nil {
return nil, []error{err}
}
return nil, nil
},
},
"option": {
Type: schema.TypeList,
Description: "Each `option` block defines a value for a user to select from.",
ForceNew: true,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Description: "The display name of this value in the UI.",
ForceNew: true,
Required: true,
},
"description": {
Type: schema.TypeString,
Description: "Describe what selecting this value does.",
ForceNew: true,
Optional: true,
},
"value": {
Type: schema.TypeString,
Description: "The value of this option set on the parameter if selected.",
ForceNew: true,
Required: true,
},
"icon": {
Type: schema.TypeString,
Description: "A URL to an icon that will display in the dashboard. View built-in " +
"icons [here](https://github.com/coder/coder/tree/main/site/static/icon). Use a " +
"built-in icon with `\"${data.coder_workspace.me.access_url}/icon/<path>\"`.",
ForceNew: true,
Optional: true,
ValidateFunc: func(i interface{}, s string) ([]string, []error) {
_, err := url.Parse(s)
if err != nil {
return nil, []error{err}
}
return nil, nil
},
},
},
},
},
"validation": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Description: "Validate the input of a parameter.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"min": {
Type: schema.TypeInt,
Optional: true,
Description: "The minimum of a number parameter.",
},
"min_disabled": {
Type: schema.TypeBool,
Computed: true,
Description: "Helper field to check if min is present",
},
"max": {
Type: schema.TypeInt,
Optional: true,
Description: "The maximum of a number parameter.",
},
"max_disabled": {
Type: schema.TypeBool,
Computed: true,
Description: "Helper field to check if max is present",
},
"monotonic": {
Type: schema.TypeString,
Optional: true,
Description: "Number monotonicity, either increasing or decreasing.",
},
"regex": {
Type: schema.TypeString,
ConflictsWith: []string{"validation.0.min", "validation.0.max", "validation.0.monotonic"},
Description: "A regex for the input parameter to match against.",
Optional: true,
},
"error": {
Type: schema.TypeString,
Optional: true,
Description: "An error message to display if the value breaks the validation rules. The following placeholders are supported: {max}, {min}, and {value}.",
},
},
},
},
"optional": {
Type: schema.TypeBool,
Computed: true,
Description: "Whether this value is optional.",
},
"order": {
Type: schema.TypeInt,
Optional: true,
Description: "The order determines the position of a template parameter in the UI/CLI presentation. The lowest order is shown first and parameters with equal order are sorted by name (ascending order).",
},
"ephemeral": {
Type: schema.TypeBool,
Default: false,
Optional: true,
Description: "The value of an ephemeral parameter will not be preserved between consecutive workspace builds.",
},
},
}
}
func fixValidationResourceData(rawConfig cty.Value, validation interface{}) (interface{}, error) {
// Read validation from raw config
rawValidation, ok := rawConfig.AsValueMap()["validation"]
if !ok {
return validation, nil // no validation rules, nothing to fix
}
rawValidationArr := rawValidation.AsValueSlice()
if len(rawValidationArr) == 0 {
return validation, nil // no validation rules, nothing to fix
}
rawValidationRule := rawValidationArr[0].AsValueMap()
// Load validation from resource data
vArr, ok := validation.([]interface{})
if !ok {
return nil, xerrors.New("validation should be an array")
}
if len(vArr) == 0 {
return validation, nil // no validation rules, nothing to fix
}
validationRule, ok := vArr[0].(map[string]interface{})
if !ok {
return nil, xerrors.New("validation rule should be a map")
}
validationRule["min_disabled"] = rawValidationRule["min"].IsNull()
validationRule["max_disabled"] = rawValidationRule["max"].IsNull()
return vArr, nil
}
func valueIsType(typ OptionType, value string, attrPath cty.Path) diag.Diagnostics {
switch typ {
case OptionTypeNumber:
_, err := strconv.ParseFloat(value, 64)
if err != nil {
return diag.Errorf("%q is not a number", value)
}
case OptionTypeBoolean:
_, err := strconv.ParseBool(value)
if err != nil {
return diag.Errorf("%q is not a bool", value)
}
case OptionTypeListString:
_, diags := valueIsListString(value, attrPath)
if diags.HasError() {
return diags
}
case OptionTypeString:
// Anything is a string!
default:
return diag.Errorf("invalid type %q", typ)
}
return nil
}
func (v *Parameter) Valid() diag.Diagnostics {
// optionType might differ from parameter.Type. This is ok, and parameter.Type
// should be used for the value type, and optionType for options.
optionType, _, err := ValidateFormType(v.Type, len(v.Option), v.FormType)
if err != nil {
return singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: "Invalid form_type for parameter",
Detail: err.Error(),
AttributePath: cty.Path{cty.GetAttrStep{Name: "form_type"}},
})
}
optionNames := map[string]interface{}{}
optionValues := map[string]interface{}{}
if len(v.Option) > 0 {
for _, option := range v.Option {
_, exists := optionNames[option.Name]
if exists {
return singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: "Option names must be unique.",
Detail: fmt.Sprintf("multiple options found with the same name %q", option.Name),
})
}
_, exists = optionValues[option.Value]
if exists {
return singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: "Option values must be unique.",
Detail: fmt.Sprintf("multiple options found with the same value %q", option.Value),
})
}
diags := valueIsType(optionType, option.Value, cty.Path{})
if diags.HasError() {
return diags
}
optionValues[option.Value] = nil
optionNames[option.Name] = nil
}
}
if v.Default != "" && len(v.Option) > 0 {
if v.Type == OptionTypeListString && optionType == OptionTypeString {
// If the type is list(string) and optionType is string, we have
// to ensure all elements of the default exist as options.
defaultValues, diags := valueIsListString(v.Default, cty.Path{cty.GetAttrStep{Name: "default"}})
if diags.HasError() {
return diags
}
// missing is used to construct a more helpful error message
var missing []string
for _, defaultValue := range defaultValues {
_, defaultIsValid := optionValues[defaultValue]
if !defaultIsValid {
missing = append(missing, defaultValue)
}
}
if len(missing) > 0 {
return singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: "Default values must be a valid option",
Detail: fmt.Sprintf(
"default value %q is not a valid option, values %q are missing from the options",
v.Default, strings.Join(missing, ", "),
),
AttributePath: cty.Path{cty.GetAttrStep{Name: "default"}},
})
}
} else {
_, defaultIsValid := optionValues[v.Default]
if !defaultIsValid {
return singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: "Default value must be a valid option",
Detail: fmt.Sprintf("the value %q must be defined as one of options", v.Default),
AttributePath: cty.Path{cty.GetAttrStep{Name: "default"}},
})
}
}
}
return nil
}
func (v *Validation) Valid(typ OptionType, value string) error {
if typ != OptionTypeNumber {
if !v.MinDisabled {
return fmt.Errorf("a min cannot be specified for a %s type", typ)
}
if !v.MaxDisabled {
return fmt.Errorf("a max cannot be specified for a %s type", typ)
}
if v.Monotonic != "" {
return fmt.Errorf("monotonic validation can only be specified for number types, not %s types", typ)
}
}
if typ != OptionTypeString && v.Regex != "" {
return fmt.Errorf("a regex cannot be specified for a %s type", typ)
}
switch typ {
case OptionTypeBoolean:
if value != "true" && value != "false" {
return fmt.Errorf(`boolean value can be either "true" or "false"`)
}
return nil
case OptionTypeString:
if v.Regex == "" {
return nil
}
regex, err := regexp.Compile(v.Regex)
if err != nil {
return fmt.Errorf("compile regex %q: %s", regex, err)
}
if v.Error == "" {
return fmt.Errorf("an error must be specified with a regex validation")
}
matched := regex.MatchString(value)
if !matched {
return fmt.Errorf("%s (value %q does not match %q)", v.Error, value, regex)
}
case OptionTypeNumber:
num, err := strconv.Atoi(value)
if err != nil {
return takeFirstError(v.errorRendered(value), fmt.Errorf("value %q is not a number", value))
}
if !v.MinDisabled && num < v.Min {
return takeFirstError(v.errorRendered(value), fmt.Errorf("value %d is less than the minimum %d", num, v.Min))
}
if !v.MaxDisabled && num > v.Max {
return takeFirstError(v.errorRendered(value), fmt.Errorf("value %d is more than the maximum %d", num, v.Max))
}
if v.Monotonic != "" && v.Monotonic != ValidationMonotonicIncreasing && v.Monotonic != ValidationMonotonicDecreasing {
return fmt.Errorf("number monotonicity can be either %q or %q", ValidationMonotonicIncreasing, ValidationMonotonicDecreasing)
}
case OptionTypeListString:
var listOfStrings []string
err := json.Unmarshal([]byte(value), &listOfStrings)
if err != nil {
return fmt.Errorf("value %q is not valid list of strings", value)
}
}
return nil
}
func valueIsListString(value string, path cty.Path) ([]string, diag.Diagnostics) {
var items []string
err := json.Unmarshal([]byte(value), &items)
if err != nil {
return nil, singleDiag(diag.Diagnostic{
Severity: diag.Error,
Summary: fmt.Sprintf("When using list(string) type, value must be a json encoded list of strings"),
Detail: fmt.Sprintf("value %q is not a valid list of strings", value),
AttributePath: path,
})
}
return items, nil
}
// ParameterEnvironmentVariable returns the environment variable to specify for
// a parameter by it's name. It's hashed because spaces and special characters
// can be used in parameter names that may not be valid in env vars.
func ParameterEnvironmentVariable(name string) string {
sum := sha256.Sum256([]byte(name))
return "CODER_PARAMETER_" + hex.EncodeToString(sum[:])
}
func takeFirstError(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return xerrors.Errorf("developer error: error message is not provided")
}
func (v *Validation) errorRendered(value string) error {
if v.Error == "" {
return nil
}
r := strings.NewReplacer(
"{min}", fmt.Sprintf("%d", v.Min),
"{max}", fmt.Sprintf("%d", v.Max),
"{value}", value)
return xerrors.Errorf(r.Replace(v.Error))
}
func singleDiag(diagnostic diag.Diagnostic) diag.Diagnostics {
return diag.Diagnostics{diagnostic}
}