sample
When define struct reference k8s.io/apimachinery/pkg/api/resource.Quantity , we can find a anyOf constraint in crd.
go types:
type StorageResource struct {
// +kubebuilder:validation:Optional
// +kubebuilder:default="10Gi"
Capacity resource.Quantity `json:"capacity,omitempty"`
// +kubebuilder:validation:Optional
StorageClass string `json:"storageClass,omitempty"`
}
result:
storage:
properties:
capacity:
anyOf:
- type: integer
- type: string
default: 10Gi
pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
x-kubernetes-int-or-string: true
storageClass:
type: string
type: object
Technical principle
In k8s.io/apimachinery/pkg/api/resource.Quantity , we can find some code :
// OpenAPISchemaType is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
//
// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators
func (_ Quantity) OpenAPISchemaType() []string { return []string{"string"} }
// OpenAPISchemaFormat is used by the kube-openapi generator when constructing
// the OpenAPI spec of this type.
func (_ Quantity) OpenAPISchemaFormat() string { return "" }
// OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing
// the OpenAPI v3 spec of this type.
func (Quantity) OpenAPIV3OneOfTypes() []string { return []string{"string", "number"} }
The Quantity implement a method OpenAPIV3OneOfTypes is the key. When controller-gen dected the OpenAPIV3OneOfTypes method, it will generate constraint anyOf, like:
anyOf:
- type: string
- type: number
sample
When define struct reference
k8s.io/apimachinery/pkg/api/resource.Quantity, we can find aanyOfconstraint in crd.go types:
result:
Technical principle
In
k8s.io/apimachinery/pkg/api/resource.Quantity, we can find some code :The
Quantityimplement a methodOpenAPIV3OneOfTypesis the key. When controller-gen dected theOpenAPIV3OneOfTypesmethod, it will generate constraintanyOf, like: