-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
resource.go
1757 lines (1476 loc) · 54 KB
/
resource.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 2024 Google Inc.
// 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 api
import (
"fmt"
"log"
"maps"
"regexp"
"sort"
"strings"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/api/product"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/api/resource"
"github.com/GoogleCloudPlatform/magic-modules/mmv1/google"
"golang.org/x/exp/slices"
)
type Resource struct {
Name string
// original value of :name before the provider override happens
// same as :name if not overridden in provider
ApiName string `yaml:"api_name,omitempty"`
// [Required] A description of the resource that's surfaced in provider
// documentation.
Description string
// [Required] Reference links provided in
// downstream documentation. Expected to follow the format as follows:
//
// references:
// guides:
// 'Guide name': 'official_documentation_url'
// api: 'rest_api_reference_url/version'
//
References resource.ReferenceLinks `yaml:"references,omitempty"`
// [Required] The GCP "relative URI" of a resource, relative to the product
// base URL. It can often be inferred from the `create` path.
BaseUrl string `yaml:"base_url,omitempty"`
// ====================
// Common Configuration
// ====================
//
// [Optional] The minimum API version this resource is in. Defaults to ga.
MinVersion string `yaml:"min_version,omitempty"`
// [Optional] If set to true, don't generate the resource.
Exclude bool `yaml:"exclude,omitempty"`
// [Optional] If set to true, the resource is not able to be updated.
Immutable bool `yaml:"immutable,omitempty"`
// [Optional] If set to true, this resource uses an update mask to perform
// updates. This is typical of newer GCP APIs.
UpdateMask bool `yaml:"update_mask,omitempty"`
// [Optional] If set to true, the object has a `self_link` field. This is
// typical of older GCP APIs.
HasSelfLink bool `yaml:"has_self_link,omitempty"`
// [Optional] The validator "relative URI" of a resource, relative to the product
// base URL. Specific to defining the resource as a CAI asset.
CaiBaseUrl string `yaml:"cai_base_url,omitempty"`
// ====================
// URL / HTTP Configuration
// ====================
//
// [Optional] The "identity" URL of the resource. Defaults to:
// * base_url when the create_verb is POST
// * self_link when the create_verb is PUT or PATCH
SelfLink string `yaml:"self_link,omitempty"`
// [Optional] The URL used to creating the resource. Defaults to:
// * collection url when the create_verb is POST
// * self_link when the create_verb is PUT or PATCH
CreateUrl string `yaml:"create_url,omitempty"`
// [Optional] The URL used to delete the resource. Defaults to the self
// link.
DeleteUrl string `yaml:"delete_url,omitempty"`
// [Optional] The URL used to update the resource. Defaults to the self
// link.
UpdateUrl string `yaml:"update_url,omitempty"`
// [Optional] The HTTP verb used during create. Defaults to POST.
CreateVerb string `yaml:"create_verb,omitempty"`
// [Optional] The HTTP verb used during read. Defaults to GET.
ReadVerb string `yaml:"read_verb,omitempty"`
// [Optional] The HTTP verb used during update. Defaults to PUT.
UpdateVerb string `yaml:"update_verb,omitempty"`
// [Optional] The HTTP verb used during delete. Defaults to DELETE.
DeleteVerb string `yaml:"delete_verb,omitempty"`
// [Optional] Additional Query Parameters to append to GET. Defaults to ""
ReadQueryParams string `yaml:"read_query_params,omitempty"`
// ====================
// Collection / Identity URL Configuration
// ====================
//
// [Optional] This is the name of the list of items
// within the collection (list) json. Will default to the
// camelcase plural name of the resource.
CollectionUrlKey string `yaml:"collection_url_key,omitempty"`
// [Optional] An ordered list of names of parameters that uniquely identify
// the resource.
// Generally, it's safe to leave empty, in which case it defaults to `name`.
// Other values are normally useful in cases where an object has a parent
// and is identified by some non-name value, such as an ip+port pair.
// If you're writing a fine-grained resource (eg with nested_query) a value
// must be set.
Identity []string `yaml:"identity,omitempty"`
// [Optional] (Api::Resource::NestedQuery) This is useful in case you need
// to change the query made for GET requests only. In particular, this is
// often used to extract an object from a parent object or a collection.
// Note that if both nested_query and custom_code.decoder are provided,
// the decoder will be included within the code handling the nested query.
NestedQuery *resource.NestedQuery `yaml:"nested_query,omitempty"`
// ====================
// IAM Configuration
// ====================
//
// [Optional] (Api::Resource::IamPolicy) Configuration of a resource's
// resource-specific IAM Policy.
IamPolicy *resource.IamPolicy `yaml:"iam_policy,omitempty"`
// [Optional] If set to true, don't generate the resource itself; only
// generate the IAM policy.
// TODO rewrite: rename?
ExcludeResource bool `yaml:"exclude_resource,omitempty"`
// [Optional] GCP kind, e.g. `compute//disk`
Kind string `yaml:"kind,omitempty"`
// [Optional] If set to true, indicates that a resource is not configurable
// such as GCP regions.
Readonly bool `yaml:"readonly,omitempty"`
// ====================
// Terraform Overrides
// ====================
// [Optional] If non-empty, overrides the full filename prefix
// i.e. google/resource_product_{{resource_filename_override}}.go
// i.e. google/resource_product_{{resource_filename_override}}_test.go
FilenameOverride string `yaml:"filename_override,omitempty"`
// If non-empty, overrides the full given resource name.
// i.e. 'google_project' for resourcemanager.Project
// Use Provider::Terraform::Config.legacy_name to override just
// product name.
// Note: This should not be used for vanity names for new products.
// This was added to handle preexisting handwritten resources that
// don't match the natural generated name exactly, and to support
// services with a mix of handwritten and generated resources.
LegacyName string `yaml:"legacy_name,omitempty"`
// The Terraform resource id format used when calling //setId(...).
// For instance, `{{name}}` means the id will be the resource name.
IdFormat string `yaml:"id_format,omitempty"`
// Override attribute used to handwrite the formats for generating regex strings
// that match templated values to a self_link when importing, only necessary when
// a resource is not adequately covered by the standard provider generated options.
// Leading a token with `%`
// i.e. {{%parent}}/resource/{{resource}}
// will allow that token to hold multiple /'s.
//
// Expected to be formatted as follows:
//
// import_format:
// - example_import_one
// - example_import_two
//
ImportFormat []string `yaml:"import_format,omitempty"`
CustomCode resource.CustomCode `yaml:"custom_code,omitempty"`
Docs resource.Docs `yaml:"docs,omitempty"`
// This block inserts entries into the customdiff.All() block in the
// resource schema -- the code for these custom diff functions must
// be included in the resource constants or come from tpgresource
CustomDiff []string `yaml:"custom_diff,omitempty"`
// Lock name for a mutex to prevent concurrent API calls for a given
// resource.
Mutex string `yaml:"mutex,omitempty"`
// Examples in documentation. Backed by generated tests, and have
// corresponding OiCS walkthroughs.
Examples []resource.Examples
// If true, generates product operation handling logic.
AutogenAsync bool `yaml:"autogen_async,omitempty"`
// If true, resource is not importable
ExcludeImport bool `yaml:"exclude_import,omitempty"`
// If true, exclude resource from Terraform Validator
// (i.e. terraform-provider-conversion)
ExcludeTgc bool `yaml:"exclude_tgc,omitempty"`
// If true, skip sweeper generation for this resource
ExcludeSweeper bool `yaml:"exclude_sweeper,omitempty"`
// Override sweeper settings
Sweeper resource.Sweeper `yaml:"sweeper,omitempty"`
Timeouts *Timeouts `yaml:"timeouts,omitempty"`
// An array of function names that determine whether an error is retryable.
ErrorRetryPredicates []string `yaml:"error_retry_predicates,omitempty"`
// An array of function names that determine whether an error is not retryable.
ErrorAbortPredicates []string `yaml:"error_abort_predicates,omitempty"`
// Optional attributes for declaring a resource's current version and generating
// state_upgrader code to the output .go file from files stored at
// mmv1/templates/terraform/state_migrations/
// used for maintaining state stability with resources first provisioned on older api versions.
SchemaVersion int `yaml:"schema_version,omitempty"`
// From this schema version on, state_upgrader code is generated for the resource.
// When unset, state_upgrade_base_schema_version defauts to 0.
// Normally, it is not needed to be set.
StateUpgradeBaseSchemaVersion int `yaml:"state_upgrade_base_schema_version,omitempty"`
StateUpgraders bool `yaml:"state_upgraders,omitempty"`
// Do not apply the default attribution label
ExcludeAttributionLabel bool `yaml:"exclude_attribution_label,omitempty"`
// This block inserts the named function and its attribute into the
// resource schema -- the code for the migrate_state function must
// be included in the resource constants or come from tpgresource
// included for backwards compatibility as an older state migration method
// and should not be used for new resources.
MigrateState string `yaml:"migrate_state,omitempty"`
// Set to true for resources that are unable to be deleted, such as KMS keyrings or project
// level resources such as firebase project
ExcludeDelete bool `yaml:"exclude_delete,omitempty"`
// Set to true for resources that are unable to be read from the API, such as
// public ca external account keys
ExcludeRead bool `yaml:"exclude_read,omitempty"`
// Set to true for resources that wish to disable automatic generation of default provider
// value customdiff functions
// TODO rewrite: 1 instance used
ExcludeDefaultCdiff bool `yaml:"exclude_default_cdiff,omitempty"`
// This enables resources that get their project via a reference to a different resource
// instead of a project field to use User Project Overrides
SupportsIndirectUserProjectOverride bool `yaml:"supports_indirect_user_project_override,omitempty"`
// If true, the resource's project field can be specified as either the short form project
// id or the long form projects/project-id. The extra projects/ string will be removed from
// urls and ids. This should only be used for resources that previously supported long form
// project ids for backwards compatibility.
LegacyLongFormProject bool `yaml:"legacy_long_form_project,omitempty"`
// Function to transform a read error so that handleNotFound recognises
// it as a 404. This should be added as a handwritten fn that takes in
// an error and returns one.
ReadErrorTransform string `yaml:"read_error_transform,omitempty"`
// If true, resources that failed creation will be marked as tainted. As a consequence
// these resources will be deleted and recreated on the next apply call. This pattern
// is preferred over deleting the resource directly in post_create_failure hooks.
TaintResourceOnFailedCreate bool `yaml:"taint_resource_on_failed_create,omitempty"`
// Add a deprecation message for a resource that's been deprecated in the API.
DeprecationMessage string `yaml:"deprecation_message,omitempty"`
Async *Async
// Tag autogen resources so that we can track them. In the future this will
// control if a resource is continuously generated from public OpenAPI docs
AutogenStatus string `yaml:"autogen_status"`
// The three groups of []*Type fields are expected to be strictly ordered within a yaml file
// in the sequence of Virtual Fields -> Parameters -> Properties
// Virtual fields are Terraform-only fields that control Terraform's
// behaviour. They don't map to underlying API fields (although they
// may map to parameters), and will require custom code to be added to
// control them.
//
// Virtual fields are similar to url_param_only fields in that they create
// a schema entry which is not read from or submitted to the API. However
// virtual fields are meant to provide toggles for Terraform-specific behavior in a resource
// (eg: delete_contents_on_destroy) whereas url_param_only fields _should_
// be used for url construction.
//
// Both are resource level fields and do not make sense, and are also not
// supported, for nested fields. Nested fields that shouldn't be included
// in API payloads are better handled with custom expand/encoder logic.
VirtualFields []*Type `yaml:"virtual_fields,omitempty"`
Parameters []*Type
Properties []*Type
ProductMetadata *Product `yaml:"-"`
// The version name provided by the user through CI
TargetVersionName string `yaml:"-"`
// The compiler to generate the downstream files, for example "terraformgoogleconversion-codegen".
Compiler string `yaml:"-"`
ApiResourceTypeKind string `yaml:"api_resource_type_kind,omitempty"`
ImportPath string `yaml:"-"`
}
func (r *Resource) UnmarshalYAML(unmarshal func(any) error) error {
type resourceAlias Resource
aliasObj := (*resourceAlias)(r)
err := unmarshal(aliasObj)
if err != nil {
return err
}
return nil
}
func (r *Resource) SetDefault(product *Product) {
if r.CreateVerb == "" {
r.CreateVerb = "POST"
}
if r.ReadVerb == "" {
r.ReadVerb = "GET"
}
if r.DeleteVerb == "" {
r.DeleteVerb = "DELETE"
}
if r.UpdateVerb == "" {
r.UpdateVerb = "PUT"
}
if r.ApiName == "" {
r.ApiName = r.Name
}
if r.CollectionUrlKey == "" {
r.CollectionUrlKey = google.Camelize(google.Plural(r.Name), "lower")
}
if r.IdFormat == "" {
r.IdFormat = r.SelfLinkUri()
}
if len(r.VirtualFields) > 0 {
for _, f := range r.VirtualFields {
f.ClientSide = true
}
}
r.ProductMetadata = product
for _, property := range r.AllProperties() {
property.SetDefault(r)
}
for _, vf := range r.VirtualFields {
vf.SetDefault(r)
}
if r.IamPolicy != nil && r.IamPolicy.MinVersion == "" {
r.IamPolicy.MinVersion = r.MinVersion
}
if r.Timeouts == nil {
r.Timeouts = NewTimeouts()
}
}
func (r *Resource) Validate() {
if r.Name == "" {
log.Fatalf("Missing `name` for resource")
}
if r.NestedQuery != nil && r.NestedQuery.IsListOfIds && len(r.Identity) != 1 {
log.Fatalf("`is_list_of_ids: true` implies resource has exactly one `identity` property")
}
// Ensures we have all properties defined
for _, i := range r.Identity {
hasIdentify := slices.ContainsFunc(r.AllUserProperties(), func(p *Type) bool {
return p.Name == i
})
if !hasIdentify {
log.Fatalf("Missing property/parameter for identity %s", i)
}
}
if r.Description == "" {
log.Fatalf("Missing `description` for resource %s", r.Name)
}
if !r.Exclude {
if len(r.Properties) == 0 {
log.Fatalf("Missing `properties` for resource %s", r.Name)
}
}
allowed := []string{"POST", "PUT", "PATCH"}
if !slices.Contains(allowed, r.CreateVerb) {
log.Fatalf("Value on `create_verb` should be one of %#v", allowed)
}
allowed = []string{"GET", "POST"}
if !slices.Contains(allowed, r.ReadVerb) {
log.Fatalf("Value on `read_verb` should be one of %#v", allowed)
}
allowed = []string{"POST", "PUT", "PATCH", "DELETE"}
if !slices.Contains(allowed, r.DeleteVerb) {
log.Fatalf("Value on `delete_verb` should be one of %#v", allowed)
}
allowed = []string{"POST", "PUT", "PATCH"}
if !slices.Contains(allowed, r.UpdateVerb) {
log.Fatalf("Value on `update_verb` should be one of %#v", allowed)
}
for _, property := range r.AllProperties() {
property.Validate(r.Name)
}
if r.IamPolicy != nil {
r.IamPolicy.Validate(r.Name)
}
if r.NestedQuery != nil {
r.NestedQuery.Validate(r.Name)
}
for _, example := range r.Examples {
example.Validate(r.Name)
}
if r.Async != nil {
r.Async.Validate()
}
}
// ====================
// Custom Getters and Setters
// ====================
// Returns all properties and parameters including the ones that are
// excluded. This is used for PropertyOverride validation
func (r Resource) AllProperties() []*Type {
return google.Concat(r.Properties, r.Parameters)
}
func (r Resource) AllPropertiesInVersion() []*Type {
return google.Reject(google.Concat(r.Properties, r.Parameters), func(p *Type) bool {
return p.Exclude
})
}
func (r Resource) PropertiesWithExcluded() []*Type {
return r.Properties
}
func (r Resource) UserProperites() []*Type {
return google.Reject(r.Properties, func(p *Type) bool {
return p.Exclude
})
}
func (r Resource) UserParameters() []*Type {
return google.Reject(r.Parameters, func(p *Type) bool {
return p.Exclude
})
}
func (r Resource) ServiceVersion() string {
if r.CaiBaseUrl != "" {
return extractVersionFromBaseUrl(r.CaiBaseUrl)
}
return extractVersionFromBaseUrl(r.BaseUrl)
}
func extractVersionFromBaseUrl(baseUrl string) string {
parts := strings.Split(baseUrl, "/")
// starts with v...
if parts[0] != "" && parts[0][0] == 'v' {
return parts[0]
}
// starts with /v...
if parts[0] == "" && parts[1][0] == 'v' {
return parts[1]
}
return ""
}
// Return the user-facing properties in client tools; this ends up meaning
// both properties and parameters but without any that are excluded due to
// version mismatches or manual exclusion
func (r Resource) AllUserProperties() []*Type {
return google.Concat(r.UserProperites(), r.UserParameters())
}
func (r Resource) RequiredProperties() []*Type {
return google.Select(r.AllUserProperties(), func(p *Type) bool {
return p.Required
})
}
func (r Resource) AllNestedProperties(props []*Type) []*Type {
nested := props
for _, prop := range props {
if nestedProperties := prop.NestedProperties(); !prop.FlattenObject && nestedProperties != nil {
nested = google.Concat(nested, r.AllNestedProperties(nestedProperties))
}
}
return nested
}
func (r Resource) SensitiveProps() []*Type {
props := r.AllNestedProperties(r.RootProperties())
return google.Select(props, func(p *Type) bool {
return p.Sensitive
})
}
func (r Resource) SensitivePropsToString() string {
var props []string
for _, prop := range r.SensitiveProps() {
props = append(props, fmt.Sprintf("`%s`", prop.Lineage()))
}
return strings.Join(props, ", ")
}
// All settable properties in the resource.
// Fingerprints aren't *really" settable properties, but they behave like one.
// At Create, they have no value but they can just be read in anyways, and after a Read
// they will need to be set in every Update.
func (r Resource) SettableProperties() []*Type {
props := make([]*Type, 0)
props = google.Reject(r.AllUserProperties(), func(v *Type) bool {
return v.Output && !v.IsA("Fingerprint") && !v.IsA("KeyValueEffectiveLabels")
})
props = google.Reject(props, func(v *Type) bool {
return v.UrlParamOnly
})
props = google.Reject(props, func(v *Type) bool {
return v.IsA("KeyValueLabels") || v.IsA("KeyValueAnnotations")
})
return props
}
func (r Resource) IsSettableProperty(t *Type) bool {
return slices.Contains(r.SettableProperties(), t)
}
func (r Resource) UnorderedListProperties() []*Type {
return google.Select(r.SettableProperties(), func(t *Type) bool {
return t.UnorderedList
})
}
// Properties that will be returned in the API body
func (r Resource) GettableProperties() []*Type {
return google.Reject(r.AllUserProperties(), func(v *Type) bool {
return v.UrlParamOnly
})
}
// Returns the list of top-level properties once any nested objects with flatten_object
// set to true have been collapsed
func (r Resource) RootProperties() []*Type {
props := make([]*Type, 0)
for _, p := range r.AllUserProperties() {
if p.FlattenObject {
props = google.Concat(props, p.RootProperties())
} else {
props = append(props, p)
}
}
return props
}
// Return the product-level async object, or the resource-specific one
// if one exists.
func (r Resource) GetAsync() *Async {
if r.Async != nil {
return r.Async
}
return r.ProductMetadata.Async
}
// Return the resource-specific identity properties, or a best guess of the
// `name` value for the resource.
func (r Resource) GetIdentity() []*Type {
props := r.AllUserProperties()
if r.Identity != nil {
identities := google.Select(props, func(p *Type) bool {
return slices.Contains(r.Identity, p.Name)
})
slices.SortFunc(identities, func(a, b *Type) int {
return slices.Index(r.Identity, a.Name) - slices.Index(r.Identity, b.Name)
})
return identities
}
return google.Select(props, func(p *Type) bool {
return p.Name == "name"
})
}
func (r *Resource) AddLabelsRelatedFields(props []*Type, parent *Type) []*Type {
for _, p := range props {
if p.IsA("KeyValueLabels") {
props = r.addLabelsFields(props, parent, p)
} else if p.IsA("KeyValueAnnotations") {
props = r.addAnnotationsFields(props, parent, p)
} else if p.IsA("NestedObject") && len(p.AllProperties()) > 0 {
p.Properties = r.AddLabelsRelatedFields(p.AllProperties(), p)
}
}
return props
}
func (r *Resource) addLabelsFields(props []*Type, parent *Type, labels *Type) []*Type {
if parent == nil || parent.FlattenObject {
if r.ExcludeAttributionLabel {
r.CustomDiff = append(r.CustomDiff, "tpgresource.SetLabelsDiffWithoutAttributionLabel")
} else {
r.CustomDiff = append(r.CustomDiff, "tpgresource.SetLabelsDiff")
}
} else if parent.Name == "metadata" {
r.CustomDiff = append(r.CustomDiff, "tpgresource.SetMetadataLabelsDiff")
}
terraformLabelsField := buildTerraformLabelsField("labels", parent, labels)
effectiveLabelsField := buildEffectiveLabelsField("labels", labels)
props = append(props, terraformLabelsField, effectiveLabelsField)
// The effective_labels field is used to write to API, instead of the labels field.
labels.IgnoreWrite = true
labels.Description = fmt.Sprintf("%s\n\n%s", labels.Description, getLabelsFieldNote(labels.Name))
if parent == nil {
labels.Immutable = false
}
return props
}
func (r *Resource) HasLabelsField() bool {
for _, p := range r.Properties {
if p.Name == "labels" {
return true
}
}
return false
}
func (r *Resource) addAnnotationsFields(props []*Type, parent *Type, annotations *Type) []*Type {
// The effective_annotations field is used to write to API,
// instead of the annotations field.
annotations.IgnoreWrite = true
annotations.Description = fmt.Sprintf("%s\n\n%s", annotations.Description, getLabelsFieldNote(annotations.Name))
if parent == nil {
r.CustomDiff = append(r.CustomDiff, "tpgresource.SetAnnotationsDiff")
} else if parent.Name == "metadata" {
r.CustomDiff = append(r.CustomDiff, "tpgresource.SetMetadataAnnotationsDiff")
}
effectiveAnnotationsField := buildEffectiveLabelsField("annotations", annotations)
props = append(props, effectiveAnnotationsField)
return props
}
func buildEffectiveLabelsField(name string, labels *Type) *Type {
description := fmt.Sprintf("All of %s (key/value pairs) present on the resource in GCP, "+
"including the %s configured through Terraform, other clients and services.", name, name)
t := "KeyValueEffectiveLabels"
n := fmt.Sprintf("effective%s", strings.Title(name))
options := []func(*Type){
propertyWithType(t),
propertyWithOutput(true),
propertyWithDescription(description),
propertyWithMinVersion(labels.fieldMinVersion()),
propertyWithUpdateVerb(labels.UpdateVerb),
propertyWithUpdateUrl(labels.UpdateUrl),
propertyWithImmutable(labels.Immutable),
}
return NewProperty(n, name, options)
}
func buildTerraformLabelsField(name string, parent *Type, labels *Type) *Type {
description := fmt.Sprintf("The combination of %s configured directly on the resource\n"+
" and default %s configured on the provider.", name, name)
immutable := false
if parent != nil {
immutable = labels.Immutable
}
n := fmt.Sprintf("terraform%s", strings.Title(name))
options := []func(*Type){
propertyWithType("KeyValueTerraformLabels"),
propertyWithOutput(true),
propertyWithDescription(description),
propertyWithMinVersion(labels.fieldMinVersion()),
propertyWithIgnoreWrite(true),
propertyWithUpdateUrl(labels.UpdateUrl),
propertyWithImmutable(immutable),
}
return NewProperty(n, name, options)
}
// Check if the resource has root "labels" field
func (r Resource) RootLabels() bool {
for _, p := range r.RootProperties() {
if p.IsA("KeyValueLabels") {
return true
}
}
return false
}
// Return labels fields that should be added to ImportStateVerifyIgnore
func (r Resource) IgnoreReadLabelsFields(props []*Type) []string {
fields := make([]string, 0)
for _, p := range props {
if p.IsA("KeyValueLabels") ||
p.IsA("KeyValueTerraformLabels") ||
p.IsA("KeyValueAnnotations") {
fields = append(fields, p.TerraformLineage())
} else if p.IsA("NestedObject") && len(p.AllProperties()) > 0 {
fields = google.Concat(fields, r.IgnoreReadLabelsFields(p.AllProperties()))
}
}
return fields
}
func getLabelsFieldNote(title string) string {
return fmt.Sprintf(
"**Note**: This field is non-authoritative, and will only manage the %s present "+
"in your configuration.\n"+
"Please refer to the field `effective_%s` for all of the %s present on the resource.",
title, title, title)
}
func (r Resource) StateMigrationFile() string {
return fmt.Sprintf("templates/terraform/state_migrations/%s_%s.go.tmpl", google.Underscore(r.ProductMetadata.Name), google.Underscore(r.Name))
}
// ====================
// Version-related methods
// ====================
func (r Resource) MinVersionObj() *product.Version {
if r.MinVersion != "" {
return r.ProductMetadata.versionObj(r.MinVersion)
} else {
return r.ProductMetadata.lowestVersion()
}
}
func (r Resource) NotInVersion(version *product.Version) bool {
return version.CompareTo(r.MinVersionObj()) < 0
}
// Recurses through all nested properties and parameters and changes their
// 'exclude' instance variable if the property is at a version below the
// one that is passed in.
func (r *Resource) ExcludeIfNotInVersion(version *product.Version) {
if !r.Exclude {
r.Exclude = r.NotInVersion(version)
}
if r.Properties != nil {
for _, p := range r.Properties {
p.ExcludeIfNotInVersion(version)
}
}
if r.Parameters != nil {
for _, p := range r.Parameters {
p.ExcludeIfNotInVersion(version)
}
}
}
// ====================
// URL-related methods
// ====================
// Returns the "self_link_url" which is generally really the resource's GET
// URL. In older resources generally, this was the self_link value & was the
// product.base_url + resource.base_url + '/name'
// In newer resources there is much less standardisation in terms of value.
// Generally for them though, it's the product.base_url + resource.name
func (r Resource) SelfLinkUrl() string {
s := []string{r.ProductMetadata.BaseUrl, r.SelfLinkUri()}
return strings.Join(s, "")
}
// Returns the partial uri / relative path of a resource. In newer resources,
// this is the name. This fn is named self_link_uri for consistency, but
// could otherwise be considered to be "path"
func (r Resource) SelfLinkUri() string {
// If the terms in this are not snake-cased, this will require
// an override in Terraform.
if r.SelfLink != "" {
return r.SelfLink
}
return strings.Join([]string{r.BaseUrl, "{{name}}"}, "/")
}
func (r Resource) CollectionUrl() string {
s := []string{r.ProductMetadata.BaseUrl, r.collectionUri()}
return strings.Join(s, "")
}
func (r Resource) collectionUri() string {
return r.BaseUrl
}
func (r Resource) CreateUri() string {
if r.CreateUrl != "" {
return r.CreateUrl
}
if r.CreateVerb == "" || r.CreateVerb == "POST" {
return r.collectionUri()
}
return r.SelfLinkUri()
}
func (r Resource) UpdateUri() string {
if r.UpdateUrl != "" {
return r.UpdateUrl
}
return r.SelfLinkUri()
}
func (r Resource) DeleteUri() string {
if r.DeleteUrl != "" {
return r.DeleteUrl
}
return r.SelfLinkUri()
}
func (r Resource) ResourceName() string {
return fmt.Sprintf("%s%s", r.ProductMetadata.Name, r.Name)
}
// Filter the properties to keep only the ones don't have custom update
// method and group them by update url & verb.
func propertiesWithoutCustomUpdate(properties []*Type) []*Type {
return google.Select(properties, func(p *Type) bool {
return p.UpdateUrl == "" || p.UpdateVerb == "" || p.UpdateVerb == "NOOP"
})
}
func (r Resource) UpdateBodyProperties() []*Type {
updateProp := propertiesWithoutCustomUpdate(r.SettableProperties())
if r.UpdateVerb == "PATCH" {
updateProp = google.Reject(updateProp, func(p *Type) bool {
return p.Immutable
})
}
return updateProp
}
// Handwritten TF Operation objects will be shaped like accessContextManager
// while the Google Go Client will have a name like accesscontextmanager
func (r Resource) ClientNamePascal() string {
clientName := r.ProductMetadata.ClientName
if clientName == "" {
clientName = r.ProductMetadata.Name
}
return google.Camelize(clientName, "upper")
}
func (r Resource) PackageName() string {
return strings.ToLower(r.ProductMetadata.Name)
}
// In order of preference, use TF override,
// general defined timeouts, or default Timeouts
func (r Resource) GetTimeouts() *Timeouts {
timeoutsFiltered := r.Timeouts
if timeoutsFiltered == nil {
if async := r.GetAsync(); async != nil && async.Operation != nil {
timeoutsFiltered = async.Operation.Timeouts
}
if timeoutsFiltered == nil {
timeoutsFiltered = NewTimeouts()
}
}
return timeoutsFiltered
}
func (r Resource) HasProject() bool {
return strings.Contains(r.BaseUrl, "{{project}}") || strings.Contains(r.CreateUrl, "{{project}}")
}
func (r Resource) IncludeProjectForOperation() bool {
return strings.Contains(r.BaseUrl, "{{project}}") || (r.GetAsync().IsA("OpAsync") && r.GetAsync().IncludeProject)
}
func (r Resource) HasRegion() bool {
found := false
for _, p := range r.Parameters {
if p.Name == "region" && p.IgnoreRead {
found = true
break
}
}
return found && strings.Contains(r.BaseUrl, "{{region}}")
}
func (r Resource) HasZone() bool {
found := false
for _, p := range r.Parameters {
if p.Name == "zone" && p.IgnoreRead {
found = true
break
}
}
return found && strings.Contains(r.BaseUrl, "{{zone}}")
}
// resource functions needed for template that previously existed in terraform.go
// but due to how files are being inherited here it was easier to put in here
// taken wholesale from tpgtools
func (r Resource) Updatable() bool {
if !r.Immutable {
return true
}
for _, p := range r.AllPropertiesInVersion() {
if p.UpdateUrl != "" {
return true
}
}
return false
}
// ====================
// Debugging Methods
// ====================
// Prints a dot notation path to where the field is nested within the parent
// object when called on a property. eg: parent.meta.label.foo
// Redefined on Resource to terminate the calls up the parent chain.
func (r Resource) Lineage() string {
return r.Name
}