io.kubernetes.client.util.ClientBuilder Java Examples

The following examples show how to use io.kubernetes.client.util.ClientBuilder. 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: GenericKubernetesApiForCoreApiTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadTimeoutShouldThrowException() {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8181).build();
  apiClient.setHttpClient(
      apiClient
          .getHttpClient()
          .newBuilder()
          .readTimeout(1, TimeUnit.MILLISECONDS) // timeout everytime
          .build());
  podClient =
      new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "", "v1", "pods", apiClient);
  try {
    KubernetesApiResponse<V1Pod> response = podClient.get("foo", "test");
  } catch (Throwable t) {
    assertTrue(t.getCause() instanceof SocketTimeoutException);
    return;
  }
  fail("no exception happened");
}
 
Example #3
Source File: GenericKubernetesApiTest.java    From java with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadTimeoutShouldThrowException() {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8181).build();
  apiClient.setHttpClient(
      apiClient
          .getHttpClient()
          .newBuilder()
          .readTimeout(1, TimeUnit.MILLISECONDS) // timeout everytime
          .build());
  jobClient =
      new GenericKubernetesApi<>(V1Job.class, V1JobList.class, "batch", "v1", "jobs", apiClient);
  try {
    KubernetesApiResponse<V1Job> response = jobClient.get("foo", "test");
  } catch (Throwable t) {
    assertTrue(t.getCause() instanceof SocketTimeoutException);
    return;
  }
  fail("no exception happened");
}
 
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: PodLogsTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();

  namespace = "default";
  podName = "apod";
  container = "container";
}
 
Example #6
Source File: KubeExternalResource.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    String kubeServer = Preconditions.checkNotNull(System.getenv("KUBE_API_SERVER"),
            "'KUBE_API_SERVER' environment variable not set"
    );

    this.client = ClientBuilder
            .standard()
            .setBasePath(String.format("http://%s:7001", kubeServer))
            .build();
    client.setReadTimeout(0); // infinite timeout
}
 
Example #7
Source File: KubernetesController.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public static ApiClient getApiClient() {
  if (client != null) {
    return client;
  }
  try {
    client = ClientBuilder.standard()
        .setOverridePatchFormat(V1Patch.PATCH_FORMAT_JSON_PATCH)
        .build();
    return client;
  } catch (IOException e) {
    LOG.log(Level.SEVERE, "Exception when creating ApiClient: ", e);
    throw new RuntimeException(e);
  }
}
 
Example #8
Source File: GenericKubernetesGetApiTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8181).build();
  jobClient =
      new GenericKubernetesApi<>(V1Job.class, V1JobList.class, "batch", "v1", "jobs", apiClient);
  fooClient =
      new GenericKubernetesApi<>(
          FooCustomResource.class,
          FooCustomResourceList.class,
          "example.io",
          "v1",
          "foos",
          apiClient);
}
 
Example #9
Source File: AttachTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();

  namespace = "default";
  podName = "apod";
  container = "acontainer";
}
 
Example #10
Source File: DefaultSharedIndexInformerTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();

  namespace = "default";
  podName = "apod";
  container = "container";
}
 
Example #11
Source File: ExperimentRestApiIT.java    From submarine with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startUp() throws IOException {
  Assert.assertTrue(checkIfServerIsRunning());

  // The kube config path defined by kind-cluster-build.sh
  String confPath = System.getProperty("user.home") + "/.kube/kind-config-kind";
  KubeConfig config = KubeConfig.loadKubeConfig(new FileReader(confPath));
  ApiClient client = ClientBuilder.kubeconfig(config).build();
  Configuration.setDefaultApiClient(client);
  k8sApi = new CustomObjectsApi();

  kfOperatorMap = new HashMap<>();
  kfOperatorMap.put("tensorflow", new KfOperator("v1", "tfjobs"));
  kfOperatorMap.put("pytorch", new KfOperator("v1", "pytorchjobs"));
}
 
Example #12
Source File: ExecTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();

  namespace = "default";
  podName = "apod";
  // TODO: When WireMock supports multiple query params with the same name expand
  // this
  // See: https://github.com/tomakehurst/wiremock/issues/398
  cmd = new String[] {"cmd"};
}
 
Example #13
Source File: PortForwardTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();

  namespace = "default";
  podName = "apod";
  container = "acontainer";
}
 
Example #14
Source File: CopyTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();

  namespace = "default";
  podName = "apod";
}
 
Example #15
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 #16
Source File: KubernetesNatManager.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws NatInitializationException {
  LOG.info("Starting kubernetes NAT manager.");
  try {

    KubeConfig.registerAuthenticator(new GCPAuthenticator());

    LOG.debug("Trying to update information using Kubernetes client SDK.");
    final ApiClient client = ClientBuilder.cluster().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.
    final CoreV1Api api = new CoreV1Api();
    // invokes the CoreV1Api client
    final V1Service service =
        api.listServiceForAllNamespaces(null, null, null, null, null, null, null, null, null)
            .getItems().stream()
            .filter(v1Service -> v1Service.getMetadata().getName().contains(besuPodNameFilter))
            .findFirst()
            .orElseThrow(() -> new NatInitializationException("Service not found"));
    updateUsingBesuService(service);
  } catch (Exception e) {
    throw new NatInitializationException(e.getMessage(), e);
  }
}
 
Example #17
Source File: GenericKubernetesApiTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws IOException {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8181).build();
  jobClient =
      new GenericKubernetesApi<>(V1Job.class, V1JobList.class, "batch", "v1", "jobs", apiClient);
}
 
Example #18
Source File: SpringControllerExample.java    From java with Apache License 2.0 4 votes vote down vote up
@Bean
public ApiClient myApiClient() throws IOException {
  ApiClient apiClient = ClientBuilder.standard().build();
  return apiClient.setHttpClient(
      apiClient.getHttpClient().newBuilder().readTimeout(Duration.ZERO).build());
}
 
Example #19
Source File: GenericKubernetesApiForCoreApiTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws IOException {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8181).build();
  podClient =
      new GenericKubernetesApi<>(V1Pod.class, V1PodList.class, "", "v1", "pods", apiClient);
}
 
Example #20
Source File: PatchExample.java    From java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
  try {
    ExtensionsV1beta1Api api = new ExtensionsV1beta1Api(ClientBuilder.standard().build());
    ExtensionsV1beta1Deployment body =
        Configuration.getDefaultApiClient()
            .getJSON()
            .deserialize(jsonDeploymentStr, ExtensionsV1beta1Deployment.class);

    // create a deployment
    ExtensionsV1beta1Deployment deploy1 =
        api.createNamespacedDeployment("default", body, null, null, null);
    System.out.println("original deployment" + deploy1);

    // json-patch a deployment
    ExtensionsV1beta1Deployment deploy2 =
        PatchUtils.patch(
            ExtensionsV1beta1Deployment.class,
            () ->
                api.patchNamespacedDeploymentCall(
                    "hello-node",
                    "default",
                    new V1Patch(jsonPatchStr),
                    null,
                    null,
                    null,
                    null,
                    null),
            V1Patch.PATCH_FORMAT_JSON_PATCH,
            api.getApiClient());
    System.out.println("json-patched deployment" + deploy2);

    // strategic-merge-patch a deployment
    ExtensionsV1beta1Deployment deploy3 =
        PatchUtils.patch(
            ExtensionsV1beta1Deployment.class,
            () ->
                api.patchNamespacedDeploymentCall(
                    "hello-node",
                    "default",
                    new V1Patch(strategicMergePatchStr),
                    null,
                    null,
                    null,
                    null,
                    null),
            V1Patch.PATCH_FORMAT_STRATEGIC_MERGE_PATCH,
            api.getApiClient());
    System.out.println("strategic-merge-patched deployment" + deploy3);

    // apply-yaml a deployment, server side apply is alpha in kubernetes v1.14,
    // You need to actively enable the Server Side Apply alpha feature
    // https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply
    ExtensionsV1beta1Deployment deploy4 =
        PatchUtils.patch(
            ExtensionsV1beta1Deployment.class,
            () ->
                api.patchNamespacedDeploymentCall(
                    "hello-node",
                    "default",
                    new V1Patch(applyYamlStr),
                    null,
                    null,
                    null,
                    null,
                    null),
            V1Patch.PATCH_FORMAT_APPLY_YAML,
            api.getApiClient());
    System.out.println("application/apply-patch+yaml deployment" + deploy4);

  } catch (ApiException e) {
    System.out.println(e.getResponseBody());
    e.printStackTrace();
  }
}
 
Example #21
Source File: DefaultControllerBuilderTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();
}
 
Example #22
Source File: PagerTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws IOException {
  client = new ClientBuilder().setBasePath("http://localhost:" + PORT).build();
}
 
Example #23
Source File: KubernetesInformerCreatorTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Bean
public ApiClient testingApiClient() {
  ApiClient apiClient = new ClientBuilder().setBasePath("http://localhost:" + 8188).build();
  return apiClient;
}