Search in sources :

Example 11 with ReflectException

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

the class DubboConsumerInterceptor method beforeLast.

@Override
public void beforeLast(Advice advice) throws ProcessControlException {
    final RpcInvocation invocation = (RpcInvocation) advice.getParameterArray()[0];
    String interfaceName = getInterfaceName(invocation);
    String methodName = invocation.getMethodName();
    MatchConfig config = ClusterTestUtils.rpcClusterTest(interfaceName, methodName);
    invocation.setAttachment(PradarService.PRADAR_WHITE_LIST_CHECK, String.valueOf(config.isSuccess()));
    config.addArgs("args", advice.getParameterArray());
    config.addArgs("url", interfaceName.concat("#").concat(methodName));
    config.addArgs("isInterface", Boolean.TRUE);
    config.addArgs("class", interfaceName);
    config.addArgs("method", methodName);
    config.addArgs("invocation", invocation);
    if (isShentongEvent(interfaceName)) {
        config.addArgs(PradarService.PRADAR_WHITE_LIST_CHECK, "true");
    }
    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) {
            try {
                // for 2.8.4
                return Reflect.on("org.apache.dubbo.rpc.RpcResult").create(param).get();
            } catch (Exception e) {
                if (logger.isInfoEnabled()) {
                    logger.info("find dubbo 2.8.4 class org.apache.dubbo.rpc.RpcResult fail, find others!", e);
                }
            // 
            }
            try {
                Reflect reflect = Reflect.on("org.apache.dubbo.rpc.AsyncRpcResult");
                try {
                    // for 2.7.5
                    java.util.concurrent.CompletableFuture<AppResponse> future = new java.util.concurrent.CompletableFuture<AppResponse>();
                    future.complete(new AppResponse(param));
                    Reflect result = reflect.create(future, invocation);
                    return result.get();
                } catch (ReflectException e) {
                    // for 2.7.3
                    Reflect result = reflect.create(invocation);
                    return result.get();
                }
            } catch (Exception e) {
                logger.error("fail to load dubbo 2.7.x class org.apache.dubbo.rpc.AsyncRpcResult", e);
                throw new ReflectException("fail to load dubbo 2.7.x class org.apache.dubbo.rpc.AsyncRpcResult", e);
            }
        }
    });
}
Also used : MatchConfig(com.pamirs.pradar.internal.config.MatchConfig) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException) PradarException(com.pamirs.pradar.exception.PradarException) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException) ProcessControlException(com.shulie.instrument.simulator.api.ProcessControlException) JsonMockStrategy(com.pamirs.pradar.pressurement.mock.JsonMockStrategy) Reflect(com.shulie.instrument.simulator.api.reflect.Reflect) ExecutionCall(com.pamirs.pradar.internal.config.ExecutionCall)

Example 12 with ReflectException

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

the class RestRequestIndexRename method reindex0.

@Override
public List<String> reindex0(Object target) {
    Request req = (Request) target;
    String endpoint = req.getEndpoint();
    String start = "";
    if (StringUtils.startsWith(endpoint, "/")) {
        start += '/';
        endpoint = endpoint.substring(1);
    }
    String end = "";
    String index = "";
    final int indexOfSlash = StringUtils.indexOf(endpoint, '/');
    if (indexOfSlash != -1) {
        index = StringUtils.substring(endpoint, 0, indexOfSlash);
        end = StringUtils.substring(endpoint, indexOfSlash);
    } else {
        index = endpoint;
    }
    if (StringUtils.startsWith(index, "_")) {
        return Collections.EMPTY_LIST;
    }
    if (!Pradar.isClusterTestPrefix(index)) {
        index = Pradar.addClusterTestPrefixLower(index);
        String newEndpoint = start + index + end;
        try {
            Reflect.on(req).set("endpoint", newEndpoint);
        } catch (ReflectException e) {
        }
    }
    return Arrays.asList(index);
}
Also used : Request(org.elasticsearch.client.Request) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException)

Example 13 with ReflectException

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

the class CloseIndexRequestIndexRename0 method reindex0.

@Override
public List<String> reindex0(Object target) {
    CloseIndexRequest req = (CloseIndexRequest) target;
    String[] indexes = req.indices();
    for (int i = 0, len = indexes.length; i < len; i++) {
        String index = indexes[i];
        /**
         * 如果在白名单中则不允许写
         */
        if (GlobalConfig.getInstance().getSearchWhiteList().contains(index)) {
            throw new PressureMeasureError("Cluster Test request can't refresh business index ! " + index);
        }
        if (!Pradar.isClusterTestPrefix(index)) {
            index = Pradar.addClusterTestPrefixLower(index);
            indexes[i] = index;
        }
    }
    try {
        Reflect.on(req).set("indices", indexes);
    } catch (ReflectException e) {
        throw new PressureMeasureError("can't found field indices from " + CloseIndexRequest.class.getName());
    }
    return Arrays.asList(indexes);
}
Also used : CloseIndexRequest(org.elasticsearch.client.indices.CloseIndexRequest) PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException)

Example 14 with ReflectException

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

the class AnalyzeRequestIndexRename0 method reindex0.

@Override
public List<String> reindex0(Object target) {
    AnalyzeRequest req = (AnalyzeRequest) target;
    String index = req.index();
    /**
     * 如果在白名单中则不允许写
     */
    if (GlobalConfig.getInstance().getSearchWhiteList().contains(index)) {
        return Arrays.asList(index);
    }
    if (!Pradar.isClusterTestPrefix(index)) {
        index = Pradar.addClusterTestPrefixLower(index);
    }
    try {
        Reflect.on(req).set("index", index);
    } catch (ReflectException e) {
        throw new PressureMeasureError("can't found field index from " + AnalyzeRequest.class.getName());
    }
    return Arrays.asList(index);
}
Also used : PressureMeasureError(com.pamirs.pradar.exception.PressureMeasureError) AnalyzeRequest(org.elasticsearch.client.indices.AnalyzeRequest) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException)

Example 15 with ReflectException

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

the class KafkaListenerContainerInterceptor method doBefore.

@Override
public void doBefore(Advice advice) {
    if (PradarSpringUtil.getBeanFactory() == null) {
        if (!tryRefreshBeanFactory(advice.getTarget())) {
            logger.warn("can't init shadow consumer because spring beanFactory is null, plz init spring context!");
            return;
        }
    }
    Object thisObj = advice.getTarget();
    /**
     * 如果已经初始化过了,则忽略
     */
    if (ConfigCache.isInited(thisObj)) {
        return;
    }
    Object externalContainer = null;
    try {
        externalContainer = Reflect.on(thisObj).get("this$0");
    } catch (ReflectException e) {
        logger.warn("SIMULATOR: kafka consumer register error. can't found field this$0. {}", thisObj.getClass().getName());
        return;
    }
    if (externalContainer == null) {
        logger.warn("SIMULATOR: kafka consumer register error. field this$0 is null. {}", thisObj.getClass().getName());
        return;
    }
    if (externalContainer instanceof KafkaMessageListenerContainer && Pradar.isClusterTestPrefix(((KafkaMessageListenerContainer) externalContainer).getBeanName())) {
        return;
    }
    Object container = null;
    try {
        container = Reflect.on(externalContainer).get(KafkaConstants.REFLECT_FIELD_THIS_OR_PARENT_CONTAINER);
    } catch (ReflectException e) {
    }
    if (container == null) {
        try {
            container = Reflect.on(externalContainer).get(KafkaConstants.REFLECT_FIELD_CONTAINER);
        } catch (ReflectException e) {
        }
    }
    if (container == null) {
        container = externalContainer;
        logger.warn("SIMULATOR: kafka consumer register error. field {} is null. {}", KafkaConstants.REFLECT_FIELD_CONTAINER, externalContainer.getClass().getName());
    // return;
    }
    Object containerProperties = null;
    try {
        containerProperties = Reflect.on(container).get(KafkaConstants.REFLECT_FIELD_CONTAINER_PROPERTIES);
    } catch (ReflectException e) {
    }
    if (containerProperties == null) {
        try {
            containerProperties = Reflect.on(container).call(KafkaConstants.REFLECT_METHOD_GET_CONTAINER_PROPERTIES).get();
        } catch (ReflectException e) {
        }
    }
    if (containerProperties == null) {
        logger.warn("SIMULATOR: kafka consumer register error. got a null containerProperties from {}.", container.getClass().getName());
        return;
    }
    String groupId = null;
    try {
        groupId = Reflect.on(containerProperties).call(KafkaConstants.REFLECT_METHOD_GET_GROUP_ID).get();
    } catch (ReflectException e) {
    }
    /**
     * 如果是影子 topic,则不需要再创建对应的消费者
     */
    List<String> topicList = getShadowTopics(containerProperties, groupId);
    if (CollectionUtils.isEmpty(topicList)) {
        logger.warn("SIMULATOR: shadow kafka consumer config not found  for groupId : {} containerProperties : {}", groupId, containerProperties);
        return;
    }
    Object messageListener = null;
    try {
        messageListener = Reflect.on(containerProperties).call(KafkaConstants.REFLECT_METHOD_GET_MESSAGE_LISTENER).get();
    } catch (ReflectException e) {
    }
    if (null == messageListener) {
        logger.warn("SIMULATOR: kafka consumer register error. got a null messageListener from {}.", containerProperties);
        return;
    }
    Object ptObject = null;
    try {
        ptObject = Reflect.on(containerProperties.getClass()).create(new Object[] { topicList.toArray(new String[0]) }).get();
    } catch (ReflectException e) {
    }
    if (null == ptObject) {
        logger.warn("SIMULATOR: kafka consumer register error. got a null messageListener from {}.", containerProperties);
        return;
    }
    // 设置业务Consumer属性
    setContainerProperties(ptObject, containerProperties);
    try {
        Reflect.on(ptObject).call(KafkaConstants.REFLECT_METHOD_SET_MESSAGE_LISTENER, messageListener);
    } catch (ReflectException e) {
    }
    final DefaultListableBeanFactory defaultListableBeanFactory = PradarSpringUtil.getBeanFactory();
    // 获取bean工厂并转换为DefaultListableBeanFactory
    final String beanName = toShadowTopicString(topicList) + groupId + container.getClass().getSimpleName();
    int concurrency = 0;
    try {
        concurrency = Reflect.on(container).call(KafkaConstants.REFLECT_METHOD_GET_CONCURRENCY).get();
    } catch (ReflectException e) {
        // 低版本spring-kafka无法获取到该值,TODO 考虑是否通过配置的方式
        concurrency = 1;
    }
    Object consumerFactory = null;
    try {
        consumerFactory = Reflect.on(container).get(KafkaConstants.REFLECT_FIELD_CONSUMER_FACTORY);
    } catch (ReflectException e) {
    }
    if (consumerFactory == null) {
        logger.warn("SIMULATOR: kafka consumer register error. got a null consumerFactory from {}.", container);
        return;
    }
    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(ConcurrentMessageListenerContainer.class).setInitMethodName("doStart").addConstructorArgValue(consumerFactory).addConstructorArgValue(ptObject).addPropertyValue("concurrency", concurrency);
    // 注册bean
    defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinitionBuilder.getBeanDefinition());
    saveTopicGroupInfo(topicList, groupId, beanName, System.identityHashCode(thisObj));
    /**
     * 添加释放资源,会在模块卸载的时候调用
     */
    moduleController.addReleaseResource(new ReleaseResource<Object>(null) {

        @Override
        public void release() {
            Object bean = defaultListableBeanFactory.getBean(beanName);
            if (bean != null) {
                try {
                    Reflect.on(bean).call(KafkaConstants.REFLECT_METHOD_STOP);
                } catch (ReflectException e) {
                }
            }
            defaultListableBeanFactory.removeBeanDefinition(beanName);
        }
    });
    PradarSpringUtil.getBeanFactory().getBean(beanName);
    ConfigCache.setInited(advice.getTarget());
    if (logger.isInfoEnabled()) {
        logger.info("SIMULATOR: kafka consumer register successful!. groupId : {}, topic : {}", Pradar.addClusterTestPrefix(groupId), topicList);
    }
}
Also used : BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) DefaultListableBeanFactory(org.springframework.beans.factory.support.DefaultListableBeanFactory) KafkaMessageListenerContainer(org.springframework.kafka.listener.KafkaMessageListenerContainer) ReflectException(com.shulie.instrument.simulator.api.reflect.ReflectException)

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