-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathserve.go
1423 lines (1256 loc) · 45.3 KB
/
serve.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
package tfsdk
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/internal/proto6"
"github.com/hashicorp/terraform-plugin-go/tfprotov6"
"github.com/hashicorp/terraform-plugin-go/tfprotov6/tf6server"
"github.com/hashicorp/terraform-plugin-go/tftypes"
"github.com/hashicorp/terraform-plugin-log/tfsdklog"
)
var _ tfprotov6.ProviderServer = &server{}
type server struct {
p Provider
contextCancels []context.CancelFunc
contextCancelsMu sync.Mutex
}
// ServeOpts are options for serving the provider.
type ServeOpts struct {
// Name is the name of the provider, in full address form. For example:
// registry.terraform.io/hashicorp/random.
Name string
// Debug runs the provider in a mode acceptable for debugging and testing
// processes, such as delve, by managing the process lifecycle. Information
// needed for Terraform CLI to connect to the provider is output to stdout.
// os.Interrupt (Ctrl-c) can be used to stop the provider.
Debug bool
}
// NewProtocol6Server returns a tfprotov6.ProviderServer implementation based
// on the passed Provider implementation.
func NewProtocol6Server(p Provider) tfprotov6.ProviderServer {
return &server{
p: p,
}
}
// Serve serves a provider, blocking until the context is canceled.
func Serve(ctx context.Context, providerFunc func() Provider, opts ServeOpts) error {
var tf6serverOpts []tf6server.ServeOpt
if opts.Debug {
tf6serverOpts = append(tf6serverOpts, tf6server.WithManagedDebug())
}
return tf6server.Serve(opts.Name, func() tfprotov6.ProviderServer {
return &server{
p: providerFunc(),
}
}, tf6serverOpts...)
}
func (s *server) registerContext(in context.Context) context.Context {
ctx, cancel := context.WithCancel(in)
s.contextCancelsMu.Lock()
defer s.contextCancelsMu.Unlock()
s.contextCancels = append(s.contextCancels, cancel)
return ctx
}
func (s *server) cancelRegisteredContexts(_ context.Context) {
s.contextCancelsMu.Lock()
defer s.contextCancelsMu.Unlock()
for _, cancel := range s.contextCancels {
cancel()
}
s.contextCancels = nil
}
func (s *server) getResourceType(ctx context.Context, typ string) (ResourceType, diag.Diagnostics) {
resourceTypes, diags := s.p.GetResources(ctx)
if diags.HasError() {
return nil, diags
}
resourceType, ok := resourceTypes[typ]
if !ok {
diags.AddError(
"Resource not found",
fmt.Sprintf("No resource named %q is configured on the provider", typ),
)
return nil, diags
}
return resourceType, diags
}
func (s *server) getDataSourceType(ctx context.Context, typ string) (DataSourceType, diag.Diagnostics) {
dataSourceTypes, diags := s.p.GetDataSources(ctx)
if diags.HasError() {
return nil, diags
}
dataSourceType, ok := dataSourceTypes[typ]
if !ok {
diags.AddError(
"Data source not found",
fmt.Sprintf("No data source named %q is configured on the provider", typ),
)
return nil, diags
}
return dataSourceType, diags
}
// getProviderSchemaResponse is a thin abstraction to allow native Diagnostics usage
type getProviderSchemaResponse struct {
Provider *tfprotov6.Schema
ProviderMeta *tfprotov6.Schema
ResourceSchemas map[string]*tfprotov6.Schema
DataSourceSchemas map[string]*tfprotov6.Schema
Diagnostics diag.Diagnostics
}
func (r getProviderSchemaResponse) toTfprotov6() *tfprotov6.GetProviderSchemaResponse {
return &tfprotov6.GetProviderSchemaResponse{
Provider: r.Provider,
ProviderMeta: r.ProviderMeta,
ResourceSchemas: r.ResourceSchemas,
DataSourceSchemas: r.DataSourceSchemas,
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
}
}
func (s *server) GetProviderSchema(ctx context.Context, _ *tfprotov6.GetProviderSchemaRequest) (*tfprotov6.GetProviderSchemaResponse, error) {
ctx = s.registerContext(ctx)
resp := new(getProviderSchemaResponse)
s.getProviderSchema(ctx, resp)
return resp.toTfprotov6(), nil
}
func (s *server) getProviderSchema(ctx context.Context, resp *getProviderSchemaResponse) {
// get the provider schema
providerSchema, diags := s.p.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if diags.HasError() {
return
}
// convert the provider schema to a *tfprotov6.Schema
provider6Schema, err := providerSchema.tfprotov6Schema(ctx)
if err != nil {
resp.Diagnostics.AddError(
"Error converting provider schema",
"The provider schema couldn't be converted into a usable type. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
// don't set the schema on the response yet, we want it to be able to
// accrue warning diagnostics and return them on the first error
// diagnostic without returning a partial schema, so we need to wait
// until the very end to set the schemas on the response
// if we have a provider_meta schema, get it
var providerMeta6Schema *tfprotov6.Schema
if pm, ok := s.p.(ProviderWithProviderMeta); ok {
providerMetaSchema, diags := pm.GetMetaSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
pm6Schema, err := providerMetaSchema.tfprotov6Schema(ctx)
if err != nil {
resp.Diagnostics.AddError(
"Error converting provider_meta schema",
"The provider_meta schema couldn't be converted into a usable type. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
providerMeta6Schema = pm6Schema
}
// get our resource schemas
resourceSchemas, diags := s.p.GetResources(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resource6Schemas := map[string]*tfprotov6.Schema{}
for k, v := range resourceSchemas {
schema, diags := v.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
schema6, err := schema.tfprotov6Schema(ctx)
if err != nil {
resp.Diagnostics.AddError(
"Error converting resource schema",
"The schema for the resource \""+k+"\" couldn't be converted into a usable type. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
resource6Schemas[k] = schema6
}
// get our data source schemas
dataSourceSchemas, diags := s.p.GetDataSources(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
dataSource6Schemas := map[string]*tfprotov6.Schema{}
for k, v := range dataSourceSchemas {
schema, diags := v.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
schema6, err := schema.tfprotov6Schema(ctx)
if err != nil {
resp.Diagnostics.AddError(
"Error converting data sourceschema",
"The schema for the data source \""+k+"\" couldn't be converted into a usable type. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
dataSource6Schemas[k] = schema6
}
// ok, we didn't get any error diagnostics, populate the schemas and
// send the response
resp.Provider = provider6Schema
resp.ProviderMeta = providerMeta6Schema
resp.ResourceSchemas = resource6Schemas
resp.DataSourceSchemas = dataSource6Schemas
}
// validateProviderConfigResponse is a thin abstraction to allow native Diagnostics usage
type validateProviderConfigResponse struct {
PreparedConfig *tfprotov6.DynamicValue
Diagnostics diag.Diagnostics
}
func (r validateProviderConfigResponse) toTfprotov6() *tfprotov6.ValidateProviderConfigResponse {
return &tfprotov6.ValidateProviderConfigResponse{
PreparedConfig: r.PreparedConfig,
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
}
}
func (s *server) ValidateProviderConfig(ctx context.Context, req *tfprotov6.ValidateProviderConfigRequest) (*tfprotov6.ValidateProviderConfigResponse, error) {
ctx = s.registerContext(ctx)
resp := &validateProviderConfigResponse{
// This RPC allows a modified configuration to be returned. This was
// previously used to allow a "required" provider attribute (as defined
// by a schema) to still be "optional" with a default value, typically
// through an environment variable. Other tooling based on the provider
// schema information could not determine this implementation detail.
// To ensure accuracy going forward, this implementation is opinionated
// towards accurate provider schema definitions and optional values
// can be filled in or return errors during ConfigureProvider().
PreparedConfig: req.Config,
}
s.validateProviderConfig(ctx, req, resp)
return resp.toTfprotov6(), nil
}
func (s *server) validateProviderConfig(ctx context.Context, req *tfprotov6.ValidateProviderConfigRequest, resp *validateProviderConfigResponse) {
schema, diags := s.p.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
config, err := req.Config.Unmarshal(schema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing config",
"The provider had a problem parsing the config. Report this to the provider developer:\n\n"+err.Error(),
)
return
}
vpcReq := ValidateProviderConfigRequest{
Config: Config{
Raw: config,
Schema: schema,
},
}
if provider, ok := s.p.(ProviderWithConfigValidators); ok {
for _, configValidator := range provider.ConfigValidators(ctx) {
vpcRes := &ValidateProviderConfigResponse{
Diagnostics: resp.Diagnostics,
}
configValidator.Validate(ctx, vpcReq, vpcRes)
resp.Diagnostics = vpcRes.Diagnostics
}
}
if provider, ok := s.p.(ProviderWithValidateConfig); ok {
vpcRes := &ValidateProviderConfigResponse{
Diagnostics: resp.Diagnostics,
}
provider.ValidateConfig(ctx, vpcReq, vpcRes)
resp.Diagnostics = vpcRes.Diagnostics
}
validateSchemaReq := ValidateSchemaRequest{
Config: Config{
Raw: config,
Schema: schema,
},
}
validateSchemaResp := ValidateSchemaResponse{
Diagnostics: resp.Diagnostics,
}
schema.validate(ctx, validateSchemaReq, &validateSchemaResp)
resp.Diagnostics = validateSchemaResp.Diagnostics
}
// configureProviderResponse is a thin abstraction to allow native Diagnostics usage
type configureProviderResponse struct {
Diagnostics diag.Diagnostics
}
func (r configureProviderResponse) toTfprotov6() *tfprotov6.ConfigureProviderResponse {
return &tfprotov6.ConfigureProviderResponse{
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
}
}
func (s *server) ConfigureProvider(ctx context.Context, req *tfprotov6.ConfigureProviderRequest) (*tfprotov6.ConfigureProviderResponse, error) {
ctx = s.registerContext(ctx)
resp := &configureProviderResponse{}
s.configureProvider(ctx, req, resp)
return resp.toTfprotov6(), nil
}
func (s *server) configureProvider(ctx context.Context, req *tfprotov6.ConfigureProviderRequest, resp *configureProviderResponse) {
schema, diags := s.p.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
config, err := req.Config.Unmarshal(schema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing config",
"The provider had a problem parsing the config. Report this to the provider developer:\n\n"+err.Error(),
)
return
}
r := ConfigureProviderRequest{
TerraformVersion: req.TerraformVersion,
Config: Config{
Raw: config,
Schema: schema,
},
}
res := &ConfigureProviderResponse{}
s.p.Configure(ctx, r, res)
resp.Diagnostics.Append(res.Diagnostics...)
}
func (s *server) StopProvider(ctx context.Context, _ *tfprotov6.StopProviderRequest) (*tfprotov6.StopProviderResponse, error) {
s.cancelRegisteredContexts(ctx)
return &tfprotov6.StopProviderResponse{}, nil
}
// validateResourceConfigResponse is a thin abstraction to allow native Diagnostics usage
type validateResourceConfigResponse struct {
Diagnostics diag.Diagnostics
}
func (r validateResourceConfigResponse) toTfprotov6() *tfprotov6.ValidateResourceConfigResponse {
return &tfprotov6.ValidateResourceConfigResponse{
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
}
}
func (s *server) ValidateResourceConfig(ctx context.Context, req *tfprotov6.ValidateResourceConfigRequest) (*tfprotov6.ValidateResourceConfigResponse, error) {
ctx = s.registerContext(ctx)
resp := &validateResourceConfigResponse{}
s.validateResourceConfig(ctx, req, resp)
return resp.toTfprotov6(), nil
}
func (s *server) validateResourceConfig(ctx context.Context, req *tfprotov6.ValidateResourceConfigRequest, resp *validateResourceConfigResponse) {
// Get the type of resource, so we can get its schema and create an
// instance
resourceType, diags := s.getResourceType(ctx, req.TypeName)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Get the schema from the resource type, so we can embed it in the
// config
resourceSchema, diags := resourceType.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Create the resource instance, so we can call its methods and handle
// the request
resource, diags := resourceType.NewResource(ctx, s.p)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
config, err := req.Config.Unmarshal(resourceSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing config",
"The provider had a problem parsing the config. Report this to the provider developer:\n\n"+err.Error(),
)
return
}
vrcReq := ValidateResourceConfigRequest{
Config: Config{
Raw: config,
Schema: resourceSchema,
},
}
if resource, ok := resource.(ResourceWithConfigValidators); ok {
for _, configValidator := range resource.ConfigValidators(ctx) {
vrcRes := &ValidateResourceConfigResponse{
Diagnostics: resp.Diagnostics,
}
configValidator.Validate(ctx, vrcReq, vrcRes)
resp.Diagnostics = vrcRes.Diagnostics
}
}
if resource, ok := resource.(ResourceWithValidateConfig); ok {
vrcRes := &ValidateResourceConfigResponse{
Diagnostics: resp.Diagnostics,
}
resource.ValidateConfig(ctx, vrcReq, vrcRes)
resp.Diagnostics = vrcRes.Diagnostics
}
validateSchemaReq := ValidateSchemaRequest{
Config: Config{
Raw: config,
Schema: resourceSchema,
},
}
validateSchemaResp := ValidateSchemaResponse{
Diagnostics: resp.Diagnostics,
}
resourceSchema.validate(ctx, validateSchemaReq, &validateSchemaResp)
resp.Diagnostics = validateSchemaResp.Diagnostics
}
func (s *server) UpgradeResourceState(ctx context.Context, req *tfprotov6.UpgradeResourceStateRequest) (*tfprotov6.UpgradeResourceStateResponse, error) {
// uncomment when we implement this function
//ctx = s.registerContext(ctx)
// TODO: support state upgrades
return &tfprotov6.UpgradeResourceStateResponse{
UpgradedState: &tfprotov6.DynamicValue{
JSON: req.RawState.JSON,
},
}, nil
}
// readResourceResponse is a thin abstraction to allow native Diagnostics usage
type readResourceResponse struct {
NewState *tfprotov6.DynamicValue
Diagnostics diag.Diagnostics
Private []byte
}
func (r readResourceResponse) toTfprotov6() *tfprotov6.ReadResourceResponse {
return &tfprotov6.ReadResourceResponse{
NewState: r.NewState,
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
Private: r.Private,
}
}
func (s *server) ReadResource(ctx context.Context, req *tfprotov6.ReadResourceRequest) (*tfprotov6.ReadResourceResponse, error) {
ctx = s.registerContext(ctx)
resp := &readResourceResponse{}
s.readResource(ctx, req, resp)
return resp.toTfprotov6(), nil
}
func (s *server) readResource(ctx context.Context, req *tfprotov6.ReadResourceRequest, resp *readResourceResponse) {
resourceType, diags := s.getResourceType(ctx, req.TypeName)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resourceSchema, diags := resourceType.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resource, diags := resourceType.NewResource(ctx, s.p)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
state, err := req.CurrentState.Unmarshal(resourceSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing current state",
"There was an error parsing the current state. Please report this to the provider developer:\n\n"+err.Error(),
)
return
}
readReq := ReadResourceRequest{
State: State{
Raw: state,
Schema: resourceSchema,
},
}
if pm, ok := s.p.(ProviderWithProviderMeta); ok {
pmSchema, diags := pm.GetMetaSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
readReq.ProviderMeta = Config{
Schema: pmSchema,
Raw: tftypes.NewValue(pmSchema.TerraformType(ctx), nil),
}
if req.ProviderMeta != nil {
pmValue, err := req.ProviderMeta.Unmarshal(pmSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing provider_meta",
"There was an error parsing the provider_meta block. Please report this to the provider developer:\n\n"+err.Error(),
)
return
}
readReq.ProviderMeta.Raw = pmValue
}
}
readResp := ReadResourceResponse{
State: State{
Raw: state,
Schema: resourceSchema,
},
Diagnostics: resp.Diagnostics,
}
resource.Read(ctx, readReq, &readResp)
resp.Diagnostics = readResp.Diagnostics
// don't return even if we have error diagnostics, we need to set the
// state on the response, first
newState, err := tfprotov6.NewDynamicValue(resourceSchema.TerraformType(ctx), readResp.State.Raw)
if err != nil {
resp.Diagnostics.AddError(
"Error converting read response",
"An unexpected error was encountered when converting the read response to a usable type. This is always a problem with the provider. Please give the following information to the provider developer:\n\n"+err.Error(),
)
return
}
resp.NewState = &newState
}
func markComputedNilsAsUnknown(ctx context.Context, config tftypes.Value, resourceSchema Schema) func(*tftypes.AttributePath, tftypes.Value) (tftypes.Value, error) {
return func(path *tftypes.AttributePath, val tftypes.Value) (tftypes.Value, error) {
// we are only modifying attributes, not the entire resource
if len(path.Steps()) < 1 {
return val, nil
}
configVal, _, err := tftypes.WalkAttributePath(config, path)
if err != tftypes.ErrInvalidStep && err != nil {
tfsdklog.Error(ctx, "error walking attribute path", "path", path)
return val, err
} else if err != tftypes.ErrInvalidStep && !configVal.(tftypes.Value).IsNull() {
tfsdklog.Trace(ctx, "attribute not null in config, not marking unknown", "path", path)
return val, nil
}
attribute, err := resourceSchema.AttributeAtPath(path)
if err != nil {
if errors.Is(err, ErrPathInsideAtomicAttribute) {
// ignore attributes/elements inside schema.Attributes, they have no schema of their own
tfsdklog.Trace(ctx, "attribute is a non-schema attribute, not marking unknown", "path", path)
return val, nil
}
tfsdklog.Error(ctx, "couldn't find attribute in resource schema", "path", path)
return tftypes.Value{}, fmt.Errorf("couldn't find attribute in resource schema: %w", err)
}
if !attribute.Computed {
tfsdklog.Trace(ctx, "attribute is not computed in schema, not marking unknown", "path", path)
return val, nil
}
tfsdklog.Debug(ctx, "marking computed attribute that is null in the config as unknown", "path", path)
return tftypes.NewValue(val.Type(), tftypes.UnknownValue), nil
}
}
// planResourceChangeResponse is a thin abstraction to allow native Diagnostics usage
type planResourceChangeResponse struct {
PlannedState *tfprotov6.DynamicValue
Diagnostics diag.Diagnostics
RequiresReplace []*tftypes.AttributePath
PlannedPrivate []byte
}
func (r planResourceChangeResponse) toTfprotov6() *tfprotov6.PlanResourceChangeResponse {
return &tfprotov6.PlanResourceChangeResponse{
PlannedState: r.PlannedState,
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
RequiresReplace: r.RequiresReplace,
PlannedPrivate: r.PlannedPrivate,
}
}
func (s *server) PlanResourceChange(ctx context.Context, req *tfprotov6.PlanResourceChangeRequest) (*tfprotov6.PlanResourceChangeResponse, error) {
ctx = s.registerContext(ctx)
resp := &planResourceChangeResponse{}
s.planResourceChange(ctx, req, resp)
return resp.toTfprotov6(), nil
}
func (s *server) planResourceChange(ctx context.Context, req *tfprotov6.PlanResourceChangeRequest, resp *planResourceChangeResponse) {
// get the type of resource, so we can get its schema and create an
// instance
resourceType, diags := s.getResourceType(ctx, req.TypeName)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// get the schema from the resource type, so we can embed it in the
// config and plan
resourceSchema, diags := resourceType.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
config, err := req.Config.Unmarshal(resourceSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing configuration",
"An unexpected error was encountered trying to parse the configuration. This is always an error in the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
plan, err := req.ProposedNewState.Unmarshal(resourceSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing plan",
"There was an unexpected error parsing the plan. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
state, err := req.PriorState.Unmarshal(resourceSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing prior state",
"An unexpected error was encountered trying to parse the prior state. This is always an error in the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
resp.PlannedState = req.ProposedNewState
// create the resource instance, so we can call its methods and handle
// the request
resource, diags := resourceType.NewResource(ctx, s.p)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Execute any AttributePlanModifiers.
//
// This pass is before any Computed-only attributes are marked as unknown
// to ensure any plan changes will trigger that behavior. These plan
// modifiers are run again after that marking to allow setting values
// and preventing extraneous plan differences.
//
// We only do this if there's a plan to modify; otherwise, it
// represents a resource being deleted and there's no point.
//
// TODO: Enabling this pass will generate the following test error:
//
// --- FAIL: TestServerPlanResourceChange/two_modifyplan_add_list_elem (0.00s)
// serve_test.go:3303: An unexpected error was encountered trying to read an attribute from the configuration. This is always an error in the provider. Please report the following to the provider developer:
//
// ElementKeyInt(1).AttributeName("name") still remains in the path: step cannot be applied to this value
//
// To fix this, (Config).GetAttribute() should return nil instead of the error.
// Reference: https://github.com/hashicorp/terraform-plugin-framework/issues/183
// Reference: https://github.com/hashicorp/terraform-plugin-framework/issues/150
// See also: https://github.com/hashicorp/terraform-plugin-framework/pull/167
// Execute any resource-level ModifyPlan method.
//
// This pass is before any Computed-only attributes are marked as unknown
// to ensure any plan changes will trigger that behavior. These plan
// modifiers be run again after that marking to allow setting values and
// preventing extraneous plan differences.
//
// TODO: Enabling this pass will generate the following test error:
//
// --- FAIL: TestServerPlanResourceChange/two_modifyplan_add_list_elem (0.00s)
// serve_test.go:3303: An unexpected error was encountered trying to read an attribute from the configuration. This is always an error in the provider. Please report the following to the provider developer:
//
// ElementKeyInt(1).AttributeName("name") still remains in the path: step cannot be applied to this value
//
// To fix this, (Config).GetAttribute() should return nil instead of the error.
// Reference: https://github.com/hashicorp/terraform-plugin-framework/issues/183
// Reference: https://github.com/hashicorp/terraform-plugin-framework/issues/150
// See also: https://github.com/hashicorp/terraform-plugin-framework/pull/167
// After ensuring there are proposed changes, mark any computed attributes
// that are null in the config as unknown in the plan, so providers have
// the choice to update them.
//
// Later attribute and resource plan modifier passes can override the
// unknown with a known value using any plan modifiers.
//
// We only do this if there's a plan to modify; otherwise, it
// represents a resource being deleted and there's no point.
if !plan.IsNull() && !plan.Equal(state) {
tfsdklog.Trace(ctx, "marking computed null values as unknown")
modifiedPlan, err := tftypes.Transform(plan, markComputedNilsAsUnknown(ctx, config, resourceSchema))
if err != nil {
resp.Diagnostics.AddError(
"Error modifying plan",
"There was an unexpected error updating the plan. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
if !plan.Equal(modifiedPlan) {
tfsdklog.Trace(ctx, "at least one value was changed to unknown")
}
plan = modifiedPlan
}
// Execute any AttributePlanModifiers again. This allows overwriting
// any unknown values.
//
// We only do this if there's a plan to modify; otherwise, it
// represents a resource being deleted and there's no point.
if !plan.IsNull() {
modifySchemaPlanReq := ModifySchemaPlanRequest{
Config: Config{
Schema: resourceSchema,
Raw: config,
},
State: State{
Schema: resourceSchema,
Raw: state,
},
Plan: Plan{
Schema: resourceSchema,
Raw: plan,
},
}
if pm, ok := s.p.(ProviderWithProviderMeta); ok {
pmSchema, diags := pm.GetMetaSchema(ctx)
if diags != nil {
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
modifySchemaPlanReq.ProviderMeta = Config{
Schema: pmSchema,
Raw: tftypes.NewValue(pmSchema.TerraformType(ctx), nil),
}
if req.ProviderMeta != nil {
pmValue, err := req.ProviderMeta.Unmarshal(pmSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing provider_meta",
"There was an error parsing the provider_meta block. Please report this to the provider developer:\n\n"+err.Error(),
)
return
}
modifySchemaPlanReq.ProviderMeta.Raw = pmValue
}
}
modifySchemaPlanResp := ModifySchemaPlanResponse{
Plan: Plan{
Schema: resourceSchema,
Raw: plan,
},
Diagnostics: resp.Diagnostics,
}
resourceSchema.modifyPlan(ctx, modifySchemaPlanReq, &modifySchemaPlanResp)
resp.RequiresReplace = append(resp.RequiresReplace, modifySchemaPlanResp.RequiresReplace...)
plan = modifySchemaPlanResp.Plan.Raw
resp.Diagnostics = modifySchemaPlanResp.Diagnostics
if resp.Diagnostics.HasError() {
return
}
}
// Execute any resource-level ModifyPlan method again. This allows
// overwriting any unknown values.
//
// We do this regardless of whether the plan is null or not, because we
// want resources to be able to return diagnostics when planning to
// delete resources, e.g. to inform practitioners that the resource
// _can't_ be deleted in the API and will just be removed from
// Terraform's state
var modifyPlanResp ModifyResourcePlanResponse
if resource, ok := resource.(ResourceWithModifyPlan); ok {
modifyPlanReq := ModifyResourcePlanRequest{
Config: Config{
Schema: resourceSchema,
Raw: config,
},
State: State{
Schema: resourceSchema,
Raw: state,
},
Plan: Plan{
Schema: resourceSchema,
Raw: plan,
},
}
if pm, ok := s.p.(ProviderWithProviderMeta); ok {
pmSchema, diags := pm.GetMetaSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
modifyPlanReq.ProviderMeta = Config{
Schema: pmSchema,
Raw: tftypes.NewValue(pmSchema.TerraformType(ctx), nil),
}
if req.ProviderMeta != nil {
pmValue, err := req.ProviderMeta.Unmarshal(pmSchema.TerraformType(ctx))
if err != nil {
resp.Diagnostics.AddError(
"Error parsing provider_meta",
"There was an error parsing the provider_meta block. Please report this to the provider developer:\n\n"+err.Error(),
)
return
}
modifyPlanReq.ProviderMeta.Raw = pmValue
}
}
modifyPlanResp = ModifyResourcePlanResponse{
Plan: Plan{
Schema: resourceSchema,
Raw: plan,
},
RequiresReplace: []*tftypes.AttributePath{},
Diagnostics: resp.Diagnostics,
}
resource.ModifyPlan(ctx, modifyPlanReq, &modifyPlanResp)
resp.Diagnostics = modifyPlanResp.Diagnostics
plan = modifyPlanResp.Plan.Raw
}
plannedState, err := tfprotov6.NewDynamicValue(plan.Type(), plan)
if err != nil {
resp.Diagnostics.AddError(
"Error converting response",
"There was an unexpected error converting the state in the response to a usable type. This is always a problem with the provider. Please report the following to the provider developer:\n\n"+err.Error(),
)
return
}
resp.PlannedState = &plannedState
resp.RequiresReplace = append(resp.RequiresReplace, modifyPlanResp.RequiresReplace...)
// ensure deterministic RequiresReplace by sorting and deduplicating
resp.RequiresReplace = normaliseRequiresReplace(ctx, resp.RequiresReplace)
}
// applyResourceChangeResponse is a thin abstraction to allow native Diagnostics usage
type applyResourceChangeResponse struct {
NewState *tfprotov6.DynamicValue
Private []byte
Diagnostics diag.Diagnostics
}
func (r applyResourceChangeResponse) toTfprotov6() *tfprotov6.ApplyResourceChangeResponse {
return &tfprotov6.ApplyResourceChangeResponse{
NewState: r.NewState,
Private: r.Private,
Diagnostics: r.Diagnostics.ToTfprotov6Diagnostics(),
}
}
// normaliseRequiresReplace sorts and deduplicates the slice of AttributePaths
// used in the RequiresReplace response field.
// Sorting is lexical based on the string representation of each AttributePath.
func normaliseRequiresReplace(ctx context.Context, rs []*tftypes.AttributePath) []*tftypes.AttributePath {
if len(rs) < 2 {
return rs
}
sort.Slice(rs, func(i, j int) bool {
return rs[i].String() < rs[j].String()
})
ret := make([]*tftypes.AttributePath, len(rs))
ret[0] = rs[0]
// deduplicate
j := 1
for i := 1; i < len(rs); i++ {
if rs[i].Equal(ret[j-1]) {
tfsdklog.Debug(ctx, "attribute found multiple times in RequiresReplace, removing duplicate", "path", rs[i])
continue
}
ret[j] = rs[i]
j++
}
return ret[:j]
}
func (s *server) ApplyResourceChange(ctx context.Context, req *tfprotov6.ApplyResourceChangeRequest) (*tfprotov6.ApplyResourceChangeResponse, error) {
ctx = s.registerContext(ctx)
resp := &applyResourceChangeResponse{
// default to the prior state, so the state won't change unless
// we choose to change it
NewState: req.PriorState,
}
s.applyResourceChange(ctx, req, resp)
return resp.toTfprotov6(), nil
}
func (s *server) applyResourceChange(ctx context.Context, req *tfprotov6.ApplyResourceChangeRequest, resp *applyResourceChangeResponse) {
// get the type of resource, so we can get its schema and create an
// instance
resourceType, diags := s.getResourceType(ctx, req.TypeName)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// get the schema from the resource type, so we can embed it in the
// config and plan
resourceSchema, diags := resourceType.GetSchema(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// create the resource instance, so we can call its methods and handle
// the request
resource, diags := resourceType.NewResource(ctx, s.p)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
config, err := req.Config.Unmarshal(resourceSchema.TerraformType(ctx))
if err != nil {