/
OperationSupport.java
601 lines (540 loc) · 24 KB
/
OperationSupport.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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/**
* 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.dsl.base;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.api.model.DeleteOptions;
import io.fabric8.kubernetes.api.model.DeletionPropagation;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Status;
import io.fabric8.kubernetes.api.model.StatusBuilder;
import io.fabric8.kubernetes.api.model.autoscaling.v1.Scale;
import io.fabric8.kubernetes.api.model.extensions.DeploymentRollback;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.internal.VersionUsageUtils;
import io.fabric8.kubernetes.client.utils.Serialization;
import io.fabric8.kubernetes.client.utils.URLUtils;
import io.fabric8.kubernetes.client.utils.Utils;
import io.fabric8.zjsonpatch.JsonDiff;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import static io.fabric8.kubernetes.client.internal.PatchUtils.patchMapper;
public class OperationSupport {
public static final MediaType JSON = MediaType.parse("application/json");
public static final MediaType JSON_PATCH = MediaType.parse("application/json-patch+json");
public static final MediaType STRATEGIC_MERGE_JSON_PATCH = MediaType.parse("application/strategic-merge-patch+json");
protected static final ObjectMapper JSON_MAPPER = Serialization.jsonMapper();
protected static final ObjectMapper YAML_MAPPER = Serialization.yamlMapper();
private static final String CLIENT_STATUS_FLAG = "CLIENT_STATUS_FLAG";
protected OperationContext context;
protected final OkHttpClient client;
protected final Config config;
protected final String resourceT;
protected String namespace;
protected String name;
protected String apiGroupName;
protected String apiGroupVersion;
public OperationSupport() {
this (new OperationContext());
}
public OperationSupport(OkHttpClient client, Config config) {
this(new OperationContext().withOkhttpClient(client).withConfig(config));
}
public OperationSupport(OkHttpClient client, Config config, String namespace, DeletionPropagation propagationPolicy) {
this(new OperationContext().withOkhttpClient(client).withConfig(config).withNamespace(namespace).withPropagationPolicy(propagationPolicy));
}
public OperationSupport(OperationContext ctx) {
this.context = ctx;
this.client = ctx.getClient();
this.config = ctx.getConfig();
this.resourceT = ctx.getPlural();
this.namespace = ctx.getNamespace();
this.name = ctx.getName() ;
this.apiGroupName = ctx.getApiGroupName();
if (ctx.getApiGroupVersion() != null) {
this.apiGroupVersion = ctx.getApiGroupVersion();
} else if (ctx.getConfig() != null) {
this.apiGroupVersion = ctx.getConfig().getApiVersion();
} else {
this.apiGroupVersion = "v1";
}
}
public String getAPIGroup() {
return apiGroupName;
}
public String getAPIVersion() {
return apiGroupVersion;
}
public String getResourceT() {
return resourceT;
}
public String getNamespace() {
return namespace;
}
public String getName() {
return name;
}
public boolean isResourceNamespaced() {
return true;
}
public URL getRootUrl() {
try {
if (!Utils.isNullOrEmpty(apiGroupName)) {
return new URL(URLUtils.join(config.getMasterUrl().toString(), "apis", apiGroupName, apiGroupVersion));
}
return new URL(URLUtils.join(config.getMasterUrl().toString(), "api", apiGroupVersion));
} catch (MalformedURLException e) {
throw KubernetesClientException.launderThrowable(e);
}
}
public URL getNamespacedUrl(String namespace) throws MalformedURLException {
URL requestUrl = getRootUrl();
if (!isResourceNamespaced()) {
//if resource is not namespaced don't even bother to check the namespace.
} else if (Utils.isNotNullOrEmpty(namespace)) {
requestUrl = new URL(URLUtils.join(requestUrl.toString(), "namespaces", namespace));
}
requestUrl = new URL(URLUtils.join(requestUrl.toString(), resourceT));
return requestUrl;
}
public URL getNamespacedUrl() throws MalformedURLException {
return getNamespacedUrl(getNamespace());
}
public <T> URL getNamespacedUrl(T item) throws MalformedURLException {
return getNamespacedUrl(checkNamespace(item));
}
public URL getResourceUrl(String namespace, String name) throws MalformedURLException {
if (name == null) {
return getNamespacedUrl(namespace);
}
return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name));
}
public URL getResourceUrl() throws MalformedURLException {
if (name == null) {
return getNamespacedUrl();
}
return new URL(URLUtils.join(getNamespacedUrl().toString(), name));
}
protected <T> String checkNamespace(T item) {
String operationNs = getNamespace();
String itemNs = (item instanceof HasMetadata && ((HasMetadata)item).getMetadata() != null) ? ((HasMetadata) item).getMetadata().getNamespace() : null;
if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) {
if (!isResourceNamespaced()) {
return null;
} else {
throw new KubernetesClientException("Namespace not specified. But operation requires namespace.");
}
} else if (Utils.isNullOrEmpty(itemNs)) {
return operationNs;
} else if (Utils.isNullOrEmpty(operationNs)) {
return itemNs;
} else if (itemNs.equals(operationNs)) {
return itemNs;
}
throw new KubernetesClientException("Namespace mismatch. Item namespace:" + itemNs + ". Operation namespace:" + operationNs + ".");
}
protected <T> String checkName(T item) {
String operationName = getName();
String itemName = item instanceof HasMetadata ? ((HasMetadata) item).getMetadata().getName() : null;
if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) {
return null;
} else if (Utils.isNullOrEmpty(itemName)) {
return operationName;
} else if (Utils.isNullOrEmpty(operationName)) {
return itemName;
} else if (itemName.equals(operationName)) {
return itemName;
}
throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + ".");
}
protected <T> T handleMetric(String resourceUrl, Class<T> type) throws InterruptedException, IOException, ExecutionException {
Request.Builder requestBuilder = new Request.Builder()
.get()
.url(resourceUrl);
return handleResponse(requestBuilder, type);
}
protected <T> void handleDelete(T resource, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, IOException {
handleDelete(getResourceUrl(checkNamespace(resource), checkName(resource)), gracePeriodSeconds, propagationPolicy, cascading);
}
protected void handleDelete(URL requestUrl, long gracePeriodSeconds, DeletionPropagation propagationPolicy, boolean cascading) throws ExecutionException, InterruptedException, IOException {
RequestBody requestBody = null;
DeleteOptions deleteOptions = new DeleteOptions();
if (gracePeriodSeconds >= 0) {
deleteOptions.setGracePeriodSeconds(gracePeriodSeconds);
}
/*
* Either the propagation policy or the orphan dependent (deprecated) property must be set, but not both.
*/
if (propagationPolicy != null) {
deleteOptions.setPropagationPolicy(propagationPolicy.toString());
} else {
deleteOptions.setOrphanDependents(!cascading);
}
requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deleteOptions));
Request.Builder requestBuilder = new Request.Builder().delete(requestBody).url(requestUrl);
handleResponse(requestBuilder, null, Collections.<String, String>emptyMap());
}
/**
* Create a resource.
*
* @param resource resource provided
* @param outputType resource type you want as output
* @param <T> template argument for output type
* @param <I> template argument for resource
*
* @return returns de-serialized version of apiserver response in form of type provided
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T, I> T handleCreate(I resource, Class<T> outputType) throws ExecutionException, InterruptedException, IOException {
RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(resource));
Request.Builder requestBuilder = new Request.Builder().post(body).url(getNamespacedUrl(checkNamespace(resource)));
return handleResponse(requestBuilder, outputType, Collections.<String, String>emptyMap());
}
/**
* Replace a resource.
*
* @param updated updated object
* @param type type of the object provided
* @param <T> template argument provided
*
* @return returns de-serialized version of api server response
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleReplace(T updated, Class<T> type) throws ExecutionException, InterruptedException, IOException {
return handleReplace(updated, type, Collections.<String, String>emptyMap());
}
/**
* Replace a resource, optionally performing placeholder substitution to the response.
*
* @param updated updated object
* @param type type of object provided
* @param parameters a HashMap containing parameters for processing object
* @param <T> template argument provided
*
* @return returns de-serialized version of api server response.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleReplace(T updated, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException {
RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(updated));
Request.Builder requestBuilder = new Request.Builder().put(body).url(getResourceUrl(checkNamespace(updated), checkName(updated)));
return handleResponse(requestBuilder, type, parameters);
}
protected <T> T handleStatusUpdate(T updated, Class<T> type) throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(updated));
Request.Builder requestBuilder = new Request.Builder().put(body).url(getResourceUrl(checkNamespace(updated), checkName(updated)) + "/status");
return handleResponse(requestBuilder, type);
}
/**
* Send an http patch and handle the response.
*
* @param current current object
* @param updated updated object
* @param type type of object
* @param <T> template argument provided
*
* @return returns de-serialized version of api server response
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handlePatch(T current, T updated, Class<T> type) throws ExecutionException, InterruptedException, IOException {
JsonNode diff = JsonDiff.asJson(patchMapper().valueToTree(current), patchMapper().valueToTree(updated));
RequestBody body = RequestBody.create(JSON_PATCH, JSON_MAPPER.writeValueAsString(diff));
Request.Builder requestBuilder = new Request.Builder().patch(body).url(getResourceUrl(checkNamespace(updated), checkName(updated)));
return handleResponse(requestBuilder, type, Collections.<String, String>emptyMap());
}
/**
* Send an http patch and handle the response.
*
* @param current current object
* @param patchForUpdate updated object spec as json string
* @param type type of object
* @param <T> template argument provided
*
* @return returns de-serialized version of api server response
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handlePatch(T current, Map<String, Object> patchForUpdate, Class<T> type) throws ExecutionException, InterruptedException, IOException {
RequestBody body = RequestBody.create(STRATEGIC_MERGE_JSON_PATCH, JSON_MAPPER.writeValueAsString(patchForUpdate));
Request.Builder requestBuilder = new Request.Builder().patch(body).url(getResourceUrl(checkNamespace(current), checkName(current)));
return handleResponse(requestBuilder, type, Collections.<String, String>emptyMap());
}
/**
* Replace Scale of specified Kubernetes Resource
*
* @param resourceUrl Kubernetes resource URL
* @param scale Scale object which we want to inject
* @return updated Scale object
* @throws ExecutionException in case of any execution exception
* @throws InterruptedException in case thread is interrupted
* @throws IOException in some other I/O problem
*/
protected Scale handleScale(String resourceUrl, Scale scale) throws ExecutionException, InterruptedException, IOException {
Request.Builder requestBuilder;
if (scale != null) {
RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(scale));
requestBuilder = new Request.Builder().put(body).url(resourceUrl + "/scale");
} else {
requestBuilder = new Request.Builder().get().url(resourceUrl + "/scale");
}
return handleResponse(requestBuilder, Scale.class);
}
/**
* Create rollback of a Deployment
*
* @param resourceUrl resource url
* @param deploymentRollback DeploymentRollback resource
* @return Status
* @throws ExecutionException in case of any execution exception
* @throws InterruptedException in case thread is interrupted
* @throws IOException in some other I/O problem
*/
protected Status handleDeploymentRollback(String resourceUrl, DeploymentRollback deploymentRollback) throws ExecutionException, InterruptedException, IOException {
RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(deploymentRollback));
Request.Builder requestBuilder = new Request.Builder().post(body).url(resourceUrl + "/rollback");
return handleResponse(requestBuilder, Status.class);
}
/**
* Send an http get.
*
* @param resourceUrl resource URL to be processed
* @param type type of resource
* @param <T> template argument provided
*
* @return returns a deserialized object as api server response of provided type.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleGet(URL resourceUrl, Class<T> type) throws ExecutionException, InterruptedException, IOException {
return handleGet(resourceUrl, type, Collections.<String, String>emptyMap());
}
/**
* Send an http, optionally performing placeholder substitution to the response.
*
* @param resourceUrl resource URL to be processed
* @param type type of resource
* @param parameters A HashMap of strings containing parameters to be passed in request
* @param <T> template argument provided
*
* @return Returns a deserialized object as api server response of provided type.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleGet(URL resourceUrl, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException {
Request.Builder requestBuilder = new Request.Builder().get().url(resourceUrl);
return handleResponse(requestBuilder, type, parameters);
}
/**
* Send an http request and handle the response.
*
* @param requestBuilder Request Builder object
* @param type type of resource
* @param <T> template argument provided
*
* @return Returns a de-serialized object as api server response of provided type.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleResponse(Request.Builder requestBuilder, Class<T> type) throws ExecutionException, InterruptedException, IOException {
return handleResponse(requestBuilder, type, Collections.<String, String>emptyMap());
}
/**
* Send an http request and handle the response, optionally performing placeholder substitution to the response.
*
* @param requestBuilder request builder
* @param type type of object
* @param parameters a hashmap containing parameters
* @param <T> template argument provided
*
* @return Returns a de-serialized object as api server response of provided type.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleResponse(Request.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException {
return handleResponse(client, requestBuilder, type, parameters);
}
/**
* Send an http request and handle the response.
*
* @param client OkHttp client object
* @param requestBuilder request builder
* @param type type of object
* @param <T> template argument provided
*
* @return Returns a de-serialized object as api server response of provided type.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class<T> type) throws ExecutionException, InterruptedException, IOException {
return handleResponse(client, requestBuilder, type, Collections.<String, String>emptyMap());
}
/**
* Send an http request and handle the response, optionally performing placeholder substitution to the response.
*
* @param client OkHttp client provided
* @param requestBuilder Request builder
* @param type Type of object provided
* @param parameters A hashmap containing parameters
* @param <T> Template argument provided
*
* @return Returns a de-serialized object as api server response of provided type.
* @throws ExecutionException Execution Exception
* @throws InterruptedException Interrupted Exception
* @throws IOException IOException
*/
protected <T> T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, IOException {
VersionUsageUtils.log(this.resourceT, this.apiGroupVersion);
Request request = requestBuilder.build();
Response response = client.newCall(request).execute();
try (ResponseBody body = response.body()) {
assertResponseCode(request, response);
if (type != null) {
try (InputStream bodyInputStream = body.byteStream()) {
return Serialization.unmarshal(bodyInputStream, type, parameters);
}
} else {
return null;
}
} catch (Exception e) {
if (e instanceof KubernetesClientException) {
throw e;
}
throw requestException(request, e);
} finally {
if(response != null && response.body() != null) {
response.body().close();
}
}
}
/**
* Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not.
*
* @param request The {#link Request} object.
* @param response The {@link Response} object.
*/
protected void assertResponseCode(Request request, Response response) {
int statusCode = response.code();
String customMessage = config.getErrorMessages().get(statusCode);
if (response.isSuccessful()) {
return;
} else if (customMessage != null) {
throw requestFailure(request, createStatus(statusCode, combineMessages(customMessage, createStatus(response))));
} else {
throw requestFailure(request, createStatus(response));
}
}
private String combineMessages(String customMessage, Status defaultStatus) {
if (defaultStatus != null) {
String message = defaultStatus.getMessage();
if (message != null && message.length() > 0) {
return customMessage + " " + message;
}
}
return customMessage;
}
public static Status createStatus(Response response) {
String statusMessage = "";
ResponseBody body = response != null ? response.body() : null;
int statusCode = response != null ? response.code() : 0;
try {
if (response == null) {
statusMessage = "No response";
} else if (body != null) {
statusMessage = body.string();
} else if (response.message() != null) {
statusMessage = response.message();
}
Status status = JSON_MAPPER.readValue(statusMessage, Status.class);
if (status.getCode() == null) {
status = new StatusBuilder(status).withCode(statusCode).build();
}
return status;
} catch (JsonParseException e) {
return createStatus(statusCode, statusMessage);
} catch (IOException e) {
return createStatus(statusCode, statusMessage);
}
}
public static Status createStatus(int statusCode, String message) {
Status status = new StatusBuilder()
.withCode(statusCode)
.withMessage(message)
.build();
status.getAdditionalProperties().put(CLIENT_STATUS_FLAG, "true");
return status;
}
public static KubernetesClientException requestFailure(Request request, Status status) {
StringBuilder sb = new StringBuilder();
sb.append("Failure executing: ").append(request.method())
.append(" at: ").append(request.url().toString()).append(".");
if (status.getMessage() != null && !status.getMessage().isEmpty()) {
sb.append(" Message: ").append(status.getMessage()).append(".");
}
if (status != null && !status.getAdditionalProperties().containsKey(CLIENT_STATUS_FLAG)) {
sb.append(" Received status: ").append(status).append(".");
}
return new KubernetesClientException(sb.toString(), status.getCode(), status);
}
public static KubernetesClientException requestException(Request request, Exception e) {
StringBuilder sb = new StringBuilder();
sb.append("Error executing: ").append(request.method())
.append(" at: ").append(request.url().toString())
.append(". Cause: ").append(e.getMessage());
return new KubernetesClientException(sb.toString(), e);
}
protected static <T> T unmarshal(InputStream is) {
return Serialization.unmarshal(is);
}
protected static <T> T unmarshal(InputStream is, final Class<T> type) {
return Serialization.unmarshal(is, type);
}
protected static <T> T unmarshal(InputStream is, TypeReference<T> type) {
return Serialization.unmarshal(is, type);
}
protected static <T> Map getObjectValueAsMap(T object) {
return JSON_MAPPER.convertValue(object, Map.class);
}
public Config getConfig() {
return config;
}
}