io.kubernetes.client.openapi.apis.CoreV1Api Java Examples

The following examples show how to use io.kubernetes.client.openapi.apis.CoreV1Api. 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: 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 #3
Source File: SharedInformerFactoryTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void shutdownInformerFactoryInstantlyAfterStarting() {
  CoreV1Api api = new CoreV1Api();
  SharedInformerFactory factory = new SharedInformerFactory();
  factory.sharedIndexInformerFor(
      (CallGeneratorParams params) -> {
        return api.listNamespaceCall(
            null,
            null,
            null,
            null,
            null,
            null,
            params.resourceVersion,
            params.timeoutSeconds,
            params.watch,
            null);
      },
      V1Namespace.class,
      V1NamespaceList.class);

  factory.startAllRegisteredInformers();
  factory.stopAllRegisteredInformers();
}
 
Example #4
Source File: TokenFileAuthenticationTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testTokenProvided() throws IOException, ApiException {
  stubFor(
      get(urlPathEqualTo("/api/v1/pods")).willReturn(okForContentType("application/json", "{}")));
  CoreV1Api api = new CoreV1Api();

  api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  WireMock.verify(
      1,
      getRequestedFor(urlPathEqualTo("/api/v1/pods"))
          .withHeader("Authorization", equalTo("Bearer token1")));

  this.auth.setFile(SERVICEACCOUNT_TOKEN2_PATH);
  api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  WireMock.verify(
      2,
      getRequestedFor(urlPathEqualTo("/api/v1/pods"))
          .withHeader("Authorization", equalTo("Bearer token1")));

  this.auth.setExpiry(Instant.now().minusSeconds(1));
  api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  WireMock.verify(
      1,
      getRequestedFor(urlPathEqualTo("/api/v1/pods"))
          .withHeader("Authorization", equalTo("Bearer token2")));
}
 
Example #5
Source File: PatchUtilsTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStrategicMergePatchPod() throws ApiException {
  CoreV1Api coreV1Api = new CoreV1Api(client);
  stubFor(
      patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))
          .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody("{}")));

  PatchUtils.patch(
      V1Pod.class,
      () ->
          coreV1Api.patchNamespacedPodCall(
              "foo", "default", new V1Patch("[]"), null, null, null, null, null),
      V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH,
      client);

  verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
}
 
Example #6
Source File: PatchUtilsTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testMergePatchPod() throws ApiException {
  CoreV1Api coreV1Api = new CoreV1Api(client);
  stubFor(
      patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))
          .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody("{}")));

  PatchUtils.patch(
      V1Pod.class,
      () ->
          coreV1Api.patchNamespacedPodCall(
              "foo", "default", new V1Patch("[]"), null, null, null, null, null),
      V1Patch.PATCH_FORMAT_JSON_MERGE_PATCH,
      client);

  verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
}
 
Example #7
Source File: PatchUtilsTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonPatchPod() throws ApiException {
  CoreV1Api coreV1Api = new CoreV1Api(client);
  stubFor(
      patch(urlPathEqualTo("/api/v1/namespaces/default/pods/foo"))
          .withHeader("Content-Type", containing(V1Patch.PATCH_FORMAT_JSON_PATCH))
          .willReturn(
              aResponse()
                  .withStatus(200)
                  .withHeader("Content-Type", "application/json")
                  .withBody("{}")));

  PatchUtils.patch(
      V1Pod.class,
      () ->
          coreV1Api.patchNamespacedPodCall(
              "foo", "default", new V1Patch("[]"), null, null, null, null, null),
      V1Patch.PATCH_FORMAT_JSON_PATCH,
      client);

  verify(1, patchRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
}
 
Example #8
Source File: K8sClient.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Method used to create a namespace. This blocks until the namespace is created.
 * @param namespace Namespace to be created.
 * @return V1Namespace.
 */
@SneakyThrows(ApiException.class)
public V1Namespace createNamespace(final String namespace) {
    CoreV1Api api = new CoreV1Api();
    try {
        V1Namespace existing = api.readNamespace(namespace, PRETTY_PRINT, Boolean.FALSE, Boolean.FALSE);
        if (existing != null) {
            log.info("Namespace {} already exists, ignoring namespace create operation.", namespace);
            return existing;
        }
    } catch (ApiException ignore) {
        // ignore exception and proceed with Namespace creation.
    }

    V1Namespace body = new V1Namespace();
    // Set the required api version and kind of resource
    body.setApiVersion("v1");
    body.setKind("Namespace");

    // Setup the standard object metadata
    V1ObjectMeta meta = new V1ObjectMeta();
    meta.setName(namespace);
    body.setMetadata(meta);

    return api.createNamespace(body, PRETTY_PRINT, DRY_RUN, FIELD_MANAGER);
}
 
Example #9
Source File: ExampleTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void exactUrlOnly() throws IOException, ApiException {
  ApiClient client = new ApiClient();
  client.setBasePath("http://localhost:" + PORT);
  Configuration.setDefaultApiClient(client);

  V1Namespace ns1 = new V1Namespace().metadata(new V1ObjectMeta().name("name"));

  stubFor(
      get(urlEqualTo("/api/v1/namespaces/name"))
          .willReturn(
              aResponse()
                  .withHeader("Content-Type", "application/json")
                  .withBody(client.getJSON().serialize(ns1))));

  CoreV1Api api = new CoreV1Api();
  V1Namespace ns2 = api.readNamespace("name", null, null, null);
  assertEquals(ns1, ns2);
}
 
Example #10
Source File: WatchExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException {
  ApiClient client = Config.defaultClient();
  // infinite timeout
  OkHttpClient httpClient =
      client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
  client.setHttpClient(httpClient);
  Configuration.setDefaultApiClient(client);

  CoreV1Api api = new CoreV1Api();

  Watch<V1Namespace> watch =
      Watch.createWatch(
          client,
          api.listNamespaceCall(null, null, null, null, null, 5, null, null, Boolean.TRUE, null),
          new TypeToken<Watch.Response<V1Namespace>>() {}.getType());

  try {
    for (Watch.Response<V1Namespace> item : watch) {
      System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName());
    }
  } finally {
    watch.close();
  }
}
 
Example #11
Source File: K8sClient.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Delete persistent volume claim.
 * @param namespace Namespace.
 * @param name Persistent volume claim name.
 */
@SneakyThrows(ApiException.class)
public void deletePVC(String namespace, String name) {
    CoreV1Api api = new CoreV1Api();
    try {
        api.deleteNamespacedPersistentVolumeClaim(name, namespace, PRETTY_PRINT, DRY_RUN, null, null, null, new V1DeleteOptions());
    } catch (JsonSyntaxException e) {
        // https://github.com/kubernetes-client/java/issues/86
        if (e.getCause() instanceof IllegalStateException) {
            IllegalStateException ise = (IllegalStateException) e.getCause();
            if (ise.getMessage() != null && ise.getMessage().contains("Expected a string but was BEGIN_OBJECT")) {
                log.debug("Ignoring exception", e);
                return;
            }
        }
        throw e;
    }
}
 
Example #12
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public static CoreV1Api getCoreApi() {
  if (coreApi == null) {
    createApiInstances();
  }

  return coreApi;
}
 
Example #13
Source File: DefaultKubeApiFacade.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Inject
public DefaultKubeApiFacade(DirectKubeConfiguration configuration, ApiClient apiClient, TitusRuntime titusRuntime) {
    this.configuration = configuration;
    this.apiClient = apiClient;
    this.coreV1Api = new CoreV1Api(apiClient);
    this.customObjectsApi = new CustomObjectsApi(apiClient);
    this.titusRuntime = titusRuntime;
}
 
Example #14
Source File: WorkerLogger.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public WorkerLogger(String namespace,
                    String podName,
                    String containerName,
                    String id,
                    String logsDir,
                    CoreV1Api coreV1Api,
                    JobLogger jobLogger) {
  this.namespace = namespace;
  this.podName = podName;
  this.containerName = containerName;
  this.id = id;
  this.logsDir = logsDir;
  this.coreV1Api = coreV1Api;
  this.jobLogger = jobLogger;
}
 
Example #15
Source File: KubernetesController.java    From twister2 with Apache License 2.0 5 votes vote down vote up
/**
 * create CoreV1Api that does not time out
 */
public static CoreV1Api createCoreV1Api() {
  if (client == null) {
    getApiClient();
  }
  OkHttpClient httpClient =
      client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
  client.setHttpClient(httpClient);
  Configuration.setDefaultApiClient(client);
  return new CoreV1Api(client);
}
 
Example #16
Source File: KubernetesController.java    From twister2 with Apache License 2.0 5 votes vote down vote up
private static void initApiInstances() {
  if (client == null) {
    getApiClient();
  }

  Configuration.setDefaultApiClient(client);
  coreApi = new CoreV1Api();
  appsApi = new AppsV1Api(client);
}
 
Example #17
Source File: PagerExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {

    ApiClient client = Config.defaultClient();
    OkHttpClient httpClient =
        client.getHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
    client.setHttpClient(httpClient);
    Configuration.setDefaultApiClient(client);
    CoreV1Api api = new CoreV1Api();
    int i = 0;
    Pager<V1Namespace, V1NamespaceList> pager =
        new Pager<V1Namespace, V1NamespaceList>(
            (Pager.PagerParams param) -> {
              try {
                return api.listNamespaceCall(
                    null,
                    null,
                    param.getContinueToken(),
                    null,
                    null,
                    param.getLimit(),
                    null,
                    1,
                    null,
                    null);
              } catch (Exception e) {
                throw new RuntimeException(e);
              }
            },
            client,
            10,
            V1NamespaceList.class);
    for (V1Namespace namespace : pager) {
      System.out.println(namespace.getMetadata().getName());
    }
    System.out.println("------------------");
  }
 
Example #18
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 #19
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Deploy a pod. This ignores exception when the pod has already been deployed.
 * @param namespace Namespace.
 * @param pod Pod details.
 * @return Future which is completed once the deployemnt has been triggered.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1Pod> deployPod(final String namespace, final V1Pod pod) {
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1Pod> callback = new K8AsyncCallback<>("createPod");
    api.createNamespacedPodAsync(namespace, pod, PRETTY_PRINT, DRY_RUN, FIELD_MANAGER, callback);
    return exceptionallyExpecting(callback.getFuture(), isConflict, null);
}
 
Example #20
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 #21
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 #22
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Create a service account.
 * @param namespace The namespace.
 * @param account Service Account.
 * @return A future indicating the status of create service account operation.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1ServiceAccount> createServiceAccount(String namespace, V1ServiceAccount account) {
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1ServiceAccount> callback = new K8AsyncCallback<>("createServiceAccount");
    api.createNamespacedServiceAccountAsync(namespace, account, PRETTY_PRINT, DRY_RUN, FIELD_MANAGER, callback);
    return exceptionallyExpecting(callback.getFuture(), isConflict, null);
}
 
Example #23
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({ApiException.class, IOException.class})
private Optional<V1ContainerStateTerminated> createAWatchAndReturnOnTermination(String namespace, String podName) {
    log.debug("Creating a watch for pod {}/{}", namespace, podName);
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1ServiceAccount> callback = new K8AsyncCallback<>("createAWatchAndReturnOnTermination");
    @Cleanup
    Watch<V1Pod> watch = Watch.createWatch(
            client,
            api.listNamespacedPodCall(namespace, PRETTY_PRINT, ALLOW_WATCH_BOOKMARKS, null, null, "POD_NAME=" + podName, null,
                                      null, null, Boolean.TRUE, callback),
            new TypeToken<Watch.Response<V1Pod>>() {
            }.getType());

    for (Watch.Response<V1Pod> v1PodResponse : watch) {

        List<V1ContainerStatus> containerStatuses = v1PodResponse.object.getStatus().getContainerStatuses();
        log.debug("Container status for the pod {} is {}", podName, containerStatuses);
        if (containerStatuses == null || containerStatuses.size() == 0) {
            log.debug("Container status is not part of the pod {}/{}, wait for the next update from KUBERNETES Cluster", namespace, podName);
            continue;
        }
        // We check only the first container as there is only one container in the pod.
        V1ContainerState containerStatus = containerStatuses.get(0).getState();
        log.debug("Current container status is {}", containerStatus);
        if (containerStatus.getTerminated() != null) {
            log.info("Pod {}/{} has terminated", namespace, podName);
            return Optional.of(containerStatus.getTerminated());
        }
    }
    return Optional.empty();
}
 
Example #24
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 5 votes vote down vote up
private static void createApiInstances() {

    try {
      apiClient = io.kubernetes.client.util.Config.defaultClient();
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "Exception when creating ApiClient: ", e);
      throw new RuntimeException(e);
    }

    OkHttpClient httpClient =
        apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);
    Configuration.setDefaultApiClient(apiClient);
    coreApi = new CoreV1Api(apiClient);
  }
 
Example #25
Source File: DefaultControllerBuilderTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildWatchShouldWorkIfInformerPresent() {
  CoreV1Api api = new CoreV1Api();
  informerFactory.sharedIndexInformerFor(
      (CallGeneratorParams params) -> {
        return api.listPodForAllNamespacesCall(
            null,
            null,
            null,
            null,
            null,
            null,
            params.resourceVersion,
            params.timeoutSeconds,
            params.watch,
            null);
      },
      V1Pod.class,
      V1PodList.class);
  ControllerBuilder.defaultBuilder(informerFactory)
      .watch(
          (workQueue) -> ControllerBuilder.controllerWatchBuilder(V1Pod.class, workQueue).build())
      .withReconciler(
          new Reconciler() {
            @Override
            public Result reconcile(Request request) {
              return new Result(false);
            }
          })
      .build();
}
 
Example #26
Source File: Exec.java    From java with Apache License 2.0 5 votes vote down vote up
public Process execute() throws ApiException, IOException {
  if (container == null) {
    CoreV1Api api = new CoreV1Api(apiClient);
    V1Pod pod = api.readNamespacedPod(name, namespace, "false", null, null);
    container = pod.getSpec().getContainers().get(0).getName();
  }

  ExecProcess exec = new ExecProcess(apiClient);
  WebSocketStreamHandler handler = exec.getHandler();
  WebSockets.stream(makePath(), "GET", apiClient, handler);

  return exec;
}
 
Example #27
Source File: LogsExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException, InterruptedException {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);
  CoreV1Api coreApi = new CoreV1Api(client);

  PodLogs logs = new PodLogs();
  V1Pod pod =
      coreApi
          .listNamespacedPod("default", "false", null, null, null, null, null, null, null, null)
          .getItems()
          .get(0);

  InputStream is = logs.streamNamespacedPodLog(pod);
  ByteStreams.copy(is, System.out);
}
 
Example #28
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 #29
Source File: YamlExample.java    From java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, ApiException, ClassNotFoundException {
  V1Pod pod =
      new V1PodBuilder()
          .withNewMetadata()
          .withName("apod")
          .endMetadata()
          .withNewSpec()
          .addNewContainer()
          .withName("www")
          .withImage("nginx")
          .withNewResources()
          .withLimits(new HashMap<>())
          .endResources()
          .endContainer()
          .endSpec()
          .build();
  System.out.println(Yaml.dump(pod));

  V1Service svc =
      new V1ServiceBuilder()
          .withNewMetadata()
          .withName("aservice")
          .endMetadata()
          .withNewSpec()
          .withSessionAffinity("ClientIP")
          .withType("NodePort")
          .addNewPort()
          .withProtocol("TCP")
          .withName("client")
          .withPort(8008)
          .withNodePort(8080)
          .withTargetPort(new IntOrString(8080))
          .endPort()
          .endSpec()
          .build();
  System.out.println(Yaml.dump(svc));

  // Read yaml configuration file, and deploy it
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  //  See issue #474. Not needed at most cases, but it is needed if you are using war
  //  packging or running this on JUnit.
  Yaml.addModelMap("v1", "Service", V1Service.class);

  // Example yaml file can be found in $REPO_DIR/test-svc.yaml
  File file = new File("test-svc.yaml");
  V1Service yamlSvc = (V1Service) Yaml.load(file);

  // Deployment and StatefulSet is defined in apps/v1, so you should use AppsV1Api instead of
  // CoreV1API
  CoreV1Api api = new CoreV1Api();
  V1Service createResult = api.createNamespacedService("default", yamlSvc, null, null, null);

  System.out.println(createResult);

  V1Status deleteResult =
      api.deleteNamespacedService(
          yamlSvc.getMetadata().getName(),
          "default",
          null,
          null,
          null,
          null,
          null,
          new V1DeleteOptions());
  System.out.println(deleteResult);
}
 
Example #30
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());
  }
}