io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable Java Examples

The following examples show how to use io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReplicaSetRollingUpdater.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
protected PodList listSelectedPods(ReplicaSet obj) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = pods().inNamespace(namespace);
  if (obj.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(obj.getSpec().getSelector().getMatchLabels());
  }
  if (obj.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : obj.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
        case "In":
          podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          podLister.withoutLabel(req.getKey());
          break;
        case "Exists":
          podLister.withLabel(req.getKey());
          break;
      }
    }
  }
  return podLister.list();
}
 
Example #2
Source File: StatefulSetRollingUpdater.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
protected PodList listSelectedPods(StatefulSet obj) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = pods().inNamespace(namespace);
  if (obj.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(obj.getSpec().getSelector().getMatchLabels());
  }
  if (obj.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : obj.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
        case "In":
          podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          podLister.withoutLabel(req.getKey());
          break;
        case "Exists":
          podLister.withLabel(req.getKey());
          break;
      }
    }
  }
  return podLister.list();
}
 
Example #3
Source File: DeploymentRollingUpdater.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
protected PodList listSelectedPods(Deployment obj) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = pods().inNamespace(namespace);
  if (obj.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(obj.getSpec().getSelector().getMatchLabels());
  }
  if (obj.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : obj.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
        case "In":
          podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          podLister.withoutLabel(req.getKey());
          break;
        case "Exists":
          podLister.withLabel(req.getKey());
          break;
      }
    }
  }
  return podLister.list();
}
 
Example #4
Source File: KubernetesDeploymentsTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = InfrastructureException.class,
    expectedExceptionsMessageRegExp = "Found multiple pods in Deployment 'existing'")
public void shouldThrowExceptionWhenMultiplePodsExistsForDeploymentsOnPodFetching()
    throws Exception {
  // given
  when(podResource.get()).thenReturn(null);
  when(deploymentResource.get()).thenReturn(deployment);
  LabelSelector labelSelector = mock(LabelSelector.class);
  doReturn(labelSelector).when(deploymentSpec).getSelector();
  doReturn(ImmutableMap.of("deployment", "existing")).when(labelSelector).getMatchLabels();

  FilterWatchListDeletable filterList = mock(FilterWatchListDeletable.class);
  doReturn(filterList).when(podsNamespaceOperation).withLabels(any());
  PodList podList = mock(PodList.class);
  doReturn(asList(pod, pod)).when(podList).getItems();
  doReturn(podList).when(filterList).list();

  // when
  kubernetesDeployments.get("existing");
}
 
Example #5
Source File: KubernetesDeploymentsTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldReturnOptionalWithPodWhenPodWasNotFoundButDeploymentExists() throws Exception {
  // given
  when(podResource.get()).thenReturn(null);
  when(deploymentResource.get()).thenReturn(deployment);
  LabelSelector labelSelector = mock(LabelSelector.class);
  doReturn(labelSelector).when(deploymentSpec).getSelector();
  doReturn(ImmutableMap.of("deployment", "existing")).when(labelSelector).getMatchLabels();

  FilterWatchListDeletable filterList = mock(FilterWatchListDeletable.class);
  doReturn(filterList).when(podsNamespaceOperation).withLabels(any());
  PodList podList = mock(PodList.class);
  doReturn(singletonList(pod)).when(podList).getItems();
  doReturn(podList).when(filterList).list();

  // when
  Optional<Pod> fetchedPodOpt = kubernetesDeployments.get("existing");

  // then
  assertTrue(fetchedPodOpt.isPresent());
  verify(podsNamespaceOperation).withName("existing");
  verify(deploymentsNamespaceOperation).withName("existing");
  assertEquals(fetchedPodOpt.get(), pod);
}
 
Example #6
Source File: AbstractResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked") // due to L extends KubernetesResourceList/*<T>*/
protected List<T> listInNamespace(String namespace, Labels selector) {
    NonNamespaceOperation<T, L, D, R> tldrNonNamespaceOperation = operation().inNamespace(namespace);

    if (selector != null) {
        Map<String, String> labels = selector.toMap();
        FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> tlBooleanWatchWatcherFilterWatchListDeletable = tldrNonNamespaceOperation.withLabels(labels);
        return tlBooleanWatchWatcherFilterWatchListDeletable
                .list()
                .getItems();
    } else {
        return tldrNonNamespaceOperation
                .list()
                .getItems();
    }
}
 
Example #7
Source File: AbstractResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Future<List<T>> listAsync(String namespace, Optional<LabelSelector> selector) {
    Promise<List<T>> result = Promise.promise();
    vertx.createSharedWorkerExecutor("kubernetes-ops-tool").executeBlocking(
        future -> {
            FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> operation;
            if (AbstractWatchableResourceOperator.ANY_NAMESPACE.equals(namespace))  {
                operation = operation().inAnyNamespace();
            } else {
                operation = operation().inNamespace(namespace);
            }
            if (selector.isPresent()) {
                operation = operation.withLabelSelector(selector.get());
            }
            future.complete(operation.list().getItems());
        }, true, result
    );
    return result.future();
}
 
Example #8
Source File: BaseOperationTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testChainingGracePeriodAndPropagationPolicy() {
  final BaseOperation operation = new BaseOperation(new OperationContext());
  FilterWatchListDeletable<?, ?, Boolean, Watch, Watcher<?>> operationWithGracePeriod = operation.withGracePeriod(10L);
  FilterWatchListDeletable<?, ?, Boolean, Watch, Watcher<?>> operationWithPropagationPolicy = operation.withPropagationPolicy(DeletionPropagation.FOREGROUND);

  Object chainedGracePeriod = operationWithPropagationPolicy.withGracePeriod(10);
  Object chainedPropagationPolicy = operationWithGracePeriod.withPropagationPolicy(DeletionPropagation.FOREGROUND);

  assertThat(chainedGracePeriod, is(notNullValue()));
  assertThat(chainedPropagationPolicy, is(notNullValue()));
}
 
Example #9
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> withSelector(NonNamespaceOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods, LabelSelector selector, KitLogger log) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> answer = pods;
    Map<String, String> matchLabels = selector.getMatchLabels();
    if (matchLabels != null && !matchLabels.isEmpty()) {
        answer = answer.withLabels(matchLabels);
    }
    List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
    if (matchExpressions != null) {
        for (LabelSelectorRequirement expression : matchExpressions) {
            String key = expression.getKey();
            List<String> values = expression.getValues();
            if (StringUtils.isBlank(key)) {
                log.warn("Ignoring empty key in selector expression %s", expression);
                continue;
            }
            if (values == null || values.isEmpty()) {
                log.warn("Ignoring empty values in selector expression %s", expression);
                continue;
            }
            String[] valuesArray = values.toArray(new String[values.size()]);
            String operator = expression.getOperator();
            switch (operator) {
            case "In":
                answer = answer.withLabelIn(key, valuesArray);
                break;
            case "NotIn":
                answer = answer.withLabelNotIn(key, valuesArray);
                break;
            default:
                log.warn("Ignoring unknown operator %s in selector expression %s", operator, expression);
            }
        }
    }
    return answer;
}
 
Example #10
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> withoutField(String key, String value) {
  fieldsNot.merge(key, new String[]{value}, (oldList, newList) -> {
    if (Utils.isNotNullOrEmpty(newList[0])) { // Only add new values when not null
      final String[] concatList = (String[]) Array.newInstance(String.class, oldList.length + newList.length);
      System.arraycopy(oldList, 0, concatList, 0, oldList.length);
      System.arraycopy(newList, 0, concatList, oldList.length, newList.length);
      return concatList;
    } else {
      return oldList;
    }
  });
  return this;
}
 
Example #11
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> withoutFields(Map<String, String> fields) throws
  KubernetesClientException {
  // Re-use "withoutField" to convert values from String to String[]
  labels.forEach(this::withoutField);
  return this;
}
 
Example #12
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> withoutLabel(String key, String value) {
  labelsNot.merge(key, new String[]{value}, (oldList, newList) -> {
    final String[] concatList = (String[]) Array.newInstance(String.class, oldList.length + newList.length);
    System.arraycopy(oldList, 0, concatList, 0, oldList.length);
    System.arraycopy(newList, 0, concatList, oldList.length, newList.length);
    return concatList;
  });
  return this;
}
 
Example #13
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
@Deprecated
public FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> withoutLabels(Map<String, String> labels) throws
  KubernetesClientException {
  // Re-use "withoutLabel" to convert values from String to String[]
  labels.forEach(this::withoutLabel);
  return this;
}
 
Example #14
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> withLabelSelector(LabelSelector selector) {
  Map<String, String> matchLabels = selector.getMatchLabels();
  if (matchLabels != null) {
    this.labels.putAll(matchLabels);
  }
  List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
  if (matchExpressions != null) {
    for (LabelSelectorRequirement req : matchExpressions) {
      String operator = req.getOperator();
      String key = req.getKey();
      switch (operator) {
        case "In":
          withLabelIn(key, req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          withLabelNotIn(key, req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          withoutLabel(key);
          break;
        case "Exists":
          withLabel(key);
          break;
        default:
          throw new IllegalArgumentException("Unsupported operator: " + operator);
      }
    }
  }
  return this;
}
 
Example #15
Source File: KubeDiscovery.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static FilterWatchListDeletable<Service, ServiceList, Boolean, Watch, Watcher<Service>>
    createLabelFilterQuery(
        Map<String, String> labels,
        MixedOperation<Service, ServiceList, DoneableService, Resource<Service, DoneableService>>
            services) {
  FilterWatchListDeletable<Service, ServiceList, Boolean, Watch, Watcher<Service>> listable =
      null;
  for (Entry<String, String> entry : labels.entrySet()) {
    listable =
        listable == null
            ? services.withLabel(entry.getKey(), entry.getValue())
            : listable.withLabel(entry.getKey(), entry.getValue());
  }
  return listable;
}
 
Example #16
Source File: KubeDiscovery.java    From vxms with Apache License 2.0 5 votes vote down vote up
private static ServiceList getServicesByLabel(Map<String, String> labels, KubernetesClient client)
    throws KubernetesClientException {
  Objects.requireNonNull(client, "no client available");
  final MixedOperation<Service, ServiceList, DoneableService, Resource<Service, DoneableService>>
      services = client.services();
  final FilterWatchListDeletable<Service, ServiceList, Boolean, Watch, Watcher<Service>>
      listable = createLabelFilterQuery(labels, services);
  return listable.list();
}
 
Example #17
Source File: PortForwardService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private Pod getNewestPod(LabelSelector selector) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods =
            KubernetesHelper.withSelector(kubernetes.pods(), selector, log);

    PodList list = pods.list();
    if (list != null) {
        List<Pod> items = list.getItems();
        return getNewestPod(items);
    }
    return null;
}
 
Example #18
Source File: KubernetesTaskLauncher.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deletePod(String id) {
	FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podsToDelete = client.pods()
			.withLabel(SPRING_APP_KEY, id);

	if (podsToDelete != null && podsToDelete.list().getItems() != null) {
		logger.debug(String.format("Deleting Pod for task: %s", id));
		boolean podsDeleted = podsToDelete.delete();
		logger.debug(String.format("Pod deleted for: %s - %b", id, podsDeleted));
	}
}
 
Example #19
Source File: KubernetesTaskLauncher.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deleteJob(String id) {
	FilterWatchListDeletable<Job, JobList, Boolean, Watch, Watcher<Job>> jobsToDelete = client.batch().jobs()
			.withLabel(SPRING_APP_KEY, id);

	if (jobsToDelete != null && jobsToDelete.list().getItems() != null) {
		logger.debug(String.format("Deleting Job for task: %s", id));
		boolean jobDeleted = jobsToDelete.delete();
		logger.debug(String.format("Job deleted for: %s - %b", id, jobDeleted));
	}
}
 
Example #20
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deletePvc(Map<String, String> labels) {
	FilterWatchListDeletable<PersistentVolumeClaim, PersistentVolumeClaimList, Boolean, Watch,
			Watcher<PersistentVolumeClaim>> pvcsToDelete = client.persistentVolumeClaims()
			.withLabels(labels);

	if (pvcsToDelete != null && pvcsToDelete.list().getItems() != null) {
		boolean pvcsDeleted = pvcsToDelete.delete();
		logger.debug(String.format("PVC deleted for: %s - %b", labels, pvcsDeleted));
	}
}
 
Example #21
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> withSelector(NonNamespaceOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> pods, LabelSelector selector, KitLogger log) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> answer = pods;
    Map<String, String> matchLabels = selector.getMatchLabels();
    if (matchLabels != null && !matchLabels.isEmpty()) {
        answer = answer.withLabels(matchLabels);
    }
    List<LabelSelectorRequirement> matchExpressions = selector.getMatchExpressions();
    if (matchExpressions != null) {
        for (LabelSelectorRequirement expression : matchExpressions) {
            String key = expression.getKey();
            List<String> values = expression.getValues();
            if (StringUtils.isBlank(key)) {
                log.warn("Ignoring empty key in selector expression %s", expression);
                continue;
            }
            if (values == null || values.isEmpty()) {
                log.warn("Ignoring empty values in selector expression %s", expression);
                continue;
            }
            String[] valuesArray = values.toArray(new String[values.size()]);
            String operator = expression.getOperator();
            switch (operator) {
                case "In":
                    answer = answer.withLabelIn(key, valuesArray);
                    break;
                case "NotIn":
                    answer = answer.withLabelNotIn(key, valuesArray);
                    break;
                default:
                    log.warn("Ignoring unknown operator %s in selector expression %s", operator, expression);
            }
        }
    }
    return answer;
}
 
Example #22
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deletePod(Map<String, String> labels) {
	FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podsToDelete = client.pods()
			.withLabels(labels);

	if (podsToDelete != null && podsToDelete.list().getItems() != null) {
		boolean podsDeleted = podsToDelete.delete();
		logger.debug(String.format("Pod deleted for: %s - %b", labels, podsDeleted));
	}
}
 
Example #23
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deleteStatefulSet(Map<String, String> labels) {
	FilterWatchListDeletable<StatefulSet, StatefulSetList, Boolean, Watch, Watcher<StatefulSet>> ssToDelete =
			client.apps().statefulSets().withLabels(labels);

	if (ssToDelete != null && ssToDelete.list().getItems() != null) {
		boolean ssDeleted = ssToDelete.delete();
		logger.debug(String.format("StatefulSet deleted for: %s - %b", labels, ssDeleted));
	}
}
 
Example #24
Source File: Pods.java    From dekorate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link PodList} that match the specified {@link Deployment}.
 * @param deployment The {@link Deployment}
 */
protected PodList map(Deployment deployment) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = client.pods()
      .inNamespace(deployment.getMetadata().getNamespace());
  if (deployment.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(deployment.getSpec().getSelector().getMatchLabels());
  }
  if (deployment.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : deployment.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
      case "In":
        podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[] {}));
        break;
      case "NotIn":
        podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[] {}));
        break;
      case "DoesNotExist":
        podLister.withoutLabel(req.getKey());
        break;
      case "Exists":
        podLister.withLabel(req.getKey());
        break;
      }
    }
  }
  return podLister.list();
}
 
Example #25
Source File: AbstractWatchableResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public Watch watch(String namespace, Optional<LabelSelector> selector, Watcher<T> watcher) {
    FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> operation
            = ANY_NAMESPACE.equals(namespace) ? operation().inAnyNamespace() : operation().inNamespace(namespace);
    if (selector.isPresent()) {
        operation = operation.withLabelSelector(selector.get());
    }
    return operation.watch(watcher);
}
 
Example #26
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deleteDeployment(Map<String, String> labels) {
	FilterWatchListDeletable<Deployment, DeploymentList, Boolean, Watch, Watcher<Deployment>> deploymentsToDelete =
			client.apps().deployments().withLabels(labels);

	if (deploymentsToDelete != null && deploymentsToDelete.list().getItems() != null) {
		boolean deploymentsDeleted = deploymentsToDelete.delete();
		logger.debug(String.format("Deployment deleted for: %s - %b", labels, deploymentsDeleted));
	}
}
 
Example #27
Source File: Pods.java    From dekorate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@link PodList} that match the specified {@link ReplicaSet}.
 *
 * @param replicaSet The {@link ReplicaSet}
 */
protected PodList map(ReplicaSet replicaSet) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = client.pods()
      .inNamespace(replicaSet.getMetadata().getNamespace());
  if (replicaSet.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(replicaSet.getSpec().getSelector().getMatchLabels());
  }
  if (replicaSet.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : replicaSet.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
      case "In":
        podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[] {}));
        break;
      case "NotIn":
        podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[] {}));
        break;
      case "DoesNotExist":
        podLister.withoutLabel(req.getKey());
        break;
      case "Exists":
        podLister.withLabel(req.getKey());
        break;
      }
    }
  }
  return podLister.list();
}
 
Example #28
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deleteService(Map<String, String> labels) {
	FilterWatchListDeletable<Service, ServiceList, Boolean, Watch, Watcher<Service>> servicesToDelete =
			client.services().withLabels(labels);

	if (servicesToDelete != null && servicesToDelete.list().getItems() != null) {
		boolean servicesDeleted = servicesToDelete.delete();
		logger.debug(String.format("Service deleted for: %s - %b", labels, servicesDeleted));
	}
}
 
Example #29
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public FilterWatchListDeletable<T, L, Boolean, Watch, Watcher<T>> withLabel(String key) {
  return withLabel(key, null);
}
 
Example #30
Source File: K8SConsecutiveAllocationPolicy.java    From dynein with Apache License 2.0 4 votes vote down vote up
public List<Integer> getPartitions() {
  String podName = System.getenv("K8S_POD_NAME");
  String namespace = System.getenv("K8S_NAMESPACE");
  NamespacedKubernetesClient namespacedClient = kubernetesClient.inNamespace(namespace);
  ReplicaSet replicaSet;

  Pod pod = namespacedClient.pods().withName(podName).get();
  String replicaSetName = pod.getMetadata().getOwnerReferences().get(0).getName();
  replicaSet = appsClient.replicaSets().inNamespace(namespace).withName(replicaSetName).get();
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> deploymentPods =
      namespacedClient.pods().withLabelSelector(replicaSet.getSpec().getSelector());

  List<String> activePods =
      deploymentPods
          .list()
          .getItems()
          .stream()
          .filter(
              isActive ->
                  isActive
                      .getStatus()
                      .getConditions()
                      .stream()
                      .anyMatch(
                          condition ->
                              condition.getType().equals(K8S_CONDITION_READY)
                                  && condition.getStatus().equals(K8S_CONDITION_TRUE)))
          .map(it -> it.getMetadata().getName())
          .sorted(Collator.getInstance())
          .collect(Collectors.toList());

  int podIndex = activePods.indexOf(podName);
  int numPods = activePods.size();

  if (numPods == 0 || podIndex == -1) {
    return new ArrayList<>();
  }
  List<Integer> partitions = new ArrayList<>();
  int split = numPartitions / numPods;
  int start = podIndex * split;
  int end = (podIndex == numPods - 1) ? numPartitions - 1 : ((podIndex + 1) * split) - 1;
  for (int i = start; i <= end; i++) {
    partitions.add(i);
  }
  return partitions;
}