forked from kcp-dev/api-syncagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublished_resource.go
More file actions
496 lines (430 loc) · 23.3 KB
/
Copy pathpublished_resource.go
File metadata and controls
496 lines (430 loc) · 23.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
Copyright 2025 The KCP Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// All of these constants are used in the deprecated local naming scheme for
// PublishedResources. New code should not use them, but instead rely on
// Go templated expressions.
const (
// Deprecated: Use Go templates instead.
PlaceholderRemoteClusterName = "$remoteClusterName"
// Deprecated: Use Go templates instead.
PlaceholderRemoteNamespace = "$remoteNamespace"
// Deprecated: Use Go templates instead.
PlaceholderRemoteNamespaceHash = "$remoteNamespaceHash"
// Deprecated: Use Go templates instead.
PlaceholderRemoteName = "$remoteName"
// Deprecated: Use Go templates instead.
PlaceholderRemoteNameHash = "$remoteNameHash"
)
// +genclient
// +genclient:nonNamespaced
// +kubebuilder:object:root=true
// +kubebuilder:resource:scope=Cluster
// +kubebuilder:subresource:status
// PublishedResource describes how an API type (usually defined by a CRD)
// on the service cluster should be exposed in kcp workspaces. Besides
// controlling how namespaced and cluster-wide resources should be mapped,
// the GVK can also be transformed to provide a uniform, implementation-independent
// access to the APIs inside kcp.
type PublishedResource struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PublishedResourceSpec `json:"spec"`
// Status contains reconciliation information for the published resource.
Status PublishedResourceStatus `json:"status,omitempty"`
}
// PublishedResourceSpec describes the desired resource publication from a service
// cluster to kcp.
type PublishedResourceSpec struct {
// Describes the "source" Resource that exists on this, the service cluster,
// that should be exposed in kcp workspaces. All fields have to be specified.
Resource SourceResourceDescriptor `json:"resource"`
// If specified, the filter will be applied to the resources in a workspace
// and allow restricting which of them will be handled by the Sync Agent.
Filter *ResourceFilter `json:"filter,omitempty"`
// Naming can be used to control how the namespace and names for local objects
// are formed. If not specified, the Sync Agent will use defensive defaults to
// prevent naming collisions in the service cluster.
// When configuring this, great care must be taken to not allow for naming
// collisions to happen; keep in mind that the same name/namespace can exists in
// many different kcp workspaces.
Naming *ResourceNaming `json:"naming,omitempty"`
// EnableWorkspacePaths toggles whether the Sync Agent will not just store the kcp
// cluster name as a label on each locally synced object, but also the full workspace
// path. This is optional because it requires additional requests to kcp and
// should only be used if the workspace path is of interest on the
// service cluster side.
EnableWorkspacePaths bool `json:"enableWorkspacePaths,omitempty"`
// Projection is used to change the GVK of a published resource within kcp.
// This can be used to hide implementation details and provide a customized API
// experience to the user.
// All fields in the projection are optional. If a field is set, it will overwrite
// that field in the GVK. The namespaced field can be set to turn a cluster-wide
// resource namespaced or vice-versa.
Projection *ResourceProjection `json:"projection,omitempty"`
// Mutation allows to configure "rewrite rules" to modify the objects in both
// directions during the synchronization.
Mutation *ResourceMutationSpec `json:"mutation,omitempty"`
// Related configures additional resources that semantically belong to the synced
// resource, like a Secret containing generated credentials. Related objects are
// synced along the main resource.
Related []RelatedResourceSpec `json:"related,omitempty"`
// Synchronization allows to configure how the syncagent processes this resource.
Synchronization *SynchronizationSpec `json:"synchronization,omitempty"`
}
// ResourceNaming describes how the names for local objects should be formed.
type ResourceNaming struct {
// The name field allows to control the name the local objects created by the Sync Agent.
// If left empty, the default value is:
//
// "{{ .Object.metadata.namespace | sha3short }}-{{ .Object.metadata.name | sha3short }}"
//
// This guarantees unique names as long as the cluster name is used for the local namespace
// (the default unless configured otherwise).
//
// This value is a Go template, see the documentation for the available variables and functions.
//
// Alternatively (but deprecated), this value can be a simple string using one of the following
// placeholders:
//
// - $remoteClusterName -- the kcp workspace's cluster name (e.g. "1084s8ceexsehjm2")
// - $remoteNamespace -- the original namespace used by the consumer inside the kcp
// workspace (if targetNamespace is left empty, it's equivalent
// to setting "$remote_ns")
// - $remoteNamespaceHash -- first 20 hex characters of the SHA-1 hash of $remoteNamespace
// - $remoteName -- the original name of the object inside the kcp workspace
// (rarely used to construct local namespace names)
// - $remoteNameHash -- first 20 hex characters of the SHA-1 hash of $remoteName
//
// Authors are advised to use Go templates instead, as the custom variable syntax is deprecated
// and will be removed from a future release of the Sync Agent.
Name string `json:"name,omitempty"`
// For namespaced resources, the this field allows to control where the local objects will
// be created. If left empty, "{{ .ClusterName }}" is assumed.
//
// This value is a Go template, see the documentation for the available variables and functions.
//
// Alternatively (but deprecated), this value can be a simple string using one of the following
// placeholders:
//
// - $remoteClusterName -- the kcp workspace's cluster name (e.g. "1084s8ceexsehjm2")
// - $remoteNamespace -- the original namespace used by the consumer inside the kcp
// workspace (if targetNamespace is left empty, it's equivalent
// to setting "$remote_ns")
// - $remoteNamespaceHash -- first 20 hex characters of the SHA-1 hash of $remoteNamespace
// - $remoteName -- the original name of the object inside the kcp workspace
// (rarely used to construct local namespace names)
// - $remoteNameHash -- first 20 hex characters of the SHA-1 hash of $remoteName
//
// Authors are advised to use Go templates instead, as the custom variable syntax is deprecated
// and will be removed from a future release of the Sync Agent.
Namespace string `json:"namespace,omitempty"`
}
// ResourceMutationSpec allows to configure "rewrite rules" to modify the objects in both
// directions during the synchronization.
type ResourceMutationSpec struct {
Spec []ResourceMutation `json:"spec,omitempty"`
Status []ResourceMutation `json:"status,omitempty"`
}
type ResourceMutation struct {
// Must use exactly one of these options, never more, never fewer.
// TODO: Add validation code for this somewhere.
Delete *ResourceDeleteMutation `json:"delete,omitempty"`
Regex *ResourceRegexMutation `json:"regex,omitempty"`
Template *ResourceTemplateMutation `json:"template,omitempty"`
CEL *ResourceCELMutation `json:"cel,omitempty"`
}
type ResourceDeleteMutation struct {
Path string `json:"path"`
}
type ResourceRegexMutation struct {
Path string `json:"path"`
// Pattern can be left empty to simply replace the entire value with the
// replacement.
Pattern string `json:"pattern,omitempty"`
Replacement string `json:"replacement,omitempty"`
}
type ResourceTemplateMutation struct {
Path string `json:"path"`
Template string `json:"template"`
}
type ResourceCELMutation struct {
Path string `json:"path"`
Expression string `json:"expression"`
}
type RelatedResourceOrigin string
const (
RelatedResourceOriginService RelatedResourceOrigin = "service"
RelatedResourceOriginKcp RelatedResourceOrigin = "kcp"
)
// RelatedResourceSpec describes a single related resource, which might point to
// any number of actual Kubernetes objects.
//
// (in the following rule, group is optional becaue core/v1 is represented by group="")
// +kubebuilder:validation:XValidation:rule="has(self.kind) != (has(self.version) || has(self.resource))",message="must specify either kind (deprecated) or group, version, resource"
// +kubebuilder:validation:XValidation:rule="has(self.resource) == has(self.version)",message="resource and version must be configured together or not at all"
// +kubebuilder:validation:XValidation:rule="!has(self.group) || (has(self.resource) && has(self.version))",message="configuring a group also requires a version and resource"
// group is included here because when an identityHash is used, core/v1 cannot possible be targetted
// +kubebuilder:validation:XValidation:rule="!has(self.identityHash) || (has(self.group) && has(self.version) && has(self.resource))",message="identity hashes can only be used with GVRs"
// +kubebuilder:validation:XValidation:rule="!(self.origin == 'service' && has(self.syncStatus) && self.syncStatus) || has(self.watch)",message="watch must be configured when origin is service and syncStatus is true"
type RelatedResourceSpec struct {
// Identifier is a unique name for this related resource. The name must be unique within one
// PublishedResource and is the key by which consumers (end users) can identify and consume the
// related resource. Common names are "connection-details" or "credentials".
// The identifier must be an alphanumeric string.
Identifier string `json:"identifier"`
// +kubebuilder:validation:Enum=service;kcp
Origin RelatedResourceOrigin `json:"origin"`
// Group is the API group of the related resource. This should be left blank for resources
// in the core API group.
Group string `json:"group,omitempty"`
// Version is the API version of the related resource. This can be left blank to automatically
// use the preferred version.
Version string `json:"version,omitempty"`
// Resource is the name of the related resource (for example "secrets").
Resource string `json:"resource,omitempty"`
// Kind is the object kind of the related resource (for example "Secret").
//
// Deprecated: Use "Resource" instead. This field is limited to "ConfigMap" and "Secret" and will
// be removed in the future. Kind and Resource cannot be specified at the same time.
//
// +kubebuilder:validation:Enum=ConfigMap;Secret
Kind string `json:"kind,omitempty"`
// IdentityHash is the identity hash of a kcp APIExport, in case the given Kind is
// provided by an APIExport and not Kube-native.
IdentityHash string `json:"identityHash,omitempty"`
// Cleanup can be set to true to make the syncagent delete any copy of this related resource on
// the destination side (i.e. the original related object will not be touched, regardless of this
// option). Leaving this disabled, the syncagent will only create copies of the related objects,
// but never delete them itself.
Cleanup bool `json:"cleanup,omitempty"`
// Projection is used to change the GVK of a related resource on the opposite side of
// its origin.
// All fields in the projection are optional. If a field is set, it will overwrite
// that field in the GVK.
Projection *RelatedResourceProjection `json:"projection,omitempty"`
// Object describes how the related resource can be found on the origin side
// and where it is to supposed to be created on the destination side.
Object RelatedResourceObject `json:"object"`
// Mutation configures optional transformation rules for the related resource.
// Status mutations are only performed when the related resource originates in kcp.
Mutation *ResourceMutationSpec `json:"mutation,omitempty"`
// Watch configures how the agent identifies the owning primary object when a related
// resource with origin: kcp changes. When set, the agent sets up a watch on the related
// resource type and uses the configured rule to enqueue the correct primary object.
// Without this field, changes to origin:kcp related resources do not trigger reconciliation.
Watch *RelatedResourceWatch `json:"watch,omitempty"`
// SyncStatus enables synchronization of the status subresource in the same direction as
// the spec (from the origin side to the destination side). When enabled, the agent will
// use the status subresource endpoint to update the destination object's status.
// This requires the related resource to have a status subresource configured in its CRD.
//
// - origin: kcp -> status is synced from kcp to the service cluster
// - origin: service -> status is synced from the service cluster to kcp
//
// For origin: service, Watch must also be configured so that changes to the related
// resource's status trigger reconciliation and ensure the informer cache is populated.
//
// +optional
SyncStatus bool `json:"syncStatus,omitempty"`
}
// RelatedResourceWatch configures how the watch handler maps a changed related resource
// back to its owning primary object.
// Exactly one of ByOwner or BySelector must be set.
// +kubebuilder:validation:XValidation:rule="has(self.byOwner) != has(self.bySelector)",message="exactly one of byOwner or bySelector must be set"
type RelatedResourceWatch struct {
// ByOwner configures the watch handler to inspect the OwnerReferences of the changed
// object. When an OwnerReference with the given Kind is found, the referenced owner
// is enqueued as the primary object.
// +optional
ByOwner *RelatedResourceWatchByOwner `json:"byOwner,omitempty"`
// BySelector configures the watch handler to list primary objects matching the given label
// selector. When a related object changes, all primary objects matching this selector
// are enqueued for reconciliation.
// +optional
BySelector *metav1.LabelSelector `json:"bySelector,omitempty"`
}
// RelatedResourceWatchByOwner configures reverse lookup via OwnerReferences.
// The agent already knows the GVK of the primary object, so no further configuration
// is needed: when a related object changes, its OwnerReferences are inspected for a
// reference whose Kind matches the primary object's Kind.
type RelatedResourceWatchByOwner struct{}
// RelatedResourceProjection describes how the source GVK of a related resource (i.e.
// the GVK on the related resource's origin side) should be modified when an object
// is copied from the origin to the destination.
type RelatedResourceProjection struct {
// The API group, for example "myservice.example.com". Leave empty to not modify the API group.
Group string `json:"group,omitempty"`
// The API version, for example "v1beta1". Leave empty to not modify the version.
Version string `json:"version,omitempty"`
// The resource name, for example "databases". Leave empty to not modify the resource.
Resource string `json:"resource,omitempty"`
}
// RelatedResourceSource configures how the related resource can be found on the origin side
// and where it is to supposed to be created on the destination side.
type RelatedResourceObject struct {
RelatedResourceObjectSpec `json:",inline"`
// Namespace configures in what namespace the related object resides in. If
// not specified, the same namespace as the main object is assumed. If the
// main object is cluster-scoped, this field is required and an error will be
// raised during syncing if the field is not specified.
Namespace *RelatedResourceObjectSpec `json:"namespace,omitempty"`
}
// RelatedResourceObjectSpec configures different ways an object can be located.
// All fields are mutually exclusive.
type RelatedResourceObjectSpec struct {
// Selector is a label selector that is useful if no reference is in the
// main resource (i.e. if the related object links back to its parent, instead
// of the parent pointing to the related object).
Selector *RelatedResourceObjectSelector `json:"selector,omitempty"`
// Reference points to a field inside the main object. This reference is
// evaluated on both source and destination sides to find the related object.
Reference *RelatedResourceObjectReference `json:"reference,omitempty"`
// Template is a Go templated string that can make use of variables to
// construct the resulting string.
Template *TemplateExpression `json:"template,omitempty"`
}
// RelatedResourceObjectReference describes a path expression that is evaluated inside
// a JSON-marshalled Kubernetes object, yielding a string when evaluated.
type RelatedResourceObjectReference struct {
// Path is a simplified JSONPath expression like "metadata.name". A reference
// must always select at least _something_ in the object, even if the value
// is discarded by the regular expression.
Path string `json:"path"`
// Regex is a Go regular expression that is optionally applied to the selected
// value from the path.
Regex *RegularExpression `json:"regex,omitempty"`
}
// RelatedResourceSelector is a dedicated struct in case we need additional options
// for evaluating the label selector.
// RelatedResourceObjectSelector describes how to locate a related object based on
// labels. This is useful if the main resource has no and cannot construct a
// reference to the related object because its name/namespace might be randomized.
type RelatedResourceObjectSelector struct {
metav1.LabelSelector `json:",inline"`
Rewrite RelatedResourceSelectorRewrite `json:"rewrite"`
}
type RelatedResourceSelectorRewrite struct {
// Regex is a Go regular expression that is optionally applied to the selected
// value from the path.
Regex *RegularExpression `json:"regex,omitempty"`
Template *TemplateExpression `json:"template,omitempty"`
}
// RegularExpression models a Go regular expression string replacement. See
// https://pkg.go.dev/regexp/syntax for more information on the syntax.
type RegularExpression struct {
// Pattern can be left empty to simply replace the entire value with the
// replacement.
Pattern string `json:"pattern,omitempty"`
// Replacement is the string that the matched pattern is replaced with. It
// can contain references to groups in the pattern by using \N.
Replacement string `json:"replacement,omitempty"`
}
// TemplateExpression is a Go templated string that can make use of variables to
// construct the resulting string.
type TemplateExpression struct {
Template string `json:"template,omitempty"`
}
// SourceResourceDescriptor uniquely describes a resource type in the cluster.
type SourceResourceDescriptor struct {
// The API group of a resource, for example "storage.initroid.com".
APIGroup string `json:"apiGroup"`
// The API version, for example "v1beta1". Setting this field will only publish
// the given version, otherwise all versions for the group/kind will be
// published.
//
// Deprecated: Use .versions instead.
Version string `json:"version,omitempty"`
// Versions allows to select a subset of versions to publish. Leave empty
// to publish all available versions.
Versions []string `json:"versions,omitempty"`
// The resource Kind, for example "Database".
Kind string `json:"kind"`
}
// ResourceScope is an enum defining the different scopes available to a custom resource.
// This ENUM matches apiextensionsv1.ResourceScope, but was copied here to avoid a costly
// dependency and since the ENUM will unlikely be extended/changed in future Kubernetes
// releases.
type ResourceScope string
const (
ClusterScoped ResourceScope = "Cluster"
NamespaceScoped ResourceScope = "Namespaced"
)
// ResourceProjection describes how the source GVK should be modified before it's published in kcp.
type ResourceProjection struct {
// The API group, for example "myservice.example.com". Leave empty to not modify the API group.
Group string `json:"group,omitempty"`
// The API version, for example "v1beta1". Leave empty to not modify the version.
//
// This field must not be set when multiple versions have been selected.
//
// Deprecated: Use .versions instead.
Version string `json:"version,omitempty"`
// Versions allows to map API versions onto new values in kcp. Leave empty to not modify the
// versions.
Versions map[string]string `json:"versions,omitempty"`
// Whether or not the resource is namespaced.
// +kubebuilder:validation:Enum=Cluster;Namespaced
Scope ResourceScope `json:"scope,omitempty"`
// The resource Kind, for example "Database". Setting this field will also overwrite
// the singular name by lowercasing the resource kind. In addition, if this is set,
// the plural name will also be updated by taking the lowercased kind name and appending
// an "s". If this would yield an undesirable name, use the plural field to explicitly
// give the plural name.
Kind string `json:"kind,omitempty"`
// When overwriting the Kind, it can be necessary to also override the plural name in
// case of more complex pluralization rules.
Plural string `json:"plural,omitempty"`
// ShortNames can be used to overwrite the original short names for a resource, usually
// when the Kind is remapped, new short names are also in order. Set this to an empty
// list to remove all short names.
// +optional
ShortNames []string `json:"shortNames"` // not omitempty because we need to distinguish between [] and nil
// Categories can be used to overwrite the original categories a resource was in. Set
// this to an empty list to remove all categories.
// +optional
Categories []string `json:"categories"` // not omitempty because we need to distinguish between [] and nil
}
// ResourceFilter can be used to limit what resources should be included in an operation.
type ResourceFilter struct {
// When given, the namespace filter will be applied to a resource's namespace.
Namespace *metav1.LabelSelector `json:"namespace,omitempty"`
// When given, the resource filter will be applied to a resource itself.
Resource *metav1.LabelSelector `json:"resource,omitempty"`
}
// SynchronizationSpec allows to configure how the syncagent processes a
// PublishedResource.
type SynchronizationSpec struct {
// Enabled can be used to toggle the synchronization as a whole. When set to
// false, the syncagent will only copy the CRD and include it in the APIExport,
// but not will attempt to synchronize objects of this resource from the kcp
// workspaces to the provider.
// Synchronization must be disabled for resources that are used as related
// resources for other PublishedResources. Otherwise the syncagent would
// potentially loop and never finish processing an object.
Enabled bool `json:"enabled"`
}
// PublishedResourceStatus stores status information about a published resource.
type PublishedResourceStatus struct {
ResourceSchemaName string `json:"resourceSchemaName,omitempty"`
}
// +kubebuilder:object:root=true
// PublishedResourceList contains a list of PublishedResources.
type PublishedResourceList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []PublishedResource `json:"items"`
}