-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
binder_schema.go
613 lines (556 loc) 路 16.4 KB
/
binder_schema.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
607
608
609
610
611
612
613
// Copyright 2016-2020, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package pcl
import (
"fmt"
"strings"
"sync"
"github.com/blang/semver"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/pulumi/pulumi/pkg/v3/codegen"
"github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model"
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/zclconf/go-cty/cty"
)
type packageSchema struct {
schema schema.PackageReference
// These maps map from canonical tokens to actual tokens.
resourceTokenMap map[string]string
functionTokenMap map[string]string
}
type packageOpts struct {
version string
pluginDownloadURL string
}
func (ps *packageSchema) LookupFunction(token string) (*schema.Function, string, bool, error) {
contract.Assert(ps != nil)
schemaToken, ok := ps.functionTokenMap[token]
if !ok {
token = canonicalizeToken(token, ps.schema)
schemaToken, ok = ps.functionTokenMap[token]
if !ok {
return nil, "", false, nil
}
}
fn, ok, err := ps.schema.Functions().Get(schemaToken)
return fn, token, ok, err
}
func (ps *packageSchema) LookupResource(token string) (*schema.Resource, string, bool, error) {
contract.Assert(ps != nil)
schemaToken, ok := ps.resourceTokenMap[token]
if !ok {
token = canonicalizeToken(token, ps.schema)
schemaToken, ok = ps.resourceTokenMap[token]
if !ok {
return nil, "", false, nil
}
}
res, ok, err := ps.schema.Resources().Get(schemaToken)
return res, token, ok, err
}
type PackageInfo struct {
name string
version string
}
type PackageCache struct {
m sync.RWMutex
// cache by (name, version)
entries map[PackageInfo]*packageSchema
}
func NewPackageCache() *PackageCache {
return &PackageCache{
entries: map[PackageInfo]*packageSchema{},
}
}
func (c *PackageCache) getPackageSchema(pkg PackageInfo) (*packageSchema, bool) {
c.m.RLock()
defer c.m.RUnlock()
schema, ok := c.entries[pkg]
return schema, ok
}
// loadPackageSchema loads the schema for a given package by loading the corresponding provider and calling its
// GetSchema method.
// If a version is passed in, the cache will be bypassed and the package will be reloaded.
func (c *PackageCache) loadPackageSchema(loader schema.Loader, name, version string) (*packageSchema, error) {
pkgInfo := PackageInfo{
name: name,
version: version,
}
if s, ok := c.getPackageSchema(pkgInfo); ok {
return s, nil
}
var versionSemver *semver.Version
if v, err := semver.Make(version); err == nil {
versionSemver = &v
}
pkg, err := schema.LoadPackageReference(loader, name, versionSemver)
if err != nil {
return nil, err
}
resourceTokenMap := map[string]string{}
for it := pkg.Resources().Range(); it.Next(); {
resourceTokenMap[canonicalizeToken(it.Token(), pkg)] = it.Token()
}
functionTokenMap := map[string]string{}
for it := pkg.Functions().Range(); it.Next(); {
functionTokenMap[canonicalizeToken(it.Token(), pkg)] = it.Token()
}
schema := &packageSchema{
schema: pkg,
resourceTokenMap: resourceTokenMap,
functionTokenMap: functionTokenMap,
}
c.m.Lock()
defer c.m.Unlock()
c.entries[pkgInfo] = schema
return schema, nil
}
// canonicalizeToken converts a Pulumi token into its canonical "pkg:module:member" form.
func canonicalizeToken(tok string, pkg schema.PackageReference) string {
_, _, member, _ := DecomposeToken(tok, hcl.Range{})
return fmt.Sprintf("%s:%s:%s", pkg.Name(), pkg.TokenToModule(tok), member)
}
// getPkgOpts gets the package options from an unbound resource node.
func (b *binder) getPkgOpts(node *Resource) packageOpts {
node.VariableType = model.NewObjectType(map[string]model.Type{
"id": model.NewOutputType(model.StringType),
"urn": model.NewOutputType(model.StringType),
})
var rangeKey, rangeValue model.Type
for _, block := range node.syntax.Body.Blocks {
if block.Type == "options" {
if rng, hasRange := block.Body.Attributes["range"]; hasRange {
expr, _ := model.BindExpression(rng.Expr, b.root, b.tokens, b.options.modelOptions()...)
typ := model.ResolveOutputs(expr.Type())
rk, rv, _ := model.GetCollectionTypes(typ, rng.Range())
rangeKey, rangeValue = rk, rv
}
}
}
scopes := newResourceScopes(b.root, node, rangeKey, rangeValue)
block, _ := model.BindBlock(node.syntax, scopes, b.tokens, b.options.modelOptions()...)
var options *model.Block
for _, item := range block.Body.Items {
if item, ok := item.(*model.Block); ok && item.Type == "options" {
options = item
break
}
}
pkgOpts := packageOpts{}
// Typecheck the options block.
if options != nil {
resourceOptions := &ResourceOptions{}
for _, item := range options.Body.Items {
switch item := item.(type) {
case *model.Attribute:
switch item.Name {
case "version":
pkgOpts.version = modelExprToString(&item.Value)
case "pluginDownloadURL":
pkgOpts.pluginDownloadURL = modelExprToString(&item.Value)
}
}
}
node.Options = resourceOptions
}
return pkgOpts
}
// loadReferencedPackageSchemas loads the schemas for any packages referenced by a given node.
func (b *binder) loadReferencedPackageSchemas(n Node) error {
var pkgOpts packageOpts
packageNames := codegen.StringSet{}
if r, ok := n.(*Resource); ok {
token, tokenRange := getResourceToken(r)
packageName, mod, name, _ := DecomposeToken(token, tokenRange)
if mod == "providers" {
packageNames.Add(name)
} else {
packageNames.Add(packageName)
}
pkgOpts = b.getPkgOpts(r)
}
diags := hclsyntax.VisitAll(n.SyntaxNode(), func(node hclsyntax.Node) hcl.Diagnostics {
call, ok := node.(*hclsyntax.FunctionCallExpr)
if !ok {
return nil
}
token, tokenRange, ok := getInvokeToken(call)
if !ok {
return nil
}
packageName, mod, name, _ := DecomposeToken(token, tokenRange)
if packageName != pulumiPackage {
packageNames.Add(packageName)
} else if mod == "providers" {
packageNames.Add(name)
}
return nil
})
contract.Assert(len(diags) == 0)
for _, name := range packageNames.SortedValues() {
if _, ok := b.referencedPackages[name]; ok && pkgOpts.version == "" || name == "" {
continue
}
pkg, err := b.options.packageCache.loadPackageSchema(b.options.loader, name, pkgOpts.version)
if err != nil {
return err
}
b.referencedPackages[name] = pkg.schema
}
return nil
}
func buildEnumValue(v interface{}) cty.Value {
switch v := v.(type) {
case string:
return cty.StringVal(v)
case bool:
return cty.BoolVal(v)
case int:
return cty.NumberIntVal(int64(v))
case int64:
return cty.NumberIntVal(v)
case float64:
return cty.NumberFloatVal(v)
default:
contract.Failf("Found unexpected constant type %T: %[1]v", v)
return cty.NilVal
}
}
// A marker struct to ensure type safety when retrieving the type from an
// annotated `model.EnumType`.
type enumSchemaType struct {
Type *schema.EnumType
}
// schemaTypeToType converts a schema.Type to a model Type.
func (b *binder) schemaTypeToType(src schema.Type) model.Type {
switch src := src.(type) {
case *schema.ArrayType:
return model.NewListType(b.schemaTypeToType(src.ElementType))
case *schema.MapType:
return model.NewMapType(b.schemaTypeToType(src.ElementType))
case *schema.EnumType:
values := []cty.Value{}
elType := b.schemaTypeToType(src.ElementType)
for _, el := range src.Elements {
values = append(values, buildEnumValue(el.Value))
}
return model.NewEnumType(src.Token, elType, values, enumSchemaType{src})
case *schema.ObjectType:
if t, ok := b.schemaTypes[src]; ok {
return t
}
properties := map[string]model.Type{}
objType := model.NewObjectType(properties, src)
b.schemaTypes[src] = objType
for _, prop := range src.Properties {
typ := prop.Type
if b.options.allowMissingProperties {
typ = &schema.OptionalType{ElementType: typ}
}
properties[prop.Name] = b.schemaTypeToTypeOrConst(typ, prop)
}
return objType
case *schema.TokenType:
t := model.NewOpaqueType(src.Token)
if src.UnderlyingType != nil {
underlyingType := b.schemaTypeToType(src.UnderlyingType)
return model.NewUnionType(t, underlyingType)
}
return t
case *schema.InputType:
elementType := b.schemaTypeToType(src.ElementType)
resolvedElementType := b.schemaTypeToType(codegen.ResolvedType(src.ElementType))
return model.NewUnionTypeAnnotated([]model.Type{elementType, model.NewOutputType(resolvedElementType)}, src)
case *schema.OptionalType:
elementType := b.schemaTypeToType(src.ElementType)
return model.NewOptionalType(elementType)
case *schema.UnionType:
types := make([]model.Type, len(src.ElementTypes))
for i, src := range src.ElementTypes {
types[i] = b.schemaTypeToType(src)
}
if src.Discriminator != "" {
return model.NewUnionTypeAnnotated(types, src)
}
return model.NewUnionType(types...)
case *schema.ResourceType:
if t, ok := b.schemaTypes[src]; ok {
return t
}
properties := map[string]model.Type{}
objType := model.NewObjectType(properties, src)
b.schemaTypes[src] = objType
for _, prop := range src.Resource.Properties {
typ := prop.Type
if !prop.IsRequired() {
typ = &schema.OptionalType{ElementType: typ}
}
properties[prop.Name] = b.schemaTypeToTypeOrConst(typ, prop)
}
return objType
default:
switch src {
case schema.BoolType:
return model.BoolType
case schema.IntType:
return model.IntType
case schema.NumberType:
return model.NumberType
case schema.StringType:
return model.StringType
case schema.ArchiveType:
return ArchiveType
case schema.AssetType:
return AssetType
case schema.JSONType:
fallthrough
case schema.AnyType:
return model.DynamicType
default:
return model.NoneType
}
}
}
func (b *binder) schemaTypeToTypeOrConst(typ schema.Type, prop *schema.Property) model.Type {
t := b.schemaTypeToType(typ)
if prop.ConstValue != nil {
var value cty.Value
switch v := prop.ConstValue.(type) {
case bool:
value = cty.BoolVal(v)
case float64:
value = cty.NumberFloatVal(v)
case string:
value = cty.StringVal(v)
default:
contract.Failf("unexpected constant type %T", v)
}
t = model.NewConstType(t, value)
}
return t
}
var schemaArrayTypes = make(map[schema.Type]*schema.ArrayType)
// GetSchemaForType extracts the schema.Type associated with a model.Type, if any.
//
// The result may be a *schema.UnionType if multiple schema types are associated with the input type.
func GetSchemaForType(t model.Type) (schema.Type, bool) {
switch t := t.(type) {
case *model.ListType:
element, ok := GetSchemaForType(t.ElementType)
if !ok {
return nil, false
}
if t, ok := schemaArrayTypes[element]; ok {
return t, true
}
schemaArrayTypes[element] = &schema.ArrayType{ElementType: element}
return schemaArrayTypes[element], true
case *model.ObjectType:
if len(t.Annotations) == 0 {
return nil, false
}
for _, a := range t.Annotations {
if t, ok := a.(schema.Type); ok {
return t, true
}
}
return nil, false
case *model.OutputType:
return GetSchemaForType(t.ElementType)
case *model.PromiseType:
return GetSchemaForType(t.ElementType)
case *model.UnionType:
for _, a := range t.Annotations {
switch a := a.(type) {
case *schema.UnionType:
return a, true
case *schema.InputType:
return a, true
}
}
schemas := codegen.Set{}
for _, t := range t.ElementTypes {
if s, ok := GetSchemaForType(t); ok {
if union, ok := s.(*schema.UnionType); ok {
for _, s := range union.ElementTypes {
schemas.Add(s)
}
} else {
schemas.Add(s)
}
}
}
if len(schemas) == 0 {
return nil, false
}
schemaTypes := make([]schema.Type, 0, len(schemas))
for t := range schemas {
schemaTypes = append(schemaTypes, t.(schema.Type))
}
if len(schemaTypes) == 1 {
return schemaTypes[0], true
}
return &schema.UnionType{ElementTypes: schemaTypes}, true
case *model.EnumType:
for _, t := range t.Annotations {
if t, ok := t.(enumSchemaType); ok {
contract.Assert(t.Type != nil)
return t.Type, true
}
}
return nil, false
default:
return nil, false
}
}
// GetDiscriminatedUnionObjectMapping calculates a map of type names to object types for a given
// union type.
func GetDiscriminatedUnionObjectMapping(t *model.UnionType) map[string]model.Type {
mapping := map[string]model.Type{}
for _, t := range t.ElementTypes {
k, v := getDiscriminatedUnionObjectItem(t)
mapping[k] = v
}
return mapping
}
func getDiscriminatedUnionObjectItem(t model.Type) (string, model.Type) {
switch t := t.(type) {
case *model.ListType:
return getDiscriminatedUnionObjectItem(t.ElementType)
case *model.ObjectType:
if schemaType, ok := GetSchemaForType(t); ok {
if objType, ok := schemaType.(*schema.ObjectType); ok {
return objType.Token, t
}
}
case *model.OutputType:
return getDiscriminatedUnionObjectItem(t.ElementType)
case *model.PromiseType:
return getDiscriminatedUnionObjectItem(t.ElementType)
}
return "", nil
}
// EnumMember returns the name of the member that matches the given `value`. If
// no member if found, (nil, true) returned. If the query is nonsensical, either
// because no schema is associated with the EnumMember or if the type of value
// mismatches the type of the schema, (nil, false) is returned.
func EnumMember(t *model.EnumType, value cty.Value) (*schema.Enum, bool) {
srcBase, ok := GetSchemaForType(t)
if !ok {
return nil, false
}
src := srcBase.(*schema.EnumType)
switch {
case t.Type.Equals(model.StringType):
s := value.AsString()
for _, el := range src.Elements {
v := el.Value.(string)
if v == s {
return el, true
}
}
return nil, true
case t.Type.Equals(model.NumberType):
f, _ := value.AsBigFloat().Float64()
for _, el := range src.Elements {
if el.Value.(float64) == f {
return el, true
}
}
return nil, true
case t.Type.Equals(model.IntType):
f, _ := value.AsBigFloat().Int64()
for _, el := range src.Elements {
if el.Value.(int64) == f {
return el, true
}
}
return nil, true
default:
return nil, false
}
}
// GenEnum is a helper function when generating an enum.
// Given an enum, and instructions on what to do when you find a known value,
// and an unknown value, return a function that will generate an the given enum
// from the given expression.
//
// This function should probably live in the `codegen` namespace, but cannot
// because of import cycles.
func GenEnum(
t *model.EnumType,
from model.Expression,
safeEnum func(member *schema.Enum),
unsafeEnum func(from model.Expression),
) *hcl.Diagnostic {
known := cty.NilVal
if from, ok := from.(*model.TemplateExpression); ok && len(from.Parts) == 1 {
if from, ok := from.Parts[0].(*model.LiteralValueExpression); ok {
known = from.Value
}
}
if from, ok := from.(*model.LiteralValueExpression); ok {
known = from.Value
}
if known != cty.NilVal {
// If the value is known, but we can't find a member, we should have
// indicated a conversion is impossible when type checking.
member, ok := EnumMember(t, known)
contract.Assertf(ok,
"We have determined %s is a safe enum, which we define as "+
"being able to calculate a member for", t)
if member != nil {
safeEnum(member)
} else {
unsafeEnum(from)
knownVal := strings.Split(strings.Split(known.GoString(), "(")[1], ")")[0]
diag := &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("%v is not a valid value of the enum \"%v\"", knownVal, t.Token),
}
if members := enumMemberValues(t); len(members) > 0 {
diag.Detail = fmt.Sprintf("Valid members are %v", listToString(members))
}
return diag
}
} else {
unsafeEnum(from)
}
return nil
}
func enumMemberValues(t *model.EnumType) []interface{} {
srcBase, ok := GetSchemaForType(t)
if !ok {
return nil
}
src := srcBase.(*schema.EnumType)
members := make([]interface{}, len(src.Elements))
for i, el := range src.Elements {
members[i] = el.Value
}
return members
}
func listToString(l []interface{}) string {
vals := ""
for i, v := range l {
if i == 0 {
vals = fmt.Sprintf("\"%v\"", v)
} else {
vals = fmt.Sprintf("%s, \"%v\"", vals, v)
}
}
return vals
}