/
ResourceUtils.java
1284 lines (1178 loc) · 40.2 KB
/
ResourceUtils.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 (c) 2015-2018 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.openshift.internal.core.util;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jgit.transport.URIish;
import org.eclipse.osgi.util.NLS;
import org.jboss.dmr.ModelNode;
import org.jboss.tools.foundation.core.plugin.log.StatusFactory;
import org.jboss.tools.openshift.core.OpenShiftAPIAnnotations;
import org.jboss.tools.openshift.core.OpenShiftResourceSelectors;
import org.jboss.tools.openshift.core.connection.Connection;
import org.jboss.tools.openshift.egit.core.EGitUtils;
import org.jboss.tools.openshift.internal.common.core.util.KeyValueFilterFactory;
import org.jboss.tools.openshift.internal.common.core.util.KeyValueFilterFactory.KeyValueFilter;
import org.jboss.tools.openshift.internal.core.OpenShiftCoreActivator;
import com.openshift.restclient.IClient;
import com.openshift.restclient.ResourceKind;
import com.openshift.restclient.capability.CapabilityVisitor;
import com.openshift.restclient.capability.resources.IClientCapability;
import com.openshift.restclient.capability.resources.ITags;
import com.openshift.restclient.images.DockerImageURI;
import com.openshift.restclient.model.IBuild;
import com.openshift.restclient.model.IBuildConfig;
import com.openshift.restclient.model.IDeploymentConfig;
import com.openshift.restclient.model.IObjectReference;
import com.openshift.restclient.model.IPod;
import com.openshift.restclient.model.IProject;
import com.openshift.restclient.model.IReplicationController;
import com.openshift.restclient.model.IResource;
import com.openshift.restclient.model.IService;
import com.openshift.restclient.model.IStatus;
import com.openshift.restclient.model.deploy.DeploymentTriggerType;
import com.openshift.restclient.model.deploy.IDeploymentImageChangeTrigger;
import com.openshift.restclient.model.deploy.IDeploymentTrigger;
import com.openshift.restclient.model.image.IImageStreamImport;
import com.openshift.restclient.model.route.IRoute;
public class ResourceUtils {
public static final String DOCKER_IMAGE_KIND = "DockerImage";
public static final String IMAGE_STREAM_IMAGE_KIND = "ImageStreamImage";
public static final String DEPLOYMENT_CONFIG = "deploymentconfig";
private static final String POD_STATUS_RUNNING = "Running";
private ResourceUtils() {
}
public static IClient getClient(IResource resource) {
return resource.accept(new CapabilityVisitor<IClientCapability, IClient>() {
@Override
public IClient visit(IClientCapability cap) {
return cap.getClient();
}
}, null);
}
public static IClient checkedGetClient(IResource resource) throws CoreException {
IClient client = getClient(resource);
if (client == null) {
throw new CoreException(StatusFactory.errorStatus(OpenShiftCoreActivator.PLUGIN_ID,
NLS.bind("Could not get client for resource {0}", resource.getName())));
}
return client;
}
/**
* Returns {@code true} if the given route points to the given service and the
* given service is the service that the given route points to.
*
* @param route
* @param service
* @return
*
* @see IRoute#getServiceName()
* @see IService#getName()
*/
public static boolean areRelated(IRoute route, IService service) {
if (service != null && !StringUtils.isEmpty(service.getName()) && route != null) {
return service.getName().equals(route.getServiceName());
}
return false;
}
/**
* Returns {@code true} if the given build config matches the name of the given
* service.
*
* @param config
* @param service
* @return
*/
public static boolean areRelated(final IBuildConfig config, final IService service) {
if (service != null && !StringUtils.isEmpty(service.getName()) && config != null) {
return service.getName().equals(config.getName());
}
return false;
}
public static boolean areRelated(IDeploymentConfig dc, IService s) {
return containsAll(s.getSelector(), dc.getReplicaSelector());
}
public static boolean areRelated(IReplicationController rc, IService s) {
return containsAll(s.getSelector(), rc.getReplicaSelector());
}
public static boolean areRelated(IReplicationController rc, IDeploymentConfig dc) {
if (dc == null || rc == null) {
return false;
}
return StringUtils.equals(dc.getName(), getDeploymentConfigNameFor(rc));
}
public static boolean hasRelatedPods(IPod pod, List<IResource> resources) {
return resources.stream().anyMatch(r -> ResourceKind.REPLICATION_CONTROLLER.equals(r.getKind())
&& areRelated(pod, (IReplicationController) r));
}
public static boolean hasRelatedDc(IReplicationController rc, List<IResource> resources) {
return resources.stream().anyMatch(
r -> ResourceKind.DEPLOYMENT_CONFIG.equals(r.getKind()) && areRelated(rc, (IDeploymentConfig) r));
}
public static boolean areRelated(IPod pod, IService s) {
return containsAll(s.getSelector(), pod.getLabels());
}
public static boolean areRelated(IPod pod, IReplicationController rc) {
return containsAll(rc.getReplicaSelector(), pod.getLabels());
}
/**
* Returns the resource labels, that match the given filter. A {@code null}
* filter matches any label. A {@code null} filter returns an empty map if the
* given resource has no labels.
*
* @param filter
* @param resource
* @return the labels that match the given filter
*
* @see KeyValueFilterFactory
* @see KeyValueFilterFactory.KeyValueFilter
* @see IResource#getLabels()
*/
public static Map<String, String> getMatchingLabels(KeyValueFilter filter, IResource resource) {
Map<String, String> labels = resource.getLabels();
return labels.entrySet().stream().filter(entry -> {
if (filter == null) {
return true;
}
return filter.matchesKey(entry.getKey()) && filter.matchesValue(entry.getValue());
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
/**
* Returns {@code true} any label of the given resource is matching the given
* filter. A {@code null} filter matches any label and also matches a resource
* that has no labels at all.
*
* @param filter
* @param resource
* @return true if the given filter is matching any label in the given resource.
*
* @see KeyValueFilterFactory
* @see KeyValueFilterFactory.KeyValueFilter
* @see IResource#getLabels()
*/
public static boolean hasMatchingLabels(KeyValueFilter filter, IResource resource) {
if (filter == null || filter.isEmpty()) {
return true;
}
return !getMatchingLabels(filter, resource).isEmpty();
}
/**
* Returns <code>true</code> if the given resource contains the given text in
* name or tags.
*
* @param filterText
* @param resource
* @return
*/
public static boolean isMatchingNameOrTag(final String filterText, IResource resource) {
if (resource == null || StringUtils.isBlank(filterText)) {
return true;
}
return resource.accept(new CapabilityVisitor<ITags, Boolean>() {
@Override
public Boolean visit(ITags capability) {
return isMatchingNameOrTag(filterText, resource.getName(), capability.getTags());
}
}, Boolean.FALSE);
}
public static boolean isMatchingNameOrTag(final String filterText, String name, Collection<String> tags) {
if (StringUtils.isBlank(filterText)) {
return true;
}
final Set<String> items = new HashSet<>(
Arrays.asList(filterText.replaceAll(",", " ").toLowerCase().split(" ")));
if (containsAll(name, items)) {
return true;
}
for (String item : items) {
if (!inCollection(item, tags)) {
return false;
}
}
return true;
}
private static boolean containsAll(String text, final Collection<String> items) {
final String lowerCase = text.toLowerCase();
return items.stream().allMatch(lowerCase::contains);
}
private static boolean inCollection(String item, final Collection<String> texts) {
final String lowerCaseItem = item.toLowerCase();
return texts.stream().anyMatch(text -> text.toLowerCase().contains(lowerCaseItem));
}
/**
* Determine if the source map overlaps the target map (i.e. Matching a service
* to a pod). There is match if the target includes all the the keys from the
* source and those keys have matching values
*
* @param source
* @param target
* @return true if there is overlap; false; otherwise
*/
public static boolean containsAll(Map<String, String> source, Map<String, String> target) {
if (source == null || target == null) {
return false;
}
if (!target.keySet().isEmpty() && source.keySet().isEmpty()) {
return false;
}
if (!target.keySet().containsAll(source.keySet())) {
return false;
}
for (Entry<String, String> entry : source.entrySet()) {
if (!Objects.deepEquals(target.get(entry.getKey()), entry.getValue())) {
return false;
}
}
return true;
}
public static Collection<IService> getServicesFor(IResource resource, Collection<IService> services) {
if (resource instanceof IService) {
return Collections.singleton((IService) resource);
} else if (resource instanceof IReplicationController) {
return getServicesFor((IReplicationController) resource, services);
} else if (resource instanceof IPod) {
return getServicesFor((IPod) resource, services);
} else {
return Collections.emptyList();
}
}
/**
* Find the collection of services whos selectors match the given pod
*
* @param pod
* @param services
* @return
*/
public static Collection<IService> getServicesFor(IPod pod, Collection<IService> services) {
return services.stream().filter(s -> containsAll(s.getSelector(), pod.getLabels())).collect(Collectors.toSet());
}
public static Collection<IService> getServicesFor(IReplicationController rc, Collection<IService> services) {
return services.stream().filter(service -> areRelated(rc, service)).collect(Collectors.toSet());
}
/**
* Find the collection of pods that match the selector of the given service
*
* @param service
* @param pods
* @return
*/
public static List<IPod> getPodsFor(IService service, List<IPod> pods) {
final Map<String, String> serviceSelector = service.getSelector();
return getPodsForSelector(serviceSelector, pods);
}
/**
* Find the collection of pods that match the deployment name annotation
*
* @param replicationController
* the replication controller to match
* @param pods
* the list of pods to search for
* @return the matched pods
*/
public static List<IPod> getPodsFor(IDeploymentConfig deploymentConfig, List<IPod> pods) {
return pods.stream().filter(pod -> {
String configName = pod.getAnnotation(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME);
return deploymentConfig.getName().equals(configName);
}).collect(Collectors.toList());
}
/**
* Find the collection of pods that match the selector of the given resource
*
* @param resource
* the OpenShift resource to start from
* @param pods
* the list of pods to search
* @return the list of linked pods
*/
public static List<IPod> getPodsFor(IResource resource, List<IPod> pods) {
if (resource instanceof IService) {
return getPodsFor((IService) resource, pods);
} else if (resource instanceof IDeploymentConfig) {
return getPodsFor((IDeploymentConfig) resource, pods);
} else if (resource instanceof IReplicationController) {
return getPodsFor((IReplicationController) resource, pods);
} else {
return Collections.emptyList();
}
}
/**
* Return the deployment config associated with this pod. Uses annotations to do
* the matching.
*
* @param pod
* the pod to look for
* @return the deployment config
*/
public static Optional<IDeploymentConfig> getDeploymentConfig(IPod pod,
Collection<IDeploymentConfig> deploymentConfigs) {
return deploymentConfigs.stream()
.filter(dc -> dc.getName().equals(pod.getAnnotation(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME)))
.findFirst();
}
/**
* Return the deployment config or replication controller associated with this
* pod. Uses annotations to do the matching.
*
* @param pod
* the pod to look for
* @return the deployment config or replication controller
*/
public static IReplicationController getDeploymentConfigOrReplicationControllerFor(IPod pod) {
Optional<? extends IResource> rcOrDc = getDeploymentConfig(pod,
pod.getProject().getResources(ResourceKind.DEPLOYMENT_CONFIG));
if (!rcOrDc.isPresent()) {
rcOrDc = Optional.ofNullable(getReplicationControllerFor(pod,
pod.getProject().getResources(ResourceKind.REPLICATION_CONTROLLER)));
}
return (IReplicationController) rcOrDc.orElse(null);
}
/**
* Find the collection of pods that match the given selector
*
* @param selector
* @param pods
* @return
*/
private static List<IPod> getPodsForSelector(Map<String, String> serviceSelector, Collection<IPod> pods) {
return pods.stream().filter(p -> containsAll(serviceSelector, p.getLabels())).distinct()
.collect(Collectors.toList());
}
/**
* Returns {@code true} if the given pod is a pod running builds. This is the
* case if the pod is annotated with the build name. Returns {@code false} if
* the given pod is a pod running an application or is null.
*
* @param pod
* the pod that shall be checked whether it's a build pod
* @return true if pod is annotated with the build name; false otherwise;
*
* @see IPod
* @see OpenShiftAPIAnnotations#BUILD_NAME
*/
public static boolean isBuildPod(IPod pod) {
if (pod == null) {
return false;
}
return pod.isAnnotatedWith(OpenShiftAPIAnnotations.BUILD_NAME);
}
public static Collection<IPod> getBuildPods(Collection<IPod> allPods) {
return allPods.stream().filter(ResourceUtils::isBuildPod).collect(Collectors.toList());
}
/**
* Returns {@code true} if the given pod is a pod running deployments. This is
* the case if the pod has a label which tells it to be a deployer for some pod.
* Returns {@code false} otherwise.
*
* @param pod
* the pod that shall be checked whether it's a deployer pod
* @return true if pod is annotated with the build name; false otherwise;
*
* @see IPod
* @see OpenShiftAPIAnnotations#DEPLOYER_POD_FOR
*/
public static boolean isDeployerPod(IPod pod) {
if (pod == null) {
return false;
}
return pod.getLabels().containsKey(OpenShiftAPIAnnotations.DEPLOYER_POD_FOR);
}
/**
* Returns {@code true} if the given pod is a pod running applications. This is
* the case if the pod is neither a build nor deployer pod. Returns
* {@code false} otherwise. example:
*
* <pre>
* "labels": {
* "openshift.io/deployer-pod-for.name": "nodejs-5"
* },
* </pre>
*
* @param pod
* the pod that shall be checked whether it's a runtime/application
* pod
* @return true if pod is annotated with the build name; false otherwise;
*
* @see IPod
* @see OpenShiftAPIAnnotations#DEPLOYER_POD_FOR
*/
public static boolean isRuntimePod(IPod pod) {
if (pod == null) {
return false;
}
return !isBuildPod(pod) && !isDeployerPod(pod);
}
public static Collection<IPod> getRuntimePods(Collection<IPod> allPods) {
return allPods.stream().filter(ResourceUtils::isRuntimePod).collect(Collectors.toList());
}
/**
* Returns {@code true} if the given pod is running. Returns
* {@code false} otherwise.
*
* @param pod
* @return true if the given pod is running.
*/
public static boolean isRunning(IPod pod) {
return pod != null
&& POD_STATUS_RUNNING.equals(pod.getStatus());
}
/**
* Returns {@code true} if the given pod fullfills the following criteria:
* <ul>
* <li>is a runtime pod (not a deployer pod)</li>
* <li>is running</li>
* <li>is ready</li>
* <li>is created via the given dc</li>
* </ul>
*
* @param pod the pod to be checked
* @param dc the deployment config that the given pod originates from
* @return true if the given pod is a runtime pod, that's running, is ready and
* originates from the given dc
*/
public static boolean isNewRuntimePodFor(IPod pod, IDeploymentConfig dc) {
return pod != null
&& isRuntimePod(pod)
&& isRunning(pod)
&& pod.isReady()
&& areRelated(pod, dc);
}
/**
* The image reference for an image change trigger used to correlate a
* deploymentconfig to a buildconfig
*
* @param trigger
* @return
*/
public static String imageRef(IDeploymentImageChangeTrigger trigger) {
String ref = "";
if (trigger != null) {
switch (trigger.getKind()) {
case ResourceKind.IMAGE_STREAM_TAG:
case IMAGE_STREAM_IMAGE_KIND:
case DOCKER_IMAGE_KIND:
ref = trigger.getFrom().getNameAndTag();
break;
default:
}
}
return ref;
}
/**
* Returns all the images for the given build configs.
*
* @param buildConfigs
* the build configs to extract the image refs from
* @return all the image references within the given build configs
*
* @see #imageRef(IBuildConfig)
*/
public static List<String> getImageRefs(List<IBuildConfig> buildConfigs) {
if (buildConfigs == null) {
return null;
}
return buildConfigs.stream().map(ResourceUtils::imageRef).collect(Collectors.toList());
}
/**
* The image reference for an image change trigger used to correlate a
* buildconfig to a deploymentconfig
*
* @param trigger
* @return
*/
public static String imageRef(IBuildConfig config) {
if (config != null) {
IObjectReference outputRef = config.getBuildOutputReference();
if (outputRef != null) {
String kind = outputRef.getKind();
if (ResourceKind.IMAGE_STREAM_TAG.equals(kind) || IMAGE_STREAM_IMAGE_KIND.equals(kind)) {
return outputRef.getName();
}
}
}
return "";
}
/**
* Returns the image referenced by a given build. Returns empty string if none
* is found.
*
* @param build
* @return the image referenced
*/
public static String imageRef(IBuild build) {
String ref = "";
if (build != null) {
switch (build.getOutputKind()) {
case ResourceKind.IMAGE_STREAM_TAG:
case IMAGE_STREAM_IMAGE_KIND:
case DOCKER_IMAGE_KIND:
ref = build.getOutputTo().getNameAndTag();
break;
default:
}
}
return ref;
}
/**
* Returns the image stream tag among the given ones that matches the given
* docker image digest. The image stream tag property in "image.metadata.name"
* is being matched against the given digest.
*
* @param digest
* the digest that the image stream tag shall match in the property
* "image.metadata.name"
* @param imageStreamTags
* the image stream tags to inspect
* @return
*/
public static IResource getImageStreamTagForDigest(String digest, Collection<? extends IResource> imageStreamTags) {
return imageStreamTags.stream()
.filter(istag -> {
String imageName = ModelNode.fromJSONString(
istag.toJson()).get("image").get("metadata").get("name")
.asString();
return digest.equals(imageName);
})
.findFirst()
.orElse(null);
}
/**
* Returns the {@link DockerImageURI} for a given IDeploymentConfig.
* Alternatively tries to get it from IDeploymentImageChangeTrigger or then
* container images.
*
* @param dc
* @return
*/
public static DockerImageURI getDockerImageUri(IDeploymentConfig dc) {
DockerImageURI image = getImageChangeTriggerImage(dc);
if (image != null) {
return image;
} else {
return getContainerImage(dc);
}
}
private static DockerImageURI getImageChangeTriggerImage(IDeploymentConfig dc) {
IDeploymentImageChangeTrigger trigger = getImageChangeTrigger(dc.getTriggers());
if (trigger == null) {
return null;
}
return trigger.getFrom();
}
private static IDeploymentImageChangeTrigger getImageChangeTrigger(Collection<IDeploymentTrigger> triggers) {
return triggers.stream()
.filter(trigger -> DeploymentTriggerType.IMAGE_CHANGE.equals(trigger.getType()))
.findAny()
.map(trigger -> (IDeploymentImageChangeTrigger) trigger)
.orElse(null);
}
private static DockerImageURI getContainerImage(IDeploymentConfig dc) {
Collection<String> images = dc.getImages();
if (images.isEmpty()) {
return null;
}
// TODO: handle if there are 2+ images
return new DockerImageURI(images.iterator().next());
}
/**
* Find the collection of pods for the given replication controller
*
* @param replicationController
* the replication controller to search pods for
* @param pods
* the list of pods to search
* @return the list of matched pods
*/
public static List<IPod> getPodsFor(IReplicationController replicationController, List<IPod> allPods) {
Map<String, String> selector = replicationController.getReplicaSelector();
return getPodsForSelector(selector, allPods);
}
/**
* Returns the first route that's found and matches the given service.
*
* @param service
* @param routes
* @return
*/
public static IRoute getRouteFor(final IService service, Collection<IRoute> routes) {
List<IRoute> matchingRoutes = getRoutesFor(service, routes);
if (matchingRoutes.isEmpty()) {
return null;
} else {
return matchingRoutes.get(0);
}
}
/**
*
* Returns the routes from the given routes that match the given service.
*
* @param service
* @param routes
* @return
*/
public static List<IRoute> getRoutesFor(final IService service, Collection<IRoute> routes) {
if (routes == null || routes.isEmpty()) {
return Collections.emptyList();
}
return routes.stream().filter(r -> areRelated(r, service)).collect(Collectors.toList());
}
/**
* Returns build configs of the given list of build configs that match the given
* service.
*
* @param service
* @param buildConfigs
* @return
*
* @see #areRelated(IBuildConfig, IService)
* @see IBuildConfig
* @see IService
*/
public static List<IBuildConfig> getBuildConfigsFor(IService service, List<IBuildConfig> buildConfigs) {
if (buildConfigs == null || buildConfigs.isEmpty()) {
return Collections.emptyList();
}
return buildConfigs.stream().filter(bc -> areRelated(bc, service)).collect(Collectors.toList());
}
/**
* Returns the 1st replication controllers that's found matching the given
* service. The lookup is done by matching the label in the service and
* replication controller pod template. No existing pods are required.
*
* @param service
* @param allReplicationControllers
* @return
*/
public static IReplicationController getReplicationControllerFor(IService service,
List<IReplicationController> allReplicationControllers) {
if (allReplicationControllers == null || allReplicationControllers.isEmpty() || service == null) {
return null;
}
List<IReplicationController> rcs = allReplicationControllers.stream()
.filter(rc -> containsAll(service.getSelector(), rc.getTemplateLabels())).collect(Collectors.toList());
return getLatestDeploymentConfigVersion(rcs);
}
/**
* Returns the 1st replication controllers that's found matching the given
* service. The lookup is done by matching the label in the service and
* replication controller pod template. No existing pods are required.
*
* @param pod
* @param allReplicationControllers
* @return
*/
public static IReplicationController getReplicationControllerFor(IPod pod,
List<IReplicationController> allReplicationControllers) {
if (allReplicationControllers == null || allReplicationControllers.isEmpty() || pod == null) {
return null;
}
return allReplicationControllers.stream().filter(rc -> containsAll(rc.getReplicaSelector(), pod.getLabels()))
.findFirst().orElse(null);
}
public static IReplicationController getLatestDeploymentConfigVersion(List<IReplicationController> rcs) {
if (rcs == null || rcs.isEmpty()) {
return null;
}
return rcs.stream().max(new NumericResourceAttributeComparator<IReplicationController>() {
@Override
protected int getResourceAttribute(IReplicationController rc) {
return safeParseInt(rc.getAnnotation(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_LATEST_VERSION));
}
}).orElse(null);
}
/**
* Returns {@code true} if the given 1st resource has a lower resource version
* as the given 2nd resource. Failing to retrieve the resource version on any of
* the 2 resources also returns {@code true}.
*
* @param thisResource
* @param thatResource
* @return true if the 1st resource is older than the 2nd one
*
* @see
*/
public static boolean isOlder(IResource thisResource, IResource thatResource) {
try {
int thisVersion = Integer.parseInt(thisResource.getResourceVersion());
int thatVersion = Integer.parseInt(thatResource.getResourceVersion());
return thisVersion < thatVersion;
} catch (NumberFormatException e) {
return true;
}
}
/**
* Returns the latest version of the given collection of deployment configs.
*
* @param resources
* @return
*/
public static <R extends IResource> R getLatestResourceVersion(List<R> resources) {
if (resources == null || resources.isEmpty()) {
return null;
}
return resources.stream().max(new NumericResourceAttributeComparator<R>() {
@Override
protected int getResourceAttribute(R resource) {
return safeParseInt(resource.getResourceVersion());
}
}).orElse(null);
}
private abstract static class NumericResourceAttributeComparator<R> implements Comparator<R> {
@Override
public int compare(R r1, R r2) {
if (r1 == null) {
if (r2 == null) {
return 0;
} else {
return 1;
}
} else {
if (r2 == null) {
return -1;
} else {
int attr1 = getResourceAttribute(r1);
int attr2 = getResourceAttribute(r2);
if (attr1 < attr2) {
return -1;
} else if (attr1 == attr2) {
return 0;
} else {
return 1;
}
}
}
}
protected abstract int getResourceAttribute(R r);
protected int safeParseInt(String string) {
try {
return Integer.parseInt(string);
} catch (NumberFormatException e1) {
return -1;
}
}
}
/**
* Returns the first build config out of the given list of build configs that
* matches the given service.
*
* @param service
* the service that the build configs shall match
* @param buildConfigs
* the build configs that shall be introspected
* @return
*
* @see #getBuildConfigsFor(IService, List)
* @see #areRelated(IBuildConfig, IService)
* @see IBuildConfig
* @see IService
*/
public static IBuildConfig getBuildConfigFor(IService service, List<IBuildConfig> buildConfigs) {
List<IBuildConfig> matchinBuildConfigs = getBuildConfigsFor(service, buildConfigs);
if (matchinBuildConfigs.isEmpty()) {
return null;
} else {
return matchinBuildConfigs.get(0);
}
}
/**
* Returns the first build config out of the given list of build configs that
* matches the given deployment config.
*
* @param deploymentConfig
* the deployment config that the build configs shall match
* @param buildConfigs
* the build configs that shall be introspected
* @return
*
* @see #getBuildConfigsForService(IService, List)
* @see #areRelated(IBuildConfig, IService)
* @see IBuildConfig
* @see IDeploymentConfig
*/
private static IBuildConfig getBuildConfigFor(IDeploymentConfig deploymentConfig, List<IBuildConfig> buildConfigs) {
List<IBuildConfig> matchinBuildConfigs = getBuildConfigsFor(deploymentConfig, buildConfigs);
if (matchinBuildConfigs.isEmpty()) {
return null;
} else {
return matchinBuildConfigs.get(0);
}
}
/**
* Returns build configs of the given list of build configs that match the given
* deployment config.
*
* @param serv
* @param buildConfigs
* @return
*
* @see #areRelated(IBuildConfig, IService)
* @see IBuildConfig
* @see IService
*/
public static List<IBuildConfig> getBuildConfigsFor(IDeploymentConfig deploymentConfig,
List<IBuildConfig> buildConfigs) {
if (buildConfigs == null || buildConfigs.isEmpty()) {
return Collections.emptyList();
}
return buildConfigs.stream().filter(bc -> areRelated(bc, deploymentConfig)).collect(Collectors.toList());
}
/**
* Returns the first build config out of the given list of build configs that
* matches the given OpenShift resource (service, replication controller,...).
*
* @param resource
* the OpenShift resource that the build configs shall match
* @param buildConfigs
* the build configs that shall be introspected
* @return
*
* @see #getBuildConfigsForService(IService, List)
* @see IBuildConfig
*/
public static IBuildConfig getBuildConfigFor(IResource resource, List<IBuildConfig> buildConfigs) {
if (resource == null) {
return null;
}
if (ResourceKind.SERVICE.equals(resource.getKind())) {
return getBuildConfigFor((IService) resource, buildConfigs);
} else if (ResourceKind.DEPLOYMENT_CONFIG.equals(resource.getKind())) {
return getBuildConfigFor((IDeploymentConfig) resource, buildConfigs);
} else {
return null;
}
}
/**
* Returns {@code true} if the given build config matches the name of the given
* service.
*
* @param config
* @param deploymentConfig
* @return
*/
public static boolean areRelated(final IBuildConfig config, final IDeploymentConfig deploymentConfig) {
if (deploymentConfig != null && !StringUtils.isEmpty(deploymentConfig.getName()) && config != null) {
return deploymentConfig.getName().equals(config.getName());
}
return false;
}
/**
* Returns {@code true} if the given service and given deployment config are
* related given the existing pods.
*
* @param service
* the service to match
* @param dc
* the deployment config to match
* @return true if they are related
*/
public static boolean areRelated(final IService service, IDeploymentConfig dc, Collection<IPod> allPods) {
if (dc == null) {
return false;
}
String dcName = dc.getName();
return allPods.stream()
.filter(pod -> dcName.equals(pod.getAnnotation(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME)))
.filter(pod -> areRelated(pod, service)).count() > 0;
}
/**
* Returns git controlled workspace projects that match the uri of the given
* build config.
*
* @param buildConfig
* the build config whose source git shall be matched
* @param workspaceProjects
* all workspace projects that shall be inspected
* @return
*
* @see IBuildConfig#getSourceURI()
* @see org.eclipse.core.resources.IProject
* @see EGitUtils#isSharedWithGit(org.eclipse.core.resources.IProject)
*/
public static org.eclipse.core.resources.IProject getWorkspaceProjectFor(IBuildConfig buildConfig,
List<org.eclipse.core.resources.IProject> workspaceProjects) {
if (workspaceProjects == null || workspaceProjects.isEmpty()) {
return null;
}