Search in sources :

Example 71 with HttpClient

use of io.vertx.core.http.HttpClient in project java-chassis by ServiceComb.

the class CommonHttpEdgeDispatcher method onRequest.

protected void onRequest(RoutingContext context) {
    URLMappedConfigurationItem configurationItem = findConfigurationItem(context.request().uri());
    if (configurationItem == null) {
        context.next();
        return;
    }
    String uri = Utils.findActualPath(context.request().uri(), configurationItem.getPrefixSegmentCount());
    Invocation invocation = new Invocation() {

        @Override
        public String getConfigTransportName() {
            return "rest";
        }

        @Override
        public String getMicroserviceName() {
            return configurationItem.getMicroserviceName();
        }
    };
    LoadBalancer loadBalancer = getOrCreateLoadBalancer(invocation, configurationItem.getMicroserviceName(), configurationItem.getVersionRule());
    ServiceCombServer server = loadBalancer.chooseServer(invocation);
    if (server == null) {
        LOG.warn("no available server for service {}", configurationItem.getMicroserviceName());
        serverNotReadyResponse(context);
        return;
    }
    URIEndpointObject endpointObject = new URIEndpointObject(server.getEndpoint().getEndpoint());
    RequestOptions requestOptions = new RequestOptions();
    requestOptions.setHost(endpointObject.getHostOrIp()).setPort(endpointObject.getPort()).setSsl(endpointObject.isSslEnabled()).setMethod(context.request().method()).setURI(uri);
    HttpClient httpClient;
    if (endpointObject.isHttp2Enabled()) {
        httpClient = HttpClients.getClient(Http2TransportHttpClientOptionsSPI.CLIENT_NAME, false).getHttpClient();
    } else {
        httpClient = HttpClients.getClient(HttpTransportHttpClientOptionsSPI.CLIENT_NAME, false).getHttpClient();
    }
    context.request().pause();
    httpClient.request(requestOptions).compose(httpClientRequest -> {
        context.request().headers().forEach((header) -> httpClientRequest.headers().set(header.getKey(), header.getValue()));
        context.request().resume();
        context.request().handler(httpClientRequest::write);
        context.request().endHandler((v) -> httpClientRequest.end());
        return httpClientRequest.response().compose(httpClientResponse -> {
            context.response().setStatusCode(httpClientResponse.statusCode());
            httpClientResponse.headers().forEach((header) -> context.response().headers().set(header.getKey(), header.getValue()));
            httpClientResponse.handler(this.responseHandler(context));
            httpClientResponse.endHandler((v) -> context.response().end());
            return Future.succeededFuture();
        });
    }).onFailure(failure -> {
        LOG.warn("send request to target {}:{} failed, cause {}", endpointObject.getHostOrIp(), endpointObject.getPort(), failure.getMessage());
        serverNotReadyResponse(context);
    });
}
Also used : ServiceCombServer(org.apache.servicecomb.loadbalance.ServiceCombServer) ServerDiscoveryFilter(org.apache.servicecomb.loadbalance.filter.ServerDiscoveryFilter) ServiceCombServer(org.apache.servicecomb.loadbalance.ServiceCombServer) HttpTransportHttpClientOptionsSPI(org.apache.servicecomb.transport.rest.client.HttpTransportHttpClientOptionsSPI) LoggerFactory(org.slf4j.LoggerFactory) Router(io.vertx.ext.web.Router) HashMap(java.util.HashMap) RequestOptions(io.vertx.core.http.RequestOptions) RoutingContext(io.vertx.ext.web.RoutingContext) HttpClients(org.apache.servicecomb.foundation.vertx.client.http.HttpClients) DiscoveryContext(org.apache.servicecomb.registry.discovery.DiscoveryContext) Map(java.util.Map) LoadbalanceHandler(org.apache.servicecomb.loadbalance.LoadbalanceHandler) ConcurrentHashMapEx(org.apache.servicecomb.foundation.common.concurrent.ConcurrentHashMapEx) RuleExt(org.apache.servicecomb.loadbalance.RuleExt) RegistrationManager(org.apache.servicecomb.registry.RegistrationManager) LoadBalancer(org.apache.servicecomb.loadbalance.LoadBalancer) Logger(org.slf4j.Logger) Http2TransportHttpClientOptionsSPI(org.apache.servicecomb.transport.rest.client.Http2TransportHttpClientOptionsSPI) VersionedCache(org.apache.servicecomb.foundation.common.cache.VersionedCache) Future(io.vertx.core.Future) DynamicPropertyFactory(com.netflix.config.DynamicPropertyFactory) Invocation(org.apache.servicecomb.core.Invocation) ConcurrentCompositeConfiguration(com.netflix.config.ConcurrentCompositeConfiguration) Buffer(io.vertx.core.buffer.Buffer) DiscoveryTree(org.apache.servicecomb.registry.discovery.DiscoveryTree) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject) Handler(io.vertx.core.Handler) ExtensionsManager(org.apache.servicecomb.loadbalance.ExtensionsManager) HttpClient(io.vertx.core.http.HttpClient) Invocation(org.apache.servicecomb.core.Invocation) RequestOptions(io.vertx.core.http.RequestOptions) HttpClient(io.vertx.core.http.HttpClient) LoadBalancer(org.apache.servicecomb.loadbalance.LoadBalancer) URIEndpointObject(org.apache.servicecomb.foundation.common.net.URIEndpointObject)

Example 72 with HttpClient

use of io.vertx.core.http.HttpClient in project java-chassis by ServiceComb.

the class HttpClientPoolFactory method createClientPool.

@Override
public HttpClientWithContext createClientPool(Context context) {
    HttpClient httpClient = context.owner().createHttpClient(httpClientOptions);
    httpClient.connectionHandler(connection -> {
        LOGGER.debug("http connection connected, local:{}, remote:{}.", connection.localAddress(), connection.remoteAddress());
        connection.closeHandler(v -> LOGGER.debug("http connection closed, local:{}, remote:{}.", connection.localAddress(), connection.remoteAddress()));
        connection.exceptionHandler(e -> LOGGER.info("http connection exception, local:{}, remote:{}.", connection.localAddress(), connection.remoteAddress(), e));
    });
    return new HttpClientWithContext(httpClient, context);
}
Also used : HttpClient(io.vertx.core.http.HttpClient)

Example 73 with HttpClient

use of io.vertx.core.http.HttpClient in project pinpoint by naver.

the class Vertx4PluginTestStarter method request.

public void request(int port, String host, String uri) {
    final HttpClient client = vertx.createHttpClient();
    client.request(HttpMethod.GET, port, host, uri, new Handler<AsyncResult<HttpClientRequest>>() {

        @Override
        public void handle(AsyncResult<HttpClientRequest> asyncResult) {
            System.out.println("## Result=" + asyncResult.result());
        }
    });
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) AsyncResult(io.vertx.core.AsyncResult)

Example 74 with HttpClient

use of io.vertx.core.http.HttpClient in project gravitee-gateway by gravitee-io.

the class HttpEndpointRuleHandler method handle.

@Override
public void handle(Long timer) {
    HttpEndpoint endpoint = (HttpEndpoint) rule.endpoint();
    logger.debug("Running health-check for endpoint: {} [{}]", endpoint.getName(), endpoint.getTarget());
    // Run request for each step
    for (io.gravitee.definition.model.services.healthcheck.Step step : rule.steps()) {
        try {
            URI hcRequestUri = create(endpoint.getTarget(), step.getRequest());
            // Prepare HTTP client
            HttpClientOptions httpClientOptions = new HttpClientOptions().setMaxPoolSize(1).setKeepAlive(false).setTcpKeepAlive(false);
            if (endpoint.getHttpClientOptions() != null) {
                httpClientOptions.setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000)).setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout()).setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression());
            }
            // Configure HTTP proxy
            HttpProxy proxy = endpoint.getHttpProxy();
            if (proxy != null && proxy.isEnabled()) {
                ProxyOptions proxyOptions = new ProxyOptions().setHost(proxy.getHost()).setPort(proxy.getPort()).setUsername(proxy.getUsername()).setPassword(proxy.getPassword()).setType(ProxyType.valueOf(proxy.getType().name()));
                httpClientOptions.setProxyOptions(proxyOptions);
            }
            // Configure TLS if required
            HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions();
            if (sslOptions != null && sslOptions.isEnabled()) {
                httpClientOptions.setSsl(sslOptions.isEnabled()).setVerifyHost(sslOptions.isHostnameVerifier()).setTrustAll(sslOptions.isTrustAll());
                if (sslOptions.getPem() != null && !sslOptions.getPem().isEmpty()) {
                    httpClientOptions.setPemTrustOptions(new PemTrustOptions().addCertValue(io.vertx.core.buffer.Buffer.buffer(sslOptions.getPem())));
                }
            } else if (HTTPS_SCHEME.equalsIgnoreCase(hcRequestUri.getScheme())) {
                // SSL is not configured but the endpoint scheme is HTTPS so let's enable the SSL on Vert.x HTTP client
                // automatically
                httpClientOptions.setSsl(true).setTrustAll(true);
            }
            HttpClient httpClient = vertx.createHttpClient(httpClientOptions);
            final int port = hcRequestUri.getPort() != -1 ? hcRequestUri.getPort() : (HTTPS_SCHEME.equals(hcRequestUri.getScheme()) ? 443 : 80);
            String relativeUri = (hcRequestUri.getRawQuery() == null) ? hcRequestUri.getRawPath() : hcRequestUri.getRawPath() + '?' + hcRequestUri.getRawQuery();
            // Run health-check
            HttpClientRequest healthRequest = httpClient.request(HttpMethod.valueOf(step.getRequest().getMethod().name().toUpperCase()), port, hcRequestUri.getHost(), relativeUri);
            // Set timeout on request
            if (endpoint.getHttpClientOptions() != null) {
                healthRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());
            }
            // Prepare request
            if (step.getRequest().getHeaders() != null) {
                step.getRequest().getHeaders().forEach(httpHeader -> healthRequest.headers().set(httpHeader.getName(), httpHeader.getValue()));
            }
            final EndpointStatus.Builder healthBuilder = EndpointStatus.forEndpoint(rule.api(), endpoint.getName()).on(System.currentTimeMillis());
            long startTime = System.currentTimeMillis();
            Request request = new Request();
            request.setMethod(step.getRequest().getMethod());
            request.setUri(hcRequestUri.toString());
            healthRequest.handler(response -> response.bodyHandler(buffer -> {
                long endTime = System.currentTimeMillis();
                logger.debug("Health-check endpoint returns a response with a {} status code", response.statusCode());
                String body = buffer.toString();
                EndpointStatus.StepBuilder stepBuilder = validateAssertions(step, new EvaluableHttpResponse(response, body));
                stepBuilder.request(request);
                stepBuilder.responseTime(endTime - startTime);
                Response healthResponse = new Response();
                healthResponse.setStatus(response.statusCode());
                // If validation fail, store request and response data
                if (!stepBuilder.isSuccess()) {
                    request.setBody(step.getRequest().getBody());
                    if (step.getRequest().getHeaders() != null) {
                        HttpHeaders reqHeaders = new HttpHeaders();
                        step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders.put(httpHeader.getName(), Collections.singletonList(httpHeader.getValue())));
                        request.setHeaders(reqHeaders);
                    }
                    // Extract headers
                    HttpHeaders headers = new HttpHeaders();
                    response.headers().names().forEach(headerName -> headers.put(headerName, response.headers().getAll(headerName)));
                    healthResponse.setHeaders(headers);
                    // Store body
                    healthResponse.setBody(body);
                }
                stepBuilder.response(healthResponse);
                // Append step stepBuilder
                healthBuilder.step(stepBuilder.build());
                report(healthBuilder.build());
                // Close client
                httpClient.close();
            }));
            healthRequest.exceptionHandler(event -> {
                long endTime = System.currentTimeMillis();
                EndpointStatus.StepBuilder stepBuilder = EndpointStatus.forStep(step.getName());
                stepBuilder.fail(event.getMessage());
                Response healthResponse = new Response();
                // Extract request information
                request.setBody(step.getRequest().getBody());
                if (step.getRequest().getHeaders() != null) {
                    HttpHeaders reqHeaders = new HttpHeaders();
                    step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders.put(httpHeader.getName(), Collections.singletonList(httpHeader.getValue())));
                    request.setHeaders(reqHeaders);
                }
                if (event instanceof ConnectTimeoutException) {
                    stepBuilder.fail(event.getMessage());
                    healthResponse.setStatus(HttpStatusCode.REQUEST_TIMEOUT_408);
                } else {
                    healthResponse.setStatus(HttpStatusCode.SERVICE_UNAVAILABLE_503);
                }
                Step result = stepBuilder.build();
                result.setResponse(healthResponse);
                result.setRequest(request);
                result.setResponseTime(endTime - startTime);
                // Append step result
                healthBuilder.step(result);
                report(healthBuilder.build());
                try {
                    // Close client
                    httpClient.close();
                } catch (IllegalStateException ise) {
                // Do not take care about exception when closing client
                }
            });
            // Send request
            logger.debug("Execute health-check request: {}", healthRequest);
            if (step.getRequest().getBody() != null && !step.getRequest().getBody().isEmpty()) {
                healthRequest.end(step.getRequest().getBody());
            } else {
                healthRequest.end();
            }
        } catch (Exception ex) {
            logger.error("An unexpected error occurs", ex);
        }
    }
}
Also used : Step(io.gravitee.reporter.api.health.Step) HttpHeaders(io.gravitee.common.http.HttpHeaders) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) EndpointStatus(io.gravitee.reporter.api.health.EndpointStatus) HttpStatusCode(io.gravitee.common.http.HttpStatusCode) EvaluationException(io.gravitee.gateway.services.healthcheck.eval.EvaluationException) HttpClientSslOptions(io.gravitee.definition.model.HttpClientSslOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Response(io.gravitee.reporter.api.common.Response) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) EndpointRule(io.gravitee.gateway.services.healthcheck.EndpointRule) EndpointStatusDecorator(io.gravitee.gateway.services.healthcheck.EndpointStatusDecorator) HttpClientOptions(io.vertx.core.http.HttpClientOptions) URI(java.net.URI) PemTrustOptions(io.vertx.core.net.PemTrustOptions) Request(io.gravitee.reporter.api.common.Request) ProxyOptions(io.vertx.core.net.ProxyOptions) Logger(org.slf4j.Logger) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) Iterator(java.util.Iterator) HttpProxy(io.gravitee.definition.model.HttpProxy) Vertx(io.vertx.core.Vertx) EvaluableHttpResponse(io.gravitee.gateway.services.healthcheck.http.el.EvaluableHttpResponse) ProxyType(io.vertx.core.net.ProxyType) AssertionEvaluation(io.gravitee.gateway.services.healthcheck.eval.assertion.AssertionEvaluation) HttpMethod(io.vertx.core.http.HttpMethod) Pattern(java.util.regex.Pattern) Handler(io.vertx.core.Handler) Collections(java.util.Collections) HttpClient(io.vertx.core.http.HttpClient) HttpHeaders(io.gravitee.common.http.HttpHeaders) ProxyOptions(io.vertx.core.net.ProxyOptions) Step(io.gravitee.reporter.api.health.Step) URI(java.net.URI) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Request(io.gravitee.reporter.api.common.Request) HttpClientSslOptions(io.gravitee.definition.model.HttpClientSslOptions) EvaluableHttpResponse(io.gravitee.gateway.services.healthcheck.http.el.EvaluableHttpResponse) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) PemTrustOptions(io.vertx.core.net.PemTrustOptions) HttpEndpoint(io.gravitee.definition.model.endpoint.HttpEndpoint) URISyntaxException(java.net.URISyntaxException) EvaluationException(io.gravitee.gateway.services.healthcheck.eval.EvaluationException) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException) HttpProxy(io.gravitee.definition.model.HttpProxy) EndpointStatus(io.gravitee.reporter.api.health.EndpointStatus) Response(io.gravitee.reporter.api.common.Response) EvaluableHttpResponse(io.gravitee.gateway.services.healthcheck.http.el.EvaluableHttpResponse) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClient(io.vertx.core.http.HttpClient) ConnectTimeoutException(io.netty.channel.ConnectTimeoutException)

Example 75 with HttpClient

use of io.vertx.core.http.HttpClient in project vert.x by eclipse.

the class ProxyErrorTest method proxyTest.

private void proxyTest(int error, String username, String url, Handler<AsyncResult<HttpClientResponse>> assertResponse) throws Exception {
    startProxy(error, username);
    final HttpClientOptions options = new HttpClientOptions().setSsl(url.startsWith("https")).setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP).setHost("localhost").setPort(proxy.getPort()));
    HttpClient client = vertx.createHttpClient(options);
    client.request(new RequestOptions().setAbsoluteURI(url), ar -> {
        if (ar.succeeded()) {
            HttpClientRequest request = ar.result();
            request.send(assertResponse);
        } else {
            assertResponse.handle(Future.failedFuture(ar.cause()));
        }
    });
    await();
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) RequestOptions(io.vertx.core.http.RequestOptions) HttpClient(io.vertx.core.http.HttpClient) HttpClientOptions(io.vertx.core.http.HttpClientOptions)

Aggregations

HttpClient (io.vertx.core.http.HttpClient)77 Test (org.junit.Test)47 HttpClientRequest (io.vertx.core.http.HttpClientRequest)36 HttpClientOptions (io.vertx.core.http.HttpClientOptions)25 Vertx (io.vertx.core.Vertx)22 HttpMethod (io.vertx.core.http.HttpMethod)22 JsonObject (io.vertx.core.json.JsonObject)22 Handler (io.vertx.core.Handler)18 Buffer (io.vertx.core.buffer.Buffer)18 HttpClientResponse (io.vertx.core.http.HttpClientResponse)16 TimeUnit (java.util.concurrent.TimeUnit)16 HttpServer (io.vertx.core.http.HttpServer)15 Async (io.vertx.ext.unit.Async)15 Before (org.junit.Before)15 File (java.io.File)14 CountDownLatch (java.util.concurrent.CountDownLatch)14 URL (java.net.URL)12 HttpServerOptions (io.vertx.core.http.HttpServerOptions)11 IOException (java.io.IOException)10 List (java.util.List)10