Search in sources :

Example 26 with HttpClient

use of io.fabric8.kubernetes.client.http.HttpClient in project strimzi by strimzi.

the class Main method isOnOpenShift.

static Future<Boolean> isOnOpenShift(Vertx vertx, KubernetesClient client) {
    URL kubernetesApi = client.getMasterUrl();
    Future<Boolean> fut = Future.future();
    HttpClientOptions httpClientOptions = new HttpClientOptions();
    httpClientOptions.setDefaultHost(kubernetesApi.getHost());
    if (kubernetesApi.getPort() == -1) {
        httpClientOptions.setDefaultPort(kubernetesApi.getDefaultPort());
    } else {
        httpClientOptions.setDefaultPort(kubernetesApi.getPort());
    }
    if (kubernetesApi.getProtocol().equals("https")) {
        httpClientOptions.setSsl(true);
        httpClientOptions.setTrustAll(true);
    }
    HttpClient httpClient = vertx.createHttpClient(httpClientOptions);
    httpClient.getNow("/oapi", res -> {
        if (res.statusCode() == HttpResponseStatus.OK.code()) {
            log.debug("{} returned {}. We are on OpenShift.", res.request().absoluteURI(), res.statusCode());
            // We should be on OpenShift based on the /oapi result. We can now safely try isAdaptable() to be 100% sure.
            Boolean isOpenShift = Boolean.TRUE.equals(client.isAdaptable(OpenShiftClient.class));
            fut.complete(isOpenShift);
        } else {
            log.debug("{} returned {}. We are not on OpenShift.", res.request().absoluteURI(), res.statusCode());
            fut.complete(Boolean.FALSE);
        }
    });
    return fut;
}
Also used : HttpClient(io.vertx.core.http.HttpClient) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) URL(java.net.URL) HttpClientOptions(io.vertx.core.http.HttpClientOptions)

Example 27 with HttpClient

use of io.fabric8.kubernetes.client.http.HttpClient in project vertx-openshift-it by cescoffier.

the class MapsIT method testClusterWideUpdate.

@Test
public void testClusterWideUpdate() throws Exception {
    HttpClient httpClient = vertx.createHttpClient();
    int loops = 30;
    CountDownLatch latch = new CountDownLatch(loops);
    for (int i = 0; i < loops; i++) {
        String key = getKey(i);
        String value = getValue(i);
        URL url = Kube.urlForRoute(client.routes().withName(APPLICATION_NAME).get(), "/maps/" + testName.getMethodName() + "/" + key);
        httpClient.putAbs(url.toString()).handler(resp -> latch.countDown()).exceptionHandler(t -> {
            t.printStackTrace();
            latch.countDown();
        }).end(value);
    }
    latch.await(1, TimeUnit.MINUTES);
    for (int i = 0; i < loops; i++) {
        String key = getKey(i);
        String value = getValue(i);
        URL url = Kube.urlForRoute(client.routes().withName(APPLICATION_NAME).get(), "/maps/" + testName.getMethodName() + "/" + key);
        get(url).then().assertThat().statusCode(200).body(equalTo(value));
    }
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) BeforeClass(org.junit.BeforeClass) URL(java.net.URL) OC(io.vertx.it.openshift.utils.OC) Route(io.fabric8.openshift.api.model.Route) OpenShiftHelper(io.vertx.it.openshift.utils.OpenShiftHelper) AbstractTestClass(io.vertx.it.openshift.utils.AbstractTestClass) Ensure(io.vertx.it.openshift.utils.Ensure) TestName(org.junit.rules.TestName) After(org.junit.After) Assertions(org.assertj.core.api.Assertions) Service(io.fabric8.kubernetes.api.model.Service) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) Kube(io.vertx.it.openshift.utils.Kube) Test(org.junit.Test) IOException(java.io.IOException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) TreeMap(java.util.TreeMap) RestAssured(io.restassured.RestAssured) Awaitility(org.awaitility.Awaitility) SortedMap(java.util.SortedMap) HttpClient(io.vertx.core.http.HttpClient) HttpClient(io.vertx.core.http.HttpClient) CountDownLatch(java.util.concurrent.CountDownLatch) URL(java.net.URL) Test(org.junit.Test)

Example 28 with HttpClient

use of io.fabric8.kubernetes.client.http.HttpClient in project vertx-openshift-it by cescoffier.

the class WebSessionIT method testClusteredWebSession.

@Test
public void testClusteredWebSession() throws Exception {
    HttpClient httpClient = vertx.createHttpClient();
    AtomicReference<Map.Entry<String, String>> cookie = new AtomicReference<>();
    int loops = 30;
    for (int i = 0; i < loops; i++) {
        String key = getKey(i);
        String value = getValue(i);
        URL url = Kube.urlForRoute(client.routes().withName(APPLICATION_NAME).get(), "/web-session/" + key);
        CountDownLatch latch = new CountDownLatch(1);
        HttpClientRequest request = httpClient.putAbs(url.toString());
        Optional.ofNullable(cookie.get()).ifPresent(c -> request.headers().add("cookie", c.getKey() + "=" + c.getValue()));
        request.handler(resp -> {
            resp.cookies().stream().map(c -> c.split("=", 2)).map(split -> new SimpleImmutableEntry<>(split[0], split[1].split(";")[0])).filter(entry -> "vertx-web.session".equals(entry.getKey())).forEach(cookie::set);
            latch.countDown();
        }).exceptionHandler(t -> {
            t.printStackTrace();
            latch.countDown();
        }).end(value);
        latch.await(1, TimeUnit.MINUTES);
        // Give some time to the replication operation
        TimeUnit.SECONDS.sleep(1);
    }
    scaleTo(2);
    // Give some time to the rebalancing process
    TimeUnit.SECONDS.sleep(10);
    assertNotNull("No session cookie", cookie.get());
    for (int i = 0; i < loops; i++) {
        String key = getKey(i);
        String value = getValue(i);
        URL url = Kube.urlForRoute(client.routes().withName(APPLICATION_NAME).get(), "/web-session/" + key);
        given().cookie(cookie.get().getKey(), cookie.get().getValue()).when().get(url).then().assertThat().statusCode(200).body(equalTo(value));
    }
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) BeforeClass(org.junit.BeforeClass) URL(java.net.URL) OC(io.vertx.it.openshift.utils.OC) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Route(io.fabric8.openshift.api.model.Route) OpenShiftHelper(io.vertx.it.openshift.utils.OpenShiftHelper) AbstractTestClass(io.vertx.it.openshift.utils.AbstractTestClass) Ensure(io.vertx.it.openshift.utils.Ensure) After(org.junit.After) Map(java.util.Map) Assertions(org.assertj.core.api.Assertions) Service(io.fabric8.kubernetes.api.model.Service) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) Kube(io.vertx.it.openshift.utils.Kube) Test(org.junit.Test) IOException(java.io.IOException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) TreeMap(java.util.TreeMap) Optional(java.util.Optional) RestAssured.given(io.restassured.RestAssured.given) RestAssured(io.restassured.RestAssured) Assert(org.junit.Assert) Awaitility(org.awaitility.Awaitility) SortedMap(java.util.SortedMap) HttpClient(io.vertx.core.http.HttpClient) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URL(java.net.URL) Test(org.junit.Test)

Example 29 with HttpClient

use of io.fabric8.kubernetes.client.http.HttpClient in project strimzi by strimzi.

the class Kubernetes method defaultClient.

@Override
public KubeClient defaultClient() {
    HttpClient httpClient = HttpClientUtils.createHttpClient(CONFIG);
    httpClient = httpClient.newBuilder().preferHttp11().connectTimeout(60L, TimeUnit.SECONDS).writeTimeout(60L, TimeUnit.SECONDS).readTimeout(60L, TimeUnit.SECONDS).build();
    return new KubeClient(new DefaultKubernetesClient(httpClient, CONFIG), "default");
}
Also used : KubeClient(io.strimzi.test.k8s.KubeClient) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient)

Example 30 with HttpClient

use of io.fabric8.kubernetes.client.http.HttpClient in project strimzi-kafka-operator by strimzi.

the class CruiseControlApiImpl method getUserTaskStatus.

@Override
@SuppressWarnings("deprecation")
public Future<CruiseControlResponse> getUserTaskStatus(String host, int port, String userTaskId) {
    PathBuilder pathBuilder = new PathBuilder(CruiseControlEndpoints.USER_TASKS).withParameter(CruiseControlParameters.JSON, "true").withParameter(CruiseControlParameters.FETCH_COMPLETE, "true");
    if (userTaskId != null) {
        pathBuilder.withParameter(CruiseControlParameters.USER_TASK_IDS, userTaskId);
    }
    String path = pathBuilder.build();
    HttpClientOptions options = getHttpClientOptions();
    return HttpClientUtils.withHttpClient(vertx, options, (httpClient, result) -> {
        httpClient.request(HttpMethod.GET, port, host, path, request -> {
            if (request.succeeded()) {
                if (authHttpHeader != null) {
                    request.result().putHeader(authHttpHeader.getName(), authHttpHeader.getValue());
                }
                request.result().send(response -> {
                    if (response.succeeded()) {
                        if (response.result().statusCode() == 200 || response.result().statusCode() == 201) {
                            String userTaskID = response.result().getHeader(CC_REST_API_USER_ID_HEADER);
                            response.result().bodyHandler(buffer -> {
                                JsonObject json = buffer.toJsonObject();
                                JsonObject jsonUserTask = json.getJsonArray("userTasks").getJsonObject(0);
                                // This should not be an error with a 200 status but we play it safe
                                if (jsonUserTask.containsKey(CC_REST_API_ERROR_KEY)) {
                                    result.fail(new CruiseControlRestException("Error for request: " + host + ":" + port + path + ". Server returned: " + json.getString(CC_REST_API_ERROR_KEY)));
                                }
                                JsonObject statusJson = new JsonObject();
                                String taskStatusStr = jsonUserTask.getString(STATUS_KEY);
                                statusJson.put(STATUS_KEY, taskStatusStr);
                                CruiseControlUserTaskStatus taskStatus = CruiseControlUserTaskStatus.lookup(taskStatusStr);
                                switch(taskStatus) {
                                    case ACTIVE:
                                        // If the status is ACTIVE there will not be a "summary" so we skip pulling the summary key
                                        break;
                                    case IN_EXECUTION:
                                    // We handle these in the same way as COMPLETED tasks so we drop down to that case.
                                    case COMPLETED:
                                        // Completed tasks will have the original rebalance proposal summary in their original response
                                        JsonObject originalResponse = (JsonObject) Json.decodeValue(jsonUserTask.getString(CruiseControlRebalanceKeys.ORIGINAL_RESPONSE.getKey()));
                                        statusJson.put(CruiseControlRebalanceKeys.SUMMARY.getKey(), originalResponse.getJsonObject(CruiseControlRebalanceKeys.SUMMARY.getKey()));
                                        // Extract the load before/after information for the brokers
                                        statusJson.put(CruiseControlRebalanceKeys.LOAD_BEFORE_OPTIMIZATION.getKey(), originalResponse.getJsonObject(CruiseControlRebalanceKeys.LOAD_BEFORE_OPTIMIZATION.getKey()));
                                        statusJson.put(CruiseControlRebalanceKeys.LOAD_AFTER_OPTIMIZATION.getKey(), originalResponse.getJsonObject(CruiseControlRebalanceKeys.LOAD_AFTER_OPTIMIZATION.getKey()));
                                        break;
                                    case COMPLETED_WITH_ERROR:
                                        // Completed with error tasks will have "CompletedWithError" as their original response, which is not Json.
                                        statusJson.put(CruiseControlRebalanceKeys.SUMMARY.getKey(), jsonUserTask.getString(CruiseControlRebalanceKeys.ORIGINAL_RESPONSE.getKey()));
                                        break;
                                    default:
                                        throw new IllegalStateException("Unexpected user task status: " + taskStatus);
                                }
                                result.complete(new CruiseControlResponse(userTaskID, statusJson));
                            });
                        } else if (response.result().statusCode() == 500) {
                            response.result().bodyHandler(buffer -> {
                                JsonObject json = buffer.toJsonObject();
                                String errorString;
                                if (json.containsKey(CC_REST_API_ERROR_KEY)) {
                                    errorString = json.getString(CC_REST_API_ERROR_KEY);
                                } else {
                                    errorString = json.toString();
                                }
                                result.fail(new CruiseControlRestException("Error for request: " + host + ":" + port + path + ". Server returned: " + errorString));
                            });
                        } else {
                            result.fail(new CruiseControlRestException("Unexpected status code " + response.result().statusCode() + " for GET request to " + host + ":" + port + path));
                        }
                    } else {
                        result.fail(response.cause());
                    }
                });
                if (idleTimeout != HTTP_DEFAULT_IDLE_TIMEOUT_SECONDS) {
                    request.result().setTimeout(idleTimeout * 1000);
                }
            } else {
                httpExceptionHandler(result, request.cause());
            }
        });
    });
}
Also used : CruiseControl(io.strimzi.operator.cluster.model.CruiseControl) Json(io.vertx.core.json.Json) Promise(io.vertx.core.Promise) HTTPHeader(io.fabric8.kubernetes.api.model.HTTPHeader) Vertx(io.vertx.core.Vertx) TimeoutException(java.util.concurrent.TimeoutException) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Util(io.strimzi.operator.common.Util) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) Secret(io.fabric8.kubernetes.api.model.Secret) JsonObject(io.vertx.core.json.JsonObject) ConnectException(java.net.ConnectException) HttpClientUtils(io.strimzi.operator.cluster.operator.resource.HttpClientUtils) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) PemTrustOptions(io.vertx.core.net.PemTrustOptions) JsonObject(io.vertx.core.json.JsonObject) HttpClientOptions(io.vertx.core.http.HttpClientOptions)

Aggregations

IOException (java.io.IOException)17 HttpClient (io.fabric8.kubernetes.client.http.HttpClient)16 URL (java.net.URL)10 Pod (io.fabric8.kubernetes.api.model.Pod)8 Test (org.junit.jupiter.api.Test)8 HttpRequest (io.fabric8.kubernetes.client.http.HttpRequest)7 Vertx (io.vertx.core.Vertx)7 File (java.io.File)7 OkHttpClient (okhttp3.OkHttpClient)7 ConfigBuilder (io.fabric8.kubernetes.client.ConfigBuilder)6 HttpClient (io.vertx.core.http.HttpClient)6 TreeMap (java.util.TreeMap)6 Service (io.fabric8.kubernetes.api.model.Service)5 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)5 Resource (io.fabric8.kubernetes.client.dsl.Resource)5 OperationContext (io.fabric8.kubernetes.client.dsl.internal.OperationContext)5 Route (io.fabric8.openshift.api.model.Route)5 RestAssured (io.restassured.RestAssured)5 AbstractTestClass (io.vertx.it.openshift.utils.AbstractTestClass)5 Ensure (io.vertx.it.openshift.utils.Ensure)5