Search in sources :

Example 21 with HttpClient

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

the class LocksIT method testAcquireLock.

@Test
@Ignore("Currently, IPSN locks can be re-acquired on the same VM")
public void testAcquireLock() throws Exception {
    HttpClient httpClient = vertx.createHttpClient();
    URL url = Kube.urlForRoute(client.routes().withName(APPLICATION_NAME).get(), "/locks/" + testName.getMethodName());
    int loops = 30;
    AtomicInteger acquired = new AtomicInteger();
    CountDownLatch latch = new CountDownLatch(loops);
    for (int i = 0; i < loops; i++) {
        httpClient.getAbs(url.toString()).handler(resp -> {
            if (resp.statusCode() == 200) {
                acquired.incrementAndGet();
            }
            latch.countDown();
        }).exceptionHandler(t -> latch.countDown()).end();
    }
    latch.await(1, TimeUnit.MINUTES);
    assertEquals(1, acquired.get());
}
Also used : 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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) 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) Ignore(org.junit.Ignore) TreeMap(java.util.TreeMap) RestAssured(io.restassured.RestAssured) Assert(org.junit.Assert) Awaitility(org.awaitility.Awaitility) SortedMap(java.util.SortedMap) HttpClient(io.vertx.core.http.HttpClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpClient(io.vertx.core.http.HttpClient) CountDownLatch(java.util.concurrent.CountDownLatch) URL(java.net.URL) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 22 with HttpClient

use of io.fabric8.kubernetes.client.http.HttpClient in project strimzi 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)

Example 23 with HttpClient

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

the class KubernetesClientFactory method build.

public KubernetesClient build(final MetricRegistry metrics, final LifecycleEnvironment lifecycle, final HealthCheckRegistry healthChecks, final String appName, @Nullable final Tracing tracing) throws Exception {
    final RequestConfig requestConf = requestConfig != null ? requestConfig.build() : null;
    final Config k8sConfig = config.build(appName, requestConf);
    if (httpClient == null) {
        return new DefaultKubernetesClient(k8sConfig);
    }
    final OkHttpClient okHttpClient = httpClient.build(k8sConfig, metrics, name, requestConf, tracing);
    final KubernetesClient client = new DefaultKubernetesClient(okHttpClient, k8sConfig);
    // manage
    lifecycle.manage(new KubernetesClientManager(client, name));
    // health checks
    final String healthCheckUrl = getHealthCheckUrl(k8sConfig);
    final KubernetesClientHealthCheck healthCheck = new KubernetesClientHealthCheck(okHttpClient, name, healthCheckUrl);
    healthChecks.register(name, healthCheck);
    return client;
}
Also used : RequestConfig(io.fabric8.kubernetes.client.RequestConfig) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) OkHttpClient(okhttp3.OkHttpClient) RequestConfig(io.fabric8.kubernetes.client.RequestConfig) Config(io.fabric8.kubernetes.client.Config) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClientHealthCheck(io.dropwizard.kubernetes.health.KubernetesClientHealthCheck) KubernetesClientManager(io.dropwizard.kubernetes.managed.KubernetesClientManager)

Example 24 with HttpClient

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

the class OkHttpClientFactoryTest method shouldBuildAConfigWithNoRequestConfig.

@Test
public void shouldBuildAConfigWithNoRequestConfig() throws Exception {
    // given
    final File yaml = new File(Resources.getResource("yaml/http/http-client.yaml").toURI());
    final OkHttpClientFactory httpClientFactory = factory.build(yaml);
    final Config config = new ConfigBuilder().build();
    final RequestConfig requestConfig = new RequestConfigBuilder().build();
    // when
    final OkHttpClient httpClient = httpClientFactory.build(config, metrics, "app123", requestConfig, tracing);
    // then
    assertThat(httpClient).isInstanceOf(OkHttpClient.class);
    assertThat(httpClient.interceptors().size()).isEqualTo(2);
    assertThat(httpClient.proxy()).isNotNull();
    assertThat(httpClient.followRedirects()).isFalse();
    assertThat(httpClient.followRedirects()).isFalse();
}
Also used : RequestConfig(io.fabric8.kubernetes.client.RequestConfig) OkHttpClient(okhttp3.OkHttpClient) RequestConfig(io.fabric8.kubernetes.client.RequestConfig) Config(io.fabric8.kubernetes.client.Config) RequestConfigBuilder(io.fabric8.kubernetes.client.RequestConfigBuilder) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) RequestConfigBuilder(io.fabric8.kubernetes.client.RequestConfigBuilder) File(java.io.File) Test(org.junit.Test)

Example 25 with HttpClient

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

the class DevOpsConnector method createGerritRepo.

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd, String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {
    // lets add defaults if not env vars
    if (Strings.isNullOrBlank(gerritUser)) {
        gerritUser = "admin";
    }
    if (Strings.isNullOrBlank(gerritPwd)) {
        gerritPwd = "secret";
    }
    log.info("A Gerrit git repo will be created for this name : " + repoName);
    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http", true);
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace + " on Kubernetes address: " + kubernetes.getMasterUrl());
    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpClient httpclientPost = HttpClients.createDefault();
    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;
    HttpGet httpget = new HttpGet(GERRIT_URL);
    System.out.println("Requesting : " + httpget.getURI());
    try {
        // Initial request without credentials returns "HTTP/1.1 401 Unauthorized"
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getStatusLine());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // Get current current "WWW-Authenticate" header from response
            // WWW-Authenticate:Digest realm="My Test Realm", qop="auth",
            // nonce="cdcf6cbe6ee17ae0790ed399935997e8", opaque="ae40d7c8ca6a35af15460d352be5e71c"
            Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
            System.out.println("authHeader = " + authHeader);
            DigestScheme digestScheme = new DigestScheme();
            // Parse realm, nonce sent by server.
            digestScheme.processChallenge(authHeader);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(gerritUser, gerritPwd);
            httpget.addHeader(digestScheme.authenticate(creds, httpget, null));
            HttpPost httpPost = new HttpPost(GERRIT_URL);
            httpPost.addHeader(digestScheme.authenticate(creds, httpPost, null));
            httpPost.addHeader("Content-Type", "application/json");
            CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
            createRepoDTO.setDescription(gerritGitRepoDescription);
            createRepoDTO.setName(repoName);
            createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(createRepoDTO);
            HttpEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclientPost.execute(httpPost, responseHandler);
            System.out.println("responseBody : " + responseBody);
        }
    } catch (MalformedChallengeException e) {
        e.printStackTrace();
    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        System.out.println("Gerrit Server is not responding");
    } catch (HttpResponseException e) {
        System.out.println("Response from Gerrit Server : " + e.getMessage());
        throw new Exception("Repository " + repoName + " already exists !");
    } finally {
        httpclient.close();
        httpclientPost.close();
    }
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponse(org.apache.http.HttpResponse) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) SAXException(org.xml.sax.SAXException) WebApplicationException(javax.ws.rs.WebApplicationException) AuthenticationException(org.apache.http.auth.AuthenticationException) ConnectException(java.net.ConnectException) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) Header(org.apache.http.Header) CreateRepositoryDTO(io.fabric8.gerrit.CreateRepositoryDTO) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConnectException(java.net.ConnectException)

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