Skip to content

How to implement anyOf constraint in crd by go struct #340

@whg517

Description

@whg517

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions