diff --git a/.gitignore b/.gitignore index b9a90ae4..be2d6482 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ bin **/*.key .DS_Store *.tgz +kind.yaml diff --git a/Makefile b/Makefile index e444eb95..1d1df373 100644 --- a/Makefile +++ b/Makefile @@ -139,7 +139,10 @@ dev-setup: export CA_BUNDLE=`openssl base64 -in /tmp/k8s-webhook-server/serving-certs/tls.crt | tr -d '\n'`; \ kubectl patch MutatingWebhookConfiguration capsule-mutating-webhook-configuration \ --type='json' -p="[\ - {'op': 'replace', 'path': '/webhooks/0/clientConfig', 'value':{'url':\"$${WEBHOOK_URL}/namespace-owner-reference\",'caBundle':\"$${CA_BUNDLE}\"}}\ + {'op': 'replace', 'path': '/webhooks/0/clientConfig', 'value':{'url':\"$${WEBHOOK_URL}/defaults\",'caBundle':\"$${CA_BUNDLE}\"}},\ + {'op': 'replace', 'path': '/webhooks/1/clientConfig', 'value':{'url':\"$${WEBHOOK_URL}/defaults\",'caBundle':\"$${CA_BUNDLE}\"}},\ + {'op': 'replace', 'path': '/webhooks/2/clientConfig', 'value':{'url':\"$${WEBHOOK_URL}/defaults\",'caBundle':\"$${CA_BUNDLE}\"}},\ + {'op': 'replace', 'path': '/webhooks/3/clientConfig', 'value':{'url':\"$${WEBHOOK_URL}/namespace-owner-reference\",'caBundle':\"$${CA_BUNDLE}\"}}\ ]" && \ kubectl patch ValidatingWebhookConfiguration capsule-validating-webhook-configuration \ --type='json' -p="[\ diff --git a/api/v1beta2/ingress_options.go b/api/v1beta2/ingress_options.go index 9e821afc..3fe8c4cd 100644 --- a/api/v1beta2/ingress_options.go +++ b/api/v1beta2/ingress_options.go @@ -8,8 +8,11 @@ import ( ) type IngressOptions struct { - // Specifies the allowed IngressClasses assigned to the Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. Optional. - AllowedClasses *api.SelectorAllowedListSpec `json:"allowedClasses,omitempty"` + // Specifies the allowed IngressClasses assigned to the Tenant. + // Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. + // A default value can be specified, and all the Ingress resources created will inherit the declared class. + // Optional. + AllowedClasses *api.DefaultAllowedListSpec `json:"allowedClasses,omitempty"` // Defines the scope of hostname collision check performed when Tenant Owners create Ingress with allowed hostnames. // // diff --git a/api/v1beta2/tenant_conversion_hub.go b/api/v1beta2/tenant_conversion_hub.go index a3dee20a..45c03bb4 100644 --- a/api/v1beta2/tenant_conversion_hub.go +++ b/api/v1beta2/tenant_conversion_hub.go @@ -86,8 +86,10 @@ func (in *Tenant) ConvertFrom(raw conversion.Hub) error { in.Spec.ServiceOptions = src.Spec.ServiceOptions if src.Spec.StorageClasses != nil { - in.Spec.StorageClasses = &api.SelectorAllowedListSpec{ - AllowedListSpec: *src.Spec.StorageClasses, + in.Spec.StorageClasses = &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: *src.Spec.StorageClasses, + }, } } @@ -106,8 +108,10 @@ func (in *Tenant) ConvertFrom(raw conversion.Hub) error { } if ingressClass := src.Spec.IngressOptions.AllowedClasses; ingressClass != nil { - in.Spec.IngressOptions.AllowedClasses = &api.SelectorAllowedListSpec{ - AllowedListSpec: *ingressClass, + in.Spec.IngressOptions.AllowedClasses = &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: *ingressClass, + }, } } @@ -124,8 +128,10 @@ func (in *Tenant) ConvertFrom(raw conversion.Hub) error { in.Spec.ImagePullPolicies = src.Spec.ImagePullPolicies if src.Spec.PriorityClasses != nil { - in.Spec.PriorityClasses = &api.SelectorAllowedListSpec{ - AllowedListSpec: *src.Spec.PriorityClasses, + in.Spec.PriorityClasses = &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: *src.Spec.PriorityClasses, + }, } } diff --git a/api/v1beta2/tenant_types.go b/api/v1beta2/tenant_types.go index 2d9ac06c..c7a18f46 100644 --- a/api/v1beta2/tenant_types.go +++ b/api/v1beta2/tenant_types.go @@ -17,8 +17,11 @@ type TenantSpec struct { NamespaceOptions *NamespaceOptions `json:"namespaceOptions,omitempty"` // Specifies options for the Service, such as additional metadata or block of certain type of Services. Optional. ServiceOptions *api.ServiceOptions `json:"serviceOptions,omitempty"` - // Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. Optional. - StorageClasses *api.SelectorAllowedListSpec `json:"storageClasses,omitempty"` + // Specifies the allowed StorageClasses assigned to the Tenant. + // Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. + // A default value can be specified, and all the PersistentVolumeClaim resources created will inherit the declared class. + // Optional. + StorageClasses *api.DefaultAllowedListSpec `json:"storageClasses,omitempty"` // Specifies options for the Ingress resources, such as allowed hostnames and IngressClass. Optional. IngressOptions IngressOptions `json:"ingressOptions,omitempty"` // Specifies the trusted Image Registries assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed trusted registries. Optional. @@ -35,10 +38,15 @@ type TenantSpec struct { AdditionalRoleBindings []api.AdditionalRoleBindingsSpec `json:"additionalRoleBindings,omitempty"` // Specify the allowed values for the imagePullPolicies option in Pod resources. Capsule assures that all Pod resources created in the Tenant can use only one of the allowed policy. Optional. ImagePullPolicies []api.ImagePullPolicySpec `json:"imagePullPolicies,omitempty"` - // Specifies the allowed RuntimeClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed RuntimeClasses. Optional. + // Specifies the allowed RuntimeClasses assigned to the Tenant. + // Capsule assures that all Pods resources created in the Tenant can use only one of the allowed RuntimeClasses. + // Optional. RuntimeClasses *api.SelectorAllowedListSpec `json:"runtimeClasses,omitempty"` - // Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. Optional. - PriorityClasses *api.SelectorAllowedListSpec `json:"priorityClasses,omitempty"` + // Specifies the allowed priorityClasses assigned to the Tenant. + // Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. + // A default value can be specified, and all the Pod resources created will inherit the declared class. + // Optional. + PriorityClasses *api.DefaultAllowedListSpec `json:"priorityClasses,omitempty"` // Toggling the Tenant resources cordoning, when enable resources cannot be deleted. Cordoned bool `json:"cordoned,omitempty"` // Prevent accidental deletion of the Tenant. diff --git a/api/v1beta2/zz_generated.deepcopy.go b/api/v1beta2/zz_generated.deepcopy.go index 2d044ffb..141f2fe9 100644 --- a/api/v1beta2/zz_generated.deepcopy.go +++ b/api/v1beta2/zz_generated.deepcopy.go @@ -261,7 +261,7 @@ func (in *IngressOptions) DeepCopyInto(out *IngressOptions) { *out = *in if in.AllowedClasses != nil { in, out := &in.AllowedClasses, &out.AllowedClasses - *out = new(api.SelectorAllowedListSpec) + *out = new(api.DefaultAllowedListSpec) (*in).DeepCopyInto(*out) } if in.AllowedHostnames != nil { @@ -718,7 +718,7 @@ func (in *TenantSpec) DeepCopyInto(out *TenantSpec) { } if in.StorageClasses != nil { in, out := &in.StorageClasses, &out.StorageClasses - *out = new(api.SelectorAllowedListSpec) + *out = new(api.DefaultAllowedListSpec) (*in).DeepCopyInto(*out) } in.IngressOptions.DeepCopyInto(&out.IngressOptions) @@ -756,7 +756,7 @@ func (in *TenantSpec) DeepCopyInto(out *TenantSpec) { } if in.PriorityClasses != nil { in, out := &in.PriorityClasses, &out.PriorityClasses - *out = new(api.SelectorAllowedListSpec) + *out = new(api.DefaultAllowedListSpec) (*in).DeepCopyInto(*out) } } diff --git a/charts/capsule/README.md b/charts/capsule/README.md index a4772e96..3d34b8d3 100644 --- a/charts/capsule/README.md +++ b/charts/capsule/README.md @@ -130,6 +130,15 @@ Here the values you can override: | webhooks.cordoning.failurePolicy | string | `"Fail"` | | | webhooks.cordoning.namespaceSelector.matchExpressions[0].key | string | `"capsule.clastix.io/tenant"` | | | webhooks.cordoning.namespaceSelector.matchExpressions[0].operator | string | `"Exists"` | | +| webhooks.defaults.ingress.failurePolicy | string | `"Fail"` | | +| webhooks.defaults.ingress.namespaceSelector.matchExpressions[0].key | string | `"capsule.clastix.io/tenant"` | | +| webhooks.defaults.ingress.namespaceSelector.matchExpressions[0].operator | string | `"Exists"` | | +| webhooks.defaults.pods.failurePolicy | string | `"Fail"` | | +| webhooks.defaults.pods.namespaceSelector.matchExpressions[0].key | string | `"capsule.clastix.io/tenant"` | | +| webhooks.defaults.pods.namespaceSelector.matchExpressions[0].operator | string | `"Exists"` | | +| webhooks.defaults.pvc.failurePolicy | string | `"Fail"` | | +| webhooks.defaults.pvc.namespaceSelector.matchExpressions[0].key | string | `"capsule.clastix.io/tenant"` | | +| webhooks.defaults.pvc.namespaceSelector.matchExpressions[0].operator | string | `"Exists"` | | | webhooks.ingresses.failurePolicy | string | `"Fail"` | | | webhooks.ingresses.namespaceSelector.matchExpressions[0].key | string | `"capsule.clastix.io/tenant"` | | | webhooks.ingresses.namespaceSelector.matchExpressions[0].operator | string | `"Exists"` | | diff --git a/charts/capsule/crds/tenant-crd.yaml b/charts/capsule/crds/tenant-crd.yaml index f783ba48..ae8b2a15 100644 --- a/charts/capsule/crds/tenant-crd.yaml +++ b/charts/capsule/crds/tenant-crd.yaml @@ -4,3190 +4,2124 @@ kind: CustomResourceDefinition metadata: annotations: controller-gen.kubebuilder.io/version: v0.10.0 - creationTimestamp: null name: tenants.capsule.clastix.io spec: + conversion: + strategy: Webhook + webhook: + clientConfig: + service: + name: capsule-webhook-service + namespace: capsule-system + path: /convert + conversionReviewVersions: + - v1alpha1 + - v1beta1 + - v1beta2 group: capsule.clastix.io names: kind: Tenant listKind: TenantList plural: tenants shortNames: - - tnt + - tnt singular: tenant scope: Cluster versions: - - additionalPrinterColumns: - - description: The max amount of Namespaces can be created - jsonPath: .spec.namespaceQuota - name: Namespace quota - type: integer - - description: The total amount of Namespaces in use - jsonPath: .status.size - name: Namespace count - type: integer - - description: The assigned Tenant owner - jsonPath: .spec.owner.name - name: Owner name - type: string - - description: The assigned Tenant owner kind - jsonPath: .spec.owner.kind - name: Owner kind - type: string - - description: Node Selector applied to Pods - jsonPath: .spec.nodeSelector - name: Node selector - type: string - - description: Age - jsonPath: .metadata.creationTimestamp - name: Age - type: date - deprecated: true - deprecationWarning: This version is going to be dropped in the upcoming version - of Capsule; please, migrate to v1beta2 version. - name: v1alpha1 - schema: - openAPIV3Schema: - description: Tenant is the Schema for the tenants API. - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: TenantSpec defines the desired state of Tenant. - properties: - additionalRoleBindings: - items: + - additionalPrinterColumns: + - description: The max amount of Namespaces can be created + jsonPath: .spec.namespaceQuota + name: Namespace quota + type: integer + - description: The total amount of Namespaces in use + jsonPath: .status.size + name: Namespace count + type: integer + - description: The assigned Tenant owner + jsonPath: .spec.owner.name + name: Owner name + type: string + - description: The assigned Tenant owner kind + jsonPath: .spec.owner.kind + name: Owner kind + type: string + - description: Node Selector applied to Pods + jsonPath: .spec.nodeSelector + name: Node selector + type: string + - description: Age + jsonPath: .metadata.creationTimestamp + name: Age + type: date + deprecated: true + deprecationWarning: This version is going to be dropped in the upcoming version of Capsule; please, migrate to v1beta2 version. + name: v1alpha1 + schema: + openAPIV3Schema: + description: Tenant is the Schema for the tenants API. + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + description: TenantSpec defines the desired state of Tenant. + properties: + additionalRoleBindings: + items: + properties: + clusterRoleName: + type: string + subjects: + description: kubebuilder:validation:Minimum=1 + items: + description: Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names. + properties: + apiGroup: + description: APIGroup holds the API group of the referenced subject. Defaults to "" for ServiceAccount subjects. Defaults to "rbac.authorization.k8s.io" for User and Group subjects. + type: string + kind: + description: Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". If the Authorizer does not recognized the kind value, the Authorizer should report an error. + type: string + name: + description: Name of the object being referenced. + type: string + namespace: + description: Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty the Authorizer should report an error. + type: string + required: + - kind + - name + type: object + x-kubernetes-map-type: atomic + type: array + required: + - clusterRoleName + - subjects + type: object + type: array + containerRegistries: properties: - clusterRoleName: - type: string - subjects: - description: kubebuilder:validation:Minimum=1 + allowed: items: - description: Subject contains a reference to the object or - user identities a role binding applies to. This can either - hold a direct API object reference, or a value for non-objects - such as user and group names. - properties: - apiGroup: - description: APIGroup holds the API group of the referenced - subject. Defaults to "" for ServiceAccount subjects. - Defaults to "rbac.authorization.k8s.io" for User and - Group subjects. - type: string - kind: - description: Kind of object being referenced. Values defined - by this API group are "User", "Group", and "ServiceAccount". - If the Authorizer does not recognized the kind value, - the Authorizer should report an error. - type: string - name: - description: Name of the object being referenced. - type: string - namespace: - description: Namespace of the referenced object. If the - object kind is non-namespace, such as "User" or "Group", - and this value is not empty the Authorizer should report - an error. - type: string - required: - - kind - - name - type: object - x-kubernetes-map-type: atomic + type: string type: array - required: - - clusterRoleName - - subjects - type: object - type: array - containerRegistries: - properties: - allowed: - items: - type: string - type: array - allowedRegex: - type: string - type: object - externalServiceIPs: - properties: - allowed: - items: - pattern: ^([0-9]{1,3}.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ + allowedRegex: type: string - type: array - required: - - allowed - type: object - ingressClasses: - properties: - allowed: - items: - type: string - type: array - allowedRegex: - type: string - type: object - ingressHostnames: - properties: - allowed: - items: - type: string - type: array - allowedRegex: - type: string - type: object - limitRanges: - items: - description: LimitRangeSpec defines a min/max usage limit for resources - that match on kind. + type: object + externalServiceIPs: properties: - limits: - description: Limits is the list of LimitRangeItem objects that - are enforced. + allowed: items: - description: LimitRangeItem defines a min/max usage limit - for any resource that matches on kind. - properties: - default: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Default resource requirement limit value - by resource name if resource limit is omitted. - type: object - defaultRequest: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: DefaultRequest is the default resource requirement - request value by resource name if resource request is - omitted. - type: object - max: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Max usage constraints on this kind by resource - name. - type: object - maxLimitRequestRatio: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: MaxLimitRequestRatio if specified, the named - resource must have a request and limit that are both - non-zero where limit divided by request is less than - or equal to the enumerated value; this represents the - max burst for the named resource. - type: object - min: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Min usage constraints on this kind by resource - name. - type: object - type: - description: Type of resource that this limit applies - to. - type: string - required: - - type - type: object + pattern: ^([0-9]{1,3}.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ + type: string type: array required: - - limits + - allowed type: object - type: array - namespaceQuota: - format: int32 - minimum: 1 - type: integer - namespacesMetadata: - properties: - additionalAnnotations: - additionalProperties: - type: string - type: object - additionalLabels: - additionalProperties: + ingressClasses: + properties: + allowed: + items: + type: string + type: array + allowedRegex: type: string - type: object - type: object - networkPolicies: - items: - description: NetworkPolicySpec provides the specification of a NetworkPolicy + type: object + ingressHostnames: properties: - egress: - description: List of egress rules to be applied to the selected - pods. Outgoing traffic is allowed if there are no NetworkPolicies - selecting the pod (and cluster policy otherwise allows the - traffic), OR if the traffic matches at least one egress rule - across all of the NetworkPolicy objects whose podSelector - matches the pod. If this field is empty then this NetworkPolicy - limits all outgoing traffic (and serves solely to ensure that - the pods it selects are isolated by default). This field is - beta-level in 1.8 + allowed: items: - description: NetworkPolicyEgressRule describes a particular - set of traffic that is allowed out of pods matched by a - NetworkPolicySpec's podSelector. The traffic must match - both ports and to. This type is beta-level in 1.8 - properties: - ports: - description: List of destination ports for outgoing traffic. - Each item in this list is combined using a logical OR. - If this field is empty or missing, this rule matches - all ports (traffic not restricted by port). If this - field is present and contains at least one item, then - this rule allows traffic only if the traffic matches - at least one port in the list. - items: - description: NetworkPolicyPort describes a port to allow - traffic on - properties: - endPort: - description: If set, indicates that the range of - ports from port to endPort, inclusive, should - be allowed by the policy. This field cannot be - defined if the port field is not defined or if - the port field is defined as a named (string) - port. The endPort must be equal or greater than - port. This feature is in Beta state and is enabled - by default. It can be disabled using the Feature - Gate "NetworkPolicyEndPort". - format: int32 - type: integer - port: - anyOf: + type: string + type: array + allowedRegex: + type: string + type: object + limitRanges: + items: + description: LimitRangeSpec defines a min/max usage limit for resources that match on kind. + properties: + limits: + description: Limits is the list of LimitRangeItem objects that are enforced. + items: + description: LimitRangeItem defines a min/max usage limit for any resource that matches on kind. + properties: + default: + additionalProperties: + anyOf: - type: integer - type: string - description: The port on the given protocol. This - can either be a numerical or named port on a pod. - If this field is not provided, this matches all - port names and numbers. If present, only traffic - on the specified protocol AND port will be matched. - x-kubernetes-int-or-string: true - protocol: - default: TCP - description: The protocol (TCP, UDP, or SCTP) which - traffic must match. If not specified, this field - defaults to TCP. - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Default resource requirement limit value by resource name if resource limit is omitted. type: object - type: array - to: - description: List of destinations for outgoing traffic - of pods selected for this rule. Items in this list are - combined using a logical OR operation. If this field - is empty or missing, this rule matches all destinations - (traffic not restricted by destination). If this field - is present and contains at least one item, this rule - allows traffic only if the traffic matches at least - one item in the to list. - items: - description: NetworkPolicyPeer describes a peer to allow - traffic to/from. Only certain combinations of fields - are allowed - properties: - ipBlock: - description: IPBlock defines policy on a particular - IPBlock. If this field is set then neither of - the other fields can be. - properties: - cidr: - description: CIDR is a string representing the - IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" - type: string - except: - description: Except is a slice of CIDRs that - should not be included within an IP Block - Valid examples are "192.168.1.1/24" or "2001:db9::/64" - Except values will be rejected if they are - outside the CIDR range - items: + defaultRequest: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: DefaultRequest is the default resource requirement request value by resource name if resource request is omitted. + type: object + max: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Max usage constraints on this kind by resource name. + type: object + maxLimitRequestRatio: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: MaxLimitRequestRatio if specified, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource. + type: object + min: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Min usage constraints on this kind by resource name. + type: object + type: + description: Type of resource that this limit applies to. + type: string + required: + - type + type: object + type: array + required: + - limits + type: object + type: array + namespaceQuota: + format: int32 + minimum: 1 + type: integer + namespacesMetadata: + properties: + additionalAnnotations: + additionalProperties: + type: string + type: object + additionalLabels: + additionalProperties: + type: string + type: object + type: object + networkPolicies: + items: + description: NetworkPolicySpec provides the specification of a NetworkPolicy + properties: + egress: + description: List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 + items: + description: NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to. This type is beta-level in 1.8 + properties: + ports: + description: List of destination ports for outgoing traffic. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + items: + description: NetworkPolicyPort describes a port to allow traffic on + properties: + endPort: + description: If set, indicates that the range of ports from port to endPort, inclusive, should be allowed by the policy. This field cannot be defined if the port field is not defined or if the port field is defined as a named (string) port. The endPort must be equal or greater than port. This feature is in Beta state and is enabled by default. It can be disabled using the Feature Gate "NetworkPolicyEndPort". + format: int32 + type: integer + port: + anyOf: + - type: integer + - type: string + description: The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched. + x-kubernetes-int-or-string: true + protocol: + default: TCP + description: The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. + type: string + type: object + type: array + to: + description: List of destinations for outgoing traffic of pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all destinations (traffic not restricted by destination). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the to list. + items: + description: NetworkPolicyPeer describes a peer to allow traffic to/from. Only certain combinations of fields are allowed + properties: + ipBlock: + description: IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. + properties: + cidr: + description: CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" type: string - type: array - required: - - cidr - type: object - namespaceSelector: - description: "Selects Namespaces using cluster-scoped - labels. This field follows standard label selector - semantics; if present but empty, it selects all - namespaces. \n If PodSelector is also set, then - the NetworkPolicyPeer as a whole selects the Pods - matching PodSelector in the Namespaces selected - by NamespaceSelector. Otherwise it selects all - Pods in the Namespaces selected by NamespaceSelector." - properties: - matchExpressions: - description: matchExpressions is a list of label - selector requirements. The requirements are - ANDed. - items: - description: A label selector requirement - is a selector that contains values, a key, - and an operator that relates the key and - values. - properties: - key: - description: key is the label key that - the selector applies to. - type: string - operator: - description: operator represents a key's - relationship to a set of values. Valid - operators are In, NotIn, Exists and - DoesNotExist. - type: string - values: - description: values is 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. This - array is replaced during a strategic - merge patch. - items: + except: + description: Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" Except values will be rejected if they are outside the CIDR range + items: + type: string + type: array + required: + - cidr + type: object + namespaceSelector: + description: "Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. \n If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator is - "In", and the values array contains only "value". - The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - podSelector: - description: "This is a label selector which selects - Pods. This field follows standard label selector - semantics; if present but empty, it selects all - pods. \n If NamespaceSelector is also set, then - the NetworkPolicyPeer as a whole selects the Pods - matching PodSelector in the Namespaces selected - by NamespaceSelector. Otherwise it selects the - Pods matching PodSelector in the policy's own - Namespace." - properties: - matchExpressions: - description: matchExpressions is a list of label - selector requirements. The requirements are - ANDed. - items: - description: A label selector requirement - is a selector that contains values, a key, - and an operator that relates the key and - values. - properties: - key: - description: key is the label key that - the selector applies to. - type: string - operator: - description: operator represents a key's - relationship to a set of values. Valid - operators are In, NotIn, Exists and - DoesNotExist. - type: string - values: - description: values is 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. This - array is replaced during a strategic - merge patch. - items: + type: object + x-kubernetes-map-type: atomic + podSelector: + description: "This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. \n If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator is - "In", and the values array contains only "value". - The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - type: array - type: object - type: array - ingress: - description: List of ingress rules to be applied to the selected - pods. Traffic is allowed to a pod if there are no NetworkPolicies - selecting the pod (and cluster policy otherwise allows the - traffic), OR if the traffic source is the pod's local node, - OR if the traffic matches at least one ingress rule across - all of the NetworkPolicy objects whose podSelector matches - the pod. If this field is empty then this NetworkPolicy does - not allow any traffic (and serves solely to ensure that the - pods it selects are isolated by default) - items: - description: NetworkPolicyIngressRule describes a particular - set of traffic that is allowed to the pods matched by a - NetworkPolicySpec's podSelector. The traffic must match - both ports and from. - properties: - from: - description: List of sources which should be able to access - the pods selected for this rule. Items in this list - are combined using a logical OR operation. If this field - is empty or missing, this rule matches all sources (traffic - not restricted by source). If this field is present - and contains at least one item, this rule allows traffic - only if the traffic matches at least one item in the - from list. - items: - description: NetworkPolicyPeer describes a peer to allow - traffic to/from. Only certain combinations of fields - are allowed - properties: - ipBlock: - description: IPBlock defines policy on a particular - IPBlock. If this field is set then neither of - the other fields can be. - properties: - cidr: - description: CIDR is a string representing the - IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" - type: string - except: - description: Except is a slice of CIDRs that - should not be included within an IP Block - Valid examples are "192.168.1.1/24" or "2001:db9::/64" - Except values will be rejected if they are - outside the CIDR range - items: + type: object + x-kubernetes-map-type: atomic + type: object + type: array + type: object + type: array + ingress: + description: List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) + items: + description: NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from. + properties: + from: + description: List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the from list. + items: + description: NetworkPolicyPeer describes a peer to allow traffic to/from. Only certain combinations of fields are allowed + properties: + ipBlock: + description: IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. + properties: + cidr: + description: CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" type: string - type: array - required: - - cidr - type: object - namespaceSelector: - description: "Selects Namespaces using cluster-scoped - labels. This field follows standard label selector - semantics; if present but empty, it selects all - namespaces. \n If PodSelector is also set, then - the NetworkPolicyPeer as a whole selects the Pods - matching PodSelector in the Namespaces selected - by NamespaceSelector. Otherwise it selects all - Pods in the Namespaces selected by NamespaceSelector." - properties: - matchExpressions: - description: matchExpressions is a list of label - selector requirements. The requirements are - ANDed. - items: - description: A label selector requirement - is a selector that contains values, a key, - and an operator that relates the key and - values. - properties: - key: - description: key is the label key that - the selector applies to. - type: string - operator: - description: operator represents a key's - relationship to a set of values. Valid - operators are In, NotIn, Exists and - DoesNotExist. - type: string - values: - description: values is 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. This - array is replaced during a strategic - merge patch. - items: + except: + description: Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" Except values will be rejected if they are outside the CIDR range + items: + type: string + type: array + required: + - cidr + type: object + namespaceSelector: + description: "Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. \n If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator is - "In", and the values array contains only "value". - The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - podSelector: - description: "This is a label selector which selects - Pods. This field follows standard label selector - semantics; if present but empty, it selects all - pods. \n If NamespaceSelector is also set, then - the NetworkPolicyPeer as a whole selects the Pods - matching PodSelector in the Namespaces selected - by NamespaceSelector. Otherwise it selects the - Pods matching PodSelector in the policy's own - Namespace." - properties: - matchExpressions: - description: matchExpressions is a list of label - selector requirements. The requirements are - ANDed. - items: - description: A label selector requirement - is a selector that contains values, a key, - and an operator that relates the key and - values. - properties: - key: - description: key is the label key that - the selector applies to. - type: string - operator: - description: operator represents a key's - relationship to a set of values. Valid - operators are In, NotIn, Exists and - DoesNotExist. - type: string - values: - description: values is 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. This - array is replaced during a strategic - merge patch. - items: + type: object + x-kubernetes-map-type: atomic + podSelector: + description: "This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. \n If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator is - "In", and the values array contains only "value". - The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - type: array - ports: - description: List of ports which should be made accessible - on the pods selected for this rule. Each item in this - list is combined using a logical OR. If this field is - empty or missing, this rule matches all ports (traffic - not restricted by port). If this field is present and - contains at least one item, then this rule allows traffic - only if the traffic matches at least one port in the - list. + type: object + x-kubernetes-map-type: atomic + type: object + type: array + ports: + description: List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + items: + description: NetworkPolicyPort describes a port to allow traffic on + properties: + endPort: + description: If set, indicates that the range of ports from port to endPort, inclusive, should be allowed by the policy. This field cannot be defined if the port field is not defined or if the port field is defined as a named (string) port. The endPort must be equal or greater than port. This feature is in Beta state and is enabled by default. It can be disabled using the Feature Gate "NetworkPolicyEndPort". + format: int32 + type: integer + port: + anyOf: + - type: integer + - type: string + description: The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched. + x-kubernetes-int-or-string: true + protocol: + default: TCP + description: The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. + type: string + type: object + type: array + type: object + type: array + podSelector: + description: Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: - description: NetworkPolicyPort describes a port to allow - traffic on + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: - endPort: - description: If set, indicates that the range of - ports from port to endPort, inclusive, should - be allowed by the policy. This field cannot be - defined if the port field is not defined or if - the port field is defined as a named (string) - port. The endPort must be equal or greater than - port. This feature is in Beta state and is enabled - by default. It can be disabled using the Feature - Gate "NetworkPolicyEndPort". - format: int32 - type: integer - port: - anyOf: - - type: integer - - type: string - description: The port on the given protocol. This - can either be a numerical or named port on a pod. - If this field is not provided, this matches all - port names and numbers. If present, only traffic - on the specified protocol AND port will be matched. - x-kubernetes-int-or-string: true - protocol: - default: TCP - description: The protocol (TCP, UDP, or SCTP) which - traffic must match. If not specified, this field - defaults to TCP. + key: + description: key is the label key that the selector applies to. type: string + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator type: object type: array - type: object - type: array - podSelector: - description: Selects the pods to which this NetworkPolicy object - applies. The array of ingress rules is applied to any pods - selected by this field. Multiple network policies can select - the same set of pods. In this case, the ingress rules for - each are combined additively. This field is NOT optional and - follows standard label selector semantics. An empty podSelector - matches all pods in this namespace. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: A label selector requirement is a selector - that contains values, a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: operator represents a key's relationship - to a set of values. Valid operators are In, NotIn, - Exists and DoesNotExist. - type: string - values: - description: values is 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. This - array is replaced during a strategic merge patch. - items: - type: string - type: array - required: - - key - - operator - type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} pairs. - A single {key,value} in the matchLabels map is equivalent - to an element of matchExpressions, whose key field is - "key", the operator is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - policyTypes: - description: List of rule types that the NetworkPolicy relates - to. Valid options are ["Ingress"], ["Egress"], or ["Ingress", - "Egress"]. If this field is not specified, it will default - based on the existence of Ingress or Egress rules; policies - that contain an Egress section are assumed to affect Egress, - and all policies (whether or not they contain an Ingress section) - are assumed to affect Ingress. If you want to write an egress-only - policy, you must explicitly specify policyTypes [ "Egress" - ]. Likewise, if you want to write a policy that specifies - that no egress is allowed, you must specify a policyTypes - value that include "Egress" (since such a policy would not - include an Egress section and would otherwise default to just - [ "Ingress" ]). This field is beta-level in 1.8 - items: - description: PolicyType string describes the NetworkPolicy - type This type is beta-level in 1.8 - type: string - type: array - required: - - podSelector - type: object - type: array - nodeSelector: - additionalProperties: - type: string - type: object - owner: - description: OwnerSpec defines tenant owner name and kind. - properties: - kind: - enum: - - User - - Group - type: string - name: - type: string - required: - - kind - - name - type: object - resourceQuotas: - items: - description: ResourceQuotaSpec defines the desired hard limits to - enforce for Quota. - properties: - hard: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: 'hard is the set of desired hard limits for each - named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/' - type: object - scopeSelector: - description: scopeSelector is also a collection of filters like - scopes that must match each object tracked by a quota but - expressed using ScopeSelectorOperator in combination with - possible values. For a resource to match, both scopes AND - scopeSelector (if specified in spec), must be matched. - properties: - matchExpressions: - description: A list of scope selector requirements by scope - of the resources. - items: - description: A scoped-resource selector requirement is - a selector that contains values, a scope name, and an - operator that relates the scope name and values. - properties: - operator: - description: Represents a scope's relationship to - a set of values. Valid operators are In, NotIn, - Exists, DoesNotExist. - type: string - scopeName: - description: The name of the scope that the selector - applies to. - 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. This array is replaced during - a strategic merge patch. - items: - type: string - type: array - required: - - operator - - scopeName + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - type: object - x-kubernetes-map-type: atomic - scopes: - description: A collection of filters that must match each object - tracked by a quota. If not specified, the quota matches all - objects. - items: - description: A ResourceQuotaScope defines a filter that must - match each object tracked by a quota - type: string - type: array - type: object - type: array - servicesMetadata: - properties: - additionalAnnotations: - additionalProperties: - type: string - type: object - additionalLabels: - additionalProperties: - type: string + type: object + x-kubernetes-map-type: atomic + policyTypes: + description: List of rule types that the NetworkPolicy relates to. Valid options are ["Ingress"], ["Egress"], or ["Ingress", "Egress"]. If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include "Egress" (since such a policy would not include an Egress section and would otherwise default to just [ "Ingress" ]). This field is beta-level in 1.8 + items: + description: PolicyType string describes the NetworkPolicy type This type is beta-level in 1.8 + type: string + type: array + required: + - podSelector type: object - type: object - storageClasses: - properties: - allowed: - items: - type: string - type: array - allowedRegex: + type: array + nodeSelector: + additionalProperties: type: string - type: object - required: - - owner - type: object - status: - description: TenantStatus defines the observed state of Tenant. - properties: - namespaces: - items: - type: string - type: array - size: - type: integer - required: - - size - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - description: The actual state of the Tenant - jsonPath: .status.state - name: State - type: string - - description: The max amount of Namespaces can be created - jsonPath: .spec.namespaceOptions.quota - name: Namespace quota - type: integer - - description: The total amount of Namespaces in use - jsonPath: .status.size - name: Namespace count - type: integer - - description: Node Selector applied to Pods - jsonPath: .spec.nodeSelector - name: Node selector - type: string - - description: Age - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1beta1 - schema: - openAPIV3Schema: - description: Tenant is the Schema for the tenants API. - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: TenantSpec defines the desired state of Tenant. - properties: - additionalRoleBindings: - description: Specifies additional RoleBindings assigned to the Tenant. - Capsule will ensure that all namespaces in the Tenant always contain - the RoleBinding for the given ClusterRole. Optional. - items: + type: object + owner: + description: OwnerSpec defines tenant owner name and kind. properties: - clusterRoleName: + kind: + enum: + - User + - Group + type: string + name: type: string - subjects: - description: kubebuilder:validation:Minimum=1 - items: - description: Subject contains a reference to the object or - user identities a role binding applies to. This can either - hold a direct API object reference, or a value for non-objects - such as user and group names. - properties: - apiGroup: - description: APIGroup holds the API group of the referenced - subject. Defaults to "" for ServiceAccount subjects. - Defaults to "rbac.authorization.k8s.io" for User and - Group subjects. - type: string - kind: - description: Kind of object being referenced. Values defined - by this API group are "User", "Group", and "ServiceAccount". - If the Authorizer does not recognized the kind value, - the Authorizer should report an error. - type: string - name: - description: Name of the object being referenced. - type: string - namespace: - description: Namespace of the referenced object. If the - object kind is non-namespace, such as "User" or "Group", - and this value is not empty the Authorizer should report - an error. - type: string - required: - - kind - - name - type: object - x-kubernetes-map-type: atomic - type: array required: - - clusterRoleName - - subjects + - kind + - name type: object - type: array - containerRegistries: - description: Specifies the trusted Image Registries assigned to the - Tenant. Capsule assures that all Pods resources created in the Tenant - can use only one of the allowed trusted registries. Optional. - properties: - allowed: - items: - type: string - type: array - allowedRegex: - type: string - type: object - imagePullPolicies: - description: Specify the allowed values for the imagePullPolicies - option in Pod resources. Capsule assures that all Pod resources - created in the Tenant can use only one of the allowed policy. Optional. - items: - enum: - - Always - - Never - - IfNotPresent - type: string - type: array - ingressOptions: - description: Specifies options for the Ingress resources, such as - allowed hostnames and IngressClass. Optional. - properties: - allowedClasses: - description: Specifies the allowed IngressClasses assigned to - the Tenant. Capsule assures that all Ingress resources created - in the Tenant can use only one of the allowed IngressClasses. - Optional. + resourceQuotas: + items: + description: ResourceQuotaSpec defines the desired hard limits to enforce for Quota. properties: - allowed: + hard: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: 'hard is the set of desired hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/' + type: object + scopeSelector: + description: scopeSelector is also a collection of filters like scopes that must match each object tracked by a quota but expressed using ScopeSelectorOperator in combination with possible values. For a resource to match, both scopes AND scopeSelector (if specified in spec), must be matched. + properties: + matchExpressions: + description: A list of scope selector requirements by scope of the resources. + items: + description: A scoped-resource selector requirement is a selector that contains values, a scope name, and an operator that relates the scope name and values. + properties: + operator: + description: Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. + type: string + scopeName: + description: The name of the scope that the selector applies to. + 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - operator + - scopeName + type: object + type: array + type: object + x-kubernetes-map-type: atomic + scopes: + description: A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects. items: + description: A ResourceQuotaScope defines a filter that must match each object tracked by a quota type: string type: array - allowedRegex: - type: string type: object - allowedHostnames: - description: Specifies the allowed hostnames in Ingresses for - the given Tenant. Capsule assures that all Ingress resources - created in the Tenant can use only one of the allowed hostnames. - Optional. - properties: - allowed: - items: - type: string - type: array - allowedRegex: + type: array + servicesMetadata: + properties: + additionalAnnotations: + additionalProperties: type: string - type: object - hostnameCollisionScope: - default: Disabled - description: "Defines the scope of hostname collision check performed - when Tenant Owners create Ingress with allowed hostnames. \n - - Cluster: disallow the creation of an Ingress if the pair hostname - and path is already used across the Namespaces managed by Capsule. - \n - Tenant: disallow the creation of an Ingress if the pair - hostname and path is already used across the Namespaces of the - Tenant. \n - Namespace: disallow the creation of an Ingress - if the pair hostname and path is already used in the Ingress - Namespace. \n Optional." - enum: - - Cluster - - Tenant - - Namespace - - Disabled + type: object + additionalLabels: + additionalProperties: + type: string + type: object + type: object + storageClasses: + properties: + allowed: + items: + type: string + type: array + allowedRegex: + type: string + type: object + required: + - owner + type: object + status: + description: TenantStatus defines the observed state of Tenant. + properties: + namespaces: + items: type: string - type: object - limitRanges: - description: Specifies the resource min/max usage restrictions to - the Tenant. The assigned values are inherited by any namespace created - in the Tenant. Optional. - properties: + type: array + size: + type: integer + required: + - size + type: object + type: object + served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: The actual state of the Tenant + jsonPath: .status.state + name: State + type: string + - description: The max amount of Namespaces can be created + jsonPath: .spec.namespaceOptions.quota + name: Namespace quota + type: integer + - description: The total amount of Namespaces in use + jsonPath: .status.size + name: Namespace count + type: integer + - description: Node Selector applied to Pods + jsonPath: .spec.nodeSelector + name: Node selector + type: string + - description: Age + jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1beta1 + schema: + openAPIV3Schema: + description: Tenant is the Schema for the tenants API. + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + description: TenantSpec defines the desired state of Tenant. + properties: + additionalRoleBindings: + description: Specifies additional RoleBindings assigned to the Tenant. Capsule will ensure that all namespaces in the Tenant always contain the RoleBinding for the given ClusterRole. Optional. items: - items: - description: LimitRangeSpec defines a min/max usage limit for - resources that match on kind. - properties: - limits: - description: Limits is the list of LimitRangeItem objects - that are enforced. - items: - description: LimitRangeItem defines a min/max usage limit - for any resource that matches on kind. - properties: - default: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Default resource requirement limit value - by resource name if resource limit is omitted. - type: object - defaultRequest: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: DefaultRequest is the default resource - requirement request value by resource name if resource - request is omitted. - type: object - max: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Max usage constraints on this kind by - resource name. - type: object - maxLimitRequestRatio: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: MaxLimitRequestRatio if specified, the - named resource must have a request and limit that - are both non-zero where limit divided by request - is less than or equal to the enumerated value; this - represents the max burst for the named resource. - type: object - min: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Min usage constraints on this kind by - resource name. - type: object - type: - description: Type of resource that this limit applies - to. - type: string - required: - - type - type: object - type: array - required: - - limits - type: object - type: array - type: object - namespaceOptions: - description: Specifies options for the Namespaces, such as additional - metadata or maximum number of namespaces allowed for that Tenant. - Once the namespace quota assigned to the Tenant has been reached, - the Tenant owner cannot create further namespaces. Optional. - properties: - additionalMetadata: - description: Specifies additional labels and annotations the Capsule - operator places on any Namespace resource in the Tenant. Optional. - properties: - annotations: - additionalProperties: - type: string - type: object - labels: - additionalProperties: - type: string - type: object + properties: + clusterRoleName: + type: string + subjects: + description: kubebuilder:validation:Minimum=1 + items: + description: Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names. + properties: + apiGroup: + description: APIGroup holds the API group of the referenced subject. Defaults to "" for ServiceAccount subjects. Defaults to "rbac.authorization.k8s.io" for User and Group subjects. + type: string + kind: + description: Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". If the Authorizer does not recognized the kind value, the Authorizer should report an error. + type: string + name: + description: Name of the object being referenced. + type: string + namespace: + description: Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty the Authorizer should report an error. + type: string + required: + - kind + - name + type: object + x-kubernetes-map-type: atomic + type: array + required: + - clusterRoleName + - subjects type: object - quota: - description: Specifies the maximum number of namespaces allowed - for that Tenant. Once the namespace quota assigned to the Tenant - has been reached, the Tenant owner cannot create further namespaces. - Optional. - format: int32 - minimum: 1 - type: integer - type: object - networkPolicies: - description: Specifies the NetworkPolicies assigned to the Tenant. - The assigned NetworkPolicies are inherited by any namespace created - in the Tenant. Optional. - properties: + type: array + containerRegistries: + description: Specifies the trusted Image Registries assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed trusted registries. Optional. + properties: + allowed: + items: + type: string + type: array + allowedRegex: + type: string + type: object + imagePullPolicies: + description: Specify the allowed values for the imagePullPolicies option in Pod resources. Capsule assures that all Pod resources created in the Tenant can use only one of the allowed policy. Optional. items: - items: - description: NetworkPolicySpec provides the specification of - a NetworkPolicy + enum: + - Always + - Never + - IfNotPresent + type: string + type: array + ingressOptions: + description: Specifies options for the Ingress resources, such as allowed hostnames and IngressClass. Optional. + properties: + allowedClasses: + description: Specifies the allowed IngressClasses assigned to the Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. Optional. properties: - egress: - description: List of egress rules to be applied to the selected - pods. Outgoing traffic is allowed if there are no NetworkPolicies - selecting the pod (and cluster policy otherwise allows - the traffic), OR if the traffic matches at least one egress - rule across all of the NetworkPolicy objects whose podSelector - matches the pod. If this field is empty then this NetworkPolicy - limits all outgoing traffic (and serves solely to ensure - that the pods it selects are isolated by default). This - field is beta-level in 1.8 + allowed: items: - description: NetworkPolicyEgressRule describes a particular - set of traffic that is allowed out of pods matched by - a NetworkPolicySpec's podSelector. The traffic must - match both ports and to. This type is beta-level in - 1.8 - properties: - ports: - description: List of destination ports for outgoing - traffic. Each item in this list is combined using - a logical OR. If this field is empty or missing, - this rule matches all ports (traffic not restricted - by port). If this field is present and contains - at least one item, then this rule allows traffic - only if the traffic matches at least one port in - the list. - items: - description: NetworkPolicyPort describes a port - to allow traffic on - properties: - endPort: - description: If set, indicates that the range - of ports from port to endPort, inclusive, - should be allowed by the policy. This field - cannot be defined if the port field is not - defined or if the port field is defined as - a named (string) port. The endPort must be - equal or greater than port. This feature is - in Beta state and is enabled by default. It - can be disabled using the Feature Gate "NetworkPolicyEndPort". - format: int32 - type: integer - port: - anyOf: + type: string + type: array + allowedRegex: + type: string + type: object + allowedHostnames: + description: Specifies the allowed hostnames in Ingresses for the given Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed hostnames. Optional. + properties: + allowed: + items: + type: string + type: array + allowedRegex: + type: string + type: object + hostnameCollisionScope: + default: Disabled + description: "Defines the scope of hostname collision check performed when Tenant Owners create Ingress with allowed hostnames. \n - Cluster: disallow the creation of an Ingress if the pair hostname and path is already used across the Namespaces managed by Capsule. \n - Tenant: disallow the creation of an Ingress if the pair hostname and path is already used across the Namespaces of the Tenant. \n - Namespace: disallow the creation of an Ingress if the pair hostname and path is already used in the Ingress Namespace. \n Optional." + enum: + - Cluster + - Tenant + - Namespace + - Disabled + type: string + type: object + limitRanges: + description: Specifies the resource min/max usage restrictions to the Tenant. The assigned values are inherited by any namespace created in the Tenant. Optional. + properties: + items: + items: + description: LimitRangeSpec defines a min/max usage limit for resources that match on kind. + properties: + limits: + description: Limits is the list of LimitRangeItem objects that are enforced. + items: + description: LimitRangeItem defines a min/max usage limit for any resource that matches on kind. + properties: + default: + additionalProperties: + anyOf: - type: integer - type: string - description: The port on the given protocol. - This can either be a numerical or named port - on a pod. If this field is not provided, this - matches all port names and numbers. If present, - only traffic on the specified protocol AND - port will be matched. - x-kubernetes-int-or-string: true - protocol: - default: TCP - description: The protocol (TCP, UDP, or SCTP) - which traffic must match. If not specified, - this field defaults to TCP. - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Default resource requirement limit value by resource name if resource limit is omitted. type: object - type: array - to: - description: List of destinations for outgoing traffic - of pods selected for this rule. Items in this list - are combined using a logical OR operation. If this - field is empty or missing, this rule matches all - destinations (traffic not restricted by destination). - If this field is present and contains at least one - item, this rule allows traffic only if the traffic - matches at least one item in the to list. - items: - description: NetworkPolicyPeer describes a peer - to allow traffic to/from. Only certain combinations - of fields are allowed - properties: - ipBlock: - description: IPBlock defines policy on a particular - IPBlock. If this field is set then neither - of the other fields can be. - properties: - cidr: - description: CIDR is a string representing - the IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" - type: string - except: - description: Except is a slice of CIDRs - that should not be included within an - IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" Except values will - be rejected if they are outside the CIDR - range - items: + defaultRequest: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: DefaultRequest is the default resource requirement request value by resource name if resource request is omitted. + type: object + max: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Max usage constraints on this kind by resource name. + type: object + maxLimitRequestRatio: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: MaxLimitRequestRatio if specified, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource. + type: object + min: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Min usage constraints on this kind by resource name. + type: object + type: + description: Type of resource that this limit applies to. + type: string + required: + - type + type: object + type: array + required: + - limits + type: object + type: array + type: object + namespaceOptions: + description: Specifies options for the Namespaces, such as additional metadata or maximum number of namespaces allowed for that Tenant. Once the namespace quota assigned to the Tenant has been reached, the Tenant owner cannot create further namespaces. Optional. + properties: + additionalMetadata: + description: Specifies additional labels and annotations the Capsule operator places on any Namespace resource in the Tenant. Optional. + properties: + annotations: + additionalProperties: + type: string + type: object + labels: + additionalProperties: + type: string + type: object + type: object + quota: + description: Specifies the maximum number of namespaces allowed for that Tenant. Once the namespace quota assigned to the Tenant has been reached, the Tenant owner cannot create further namespaces. Optional. + format: int32 + minimum: 1 + type: integer + type: object + networkPolicies: + description: Specifies the NetworkPolicies assigned to the Tenant. The assigned NetworkPolicies are inherited by any namespace created in the Tenant. Optional. + properties: + items: + items: + description: NetworkPolicySpec provides the specification of a NetworkPolicy + properties: + egress: + description: List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 + items: + description: NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to. This type is beta-level in 1.8 + properties: + ports: + description: List of destination ports for outgoing traffic. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + items: + description: NetworkPolicyPort describes a port to allow traffic on + properties: + endPort: + description: If set, indicates that the range of ports from port to endPort, inclusive, should be allowed by the policy. This field cannot be defined if the port field is not defined or if the port field is defined as a named (string) port. The endPort must be equal or greater than port. This feature is in Beta state and is enabled by default. It can be disabled using the Feature Gate "NetworkPolicyEndPort". + format: int32 + type: integer + port: + anyOf: + - type: integer + - type: string + description: The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched. + x-kubernetes-int-or-string: true + protocol: + default: TCP + description: The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. + type: string + type: object + type: array + to: + description: List of destinations for outgoing traffic of pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all destinations (traffic not restricted by destination). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the to list. + items: + description: NetworkPolicyPeer describes a peer to allow traffic to/from. Only certain combinations of fields are allowed + properties: + ipBlock: + description: IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. + properties: + cidr: + description: CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" type: string - type: array - required: - - cidr - type: object - namespaceSelector: - description: "Selects Namespaces using cluster-scoped - labels. This field follows standard label - selector semantics; if present but empty, - it selects all namespaces. \n If PodSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects all Pods in the Namespaces - selected by NamespaceSelector." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + except: + description: Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" Except values will be rejected if they are outside the CIDR range + items: + type: string + type: array + required: + - cidr + type: object + namespaceSelector: + description: "Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. \n If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - podSelector: - description: "This is a label selector which - selects Pods. This field follows standard - label selector semantics; if present but empty, - it selects all pods. \n If NamespaceSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects the Pods matching PodSelector - in the policy's own Namespace." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + type: object + x-kubernetes-map-type: atomic + podSelector: + description: "This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. \n If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - type: array - type: object - type: array - ingress: - description: List of ingress rules to be applied to the - selected pods. Traffic is allowed to a pod if there are - no NetworkPolicies selecting the pod (and cluster policy - otherwise allows the traffic), OR if the traffic source - is the pod's local node, OR if the traffic matches at - least one ingress rule across all of the NetworkPolicy - objects whose podSelector matches the pod. If this field - is empty then this NetworkPolicy does not allow any traffic - (and serves solely to ensure that the pods it selects - are isolated by default) - items: - description: NetworkPolicyIngressRule describes a particular - set of traffic that is allowed to the pods matched by - a NetworkPolicySpec's podSelector. The traffic must - match both ports and from. - properties: - from: - description: List of sources which should be able - to access the pods selected for this rule. Items - in this list are combined using a logical OR operation. - If this field is empty or missing, this rule matches - all sources (traffic not restricted by source). - If this field is present and contains at least one - item, this rule allows traffic only if the traffic - matches at least one item in the from list. - items: - description: NetworkPolicyPeer describes a peer - to allow traffic to/from. Only certain combinations - of fields are allowed - properties: - ipBlock: - description: IPBlock defines policy on a particular - IPBlock. If this field is set then neither - of the other fields can be. - properties: - cidr: - description: CIDR is a string representing - the IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" - type: string - except: - description: Except is a slice of CIDRs - that should not be included within an - IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" Except values will - be rejected if they are outside the CIDR - range - items: + type: object + x-kubernetes-map-type: atomic + type: object + type: array + type: object + type: array + ingress: + description: List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) + items: + description: NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from. + properties: + from: + description: List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the from list. + items: + description: NetworkPolicyPeer describes a peer to allow traffic to/from. Only certain combinations of fields are allowed + properties: + ipBlock: + description: IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. + properties: + cidr: + description: CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" type: string - type: array - required: - - cidr - type: object - namespaceSelector: - description: "Selects Namespaces using cluster-scoped - labels. This field follows standard label - selector semantics; if present but empty, - it selects all namespaces. \n If PodSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects all Pods in the Namespaces - selected by NamespaceSelector." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + except: + description: Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" Except values will be rejected if they are outside the CIDR range + items: + type: string + type: array + required: + - cidr + type: object + namespaceSelector: + description: "Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. \n If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - podSelector: - description: "This is a label selector which - selects Pods. This field follows standard - label selector semantics; if present but empty, - it selects all pods. \n If NamespaceSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects the Pods matching PodSelector - in the policy's own Namespace." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + type: object + x-kubernetes-map-type: atomic + podSelector: + description: "This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. \n If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - type: array - ports: - description: List of ports which should be made accessible - on the pods selected for this rule. Each item in - this list is combined using a logical OR. If this - field is empty or missing, this rule matches all - ports (traffic not restricted by port). If this - field is present and contains at least one item, - then this rule allows traffic only if the traffic - matches at least one port in the list. + type: object + x-kubernetes-map-type: atomic + type: object + type: array + ports: + description: List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + items: + description: NetworkPolicyPort describes a port to allow traffic on + properties: + endPort: + description: If set, indicates that the range of ports from port to endPort, inclusive, should be allowed by the policy. This field cannot be defined if the port field is not defined or if the port field is defined as a named (string) port. The endPort must be equal or greater than port. This feature is in Beta state and is enabled by default. It can be disabled using the Feature Gate "NetworkPolicyEndPort". + format: int32 + type: integer + port: + anyOf: + - type: integer + - type: string + description: The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched. + x-kubernetes-int-or-string: true + protocol: + default: TCP + description: The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. + type: string + type: object + type: array + type: object + type: array + podSelector: + description: Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: - description: NetworkPolicyPort describes a port - to allow traffic on + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: - endPort: - description: If set, indicates that the range - of ports from port to endPort, inclusive, - should be allowed by the policy. This field - cannot be defined if the port field is not - defined or if the port field is defined as - a named (string) port. The endPort must be - equal or greater than port. This feature is - in Beta state and is enabled by default. It - can be disabled using the Feature Gate "NetworkPolicyEndPort". - format: int32 - type: integer - port: - anyOf: - - type: integer - - type: string - description: The port on the given protocol. - This can either be a numerical or named port - on a pod. If this field is not provided, this - matches all port names and numbers. If present, - only traffic on the specified protocol AND - port will be matched. - x-kubernetes-int-or-string: true - protocol: - default: TCP - description: The protocol (TCP, UDP, or SCTP) - which traffic must match. If not specified, - this field defaults to TCP. + key: + description: key is the label key that the selector applies to. + type: string + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator type: object type: array - type: object - type: array - podSelector: - description: Selects the pods to which this NetworkPolicy - object applies. The array of ingress rules is applied - to any pods selected by this field. Multiple network policies - can select the same set of pods. In this case, the ingress - rules for each are combined additively. This field is - NOT optional and follows standard label selector semantics. - An empty podSelector matches all pods in this namespace. - properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. - items: - description: A label selector requirement is a selector - that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: operator represents a key's relationship - to a set of values. Valid operators are In, - NotIn, Exists and DoesNotExist. - type: string - values: - description: values is 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. - This array is replaced during a strategic merge - patch. - items: - type: string - type: array - required: - - key - - operator + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} pairs. - A single {key,value} in the matchLabels map is equivalent - to an element of matchExpressions, whose key field - is "key", the operator is "In", and the values array - contains only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - policyTypes: - description: List of rule types that the NetworkPolicy relates - to. Valid options are ["Ingress"], ["Egress"], or ["Ingress", - "Egress"]. If this field is not specified, it will default - based on the existence of Ingress or Egress rules; policies - that contain an Egress section are assumed to affect Egress, - and all policies (whether or not they contain an Ingress - section) are assumed to affect Ingress. If you want to - write an egress-only policy, you must explicitly specify - policyTypes [ "Egress" ]. Likewise, if you want to write - a policy that specifies that no egress is allowed, you - must specify a policyTypes value that include "Egress" - (since such a policy would not include an Egress section - and would otherwise default to just [ "Ingress" ]). This - field is beta-level in 1.8 - items: - description: PolicyType string describes the NetworkPolicy - type This type is beta-level in 1.8 - type: string - type: array - required: - - podSelector - type: object - type: array - type: object - nodeSelector: - additionalProperties: - type: string - description: Specifies the label to control the placement of pods - on a given pool of worker nodes. All namespaces created within the - Tenant will have the node selector annotation. This annotation tells - the Kubernetes scheduler to place pods on the nodes having the selector - label. Optional. - type: object - owners: - description: Specifies the owners of the Tenant. Mandatory. - items: - properties: - kind: - description: Kind of tenant owner. Possible values are "User", - "Group", and "ServiceAccount" - enum: - - User - - Group - - ServiceAccount - type: string - name: - description: Name of tenant owner. - type: string - proxySettings: - description: Proxy settings for tenant owner. - items: - properties: - kind: - enum: - - Nodes - - StorageClasses - - IngressClasses - - PriorityClasses - type: string - operations: + type: object + x-kubernetes-map-type: atomic + policyTypes: + description: List of rule types that the NetworkPolicy relates to. Valid options are ["Ingress"], ["Egress"], or ["Ingress", "Egress"]. If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include "Egress" (since such a policy would not include an Egress section and would otherwise default to just [ "Ingress" ]). This field is beta-level in 1.8 items: - enum: - - List - - Update - - Delete + description: PolicyType string describes the NetworkPolicy type This type is beta-level in 1.8 type: string type: array required: - - kind - - operations + - podSelector type: object type: array - required: - - kind - - name type: object - type: array - priorityClasses: - description: Specifies the allowed priorityClasses assigned to the - Tenant. Capsule assures that all Pods resources created in the Tenant - can use only one of the allowed PriorityClasses. Optional. - properties: - allowed: - items: - type: string - type: array - allowedRegex: + nodeSelector: + additionalProperties: type: string - type: object - resourceQuotas: - description: Specifies a list of ResourceQuota resources assigned - to the Tenant. The assigned values are inherited by any namespace - created in the Tenant. The Capsule operator aggregates ResourceQuota - at Tenant level, so that the hard quota is never crossed for the - given Tenant. This permits the Tenant owner to consume resources - in the Tenant regardless of the namespace. Optional. - properties: + description: Specifies the label to control the placement of pods on a given pool of worker nodes. All namespaces created within the Tenant will have the node selector annotation. This annotation tells the Kubernetes scheduler to place pods on the nodes having the selector label. Optional. + type: object + owners: + description: Specifies the owners of the Tenant. Mandatory. items: - items: - description: ResourceQuotaSpec defines the desired hard limits - to enforce for Quota. - properties: - hard: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: 'hard is the set of desired hard limits for - each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/' - type: object - scopeSelector: - description: scopeSelector is also a collection of filters - like scopes that must match each object tracked by a quota - but expressed using ScopeSelectorOperator in combination - with possible values. For a resource to match, both scopes - AND scopeSelector (if specified in spec), must be matched. + properties: + kind: + description: Kind of tenant owner. Possible values are "User", "Group", and "ServiceAccount" + enum: + - User + - Group + - ServiceAccount + type: string + name: + description: Name of tenant owner. + type: string + proxySettings: + description: Proxy settings for tenant owner. + items: properties: - matchExpressions: - description: A list of scope selector requirements by - scope of the resources. + kind: + enum: + - Nodes + - StorageClasses + - IngressClasses + - PriorityClasses + type: string + operations: items: - description: A scoped-resource selector requirement - is a selector that contains values, a scope name, - and an operator that relates the scope name and - values. - properties: - operator: - description: Represents a scope's relationship - to a set of values. Valid operators are In, - NotIn, Exists, DoesNotExist. - type: string - scopeName: - description: The name of the scope that the selector - applies to. - 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. This array is - replaced during a strategic merge patch. - items: - type: string - type: array - required: - - operator - - scopeName - type: object + enum: + - List + - Update + - Delete + type: string type: array - type: object - x-kubernetes-map-type: atomic - scopes: - description: A collection of filters that must match each - object tracked by a quota. If not specified, the quota - matches all objects. - items: - description: A ResourceQuotaScope defines a filter that - must match each object tracked by a quota - type: string - type: array - type: object - type: array - scope: - default: Tenant - description: Define if the Resource Budget should compute resource - across all Namespaces in the Tenant or individually per cluster. - Default is Tenant - enum: - - Tenant - - Namespace - type: string - type: object - serviceOptions: - description: Specifies options for the Service, such as additional - metadata or block of certain type of Services. Optional. - properties: - additionalMetadata: - description: Specifies additional labels and annotations the Capsule - operator places on any Service resource in the Tenant. Optional. - properties: - annotations: - additionalProperties: - type: string - type: object - labels: - additionalProperties: - type: string - type: object - type: object - allowedServices: - description: Block or deny certain type of Services. Optional. - properties: - externalName: - default: true - description: Specifies if ExternalName service type resources - are allowed for the Tenant. Default is true. Optional. - type: boolean - loadBalancer: - default: true - description: Specifies if LoadBalancer service type resources - are allowed for the Tenant. Default is true. Optional. - type: boolean - nodePort: - default: true - description: Specifies if NodePort service type resources - are allowed for the Tenant. Default is true. Optional. - type: boolean - type: object - externalIPs: - description: Specifies the external IPs that can be used in Services - with type ClusterIP. An empty list means no IPs are allowed. - Optional. - properties: - allowed: - items: - pattern: ^([0-9]{1,3}.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ - type: string + required: + - kind + - operations + type: object type: array required: - - allowed + - kind + - name type: object - type: object - storageClasses: - description: Specifies the allowed StorageClasses assigned to the - Tenant. Capsule assures that all PersistentVolumeClaim resources - created in the Tenant can use only one of the allowed StorageClasses. - Optional. - properties: - allowed: - items: - type: string - type: array - allowedRegex: - type: string - type: object - required: - - owners - type: object - status: - description: Returns the observed state of the Tenant. - properties: - namespaces: - description: List of namespaces assigned to the Tenant. - items: - type: string - type: array - size: - description: How many namespaces are assigned to the Tenant. - type: integer - state: - default: Active - description: The operational state of the Tenant. Possible values - are "Active", "Cordoned". - enum: - - Cordoned - - Active - type: string - required: - - size - - state - type: object - type: object - served: true - storage: false - subresources: - status: {} - - additionalPrinterColumns: - - description: The actual state of the Tenant - jsonPath: .status.state - name: State - type: string - - description: The max amount of Namespaces can be created - jsonPath: .spec.namespaceOptions.quota - name: Namespace quota - type: integer - - description: The total amount of Namespaces in use - jsonPath: .status.size - name: Namespace count - type: integer - - description: Node Selector applied to Pods - jsonPath: .spec.nodeSelector - name: Node selector - type: string - - description: Age - jsonPath: .metadata.creationTimestamp - name: Age - type: date - name: v1beta2 - schema: - openAPIV3Schema: - description: Tenant is the Schema for the tenants API. - properties: - apiVersion: - description: 'APIVersion defines the versioned schema of this representation - of an object. Servers should convert recognized schemas to the latest - internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' - type: string - kind: - description: 'Kind is a string value representing the REST resource this - object represents. Servers may infer this from the endpoint the client - submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' - type: string - metadata: - type: object - spec: - description: TenantSpec defines the desired state of Tenant. - properties: - additionalRoleBindings: - description: Specifies additional RoleBindings assigned to the Tenant. - Capsule will ensure that all namespaces in the Tenant always contain - the RoleBinding for the given ClusterRole. Optional. - items: + type: array + priorityClasses: + description: Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. Optional. properties: - clusterRoleName: + allowed: + items: + type: string + type: array + allowedRegex: type: string - subjects: - description: kubebuilder:validation:Minimum=1 + type: object + resourceQuotas: + description: Specifies a list of ResourceQuota resources assigned to the Tenant. The assigned values are inherited by any namespace created in the Tenant. The Capsule operator aggregates ResourceQuota at Tenant level, so that the hard quota is never crossed for the given Tenant. This permits the Tenant owner to consume resources in the Tenant regardless of the namespace. Optional. + properties: + items: items: - description: Subject contains a reference to the object or - user identities a role binding applies to. This can either - hold a direct API object reference, or a value for non-objects - such as user and group names. + description: ResourceQuotaSpec defines the desired hard limits to enforce for Quota. properties: - apiGroup: - description: APIGroup holds the API group of the referenced - subject. Defaults to "" for ServiceAccount subjects. - Defaults to "rbac.authorization.k8s.io" for User and - Group subjects. - type: string - kind: - description: Kind of object being referenced. Values defined - by this API group are "User", "Group", and "ServiceAccount". - If the Authorizer does not recognized the kind value, - the Authorizer should report an error. + hard: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: 'hard is the set of desired hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/' + type: object + scopeSelector: + description: scopeSelector is also a collection of filters like scopes that must match each object tracked by a quota but expressed using ScopeSelectorOperator in combination with possible values. For a resource to match, both scopes AND scopeSelector (if specified in spec), must be matched. + properties: + matchExpressions: + description: A list of scope selector requirements by scope of the resources. + items: + description: A scoped-resource selector requirement is a selector that contains values, a scope name, and an operator that relates the scope name and values. + properties: + operator: + description: Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. + type: string + scopeName: + description: The name of the scope that the selector applies to. + 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - operator + - scopeName + type: object + type: array + type: object + x-kubernetes-map-type: atomic + scopes: + description: A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects. + items: + description: A ResourceQuotaScope defines a filter that must match each object tracked by a quota + type: string + type: array + type: object + type: array + scope: + default: Tenant + description: Define if the Resource Budget should compute resource across all Namespaces in the Tenant or individually per cluster. Default is Tenant + enum: + - Tenant + - Namespace + type: string + type: object + serviceOptions: + description: Specifies options for the Service, such as additional metadata or block of certain type of Services. Optional. + properties: + additionalMetadata: + description: Specifies additional labels and annotations the Capsule operator places on any Service resource in the Tenant. Optional. + properties: + annotations: + additionalProperties: type: string - name: - description: Name of the object being referenced. + type: object + labels: + additionalProperties: type: string - namespace: - description: Namespace of the referenced object. If the - object kind is non-namespace, such as "User" or "Group", - and this value is not empty the Authorizer should report - an error. + type: object + type: object + allowedServices: + description: Block or deny certain type of Services. Optional. + properties: + externalName: + default: true + description: Specifies if ExternalName service type resources are allowed for the Tenant. Default is true. Optional. + type: boolean + loadBalancer: + default: true + description: Specifies if LoadBalancer service type resources are allowed for the Tenant. Default is true. Optional. + type: boolean + nodePort: + default: true + description: Specifies if NodePort service type resources are allowed for the Tenant. Default is true. Optional. + type: boolean + type: object + externalIPs: + description: Specifies the external IPs that can be used in Services with type ClusterIP. An empty list means no IPs are allowed. Optional. + properties: + allowed: + items: + pattern: ^([0-9]{1,3}.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ type: string - required: - - kind - - name - type: object - x-kubernetes-map-type: atomic - type: array - required: - - clusterRoleName - - subjects + type: array + required: + - allowed + type: object type: object - type: array - containerRegistries: - description: Specifies the trusted Image Registries assigned to the - Tenant. Capsule assures that all Pods resources created in the Tenant - can use only one of the allowed trusted registries. Optional. - properties: - allowed: - items: + storageClasses: + description: Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. Optional. + properties: + allowed: + items: + type: string + type: array + allowedRegex: type: string - type: array - allowedRegex: + type: object + required: + - owners + type: object + status: + description: Returns the observed state of the Tenant. + properties: + namespaces: + description: List of namespaces assigned to the Tenant. + items: type: string - type: object - cordoned: - description: Toggling the Tenant resources cordoning, when enable - resources cannot be deleted. - type: boolean - imagePullPolicies: - description: Specify the allowed values for the imagePullPolicies - option in Pod resources. Capsule assures that all Pod resources - created in the Tenant can use only one of the allowed policy. Optional. - items: + type: array + size: + description: How many namespaces are assigned to the Tenant. + type: integer + state: + default: Active + description: The operational state of the Tenant. Possible values are "Active", "Cordoned". enum: - - Always - - Never - - IfNotPresent + - Cordoned + - Active type: string - type: array - ingressOptions: - description: Specifies options for the Ingress resources, such as - allowed hostnames and IngressClass. Optional. - properties: - allowWildcardHostnames: - description: Toggles the ability for Ingress resources created - in a Tenant to have a hostname wildcard. - type: boolean - allowedClasses: - description: Specifies the allowed IngressClasses assigned to - the Tenant. Capsule assures that all Ingress resources created - in the Tenant can use only one of the allowed IngressClasses. - Optional. + required: + - size + - state + type: object + type: object + served: true + storage: false + subresources: + status: {} + - additionalPrinterColumns: + - description: The actual state of the Tenant + jsonPath: .status.state + name: State + type: string + - description: The max amount of Namespaces can be created + jsonPath: .spec.namespaceOptions.quota + name: Namespace quota + type: integer + - description: The total amount of Namespaces in use + jsonPath: .status.size + name: Namespace count + type: integer + - description: Node Selector applied to Pods + jsonPath: .spec.nodeSelector + name: Node selector + type: string + - description: Age + jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1beta2 + schema: + openAPIV3Schema: + description: Tenant is the Schema for the tenants API. + properties: + apiVersion: + description: 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' + type: string + kind: + description: 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' + type: string + metadata: + type: object + spec: + description: TenantSpec defines the desired state of Tenant. + properties: + additionalRoleBindings: + description: Specifies additional RoleBindings assigned to the Tenant. Capsule will ensure that all namespaces in the Tenant always contain the RoleBinding for the given ClusterRole. Optional. + items: properties: - allowed: - items: - type: string - type: array - allowedRegex: + clusterRoleName: type: string - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. + subjects: + description: kubebuilder:validation:Minimum=1 items: - description: A label selector requirement is a selector - that contains values, a key, and an operator that relates - the key and values. + description: Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names. properties: - key: - description: key is the label key that the selector - applies to. + apiGroup: + description: APIGroup holds the API group of the referenced subject. Defaults to "" for ServiceAccount subjects. Defaults to "rbac.authorization.k8s.io" for User and Group subjects. type: string - operator: - description: operator represents a key's relationship - to a set of values. Valid operators are In, NotIn, - Exists and DoesNotExist. + kind: + description: Kind of object being referenced. Values defined by this API group are "User", "Group", and "ServiceAccount". If the Authorizer does not recognized the kind value, the Authorizer should report an error. + type: string + name: + description: Name of the object being referenced. + type: string + namespace: + description: Namespace of the referenced object. If the object kind is non-namespace, such as "User" or "Group", and this value is not empty the Authorizer should report an error. type: string - values: - description: values is 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. This array is replaced - during a strategic merge patch. - items: - type: string - type: array required: - - key - - operator + - kind + - name type: object + x-kubernetes-map-type: atomic type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} pairs. A - single {key,value} in the matchLabels map is equivalent - to an element of matchExpressions, whose key field is "key", - the operator is "In", and the values array contains only - "value". The requirements are ANDed. - type: object + required: + - clusterRoleName + - subjects type: object - x-kubernetes-map-type: atomic - allowedHostnames: - description: Specifies the allowed hostnames in Ingresses for - the given Tenant. Capsule assures that all Ingress resources - created in the Tenant can use only one of the allowed hostnames. - Optional. - properties: - allowed: - items: - type: string - type: array - allowedRegex: + type: array + containerRegistries: + description: Specifies the trusted Image Registries assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed trusted registries. Optional. + properties: + allowed: + items: type: string - type: object - hostnameCollisionScope: - default: Disabled - description: "Defines the scope of hostname collision check performed - when Tenant Owners create Ingress with allowed hostnames. \n - - Cluster: disallow the creation of an Ingress if the pair hostname - and path is already used across the Namespaces managed by Capsule. - \n - Tenant: disallow the creation of an Ingress if the pair - hostname and path is already used across the Namespaces of the - Tenant. \n - Namespace: disallow the creation of an Ingress - if the pair hostname and path is already used in the Ingress - Namespace. \n Optional." + type: array + allowedRegex: + type: string + type: object + cordoned: + description: Toggling the Tenant resources cordoning, when enable resources cannot be deleted. + type: boolean + imagePullPolicies: + description: Specify the allowed values for the imagePullPolicies option in Pod resources. Capsule assures that all Pod resources created in the Tenant can use only one of the allowed policy. Optional. + items: enum: - - Cluster - - Tenant - - Namespace - - Disabled + - Always + - Never + - IfNotPresent type: string - required: - - allowWildcardHostnames - type: object - limitRanges: - description: Specifies the resource min/max usage restrictions to - the Tenant. The assigned values are inherited by any namespace created - in the Tenant. Optional. - properties: - items: - items: - description: LimitRangeSpec defines a min/max usage limit for - resources that match on kind. + type: array + ingressOptions: + description: Specifies options for the Ingress resources, such as allowed hostnames and IngressClass. Optional. + properties: + allowWildcardHostnames: + description: Toggles the ability for Ingress resources created in a Tenant to have a hostname wildcard. + type: boolean + allowedClasses: + description: Specifies the allowed IngressClasses assigned to the Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. A default value can be specified, and all the Ingress resources created will inherit the declared class. Optional. properties: - limits: - description: Limits is the list of LimitRangeItem objects - that are enforced. + allowed: + items: + type: string + type: array + allowedRegex: + type: string + default: + type: string + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: - description: LimitRangeItem defines a min/max usage limit - for any resource that matches on kind. + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: - default: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Default resource requirement limit value - by resource name if resource limit is omitted. - type: object - defaultRequest: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: DefaultRequest is the default resource - requirement request value by resource name if resource - request is omitted. - type: object - max: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Max usage constraints on this kind by - resource name. - type: object - maxLimitRequestRatio: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: MaxLimitRequestRatio if specified, the - named resource must have a request and limit that - are both non-zero where limit divided by request - is less than or equal to the enumerated value; this - represents the max burst for the named resource. - type: object - min: - additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: Min usage constraints on this kind by - resource name. - type: object - type: - description: Type of resource that this limit applies - to. + key: + description: key is the label key that the selector applies to. + type: string + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array required: - - type + - key + - operator type: object type: array - required: - - limits + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object type: object - type: array - type: object - namespaceOptions: - description: Specifies options for the Namespaces, such as additional - metadata or maximum number of namespaces allowed for that Tenant. - Once the namespace quota assigned to the Tenant has been reached, - the Tenant owner cannot create further namespaces. Optional. - properties: - additionalMetadata: - description: Specifies additional labels and annotations the Capsule - operator places on any Namespace resource in the Tenant. Optional. - properties: - annotations: - additionalProperties: - type: string - type: object - labels: - additionalProperties: - type: string - type: object - type: object - forbiddenAnnotations: - description: Define the annotations that a Tenant Owner cannot - set for their Namespace resources. - properties: - denied: - items: - type: string - type: array - deniedRegex: - type: string - type: object - forbiddenLabels: - description: Define the labels that a Tenant Owner cannot set - for their Namespace resources. - properties: - denied: - items: - type: string - type: array - deniedRegex: - type: string - type: object - quota: - description: Specifies the maximum number of namespaces allowed - for that Tenant. Once the namespace quota assigned to the Tenant - has been reached, the Tenant owner cannot create further namespaces. - Optional. - format: int32 - minimum: 1 - type: integer - required: - - forbiddenAnnotations - - forbiddenLabels - type: object - networkPolicies: - description: Specifies the NetworkPolicies assigned to the Tenant. - The assigned NetworkPolicies are inherited by any namespace created - in the Tenant. Optional. - properties: - items: - items: - description: NetworkPolicySpec provides the specification of - a NetworkPolicy + x-kubernetes-map-type: atomic + allowedHostnames: + description: Specifies the allowed hostnames in Ingresses for the given Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed hostnames. Optional. properties: - egress: - description: List of egress rules to be applied to the selected - pods. Outgoing traffic is allowed if there are no NetworkPolicies - selecting the pod (and cluster policy otherwise allows - the traffic), OR if the traffic matches at least one egress - rule across all of the NetworkPolicy objects whose podSelector - matches the pod. If this field is empty then this NetworkPolicy - limits all outgoing traffic (and serves solely to ensure - that the pods it selects are isolated by default). This - field is beta-level in 1.8 + allowed: items: - description: NetworkPolicyEgressRule describes a particular - set of traffic that is allowed out of pods matched by - a NetworkPolicySpec's podSelector. The traffic must - match both ports and to. This type is beta-level in - 1.8 - properties: - ports: - description: List of destination ports for outgoing - traffic. Each item in this list is combined using - a logical OR. If this field is empty or missing, - this rule matches all ports (traffic not restricted - by port). If this field is present and contains - at least one item, then this rule allows traffic - only if the traffic matches at least one port in - the list. - items: - description: NetworkPolicyPort describes a port - to allow traffic on - properties: - endPort: - description: If set, indicates that the range - of ports from port to endPort, inclusive, - should be allowed by the policy. This field - cannot be defined if the port field is not - defined or if the port field is defined as - a named (string) port. The endPort must be - equal or greater than port. This feature is - in Beta state and is enabled by default. It - can be disabled using the Feature Gate "NetworkPolicyEndPort". - format: int32 - type: integer - port: - anyOf: + type: string + type: array + allowedRegex: + type: string + type: object + hostnameCollisionScope: + default: Disabled + description: "Defines the scope of hostname collision check performed when Tenant Owners create Ingress with allowed hostnames. \n - Cluster: disallow the creation of an Ingress if the pair hostname and path is already used across the Namespaces managed by Capsule. \n - Tenant: disallow the creation of an Ingress if the pair hostname and path is already used across the Namespaces of the Tenant. \n - Namespace: disallow the creation of an Ingress if the pair hostname and path is already used in the Ingress Namespace. \n Optional." + enum: + - Cluster + - Tenant + - Namespace + - Disabled + type: string + required: + - allowWildcardHostnames + type: object + limitRanges: + description: Specifies the resource min/max usage restrictions to the Tenant. The assigned values are inherited by any namespace created in the Tenant. Optional. + properties: + items: + items: + description: LimitRangeSpec defines a min/max usage limit for resources that match on kind. + properties: + limits: + description: Limits is the list of LimitRangeItem objects that are enforced. + items: + description: LimitRangeItem defines a min/max usage limit for any resource that matches on kind. + properties: + default: + additionalProperties: + anyOf: - type: integer - type: string - description: The port on the given protocol. - This can either be a numerical or named port - on a pod. If this field is not provided, this - matches all port names and numbers. If present, - only traffic on the specified protocol AND - port will be matched. - x-kubernetes-int-or-string: true - protocol: - default: TCP - description: The protocol (TCP, UDP, or SCTP) - which traffic must match. If not specified, - this field defaults to TCP. - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Default resource requirement limit value by resource name if resource limit is omitted. type: object - type: array - to: - description: List of destinations for outgoing traffic - of pods selected for this rule. Items in this list - are combined using a logical OR operation. If this - field is empty or missing, this rule matches all - destinations (traffic not restricted by destination). - If this field is present and contains at least one - item, this rule allows traffic only if the traffic - matches at least one item in the to list. - items: - description: NetworkPolicyPeer describes a peer - to allow traffic to/from. Only certain combinations - of fields are allowed - properties: - ipBlock: - description: IPBlock defines policy on a particular - IPBlock. If this field is set then neither - of the other fields can be. - properties: - cidr: - description: CIDR is a string representing - the IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" - type: string - except: - description: Except is a slice of CIDRs - that should not be included within an - IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" Except values will - be rejected if they are outside the CIDR - range - items: + defaultRequest: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: DefaultRequest is the default resource requirement request value by resource name if resource request is omitted. + type: object + max: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Max usage constraints on this kind by resource name. + type: object + maxLimitRequestRatio: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: MaxLimitRequestRatio if specified, the named resource must have a request and limit that are both non-zero where limit divided by request is less than or equal to the enumerated value; this represents the max burst for the named resource. + type: object + min: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: Min usage constraints on this kind by resource name. + type: object + type: + description: Type of resource that this limit applies to. + type: string + required: + - type + type: object + type: array + required: + - limits + type: object + type: array + type: object + namespaceOptions: + description: Specifies options for the Namespaces, such as additional metadata or maximum number of namespaces allowed for that Tenant. Once the namespace quota assigned to the Tenant has been reached, the Tenant owner cannot create further namespaces. Optional. + properties: + additionalMetadata: + description: Specifies additional labels and annotations the Capsule operator places on any Namespace resource in the Tenant. Optional. + properties: + annotations: + additionalProperties: + type: string + type: object + labels: + additionalProperties: + type: string + type: object + type: object + forbiddenAnnotations: + description: Define the annotations that a Tenant Owner cannot set for their Namespace resources. + properties: + denied: + items: + type: string + type: array + deniedRegex: + type: string + type: object + forbiddenLabels: + description: Define the labels that a Tenant Owner cannot set for their Namespace resources. + properties: + denied: + items: + type: string + type: array + deniedRegex: + type: string + type: object + quota: + description: Specifies the maximum number of namespaces allowed for that Tenant. Once the namespace quota assigned to the Tenant has been reached, the Tenant owner cannot create further namespaces. Optional. + format: int32 + minimum: 1 + type: integer + required: + - forbiddenAnnotations + - forbiddenLabels + type: object + networkPolicies: + description: Specifies the NetworkPolicies assigned to the Tenant. The assigned NetworkPolicies are inherited by any namespace created in the Tenant. Optional. + properties: + items: + items: + description: NetworkPolicySpec provides the specification of a NetworkPolicy + properties: + egress: + description: List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 + items: + description: NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to. This type is beta-level in 1.8 + properties: + ports: + description: List of destination ports for outgoing traffic. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + items: + description: NetworkPolicyPort describes a port to allow traffic on + properties: + endPort: + description: If set, indicates that the range of ports from port to endPort, inclusive, should be allowed by the policy. This field cannot be defined if the port field is not defined or if the port field is defined as a named (string) port. The endPort must be equal or greater than port. This feature is in Beta state and is enabled by default. It can be disabled using the Feature Gate "NetworkPolicyEndPort". + format: int32 + type: integer + port: + anyOf: + - type: integer + - type: string + description: The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched. + x-kubernetes-int-or-string: true + protocol: + default: TCP + description: The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. + type: string + type: object + type: array + to: + description: List of destinations for outgoing traffic of pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all destinations (traffic not restricted by destination). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the to list. + items: + description: NetworkPolicyPeer describes a peer to allow traffic to/from. Only certain combinations of fields are allowed + properties: + ipBlock: + description: IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. + properties: + cidr: + description: CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" type: string - type: array - required: - - cidr - type: object - namespaceSelector: - description: "Selects Namespaces using cluster-scoped - labels. This field follows standard label - selector semantics; if present but empty, - it selects all namespaces. \n If PodSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects all Pods in the Namespaces - selected by NamespaceSelector." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + except: + description: Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" Except values will be rejected if they are outside the CIDR range + items: + type: string + type: array + required: + - cidr + type: object + namespaceSelector: + description: "Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. \n If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - podSelector: - description: "This is a label selector which - selects Pods. This field follows standard - label selector semantics; if present but empty, - it selects all pods. \n If NamespaceSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects the Pods matching PodSelector - in the policy's own Namespace." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + type: object + x-kubernetes-map-type: atomic + podSelector: + description: "This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. \n If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - type: array - type: object - type: array - ingress: - description: List of ingress rules to be applied to the - selected pods. Traffic is allowed to a pod if there are - no NetworkPolicies selecting the pod (and cluster policy - otherwise allows the traffic), OR if the traffic source - is the pod's local node, OR if the traffic matches at - least one ingress rule across all of the NetworkPolicy - objects whose podSelector matches the pod. If this field - is empty then this NetworkPolicy does not allow any traffic - (and serves solely to ensure that the pods it selects - are isolated by default) - items: - description: NetworkPolicyIngressRule describes a particular - set of traffic that is allowed to the pods matched by - a NetworkPolicySpec's podSelector. The traffic must - match both ports and from. - properties: - from: - description: List of sources which should be able - to access the pods selected for this rule. Items - in this list are combined using a logical OR operation. - If this field is empty or missing, this rule matches - all sources (traffic not restricted by source). - If this field is present and contains at least one - item, this rule allows traffic only if the traffic - matches at least one item in the from list. - items: - description: NetworkPolicyPeer describes a peer - to allow traffic to/from. Only certain combinations - of fields are allowed - properties: - ipBlock: - description: IPBlock defines policy on a particular - IPBlock. If this field is set then neither - of the other fields can be. - properties: - cidr: - description: CIDR is a string representing - the IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" - type: string - except: - description: Except is a slice of CIDRs - that should not be included within an - IP Block Valid examples are "192.168.1.1/24" - or "2001:db9::/64" Except values will - be rejected if they are outside the CIDR - range - items: + type: object + x-kubernetes-map-type: atomic + type: object + type: array + type: object + type: array + ingress: + description: List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) + items: + description: NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from. + properties: + from: + description: List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the from list. + items: + description: NetworkPolicyPeer describes a peer to allow traffic to/from. Only certain combinations of fields are allowed + properties: + ipBlock: + description: IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be. + properties: + cidr: + description: CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" type: string - type: array - required: - - cidr - type: object - namespaceSelector: - description: "Selects Namespaces using cluster-scoped - labels. This field follows standard label - selector semantics; if present but empty, - it selects all namespaces. \n If PodSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects all Pods in the Namespaces - selected by NamespaceSelector." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + except: + description: Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" or "2001:db9::/64" Except values will be rejected if they are outside the CIDR range + items: + type: string + type: array + required: + - cidr + type: object + namespaceSelector: + description: "Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces. \n If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - podSelector: - description: "This is a label selector which - selects Pods. This field follows standard - label selector semantics; if present but empty, - it selects all pods. \n If NamespaceSelector - is also set, then the NetworkPolicyPeer as - a whole selects the Pods matching PodSelector - in the Namespaces selected by NamespaceSelector. - Otherwise it selects the Pods matching PodSelector - in the policy's own Namespace." - properties: - matchExpressions: - description: matchExpressions is a list - of label selector requirements. The requirements - are ANDed. - items: - description: A label selector requirement - is a selector that contains values, - a key, and an operator that relates - the key and values. - properties: - key: - description: key is the label key - that the selector applies to. - type: string - operator: - description: operator represents a - key's relationship to a set of values. - Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array - is replaced during a strategic merge - patch. - items: + type: object + x-kubernetes-map-type: atomic + podSelector: + description: "This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods. \n If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace." + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} - pairs. A single {key,value} in the matchLabels - map is equivalent to an element of matchExpressions, - whose key field is "key", the operator - is "In", and the values array contains - only "value". The requirements are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - type: object - type: array - ports: - description: List of ports which should be made accessible - on the pods selected for this rule. Each item in - this list is combined using a logical OR. If this - field is empty or missing, this rule matches all - ports (traffic not restricted by port). If this - field is present and contains at least one item, - then this rule allows traffic only if the traffic - matches at least one port in the list. + type: object + x-kubernetes-map-type: atomic + type: object + type: array + ports: + description: List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + items: + description: NetworkPolicyPort describes a port to allow traffic on + properties: + endPort: + description: If set, indicates that the range of ports from port to endPort, inclusive, should be allowed by the policy. This field cannot be defined if the port field is not defined or if the port field is defined as a named (string) port. The endPort must be equal or greater than port. This feature is in Beta state and is enabled by default. It can be disabled using the Feature Gate "NetworkPolicyEndPort". + format: int32 + type: integer + port: + anyOf: + - type: integer + - type: string + description: The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched. + x-kubernetes-int-or-string: true + protocol: + default: TCP + description: The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP. + type: string + type: object + type: array + type: object + type: array + podSelector: + description: Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: - description: NetworkPolicyPort describes a port - to allow traffic on + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: - endPort: - description: If set, indicates that the range - of ports from port to endPort, inclusive, - should be allowed by the policy. This field - cannot be defined if the port field is not - defined or if the port field is defined as - a named (string) port. The endPort must be - equal or greater than port. This feature is - in Beta state and is enabled by default. It - can be disabled using the Feature Gate "NetworkPolicyEndPort". - format: int32 - type: integer - port: - anyOf: - - type: integer - - type: string - description: The port on the given protocol. - This can either be a numerical or named port - on a pod. If this field is not provided, this - matches all port names and numbers. If present, - only traffic on the specified protocol AND - port will be matched. - x-kubernetes-int-or-string: true - protocol: - default: TCP - description: The protocol (TCP, UDP, or SCTP) - which traffic must match. If not specified, - this field defaults to TCP. + key: + description: key is the label key that the selector applies to. + type: string + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator type: object type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object type: object - type: array - podSelector: - description: Selects the pods to which this NetworkPolicy - object applies. The array of ingress rules is applied - to any pods selected by this field. Multiple network policies - can select the same set of pods. In this case, the ingress - rules for each are combined additively. This field is - NOT optional and follows standard label selector semantics. - An empty podSelector matches all pods in this namespace. + x-kubernetes-map-type: atomic + policyTypes: + description: List of rule types that the NetworkPolicy relates to. Valid options are ["Ingress"], ["Egress"], or ["Ingress", "Egress"]. If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include "Egress" (since such a policy would not include an Egress section and would otherwise default to just [ "Ingress" ]). This field is beta-level in 1.8 + items: + description: PolicyType string describes the NetworkPolicy type This type is beta-level in 1.8 + type: string + type: array + required: + - podSelector + type: object + type: array + type: object + nodeSelector: + additionalProperties: + type: string + description: Specifies the label to control the placement of pods on a given pool of worker nodes. All namespaces created within the Tenant will have the node selector annotation. This annotation tells the Kubernetes scheduler to place pods on the nodes having the selector label. Optional. + type: object + owners: + description: Specifies the owners of the Tenant. Mandatory. + items: + properties: + clusterRoles: + default: + - admin + - capsule-namespace-deleter + description: Defines additional cluster-roles for the specific Owner. + items: + type: string + type: array + kind: + description: Kind of tenant owner. Possible values are "User", "Group", and "ServiceAccount" + enum: + - User + - Group + - ServiceAccount + type: string + name: + description: Name of tenant owner. + type: string + proxySettings: + description: Proxy settings for tenant owner. + items: properties: - matchExpressions: - description: matchExpressions is a list of label selector - requirements. The requirements are ANDed. + kind: + enum: + - Nodes + - StorageClasses + - IngressClasses + - PriorityClasses + type: string + operations: items: - description: A label selector requirement is a selector - that contains values, a key, and an operator that - relates the key and values. - properties: - key: - description: key is the label key that the selector - applies to. - type: string - operator: - description: operator represents a key's relationship - to a set of values. Valid operators are In, - NotIn, Exists and DoesNotExist. - type: string - values: - description: values is 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. - This array is replaced during a strategic merge - patch. - items: - type: string - type: array - required: - - key - - operator - type: object - type: array - matchLabels: - additionalProperties: + enum: + - List + - Update + - Delete type: string - description: matchLabels is a map of {key,value} pairs. - A single {key,value} in the matchLabels map is equivalent - to an element of matchExpressions, whose key field - is "key", the operator is "In", and the values array - contains only "value". The requirements are ANDed. - type: object + type: array + required: + - kind + - operations type: object - x-kubernetes-map-type: atomic - policyTypes: - description: List of rule types that the NetworkPolicy relates - to. Valid options are ["Ingress"], ["Egress"], or ["Ingress", - "Egress"]. If this field is not specified, it will default - based on the existence of Ingress or Egress rules; policies - that contain an Egress section are assumed to affect Egress, - and all policies (whether or not they contain an Ingress - section) are assumed to affect Ingress. If you want to - write an egress-only policy, you must explicitly specify - policyTypes [ "Egress" ]. Likewise, if you want to write - a policy that specifies that no egress is allowed, you - must specify a policyTypes value that include "Egress" - (since such a policy would not include an Egress section - and would otherwise default to just [ "Ingress" ]). This - field is beta-level in 1.8 - items: - description: PolicyType string describes the NetworkPolicy - type This type is beta-level in 1.8 - type: string - type: array - required: - - podSelector - type: object - type: array - type: object - nodeSelector: - additionalProperties: - type: string - description: Specifies the label to control the placement of pods - on a given pool of worker nodes. All namespaces created within the - Tenant will have the node selector annotation. This annotation tells - the Kubernetes scheduler to place pods on the nodes having the selector - label. Optional. - type: object - owners: - description: Specifies the owners of the Tenant. Mandatory. - items: + type: array + required: + - kind + - name + type: object + type: array + preventDeletion: + description: Prevent accidental deletion of the Tenant. When enabled, the deletion request will be declined. + type: boolean + priorityClasses: + description: Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. A default value can be specified, and all the Pod resources created will inherit the declared class. Optional. properties: - clusterRoles: - default: - - admin - - capsule-namespace-deleter - description: Defines additional cluster-roles for the specific - Owner. + allowed: items: type: string type: array - kind: - description: Kind of tenant owner. Possible values are "User", - "Group", and "ServiceAccount" - enum: - - User - - Group - - ServiceAccount + allowedRegex: type: string - name: - description: Name of tenant owner. + default: type: string - proxySettings: - description: Proxy settings for tenant owner. + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: - kind: - enum: - - Nodes - - StorageClasses - - IngressClasses - - PriorityClasses + key: + description: key is the label key that the selector applies to. + type: string + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. type: string - operations: + values: + description: values is 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. This array is replaced during a strategic merge patch. items: - enum: - - List - - Update - - Delete type: string type: array required: - - kind - - operations + - key + - operator type: object type: array - required: - - kind - - name + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object type: object - type: array - preventDeletion: - description: Prevent accidental deletion of the Tenant. When enabled, - the deletion request will be declined. - type: boolean - priorityClasses: - description: Specifies the allowed priorityClasses assigned to the - Tenant. Capsule assures that all Pods resources created in the Tenant - can use only one of the allowed PriorityClasses. Optional. - properties: - allowed: + x-kubernetes-map-type: atomic + resourceQuotas: + description: Specifies a list of ResourceQuota resources assigned to the Tenant. The assigned values are inherited by any namespace created in the Tenant. The Capsule operator aggregates ResourceQuota at Tenant level, so that the hard quota is never crossed for the given Tenant. This permits the Tenant owner to consume resources in the Tenant regardless of the namespace. Optional. + properties: items: + items: + description: ResourceQuotaSpec defines the desired hard limits to enforce for Quota. + properties: + hard: + additionalProperties: + anyOf: + - type: integer + - type: string + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + description: 'hard is the set of desired hard limits for each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/' + type: object + scopeSelector: + description: scopeSelector is also a collection of filters like scopes that must match each object tracked by a quota but expressed using ScopeSelectorOperator in combination with possible values. For a resource to match, both scopes AND scopeSelector (if specified in spec), must be matched. + properties: + matchExpressions: + description: A list of scope selector requirements by scope of the resources. + items: + description: A scoped-resource selector requirement is a selector that contains values, a scope name, and an operator that relates the scope name and values. + properties: + operator: + description: Represents a scope's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. + type: string + scopeName: + description: The name of the scope that the selector applies to. + 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - operator + - scopeName + type: object + type: array + type: object + x-kubernetes-map-type: atomic + scopes: + description: A collection of filters that must match each object tracked by a quota. If not specified, the quota matches all objects. + items: + description: A ResourceQuotaScope defines a filter that must match each object tracked by a quota + type: string + type: array + type: object + type: array + scope: + default: Tenant + description: Define if the Resource Budget should compute resource across all Namespaces in the Tenant or individually per cluster. Default is Tenant + enum: + - Tenant + - Namespace type: string - type: array - allowedRegex: - type: string - matchExpressions: - description: matchExpressions is a list of label selector requirements. - The requirements are ANDed. - items: - description: A label selector requirement is a selector that - contains values, a key, and an operator that relates the key - and values. - properties: - key: - description: key is the label key that the selector applies - to. - type: string - operator: - description: operator represents a key's relationship to - a set of values. Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array is replaced during a strategic - merge patch. - items: + type: object + runtimeClasses: + description: Specifies the allowed RuntimeClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed RuntimeClasses. Optional. + properties: + allowed: + items: + type: string + type: array + allowedRegex: + type: string + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} pairs. A single - {key,value} in the matchLabels map is equivalent to an element - of matchExpressions, whose key field is "key", the operator - is "In", and the values array contains only "value". The requirements - are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - resourceQuotas: - description: Specifies a list of ResourceQuota resources assigned - to the Tenant. The assigned values are inherited by any namespace - created in the Tenant. The Capsule operator aggregates ResourceQuota - at Tenant level, so that the hard quota is never crossed for the - given Tenant. This permits the Tenant owner to consume resources - in the Tenant regardless of the namespace. Optional. - properties: - items: - items: - description: ResourceQuotaSpec defines the desired hard limits - to enforce for Quota. + type: object + x-kubernetes-map-type: atomic + serviceOptions: + description: Specifies options for the Service, such as additional metadata or block of certain type of Services. Optional. + properties: + additionalMetadata: + description: Specifies additional labels and annotations the Capsule operator places on any Service resource in the Tenant. Optional. properties: - hard: + annotations: additionalProperties: - anyOf: - - type: integer - - type: string - pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ - x-kubernetes-int-or-string: true - description: 'hard is the set of desired hard limits for - each named resource. More info: https://kubernetes.io/docs/concepts/policy/resource-quotas/' - type: object - scopeSelector: - description: scopeSelector is also a collection of filters - like scopes that must match each object tracked by a quota - but expressed using ScopeSelectorOperator in combination - with possible values. For a resource to match, both scopes - AND scopeSelector (if specified in spec), must be matched. - properties: - matchExpressions: - description: A list of scope selector requirements by - scope of the resources. - items: - description: A scoped-resource selector requirement - is a selector that contains values, a scope name, - and an operator that relates the scope name and - values. - properties: - operator: - description: Represents a scope's relationship - to a set of values. Valid operators are In, - NotIn, Exists, DoesNotExist. - type: string - scopeName: - description: The name of the scope that the selector - applies to. - 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. This array is - replaced during a strategic merge patch. - items: - type: string - type: array - required: - - operator - - scopeName - type: object - type: array + type: string type: object - x-kubernetes-map-type: atomic - scopes: - description: A collection of filters that must match each - object tracked by a quota. If not specified, the quota - matches all objects. - items: - description: A ResourceQuotaScope defines a filter that - must match each object tracked by a quota + labels: + additionalProperties: type: string - type: array + type: object type: object - type: array - scope: - default: Tenant - description: Define if the Resource Budget should compute resource - across all Namespaces in the Tenant or individually per cluster. - Default is Tenant - enum: - - Tenant - - Namespace - type: string - type: object - runtimeClasses: - description: Specifies the allowed RuntimeClasses assigned to the - Tenant. Capsule assures that all Pods resources created in the Tenant - can use only one of the allowed RuntimeClasses. Optional. - properties: - allowed: - items: - type: string - type: array - allowedRegex: - type: string - matchExpressions: - description: matchExpressions is a list of label selector requirements. - The requirements are ANDed. - items: - description: A label selector requirement is a selector that - contains values, a key, and an operator that relates the key - and values. + allowedServices: + description: Block or deny certain type of Services. Optional. properties: - key: - description: key is the label key that the selector applies - to. - type: string - operator: - description: operator represents a key's relationship to - a set of values. Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array is replaced during a strategic - merge patch. + externalName: + default: true + description: Specifies if ExternalName service type resources are allowed for the Tenant. Default is true. Optional. + type: boolean + loadBalancer: + default: true + description: Specifies if LoadBalancer service type resources are allowed for the Tenant. Default is true. Optional. + type: boolean + nodePort: + default: true + description: Specifies if NodePort service type resources are allowed for the Tenant. Default is true. Optional. + type: boolean + type: object + externalIPs: + description: Specifies the external IPs that can be used in Services with type ClusterIP. An empty list means no IPs are allowed. Optional. + properties: + allowed: items: + pattern: ^([0-9]{1,3}.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ type: string type: array required: - - key - - operator + - allowed type: object - type: array - matchLabels: - additionalProperties: + type: object + storageClasses: + description: Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. A default value can be specified, and all the PersistentVolumeClaim resources created will inherit the declared class. Optional. + properties: + allowed: + items: + type: string + type: array + allowedRegex: type: string - description: matchLabels is a map of {key,value} pairs. A single - {key,value} in the matchLabels map is equivalent to an element - of matchExpressions, whose key field is "key", the operator - is "In", and the values array contains only "value". The requirements - are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - serviceOptions: - description: Specifies options for the Service, such as additional - metadata or block of certain type of Services. Optional. - properties: - additionalMetadata: - description: Specifies additional labels and annotations the Capsule - operator places on any Service resource in the Tenant. Optional. - properties: - annotations: - additionalProperties: - type: string - type: object - labels: - additionalProperties: - type: string - type: object - type: object - allowedServices: - description: Block or deny certain type of Services. Optional. - properties: - externalName: - default: true - description: Specifies if ExternalName service type resources - are allowed for the Tenant. Default is true. Optional. - type: boolean - loadBalancer: - default: true - description: Specifies if LoadBalancer service type resources - are allowed for the Tenant. Default is true. Optional. - type: boolean - nodePort: - default: true - description: Specifies if NodePort service type resources - are allowed for the Tenant. Default is true. Optional. - type: boolean - type: object - externalIPs: - description: Specifies the external IPs that can be used in Services - with type ClusterIP. An empty list means no IPs are allowed. - Optional. - properties: - allowed: - items: - pattern: ^([0-9]{1,3}.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ - type: string - type: array - required: - - allowed - type: object - type: object - storageClasses: - description: Specifies the allowed StorageClasses assigned to the - Tenant. Capsule assures that all PersistentVolumeClaim resources - created in the Tenant can use only one of the allowed StorageClasses. - Optional. - properties: - allowed: - items: + default: type: string - type: array - allowedRegex: - type: string - matchExpressions: - description: matchExpressions is a list of label selector requirements. - The requirements are ANDed. - items: - description: A label selector requirement is a selector that - contains values, a key, and an operator that relates the key - and values. - properties: - key: - description: key is the label key that the selector applies - to. - type: string - operator: - description: operator represents a key's relationship to - a set of values. Valid operators are In, NotIn, Exists - and DoesNotExist. - type: string - values: - description: values is 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. This array is replaced during a strategic - merge patch. - items: + matchExpressions: + description: matchExpressions is a list of label selector requirements. The requirements are ANDed. + items: + description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + properties: + key: + description: key is the label key that the selector applies to. type: string - type: array - required: - - key - - operator + operator: + description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: values is 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. This array is replaced during a strategic merge patch. + items: + type: string + type: array + required: + - key + - operator + type: object + type: array + matchLabels: + additionalProperties: + type: string + description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. type: object - type: array - matchLabels: - additionalProperties: - type: string - description: matchLabels is a map of {key,value} pairs. A single - {key,value} in the matchLabels map is equivalent to an element - of matchExpressions, whose key field is "key", the operator - is "In", and the values array contains only "value". The requirements - are ANDed. - type: object - type: object - x-kubernetes-map-type: atomic - required: - - owners - type: object - status: - description: Returns the observed state of the Tenant. - properties: - namespaces: - description: List of namespaces assigned to the Tenant. - items: + type: object + x-kubernetes-map-type: atomic + required: + - owners + type: object + status: + description: Returns the observed state of the Tenant. + properties: + namespaces: + description: List of namespaces assigned to the Tenant. + items: + type: string + type: array + size: + description: How many namespaces are assigned to the Tenant. + type: integer + state: + default: Active + description: The operational state of the Tenant. Possible values are "Active", "Cordoned". + enum: + - Cordoned + - Active type: string - type: array - size: - description: How many namespaces are assigned to the Tenant. - type: integer - state: - default: Active - description: The operational state of the Tenant. Possible values - are "Active", "Cordoned". - enum: - - Cordoned - - Active - type: string - required: - - size - - state - type: object - type: object - served: true - storage: true - subresources: - status: {} + required: + - size + - state + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/charts/capsule/templates/mutatingwebhookconfiguration.yaml b/charts/capsule/templates/mutatingwebhookconfiguration.yaml index 9997e702..0d396ee8 100644 --- a/charts/capsule/templates/mutatingwebhookconfiguration.yaml +++ b/charts/capsule/templates/mutatingwebhookconfiguration.yaml @@ -12,6 +12,86 @@ metadata: {{- toYaml . | nindent 4 }} {{- end }} webhooks: +{{- with .Values.webhooks.defaults.pods }} +- admissionReviewVersions: + - v1 + clientConfig: + {{- if not $.Values.certManager.generateCertificates }} + caBundle: Cg== + {{- end }} + service: + name: {{ include "capsule.fullname" $ }}-webhook-service + namespace: {{ $.Release.Namespace }} + path: /defaults + failurePolicy: {{ .failurePolicy }} + name: pod.defaults.capsule.clastix.io + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - CREATE + resources: + - pods + namespaceSelector: + {{- toYaml .namespaceSelector | nindent 4}} + sideEffects: None +{{- end }} +{{- with .Values.webhooks.defaults.pvc }} +- admissionReviewVersions: + - v1 + clientConfig: + {{- if not $.Values.certManager.generateCertificates }} + caBundle: Cg== + {{- end }} + service: + name: {{ include "capsule.fullname" $ }}-webhook-service + namespace: {{ $.Release.Namespace }} + path: /defaults + failurePolicy: {{ .failurePolicy }} + name: storage.defaults.capsule.clastix.io + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - CREATE + resources: + - persistentvolumeclaims + namespaceSelector: + {{- toYaml .namespaceSelector | nindent 4}} + sideEffects: None +{{- end }} +{{- with .Values.webhooks.defaults.ingress }} +- admissionReviewVersions: + - v1 + clientConfig: + {{- if not $.Values.certManager.generateCertificates }} + caBundle: Cg== + {{- end }} + service: + name: {{ include "capsule.fullname" $ }}-webhook-service + namespace: {{ $.Release.Namespace }} + path: /defaults + failurePolicy: {{ .failurePolicy }} + name: ingress.defaults.capsule.clastix.io + rules: + - apiGroups: + - networking.k8s.io + apiVersions: + - v1beta1 + - v1 + operations: + - CREATE + - UPDATE + resources: + - ingresses + namespaceSelector: + {{- toYaml .namespaceSelector | nindent 4}} + sideEffects: None +{{- end }} - admissionReviewVersions: - v1 - v1beta1 diff --git a/charts/capsule/templates/validatingwebhookconfiguration.yaml b/charts/capsule/templates/validatingwebhookconfiguration.yaml index c20b22a7..80b80c03 100644 --- a/charts/capsule/templates/validatingwebhookconfiguration.yaml +++ b/charts/capsule/templates/validatingwebhookconfiguration.yaml @@ -145,6 +145,34 @@ webhooks: clientConfig: {{- if not .Values.certManager.generateCertificates }} caBundle: Cg== +{{- end }} + service: + name: {{ include "capsule.fullname" . }}-webhook-service + namespace: {{ .Release.Namespace }} + path: /nodes + port: 443 + failurePolicy: {{ .Values.webhooks.nodes.failurePolicy }} + name: nodes.capsule.clastix.io + matchPolicy: Exact + namespaceSelector: {} + objectSelector: {} + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - UPDATE + resources: + - nodes + sideEffects: None + timeoutSeconds: {{ .Values.validatingWebhooksTimeoutSeconds }} +- admissionReviewVersions: + - v1 + - v1beta1 + clientConfig: +{{- if not .Values.certManager.generateCertificates }} + caBundle: Cg== {{- end }} service: name: {{ include "capsule.fullname" . }}-webhook-service @@ -260,31 +288,3 @@ webhooks: scope: '*' sideEffects: None timeoutSeconds: {{ .Values.validatingWebhooksTimeoutSeconds }} -- admissionReviewVersions: - - v1 - - v1beta1 - clientConfig: -{{- if not .Values.certManager.generateCertificates }} - caBundle: Cg== -{{- end }} - service: - name: {{ include "capsule.fullname" . }}-webhook-service - namespace: {{ .Release.Namespace }} - path: /nodes - port: 443 - failurePolicy: {{ .Values.webhooks.nodes.failurePolicy }} - name: nodes.capsule.clastix.io - matchPolicy: Exact - namespaceSelector: {} - objectSelector: {} - rules: - - apiGroups: - - "" - apiVersions: - - v1 - operations: - - UPDATE - resources: - - nodes - sideEffects: None - timeoutSeconds: {{ .Values.validatingWebhooksTimeoutSeconds }} diff --git a/charts/capsule/values.yaml b/charts/capsule/values.yaml index 8885801a..b3e89642 100644 --- a/charts/capsule/values.yaml +++ b/charts/capsule/values.yaml @@ -172,6 +172,26 @@ webhooks: operator: Exists nodes: failurePolicy: Fail + defaults: + ingress: + failurePolicy: Fail + namespaceSelector: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists + pvc: + failurePolicy: Fail + namespaceSelector: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists + pods: + failurePolicy: Fail + namespaceSelector: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists + # -- Timeout in seconds for mutating webhooks mutatingWebhooksTimeoutSeconds: 30 diff --git a/config/crd/bases/capsule.clastix.io_tenants.yaml b/config/crd/bases/capsule.clastix.io_tenants.yaml index f783ba48..8f3f4bd0 100644 --- a/config/crd/bases/capsule.clastix.io_tenants.yaml +++ b/config/crd/bases/capsule.clastix.io_tenants.yaml @@ -2048,7 +2048,8 @@ spec: description: Specifies the allowed IngressClasses assigned to the Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. - Optional. + A default value can be specified, and all the Ingress resources + created will inherit the declared class. Optional. properties: allowed: items: @@ -2056,6 +2057,8 @@ spec: type: array allowedRegex: type: string + default: + type: string matchExpressions: description: matchExpressions is a list of label selector requirements. The requirements are ANDed. @@ -2868,7 +2871,9 @@ spec: priorityClasses: description: Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant - can use only one of the allowed PriorityClasses. Optional. + can use only one of the allowed PriorityClasses. A default value + can be specified, and all the Pod resources created will inherit + the declared class. Optional. properties: allowed: items: @@ -2876,6 +2881,8 @@ spec: type: array allowedRegex: type: string + default: + type: string matchExpressions: description: matchExpressions is a list of label selector requirements. The requirements are ANDed. @@ -3110,7 +3117,8 @@ spec: description: Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. - Optional. + A default value can be specified, and all the PersistentVolumeClaim + resources created will inherit the declared class. Optional. properties: allowed: items: @@ -3118,6 +3126,8 @@ spec: type: array allowedRegex: type: string + default: + type: string matchExpressions: description: matchExpressions is a list of label selector requirements. The requirements are ANDed. diff --git a/config/install.yaml b/config/install.yaml index 8d4dcedd..00e83c9d 100644 --- a/config/install.yaml +++ b/config/install.yaml @@ -1940,7 +1940,7 @@ spec: description: Toggles the ability for Ingress resources created in a Tenant to have a hostname wildcard. type: boolean allowedClasses: - description: Specifies the allowed IngressClasses assigned to the Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. Optional. + description: Specifies the allowed IngressClasses assigned to the Tenant. Capsule assures that all Ingress resources created in the Tenant can use only one of the allowed IngressClasses. A default value can be specified, and all the Ingress resources created will inherit the declared class. Optional. properties: allowed: items: @@ -1948,6 +1948,8 @@ spec: type: array allowedRegex: type: string + default: + type: string matchExpressions: description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: @@ -2442,7 +2444,7 @@ spec: description: Prevent accidental deletion of the Tenant. When enabled, the deletion request will be declined. type: boolean priorityClasses: - description: Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. Optional. + description: Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. A default value can be specified, and all the Pod resources created will inherit the declared class. Optional. properties: allowed: items: @@ -2450,6 +2452,8 @@ spec: type: array allowedRegex: type: string + default: + type: string matchExpressions: description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: @@ -2617,7 +2621,7 @@ spec: type: object type: object storageClasses: - description: Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. Optional. + description: Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. A default value can be specified, and all the PersistentVolumeClaim resources created will inherit the declared class. Optional. properties: allowed: items: @@ -2625,6 +2629,8 @@ spec: type: array allowedRegex: type: string + default: + type: string matchExpressions: description: matchExpressions is a list of label selector requirements. The requirements are ANDed. items: @@ -2812,6 +2818,80 @@ metadata: creationTimestamp: null name: capsule-mutating-webhook-configuration webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: capsule-webhook-service + namespace: capsule-system + path: /defaults + failurePolicy: Fail + name: pod.defaults.capsule.clastix.io + namespaceSelector: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - CREATE + resources: + - pods + scope: Namespaced + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: capsule-webhook-service + namespace: capsule-system + path: /defaults + failurePolicy: Fail + name: storage.defaults.capsule.clastix.io + namespaceSelector: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - CREATE + resources: + - persistentvolumeclaims + scope: Namespaced + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: capsule-webhook-service + namespace: capsule-system + path: /defaults + failurePolicy: Fail + name: ingress.defaults.capsule.clastix.io + namespaceSelector: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists + rules: + - apiGroups: + - networking.k8s.io + apiVersions: + - v1beta1 + - v1 + operations: + - CREATE + - UPDATE + resources: + - ingresses + scope: Namespaced + sideEffects: None - admissionReviewVersions: - v1 clientConfig: diff --git a/config/webhook/kustomization.yaml b/config/webhook/kustomization.yaml index 8b7eb535..8ff7dd79 100644 --- a/config/webhook/kustomization.yaml +++ b/config/webhook/kustomization.yaml @@ -8,7 +8,14 @@ patchesJson6902: kind: ValidatingWebhookConfiguration name: validating-webhook-configuration version: v1 - path: patch_ns_selector.yaml + path: patch_validating_ns_selector.yaml +- target: + group: admissionregistration.k8s.io + kind: MutatingWebhookConfiguration + name: mutating-webhook-configuration + version: v1 + path: patch_mutating_ns_selector.yaml + configurations: - kustomizeconfig.yaml diff --git a/config/webhook/manifests.yaml b/config/webhook/manifests.yaml index db05648a..f82891d2 100644 --- a/config/webhook/manifests.yaml +++ b/config/webhook/manifests.yaml @@ -5,6 +5,65 @@ metadata: creationTimestamp: null name: mutating-webhook-configuration webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /defaults + failurePolicy: Fail + name: pod.defaults.capsule.clastix.io + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - CREATE + resources: + - pods + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /defaults + failurePolicy: Fail + name: storage.defaults.capsule.clastix.io + rules: + - apiGroups: + - "" + apiVersions: + - v1 + operations: + - CREATE + resources: + - persistentvolumeclaims + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /defaults + failurePolicy: Fail + name: ingress.defaults.capsule.clastix.io + rules: + - apiGroups: + - networking.k8s.io + apiVersions: + - v1beta1 + - v1 + operations: + - CREATE + - UPDATE + resources: + - ingresses + sideEffects: None - admissionReviewVersions: - v1 clientConfig: diff --git a/config/webhook/patch_mutating_ns_selector.yaml b/config/webhook/patch_mutating_ns_selector.yaml new file mode 100644 index 00000000..790b06e1 --- /dev/null +++ b/config/webhook/patch_mutating_ns_selector.yaml @@ -0,0 +1,27 @@ +- op: add + path: /webhooks/0/namespaceSelector + value: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists +- op: add + path: /webhooks/1/namespaceSelector + value: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists +- op: add + path: /webhooks/2/namespaceSelector + value: + matchExpressions: + - key: capsule.clastix.io/tenant + operator: Exists +- op: add + path: /webhooks/0/rules/0/scope + value: Namespaced +- op: add + path: /webhooks/1/rules/0/scope + value: Namespaced +- op: add + path: /webhooks/2/rules/0/scope + value: Namespaced diff --git a/config/webhook/patch_ns_selector.yaml b/config/webhook/patch_validating_ns_selector.yaml similarity index 100% rename from config/webhook/patch_ns_selector.yaml rename to config/webhook/patch_validating_ns_selector.yaml diff --git a/docs/content/general/crds-apis.md b/docs/content/general/crds-apis.md index 999b41f2..73cb38e8 100644 --- a/docs/content/general/crds-apis.md +++ b/docs/content/general/crds-apis.md @@ -2974,7 +2974,7 @@ TenantSpec defines the desired state of Tenant.
false | +|||||||||||||||
default | +string | +
+ + |
+ false | ||||||||||||
matchExpressions | []object | @@ -4394,7 +4401,7 @@ NetworkPolicyPort describes a port to allow traffic on -Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. Optional. +Specifies the allowed priorityClasses assigned to the Tenant. Capsule assures that all Pods resources created in the Tenant can use only one of the allowed PriorityClasses. A default value can be specified, and all the Pod resources created will inherit the declared class. Optional.
false | +||||||||
default | +string | +
+ + |
+ false | |||||
matchExpressions | []object | @@ -4855,7 +4869,7 @@ Specifies the external IPs that can be used in Services with type ClusterIP. An -Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. Optional. +Specifies the allowed StorageClasses assigned to the Tenant. Capsule assures that all PersistentVolumeClaim resources created in the Tenant can use only one of the allowed StorageClasses. A default value can be specified, and all the PersistentVolumeClaim resources created will inherit the declared class. Optional.
false | +|||
default | +string | +
+ + |
+ false |
matchExpressions | []object | diff --git a/docs/content/general/tutorial.md b/docs/content/general/tutorial.md index 08d28d0a..7132252a 100644 --- a/docs/content/general/tutorial.md +++ b/docs/content/general/tutorial.md @@ -819,7 +819,7 @@ To prevent misuses of Pod Priority Class, Bill, the cluster admin, can enforce t ```yaml kubectl apply -f - << EOF -apiVersion: capsule.clastix.io/v1beta1 +apiVersion: capsule.clastix.io/v1beta2 kind: Tenant metadata: name: oil @@ -829,22 +829,73 @@ spec: kind: User priorityClasses: allowed: - - default + - custom allowedRegex: "^tier-.*$" + selector: + matchLabels: + env: "production" EOF ``` With the said Tenant specification, Alice can create a Pod resource if `spec.priorityClassName` equals to: -- `default` +- `custom` - `tier-gold`, `tier-silver`, or `tier-bronze`, since these compile the allowed regex. +- Any PriorityClass which has the label `env` with the value `production` If a Pod is going to use a non-allowed _Priority Class_, it will be rejected by the Validation Webhook enforcing it. +### Assign Pod Priority Class as tenant default + +It's possible to assign each tenant a PriorityClass which will be used, if no PriorityClass is set on pod basis: + +```yaml +kubectl apply -f - << EOF +apiVersion: capsule.clastix.io/v1beta2 +kind: Tenant +metadata: + name: oil +spec: + owners: + - name: alice + kind: User + priorityClasses: + allowed: + - custom + default: "tenant-default" + allowedRegex: "^tier-.*$" + selector: + matchLabels: + env: "production" +EOF +``` + +Here's how the new PriorityClass could look like + +```yaml +kubectl apply -f - << EOF +apiVersion: scheduling.k8s.io/v1 +kind: PriorityClass +metadata: + name: tenant-default +value: 1313 +preemptionPolicy: Never +globalDefault: false +description: "This is the default PriorityClass for the oil-tenant" +EOF +``` + +If a Pod has no value for `spec.priorityClassName`, the default value for PriorityClass (`tenant-default`) will be used. + +> This feature allows specifying a custom default value on a Tenant basis, bypassing the global cluster default (`globalDefault=true`) that acts only at the cluster level. + +**Note**: This feature supports type `PriorityClass` only on API version `scheduling.k8s.io/v1` + ## Assign Pod Runtime Classes -Pods can be assigned different runtime classes. With the assigned runtime you can control Container Runtime Interface (CRI) is used for each pod. See [Kubernetes documentation](https://kubernetes.io/docs/concepts/containers/runtime-class/). +Pods can be assigned different runtime classes. With the assigned runtime you can control Container Runtime Interface (CRI) is used for each pod. +See [Kubernetes documentation](https://kubernetes.io/docs/concepts/containers/runtime-class/) for more information. To prevent misuses of Pod Runtime Classes, Bill, the cluster admin, can enforce the allowed Pod Runtime Class at tenant level: @@ -868,15 +919,14 @@ spec: EOF ``` -With the said Tenant specification, Alice can create a Pod resource if `spec.RuntimeClasses` equals to: +With the said Tenant specification, Alice can create a Pod resource if `spec.runtimeClassName` equals to: - `legacy` -- `hardened-crio` or `hardened-containerd`, since these compile the allowed regex. -- Any RuntimeClass which has the label `env` with the value `production` +- e.g.: `hardened-crio` or `hardened-containerd`, since these compile the allowed regex (`^hardened-.*$"`). +- any RuntimeClass which has the label `env` with the value `production` If a Pod is going to use a non-allowed _Runtime Class_, it will be rejected by the Validation Webhook enforcing it. - ## Assign Nodes Pool Bill, the cluster admin, can dedicate a pool of worker nodes to the `oil` tenant, to isolate the tenant applications from other noisy neighbors. @@ -946,7 +996,7 @@ Bill can assign a set of dedicated Ingress Classes to the `oil` tenant to force ```yaml kubectl apply -f - << EOF -apiVersion: capsule.clastix.io/v1beta1 +apiVersion: capsule.clastix.io/v1beta2 kind: Tenant metadata: name: oil @@ -957,12 +1007,21 @@ spec: ingressOptions: allowedClasses: allowed: - - default + - legacy allowedRegex: ^\w+-lb$ + selector: + matchLabels: + env: "production" EOF ``` -Capsule assures that all Ingresses created in the tenant can use only one of the valid Ingress Classes. +With the said Tenant specification, Alice can create a Ingress resource if `spec.ingressClassName` or `metadata.annotations."kubernetes.io/ingress.class"` equals to: + +- `legacy` +- eg. `haproxy-lb` or `nginx-lb`, since these compile the allowed regex (`^\w+-lb$`). +- Any IngressClass which has the label `env` with the value `production` + +If an Ingress is going to use a non-allowed _IngressClass_, it will be rejected by the Validation Webhook enforcing it. Alice can create an Ingress using only an allowed Ingress Class: @@ -974,7 +1033,7 @@ metadata: name: nginx namespace: oil-production annotations: - kubernetes.io/ingress.class: default + kubernetes.io/ingress.class: legacy spec: rules: - host: oil.acmecorp.com @@ -989,6 +1048,58 @@ EOF Any attempt of Alice to use a non-valid Ingress Class, or missing it, is denied by the Validation Webhook enforcing it. +### Assign Ingress Class as tenant default + +It's possible to assign each tenant an Ingress Class which will be used, if a class is not set on ingress basis: + +```yaml +kubectl apply -f - << EOF +apiVersion: capsule.clastix.io/v1beta2 +kind: Tenant +metadata: + name: oil +spec: + owners: + - name: alice + kind: User + ingressOptions: + allowedClasses: + allowed: + - legacy + default: "tenant-default" + allowedRegex: ^\w+-lb$ + selector: + matchLabels: + env: "production" +EOF +``` + +Here's how the Tenant default IngressClass could look like: + +```yaml +kubectl apply -f - << EOF +apiVersion: networking.k8s.io/v1 +kind: IngressClass +metadata: + labels: + app.kubernetes.io/component: controller + name: tenant-default + annotations: + ingressclass.kubernetes.io/is-default-class: "false" +spec: + controller: k8s.io/customer-nginx +EOF +``` + +If an Ingress has no value for `spec.ingressClassName` or `metadata.annotations."kubernetes.io/ingress.class"`, the `tenant-default` IngressClass is automatically applied to the Ingress resource. + +> This feature allows specifying a custom default value on a Tenant basis, bypassing the global cluster default (with the annotation `metadata.annotations.ingressclass.kubernetes.io/is-default-class=true`) that acts only at the cluster level. +> +> More information: [Default IngressClass](https://kubernetes.io/docs/concepts/services-networking/ingress/#default-ingress-class) + +**Note**: This feature is offered only by API type `IngressClass` in group `networking.k8s.io` version `v1`. +However, resource `Ingress` is supported in `networking.k8s.io/v1` and `networking.k8s.io/v1beta1` + ## Assign Ingress Hostnames Bill can control ingress hostnames in the `oil` tenant to force the applications to be published only using the given hostname or set of hostnames: @@ -1124,7 +1235,7 @@ Persistent storage infrastructure is provided to tenants. Different types of sto ```yaml kubectl apply -f - << EOF -apiVersion: capsule.clastix.io/v1beta1 +apiVersion: capsule.clastix.io/v1beta2 kind: Tenant metadata: name: oil @@ -1137,9 +1248,18 @@ spec: - ceph-rbd - ceph-nfs allowedRegex: "^ceph-.*$" + selector: + matchLabels: + env: "production" EOF ``` +With the said Tenant specification, Alice can create a Persistent Volume Claims if `spec.storageClassName` equals to: + +- `ceph-rbd` or `ceph-nfs` +- eg. `ceph-hdd` or `ceph-ssd`, since these compile the allowed regex (`^ceph-.*$`). +- Any IngressClass which has the label `env` with the value `production` + Capsule assures that all Persistent Volume Claims created by Alice will use only one of the valid storage classes: ```yaml @@ -1159,7 +1279,56 @@ spec: EOF ``` -Any attempt of Alice to use a non-valid Storage Class, or missing it, is denied by the Validation Webhook enforcing it. +If a Persistent Volume Claim is going to use a non-allowed _Storage Class_, it will be rejected by the Validation Webhook enforcing it. + +### Assign Storage Class as tenant default + +It's possible to assign each tenant a StorageClass which will be used, if no value is set on Persistent Volume Claim basis: + +```yaml +kubectl apply -f - << EOF +apiVersion: capsule.clastix.io/v1beta2 +kind: Tenant +metadata: + name: oil +spec: + owners: + - name: alice + kind: User + storageClasses: + default: "tenant-default" + allowed: + - ceph-rbd + - ceph-nfs + allowedRegex: "^ceph-.*$" + selector: + matchLabels: + env: "production" +EOF +``` + +Here's how the new Storage Class could look like + +```yaml +kubectl apply -f - << EOF +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: tenant-default + annotations: + storageclass.kubernetes.io/is-default-class: "false" +provisioner: kubernetes.io/no-provisioner +volumeBindingMode: WaitForFirstConsumer +EOF +``` + +If a Persistent Volume Claim has no value for `spec.storageClassName` the `tenant-default` value will be used on new Persistent Volume Claim resources. + +> This feature allows specifying a custom default value on a Tenant basis, bypassing the global cluster default (`.metadata.annotations.storageclass.kubernetes.io/is-default-class=true`) that acts only at the cluster level. +> +> See the [Default Storage Class](https://kubernetes.io/docs/tasks/administer-cluster/change-default-storage-class/) section on Kubernetes documentation. + +**Note**: This feature supports type `StorageClass` only on API version `storage.k8s.io/v1` ## Assign Network Policies Kubernetes network policies control network traffic between namespaces and between pods in the same namespace. Bill, the cluster admin, can enforce network traffic isolation between different tenants while leaving to Alice, the tenant owner, the freedom to set isolation between namespaces in the same tenant or even between pods in the same namespace. diff --git a/e2e/container_registry_test.go b/e2e/container_registry_test.go index 1573f1f8..4a1a3bfb 100644 --- a/e2e/container_registry_test.go +++ b/e2e/container_registry_test.go @@ -7,6 +7,7 @@ package e2e import ( "context" + "encoding/json" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -18,6 +19,12 @@ import ( "github.com/clastix/capsule/pkg/api" ) +type Patch struct { + Op string `json:"op"` + Path string `json:"path"` + Value string `json:"value"` +} + var _ = Describe("enforcing a Container Registry", func() { tnt := &capsulev1beta2.Tenant{ ObjectMeta: metav1.ObjectMeta{ @@ -112,8 +119,7 @@ var _ = Describe("enforcing a Container Registry", func() { }) It("should deny patching a not matching registry after applying with a matching (Container)", func() { - ns := NewNamespace("reg-deny-container-patch") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + ns := NewNamespace("") pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -130,23 +136,33 @@ var _ = Describe("enforcing a Container Registry", func() { } cs := ownerClient(tnt.Spec.Owners[0]) + + NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.Name).Create(context.Background(), pod, metav1.CreateOptions{}) return err }).Should(Succeed()) - Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: pod.GetName(), Namespace: ns.GetName()}, pod)).ToNot(HaveOccurred()) - - pod.Spec.Containers[0].Image = "attacker/google-containers/pause-amd64:3.0" - Expect(k8sClient.Update(context.Background(), pod)).To(HaveOccurred()) - - Expect(k8sClient.Delete(context.TODO(), ns)).Should(Succeed()) + Eventually(func() error { + payload := []Patch{{ + Op: "replace", + Path: "/spec/containers/0/image", + Value: "attacker/google-containers/pause-amd64:3.0", + }} + payloadBytes, _ := json.Marshal(payload) + _, err := cs.CoreV1().Pods(ns.GetName()).Patch(context.TODO(), pod.GetName(), types.JSONPatchType, payloadBytes, metav1.PatchOptions{}) + if err != nil { + return err + } + return nil + }).ShouldNot(Succeed()) }) It("should deny patching a not matching registry after applying with a matching (initContainer)", func() { - ns := NewNamespace("reg-deny-init-patch") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + ns := NewNamespace("") pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -169,23 +185,33 @@ var _ = Describe("enforcing a Container Registry", func() { } cs := ownerClient(tnt.Spec.Owners[0]) + + NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.Name).Create(context.Background(), pod, metav1.CreateOptions{}) return err }).Should(Succeed()) - Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: pod.GetName(), Namespace: ns.GetName()}, pod)).ToNot(HaveOccurred()) - - pod.Spec.InitContainers[0].Image = "attacker/google-containers/pause-amd64:3.0" - Expect(k8sClient.Update(context.Background(), pod)).To(HaveOccurred()) - - Expect(k8sClient.Delete(context.TODO(), ns)).Should(Succeed()) + Eventually(func() error { + payload := []Patch{{ + Op: "replace", + Path: "/spec/initContainers/0/image", + Value: "attacker/google-containers/pause-amd64:3.0", + }} + payloadBytes, _ := json.Marshal(payload) + _, err := cs.CoreV1().Pods(ns.GetName()).Patch(context.TODO(), pod.GetName(), types.JSONPatchType, payloadBytes, metav1.PatchOptions{}) + if err != nil { + return err + } + return nil + }).ShouldNot(Succeed()) }) It("should allow patching a matching registry after applying with a matching (Container)", func() { - ns := NewNamespace("reg-allow-container-patch") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + ns := NewNamespace("") pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -202,23 +228,33 @@ var _ = Describe("enforcing a Container Registry", func() { } cs := ownerClient(tnt.Spec.Owners[0]) + + NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.Name).Create(context.Background(), pod, metav1.CreateOptions{}) return err }).Should(Succeed()) - Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: pod.GetName(), Namespace: ns.GetName()}, pod)).ToNot(HaveOccurred()) - - pod.Spec.Containers[0].Image = "myregistry.azurecr.io/google-containers/pause-amd64:3.1" - Expect(k8sClient.Update(context.Background(), pod)).To(HaveOccurred()) - - Expect(k8sClient.Delete(context.TODO(), ns)).Should(Succeed()) + Eventually(func() error { + payload := []Patch{{ + Op: "replace", + Path: "/spec/containers/0/image", + Value: "myregistry.azurecr.io/google-containers/pause-amd64:3.1", + }} + payloadBytes, _ := json.Marshal(payload) + _, err := cs.CoreV1().Pods(ns.GetName()).Patch(context.TODO(), pod.GetName(), types.JSONPatchType, payloadBytes, metav1.PatchOptions{}) + if err != nil { + return err + } + return nil + }).Should(Succeed()) }) It("should allow patching a matching registry after applying with a matching (initContainer)", func() { - ns := NewNamespace("reg-allow-container-patch") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + ns := NewNamespace("") pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -241,18 +277,29 @@ var _ = Describe("enforcing a Container Registry", func() { } cs := ownerClient(tnt.Spec.Owners[0]) + + NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.Name).Create(context.Background(), pod, metav1.CreateOptions{}) return err }).Should(Succeed()) - Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: pod.GetName(), Namespace: ns.GetName()}, pod)).ToNot(HaveOccurred()) - - pod.Spec.InitContainers[0].Image = "myregistry.azurecr.io/google-containers/pause-amd64:3.1" - Expect(k8sClient.Update(context.Background(), pod)).To(HaveOccurred()) - - Expect(k8sClient.Delete(context.TODO(), ns)).Should(Succeed()) + Eventually(func() error { + payload := []Patch{{ + Op: "replace", + Path: "/spec/initContainers/0/image", + Value: "myregistry.azurecr.io/google-containers/pause-amd64:3.1", + }} + payloadBytes, _ := json.Marshal(payload) + _, err := cs.CoreV1().Pods(ns.GetName()).Patch(context.TODO(), pod.GetName(), types.JSONPatchType, payloadBytes, metav1.PatchOptions{}) + if err != nil { + return err + } + return nil + }).Should(Succeed()) }) It("should allow using an exact match", func() { diff --git a/e2e/ingress_class_extensions_test.go b/e2e/ingress_class_extensions_test.go index e17b205e..71b912be 100644 --- a/e2e/ingress_class_extensions_test.go +++ b/e2e/ingress_class_extensions_test.go @@ -35,13 +35,18 @@ var _ = Describe("when Tenant handles Ingress classes with extensions/v1beta1", }, }, IngressOptions: capsulev1beta2.IngressOptions{ - AllowedClasses: &api.SelectorAllowedListSpec{ - AllowedListSpec: api.AllowedListSpec{ - Exact: []string{ - "nginx", - "haproxy", + AllowedClasses: &api.DefaultAllowedListSpec{ + Default: "tenant-default", + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: api.AllowedListSpec{ + Exact: []string{"nginx", "haproxy"}, + Regex: "^oil-.*$", + }, + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "env": "customers", + }, }, - Regex: "^oil-.*$", }, }, }, diff --git a/e2e/ingress_class_networking_test.go b/e2e/ingress_class_networking_test.go index 0ecdd67b..99e19118 100644 --- a/e2e/ingress_class_networking_test.go +++ b/e2e/ingress_class_networking_test.go @@ -9,52 +9,151 @@ import ( "context" "errors" "fmt" + "strconv" + "strings" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" networkingv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/selection" + "k8s.io/apimachinery/pkg/types" "k8s.io/utils/pointer" + "sigs.k8s.io/controller-runtime/pkg/client" capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" "github.com/clastix/capsule/pkg/api" ) var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1", func() { - tnt := &capsulev1beta2.Tenant{ + tntNoDefault := &capsulev1beta2.Tenant{ ObjectMeta: metav1.ObjectMeta{ - Name: "ingress-class-networking-v1", + Name: "ic-selector-networking-v1", }, Spec: capsulev1beta2.TenantSpec{ Owners: []capsulev1beta2.OwnerSpec{ { - Name: "ingress", + Name: "ingress-selector", Kind: "User", }, }, IngressOptions: capsulev1beta2.IngressOptions{ - AllowedClasses: &api.SelectorAllowedListSpec{ - AllowedListSpec: api.AllowedListSpec{ - Exact: []string{ - "nginx", - "haproxy", + AllowedClasses: &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: api.AllowedListSpec{ + Exact: []string{"nginx", "haproxy"}, + Regex: "^oil-.*$", + }, + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "env": "customers", + }, + }, + }, + }, + }, + }, + } + + tntWithDefault := &capsulev1beta2.Tenant{ + ObjectMeta: metav1.ObjectMeta{ + Name: "ic-default-networking-v1", + }, + Spec: capsulev1beta2.TenantSpec{ + Owners: []capsulev1beta2.OwnerSpec{ + { + Name: "ingress-default", + Kind: "User", + }, + }, + IngressOptions: capsulev1beta2.IngressOptions{ + AllowedClasses: &api.DefaultAllowedListSpec{ + Default: "tenant-default", + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "name": "tenant-default", + }, }, - Regex: "^oil-.*$", }, }, }, }, } + tenantDefault := networkingv1.IngressClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default", + Labels: map[string]string{ + "name": "tenant-default", + "env": "e2e", + }, + }, + Spec: networkingv1.IngressClassSpec{ + Controller: "k8s.io/ingress-nginx", + }, + } + + globalDefault := networkingv1.IngressClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "global-default", + Labels: map[string]string{ + "name": "global-default", + "env": "customers", + }, + Annotations: map[string]string{ + "ingressclass.kubernetes.io/is-default-class": "true", + }, + }, + Spec: networkingv1.IngressClassSpec{ + Controller: "k8s.io/ingress-nginx", + }, + } + + disallowedGlobalDefault := networkingv1.IngressClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "disallowed", + Labels: map[string]string{ + "name": "disallowed-global-default", + "env": "e2e", + }, + Annotations: map[string]string{ + "ingressclass.kubernetes.io/is-default-class": "true", + }, + }, + Spec: networkingv1.IngressClassSpec{ + Controller: "k8s.io/ingress-nginx", + }, + } + JustBeforeEach(func() { - EventuallyCreation(func() error { - tnt.ResourceVersion = "" - return k8sClient.Create(context.TODO(), tnt) - }).Should(Succeed()) + for _, tnt := range []*capsulev1beta2.Tenant{tntWithDefault, tntNoDefault} { + EventuallyCreation(func() error { + tnt.ResourceVersion = "" + + return k8sClient.Create(context.TODO(), tnt) + }).Should(Succeed()) + } }) + JustAfterEach(func() { - Expect(k8sClient.Delete(context.TODO(), tnt)).Should(Succeed()) + for _, tnt := range []*capsulev1beta2.Tenant{tntWithDefault, tntNoDefault} { + Eventually(func() error { + return k8sClient.Delete(context.TODO(), tnt) + }, defaultTimeoutInterval, defaultPollInterval).Should(Succeed()) + } + + Eventually(func() (err error) { + req, _ := labels.NewRequirement("env", selection.Exists, nil) + + return k8sClient.DeleteAllOf(context.TODO(), &networkingv1.IngressClass{}, &client.DeleteAllOfOptions{ + ListOptions: client.ListOptions{ + LabelSelector: labels.NewSelector().Add(*req), + }, + }) + }, defaultTimeoutInterval, defaultPollInterval).Should(Succeed()) }) It("should block a non allowed class", func() { @@ -66,10 +165,10 @@ var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1" } ns := NewNamespace("") - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefault.Spec.Owners[0]) - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) By("non-specifying at all", func() { Eventually(func() (err error) { @@ -149,12 +248,12 @@ var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1" } ns := NewNamespace("") - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefault.Spec.Owners[0]) - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) - for _, c := range tnt.Spec.IngressOptions.AllowedClasses.Exact { + for _, c := range tntNoDefault.Spec.IngressOptions.AllowedClasses.Exact { Eventually(func() (err error) { i := &networkingv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ @@ -189,12 +288,12 @@ var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1" } ns := NewNamespace("") - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefault.Spec.Owners[0]) - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) - for _, c := range tnt.Spec.IngressOptions.AllowedClasses.Exact { + for _, c := range tntNoDefault.Spec.IngressOptions.AllowedClasses.Exact { Eventually(func() (err error) { i := &networkingv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ @@ -227,11 +326,11 @@ var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1" } ns := NewNamespace("") - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefault.Spec.Owners[0]) ingressClass := "oil-ingress" - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) Eventually(func() (err error) { i := &networkingv1.Ingress{ @@ -266,11 +365,11 @@ var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1" } ns := NewNamespace("") - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefault.Spec.Owners[0]) ingressClass := "oil-haproxy" - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) Eventually(func() (err error) { i := &networkingv1.Ingress{ @@ -293,4 +392,276 @@ var _ = Describe("when Tenant handles Ingress classes with networking.k8s.io/v1" return }, defaultTimeoutInterval, defaultPollInterval).Should(Succeed()) }) + + It("should allow enabled Ingress by selector using the deprecated annotation", func() { + if err := k8sClient.List(context.Background(), &networkingv1.IngressList{}); err != nil { + missingAPIError := &meta.NoKindMatchError{} + if errors.As(err, &missingAPIError) { + Skip(fmt.Sprintf("Running test due to unsupported API kind: %s", err.Error())) + } + } + + for i, sc := range []string{"customer-nginx", "customer-haproxy"} { + ingressClass := strings.Join([]string{sc, "-", strconv.Itoa(i)}, "") + class := &networkingv1.IngressClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: ingressClass, + Labels: map[string]string{ + "name": ingressClass, + "env": "customers", + }, + }, + Spec: networkingv1.IngressClassSpec{ + Controller: "k8s.io/ingress-nginx", + }, + } + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + i := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("allowed-%s", ingressClass), + Annotations: map[string]string{ + "kubernetes.io/ingress.class": ingressClass, + }, + }, + Spec: networkingv1.IngressSpec{ + DefaultBackend: &networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: "foo", + Port: networkingv1.ServiceBackendPort{ + Number: 8080, + }, + }, + }, + }, + } + + ns := NewNamespace("") + cs := ownerClient(tntNoDefault.Spec.Owners[0]) + + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + EventuallyCreation(func() error { + _, err := cs.NetworkingV1().Ingresses(ns.GetName()).Create(context.TODO(), i, metav1.CreateOptions{}) + return err + }).Should(Succeed()) + } + }) + + It("should allow enabled Ingress by selector using the ingressClassName field", func() { + if err := k8sClient.List(context.Background(), &networkingv1.IngressList{}); err != nil { + missingAPIError := &meta.NoKindMatchError{} + if errors.As(err, &missingAPIError) { + Skip(fmt.Sprintf("Running test due to unsupported API kind: %s", err.Error())) + } + } + + for i, sc := range []string{"customer-nginx", "customer-haproxy"} { + ingressClass := strings.Join([]string{sc, "-", strconv.Itoa(i)}, "") + class := &networkingv1.IngressClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: ingressClass, + Labels: map[string]string{ + "name": ingressClass, + "env": "customers", + }, + }, + Spec: networkingv1.IngressClassSpec{ + Controller: "k8s.io/ingress-nginx", + }, + } + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + i := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("allowed-%s", ingressClass), + }, + Spec: networkingv1.IngressSpec{ + IngressClassName: &ingressClass, + DefaultBackend: &networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: "foo", + Port: networkingv1.ServiceBackendPort{ + Number: 8080, + }, + }, + }, + }, + } + + ns := NewNamespace("") + cs := ownerClient(tntNoDefault.Spec.Owners[0]) + + NamespaceCreation(ns, tntNoDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + EventuallyCreation(func() error { + _, err := cs.NetworkingV1().Ingresses(ns.GetName()).Create(context.TODO(), i, metav1.CreateOptions{}) + return err + }).Should(Succeed()) + } + }) + + It("should mutate to default tenant IngressClass (class not does not exist)", func() { + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + i := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "e2e-default-ingress", + Namespace: ns.GetName(), + }, + Spec: networkingv1.IngressSpec{ + DefaultBackend: &networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: "foo", + Port: networkingv1.ServiceBackendPort{ + Number: 8080, + }, + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), i) + }).Should(Succeed()) + + Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: i.GetName(), Namespace: ns.GetName()}, i)) + Expect(*i.Spec.IngressClassName).To(Equal("tenant-default")) + }) + + It("should mutate to default tenant IngressClass (class exists)", func() { + if err := k8sClient.List(context.Background(), &networkingv1.IngressList{}); err != nil { + missingAPIError := &meta.NoKindMatchError{} + if errors.As(err, &missingAPIError) { + Skip(fmt.Sprintf("Running test due to unsupported API kind: %s", err.Error())) + } + } + + class := tenantDefault + Expect(k8sClient.Create(context.TODO(), &class)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + i := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "e2e-default-ingress", + Namespace: ns.GetName(), + }, + Spec: networkingv1.IngressSpec{ + DefaultBackend: &networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: "foo", + Port: networkingv1.ServiceBackendPort{ + Number: 8080, + }, + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), i) + }).Should(Succeed()) + + Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: i.GetName(), Namespace: ns.GetName()}, i)) + Expect(*i.Spec.IngressClassName).To(Equal(class.GetName())) + }) + + It("shoult mutate to default tenant IngressClass although the cluster global one is not allowed", func() { + if err := k8sClient.List(context.Background(), &networkingv1.IngressList{}); err != nil { + missingAPIError := &meta.NoKindMatchError{} + if errors.As(err, &missingAPIError) { + Skip(fmt.Sprintf("Running test due to unsupported API kind: %s", err.Error())) + } + } + + class := tenantDefault + global := disallowedGlobalDefault + + Expect(k8sClient.Create(context.TODO(), &class)).Should(Succeed()) + Expect(k8sClient.Create(context.TODO(), &global)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + i := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "e2e-default-global-ingress", + Namespace: ns.GetName(), + }, + Spec: networkingv1.IngressSpec{ + DefaultBackend: &networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: "foo", + Port: networkingv1.ServiceBackendPort{ + Number: 8080, + }, + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), i) + }).Should(Succeed()) + Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: i.GetName(), Namespace: ns.GetName()}, i)) + Expect(*i.Spec.IngressClassName).To(Equal(class.GetName())) + // Run Patch To verify same happens on Update + i.Spec.IngressClassName = nil + Expect(k8sClient.Update(context.Background(), i)).Should(Succeed()) + Expect(k8sClient.Get(context.Background(), types.NamespacedName{Name: i.GetName(), Namespace: ns.GetName()}, i)) + Expect(*i.Spec.IngressClassName).To(Equal(class.GetName())) + }) + + It("should mutate to default tenant IngressClass although the cluster global one is allowed", func() { + if err := k8sClient.List(context.Background(), &networkingv1.IngressList{}); err != nil { + missingAPIError := &meta.NoKindMatchError{} + if errors.As(err, &missingAPIError) { + Skip(fmt.Sprintf("Running test due to unsupported API kind: %s", err.Error())) + } + } + + class := tenantDefault + global := globalDefault + + Expect(k8sClient.Create(context.TODO(), &class)).Should(Succeed()) + Expect(k8sClient.Create(context.TODO(), &global)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + i := &networkingv1.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "e2e-default-global-ingress", + Namespace: ns.GetName(), + }, + Spec: networkingv1.IngressSpec{ + DefaultBackend: &networkingv1.IngressBackend{ + Service: &networkingv1.IngressServiceBackend{ + Name: "foo", + Port: networkingv1.ServiceBackendPort{ + Number: 8080, + }, + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), i) + }).Should(Succeed()) + Expect(*i.Spec.IngressClassName).To(Equal(class.GetName())) + // Run Patch To verify same happens on Update + i.Spec.IngressClassName = nil + Expect(k8sClient.Update(context.Background(), i)).Should(Succeed()) + Expect(*i.Spec.IngressClassName).To(Equal(class.GetName())) + }) }) diff --git a/e2e/owner_webhooks_test.go b/e2e/owner_webhooks_test.go index b20772b6..57a990b5 100644 --- a/e2e/owner_webhooks_test.go +++ b/e2e/owner_webhooks_test.go @@ -33,11 +33,13 @@ var _ = Describe("when Tenant owner interacts with the webhooks", func() { Kind: "User", }, }, - StorageClasses: &api.SelectorAllowedListSpec{ - AllowedListSpec: api.AllowedListSpec{ - Exact: []string{ - "cephfs", - "glusterfs", + StorageClasses: &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: api.AllowedListSpec{ + Exact: []string{ + "cephfs", + "glusterfs", + }, }, }, }, diff --git a/e2e/pod_priority_class_test.go b/e2e/pod_priority_class_test.go index f2251f79..d4737650 100644 --- a/e2e/pod_priority_class_test.go +++ b/e2e/pod_priority_class_test.go @@ -13,52 +13,135 @@ import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/scheduling/v1" + schedulingv1 "k8s.io/api/scheduling/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/selection" + "sigs.k8s.io/controller-runtime/pkg/client" capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" "github.com/clastix/capsule/pkg/api" ) var _ = Describe("enforcing a Priority Class", func() { - tnt := &capsulev1beta2.Tenant{ + tntWithDefaults := &capsulev1beta2.Tenant{ ObjectMeta: metav1.ObjectMeta{ - Name: "priority-class", + Name: "priority-class-defaults", }, Spec: capsulev1beta2.TenantSpec{ Owners: capsulev1beta2.OwnerListSpec{ { - Name: "george", + Name: "paul", Kind: "User", }, }, - PriorityClasses: &api.SelectorAllowedListSpec{ - AllowedListSpec: api.AllowedListSpec{ - Exact: []string{"gold"}, - Regex: "pc\\-\\w+", + PriorityClasses: &api.DefaultAllowedListSpec{ + Default: "tenant-default", + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "env": "customer", + }, + }, + }, + }, + }, + } + + tntNoDefaults := &capsulev1beta2.Tenant{ + ObjectMeta: metav1.ObjectMeta{ + Name: "priority-class-no-defaults", + }, + Spec: capsulev1beta2.TenantSpec{ + Owners: capsulev1beta2.OwnerListSpec{ + { + Name: "george", + Kind: "User", }, - LabelSelector: metav1.LabelSelector{ - MatchLabels: map[string]string{ - "env": "customers", + }, + PriorityClasses: &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: api.AllowedListSpec{ + Exact: []string{"gold"}, + Regex: "pc\\-\\w+", + }, + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "env": "customer", + }, }, }, }, }, } + pcTenantPreemption := corev1.PreemptionPolicy("PreemptLowerPriority") + tenantDefault := schedulingv1.PriorityClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default", + Labels: map[string]string{ + "env": "e2e", + }, + }, + Description: "tenant default priorityclass", + Value: 1212, + PreemptionPolicy: &pcTenantPreemption, + GlobalDefault: false, + } + + globalDefault := schedulingv1.PriorityClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "global-default", + Labels: map[string]string{ + "env": "customer", + }, + }, + Description: "global default priorityclass", + Value: 100000, + GlobalDefault: true, + } + + disallowedGlobalDefault := schedulingv1.PriorityClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "disallowed-global-default", + Labels: map[string]string{ + "env": "e2e", + }, + }, + Description: "global default priorityclass", + Value: 100000, + GlobalDefault: true, + } + JustBeforeEach(func() { - EventuallyCreation(func() error { - tnt.ResourceVersion = "" - return k8sClient.Create(context.TODO(), tnt) - }).Should(Succeed()) + for _, tnt := range []*capsulev1beta2.Tenant{tntWithDefaults, tntNoDefaults} { + EventuallyCreation(func() error { + tnt.ResourceVersion = "" + + return k8sClient.Create(context.TODO(), tnt) + }).Should(Succeed()) + } }) + JustAfterEach(func() { - Expect(k8sClient.Delete(context.TODO(), tnt)).Should(Succeed()) + for _, tnt := range []*capsulev1beta2.Tenant{tntWithDefaults, tntNoDefaults} { + Expect(k8sClient.Delete(context.TODO(), tnt)).Should(Succeed()) + } + + Eventually(func() (err error) { + req, _ := labels.NewRequirement("env", selection.Exists, nil) + + return k8sClient.DeleteAllOf(context.TODO(), &schedulingv1.PriorityClass{}, &client.DeleteAllOfOptions{ + ListOptions: client.ListOptions{ + LabelSelector: labels.NewSelector().Add(*req), + }, + }) + }, defaultTimeoutInterval, defaultPollInterval).Should(Succeed()) }) It("should block non allowed Priority Class", func() { ns := NewNamespace("") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -75,29 +158,71 @@ var _ = Describe("enforcing a Priority Class", func() { }, } - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.GetName()).Create(context.Background(), pod, metav1.CreateOptions{}) return err }).ShouldNot(Succeed()) }) + It("should block non matching selector match", func() { + for i, pc := range []string{"internal-bronze", "internal-silver", "internal-gold"} { + priorityName := strings.Join([]string{pc, "-", strconv.Itoa(i)}, "") + class := &schedulingv1.PriorityClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: priorityName, + Labels: map[string]string{ + "env": "internal", + }, + }, + Description: "fake PriorityClass for e2e", + Value: int32(10000 * (i + 2)), + } + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: pc, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "container", + Image: "quay.io/google-containers/pause-amd64:3.0", + }, + }, + PriorityClassName: class.GetName(), + }, + } + + ns := NewNamespace("") + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) + + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + EventuallyCreation(func() error { + _, err := cs.CoreV1().Pods(ns.GetName()).Create(context.Background(), pod, metav1.CreateOptions{}) + return err + }).ShouldNot(Succeed()) + } + }) + It("should allow exact match", func() { - pc := &v1.PriorityClass{ + pc := &schedulingv1.PriorityClass{ ObjectMeta: metav1.ObjectMeta{ Name: "gold", + Labels: map[string]string{ + "env": "e2e", + }, }, Description: "fake PriorityClass for e2e", Value: 10000, } Expect(k8sClient.Create(context.TODO(), pc)).Should(Succeed()) - defer func() { - Expect(k8sClient.Delete(context.TODO(), pc)).Should(Succeed()) - }() - ns := NewNamespace("") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ @@ -114,7 +239,7 @@ var _ = Describe("enforcing a Priority Class", func() { }, } - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.GetName()).Create(context.Background(), pod, metav1.CreateOptions{}) return err @@ -123,13 +248,15 @@ var _ = Describe("enforcing a Priority Class", func() { It("should allow regex match", func() { ns := NewNamespace("") - - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) for i, pc := range []string{"pc-bronze", "pc-silver", "pc-gold"} { - class := &v1.PriorityClass{ + class := &schedulingv1.PriorityClass{ ObjectMeta: metav1.ObjectMeta{ Name: pc, + Labels: map[string]string{ + "env": "e2e", + }, }, Description: "fake PriorityClass for e2e", Value: int32(10000 * (i + 2)), @@ -137,45 +264,36 @@ var _ = Describe("enforcing a Priority Class", func() { Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) - pod := &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: pc, - }, - Spec: corev1.PodSpec{ - Containers: []corev1.Container{ - { - Name: "container", - Image: "quay.io/google-containers/pause-amd64:3.0", + EventuallyCreation(func() error { + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: pc, + Namespace: ns.GetName(), + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "container", + Image: "quay.io/google-containers/pause-amd64:3.0", + }, }, + PriorityClassName: class.GetName(), }, - PriorityClassName: class.GetName(), - }, - } - - cs := ownerClient(tnt.Spec.Owners[0]) + } - EventuallyCreation(func() error { - _, err := cs.CoreV1().Pods(ns.GetName()).Create(context.Background(), pod, metav1.CreateOptions{}) - return err + return k8sClient.Create(context.Background(), pod) }).Should(Succeed()) - - Expect(k8sClient.Delete(context.TODO(), class)).Should(Succeed()) } }) It("should allow selector match", func() { - ns := NewNamespace("priority-selector-match") - - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - for i, pc := range []string{"customer-bronze", "customer-silver", "customer-gold"} { priorityName := strings.Join([]string{pc, "-", strconv.Itoa(i)}, "") - class := &v1.PriorityClass{ + class := &schedulingv1.PriorityClass{ ObjectMeta: metav1.ObjectMeta{ - Name: pc, + Name: priorityName, Labels: map[string]string{ - "name": priorityName, - "env": "customers", + "env": "customer", }, }, Description: "fake PriorityClass for e2e", @@ -198,15 +316,153 @@ var _ = Describe("enforcing a Priority Class", func() { }, } - cs := ownerClient(tnt.Spec.Owners[0]) + ns := NewNamespace("") + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) + + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) EventuallyCreation(func() error { _, err := cs.CoreV1().Pods(ns.GetName()).Create(context.Background(), pod, metav1.CreateOptions{}) return err }).Should(Succeed()) + } + }) + + It("fail if default tenant PriorityClass is absent", func() { + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default", + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "container", + Image: "quay.io/google-containers/pause-amd64:3.0", + }, + }, + }, + } + + ns := NewNamespace("") + cs := ownerClient(tntWithDefaults.Spec.Owners[0]) + + NamespaceCreation(ns, tntWithDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + EventuallyCreation(func() error { + _, err := cs.CoreV1().Pods(ns.GetName()).Create(context.Background(), pod, metav1.CreateOptions{}) + + return err + }).ShouldNot(Succeed()) + + Expect(k8sClient.Delete(context.TODO(), ns)).Should(Succeed()) + }) + + It("should mutate to default tenant PriorityClass", func() { + class := tenantDefault.DeepCopy() + class.SetResourceVersion("") + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + pod := corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default-present", + Namespace: ns.GetName(), + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "container", + Image: "quay.io/google-containers/pause-amd64:3.0", + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), &pod) + }).Should(Succeed()) + // Check if correct mutated + Expect(pod.Spec.PriorityClassName).To(Equal(class.GetName())) + Expect(pod.Spec.Priority).To(Equal(&class.Value)) + Expect(pod.Spec.PreemptionPolicy).To(Equal(class.PreemptionPolicy)) + }) + + It("should mutate to default tenant PriorityClass although the cluster global one is not allowed", func() { + class := tenantDefault.DeepCopy() + class.SetResourceVersion("") + + global := disallowedGlobalDefault.DeepCopy() + global.SetResourceVersion("") + + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + Expect(k8sClient.Create(context.TODO(), global)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) - Expect(k8sClient.Delete(context.TODO(), class)).Should(Succeed()) + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default-global-default", + Namespace: ns.GetName(), + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "container", + Image: "quay.io/google-containers/pause-amd64:3.0", + }, + }, + }, } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), pod) + }).Should(Succeed()) + // Check if correct applied + Expect(pod.Spec.PriorityClassName).To(Equal(class.GetName())) + Expect(pod.Spec.Priority).To(Equal(&class.Value)) + Expect(pod.Spec.PreemptionPolicy).To(Equal(class.PreemptionPolicy)) }) + It("should mutate to default tenant PriorityClass although the cluster global one is allowed", func() { + class := tenantDefault.DeepCopy() + class.SetResourceVersion("") + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + global := globalDefault.DeepCopy() + global.SetResourceVersion("") + Expect(k8sClient.Create(context.TODO(), global)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default-allowed", + Namespace: ns.GetName(), + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "container", + Image: "quay.io/google-containers/pause-amd64:3.0", + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), pod) + }).Should(Succeed()) + // Check if correctly applied + Expect(pod.Spec.PriorityClassName).To(Equal(class.GetName())) + Expect(*pod.Spec.Priority).To(Equal(class.Value)) + }) }) diff --git a/e2e/storage_class_test.go b/e2e/storage_class_test.go index 2469a871..d40d81df 100644 --- a/e2e/storage_class_test.go +++ b/e2e/storage_class_test.go @@ -3,64 +3,148 @@ // Copyright 2020-2021 Clastix Labs // SPDX-License-Identifier: Apache-2.0 +// "sigs.k8s.io/controller-runtime/pkg/client" + package e2e import ( "context" + "fmt" + "strconv" + "strings" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/selection" "k8s.io/utils/pointer" + "sigs.k8s.io/controller-runtime/pkg/client" capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" "github.com/clastix/capsule/pkg/api" ) var _ = Describe("when Tenant handles Storage classes", func() { - tnt := &capsulev1beta2.Tenant{ + tntNoDefaults := &capsulev1beta2.Tenant{ + ObjectMeta: metav1.ObjectMeta{ + Name: "storage-class-selector", + }, + Spec: capsulev1beta2.TenantSpec{ + Owners: capsulev1beta2.OwnerListSpec{ + { + Name: "selector", + Kind: "User", + }, + }, + StorageClasses: &api.DefaultAllowedListSpec{ + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + AllowedListSpec: api.AllowedListSpec{ + Exact: []string{"cephfs", "glusterfs"}, + Regex: "^oil-.*$", + }, + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "env": "customer", + }, + }, + }, + }, + }, + } + + tntWithDefault := &capsulev1beta2.Tenant{ ObjectMeta: metav1.ObjectMeta{ - Name: "storage-class", + Name: "storage-class-default", }, Spec: capsulev1beta2.TenantSpec{ Owners: capsulev1beta2.OwnerListSpec{ { - Name: "storage", + Name: "default", Kind: "User", }, }, - StorageClasses: &api.SelectorAllowedListSpec{ - AllowedListSpec: api.AllowedListSpec{ - Exact: []string{ - "cephfs", - "glusterfs", + StorageClasses: &api.DefaultAllowedListSpec{ + Default: "tenant-default", + SelectorAllowedListSpec: api.SelectorAllowedListSpec{ + LabelSelector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "name": "tenant-default", + }, }, - Regex: "^oil-.*$", }, }, }, } + tenantDefault := storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "tenant-default", + Labels: map[string]string{ + "name": "tenant-default", + "env": "e2e", + }, + }, + Provisioner: "kubernetes.io/no-provisioner", + } + globalDefault := storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "global-default", + Labels: map[string]string{ + "env": "customer", + }, + }, + Provisioner: "kubernetes.io/no-provisioner", + } + disallowedGlobalDefault := storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: "disallowed-global-default", + Labels: map[string]string{ + "name": "disallowed-global-default", + "env": "e2e", + }, + }, + Provisioner: "kubernetes.io/no-provisioner", + } + JustBeforeEach(func() { - EventuallyCreation(func() error { - tnt.ResourceVersion = "" - return k8sClient.Create(context.TODO(), tnt) - }).Should(Succeed()) + for _, tnt := range []*capsulev1beta2.Tenant{tntNoDefaults, tntWithDefault} { + EventuallyCreation(func() error { + tnt.ResourceVersion = "" + + return k8sClient.Create(context.TODO(), tnt) + }).Should(Succeed()) + } }) JustAfterEach(func() { - Expect(k8sClient.Delete(context.TODO(), tnt)).Should(Succeed()) + for _, tnt := range []*capsulev1beta2.Tenant{tntNoDefaults, tntWithDefault} { + Expect(k8sClient.Delete(context.TODO(), tnt)).Should(Succeed()) + } + + Eventually(func() (err error) { + req, _ := labels.NewRequirement("env", selection.Exists, nil) + + return k8sClient.DeleteAllOf(context.TODO(), &storagev1.StorageClass{}, &client.DeleteAllOfOptions{ + ListOptions: client.ListOptions{ + LabelSelector: labels.NewSelector().Add(*req), + }, + }) + }, defaultTimeoutInterval, defaultPollInterval).Should(Succeed()) }) - It("should fails", func() { + It("should fail", func() { + k8sClient.Create(context.TODO(), tntNoDefaults) + ns := NewNamespace("") - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) By("non-specifying it", func() { Eventually(func() (err error) { - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) p := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "denied-pvc", @@ -80,7 +164,7 @@ var _ = Describe("when Tenant handles Storage classes", func() { }) By("specifying a forbidden one", func() { Eventually(func() (err error) { - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) p := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: "mighty-storage", @@ -98,16 +182,54 @@ var _ = Describe("when Tenant handles Storage classes", func() { return }, defaultTimeoutInterval, defaultPollInterval).ShouldNot(Succeed()) }) + By("specifying with not matching label", func() { + for i, sc := range []string{"internal-hdd", "internal-ssd"} { + storageName := strings.Join([]string{sc, "-", strconv.Itoa(i)}, "") + class := &storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: fmt.Sprintf("sc-%s", storageName), + Labels: map[string]string{ + "env": "internal", + }, + }, + Provisioner: "kubernetes.io/no-provisioner", + } + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: storageName, + }, + Spec: corev1.PersistentVolumeClaimSpec{ + StorageClassName: &storageName, + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: map[corev1.ResourceName]resource.Quantity{ + corev1.ResourceStorage: resource.MustParse("3Gi"), + }, + }, + }, + } + + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) + + EventuallyCreation(func() error { + _, err := cs.CoreV1().PersistentVolumeClaims(ns.GetName()).Create(context.Background(), p, metav1.CreateOptions{}) + return err + }).ShouldNot(Succeed()) + } + }) + }) It("should allow", func() { ns := NewNamespace("") - cs := ownerClient(tnt.Spec.Owners[0]) + cs := ownerClient(tntNoDefaults.Spec.Owners[0]) - NamespaceCreation(ns, tnt.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) - TenantNamespaceList(tnt, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + NamespaceCreation(ns, tntNoDefaults.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntNoDefaults, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) By("using exact matches", func() { - for _, c := range tnt.Spec.StorageClasses.Exact { + for _, c := range tntNoDefaults.Spec.StorageClasses.Exact { Eventually(func() (err error) { p := &corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ @@ -149,5 +271,156 @@ var _ = Describe("when Tenant handles Storage classes", func() { return }, defaultTimeoutInterval, defaultPollInterval).Should(Succeed()) }) + By("using a selector match", func() { + for i, sc := range []string{"customer-hdd", "customer-ssd"} { + storageName := strings.Join([]string{sc, "-", strconv.Itoa(i)}, "") + class := &storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{ + Name: storageName, + Labels: map[string]string{ + "env": "customer", + }, + }, + Provisioner: "kubernetes.io/no-provisioner", + } + Expect(k8sClient.Create(context.TODO(), class)).Should(Succeed()) + + EventuallyCreation(func() error { + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: storageName, + Namespace: ns.GetName(), + }, + Spec: corev1.PersistentVolumeClaimSpec{ + StorageClassName: &storageName, + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: map[corev1.ResourceName]resource.Quantity{ + corev1.ResourceStorage: resource.MustParse("3Gi"), + }, + }, + }, + } + + return k8sClient.Create(context.Background(), p) + }).Should(Succeed()) + } + }) + }) + + It("should mutate to default tenant StorageClass (class does not exists)", func() { + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "pvc-default-sc", + Namespace: ns.GetName(), + }, + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: map[corev1.ResourceName]resource.Quantity{ + corev1.ResourceStorage: resource.MustParse("3Gi"), + }, + }, + }, + } + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), p) + }).Should(Succeed()) + Expect(*p.Spec.StorageClassName).To(Equal("tenant-default")) + }) + + It("should mutate to default tenant StorageClass (class exists)", func() { + class := tenantDefault + Expect(k8sClient.Create(context.TODO(), &class)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "pvc-default-sc-present", + Namespace: ns.GetName(), + }, + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: map[corev1.ResourceName]resource.Quantity{ + corev1.ResourceStorage: resource.MustParse("3Gi"), + }, + }, + }, + } + + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), p) + }).Should(Succeed()) + Expect(*p.Spec.StorageClassName).To(Equal(class.GetName())) + }) + + It("should mutate to default tenant StorageClass although cluster global ons is not allowed", func() { + class := tenantDefault + global := disallowedGlobalDefault + + Expect(k8sClient.Create(context.TODO(), &class)).Should(Succeed()) + Expect(k8sClient.Create(context.TODO(), &global)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "pvc-default-sc-present", + Namespace: ns.GetName(), + }, + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: map[corev1.ResourceName]resource.Quantity{ + corev1.ResourceStorage: resource.MustParse("3Gi"), + }, + }, + }, + } + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), p) + }).Should(Succeed()) + Expect(*p.Spec.StorageClassName).To(Equal(class.GetName())) + }) + + It("should mutate to default tenant StorageClass although cluster global ons is allowed", func() { + class := tenantDefault + global := globalDefault + + Expect(k8sClient.Create(context.TODO(), &class)).Should(Succeed()) + Expect(k8sClient.Create(context.TODO(), &global)).Should(Succeed()) + + ns := NewNamespace("") + NamespaceCreation(ns, tntWithDefault.Spec.Owners[0], defaultTimeoutInterval).Should(Succeed()) + TenantNamespaceList(tntWithDefault, defaultTimeoutInterval).Should(ContainElement(ns.GetName())) + + p := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: "pvc-default-sc-present", + Namespace: ns.GetName(), + }, + Spec: corev1.PersistentVolumeClaimSpec{ + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.ResourceRequirements{ + Requests: map[corev1.ResourceName]resource.Quantity{ + corev1.ResourceStorage: resource.MustParse("3Gi"), + }, + }, + }, + } + EventuallyCreation(func() error { + return k8sClient.Create(context.Background(), p) + }).Should(Succeed()) + Expect(*p.Spec.StorageClassName).To(Equal(class.GetName())) }) }) diff --git a/main.go b/main.go index bb901260..323f66a1 100644 --- a/main.go +++ b/main.go @@ -38,6 +38,7 @@ import ( "github.com/clastix/capsule/pkg/configuration" "github.com/clastix/capsule/pkg/indexer" "github.com/clastix/capsule/pkg/webhook" + "github.com/clastix/capsule/pkg/webhook/defaults" "github.com/clastix/capsule/pkg/webhook/ingress" namespacewebhook "github.com/clastix/capsule/pkg/webhook/namespace" "github.com/clastix/capsule/pkg/webhook/networkpolicy" @@ -237,7 +238,7 @@ func main() { make([]webhook.Webhook, 0), route.Pod(pod.ImagePullPolicy(), pod.ContainerRegistry(), pod.PriorityClass(), pod.RuntimeClass()), route.Namespace(utils.InCapsuleGroups(cfg, namespacewebhook.PatchHandler(), namespacewebhook.QuotaHandler(), namespacewebhook.FreezeHandler(cfg), namespacewebhook.PrefixHandler(cfg), namespacewebhook.UserMetadataHandler())), - route.Ingress(ingress.Class(cfg), ingress.Hostnames(cfg), ingress.Collision(cfg), ingress.Wildcard()), + route.Ingress(ingress.Class(cfg, kubeVersion), ingress.Hostnames(cfg), ingress.Collision(cfg), ingress.Wildcard()), route.PVC(pvc.Handler()), route.Service(service.Handler()), route.NetworkPolicy(utils.InCapsuleGroups(cfg, networkpolicy.Handler())), @@ -245,6 +246,7 @@ func main() { route.OwnerReference(utils.InCapsuleGroups(cfg, namespacewebhook.OwnerReferenceHandler(), ownerreference.Handler(cfg))), route.Cordoning(tenant.CordoningHandler(cfg), tenant.ResourceCounterHandler()), route.Node(utils.InCapsuleGroups(cfg, node.UserMetadataHandler(cfg, kubeVersion))), + route.Defaults(defaults.Handler(cfg, kubeVersion)), ) nodeWebhookSupported, _ := utils.NodeWebhookSupported(kubeVersion) diff --git a/pkg/api/allowed_list.go b/pkg/api/allowed_list.go index 0784ec6e..3d2ef867 100644 --- a/pkg/api/allowed_list.go +++ b/pkg/api/allowed_list.go @@ -15,18 +15,41 @@ import ( // +kubebuilder:object:generate=true +type DefaultAllowedListSpec struct { + SelectorAllowedListSpec `json:",inline"` + Default string `json:"default,omitempty"` +} + +func (in *DefaultAllowedListSpec) MatchDefault(value string) bool { + return in.Default == value +} + +// +kubebuilder:object:generate=true + type SelectorAllowedListSpec struct { AllowedListSpec `json:",inline"` metav1.LabelSelector `json:",inline"` } +func (in *SelectorAllowedListSpec) MatchSelectByName(obj client.Object) bool { + if obj != nil { + return in.AllowedListSpec.Match(obj.GetName()) || in.SelectorMatch(obj) + } + + return false +} + func (in *SelectorAllowedListSpec) SelectorMatch(obj client.Object) bool { - selector, err := metav1.LabelSelectorAsSelector(&in.LabelSelector) - if err != nil { - return false + if obj != nil { + selector, err := metav1.LabelSelectorAsSelector(&in.LabelSelector) + if err != nil { + return false + } + + return selector.Matches(labels.Set(obj.GetLabels())) } - return selector.Matches(labels.Set(obj.GetLabels())) + return false } // +kubebuilder:object:generate=true @@ -36,6 +59,14 @@ type AllowedListSpec struct { Regex string `json:"allowedRegex,omitempty"` } +func (in *AllowedListSpec) Match(value string) (ok bool) { + if in.ExactMatch(value) || in.RegexMatch(value) { + return true + } + + return false +} + func (in *AllowedListSpec) ExactMatch(value string) (ok bool) { if len(in.Exact) > 0 { sort.SliceStable(in.Exact, func(i, j int) bool { diff --git a/pkg/api/zz_generated.deepcopy.go b/pkg/api/zz_generated.deepcopy.go index 9419894f..93b61c23 100644 --- a/pkg/api/zz_generated.deepcopy.go +++ b/pkg/api/zz_generated.deepcopy.go @@ -113,6 +113,22 @@ func (in *AllowedServices) DeepCopy() *AllowedServices { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *DefaultAllowedListSpec) DeepCopyInto(out *DefaultAllowedListSpec) { + *out = *in + in.SelectorAllowedListSpec.DeepCopyInto(&out.SelectorAllowedListSpec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DefaultAllowedListSpec. +func (in *DefaultAllowedListSpec) DeepCopy() *DefaultAllowedListSpec { + if in == nil { + return nil + } + out := new(DefaultAllowedListSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ExternalServiceIPsSpec) DeepCopyInto(out *ExternalServiceIPsSpec) { *out = *in diff --git a/pkg/webhook/defaults/errors.go b/pkg/webhook/defaults/errors.go new file mode 100644 index 00000000..85202fb2 --- /dev/null +++ b/pkg/webhook/defaults/errors.go @@ -0,0 +1,56 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package defaults + +import ( + "fmt" +) + +type StorageClassError struct { + storageClass string + msg error +} + +func NewStorageClassError(class string, msg error) error { + return &StorageClassError{ + storageClass: class, + msg: msg, + } +} + +func (e StorageClassError) Error() string { + return fmt.Sprintf("Failed to resolve Storage Class %s: %s", e.storageClass, e.msg) +} + +type IngressClassError struct { + ingressClass string + msg error +} + +func NewIngressClassError(class string, msg error) error { + return &IngressClassError{ + ingressClass: class, + msg: msg, + } +} + +func (e IngressClassError) Error() string { + return fmt.Sprintf("Failed to resolve Ingress Class %s: %s", e.ingressClass, e.msg) +} + +type PriorityClassError struct { + priorityClass string + msg error +} + +func NewPriorityClassError(class string, msg error) error { + return &PriorityClassError{ + priorityClass: class, + msg: msg, + } +} + +func (e PriorityClassError) Error() string { + return fmt.Sprintf("Failed to resolve Priority Class %s: %s", e.priorityClass, e.msg) +} diff --git a/pkg/webhook/defaults/handler.go b/pkg/webhook/defaults/handler.go new file mode 100644 index 00000000..5a3a4f1e --- /dev/null +++ b/pkg/webhook/defaults/handler.go @@ -0,0 +1,68 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package defaults + +import ( + "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/version" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "github.com/clastix/capsule/pkg/configuration" + capsulewebhook "github.com/clastix/capsule/pkg/webhook" +) + +type handler struct { + cfg configuration.Configuration + version *version.Version +} + +func Handler(cfg configuration.Configuration, version *version.Version) capsulewebhook.Handler { + return &handler{ + cfg: cfg, + version: version, + } +} + +func (h *handler) OnCreate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return h.mutate(ctx, req, client, decoder, recorder) + } +} + +func (h *handler) OnDelete(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return nil + } +} + +func (h *handler) OnUpdate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return h.mutate(ctx, req, client, decoder, recorder) + } +} + +func (h *handler) mutate(ctx context.Context, req admission.Request, c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + var response *admission.Response + + switch { + case req.Resource == (metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"}): + response = mutatePodDefaults(ctx, req, c, decoder, recorder) + case req.Resource == (metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "persistentvolumeclaims"}): + response = mutatePVCDefaults(ctx, req, c, decoder, recorder) + case req.Resource == (metav1.GroupVersionResource{Group: "networking.k8s.io", Version: "v1", Resource: "ingresses"}) || req.Resource == (metav1.GroupVersionResource{Group: "networking.k8s.io", Version: "v1beta1", Resource: "ingresses"}): + response = mutateIngressDefaults(ctx, req, h.version, c, decoder, recorder) + } + + if response == nil { + skip := admission.Allowed("Skipping Mutation") + + response = &skip + } + + return response +} diff --git a/pkg/webhook/defaults/ingress.go b/pkg/webhook/defaults/ingress.go new file mode 100644 index 00000000..8ec687cd --- /dev/null +++ b/pkg/webhook/defaults/ingress.go @@ -0,0 +1,78 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package defaults + +import ( + "context" + "encoding/json" + "net/http" + + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/util/version" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" + capsuleingress "github.com/clastix/capsule/pkg/webhook/ingress" + "github.com/clastix/capsule/pkg/webhook/utils" +) + +func mutateIngressDefaults(ctx context.Context, req admission.Request, version *version.Version, c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + ingress, err := capsuleingress.FromRequest(req, decoder) + if err != nil { + return utils.ErroredResponse(err) + } + + var tnt *capsulev1beta2.Tenant + + tnt, err = capsuleingress.TenantFromIngress(ctx, c, ingress) + if err != nil { + return utils.ErroredResponse(err) + } + + if tnt == nil { + return nil + } + // Validate Default Ingress + allowed := tnt.Spec.IngressOptions.AllowedClasses + + if allowed == nil || allowed.Default == "" { + return nil + } + + var mutate bool + + var ingressClass client.Object + + if ingressClassName := ingress.IngressClass(); ingressClassName != nil && *ingressClassName != allowed.Default { + if ingressClass, err = utils.GetIngressClassByName(ctx, version, c, ingressClassName); err != nil && !k8serrors.IsNotFound(err) { + response := admission.Denied(NewIngressClassError(*ingressClassName, err).Error()) + + return &response + } + } else { + mutate = true + } + + if mutate = mutate || (utils.IsDefaultIngressClass(ingressClass) && ingressClass.GetName() != allowed.Default); !mutate { + return nil + } + + ingress.SetIngressClass(allowed.Default) + // Marshal Manifest + marshaled, err := json.Marshal(ingress) + if err != nil { + response := admission.Errored(http.StatusInternalServerError, err) + + return &response + } + + recorder.Eventf(tnt, corev1.EventTypeNormal, "TenantDefault", "Assigned Tenant default Ingress Class %s to %s/%s", allowed.Default, ingress.Name(), ingress.Namespace()) + + response := admission.PatchResponseFromRaw(req.Object.Raw, marshaled) + + return &response +} diff --git a/pkg/webhook/defaults/pods.go b/pkg/webhook/defaults/pods.go new file mode 100644 index 00000000..7b1036f7 --- /dev/null +++ b/pkg/webhook/defaults/pods.go @@ -0,0 +1,87 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package defaults + +import ( + "context" + "encoding/json" + "fmt" + + corev1 "k8s.io/api/core/v1" + schedulev1 "k8s.io/api/scheduling/v1" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" + "github.com/clastix/capsule/pkg/webhook/utils" +) + +func mutatePodDefaults(ctx context.Context, req admission.Request, c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + var err error + + pod := &corev1.Pod{} + if err = decoder.Decode(req, pod); err != nil { + return utils.ErroredResponse(err) + } + + var tnt *capsulev1beta2.Tenant + + tnt, err = utils.TenantByStatusNamespace(ctx, c, pod.Namespace) + if err != nil { + return utils.ErroredResponse(err) + } + + if tnt == nil { + return nil + } + + allowed := tnt.Spec.PriorityClasses + + if allowed == nil || allowed.Default == "" { + return nil + } + + priorityClassPod := pod.Spec.PriorityClassName + + var mutate bool + + var cpc *schedulev1.PriorityClass + // PriorityClass name is empty, if no GlobalDefault is set and no PriorityClass was given on pod + if len(priorityClassPod) > 0 && priorityClassPod != allowed.Default { + cpc, err = utils.GetPriorityClassByName(ctx, c, priorityClassPod) + // Should not happen, since API already checks if PC present + if err != nil { + response := admission.Denied(NewPriorityClassError(priorityClassPod, err).Error()) + + return &response + } + } else { + mutate = true + } + + if mutate = mutate || (utils.IsDefaultPriorityClass(cpc) && cpc.GetName() != allowed.Default); !mutate { + return nil + } + + pc, err := utils.GetPriorityClassByName(ctx, c, allowed.Default) + if err != nil { + return utils.ErroredResponse(fmt.Errorf("failed to assign tenant default Priority Class: %w", err)) + } + + pod.Spec.PreemptionPolicy = pc.PreemptionPolicy + pod.Spec.Priority = &pc.Value + pod.Spec.PriorityClassName = pc.Name + // Marshal Pod + marshaled, err := json.Marshal(pod) + if err != nil { + return utils.ErroredResponse(err) + } + + recorder.Eventf(tnt, corev1.EventTypeNormal, "TenantDefault", "Assigned Tenant default Priority Class %s to %s/%s", allowed.Default, pod.Namespace, pod.Name) + + response := admission.PatchResponseFromRaw(req.Object.Raw, marshaled) + + return &response +} diff --git a/pkg/webhook/defaults/storage.go b/pkg/webhook/defaults/storage.go new file mode 100644 index 00000000..e6c12041 --- /dev/null +++ b/pkg/webhook/defaults/storage.go @@ -0,0 +1,77 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package defaults + +import ( + "context" + "encoding/json" + + corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" + "github.com/clastix/capsule/pkg/webhook/utils" +) + +func mutatePVCDefaults(ctx context.Context, req admission.Request, c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + var err error + + pvc := &corev1.PersistentVolumeClaim{} + if err = decoder.Decode(req, pvc); err != nil { + return utils.ErroredResponse(err) + } + + var tnt *capsulev1beta2.Tenant + + tnt, err = utils.TenantByStatusNamespace(ctx, c, pvc.Namespace) + if err != nil { + return utils.ErroredResponse(err) + } + + if tnt == nil { + return nil + } + + allowed := tnt.Spec.StorageClasses + + if allowed == nil || allowed.Default == "" { + return nil + } + + var mutate bool + + var csc *storagev1.StorageClass + + if storageClassName := pvc.Spec.StorageClassName; storageClassName != nil && *storageClassName != allowed.Default { + csc, err = utils.GetStorageClassByName(ctx, c, *storageClassName) + if err != nil && !k8serrors.IsNotFound(err) { + response := admission.Denied(NewStorageClassError(*storageClassName, err).Error()) + + return &response + } + } else { + mutate = true + } + + if mutate = mutate || (utils.IsDefaultStorageClass(csc) && csc.GetName() != allowed.Default); !mutate { + return nil + } + + pvc.Spec.StorageClassName = &tnt.Spec.StorageClasses.Default + // Marshal Manifest + marshaled, err := json.Marshal(pvc) + if err != nil { + return utils.ErroredResponse(err) + } + + recorder.Eventf(tnt, corev1.EventTypeNormal, "TenantDefault", "Assigned Tenant default Storage Class %s to %s/%s", allowed.Default, pvc.Namespace, pvc.Name) + + response := admission.PatchResponseFromRaw(req.Object.Raw, marshaled) + + return &response +} diff --git a/pkg/webhook/ingress/errors.go b/pkg/webhook/ingress/errors.go index c8191c01..040a0097 100644 --- a/pkg/webhook/ingress/errors.go +++ b/pkg/webhook/ingress/errors.go @@ -8,22 +8,25 @@ import ( "strings" "github.com/clastix/capsule/pkg/api" + "github.com/clastix/capsule/pkg/webhook/utils" ) type ingressClassForbiddenError struct { - className string - spec api.SelectorAllowedListSpec + ingressClassName string + spec api.DefaultAllowedListSpec } -func NewIngressClassForbidden(className string, spec api.SelectorAllowedListSpec) error { +func NewIngressClassForbidden(class string, spec api.DefaultAllowedListSpec) error { return &ingressClassForbiddenError{ - className: className, - spec: spec, + ingressClassName: class, + spec: spec, } } func (i ingressClassForbiddenError) Error() string { - return fmt.Sprintf("Ingress Class %s is forbidden for the current Tenant%s", i.className, appendClassError(i.spec)) + err := fmt.Sprintf("Ingress Class %s is forbidden for the current Tenant: ", i.ingressClassName) + + return utils.DefaultAllowedValuesErrorMessage(i.spec, err) } type ingressHostnameNotValidError struct { @@ -53,35 +56,36 @@ func (i ingressHostnameNotValidError) Error() string { i.invalidHostnames, i.notMatchingHostnames, appendHostnameError(i.spec)) } -type ingressClassNotValidError struct { - spec api.SelectorAllowedListSpec +type ingressClassUndefinedError struct { + spec api.DefaultAllowedListSpec } -func NewIngressClassNotValid(spec api.SelectorAllowedListSpec) error { - return &ingressClassNotValidError{ +func NewIngressClassUndefined(spec api.DefaultAllowedListSpec) error { + return &ingressClassUndefinedError{ spec: spec, } } -func (i ingressClassNotValidError) Error() string { - return "A valid Ingress Class must be used" + appendClassError(i.spec) +func (i ingressClassUndefinedError) Error() string { + return utils.DefaultAllowedValuesErrorMessage(i.spec, "No Ingress Class is forbidden for the current Tenant. Specify a Ingress Class which is allowed within the Tenant: ") } -// nolint:predeclared -func appendClassError(spec api.SelectorAllowedListSpec) (append string) { - if len(spec.Exact) > 0 { - append += fmt.Sprintf(", one of the following (%s)", strings.Join(spec.Exact, ", ")) - } +type ingressClassNotValidError struct { + ingressClassName string + spec api.DefaultAllowedListSpec +} - if len(spec.Regex) > 0 { - append += fmt.Sprintf(", or matching the regex %s", spec.Regex) +func NewIngressClassNotValid(class string, spec api.DefaultAllowedListSpec) error { + return &ingressClassNotValidError{ + ingressClassName: class, + spec: spec, } +} - if len(spec.MatchLabels) > 0 || len(spec.MatchExpressions) > 0 { - append += fmt.Sprintf(", or matching the label selector defined in the Tenant") - } +func (i ingressClassNotValidError) Error() string { + err := fmt.Sprintf("Ingress Class %s is forbidden for the current Tenant: ", i.ingressClassName) - return + return utils.DefaultAllowedValuesErrorMessage(i.spec, err) } // nolint:predeclared diff --git a/pkg/webhook/ingress/types.go b/pkg/webhook/ingress/types.go index 99bab5c3..717eeb45 100644 --- a/pkg/webhook/ingress/types.go +++ b/pkg/webhook/ingress/types.go @@ -21,6 +21,7 @@ type Ingress interface { Namespace() string Name() string HostnamePathsPairs() map[string]sets.String + SetIngressClass(string) } type NetworkingV1 struct { @@ -44,6 +45,20 @@ func (n NetworkingV1) IngressClass() (res *string) { return } +func (n NetworkingV1) SetIngressClass(ingressClassName string) { + if n.Spec.IngressClassName == nil { + if a := n.GetAnnotations(); a != nil { + if _, ok := a[annotationName]; ok { + a[annotationName] = ingressClassName + + return + } + } + } + // Assign in case the IngressClassName property was not set + n.Spec.IngressClassName = &ingressClassName +} + func (n NetworkingV1) Namespace() string { return n.GetNamespace() } @@ -96,6 +111,20 @@ func (n NetworkingV1Beta1) IngressClass() (res *string) { return } +func (n NetworkingV1Beta1) SetIngressClass(ingressClassName string) { + if n.Spec.IngressClassName == nil { + if a := n.GetAnnotations(); a != nil { + if _, ok := a[annotationName]; ok { + a[annotationName] = ingressClassName + + return + } + } + } + // Assign in case the IngressClassName property was not set + n.Annotations[annotationName] = ingressClassName +} + func (n NetworkingV1Beta1) Namespace() string { return n.GetNamespace() } @@ -148,6 +177,18 @@ func (e Extension) IngressClass() (res *string) { return } +func (e Extension) SetIngressClass(ingressClassName string) { + if a := e.GetAnnotations(); a != nil { + if _, ok := a[annotationName]; ok { + a[annotationName] = ingressClassName + + return + } + } + // Assign in case the IngressClassName property was not set + e.Annotations[annotationName] = ingressClassName +} + func (e Extension) Namespace() string { return e.GetNamespace() } diff --git a/pkg/webhook/ingress/utils.go b/pkg/webhook/ingress/utils.go index c9185b93..80ad08b4 100644 --- a/pkg/webhook/ingress/utils.go +++ b/pkg/webhook/ingress/utils.go @@ -17,7 +17,7 @@ import ( capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" ) -func tenantFromIngress(ctx context.Context, c client.Client, ingress Ingress) (*capsulev1beta2.Tenant, error) { +func TenantFromIngress(ctx context.Context, c client.Client, ingress Ingress) (*capsulev1beta2.Tenant, error) { tenantList := &capsulev1beta2.TenantList{} if err := c.List(ctx, tenantList, client.MatchingFieldsSelector{ Selector: fields.OneTermEqualSelector(".status.namespaces", ingress.Namespace()), @@ -33,7 +33,7 @@ func tenantFromIngress(ctx context.Context, c client.Client, ingress Ingress) (* } // nolint:nakedret -func ingressFromRequest(req admission.Request, decoder *admission.Decoder) (ingress Ingress, err error) { +func FromRequest(req admission.Request, decoder *admission.Decoder) (ingress Ingress, err error) { switch req.Kind.Group { case "networking.k8s.io": if req.Kind.Version == "v1" { diff --git a/pkg/webhook/ingress/validate_class.go b/pkg/webhook/ingress/validate_class.go index 93021072..9f2018d2 100644 --- a/pkg/webhook/ingress/validate_class.go +++ b/pkg/webhook/ingress/validate_class.go @@ -7,12 +7,8 @@ import ( "context" "net/http" - "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" - networkingv1 "k8s.io/api/networking/v1" - networkingv1beta1 "k8s.io/api/networking/v1beta1" k8serrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/version" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" @@ -29,170 +25,91 @@ type class struct { version *version.Version } -func Class(configuration configuration.Configuration) capsulewebhook.Handler { - version, _ := utils.GetK8sVersion() - +func Class(configuration configuration.Configuration, version *version.Version) capsulewebhook.Handler { return &class{ configuration: configuration, version: version, } } -func (r *class) retrieveIngressClass(ctx context.Context, ctrlClient client.Client, ingressClassName *string) (client.Object, error) { - if r.version == nil || ingressClassName == nil { - return nil, nil - } - - var obj client.Object - - switch { - case r.version.Minor() < 18: - return nil, nil - case r.version.Minor() < 19: - obj = &networkingv1beta1.IngressClass{} - default: - obj = &networkingv1.IngressClass{} +func (r *class) OnCreate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return r.validate(ctx, r.version, client, req, decoder, recorder) } +} - if err := ctrlClient.Get(ctx, types.NamespacedName{Name: *ingressClassName}, obj); err != nil { - if k8serrors.IsNotFound(err) { - return nil, nil - } - - return nil, err +func (r *class) OnUpdate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return r.validate(ctx, r.version, client, req, decoder, recorder) } - - return obj, nil } -// nolint:dupl -func (r *class) OnCreate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { +func (r *class) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - ingress, err := ingressFromRequest(req, decoder) - if err != nil { - return utils.ErroredResponse(err) - } - - var tenant *capsulev1beta2.Tenant - - tenant, err = tenantFromIngress(ctx, client, ingress) - if err != nil { - return utils.ErroredResponse(err) - } + return nil + } +} - if tenant == nil { - return nil - } +func (r *class) validate(ctx context.Context, version *version.Version, client client.Client, req admission.Request, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + ingress, err := FromRequest(req, decoder) + if err != nil { + return utils.ErroredResponse(err) + } - ic, err := r.retrieveIngressClass(ctx, client, ingress.IngressClass()) - if err != nil { - response := admission.Errored(http.StatusInternalServerError, err) + var tnt *capsulev1beta2.Tenant - return &response - } + tnt, err = TenantFromIngress(ctx, client, ingress) + if err != nil { + return utils.ErroredResponse(err) + } - if err = r.validateClass(*tenant, ingress.IngressClass(), ic); err == nil { - return nil - } + if tnt == nil { + return nil + } - var forbiddenErr *ingressClassForbiddenError + allowed := tnt.Spec.IngressOptions.AllowedClasses - if errors.As(err, &forbiddenErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressClassForbidden", "Ingress %s/%s class is forbidden", ingress.Namespace(), ingress.Name()) - } + if allowed == nil { + return nil + } - var invalidErr *ingressClassNotValidError + ingressClass := ingress.IngressClass() - if errors.As(err, &invalidErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressClassNotValid", "Ingress %s/%s class is invalid", ingress.Namespace(), ingress.Name()) - } + if ingressClass == nil { + recorder.Eventf(tnt, corev1.EventTypeWarning, "MissingIngressClass", "Ingress %s/%s is missing IngressClass", req.Namespace, req.Name) - response := admission.Denied(err.Error()) + response := admission.Denied(NewIngressClassUndefined(*allowed).Error()) return &response } -} - -// nolint:dupl -func (r *class) OnUpdate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { - return func(ctx context.Context, req admission.Request) *admission.Response { - ingress, err := ingressFromRequest(req, decoder) - if err != nil { - return utils.ErroredResponse(err) - } - var tenant *capsulev1beta2.Tenant + selector := false - tenant, err = tenantFromIngress(ctx, client, ingress) - if err != nil { - return utils.ErroredResponse(err) - } - - if tenant == nil { - return nil - } - - ic, err := r.retrieveIngressClass(ctx, client, ingress.IngressClass()) - if err != nil { + // Verify if the IngressClass exists and matches the label selector/expression + if len(allowed.MatchExpressions) > 0 || len(allowed.MatchLabels) > 0 { + ingressClassObj, err := utils.GetIngressClassByName(ctx, version, client, ingressClass) + if err != nil && !k8serrors.IsNotFound(err) { response := admission.Errored(http.StatusInternalServerError, err) return &response } - if err = r.validateClass(*tenant, ingress.IngressClass(), ic); err == nil { - return nil + // Ingress Class is present, check if it matches the selector + if ingressClassObj != nil { + selector = allowed.SelectorMatch(ingressClassObj) } - - var forbiddenErr *ingressClassForbiddenError - - if errors.As(err, &forbiddenErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressClassForbidden", "Ingress %s/%s class is forbidden", ingress.Namespace(), ingress.Name()) - } - - var invalidErr *ingressClassNotValidError - - if errors.As(err, &invalidErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressClassNotValid", "Ingress %s/%s class is invalid", ingress.Namespace(), ingress.Name()) - } - - response := admission.Denied(err.Error()) - - return &response } -} -func (r *class) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { - return func(ctx context.Context, req admission.Request) *admission.Response { + switch { + case allowed.MatchDefault(*ingressClass): return nil - } -} - -func (r *class) validateClass(tenant capsulev1beta2.Tenant, ingressClass *string, ingressClassObj client.Object) error { - if tenant.Spec.IngressOptions.AllowedClasses == nil { + case allowed.Match(*ingressClass) || selector: return nil - } - - if ingressClass == nil { - return NewIngressClassNotValid(*tenant.Spec.IngressOptions.AllowedClasses) - } - - var valid, regex, match bool - - if len(tenant.Spec.IngressOptions.AllowedClasses.Exact) > 0 { - valid = tenant.Spec.IngressOptions.AllowedClasses.ExactMatch(*ingressClass) - } - - regex = tenant.Spec.IngressOptions.AllowedClasses.RegexMatch(*ingressClass) + default: + recorder.Eventf(tnt, corev1.EventTypeWarning, "ForbiddenIngressClass", "Ingress %s/%s IngressClass %s is forbidden for the current Tenant", req.Namespace, req.Name, &ingressClass) - if ingressClassObj != nil { - match = tenant.Spec.IngressOptions.AllowedClasses.SelectorMatch(ingressClassObj) - } else { - match = true - } + response := admission.Denied(NewIngressClassForbidden(*ingressClass, *allowed).Error()) - if !valid && !regex && !match { - return NewIngressClassForbidden(*ingressClass, *tenant.Spec.IngressOptions.AllowedClasses) + return &response } - - return nil } diff --git a/pkg/webhook/ingress/validate_collision.go b/pkg/webhook/ingress/validate_collision.go index dd9a73b6..8f286a35 100644 --- a/pkg/webhook/ingress/validate_collision.go +++ b/pkg/webhook/ingress/validate_collision.go @@ -34,80 +34,54 @@ func Collision(configuration configuration.Configuration) capsulewebhook.Handler return &collision{configuration: configuration} } -// nolint:dupl func (r *collision) OnCreate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - ing, err := ingressFromRequest(req, decoder) - if err != nil { - return utils.ErroredResponse(err) - } - - var tenant *capsulev1beta2.Tenant - - tenant, err = tenantFromIngress(ctx, client, ing) - if err != nil { - return utils.ErroredResponse(err) - } - - if tenant == nil || tenant.Spec.IngressOptions.HostnameCollisionScope == api.HostnameCollisionScopeDisabled { - return nil - } - - if err = r.validateCollision(ctx, client, ing, tenant.Spec.IngressOptions.HostnameCollisionScope); err == nil { - return nil - } - - var collisionErr *ingressHostnameCollisionError - - if errors.As(err, &collisionErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressHostnameCollision", "Ingress %s/%s hostname is colliding", ing.Namespace(), ing.Name()) - } - - response := admission.Denied(err.Error()) - - return &response + return r.validate(ctx, client, req, decoder, recorder) } } -// nolint:dupl func (r *collision) OnUpdate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - ing, err := ingressFromRequest(req, decoder) - if err != nil { - return utils.ErroredResponse(err) - } + return r.validate(ctx, client, req, decoder, recorder) + } +} - var tenant *capsulev1beta2.Tenant +func (r *collision) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return nil + } +} - tenant, err = tenantFromIngress(ctx, client, ing) - if err != nil { - return utils.ErroredResponse(err) - } +func (r *collision) validate(ctx context.Context, client client.Client, req admission.Request, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + ing, err := FromRequest(req, decoder) + if err != nil { + return utils.ErroredResponse(err) + } - if tenant == nil || tenant.Spec.IngressOptions.HostnameCollisionScope == api.HostnameCollisionScopeDisabled { - return nil - } + var tenant *capsulev1beta2.Tenant - if err = r.validateCollision(ctx, client, ing, tenant.Spec.IngressOptions.HostnameCollisionScope); err == nil { - return nil - } + tenant, err = TenantFromIngress(ctx, client, ing) + if err != nil { + return utils.ErroredResponse(err) + } - var collisionErr *ingressHostnameCollisionError + if tenant == nil || tenant.Spec.IngressOptions.HostnameCollisionScope == api.HostnameCollisionScopeDisabled { + return nil + } - if errors.As(err, &collisionErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressHostnameCollision", "Ingress %s/%s hostname is colliding", ing.Namespace(), ing.Name()) - } + if err = r.validateCollision(ctx, client, ing, tenant.Spec.IngressOptions.HostnameCollisionScope); err == nil { + return nil + } - response := admission.Denied(err.Error()) + var collisionErr *ingressHostnameCollisionError - return &response + if errors.As(err, &collisionErr) { + recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressHostnameCollision", "Ingress %s/%s hostname is colliding", ing.Namespace(), ing.Name()) } -} -func (r *collision) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { - return func(ctx context.Context, req admission.Request) *admission.Response { - return nil - } + response := admission.Denied(err.Error()) + + return &response } // nolint:gocognit,gocyclo,cyclop diff --git a/pkg/webhook/ingress/validate_hostnames.go b/pkg/webhook/ingress/validate_hostnames.go index 84c69af5..c854953e 100644 --- a/pkg/webhook/ingress/validate_hostnames.go +++ b/pkg/webhook/ingress/validate_hostnames.go @@ -30,90 +30,59 @@ func Hostnames(configuration configuration.Configuration) capsulewebhook.Handler func (r *hostnames) OnCreate(c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - ingress, err := ingressFromRequest(req, decoder) - if err != nil { - return utils.ErroredResponse(err) - } - - var tenant *capsulev1beta2.Tenant - - tenant, err = tenantFromIngress(ctx, c, ingress) - if err != nil { - return utils.ErroredResponse(err) - } - - if tenant == nil || tenant.Spec.IngressOptions.AllowedHostnames == nil { - return nil - } - - hostnameList := sets.NewString() - for hostname := range ingress.HostnamePathsPairs() { - hostnameList.Insert(hostname) - } - - if err = r.validateHostnames(*tenant, hostnameList); err == nil { - return nil - } - - var hostnameNotValidErr *ingressHostnameNotValidError - - if errors.As(err, &hostnameNotValidErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressHostnameNotValid", "Ingress %s/%s hostname is not valid", ingress.Namespace(), ingress.Name()) - - response := admission.Denied(err.Error()) - - return &response - } - - return utils.ErroredResponse(err) + return r.validate(ctx, c, req, decoder, recorder) } } func (r *hostnames) OnUpdate(c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - ingress, err := ingressFromRequest(req, decoder) - if err != nil { - return utils.ErroredResponse(err) - } + return r.validate(ctx, c, req, decoder, recorder) + } +} + +func (r *hostnames) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { + return func(ctx context.Context, req admission.Request) *admission.Response { + return nil + } +} - var tenant *capsulev1beta2.Tenant +func (r *hostnames) validate(ctx context.Context, client client.Client, req admission.Request, decoder *admission.Decoder, recorder record.EventRecorder) *admission.Response { + ingress, err := FromRequest(req, decoder) + if err != nil { + return utils.ErroredResponse(err) + } - tenant, err = tenantFromIngress(ctx, c, ingress) - if err != nil { - return utils.ErroredResponse(err) - } + var tenant *capsulev1beta2.Tenant - if tenant == nil { - return nil - } + tenant, err = TenantFromIngress(ctx, client, ingress) + if err != nil { + return utils.ErroredResponse(err) + } - hostnameSet := sets.NewString() - for hostname := range ingress.HostnamePathsPairs() { - hostnameSet.Insert(hostname) - } + if tenant == nil || tenant.Spec.IngressOptions.AllowedHostnames == nil { + return nil + } - if err = r.validateHostnames(*tenant, hostnameSet); err == nil { - return nil - } + hostnameList := sets.NewString() + for hostname := range ingress.HostnamePathsPairs() { + hostnameList.Insert(hostname) + } - var hostnameNotValidErr *ingressHostnameNotValidError + if err = r.validateHostnames(*tenant, hostnameList); err == nil { + return nil + } - if errors.As(err, &hostnameNotValidErr) { - recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressHostnameNotValid", "Ingress %s/%s hostname is not valid", ingress.Namespace(), ingress.Name()) + var hostnameNotValidErr *ingressHostnameNotValidError - response := admission.Denied(err.Error()) + if errors.As(err, &hostnameNotValidErr) { + recorder.Eventf(tenant, corev1.EventTypeWarning, "IngressHostnameNotValid", "Ingress %s/%s hostname is not valid", ingress.Namespace(), ingress.Name()) - return &response - } + response := admission.Denied(err.Error()) - return utils.ErroredResponse(err) + return &response } -} -func (r *hostnames) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func { - return func(ctx context.Context, req admission.Request) *admission.Response { - return nil - } + return utils.ErroredResponse(err) } func (r *hostnames) validateHostnames(tenant capsulev1beta2.Tenant, hostnames sets.String) error { diff --git a/pkg/webhook/ingress/validate_wildcard.go b/pkg/webhook/ingress/validate_wildcard.go index 1cc9a4a3..c4c8a132 100644 --- a/pkg/webhook/ingress/validate_wildcard.go +++ b/pkg/webhook/ingress/validate_wildcard.go @@ -27,7 +27,7 @@ func Wildcard() capsulewebhook.Handler { func (h *wildcard) OnCreate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - return h.wildcardHandler(ctx, client, req, recorder, decoder) + return h.validate(ctx, client, req, recorder, decoder) } } @@ -39,11 +39,11 @@ func (h *wildcard) OnDelete(client client.Client, decoder *admission.Decoder, re func (h *wildcard) OnUpdate(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { - return h.wildcardHandler(ctx, client, req, recorder, decoder) + return h.validate(ctx, client, req, recorder, decoder) } } -func (h *wildcard) wildcardHandler(ctx context.Context, clt client.Client, req admission.Request, recorder record.EventRecorder, decoder *admission.Decoder) *admission.Response { +func (h *wildcard) validate(ctx context.Context, clt client.Client, req admission.Request, recorder record.EventRecorder, decoder *admission.Decoder) *admission.Response { tntList := &capsulev1beta2.TenantList{} if err := clt.List(ctx, tntList, client.MatchingFieldsSelector{ @@ -61,7 +61,7 @@ func (h *wildcard) wildcardHandler(ctx context.Context, clt client.Client, req a if !tnt.Spec.IngressOptions.AllowWildcardHostnames { // Retrieve ingress resource from request. - ingress, err := ingressFromRequest(req, decoder) + ingress, err := FromRequest(req, decoder) if err != nil { return utils.ErroredResponse(err) } diff --git a/pkg/webhook/pod/priorityclass.go b/pkg/webhook/pod/priorityclass.go index f431b900..d56ceb95 100644 --- a/pkg/webhook/pod/priorityclass.go +++ b/pkg/webhook/pod/priorityclass.go @@ -10,13 +10,11 @@ import ( corev1 "k8s.io/api/core/v1" schedulingv1 "k8s.io/api/scheduling/v1" "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" capsulewebhook "github.com/clastix/capsule/pkg/webhook" "github.com/clastix/capsule/pkg/webhook/utils" ) @@ -52,44 +50,57 @@ func (h *priorityClass) OnCreate(c client.Client, decoder *admission.Decoder, re return utils.ErroredResponse(err) } - tntList := &capsulev1beta2.TenantList{} - - if err := c.List(ctx, tntList, client.MatchingFieldsSelector{ - Selector: fields.OneTermEqualSelector(".status.namespaces", pod.Namespace), - }); err != nil { + tnt, err := utils.TenantByStatusNamespace(ctx, c, pod.Namespace) + if err != nil { return utils.ErroredResponse(err) } - if len(tntList.Items) == 0 { + if tnt == nil { return nil } - allowed := tntList.Items[0].Spec.PriorityClasses + allowed := tnt.Spec.PriorityClasses + + if allowed == nil { + return nil + } priorityClassName := pod.Spec.PriorityClassName - class, err := h.class(ctx, c, priorityClassName) - if err != nil { - response := admission.Errored(http.StatusInternalServerError, err) + if len(priorityClassName) == 0 { + // We don't have to force Pod to specify a Priority Class + return nil + } - return &response + selector := false + + // Verify if the StorageClass exists and matches the label selector/expression + if len(allowed.MatchExpressions) > 0 || len(allowed.MatchLabels) > 0 { + priorityClassObj, err := utils.GetPriorityClassByName(ctx, c, priorityClassName) + if err != nil { + response := admission.Errored(http.StatusInternalServerError, err) + + return &response + } + + // Storage Class is present, check if it matches the selector + if priorityClassObj != nil { + selector = allowed.SelectorMatch(priorityClassObj) + } } switch { - case allowed == nil: - // Enforcement is not in place, skipping it at all + case allowed.MatchDefault(priorityClassName): + // Allow if given Priority Class is equal tenant default (eventough it's not allowed by selector) return nil - case len(priorityClassName) == 0: - // We don't have to force Pod to specify a Priority Class + case allowed.Match(priorityClassName) || selector: return nil - case !allowed.ExactMatch(priorityClassName) && !allowed.RegexMatch(priorityClassName) && !allowed.SelectorMatch(class): - recorder.Eventf(&tntList.Items[0], corev1.EventTypeWarning, "ForbiddenPriorityClass", "Pod %s/%s is using Priority Class %s is forbidden for the current Tenant", pod.Namespace, pod.Name, priorityClassName) + default: + recorder.Eventf(tnt, corev1.EventTypeWarning, "ForbiddenPriorityClass", "Pod %s/%s is using Priority Class %s is forbidden for the current Tenant", pod.Namespace, pod.Name, priorityClassName) response := admission.Denied(NewPodPriorityClassForbidden(priorityClassName, *allowed).Error()) return &response - default: - return nil } } } diff --git a/pkg/webhook/pod/priorityclass_errors.go b/pkg/webhook/pod/priorityclass_errors.go index 64f2cf12..9198d598 100644 --- a/pkg/webhook/pod/priorityclass_errors.go +++ b/pkg/webhook/pod/priorityclass_errors.go @@ -12,10 +12,10 @@ import ( type podPriorityClassForbiddenError struct { priorityClassName string - spec api.SelectorAllowedListSpec + spec api.DefaultAllowedListSpec } -func NewPodPriorityClassForbidden(priorityClassName string, spec api.SelectorAllowedListSpec) error { +func NewPodPriorityClassForbidden(priorityClassName string, spec api.DefaultAllowedListSpec) error { return &podPriorityClassForbiddenError{ priorityClassName: priorityClassName, spec: spec, @@ -23,7 +23,7 @@ func NewPodPriorityClassForbidden(priorityClassName string, spec api.SelectorAll } func (f podPriorityClassForbiddenError) Error() (err string) { - err = fmt.Sprintf("Pod Priorioty Class %s is forbidden for the current Tenant: ", f.priorityClassName) + msg := fmt.Sprintf("Pod Priority Class %s is forbidden for the current Tenant: ", f.priorityClassName) - return utils.AllowedValuesErrorMessage(f.spec, err) + return utils.DefaultAllowedValuesErrorMessage(f.spec, msg) } diff --git a/pkg/webhook/pod/runtimeclass.go b/pkg/webhook/pod/runtimeclass.go index 0de42591..08d539c0 100644 --- a/pkg/webhook/pod/runtimeclass.go +++ b/pkg/webhook/pod/runtimeclass.go @@ -9,13 +9,11 @@ import ( corev1 "k8s.io/api/core/v1" nodev1 "k8s.io/api/node/v1" - "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" capsulewebhook "github.com/clastix/capsule/pkg/webhook" "github.com/clastix/capsule/pkg/webhook/utils" ) @@ -63,19 +61,16 @@ func (h *runtimeClass) validate(ctx context.Context, c client.Client, decoder *a return utils.ErroredResponse(err) } - tntList := &capsulev1beta2.TenantList{} - - if err := c.List(ctx, tntList, client.MatchingFieldsSelector{ - Selector: fields.OneTermEqualSelector(".status.namespaces", pod.Namespace), - }); err != nil { + tnt, err := utils.TenantByStatusNamespace(ctx, c, pod.Namespace) + if err != nil { return utils.ErroredResponse(err) } - if len(tntList.Items) == 0 { + if tnt == nil { return nil } - allowed := tntList.Items[0].Spec.RuntimeClasses + allowed := tnt.Spec.RuntimeClasses runtimeClassName := "" if pod.Spec.RuntimeClassName != nil { @@ -96,8 +91,8 @@ func (h *runtimeClass) validate(ctx context.Context, c client.Client, decoder *a case len(runtimeClassName) == 0: // We don't have to force Pod to specify a RuntimeClass return nil - case !allowed.ExactMatch(runtimeClassName) && !allowed.RegexMatch(runtimeClassName) && !allowed.SelectorMatch(class): - recorder.Eventf(&tntList.Items[0], corev1.EventTypeWarning, "ForbiddenRuntimeClass", "Pod %s/%s is using Runtime Class %s is forbidden for the current Tenant", pod.Namespace, pod.Name, runtimeClassName) + case !allowed.MatchSelectByName(class): + recorder.Eventf(tnt, corev1.EventTypeWarning, "ForbiddenRuntimeClass", "Pod %s/%s is using Runtime Class %s is forbidden for the current Tenant", pod.Namespace, pod.Name, runtimeClassName) response := admission.Denied(NewPodRuntimeClassForbidden(runtimeClassName, *allowed).Error()) diff --git a/pkg/webhook/pvc/errors.go b/pkg/webhook/pvc/errors.go index 54660f39..f02789ae 100644 --- a/pkg/webhook/pvc/errors.go +++ b/pkg/webhook/pvc/errors.go @@ -5,48 +5,33 @@ package pvc import ( "fmt" - "strings" "github.com/clastix/capsule/pkg/api" + "github.com/clastix/capsule/pkg/webhook/utils" ) type storageClassNotValidError struct { - spec api.SelectorAllowedListSpec + spec api.DefaultAllowedListSpec } -func NewStorageClassNotValid(storageClasses api.SelectorAllowedListSpec) error { +func NewStorageClassNotValid(storageClasses api.DefaultAllowedListSpec) error { return &storageClassNotValidError{ spec: storageClasses, } } -// nolint:predeclared -func appendError(spec api.SelectorAllowedListSpec) (append string) { - if len(spec.Exact) > 0 { - append += fmt.Sprintf(", one of the following (%s)", strings.Join(spec.Exact, ", ")) - } - - if len(spec.Regex) > 0 { - append += fmt.Sprintf(", or matching the regex %s", spec.Regex) - } - - if len(spec.MatchLabels) > 0 || len(spec.MatchExpressions) > 0 { - append += ", or matching the label selector defined in the Tenant" - } - - return -} - func (s storageClassNotValidError) Error() (err string) { - return "A valid Storage Class must be used" + appendError(s.spec) + msg := "A valid Storage Class must be used: " + + return utils.DefaultAllowedValuesErrorMessage(s.spec, msg) } type storageClassForbiddenError struct { className string - spec api.SelectorAllowedListSpec + spec api.DefaultAllowedListSpec } -func NewStorageClassForbidden(className string, storageClasses api.SelectorAllowedListSpec) error { +func NewStorageClassForbidden(className string, storageClasses api.DefaultAllowedListSpec) error { return &storageClassForbiddenError{ className: className, spec: storageClasses, @@ -54,5 +39,7 @@ func NewStorageClassForbidden(className string, storageClasses api.SelectorAllow } func (f storageClassForbiddenError) Error() string { - return fmt.Sprintf("Storage Class %s is forbidden for the current Tenant%s", f.className, appendError(f.spec)) + msg := fmt.Sprintf("Storage Class %s is forbidden for the current Tenant ", f.className) + + return utils.DefaultAllowedValuesErrorMessage(f.spec, msg) } diff --git a/pkg/webhook/pvc/validating.go b/pkg/webhook/pvc/validating.go index 4014c949..52d2dc70 100644 --- a/pkg/webhook/pvc/validating.go +++ b/pkg/webhook/pvc/validating.go @@ -8,15 +8,11 @@ import ( "net/http" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/api/storage/v1" "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" capsulewebhook "github.com/clastix/capsule/pkg/webhook" "github.com/clastix/capsule/pkg/webhook/utils" ) @@ -27,20 +23,6 @@ func Handler() capsulewebhook.Handler { return &handler{} } -func (h *handler) getStorageClass(ctx context.Context, c client.Client, name string) (client.Object, error) { - obj := &v1.StorageClass{} - - if err := c.Get(ctx, types.NamespacedName{Name: name}, obj); err != nil { - if errors.IsNotFound(err) { - return nil, nil - } - - return nil, err - } - - return obj, nil -} - func (h *handler) OnCreate(c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func { return func(ctx context.Context, req admission.Request) *admission.Response { pvc := &corev1.PersistentVolumeClaim{} @@ -48,59 +30,60 @@ func (h *handler) OnCreate(c client.Client, decoder *admission.Decoder, recorder return utils.ErroredResponse(err) } - tntList := &capsulev1beta2.TenantList{} - if err := c.List(ctx, tntList, client.MatchingFieldsSelector{ - Selector: fields.OneTermEqualSelector(".status.namespaces", pvc.Namespace), - }); err != nil { + tnt, err := utils.TenantByStatusNamespace(ctx, c, pvc.Namespace) + if err != nil { return utils.ErroredResponse(err) } - if len(tntList.Items) == 0 { + if tnt == nil { return nil } - tnt := tntList.Items[0] + allowed := tnt.Spec.StorageClasses - if tnt.Spec.StorageClasses == nil { + if allowed == nil { return nil } - if pvc.Spec.StorageClassName == nil { - recorder.Eventf(&tnt, corev1.EventTypeWarning, "MissingStorageClass", "PersistentVolumeClaim %s/%s is missing StorageClass", req.Namespace, req.Name) - - response := admission.Denied(NewStorageClassNotValid(*tntList.Items[0].Spec.StorageClasses).Error()) + storageClass := pvc.Spec.StorageClassName - return &response - } + if storageClass == nil { + recorder.Eventf(tnt, corev1.EventTypeWarning, "MissingStorageClass", "PersistentVolumeClaim %s/%s is missing StorageClass", req.Namespace, req.Name) - sc := *pvc.Spec.StorageClassName - - scObj, err := h.getStorageClass(ctx, c, sc) - if err != nil { - response := admission.Errored(http.StatusInternalServerError, err) + response := admission.Denied(NewStorageClassNotValid(*tnt.Spec.StorageClasses).Error()) return &response } - var valid, regex, match bool + selector := false + + // Verify if the StorageClass exists and matches the label selector/expression + if len(allowed.MatchExpressions) > 0 || len(allowed.MatchLabels) > 0 { + storageClassObj, err := utils.GetStorageClassByName(ctx, c, *storageClass) + if err != nil && !errors.IsNotFound(err) { + response := admission.Errored(http.StatusInternalServerError, err) - valid, regex = tnt.Spec.StorageClasses.ExactMatch(sc), tnt.Spec.StorageClasses.RegexMatch(sc) + return &response + } - if scObj != nil { - match = tnt.Spec.StorageClasses.SelectorMatch(scObj) - } else { - match = true + // Storage Class is present, check if it matches the selector + if storageClassObj != nil { + selector = allowed.SelectorMatch(storageClassObj) + } } - if !valid && !regex && !match { - recorder.Eventf(&tnt, corev1.EventTypeWarning, "ForbiddenStorageClass", "PersistentVolumeClaim %s/%s StorageClass %s is forbidden for the current Tenant", req.Namespace, req.Name, sc) + switch { + case allowed.MatchDefault(*storageClass): + return nil + case allowed.Match(*storageClass) || selector: + return nil + default: + recorder.Eventf(tnt, corev1.EventTypeWarning, "ForbiddenStorageClass", "PersistentVolumeClaim %s/%s StorageClass %s is forbidden for the current Tenant", req.Namespace, req.Name, *storageClass) response := admission.Denied(NewStorageClassForbidden(*pvc.Spec.StorageClassName, *tnt.Spec.StorageClasses).Error()) return &response } - - return nil } } diff --git a/pkg/webhook/route/defaults.go b/pkg/webhook/route/defaults.go new file mode 100644 index 00000000..b42ca895 --- /dev/null +++ b/pkg/webhook/route/defaults.go @@ -0,0 +1,28 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package route + +import ( + capsulewebhook "github.com/clastix/capsule/pkg/webhook" +) + +// +kubebuilder:webhook:path=/defaults,mutating=true,sideEffects=None,admissionReviewVersions=v1,failurePolicy=fail,groups="",resources=pods,verbs=create,versions=v1,name=pod.defaults.capsule.clastix.io +// +kubebuilder:webhook:path=/defaults,mutating=true,sideEffects=None,admissionReviewVersions=v1,failurePolicy=fail,groups="",resources=persistentvolumeclaims,verbs=create,versions=v1,name=storage.defaults.capsule.clastix.io +// +kubebuilder:webhook:path=/defaults,mutating=true,sideEffects=None,admissionReviewVersions=v1,failurePolicy=fail,groups=networking.k8s.io,resources=ingresses,verbs=create;update,versions=v1beta1;v1,name=ingress.defaults.capsule.clastix.io + +type defaults struct { + handlers []capsulewebhook.Handler +} + +func Defaults(handler ...capsulewebhook.Handler) capsulewebhook.Webhook { + return &defaults{handlers: handler} +} + +func (w *defaults) GetHandlers() []capsulewebhook.Handler { + return w.handlers +} + +func (w *defaults) GetPath() string { + return "/defaults" +} diff --git a/pkg/webhook/utils/error.go b/pkg/webhook/utils/error.go index 24a34799..fe137ee9 100644 --- a/pkg/webhook/utils/error.go +++ b/pkg/webhook/utils/error.go @@ -19,6 +19,10 @@ func ErroredResponse(err error) *admission.Response { return &response } +func DefaultAllowedValuesErrorMessage(allowed api.DefaultAllowedListSpec, err string) string { + return AllowedValuesErrorMessage(allowed.SelectorAllowedListSpec, err) +} + func AllowedValuesErrorMessage(allowed api.SelectorAllowedListSpec, err string) string { var extra []string if len(allowed.Exact) > 0 { @@ -26,11 +30,11 @@ func AllowedValuesErrorMessage(allowed api.SelectorAllowedListSpec, err string) } if len(allowed.Regex) > 0 { - extra = append(extra, fmt.Sprintf(" use one matching the following regex (%s)", allowed.Regex)) + extra = append(extra, fmt.Sprintf("use one matching the following regex (%s)", allowed.Regex)) } if len(allowed.MatchLabels) > 0 || len(allowed.MatchExpressions) > 0 { - extra = append(extra, ", or matching the label selector defined in the Tenant") + extra = append(extra, "matching the label selector defined in the Tenant") } err += strings.Join(extra, " or ") diff --git a/pkg/webhook/utils/resources.go b/pkg/webhook/utils/resources.go new file mode 100644 index 00000000..d729a0e9 --- /dev/null +++ b/pkg/webhook/utils/resources.go @@ -0,0 +1,100 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package utils + +import ( + "context" + + networkingv1 "k8s.io/api/networking/v1" + networkingv1beta1 "k8s.io/api/networking/v1beta1" + schedulev1 "k8s.io/api/scheduling/v1" + storagev1 "k8s.io/api/storage/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/version" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const TRUE string = "true" + +// Get PriorityClass by name (Does not return error if not found). +func GetPriorityClassByName(ctx context.Context, c client.Client, name string) (*schedulev1.PriorityClass, error) { + class := &schedulev1.PriorityClass{} + if err := c.Get(ctx, types.NamespacedName{Name: name}, class); err != nil { + return nil, err + } + + return class, nil +} + +// Get StorageClass by name (Does not return error if not found). +func GetStorageClassByName(ctx context.Context, c client.Client, name string) (*storagev1.StorageClass, error) { + class := &storagev1.StorageClass{} + if err := c.Get(ctx, types.NamespacedName{Name: name}, class); err != nil { + return nil, err + } + + return class, nil +} + +// Get IngressClass by name (Does not return error if not found). +func GetIngressClassByName(ctx context.Context, version *version.Version, c client.Client, ingressClassName *string) (client.Object, error) { + if ingressClassName == nil { + return nil, nil + } + + var obj client.Object + + switch { + case version == nil: + obj = &networkingv1.IngressClass{} + case version.Minor() < 18: + return nil, nil + case version.Minor() < 19: + obj = &networkingv1beta1.IngressClass{} + default: + obj = &networkingv1.IngressClass{} + } + + if err := c.Get(ctx, types.NamespacedName{Name: *ingressClassName}, obj); err != nil { + return nil, err + } + + return obj, nil +} + +// IsDefaultPriorityClass checks if the given PriorityClass is cluster default. +func IsDefaultPriorityClass(class *schedulev1.PriorityClass) bool { + if class != nil { + return class.GlobalDefault + } + + return false +} + +func IsDefaultIngressClass(class client.Object) bool { + annotation := "ingressclass.kubernetes.io/is-default-class" + + if class != nil { + annotations := class.GetAnnotations() + if v, ok := annotations[annotation]; ok && v == TRUE { + return true + } + } + + return false +} + +// IsDefaultStorageClass checks if the given StorageClass is cluster default. +func IsDefaultStorageClass(class client.Object) bool { + annotation := "storageclass.kubernetes.io/is-default-class" + + if class != nil { + annotations := class.GetAnnotations() + if v, ok := annotations[annotation]; ok && v == TRUE { + return true + } + } + + return false +} diff --git a/pkg/webhook/utils/tenant_by_field.go b/pkg/webhook/utils/tenant_by_field.go new file mode 100644 index 00000000..3c9af276 --- /dev/null +++ b/pkg/webhook/utils/tenant_by_field.go @@ -0,0 +1,32 @@ +// Copyright 2020-2021 Clastix Labs +// SPDX-License-Identifier: Apache-2.0 + +package utils + +import ( + "context" + + "k8s.io/apimachinery/pkg/fields" + "sigs.k8s.io/controller-runtime/pkg/client" + + capsulev1beta2 "github.com/clastix/capsule/api/v1beta2" +) + +func TenantByStatusNamespace(ctx context.Context, c client.Client, namespace string) (*capsulev1beta2.Tenant, error) { + tntList := &capsulev1beta2.TenantList{} + tnt := &capsulev1beta2.Tenant{} + + if err := c.List(ctx, tntList, client.MatchingFieldsSelector{ + Selector: fields.OneTermEqualSelector(".status.namespaces", namespace), + }); err != nil { + return nil, err + } + + if len(tntList.Items) == 0 { + return tnt, nil + } + + *tnt = tntList.Items[0] + + return tnt, nil +}