Search in sources :

Example 16 with ProcessControlException

use of com.shulie.instrument.simulator.api.ProcessControlException in project LinkAgent by shulieTech.

the class HttpRequestExecuteMethodInterceptor method afterFirst.

@Override
public void afterFirst(Advice advice) throws ProcessControlException {
    Object target = advice.getTarget();
    final HttpRequest request = (HttpRequest) target;
    String url = request.getUrl().build();
    String whiteList = request.getHeaders().getFirstHeaderStringValue(PradarService.PRADAR_WHITE_LIST_CHECK);
    final MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, whiteList);
    config.addArgs("url", url);
    config.addArgs("request", request);
    config.addArgs("method", url);
    config.addArgs("isInterface", Boolean.FALSE);
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionForwardCall() {

        @Override
        public Object forward(Object param) throws ProcessControlException {
            GenericUrl url1 = new GenericUrl(config.getForwarding());
            Reflect.on(request).set("url", url1);
            return null;
        }

        @Override
        public Object call(Object param) throws ProcessControlException {
            return param;
        }
    });
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) ExecutionForwardCall(com.pamirs.pradar.internal.adapter.ExecutionForwardCall) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) GenericUrl(com.google.api.client.http.GenericUrl)

Example 17 with ProcessControlException

use of com.shulie.instrument.simulator.api.ProcessControlException in project LinkAgent by shulieTech.

the class AsyncHttpClientv5MethodInterceptor2 method doBefore.

@Override
public void doBefore(final Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    // AsyncRequestProducer
    BasicRequestProducer requestBasic = (BasicRequestProducer) args[0];
    // 这里应该有问题先用这个类定义,后面debug之后再做修改
    final HttpRequest request;
    try {
        Field field = requestBasic.getClass().getSuperclass().getDeclaredField("request");
        field.setAccessible(true);
        request = (HttpRequest) field.get(requestBasic);
    } catch (Exception e) {
        logger.error("获取request参数错误", e);
        return;
    }
    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[] 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);
    String method = request.getMethod();
    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);
        }
    }
    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 : SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) HttpRequest(org.apache.hc.core5.http.HttpRequest) BasicRequestProducer(org.apache.hc.core5.http.nio.support.BasicRequestProducer) 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) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) Field(java.lang.reflect.Field) Header(org.apache.hc.core5.http.Header) 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 18 with ProcessControlException

use of com.shulie.instrument.simulator.api.ProcessControlException in project LinkAgent by shulieTech.

the class HttpClientv4MethodInterceptor method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    Object[] args = advice.getParameterArray();
    HttpHost httpHost = (HttpHost) args[0];
    final HttpRequest request = (HttpRequest) args[1];
    if (httpHost == null) {
        return;
    }
    String host = httpHost.getHostName();
    int port = httpHost.getPort();
    String path = httpHost.getHostName();
    if (request instanceof HttpUriRequest) {
        path = ((HttpUriRequest) request).getURI().getPath();
    }
    // 判断是否在白名单中
    String url = getService(httpHost.getSchemeName(), host, port, path);
    MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    Header[] headers = request.getHeaders(PradarService.PRADAR_WHITE_LIST_CHECK);
    if (headers != null && 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)

Example 19 with ProcessControlException

use of com.shulie.instrument.simulator.api.ProcessControlException in project LinkAgent by shulieTech.

the class EventListenerHandler method handleEvent.

/**
 * 调用出发事件处理&调用执行流程控制
 *
 * @param listenerId 处理器ID
 * @param processId  调用过程ID
 * @param invokeId   调用ID
 * @param event      调用事件
 * @param processor  事件处理器
 * @return 处理返回结果
 * @throws Throwable 当出现未知异常时,且事件处理器为中断流程事件时抛出
 */
private final Result handleEvent(final int listenerId, final int processId, final int invokeId, final Class clazz, final Event event, final InvokeProcessor processor) throws Throwable {
    final EventListener listener = processor.listener;
    /**
     * 如果当前事件不在事件监听器处理列表中,则直接返回,不处理事件
     */
    if (!ArrayUtils.contains(processor.eventEventTypes, event.getType())) {
        return Result.RESULT_NONE;
    }
    try {
        if (isDebugEnabled) {
            logger.debug("SIMULATOR: on-event: event -> eventType={}, processId={}, invokeId={}, listenerId={}", event.getType(), processId, invokeId, listenerId);
        }
        /**
         * 调用事件处理
         */
        ProcessControlEntity pce = listener.onEvent(event);
        int state = pce.getState();
        if (state != ProcessControlEntity.NONE_IMMEDIATELY) {
            return processInterrupt(listenerId, processId, invokeId, clazz, event, processor, pce);
        }
    } catch (ProcessControlException pce) {
        return processInterrupt(listenerId, processId, invokeId, clazz, event, processor, pce.toEntity());
    } catch (Throwable throwable) {
        /**
         * 如果当前事件处理器是可中断的事件处理器,则对外抛出UnCaughtException
         * 中断当前方法
         */
        if (ReflectUtils.isInterruptEventHandler(listener)) {
            throw throwable;
        } else {
            /**
             * 普通事件处理器则可以打个日志后,直接放行
             */
            ExceptionHandler exceptionHandler = getExceptionHandler();
            if (exceptionHandler != null) {
                exceptionHandler.handleException(throwable, String.format("on-event: event -> eventType=%s, processId=%s, invokeId=%s, listenerId=%s occur an error.", EventType.name(event.getType()), processId, invokeId, listenerId), listener);
            } else {
                logger.warn("SIMULATOR: on-event: event -> eventType={}, processId={}, invokeId={}, listenerId={} occur an " + "error.", event.getType(), processId, invokeId, listenerId, throwable);
            }
        }
    }
    /**
     * 默认返回不进行任何流程变更
     */
    return Result.RESULT_NONE;
}
Also used : ExceptionHandler(com.shulie.instrument.simulator.message.exception.ExceptionHandler) ProcessControlEntity(com.shulie.instrument.simulator.api.ProcessControlEntity) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) EventListener(com.shulie.instrument.simulator.api.listener.EventListener)

Example 20 with ProcessControlException

use of com.shulie.instrument.simulator.api.ProcessControlException in project LinkAgent by shulieTech.

the class RealCallExecuteV3Interceptor method beforeFirst.

@Override
public void beforeFirst(Advice advice) throws ProcessControlException {
    if (!Pradar.isClusterTest()) {
        return;
    }
    Object target = advice.getTarget();
    final Call call = (Call) target;
    final HttpUrl httpUrl = call.request().url();
    String url = OKHttpConstants.getService(httpUrl.scheme(), httpUrl.host(), httpUrl.port(), httpUrl.encodedPath());
    final MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    String check = call.request().header(PradarService.PRADAR_WHITE_LIST_CHECK);
    config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, check);
    config.addArgs("url", url);
    config.addArgs("isInterface", Boolean.FALSE);
    if (config.getStrategy() instanceof JsonMockStrategy) {
        config.addArgs("call", call);
        MockReturnUtils.fixJsonStrategy.processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config);
    }
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionForwardCall() {

        @Override
        public Object forward(Object param) throws ProcessControlException {
            String configUrl = config.getForwarding();
            if (httpUrl.queryParameterNames().size() > 0) {
                StringBuilder builder = new StringBuilder(128).append(configUrl).append("?");
                boolean first = true;
                for (String queryParameterName : httpUrl.queryParameterNames()) {
                    if (!first) {
                        builder.append("&");
                    }
                    builder.append(queryParameterName).append("=").append(httpUrl.queryParameter(queryParameterName));
                    first = false;
                }
                configUrl = builder.toString();
            }
            HttpUrl forwardHttpUrl = HttpUrl.parse(configUrl);
            Reflect.on(call.request()).set("url", forwardHttpUrl);
            return null;
        }

        @Override
        public Object call(Object param) {
            Headers header = new Headers.Builder().build();
            Buffer buffer = new Buffer();
            try {
                if (param instanceof String) {
                    buffer.write(String.valueOf(param).getBytes("UTF-8"));
                } else {
                    buffer.write(JSONObject.toJSONBytes(param));
                }
            } catch (IOException e) {
            }
            return new Response.Builder().code(200).body(new RealResponseBody(header, buffer)).request(call.request()).protocol(Protocol.HTTP_1_0).message("OK").build();
        }
    });
}
Also used : Buffer(okio.Buffer) ExecutionForwardCall(com.pamirs.pradar.internal.adapter.ExecutionForwardCall) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) RealResponseBody(okhttp3.internal.http.RealResponseBody) IOException(java.io.IOException) JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) ExecutionForwardCall(com.pamirs.pradar.internal.adapter.ExecutionForwardCall) JSONObject(com.alibaba.fastjson.JSONObject)

Aggregations

ProcessControlException (com.shulie.instrument.simulator.api.ProcessControlException)23 MatchConfig (com.pamirs.pradar.internal.config.MatchConfig)21 JSONObject (com.alibaba.fastjson.JSONObject)15 ExecutionCall (com.pamirs.pradar.internal.config.ExecutionCall)12 SocketTimeoutException (java.net.SocketTimeoutException)10 JsonMockStrategy (com.pamirs.pradar.pressurement.mock.JsonMockStrategy)9 IOException (java.io.IOException)8 PressureMeasureError (com.pamirs.pradar.exception.PressureMeasureError)7 ExecutionForwardCall (com.pamirs.pradar.internal.adapter.ExecutionForwardCall)6 Map (java.util.Map)6 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 URISyntaxException (java.net.URISyntaxException)4 Buffer (okio.Buffer)4 Header (org.apache.hc.core5.http.Header)4 ScriptEvaluator (com.pamirs.pradar.script.ScriptEvaluator)3 ReflectException (com.shulie.instrument.simulator.api.reflect.ReflectException)3 URI (java.net.URI)3