-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathmodel.go
More file actions
1322 lines (1247 loc) · 42.8 KB
/
Copy pathmodel.go
File metadata and controls
1322 lines (1247 loc) · 42.8 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 Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 model
import (
"errors"
"fmt"
"sort"
"strings"
awssdkmodel "github.com/aws-controllers-k8s/code-generator/pkg/api"
"github.com/aws-controllers-k8s/pkg/names"
ackgenconfig "github.com/aws-controllers-k8s/code-generator/pkg/config"
ackfp "github.com/aws-controllers-k8s/code-generator/pkg/fieldpath"
"github.com/aws-controllers-k8s/code-generator/pkg/generate/templateset"
"github.com/aws-controllers-k8s/code-generator/pkg/util"
)
var (
// ErrNilShapePointer indicates an unexpected nil Shape pointer
ErrNilShapePointer = errors.New("found nil Shape pointer")
)
// Model contains the ACK model for the generator to process and apply
// templates against.
type Model struct {
SDKAPI *SDKAPI
servicePackageName string
apiVersion string
crds []*CRD
typeDefs []*TypeDef
typeImports map[string]string
typeRenames map[string]string
// Instructions to the code generator how to handle the API and its
// resources
cfg *ackgenconfig.Config
docCfg *ackgenconfig.DocumentationConfig
}
// MetaVars returns a MetaVars struct populated with metadata about the AWS
// service API
func (m *Model) MetaVars() templateset.MetaVars {
controllerName := m.cfg.ControllerName
if controllerName == "" {
controllerName = m.servicePackageName
}
// NOTE(a-hilaly): I know this is a bit of a hack and it's confusing, but
// long time ago, we assumed that model_name is always equal to the service
// name. This is not the case anymore, prometheusservice and documentdb
// are examples of services that have different model names.
//
// TODO(a-hilaly): We should probably rework all this naming stuff to be
// more consistent. To whoever is reading this, I'm sorry.
servicePackageName := m.servicePackageName
if m.cfg.SDKNames.Package != "" {
servicePackageName = m.cfg.SDKNames.Package
}
return templateset.MetaVars{
ControllerName: controllerName,
ServicePackageName: servicePackageName,
ServiceID: m.SDKAPI.ServiceID(),
ServiceModelName: m.cfg.SDKNames.Model,
APIGroup: m.APIGroup(),
APIVersion: m.apiVersion,
ClientInterfaceTypeName: m.ClientInterfaceTypeName(),
ClientStructTypeName: m.ClientStructTypeName(),
CRDNames: m.crdNames(),
}
}
// crdNames returns all crd names lowercased and in plural
func (m *Model) crdNames() []string {
var crdConfigs []string
crds, _ := m.GetCRDs()
for _, crd := range crds {
crdConfigs = append(crdConfigs, strings.ToLower(crd.Plural))
}
return crdConfigs
}
// GetCRDs returns a slice of `CRD` structs that describe the
// top-level resources discovered by the code generator for an AWS service API
func (m *Model) GetCRDs() ([]*CRD, error) {
if m.crds != nil {
return m.crds, nil
}
crds := []*CRD{}
opMap, err := m.SDKAPI.GetOperationMap(m.cfg)
if err != nil {
return nil, err
}
createOps := (*opMap)[OpTypeCreate]
readOneOps := (*opMap)[OpTypeGet]
readManyOps := (*opMap)[OpTypeList]
updateOps := (*opMap)[OpTypeUpdate]
deleteOps := (*opMap)[OpTypeDelete]
getAttributesOps := (*opMap)[OpTypeGetAttributes]
setAttributesOps := (*opMap)[OpTypeSetAttributes]
// Validate generator config against SDK before building CRDs
sdkOps := make(map[string]struct{}, len(m.SDKAPI.API.Operations))
for opName := range m.SDKAPI.API.Operations {
sdkOps[opName] = struct{}{}
}
if validationErrs := ackgenconfig.ValidateConfig(m.cfg, sdkOps); len(validationErrs) > 0 {
msgs := make([]string, len(validationErrs))
for i, e := range validationErrs {
msgs[i] = e.Error()
}
return nil, fmt.Errorf("generator.yaml validation failed:\n %s", strings.Join(msgs, "\n "))
}
crdNameKeys := make([]string, 0, len(createOps))
for crdName := range createOps {
crdNameKeys = append(crdNameKeys, crdName)
}
sort.Strings(crdNameKeys)
for _, crdName := range crdNameKeys {
createOp := createOps[crdName]
if m.cfg.ResourceIsIgnored(crdName) {
continue
}
crdNames := names.New(crdName)
ops := Ops{
Create: createOps[crdName],
ReadOne: readOneOps[crdName],
ReadMany: readManyOps[crdName],
Update: updateOps[crdName],
Delete: deleteOps[crdName],
GetAttributes: getAttributesOps[crdName],
SetAttributes: setAttributesOps[crdName],
}
m.RemoveIgnoredOperations(&ops)
crd := NewCRD(m.SDKAPI, m.cfg, m.docCfg, crdNames, ops)
// OK, begin to gather the CRDFields that will go into the Spec struct.
// These fields are those members of the Create operation's Input
// Shape.
inputShape := createOp.InputRef.Shape
if inputShape == nil {
return nil, ErrNilShapePointer
}
// Check if there's an input wrapper field path configured. If so, we
// flatten the wrapper's fields into the Spec instead of creating a
// nested structure.
//
// NOTE(input_wrapper_field_path): We intentionally don't reuse
// CRD.GetInputShape() here because this code runs during CRD construction
// before the CRD is fully initialized. GetInputShape is designed for use
// after CRD construction (e.g., in code generation). The logic is similar
// but operates at different lifecycle stages.
inputWrapperFieldPath := m.cfg.GetInputWrapperFieldPath(createOp)
for _, memberName := range inputShape.MemberNames() {
memberShapeRef := inputShape.MemberRefs[memberName]
if memberShapeRef.Shape == nil {
return nil, ErrNilShapePointer
}
// Idempotency tokens are SDK implementation details that are
// auto-filled by the SDK middleware when nil. They should not
// be exposed in the CRD as they are not resource properties.
// This filtering is opt-in via resources.<name>.ignore_idempotency_token
// in generator.yaml.
resConfig := m.cfg.GetResourceConfig(crdName)
if resConfig != nil && resConfig.IgnoreIdempotencyToken &&
(memberShapeRef.IdempotencyToken || memberShapeRef.Shape.IdempotencyToken) {
continue
}
// If this is the wrapper field and we have input_wrapper_field_path
// configured, add the wrapper's member fields instead of the wrapper
if inputWrapperFieldPath != nil && memberName == *inputWrapperFieldPath {
wrapperShape := memberShapeRef.Shape
// NOTE(input_wrapper_field_path): Currently only structure wrappers
// are supported. If needed, support for nested paths (e.g., a.b.c
// where b is a list) could be added in a future PR by extending
// this logic to handle list/map types similar to getWrapperShape
// in crd.go.
if wrapperShape.Type == "structure" {
for _, wrapperMemberName := range wrapperShape.MemberNames() {
wrapperMemberShapeRef := wrapperShape.MemberRefs[wrapperMemberName]
if wrapperMemberShapeRef.Shape == nil {
return nil, ErrNilShapePointer
}
// Handles field renames, if applicable
fieldName := m.cfg.GetResourceFieldName(
crd.Names.Original,
createOp.Name,
wrapperMemberName,
)
wrapperMemberNames := names.New(fieldName)
if err := crd.AddSpecField(wrapperMemberNames, wrapperMemberShapeRef); err != nil {
return nil, err
}
}
}
continue
}
// When input_wrapper_field_path is configured, skip fields that are
// not part of the wrapper. This is consistent with output_wrapper_field_path
// behavior - only the wrapper's fields are flattened into the CRD.
if inputWrapperFieldPath != nil {
continue
}
// Handles field renames, if applicable
fieldName := m.cfg.GetResourceFieldName(
crd.Names.Original,
createOp.Name,
memberName,
)
memberNames := names.New(fieldName)
if memberName == "Attributes" && m.cfg.ResourceContainsAttributesMap(crdName) {
if err := crd.UnpackAttributes(); err != nil {
return nil, err
}
continue
}
if err := crd.AddSpecField(memberNames, memberShapeRef); err != nil {
return nil, err
}
}
// A list of fields that should be processed after gathering
// the Spec and Status top level fields. The customNestedFields will be
// injected into the Spec or Status struct as a nested field.
//
// Note that we could reuse the Field struct here, but we don't because
// we don't need all the fields that the Field struct provides. We only
// need the field path and the FieldConfig. Using Field could lead to
// confusion.
customNestedFields := make(map[string]*ackgenconfig.FieldConfig)
fieldConfigs := m.cfg.GetFieldConfigs(crdName)
fieldConfigNames := make([]string, 0, len(fieldConfigs))
for fn := range fieldConfigs {
fieldConfigNames = append(fieldConfigNames, fn)
}
sort.Strings(fieldConfigNames)
for _, targetFieldName := range fieldConfigNames {
fieldConfig := fieldConfigs[targetFieldName]
if fieldConfig.IsReadOnly {
// It's a Status field...
continue
}
var found bool
var memberShapeRef *awssdkmodel.ShapeRef
if fieldConfig.From != nil {
from := fieldConfig.From
memberShapeRef, found = m.SDKAPI.GetInputShapeRef(
from.Operation, from.Path,
)
// allowing getting spec fields from output shape
if !found {
memberShapeRef, found = m.SDKAPI.GetOutputShapeRef(
from.Operation, from.Path,
)
}
if !found {
return nil, fmt.Errorf(
"resource %q: unknown Spec field source — operation %q path %q not found in input or output shapes",
crdName, from.Operation, from.Path,
)
}
} else if fieldConfig.CustomField != nil {
customField := fieldConfig.CustomField
if customField.ListOf != "" {
memberShapeRef = m.SDKAPI.GetCustomShapeRef(customField.ListOf)
} else {
memberShapeRef = m.SDKAPI.GetCustomShapeRef(customField.MapOf)
}
if memberShapeRef == nil {
return nil, fmt.Errorf(
"resource %q: unknown custom Spec field — custom field %+v has no matching shape",
crdName, customField,
)
}
} else if fieldConfig.Type != nil {
// A nested field will always have a "." in the field path.
// Let's collect those fields and process them after we've
// gathered all the top level fields.
if strings.Contains(targetFieldName, ".") {
// This is a nested field
customNestedFields[targetFieldName] = fieldConfig
continue
}
// If we're here, we have a custom top level field (non-nested).
// We have a custom field that has a type override and has not
// been inferred via the normal Create Input shape or via the
// SourceFieldConfig. Manually construct the field and its
// shape reference here.
typeOverride := *fieldConfig.Type
var err error
memberShapeRef, err = m.SDKAPI.GetShapeRefFromType(typeOverride)
if err != nil {
return nil, fmt.Errorf("resource %q, field %q: %w", crdName, targetFieldName, err)
}
} else {
// Spec field is not well defined
continue
}
memberNames := names.New(targetFieldName)
if err := crd.AddSpecField(memberNames, memberShapeRef); err != nil {
return nil, err
}
}
// Now process the fields that will go into the Status struct. We want
// fields that are in the Create operation's Output Shape but that are
// not in the Input Shape.
outputShape, err := crd.GetOutputShape(createOp)
if err != nil {
return nil, err
}
if outputShape.UsedAsOutput && len(outputShape.MemberRefs) == 1 {
// We might be in a "wrapper" shape. Unwrap it to find the real object
// representation for the CRD's createOp. If there is a single member
// shape and that member shape is a structure, unwrap it.
for _, mn := range outputShape.MemberNames() {
memberRef := outputShape.MemberRefs[mn]
if memberRef.Shape.Type == "structure" {
outputShape = memberRef.Shape
}
}
}
for _, memberName := range outputShape.MemberNames() {
memberShapeRef := outputShape.MemberRefs[memberName]
if memberShapeRef.Shape == nil {
return nil, ErrNilShapePointer
}
// Check that the field in the output shape isn't the same as
// fields in the input shape (handles field renames, if applicable)
fieldName := m.cfg.GetResourceFieldName(
crd.Names.Original,
createOp.Name,
memberName,
)
if inSpec, _ := crd.HasMember(fieldName, createOp.Name); inSpec {
// We don't put fields that are already in the Spec struct into
// the Status struct
continue
}
memberNames := names.New(fieldName)
//TODO:(brycahta) should we support overriding these fields?
if memberName == "Attributes" && m.cfg.ResourceContainsAttributesMap(crdName) {
continue
}
if crd.IsPrimaryARNField(memberName) {
// We automatically place the primary resource ARN value into
// the Status.ACKResourceMetadata.ARN field
continue
}
if err := crd.AddStatusField(memberNames, memberShapeRef); err != nil {
return nil, err
}
}
// Now add the additional Status fields that are required from other
// API operations.
statusFieldConfigs := m.cfg.GetFieldConfigs(crdName)
statusFieldConfigNames := make([]string, 0, len(statusFieldConfigs))
for fn := range statusFieldConfigs {
statusFieldConfigNames = append(statusFieldConfigNames, fn)
}
sort.Strings(statusFieldConfigNames)
for _, targetFieldName := range statusFieldConfigNames {
fieldConfig := statusFieldConfigs[targetFieldName]
if !fieldConfig.IsReadOnly {
// It's a Spec field...
continue
}
var found bool
var memberShapeRef *awssdkmodel.ShapeRef
if fieldConfig.From != nil {
from := fieldConfig.From
memberShapeRef, found = m.SDKAPI.GetOutputShapeRef(
from.Operation, from.Path,
)
// allowing to get status fields from output shapes
if !found {
memberShapeRef, found = m.SDKAPI.GetInputShapeRef(
from.Operation, from.Path,
)
}
if !found {
return nil, fmt.Errorf(
"resource %q: unknown Status field source — operation %q path %q not found in input or output shapes",
crdName, from.Operation, from.Path,
)
}
} else if fieldConfig.CustomField != nil {
customField := fieldConfig.CustomField
if customField.ListOf != "" {
memberShapeRef = m.SDKAPI.GetCustomShapeRef(customField.ListOf)
} else {
memberShapeRef = m.SDKAPI.GetCustomShapeRef(customField.MapOf)
}
if memberShapeRef == nil {
return nil, fmt.Errorf(
"resource %q: unknown custom Status field — custom field %+v has no matching shape",
crdName, customField,
)
}
} else if fieldConfig.Type != nil {
// A nested field will always have a "." in the field path.
// Let's collect those fields and process them after we've
// gathered all the top level fields.
if strings.Contains(targetFieldName, ".") {
// This is a nested field
customNestedFields[targetFieldName] = fieldConfig
continue
}
// If we're here, we have a custom top level field (non-nested).
// We have a custom field that has a type override and has not
// been inferred via the normal Create Input shape or via the
// SourceFieldConfig. Manually construct the field and its
// shape reference here.
typeOverride := *fieldConfig.Type
var err error
memberShapeRef, err = m.SDKAPI.GetShapeRefFromType(typeOverride)
if err != nil {
return nil, fmt.Errorf("resource %q, field %q: %w", crdName, targetFieldName, err)
}
} else {
// Status field is not well defined
continue
}
memberNames := names.New(targetFieldName)
if err := crd.AddStatusField(memberNames, memberShapeRef); err != nil {
return nil, err
}
}
// Now add the additional printer columns that have been defined explicitly
// in additional_columns
crd.addAdditionalPrinterColumns(m.cfg.GetAdditionalColumns(crdName))
// Process the custom nested fields
if err := crd.addCustomNestedFields(customNestedFields); err != nil {
return nil, err
}
crds = append(crds, crd)
}
sort.Slice(crds, func(i, j int) bool {
return crds[i].Names.Camel < crds[j].Names.Camel
})
// This is the place that we build out the CRD.Fields map with
// `pkg/model.Field` objects that represent the non-top-level Spec and
// Status fields.
if err := m.processFields(crds); err != nil {
return nil, err
}
// Validate that field configs reference actual CRD fields. Field configs
// without From/CustomField/Type are modifiers (is_secret, references,
// compare, set, etc.) that must match an existing field.
var fieldErrs []string
for _, crd := range crds {
fieldConfigs := m.cfg.GetFieldConfigs(crd.Names.Original)
for fieldName, fc := range fieldConfigs {
if fc.From != nil || fc.CustomField != nil || fc.Type != nil {
continue
}
// These fields are metadata markers or configs that reference
// fields by alias names, not actual CRD field names.
if fc.IsARN || fc.IsOwnerAccountID || fc.IsPrimaryKey {
continue
}
// LateInitialize configs can reference fields by alias
// names that are resolved separately.
if fc.LateInitialize != nil {
continue
}
// Primary ARN fields (e.g. TopicArn for Topic) are stored in
// ACKResourceMetadata and skipped by UnpackAttributes.
if crd.IsPrimaryARNField(fieldName) {
continue
}
// For nested paths (e.g. "Spec.Foo.Bar"), validate the
// top-level field name.
checkName := ackfp.FromString(fieldName).Front()
if !crdHasField(crd, checkName) {
fieldErrs = append(fieldErrs, fmt.Sprintf(
"resources.%s.fields.%s: field not found in CRD (no matching SDK shape member). "+
"If this is a custom field, add 'from', 'custom_field', or 'type'",
crd.Names.Original, fieldName,
))
}
}
}
if len(fieldErrs) > 0 {
return nil, fmt.Errorf("generator.yaml validation failed:\n %s", strings.Join(fieldErrs, "\n "))
}
m.crds = crds
return crds, nil
}
// crdHasField returns true if the CRD has a field matching the given name
// (case-insensitive) in SpecFields, StatusFields, or Fields.
func crdHasField(crd *CRD, fieldName string) bool {
lower := strings.ToLower(fieldName)
for k := range crd.SpecFields {
if strings.ToLower(k) == lower {
return true
}
}
for k := range crd.StatusFields {
if strings.ToLower(k) == lower {
return true
}
}
for k := range crd.Fields {
if strings.ToLower(k) == lower {
return true
}
}
return false
}
// RemoveIgnoredOperations updates Ops argument by setting those
// operations to nil that are configured to be ignored in generator config for
// the AWS service
func (m *Model) RemoveIgnoredOperations(ops *Ops) {
if m.cfg.OperationIsIgnored(ops.Create) {
ops.Create = nil
}
if m.cfg.OperationIsIgnored(ops.ReadOne) {
ops.ReadOne = nil
}
if m.cfg.OperationIsIgnored(ops.ReadMany) {
ops.ReadMany = nil
}
if m.cfg.OperationIsIgnored(ops.Update) {
ops.Update = nil
}
if m.cfg.OperationIsIgnored(ops.Delete) {
ops.Delete = nil
}
if m.cfg.OperationIsIgnored(ops.GetAttributes) {
ops.GetAttributes = nil
}
if m.cfg.OperationIsIgnored(ops.SetAttributes) {
ops.SetAttributes = nil
}
}
// IsShapeUsedInCRDs returns true if the supplied shape name is a member of amy
// CRD's payloads or those payloads sub-member shapes
func (m *Model) IsShapeUsedInCRDs(shapeName string, crds []*CRD) bool {
for _, crd := range crds {
if crd.HasShapeAsMember(shapeName) {
return true
}
}
return false
}
// GetTypeDefs returns a slice of `TypeDef` pointers
func (m *Model) GetTypeDefs() ([]*TypeDef, error) {
if m.typeDefs != nil {
return m.typeDefs, nil
}
tdefs := []*TypeDef{}
// Map, keyed by original Shape GoTypeElem(), with the values being a
// renamed type name (due to conflicting names)
trenames := map[string]string{}
payloads := m.SDKAPI.GetPayloads()
crds, err := m.GetCRDs()
if err != nil {
return nil, err
}
shapeNames := make([]string, 0, len(m.SDKAPI.API.Shapes))
for shapeName := range m.SDKAPI.API.Shapes {
shapeNames = append(shapeNames, shapeName)
}
sort.Strings(shapeNames)
for _, shapeName := range shapeNames {
shape := m.SDKAPI.API.Shapes[shapeName]
if util.InStrings(shapeName, payloads) && !m.IsShapeUsedInCRDs(shapeName, crds) {
// Payloads are not type defs, unless explicitly used
continue
}
if shape.Type != "structure" {
continue
}
if shape.Exception {
// Neither are exceptions
continue
}
tdefNames := names.New(shapeName)
if m.SDKAPI.HasConflictingTypeName(shapeName, m.cfg) {
tdefNames.Camel += ConflictingNameSuffix
trenames[shapeName] = tdefNames.Camel
}
attrs := map[string]*Attr{}
for _, memberName := range shape.MemberNames() {
memberRef := shape.MemberRefs[memberName]
memberNames := names.New(memberName)
memberShape := memberRef.Shape
if !m.IsShapeUsedInCRDs(memberShape.ShapeName, crds) {
continue
}
gt, err := m.getShapeCleanGoType(memberShape)
if err != nil {
return nil, err
}
attrs[memberName] = NewAttr(memberNames, gt, memberShape, memberRef)
}
if len(attrs) == 0 {
// Just ignore these...
continue
}
tdefs = append(tdefs, &TypeDef{
Shape: shape,
Names: tdefNames,
Attrs: attrs,
})
}
sort.Slice(tdefs, func(i, j int) bool {
return tdefs[i].Names.Camel < tdefs[j].Names.Camel
})
if err := m.processNestedFieldTypeDefs(tdefs); err != nil {
return nil, err
}
m.typeDefs = tdefs
m.typeRenames = trenames
return tdefs, nil
}
// getShapeCleanGoType returns a cleaned-up and Camel-cased GoType name for a given shape.
func (m *Model) getShapeCleanGoType(shape *awssdkmodel.Shape) (string, error) {
switch shape.Type {
case "map":
// If it's a map type we need to set the GoType to the cleaned-up
// Camel-cased name
gt, err := m.getShapeCleanGoType(shape.ValueRef.Shape)
if err != nil {
return "", err
}
return "map[string]" + gt, nil
case "list", "array":
// If it's a list type, we need to set the GoType to the cleaned-up
// Camel-cased name
gt, err := m.getShapeCleanGoType(shape.MemberRef.Shape)
if err != nil {
return "", err
}
// For timestamp list members, use the non-pointer form
// (metav1.Time instead of *metav1.Time) because controller-gen's
// deepcopy generator does not handle []*metav1.Time correctly.
if shape.MemberRef.Shape.Type == "timestamp" {
gt = strings.TrimPrefix(gt, "*")
}
return "[]" + gt, nil
case "timestamp":
// time.Time needs to be converted to apimachinery/metav1.Time
// otherwise there is no DeepCopy support
return "*metav1.Time", nil
case "structure":
if len(shape.MemberRefs) == 0 {
if m.cfg.HasEmptyShape(shape.ShapeName) {
return "map[string]*string", nil
}
return "", fmt.Errorf(
"structure %q has no fields — configure it as an empty_shape or manually set the field type in generator.yaml",
shape.ShapeName,
)
}
// There are shapes that are called things like DBProxyStatus that are
// fields in a DBProxy CRD... we need to ensure the type names don't
// conflict. Also, the name of the Go type in the generated code is
// Camel-cased and normalized, so we use that as the Go type
goType := shape.GoType()
typeNames := names.New(goType)
if m.SDKAPI.HasConflictingTypeName(goType, m.cfg) {
typeNames.Camel += ConflictingNameSuffix
}
return "*" + typeNames.Camel, nil
default:
return shape.GoType(), nil
}
}
// processNestedFieldTypeDefs updates the supplied TypeDef structs' if a nested
// field has been configured with a type overriding FieldConfig -- such as
// FieldConfig.IsSecret.
func (m *Model) processNestedFieldTypeDefs(
tdefs []*TypeDef,
) error {
crds, err := m.GetCRDs()
if err != nil {
return err
}
for _, crd := range crds {
for _, fieldPath := range crd.SortedFieldNames() {
field := crd.Fields[fieldPath]
if !strings.Contains(fieldPath, ".") {
// top-level fields have already had their structure
// transformed during the CRD.AddSpecField and
// CRD.AddStatusField methods. All we need to do here is look
// at nested fields, which are identifiable as fields with
// field paths contains a dot (".")
continue
}
if field.FieldConfig == nil {
// Likewise, we don't need to transform any TypeDef if the
// nested field doesn't have a FieldConfig instructing us to
// treat this field differently.
continue
}
if field.FieldConfig.IsSecret {
// Find the TypeDef that was created for the *containing*
// secret field struct. For example, assume the nested field
// path `Users..Password`, we'd want to find the TypeDef that
// was created for the `Users` field's element type (which is a
// struct)
if err := replaceSecretAttrGoType(crd, field, tdefs); err != nil {
return fmt.Errorf("resource %q, field %q: %w", crd.Names.Original, fieldPath, err)
}
}
if field.FieldConfig.References != nil {
if err := updateTypeDefAttributeWithReference(crd, fieldPath, tdefs); err != nil {
return fmt.Errorf("resource %q, field %q: %w", crd.Names.Original, fieldPath, err)
}
}
if field.FieldConfig.GoTag != nil {
if err := setTypeDefAttributeGoTag(crd, fieldPath, field, tdefs); err != nil {
return fmt.Errorf("resource %q, field %q: %w", crd.Names.Original, fieldPath, err)
}
}
if field.IsImmutable() {
if err := setTypeDefAttributeImmutable(crd, fieldPath, tdefs); err != nil {
return fmt.Errorf("resource %q, field %q: %w", crd.Names.Original, fieldPath, err)
}
}
}
}
return nil
}
// getAttributeFromPath extracts the parent TypeDef and the target attribute for
// the corresponding fieldPath of nested field. This function should only be
// called for nested fieldPath. Non-nested fieldPath should be handled by higher
// level functions.
func getAttributeFromPath(crd *CRD, fieldPath string, tdefs []*TypeDef) (parentTypeDef *TypeDef, target *Attr, err error) {
fp := ackfp.FromString(fieldPath)
if fp.Size() < 2 {
// This function should only be called for nested fieldPath. Non-nested
// fieldPath should be handled by higher level functions.
return nil, nil, nil
}
// First part of nested reference fieldPath is the name of top level Spec
// field. Ex: For 'ResourcesVpcConfig.SecurityGroupIds' fieldpath the
// topLevelFieldName is 'ResourcesVpcConfig'
topLevelFieldName := fp.Front()
var topLevelField *Field
foundInSpec := false
foundInStatus := false
for fName, field := range crd.SpecFields {
if strings.EqualFold(fName, topLevelFieldName) {
topLevelField = field
foundInSpec = true
break
}
}
if !foundInSpec {
for fName, field := range crd.StatusFields {
if strings.EqualFold(fName, topLevelFieldName) {
topLevelField = field
foundInStatus = true
}
}
}
if !foundInSpec && !foundInStatus {
return nil, nil, fmt.Errorf(
"unable to find a spec or status field with name %s for path %s",
topLevelFieldName, fieldPath,
)
}
if foundInSpec && foundInStatus {
return nil, nil, fmt.Errorf(
"field %s in path %s exists in both spec and status",
topLevelFieldName, fieldPath,
)
}
// Create a new fieldPath starting with ShapeName of Spec Field
// to determine the shape of typedef which will contain the reference
// attribute. We replace the spec-field Name with spec-field ShapeName in
// the beginning of field path and leave rest of nested member names as is.
// Ex: ResourcesVpcConfig.SecurityGroupIDs will become VPCConfigRequest.SecurityGroupIDs
// for Cluster resource in eks-controller.
specFieldShapeRef := topLevelField.ShapeRef
specFieldShapeName := specFieldShapeRef.ShapeName
switch shapeType := specFieldShapeRef.Shape.Type; shapeType {
case "list":
specFieldShapeName = topLevelField.ShapeRef.Shape.MemberRef.ShapeName
specFieldShapeRef = &topLevelField.ShapeRef.Shape.MemberRef
case "map":
specFieldShapeName = topLevelField.ShapeRef.Shape.ValueRef.ShapeName
specFieldShapeRef = &topLevelField.ShapeRef.Shape.ValueRef
}
fieldShapePath := strings.Replace(fieldPath, topLevelFieldName, specFieldShapeName, 1)
fsp := ackfp.FromString(fieldShapePath)
// "fieldName" is the member name for which reference field will be created.
// Ex: SecurityGroupIDs in ResourcesVpcConfig.SecurityGroupIDs
fieldName := fsp.Pop()
// "parentFieldName" is the Shape/Member name whose "TypeDef" contains the
// "fieldName" as attribute. To add a corresponding reference for "fieldName"
// , we will add new attribute in TypeDef for "parentFieldName".
parentFieldName := fsp.Back()
parentFieldShapeRef := fsp.ShapeRef(specFieldShapeRef)
if parentFieldShapeRef == nil {
return nil, nil, fmt.Errorf(
"unable to find shape member %s for path %s",
parentFieldName, fieldPath,
)
}
parentFieldTypeDefName := parentFieldShapeRef.ShapeName
var parentFieldTypeDef *TypeDef
for _, td := range tdefs {
fallbackName := ""
switch parentFieldShapeRef.Shape.Type {
case "list":
// e.g FunctionAssociationsList in CloudFront DistributionConfig.DefaultCacheBehavior.FunctionAssociations
fallbackName = parentFieldShapeRef.Shape.MemberRef.ShapeName
fallbackName = strings.TrimSuffix(fallbackName, "List")
default:
// NOTE(a-hilaly): Very likely that we will need to add more cases here
// as we encounter more special APIs in the future.
}
if strings.EqualFold(td.Names.Original, parentFieldTypeDefName) ||
(fallbackName != "" && strings.EqualFold(td.Names.Original, fallbackName)) {
parentFieldTypeDef = td
break
}
}
if parentFieldTypeDef == nil {
return nil, nil, fmt.Errorf(
"unable to find TypeDef %s in service model for path %s",
parentFieldTypeDefName, fieldPath,
)
}
fieldAttr := parentFieldTypeDef.GetAttribute(fieldName)
if fieldAttr == nil {
return nil, nil, fmt.Errorf(
"unable to find member %s in TypeDef %s for path %s",
fieldName, parentFieldTypeDefName, fieldPath,
)
}
return parentFieldTypeDef, fieldAttr, nil
}
// setTypeDefAttributeGoTag sets the GoTag for the corresponding attribute
// represented by fieldPath of nested field.
func setTypeDefAttributeGoTag(crd *CRD, fieldPath string, f *Field, tdefs []*TypeDef) error {
_, fieldAttr, err := getAttributeFromPath(crd, fieldPath, tdefs)
if err != nil {
return err
}
if fieldAttr != nil {
fieldAttr.GoTag = f.GetGoTag()
}
return nil
}
// setTypeDefAttributeImmutable sets the IsImmutable flag for the corresponding
// attribute represented by fieldPath of nested field.
func setTypeDefAttributeImmutable(crd *CRD, fieldPath string, tdefs []*TypeDef) error {
_, fieldAttr, err := getAttributeFromPath(crd, fieldPath, tdefs)
if err != nil {
return err
}
if fieldAttr != nil {
fieldAttr.IsImmutable = true
}
return nil
}
// updateTypeDefAttributeWithReference adds a new AWSResourceReference attribute
// for the corresponding attribute represented by fieldPath of nested field
func updateTypeDefAttributeWithReference(crd *CRD, fieldPath string, tdefs []*TypeDef) error {
parentFieldTypeDef, fieldAttr, err := getAttributeFromPath(crd, fieldPath, tdefs)
if err != nil {
return err
}
if fieldAttr != nil && parentFieldTypeDef != nil {
if err := addReferenceAttribute(parentFieldTypeDef, fieldAttr); err != nil {
return err
}
}
return nil
}
// addReferenceAttribute creates a corresponding reference attribute for
// "attr" attribute and adds it to "td" TypeDef
func addReferenceAttribute(td *TypeDef, attr *Attr) error {
// Create a custom "model.Field" to generate ReferenceFieldName and reuse
// the existing method for generating top-level reference fields
fieldShapeRef := awssdkmodel.ShapeRef{Shape: attr.Shape}
field := &Field{
Names: attr.Names,
ShapeRef: &fieldShapeRef,
}
refAttrName, err := field.GetReferenceFieldName()
if err != nil {
return err
}
refAttrShape := &awssdkmodel.Shape{
Documentation: "// Reference field for " + attr.Names.Camel,
}
refAttrGoType := "*ackv1alpha1.AWSResourceReferenceWrapper"
if attr.Shape.Type == "list" {
refAttrGoType = fmt.Sprintf("[]%s", refAttrGoType)
}
refAttr := NewAttr(refAttrName, refAttrGoType, refAttrShape, nil)
// Add reference attribute to the parent field typedef
td.Attrs[refAttrName.Original] = refAttr
return nil
}
// replaceSecretAttrGoType replaces a nested field Attr's GoType with
// `*ackv1alpha1.SecretKeyReference`.
func replaceSecretAttrGoType(
crd *CRD,
field *Field,
tdefs []*TypeDef,
) error {
fieldPath := ackfp.FromString(field.Path)
parentFieldPath := fieldPath.Copy()
parentFieldPath.Pop()
parentField, ok := crd.Fields[parentFieldPath.String()]
if !ok {
return fmt.Errorf(
"cannot find parent field at path %s for %s",
parentFieldPath, fieldPath,
)
}
if parentField.ShapeRef == nil {
return fmt.Errorf(
"parent field at path %s has a nil ShapeRef",
parentFieldPath,
)
}
parentFieldShape := parentField.ShapeRef.Shape
parentFieldShapeName := parentField.ShapeRef.ShapeName
parentFieldShapeType := parentFieldShape.Type
// For list and map types, we need to grab the element/value
// type, since that's the type def we need to modify.
if parentFieldShapeType == "list" {
if parentFieldShape.MemberRef.Shape.Type != "structure" {
return fmt.Errorf(
"parent field at path %s is a list with non-structure element type %s",
parentFieldPath, parentFieldShape.MemberRef.Shape.Type,
)
}
parentFieldShapeName = parentField.ShapeRef.Shape.MemberRef.ShapeName
} else if parentFieldShapeType == "map" {
if parentFieldShape.ValueRef.Shape.Type != "structure" {
return fmt.Errorf(
"parent field at path %s is a map with non-structure value type %s",
parentFieldPath, parentFieldShape.ValueRef.Shape.Type,