/
Utils.java
429 lines (379 loc) · 13.5 KB
/
Utils.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
/**
* 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.client.utils;
import io.fabric8.kubernetes.api.model.Namespaced;
import io.fabric8.kubernetes.model.annotation.ApiGroup;
import io.fabric8.kubernetes.model.annotation.ApiVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Stream;
import io.fabric8.kubernetes.client.KubernetesClientException;
public class Utils {
private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);
private static final String ALL_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
private Utils() {
}
public static <T> T checkNotNull(T ref, String message) {
if (ref == null) {
throw new NullPointerException(message);
}
return ref;
}
public static String getSystemPropertyOrEnvVar(String systemPropertyName, String envVarName, String defaultValue) {
String answer = System.getProperty(systemPropertyName);
if (isNotNullOrEmpty(answer)) {
return answer;
}
answer = System.getenv(envVarName);
if (isNotNullOrEmpty(answer)) {
return answer;
}
return defaultValue;
}
public static String convertSystemPropertyNameToEnvVar(String systemPropertyName) {
return systemPropertyName.toUpperCase(Locale.ROOT).replaceAll("[.-]", "_");
}
public static String getEnvVar(String envVarName, String defaultValue) {
String answer = System.getenv(envVarName);
return isNotNullOrEmpty(answer) ? answer : defaultValue;
}
public static String getSystemPropertyOrEnvVar(String systemPropertyName, String defaultValue) {
return getSystemPropertyOrEnvVar(systemPropertyName, convertSystemPropertyNameToEnvVar(systemPropertyName), defaultValue);
}
public static String getSystemPropertyOrEnvVar(String systemPropertyName) {
return getSystemPropertyOrEnvVar(systemPropertyName, (String) null);
}
public static boolean getSystemPropertyOrEnvVar(String systemPropertyName, Boolean defaultValue) {
String result = getSystemPropertyOrEnvVar(systemPropertyName, defaultValue.toString());
return Boolean.parseBoolean(result);
}
public static int getSystemPropertyOrEnvVar(String systemPropertyName, int defaultValue) {
String result = getSystemPropertyOrEnvVar(systemPropertyName, new Integer(defaultValue).toString());
return Integer.parseInt(result);
}
public static String join(final Object[] array) {
return join(array, ',');
}
public static String join(final Object[] array, final char separator) {
if (array == null) {
return null;
}
if (array.length == 0) {
return "";
}
final StringBuilder buf = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* Wait until an other thread signals the completion of a task.
* If an exception is passed, it will be propagated to the caller.
* @param queue The communication channel.
* @param amount The amount of time to wait.
* @param timeUnit The time unit.
*
* @return a boolean value indicating resource is ready or not.
*/
public static boolean waitUntilReady(BlockingQueue<Object> queue, long amount, TimeUnit timeUnit) {
try {
Object obj = queue.poll(amount, timeUnit);
if (obj instanceof Boolean) {
return (Boolean) obj;
} else if (obj instanceof Throwable) {
Throwable t = (Throwable) obj;
t.addSuppressed(new Throwable("waiting here"));
throw t;
}
return false;
} catch (Throwable t) {
throw KubernetesClientException.launderThrowable(t);
}
}
/**
* Closes the specified {@link ExecutorService}.
* @param executorService The executorService.
* @return True if shutdown is complete.
*/
public static boolean shutdownExecutorService(ExecutorService executorService) {
if (executorService == null) {
return false;
}
//If it hasn't already shutdown, do shutdown.
if (!executorService.isShutdown()) {
executorService.shutdown();
}
try {
//Wait for clean termination
if (executorService.awaitTermination(5, TimeUnit.SECONDS)) {
return true;
}
//If not already terminated (via shutdownNow) do shutdownNow.
if (!executorService.isTerminated()) {
executorService.shutdownNow();
}
if (executorService.awaitTermination(5, TimeUnit.SECONDS)) {
return true;
}
if (LOGGER.isDebugEnabled()) {
List<Runnable> tasks = executorService.shutdownNow();
if (!tasks.isEmpty()) {
LOGGER.debug("ExecutorService was not cleanly shutdown, after waiting for 10 seconds. Number of remaining tasks:" + tasks.size());
}
}
} catch (InterruptedException e) {
executorService.shutdownNow();
//Preserve interrupted status
Thread.currentThread().interrupt();
}
return false;
}
/**
* Closes and flushes the specified {@link Closeable} items.
* @param closeables An {@link Iterable} of {@link Closeable} items.
*/
public static void closeQuietly(Iterable<Closeable> closeables) {
for (Closeable c : closeables) {
try {
//Check if we also need to flush
if (c instanceof Flushable) {
((Flushable) c).flush();
}
if (c != null) {
c.close();
}
} catch (IOException e) {
LOGGER.debug("Error closing:" + c);
}
}
}
/**
* Closes and flushes the specified {@link Closeable} items.
* @param closeables An array of {@link Closeable} items.
*/
public static void closeQuietly(Closeable... closeables) {
closeQuietly(Arrays.asList(closeables));
}
public static String coalesce(String... items) {
for (String str : items) {
if (str != null) {
return str;
}
}
return null;
}
public static String randomString(int length) {
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = random.nextInt(ALL_CHARS.length());
sb.append(ALL_CHARS.charAt(index));
}
return sb.toString();
}
public static String randomString(String prefix, int length) {
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length - prefix.length(); i++) {
int index = random.nextInt(ALL_CHARS.length());
sb.append(ALL_CHARS.charAt(index));
}
return sb.toString();
}
public static String filePath(URL path) {
try {
return Paths.get(path.toURI()).toString();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
/**
* Replaces all occurrences of the from text with to text without any regular expressions
*
* @param text text string
* @param from from string
* @param to to string
* @return returns processed string
*/
public static String replaceAllWithoutRegex(String text, String from, String to) {
if (text == null) {
return null;
}
int idx = 0;
while (true) {
idx = text.indexOf(from, idx);
if (idx >= 0) {
text = text.substring(0, idx) + to + text.substring(idx + from.length());
// lets start searching after the end of the `to` to avoid possible infinite recursion
idx += to.length();
} else {
break;
}
}
return text;
}
public static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
public static boolean isNotNullOrEmpty(Map map) {
return !(map == null || map.isEmpty());
}
public static boolean isNotNullOrEmpty(String str) {
return !isNullOrEmpty(str);
}
public static boolean isNotNullOrEmpty(String[] array) {
return !(array == null || array.length == 0);
}
public static <T> boolean isNotNull(T ...refList) {
return Optional.ofNullable(refList)
.map(refs -> Stream.of(refs).allMatch(Objects::nonNull))
.orElse(false);
}
public static String getProperty(Map<String, Object> properties, String propertyName, String defaultValue) {
String answer = (String) properties.get(propertyName);
if (!isNullOrEmpty(answer)) {
return answer;
}
return getSystemPropertyOrEnvVar(propertyName, defaultValue);
}
public static String getProperty(Map<String, Object> properties, String propertyName) {
return getProperty(properties, propertyName, null);
}
/**
* Converts string to URL encoded string.
*
* @param str Url as string
* @return returns encoded string
*/
public static final String toUrlEncoded(String str) {
try {
return URLEncoder.encode(str, StandardCharsets.UTF_8.displayName());
} catch (UnsupportedEncodingException exception) {
// Ignore
}
return null;
}
public static String getPluralFromKind(String kind) {
StringBuffer pluralBuffer = new StringBuffer(kind.toLowerCase(Locale.ROOT));
switch (kind) {
case "ComponentStatus":
case "Ingress":
case "RuntimeClass":
case "PriorityClass":
case "StorageClass":
pluralBuffer.append("es");
break;
case "NetworkPolicy":
case "PodSecurityPolicy":
// Delete last character
pluralBuffer.deleteCharAt(pluralBuffer.length() - 1);
pluralBuffer.append("ies");
break;
case "Endpoints":
break;
default:
pluralBuffer.append("s");
}
return pluralBuffer.toString();
}
/**
* Reads @Namespaced annotation in resource class to check whether
* resource is namespaced or not
*
* @param kubernetesResourceType class for resource
* @return boolean value indicating it's namespaced or not
*/
public static boolean isResourceNamespaced(Class kubernetesResourceType) {
return Namespaced.class.isAssignableFrom(kubernetesResourceType);
}
public static String getAnnotationValue(Class kubernetesResourceType, Class annotationClass) {
Annotation annotation = getAnnotation(kubernetesResourceType, annotationClass);
if (annotation instanceof ApiGroup) {
return ((ApiGroup) annotation).value();
} else if (annotation instanceof ApiVersion) {
return ((ApiVersion) annotation).value();
}
return null;
}
private static Annotation getAnnotation(Class kubernetesResourceType, Class annotationClass) {
return Arrays.stream(kubernetesResourceType.getAnnotations())
.filter(annotation -> annotation.annotationType().equals(annotationClass))
.findFirst()
.orElse(null);
}
/**
* Interpolates a String containing variable placeholders with the values provided in the valuesMap.
*
* <p> This method is intended to interpolate templates loaded from YAML and JSON files.
*
* <p> Placeholders are indicated by the dollar sign and curly braces ({@code ${VARIABLE_KEY}}).
*
* <p> Placeholders can also be indicated by the dollar sign and double curly braces ({@code ${{VARIABLE_KEY}}}),
* when this notation is used, the resulting value will be unquoted (if applicable), expected values should be JSON
* compatible.
*
* @see <a href="https://docs.openshift.com/container-platform/4.3/openshift_images/using-templates.html#templates-writing-parameters_using-templates">OpenShift Templates</a>
* @param valuesMap to interpolate in the String
* @param templateInput raw input containing a String with placeholders ready to be interpolated
* @return the interpolated String
*/
public static String interpolateString(String templateInput, Map<String, String> valuesMap) {
return Optional.ofNullable(valuesMap).orElse(Collections.emptyMap()).entrySet().stream()
.filter(entry -> entry.getKey() != null)
.filter(entry -> entry.getValue() != null)
.flatMap(entry -> {
final String key = entry.getKey();
final String value = entry.getValue();
return Stream.of(
new AbstractMap.SimpleEntry<>("${" + key + "}", value),
new AbstractMap.SimpleEntry<>("\"${{" + key + "}}\"", value),
new AbstractMap.SimpleEntry<>("${{" + key + "}}", value)
);
})
.map(explodedParam -> (Function<String, String>) s -> s.replace(explodedParam.getKey(), explodedParam.getValue()))
.reduce(Function.identity(), Function::andThen)
.apply(Objects.requireNonNull(templateInput, "templateInput is required"));
}
}