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());
}
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());
}
});
});
}
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;
}
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();
}
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();
}
}
Aggregations