public interface PluginActivator {
// 让插件本身判断是否要启动
boolean enabled(PluginContext context);
public void init(PluginContext context) throws Exception;
/**
* Before calling this method, the {@link PluginState} is
* {@link PluginState#STARTING}, after calling, the {@link PluginState} is
* {@link PluginState#ACTIVE}
*
* @param context
*/
public void start(PluginContext context) throws Exception;
/**
* Before calling this method, the {@link PluginState} is
* {@link PluginState#STOPPING}, after calling, the {@link PluginState} is
* {@link PluginState#RESOLVED}
*
* @param context
*/
public void stop(PluginContext context) throws Exception;
}
one-java-agent
目标
插件系统
插件如果希望感知生命周期,可以实现
PluginActivator接口:传统的java agent
插件目录下面放一个
plugin.properties,并且放上原生的agent jar文件。例如:
则 one java agent会启动这个
demo-agent。配置注入
One Java Agent很方便可以注入配置到插件里。
plugin.properties文件里-D参数配置,比如插件aaa,则可以配置为-Doneagent.plugin.aaa.key1=value1然后可以通过
PluginContext#getProperty("key1")来获取值。迁移
-javaagent方式和 one java agent形式?比如一个传统的Agent,它会有一个包含 premain 函数的类:
把上面的Agent做同时支持非常简单,先把原来的初始化逻辑抽取为
init函数,把原来的初始化逻辑移到里面:然后按上面的文档,编写一个
MyActivator,在init函数里调用原来的MyAgent.init(args, instrumentation);函数在MyActivator init函数里,args可以通过
配置注入一节注入,或者通过自定义的方式来获取。这样子,Agent就可以同时支持传统方式和One Java Agent方式启动。
插件之间类共享
参考
fastjson-demo-plugin,它在plugin.properties里配置了exportPackages=com.alibaba.fastjson。当其它插件想引用共享的fastjson时,需要在
plugin.properties里配置:插件注册自定义 ClassLoaderHandler
当插件增强应用ClassLoader里加载的类时,会出现一个问题,当调用插件自己的类时,会加载不到。因此提供一个
ClassLoaderHandler机制,插件方可以自行注册处理自己package下的类加载。参考
dubbo-test-plugin里:在
MonitorFilter里调用了在 plugin里加载的com.test.dubbo.RpcUtils。配置define 工具类
在增强代码之后,如果把逻辑全部写到
@Instrument里:@Instrument里插入的代码缺少行号那么可以定义一些工具类,在运行时动态 define 到应用的 ClassLoader 里。
参考:
dubbo-test-instrument/src/main/resources/instrument.properties里define配置。编译开发
mvn clean installbytekitmvn clean package -DskipTests && mvn testmvn clean package -P local -DskipTests会打包后安装最新到本地~/oneoneagent目录下