Search in sources :

Example 1 with JsonMockStrategy

use of com.pamirs.pradar.pressurement.mock.JsonMockStrategy in project LinkAgent by shulieTech.

the class FeignMockInterceptor method beforeFirst.

@Override
public void beforeFirst(Advice advice) throws ProcessControlException {
    if (Pradar.isClusterTest()) {
        Object[] parameterArray = advice.getParameterArray();
        Method method = (Method) parameterArray[1];
        String className = method.getDeclaringClass().getName();
        final String methodName = method.getName();
        // todo ClusterTestUtils.rpcClusterTest里面已经做了对象copy,这么写是为了能单模块更新,后面要去掉
        MatchConfig config = copyMatchConfig(ClusterTestUtils.rpcClusterTest(className, methodName));
        config.addArgs("args", advice.getParameterArray());
        config.addArgs("mockLogger", mockLogger);
        config.addArgs("url", className.concat("#").concat(methodName));
        config.addArgs("isInterface", Boolean.TRUE);
        config.addArgs("class", className);
        config.addArgs("method", methodName);
        if (config.getStrategy() instanceof JsonMockStrategy) {
            config.addArgs("advice", advice);
            fixJsonStrategy.processBlock(method.getReturnType(), advice.getClassLoader(), config);
        }
        config.getStrategy().processBlock(method.getReturnType(), advice.getClassLoader(), config);
    }
}
Also used : JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) Method(java.lang.reflect.Method)

Example 2 with JsonMockStrategy

use of com.pamirs.pradar.pressurement.mock.JsonMockStrategy in project LinkAgent by shulieTech.

the class AsyncHttpClientv4MethodInterceptor1 method doBefore.

@Override
public void doBefore(final Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    final HttpUriRequest request = (HttpUriRequest) args[0];
    if (request == null) {
        return;
    }
    InnerWhiteListCheckUtil.check();
    String host = request.getURI().getHost();
    int port = request.getURI().getPort();
    String path = request.getURI().getPath();
    // 判断是否在白名单中
    String url = getService(request.getURI().getScheme(), host, port, path);
    final 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);
    if (args.length == 2) {
        config.addArgs("futureCallback", args[1]);
    } else if (args.length == 3) {
        config.addArgs("futureCallback", args[2]);
    }
    if (config.getStrategy() instanceof JsonMockStrategy) {
        fixJsonStrategy.processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config);
    }
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

        @Override
        public Object call(Object param) {
            if (null == config.getArgs().get("futureCallback")) {
                return null;
            }
            // 现在先暂时注释掉因为只有jdk8以上才能用
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) config.getArgs().get("futureCallback");
            StatusLine statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "");
            try {
                HttpEntity entity = null;
                if (param instanceof String) {
                    entity = new StringEntity(String.valueOf(param));
                } else {
                    entity = new ByteArrayEntity(JSONObject.toJSONBytes(param));
                }
                BasicHttpResponse response = new BasicHttpResponse(statusline);
                response.setEntity(entity);
                futureCallback.completed(response);
                java.util.concurrent.CompletableFuture future = new java.util.concurrent.CompletableFuture();
                future.complete(response);
                return future;
            } catch (Exception e) {
            }
            return null;
        }
    });
    String method = request.getMethod();
    Pradar.startClientInvoke(path, method);
    Pradar.remoteIp(host);
    Pradar.remotePort(port);
    Pradar.middlewareName(HttpClientConstants.HTTP_CLIENT_NAME_4X);
    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.popInvokeContext();
    final Object future = args[args.length - 1];
    if (!(future instanceof FutureCallback)) {
        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 HttpResponse) {
                    afterTrace(request, (HttpResponse) 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 : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) FutureCallback(org.apache.http.concurrent.FutureCallback) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) BasicStatusLine(org.apache.http.message.BasicStatusLine) JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) Map(java.util.Map)

Example 3 with JsonMockStrategy

use of com.pamirs.pradar.pressurement.mock.JsonMockStrategy in project LinkAgent by shulieTech.

the class AsyncHttpClientv4MethodInterceptor2 method doBefore.

@Override
public void doBefore(final Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    HttpAsyncRequestProducer httpAsyncRequestProducer = (HttpAsyncRequestProducer) args[0];
    HttpHost httpHost = httpAsyncRequestProducer.getTarget();
    HttpRequest request = null;
    try {
        request = httpAsyncRequestProducer.generateRequest();
    } catch (Throwable e) {
        LOGGER.error("AsyncHttpClient org.apache.http.impl.nio.client.CloseableHttpAsyncClient.execute(org.apache.http.nio.protocol.HttpAsyncRequestProducer, org.apache.http.nio.protocol.HttpAsyncResponseConsumer<T>, org.apache.http.concurrent.FutureCallback<T>) generateRequest error. ignore it", e);
    }
    if (httpHost == null) {
        return;
    }
    InnerWhiteListCheckUtil.check();
    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(" ")));
    if (request instanceof HttpUriRequest) {
        path = ((HttpUriRequest) request).getURI().getPath();
        method = ((HttpUriRequest) request).getMethod();
    }
    // 判断是否在白名单中
    String url = getService(httpHost.getSchemeName(), host, port, path);
    final 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);
    if (args.length == 3) {
        config.addArgs("futureCallback", args[2]);
    }
    if (config.getStrategy() instanceof JsonMockStrategy) {
        fixJsonStrategy.processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config);
    }
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

        @Override
        public Object call(Object param) {
            if (null == config.getArgs().get("futureCallback")) {
                return null;
            }
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) config.getArgs().get("futureCallback");
            StatusLine statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "");
            try {
                HttpEntity entity = null;
                if (param instanceof String) {
                    entity = new StringEntity(String.valueOf(param));
                } else {
                    entity = new ByteArrayEntity(JSONObject.toJSONBytes(param));
                }
                BasicHttpResponse response = new BasicHttpResponse(statusline);
                response.setEntity(entity);
                futureCallback.completed(response);
                java.util.concurrent.CompletableFuture future = new java.util.concurrent.CompletableFuture();
                future.complete(response);
                return future;
            } catch (Exception e) {
            }
            return null;
        }
    });
    Pradar.startClientInvoke(path, method);
    Pradar.remoteIp(host);
    Pradar.remotePort(port);
    Pradar.middlewareName(HttpClientConstants.HTTP_CLIENT_NAME_4X);
    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.popInvokeContext();
    final Object future = args[args.length - 1];
    if (!(future instanceof FutureCallback)) {
        return;
    }
    final HttpRequest finalRequest = request;
    advice.changeParameter(args.length - 1, new FutureCallback() {

        @Override
        public void completed(Object result) {
            Pradar.setInvokeContext(context);
            ((FutureCallback) future).completed(result);
            try {
                if (result instanceof HttpResponse) {
                    afterTrace(finalRequest, (HttpResponse) result);
                } else {
                    afterTrace(finalRequest, 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(finalRequest, 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(finalRequest, null);
            } catch (Throwable e) {
                LOGGER.error("AsyncHttpClient execute future endTrace error.", e);
                Pradar.endClientInvoke("200", HttpClientConstants.PLUGIN_TYPE);
            }
        }
    });
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) FutureCallback(org.apache.http.concurrent.FutureCallback) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) BasicStatusLine(org.apache.http.message.BasicStatusLine) JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall) Map(java.util.Map)

Example 4 with JsonMockStrategy

use of com.pamirs.pradar.pressurement.mock.JsonMockStrategy in project LinkAgent by shulieTech.

the class HttpClientv3MethodInterceptor method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    try {
        final HttpMethod method = (HttpMethod) args[1];
        if (method == null) {
            return;
        }
        int port = method.getURI().getPort();
        String path = method.getURI().getPath();
        String url = getService(method.getURI().getScheme(), method.getURI().getHost(), port, path);
        final MatchConfig config = ClusterTestUtils.httpClusterTest(url);
        Header header = method.getRequestHeader(PradarService.PRADAR_WHITE_LIST_CHECK);
        if (header == null) {
            config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, true);
        } else {
            config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, header.getValue());
        }
        config.addArgs("url", url);
        config.addArgs("isInterface", Boolean.FALSE);
        if (config.getStrategy() instanceof JsonMockStrategy) {
            config.addArgs("extraMethod", method);
            fixJsonStrategy.processBlock(java.lang.String.class, advice.getClassLoader(), config);
        }
        config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionForwardCall() {

            @Override
            public Object call(Object param) throws ProcessControlException {
                byte[] bytes = JSONObject.toJSONBytes(param);
                Reflect.on(method).set("responseBody", bytes);
                ProcessController.returnImmediately(int.class, 200);
                return true;
            }

            @Override
            public Object forward(Object param) throws ProcessControlException {
                String forwarding = config.getForwarding();
                try {
                    method.setURI(new URI(forwarding));
                } catch (URIException e) {
                }
                return null;
            }
        });
    } catch (URIException e) {
        LOGGER.error("", e);
        if (Pradar.isClusterTest()) {
            throw new PressureMeasureError(e);
        }
    } catch (ProcessControlException pce) {
        throw pce;
    } catch (Throwable t) {
        LOGGER.error("", t);
        if (Pradar.isClusterTest()) {
            throw new PressureMeasureError(t);
        }
    }
}
Also used : ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) URI(org.apache.commons.httpclient.URI) JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) ExecutionForwardCall(com.pamirs.pradar.internal.adapter.ExecutionForwardCall) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) JSONObject(com.alibaba.fastjson.JSONObject) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 5 with JsonMockStrategy

use of com.pamirs.pradar.pressurement.mock.JsonMockStrategy in project LinkAgent by shulieTech.

the class HttpClientv4MethodInterceptor1 method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    if (!Pradar.isClusterTest()) {
        return;
    }
    Object[] args = advice.getParameterArray();
    final HttpUriRequest request = (HttpUriRequest) args[0];
    if (request == null) {
        return;
    }
    String host = request.getURI().getHost();
    int port = request.getURI().getPort();
    String path = request.getURI().getPath();
    // 判断是否在白名单中
    String url = getService(request.getURI().getScheme(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] headers = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    if (headers.length > 0) {
        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);
    if (config.getStrategy() instanceof JsonMockStrategy) {
        fixJsonStrategy.processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config);
    }
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionCall() {

        @Override
        public Object call(Object param) {
            StatusLine statusline = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "");
            try {
                HttpEntity entity = null;
                if (param instanceof String) {
                    entity = new StringEntity(String.valueOf(param), "UTF-8");
                } else {
                    entity = new ByteArrayEntity(JSONObject.toJSONBytes(param));
                }
                BasicHttpResponse response = new BasicHttpResponse(statusline);
                response.setEntity(entity);
                if (HttpClientConstants.clazz == null) {
                    HttpClientConstants.clazz = Class.forName("org.apache.http.impl.execchain.HttpResponseProxy");
                }
                return Reflect.on(HttpClientConstants.clazz).create(response, null).get();
            } catch (Exception e) {
            }
            return null;
        }
    });
}
Also used : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) IOException(java.io.IOException) BasicStatusLine(org.apache.http.message.BasicStatusLine) JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) BasicStatusLine(org.apache.http.message.BasicStatusLine) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JSONObject(com.alibaba.fastjson.JSONObject) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall)

Aggregations

MatchConfig (com.pamirs.pradar.internal.config.MatchConfig)12 JsonMockStrategy (com.pamirs.pradar.pressurement.mock.JsonMockStrategy)12 ProcessControlException (com.shulie.instrument.simulator.api.ProcessControlException)9 JSONObject (com.alibaba.fastjson.JSONObject)8 ExecutionCall (com.pamirs.pradar.internal.config.ExecutionCall)6 SocketTimeoutException (java.net.SocketTimeoutException)5 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)5 StringEntity (org.apache.http.entity.StringEntity)5 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)5 BasicStatusLine (org.apache.http.message.BasicStatusLine)5 IOException (java.io.IOException)4 ExecutionForwardCall (com.pamirs.pradar.internal.adapter.ExecutionForwardCall)3 Map (java.util.Map)3 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)3 FutureCallback (org.apache.http.concurrent.FutureCallback)3 ExecutionStrategy (com.pamirs.pradar.internal.adapter.ExecutionStrategy)2 MockStrategy (com.pamirs.pradar.pressurement.mock.MockStrategy)2 HttpURLConnection (java.net.HttpURLConnection)2 URL (java.net.URL)2 RealResponseBody (okhttp3.internal.http.RealResponseBody)2