io.fabric8.kubernetes.client.utils.HttpClientUtils Java Examples

The following examples show how to use io.fabric8.kubernetes.client.utils.HttpClientUtils. 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: OpenShift.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public OpenShift(Environment environment) {
    super(environment, () -> {
        Config config = new ConfigBuilder().withMasterUrl(environment.getApiUrl())
                .withOauthToken(environment.getApiToken())
                .build();
        OkHttpClient httpClient = HttpClientUtils.createHttpClient(config);
        // Workaround https://github.com/square/okhttp/issues/3146
        httpClient = httpClient.newBuilder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectTimeout(environment.getKubernetesApiConnectTimeout())
                .writeTimeout(environment.getKubernetesApiWriteTimeout())
                .readTimeout(environment.getKubernetesApiReadTimeout())
                .build();
        return new DefaultOpenShiftClient(httpClient, new OpenShiftConfig(config));
    });
}
 
Example #2
Source File: KubernetesClientFactory.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Inject
public KubernetesClientFactory(
    @Nullable @Named("che.infra.kubernetes.master_url") String masterUrl,
    @Nullable @Named("che.infra.kubernetes.trust_certs") Boolean doTrustCerts,
    @Named("che.infra.kubernetes.client.http.async_requests.max") int maxConcurrentRequests,
    @Named("che.infra.kubernetes.client.http.async_requests.max_per_host")
        int maxConcurrentRequestsPerHost,
    @Named("che.infra.kubernetes.client.http.connection_pool.max_idle") int maxIdleConnections,
    @Named("che.infra.kubernetes.client.http.connection_pool.keep_alive_min")
        int connectionPoolKeepAlive,
    EventListener eventListener) {
  this.defaultConfig = buildDefaultConfig(masterUrl, doTrustCerts);
  OkHttpClient temporary = HttpClientUtils.createHttpClient(defaultConfig);
  OkHttpClient.Builder builder = temporary.newBuilder();
  ConnectionPool oldPool = temporary.connectionPool();
  builder.connectionPool(
      new ConnectionPool(maxIdleConnections, connectionPoolKeepAlive, TimeUnit.MINUTES));
  oldPool.evictAll();
  this.httpClient = builder.eventListener(eventListener).build();
  httpClient.dispatcher().setMaxRequests(maxConcurrentRequests);
  httpClient.dispatcher().setMaxRequestsPerHost(maxConcurrentRequestsPerHost);
}
 
Example #3
Source File: SSLUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isHttpsAvailable(Config config) {
    Config sslConfig = new ConfigBuilder(config)
            .withMasterUrl(Config.HTTPS_PROTOCOL_PREFIX + config.getMasterUrl())
            .withRequestTimeout(1000)
            .withConnectionTimeout(1000)
            .build();

    OkHttpClient client = HttpClientUtils.createHttpClient(config);
    try {
        Request request = new Request.Builder().get().url(sslConfig.getMasterUrl())
                .build();
        Response response = client.newCall(request).execute();
        try (ResponseBody body = response.body()) {
          return response.isSuccessful();
        }
    } catch (Throwable t) {
        LOG.warn("SSL handshake failed. Falling back to insecure connection.");
    } finally {
        if (client != null && client.connectionPool() != null) {
            client.connectionPool().evictAll();
        }
    }
    return false;
}
 
Example #4
Source File: SDKEntrypoint.java    From abstract-operator with Apache License 2.0 5 votes vote down vote up
private void checkIfOnOpenshift() {
    try {
        URL kubernetesApi = client.getMasterUrl();

        HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
        urlBuilder.host(kubernetesApi.getHost());

        if (kubernetesApi.getPort() == -1) {
            urlBuilder.port(kubernetesApi.getDefaultPort());
        } else {
            urlBuilder.port(kubernetesApi.getPort());
        }
        if (kubernetesApi.getProtocol().equals("https")) {
            urlBuilder.scheme("https");
        }
        urlBuilder.addPathSegment("apis/route.openshift.io/v1");

        OkHttpClient httpClient = HttpClientUtils.createHttpClient(new ConfigBuilder().build());
        HttpUrl url = urlBuilder.build();
        Response response = httpClient.newCall(new Request.Builder().url(url).build()).execute();
        boolean success = response.isSuccessful();
        if (success) {
            log.info("{} returned {}. We are on OpenShift.", url, response.code());
        } else {
            log.info("{} returned {}. We are not on OpenShift. Assuming, we are on Kubernetes.", url, response.code());
        }
        isOpenShift = success;
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Failed to distinguish between Kubernetes and OpenShift");
        log.warn("Let's assume we are on K8s");
        isOpenShift = false;
    }
}
 
Example #5
Source File: StyxScheduler.java    From styx with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static NamespacedKubernetesClient getKubernetesClient(Config rootConfig, String id,
                                                      Container gke, KubernetesClientFactory clientFactory) {
  try {
    final Config config = rootConfig
        .getConfig(GKE_CLUSTER_PATH)
        .getConfig(id);

    final Cluster cluster = gke.projects().locations().clusters()
        .get(String.format("projects/%s/locations/%s/clusters/%s",
                           config.getString(GKE_CLUSTER_PROJECT_ID),
                           config.getString(GKE_CLUSTER_ZONE),
                           config.getString(GKE_CLUSTER_ID))).execute();

    final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder()
        .withMasterUrl("https://" + cluster.getEndpoint())
        // missing container.clusters.getCredentials permission in GCP will result null cert and key
        // and we want it to fail loudly
        .withCaCertData(Objects.requireNonNull(cluster.getMasterAuth().getClusterCaCertificate(),
            "clusterCaCertificate"))
        .withClientCertData(Objects.requireNonNull(cluster.getMasterAuth().getClientCertificate(),
            "clientCertificate"))
        .withClientKeyData(Objects.requireNonNull(cluster.getMasterAuth().getClientKey(),
            "clientKey"))
        .withNamespace(config.getString(GKE_CLUSTER_NAMESPACE))
        .withRequestTimeout(get(rootConfig, rootConfig::getInt, KUBERNETES_REQUEST_TIMEOUT)
            .orElse(DEFAULT_KUBERNETES_REQUEST_TIMEOUT_MILLIS))
        .build();

    final OkHttpClient httpClient = HttpClientUtils.createHttpClient(kubeConfig).newBuilder()
        .protocols(Collections.singletonList(Protocol.HTTP_1_1))
        .build();

    return clientFactory.apply(httpClient, kubeConfig);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #6
Source File: Minikube.java    From enmasse with Apache License 2.0 5 votes vote down vote up
protected Minikube(Environment environment) {
    super(environment, () -> {
        Config config = new ConfigBuilder().build();
        OkHttpClient httpClient = HttpClientUtils.createHttpClient(config);
        // Workaround https://github.com/square/okhttp/issues/3146
        httpClient = httpClient.newBuilder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectTimeout(environment.getKubernetesApiConnectTimeout())
                .writeTimeout(environment.getKubernetesApiWriteTimeout())
                .readTimeout(environment.getKubernetesApiReadTimeout())
                .build();
        return new DefaultKubernetesClient(httpClient, config);
    });
}
 
Example #7
Source File: GenericKubernetes.java    From enmasse with Apache License 2.0 5 votes vote down vote up
protected GenericKubernetes(Environment environment) {
    super(environment, () -> {
        Config config = new ConfigBuilder().build();
        OkHttpClient httpClient = HttpClientUtils.createHttpClient(config);
        // Workaround https://github.com/square/okhttp/issues/3146
        httpClient = httpClient.newBuilder()
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))
                .connectTimeout(environment.getKubernetesApiConnectTimeout())
                .writeTimeout(environment.getKubernetesApiWriteTimeout())
                .readTimeout(environment.getKubernetesApiReadTimeout())
                .build();
        return new DefaultKubernetesClient(httpClient, config);
    });
}
 
Example #8
Source File: RawCustomResourceOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected HttpUrl.Builder fetchWatchUrl(String namespace, String name, Map<String, String> labels, ListOptions options) throws MalformedURLException {
  String resourceUrl = fetchUrl(namespace, null, labels);
  if (resourceUrl.endsWith("/")) {
    resourceUrl = resourceUrl.substring(0, resourceUrl.length() - 1);
  }
  URL url = new URL(resourceUrl);
  HttpUrl.Builder httpUrlBuilder = HttpUrl.get(url).newBuilder();

  if (name != null) {
    httpUrlBuilder.addQueryParameter("fieldSelector", "metadata.name=" + name);
  }

  HttpClientUtils.appendListOptionParams(httpUrlBuilder, options);
  return httpUrlBuilder;
}
 
Example #9
Source File: KubernetesSupport.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public KubernetesSupport(KubernetesClient client) {
    this.client = client;
    this.okHttpClient = HttpClientUtils.createHttpClient(this.client.getConfiguration());
}
 
Example #10
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
protected URL fetchListUrl(URL url, ListOptions listOptions) throws MalformedURLException {
  return new URL(HttpClientUtils.appendListOptionParams(HttpUrl.get(url.toString()).newBuilder(), listOptions).toString());
}
 
Example #11
Source File: BaseClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public BaseClient(final Config config) throws KubernetesClientException {
  this(HttpClientUtils.createHttpClient(config), config);
}