Java Code Examples for io.kubernetes.client.openapi.ApiClient#setHttpClient()

The following examples show how to use io.kubernetes.client.openapi.ApiClient#setHttpClient() . 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: 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 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: 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 4
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 5
Source File: ClientBuilder.java    From java with Apache License 2.0 5 votes vote down vote up
public ApiClient build() {
  final ApiClient client = new ApiClient();

  // defaulting client protocols to HTTP1.1
  client.setHttpClient(
      client.getHttpClient().newBuilder().protocols(Arrays.asList(Protocol.HTTP_1_1)).build());

  if (basePath != null) {
    if (basePath.endsWith("/")) {
      basePath = basePath.substring(0, basePath.length() - 1);
    }
    client.setBasePath(basePath);
  }

  client.setVerifyingSsl(verifyingSsl);

  if (authentication != null) {
    authentication.provide(client);
  }

  // NOTE: this ordering is important.  The API Client re-evaluates the CA certificate every
  // time the SSL info changes, which means that if this comes after the following call
  // you will try to load a certificate with an exhausted InputStream. So setting the CA
  // certificate _has_ to be the last thing that you do related to SSL.
  //
  // TODO: this (imho) is broken in the generate Java Swagger Client code. We should fix it
  // upstream and remove this dependency.
  //
  // TODO: Add a test to ensure that this works correctly...
  if (caCertBytes != null) {
    client.setSslCaCert(new ByteArrayInputStream(caCertBytes));
  }

  return client;
}
 
Example 6
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 7
Source File: K8sClient.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Create an instance of K8 api client and initialize with the KUBERNETES config. The config used follows the below pattern.
 *      1. If $KUBECONFIG is defined, use that config file.
 *      2. If $HOME/.kube/config can be found, use that.
 *      3. If the in-cluster service account can be found, assume in cluster config.
 *      4. Default to localhost:8080 as a last resort.
 */
private ApiClient initializeApiClient() {
    ApiClient client;
    try {
        log.debug("Initialize KUBERNETES api client");
        client = Config.defaultClient();
        client.setDebugging(false); // this can be set to true enable http dump.
        client.setHttpClient(client.getHttpClient().newBuilder().readTimeout(DEFAULT_TIMEOUT_MINUTES, TimeUnit.MINUTES).build());
        Configuration.setDefaultApiClient(client);
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));
    } catch (IOException e) {
        throw new TestFrameworkException(ConnectionFailed, "Connection to the k8 cluster failed, ensure .kube/config is configured correctly.", e);
    }
    return client;
}
 
Example 8
Source File: ControllerExample.java    From java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {

    CoreV1Api coreV1Api = new CoreV1Api();
    ApiClient apiClient = coreV1Api.getApiClient();
    OkHttpClient httpClient =
        apiClient.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();
    apiClient.setHttpClient(httpClient);

    // instantiating an informer-factory, and there should be only one informer-factory globally.
    SharedInformerFactory informerFactory = new SharedInformerFactory();
    // registering node-informer into the informer-factory.
    SharedIndexInformer<V1Node> nodeInformer =
        informerFactory.sharedIndexInformerFor(
            (CallGeneratorParams params) -> {
              return coreV1Api.listNodeCall(
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  params.resourceVersion,
                  params.timeoutSeconds,
                  params.watch,
                  null);
            },
            V1Node.class,
            V1NodeList.class);
    informerFactory.startAllRegisteredInformers();

    EventBroadcaster eventBroadcaster = new LegacyEventBroadcaster(coreV1Api);

    // nodeReconciler prints node information on events
    NodePrintingReconciler nodeReconciler =
        new NodePrintingReconciler(
            nodeInformer,
            eventBroadcaster.newRecorder(
                new V1EventSource().host("localhost").component("node-printer")));

    // Use builder library to construct a default controller.
    Controller controller =
        ControllerBuilder.defaultBuilder(informerFactory)
            .watch(
                (workQueue) ->
                    ControllerBuilder.controllerWatchBuilder(V1Node.class, workQueue)
                        .withWorkQueueKeyFunc(
                            (V1Node node) ->
                                new Request(node.getMetadata().getName())) // optional, default to
                        .withOnAddFilter(
                            (V1Node createdNode) ->
                                createdNode
                                    .getMetadata()
                                    .getName()
                                    .startsWith("docker-")) // optional, set onAdd filter
                        .withOnUpdateFilter(
                            (V1Node oldNode, V1Node newNode) ->
                                newNode
                                    .getMetadata()
                                    .getName()
                                    .startsWith("docker-")) // optional, set onUpdate filter
                        .withOnDeleteFilter(
                            (V1Node deletedNode, Boolean stateUnknown) ->
                                deletedNode
                                    .getMetadata()
                                    .getName()
                                    .startsWith("docker-")) // optional, set onDelete filter
                        .build())
            .withReconciler(nodeReconciler) // required, set the actual reconciler
            .withName("node-printing-controller") // optional, set name for controller
            .withWorkerCount(4) // optional, set worker thread count
            .withReadyFunc(
                nodeInformer
                    ::hasSynced) // optional, only starts controller when the cache has synced up
            .build();

    // Use builder library to manage one or multiple controllers.
    ControllerManager controllerManager =
        ControllerBuilder.controllerManagerBuilder(informerFactory)
            .addController(controller)
            .build();

    LeaderElectingController leaderElectingController =
        new LeaderElectingController(
            new LeaderElector(
                new LeaderElectionConfig(
                    new EndpointsLock("kube-system", "leader-election", "foo"),
                    Duration.ofMillis(10000),
                    Duration.ofMillis(8000),
                    Duration.ofMillis(5000))),
            controllerManager);

    leaderElectingController.run();
  }
 
Example 9
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 10
Source File: TokenFileAuthentication.java    From java with Apache License 2.0 4 votes vote down vote up
@Override
public void provide(ApiClient client) {
  OkHttpClient withInterceptor = client.getHttpClient().newBuilder().addInterceptor(this).build();
  client.setHttpClient(withInterceptor);
}