-
Notifications
You must be signed in to change notification settings - Fork 43
/
provider.go
1987 lines (1743 loc) · 69.1 KB
/
provider.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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016-2022, 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 tfbridge
import (
"encoding/json"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"unicode"
"github.com/golang/glog"
pbempty "github.com/golang/protobuf/ptypes/empty"
pbstruct "github.com/golang/protobuf/ptypes/struct"
"github.com/hashicorp/go-multierror"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema"
"github.com/pulumi/pulumi/pkg/v3/resource/provider"
"github.com/pulumi/pulumi/sdk/v3/go/common/diag"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource"
"github.com/pulumi/pulumi/sdk/v3/go/common/resource/plugin"
"github.com/pulumi/pulumi/sdk/v3/go/common/tokens"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/cmdutil"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/rpcutil/rpcerror"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge/info"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge/typechecker"
shim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim/walk"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/x/muxer"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/logging"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/metadata"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/propertyvalue"
)
type providerOptions struct {
defaultZeroSchemaVersion bool
enableAccurateBridgePreview bool
}
type providerOption func(providerOptions) (providerOptions, error)
func WithDefaultZeroSchemaVersion() providerOption { //nolint:revive
return func(opts providerOptions) (providerOptions, error) {
opts.defaultZeroSchemaVersion = true
return opts, nil
}
}
func withAccurateBridgePreview() providerOption {
return func(opts providerOptions) (providerOptions, error) {
opts.enableAccurateBridgePreview = true
return opts, nil
}
}
func getProviderOptions(opts []providerOption) (providerOptions, error) {
res := providerOptions{}
for _, o := range opts {
var err error
res, err = o(res)
if err != nil {
return res, err
}
}
return res, nil
}
// Provider implements the Pulumi resource provider operations for any Terraform plugin.
type Provider struct {
pulumirpc.UnimplementedResourceProviderServer
host *provider.HostClient // the RPC link back to the Pulumi engine.
module string // the Terraform module name.
version string // the plugin version number.
tf shim.Provider // the Terraform resource provider to use.
info ProviderInfo // overlaid info about this provider.
config shim.SchemaMap // the Terraform config schema.
configValues resource.PropertyMap // this package's config values.
resources map[tokens.Type]Resource // a map of Pulumi type tokens to resource info.
dataSources map[tokens.ModuleMember]DataSource // a map of Pulumi module tokens to data sources.
supportsSecrets bool // true if the engine supports secret property values
pulumiSchema []byte // the JSON-encoded Pulumi schema.
pulumiSchemaSpec *pschema.PackageSpec
memStats memStatCollector
hasTypeErrors map[resource.URN]struct{}
providerOpts []providerOption
}
// MuxProvider defines an interface which must be implemented by providers
// that shall be used as mixins of a wrapped Terraform provider
type MuxProvider = info.MuxProvider
// Resource wraps both the Terraform resource type info plus the overlay resource info.
type Resource struct {
Schema *ResourceInfo // optional provider overrides.
TF shim.Resource // the Terraform resource schema.
TFName string // the Terraform resource name.
}
// runTerraformImporter runs the Terraform Importer defined on the Resource for the given
// resource ID, and returns a replacement input map if any resources are matched. A nil map
// with no error should be interpreted by the caller as meaning the resource does not exist,
// but there were no errors in determining this.
func (res *Resource) runTerraformImporter(
ctx context.Context, id string, provider *Provider,
) (shim.InstanceState, error) {
contract.Assertf(res.TF.Importer() != nil, "res.TF.Importer() != nil")
// Run the importer defined in the Terraform resource schema
states, err := res.TF.Importer()(res.TFName, id, provider.tf.Meta(ctx))
if err != nil {
return nil, errors.Wrapf(err, "importing %s", id)
}
// No resources were returned. There are a few different ways this can happen - principally
// - The resource never existed
// - The resource did exist but was deleted
//
// The engine is capable of converting an empty response into an appropriate error for the
// user, so we don't want to disable that behaviour by returning our own (likely different)
// error up the chain. Instead, we return a nil map _and_ a nil error, and it is the
// responsibility of the caller to convert this into an appropriate error message.
//
// We consider the case in which multiple results are returned from the importer, but none
// match the ID expected to be an error, and this is handled later in this function.
if len(states) < 1 {
return nil, nil
}
// A Terraform importer can return multiple ResourceData instances for different resources. For
// example, an AWS security group will also import the related security group rules as independent
// resources.
//
// Some Terraform importers _change_ the ID of the resource to allow for multiple formats to be
// specified by a user (for example, an AWS API Gateway Response). In the case that we only have
// a single ResourceData returned, we will use that ResourceData regardless of whether the ID
// matches, provided the resource Type does match.
//
// If we get multiple ResourceData back, we need to search the results for one which matches both
// the Type and ID of the resource we were trying to import (the "primary" InstanceState).
//
// The Type can be identified by looking at the ephemeral data attached to the InstanceState, since
// it is not stored in all cases - only for import.
var candidates []shim.InstanceState
for _, state := range states {
if state.Type() == res.TFName {
candidates = append(candidates, state)
}
}
var primaryInstanceState shim.InstanceState
if len(candidates) == 1 {
// Take the only result.
primaryInstanceState = candidates[0]
} else {
// Search for a resource with a matching ID. If one exists, take it.
for _, result := range candidates {
if result.ID() == id {
primaryInstanceState = result
break
}
}
}
// No resources were matched - error out
if primaryInstanceState == nil {
return nil, errors.Errorf("importer for %s returned no matching resources", id)
}
return primaryInstanceState, nil
}
// DataSource wraps both the Terraform data source (resource) type info plus the overlay resource info.
type DataSource struct {
Schema *DataSourceInfo // optional provider overrides.
TF shim.Resource // the Terraform data source schema.
TFName string // the Terraform resource name.
}
type CheckFailureErrorElement struct {
Reason string
Property string
}
// CheckFailureError can be returned from a PreConfigureCallback to indicate that the
// configuration is invalid along with an actionable error message. These will be
// returned as failures in the CheckConfig response instead of errors.
type CheckFailureError struct {
Failures []CheckFailureErrorElement
}
func (e CheckFailureError) Error() string {
return fmt.Sprintf("CheckFailureErrors %s", e.Failures)
}
// callWithRecover is a generic function that takes a resource URN, a recovery
// function, and a callable function as parameters. It attempts to call the
// provided callable function and returns its results. If the callable function
// panics, callWithRecover will recover from the panic and call the recovery
// function with the resource URN and the panic value. The recovery function is
// expected to convert the panic value into an error, which is then returned by
// callWithRecover. This function is useful for handling panics in a controlled
// manner and converting them into errors.
func callWithRecover[T any](
urn resource.URN,
rec func(resource.URN, any) error,
call func() (T, error),
) (_ T, err error) {
defer func() {
if r := recover(); r != nil {
err = rec(urn, r)
contract.Assertf(err != nil, "Panic handlers must return an error")
}
}()
return call()
}
// if we have type errors that were generated during check
// we don't want to log the panic. In the future these type errors
// will hard fail during check and we will never make it to create
//
// We do our best to restrict catching panics to where the panic will
// occur. The type checking will catch panics that occur as part
// of the `Diff` function
func (p *Provider) recoverOnTypeError(urn resource.URN, payload any) error {
if _, ok := p.hasTypeErrors[urn]; !ok {
panic(payload)
}
if err, ok := payload.(error); ok {
return fmt.Errorf("panicked: %w", err)
}
return fmt.Errorf("panicked: %#v", payload)
}
// NewProvider creates a new Pulumi RPC server wired up to the given host and wrapping the given Terraform provider.
func NewProvider(ctx context.Context, host *provider.HostClient, module, version string,
tf shim.Provider, info ProviderInfo, pulumiSchema []byte,
) pulumirpc.ResourceProviderServer {
if len(info.MuxWith) > 0 {
p, err := newMuxWithProvider(ctx, host, module, version, info, pulumiSchema)
if err != nil {
panic(err)
}
return p
}
return newProvider(ctx, host, module, version, tf, info, pulumiSchema)
}
func newProvider(ctx context.Context, host *provider.HostClient,
module, version string, tf shim.Provider, info ProviderInfo, pulumiSchema []byte,
) *Provider {
opts := []providerOption{}
if info.EnableZeroDefaultSchemaVersion {
opts = append(opts, WithDefaultZeroSchemaVersion())
}
if info.EnableAccurateBridgePreview || cmdutil.IsTruthy(os.Getenv("PULUMI_TF_BRIDGE_ACCURATE_BRIDGE_PREVIEW")) {
opts = append(opts, withAccurateBridgePreview())
}
p := &Provider{
host: host,
module: module,
version: version,
tf: tf,
info: info,
config: tf.Schema(),
pulumiSchema: pulumiSchema,
hasTypeErrors: make(map[resource.URN]struct{}),
providerOpts: opts,
}
ctx = p.loggingContext(ctx, "")
p.initResourceMaps()
if pulumiSchema != nil || len(pulumiSchema) != 0 {
var schema pschema.PackageSpec
if err := json.Unmarshal(pulumiSchema, &schema); err != nil {
GetLogger(ctx).Debug(fmt.Sprintf("unable to unmarshal pulumi package spec: %s", err.Error()))
}
p.pulumiSchemaSpec = &schema
}
return p
}
func newMuxWithProvider(ctx context.Context, host *provider.HostClient,
module, version string, info ProviderInfo, pulumiSchema []byte,
) (pulumirpc.ResourceProviderServer, error) {
var mapping muxer.DispatchTable
if m, found, err := metadata.Get[muxer.DispatchTable](info.GetMetadata(), "mux"); err != nil {
return nil, err
} else if found {
mapping = m
} else {
return nil, fmt.Errorf("missing pre-computed muxer mapping")
}
servers := []muxer.Endpoint{{
Server: func(host *provider.HostClient) (pulumirpc.ResourceProviderServer, error) {
return newProvider(ctx, host, module, version, info.P, info, pulumiSchema), nil
},
}}
for _, f := range info.MuxWith {
servers = append(servers, muxer.Endpoint{
Server: func(hc *provider.HostClient) (pulumirpc.ResourceProviderServer, error) {
return f.GetInstance(ctx, module, version, hc)
},
})
}
return muxer.Main{
Schema: pulumiSchema,
DispatchTable: mapping,
Servers: servers,
}.Server(host, module, version)
}
var _ pulumirpc.ResourceProviderServer = (*Provider)(nil)
func (p *Provider) pkg() tokens.Package {
return tokens.NewPackageToken(tokens.PackageName(tokens.IntoQName(p.module)))
}
func (p *Provider) baseDataMod() tokens.Module {
return tokens.NewModuleToken(p.pkg(), tokens.ModuleName("data"))
}
func (p *Provider) Attach(context context.Context, req *pulumirpc.PluginAttach) (*emptypb.Empty, error) {
host, err := provider.NewHostClient(req.GetAddress())
if err != nil {
return nil, err
}
p.host = host
return &pbempty.Empty{}, nil
}
func (p *Provider) loggingContext(ctx context.Context, urn resource.URN) context.Context {
// add the resource URN to the context
ctx = XWithUrn(ctx, urn)
// There is no host in a testing context.
if p.host == nil {
// For tests that did not call InitLogging yet, we should call it here so that
// GetLogger does not panic.
if ctx.Value(logging.CtxKey) == nil {
return logging.InitLogging(ctx, logging.LogOptions{
URN: urn,
ProviderName: p.info.Name,
ProviderVersion: p.version,
})
}
// Otherwise keep the context as-is.
return ctx
}
log.SetOutput(NewTerraformLogRedirector(ctx, p.host))
return logging.InitLogging(ctx, logging.LogOptions{
LogSink: p.host,
URN: urn,
ProviderName: p.info.Name,
ProviderVersion: p.version,
})
}
func (p *Provider) label() string {
return fmt.Sprintf("tf.Provider[%s]", p.module)
}
func ignoredTokens(info *info.Provider) map[string]bool {
ignored := map[string]bool{}
if info == nil {
return ignored
}
for _, tk := range info.IgnoreMappings {
ignored[tk] = true
}
return ignored
}
// initResourceMaps creates maps from Pulumi types and tokens to Terraform resource type.
func (p *Provider) initResourceMaps() {
ignoredTokens := ignoredTokens(&p.info)
// Fetch a list of all resource types handled by this provider and make a map.
p.resources = make(map[tokens.Type]Resource)
p.tf.ResourcesMap().Range(func(name string, res shim.Resource) bool {
schema, ok := p.info.Resources[name]
// The logic for processing `ignoredTokens` is a little funny, since we are
// careful to avoid breaking legacy providers.
//
// We don't process resources that correspond to `ignoredTokens`, unless
// they are explicitly mentioned in the schema map. If they are mentioned,
// then that overrides the ignore directive.
//
// This is because there have been providers in the wild that is
// [tfbridge.ProviderInfo.IgnoreMappings] to specify a Datasource to
// ignore, then manually map the Resource (or vice versa). We don't want
// to break those providers when implementing support for
// [tfbridge.ProviderInfo.IgnoreMappings] in the resource map.
if ignoredTokens[name] && !ok {
return true // continue
}
var tok tokens.Type
// See if there is override information for this resource. If yes, use that to decode the token.
if schema != nil && schema.Tok != "" {
tok = schema.Tok
} else { // Otherwise, we default to the standard naming scheme.
// Manufacture a token with the package, module, and resource type name.
camelName, pascalName := p.camelPascalPulumiName(name)
modTok := tokens.NewModuleToken(p.pkg(), tokens.ModuleName(camelName))
tok = tokens.NewTypeToken(modTok, tokens.TypeName(pascalName))
}
p.resources[tok] = Resource{
TF: res,
TFName: name,
Schema: schema,
}
return true
})
// Fetch a list of all data source types handled by this provider and make a similar map.
p.dataSources = make(map[tokens.ModuleMember]DataSource)
p.tf.DataSourcesMap().Range(func(name string, ds shim.Resource) bool {
var tok tokens.ModuleMember
schema, ok := p.info.DataSources[name]
// See if there is override information for this resource. If yes, use that to decode the token.
// See equivalent block above for an explanation of the logic here.
if ignoredTokens[name] && !ok {
return true // continue
}
if schema != nil && schema.Tok != "" {
tok = schema.Tok
} else { // Otherwise, we default to the standard naming scheme.
// Manufacture a token with the data module and camel-cased name.
camelName, _ := p.camelPascalPulumiName(name)
tok = tokens.NewModuleMemberToken(p.baseDataMod(), tokens.ModuleMemberName(camelName))
}
p.dataSources[tok] = DataSource{
TF: ds,
TFName: name,
Schema: schema,
}
return true
})
}
// camelPascalPulumiName returns the camel and pascal cased name for a given terraform name.
func (p *Provider) camelPascalPulumiName(name string) (string, string) {
prefix := p.info.GetResourcePrefix() + "_"
contract.Assertf(strings.HasPrefix(name, prefix),
"Expected all Terraform resources in this module to have a '%v' prefix (%q)", prefix, name)
name = name[len(prefix):]
camel := TerraformToPulumiNameV2(name, nil, nil)
pascal := camel
if pascal != "" {
pascal = string(unicode.ToUpper(rune(pascal[0]))) + pascal[1:]
}
return camel, pascal
}
// GetSchema returns the JSON-encoded schema for this provider's package.
func (p *Provider) GetSchema(ctx context.Context,
req *pulumirpc.GetSchemaRequest,
) (*pulumirpc.GetSchemaResponse, error) {
if v := req.GetVersion(); v > 1 {
return nil, errors.Errorf("unsupported schema version %v", v)
}
return &pulumirpc.GetSchemaResponse{
Schema: string(p.pulumiSchema),
}, nil
}
func makeCheckResponseFromCheckErr(err CheckFailureError) *pulumirpc.CheckResponse {
failures := make([]*pulumirpc.CheckFailure, len(err.Failures))
for i, failure := range err.Failures {
failures[i] = &pulumirpc.CheckFailure{
Reason: failure.Reason,
Property: failure.Property,
}
}
return &pulumirpc.CheckResponse{
Failures: failures,
}
}
// CheckConfig validates the configuration for this Terraform provider.
func (p *Provider) CheckConfig(ctx context.Context, req *pulumirpc.CheckRequest) (*pulumirpc.CheckResponse, error) {
urn := resource.URN(req.GetUrn())
ctx = p.loggingContext(ctx, urn)
label := fmt.Sprintf("%s.CheckConfig(%s)", p.label(), urn)
glog.V(9).Infof("%s executing", label)
configEnc := NewConfigEncoding(p.config, p.info.Config)
news, validationErrors := configEnc.UnmarshalProperties(req.GetNews())
if validationErrors != nil {
return nil, errors.Wrap(validationErrors, "CheckConfig failed because of malformed resource inputs")
}
checkConfigSpan, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.CheckConfig",
opentracing.Tag{Key: "provider", Value: p.info.Name},
opentracing.Tag{Key: "version", Value: p.version},
opentracing.Tag{Key: "inputs", Value: resource.NewObjectProperty(news).String()},
opentracing.Tag{Key: "urn", Value: string(urn)},
)
defer checkConfigSpan.Finish()
p.memStats.collectMemStats(ctx, checkConfigSpan)
config, validationErrors := buildTerraformConfig(ctx, p, news)
if validationErrors != nil {
return nil, errors.Wrap(validationErrors, "could not marshal config state")
}
// It is currently a breaking change to call PreConfigureCallback with unknown values. The user code does not
// expect them and may panic.
//
// Currently we do not call it at all if there are any unknowns.
//
// See pulumi/pulumi-terraform-bridge#1087
if !news.ContainsUnknowns() {
if err := p.preConfigureCallback(ctx, news, config); err != nil {
if failureErr, ok := err.(CheckFailureError); ok {
return makeCheckResponseFromCheckErr(failureErr), nil
}
return nil, err
}
if err := p.preConfigureCallbackWithLogger(ctx, news, config); err != nil {
if failureErr, ok := err.(CheckFailureError); ok {
return makeCheckResponseFromCheckErr(failureErr), nil
}
return nil, err
}
}
if check := p.typeCheckConfig(ctx, urn, news); check != nil {
return check, nil
}
checkFailures := validateProviderConfig(ctx, urn, p, config)
if len(checkFailures) > 0 {
return &pulumirpc.CheckResponse{
Failures: checkFailures,
}, nil
}
// Ensure properties marked secret in the schema have secret values.
secretNews := MarkSchemaSecrets(ctx, p.config, p.info.Config, resource.NewObjectProperty(news)).ObjectValue()
// In case news was modified by pre-configure callbacks, marshal it again to send out the modified value.
newsStruct, err := configEnc.MarshalProperties(secretNews)
if err != nil {
return nil, err
}
return &pulumirpc.CheckResponse{
Inputs: newsStruct,
}, nil
}
func (p *Provider) typeCheckConfig(
ctx context.Context,
urn resource.URN,
news resource.PropertyMap,
) *pulumirpc.CheckResponse {
span, _ := opentracing.StartSpanFromContext(ctx, "sdkv2.typeCheckConfig")
defer span.Finish()
logger := GetLogger(ctx)
// for now we are just going to log warnings if there are failures.
// over time we may want to turn these into actual errors
validateShouldError := cmdutil.IsTruthy(os.Getenv("PULUMI_ERROR_CONFIG_TYPE_CHECKER"))
// If we don't have a schema, then we don't attempt to type check the config at
// all.
if p.pulumiSchemaSpec == nil {
logger.Debug("p.pulumiSchemaSpec == nil, skipping type checking config")
return nil
}
typeFailures := typechecker.New(*p.pulumiSchemaSpec, true).ValidateConfig(news)
if validateShouldError {
return p.convertTypeFailures(urn, typeFailures)
}
// If we don't have any type errors, we can just return.
if len(typeFailures) == 0 {
return nil
}
// warningSpaces is same length as the string that prefixes a [logger.Warn] invocation.
//
// "warning: "
const warningSpaces = " "
prefix := func(indent int) string {
if indent == 0 {
return ""
}
const fourSpaces = " "
return warningSpaces + strings.Repeat(fourSpaces, indent-1)
}
var msg strings.Builder
msg.WriteString("Type checking failed:\n")
msg.WriteString(prefix(0) + "\n")
for _, e := range typeFailures {
msg.WriteString(prefix(2) + fmt.Sprintf("Unexpected type at field %q:\n", e.ResourcePath))
msg.WriteString(prefix(3) + e.Reason + "\n")
msg.WriteString(prefix(0) + "\n")
}
msg.WriteString(prefix(1) + "Type checking is still experimental. If you believe that a warning is incorrect,\n" +
prefix(1) + "please let us know by creating an " +
"issue at https://github.com/pulumi/pulumi-terraform-bridge/issues.\n" +
prefix(1) + "This will become a hard error in the future.",
)
logger.Warn(msg.String())
return nil
}
func (p *Provider) convertTypeFailures(
urn resource.URN, typeFailures []typechecker.Failure,
) *pulumirpc.CheckResponse {
if len(typeFailures) == 0 {
return nil
}
schemaMap := p.config
schemaInfos := p.info.GetConfig()
failures := make([]*pulumirpc.CheckFailure, len(typeFailures))
for i, e := range typeFailures {
pp := NewCheckFailurePath(schemaMap, schemaInfos, e.ResourcePath)
cf := NewCheckFailure(MiscFailure, e.Reason, &pp, urn, false, p.module, schemaMap, schemaInfos)
failures[i] = &pulumirpc.CheckFailure{
Property: string(cf.Property),
Reason: cf.Reason,
}
}
return &pulumirpc.CheckResponse{Failures: failures}
}
func (p *Provider) preConfigureCallback(
ctx context.Context,
news resource.PropertyMap,
config shim.ResourceConfig,
) error {
if p.info.PreConfigureCallback == nil {
return nil
}
span, _ := opentracing.StartSpanFromContext(ctx, "sdkv2.PreConfigureCallback")
defer span.Finish()
// NOTE: the user code may modify news in-place.
return p.info.PreConfigureCallback(news, config)
}
func (p *Provider) preConfigureCallbackWithLogger(
ctx context.Context,
news resource.PropertyMap,
config shim.ResourceConfig,
) error {
if p.info.PreConfigureCallbackWithLogger == nil {
return nil
}
span, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.PreConfigureCallbackWithLogger")
defer span.Finish()
// NOTE: the user code may modify news in-place.
return p.info.PreConfigureCallbackWithLogger(ctx, p.host, news, config)
}
func buildTerraformConfig(ctx context.Context, p *Provider, vars resource.PropertyMap) (shim.ResourceConfig, error) {
tfVars := make(resource.PropertyMap)
ignoredKeys := map[string]bool{"version": true, "pluginDownloadURL": true}
for k, v := range vars {
// we need to skip the version as adding that will cause the provider validation to fail
if ignoredKeys[string(k)] {
continue
}
if _, has := p.info.ExtraConfig[string(k)]; !has {
tfVars[k] = v
}
}
inputs, _, err := makeTerraformInputsWithOptions(ctx, nil, tfVars, nil, tfVars, p.config, p.info.Config,
makeTerraformInputsOptions{UnknownCollectionsSupported: p.tf.SupportsUnknownCollections()})
if err != nil {
return nil, err
}
return MakeTerraformConfigFromInputsWithOpts(ctx, p.tf, inputs, MakeTerraformInputsOptions{ProviderConfig: true}), nil
}
func validateProviderConfig(
ctx context.Context,
urn resource.URN,
p *Provider,
config shim.ResourceConfig,
) []*pulumirpc.CheckFailure {
span, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.ValidateProviderConfig")
defer span.Finish()
schemaMap := p.config
schemaInfos := p.info.GetConfig()
var missingKeys []*pulumirpc.CheckFailure
p.config.Range(func(key string, meta shim.Schema) bool {
if meta.Required() && !config.IsSet(key) {
pp := NewCheckFailurePath(schemaMap, schemaInfos, key)
cf := NewCheckFailure(MissingKey, "Missing key", &pp, urn, true /*isProvider*/, p.module,
schemaMap, schemaInfos)
checkFailure := pulumirpc.CheckFailure{
Property: string(cf.Property),
Reason: cf.Reason,
}
missingKeys = append(missingKeys, &checkFailure)
}
return true
})
if len(missingKeys) > 0 {
return missingKeys
}
// Perform validation of the config state so we can offer nice errors.
warns, errs := p.tf.Validate(ctx, config)
for _, warn := range warns {
logErr := p.host.Log(ctx, diag.Warning, "", fmt.Sprintf("provider config warning: %v", warn))
if logErr != nil {
glog.V(9).Infof("Failed to log to the engine: %v", logErr)
continue
}
}
return p.adaptCheckFailures(ctx, urn, true /*isProvider*/, p.config, p.info.GetConfig(), errs)
}
// A DiffConfig implementation enables the Pulumi provider to detect when provider configuration is
// changing and suggest a replacement plans when some properties require a replace. Replacing a
// provider then replaces all resources provisioned against this provider. See also the section on
// Explicit Provider Configuration in the docs:
//
// https://www.pulumi.com/docs/concepts/resources/providers/
//
// There is no matching context in Terraform so this remains a Pulumi-level feature.
func (p *Provider) DiffConfig(
ctx context.Context, req *pulumirpc.DiffRequest,
) (*pulumirpc.DiffResponse, error) {
urn := resource.URN(req.GetUrn())
label := fmt.Sprintf("%s.DiffConfig(%s)", p.label(), urn)
glog.V(9).Infof("%s executing", label)
return plugin.NewProviderServer(&configDiffer{
schemaMap: p.config,
schemaInfos: p.info.Config,
}).DiffConfig(ctx, req)
}
// Re-exported to reuse for Plugin Framework based providers.
func DiffConfig(
config shim.SchemaMap, configInfos map[string]*SchemaInfo,
) func(
urn resource.URN, oldInputs, oldOutputs, newInputs resource.PropertyMap,
allowUnknowns bool, ignoreChanges []string,
) (plugin.DiffResult, error) {
differ := &configDiffer{
schemaMap: config,
schemaInfos: configInfos,
}
return func(
urn resource.URN, oldInputs, oldOutputs, newInputs resource.PropertyMap,
allowUnknowns bool, ignoreChanges []string,
) (plugin.DiffResult, error) {
return differ.DiffConfig(context.TODO(), plugin.DiffConfigRequest{
URN: urn,
OldInputs: oldInputs,
OldOutputs: oldOutputs,
NewInputs: newInputs,
AllowUnknowns: allowUnknowns,
IgnoreChanges: ignoreChanges,
})
}
}
type configDiffer struct {
plugin.UnimplementedProvider
schemaMap shim.SchemaMap
schemaInfos map[string]*SchemaInfo
}
// Schema may specify that changing a property requires a replacement.
func (p *configDiffer) forcesProviderReplace(path resource.PropertyPath) bool {
schemaPath := PropertyPathToSchemaPath(path, p.schemaMap, p.schemaInfos)
_, info, err := LookupSchemas(schemaPath, p.schemaMap, p.schemaInfos)
if err != nil {
contract.IgnoreError(err)
return false
}
if info != nil && info.ForcesProviderReplace != nil {
return *info.ForcesProviderReplace
}
return false
}
func (p *configDiffer) DiffConfig(
ctx context.Context, req plugin.DiffConfigRequest,
) (plugin.DiffConfigResponse, error) {
contract.Assertf(req.AllowUnknowns, "Expected allowUnknowns to always be true for DiffConfig")
// Seems that DiffIncludeUnknowns only accepts func (PropertyKey) bool to support ignoring
// changes which is awkward for recursive changes, would be better if it supported
// func(PropertyPath) bool. Instead of doing this, support IgnoreChanges by copying old
// values to new values to disable the diff.
newInputsIC, err := propertyvalue.ApplyIgnoreChanges(req.OldInputs, req.NewInputs, req.IgnoreChanges)
if err != nil {
return plugin.DiffResult{}, fmt.Errorf("Error applying ignoreChanges: %v", err)
}
objDiff := req.OldInputs.DiffIncludeUnknowns(newInputsIC)
inputDiff := true
detailedDiff := plugin.NewDetailedDiffFromObjectDiff(objDiff, inputDiff)
// Ensure that if schema specifies ForceNew, a change becomes a replacement.
for key, change := range detailedDiff {
keyPath, err := resource.ParsePropertyPath(key)
contract.AssertNoErrorf(err, "Unexpected failed parse of PropertyPath %q", key)
if p.forcesProviderReplace(keyPath) {
// NOTE: for states provisioned on the older versions of Pulumi CLI oldInputs will have no entry
// for the changing property. Causing cascading replacements in this case is undesirable, since
// it is not a real change. Err on the side of not replacing (pulumi/pulumi-aws#3826).
if _, ok := keyPath.Get(resource.NewObjectProperty(req.OldInputs)); !ok {
continue
}
detailedDiff[key] = change.ToReplace()
}
}
return plugin.DiffResult{
// This is never true for DiffConfig at the provider level, making this explicit.
DeleteBeforeReplace: false,
// Everything else will be inferred from DetailedDiff by plugin.NewProviderServer.
DetailedDiff: detailedDiff,
}, nil
}
// Configure configures the underlying Terraform provider with the live Pulumi variable state.
//
// NOTE that validation and calling PreConfigureCallbacks are not called here but are called in CheckConfig. Pulumi will
// always call CheckConfig first and call Configure with validated (or extended) results of CheckConfig.
func (p *Provider) Configure(ctx context.Context,
req *pulumirpc.ConfigureRequest,
) (*pulumirpc.ConfigureResponse, error) {
if req.AcceptSecrets {
p.supportsSecrets = true
}
ctx = p.loggingContext(ctx, "")
configEnc := NewConfigEncoding(p.config, p.info.Config)
configMap, err := configEnc.UnmarshalProperties(req.GetArgs())
if err != nil {
return nil, err
}
configureSpan, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.Configure",
opentracing.Tag{Key: "provider", Value: p.info.Name},
opentracing.Tag{Key: "version", Value: p.version},
opentracing.Tag{Key: "inputs", Value: resource.NewObjectProperty(configMap).String()},
)
defer configureSpan.Finish()
p.memStats.collectMemStats(ctx, configureSpan)
// Store the config values with their Pulumi names and values, before translation. This lets us fetch
// them later on for purposes of (e.g.) config-based defaults.
p.configValues = configMap
config, err := buildTerraformConfig(ctx, p, configMap)
if err != nil {
return nil, errors.Wrap(err, "could not marshal config state")
}
// Now actually attempt to do the configuring and return its resulting error (if any).
if err = p.tf.Configure(ctx, config); err != nil {
replacedErr, replacementError := ReplaceConfigProperties(err.Error(), p.info.Config, p.config)
if replacementError != nil {
wrappedErr := errors.Wrapf(
replacementError,
"failed to replace config properties in error message",
)
return nil, multierror.Append(err, wrappedErr)
}
return nil, errors.New(replacedErr)
}
return &pulumirpc.ConfigureResponse{
SupportsPreview: true,
}, nil
}
// Check validates that the given property bag is valid for a resource of the given type.
func (p *Provider) Check(ctx context.Context, req *pulumirpc.CheckRequest) (*pulumirpc.CheckResponse, error) {
ctx = p.loggingContext(ctx, resource.URN(req.GetUrn()))
urn := resource.URN(req.GetUrn())
failures := []*pulumirpc.CheckFailure{}
t := urn.Type()
res, has := p.resources[t]
if !has {
return nil, errors.Errorf("unrecognized resource type (Check): %s", t)
}
span, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.Check",
opentracing.Tag{Key: "urn", Value: string(urn)},
)
defer span.Finish()
p.memStats.collectMemStats(ctx, span)
label := fmt.Sprintf("%s.Check(%s/%s)", p.label(), urn, res.TFName)
glog.V(9).Infof("%s executing", label)
// Unmarshal the old and new properties.
var olds resource.PropertyMap
var err error
if req.GetOlds() != nil {
olds, err = plugin.UnmarshalProperties(req.GetOlds(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.olds", label), KeepUnknowns: true,
})
if err != nil {
return nil, err
}
olds, err = transformFromState(ctx, res.Schema, olds)
if err != nil {
return nil, err
}
}
news, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
Label: fmt.Sprintf("%s.news", label), KeepUnknowns: true, SkipNulls: true,
})
if err != nil {
return nil, err
}
logger := GetLogger(ctx)
// for now we are just going to log warnings if there are failures.
// over time we may want to turn these into actual errors
validateShouldError := cmdutil.IsTruthy(os.Getenv("PULUMI_ERROR_TYPE_CHECKER"))
schemaMap, schemaInfos := res.TF.Schema(), res.Schema.GetFields()
if p.pulumiSchema != nil {
schema := p.pulumiSchemaSpec
if schema != nil {
typeFailures := typechecker.New(*schema, false).ValidateInputs(t, news)
if len(typeFailures) > 0 {
p.hasTypeErrors[urn] = struct{}{}
logger.Warn("Type checking failed: ")
for _, e := range typeFailures {
if validateShouldError {
pp := NewCheckFailurePath(schemaMap, schemaInfos, e.ResourcePath)
cf := NewCheckFailure(MiscFailure, e.Reason, &pp, urn, false, p.module, schemaMap, schemaInfos)
failures = append(failures, &pulumirpc.CheckFailure{
Reason: cf.Reason,
Property: string(cf.Property),
})
} else {
logger.Warn(
fmt.Sprintf("Unexpected type at field %q: \n %s", e.ResourcePath, e.Reason),
)
}