Search in sources :

Example 1 with Interceptor

use of io.fabric8.kubernetes.client.http.Interceptor in project che-server by eclipse-che.

the class OpenShiftClientFactory method buildKubernetesInterceptor.

@Override
protected Interceptor buildKubernetesInterceptor(Config config) {
    final String oauthToken;
    if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) {
        synchronized (getHttpClient()) {
            try {
                OkHttpClient.Builder builder = getHttpClient().newBuilder();
                builder.interceptors().clear();
                OkHttpClient clone = builder.build();
                String credential = Credentials.basic(config.getUsername(), config.getPassword());
                URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
                Response response = clone.newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()).execute();
                // False positive warn: according to javadocs response.body() returns non-null value
                // if called after Call.execute()
                response.body().close();
                response = response.priorResponse() != null ? response.priorResponse() : response;
                response = response.networkResponse() != null ? response.networkResponse() : response;
                String token = response.header(LOCATION);
                if (token == null || token.isEmpty()) {
                    throw new KubernetesClientException("Unexpected response (" + response.code() + " " + response.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!");
                }
                token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
                token = token.substring(0, token.indexOf(AFTER_TOKEN));
                oauthToken = token;
            } catch (Exception e) {
                throw KubernetesClientException.launderThrowable(e);
            }
        }
    } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
        oauthToken = config.getOauthToken();
    } else {
        oauthToken = null;
    }
    return chain -> {
        Request request = chain.request();
        if (isNotNullOrEmpty(oauthToken)) {
            Request authReq = chain.request().newBuilder().addHeader("Authorization", "Bearer " + oauthToken).build();
            return chain.proceed(authReq);
        }
        return chain.proceed(request);
    };
}
Also used : Response(okhttp3.Response) KubernetesClientFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory) Authenticator(okhttp3.Authenticator) URL(java.net.URL) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) Singleton(javax.inject.Singleton) Inject(javax.inject.Inject) Utils(io.fabric8.kubernetes.client.utils.Utils) EventListener(okhttp3.EventListener) Response(okhttp3.Response) Named(javax.inject.Named) KubernetesClientConfigFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientConfigFactory) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) Interceptor(okhttp3.Interceptor) OpenShiftOAuthInterceptor(io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor) Request(okhttp3.Request) URLUtils(io.fabric8.kubernetes.client.utils.URLUtils) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Credentials(okhttp3.Credentials) Nullable(org.eclipse.che.commons.annotation.Nullable) Consumer(java.util.function.Consumer) Config(io.fabric8.kubernetes.client.Config) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) OpenShiftConfig(io.fabric8.openshift.client.OpenShiftConfig) OkHttpClient(okhttp3.OkHttpClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) ImpersonatorInterceptor(io.fabric8.kubernetes.client.utils.ImpersonatorInterceptor) Utils.isNotNullOrEmpty(io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty) OkHttpClient(okhttp3.OkHttpClient) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) Request(okhttp3.Request) URL(java.net.URL) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 2 with Interceptor

use of io.fabric8.kubernetes.client.http.Interceptor in project kubernetes-client by fabric8io.

the class JdkHttpClientImpl method buildAsync.

public CompletableFuture<WebSocket> buildAsync(JdkWebSocketImpl.BuilderImpl webSocketBuilder, Listener listener) {
    JdkWebSocketImpl.BuilderImpl copy = webSocketBuilder.copy();
    for (Interceptor interceptor : builder.interceptors.values()) {
        interceptor.before(copy, new JdkHttpRequestImpl(null, copy.asRequest()));
    }
    CompletableFuture<WebSocket> result = new CompletableFuture<>();
    CompletableFuture<WebSocketResponse> cf = internalBuildAsync(copy, listener);
    for (Interceptor interceptor : builder.interceptors.values()) {
        cf = cf.thenCompose(response -> {
            if (response.wshse != null && response.wshse.getResponse() != null && interceptor.afterFailure(copy, new JdkHttpResponseImpl<>(response.wshse.getResponse()))) {
                return this.internalBuildAsync(copy, listener);
            }
            return CompletableFuture.completedFuture(response);
        });
    }
    // map back to the expected convention with the future completed by the response exception
    cf.whenComplete((r, t) -> {
        if (t != null) {
            result.completeExceptionally(t);
        } else if (r != null) {
            if (r.wshse != null) {
                result.completeExceptionally(new io.fabric8.kubernetes.client.http.WebSocketHandshakeException(new JdkHttpResponseImpl<>(r.wshse.getResponse())).initCause(r.wshse));
            } else {
                result.complete(r.webSocket);
            }
        } else {
            // shouldn't happen
            result.complete(null);
        }
    });
    return result;
}
Also used : BodyHandlers(java.net.http.HttpResponse.BodyHandlers) Listener(io.fabric8.kubernetes.client.http.WebSocket.Listener) HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) BodySubscribers(java.net.http.HttpResponse.BodySubscribers) BodyHandler(java.net.http.HttpResponse.BodyHandler) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) InterruptedIOException(java.io.InterruptedIOException) StandardCharsets(java.nio.charset.StandardCharsets) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Interceptor(io.fabric8.kubernetes.client.http.Interceptor) WebSocketHandshakeException(java.net.http.WebSocketHandshakeException) Optional(java.util.Optional) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) URI(java.net.URI) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) InputStream(java.io.InputStream) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) CompletableFuture(java.util.concurrent.CompletableFuture) Interceptor(io.fabric8.kubernetes.client.http.Interceptor)

Example 3 with Interceptor

use of io.fabric8.kubernetes.client.http.Interceptor in project kubernetes-client by fabric8io.

the class JdkHttpClientImpl method sendAsync.

@Override
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, Class<T> type) {
    JdkHttpRequestImpl jdkRequest = (JdkHttpRequestImpl) request;
    JdkHttpRequestImpl.BuilderImpl builderImpl = jdkRequest.newBuilder();
    for (Interceptor interceptor : builder.interceptors.values()) {
        interceptor.before(builderImpl, jdkRequest);
        jdkRequest = builderImpl.build();
    }
    BodyHandler<T> bodyHandler;
    if (type == null) {
        bodyHandler = (BodyHandler<T>) BodyHandlers.discarding();
    } else if (type == InputStream.class) {
        bodyHandler = (BodyHandler<T>) BodyHandlers.ofInputStream();
    } else if (type == String.class) {
        bodyHandler = (BodyHandler<T>) BodyHandlers.ofString();
    } else {
        bodyHandler = responseInfo -> {
            BodySubscriber<InputStream> upstream = BodyHandlers.ofInputStream().apply(responseInfo);
            BodySubscriber<Reader> downstream = BodySubscribers.mapping(upstream, (InputStream is) -> new InputStreamReader(is, StandardCharsets.UTF_8));
            return (BodySubscriber<T>) downstream;
        };
    }
    CompletableFuture<java.net.http.HttpResponse<T>> cf = this.httpClient.sendAsync(builderImpl.build().request, bodyHandler);
    for (Interceptor interceptor : builder.interceptors.values()) {
        cf = cf.thenCompose(response -> {
            if (response != null && !HttpResponse.isSuccessful(response.statusCode()) && interceptor.afterFailure(builderImpl, new JdkHttpResponseImpl<>(response))) {
                return this.httpClient.sendAsync(builderImpl.build().request, bodyHandler);
            }
            return CompletableFuture.completedFuture(response);
        });
    }
    return cf.thenApply(JdkHttpResponseImpl::new);
}
Also used : BodyHandlers(java.net.http.HttpResponse.BodyHandlers) Listener(io.fabric8.kubernetes.client.http.WebSocket.Listener) HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) BodySubscribers(java.net.http.HttpResponse.BodySubscribers) BodyHandler(java.net.http.HttpResponse.BodyHandler) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) InterruptedIOException(java.io.InterruptedIOException) StandardCharsets(java.nio.charset.StandardCharsets) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Interceptor(io.fabric8.kubernetes.client.http.Interceptor) WebSocketHandshakeException(java.net.http.WebSocketHandshakeException) Optional(java.util.Optional) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) URI(java.net.URI) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) InputStream(java.io.InputStream) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) BodyHandler(java.net.http.HttpResponse.BodyHandler) Interceptor(io.fabric8.kubernetes.client.http.Interceptor)

Example 4 with Interceptor

use of io.fabric8.kubernetes.client.http.Interceptor in project kubernetes-client by fabric8io.

the class HttpClientUtils method createApplicableInterceptors.

public static Map<String, io.fabric8.kubernetes.client.http.Interceptor> createApplicableInterceptors(Config config, HttpClient.Factory factory) {
    Map<String, io.fabric8.kubernetes.client.http.Interceptor> interceptors = new LinkedHashMap<>();
    // Header Interceptor
    interceptors.put(HEADER_INTERCEPTOR, new Interceptor() {

        @Override
        public void before(BasicBuilder builder, HttpHeaders headers) {
            if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) {
                builder.header("Authorization", basicCredentials(config.getUsername(), config.getPassword()));
            } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
                builder.header("Authorization", "Bearer " + config.getOauthToken());
            }
            if (config.getCustomHeaders() != null && !config.getCustomHeaders().isEmpty()) {
                for (Map.Entry<String, String> entry : config.getCustomHeaders().entrySet()) {
                    builder.header(entry.getKey(), entry.getValue());
                }
            }
            if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
                builder.setHeader("User-Agent", config.getUserAgent());
            }
        }
    });
    // Impersonator Interceptor
    interceptors.put(ImpersonatorInterceptor.NAME, new ImpersonatorInterceptor(config));
    // Token Refresh Interceptor
    interceptors.put(TokenRefreshInterceptor.NAME, new TokenRefreshInterceptor(config, factory));
    // Backwards Compatibility Interceptor
    String shouldDisableBackwardsCompatibilityInterceptor = Utils.getSystemPropertyOrEnvVar(KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE, "false");
    if (!Boolean.parseBoolean(shouldDisableBackwardsCompatibilityInterceptor)) {
        interceptors.put(BackwardsCompatibilityInterceptor.NAME, new BackwardsCompatibilityInterceptor());
    }
    return interceptors;
}
Also used : HttpHeaders(io.fabric8.kubernetes.client.http.HttpHeaders) LinkedHashMap(java.util.LinkedHashMap) BasicBuilder(io.fabric8.kubernetes.client.http.BasicBuilder) Interceptor(io.fabric8.kubernetes.client.http.Interceptor)

Example 5 with Interceptor

use of io.fabric8.kubernetes.client.http.Interceptor in project kubernetes-client by fabric8io.

the class HttpClientUtilsTest method testCreateApplicableInterceptors.

@Test
void testCreateApplicableInterceptors() {
    // Given
    Config config = new ConfigBuilder().build();
    // When
    Collection<Interceptor> interceptorList = HttpClientUtils.createApplicableInterceptors(config, null).values();
    // Then
    assertThat(interceptorList).isNotNull().hasSize(4).hasAtLeastOneElementOfType(BackwardsCompatibilityInterceptor.class).hasAtLeastOneElementOfType(ImpersonatorInterceptor.class).hasAtLeastOneElementOfType(TokenRefreshInterceptor.class);
}
Also used : Config(io.fabric8.kubernetes.client.Config) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) Interceptor(io.fabric8.kubernetes.client.http.Interceptor) Test(org.junit.jupiter.api.Test)

Aggregations

Config (io.fabric8.kubernetes.client.Config)11 ConfigBuilder (io.fabric8.kubernetes.client.ConfigBuilder)9 File (java.io.File)9 Interceptor (okhttp3.Interceptor)9 Interceptor (io.fabric8.kubernetes.client.http.Interceptor)7 Test (org.junit.Test)7 Test (org.junit.jupiter.api.Test)6 HttpRequest (io.fabric8.kubernetes.client.http.HttpRequest)5 BasicBuilder (io.fabric8.kubernetes.client.http.BasicBuilder)3 HttpClient (io.fabric8.kubernetes.client.http.HttpClient)3 HttpResponse (io.fabric8.kubernetes.client.http.HttpResponse)3 ImpersonatorInterceptor (io.fabric8.kubernetes.client.utils.ImpersonatorInterceptor)3 Strings.isNullOrEmpty (com.google.common.base.Strings.isNullOrEmpty)2 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)2 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)2 OAuthTokenProvider (io.fabric8.kubernetes.client.OAuthTokenProvider)2 HttpHeaders (io.fabric8.kubernetes.client.http.HttpHeaders)2 WebSocket (io.fabric8.kubernetes.client.http.WebSocket)2 Listener (io.fabric8.kubernetes.client.http.WebSocket.Listener)2 URLUtils (io.fabric8.kubernetes.client.utils.URLUtils)2