1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package apiextensions
18
19import (
20	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
21)
22
23// ConversionStrategyType describes different conversion types.
24type ConversionStrategyType string
25
26const (
27	// NoneConverter is a converter that only sets apiversion of the CR and leave everything else unchanged.
28	NoneConverter ConversionStrategyType = "None"
29	// WebhookConverter is a converter that calls to an external webhook to convert the CR.
30	WebhookConverter ConversionStrategyType = "Webhook"
31)
32
33// CustomResourceDefinitionSpec describes how a user wants their resource to appear
34type CustomResourceDefinitionSpec struct {
35	// Group is the group this resource belongs in
36	Group string
37	// Version is the version this resource belongs in
38	// Should be always first item in Versions field if provided.
39	// Optional, but at least one of Version or Versions must be set.
40	// Deprecated: Please use `Versions`.
41	Version string
42	// Names are the names used to describe this custom resource
43	Names CustomResourceDefinitionNames
44	// Scope indicates whether this resource is cluster or namespace scoped.  Default is namespaced
45	Scope ResourceScope
46	// Validation describes the validation methods for CustomResources
47	// Optional, the global validation schema for all versions.
48	// Top-level and per-version schemas are mutually exclusive.
49	// +optional
50	Validation *CustomResourceValidation
51	// Subresources describes the subresources for CustomResource
52	// Optional, the global subresources for all versions.
53	// Top-level and per-version subresources are mutually exclusive.
54	// +optional
55	Subresources *CustomResourceSubresources
56	// Versions is the list of all supported versions for this resource.
57	// If Version field is provided, this field is optional.
58	// Validation: All versions must use the same validation schema for now. i.e., top
59	// level Validation field is applied to all of these versions.
60	// Order: The version name will be used to compute the order.
61	// If the version string is "kube-like", it will sort above non "kube-like" version strings, which are ordered
62	// lexicographically. "Kube-like" versions start with a "v", then are followed by a number (the major version),
63	// then optionally the string "alpha" or "beta" and another number (the minor version). These are sorted first
64	// by GA > beta > alpha (where GA is a version with no suffix such as beta or alpha), and then by comparing
65	// major version, then minor version. An example sorted list of versions:
66	// v10, v2, v1, v11beta2, v10beta3, v3beta1, v12alpha1, v11alpha2, foo1, foo10.
67	Versions []CustomResourceDefinitionVersion
68	// AdditionalPrinterColumns are additional columns shown e.g. in kubectl next to the name. Defaults to a created-at column.
69	// Optional, the global columns for all versions.
70	// Top-level and per-version columns are mutually exclusive.
71	// +optional
72	AdditionalPrinterColumns []CustomResourceColumnDefinition
73
74	// `conversion` defines conversion settings for the CRD.
75	Conversion *CustomResourceConversion
76
77	// preserveUnknownFields disables pruning of object fields which are not
78	// specified in the OpenAPI schema. apiVersion, kind, metadata and known
79	// fields inside metadata are always preserved.
80	// Defaults to true in v1beta and will default to false in v1.
81	PreserveUnknownFields *bool
82}
83
84// CustomResourceConversion describes how to convert different versions of a CR.
85type CustomResourceConversion struct {
86	// `strategy` specifies the conversion strategy. Allowed values are:
87	// - `None`: The converter only change the apiVersion and would not touch any other field in the CR.
88	// - `Webhook`: API Server will call to an external webhook to do the conversion. Additional information
89	//   is needed for this option. This requires spec.preserveUnknownFields to be false.
90	Strategy ConversionStrategyType
91
92	// `webhookClientConfig` is the instructions for how to call the webhook if strategy is `Webhook`.
93	WebhookClientConfig *WebhookClientConfig
94
95	// ConversionReviewVersions is an ordered list of preferred `ConversionReview`
96	// versions the Webhook expects. API server will try to use first version in
97	// the list which it supports. If none of the versions specified in this list
98	// supported by API server, conversion will fail for this object.
99	// If a persisted Webhook configuration specifies allowed versions and does not
100	// include any versions known to the API Server, calls to the webhook will fail.
101	// +optional
102	ConversionReviewVersions []string
103}
104
105// WebhookClientConfig contains the information to make a TLS
106// connection with the webhook. It has the same field as admissionregistration.internal.WebhookClientConfig.
107type WebhookClientConfig struct {
108	// `url` gives the location of the webhook, in standard URL form
109	// (`scheme://host:port/path`). Exactly one of `url` or `service`
110	// must be specified.
111	//
112	// The `host` should not refer to a service running in the cluster; use
113	// the `service` field instead. The host might be resolved via external
114	// DNS in some apiservers (e.g., `kube-apiserver` cannot resolve
115	// in-cluster DNS as that would be a layering violation). `host` may
116	// also be an IP address.
117	//
118	// Please note that using `localhost` or `127.0.0.1` as a `host` is
119	// risky unless you take great care to run this webhook on all hosts
120	// which run an apiserver which might need to make calls to this
121	// webhook. Such installs are likely to be non-portable, i.e., not easy
122	// to turn up in a new cluster.
123	//
124	// The scheme must be "https"; the URL must begin with "https://".
125	//
126	// A path is optional, and if present may be any string permissible in
127	// a URL. You may use the path to pass an arbitrary string to the
128	// webhook, for example, a cluster identifier.
129	//
130	// Attempting to use a user or basic auth e.g. "user:password@" is not
131	// allowed. Fragments ("#...") and query parameters ("?...") are not
132	// allowed, either.
133	//
134	// +optional
135	URL *string
136
137	// `service` is a reference to the service for this webhook. Either
138	// `service` or `url` must be specified.
139	//
140	// If the webhook is running within the cluster, then you should use `service`.
141	//
142	// +optional
143	Service *ServiceReference
144
145	// `caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate.
146	// If unspecified, system trust roots on the apiserver are used.
147	// +optional
148	CABundle []byte
149}
150
151// ServiceReference holds a reference to Service.legacy.k8s.io
152type ServiceReference struct {
153	// `namespace` is the namespace of the service.
154	// Required
155	Namespace string
156	// `name` is the name of the service.
157	// Required
158	Name string
159
160	// `path` is an optional URL path which will be sent in any request to
161	// this service.
162	// +optional
163	Path *string
164
165	// If specified, the port on the service that hosting webhook.
166	// `port` should be a valid port number (1-65535, inclusive).
167	// +optional
168	Port int32
169}
170
171// CustomResourceDefinitionVersion describes a version for CRD.
172type CustomResourceDefinitionVersion struct {
173	// Name is the version name, e.g. “v1”, “v2beta1”, etc.
174	Name string
175	// Served is a flag enabling/disabling this version from being served via REST APIs
176	Served bool
177	// Storage flags the version as storage version. There must be exactly one flagged
178	// as storage version.
179	Storage bool
180	// deprecated indicates this version of the custom resource API is deprecated.
181	// When set to true, API requests to this version receive a warning header in the server response.
182	// Defaults to false.
183	Deprecated bool
184	// deprecationWarning overrides the default warning returned to API clients.
185	// May only be set when `deprecated` is true.
186	// The default warning indicates this version is deprecated and recommends use
187	// of the newest served version of equal or greater stability, if one exists.
188	DeprecationWarning *string
189	// Schema describes the schema for CustomResource used in validation, pruning, and defaulting.
190	// Top-level and per-version schemas are mutually exclusive.
191	// Per-version schemas must not all be set to identical values (top-level validation schema should be used instead)
192	// This field is alpha-level and is only honored by servers that enable the CustomResourceWebhookConversion feature.
193	// +optional
194	Schema *CustomResourceValidation
195	// Subresources describes the subresources for CustomResource
196	// Top-level and per-version subresources are mutually exclusive.
197	// Per-version subresources must not all be set to identical values (top-level subresources should be used instead)
198	// This field is alpha-level and is only honored by servers that enable the CustomResourceWebhookConversion feature.
199	// +optional
200	Subresources *CustomResourceSubresources
201	// AdditionalPrinterColumns are additional columns shown e.g. in kubectl next to the name. Defaults to a created-at column.
202	// Top-level and per-version columns are mutually exclusive.
203	// Per-version columns must not all be set to identical values (top-level columns should be used instead)
204	// This field is alpha-level and is only honored by servers that enable the CustomResourceWebhookConversion feature.
205	// NOTE: CRDs created prior to 1.13 populated the top-level additionalPrinterColumns field by default. To apply an
206	// update that changes to per-version additionalPrinterColumns, the top-level additionalPrinterColumns field must
207	// be explicitly set to null
208	// +optional
209	AdditionalPrinterColumns []CustomResourceColumnDefinition
210}
211
212// CustomResourceColumnDefinition specifies a column for server side printing.
213type CustomResourceColumnDefinition struct {
214	// name is a human readable name for the column.
215	Name string
216	// type is an OpenAPI type definition for this column.
217	// See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.
218	Type string
219	// format is an optional OpenAPI type definition for this column. The 'name' format is applied
220	// to the primary identifier column to assist in clients identifying column is the resource name.
221	// See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types for more.
222	Format string
223	// description is a human readable description of this column.
224	Description string
225	// priority is an integer defining the relative importance of this column compared to others. Lower
226	// numbers are considered higher priority. Columns that may be omitted in limited space scenarios
227	// should be given a higher priority.
228	Priority int32
229
230	// JSONPath is a simple JSON path, i.e. without array notation.
231	JSONPath string
232}
233
234// CustomResourceDefinitionNames indicates the names to serve this CustomResourceDefinition
235type CustomResourceDefinitionNames struct {
236	// Plural is the plural name of the resource to serve.  It must match the name of the CustomResourceDefinition-registration
237	// too: plural.group and it must be all lowercase.
238	Plural string
239	// Singular is the singular name of the resource.  It must be all lowercase  Defaults to lowercased <kind>
240	Singular string
241	// ShortNames are short names for the resource.  It must be all lowercase.
242	ShortNames []string
243	// Kind is the serialized kind of the resource.  It is normally CamelCase and singular.
244	Kind string
245	// ListKind is the serialized kind of the list for this resource.  Defaults to <kind>List.
246	ListKind string
247	// Categories is a list of grouped resources custom resources belong to (e.g. 'all')
248	// +optional
249	Categories []string
250}
251
252// ResourceScope is an enum defining the different scopes available to a custom resource
253type ResourceScope string
254
255const (
256	ClusterScoped   ResourceScope = "Cluster"
257	NamespaceScoped ResourceScope = "Namespaced"
258)
259
260type ConditionStatus string
261
262// These are valid condition statuses. "ConditionTrue" means a resource is in the condition.
263// "ConditionFalse" means a resource is not in the condition. "ConditionUnknown" means kubernetes
264// can't decide if a resource is in the condition or not. In the future, we could add other
265// intermediate conditions, e.g. ConditionDegraded.
266const (
267	ConditionTrue    ConditionStatus = "True"
268	ConditionFalse   ConditionStatus = "False"
269	ConditionUnknown ConditionStatus = "Unknown"
270)
271
272// CustomResourceDefinitionConditionType is a valid value for CustomResourceDefinitionCondition.Type
273type CustomResourceDefinitionConditionType string
274
275const (
276	// Established means that the resource has become active. A resource is established when all names are
277	// accepted without a conflict for the first time. A resource stays established until deleted, even during
278	// a later NamesAccepted due to changed names. Note that not all names can be changed.
279	Established CustomResourceDefinitionConditionType = "Established"
280	// NamesAccepted means the names chosen for this CustomResourceDefinition do not conflict with others in
281	// the group and are therefore accepted.
282	NamesAccepted CustomResourceDefinitionConditionType = "NamesAccepted"
283	// NonStructuralSchema means that one or more OpenAPI schema is not structural.
284	//
285	// A schema is structural if it specifies types for all values, with the only exceptions of those with
286	// - x-kubernetes-int-or-string: true — for fields which can be integer or string
287	// - x-kubernetes-preserve-unknown-fields: true — for raw, unspecified JSON values
288	// and there is no type, additionalProperties, default, nullable or x-kubernetes-* vendor extenions
289	// specified under allOf, anyOf, oneOf or not.
290	//
291	// Non-structural schemas will not be allowed anymore in v1 API groups. Moreover, new features will not be
292	// available for non-structural CRDs:
293	// - pruning
294	// - defaulting
295	// - read-only
296	// - OpenAPI publishing
297	// - webhook conversion
298	NonStructuralSchema CustomResourceDefinitionConditionType = "NonStructuralSchema"
299	// Terminating means that the CustomResourceDefinition has been deleted and is cleaning up.
300	Terminating CustomResourceDefinitionConditionType = "Terminating"
301	// KubernetesAPIApprovalPolicyConformant indicates that an API in *.k8s.io or *.kubernetes.io is or is not approved.  For CRDs
302	// outside those groups, this condition will not be set.  For CRDs inside those groups, the condition will
303	// be true if .metadata.annotations["api-approved.kubernetes.io"] is set to a URL, otherwise it will be false.
304	// See https://github.com/kubernetes/enhancements/pull/1111 for more details.
305	KubernetesAPIApprovalPolicyConformant CustomResourceDefinitionConditionType = "KubernetesAPIApprovalPolicyConformant"
306)
307
308// CustomResourceDefinitionCondition contains details for the current condition of this pod.
309type CustomResourceDefinitionCondition struct {
310	// Type is the type of the condition. Types include Established, NamesAccepted and Terminating.
311	Type CustomResourceDefinitionConditionType
312	// Status is the status of the condition.
313	// Can be True, False, Unknown.
314	Status ConditionStatus
315	// Last time the condition transitioned from one status to another.
316	// +optional
317	LastTransitionTime metav1.Time
318	// Unique, one-word, CamelCase reason for the condition's last transition.
319	// +optional
320	Reason string
321	// Human-readable message indicating details about last transition.
322	// +optional
323	Message string
324}
325
326// CustomResourceDefinitionStatus indicates the state of the CustomResourceDefinition
327type CustomResourceDefinitionStatus struct {
328	// Conditions indicate state for particular aspects of a CustomResourceDefinition
329	// +listType=map
330	// +listMapKey=type
331	Conditions []CustomResourceDefinitionCondition
332
333	// AcceptedNames are the names that are actually being used to serve discovery
334	// They may be different than the names in spec.
335	AcceptedNames CustomResourceDefinitionNames
336
337	// StoredVersions are all versions of CustomResources that were ever persisted. Tracking these
338	// versions allows a migration path for stored versions in etcd. The field is mutable
339	// so the migration controller can first finish a migration to another version (i.e.
340	// that no old objects are left in the storage), and then remove the rest of the
341	// versions from this list.
342	// None of the versions in this list can be removed from the spec.Versions field.
343	StoredVersions []string
344}
345
346// CustomResourceCleanupFinalizer is the name of the finalizer which will delete instances of
347// a CustomResourceDefinition
348const CustomResourceCleanupFinalizer = "customresourcecleanup.apiextensions.k8s.io"
349
350// +genclient
351// +genclient:nonNamespaced
352// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
353
354// CustomResourceDefinition represents a resource that should be exposed on the API server.  Its name MUST be in the format
355// <.spec.name>.<.spec.group>.
356type CustomResourceDefinition struct {
357	metav1.TypeMeta
358	metav1.ObjectMeta
359
360	// Spec describes how the user wants the resources to appear
361	Spec CustomResourceDefinitionSpec
362	// Status indicates the actual state of the CustomResourceDefinition
363	Status CustomResourceDefinitionStatus
364}
365
366// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
367
368// CustomResourceDefinitionList is a list of CustomResourceDefinition objects.
369type CustomResourceDefinitionList struct {
370	metav1.TypeMeta
371	metav1.ListMeta
372
373	// Items individual CustomResourceDefinitions
374	Items []CustomResourceDefinition
375}
376
377// CustomResourceValidation is a list of validation methods for CustomResources.
378type CustomResourceValidation struct {
379	// OpenAPIV3Schema is the OpenAPI v3 schema to be validated against.
380	OpenAPIV3Schema *JSONSchemaProps
381}
382
383// CustomResourceSubresources defines the status and scale subresources for CustomResources.
384type CustomResourceSubresources struct {
385	// Status denotes the status subresource for CustomResources
386	Status *CustomResourceSubresourceStatus
387	// Scale denotes the scale subresource for CustomResources
388	Scale *CustomResourceSubresourceScale
389}
390
391// CustomResourceSubresourceStatus defines how to serve the status subresource for CustomResources.
392// Status is represented by the `.status` JSON path inside of a CustomResource. When set,
393// * exposes a /status subresource for the custom resource
394// * PUT requests to the /status subresource take a custom resource object, and ignore changes to anything except the status stanza
395// * PUT/POST/PATCH requests to the custom resource ignore changes to the status stanza
396type CustomResourceSubresourceStatus struct{}
397
398// CustomResourceSubresourceScale defines how to serve the scale subresource for CustomResources.
399type CustomResourceSubresourceScale struct {
400	// SpecReplicasPath defines the JSON path inside of a CustomResource that corresponds to Scale.Spec.Replicas.
401	// Only JSON paths without the array notation are allowed.
402	// Must be a JSON Path under .spec.
403	// If there is no value under the given path in the CustomResource, the /scale subresource will return an error on GET.
404	SpecReplicasPath string
405	// StatusReplicasPath defines the JSON path inside of a CustomResource that corresponds to Scale.Status.Replicas.
406	// Only JSON paths without the array notation are allowed.
407	// Must be a JSON Path under .status.
408	// If there is no value under the given path in the CustomResource, the status replica value in the /scale subresource
409	// will default to 0.
410	StatusReplicasPath string
411	// LabelSelectorPath defines the JSON path inside of a CustomResource that corresponds to Scale.Status.Selector.
412	// Only JSON paths without the array notation are allowed.
413	// Must be a JSON Path under .status or .spec.
414	// Must be set to work with HPA.
415	// The field pointed by this JSON path must be a string field (not a complex selector struct)
416	// which contains a serialized label selector in string form.
417	// More info: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions#scale-subresource
418	// If there is no value under the given path in the CustomResource, the status label selector value in the /scale
419	// subresource will default to the empty string.
420	// +optional
421	LabelSelectorPath *string
422}
423