-
Notifications
You must be signed in to change notification settings - Fork 187
/
apply_defaulter_and_validator_interfaces.go
434 lines (373 loc) · 14.8 KB
/
apply_defaulter_and_validator_interfaces.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
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package pipeline
import (
"context"
"fmt"
"github.com/dave/dst"
"github.com/pkg/errors"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/astbuilder"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/astmodel"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/config"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/functions"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/interfaces"
)
const ApplyDefaulterAndValidatorInterfaceStageID = "applyDefaulterAndValidatorInterfaces"
// ApplyDefaulterAndValidatorInterfaces add the admission.Defaulter and admission.Validator interfaces to each resource that requires them
func ApplyDefaulterAndValidatorInterfaces(configuration *config.Configuration, idFactory astmodel.IdentifierFactory) *Stage {
stage := NewStage(
ApplyDefaulterAndValidatorInterfaceStageID,
"Add the admission.Defaulter and admission.Validator interfaces to each resource that requires them",
func(ctx context.Context, state *State) (*State, error) {
defs := state.Definitions()
updatedDefs := make(astmodel.TypeDefinitionSet)
for _, resourceDef := range astmodel.FindResourceDefinitions(defs) {
defaults, err := getDefaults(configuration, resourceDef, idFactory, state.Definitions())
if err != nil {
return nil, errors.Wrap(err, "failed to get defaults")
}
resource, err := interfaces.AddDefaulterInterface(resourceDef, idFactory, defaults)
if err != nil {
return nil, err
}
validations, err := getValidations(resource, idFactory, state.Definitions())
if err != nil {
return nil, errors.Wrapf(err, "error getting validation functions")
}
resource, err = interfaces.AddValidatorInterface(resource, idFactory, defs, validations)
if err != nil {
return nil, err
}
updatedDefs.Add(resource)
}
err := configuration.ObjectModelConfiguration.DefaultAzureName.VerifyConsumed()
if err != nil {
return nil, err
}
return state.WithOverlaidDefinitions(updatedDefs), nil
})
stage.RequiresPrerequisiteStages(ApplyKubernetesResourceInterfaceStageID, AddOperatorSpecStageID)
return stage
}
func getDefaults(
configuration *config.Configuration,
resourceDef astmodel.TypeDefinition,
idFactory astmodel.IdentifierFactory,
defs astmodel.TypeDefinitionSet,
) ([]*functions.ResourceFunction, error) {
var result []*functions.ResourceFunction
resolved, err := defs.ResolveResourceSpecAndStatus(resourceDef)
if err != nil {
return nil, errors.Wrapf(err, "unable to resolve resource %s", resourceDef.Name())
}
defaultAzureName := true
if configuredDefaultAzureName, ok := configuration.ObjectModelConfiguration.DefaultAzureName.Lookup(resourceDef.Name()); ok {
defaultAzureName = configuredDefaultAzureName
}
// Determine if the resource has a SetName function
if resolved.SpecType.HasFunctionWithName(astmodel.SetAzureNameFunc) && defaultAzureName {
result = append(result, functions.NewDefaultAzureNameFunction(resolved.ResourceType, idFactory))
}
return result, nil
}
func getValidations(
resourceDef astmodel.TypeDefinition,
idFactory astmodel.IdentifierFactory,
defs astmodel.TypeDefinitionSet,
) (map[functions.ValidationKind][]*functions.ResourceFunction, error) {
resource, ok := resourceDef.Type().(*astmodel.ResourceType)
if !ok {
return nil, errors.Errorf("resource %s did not have type of kind *astmodel.ResourceType, instead %T", resourceDef.Name(), resourceDef.Type())
}
validations := map[functions.ValidationKind][]*functions.ResourceFunction{
functions.ValidationKindCreate: {
functions.NewValidateResourceReferencesFunction(resource, idFactory),
},
functions.ValidationKindUpdate: {
functions.NewValidateResourceReferencesFunction(resource, idFactory),
functions.NewValidateWriteOncePropertiesFunction(resource, idFactory),
},
}
if !resource.Owner().IsEmpty() {
validations[functions.ValidationKindCreate] = append(
validations[functions.ValidationKindCreate],
functions.NewValidateOwnerReferenceFunction(resource, idFactory))
validations[functions.ValidationKindUpdate] = append(
validations[functions.ValidationKindUpdate],
functions.NewValidateOwnerReferenceFunction(resource, idFactory))
}
secrets, err := getOperatorSpecSubType(defs, resource, astmodel.OperatorSpecSecretsProperty)
if err != nil {
return nil, err
}
if secrets != nil {
validations[functions.ValidationKindCreate] = append(
validations[functions.ValidationKindCreate],
NewValidateSecretDestinationsFunction(resource, idFactory))
validations[functions.ValidationKindUpdate] = append(
validations[functions.ValidationKindUpdate],
NewValidateSecretDestinationsFunction(resource, idFactory))
}
configMaps, err := getOperatorSpecSubType(defs, resource, astmodel.OperatorSpecConfigMapsProperty)
if err != nil {
return nil, err
}
if configMaps != nil {
validations[functions.ValidationKindCreate] = append(
validations[functions.ValidationKindCreate],
NewValidateConfigMapDestinationsFunction(resource, idFactory))
validations[functions.ValidationKindUpdate] = append(
validations[functions.ValidationKindUpdate],
NewValidateConfigMapDestinationsFunction(resource, idFactory))
}
hasConfigMapReferencePairs, err := hasOptionalConfigMapReferencePairs(resourceDef, defs)
if err != nil {
return nil, err
}
if hasConfigMapReferencePairs {
validations[functions.ValidationKindCreate] = append(
validations[functions.ValidationKindCreate],
functions.NewValidateOptionalConfigMapReferenceFunction(resource, idFactory))
validations[functions.ValidationKindUpdate] = append(
validations[functions.ValidationKindUpdate],
functions.NewValidateOptionalConfigMapReferenceFunction(resource, idFactory))
}
return validations, nil
}
// Note: This isn't defined in the functions package because it has a dependency on getResourceSecretsType which
// doesn't make a lot of sense to put into astmodel. Functions can't import code from pipelines though, so we just
// define this function here.
func NewValidateSecretDestinationsFunction(resource *astmodel.ResourceType, idFactory astmodel.IdentifierFactory) *functions.ResourceFunction {
return functions.NewResourceFunction(
"validateSecretDestinations",
resource,
idFactory,
validateSecretDestinations,
astmodel.NewPackageReferenceSet(astmodel.GenRuntimeReference))
}
func validateSecretDestinations(
k *functions.ResourceFunction,
codeGenerationContext *astmodel.CodeGenerationContext,
receiver astmodel.TypeName,
methodName string,
) (*dst.FuncDecl, error) {
receiverIdent := k.IdFactory().CreateReceiver(receiver.Name())
receiverExpr, err := receiver.AsTypeExpr(codeGenerationContext)
if err != nil {
return nil, errors.Wrapf(err, "creating receiver expression")
}
body, err := validateOperatorSpecSliceBody(
codeGenerationContext,
k.Resource(),
receiverIdent,
astmodel.OperatorSpecSecretsProperty,
astmodel.NewOptionalType(astmodel.SecretDestinationType),
"ValidateSecretDestinations")
if err != nil {
return nil, errors.Wrapf(err, "creating body of method %s", methodName)
}
fn := &astbuilder.FuncDetails{
Name: methodName,
ReceiverIdent: receiverIdent,
ReceiverType: astbuilder.PointerTo(receiverExpr),
Body: body,
}
fn.AddReturn(astbuilder.QualifiedTypeName(codeGenerationContext.MustGetImportedPackageName(astmodel.ControllerRuntimeAdmission), "Warnings"))
fn.AddReturn(dst.NewIdent("error"))
fn.AddComments("validates there are no colliding genruntime.SecretDestination's")
return fn.DefineFunc(), nil
}
func NewValidateConfigMapDestinationsFunction(resource *astmodel.ResourceType, idFactory astmodel.IdentifierFactory) *functions.ResourceFunction {
return functions.NewResourceFunction(
"validateConfigMapDestinations",
resource,
idFactory,
validateConfigMapDestinations,
astmodel.NewPackageReferenceSet(astmodel.GenRuntimeReference))
}
func validateConfigMapDestinations(
k *functions.ResourceFunction,
codeGenerationContext *astmodel.CodeGenerationContext,
receiver astmodel.TypeName,
methodName string,
) (*dst.FuncDecl, error) {
receiverIdent := k.IdFactory().CreateReceiver(receiver.Name())
receiverExpr, err := receiver.AsTypeExpr(codeGenerationContext)
if err != nil {
return nil, errors.Wrapf(err, "creating receiver expression")
}
body, err := validateOperatorSpecSliceBody(
codeGenerationContext,
k.Resource(),
receiverIdent,
astmodel.OperatorSpecConfigMapsProperty,
astmodel.NewOptionalType(astmodel.ConfigMapDestinationType),
"ValidateConfigMapDestinations")
if err != nil {
return nil, errors.Wrapf(err, "creating body of method %s", methodName)
}
fn := &astbuilder.FuncDetails{
Name: methodName,
ReceiverIdent: receiverIdent,
ReceiverType: astbuilder.PointerTo(receiverExpr),
Body: body,
}
runtimeAdmission := codeGenerationContext.MustGetImportedPackageName(astmodel.ControllerRuntimeAdmission)
fn.AddReturn(astbuilder.QualifiedTypeName(runtimeAdmission, "Warnings"))
fn.AddReturn(dst.NewIdent("error"))
fn.AddComments("validates there are no colliding genruntime.ConfigMapDestinations")
return fn.DefineFunc(), nil
}
// validateOperatorSpecSliceBody helps generate the body of the validateResourceReferences function:
//
// func (account *DatabaseAccount) validateConfigMapDestinations() error {
// if <receiver>.Spec.OperatorSpec == nil {
// return nil
// }
// if <receiver>.Spec.OperatorSpec.<operatorSpecProperty> == nil {
// return nil
// }
// toValidate := []*<validateType>{
// account.Spec.OperatorSpec.ConfigMaps.ClientId,
// account.Spec.OperatorSpec.ConfigMaps.PrincipalId,
// ...
// }
// return genruntime.<validateFunctionName>(toValidate)
// }
func validateOperatorSpecSliceBody(
codeGenerationContext *astmodel.CodeGenerationContext,
resource *astmodel.ResourceType,
receiverIdent string,
operatorSpecProperty string,
validateType astmodel.Type,
validateFunctionName string,
) ([]dst.Stmt, error) {
genRuntime := codeGenerationContext.MustGetImportedPackageName(astmodel.GenRuntimeReference)
operatorSpecPropertyObj, err := getOperatorSpecSubType(codeGenerationContext, resource, operatorSpecProperty)
if err != nil {
return nil, errors.Wrapf(err, "getting operator spec sub type for %s", operatorSpecProperty)
}
var body []dst.Stmt
specSelector := astbuilder.Selector(dst.NewIdent(receiverIdent), "Spec")
// if <receiver>.Spec.OperatorSpec == nil {
// return nil, nil
// }
operatorSpecSelector := astbuilder.Selector(specSelector, astmodel.OperatorSpecProperty)
body = append(body, astbuilder.ReturnIfNil(operatorSpecSelector, astbuilder.Nil(), astbuilder.Nil()))
// if <receiver>.Spec.OperatorSpec.<operatorSpecProperty> == nil {
// return nil, nil
// }
specPropertySelector := astbuilder.Selector(operatorSpecSelector, operatorSpecProperty)
body = append(body, astbuilder.ReturnIfNil(specPropertySelector, astbuilder.Nil(), astbuilder.Nil()))
// secrets := []<validateType>{
// account.Spec.OperatorSpec.Secrets.PrimaryReadonlyMasterKey,
// account.Spec.OperatorSpec.Secrets.SecondaryReadonlyMasterKey,
// ...
// }
validateTypeExpr, err := validateType.AsTypeExpr(codeGenerationContext)
if err != nil {
return nil, errors.Wrapf(err, "creating type expression for %s", validateType)
}
sliceBuilder := astbuilder.NewSliceLiteralBuilder(validateTypeExpr, true)
for _, prop := range operatorSpecPropertyObj.Properties().AsSlice() {
propSelector := astbuilder.Selector(specPropertySelector, prop.PropertyName().String())
sliceBuilder.AddElement(propSelector)
}
toValidateVar := "toValidate"
body = append(body, astbuilder.ShortDeclaration(toValidateVar, sliceBuilder.Build()))
// return genruntime.<validateFunctionName>(secrets)
body = append(
body,
astbuilder.Returns(
astbuilder.CallQualifiedFunc(
genRuntime,
validateFunctionName,
dst.NewIdent(toValidateVar))))
return body, nil
}
func getOperatorSpecType(defs astmodel.ReadonlyTypeDefinitions, resource *astmodel.ResourceType) (*astmodel.ObjectType, error) {
spec, err := astmodel.ResolveResourceSpecDefinition(defs, resource)
if err != nil {
return nil, err
}
typedSpec, ok := astmodel.AsObjectType(spec.Type())
if !ok {
return nil, errors.Errorf("resource spec was not of expected type *astmodel.ObjectType, instead %T", spec.Type())
}
operatorSpecProp, ok := typedSpec.Property(astmodel.OperatorSpecProperty)
if !ok {
// No OperatorSpec property - this means no secrets
return nil, nil
}
operatorSpecTypeName, ok := astmodel.AsInternalTypeName(operatorSpecProp.PropertyType())
if !ok {
return nil, errors.Errorf(
"expected %s to be an astmodel.TypeName, but it was %T",
astmodel.OperatorSpecProperty,
operatorSpecProp.PropertyType())
}
operatorSpecDef, err := defs.GetDefinition(operatorSpecTypeName)
if err != nil {
return nil, err
}
operatorSpecType, ok := astmodel.AsObjectType(operatorSpecDef.Type())
if !ok {
return nil, errors.Errorf(
"expected %s to be an astmodel.ObjectType but it was %T",
operatorSpecTypeName,
operatorSpecDef.Type())
}
return operatorSpecType, nil
}
func getOperatorSpecSubType(defs astmodel.ReadonlyTypeDefinitions, resource *astmodel.ResourceType, name string) (*astmodel.ObjectType, error) {
operatorSpecType, err := getOperatorSpecType(defs, resource)
if err != nil {
return nil, err
}
if operatorSpecType == nil {
// Not found, just return
return nil, nil
}
secretsProp, ok := operatorSpecType.Property(astmodel.PropertyName(name))
if !ok {
// No secrets property
return nil, nil
}
secretsTypeName, ok := astmodel.AsInternalTypeName(secretsProp.PropertyType())
if !ok {
return nil, errors.Errorf(
"expected %s to be an astmodel.TypeName, but it was %T",
name,
secretsProp.PropertyType())
}
secretsDef, err := defs.GetDefinition(secretsTypeName)
if err != nil {
return nil, err
}
secretsType, ok := astmodel.AsObjectType(secretsDef.Type())
if !ok {
panic(fmt.Sprintf("expected %s to be an astmodel.ObjectType but it was %T", secretsTypeName, secretsDef.Type()))
}
return secretsType, nil
}
// hasOptionalConfigMapReferencePairs returns true if the type has optional genruntime.ConfigMapReference pairs
func hasOptionalConfigMapReferencePairs(resourceDef astmodel.TypeDefinition, defs astmodel.TypeDefinitionSet) (bool, error) {
result := false
visitor := astmodel.TypeVisitorBuilder[any]{
VisitObjectType: astmodel.MakeIdentityVisitOfObjectType(
func(ot *astmodel.ObjectType, prop *astmodel.PropertyDefinition, ctx any) (any, error) {
if prop.HasTag(astmodel.OptionalConfigMapPairTag) {
result = true
}
return ctx, nil
}),
}.Build()
walker := astmodel.NewTypeWalker(defs, visitor)
_, err := walker.Walk(resourceDef)
if err != nil {
return false, err
}
return result, nil
}