-
Notifications
You must be signed in to change notification settings - Fork 43
/
provider.go
1671 lines (1458 loc) · 58 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"
"strings"
"time"
"unicode"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"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"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/propertyvalue"
"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/contract"
"github.com/pulumi/pulumi/sdk/v3/go/common/util/rpcutil/rpcerror"
pulumirpc "github.com/pulumi/pulumi/sdk/v3/proto/go"
shim "github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfshim"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/logging"
"github.com/pulumi/pulumi-terraform-bridge/v3/unstable/metadata"
"github.com/pulumi/pulumi-terraform-bridge/x/muxer"
)
// 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.
memStats memStatCollector
}
// MuxProvider defines an interface which must be implemented by providers
// that shall be used as mixins of a wrapped Terraform provider
type MuxProvider interface {
GetSpec(ctx context.Context,
name, version string) (schema.PackageSpec, error)
GetInstance(ctx context.Context,
name, version string,
host *provider.HostClient) (pulumirpc.ResourceProviderServer, error)
}
// 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)
}
// 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 {
p := &Provider{
host: host,
module: module,
version: version,
tf: tf,
info: info,
config: tf.Schema(),
pulumiSchema: pulumiSchema,
}
p.loggingContext(ctx, "")
p.initResourceMaps()
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 {
// 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(&LogRedirector{
writers: map[string]func(string) error{
tfTracePrefix: func(msg string) error { return p.host.Log(ctx, diag.Debug, "", msg) },
tfDebugPrefix: func(msg string) error { return p.host.Log(ctx, diag.Debug, "", msg) },
tfInfoPrefix: func(msg string) error { return p.host.Log(ctx, diag.Info, "", msg) },
tfWarnPrefix: func(msg string) error { return p.host.Log(ctx, diag.Warning, "", msg) },
tfErrorPrefix: func(msg string) error { return p.host.Log(ctx, diag.Error, "", msg) },
},
})
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)
}
// initResourceMaps creates maps from Pulumi types and tokens to Terraform resource type.
func (p *Provider) initResourceMaps() {
// 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 {
var tok tokens.Type
// See if there is override information for this resource. If yes, use that to decode the token.
var schema *ResourceInfo
if p.info.Resources != nil {
schema = p.info.Resources[name]
if schema != nil {
tok = schema.Tok
}
}
// Otherwise, we default to the standard naming scheme.
if tok == "" {
// 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
// See if there is override information for this resource. If yes, use that to decode the token.
var schema *DataSourceInfo
if p.info.DataSources != nil {
schema = p.info.DataSources[name]
if schema != nil {
tok = schema.Tok
}
}
// Otherwise, we default to the standard naming scheme.
if tok == "" {
// 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())
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
}
}
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) 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 := MakeTerraformInputs(ctx, nil, tfVars, nil, tfVars, p.config, p.info.Config)
if err != nil {
return nil, err
}
return MakeTerraformConfigFromInputs(ctx, p.tf, inputs), 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)
}
// DiffConfig diffs the configuration for this Terraform provider.
func (p *Provider) DiffConfig(ctx context.Context, req *pulumirpc.DiffRequest) (*pulumirpc.DiffResponse, error) {
return nil, status.Error(codes.Unimplemented, "DiffConfig is not yet implemented")
// TO_DO - revert this comment!!
//urn := resource.URN(req.GetUrn())
//label := fmt.Sprintf("%s.DiffConfig(%s)", p.label(), urn)
//glog.V(9).Infof("%s executing", label)
//
//// There is no logic in the TF provider that suggests that provider level config
//// should force a new provider. Therefore, we are going to do this based on our
//// own schema overrides. We should use ForceNew as part of the SchemaInfo to do this
//
//// Create a Resource Schema from the config
//r := &schema.Resource{Schema: p.tf.Schema}
//
//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
// }
//}
//
//attrs, meta, err := MakeTerraformAttributes(r, olds, r.Schema, p.info.Config, p.configValues, false)
//if err != nil {
// return nil, errors.Wrapf(err, "preparing %s's old property state", urn)
//}
//state := &terraform.InstanceState{ID: req.GetId(), Attributes: attrs, Meta: meta}
//
//// Create a resource Config for the new configuration
//news, err := plugin.UnmarshalProperties(req.GetNews(), plugin.MarshalOptions{
// Label: fmt.Sprintf("%s.news", label), KeepUnknowns: true, SkipNulls: true})
//if err != nil {
// return nil, err
//}
//config, err := MakeTerraformConfig(nil, news, r.Schema, p.info.Config, nil, p.configValues, false)
//if err != nil {
// return nil, errors.Wrapf(err, "preparing %s's new property state", urn)
//}
//diff, err := r.Diff(state, config, nil)
//if err != nil {
// return nil, errors.Wrapf(err, "diffing %s", urn)
//}
//
//detailedDiff := makeDetailedDiff(r.Schema, p.info.Config, olds, news, diff)
//
//var replaces []string
//var changes pulumirpc.DiffResponse_DiffChanges
//var properties []string
//hasChanges := len(detailedDiff) > 0
//if hasChanges {
// changes = pulumirpc.DiffResponse_DIFF_SOME
// for k := range detailedDiff {
// // Turn the attribute name into a top-level property name by trimming everything after the first dot.
// if firstSep := strings.IndexAny(k, ".["); firstSep != -1 {
// k = k[:firstSep]
// }
// properties = append(properties, k)
// if p.info.Config != nil && p.info.Config[k] != nil {
// config := p.info.Config[k]
// // now is it a ForceNew or not
// if config.ForceNew != nil && *config.ForceNew {
// replaces = append(replaces, k)
// } else {
// properties = append(properties, k)
// }
// }
// }
//} else {
// changes = pulumirpc.DiffResponse_DIFF_NONE
//}
//
//return &pulumirpc.DiffResponse{
// Changes: changes,
// Replaces: replaces,
// Diffs: properties,
// DetailedDiff: detailedDiff,
// HasDetailedDiff: true,
//}, 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())
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
}
if check := res.Schema.PreCheckCallback; check != nil {
news, err = check(ctx, news, p.configValues.Copy())
if err != nil {
return nil, err
}
}
// Now fetch the default values so that (a) we can return them to the caller and (b) so that validation
// includes the default values. Otherwise, the provider wouldn't be presented with its own defaults.
tfname := res.TFName
inputs, _, err := makeTerraformInputsWithoutTFDefaults(ctx,
&PulumiResource{URN: urn, Properties: news, Seed: req.RandomSeed},
p.configValues, olds, news, res.TF.Schema(), res.Schema.Fields)
if err != nil {
return nil, err
}
// Now check with the resource provider to see if the values pass muster.
rescfg := MakeTerraformConfigFromInputs(ctx, p.tf, inputs)
warns, errs := p.tf.ValidateResource(ctx, tfname, rescfg)
for _, warn := range warns {
if err = p.host.Log(ctx, diag.Warning, urn, fmt.Sprintf("%v verification warning: %v", urn, warn)); err != nil {
return nil, err
}
}
// Now produce CheckFalures for any properties that failed verification.
failures := p.adaptCheckFailures(ctx, urn, false /*isProvider*/, res.TF.Schema(), res.Schema.GetFields(), errs)
// Now re-generate the inputs WITH the TF defaults
inputs, assets, err := MakeTerraformInputs(ctx,
&PulumiResource{URN: urn, Properties: news, Seed: req.RandomSeed},
p.configValues, olds, news, res.TF.Schema(), res.Schema.Fields)
if err != nil {
return nil, err
}
// After all is said and done, we need to go back and return only what got populated as a diff from the origin.
pinputs := MakeTerraformOutputs(
ctx, p.tf, inputs, res.TF.Schema(), res.Schema.Fields, assets, false, p.supportsSecrets,
)
pinputsWithSecrets := MarkSchemaSecrets(ctx, res.TF.Schema(), res.Schema.Fields,
resource.NewObjectProperty(pinputs)).ObjectValue()
minputs, err := plugin.MarshalProperties(pinputsWithSecrets, plugin.MarshalOptions{
Label: fmt.Sprintf("%s.inputs", label), KeepUnknowns: true, KeepSecrets: true,
})
if err != nil {
return nil, err
}
return &pulumirpc.CheckResponse{Inputs: minputs, Failures: failures}, nil
}
// For properties with MaxItemsOne, where the state is still an array
// (i.e. from a previous version without MaxItemsOne)
// we need to mark them for update manually in order to correct the state
// from an array to a flat type.
// The diff is otherwise ignored since MakeTerraformInputs won't touch
// the type if it in the right shape.
func markWronglyTypedMaxItemsOneStateDiff(
schema shim.SchemaMap, info map[string]*SchemaInfo, olds resource.PropertyMap,
) bool {
res := False()
tr := func(pulumiPath resource.PropertyPath, localValue resource.PropertyValue) (resource.PropertyValue, error) {
schemaPath := PropertyPathToSchemaPath(pulumiPath, schema, info)
localSchema, info, err := LookupSchemas(schemaPath, schema, info)
contract.IgnoreError(err)
if IsMaxItemsOne(localSchema, info) && localValue.IsArray() {
glog.V(9).Infof("Found type mismatch for %s, flagging for update.", pulumiPath)
*res = true
}
return localValue, nil // don't change just visit
}
_, err := propertyvalue.TransformPropertyValue(make(resource.PropertyPath, 0), tr, resource.NewObjectProperty(olds))
contract.AssertNoErrorf(err, "markWronglyTypedMaxItemsOneStateDiff should not return errors!")
return *res
}
// Diff checks what impacts a hypothetical update will have on the resource's properties.
func (p *Provider) Diff(ctx context.Context, req *pulumirpc.DiffRequest) (*pulumirpc.DiffResponse, error) {
ctx = p.loggingContext(ctx, resource.URN(req.GetUrn()))
urn := resource.URN(req.GetUrn())
t := urn.Type()
res, has := p.resources[t]
if !has {
return nil, errors.Errorf("unrecognized resource type (Diff): %s", urn)
}
span, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.Diff",
opentracing.Tag{Key: "urn", Value: string(urn)},
)
defer span.Finish()
p.memStats.collectMemStats(ctx, span)
label := fmt.Sprintf("%s.Diff(%s/%s)", p.label(), urn, res.TFName)
glog.V(9).Infof("%s executing", label)
// To figure out if we have a replacement, perform the diff and then look for RequiresNew flags.
olds, err := plugin.UnmarshalProperties(req.GetOlds(),
plugin.MarshalOptions{Label: fmt.Sprintf("%s.olds", label), SkipNulls: true})
if err != nil {
return nil, err
}
olds, err = transformFromState(ctx, res.Schema, olds)
if err != nil {
return nil, err
}
state, err := MakeTerraformState(ctx, res, req.GetId(), olds)
if err != nil {
return nil, errors.Wrapf(err, "unmarshaling %s's instance state", urn)
}
news, err := plugin.UnmarshalProperties(req.GetNews(),
plugin.MarshalOptions{Label: fmt.Sprintf("%s.news", label), KeepUnknowns: true})
if err != nil {
return nil, err
}
schema, fields := res.TF.Schema(), res.Schema.Fields
config, _, err := MakeTerraformConfig(ctx, p, news, schema, fields)
if err != nil {
return nil, errors.Wrapf(err, "preparing %s's new property state", urn)
}
ic := newIgnoreChanges(ctx, schema, fields, olds, news, req.GetIgnoreChanges())
diff, err := p.tf.Diff(ctx, res.TFName, state, config, shim.DiffOptions{
IgnoreChanges: ic,
})
if err != nil {
return nil, errors.Wrapf(err, "diffing %s", urn)
}
detailedDiff, changes := makeDetailedDiff(ctx, schema, fields, olds, news, diff)
// There are some providers/situations which `makeDetailedDiff` distorts the expected changes, leading
// to changes being dropped by Pulumi.
// Until we fix `makeDetailedDiff`, it is safer to refer to the Terraform Diff attribute length for setting
// the DiffResponse.
// We will still use `detailedDiff` for diff display purposes.
// See also https://github.com/pulumi/pulumi-terraform-bridge/issues/1501.
if p.info.XSkipDetailedDiffForChanges && len(diff.Attributes()) > 0 {
changes = pulumirpc.DiffResponse_DIFF_SOME
}
// If there were changes in this diff, check to see if we have a replacement.
var replaces []string
var replaced map[string]bool
var properties []string
if changes == pulumirpc.DiffResponse_DIFF_SOME {
for k, d := range detailedDiff {
// Turn the attribute name into a top-level property name by trimming everything after the first dot.
if firstSep := strings.IndexAny(k, ".["); firstSep != -1 {
k = k[:firstSep]
}
properties = append(properties, k)
switch d.Kind {
case pulumirpc.PropertyDiff_ADD_REPLACE,
pulumirpc.PropertyDiff_UPDATE_REPLACE,
pulumirpc.PropertyDiff_DELETE_REPLACE:
replaces = append(replaces, k)
if replaced == nil {
replaced = make(map[string]bool)
}
replaced[k] = true
}
}
}
// For all properties that are ForceNew, but didn't change, assume they are stable. Also recognize
// overlays that have requested that we treat specific properties as stable.
var stables []string
schema.Range(func(k string, sch shim.Schema) bool {
name, _, cust := getInfoFromTerraformName(k, schema, fields, false)
if !replaced[string(name)] &&
(sch.ForceNew() || (cust != nil && cust.Stable != nil && *cust.Stable)) {
stables = append(stables, string(name))
}
return true
})
deleteBeforeReplace := len(replaces) > 0 &&
(res.Schema.DeleteBeforeReplace || nameRequiresDeleteBeforeReplace(news, olds, schema, res.Schema))
// If the upstream diff object indicates a replace is necessary and we have not
// recorded any replaces, that means that `makeDetailedDiff` failed to translate a
// property. This is known to happen for computed input properties:
//
// https://github.com/pulumi/pulumi-aws/issues/2971
if (diff.RequiresNew() || diff.Destroy()) &&
// In theory, we should be safe to set __meta as replaces whenever
// `diff.RequiresNew() || diff.Destroy()` but by checking replaces we
// limit the blast radius of this change to diffs that we know will panic
// later on.
len(replaces) == 0 {
replaces = append(replaces, "__meta")
changes = pulumirpc.DiffResponse_DIFF_SOME
}
if changes == pulumirpc.DiffResponse_DIFF_NONE &&
markWronglyTypedMaxItemsOneStateDiff(schema, fields, olds) {
changes = pulumirpc.DiffResponse_DIFF_SOME
}
return &pulumirpc.DiffResponse{
Changes: changes,
Replaces: replaces,
Stables: stables,
DeleteBeforeReplace: deleteBeforeReplace,
Diffs: properties,
DetailedDiff: detailedDiff,
HasDetailedDiff: true,
}, nil
}
// Create allocates a new instance of the provided resource and returns its unique ID afterwards. (The input ID
// must be blank.) If this call fails, the resource must not have been created (i.e., it is "transactional").
func (p *Provider) Create(ctx context.Context, req *pulumirpc.CreateRequest) (*pulumirpc.CreateResponse, error) {
ctx = p.loggingContext(ctx, resource.URN(req.GetUrn()))
urn := resource.URN(req.GetUrn())
t := urn.Type()
res, has := p.resources[t]
if !has {
return nil, errors.Errorf("unrecognized resource type (Create): %s", t)
}
createSpan, ctx := opentracing.StartSpanFromContext(ctx, "sdkv2.Create",
opentracing.Tag{Key: "urn", Value: string(urn)},
)
defer createSpan.Finish()
p.memStats.collectMemStats(ctx, createSpan)
label := fmt.Sprintf("%s.Create(%s/%s)", p.label(), urn, res.TFName)
glog.V(9).Infof("%s executing", label)
// To get Terraform to create a new resource, the ID must be blank and existing state must be empty (since the
// resource does not exist yet), and the diff object should have no old state and all of the new state.
config, assets, err := UnmarshalTerraformConfig(ctx,
p, req.GetProperties(), res.TF.Schema(), res.Schema.Fields,