This repository has been archived by the owner on Jun 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 202
/
ApplyService.java
1412 lines (1319 loc) · 65.8 KB
/
ApplyService.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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2016 Red Hat, Inc.
*
* Red Hat licenses this file to you 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.maven.core.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ReplicationControllerSpec;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceAccount;
import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition;
import io.fabric8.kubernetes.api.model.apps.DaemonSet;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import io.fabric8.kubernetes.api.model.batch.Job;
import io.fabric8.kubernetes.api.model.extensions.Ingress;
import io.fabric8.kubernetes.api.model.rbac.Role;
import io.fabric8.kubernetes.api.model.rbac.RoleBinding;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
import io.fabric8.maven.core.util.FileUtil;
import io.fabric8.maven.core.util.ResourceUtil;
import io.fabric8.maven.core.util.kubernetes.KubernetesClientUtil;
import io.fabric8.maven.core.util.kubernetes.KubernetesHelper;
import io.fabric8.maven.core.util.kubernetes.OpenshiftHelper;
import io.fabric8.maven.core.util.kubernetes.UserConfigurationCompare;
import io.fabric8.maven.docker.util.Logger;
import io.fabric8.openshift.api.model.BuildConfig;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.DoneableImageStream;
import io.fabric8.openshift.api.model.ImageStream;
import io.fabric8.openshift.api.model.ImageStreamSpec;
import io.fabric8.openshift.api.model.OAuthClient;
import io.fabric8.openshift.api.model.Project;
import io.fabric8.openshift.api.model.ProjectRequest;
import io.fabric8.openshift.api.model.ProjectRequestBuilder;
import io.fabric8.openshift.api.model.Route;
import io.fabric8.openshift.api.model.TagReference;
import io.fabric8.openshift.api.model.Template;
import io.fabric8.openshift.client.OpenShiftClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static io.fabric8.maven.core.util.kubernetes.KubernetesHelper.getKind;
import static io.fabric8.maven.core.util.kubernetes.KubernetesHelper.getName;
import static io.fabric8.maven.core.util.kubernetes.KubernetesHelper.getOrCreateLabels;
import static io.fabric8.maven.core.util.kubernetes.KubernetesHelper.getOrCreateMetadata;
/**
* Applies DTOs to the current Kubernetes master
*/
public class ApplyService {
private final KubernetesClient kubernetesClient;
private final Logger log;
private boolean allowCreate = true;
private boolean servicesOnlyMode;
private boolean ignoreServiceMode;
private boolean ignoreRunningOAuthClients = true;
private boolean ignoreBoundPersistentVolumeClaims = true;
private boolean rollingUpgrade;
private boolean processTemplatesLocally;
private File logJsonDir;
private File basedir;
private boolean supportOAuthClients;
private boolean deletePodsOnReplicationControllerUpdate = true;
private String namespace = KubernetesHelper.getDefaultNamespace();
private boolean rollingUpgradePreserveScale = true;
private boolean recreateMode;
private PatchService patchService;
// This map is to track projects created.
private static Set<String> projectsCreated = new HashSet<>();
public ApplyService(KubernetesClient kubernetesClient, Logger log) {
this.kubernetesClient = kubernetesClient;
this.patchService = new PatchService(kubernetesClient, log);
this.log = log;
}
/**
* Applies the given DTOs onto the Kubernetes master
*/
public void apply(Object dto, String sourceName) throws Exception {
if (dto instanceof List) {
List list = (List) dto;
for (Object element : list) {
if (dto == element) {
log.warn("Found recursive nested object for " + dto + " of class: " + dto.getClass().getName());
continue;
}
apply(element, sourceName);
}
} else if (dto instanceof KubernetesList) {
applyList((KubernetesList) dto, sourceName);
} else if (dto != null) {
applyEntity(dto, sourceName);
}
}
/**
* Applies the given DTOs onto the Kubernetes master
*/
private void applyEntity(Object dto, String sourceName) throws Exception {
if (dto instanceof Pod) {
applyPod((Pod) dto, sourceName);
} else if (dto instanceof ReplicationController) {
applyReplicationController((ReplicationController) dto, sourceName);
} else if (dto instanceof Service) {
applyService((Service) dto, sourceName);
} else if (dto instanceof Route) {
applyRoute((Route) dto, sourceName);
} else if (dto instanceof BuildConfig) {
applyBuildConfig((BuildConfig) dto, sourceName);
} else if (dto instanceof DeploymentConfig) {
DeploymentConfig resource = (DeploymentConfig) dto;
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
applyResource(resource, sourceName, openShiftClient.deploymentConfigs());
} else {
log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
}
} else if (dto instanceof RoleBinding) {
applyRoleBinding((RoleBinding) dto, sourceName);
} else if (dto instanceof Role) {
Role resource = (Role) dto;
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
applyResource(resource, sourceName, openShiftClient.rbac().roles());
} else {
log.warn("Not connected to OpenShift cluster so cannot apply entity " + dto);
}
} else if (dto instanceof ImageStream) {
applyImageStream((ImageStream) dto, sourceName);
} else if (dto instanceof OAuthClient) {
applyOAuthClient((OAuthClient) dto, sourceName);
} else if (dto instanceof Template) {
applyTemplate((Template) dto, sourceName);
} else if (dto instanceof ServiceAccount) {
applyServiceAccount((ServiceAccount) dto, sourceName);
} else if (dto instanceof Secret) {
applySecret((Secret) dto, sourceName);
} else if (dto instanceof ConfigMap) {
applyResource((ConfigMap) dto, sourceName, kubernetesClient.configMaps());
} else if (dto instanceof DaemonSet) {
applyResource((DaemonSet) dto, sourceName, kubernetesClient.apps().daemonSets());
} else if (dto instanceof Deployment) {
applyResource((Deployment) dto, sourceName, kubernetesClient.extensions().deployments());
} else if (dto instanceof ReplicaSet) {
applyResource((ReplicaSet) dto, sourceName, kubernetesClient.extensions().replicaSets());
} else if (dto instanceof StatefulSet) {
applyResource((StatefulSet) dto, sourceName, kubernetesClient.apps().statefulSets());
} else if (dto instanceof Ingress) {
applyResource((Ingress) dto, sourceName, kubernetesClient.extensions().ingresses());
} else if (dto instanceof PersistentVolumeClaim) {
applyPersistentVolumeClaim((PersistentVolumeClaim) dto, sourceName);
}else if (dto instanceof CustomResourceDefinition) {
applyCustomResourceDefinition((CustomResourceDefinition) dto, sourceName);
} else if (dto instanceof Job) {
applyJob((Job) dto, sourceName);
} else if (dto instanceof HasMetadata) {
HasMetadata entity = (HasMetadata) dto;
try {
log.info("Applying " + getKind(entity) + " " + getName(entity) + " from " + sourceName);
kubernetesClient.resource(entity).inNamespace(getNamespace(entity)).createOrReplace();
} catch (Exception e) {
onApplyError("Failed to create " + getKind(entity) + " from " + sourceName + ". " + e, e);
}
} else {
throw new IllegalArgumentException("Unknown entity type " + dto);
}
}
public void applyOAuthClient(OAuthClient entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
if (supportOAuthClients) {
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
if (isServicesOnlyMode()) {
log.debug("Only processing Services right now so ignoring OAuthClient: " + id);
return;
}
OAuthClient old = openShiftClient.oAuthClients().withName(id).get();
if (isRunning(old)) {
if (isIgnoreRunningOAuthClients()) {
log.info("Not updating the OAuthClient which are shared across namespaces as its already running");
return;
}
if (UserConfigurationCompare.configEqual(entity, old)) {
log.info("OAuthClient has not changed so not doing anything");
} else {
if (isRecreateMode()) {
openShiftClient.oAuthClients().withName(id).delete();
doCreateOAuthClient(entity, sourceName);
} else {
try {
Object answer = openShiftClient.oAuthClients().withName(id).replace(entity);
log.info("Updated OAuthClient result: " + answer);
} catch (Exception e) {
onApplyError("Failed to update OAuthClient from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating an OAuthClient from " + sourceName + " name " + getName(entity));
} else {
doCreateOAuthClient(entity, sourceName);
}
}
}
}
}
protected void doCreateOAuthClient(OAuthClient entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
Object result = null;
try {
result = openShiftClient.oAuthClients().create(entity);
} catch (Exception e) {
onApplyError("Failed to create OAuthClient from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
/**
* Creates/updates the template and processes it returning the processed DTOs
*/
public Object applyTemplate(Template entity, String sourceName) throws Exception {
installTemplate(entity, sourceName);
return processTemplate(entity, sourceName);
}
/**
* Installs the template into the namespace without processing it
*/
public void installTemplate(Template entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient == null) {
// lets not install the template on Kubernetes!
return;
}
if (!isProcessTemplatesLocally()) {
String namespace = getNamespace(entity);
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
Template old = openShiftClient.templates().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
log.info("Template has not changed so not doing anything");
} else {
boolean recreateMode = isRecreateMode();
// TODO seems you can't update templates right now
recreateMode = true;
if (recreateMode) {
openShiftClient.templates().inNamespace(namespace).withName(id).delete();
doCreateTemplate(entity, namespace, sourceName);
} else {
log.info("Updating a Template from " + sourceName);
try {
Object answer = openShiftClient.templates().inNamespace(namespace).withName(id).replace(entity);
log.info("Updated Template: " + answer);
} catch (Exception e) {
onApplyError("Failed to update Template from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateTemplate(entity, namespace, sourceName);
}
}
}
}
public OpenShiftClient getOpenShiftClient() {
return OpenshiftHelper.asOpenShiftClient(kubernetesClient);
}
protected void doCreateTemplate(Template entity, String namespace, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
log.info("Creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
try {
Object answer = openShiftClient.templates().inNamespace(namespace).create(entity);
logGeneratedEntity("Created Template: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to Template entity from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
/**
* Creates/updates a service account and processes it returning the processed DTOs
*/
public void applyServiceAccount(ServiceAccount serviceAccount, String sourceName) throws Exception {
String namespace = getNamespace(serviceAccount);
String id = getName(serviceAccount);
Objects.requireNonNull(id, "No name for " + serviceAccount + " " + sourceName);
if (isServicesOnlyMode()) {
log.debug("Only processing Services right now so ignoring ServiceAccount: " + id);
return;
}
ServiceAccount old = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(serviceAccount, old)) {
log.info("ServiceAccount has not changed so not doing anything");
} else {
if (isRecreateMode()) {
kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).delete();
doCreateServiceAccount(serviceAccount, namespace, sourceName);
} else {
log.info("Updating a ServiceAccount from " + sourceName);
try {
Object answer = kubernetesClient.serviceAccounts().inNamespace(namespace).withName(id).replace(serviceAccount);
logGeneratedEntity("Updated ServiceAccount: ", namespace, serviceAccount, answer);
} catch (Exception e) {
onApplyError("Failed to update ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName(serviceAccount));
} else {
doCreateServiceAccount(serviceAccount, namespace, sourceName);
}
}
}
protected void doCreateServiceAccount(ServiceAccount serviceAccount, String namespace, String sourceName) {
log.info("Creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName
(serviceAccount));
try {
Object answer;
if (StringUtils.isNotBlank(namespace)) {
answer = kubernetesClient.serviceAccounts().inNamespace(namespace).create(serviceAccount);
} else {
answer = kubernetesClient.serviceAccounts().inNamespace(this.namespace).create(serviceAccount);
}
logGeneratedEntity("Created ServiceAccount: ", namespace, serviceAccount, answer);
} catch (Exception e) {
onApplyError("Failed to create ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount, e);
}
}
public void applyPersistentVolumeClaim(PersistentVolumeClaim entity, String sourceName) throws Exception {
// we cannot update PVCs
boolean alwaysRecreate = true;
String namespace = getNamespace(entity);
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
if (isServicesOnlyMode()) {
log.debug("Only processing Services right now so ignoring PersistentVolumeClaim: " + id);
return;
}
PersistentVolumeClaim old = kubernetesClient.persistentVolumeClaims().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
log.info("PersistentVolumeClaim has not changed so not doing anything");
} else {
if (alwaysRecreate || isRecreateMode()) {
if (!isRecreateMode() && isIgnoreBoundPersistentVolumeClaims() && isBound(old)) {
log.warn("PersistentVolumeClaim " + id + " in namespace " + namespace + " is already bound and will not be replaced with the new one from " + sourceName);
} else {
log.info("Deleting PersistentVolumeClaim from namespace " + namespace + " with name " + id);
kubernetesClient.persistentVolumeClaims().inNamespace(namespace).withName(id).delete();
log.info("Deleted PersistentVolumeClaim from namespace " + namespace + " with name " + id);
doCreatePersistentVolumeClaim(entity, namespace, sourceName);
}
} else {
log.info("Updating a PersistentVolumeClaim from " + sourceName);
try {
HasMetadata answer = patchService.compareAndPatchEntity(namespace, entity, old);
logGeneratedEntity("Updated PersistentVolumeClaim: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to update PersistentVolumeClaim from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a PersistentVolumeClaim from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreatePersistentVolumeClaim(entity, namespace, sourceName);
}
}
}
public void applyCustomResourceDefinition(CustomResourceDefinition entity, String sourceName) {
String namespace = getNamespace(entity);
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
if (isServicesOnlyMode()) {
log.debug("Only processing Services right now so ignoring Custom Resource Definition: " + namespace + ":" + id);
return;
}
CustomResourceDefinition old = kubernetesClient.customResourceDefinitions().withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
log.info("Custom Resource Definition has not changed so not doing anything");
} else {
if (isRecreateMode()) {
log.info("Deleting Custom Resource Definition: " + id);
kubernetesClient.customResourceDefinitions().withName(id).delete();
doCreateCustomResourceDefinition(entity, sourceName);
} else {
log.info("Updating a Custom Resource Definition from " + sourceName + " name " + getName(entity));
try {
HasMetadata answer = patchService.compareAndPatchEntity(namespace, entity, old);
log.info("Updated Custom Resource Definition result: " + getName(answer));
} catch (Exception e) {
onApplyError("Failed to update Custom Resource Definition from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a Custom Resource Definition from " + sourceName + " name " + getName(entity));
} else {
doCreateCustomResourceDefinition(entity, sourceName);
}
}
}
private void doCreateCustomResourceDefinition(CustomResourceDefinition entity, String sourceName) {
log.info("Creating a Custom Resource Definition from " + sourceName + " name " + getName(entity));
try {
Object answer = kubernetesClient.customResourceDefinitions().create(entity);
log.info("Created Custom Resource Definition result: " + ((CustomResourceDefinition) answer).getMetadata().getName());
} catch (Exception e) {
onApplyError("Failed to create Custom Resource Definition from " + sourceName + ". " + e + ". " + entity, e);
}
}
public void applyCustomResource(File customResourceFile, String namespace, CustomResourceDefinitionContext context) throws Exception {
Map<String, Object> cr = KubernetesClientUtil.doReadCustomResourceFile(customResourceFile);
Map<String, Object> objectMeta = (Map<String, Object>)cr.get("metadata");
String name = objectMeta.get("name").toString();
if (objectMeta.get("namespace") != null) {
namespace = objectMeta.get("namespace").toString();
}
if (isRecreateMode()) {
KubernetesClientUtil.doDeleteCustomResource(kubernetesClient, context, namespace, name);
KubernetesClientUtil.doCreateCustomResource(kubernetesClient, context, namespace, customResourceFile);
log.info("Created Custom Resource: " + name);
} else {
cr = KubernetesClientUtil.doGetCustomResource(kubernetesClient, context, namespace, name);
if (cr == null) {
KubernetesClientUtil.doCreateCustomResource(kubernetesClient, context, namespace, customResourceFile);
log.info("Created Custom Resource: " + name);
} else {
Map<String, Object> newCustomResource = KubernetesClientUtil.doLoadCustomResource(kubernetesClient, context, customResourceFile);
if (UserConfigurationCompare.configEqual(newCustomResource, cr)) {
log.info("Custom resource " + name + " not changes so not doing anything");
} else {
/*
* This is in order to resolve https://github.com/fabric8io/kubernetes-client/issues/1724
* You need to add metadata.resourceVersion in object in order to edit.
*/
Map<String, Object> metadata = (Map<String, Object>)newCustomResource.get("metadata");
if (metadata != null) {
metadata.put("resourceVersion", ((Map<String, Object>) cr.get("metadata")).get("resourceVersion"));
newCustomResource.put("metadata", metadata);
}
KubernetesClientUtil.doEditCustomResource(kubernetesClient, context, namespace, name, newCustomResource);
log.info("Updated Custom Resource: " + name);
}
}
}
}
public void deleteCustomResource(File customResourceFile, String namespace, CustomResourceDefinitionContext crdContext) throws Exception {
Map<String, Object> customResource = KubernetesClientUtil.doReadCustomResourceFile(customResourceFile);
Map<String, Object> objectMeta = (Map<String, Object>)customResource.get("metadata");
String name = objectMeta.get("name").toString();
log.info("Deleting Custom Resource " + name);
KubernetesClientUtil.doDeleteCustomResource(kubernetesClient, crdContext, namespace, name);
}
protected boolean isBound(PersistentVolumeClaim claim) {
return claim != null &&
claim.getStatus() != null &&
"Bound".equals(claim.getStatus().getPhase());
}
protected void doCreatePersistentVolumeClaim(PersistentVolumeClaim entity, String namespace, String sourceName) {
log.info("Creating a PersistentVolumeClaim from " + sourceName + " namespace " + namespace + " name " + getName(entity));
try {
Object answer;
if (StringUtils.isNotBlank(namespace)) {
answer = kubernetesClient.persistentVolumeClaims().inNamespace(namespace).create(entity);
} else {
answer = kubernetesClient.persistentVolumeClaims().inNamespace(getNamespace(entity)).create(entity);
}
logGeneratedEntity("Created PersistentVolumeClaim: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to create PersistentVolumeClaim from " + sourceName + ". " + e + ". " + entity, e);
}
}
public void applySecret(Secret secret, String sourceName) throws Exception {
String namespace = getNamespace(secret);
String id = getName(secret);
Objects.requireNonNull(id, "No name for " + secret + " " + sourceName);
if (isServicesOnlyMode()) {
log.debug("Only processing Services right now so ignoring Secrets: " + id);
return;
}
Secret old = kubernetesClient.secrets().inNamespace(namespace).withName(id).get();
// check if the secret already exists or not
if (isRunning(old)) {
// if the secret already exists and is the same, then do nothing
if (UserConfigurationCompare.configEqual(secret, old)) {
log.info("Secret has not changed so not doing anything");
return;
} else {
if (isRecreateMode()) {
kubernetesClient.secrets().inNamespace(namespace).withName(id).delete();
doCreateSecret(secret, namespace, sourceName);
} else {
log.info("Updating a Secret from " + sourceName);
try {
Object answer = patchService.compareAndPatchEntity(namespace, secret, old);
logGeneratedEntity("Updated Secret:", namespace, secret, answer);
} catch (Exception e) {
onApplyError("Failed to update secret from " + sourceName + ". " + e + ". " + secret, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a Secret from " + sourceName + " namespace " + namespace + " name " + getName(secret));
} else {
doCreateSecret(secret, namespace, sourceName);
}
}
}
protected void doCreateSecret(Secret secret, String namespace, String sourceName) {
log.info("Creating a Secret from " + sourceName + " namespace " + namespace + " name " + getName(secret));
try {
Object answer;
if (StringUtils.isNotBlank(namespace)) {
answer = kubernetesClient.secrets().inNamespace(namespace).create(secret);
} else {
answer = kubernetesClient.secrets().inNamespace(getNamespace(secret)).create(secret);
}
logGeneratedEntity("Created Secret: ", namespace, secret, answer);
} catch (Exception e) {
onApplyError("Failed to create Secret from " + sourceName + ". " + e + ". " + secret, e);
}
}
protected void logGeneratedEntity(String message, String namespace, HasMetadata entity, Object result) {
if (logJsonDir != null) {
File namespaceDir = new File(logJsonDir, namespace);
namespaceDir.mkdirs();
String kind = getKind(entity);
String name = getName(entity);
if (StringUtils.isNotBlank(kind)) {
name = kind.toLowerCase() + "-" + name;
}
if (StringUtils.isBlank(name)) {
log.warn("No name for the entity " + entity);
} else {
String fileName = name + ".json";
File file = new File(namespaceDir, fileName);
if (file.exists()) {
int idx = 1;
while (true) {
fileName = name + "-" + idx++ + ".json";
file = new File(namespaceDir, fileName);
if (!file.exists()) {
break;
}
}
}
String text;
if (result instanceof String) {
text = result.toString();
} else {
try {
text = ResourceUtil.toJson(result);
} catch (JsonProcessingException e) {
log.warn("Cannot convert " + result + " to JSON: " + e, e);
if (result != null) {
text = result.toString();
} else {
text = "null";
}
}
}
try {
FileUtils.writeStringToFile(file, text, Charset.defaultCharset());
Object fileLocation = file;
if (basedir != null) {
String path = FileUtil.getRelativePath(basedir, file).getPath();
if (path != null) {
fileLocation = FileUtil.stripPrefix(path, "/");
}
}
log.info(message + fileLocation);
} catch (IOException e) {
log.warn("Failed to write to file " + file + ". " + e, e);
}
return;
}
}
log.info(message + result);
}
public Object processTemplate(Template entity, String sourceName) {
try {
return OpenshiftHelper.processTemplatesLocally(entity, false);
} catch (IOException e) {
onApplyError("Failed to process template " + sourceName + ". " + e + ". " + entity, e);
return null;
}
}
public void applyRoute(Route entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (StringUtils.isBlank(namespace)) {
namespace = getNamespace(entity);
}
Route route = openShiftClient.routes().inNamespace(namespace).withName(id).get();
if (route == null) {
try {
log.info("Creating Route " + namespace + ":" + id + " " +
(entity.getSpec() != null ?
"host: " + entity.getSpec().getHost() :
"No Spec !"));
openShiftClient.routes().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create Route from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
}
public void applyBuildConfig(BuildConfig entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (StringUtils.isBlank(namespace)) {
namespace = getNamespace(entity);
}
applyNamespace(namespace);
BuildConfig old = openShiftClient.buildConfigs().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
log.info("BuildConfig has not changed so not doing anything");
} else {
if (isRecreateMode()) {
log.info("Deleting BuildConfig: " + id);
openShiftClient.buildConfigs().inNamespace(namespace).withName(id).delete();
doCreateBuildConfig(entity, namespace, sourceName);
} else {
log.info("Updating BuildConfig from " + sourceName);
try {
String resourceVersion = KubernetesHelper.getResourceVersion(old);
ObjectMeta metadata = getOrCreateMetadata(entity);
metadata.setNamespace(namespace);
metadata.setResourceVersion(resourceVersion);
Object answer = patchService.compareAndPatchEntity(namespace, entity, old);
logGeneratedEntity("Updated BuildConfig: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to update BuildConfig from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating BuildConfig from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateBuildConfig(entity, namespace, sourceName);
}
}
}
}
public void doCreateBuildConfig(BuildConfig entity, String namespace , String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
try {
openShiftClient.buildConfigs().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create BuildConfig from " + sourceName + ". " + e, e);
}
}
}
public void applyRoleBinding(RoleBinding entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
String id = getName(entity);
Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
String namespace = KubernetesHelper.getNamespace(entity);
if (StringUtils.isBlank(namespace)) {
namespace = getNamespace(entity);
}
applyNamespace(namespace);
RoleBinding old = openShiftClient.rbac().roleBindings().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(entity, old)) {
log.info("RoleBinding has not changed so not doing anything");
} else {
if (isRecreateMode()) {
log.info("Deleting RoleBinding: " + id);
openShiftClient.roleBindings().inNamespace(namespace).withName(id).delete();
doCreateRoleBinding(entity, namespace, sourceName);
} else {
log.info("Updating RoleBinding from " + sourceName);
try {
String resourceVersion = KubernetesHelper.getResourceVersion(old);
ObjectMeta metadata = getOrCreateMetadata(entity);
metadata.setNamespace(namespace);
metadata.setResourceVersion(resourceVersion);
Object answer = openShiftClient.rbac().roleBindings().inNamespace(namespace).withName(id).replace(entity);
logGeneratedEntity("Updated RoleBinding: ", namespace, entity, answer);
} catch (Exception e) {
onApplyError("Failed to update RoleBinding from " + sourceName + ". " + e + ". " + entity, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating RoleBinding from " + sourceName + " namespace " + namespace + " name " + getName(entity));
} else {
doCreateRoleBinding(entity, namespace, sourceName);
}
}
}
}
public void doCreateRoleBinding(RoleBinding entity, String namespace , String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
try {
openShiftClient.rbac().roleBindings().inNamespace(namespace).create(entity);
} catch (Exception e) {
onApplyError("Failed to create RoleBinding from " + sourceName + ". " + e, e);
}
}
}
public void applyImageStream(ImageStream entity, String sourceName) {
OpenShiftClient openShiftClient = getOpenShiftClient();
if (openShiftClient != null) {
String kind = getKind(entity);
String name = getName(entity);
String namespace = getNamespace(entity);
try {
Resource<ImageStream, DoneableImageStream> resource = openShiftClient.imageStreams().inNamespace(namespace).withName(name);
ImageStream old = resource.get();
if (old == null) {
log.info("Creating " + kind + " " + name + " from " + sourceName);
resource.create(entity);
} else {
log.info("Updating " + kind + " " + name + " from " + sourceName);
copyAllImageStreamTags(entity, old);
entity = patchService.compareAndPatchEntity(namespace, entity, old);
openShiftClient.resource(entity).inNamespace(namespace).createOrReplace();
}
} catch (Exception e) {
onApplyError("Failed to create " + kind + " from " + sourceName + ". " + e, e);
}
}
}
protected void copyAllImageStreamTags(ImageStream from, ImageStream to) {
ImageStreamSpec toSpec = to.getSpec();
if (toSpec == null) {
toSpec = new ImageStreamSpec();
to.setSpec(toSpec);
}
List<TagReference> toTags = toSpec.getTags();
if (toTags == null) {
toTags = new ArrayList<>();
toSpec.setTags(toTags);
}
ImageStreamSpec fromSpec = from.getSpec();
if (fromSpec != null) {
List<TagReference> fromTags = fromSpec.getTags();
if (fromTags != null) {
// lets remove all the tags with these names first
for (TagReference tag : fromTags) {
removeTagByName(toTags, tag.getName());
}
// now lets add them all in case 2 tags have the same name
for (TagReference tag : fromTags) {
toTags.add(tag);
}
}
}
}
/**
* Removes all the tags with the given name
* @return the number of tags removed
*/
private int removeTagByName(List<TagReference> tags, String tagName) {
List<TagReference> removeTags = new ArrayList<>();
for (TagReference tag : tags) {
if (Objects.equals(tagName, tag.getName())) {
removeTags.add(tag);
}
}
tags.removeAll(removeTags);
return removeTags.size();
}
public void applyList(KubernetesList list, String sourceName) throws Exception {
List<HasMetadata> entities = list.getItems();
if (entities != null) {
for (Object entity : entities) {
applyEntity(entity, sourceName);
}
}
}
public void applyService(Service service, String sourceName) throws Exception {
String namespace = getNamespace(service);
String id = getName(service);
Objects.requireNonNull(id, "No name for " + service + " " + sourceName);
if (isIgnoreServiceMode()) {
log.debug("Ignoring Service: " + namespace + ":" + id);
return;
}
Service old = kubernetesClient.services().inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(service, old)) {
log.info("Service has not changed so not doing anything");
} else {
if (isRecreateMode()) {
log.info("Deleting Service: " + id);
kubernetesClient.services().inNamespace(namespace).withName(id).delete();
doCreateService(service, namespace, sourceName);
} else {
log.info("Updating a Service from " + sourceName);
try {
Object answer = patchService.compareAndPatchEntity(namespace, service, old);
logGeneratedEntity("Updated Service: ", namespace, service, answer);
} catch (Exception e) {
onApplyError("Failed to update Service from " + sourceName + ". " + e + ". " + service, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a Service from " + sourceName + " namespace " + namespace + " name " + getName(service));
} else {
doCreateService(service, namespace, sourceName);
}
}
}
public <T extends HasMetadata, L, D> void applyResource(T resource, String sourceName, MixedOperation<T, L, D, ? extends Resource<T, D>> resources) throws Exception {
String namespace = getNamespace(resource);
String id = getName(resource);
String kind = getKind(resource);
Objects.requireNonNull(id, "No name for " + resource + " " + sourceName);
if (isServicesOnlyMode()) {
log.debug("Ignoring " + kind + ": " + namespace + ":" + id);
return;
}
T old = resources.inNamespace(namespace).withName(id).get();
if (isRunning(old)) {
if (UserConfigurationCompare.configEqual(resource, old)) {
log.info(kind + " has not changed so not doing anything");
} else {
if (isRecreateMode()) {
log.info("Deleting " + kind + ": " + id);
resources.inNamespace(namespace).withName(id).delete();
doCreateResource(resource, namespace, sourceName, resources);
} else {
log.info("Updating " + kind + " from " + sourceName);
try {
Object answer = resources.inNamespace(namespace).withName(id).replace(resource);
logGeneratedEntity("Updated " + kind + ": ", namespace, resource, answer);
} catch (Exception e) {
onApplyError("Failed to update " + kind + " from " + sourceName + ". " + e + ". " + resource, e);
}
}
}
} else {
if (!isAllowCreate()) {
log.warn("Creation disabled so not creating a " + kind + " from " + sourceName + " namespace " + namespace + " name " + getName(resource));
} else {
doCreateResource(resource, namespace, sourceName, resources);
}
}
}
protected <T extends HasMetadata,L,D> void doCreateResource(T resource, String namespace , String sourceName, MixedOperation<T, L, D, ? extends Resource<T, D>> resources) throws Exception {
String kind = getKind(resource);
log.info("Creating a " + kind + " from " + sourceName + " namespace " + namespace + " name " + getName(resource));
try {
Object answer;
if (StringUtils.isNotBlank(namespace)) {
answer = resources.inNamespace(namespace).create(resource);
} else {
answer = resources.inNamespace(this.namespace).create(resource);
}
logGeneratedEntity("Created " + kind + ": ", namespace, resource, answer);
} catch (Exception e) {
onApplyError("Failed to create " + kind + " from " + sourceName + ". " + e + ". " + resource, e);
}
}
protected void doCreateService(Service service, String namespace, String sourceName) {
log.info("Creating a Service from " + sourceName + " namespace " + namespace + " name " + getName(service));
try {
Object answer;
if (StringUtils.isNotBlank(namespace)) {
answer = kubernetesClient.services().inNamespace(namespace).create(service);
} else {
answer = kubernetesClient.services().inNamespace(this.namespace).create(service);
}
logGeneratedEntity("Created Service: ", namespace, service, answer);
} catch (Exception e) {
onApplyError("Failed to create Service from " + sourceName + ". " + e + ". " + service, e);
}
}
public boolean checkNamespace(String namespaceName) {
if (StringUtils.isBlank(namespaceName)) {
return false;
}
OpenShiftClient openshiftClient = getOpenShiftClient();
if (openshiftClient != null) {
// It is preferable to iterate on the list of projects as regular user with the 'basic-role' bound
// are not granted permission get operation on non-existing project resource that returns 403
// instead of 404. Only more privileged roles like 'view' or 'cluster-reader' are granted this permission.
List<Project> projects = openshiftClient.projects().list().getItems();
for (Project project : projects) {
if (namespaceName.equals(project.getMetadata().getName())) {
return true;
}
}
return false;
}