-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathgrpc_provider.go
More file actions
2584 lines (2146 loc) · 85.3 KB
/
grpc_provider.go
File metadata and controls
2584 lines (2146 loc) · 85.3 KB
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 IBM Corp. 2019, 2026
// SPDX-License-Identifier: MPL-2.0
package schema
import (
"context"
"encoding/json"
"fmt"
"slices"
"strconv"
"strings"
"sync"
"github.com/hashicorp/go-cty/cty"
ctyconvert "github.com/hashicorp/go-cty/cty/convert"
"github.com/hashicorp/go-cty/cty/msgpack"
"github.com/hashicorp/terraform-plugin-go/tfprotov5"
"github.com/hashicorp/terraform-plugin-go/tftypes"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/configschema"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/configs/hcl2shim"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/logging"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/plans/objchange"
"github.com/hashicorp/terraform-plugin-sdk/v2/internal/plugin/convert"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
const (
newExtraKey = "_new_extra_shim"
)
// Verify provider server interface implementation.
var _ tfprotov5.ProviderServer = (*GRPCProviderServer)(nil)
func NewGRPCProviderServer(p *Provider) *GRPCProviderServer {
return &GRPCProviderServer{
provider: p,
stopCh: make(chan struct{}),
}
}
// GRPCProviderServer handles the server, or plugin side of the rpc connection.
type GRPCProviderServer struct {
provider *Provider
stopCh chan struct{}
stopMu sync.Mutex
}
// mergeStop is called in a goroutine and waits for the global stop signal
// and propagates cancellation to the passed in ctx/cancel func. The ctx is
// also passed to this function and waited upon so no goroutine leak is caused.
func mergeStop(ctx context.Context, cancel context.CancelFunc, stopCh chan struct{}) {
select {
case <-ctx.Done():
return
case <-stopCh:
cancel()
}
}
// StopContext derives a new context from the passed in grpc context.
// It creates a goroutine to wait for the server stop and propagates
// cancellation to the derived grpc context.
func (s *GRPCProviderServer) StopContext(ctx context.Context) context.Context {
ctx = logging.InitContext(ctx)
s.stopMu.Lock()
defer s.stopMu.Unlock()
stoppable, cancel := context.WithCancel(ctx)
go mergeStop(stoppable, cancel, s.stopCh)
return stoppable
}
func (s *GRPCProviderServer) serverCapabilities() *tfprotov5.ServerCapabilities {
return &tfprotov5.ServerCapabilities{
GetProviderSchemaOptional: true,
GenerateResourceConfig: true,
}
}
func (s *GRPCProviderServer) GetResourceIdentitySchemas(ctx context.Context, req *tfprotov5.GetResourceIdentitySchemasRequest) (*tfprotov5.GetResourceIdentitySchemasResponse, error) {
ctx = logging.InitContext(ctx)
logging.HelperSchemaTrace(ctx, "Getting resource identity schemas")
resp := &tfprotov5.GetResourceIdentitySchemasResponse{
IdentitySchemas: make(map[string]*tfprotov5.ResourceIdentitySchema),
}
for typ, res := range s.provider.ResourcesMap {
logging.HelperSchemaTrace(ctx, "Found resource identity type", map[string]interface{}{logging.KeyResourceType: typ})
if res.Identity != nil {
idschema, err := res.CoreIdentitySchema()
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("getting identity schema failed for resource '%s': %w", typ, err))
return resp, nil
}
resp.IdentitySchemas[typ] = &tfprotov5.ResourceIdentitySchema{
Version: res.Identity.Version,
IdentityAttributes: convert.ConfigIdentitySchemaToProto(ctx, idschema),
}
}
}
return resp, nil
}
func (s *GRPCProviderServer) UpgradeResourceIdentity(ctx context.Context, req *tfprotov5.UpgradeResourceIdentityRequest) (*tfprotov5.UpgradeResourceIdentityResponse, error) {
ctx = logging.InitContext(ctx)
resp := &tfprotov5.UpgradeResourceIdentityResponse{}
res, ok := s.provider.ResourcesMap[req.TypeName]
if !ok {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName))
return resp, nil
}
schemaBlock, err := s.getResourceIdentitySchemaBlock(req.TypeName)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
version := req.Version
jsonMap := map[string]interface{}{}
switch {
// if there's a JSON state, we need to decode it.
case req.RawIdentity != nil && len(req.RawIdentity.JSON) > 0:
if res.UseJSONNumber {
err = unmarshalJSON(req.RawIdentity.JSON, &jsonMap)
} else {
err = json.Unmarshal(req.RawIdentity.JSON, &jsonMap)
}
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
default:
logging.HelperSchemaDebug(ctx, "no resource identity provided to upgrade")
return resp, nil
}
// complete the upgrade of the JSON states
logging.HelperSchemaTrace(ctx, "Upgrading JSON identity")
jsonMap, err = s.upgradeJSONIdentity(ctx, version, jsonMap, res)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// The provider isn't required to clean out removed fields
s.removeAttributes(ctx, jsonMap, schemaBlock.ImpliedType())
// now we need to turn the state into the default json representation, so
// that it can be re-decoded using the actual schema.
val, err := JSONMapToStateValue(jsonMap, schemaBlock)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// Now we need to make sure blocks are represented correctly, which means
// that missing blocks are empty collections, rather than null.
// First we need to CoerceValue to ensure that all object types match.
val, err = schemaBlock.CoerceValue(val)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// encode the final state to the expected msgpack format
newStateMP, err := msgpack.Marshal(val, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
resp.UpgradedIdentity = &tfprotov5.ResourceIdentityData{IdentityData: &tfprotov5.DynamicValue{MsgPack: newStateMP}}
return resp, nil
}
func (s *GRPCProviderServer) GetMetadata(ctx context.Context, req *tfprotov5.GetMetadataRequest) (*tfprotov5.GetMetadataResponse, error) {
ctx = logging.InitContext(ctx)
logging.HelperSchemaTrace(ctx, "Getting provider metadata")
resp := &tfprotov5.GetMetadataResponse{
DataSources: make([]tfprotov5.DataSourceMetadata, 0, len(s.provider.DataSourcesMap)),
EphemeralResources: make([]tfprotov5.EphemeralResourceMetadata, 0),
Functions: make([]tfprotov5.FunctionMetadata, 0),
ListResources: make([]tfprotov5.ListResourceMetadata, 0),
Actions: make([]tfprotov5.ActionMetadata, 0),
Resources: make([]tfprotov5.ResourceMetadata, 0, len(s.provider.ResourcesMap)),
ServerCapabilities: s.serverCapabilities(),
}
for typeName := range s.provider.DataSourcesMap {
resp.DataSources = append(resp.DataSources, tfprotov5.DataSourceMetadata{
TypeName: typeName,
})
}
for typeName := range s.provider.ResourcesMap {
resp.Resources = append(resp.Resources, tfprotov5.ResourceMetadata{
TypeName: typeName,
})
}
return resp, nil
}
func (s *GRPCProviderServer) GetProviderSchema(ctx context.Context, req *tfprotov5.GetProviderSchemaRequest) (*tfprotov5.GetProviderSchemaResponse, error) {
ctx = logging.InitContext(ctx)
logging.HelperSchemaTrace(ctx, "Getting provider schema")
resp := &tfprotov5.GetProviderSchemaResponse{
DataSourceSchemas: make(map[string]*tfprotov5.Schema, len(s.provider.DataSourcesMap)),
EphemeralResourceSchemas: make(map[string]*tfprotov5.Schema, 0),
Functions: make(map[string]*tfprotov5.Function, 0),
ListResourceSchemas: make(map[string]*tfprotov5.Schema, 0),
ActionSchemas: make(map[string]*tfprotov5.ActionSchema, 0),
ResourceSchemas: make(map[string]*tfprotov5.Schema, len(s.provider.ResourcesMap)),
ServerCapabilities: s.serverCapabilities(),
}
resp.Provider = &tfprotov5.Schema{
Block: convert.ConfigSchemaToProto(ctx, s.getProviderSchemaBlock()),
}
resp.ProviderMeta = &tfprotov5.Schema{
Block: convert.ConfigSchemaToProto(ctx, s.getProviderMetaSchemaBlock()),
}
for typ, res := range s.provider.ResourcesMap {
logging.HelperSchemaTrace(ctx, "Found resource type", map[string]interface{}{logging.KeyResourceType: typ})
resp.ResourceSchemas[typ] = &tfprotov5.Schema{
Version: int64(res.SchemaVersion),
Block: convert.ConfigSchemaToProto(ctx, res.CoreConfigSchema()),
}
}
for typ, dat := range s.provider.DataSourcesMap {
logging.HelperSchemaTrace(ctx, "Found data source type", map[string]interface{}{logging.KeyDataSourceType: typ})
resp.DataSourceSchemas[typ] = &tfprotov5.Schema{
Version: int64(dat.SchemaVersion),
Block: convert.ConfigSchemaToProto(ctx, dat.CoreConfigSchema()),
}
}
return resp, nil
}
func (s *GRPCProviderServer) getProviderSchemaBlock() *configschema.Block {
return InternalMap(s.provider.Schema).CoreConfigSchema()
}
func (s *GRPCProviderServer) getProviderMetaSchemaBlock() *configschema.Block {
return InternalMap(s.provider.ProviderMetaSchema).CoreConfigSchema()
}
func (s *GRPCProviderServer) getResourceSchemaBlock(name string) *configschema.Block {
res := s.provider.ResourcesMap[name]
return res.CoreConfigSchema()
}
func (s *GRPCProviderServer) getResourceIdentitySchemaBlock(name string) (*configschema.Block, error) {
res := s.provider.ResourcesMap[name]
return res.CoreIdentitySchema()
}
func (s *GRPCProviderServer) getDatasourceSchemaBlock(name string) *configschema.Block {
dat := s.provider.DataSourcesMap[name]
return dat.CoreConfigSchema()
}
func (s *GRPCProviderServer) PrepareProviderConfig(ctx context.Context, req *tfprotov5.PrepareProviderConfigRequest) (*tfprotov5.PrepareProviderConfigResponse, error) {
ctx = logging.InitContext(ctx)
resp := &tfprotov5.PrepareProviderConfigResponse{}
logging.HelperSchemaTrace(ctx, "Preparing provider configuration")
schemaBlock := s.getProviderSchemaBlock()
configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// lookup any required, top-level attributes that are Null, and see if we
// have a Default value available.
configVal, err = cty.Transform(configVal, func(path cty.Path, val cty.Value) (cty.Value, error) {
// we're only looking for top-level attributes
if len(path) != 1 {
return val, nil
}
// nothing to do if we already have a value
if !val.IsNull() {
return val, nil
}
// get the Schema definition for this attribute
getAttr, ok := path[0].(cty.GetAttrStep)
// these should all exist, but just ignore anything strange
if !ok {
return val, nil
}
attrSchema := s.provider.Schema[getAttr.Name]
// continue to ignore anything that doesn't match
if attrSchema == nil {
return val, nil
}
// this is deprecated, so don't set it
if attrSchema.Deprecated != "" {
return val, nil
}
// find a default value if it exists
def, err := attrSchema.DefaultValue()
if err != nil {
return val, fmt.Errorf("error getting default for %q: %w", getAttr.Name, err)
}
// no default
if def == nil {
return val, nil
}
// create a cty.Value and make sure it's the correct type
tmpVal := hcl2shim.HCL2ValueFromConfigValue(def)
// helper/schema used to allow setting "" to a bool
if val.Type() == cty.Bool && tmpVal.RawEquals(cty.StringVal("")) {
// return a warning about the conversion
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, "provider set empty string as default value for bool "+getAttr.Name)
tmpVal = cty.False
}
val, err = ctyconvert.Convert(tmpVal, val.Type())
if err != nil {
return val, fmt.Errorf("error setting default for %q: %w", getAttr.Name, err)
}
return val, nil
})
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
configVal, err = schemaBlock.CoerceValue(configVal)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(ctx, configVal, nil); err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
config := terraform.NewResourceConfigShimmed(configVal, schemaBlock)
logging.HelperSchemaTrace(ctx, "Calling downstream")
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, s.provider.Validate(config))
logging.HelperSchemaTrace(ctx, "Called downstream")
preparedConfigMP, err := msgpack.Marshal(configVal, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
resp.PreparedConfig = &tfprotov5.DynamicValue{MsgPack: preparedConfigMP}
return resp, nil
}
func (s *GRPCProviderServer) ValidateResourceTypeConfig(ctx context.Context, req *tfprotov5.ValidateResourceTypeConfigRequest) (*tfprotov5.ValidateResourceTypeConfigResponse, error) {
ctx = logging.InitContext(ctx)
resp := &tfprotov5.ValidateResourceTypeConfigResponse{}
schemaBlock := s.getResourceSchemaBlock(req.TypeName)
configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
if req.ClientCapabilities == nil || !req.ClientCapabilities.WriteOnlyAttributesAllowed {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, validateWriteOnlyNullValues(configVal, schemaBlock, cty.Path{}))
}
r := s.provider.ResourcesMap[req.TypeName]
// Calling all ValidateRawResourceConfigFunc here since they validate on the raw go-cty config value
// and were introduced after the public provider.ValidateResource method.
if r.ValidateRawResourceConfigFuncs != nil {
writeOnlyAllowed := false
if req.ClientCapabilities != nil {
writeOnlyAllowed = req.ClientCapabilities.WriteOnlyAttributesAllowed
}
validateReq := ValidateResourceConfigFuncRequest{
WriteOnlyAttributesAllowed: writeOnlyAllowed,
RawConfig: configVal,
}
for _, validateFunc := range r.ValidateRawResourceConfigFuncs {
validateResp := &ValidateResourceConfigFuncResponse{}
validateFunc(ctx, validateReq, validateResp)
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, validateResp.Diagnostics)
}
}
config := terraform.NewResourceConfigShimmed(configVal, schemaBlock)
logging.HelperSchemaTrace(ctx, "Calling downstream")
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, s.provider.ValidateResource(req.TypeName, config))
logging.HelperSchemaTrace(ctx, "Called downstream")
return resp, nil
}
func (s *GRPCProviderServer) ValidateDataSourceConfig(ctx context.Context, req *tfprotov5.ValidateDataSourceConfigRequest) (*tfprotov5.ValidateDataSourceConfigResponse, error) {
ctx = logging.InitContext(ctx)
resp := &tfprotov5.ValidateDataSourceConfigResponse{}
schemaBlock := s.getDatasourceSchemaBlock(req.TypeName)
configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(ctx, configVal, nil); err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
config := terraform.NewResourceConfigShimmed(configVal, schemaBlock)
logging.HelperSchemaTrace(ctx, "Calling downstream")
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, s.provider.ValidateDataSource(req.TypeName, config))
logging.HelperSchemaTrace(ctx, "Called downstream")
return resp, nil
}
func (s *GRPCProviderServer) UpgradeResourceState(ctx context.Context, req *tfprotov5.UpgradeResourceStateRequest) (*tfprotov5.UpgradeResourceStateResponse, error) {
ctx = logging.InitContext(ctx)
resp := &tfprotov5.UpgradeResourceStateResponse{}
res, ok := s.provider.ResourcesMap[req.TypeName]
if !ok {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName))
return resp, nil
}
schemaBlock := s.getResourceSchemaBlock(req.TypeName)
version := int(req.Version)
jsonMap := map[string]interface{}{}
var err error
switch {
// We first need to upgrade a flatmap state if it exists.
// There should never be both a JSON and Flatmap state in the request.
case len(req.RawState.Flatmap) > 0:
logging.HelperSchemaTrace(ctx, "Upgrading flatmap state")
jsonMap, version, err = s.upgradeFlatmapState(ctx, version, req.RawState.Flatmap, res)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// if there's a JSON state, we need to decode it.
case len(req.RawState.JSON) > 0:
if res.UseJSONNumber {
err = unmarshalJSON(req.RawState.JSON, &jsonMap)
} else {
err = json.Unmarshal(req.RawState.JSON, &jsonMap)
}
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
default:
logging.HelperSchemaDebug(ctx, "no state provided to upgrade")
return resp, nil
}
// complete the upgrade of the JSON states
logging.HelperSchemaTrace(ctx, "Upgrading JSON state")
jsonMap, err = s.upgradeJSONState(ctx, version, jsonMap, res)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// The provider isn't required to clean out removed fields
s.removeAttributes(ctx, jsonMap, schemaBlock.ImpliedType())
// now we need to turn the state into the default json representation, so
// that it can be re-decoded using the actual schema.
val, err := JSONMapToStateValue(jsonMap, schemaBlock)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// Now we need to make sure blocks are represented correctly, which means
// that missing blocks are empty collections, rather than null.
// First we need to CoerceValue to ensure that all object types match.
val, err = schemaBlock.CoerceValue(val)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// Normalize the value and fill in any missing blocks.
val = objchange.NormalizeObjectFromLegacySDK(val, schemaBlock)
// Set any write-only attribute values to null
val = setWriteOnlyNullValues(val, schemaBlock)
// encode the final state to the expected msgpack format
newStateMP, err := msgpack.Marshal(val, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
resp.UpgradedState = &tfprotov5.DynamicValue{MsgPack: newStateMP}
return resp, nil
}
// upgradeFlatmapState takes a legacy flatmap state, upgrades it using Migrate
// state if necessary, and converts it to the new JSON state format decoded as a
// map[string]interface{}.
// upgradeFlatmapState returns the json map along with the corresponding schema
// version.
func (s *GRPCProviderServer) upgradeFlatmapState(_ context.Context, version int, m map[string]string, res *Resource) (map[string]interface{}, int, error) {
// this will be the version we've upgraded so, defaulting to the given
// version in case no migration was called.
upgradedVersion := version
// first determine if we need to call the legacy MigrateState func
requiresMigrate := version < res.SchemaVersion
schemaType := res.CoreConfigSchema().ImpliedType()
// if there are any StateUpgraders, then we need to only compare
// against the first version there
if len(res.StateUpgraders) > 0 {
requiresMigrate = version < res.StateUpgraders[0].Version
}
if requiresMigrate && res.MigrateState == nil {
// Providers were previously allowed to bump the version
// without declaring MigrateState.
// If there are further upgraders, then we've only updated that far.
if len(res.StateUpgraders) > 0 {
schemaType = res.StateUpgraders[0].Type
upgradedVersion = res.StateUpgraders[0].Version
}
} else if requiresMigrate {
is := &terraform.InstanceState{
ID: m["id"],
Attributes: m,
Meta: map[string]interface{}{
"schema_version": strconv.Itoa(version),
},
}
is, err := res.MigrateState(version, is, s.provider.Meta())
if err != nil {
return nil, 0, err
}
// re-assign the map in case there was a copy made, making sure to keep
// the ID
m := is.Attributes
m["id"] = is.ID
// if there are further upgraders, then we've only updated that far
if len(res.StateUpgraders) > 0 {
schemaType = res.StateUpgraders[0].Type
upgradedVersion = res.StateUpgraders[0].Version
}
} else {
// the schema version may be newer than the MigrateState functions
// handled and older than the current, but still stored in the flatmap
// form. If that's the case, we need to find the correct schema type to
// convert the state.
for _, upgrader := range res.StateUpgraders {
if upgrader.Version == version {
schemaType = upgrader.Type
break
}
}
}
// now we know the state is up to the latest version that handled the
// flatmap format state. Now we can upgrade the format and continue from
// there.
newConfigVal, err := hcl2shim.HCL2ValueFromFlatmap(m, schemaType)
if err != nil {
return nil, 0, err
}
jsonMap, err := stateValueToJSONMap(newConfigVal, schemaType, res.UseJSONNumber)
return jsonMap, upgradedVersion, err
}
func (s *GRPCProviderServer) upgradeJSONState(ctx context.Context, version int, m map[string]interface{}, res *Resource) (map[string]interface{}, error) {
var err error
for _, upgrader := range res.StateUpgraders {
if version != upgrader.Version {
continue
}
m, err = upgrader.Upgrade(ctx, m, s.provider.Meta())
if err != nil {
return nil, err
}
version++
}
return m, nil
}
// Remove any attributes no longer present in the schema, so that the json can
// be correctly decoded.
func (s *GRPCProviderServer) removeAttributes(ctx context.Context, v interface{}, ty cty.Type) {
// we're only concerned with finding maps that correspond to object
// attributes
switch v := v.(type) {
case []interface{}:
// If these aren't blocks the next call will be a noop
if ty.IsListType() || ty.IsSetType() {
eTy := ty.ElementType()
for _, eV := range v {
s.removeAttributes(ctx, eV, eTy)
}
}
return
case map[string]interface{}:
// map blocks aren't yet supported, but handle this just in case
if ty.IsMapType() {
eTy := ty.ElementType()
for _, eV := range v {
s.removeAttributes(ctx, eV, eTy)
}
return
}
if ty == cty.DynamicPseudoType {
logging.HelperSchemaDebug(ctx, "ignoring dynamic block", map[string]interface{}{"block": v})
return
}
if !ty.IsObjectType() {
// This shouldn't happen, and will fail to decode further on, so
// there's no need to handle it here.
logging.HelperSchemaWarn(ctx, "unexpected type for map in JSON state", map[string]interface{}{"type": ty})
return
}
attrTypes := ty.AttributeTypes()
for attr, attrV := range v {
attrTy, ok := attrTypes[attr]
if !ok {
logging.HelperSchemaDebug(ctx, "attribute no longer present in schema", map[string]interface{}{"attribute": attr})
delete(v, attr)
continue
}
s.removeAttributes(ctx, attrV, attrTy)
}
}
}
func (s *GRPCProviderServer) StopProvider(ctx context.Context, _ *tfprotov5.StopProviderRequest) (*tfprotov5.StopProviderResponse, error) {
ctx = logging.InitContext(ctx)
logging.HelperSchemaTrace(ctx, "Stopping provider")
s.stopMu.Lock()
defer s.stopMu.Unlock()
// stop
close(s.stopCh)
// reset the stop signal
s.stopCh = make(chan struct{})
logging.HelperSchemaTrace(ctx, "Stopped provider")
return &tfprotov5.StopProviderResponse{}, nil
}
func (s *GRPCProviderServer) ConfigureProvider(ctx context.Context, req *tfprotov5.ConfigureProviderRequest) (*tfprotov5.ConfigureProviderResponse, error) {
ctx = logging.InitContext(ctx)
resp := &tfprotov5.ConfigureProviderResponse{}
schemaBlock := s.getProviderSchemaBlock()
configVal, err := msgpack.Unmarshal(req.Config.MsgPack, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
s.provider.TerraformVersion = req.TerraformVersion
// Ensure there are no nulls that will cause helper/schema to panic.
if err := validateConfigNulls(ctx, configVal, nil); err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
config := terraform.NewResourceConfigShimmed(configVal, schemaBlock)
// CtyValue is the raw protocol configuration data from newer APIs.
//
// This field was only added as a targeted fix for passing raw protocol data
// through the existing (helper/schema.Provider).Configure() exported method
// and is only populated in that situation. The data could theoretically be
// set in the NewResourceConfigShimmed() function, however the consequences
// of doing this were not investigated at the time the fix was introduced.
//
// Reference: https://github.com/hashicorp/terraform-plugin-sdk/issues/1270
config.CtyValue = configVal
// TODO: remove global stop context hack
// This attaches a global stop synchro'd context onto the provider.Configure
// request scoped context. This provides a substitute for the removed provider.StopContext()
// function. Ideally a provider should migrate to the context aware API that receives
// request scoped contexts, however this is a large undertaking for very large providers.
ctxHack := context.WithValue(ctx, StopContextKey, s.StopContext(context.Background()))
// NOTE: This is a hack to pass the deferral_allowed field from the Terraform client to the
// underlying (provider).Configure function, which cannot be changed because the function
// signature is public. (╯°□°)╯︵ ┻━┻
s.provider.deferralAllowed = configureDeferralAllowed(req.ClientCapabilities)
logging.HelperSchemaTrace(ctx, "Calling downstream")
diags := s.provider.Configure(ctxHack, config)
logging.HelperSchemaTrace(ctx, "Called downstream")
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, diags)
if s.provider.providerDeferred != nil {
// Check if a deferred response was incorrectly set on the provider. This would cause an error during later RPCs.
if !s.provider.deferralAllowed {
resp.Diagnostics = append(resp.Diagnostics, &tfprotov5.Diagnostic{
Severity: tfprotov5.DiagnosticSeverityError,
Summary: "Invalid Deferred Provider Response",
Detail: "Provider configured a deferred response for all resources and data sources but the Terraform request " +
"did not indicate support for deferred actions. This is an issue with the provider and should be reported to the provider developers.",
})
} else {
logging.HelperSchemaDebug(
ctx,
"Provider has configured a deferred response, all associated resources and data sources will automatically return a deferred response.",
map[string]interface{}{
logging.KeyDeferredReason: s.provider.providerDeferred.Reason.String(),
},
)
}
}
return resp, nil
}
func (s *GRPCProviderServer) ReadResource(ctx context.Context, req *tfprotov5.ReadResourceRequest) (*tfprotov5.ReadResourceResponse, error) {
ctx = logging.InitContext(ctx)
readFollowingImport := false
reqPrivate := req.Private
if reqPrivate != nil {
// unmarshal the private data
if len(reqPrivate) > 0 {
newReqPrivate := make(map[string]interface{})
if err := json.Unmarshal(reqPrivate, &newReqPrivate); err != nil {
return nil, err
}
// This internal private field is set on a resource during ImportResourceState to help framework determine if
// the resource has been recently imported. We only need to read this once, so we immediately clear it after.
if _, ok := newReqPrivate[terraform.ImportBeforeReadMetaKey]; ok {
readFollowingImport = true
delete(newReqPrivate, terraform.ImportBeforeReadMetaKey)
if len(newReqPrivate) == 0 {
// if there are no other private data, set the private data to nil
reqPrivate = nil
} else {
// set the new private data without the import key
bytes, err := json.Marshal(newReqPrivate)
if err != nil {
return nil, err
}
reqPrivate = bytes
}
}
}
}
resp := &tfprotov5.ReadResourceResponse{
// helper/schema did previously handle private data during refresh, but
// core is now going to expect this to be maintained in order to
// persist it in the state.
Private: reqPrivate,
}
res, ok := s.provider.ResourcesMap[req.TypeName]
if !ok {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("unknown resource type: %s", req.TypeName))
return resp, nil
}
schemaBlock := s.getResourceSchemaBlock(req.TypeName)
if s.provider.providerDeferred != nil {
logging.HelperSchemaDebug(
ctx,
"Provider has deferred response configured, automatically returning deferred response.",
map[string]interface{}{
logging.KeyDeferredReason: s.provider.providerDeferred.Reason.String(),
},
)
resp.NewState = req.CurrentState
resp.NewIdentity = req.CurrentIdentity
resp.Deferred = &tfprotov5.Deferred{
Reason: tfprotov5.DeferredReason(s.provider.providerDeferred.Reason),
}
return resp, nil
}
stateVal, err := msgpack.Unmarshal(req.CurrentState.MsgPack, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
instanceState, err := res.ShimInstanceStateFromValue(stateVal)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
instanceState.RawState = stateVal
var currentIdentityVal cty.Value
if req.CurrentIdentity != nil && req.CurrentIdentity.IdentityData != nil {
// convert req.CurrentIdentity to flat map identity structure
// Step 1: Turn JSON into cty.Value based on schema
identityBlock, err := s.getResourceIdentitySchemaBlock(req.TypeName)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("getting identity schema failed for resource '%s': %w", req.TypeName, err))
return resp, nil
}
currentIdentityVal, err = msgpack.Unmarshal(req.CurrentIdentity.IdentityData.MsgPack, identityBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
// Step 2: Turn cty.Value into flatmap representation
identityAttrs := hcl2shim.FlatmapValueFromHCL2(currentIdentityVal)
// Step 3: Well, set it in the instanceState
instanceState.Identity = identityAttrs
}
private := make(map[string]interface{})
if len(reqPrivate) > 0 {
if err := json.Unmarshal(reqPrivate, &private); err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
}
instanceState.Meta = private
pmSchemaBlock := s.getProviderMetaSchemaBlock()
if pmSchemaBlock != nil && req.ProviderMeta != nil {
providerSchemaVal, err := msgpack.Unmarshal(req.ProviderMeta.MsgPack, pmSchemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
instanceState.ProviderMeta = providerSchemaVal
}
newInstanceState, diags := res.RefreshWithoutUpgrade(ctx, instanceState, s.provider.Meta())
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, diags)
if diags.HasError() {
return resp, nil
}
if newInstanceState == nil || newInstanceState.ID == "" {
// The old provider API used an empty id to signal that the remote
// object appears to have been deleted, but our new protocol expects
// to see a null value (in the cty sense) in that case.
newStateMP, err := msgpack.Marshal(cty.NullVal(schemaBlock.ImpliedType()), schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
}
resp.NewState = &tfprotov5.DynamicValue{
MsgPack: newStateMP,
}
return resp, nil
}
// helper/schema should always copy the ID over, but do it again just to be safe
newInstanceState.Attributes["id"] = newInstanceState.ID
newStateVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Attributes, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
newStateVal = normalizeNullValues(newStateVal, stateVal, false)
newStateVal = copyTimeoutValues(newStateVal, stateVal)
newStateVal = setWriteOnlyNullValues(newStateVal, schemaBlock)
newStateMP, err := msgpack.Marshal(newStateVal, schemaBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
resp.NewState = &tfprotov5.DynamicValue{
MsgPack: newStateMP,
}
if newInstanceState.Identity != nil {
identityBlock, err := s.getResourceIdentitySchemaBlock(req.TypeName)
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("getting identity schema failed for resource '%s': %w", req.TypeName, err))
return resp, nil
}
newIdentityVal, err := hcl2shim.HCL2ValueFromFlatmap(newInstanceState.Identity, identityBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
if isCtyObjectNullOrEmpty(newIdentityVal) {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf(
"Missing Resource Identity After Read: The Terraform provider unexpectedly returned no resource identity after having no errors in the resource read. "+
"This is always a problem with the provider and should be reported to the provider developer",
))
return resp, nil
}
// If we're refreshing the resource state (excluding a recently imported resource), validate that the new identity isn't changing
if !res.ResourceBehavior.MutableIdentity && !readFollowingImport && !isCtyObjectNullOrEmpty(currentIdentityVal) && !currentIdentityVal.RawEquals(newIdentityVal) {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, fmt.Errorf("Unexpected Identity Change: %s", "During the read operation, the Terraform Provider unexpectedly returned a different identity then the previously stored one.\n\n"+
"This is always a problem with the provider and should be reported to the provider developer.\n\n"+
fmt.Sprintf("Current Identity: %s\n\n", currentIdentityVal.GoString())+
fmt.Sprintf("New Identity: %s", newIdentityVal.GoString())))
return resp, nil
}
newIdentityMP, err := msgpack.Marshal(newIdentityVal, identityBlock.ImpliedType())
if err != nil {
resp.Diagnostics = convert.AppendProtoDiag(ctx, resp.Diagnostics, err)
return resp, nil
}
resp.NewIdentity = &tfprotov5.ResourceIdentityData{
IdentityData: &tfprotov5.DynamicValue{
MsgPack: newIdentityMP,
},
}
}