-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
HasMetadata.java
465 lines (422 loc) · 18 KB
/
HasMetadata.java
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
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* 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 io.fabric8.kubernetes.api.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.fabric8.kubernetes.api.Pluralize;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Kind;
import io.fabric8.kubernetes.model.annotation.Plural;
import io.fabric8.kubernetes.model.annotation.Singular;
import io.fabric8.kubernetes.model.annotation.Version;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents any {@link KubernetesResource} which possesses a {@link ObjectMeta} and is associated with a kind and API version.
*/
public interface HasMetadata extends KubernetesResource {
String DNS_LABEL_START = "(?!-)[A-Za-z0-9-]{";
String DNS_LABEL_END = ",63}(?<!-)";
String DNS_LABEL_REGEXP = DNS_LABEL_START + 1 + DNS_LABEL_END;
/**
* Pattern that checks the format of finalizer identifiers, which should be in {@code <domain name>/<finalizer name>} format.
*/
Pattern FINALIZER_NAME_MATCHER = Pattern.compile(
"^((" + DNS_LABEL_REGEXP + "\\.)+" + DNS_LABEL_START + 2 + DNS_LABEL_END + ")/"
+ DNS_LABEL_REGEXP);
ObjectMeta getMetadata();
void setMetadata(ObjectMeta metadata);
/**
* Retrieves the kind associated with the specified HasMetadata implementation. If the implementation is annotated with
* {@link Kind}, the annotation value will be used, otherwise the value will be derived from the class name.
*
* @param clazz the HasMetadata implementation whose Kind we want to retrieve
* @return the kind associated with the specified HasMetadata
*/
static String getKind(Class<?> clazz) {
final Kind kind = clazz.getAnnotation(Kind.class);
return kind != null ? kind.value() : clazz.getSimpleName();
}
default String getKind() {
return getKind(getClass());
}
/**
* Computes the {@code apiVersion} associated with this HasMetadata implementation. The value is derived from the
* {@link Group} and {@link Version} annotations.
*
* @param clazz the HasMetadata whose {@code apiVersion} we want to compute
* @return the computed {@code apiVersion} or {@code null} if neither {@link Group} or {@link Version} annotations are present
* @throws IllegalArgumentException if only one of {@link Group} or {@link Version} is provided
*/
static String getApiVersion(Class<?> clazz) {
final String group = getGroup(clazz);
final String version = getVersion(clazz);
if (group != null && version != null) {
return group + "/" + version;
}
if (group != null || version != null) {
throw new IllegalArgumentException(
"You need to specify both @" + Group.NAME + " and @" + Version.NAME + " annotations if you specify either");
}
return null;
}
/**
* Retrieves the group associated with the specified HasMetadata as defined by the {@link Group} annotation.
*
* @param clazz the HasMetadata whose group we want to retrieve
* @return the associated group or {@code null} if the HasMetadata is not annotated with {@link Group}
*/
static String getGroup(Class<?> clazz) {
final Group group = clazz.getAnnotation(Group.class);
return group != null ? group.value() : null;
}
/**
* Retrieves the version associated with the specified HasMetadata as defined by the {@link Version} annotation.
*
* @param clazz the HasMetadata whose version we want to retrieve
* @return the associated version or {@code null} if the HasMetadata is not annotated with {@link Version}
*/
static String getVersion(Class<?> clazz) {
final Version version = clazz.getAnnotation(Version.class);
return version != null ? version.value() : null;
}
default String getApiVersion() {
return getApiVersion(getClass());
}
void setApiVersion(String version);
/**
* Retrieves the plural form associated with the specified class if annotated with {@link
* Plural} or computes a default value using the value returned by {@link #getSingular(Class)} as
* input to {@link Pluralize#toPlural(String)}.
*
* @param clazz the CustomResource whose plural form we want to retrieve
* @return the plural form defined by the {@link Plural} annotation or a computed default value
*/
static String getPlural(Class<?> clazz) {
final Plural fromAnnotation = clazz.getAnnotation(Plural.class);
return (fromAnnotation != null ? fromAnnotation.value().toLowerCase(Locale.ROOT)
: Pluralize.toPlural(getSingular(clazz)));
}
@JsonIgnore
default String getPlural() {
return getPlural(getClass());
}
/**
* Retrieves the singular form associated with the specified class as defined by the
* {@link Singular} annotation or computes a default value (lower-cased version of the value
* returned by {@link HasMetadata#getKind(Class)}) if the annotation is not present.
*
* @param clazz the class whose singular form we want to retrieve
* @return the singular form defined by the {@link Singular} annotation or a computed default
* value
*/
static String getSingular(Class<?> clazz) {
final Singular fromAnnotation = clazz.getAnnotation(Singular.class);
return (fromAnnotation != null ? fromAnnotation.value() : HasMetadata.getKind(clazz))
.toLowerCase(Locale.ROOT);
}
@JsonIgnore
default String getSingular() {
return getSingular(getClass());
}
static String getFullResourceName(Class<?> clazz) {
final String plural = getPlural(clazz);
final String group = getGroup(clazz);
if (plural == null || group == null) {
throw new IllegalArgumentException(
"Should provide non-null plural and/or group. Is " + clazz.getName() + " properly annotated with @" + Group.NAME + " and/or @" + Version.NAME + "?");
}
return getFullResourceName(plural, group);
}
static String getFullResourceName(String plural, String group) {
Objects.requireNonNull(plural);
Objects.requireNonNull(group);
return group.isEmpty() ? plural : plural + "." + group;
}
@JsonIgnore
@SuppressWarnings("unused")
default String getFullResourceName() {
return getFullResourceName(getClass());
}
/**
* Determines whether this {@code HasMetadata} is marked for deletion or not.
*
* @return {@code true} if the cluster marked this {@code HasMetadata} for deletion, {@code false} otherwise
*/
@JsonIgnore
default boolean isMarkedForDeletion() {
final String deletionTimestamp = optionalMetadata().map(ObjectMeta::getDeletionTimestamp)
.orElse(null);
return deletionTimestamp != null && !deletionTimestamp.isEmpty();
}
/**
* Determines whether this {@code HasMetadata} holds the specified finalizer.
*
* @param finalizer the identifier of the finalizer we want to check
* @return {@code true} if this {@code HasMetadata} holds the specified finalizer, {@code false} otherwise
*/
default boolean hasFinalizer(String finalizer) {
return getFinalizers().contains(finalizer);
}
@JsonIgnore
default List<String> getFinalizers() {
return optionalMetadata().map(ObjectMeta::getFinalizers).orElse(Collections.emptyList());
}
/**
* Adds the specified finalizer to this {@code HasMetadata} if it's valid. See {@link #isFinalizerValid(String)}.
*
* @param finalizer the identifier of the finalizer to add to this {@code HasMetadata} in {@code <domain name>/<finalizer name>} format.
* @return {@code true} if the finalizer was successfully added, {@code false} otherwise (in particular, if the object is marked for deletion)
* @throws IllegalArgumentException if the specified finalizer identifier is null or is invalid
*/
default boolean addFinalizer(String finalizer) {
if (finalizer == null || finalizer.trim().isEmpty()) {
throw new IllegalArgumentException("Must pass a non-null, non-blank finalizer.");
}
if (isMarkedForDeletion() || hasFinalizer(finalizer)) {
return false;
}
if (isFinalizerValid(finalizer)) {
ObjectMeta metadata = getMetadata();
if (metadata == null) {
metadata = new ObjectMeta();
setMetadata(metadata);
}
return metadata.getFinalizers().add(finalizer);
} else {
throw new IllegalArgumentException("Invalid finalizer name: '" + finalizer
+ "'. Must consist of a domain name, a forward slash and the valid kubernetes name.");
}
}
/**
* Determines whether the specified finalizer is valid according to the
* <a href='https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#finalizers'>finalizer
* specification</a>.
*
* @param finalizer the identifier of the finalizer which validity we want to check
* @return {@code true} if the identifier is valid, {@code false} otherwise
*/
static boolean validateFinalizer(String finalizer) {
if (finalizer == null) {
return false;
}
final Matcher matcher = FINALIZER_NAME_MATCHER.matcher(finalizer);
if (matcher.matches()) {
final String group = matcher.group(1);
return group.length() < 256;
} else {
return false;
}
}
/**
* @see HasMetadata#validateFinalizer(String)
*
* @param finalizer the identifier of the finalizer which validity we want to check
* @return {@code true} if the identifier is valid, {@code false} otherwise
*/
default boolean isFinalizerValid(String finalizer) {
return HasMetadata.validateFinalizer(finalizer);
}
/**
* Removes the specified finalizer if it's held by this {@code HasMetadata}.
*
* @param finalizer the identifier of the finalizer we want to remove
* @return {@code true} if the finalizer was successfully removed, {@code false} otherwise
*/
default boolean removeFinalizer(String finalizer) {
final List<String> finalizers = getFinalizers();
return finalizers.contains(finalizer) && finalizers.remove(finalizer);
}
/**
* Checks whether the provided {@code HasMetadata} is defined as an owner for this {@code HasMetadata}.
*
* @param owner the {@code HasMetadata} to check for potential ownership
* @return {@code true} if the provided {@code HasMetadata} is an owner of this instance
*/
default boolean hasOwnerReferenceFor(HasMetadata owner) {
return getOwnerReferenceFor(owner).isPresent();
}
/**
* Checks whether the provided UID identifies an owner for this {@code HasMetadata}.
*
* @param ownerUid the UID of a {@code HasMetadata} to check for potential ownership
* @return {@code true} if the provided {@code HasMetadata} is an owner of this instance
*/
default boolean hasOwnerReferenceFor(String ownerUid) {
return getOwnerReferenceFor(ownerUid).isPresent();
}
/**
* Retrieves the {@link OwnerReference} associated with the specified owner if it's part of this {@code HasMetadata}'s owners.
*
* @param owner the potential owner of which we want to retrieve the associated {@link OwnerReference}
* @return an {@link Optional} containing the {@link OwnerReference} associated with the specified owner if it exists or {@link Optional#empty()} otherwise.
*/
default Optional<OwnerReference> getOwnerReferenceFor(HasMetadata owner) {
if (owner == null) {
return Optional.empty();
}
final String ownerUID = owner.optionalMetadata().map(ObjectMeta::getUid).orElse(null);
return getOwnerReferenceFor(ownerUID);
}
/**
* Retrieves the {@link OwnerReference} associated with the owner identified by the specified UID if it's part of this{@code HasMetadata}'s owners.
*
* @param ownerUid the UID of the potential owner of which we want to retrieve the associated {@link
* OwnerReference}
* @return an {@link Optional} containing the {@link OwnerReference} associated with the
* owner identified by the specified UID if it exists or {@link Optional#empty()} otherwise.
*/
default Optional<OwnerReference> getOwnerReferenceFor(String ownerUid) {
if (ownerUid == null || ownerUid.isEmpty()) {
return Optional.empty();
}
return optionalMetadata()
.map(m -> Optional.ofNullable(m.getOwnerReferences()).orElse(Collections.emptyList()))
.orElse(Collections.emptyList())
.stream()
.filter(o -> ownerUid.equals(o.getUid()))
.findFirst();
}
/**
* Adds an {@link OwnerReference} to the specified owner if possible.
*
* @param owner the owner to add a reference to
* @return the newly added {@link OwnerReference}
*/
default OwnerReference addOwnerReference(HasMetadata owner) {
if (owner == null) {
throw new IllegalArgumentException("Cannot add a reference to a null owner to "
+ optionalMetadata().map(m -> "'" + m.getName() + "' ").orElse("unnamed ")
+ getKind());
}
final ObjectMeta metadata = owner.getMetadata();
if (metadata == null) {
throw new IllegalArgumentException("Cannot add a reference to an owner without metadata to "
+ optionalMetadata().map(m -> "'" + m.getName() + "' ").orElse("unnamed ")
+ getKind());
}
final OwnerReference ownerReference = new OwnerReferenceBuilder()
.withUid(metadata.getUid())
.withApiVersion(owner.getApiVersion())
.withName(metadata.getName())
.withKind(owner.getKind())
.build();
return addOwnerReference(sanitizeAndValidate(ownerReference));
}
/**
* Adds the specified, supposed valid (for example because validated by calling {@link #sanitizeAndValidate(OwnerReference)} beforehand), {@link OwnerReference} to this {@code HasMetadata}
* @param ownerReference the {@link OwnerReference} to add to this {@code HasMetadata}'s owner references
* @return the newly added {@link OwnerReference}
*/
default OwnerReference addOwnerReference(OwnerReference ownerReference) {
if (ownerReference == null) {
throw new IllegalArgumentException("Cannot add a null reference to "
+ optionalMetadata().map(m -> "'" + m.getName() + "' ").orElse("unnamed ")
+ getKind());
}
final Optional<OwnerReference> existing = getOwnerReferenceFor(ownerReference.getUid());
if (existing.isPresent()) {
return existing.get();
}
ObjectMeta metadata = getMetadata();
if (metadata == null) {
metadata = new ObjectMeta();
setMetadata(metadata);
}
List<OwnerReference> ownerReferences = metadata.getOwnerReferences();
if (ownerReferences == null) {
ownerReferences = new ArrayList<>();
metadata.setOwnerReferences(ownerReferences);
}
ownerReferences.add(ownerReference);
return ownerReference;
}
/**
* Sanitizes and validates the specified {@link OwnerReference}, presumably to add it
* @param ownerReference the {@link OwnerReference} to sanitize and validate
* @return the sanitized and validated {@link OwnerReference} which should be used instead of the original one
*/
static OwnerReference sanitizeAndValidate(OwnerReference ownerReference) {
// validate required fields are present
final StringBuilder error = new StringBuilder(100);
error.append("Owner is missing required field(s): ");
final BiFunction<String, String, Optional<String>> trimmedFieldIfValid = (field, value) -> {
boolean isError = false;
if (value == null) {
isError = true;
} else {
value = value.trim();
if (value.isEmpty()) {
isError = true;
}
}
if (isError) {
error.append(field).append(" ");
return Optional.empty();
} else {
return Optional.of(value);
}
};
final Supplier<IllegalArgumentException> exceptionSupplier = () -> new IllegalArgumentException(
error.toString());
final Optional<String> uid = trimmedFieldIfValid.apply("uid", ownerReference.getUid());
final Optional<String> apiVersion = trimmedFieldIfValid.apply("apiVersion",
ownerReference.getApiVersion());
final Optional<String> name = trimmedFieldIfValid.apply("name", ownerReference.getName());
final Optional<String> kind = trimmedFieldIfValid.apply("kind", ownerReference.getKind());
// check that required values are present
ownerReference = new OwnerReferenceBuilder(ownerReference)
.withUid(uid.orElseThrow(exceptionSupplier))
.withApiVersion(apiVersion.orElseThrow(exceptionSupplier))
.withName(name.orElseThrow(exceptionSupplier))
.withKind(kind.orElseThrow(exceptionSupplier))
.build();
return ownerReference;
}
/**
* Removes the {@link OwnerReference} identified by the specified UID if it's part of this {@code HasMetadata}'s owner references
* @param ownerUid the UID of the {@link OwnerReference} to remove
*/
default void removeOwnerReference(String ownerUid) {
if (ownerUid != null && !ownerUid.isEmpty()) {
optionalMetadata()
.map(m -> Optional.ofNullable(m.getOwnerReferences()).orElse(Collections.emptyList()))
.orElse(Collections.emptyList())
.removeIf(o -> ownerUid.equals(o.getUid()));
}
}
/**
* Removes the {@link OwnerReference} associated with the specified owner if it's part of this {@code
* HasMetadata}'s owner references
*
* @param owner the owner whose reference we want to remove
*/
default void removeOwnerReference(HasMetadata owner) {
if (owner != null) {
removeOwnerReference(owner.getMetadata().getUid());
}
}
default Optional<ObjectMeta> optionalMetadata() {
return Optional.ofNullable(getMetadata());
}
}