CRD Kubernetes - Ссылка на существующую спецификацию валидации - PullRequest
1 голос
/ 27 февраля 2020

Есть ли способ получить доступ к существующим спецификациям проверки? Например, я хочу иметь возможность установить NodeAffinity на моем CRD и хотел бы просто $ ref:. Я нашел весь API здесь: https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/swagger.json ИЛИ прокси kubectl -> localhost: 8001 / openapi / v2 (из моего кластера)

Я мог бы вручную скопировать и вставить схему проверки API, но мне было интересно, есть ли способ автоматически ссылаться на существующую проверку OpenAPI Spe c из моего CRD с помощью $ ref. Я представляю что-то вроде $ ref: localhost: 8001 / openapi / v2 / definitions / io.k8s.api.core.v1.NodeAffinity

Если это вообще возможно, разрешит ли это и внутренние $ refs?

Для справки, вот как выглядит определение узла в API:

"io.k8s.api.core.v1.NodeAffinity": {
  "description": "Node affinity is a group of node affinity scheduling rules.",
  "properties": {
    "preferredDuringSchedulingIgnoredDuringExecution": {
      "description": "The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.",
      "items": {
        "$ref": "#/definitions/io.k8s.api.core.v1.PreferredSchedulingTerm"
      },
      "type": "array"
    },
    "requiredDuringSchedulingIgnoredDuringExecution": {
      "$ref": "#/definitions/io.k8s.api.core.v1.NodeSelector",
      "description": "If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node."
    }
  },
  "type": "object"
},

(с использованием Operator-SDK с Ansible, если это имеет значение)

РЕДАКТИРОВАТЬ : (добавив полный пример для дальнейшего объяснения)

У меня есть CRD, называемый Workshop, и мне требуется проверка определенных параметров spe c.

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: workshops.k8s.example.tk
spec:
  group: k8s.example.tk
  names:
    kind: Workshop
    listKind: WorkshopList
    plural: workshops
    singular: workshop
  scope: Namespaced
  subresources:
    status: {}
  validation:
    openAPIV3Schema:
      type: object
      properties:
        spec:
          type: object
          required:
          - workshopID
          properties:
            workshopID: #
              type: string
              description: Unique identifier for this particular virtual 
workshop
              example: d8e8fca2dc0f896fd7cb4cb0031ba249

Теперь мне нужно добавить Поле nodeAffinity spe c, которое будет применяться ко всем модулям, которые находятся под этим CustomResourceDefinition. Проверка для него будет точно такой же, как проверка для nodeAffinity в модулях.

Позвольте мне извлечь проверочную спецификацию c, которая уже написана в OpenApi из: https://github.com/kubernetes/kubernetes/blob/master/api/openapi-spec/swagger.json и преобразуйте его в YAML, затем добавьте его в мою спецификацию c.

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: workshops.k8s.example.tk
spec:
  group: k8s.example.tk
  names:
    kind: Workshop
    listKind: WorkshopList
    plural: workshops
    singular: workshop
  scope: Namespaced
  subresources:
    status: {}
  validation:
    openAPIV3Schema:
      type: object
      properties:
        spec:
          type: object
          required:
          - workshopID
          properties:
            workshopID: #
              type: string
              description: Unique identifier for this particular virtual 
workshop
              example: d8e8fca2dc0f896fd7cb4cb0031ba249
            affinity: #
          type: object
          properties:
            nodeAffinity: #
              description: Node affinity is a group of node affinity scheduling rules.
              type: object
              properties:
                preferredDuringSchedulingIgnoredDuringExecution:
                  description: The scheduler will prefer to schedule pods to nodes that satisfy
                    the affinity expressions specified by this field, but it may choose a node that
                    violates one or more of the expressions. The node that is most preferred is
                    the one with the greatest sum of weights, i.e. for each node that meets all
                    of the scheduling requirements (resource request, requiredDuringScheduling affinity
                    expressions, etc.), compute a sum by iterating through the elements of this
                    field and adding "weight" to the sum if the node matches the corresponding matchExpressions;
                    the node(s) with the highest sum are the most preferred.
                  type: array
                  items:
                    description: An empty preferred scheduling term matches all objects with implicit
                      weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no
                      objects (i.e. is also a no-op).
                    type: object
                    required:
                    - weight
                    - preference
                    properties:
                      preference:
                        description: A node selector term, associated with the corresponding weight.
                          A null or empty node selector term matches no objects. The requirements
                          of them are ANDed. The TopologySelectorTerm type implements a subset of
                          the NodeSelectorTerm.
                        type: object
                        properties:
                          matchExpressions:
                            description: A list of node selector requirements by node's labels.
                            type: array
                            items:
                              description: A node selector requirement is a selector that contains
                                values, a key, and an operator that relates the key and values.
                              type: object
                              required:
                              - key
                              - operator
                              properties:
                                key:
                                  description: The label key that the selector applies to.
                                  type: string
                                operator:
                                  description: Represents a key's relationship to a set of values.
                                    Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
                                    Lt.
                                  type: string
                                values:
                                  description: An array of string values. If the operator is In
                                    or NotIn, the values array must be non-empty. If the operator
                                    is Exists or DoesNotExist, the values array must be empty. If
                                    the operator is Gt or Lt, the values array must have a single
                                    element, which will be interpreted as an integer. This array
                                    is replaced during a strategic merge patch.
                                  type: array
                                  items:
                                    type: string
                          matchFields:
                            description: A list of node selector requirements by node's fields.
                            type: array
                            items:
                              description: A node selector requirement is a selector that contains
                                values, a key, and an operator that relates the key and values.
                              type: object
                              required:
                              - key
                              - operator
                              properties:
                                key:
                                  description: The label key that the selector applies to.
                                  type: string
                                operator:
                                  description: Represents a key's relationship to a set of values.
                                    Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
                                    Lt.
                                  type: string
                                values:
                                  description: An array of string values. If the operator is In
                                    or NotIn, the values array must be non-empty. If the operator
                                    is Exists or DoesNotExist, the values array must be empty. If
                                    the operator is Gt or Lt, the values array must have a single
                                    element, which will be interpreted as an integer. This array
                                    is replaced during a strategic merge patch.
                                  type: array
                                  items:
                                    type: string
                      weight:
                        description: Weight associated with matching the corresponding nodeSelectorTerm,
                          in the range 1-100.
                        type: integer
                        format: int32
                requiredDuringSchedulingIgnoredDuringExecution:
                  description: If the affinity requirements specified by this field are not met
                    at scheduling time, the pod will not be scheduled onto the node. If the affinity
                    requirements specified by this field cease to be met at some point during pod
                    execution (e.g. due to an update), the system may or may not try to eventually
                    evict the pod from its node. A node selector represents the union of the results
                    of one or more label queries over a set of nodes; that is, it represents the
                    OR of the selectors represented by the node selector terms.
                  type: object
                  required:
                  - nodeSelectorTerms
                  properties:
                    nodeSelectorTerms:
                      description: Required. A list of node selector terms. The terms are ORed.
                      type: array
                      items:
                        description: A null or empty node selector term matches no objects. The
                          requirements of them are ANDed. The TopologySelectorTerm type implements
                          a subset of the NodeSelectorTerm.
                        type: object
                        properties:
                          matchExpressions:
                            description: A list of node selector requirements by node's labels.
                            type: array
                            items:
                              description: A node selector requirement is a selector that contains
                                values, a key, and an operator that relates the key and values.
                              type: object
                              required:
                              - key
                              - operator
                              properties:
                                key:
                                  description: The label key that the selector applies to.
                                  type: string
                                operator:
                                  description: Represents a key's relationship to a set of values.
                                    Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
                                    Lt.
                                  type: string
                                values:
                                  description: An array of string values. If the operator is In
                                    or NotIn, the values array must be non-empty. If the operator
                                    is Exists or DoesNotExist, the values array must be empty. If
                                    the operator is Gt or Lt, the values array must have a single
                                    element, which will be interpreted as an integer. This array
                                    is replaced during a strategic merge patch.
                                  type: array
                                  items:
                                    type: string
                          matchFields:
                            description: A list of node selector requirements by node's fields.
                            type: array
                            items:
                              description: A node selector requirement is a selector that contains
                                values, a key, and an operator that relates the key and values.
                              type: object
                              required:
                              - key
                              - operator
                              properties:
                                key:
                                  description: The label key that the selector applies to.
                                  type: string
                                operator:
                                  description: Represents a key's relationship to a set of values.
                                    Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and
                                    Lt.
                                  type: string
                                values:
                                  description: An array of string values. If the operator is In
                                    or NotIn, the values array must be non-empty. If the operator
                                    is Exists or DoesNotExist, the values array must be empty. If
                                    the operator is Gt or Lt, the values array must have a single
                                    element, which will be interpreted as an integer. This array
                                    is replaced during a strategic merge patch.
                                  type: array
                                  items:
                                    type: string

Вау, для проверки только одного поля (и его подполей) мое определение CRD увеличилось на 100+ строк , все просто для того, чтобы переопределить то, что уже существует в родном для Kubernetes определении pod api Также потребовалось около 15 минут для ручного копирования и вставки всех ссылок в Kubernetes spe c. Разве это не имеет особого смысла:

A) Сохраните эту длинную спецификацию API c во внешнем файле и используйте $ ref: externalfile. json, чтобы сохранить ее, чтобы сохранить мой CRD маленький и чистый.

ИЛИ ЛУЧШЕ YET

B) Вставьте фактическую проверку подлинности Kubernetes c, которая УЖЕ СУЩЕСТВУЕТ, с тегом $ ref, подобным этому:

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: workshops.k8s.example.tk
spec:
  group: k8s.example.tk
  names:
    kind: Workshop
    listKind: WorkshopList
    plural: workshops
    singular: workshop
  scope: Namespaced
  subresources:
    status: {}
  validation:
    openAPIV3Schema:
      type: object
      properties:
        spec:
          type: object
          required:
          - workshopID
          properties:
            workshopID: #
              type: string
              description: Unique identifier for this particular virtual 
workshop
              example: d8e8fca2dc0f896fd7cb4cb0031ba249
            affinity:
              type: object
              properties:
                nodeAffinity:
                  $ref: <kubernetes-api>/openapi/v2#/definitions/io.k8s.api.core.v1.NodeAffinity

Сократите до 30 или около того строк кода И ИСПОЛЬЗОВАНИЕ проверки c остается актуальной с собственной проверкой Kubernetes, поскольку она получает информацию из самого API Kubernetes. В соответствии с этим, $ ref должен поддерживаться при этом: https://swagger.io/docs/specification/using-ref/#syntax

...