Search in sources :

Example 1 with HttpClientRequest

use of reactor.ipc.netty.http.client.HttpClientRequest in project spring-cloud-sleuth by spring-cloud.

the class TraceUserInfoRestTemplateCustomizer method wrapHttpClientRequestSending.

Mono<HttpClientResponse> wrapHttpClientRequestSending(ProceedingJoinPoint pjp, HttpMethod method, String url, Function<? super HttpClientRequest, ? extends Publisher<Void>> handler) throws Throwable {
    // add headers and set CS
    final Span currentSpan = this.tracer.currentSpan();
    final AtomicReference<Span> span = new AtomicReference<>();
    Function<HttpClientRequest, Publisher<Void>> combinedFunction = req -> {
        try (Tracer.SpanInScope spanInScope = this.tracer.withSpanInScope(currentSpan)) {
            io.netty.handler.codec.http.HttpHeaders originalHeaders = req.requestHeaders().copy();
            io.netty.handler.codec.http.HttpHeaders tracedHeaders = req.requestHeaders();
            span.set(this.handler.handleSend(this.injector, tracedHeaders, req));
            io.netty.handler.codec.http.HttpHeaders addedHeaders = tracedHeaders.copy();
            originalHeaders.forEach(header -> addedHeaders.remove(header.getKey()));
            try (Tracer.SpanInScope clientInScope = this.tracer.withSpanInScope(span.get())) {
                if (log.isDebugEnabled()) {
                    log.debug("Created a new client span for Netty client");
                }
                return handle(handler, new TracedHttpClientRequest(req, addedHeaders));
            }
        }
    };
    // run
    Mono<HttpClientResponse> responseMono = (Mono<HttpClientResponse>) pjp.proceed(new Object[] { method, url, combinedFunction });
    // get response
    return responseMono.doOnSuccessOrError((httpClientResponse, throwable) -> {
        try (Tracer.SpanInScope ws = this.tracer.withSpanInScope(span.get())) {
            // status codes and CR
            this.handler.handleReceive(httpClientResponse, throwable, span.get());
            if (log.isDebugEnabled()) {
                log.debug("Setting client sent spans");
            }
        }
    });
}
Also used : HttpHeaders(io.netty.handler.codec.http.HttpHeaders) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) HttpRequest(org.springframework.http.HttpRequest) Span(brave.Span) Autowired(org.springframework.beans.factory.annotation.Autowired) WebClient(org.springframework.web.reactive.function.client.WebClient) NettyOutbound(reactor.ipc.netty.NettyOutbound) UserInfoRestTemplateCustomizer(org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoRestTemplateCustomizer) HttpClientConfiguration(org.springframework.cloud.commons.httpclient.HttpClientConfiguration) Aspect(org.aspectj.lang.annotation.Aspect) Map(java.util.Map) Path(java.nio.file.Path) RestTemplate(org.springframework.web.client.RestTemplate) HttpTracing(brave.http.HttpTracing) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Tracer(brave.Tracer) Set(java.util.Set) Pointcut(org.aspectj.lang.annotation.Pointcut) Cookie(io.netty.handler.codec.http.cookie.Cookie) TraceContext(brave.propagation.TraceContext) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse) Around(org.aspectj.lang.annotation.Around) BeanPostProcessor(org.springframework.beans.factory.config.BeanPostProcessor) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) ClientHttpRequestInterceptor(org.springframework.http.client.ClientHttpRequestInterceptor) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) TraceWebServletAutoConfiguration(org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration) HttpClientHandler(brave.http.HttpClientHandler) LogFactory(org.apache.commons.logging.LogFactory) ListableBeanFactory(org.springframework.beans.factory.ListableBeanFactory) HttpVersion(io.netty.handler.codec.http.HttpVersion) ConditionalOnClass(org.springframework.boot.autoconfigure.condition.ConditionalOnClass) RestTemplateCustomizer(org.springframework.boot.web.client.RestTemplateCustomizer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) ArrayList(java.util.ArrayList) AutoConfigureAfter(org.springframework.boot.autoconfigure.AutoConfigureAfter) Charset(java.nio.charset.Charset) ByteBuf(io.netty.buffer.ByteBuf) NettyPipeline(reactor.ipc.netty.NettyPipeline) HttpClient(reactor.ipc.netty.http.client.HttpClient) Propagation(brave.propagation.Propagation) WebsocketOutbound(reactor.ipc.netty.http.websocket.WebsocketOutbound) Subscriber(org.reactivestreams.Subscriber) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) ClientHttpRequestExecution(org.springframework.http.client.ClientHttpRequestExecution) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) Order(org.springframework.core.annotation.Order) FileChunkedStrategy(reactor.ipc.netty.channel.data.FileChunkedStrategy) Publisher(org.reactivestreams.Publisher) TracingClientHttpRequestInterceptor(brave.spring.web.TracingClientHttpRequestInterceptor) HttpMethod(io.netty.handler.codec.http.HttpMethod) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) Mono(reactor.core.publisher.Mono) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) TracingHttpAsyncClientBuilder(brave.httpasyncclient.TracingHttpAsyncClientBuilder) BeanFactory(org.springframework.beans.factory.BeanFactory) NettyContext(reactor.ipc.netty.NettyContext) HttpClientRequest(reactor.ipc.netty.http.client.HttpClientRequest) TracingHttpClientBuilder(brave.httpclient.TracingHttpClientBuilder) Log(org.apache.commons.logging.Log) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Bean(org.springframework.context.annotation.Bean) AutoConfigureBefore(org.springframework.boot.autoconfigure.AutoConfigureBefore) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) Tracer(brave.Tracer) Mono(reactor.core.publisher.Mono) AtomicReference(java.util.concurrent.atomic.AtomicReference) Publisher(org.reactivestreams.Publisher) Span(brave.Span) HttpClientRequest(reactor.ipc.netty.http.client.HttpClientRequest) HttpClientResponse(reactor.ipc.netty.http.client.HttpClientResponse)

Example 2 with HttpClientRequest

use of reactor.ipc.netty.http.client.HttpClientRequest in project spring-cloud-gateway by spring-cloud.

the class NettyRoutingFilter method filter.

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
    String scheme = requestUrl.getScheme();
    if (isAlreadyRouted(exchange) || (!"http".equals(scheme) && !"https".equals(scheme))) {
        return chain.filter(exchange);
    }
    setAlreadyRouted(exchange);
    ServerHttpRequest request = exchange.getRequest();
    final HttpMethod method = HttpMethod.valueOf(request.getMethod().toString());
    final String url = requestUrl.toString();
    HttpHeaders filtered = filterRequest(this.headersFilters.getIfAvailable(), exchange);
    final DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    filtered.forEach(httpHeaders::set);
    String transferEncoding = request.getHeaders().getFirst(HttpHeaders.TRANSFER_ENCODING);
    boolean chunkedTransfer = "chunked".equalsIgnoreCase(transferEncoding);
    boolean preserveHost = exchange.getAttributeOrDefault(PRESERVE_HOST_HEADER_ATTRIBUTE, false);
    return this.httpClient.request(method, url, req -> {
        final HttpClientRequest proxyRequest = req.options(NettyPipeline.SendOptions::flushOnEach).headers(httpHeaders).chunkedTransfer(chunkedTransfer).failOnServerError(false).failOnClientError(false);
        if (preserveHost) {
            String host = request.getHeaders().getFirst(HttpHeaders.HOST);
            proxyRequest.header(HttpHeaders.HOST, host);
        }
        return // I shouldn't need this
        proxyRequest.sendHeaders().send(request.getBody().map(dataBuffer -> ((NettyDataBuffer) dataBuffer).getNativeBuffer()));
    }).doOnNext(res -> {
        ServerHttpResponse response = exchange.getResponse();
        // put headers and status so filters can modify the response
        HttpHeaders headers = new HttpHeaders();
        res.responseHeaders().forEach(entry -> headers.add(entry.getKey(), entry.getValue()));
        HttpHeaders filteredResponseHeaders = HttpHeadersFilter.filter(this.headersFilters.getIfAvailable(), headers, exchange, Type.RESPONSE);
        response.getHeaders().putAll(filteredResponseHeaders);
        response.setStatusCode(HttpStatus.valueOf(res.status().code()));
        // Defer committing the response until all route filters have run
        // Put client response as ServerWebExchange attribute and write response later NettyWriteResponseFilter
        exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);
    }).then(chain.filter(exchange));
}
Also used : HttpHeadersFilter.filterRequest(org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter.filterRequest) CLIENT_RESPONSE_ATTR(org.springframework.cloud.gateway.support.ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR) Ordered(org.springframework.core.Ordered) PRESERVE_HOST_HEADER_ATTRIBUTE(org.springframework.cloud.gateway.support.ServerWebExchangeUtils.PRESERVE_HOST_HEADER_ATTRIBUTE) ServerWebExchangeUtils.setAlreadyRouted(org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setAlreadyRouted) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HttpHeaders(org.springframework.http.HttpHeaders) Type(org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter.Type) HttpHeadersFilter(org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter) HttpMethod(io.netty.handler.codec.http.HttpMethod) Mono(reactor.core.publisher.Mono) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) ObjectProvider(org.springframework.beans.factory.ObjectProvider) NettyPipeline(reactor.ipc.netty.NettyPipeline) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) GATEWAY_REQUEST_URL_ATTR(org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR) HttpClient(reactor.ipc.netty.http.client.HttpClient) HttpClientRequest(reactor.ipc.netty.http.client.HttpClientRequest) URI(java.net.URI) ServerWebExchangeUtils.isAlreadyRouted(org.springframework.cloud.gateway.support.ServerWebExchangeUtils.isAlreadyRouted) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) NettyDataBuffer(org.springframework.core.io.buffer.NettyDataBuffer) URI(java.net.URI) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HttpClientRequest(reactor.ipc.netty.http.client.HttpClientRequest) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Aggregations

HttpMethod (io.netty.handler.codec.http.HttpMethod)2 List (java.util.List)2 Mono (reactor.core.publisher.Mono)2 NettyPipeline (reactor.ipc.netty.NettyPipeline)2 HttpClient (reactor.ipc.netty.http.client.HttpClient)2 HttpClientRequest (reactor.ipc.netty.http.client.HttpClientRequest)2 Span (brave.Span)1 Tracer (brave.Tracer)1 HttpClientHandler (brave.http.HttpClientHandler)1 HttpTracing (brave.http.HttpTracing)1 TracingHttpAsyncClientBuilder (brave.httpasyncclient.TracingHttpAsyncClientBuilder)1 TracingHttpClientBuilder (brave.httpclient.TracingHttpClientBuilder)1 Propagation (brave.propagation.Propagation)1 TraceContext (brave.propagation.TraceContext)1 TracingClientHttpRequestInterceptor (brave.spring.web.TracingClientHttpRequestInterceptor)1 ByteBuf (io.netty.buffer.ByteBuf)1 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)1 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)1 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)1 HttpVersion (io.netty.handler.codec.http.HttpVersion)1