Search in sources :

Example 1 with Args

use of org.apache.hc.core5.util.Args in project LinkAgent by shulieTech.

the class AsyncHttpClientv5MethodInterceptor method doBefore.

@Override
public void doBefore(final Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    // HttpHost
    HttpHost httpHost = (HttpHost) args[0];
    if (httpHost == null) {
        return;
    }
    BasicRequestProducer requestBasic = (BasicRequestProducer) args[1];
    final SimpleHttpRequest request;
    try {
        Field field = requestBasic.getClass().getDeclaredField("request");
        field.setAccessible(true);
        request = (SimpleHttpRequest) field.get(requestBasic);
    } catch (Exception e) {
        logger.error("获取request参数错误", e);
        return;
    }
    if (request == null) {
        return;
    }
    String host = httpHost.getHostName();
    int port = httpHost.getPort();
    String path = httpHost.getHostName();
    String reqStr = request.toString();
    String method = StringUtils.upperCase(reqStr.substring(0, reqStr.indexOf(" ")));
    // 判断是否在白名单中
    String url = getService(httpHost.getSchemeName(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] wHeaders = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    if (wHeaders != null && wHeaders.length > 0) {
        config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, wHeaders[0].getValue());
    }
    config.addArgs("url", url);
    config.addArgs("request", request);
    config.addArgs("method", "uri");
    config.addArgs("isInterface", Boolean.FALSE);
    Pradar.startClientInvoke(path, method);
    Pradar.remoteIp(host);
    Pradar.remotePort(port);
    Pradar.middlewareName(HttpClientConstants.HTTP_CLIENT_NAME_5X);
    Header[] headers = request.getHeaders("content-length");
    if (headers != null && headers.length != 0) {
        try {
            Header header = headers[0];
            Pradar.requestSize(Integer.valueOf(header.getValue()));
        } catch (NumberFormatException e) {
        }
    }
    final Map<String, String> context = Pradar.getInvokeContextMap();
    for (Map.Entry<String, String> entry : context.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (request.getHeaders(HeaderMark.DONT_MODIFY_HEADER) == null || request.getHeaders(HeaderMark.DONT_MODIFY_HEADER).length == 0) {
            request.setHeader(key, value);
        }
    }
    // pradar启动提前为的是捕获白名单异常能trace进去的
    try {
        config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

            @Override
            public Object call(Object param) {
                // return future;
                return null;
            }
        });
    } catch (PressureMeasureError e) {
        Pradar.response(e);
        Pradar.endClientInvoke(ResultCode.INVOKE_RESULT_FAILED, HttpClientConstants.PLUGIN_TYPE);
        throw e;
    }
    Pradar.popInvokeContext();
    final Object future = args[args.length - 1];
    if (!(future instanceof FutureCallback) && future != null) {
        return;
    }
    advice.changeParameter(args.length - 1, new FutureCallback() {

        @Override
        public void completed(Object result) {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).completed(result);
            try {
                if (result instanceof SimpleHttpResponse) {
                    afterTrace(request, (SimpleHttpResponse) result);
                } else {
                    afterTrace(request, null);
                }
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }

        @Override
        public void failed(Exception ex) {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).failed(ex);
            try {
                exceptionTrace(request, ex);
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }

        @Override
        public void cancelled() {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).cancelled();
            try {
                exceptionTrace(request, null);
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }
    });
}
Also used : BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Field(java.lang.reflect.Field) Header(org.apache.hc.core5.http.Header) HttpHost(org.apache.hc.core5.http.HttpHost) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) Map(java.util.Map) FutureCallback(org.apache.hc.core5.concurrent.FutureCallback)

Example 2 with Args

use of org.apache.hc.core5.util.Args in project LinkAgent by shulieTech.

the class HttpClientv5MethodInterceptor method afterTrace.

@Override
public SpanRecord afterTrace(Advice advice) {
    Object[] args = advice.getParameterArray();
    HttpRequest request = (HttpRequest) args[1];
    SpanRecord record = new SpanRecord();
    if (advice.getReturnObj() instanceof ClassicHttpResponse) {
        ClassicHttpResponse response = (ClassicHttpResponse) advice.getReturnObj();
        try {
            record.setResponseSize(response == null ? 0 : response.getEntity().getContentLength());
        } catch (Throwable e) {
            record.setResponseSize(0);
        }
        int code = response.getCode();
        record.setResultCode(code + "");
    }
    try {
        record.setRequest(getParameters(request));
    } catch (Throwable e) {
    }
    return record;
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) SpanRecord(com.pamirs.pradar.interceptor.SpanRecord) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) JSONObject(com.alibaba.fastjson.JSONObject)

Example 3 with Args

use of org.apache.hc.core5.util.Args in project LinkAgent by shulieTech.

the class HttpClientv5MethodInterceptor method getContextTransfer.

@Override
protected ContextTransfer getContextTransfer(Advice advice) {
    Object[] args = advice.getParameterArray();
    HttpHost httpHost = (HttpHost) args[0];
    final HttpRequest request = (HttpRequest) args[1];
    if (httpHost == null) {
        return null;
    }
    return new ContextTransfer() {

        @Override
        public void transfer(String key, String value) {
            if (request.getHeaders(HeaderMark.DONT_MODIFY_HEADER) == null || request.getHeaders(HeaderMark.DONT_MODIFY_HEADER).length == 0) {
                request.setHeader(key, value);
            }
        }
    };
}
Also used : ClassicHttpRequest(org.apache.hc.core5.http.ClassicHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) ContextTransfer(com.pamirs.pradar.interceptor.ContextTransfer) HttpHost(org.apache.hc.core5.http.HttpHost) JSONObject(com.alibaba.fastjson.JSONObject)

Example 4 with Args

use of org.apache.hc.core5.util.Args in project LinkAgent by shulieTech.

the class HttpClientv5MethodInterceptor1 method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    // ClassicHttpRequest
    final ClassicHttpRequest request = (ClassicHttpRequest) args[0];
    if (request == null) {
        return;
    }
    URI uri = null;
    try {
        uri = request.getUri();
    } catch (URISyntaxException e) {
        logger.error("获取不到url", e);
    }
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    // 判断是否在白名单中
    String url = getService(uri.getScheme(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] headers = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, headers[0].getValue());
    config.addArgs("url", url);
    config.addArgs("request", request);
    config.addArgs("method", "uri");
    config.addArgs("isInterface", Boolean.FALSE);
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

        @Override
        public Object call(Object param) {
            try {
                HttpEntity entity = null;
                if (param instanceof String) {
                    entity = new StringEntity(String.valueOf(param));
                } else {
                    entity = new ByteArrayEntity(JSONObject.toJSONBytes(param), ContentType.create(request.getEntity().getContentType()));
                }
                BasicClassicHttpResponse response = new BasicClassicHttpResponse(200);
                response.setEntity(entity);
                if (HttpClientConstants.clazz == null) {
                    HttpClientConstants.clazz = Class.forName("org.apache.hc.client5.http.impl.classic.CloseableHttpResponse");
                }
                return Reflect.on(HttpClientConstants.clazz).create(response, null).get();
            } catch (Exception e) {
            }
            return null;
        }
    });
}
Also used : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) IOException(java.io.IOException) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) ByteArrayEntity(org.apache.hc.core5.http.io.entity.ByteArrayEntity) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 5 with Args

use of org.apache.hc.core5.util.Args in project LinkAgent by shulieTech.

the class HttpClientv5MethodInterceptor1 method afterTrace.

@Override
public SpanRecord afterTrace(Advice advice) {
    Object[] args = advice.getParameterArray();
    HttpRequest request = (HttpRequest) args[0];
    SpanRecord record = new SpanRecord();
    if (advice.getReturnObj() instanceof ClassicHttpResponse) {
        ClassicHttpResponse response = (ClassicHttpResponse) advice.getReturnObj();
        try {
            record.setResponseSize(response == null ? 0 : response.getEntity().getContentLength());
        } catch (Throwable e) {
            record.setResponseSize(0);
        }
        int code = response.getCode();
        record.setResultCode(code + "");
    } else {
        record.setResponse(advice.getReturnObj());
    }
    try {
        if (request.getHeaders(HeaderMark.DONT_READ_INPUT) == null || request.getHeaders(HeaderMark.DONT_READ_INPUT).length == 0) {
            record.setRequest(getParameters(request));
        }
    } catch (Throwable e) {
    }
    return record;
}
Also used : SpanRecord(com.pamirs.pradar.interceptor.SpanRecord) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) JSONObject(com.alibaba.fastjson.JSONObject)

Aggregations

HttpHost (org.apache.hc.core5.http.HttpHost)32 HttpRequest (org.apache.hc.core5.http.HttpRequest)25 HttpResponse (org.apache.hc.core5.http.HttpResponse)24 StatusLine (org.apache.hc.core5.http.message.StatusLine)22 IOReactorConfig (org.apache.hc.core5.reactor.IOReactorConfig)22 IOException (java.io.IOException)21 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)19 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)19 HttpConnection (org.apache.hc.core5.http.HttpConnection)19 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)17 Header (org.apache.hc.core5.http.Header)17 HttpException (org.apache.hc.core5.http.HttpException)16 CountDownLatch (java.util.concurrent.CountDownLatch)13 SimpleHttpRequest (org.apache.hc.client5.http.async.methods.SimpleHttpRequest)13 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)12 ClassicHttpRequest (org.apache.hc.core5.http.ClassicHttpRequest)12 StringAsyncEntityConsumer (org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer)12 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)12 EntityDetails (org.apache.hc.core5.http.EntityDetails)11 Http1StreamListener (org.apache.hc.core5.http.impl.Http1StreamListener)11