io.kubernetes.client.openapi.ApiClient Java Examples

The following examples show how to use io.kubernetes.client.openapi.ApiClient. 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: 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 #3
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 #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: LeaderElectionExample.java    From java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  ApiClient client = Config.defaultClient();
  Configuration.setDefaultApiClient(client);

  // New
  String appNamespace = "default";
  String appName = "leader-election-foobar";
  String lockHolderIdentityName = UUID.randomUUID().toString(); // Anything unique
  EndpointsLock lock = new EndpointsLock(appNamespace, appName, lockHolderIdentityName);

  LeaderElectionConfig leaderElectionConfig =
      new LeaderElectionConfig(
          lock, Duration.ofMillis(10000), Duration.ofMillis(8000), Duration.ofMillis(2000));
  LeaderElector leaderElector = new LeaderElector(leaderElectionConfig);

  leaderElector.run(
      () -> {
        System.out.println("Do something when getting leadership.");
      },
      () -> {
        System.out.println("Do something when losing leadership.");
      });
}
 
Example #6
Source File: PodWatchUtils.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public static ApiClient getApiClient() {
  if (apiClient == null) {
    createApiInstances();
  }

  return apiClient;
}
 
Example #7
Source File: ProtoExample.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);

  ProtoClient pc = new ProtoClient(client);
  ObjectOrStatus<PodList> list = pc.list(PodList.newBuilder(), "/api/v1/namespaces/default/pods");

  if (list.object.getItemsCount() > 0) {
    Pod p = list.object.getItems(0);
    System.out.println(p);
  }

  Namespace namespace =
      Namespace.newBuilder().setMetadata(ObjectMeta.newBuilder().setName("test").build()).build();

  ObjectOrStatus<Namespace> ns = pc.create(namespace, "/api/v1/namespaces", "v1", "Namespace");
  System.out.println(ns);
  if (ns.object != null) {
    namespace =
        ns.object
            .toBuilder()
            .setSpec(NamespaceSpec.newBuilder().addFinalizers("test").build())
            .build();
    // This is how you would update an object, but you can't actually
    // update namespaces, so this returns a 405
    ns = pc.update(namespace, "/api/v1/namespaces/test", "v1", "Namespace");
    System.out.println(ns.status);
  }

  ns = pc.delete(Namespace.newBuilder(), "/api/v1/namespaces/test");
  System.out.println(ns);
}
 
Example #8
Source File: KubeApiClients.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public static ApiClient createApiClient(String kubeApiServerUrl,
                                        String kubeConfigPath,
                                        String metricsNamePrefix,
                                        TitusRuntime titusRuntime,
                                        Function<Request, String> uriMapper,
                                        long readTimeoutMs) {
    OkHttpMetricsInterceptor metricsInterceptor = new OkHttpMetricsInterceptor(metricsNamePrefix, titusRuntime.getRegistry(),
            titusRuntime.getClock(), uriMapper);

    ApiClient client;
    if (Strings.isNullOrEmpty(kubeApiServerUrl)) {
        try {
            client = Config.fromConfig(kubeConfigPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        client = Config.fromUrl(kubeApiServerUrl);
    }

    client.setHttpClient(
            client.getHttpClient().newBuilder()
                    .addInterceptor(metricsInterceptor)
                    .readTimeout(readTimeoutMs, TimeUnit.SECONDS)
                    .build()
    );
    return client;
}
 
Example #9
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 #10
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 #11
Source File: ClientBuilderTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testKubeconfigPreferredOverHomeDir() throws Exception {
  environmentVariables.set("HOME", HOME_PATH);
  environmentVariables.set("KUBECONFIG", KUBECONFIG_FILE_PATH);
  final ApiClient client = ClientBuilder.standard().build();
  // $KUBECONFIG should take precedence over $HOME/.kube/config
  assertEquals("http://kubeconfig.dir.com", client.getBasePath());
}
 
Example #12
Source File: ClientCertificateAuthenticationTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidCertificatesChain() throws Exception {
  try {
    final ApiClient client = new ApiClient();
    final byte[] certificate = Files.readAllBytes(Paths.get(CLIENT_CERT_CHAIN_PATH));
    final byte[] key = Files.readAllBytes(Paths.get(CLIENT_CERT_CHAIN_KEY_PATH));
    new ClientCertificateAuthentication(certificate, key).provide(client);
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example #13
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 #14
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 #15
Source File: ConfigTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultClientKubeConfig() {
  try {
    environmentVariables.set("KUBECONFIG", configFile.getCanonicalPath());
    ApiClient client = Config.defaultClient();
    assertEquals("http://kubeconfig.dir.com", client.getBasePath());
  } catch (Exception ex) {
    ex.printStackTrace();
    fail("Unexpected exception: " + ex);
  }
}
 
Example #16
Source File: ClientBuilderTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHomeDirPreferredOverKubeConfig() throws Exception {
  environmentVariables.set("HOME", HOME_PATH);
  environmentVariables.set("KUBEDIR", KUBEDIR);
  environmentVariables.set("KUBECONFIG", KUBECONFIG);
  final ApiClient client = ClientBuilder.standard().build();
  assertEquals("http://home.dir.com", client.getBasePath());
}
 
Example #17
Source File: ClientBuilderTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultClientReadsKubeConfigMultiple() throws Exception {
  final String kubeConfigEnv = KUBECONFIG_FILE_PATH + File.pathSeparator + "/non-existent";
  environmentVariables.set("KUBECONFIG", kubeConfigEnv);
  final ApiClient client = ClientBuilder.defaultClient();
  assertEquals("http://kubeconfig.dir.com", client.getBasePath());
}
 
Example #18
Source File: UsernamePasswordAuthenticationTest.java    From java with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsernamePasswordProvided() {
  final ApiClient client = new ApiClient();
  new UsernamePasswordAuthentication(USERNAME, PASSWORD).provide(client);
  assertThat(getApiKeyAuthFromClient(client).getApiKeyPrefix(), is("Basic"));
  assertThat(
      getApiKeyAuthFromClient(client).getApiKey(),
      is(ByteString.of(USERNAME_PASSWORD_BYTES).base64()));
}
 
Example #19
Source File: AuthenticationV1beta1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public void setApiClient(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #20
Source File: StorageV1alpha1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public ApiClient getApiClient() {
    return localVarApiClient;
}
 
Example #21
Source File: CertificatesApi.java    From java with Apache License 2.0 4 votes vote down vote up
public ApiClient getApiClient() {
    return localVarApiClient;
}
 
Example #22
Source File: ApiextensionsV1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public void setApiClient(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #23
Source File: CoordinationV1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public CoordinationV1Api(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #24
Source File: SchedulingApi.java    From java with Apache License 2.0 4 votes vote down vote up
public SchedulingApi(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #25
Source File: NetworkingV1beta1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public void setApiClient(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #26
Source File: StorageApi.java    From java with Apache License 2.0 4 votes vote down vote up
public StorageApi(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #27
Source File: BatchV1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public BatchV1Api(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #28
Source File: NetworkingV1beta1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public NetworkingV1beta1Api(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}
 
Example #29
Source File: KubeApiClients.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public static SharedInformerFactory createSharedInformerFactory(String threadNamePrefix, ApiClient apiClient, TitusRuntime titusRuntime) {
    ExecutorService threadPool = ExecutorsExt.instrumentedCachedThreadPool(titusRuntime.getRegistry(), threadNamePrefix);
    return new SharedInformerFactory(apiClient, threadPool);
}
 
Example #30
Source File: SchedulingV1alpha1Api.java    From java with Apache License 2.0 4 votes vote down vote up
public void setApiClient(ApiClient apiClient) {
    this.localVarApiClient = apiClient;
}