提交 c64ce242 编写于 作者: wu-sheng's avatar wu-sheng

1.完成类构造函数、方法拦截的主要代码。#36

上级 670b5f8f
......@@ -2,6 +2,7 @@ package com.ai.cloud.skywalking.plugin;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
......@@ -18,23 +19,23 @@ public class PluginBootstrap {
}
PluginResourcesResolver resolver = new PluginResourcesResolver();
Enumeration<URL> resources = resolver.getResources();
List<URL> resources = resolver.getResources();
if (resources == null || !resources.hasMoreElements()) {
if (resources == null || resources.size() == 0) {
logger.info("no plugin files (skywalking-plugin.properties) found, continue to start application.");
return;
}
while (resources.hasMoreElements()) {
URL pluginUrl = resources.nextElement();
for (URL pluginUrl : resources) {
try {
PluginCfg.CFG.load(pluginUrl.openStream());
} catch (Throwable t) {
logger.error("plugin [{}] init failure.", pluginUrl, t);
}
}
EnhanceClazz4Interceptor enhanceClazz4Interceptor = new EnhanceClazz4Interceptor();
enhanceClazz4Interceptor.enhance();
}
}
......@@ -2,7 +2,9 @@ package com.ai.cloud.skywalking.plugin;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
......@@ -10,10 +12,11 @@ import org.apache.logging.log4j.Logger;
public class PluginResourcesResolver {
private static Logger logger = LogManager.getLogger(PluginResourcesResolver.class);
public Enumeration<URL> getResources(){
public List<URL> getResources(){
List<URL> cfgUrlPaths = new ArrayList<URL>();
Enumeration<URL> urls;
try {
urls = getDefaultClassLoader().getResources("skywalking-plugin.properties");
urls = getDefaultClassLoader().getResources("skywalking-plugin.def");
if(!urls.hasMoreElements()){
logger.info("no plugin files (skywalking-plugin.properties) found");
......@@ -21,10 +24,11 @@ public class PluginResourcesResolver {
while(urls.hasMoreElements()){
URL pluginUrl = urls.nextElement();
cfgUrlPaths.add(pluginUrl);
logger.info("find skywalking plugin define in {}", pluginUrl);
}
return urls;
return cfgUrlPaths;
} catch (IOException e) {
logger.error("read resources failure.", e);
}
......
package com.ai.cloud.skywalking.plugin;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
......@@ -16,7 +19,9 @@ public class TracingBootstrap {
private TracingBootstrap() {
}
public static void main(String[] args) {
public static void main(String[] args) throws IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException, ClassNotFoundException {
if (args.length == 0) {
throw new RuntimeException(
"bootstrap failure. need args[0] to be main class.");
......@@ -29,5 +34,10 @@ public class TracingBootstrap {
logger.error("PluginBootstrap start failure.", t);
}
String[] newArgs = Arrays.copyOfRange(args, 1, args.length);
Class.forName(args[0]).getMethod("main", String[].class)
.invoke(null, new Object[]{newArgs});
}
}
package com.ai.cloud.skywalking.plugin.interceptor;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.This;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClassConstructorInterceptor {
private static Logger logger = LogManager
.getLogger(ClassConstructorInterceptor.class);
private IAroundInterceptor interceptor;
public ClassConstructorInterceptor(IAroundInterceptor interceptor) {
this.interceptor = interceptor;
}
@RuntimeType
public void intercept(
@This Object obj,
@FieldProxy(EnhanceClazz4Interceptor.contextAttrName) FieldSetter accessor,
@AllArguments Object[] allArguments) {
try {
accessor.setValue(new EnhancedClassInstanceContext());
ConstructorContext interceptorContext = new ConstructorContext(
allArguments);
interceptor.onConstruct(null, interceptorContext);
} catch (Throwable t) {
logger.error("ClassConstructorInterceptor failue.", t);
}
}
public interface FieldGetter {
Object getValue();
}
public interface FieldSetter {
void setValue(Object value);
}
}
package com.ai.cloud.skywalking.plugin.interceptor;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.FieldValue;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.implementation.bind.annotation.This;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* 类方法拦截、控制器
*
* @author wusheng
*
*/
public class ClassMethodInterceptor {
private static Logger logger = LogManager
.getLogger(ClassMethodInterceptor.class);
private IAroundInterceptor interceptor;
public ClassMethodInterceptor(IAroundInterceptor interceptor) {
this.interceptor = interceptor;
}
@RuntimeType
public Object intercept(
@This Object obj,
@AllArguments Object[] allArguments,
@Origin Method method,
@SuperCall Callable<?> zuper,
@FieldValue(EnhanceClazz4Interceptor.contextAttrName) EnhancedClassInstanceContext instanceContext)
throws Exception {
InterceptorContext interceptorContext = new InterceptorContext(obj,
method.getName(), allArguments);
try {
interceptor.beforeMethod(instanceContext, interceptorContext);
} catch (Throwable t) {
logger.error("class[{}] before method[{}] intercept failue:{}",
obj.getClass(), method.getName(), t.getMessage(), t);
}
try {
return zuper.call();
} finally {
try {
interceptor.afterMethod(instanceContext, interceptorContext);
} catch (Throwable t) {
logger.error("class[{}] after method[{}] intercept failue:{}",
obj.getClass(), method.getName(), t.getMessage(), t);
}
}
}
}
package com.ai.cloud.skywalking.plugin.interceptor;
public class ConstructorContext {
private Object[] allArguments;
ConstructorContext(Object[] allArguments) {
this.allArguments = allArguments;
}
public Object[] allArguments(){
return this.allArguments;
}
}
package com.ai.cloud.skywalking.plugin.interceptor;
import static net.bytebuddy.matcher.ElementMatchers.isConstructor;
import static net.bytebuddy.matcher.ElementMatchers.named;
import java.util.Set;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import net.bytebuddy.pool.TypePool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.ai.cloud.skywalking.plugin.PluginCfg;
import com.ai.cloud.skywalking.plugin.interceptor.ClassConstructorInterceptor.FieldGetter;
import com.ai.cloud.skywalking.plugin.interceptor.ClassConstructorInterceptor.FieldSetter;
public class EnhanceClazz4Interceptor {
private static Logger logger = LogManager
......@@ -18,6 +28,8 @@ public class EnhanceClazz4Interceptor {
private TypePool typePool;
public static final String contextAttrName = "_$EnhancedClassInstanceContext";
public EnhanceClazz4Interceptor() {
typePool = TypePool.Default.ofClassPath();
}
......@@ -36,29 +48,79 @@ public class EnhanceClazz4Interceptor {
}
}
private void enhance0(String interceptorDefineClassName) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
InterceptorDefine define = (InterceptorDefine)Class.forName(interceptorDefineClassName).newInstance();
private void enhance0(String interceptorDefineClassName)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
logger.debug("prepare to enhance class by {}.",
interceptorDefineClassName);
InterceptorDefine define = (InterceptorDefine) Class.forName(
interceptorDefineClassName).newInstance();
String enhanceOriginClassName = define.getBeInterceptedClassName();
logger.debug("prepare to enhance class {} by {}.",
enhanceOriginClassName, interceptorDefineClassName);
/**
* rename origin class <br/>
* add '$$Origin' at the end of be enhanced classname <br/>
* such as: class com.ai.cloud.TestClass to class com.ai.cloud.TestClass$$Origin
* such as: class com.ai.cloud.TestClass to class
* com.ai.cloud.TestClass$$Origin
*/
new ByteBuddy()
String renameClassName = enhanceOriginClassName + "$$Origin";
Class<?> originClass = new ByteBuddy()
.redefine(typePool.describe(enhanceOriginClassName).resolve(),
ClassFileLocator.ForClassLoader.ofClassPath())
.name(enhanceOriginClassName + "$$Origin")
.name(renameClassName)
.make()
.load(ClassLoader.getSystemClassLoader(),
ClassLoadingStrategy.Default.INJECTION).getLoaded();
/**
* TODO: need to confirm
* define class as origin class name. and inject to classloader. <br/>
* to classloader. <br/>
*
* new class need:<br/>
* 1.add field '_$EnhancedClassInstanceContext' of type EnhancedClassInstanceContext <br/>
* 2.intercept constructor and method if required by interceptorDefineClass. use '@FieldValue' get '_$EnhancedClassInstanceContext' ref<br/>
* 1.add field '_$EnhancedClassInstanceContext' of type
* EnhancedClassInstanceContext <br/>
*
* 2.intercept constructor and method if required by
* interceptorDefineClass. use '@FieldValue' get
* '_$EnhancedClassInstanceContext' ref<br/>
*/
IAroundInterceptor interceptor = define.instance();
DynamicType.Builder<?> newClassBuilder = new ByteBuddy().subclass(
originClass, ConstructorStrategy.Default.IMITATE_SUPER_CLASS);
newClassBuilder = newClassBuilder
.defineField(contextAttrName,
EnhancedClassInstanceContext.class)
.constructor(isConstructor())
.intercept(
SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(
new ClassConstructorInterceptor(interceptor))
.appendParameterBinder(
FieldProxy.Binder.install(
FieldGetter.class,
FieldSetter.class))));
String[] methodNameList = define.getBeInterceptedMethods();
for (String methodName : methodNameList) {
newClassBuilder = newClassBuilder.method(named(methodName))
.intercept(
MethodDelegation.to(new ClassMethodInterceptor(
interceptor)));
}
/**
* naming class as origin class name, make and load class to
* classloader.
*/
newClassBuilder
.name(enhanceOriginClassName)
.make()
.load(ClassLoader.getSystemClassLoader(),
ClassLoadingStrategy.Default.INJECTION).getLoaded();
logger.debug("enhance class {} by {} completely.",
enhanceOriginClassName, interceptorDefineClassName);
}
}
package com.ai.cloud.skywalking.plugin.interceptor;
public interface IAroundInterceptor {
public void onConstruct(EnhancedClassInstanceContext context);
public void onConstruct(EnhancedClassInstanceContext context, ConstructorContext interceptorContext);
public void beforeMethod(EnhancedClassInstanceContext context);
public void beforeMethod(EnhancedClassInstanceContext context, InterceptorContext interceptorContext);
public void afterMethod(EnhancedClassInstanceContext context);
public void afterMethod(EnhancedClassInstanceContext context, InterceptorContext interceptorContext);
}
package com.ai.cloud.skywalking.plugin.interceptor;
public class InterceptorContext {
private Object objInst;
private String methodName;
private Object[] allArguments;
InterceptorContext(Object objInst, String methodName, Object[] allArguments) {
this.objInst = objInst;
this.methodName = methodName;
this.allArguments = allArguments;
}
public Object[] allArguments(){
return this.allArguments;
}
public Object inst(){
return objInst;
}
}
......@@ -5,6 +5,7 @@ import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.pool.TypePool;
......@@ -25,7 +26,7 @@ public class SimulateMain {
ClassLoadingStrategy.Default.INJECTION).getLoaded();
TestClass t22 = (TestClass) (new ByteBuddy()
.subclass(newClazz)
.subclass(newClazz, ConstructorStrategy.Default.IMITATE_SUPER_CLASS)
.method(isMethod())
.intercept(MethodDelegation.to(new MethodInterceptor()))
.constructor(isConstructor())
......
package test.ai.cloud.plugin;
public class BeInterceptedClass {
public BeInterceptedClass(){
System.out.println("BeInterceptedClass constructor.");
}
public void printabc(){
System.out.println("printabc");
}
}
package test.ai.cloud.plugin;
import java.lang.reflect.InvocationTargetException;
import org.junit.Test;
import com.ai.cloud.skywalking.plugin.TracingBootstrap;
public class PluginMainTest {
@Test
public void testMain() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
TracingBootstrap.main(new String[]{"test.ai.cloud.plugin.PluginMainTest"});
}
public static void main(String[] args){
BeInterceptedClass inst = new BeInterceptedClass();
inst.printabc();
}
}
package test.ai.cloud.plugin;
import com.ai.cloud.skywalking.plugin.interceptor.ConstructorContext;
import com.ai.cloud.skywalking.plugin.interceptor.EnhancedClassInstanceContext;
import com.ai.cloud.skywalking.plugin.interceptor.IAroundInterceptor;
import com.ai.cloud.skywalking.plugin.interceptor.InterceptorContext;
public class TestAroundInterceptor implements IAroundInterceptor {
@Override
public void onConstruct(EnhancedClassInstanceContext context, ConstructorContext interceptorContext) {
System.out.println("onConstruct, args size=" + interceptorContext.allArguments().length);
}
@Override
public void beforeMethod(EnhancedClassInstanceContext context, InterceptorContext interceptorContext) {
System.out.println("beforeMethod : " + context);
}
@Override
public void afterMethod(EnhancedClassInstanceContext context, InterceptorContext interceptorContext) {
System.out.println("afterMethod: " + context);
}
}
package test.ai.cloud.plugin;
import com.ai.cloud.skywalking.plugin.interceptor.IAroundInterceptor;
import com.ai.cloud.skywalking.plugin.interceptor.InterceptorDefine;
public class TestInterceptorDefine implements InterceptorDefine {
@Override
public String getBeInterceptedClassName() {
return "test.ai.cloud.plugin.BeInterceptedClass";
}
@Override
public String[] getBeInterceptedMethods() {
return new String[] { "printabc" };
}
@Override
public IAroundInterceptor instance() {
return new TestAroundInterceptor();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t](%F:%L) %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
<Configuration status="error">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t](%F:%L) %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
<logger name="com.ai.cloud.skywalking" level="debug">
<AppenderRef ref="Console" />
</logger>
</Loggers>
</Configuration>
\ No newline at end of file
#skyWalking用户ID
skywalking.user_id=123
#skyWalking应用编码
skywalking.application_code=test
#skywalking auth的环境变量名字
skywalking.auth_system_env_name=SKYWALKING_RUN
#skywalking数据编码
skywalking.charset=UTF-8
#是否打印数据
buriedpoint.printf=false
#埋点异常的最大长度
buriedpoint.max_exception_stack_length=4000
#业务字段的最大长度
buriedpoint.businesskey_max_length=300
#过滤异常
buriedpoint.exclusive_exceptions=java.lang.RuntimeException
#最大发送者的连接数阀比例
sender.connect_percent=100
#发送服务端配置
sender.servers_addr=127.0.0.1:34000
#最大发送的副本数量
sender.max_copy_num=2
#发送的最大长度
sender.max_send_length=20000
#当没有Sender时,尝试获取sender的等待周期
sender.retry_get_sender_wait_interval=2000
#是否开启发送消息
sender.is_off=false
#最大消费线程数
consumer.max_consumer=2
#消费者最大等待时间
consumer.max_wait_time=5
#发送失败等待时间
consumer.consumer_fail_retry_wait_interval=50
#每个Buffer的最大个数
buffer.buffer_max_size=18000
#Buffer池的最大长度
buffer.pool_size=5
#发送检查线程检查周期
senderchecker.check_polling_time=200
test.ai.cloud.plugin.TestInterceptorDefine
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册