Search in sources :

Example 81 with PressureMeasureError

use of com.pamirs.pradar.exception.PressureMeasureError in project LinkAgent by shulieTech.

the class AfterTraceInterceptor method doAfter.

@Override
public final void doAfter(Advice advice) throws Throwable {
    if (!simulatorConfig.getBooleanProperty("plugin." + getPluginName() + ".trace.enabled", true)) {
        return;
    }
    ClusterTestUtils.validateClusterTest();
    Throwable throwable = null;
    try {
        afterFirst(advice);
    } catch (PradarException e) {
        LOGGER.error("TraceInterceptor afterFirst exec err:{}", this.getClass().getName(), e);
        throwable = e;
    } catch (PressureMeasureError e) {
        LOGGER.error("TraceInterceptor afterFirst exec err:{}", this.getClass().getName(), e);
        throwable = e;
    } catch (Throwable t) {
        LOGGER.error("TraceInterceptor afterFirst exec err:{}", this.getClass().getName(), t);
        throwable = t;
    }
    try {
        if (isClient(advice)) {
            endClientInvoke(advice);
        } else {
            endServerInvoke(advice);
        }
    } catch (PradarException e) {
        LOGGER.error("TraceInterceptor after exec err:{}", this.getClass().getName(), e);
        if (Pradar.isClusterTest()) {
            throw e;
        }
    } catch (PressureMeasureError e) {
        LOGGER.error("TraceInterceptor after exec err:{}", this.getClass().getName(), e);
        if (Pradar.isClusterTest()) {
            throw e;
        }
    } catch (Throwable e) {
        if (Pradar.isClusterTest()) {
            LOGGER.error("TraceInterceptor after exec err:{}", this.getClass().getName(), e);
            throw new PressureMeasureError(e);
        }
    } finally {
        try {
            afterLast(advice);
        } catch (PradarException e) {
            LOGGER.error("TraceInterceptor afterLast exec err:{}", this.getClass().getName(), e);
            throwable = e;
        } catch (PressureMeasureError e) {
            LOGGER.error("TraceInterceptor afterLast exec err:{}", this.getClass().getName(), e);
            throwable = e;
        } catch (Throwable t) {
            LOGGER.error("TraceInterceptor afterLast exec err:{}", this.getClass().getName(), t);
            throwable = t;
        }
    }
    if (throwable != null && Pradar.isClusterTest()) {
        throw throwable;
    }
}
Also used : PradarException(com.pamirs.pradar.exception.PradarException) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError)

Example 82 with PressureMeasureError

use of com.pamirs.pradar.exception.PressureMeasureError in project LinkAgent by shulieTech.

the class LettuceMasterStrategy method match.

@Override
public List<String> match(Object obj) {
    List<String> result = new ArrayList<String>();
    if (obj instanceof Advice) {
        try {
            Object resultObj = ((Advice) obj).getReturnObj();
            String className = resultObj.getClass().getName();
            if (className.equals("io.lettuce.core.masterslave.StatefulRedisMasterSlaveConnectionImpl")) {
                Object channelWriter = Reflect.on(resultObj).get(LettuceConstants.REFLECT_FIELD_CHANNEL_WRITER);
                Object masterSlaveConnectionProvider = Reflect.on(channelWriter).get("masterSlaveConnectionProvider");
                RedisURI initialRedisUri = null;
                try {
                    initialRedisUri = Reflect.on(masterSlaveConnectionProvider).get("initialRedisUri");
                } catch (Throwable t) {
                }
                if (initialRedisUri != null && CollectionUtils.isNotEmpty(initialRedisUri.getSentinels())) {
                    /**
                     * initialRedisUri针对哨兵模式
                     */
                    if (initialRedisUri.getSentinelMasterId() != null) {
                        result.add(initialRedisUri.getSentinelMasterId());
                    }
                    if (CollectionUtils.isNotEmpty(initialRedisUri.getSentinels())) {
                        for (RedisURI redisURI : initialRedisUri.getSentinels()) {
                            result.add(redisURI.getHost() + ":" + redisURI.getPort());
                        }
                    }
                    return result;
                }
                List list = Reflect.on(masterSlaveConnectionProvider).get("knownNodes");
                for (Object redisMasterSlaveNode : list) {
                    RedisURI uri = Reflect.on(redisMasterSlaveNode).get("redisURI");
                    result.add(uri.getHost() + ":" + uri.getPort());
                }
            } else {
                throw new PressureMeasureError("not support masterSlave type. className = " + resultObj.getClass().getName());
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return result;
}
Also used : RedisURI(io.lettuce.core.RedisURI) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Advice(com.shulie.instrument.simulator.api.listener.ext.Advice)

Example 83 with PressureMeasureError

use of com.pamirs.pradar.exception.PressureMeasureError in project LinkAgent by shulieTech.

the class RequestTracer method startTrace.

/**
 * 开始调用链,注意,开始之后,不管后续处理是否正常,都需要调用。
 */
public final boolean startTrace(REQ request, RESP response, String pluginName) {
    String url = getRequestURI(request);
    if (isNeedFilter(url, request)) {
        return false;
    }
    String ip = null;
    if (!PradarSwitcher.USE_LOCAL_IP) {
        ip = getRemoteAddress(request);
    }
    String traceId = getTraceId(request);
    boolean isClusterTestRequest = isClusterTestRequest(request);
    boolean isDebug = isDebugRequest(request);
    ClusterTestUtils.validateClusterTest(isClusterTestRequest);
    boolean isTraceIdBlank = false;
    if (StringUtils.isBlank(traceId)) {
        traceId = TraceIdGenerator.generate(ip, isClusterTestRequest);
        isTraceIdBlank = true;
    }
    if (isDebug && isTraceIdBlank) {
        setResponseHeader(response, "traceId", traceId);
    }
    if (isClusterTestRequest) {
        final DoorPlank arbiterDp = ArbiterEntrance.shallWePassHttp();
        if (Pradar.DOOR_CLOSED.equals(arbiterDp.getStatus())) {
            ErrorReporter.buildError().setErrorType(ErrorTypeEnum.AgentError).setErrorCode("agent-0008").setMessage("压测开关关闭").setDetail("data receiver filter is close!").report();
            throw new PressureMeasureError("data receiver filter is close! " + arbiterDp, isClusterTestRequest);
        }
    }
    if (!isTraceIdBlank) {
        Map<String, String> context = getContext(request);
        if (context != null) {
            context.put(PradarService.PRADAR_TRACE_ID_KEY, traceId);
            context.put(PradarService.PRADAR_CLUSTER_TEST_KEY, String.valueOf(isClusterTestRequest));
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("accept web server rpcServerRecv context:{}, currentContext:{} currentMiddleware:{}", context, Pradar.getInvokeContextMap(), Pradar.getMiddlewareName());
        }
        Pradar.startServerInvoke(url, StringUtils.upperCase(getMethod(request)), context);
        setAttribute(request, "isTrace", false);
    } else {
        Pradar.clearInvokeContext();
        Pradar.startTrace(traceId, url, StringUtils.upperCase(getMethod(request)));
        setAttribute(request, "isTrace", true);
    }
    InvokeContext invokeContext = Pradar.getInvokeContext();
    invokeContext.setClusterTest(isClusterTestRequest);
    invokeContext.setDebug(isDebug);
    final long contentLength = getContentLength(request);
    invokeContext.setRequestSize(contentLength < 0 ? 0 : contentLength);
    String remoteIp = invokeContext.getRemoteIp();
    if (StringUtils.isBlank(remoteIp) || "127.0.0.1".equals(remoteIp)) {
        remoteIp = getRemoteAddress(request);
    }
    if (StringUtils.isNotBlank(remoteIp)) {
        invokeContext.setRemoteIp(remoteIp);
    }
    String port = getRemotePort(request);
    if (port != null) {
        invokeContext.setPort(port);
    }
    invokeContext.setMiddlewareName(pluginName);
    return true;
}
Also used : DoorPlank(com.pamirs.pradar.pressurement.agent.shared.domain.DoorPlank) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError)

Example 84 with PressureMeasureError

use of com.pamirs.pradar.exception.PressureMeasureError 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 85 with PressureMeasureError

use of com.pamirs.pradar.exception.PressureMeasureError in project LinkAgent by shulieTech.

the class ConsumerRecordEntryPointInterceptor2 method beforeLast.

@Override
public void beforeLast(Advice advice) {
    Object[] args = advice.getParameterArray();
    ClusterTestUtils.validateClusterTest();
    ConsumerRecord consumerRecord = (ConsumerRecord) args[0];
    String topic = consumerRecord.topic();
    boolean isClusterTest = Pradar.isClusterTestPrefix(topic);
    if (PradarSwitcher.isKafkaMessageHeadersEnabled()) {
        Headers headers = consumerRecord.headers();
        Header header = headers.lastHeader(PradarService.PRADAR_CLUSTER_TEST_KEY);
        if (header != null) {
            isClusterTest = isClusterTest || ClusterTestUtils.isClusterTestRequest(BytesUtils.toString(header.value()));
        }
    }
    if (isClusterTest) {
        Pradar.setClusterTest(true);
    }
    if (PradarService.isSilence() && isClusterTest) {
        throw new PressureMeasureError("[kafka check]silence module ! can not handle cluster test data");
    }
}
Also used : Header(org.apache.kafka.common.header.Header) Headers(org.apache.kafka.common.header.Headers) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord)

Aggregations

PressureMeasureError (com.pamirs.pradar.exception.PressureMeasureError)150 PradarException (com.pamirs.pradar.exception.PradarException)34 DataSourceMeta (com.pamirs.pradar.pressurement.agent.shared.service.DataSourceMeta)14 Connection (java.sql.Connection)14 SQLException (java.sql.SQLException)13 ArrayList (java.util.ArrayList)13 Map (java.util.Map)11 MatchConfig (com.pamirs.pradar.internal.config.MatchConfig)8 ShadowDatabaseConfig (com.pamirs.pradar.internal.config.ShadowDatabaseConfig)8 HashMap (java.util.HashMap)8 MongoNamespace (com.mongodb.MongoNamespace)7 RequestIndexRename (com.pamirs.attach.plugin.es.common.RequestIndexRename)7 ProcessControlException (com.shulie.instrument.simulator.api.ProcessControlException)7 MQTraceContext (com.pamirs.attach.plugin.alibaba.rocketmq.common.MQTraceContext)6 SpanRecord (com.pamirs.pradar.interceptor.SpanRecord)6 ReflectException (com.shulie.instrument.simulator.api.reflect.ReflectException)6 List (java.util.List)6 ConsumeMessageContext (org.apache.rocketmq.client.hook.ConsumeMessageContext)6 ConsumeMessageContext (com.alibaba.rocketmq.client.hook.ConsumeMessageContext)5 WrapperRequest (com.pamirs.attach.plugin.hessian.common.WrapperRequest)5