Search in sources :

Example 1 with EventResult

use of com.pamirs.pradar.pressurement.agent.listener.EventResult in project LinkAgent by shulieTech.

the class ShadowJobPlugin method onActive.

@Override
public boolean onActive() throws Throwable {
    final ShadowImplListener shaDowImplListener = new ShadowImplListener();
    try {
        XxlJobAdapter xxlJobAdapter = new XxlJobAdapter();
        GlobalConfig.getInstance().addJobAdaptor(xxlJobAdapter.getJobName(), xxlJobAdapter);
    } catch (Throwable t) {
    // ignore
    }
    EventRouter.router().addListener(shaDowImplListener);
    EventRouter.router().addListener(new PradarEventListener() {

        @Override
        public EventResult onEvent(IEvent event) {
            if (event instanceof ClusterTestSwitchOnEvent) {
            } else if (event instanceof ClusterTestSwitchOffEvent) {
                String message = shaDowImplListener.disableAll();
                if ("".equals(message)) {
                    return EventResult.success("shadow-job");
                }
                return EventResult.error("shadow-job", message);
            }
            return EventResult.IGNORE;
        }

        @Override
        public int order() {
            return 6;
        }
    });
    enhanceTemplate.enhance(this, "org.activiti.engine.impl.cmd.AcquireAsyncJobsDueCmd", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod constructor = target.getConstructor("org.activiti.engine.impl.asyncexecutor.AsyncExecutor");
            constructor.addInterceptor(Listeners.of(AcquireAsyncJobsDueCmdInterceptor.class));
        }
    });
    enhanceTemplate.enhance(this, "org.quartz.core.QuartzScheduler", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod constructor = target.getConstructors();
            constructor.addInterceptor(Listeners.of(QuartzInitAdapterInterceptor.class));
        }
    });
    // enhanceTemplate.enhance(this, "com.dangdang.ddframe.job.lite.api.JobScheduler", new EnhanceCallback() {
    // @Override
    // public void doEnhance(InstrumentClass target) {
    // InstrumentMethod constructor = target.getConstructors();
    // constructor.addInterceptor(Listeners.of(ElasticInitAdapterInterceptor.class));
    // }
    // });
    enhanceTemplate.enhance(this, "com.xxl.job.core.executor.XxlJobExecutor", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod declaredMethod = target.getDeclaredMethod("start");
            declaredMethod.addInterceptor(Listeners.of(XxlInitAdapterInterceptor.class));
        }
    });
    // enhanceTemplate.enhance(this, "org.springframework.context.support.ApplicationContextAwareProcessor", new EnhanceCallback() {
    // @Override
    // public void doEnhance(InstrumentClass target) {
    // InstrumentMethod getMethod = target.getDeclaredMethod("invokeAwareInterfaces", "java.lang.Object");
    // getMethod.addInterceptor(Listeners.of(SpringContextInterceptor.class));
    // }
    // });
    enhanceTemplate.enhance(this, "org.springframework.context.support.AbstractRefreshableApplicationContext", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod getMethod = target.getDeclaredMethod("refreshBeanFactory");
            getMethod.addInterceptor(Listeners.of(SpringContextInterceptor.class));
        }
    });
    /**
     * com.github.ltsopensource.spring.tasktracker.JobRunnerHolder
     * lts spring任务注册切点
     */
    enhanceTemplate.enhance(this, "com.github.ltsopensource.spring.tasktracker.JobRunnerHolder", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod getMethod = target.getDeclaredMethod("add", "java.lang.String", "com.github.ltsopensource.tasktracker.runner.JobRunner");
            getMethod.addInterceptor(Listeners.of(JobRunnerHolderAddInterceptor.class));
        }
    });
    /**
     * com.github.ltsopensource.spring.tasktracker.JobRunnerHolder
     * lts spring任务注册切点
     */
    enhanceTemplate.enhance(this, "com.github.ltsopensource.jobtracker.support.JobReceiver", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod getMethod = target.getConstructor("com.github.ltsopensource.jobtracker.domain.JobTrackerAppContext");
            getMethod.addInterceptor(Listeners.of(LtsJobReceiverInterceptor.class));
        }
    });
    /**
     * com.github.ltsopensource.spring.tasktracker.JobRunnerHolder
     * lts taskTracker切点
     */
    enhanceTemplate.enhance(this, "com.github.ltsopensource.tasktracker.TaskTracker", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod constructor = target.getConstructors();
            constructor.addInterceptor(Listeners.of(LtsInitAdapterInterceptor.class));
        }
    });
    // enhanceTemplate.enhance(this, "org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor", new EnhanceCallback() {
    // @Override
    // public void doEnhance(InstrumentClass target) {
    // InstrumentMethod getMethod = target.getDeclaredMethod("processScheduled",
    // "org.springframework.scheduling.annotation.Scheduled", "java.lang.reflect.Method", "java.lang.Object");
    // getMethod.addInterceptor(Listeners.of(ScheduleJobInitAdapterInterceptor.class));
    // }
    // });
    enhanceTemplate.enhance(this, "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            // springmvc 5.x版本
            InstrumentMethod getMethod1 = target.getDeclaredMethod("invokeHandlerMethod", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse", "org.springframework.web.method.HandlerMethod");
            getMethod1.addInterceptor(Listeners.of(RequestMappingHandlerAdapterInterceptor.class));
            // springmvc 4.x版本
            InstrumentMethod getMethod2 = target.getDeclaredMethod("invokeHandleMethod", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse", "org.springframework.web.method.HandlerMethod");
            getMethod2.addInterceptor(Listeners.of(RequestMappingHandlerAdapterInterceptor.class));
        }
    });
    // 新增对 spring bean 的调用拦截获取 BeanFactory,通过拦截器 TransactionInterceptor 获取到 BeanFactory
    enhanceTemplate.enhance(this, "org.springframework.aop.framework.ReflectiveMethodInvocation", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod method = target.getDeclaredMethod("proceed");
            method.addInterceptor(Listeners.of(ReflectiveMethodInvocationProceedInterceptor.class));
        }
    });
    enhanceTemplate.enhance(this, "com.xxl.job.core.handler.impl.MethodJobHandler", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod getMethod = target.getDeclaredMethod("execute", "java.lang.String");
            getMethod.addInterceptor(Listeners.of(MethodJobHandlerExecuteInterceptor.class));
        }
    });
    enhanceTemplate.enhance(this, "com.dangdang.ddframe.job.executor.JobExecutorFactory", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod getMethod = target.getDeclaredMethod("getJobExecutor", "com.dangdang.ddframe.job.api.ElasticJob", "com.dangdang.ddframe.job.executor.JobFacade");
            getMethod.addInterceptor(Listeners.of(JobExecutorFactoryGetJobExecutorInterceptor.class));
        }
    });
    enhanceTemplate.enhance(this, "org.springframework.scheduling.support.ScheduledMethodRunnable", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod getMethod = target.getDeclaredMethod("run");
            getMethod.addInterceptor(Listeners.of(ScheduledMethodRunnableRunInterceptor.class));
        }
    });
    // 
    // enhanceTemplate.enhance(this, "org.springframework.scheduling.quartz.QuartzJobBean", new EnhanceCallback() {
    // @Override
    // public void doEnhance(InstrumentClass target) {
    // InstrumentMethod getMethod = target.getDeclaredMethod("execute", "org.quartz.JobExecutionContext");
    // getMethod.addInterceptor(Listeners.of(QuartzJobBeanExecuteInterceptor.class));
    // }
    // });
    enhanceTemplate.enhance(this, "org.quartz.JobExecutionContext", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            InstrumentMethod constructor = target.getConstructor("org.quartz.Scheduler", "org.quartz.spi.TriggerFiredBundle", "org.quartz.Job");
            constructor.addInterceptor(Listeners.of(JobExecutionContextInterceptor.class));
        }
    });
    // org.quartz.core.JobRunShell.initialize quartz2.x
    enhanceTemplate.enhance(this, "org.quartz.core.JobRunShell", new EnhanceCallback() {

        @Override
        public void doEnhance(InstrumentClass target) {
            // 2.x
            InstrumentMethod declaredMethod_1 = target.getDeclaredMethod("initialize", "org.quartz.core.QuartzScheduler");
            if (declaredMethod_1 != null) {
                declaredMethod_1.addInterceptor(Listeners.of(JobRunShellInitializeInterceptor.class));
            }
            // 1.x
            InstrumentMethod declaredMethod_2 = target.getDeclaredMethod("initialize", "org.quartz.core.QuartzScheduler", "org.quartz.spi.TriggerFiredBundle");
            if (declaredMethod_2 != null) {
                declaredMethod_2.addInterceptor(Listeners.of(JobRunShellInitializeInterceptor_1.class));
            }
        }
    });
    try {
        Class.forName("com.dangdang.ddframe.job.spring.schedule.SpringJobScheduler");
        PradarSpringUtil.onApplicationContextLoad(new Runnable() {

            @Override
            public void run() {
                ElasticJobRegisterUtil.addShadowJob();
            }
        });
    } catch (ClassNotFoundException e) {
    // do nothing
    }
    return true;
}
Also used : IEvent(com.pamirs.pradar.pressurement.agent.event.IEvent) InstrumentClass(com.shulie.instrument.simulator.api.instrument.InstrumentClass) InstrumentMethod(com.shulie.instrument.simulator.api.instrument.InstrumentMethod) ShadowImplListener(com.pamirs.pradar.pressurement.agent.listener.impl.ShadowImplListener) EnhanceCallback(com.shulie.instrument.simulator.api.instrument.EnhanceCallback) PradarEventListener(com.pamirs.pradar.pressurement.agent.listener.PradarEventListener) EventResult(com.pamirs.pradar.pressurement.agent.listener.EventResult) XxlJobAdapter(com.pamirs.attach.plugin.shadowjob.adapter.XxlJobAdapter) ClusterTestSwitchOnEvent(com.pamirs.pradar.pressurement.agent.event.impl.ClusterTestSwitchOnEvent) ClusterTestSwitchOffEvent(com.pamirs.pradar.pressurement.agent.event.impl.ClusterTestSwitchOffEvent)

Example 2 with EventResult

use of com.pamirs.pradar.pressurement.agent.listener.EventResult in project LinkAgent by shulieTech.

the class DataSourceGetConnectionCutoffInterceptor method addListener.

private void addListener() {
    EventRouter.router().addListener(new PradarEventListener() {

        @Override
        public EventResult onEvent(IEvent event) {
            if (!(event instanceof ClusterTestSwitchOffEvent)) {
                return EventResult.IGNORE;
            }
            // 关闭压测数据源
            AtomikosDataSourceBeanWrapUtil.destroy();
            AtomikosNonXADataSourceBeanWrapUtil.destroy();
            return EventResult.success("tomcat-jdbc-plugin");
        }

        @Override
        public int order() {
            return 8;
        }
    }).addListener(new PradarEventListener() {

        @Override
        public EventResult onEvent(IEvent event) {
            if (!(event instanceof ShadowDataSourceConfigModifyEvent)) {
                return EventResult.IGNORE;
            }
            ShadowDataSourceConfigModifyEvent shadowDataSourceConfigModifyEvent = (ShadowDataSourceConfigModifyEvent) event;
            Set<ShadowDatabaseConfig> target = shadowDataSourceConfigModifyEvent.getTarget();
            if (null == target || target.size() == 0) {
                return EventResult.IGNORE;
            }
            for (ShadowDatabaseConfig config : target) {
                Iterator<Map.Entry<DataSourceMeta, AtomikosDataSourceBeanMediaDataSource>> it = AtomikosDataSourceBeanWrapUtil.pressureDataSources.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<DataSourceMeta, AtomikosDataSourceBeanMediaDataSource> entry = it.next();
                    if (StringUtils.equalsIgnoreCase(DbUrlUtils.getKey(config.getUrl(), config.getUsername()), DbUrlUtils.getKey(entry.getKey().getUrl(), entry.getKey().getUsername()))) {
                        AtomikosDataSourceBeanMediaDataSource value = entry.getValue();
                        it.remove();
                        try {
                            value.close();
                            if (logger.isInfoEnabled()) {
                                logger.info("module-atomikos-datasource: destroyed shadow table datasource success. url:{} ,username:{}", entry.getKey().getUrl(), entry.getKey().getUsername());
                            }
                        } catch (Throwable e) {
                            logger.error("module-atomikos-datasource: closed datasource err! target:{}, url:{} username:{}", entry.getKey().getDataSource().hashCode(), entry.getKey().getUrl(), entry.getKey().getUsername(), e);
                        }
                        break;
                    }
                }
                Iterator<Map.Entry<DataSourceMeta, AtomikosNonXADataSourceBeanMediaDataSource>> nonIt = AtomikosNonXADataSourceBeanWrapUtil.pressureDataSources.entrySet().iterator();
                while (nonIt.hasNext()) {
                    Map.Entry<DataSourceMeta, AtomikosNonXADataSourceBeanMediaDataSource> entry = nonIt.next();
                    if (StringUtils.equalsIgnoreCase(config.getUrl(), entry.getKey().getUrl()) && StringUtils.equalsIgnoreCase(config.getUsername(), entry.getKey().getUsername())) {
                        AtomikosNonXADataSourceBeanMediaDataSource value = entry.getValue();
                        nonIt.remove();
                        try {
                            value.close();
                            if (logger.isInfoEnabled()) {
                                logger.info("module-atomikos-datasource: destroyed shadow table datasource success. url:{} ,username:{}", entry.getKey().getUrl(), entry.getKey().getUsername());
                            }
                        } catch (Throwable e) {
                            logger.error("module-atomikos-datasource: closed datasource err! target:{}, url:{} username:{}", entry.getKey().getDataSource().hashCode(), entry.getKey().getUrl(), entry.getKey().getUsername(), e);
                        }
                        break;
                    }
                }
            }
            return EventResult.success("module-atomikos-datasource: destroyed shadow table datasource success.");
        }

        @Override
        public int order() {
            return 2;
        }
    });
}
Also used : AtomikosDataSourceBeanMediaDataSource(com.pamirs.attach.plugin.atomikos.utils.AtomikosDataSourceBeanMediaDataSource) Set(java.util.Set) IEvent(com.pamirs.pradar.pressurement.agent.event.IEvent) ShadowDataSourceConfigModifyEvent(com.pamirs.pradar.pressurement.agent.event.impl.ShadowDataSourceConfigModifyEvent) ShadowDatabaseConfig(com.pamirs.pradar.internal.config.ShadowDatabaseConfig) DataSourceMeta(com.pamirs.pradar.pressurement.agent.shared.service.DataSourceMeta) AtomikosNonXADataSourceBeanMediaDataSource(com.pamirs.attach.plugin.atomikos.utils.AtomikosNonXADataSourceBeanMediaDataSource) PradarEventListener(com.pamirs.pradar.pressurement.agent.listener.PradarEventListener) EventResult(com.pamirs.pradar.pressurement.agent.listener.EventResult) Iterator(java.util.Iterator) Map(java.util.Map) ClusterTestSwitchOffEvent(com.pamirs.pradar.pressurement.agent.event.impl.ClusterTestSwitchOffEvent)

Example 3 with EventResult

use of com.pamirs.pradar.pressurement.agent.listener.EventResult in project LinkAgent by shulieTech.

the class MockPlugin method onActive.

@Override
public boolean onActive() throws Throwable {
    try {
        this.watchers = new HashMap<String, EventWatcher>();
        EventRouter.router().addListener(new PradarEventListener() {

            @Override
            public EventResult onEvent(IEvent event) {
                if (event instanceof MockConfigAddEvent) {
                    Set<MockConfig> mockConfigs = ((MockConfigAddEvent) event).getTarget();
                    Set<MockConfig> newConfigs = new HashSet<MockConfig>();
                    for (MockConfig mockConfig : mockConfigs) {
                        if (watchers.containsKey(mockConfig.getKey())) {
                            continue;
                        }
                        newConfigs.add(mockConfig);
                    }
                    Map<String, Set<MockConfig>> map = groupByClass(newConfigs);
                    watchers.putAll(enhanceClassMethod(map));
                } else if (event instanceof MockConfigRemoveEvent) {
                    Set<MockConfig> mockConfigs = ((MockConfigRemoveEvent) event).getTarget();
                    for (MockConfig mockConfig : mockConfigs) {
                        EventWatcher watcher = watchers.remove(mockConfig.getKey());
                        if (watcher != null) {
                            if (LOGGER.isInfoEnabled()) {
                                LOGGER.info("Remove mock config interceptor {}", mockConfig.getKey());
                            }
                            watcher.onUnWatched();
                        }
                    }
                } else if (event instanceof MockConfigModifyEvent) {
                    Set<MockConfig> mockConfigs = ((MockConfigModifyEvent) event).getTarget();
                    for (MockConfig mockConfig : mockConfigs) {
                        EventWatcher watcher = watchers.remove(mockConfig.getKey());
                        if (watcher != null) {
                            if (LOGGER.isInfoEnabled()) {
                                LOGGER.info("Modify mock config pre remove interceptor  {}", mockConfig.getKey());
                            }
                            watcher.onUnWatched();
                        }
                    }
                    Map<String, Set<MockConfig>> map = groupByClass(mockConfigs);
                    watchers.putAll(enhanceClassMethod(map));
                } else {
                    return EventResult.IGNORE;
                }
                return EventResult.success("Mock config update successful.");
            }

            @Override
            public int order() {
                return -1;
            }
        });
        Set<MockConfig> mockConfigs = new HashSet<MockConfig>();
        for (MockConfig mockConfig : GlobalConfig.getInstance().getMockConfigs()) {
            if (this.watchers.containsKey(mockConfig.getKey())) {
                continue;
            }
            mockConfigs.add(mockConfig);
        }
        if (CollectionUtils.isNotEmpty(mockConfigs)) {
            Map<String, Set<MockConfig>> map = groupByClass(mockConfigs);
            watchers.putAll(enhanceClassMethod(map));
        }
    } catch (Throwable e) {
        LOGGER.warn("挡板增强失败", e);
        ErrorReporter.buildError().setErrorType(ErrorTypeEnum.LinkGuardEnhance).setErrorCode("mock-enhance-0001").setMessage("挡板增强失败!").setDetail("挡板增强失败:" + e.getMessage()).closePradar(ConfigNames.LINK_GUARD_CONFIG).report();
        throw e;
    }
    return true;
}
Also used : IEvent(com.pamirs.pradar.pressurement.agent.event.IEvent) MockConfigAddEvent(com.pamirs.pradar.pressurement.agent.event.impl.MockConfigAddEvent) EventWatcher(com.shulie.instrument.simulator.api.listener.ext.EventWatcher) PradarEventListener(com.pamirs.pradar.pressurement.agent.listener.PradarEventListener) EventResult(com.pamirs.pradar.pressurement.agent.listener.EventResult) MockConfigRemoveEvent(com.pamirs.pradar.pressurement.agent.event.impl.MockConfigRemoveEvent) MockConfig(com.pamirs.pradar.internal.config.MockConfig) MockConfigModifyEvent(com.pamirs.pradar.pressurement.agent.event.impl.MockConfigModifyEvent)

Example 4 with EventResult

use of com.pamirs.pradar.pressurement.agent.listener.EventResult in project LinkAgent by shulieTech.

the class ApacheHbasePlugin method initEventListener.

void initEventListener() {
    dynamicEventListener = new PradarEventListener() {

        @Override
        public EventResult onEvent(IEvent event) {
            if (!ShadowHbaseDynamicEvent.class.isAssignableFrom(event.getClass())) {
                return EventResult.IGNORE;
            }
            if (!GlobalConfig.getInstance().isShadowHbaseServer()) {
                return EventResult.IGNORE;
            }
            try {
                MediatorConnection.dynamic((ShadowHbaseConfig) event.getTarget());
            } catch (Exception e) {
            }
            return EventResult.success(event.getTarget());
        }

        @Override
        public int order() {
            return 10;
        }
    };
    EventRouter.router().addListener(dynamicEventListener);
    disableEventListener = new PradarEventListener() {

        @Override
        public EventResult onEvent(IEvent event) {
            if (!ShadowHbaseDisableEvent.class.isAssignableFrom(event.getClass())) {
                return EventResult.IGNORE;
            }
            try {
                MediatorConnection.disable((String) event.getTarget());
            } catch (Exception e) {
            }
            return EventResult.success(event.getTarget());
        }

        @Override
        public int order() {
            return 11;
        }
    };
    EventRouter.router().addListener(disableEventListener);
}
Also used : PradarEventListener(com.pamirs.pradar.pressurement.agent.listener.PradarEventListener) EventResult(com.pamirs.pradar.pressurement.agent.listener.EventResult) IEvent(com.pamirs.pradar.pressurement.agent.event.IEvent) ShadowHbaseConfig(com.pamirs.pradar.internal.config.ShadowHbaseConfig)

Aggregations

IEvent (com.pamirs.pradar.pressurement.agent.event.IEvent)4 EventResult (com.pamirs.pradar.pressurement.agent.listener.EventResult)4 PradarEventListener (com.pamirs.pradar.pressurement.agent.listener.PradarEventListener)4 ClusterTestSwitchOffEvent (com.pamirs.pradar.pressurement.agent.event.impl.ClusterTestSwitchOffEvent)2 AtomikosDataSourceBeanMediaDataSource (com.pamirs.attach.plugin.atomikos.utils.AtomikosDataSourceBeanMediaDataSource)1 AtomikosNonXADataSourceBeanMediaDataSource (com.pamirs.attach.plugin.atomikos.utils.AtomikosNonXADataSourceBeanMediaDataSource)1 XxlJobAdapter (com.pamirs.attach.plugin.shadowjob.adapter.XxlJobAdapter)1 MockConfig (com.pamirs.pradar.internal.config.MockConfig)1 ShadowDatabaseConfig (com.pamirs.pradar.internal.config.ShadowDatabaseConfig)1 ShadowHbaseConfig (com.pamirs.pradar.internal.config.ShadowHbaseConfig)1 ClusterTestSwitchOnEvent (com.pamirs.pradar.pressurement.agent.event.impl.ClusterTestSwitchOnEvent)1 MockConfigAddEvent (com.pamirs.pradar.pressurement.agent.event.impl.MockConfigAddEvent)1 MockConfigModifyEvent (com.pamirs.pradar.pressurement.agent.event.impl.MockConfigModifyEvent)1 MockConfigRemoveEvent (com.pamirs.pradar.pressurement.agent.event.impl.MockConfigRemoveEvent)1 ShadowDataSourceConfigModifyEvent (com.pamirs.pradar.pressurement.agent.event.impl.ShadowDataSourceConfigModifyEvent)1 ShadowImplListener (com.pamirs.pradar.pressurement.agent.listener.impl.ShadowImplListener)1 DataSourceMeta (com.pamirs.pradar.pressurement.agent.shared.service.DataSourceMeta)1 EnhanceCallback (com.shulie.instrument.simulator.api.instrument.EnhanceCallback)1 InstrumentClass (com.shulie.instrument.simulator.api.instrument.InstrumentClass)1 InstrumentMethod (com.shulie.instrument.simulator.api.instrument.InstrumentMethod)1