io.kubernetes.client.openapi.models.V1PodList Java Examples

The following examples show how to use io.kubernetes.client.openapi.models.V1PodList. 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: KubeConfigFileClientExample.java    From java with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {

    // file path to your KubeConfig
    String kubeConfigPath = "~/.kube/config";

    // loading the out-of-cluster config, a kubeconfig from file-system
    ApiClient client =
        ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list =
        api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
 
Example #2
Source File: ExpandedExample.java    From java with Apache License 2.0 6 votes vote down vote up
/**
 * List pod in specific namespace with label
 *
 * @param namespace
 * @param label
 * @return
 * @throws ApiException
 */
public static List<String> getNamespacedPod(String namespace, String label) throws ApiException {
  V1PodList listNamespacedPod =
      COREV1_API.listNamespacedPod(
          namespace,
          null,
          null,
          null,
          null,
          label,
          Integer.MAX_VALUE,
          null,
          TIME_OUT_VALUE,
          Boolean.FALSE);
  List<String> listPods =
      listNamespacedPod
          .getItems()
          .stream()
          .map(v1pod -> v1pod.getMetadata().getName())
          .collect(Collectors.toList());
  return listPods;
}
 
Example #3
Source File: DefaultKubeApiFacade.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private SharedIndexInformer<V1Pod> createPodInformer(SharedInformerFactory sharedInformerFactory) {
    return sharedInformerFactory.sharedIndexInformerFor(
            (CallGeneratorParams params) -> coreV1Api.listNamespacedPodCall(
                    KUBERNETES_NAMESPACE,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    params.resourceVersion,
                    params.timeoutSeconds,
                    params.watch,
                    null
            ),
            V1Pod.class,
            V1PodList.class,
            configuration.getKubeApiServerIntegratorRefreshIntervalMs()
    );
}
 
Example #4
Source File: InClusterClientExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {

    // loading the in-cluster config, including:
    //   1. service-account CA
    //   2. service-account bearer-token
    //   3. service-account namespace
    //   4. master endpoints(ip, port) from pre-set environment variables
    ApiClient client = ClientBuilder.cluster().build();

    // if you prefer not to refresh service account token, please use:
    // ApiClient client = ClientBuilder.oldCluster().build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list =
        api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
 
Example #5
Source File: KubernetesController.java    From twister2 with Apache License 2.0 6 votes vote down vote up
public List<String> getUploaderWebServerPods(String uploaderLabel) {

    V1PodList podList = null;
    try {
      podList = coreApi.listNamespacedPod(
          namespace, null, null, null, null, uploaderLabel, null, null, null, null);
    } catch (ApiException e) {
      LOG.log(Level.SEVERE, "Exception when getting uploader pod list.", e);
      throw new RuntimeException(e);
    }

    List<String> podNames = podList
        .getItems()
        .stream()
        .map(v1pod -> v1pod.getMetadata().getName())
        .collect(Collectors.toList());

    return podNames;
  }
 
Example #6
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 6 votes vote down vote up
/**
 * a test method to see whether kubernetes java client can connect to kubernetes master
 * and get the pod list
 */
public static void testGetPodList(String namespace) {
  if (apiClient == null || coreApi == null) {
    createApiInstances();
  }

  LOG.info("Getting the pod list for the namespace: " + namespace);
  V1PodList list = null;
  try {
    list = coreApi.listNamespacedPod(
        namespace, null, null, null, null, null, null, null, null, null);
  } catch (ApiException e) {
    String logMessage = "Exception when getting the pod list: \n"
        + "exCode: " + e.getCode() + "\n"
        + "responseBody: " + e.getResponseBody();
    LOG.log(Level.SEVERE, logMessage, e);
    throw new RuntimeException(e);
  }

  LOG.info("Number of pods in the received list: " + list.getItems().size());
  for (V1Pod item : list.getItems()) {
    LOG.info(item.getMetadata().getName());
  }
}
 
Example #7
Source File: Example.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();
  V1PodList list =
      api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
  }
}
 
Example #8
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Method to fetch all pods which match a set of labels.
 * @param namespace Namespace on which the pod(s) reside.
 * @param labels Name of the label.
 * @return Future representing the list of pod status.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1PodList> getPodsWithLabels(String namespace, Map<String, String> labels) {
    CoreV1Api api = new CoreV1Api();

    log.debug("Current number of http interceptors {}", api.getApiClient().getHttpClient().networkInterceptors().size());

    String labelSelector = labels.entrySet().stream().map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.joining());
    K8AsyncCallback<V1PodList> callback = new K8AsyncCallback<>("listPods");
    api.listNamespacedPodAsync(namespace, PRETTY_PRINT, ALLOW_WATCH_BOOKMARKS, null, null, labelSelector, null,
                               null, null, false, callback);
    return callback.getFuture();
}
 
Example #9
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to fetch the status of a Pod. V1PodStatus also helps to indicate the container status.
 * @param namespace Namespace.
 * @param podName Name of the pod.
 * @return A future representing the status of the pod.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1PodStatus> getStatusOfPod(final String namespace, final String podName) {
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1PodList> callback = new K8AsyncCallback<>("listPods");
    api.listNamespacedPodAsync(namespace, PRETTY_PRINT, ALLOW_WATCH_BOOKMARKS, null, null, "POD_NAME=" + podName, null,
                               null, null, false, callback);
    return callback.getFuture()
                   .thenApply(v1PodList -> {
                       Optional<V1Pod> vpod = v1PodList.getItems().stream().filter(v1Pod -> v1Pod.getMetadata().getName().equals(podName) &&
                               v1Pod.getMetadata().getNamespace().equals(namespace)).findFirst();
                       return vpod.map(V1Pod::getStatus).orElseThrow(() -> new RuntimeException("pod not found" + podName));
                   });
}
 
Example #10
Source File: DemoApplication.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/hello")
public String hello() throws Exception {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);

    CoreV1Api api = new CoreV1Api();
    V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);

    List<String> rlt = new ArrayList<>();
    rlt.add(new Date().toString());
    rlt.addAll(list.getItems().stream().map(value -> value.getMetadata().getNamespace() + ":" + value.getMetadata().getName()).collect(Collectors.toList()));
    return new Gson().toJson(rlt);
}
 
Example #11
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 5 votes vote down vote up
/**
   * get the IP of the node where the pod with that name is running
   */
  public static String getNodeIP(String namespace, String jobID, String podIP) {

    if (apiClient == null || coreApi == null) {
      createApiInstances();
    }

    // this is better but it does not work with another installation
//    String podNameLabel = "statefulset.kubernetes.io/pod-name=" + podName;
    String workerRoleLabel = KubernetesUtils.workerPodLabelSelector(jobID);

    V1PodList podList = null;
    try {
      podList = coreApi.listNamespacedPod(
          namespace, null, null, null, null, workerRoleLabel, null, null, null, null);
    } catch (ApiException e) {
      LOG.log(Level.SEVERE, "Exception when getting PodList.", e);
      throw new RuntimeException(e);
    }

    for (V1Pod pod : podList.getItems()) {
      if (podIP.equals(pod.getStatus().getPodIP())) {
        return pod.getStatus().getHostIP();
      }
    }

    return null;
  }
 
Example #12
Source File: GenericClientExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

    // The following codes demonstrates using generic client to manipulate pods
    V1Pod pod =
        new V1Pod()
            .metadata(new V1ObjectMeta().name("foo").namespace("default"))
            .spec(
                new V1PodSpec()
                    .containers(Arrays.asList(new V1Container().name("c").image("test"))));
    ApiClient apiClient = ClientBuilder.standard().build();
    GenericKubernetesApi<V1Pod, V1PodList> podClient =
        new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "", "v1", "pods", apiClient);

    KubernetesApiResponse<V1Pod> createResponse = podClient.create(pod);
    if (!createResponse.isSuccess()) {
      throw new RuntimeException(createResponse.getStatus().toString());
    }
    System.out.println("Created!");

    KubernetesApiResponse<V1Pod> patchResponse =
        podClient.patch(
            "default",
            "foo",
            V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH,
            new V1Patch("{\"metadata\":{\"finalizers\":[\"example.io/foo\"]}}"));
    if (!patchResponse.isSuccess()) {
      throw new RuntimeException(patchResponse.getStatus().toString());
    }
    System.out.println("Patched!");

    KubernetesApiResponse<V1Pod> deleteResponse = podClient.delete("default", "foo");
    if (!deleteResponse.isSuccess()) {
      throw new RuntimeException(deleteResponse.getStatus().toString());
    }
    if (deleteResponse.getObject() != null) {
      System.out.println(
          "Received after-deletion status of the requested object, will be deleting in background!");
    }
    System.out.println("Deleted!");
  }
 
Example #13
Source File: ExpandedExample.java    From java with Apache License 2.0 5 votes vote down vote up
/**
 * List all pod names in all namespaces in k8s cluster
 *
 * @return
 * @throws ApiException
 */
public static List<String> getPods() throws ApiException {
  V1PodList v1podList =
      COREV1_API.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  List<String> podList =
      v1podList
          .getItems()
          .stream()
          .map(v1Pod -> v1Pod.getMetadata().getName())
          .collect(Collectors.toList());
  return podList;
}
 
Example #14
Source File: FluentExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();

  V1Pod pod =
      new V1PodBuilder()
          .withNewMetadata()
          .withName("apod")
          .endMetadata()
          .withNewSpec()
          .addNewContainer()
          .withName("www")
          .withImage("nginx")
          .endContainer()
          .endSpec()
          .build();

  api.createNamespacedPod("default", pod, null, null, null);

  V1Pod pod2 =
      new V1Pod()
          .metadata(new V1ObjectMeta().name("anotherpod"))
          .spec(
              new V1PodSpec()
                  .containers(Arrays.asList(new V1Container().name("www").image("nginx"))));

  api.createNamespacedPod("default", pod2, null, null, null);

  V1PodList list =
      api.listNamespacedPod("default", null, null, null, null, null, null, null, null, null);
  for (V1Pod item : list.getItems()) {
    System.out.println(item.getMetadata().getName());
  }
}
 
Example #15
Source File: ControllerTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Test
public void testControllerProcessDeltas() throws InterruptedException {

  AtomicInteger receivingDeltasCount = new AtomicInteger(0);
  V1Pod foo1 = new V1Pod().metadata(new V1ObjectMeta().name("foo1").namespace("default"));
  V1Pod foo2 = new V1Pod().metadata(new V1ObjectMeta().name("foo2").namespace("default"));
  V1Pod foo3 = new V1Pod().metadata(new V1ObjectMeta().name("foo3").namespace("default"));

  V1PodList podList =
      new V1PodList().metadata(new V1ListMeta()).items(Arrays.asList(foo1, foo2, foo3));
  DeltaFIFO deltaFIFO = new DeltaFIFO(Caches::deletionHandlingMetaNamespaceKeyFunc, new Cache());

  AtomicBoolean runOnce = new AtomicBoolean(false);

  ListerWatcher<V1Pod, V1PodList> listerWatcher =
      new MockRunOnceListerWatcher<V1Pod, V1PodList>(
          podList, new Watch.Response<V1Pod>(EventType.MODIFIED.name(), foo3));

  Controller<V1Pod, V1PodList> controller =
      new Controller<>(
          V1Pod.class,
          deltaFIFO,
          listerWatcher,
          (deltas) -> {
            receivingDeltasCount.incrementAndGet();
          });
  Thread controllerThread = new Thread(controller::run);
  controllerThread.setDaemon(true);
  controllerThread.start();

  // sleep 1s for processing all the deltas
  Thread.sleep(1000);

  try {
    assertEquals(4, receivingDeltasCount.get());

  } catch (Throwable t) {
    throw new RuntimeException(t);
  } finally {
    controller.stop();
  }
}
 
Example #16
Source File: KubernetesInformerCreatorTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Test
public void testInformerInjection() throws InterruptedException {
  assertNotNull(podInformer);
  assertNotNull(configMapInformer);
  assertNotNull(podLister);
  assertNotNull(configMapLister);

  V1Pod foo1 =
      new V1Pod().kind("Pod").metadata(new V1ObjectMeta().namespace("default").name("foo1"));
  V1ConfigMap bar1 =
      new V1ConfigMap()
          .kind("ConfigMap")
          .metadata(new V1ObjectMeta().namespace("default").name("bar1"));

  wireMockRule.stubFor(
      get(urlMatching("^/api/v1/pods.*"))
          .withQueryParam("watch", equalTo("false"))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withBody(
                      new Gson()
                          .toJson(
                              new V1PodList()
                                  .metadata(new V1ListMeta().resourceVersion("0"))
                                  .items(Arrays.asList(foo1))))));
  wireMockRule.stubFor(
      get(urlMatching("^/api/v1/pods.*"))
          .withQueryParam("watch", equalTo("true"))
          .willReturn(aResponse().withStatus(200).withBody("{}")));

  wireMockRule.stubFor(
      get(urlMatching("^/api/v1/configmaps.*"))
          .withQueryParam("watch", equalTo("false"))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withBody(
                      new Gson()
                          .toJson(
                              new V1ConfigMapList()
                                  .metadata(new V1ListMeta().resourceVersion("0"))
                                  .items(Arrays.asList(bar1))))));
  wireMockRule.stubFor(
      get(urlMatching("^/api/v1/configmaps.*"))
          .withQueryParam("watch", equalTo("true"))
          .willReturn(aResponse().withStatus(200).withBody("{}")));

  informerFactory.startAllRegisteredInformers();

  Thread.sleep(200);

  verify(
      1,
      getRequestedFor(urlPathEqualTo("/api/v1/pods")).withQueryParam("watch", equalTo("false")));
  verify(
      getRequestedFor(urlPathEqualTo("/api/v1/pods")).withQueryParam("watch", equalTo("true")));
  verify(
      1,
      getRequestedFor(urlPathEqualTo("/api/v1/configmaps"))
          .withQueryParam("watch", equalTo("false")));
  verify(
      getRequestedFor(urlPathEqualTo("/api/v1/configmaps"))
          .withQueryParam("watch", equalTo("true")));

  assertEquals(1, podLister.list().size());
  assertEquals(1, configMapLister.list().size());
}
 
Example #17
Source File: K8sClient.java    From pravega with Apache License 2.0 2 votes vote down vote up
/**
 * Method to fetch all pods which match a label.
 * @param namespace Namespace on which the pod(s) reside.
 * @param labelName Name of the label.
 * @param labelValue Value of the label.
 * @return Future representing the list of pod status.
 */
public CompletableFuture<V1PodList> getPodsWithLabel(String namespace, String labelName, String labelValue) {
    return getPodsWithLabels(namespace, ImmutableMap.of(labelName, labelValue));
}