Search in sources :

Example 31 with ReflectException

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

the class HessianServletServiceInterceptor method getMethodArgs.

public Object[] getMethodArgs(InputStream is, SerializerFactory serializerFactory, HessianSkeleton hessianSkeleton) {
    try {
        HessianInputFactory.HeaderType header = _inputFactory.readHeader(is);
        AbstractHessianInput in;
        switch(header) {
            case CALL_1_REPLY_1:
                in = _hessianFactory.createHessianInput(is);
                break;
            case CALL_1_REPLY_2:
                in = _hessianFactory.createHessianInput(is);
                break;
            case HESSIAN_2:
                in = _hessianFactory.createHessian2Input(is);
                in.readCall();
                break;
            default:
                throw new IllegalStateException(header + " is an unknown Hessian call");
        }
        if (serializerFactory != null) {
            in.setSerializerFactory(serializerFactory);
        }
        in.skipOptionalCall();
        while ((in.readHeader()) != null) {
            in.readObject();
        }
        String methodName = in.readMethod();
        int argLength = in.readMethodArgLength();
        Method method = null;
        if (hessianSkeleton != null) {
            try {
                Map map = Reflect.on(hessianSkeleton).get(HessianConstants.DYNAMIC_FIELD_METHOD_MAP);
                method = (Method) map.get(methodName + "__" + argLength);
            } catch (ReflectException e) {
            }
        }
        if ("_hessian_getAttribute".equals(methodName)) {
            String attrName = in.readString();
            in.completeCall();
            return new Object[] { "_hessian_getAttribute", new Object[0] };
        }
        Class<?>[] args = method == null ? null : method.getParameterTypes();
        if (args == null || (argLength != args.length && argLength >= 0)) {
            return EMPTY_ARGS;
        }
        Object[] values = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            values[i] = in.readObject(args[i]);
        }
        in.completeCall();
        return new Object[] { methodName, args };
    } catch (IOException e) {
        return EMPTY_ARGS;
    }
}
Also used : Method(java.lang.reflect.Method) IOException(java.io.IOException) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException) AbstractHessianInput(com.caucho.hessian.io.AbstractHessianInput) HessianInputFactory(com.caucho.hessian.io.HessianInputFactory) Map(java.util.Map)

Example 32 with ReflectException

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

the class RealCallExecuteV2Interceptor method beforeFirst.

@Override
public void beforeFirst(Advice advice) throws ProcessControlException {
    Object target = advice.getTarget();
    Request request = null;
    try {
        request = Reflect.on(target).get(OKHttpConstants.DYNAMIC_FIELD_REQUEST);
    } catch (ReflectException e) {
        request = Reflect.on(target).get(OKHttpConstants.DYNAMIC_FIELD_ORIGINAL_REQUEST);
    }
    String url = request.urlString();
    final MatchConfig config = ClusterTestUtils.httpClusterTest(url);
    String check = request.header(OKHttpConstants.DYNAMIC_FIELD_HEADER);
    config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, check);
    config.addArgs("url", url);
    config.addArgs("isInterface", Boolean.FALSE);
    final Request finalRequest = request;
    config.getStrategy().processBlock(advice.getBehavior().getReturnType(), advice.getClassLoader(), config, new ExecutionForwardCall() {

        @Override
        public Object forward(Object param) throws ProcessControlException {
            HttpUrl httpUrl = HttpUrl.parse(config.getForwarding());
            Reflect.on(finalRequest).set("url", httpUrl);
            return null;
        }

        @Override
        public Object call(Object param) {
            Headers header = Headers.of(new String[0]);
            Buffer buffer = new Buffer();
            try {
                byte[] bytes = null;
                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(finalRequest).protocol(Protocol.HTTP_1_0).message("OK").build();
        }
    });
}
Also used : Buffer(okio.Buffer) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) Headers(com.squareup.okhttp.Headers) MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) RealResponseBody(com.squareup.okhttp.internal.http.RealResponseBody) Request(com.squareup.okhttp.Request) IOException(java.io.IOException) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException) HttpUrl(okhttp3.HttpUrl) ExecutionForwardCall(com.pamirs.pradar.internal.adapter.ExecutionForwardCall) Response(com.squareup.okhttp.Response) JSONObject(com.alibaba.fastjson.JSONObject)

Example 33 with ReflectException

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

the class ConsumerRegistry method buildMQPushConsumer.

/**
 * 构建 DefaultMQPushConsumer
 * 如果后续支持影子 server 模式,则直接修改此方法即可
 *
 * @param businessConsumer 业务消费者
 * @return 返回注册的影子消费者,如果初始化失败会返回 null
 */
private static synchronized DefaultMQPushConsumer buildMQPushConsumer(DefaultMQPushConsumer businessConsumer) {
    Map<String, SubscriptionData> topicsInWhiteList = new HashMap<String, SubscriptionData>();
    ConcurrentMap<String, SubscriptionData> map;
    try {
        map = businessConsumer.getDefaultMQPushConsumerImpl().getSubscriptionInner();
    } catch (NoSuchMethodError e) {
        try {
            map = Reflect.on(businessConsumer.getDefaultMQPushConsumerImpl()).call("getSubscriptionInner").get();
        } catch (ReflectException t) {
            logger.error("buildMQPushConsumer getSubscriptionInner error.", e);
            return null;
        }
    }
    if (map != null) {
        Long lastWhitelistWarnTime = lastWhitelistWarnTimes.get(businessConsumer);
        if (lastWhitelistWarnTime == null) {
            lastWhitelistWarnTime = 0L;
        }
        long now = System.currentTimeMillis();
        long passTime = now - lastWhitelistWarnTime;
        for (Map.Entry<String, SubscriptionData> entry : map.entrySet()) {
            String topic = entry.getKey();
            if (!isPermitInitConsumer(businessConsumer, topic)) {
                if (passTime > 5000) {
                    logger.warn("Alibaba-RocketMQ topic : {} is not in whitelist!", topic);
                    lastWhitelistWarnTimes.put(businessConsumer, now);
                }
                continue;
            }
            topicsInWhiteList.put(entry.getKey(), entry.getValue());
        }
    }
    if (topicsInWhiteList.isEmpty()) {
        return null;
    }
    DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer();
    defaultMQPushConsumer.setNamesrvAddr(businessConsumer.getNamesrvAddr());
    defaultMQPushConsumer.setConsumerGroup(Pradar.addClusterTestPrefix(businessConsumer.getConsumerGroup()));
    defaultMQPushConsumer.setConsumeFromWhere(businessConsumer.getConsumeFromWhere());
    defaultMQPushConsumer.setPullThresholdForQueue(businessConsumer.getPullThresholdForQueue());
    defaultMQPushConsumer.setPullBatchSize(businessConsumer.getPullBatchSize());
    defaultMQPushConsumer.setConsumeMessageBatchMaxSize(businessConsumer.getConsumeMessageBatchMaxSize());
    defaultMQPushConsumer.setConsumeThreadMax(businessConsumer.getConsumeThreadMax());
    defaultMQPushConsumer.setConsumeThreadMin(businessConsumer.getConsumeThreadMin());
    String instanceName = getInstanceName();
    if (instanceName != null && !instanceName.equals("DEFAULT")) {
        defaultMQPushConsumer.setInstanceName(Pradar.CLUSTER_TEST_PREFIX + instanceName);
    } else {
        defaultMQPushConsumer.setInstanceName(Pradar.addClusterTestPrefix(businessConsumer.getConsumerGroup() + instanceName));
    }
    try {
        defaultMQPushConsumer.setAdjustThreadPoolNumsThreshold(businessConsumer.getAdjustThreadPoolNumsThreshold());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        defaultMQPushConsumer.setAllocateMessageQueueStrategy(businessConsumer.getAllocateMessageQueueStrategy());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    defaultMQPushConsumer.setConsumeConcurrentlyMaxSpan(businessConsumer.getConsumeConcurrentlyMaxSpan());
    defaultMQPushConsumer.setConsumeTimestamp(businessConsumer.getConsumeTimestamp());
    defaultMQPushConsumer.setMessageModel(businessConsumer.getMessageModel());
    defaultMQPushConsumer.setMessageListener(businessConsumer.getMessageListener());
    defaultMQPushConsumer.setPostSubscriptionWhenPull(businessConsumer.isPostSubscriptionWhenPull());
    defaultMQPushConsumer.setPullInterval(businessConsumer.getPullInterval());
    defaultMQPushConsumer.setSubscription(businessConsumer.getSubscription());
    defaultMQPushConsumer.setUnitMode(businessConsumer.isUnitMode());
    try {
        defaultMQPushConsumer.setClientCallbackExecutorThreads(businessConsumer.getClientCallbackExecutorThreads());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        defaultMQPushConsumer.setClientIP(businessConsumer.getClientIP());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        defaultMQPushConsumer.setHeartbeatBrokerInterval(businessConsumer.getHeartbeatBrokerInterval());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        defaultMQPushConsumer.setPersistConsumerOffsetInterval(businessConsumer.getPersistConsumerOffsetInterval());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        defaultMQPushConsumer.setPollNameServerInteval(businessConsumer.getPollNameServerInteval());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        defaultMQPushConsumer.setUnitName(businessConsumer.getUnitName());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    try {
        /**
         * 高版本才有,低版本无此方法,所以需要做一下此方法的兼容
         */
        defaultMQPushConsumer.setVipChannelEnabled(businessConsumer.isVipChannelEnabled());
    } catch (AbstractMethodError e) {
    } catch (NoSuchMethodError e) {
    }
    MessageListener messageListener = businessConsumer.getMessageListener();
    if (messageListener != null) {
        /**
         * 低版本只有registerMessageListener(com.alibaba.rocketmq.client.consumer.listener.MessageListener)
         */
        if (messageListener instanceof MessageListenerConcurrently) {
            try {
                defaultMQPushConsumer.registerMessageListener((MessageListenerConcurrently) messageListener);
            } catch (NoSuchMethodError e) {
                defaultMQPushConsumer.registerMessageListener(messageListener);
            }
        } else if (messageListener instanceof MessageListenerOrderly) {
            try {
                defaultMQPushConsumer.registerMessageListener((MessageListenerOrderly) messageListener);
            } catch (NoSuchMethodError e) {
                defaultMQPushConsumer.registerMessageListener(messageListener);
            }
        }
    }
    for (Map.Entry<String, SubscriptionData> entry : topicsInWhiteList.entrySet()) {
        SubscriptionData subscriptionData = entry.getValue();
        String topic = entry.getKey();
        String subString = subscriptionData.getSubString();
        String filterClassSource = null;
        try {
            /**
             * 高版本才有这个方法
             */
            filterClassSource = subscriptionData.getFilterClassSource();
        } catch (AbstractMethodError e) {
        } catch (NoSuchMethodError t) {
        }
        if (filterClassSource != null) {
            try {
                defaultMQPushConsumer.subscribe(Pradar.addClusterTestPrefix(topic), subString, filterClassSource);
                logger.info("Alibaba-RocketMQ shadow consumer subscribe topic : {} subString : {} filterClassSource : {}", Pradar.addClusterTestPrefix(topic), subString, filterClassSource);
            } catch (MQClientException e) {
                ErrorReporter.buildError().setErrorType(ErrorTypeEnum.MQ).setErrorCode("MQ-0001").setMessage("Alibaba-RocketMQ消费端subscribe失败!").setDetail("topic:" + topic + " fullClassName:" + subString + " filterClassSource:" + filterClassSource + "||" + e.getMessage()).report();
                logger.error("Alibaba-RocketMQ: subscribe shadow DefaultMQPushConsumer err! topic:{} fullClassName:{} " + "filterClassSource:{}", topic, subString, filterClassSource, e);
                return null;
            }
        } else {
            try {
                defaultMQPushConsumer.subscribe(Pradar.addClusterTestPrefix(topic), subString);
                logger.info("Alibaba-RocketMQ shadow consumer subscribe topic : {} subString : {}", Pradar.addClusterTestPrefix(topic), subString);
            } catch (MQClientException e) {
                ErrorReporter.buildError().setErrorType(ErrorTypeEnum.MQ).setErrorCode("MQ-0001").setMessage("Alibaba-RocketMQ消费端subscribe失败!").setDetail("topic:" + topic + " subExpression:" + subString + "||" + e.getMessage()).report();
                logger.error("Alibaba-RocketMQ: subscribe shadow DefaultMQPushConsumer err! topic:{} subExpression:{}", topic, subString, e);
                return null;
            }
        }
    }
    return defaultMQPushConsumer;
}
Also used : MessageListenerConcurrently(com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentWeakHashMap(com.shulie.instrument.simulator.message.ConcurrentWeakHashMap) MessageListenerOrderly(com.alibaba.rocketmq.client.consumer.listener.MessageListenerOrderly) MessageListener(com.alibaba.rocketmq.client.consumer.listener.MessageListener) DefaultMQPushConsumer(com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException) SubscriptionData(com.alibaba.rocketmq.common.protocol.heartbeat.SubscriptionData) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentWeakHashMap(com.shulie.instrument.simulator.message.ConcurrentWeakHashMap) MQClientException(com.alibaba.rocketmq.client.exception.MQClientException)

Aggregations

ReflectException (com.shulie.instrument.simulator.api.reflect.ReflectException)33 SpanRecord (com.pamirs.pradar.interceptor.SpanRecord)11 PressureMeasureError (com.pamirs.pradar.exception.PressureMeasureError)6 IOException (java.io.IOException)6 Map (java.util.Map)6 JSONObject (com.alibaba.fastjson.JSONObject)4 Request (com.squareup.okhttp.Request)4 HashMap (java.util.HashMap)4 WrapperRequest (com.pamirs.attach.plugin.hessian.common.WrapperRequest)3 MatchConfig (com.pamirs.pradar.internal.config.MatchConfig)3 ProcessControlException (com.shulie.instrument.simulator.api.ProcessControlException)3 Method (java.lang.reflect.Method)3 URL (java.net.URL)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HessianInputFactory (com.caucho.hessian.io.HessianInputFactory)2 HessianSkeleton (com.caucho.hessian.server.HessianSkeleton)2 ExecutionForwardCall (com.pamirs.pradar.internal.adapter.ExecutionForwardCall)2 AMQP (com.rabbitmq.client.AMQP)2 Envelope (com.rabbitmq.client.Envelope)2 Headers (com.squareup.okhttp.Headers)2