Search in sources :

Example 21 with MatchConfig

use of com.pamirs.pradar.internal.config.MatchConfig in project LinkAgent by shulieTech.

the class AsyncHttpClientv5MethodInterceptor1 method doBefore.

@Override
public void doBefore(final Advice advice) throws ProcessControlException {
    // 现在先暂时注释掉因为只有jdk8以上才能用
    Object[] args = advice.getParameterArray();
    // SimpleHttpRequest
    final SimpleHttpRequest request = (SimpleHttpRequest) args[0];
    URI uri = null;
    if (request == null) {
        return;
    }
    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 : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) SimpleHttpRequest(org.apache.hc.client5.http.async.methods.SimpleHttpRequest) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) SimpleHttpResponse(org.apache.hc.client5.http.async.methods.SimpleHttpResponse) URISyntaxException(java.net.URISyntaxException) SocketTimeoutException(java.net.SocketTimeoutException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) 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 22 with MatchConfig

use of com.pamirs.pradar.internal.config.MatchConfig 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 23 with MatchConfig

use of com.pamirs.pradar.internal.config.MatchConfig in project LinkAgent by shulieTech.

the class ForwardStrategy method processBlock.

@Override
public Object processBlock(Class returnType, ClassLoader classLoader, Object params) {
    if (Pradar.isClusterTest()) {
        MatchConfig config = (MatchConfig) params;
        Object request = config.getArgs().get("request");
        String method = (String) config.getArgs().get("method");
        if (null != config.getForwarding() && null != request) {
            try {
                URL url = new URL(config.getForwarding());
                Reflect.on(request).set(method, url);
            } catch (Exception e) {
                try {
                    URI uri = new URI(config.getForwarding());
                    Reflect.on(request).set(method, uri);
                } catch (URISyntaxException uriSyntaxException) {
                }
            }
        }
    }
    return null;
}
Also used : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) URL(java.net.URL) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) URISyntaxException(java.net.URISyntaxException)

Example 24 with MatchConfig

use of com.pamirs.pradar.internal.config.MatchConfig in project LinkAgent by shulieTech.

the class WhiteListStrategy method processBlock.

@Override
public Object processBlock(Class returnType, ClassLoader classLoader, Object params) {
    if (!Pradar.isClusterTest()) {
        return true;
    }
    if (!PradarSwitcher.whiteListSwitchOn()) {
        return true;
    }
    if (params instanceof MatchConfig) {
        MatchConfig config = (MatchConfig) params;
        Map<String, Object> args = config.getArgs();
        // 直接通过通过白名单校验
        /* if (TRUE.equals(args.get(PradarService.PRADAR_WHITE_LIST_CHECK))) {
                return true;
            }*/
        InvokeContext invokeContext = Pradar.getInvokeContext();
        if (invokeContext.getParentInvokeContext() != null && (invokeContext.getParentInvokeContext().getInvokeType() == MiddlewareType.TYPE_RPC || invokeContext.getParentInvokeContext().getInvokeType() == MiddlewareType.TYPE_WEB_SERVER) && invokeContext.getParentInvokeContext().isPassCheck()) {
            return true;
        }
        /**
         * 部分http在beforeFirst的时候校验,还没有trace
         */
        if (invokeContext != null && (invokeContext.getInvokeType() == MiddlewareType.TYPE_RPC || invokeContext.getInvokeType() == MiddlewareType.TYPE_WEB_SERVER) && invokeContext.isPassCheck()) {
            return true;
        }
        if (!config.isSuccess()) {
            Boolean isInterface = isInterface(config);
            if (isInterface) {
                String className = (String) args.get("class");
                String methodName = (String) args.get("method");
                String message = "WhiteListError: [" + AppNameUtils.appName() + "] interface [" + className + "#" + methodName + "] is not allowed in WhiteList.";
                if (Pradar.isClusterTest()) {
                    ErrorReporter.buildError().setErrorType(ErrorTypeEnum.AgentError).setErrorCode("whiteList-0001").setMessage(message).setDetail(message).closePradar(ConfigNames.RPC_WHITE_LIST).report();
                    throw new PressureMeasureError(message);
                }
            } else {
                String url = (String) args.get("url");
                String message = "WhiteListError: [" + AppNameUtils.appName() + "] url [" + url + "] is not allowed in WhiteList.";
                ErrorReporter.buildError().setErrorType(ErrorTypeEnum.AgentError).setErrorCode("whiteList-0001").setMessage(message).setDetail(message).closePradar(ConfigNames.URL_WHITE_LIST).report();
                throw new PressureMeasureError(message);
            }
        }
    }
    return true;
}
Also used : PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig)

Example 25 with MatchConfig

use of com.pamirs.pradar.internal.config.MatchConfig in project LinkAgent by shulieTech.

the class ArbiterHttpExit method shallWePassHttpStringCache.

private static MatchConfig shallWePassHttpStringCache(String url) {
    if (url != null) {
        final int index = url.indexOf("&#47;");
        if (index != -1) {
            url = url.replace("&#47;", "/");
        }
    }
    MatchConfig config = null;
    String orgUrl = url;
    // 如果列表为空,同样是无法调用的
    if (url != null) {
        try {
            URI uri = URI.create(url);
            if (uri.getHost().startsWith("pt")) {
                try {
                    String substring = uri.getHost().substring(2);
                    if (substring.startsWith("-")) {
                        substring = substring.substring(1);
                    }
                    url = new URI(uri.getScheme(), uri.getUserInfo(), substring, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()).getPath();
                } catch (URISyntaxException e) {
                }
            } else {
                url = uri.getPath();
            }
        } catch (Throwable e) {
            if (url.startsWith("http://")) {
                url = url.substring(7);
                int index = url.indexOf("/");
                if (index != -1) {
                    url = url.substring(index + 1);
                } else {
                    url = "/";
                }
            } else if (url.startsWith("https://")) {
                url = url.substring(8);
                int index = url.indexOf("/");
                if (index != -1) {
                    url = url.substring(index + 1);
                } else {
                    url = "/";
                }
            }
            final int indexOfQuestion = url.indexOf('?');
            if (indexOfQuestion != -1) {
                url = url.substring(0, indexOfQuestion);
            }
            final int indexOfx = url.indexOf('#');
            if (indexOfx != -1) {
                url = url.substring(0, indexOfx);
            }
        // 如果不是一个正常的uri则直接忽略这一步
        }
        if (StringUtils.isBlank(url) || "/".equals(url)) {
            /**
             * 如果 url 为空或者是/没有其他值,则使用原 url 匹配一次
             */
            config = patternCache.getUnchecked(orgUrl);
            if (null != config) {
                return config;
            }
        }
        config = patternCache.getUnchecked(url);
        if (null != config) {
            return config;
        }
        if (null != PradarSwitcher.httpPassPrefix.get() && url.startsWith(PradarSwitcher.httpPassPrefix.get())) {
            return config;
        }
        LOGGER.warn("WhiteListError: url is not allowed:" + url);
    }
    return failure();
}
Also used : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Aggregations

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