forked from kubernetes-client/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYaml.java
More file actions
496 lines (449 loc) · 16.7 KB
/
Copy pathYaml.java
File metadata and controls
496 lines (449 loc) · 16.7 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 2018 The Kubernetes 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 io.kubernetes.client.util;
import com.google.common.reflect.ClassPath;
import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.custom.Quantity;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import okio.ByteString;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;
public class Yaml {
private static Map<String, Class<?>> classes = new HashMap<>();
private static Map<String, String> apiGroups = new HashMap<>();
private static List<String> apiVersions = new ArrayList<>();
static final Logger logger = LoggerFactory.getLogger(Yaml.class);
private static void initApiGroupMap() {
apiGroups.put("Admissionregistration", "admissionregistration.k8s.io");
apiGroups.put("Apiextensions", "apiextensions.k8s.io");
apiGroups.put("Apiregistration", "apiregistration.k8s.io");
apiGroups.put("Apps", "apps");
apiGroups.put("Authentication", "authentication.k8s.io");
apiGroups.put("Authorization", "authorization.k8s.io");
apiGroups.put("Autoscaling", "autoscaling");
apiGroups.put("Extensions", "extensions");
apiGroups.put("Batch", "batch");
apiGroups.put("Certificates", "certificates.k8s.io");
apiGroups.put("Networking", "networking.k8s.io");
apiGroups.put("Policy", "policy");
apiGroups.put("RbacAuthorization", "rbac.authorization.k8s.io");
apiGroups.put("Scheduling", "scheduling.k8s.io");
apiGroups.put("Settings", "settings.k8s.io");
apiGroups.put("Storage", "storage.k8s.io");
}
private static void initApiVersionList() {
// Order important
apiVersions.add("V2beta1");
apiVersions.add("V2beta2");
apiVersions.add("V2alpha1");
apiVersions.add("V1beta2");
apiVersions.add("V1beta1");
apiVersions.add("V1alpha1");
apiVersions.add("V1");
}
private static Pair<String, String> getApiGroup(String name) {
MutablePair<String, String> parts = new MutablePair<>();
for (Map.Entry<String, String> entry : apiGroups.entrySet()) {
if (name.startsWith(entry.getKey())) {
parts.left = entry.getValue();
parts.right = name.substring(entry.getKey().length());
break;
}
}
if (parts.left == null) parts.right = name;
return parts;
}
private static Pair<String, String> getApiVersion(String name) {
MutablePair<String, String> parts = new MutablePair<>();
for (String version : apiVersions) {
if (name.startsWith(version)) {
parts.left = version.toLowerCase();
parts.right = name.substring(version.length());
break;
}
}
if (parts.left == null) parts.right = name;
return parts;
}
private static void initModelMap() throws IOException {
initApiGroupMap();
initApiVersionList();
ClassPath cp = ClassPath.from(Yaml.class.getClassLoader());
Set<ClassPath.ClassInfo> allClasses =
cp.getTopLevelClasses("io.kubernetes.client.openapi.models");
for (ClassPath.ClassInfo clazz : allClasses) {
String modelName = "";
Pair<String, String> nameParts = getApiGroup(clazz.getSimpleName());
modelName += nameParts.getLeft() == null ? "" : nameParts.getLeft() + "/";
nameParts = getApiVersion(nameParts.getRight());
modelName += nameParts.getLeft() == null ? "" : nameParts.getLeft() + "/";
modelName += nameParts.getRight();
classes.put(modelName, clazz.load());
}
}
static {
try {
initModelMap();
} catch (Exception ex) {
logger.error("Unexpected exception while loading classes: " + ex);
}
}
/**
* Add a mapping from API Group/version/kind to a Class to use when calling <code>load(...)</code>
* .
*
* <p>Shouldn't really be needed as most API Group/Version/Kind are loaded dynamically at startup.
*/
public static void addModelMap(String apiGroupVersion, String kind, Class<?> clazz) {
classes.put(apiGroupVersion + "/" + kind, clazz);
}
/**
* Load an API object from a YAML string representation. Returns a concrete typed object (e.g.
* V1Pod)
*
* @param content The YAML content
* @return An instantiation of the object.
* @throws IOException If an error occurs while reading the YAML.
*/
public static Object load(String content) throws IOException {
return load(new StringReader(content));
}
/**
* Load an API object from a YAML file. Returns a concrete typed object (e.g. V1Pod)
*
* @param f The file to load.
* @return An instantiation of the object.
* @throws IOException If an error occurs while reading the YAML.
*/
public static Object load(File f) throws IOException {
return load(new FileReader(f));
}
/**
* Load an API object from a stream of data. Returns a concrete typed object (e.g. V1Pod)
*
* @param reader The stream to load.
* @return An instantiation of the object.
* @throws IOException If an error occurs while reading the YAML.
*/
public static Object load(Reader reader) throws IOException {
Map<String, Object> data = getSnakeYaml().load(reader);
return modelMapper(data);
}
/**
* Load an API object from a YAML string representation. Returns a concrete typed object using the
* type specified.
*
* @param content The YAML content
* @param clazz The class of object to return.
* @return An instantiation of the object.
* @throws IOException If an error occurs while reading the YAML.
*/
public static <T> T loadAs(String content, Class<T> clazz) {
return getSnakeYaml().loadAs(new StringReader(content), clazz);
}
/**
* Load an API object from a YAML file. Returns a concrete typed object using the type specified.
*
* @param f The YAML file
* @param clazz The class of object to return.
* @return An instantiation of the object.
* @throws IOException If an error occurs while reading the YAML.
*/
public static <T> T loadAs(File f, Class<T> clazz) throws IOException {
return getSnakeYaml().loadAs(new FileReader(f), clazz);
}
/**
* Load an API object from a YAML stream. Returns a concrete typed object using the type
* specified.
*
* @param reader The YAML stream
* @param clazz The class of object to return.
* @return An instantiation of the object.
* @throws IOException If an error occurs while reading the YAML.
*/
public static <T> T loadAs(Reader reader, Class<T> clazz) {
return getSnakeYaml().loadAs(reader, clazz);
}
/**
* Load list of instantiated API objects from a YAML string representation. Returns list of
* concrete typed objects (e.g. { V1Pod, V1SERVICE })
*
* <p>Order of API objects in list will be preserved according to order of objects in YAML string.
*
* @param content The YAML content
* @return List of instantiated objects.
* @throws IOException If an error occurs while reading the YAML.
*/
public static List<Object> loadAll(String content) throws IOException {
return loadAll(new StringReader(content));
}
/**
* Load list of instantiated API objects from a YAML file. Returns list of concrete typed objects
* (e.g. { V1Pod, V1SERVICE })
*
* <p>Order of API objects in list will be preserved according to order of objects in YAML file.
*
* @param f The file to load.
* @return List of instantiated of the objects.
* @throws IOException If an error occurs while reading the YAML.
*/
public static List<Object> loadAll(File f) throws IOException {
return loadAll(new FileReader(f));
}
/**
* Load list of instantiated API objects from a stream of data. Returns list of concrete typed
* objects (e.g. { V1Pod, V1SERVICE })
*
* <p>Order of API objects in list will be preserved according to order of objects in stream of
* data.
*
* @param reader The stream to load.
* @return List of instantiated of the objects.
* @throws IOException If an error occurs while reading the YAML.
*/
public static List<Object> loadAll(Reader reader) throws IOException {
Iterable<Object> iterable = getSnakeYaml().loadAll(reader);
List<Object> list = new ArrayList<Object>();
for (Object object : iterable) {
if (object != null) {
try {
list.add(modelMapper((Map<String, Object>) object));
} catch (ClassCastException ex) {
logger.error("Unexpected exception while casting: " + ex);
}
}
}
return list;
}
/**
* Takes an API object and returns a YAML String representing that object.
*
* @param object The API object to dump.
* @return A YAML String representing the API object.
*/
public static String dump(Object object) {
return getSnakeYaml().dump(object);
}
/**
* Takes an API object and writes a YAML string representing that object to the writer.
*
* @param object The API object to dump
* @param writer The writer to write the YAML to.
*/
public static void dump(Object object, Writer writer) {
getSnakeYaml().dump(object, writer);
}
/**
* Takes an Iterator of YAML API objects and returns a YAML string representing all of them
*
* @param data The list of YAML API objects
* @return A String representing the list of YAML API objects.
*/
public static String dumpAll(Iterator<? extends Object> data) {
return getSnakeYaml().dumpAll(data);
}
/**
* Takes an Iterator of YAML API objects and writes a YAML String representing all of them.
*
* @param data The list of YAML API objects.
* @param output The writer to output the YAML String to.
*/
public static void dumpAll(Iterator<? extends Object> data, Writer output) {
getSnakeYaml().dumpAll(data, output);
}
/** Defines constructor logic for custom types in this library. */
public static class CustomConstructor extends Constructor {
@Override
protected Object constructObject(Node node) {
if (node.getType() == IntOrString.class) {
return constructIntOrString((ScalarNode) node);
}
if (node.getType() == byte[].class) {
return constructByteArray((ScalarNode) node);
}
if (node.getType() == org.joda.time.DateTime.class) {
return constructDateTime((ScalarNode) node);
}
return super.constructObject(node);
}
private IntOrString constructIntOrString(ScalarNode node) {
try {
return new IntOrString(Integer.parseInt(node.getValue()));
} catch (NumberFormatException err) {
return new IntOrString(node.getValue());
}
}
private byte[] constructByteArray(ScalarNode node) {
return ByteString.decodeBase64(node.getValue()).toByteArray();
}
private Object constructDateTime(ScalarNode node) {
return new DateTime(((ScalarNode) node).getValue(), DateTimeZone.UTC);
}
}
public static class CustomRepresenter extends Representer {
public CustomRepresenter() {
this.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
this.representers.put(IntOrString.class, new RepresentIntOrString());
this.representers.put(byte[].class, new RepresentByteArray());
this.representers.put(Quantity.class, new RepresentQuantity());
this.representers.put(DateTime.class, new RepresentDateTime());
}
private class RepresentDateTime implements Represent {
@Override
public Node representData(Object data) {
return CustomRepresenter.this.representData(data.toString());
}
}
private class RepresentIntOrString implements Represent {
@Override
public Node representData(Object data) {
IntOrString intOrString = (IntOrString) data;
if (intOrString.isInteger()) {
return CustomRepresenter.this.representData(intOrString.getIntValue());
} else {
return CustomRepresenter.this.representData(intOrString.getStrValue());
}
}
}
private class RepresentByteArray implements Represent {
@Override
public Node representData(Object data) {
String value = ByteString.of((byte[]) data).base64();
return representScalar(Tag.STR, value);
}
}
private class RepresentQuantity implements Represent {
@Override
public Node representData(Object data) {
Quantity quantity = (Quantity) data;
return representScalar(Tag.STR, quantity.toSuffixedString());
}
}
/**
* This returns the ordering of properties that by convention should appear at the beginning of
* a Yaml object in Kubernetes.
*/
private int getPropertyPosition(String property) {
switch (property) {
case "apiVersion":
return 0;
case "kind":
return 1;
case "metadata":
return 2;
case "spec":
return 3;
case "type":
return 4;
default:
return Integer.MAX_VALUE;
}
}
@Override
protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) {
MappingNode node = super.representJavaBean(properties, javaBean);
// Always set the tag to MAP so that SnakeYaml doesn't print out the class name as a tag.
node.setTag(Tag.MAP);
// Sort the output of our map so that we put certain keys, such as apiVersion, first.
Collections.sort(
node.getValue(),
new Comparator<NodeTuple>() {
@Override
public int compare(NodeTuple a, NodeTuple b) {
String nameA = ((ScalarNode) a.getKeyNode()).getValue();
String nameB = ((ScalarNode) b.getKeyNode()).getValue();
int intCompare =
Integer.compare(getPropertyPosition(nameA), getPropertyPosition(nameB));
if (intCompare != 0) {
return intCompare;
} else {
return nameA.compareTo(nameB);
}
}
});
return node;
}
@Override
protected NodeTuple representJavaBeanProperty(
Object javaBean, Property property, Object propertyValue, Tag customTag) {
// returning null for a null property value means we won't output it in the Yaml
if (propertyValue == null) {
return null;
}
return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
}
}
/** @return An instantiated SnakeYaml Object. */
public static org.yaml.snakeyaml.Yaml getSnakeYaml() {
return new org.yaml.snakeyaml.Yaml(new CustomConstructor(), new CustomRepresenter());
}
/**
* @param data Map that will be converted to concrete API object.
* @return An instantiation of the object.
* @throws IOException
*/
private static Object modelMapper(Map<String, Object> data) throws IOException {
String kind = (String) data.get("kind");
if (kind == null) {
throw new IOException("Missing kind in YAML file!");
}
String apiVersion = (String) data.get("apiVersion");
if (apiVersion == null) {
throw new IOException("Missing apiVersion in YAML file!");
}
Class<?> clazz = (Class<?>) classes.get(apiVersion + "/" + kind);
if (clazz == null) {
// Attempt to detect class from version and kind alone
if (apiVersion.contains("/")) {
clazz = (Class<?>) classes.get(apiVersion.split("/")[1] + "/" + kind);
}
}
if (clazz == null) {
throw new IOException(
"Unknown apiVersionKind: "
+ apiVersion
+ "/"
+ kind
+ " known kinds are: "
+ classes.toString());
}
return loadAs(new StringReader(getSnakeYaml().dump(data)), clazz);
}
}