提交 64c65892 编写于 作者: A ascrutae

Revert "提交未提交代码"

This reverts commit f08ca13a.
上级 3270df2d
......@@ -17,6 +17,8 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<premain.class>com.ai.cloud.skywalking.agent.SkywalkingAgent</premain.class>
<shade.net.bytebuddy.source>net.bytebuddy</shade.net.bytebuddy.source>
<shade.net.bytebuddy.target>com.ai.cloud.skywalking.api.dependencies.net.bytebuddy</shade.net.bytebuddy.target>
<shade.io.netty.source>io.netty</shade.io.netty.source>
<shade.io.netty.target>com.ai.cloud.skywalking.api.dependencies.io.netty</shade.io.netty.target>
<shade.com.google.protobuf.source>com.google.protobuf</shade.com.google.protobuf.source>
......@@ -83,6 +85,10 @@
</transformer>
</transformers>
<relocations>
<relocation>
<pattern>${shade.net.bytebuddy.source}</pattern>
<shadedPattern>${shade.net.bytebuddy.target}</shadedPattern>
</relocation>
<relocation>
<pattern>${shade.io.netty.source}</pattern>
<shadedPattern>${shade.io.netty.target}</shadedPattern>
......
package com.ai.cloud.skywalking.agent;
import com.ai.cloud.skywalking.agent.transformer.PluginsTransformer;
import com.ai.cloud.skywalking.conf.AuthDesc;
import com.ai.cloud.skywalking.conf.Config;
import com.ai.cloud.skywalking.conf.ConfigInitializer;
import com.ai.cloud.skywalking.plugin.IPlugin;
import com.ai.cloud.skywalking.plugin.PluginBootstrap;
import com.ai.cloud.skywalking.plugin.PluginCfg;
import com.ai.cloud.skywalking.plugin.interceptor.AbstractClassEnhancePluginDefine;
import com.ai.cloud.skywalking.plugin.interceptor.enhance.ClassEnhancePluginDefine;
import com.ai.cloud.skywalking.transformer.ClassTransformer;
import java.lang.instrument.Instrumentation;
import java.util.List;
import java.util.Map;
public class SkywalkingAgent {
public static void premain(String agentArgs, Instrumentation inst) {
ConfigInitializer.initialize();
PluginBootstrap bootstrap = new PluginBootstrap();
Map<String, ClassEnhancePluginDefine> pluginDefineMap = bootstrap.loadPlugins();
if (AuthDesc.isAuth()) {
inst.addTransformer(new PluginsTransformer(pluginDefineMap));
}
if (Config.SkyWalking.ALL_METHOD_MONITOR) {
String interceptorPackage = System.getProperty("interceptor.package", "");
inst.addTransformer(new ClassTransformer(interceptorPackage));
}
PluginBootstrap bootstrap = new PluginBootstrap();
bootstrap.start();
}
}
package com.ai.cloud.skywalking.agent.transformer;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import com.ai.cloud.skywalking.plugin.interceptor.enhance.ClassEnhancePluginDefine;
import javassist.ClassPool;
import javassist.CtClass;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Map;
public class PluginsTransformer implements ClassFileTransformer {
private Logger logger = LogManager.getLogger(PluginsTransformer.class);
private Map<String, ClassEnhancePluginDefine> pluginDefineMap;
public PluginsTransformer(Map<String, ClassEnhancePluginDefine> pluginDefineMap) {
this.pluginDefineMap = pluginDefineMap;
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (pluginDefineMap.isEmpty()) {
return classfileBuffer;
}
if (className.startsWith("com/ai/cloud/skywalking")){
return classfileBuffer;
}
ClassEnhancePluginDefine pluginDefine = pluginDefineMap.get(className.replaceAll("/", "."));
if (pluginDefine != null) {
ClassPool classPool = ClassPool.getDefault();
try {
CtClass ctClass = classPool.get(className.replaceAll("/", "."));
if (ctClass.isInterface()) {
return classfileBuffer;
}
pluginDefine.enhance(ctClass);
return ctClass.toBytecode();
} catch (Exception e) {
logger.error("Failed to enhance class[" + className + "]", e);
return classfileBuffer;
}
}
return classfileBuffer;
}
/**
* Created by xin on 16/7/24.
*/
public class PluginsTransformer {
}
......@@ -26,6 +26,12 @@
<version>1.0-Final</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
......
package com.ai.cloud.skywalking.plugin;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
public interface IPlugin {
byte[] define() throws PluginException;
public void define() throws PluginException;
}
......@@ -3,57 +3,54 @@ package com.ai.cloud.skywalking.plugin;
import com.ai.cloud.skywalking.conf.AuthDesc;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import com.ai.cloud.skywalking.plugin.interceptor.enhance.ClassEnhancePluginDefine;
import javassist.ClassPool;
import net.bytebuddy.pool.TypePool;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PluginBootstrap {
private static Logger logger = LogManager.getLogger(PluginBootstrap.class);
public static ClassPool CLASS_TYPE_POOL = null;
public static TypePool CLASS_TYPE_POOL = null;
public Map<String, ClassEnhancePluginDefine> loadPlugins() {
public void start() {
if (!AuthDesc.isAuth()) {
return null;
return;
}
CLASS_TYPE_POOL = ClassPool.getDefault();
CLASS_TYPE_POOL = TypePool.Default.ofClassPath();
PluginResourcesResolver resolver = new PluginResourcesResolver();
List<URL> resources = resolver.getResources();
if (resources == null || resources.size() == 0) {
logger.info("no plugin files (skywalking-plugin.properties) found, continue to start application.");
return new HashMap<String, ClassEnhancePluginDefine>();
return;
}
for (URL pluginUrl : resources) {
try {
PluginCfg.CFG.load(pluginUrl.openStream());
} catch (Throwable t) {
logger.error("plugin [{}] init failure.", new Object[] {pluginUrl}, t);
logger.error("plugin [{}] init failure.", new Object[]{pluginUrl}, t);
}
}
List<String> pluginClassList = PluginCfg.CFG.getPluginClassList();
List<String> pluginClassList = PluginCfg.CFG
.getPluginClassList();
Map<String, ClassEnhancePluginDefine> pluginDefineMap = new HashMap<String, ClassEnhancePluginDefine>();
for (String pluginClassName : pluginClassList) {
try {
logger.debug("prepare to enhance class by plugin {}.", pluginClassName);
IPlugin plugin = (IPlugin) Class.forName(pluginClassName).newInstance();
if (plugin instanceof ClassEnhancePluginDefine) {
pluginDefineMap.put(pluginClassName, (ClassEnhancePluginDefine) plugin);
}
logger.debug("prepare to enhance class by plugin {}.",
pluginClassName);
IPlugin plugin = (IPlugin) Class.forName(
pluginClassName).newInstance();
plugin.define();
} catch (Throwable t) {
logger.error("prepare to enhance class by plugin [{}] failure.", new Object[] {pluginClassName}, t);
logger.error("prepare to enhance class by plugin [{}] failure.",
new Object[]{pluginClassName}, t);
}
}
return pluginDefineMap;
}
}
......@@ -29,7 +29,7 @@ public class TracingBootstrap {
try {
PluginBootstrap bootstrap = new PluginBootstrap();
bootstrap.loadPlugins();
bootstrap.start();
} catch (Throwable t) {
logger.error("PluginBootstrap start failure.", t);
}
......
package com.ai.cloud.skywalking.plugin.boot;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
import com.ai.cloud.skywalking.plugin.PluginException;
public class BootException extends PluginException {
private static final long serialVersionUID = 8618884011525098003L;
......
package com.ai.cloud.skywalking.plugin.boot;
import com.ai.cloud.skywalking.plugin.IPlugin;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
import com.ai.cloud.skywalking.plugin.PluginException;
public abstract class BootPluginDefine implements IPlugin {
@Override
public byte[] define() throws PluginException {
return this.boot();
public void define() throws PluginException {
this.boot();
}
protected abstract byte[] boot() throws BootException;
protected abstract void boot() throws BootException;
}
package com.ai.cloud.skywalking.plugin.exception;
public class EnhanceClassEmptyException extends PluginException{
public EnhanceClassEmptyException(String message) {
super(message);
}
public EnhanceClassEmptyException(String message, Throwable cause) {
super(message, cause);
}
/**
* Created by xin on 16/7/25.
*/
public class EnhanceClassEmptyException {
}
package com.ai.cloud.skywalking.plugin.exception;
public class EnhanceClassNotFoundException extends PluginException{
public EnhanceClassNotFoundException(String message) {
super(message);
}
/**
* Created by xin on 16/7/25.
*/
public class EnhanceClassNotFoundException {
}
......@@ -3,8 +3,5 @@ package com.ai.cloud.skywalking.plugin.exception;
/**
* Created by xin on 16/7/25.
*/
public class WitnessClassesCannotFound extends PluginException {
public WitnessClassesCannotFound(String message) {
super(message);
}
public class WitnessClassesCannotFound {
}
......@@ -3,13 +3,13 @@ package com.ai.cloud.skywalking.plugin.interceptor;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import com.ai.cloud.skywalking.plugin.IPlugin;
import com.ai.cloud.skywalking.plugin.exception.EnhanceClassEmptyException;
import com.ai.cloud.skywalking.plugin.exception.EnhanceClassNotFoundException;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
import com.ai.cloud.skywalking.plugin.exception.WitnessClassesCannotFound;
import com.ai.cloud.skywalking.plugin.PluginException;
import com.ai.cloud.skywalking.protocol.util.StringUtil;
import javassist.ClassPool;
import javassist.CtClass;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.pool.TypePool.Resolution;
import static com.ai.cloud.skywalking.plugin.PluginBootstrap.CLASS_TYPE_POOL;
......@@ -17,58 +17,64 @@ public abstract class AbstractClassEnhancePluginDefine implements IPlugin {
private static Logger logger = LogManager.getLogger(AbstractClassEnhancePluginDefine.class);
@Override
public byte[] define() throws PluginException {
public void define() throws PluginException {
String interceptorDefineClassName = this.getClass().getName();
String enhanceOriginClassName = enhanceClassName();
if (StringUtil.isEmpty(enhanceOriginClassName)) {
logger.warn("classname of being intercepted is not defined by {}.", interceptorDefineClassName);
throw new EnhanceClassEmptyException("class name of being is not deined by " + interceptorDefineClassName);
logger.warn("classname of being intercepted is not defined by {}.",
interceptorDefineClassName);
return;
}
logger.debug("prepare to enhance class {} by {}.", enhanceOriginClassName, interceptorDefineClassName);
logger.debug("prepare to enhance class {} by {}.",
enhanceOriginClassName, interceptorDefineClassName);
CtClass ctClass = findEnhanceClasses(interceptorDefineClassName, enhanceOriginClassName);
if (ctClass == null) {
logger.warn("class {} can't be resolved, enhance by {} failue.", enhanceOriginClassName, interceptorDefineClassName);
throw new EnhanceClassNotFoundException("class " + enhanceOriginClassName + " can't be resolved, enhance by " + interceptorDefineClassName + " failue.");
Resolution resolution = CLASS_TYPE_POOL.describe(enhanceOriginClassName);
if (!resolution.isResolved()) {
logger.warn("class {} can't be resolved, enhance by {} failue.",
enhanceOriginClassName, interceptorDefineClassName);
return;
}
/**
* find witness classes for enhance class
*/
String[] witnessClasses = witnessClasses();
if (witnessClasses != null) {
for (String witnessClassName : witnessClasses) {
try {
CtClass witnessClass = CLASS_TYPE_POOL.get(witnessClassName);
if (witnessClass != null) {
logger.warn("enhance class {} by plugin {} is not working. Because witness class {} is not existed.", enhanceOriginClassName, interceptorDefineClassName,
witnessClass);
throw new WitnessClassesCannotFound(
"enhance class " + enhanceOriginClassName + " by plugin " + interceptorDefineClassName + " is not working. Because witness class " + witnessClass
+ " is not existed.");
}
} catch (Exception e) {
if(witnessClasses != null) {
for (String witnessClass : witnessClasses) {
Resolution witnessClassResolution = CLASS_TYPE_POOL.describe(witnessClass);
if (!witnessClassResolution.isResolved()) {
logger.warn("enhance class {} by plugin {} is not working. Because witness class {} is not existed.", enhanceOriginClassName, interceptorDefineClassName, witnessClass);
return;
}
}
}
return enhance(ctClass);
}
/**
* find origin class source code for interceptor
*/
DynamicType.Builder<?> newClassBuilder = new ByteBuddy()
.rebase(resolution.resolve(),
ClassFileLocator.ForClassLoader.ofClassPath());
private CtClass findEnhanceClasses(String interceptorDefineClassName, String enhanceOriginClassName) throws EnhanceClassNotFoundException {
try {
ClassPool classPool = ClassPool.getDefault();
return classPool.get(enhanceOriginClassName);
} catch (Exception e) {
throw new EnhanceClassNotFoundException("class " + enhanceOriginClassName + " can't be resolved, enhance by " + interceptorDefineClassName + " failue.");
}
newClassBuilder = this.enhance(enhanceOriginClassName, newClassBuilder);
/**
* 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);
}
protected abstract byte[] enhance(CtClass ctClass) throws PluginException;
protected abstract DynamicType.Builder<?> enhance(String enhanceOriginClassName, DynamicType.Builder<?> newClassBuilder) throws PluginException;
/**
* 返回要被增强的类,应当返回类全名
......@@ -83,7 +89,7 @@ public abstract class AbstractClassEnhancePluginDefine implements IPlugin {
*
* @return
*/
protected String[] witnessClasses() {
return new String[] {};
protected String[] witnessClasses(){
return new String[]{};
}
}
package com.ai.cloud.skywalking.plugin.interceptor;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
import com.ai.cloud.skywalking.plugin.PluginException;
public class EnhanceException extends PluginException {
private static final long serialVersionUID = -2234782755784217255L;
......
package com.ai.cloud.skywalking.plugin.interceptor;
import javassist.CtMethod;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.*;
public abstract class MethodMatcher {
......@@ -42,29 +45,48 @@ public abstract class MethodMatcher {
this.modifier = modifier;
}
public abstract ElementMatcher.Junction<MethodDescription> buildMatcher();
protected String getMethodMatchDescribe() {
return methodMatchDescribe;
}
protected ElementMatcher.Junction<MethodDescription> mergeArgumentsIfNecessary(ElementMatcher.Junction<MethodDescription> matcher) {
if (argTypeArray != null) {
matcher = matcher.and(takesArguments(argTypeArray));
}
public abstract boolean match(CtMethod ctMethod);
public enum Modifier {
Public(0x00000001),
Default(0x00000000),
Private(0x00000002),
Protected(0x00000004);
private int value;
if (argNum > -1) {
matcher = matcher.and(takesArguments(argNum));
}
Modifier(int value) {
this.value = value;
if (modifier != null) {
matcher = matcher.and(modifier.elementMatcher());
}
return matcher;
}
public int getValue() {
return value;
public enum Modifier {
Public, Default, Private, Protected;
private ElementMatcher.Junction<MethodDescription> elementMatcher() {
switch (this) {
case Private: {
return isPrivate();
}
case Default: {
return isPackagePrivate();
}
case Public: {
return isPublic();
}
case Protected: {
return isProtected();
}
default:
return isPublic();
}
}
}
......@@ -72,7 +94,7 @@ public abstract class MethodMatcher {
public String toString() {
StringBuilder stringBuilder = new StringBuilder("method name=" + getMethodMatchDescribe());
if (getModifier() != null) {
stringBuilder.insert(0, getModifier() + " ");
stringBuilder.insert(0, getModifier() + " ");
}
if (getArgNum() > -1) {
......@@ -83,11 +105,11 @@ public abstract class MethodMatcher {
stringBuilder.append(", types of arguments are ");
boolean isFirst = true;
for (Class<?> argType : getArgTypeArray()) {
if (isFirst) {
isFirst = false;
} else {
stringBuilder.append(",");
}
if(isFirst){
isFirst = false;
}else{
stringBuilder.append(",");
}
stringBuilder.append(argType.getName());
}
}
......
......@@ -2,27 +2,37 @@ package com.ai.cloud.skywalking.plugin.interceptor.enhance;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
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 com.ai.cloud.skywalking.plugin.interceptor.EnhancedClassInstanceContext;
public class ClassConstructorInterceptor {
private static Logger logger = LogManager.getLogger(ClassConstructorInterceptor.class);
private static Logger logger = LogManager
.getLogger(ClassConstructorInterceptor.class);
private InstanceMethodsAroundInterceptor interceptor;
private InstanceMethodsAroundInterceptor interceptor;
public ClassConstructorInterceptor(InstanceMethodsAroundInterceptor interceptor) {
this.interceptor = interceptor;
}
public ClassConstructorInterceptor(InstanceMethodsAroundInterceptor interceptor) {
this.interceptor = interceptor;
}
public void intercept(Object obj, Object instanceContext, Object[] allArguments) {
try {
EnhancedClassInstanceContext context = new EnhancedClassInstanceContext();
// accessor.setValue(context);
instanceContext = context;
ConstructorInvokeContext interceptorContext = new ConstructorInvokeContext(obj, allArguments);
interceptor.onConstruct(context, interceptorContext);
} catch (Throwable t) {
logger.error("ClassConstructorInterceptor failue.", t);
}
@RuntimeType
public void intercept(
@This Object obj,
@FieldProxy(ClassEnhancePluginDefine.contextAttrName) FieldSetter accessor,
@AllArguments Object[] allArguments) {
try {
EnhancedClassInstanceContext context = new EnhancedClassInstanceContext();
accessor.setValue(context);
ConstructorInvokeContext interceptorContext = new ConstructorInvokeContext(obj,
allArguments);
interceptor.onConstruct(context, interceptorContext);
} catch (Throwable t) {
logger.error("ClassConstructorInterceptor failue.", t);
}
}
}
}
package com.ai.cloud.skywalking.plugin.interceptor.enhance;
import static net.bytebuddy.matcher.ElementMatchers.any;
import static net.bytebuddy.matcher.ElementMatchers.not;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.SuperMethodCall;
import net.bytebuddy.implementation.bind.annotation.FieldProxy;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import com.ai.cloud.skywalking.plugin.PluginException;
import com.ai.cloud.skywalking.plugin.interceptor.AbstractClassEnhancePluginDefine;
import com.ai.cloud.skywalking.plugin.interceptor.EnhanceException;
import com.ai.cloud.skywalking.plugin.interceptor.EnhancedClassInstanceContext;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import javassist.*;
import java.lang.reflect.Modifier;
public abstract class ClassEnhancePluginDefine extends AbstractClassEnhancePluginDefine {
private static Logger logger = LogManager.getLogger(ClassEnhancePluginDefine.class);
public static final String contextAttrName = "_$EnhancedClassInstanceContext";
public byte[] enhance(CtClass ctClass) throws PluginException {
try {
CtMethod[] ctMethod = ctClass.getDeclaredMethods();
for (CtMethod method : ctMethod) {
if (Modifier.isStatic(method.getModifiers())) {
this.enhanceClass(ctClass, method);
} else {
this.enhanceInstance(ctClass, method);
}
}
return ctClass.toBytecode();
} catch (Exception e) {
throw new PluginException("Can not compile the class", e);
}
}
private void enhanceClass(CtClass ctClass, CtMethod method) throws CannotCompileException, NotFoundException {
boolean isMatch = false;
for (MethodMatcher methodMatcher : getStaticMethodsMatchers()) {
if (methodMatcher.match(method)) {
isMatch = true;
break;
}
}
if (isMatch) {
// 修改方法名,
String methodName = method.getName();
String newMethodName = methodName + "_$SkywalkingEnhance";
method.setName(newMethodName);
CtMethod newMethod = new CtMethod(method.getReturnType(), methodName, method.getParameterTypes(), method.getDeclaringClass());
newMethod.setBody(
"{ new " + ClassStaticMethodsInterceptor.class.getName() + "(new " + getStaticMethodsInterceptor().getClass().getName() + ").intercept($class,$args,\""
+ methodName + "\"," + OriginCallCodeGenerator.generateStaticMethodOriginCallCode(ctClass.getName(), newMethodName) + ");}");
ctClass.addMethod(newMethod);
}
}
private void enhanceInstance(CtClass ctClass, CtMethod method) throws CannotCompileException, NotFoundException {
// 添加一个字段,并且带上get/set方法
CtField ctField = CtField.make("{public " + EnhancedClassInstanceContext.class.getName() + " " + contextAttrName + ";}", ctClass);
ctClass.addMethod(
CtMethod.make("public " + EnhancedClassInstanceContext.class.getName() + " get" + contextAttrName + "(){ return this." + contextAttrName + ";}", ctClass));
ctClass.addMethod(CtMethod.make(
"public void set" + contextAttrName + "(" + EnhancedClassInstanceContext.class.getName() + " " + contextAttrName + "){this." + contextAttrName + "="
+ contextAttrName + ";}", ctClass));
// 初始化构造函数
CtConstructor[] constructors = ctClass.getDeclaredConstructors();
for (CtConstructor constructor : constructors) {
constructor.insertAfter(" new " + ClassConstructorInterceptor.class.getName() + "(new " + getInstanceMethodsInterceptor().getClass().getName() + "()).intercept($0,$0."
+ contextAttrName + ",$args);");
}
boolean isMatch = false;
for (MethodMatcher methodMatcher : getInstanceMethodsMatchers()) {
if (methodMatcher.match(method)) {
isMatch = true;
break;
}
}
if (isMatch) {
// 修改方法名,
String methodName = method.getName();
String newMethodName = methodName + "_$SkywalkingEnhance";
method.setName(newMethodName);
CtMethod newMethod = new CtMethod(method.getReturnType(), methodName, method.getParameterTypes(), method.getDeclaringClass());
newMethod.setBody(
"{ new " + ClassInstanceMethodsInterceptor.class.getName() + "(new " + getInstanceMethodsInterceptor().getClass().getName() + "()).intercept($0,$args,\""
+ methodName + "\"," + OriginCallCodeGenerator.generateInstanceMethodOriginCallCode("$0", methodName) + ",$0." + contextAttrName + ");}");
ctClass.addMethod(newMethod);
}
}
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getInstanceMethodsMatchers();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部,保持单例
*
* @return
*/
protected abstract InstanceMethodsAroundInterceptor getInstanceMethodsInterceptor();
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getStaticMethodsMatchers();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部,保持单例
*
* @return
*/
protected abstract StaticMethodsAroundInterceptor getStaticMethodsInterceptor();
private static Logger logger = LogManager
.getLogger(ClassEnhancePluginDefine.class);
public static final String contextAttrName = "_$EnhancedClassInstanceContext";
protected DynamicType.Builder<?> enhance(String enhanceOriginClassName,
DynamicType.Builder<?> newClassBuilder) throws PluginException {
newClassBuilder = this.enhanceClass(enhanceOriginClassName, newClassBuilder);
newClassBuilder = this.enhanceInstance(enhanceOriginClassName, newClassBuilder);
return newClassBuilder;
}
private DynamicType.Builder<?> enhanceInstance(String enhanceOriginClassName,
DynamicType.Builder<?> newClassBuilder) throws PluginException {
MethodMatcher[] methodMatchers = getInstanceMethodsMatchers();
if(methodMatchers == null){
return newClassBuilder;
}
/**
* alter class source code.<br/>
*
* new class need:<br/>
* 1.add field '_$EnhancedClassInstanceContext' of type
* EnhancedClassInstanceContext <br/>
*
* 2.intercept constructor by default, and intercept method which it's
* required by interceptorDefineClass. <br/>
*/
InstanceMethodsAroundInterceptor interceptor = getInstanceMethodsInterceptor();
if (interceptor == null) {
throw new EnhanceException("no InstanceMethodsAroundInterceptor instance. ");
}
newClassBuilder = newClassBuilder
.defineField(contextAttrName,
EnhancedClassInstanceContext.class)
.constructor(any())
.intercept(
SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(
new ClassConstructorInterceptor(interceptor))
.appendParameterBinder(
FieldProxy.Binder.install(
FieldGetter.class,
FieldSetter.class))));
ClassInstanceMethodsInterceptor classMethodInterceptor = new ClassInstanceMethodsInterceptor(
interceptor);
StringBuilder enhanceRules = new StringBuilder(
"\nprepare to enhance class [" + enhanceOriginClassName
+ "] instance methods as following rules:\n");
int ruleIdx = 1;
for (MethodMatcher methodMatcher : methodMatchers) {
enhanceRules.append("\t" + ruleIdx++ + ". " + methodMatcher + "\n");
}
logger.debug(enhanceRules);
ElementMatcher.Junction<MethodDescription> matcher = null;
for (MethodMatcher methodMatcher : methodMatchers) {
logger.debug("enhance class {} instance methods by rule: {}",
enhanceOriginClassName, methodMatcher);
if (matcher == null) {
matcher = methodMatcher.buildMatcher();
continue;
}
matcher = matcher.or(methodMatcher.buildMatcher());
}
/**
* exclude static methods.
*/
matcher = matcher.and(not(ElementMatchers.isStatic()));
newClassBuilder = newClassBuilder.method(matcher).intercept(
MethodDelegation.to(classMethodInterceptor));
return newClassBuilder;
}
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getInstanceMethodsMatchers();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部,保持单例
*
* @return
*/
protected abstract InstanceMethodsAroundInterceptor getInstanceMethodsInterceptor();
private DynamicType.Builder<?> enhanceClass(String enhanceOriginClassName,
DynamicType.Builder<?> newClassBuilder) throws PluginException {
MethodMatcher[] methodMatchers = getStaticMethodsMatchers();
if(methodMatchers == null){
return newClassBuilder;
}
StaticMethodsAroundInterceptor interceptor = getStaticMethodsInterceptor();
if (interceptor == null) {
throw new EnhanceException("no StaticMethodsAroundInterceptor instance. ");
}
ClassStaticMethodsInterceptor classMethodInterceptor = new ClassStaticMethodsInterceptor(
interceptor);
StringBuilder enhanceRules = new StringBuilder(
"\nprepare to enhance class [" + enhanceOriginClassName
+ "] static methods as following rules:\n");
int ruleIdx = 1;
for (MethodMatcher methodMatcher : methodMatchers) {
enhanceRules.append("\t" + ruleIdx++ + ". " + methodMatcher + "\n");
}
logger.debug(enhanceRules);
ElementMatcher.Junction<MethodDescription> matcher = null;
for (MethodMatcher methodMatcher : methodMatchers) {
logger.debug("enhance class {} static methods by rule: {}",
enhanceOriginClassName, methodMatcher);
if (matcher == null) {
matcher = methodMatcher.buildMatcher();
continue;
}
matcher = matcher.or(methodMatcher.buildMatcher());
}
/**
* restrict static methods.
*/
matcher = matcher.and(ElementMatchers.isStatic());
newClassBuilder = newClassBuilder.method(matcher).intercept(
MethodDelegation.to(classMethodInterceptor));
return newClassBuilder;
}
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getStaticMethodsMatchers();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部,保持单例
*
* @return
*/
protected abstract StaticMethodsAroundInterceptor getStaticMethodsInterceptor();
}
......@@ -3,6 +3,10 @@ package com.ai.cloud.skywalking.plugin.interceptor.enhance;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import com.ai.cloud.skywalking.plugin.interceptor.EnhancedClassInstanceContext;
import net.bytebuddy.implementation.bind.annotation.*;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/**
* 类方法拦截、控制器
......@@ -10,7 +14,8 @@ import com.ai.cloud.skywalking.plugin.interceptor.EnhancedClassInstanceContext;
* @author wusheng
*/
public class ClassInstanceMethodsInterceptor {
private static Logger logger = LogManager.getLogger(ClassInstanceMethodsInterceptor.class);
private static Logger logger = LogManager
.getLogger(ClassInstanceMethodsInterceptor.class);
private InstanceMethodsAroundInterceptor interceptor;
......@@ -18,13 +23,22 @@ public class ClassInstanceMethodsInterceptor {
this.interceptor = interceptor;
}
public Object intercept(Object obj, Object[] allArguments, String methodName, OriginCall zuper, EnhancedClassInstanceContext instanceContext) throws Exception {
InstanceMethodInvokeContext interceptorContext = new InstanceMethodInvokeContext(obj, methodName, allArguments);
@RuntimeType
public Object intercept(
@This Object obj,
@AllArguments Object[] allArguments,
@Origin Method method,
@SuperCall Callable<?> zuper,
@FieldValue(ClassEnhancePluginDefine.contextAttrName) EnhancedClassInstanceContext instanceContext)
throws Exception {
InstanceMethodInvokeContext interceptorContext = new InstanceMethodInvokeContext(obj,
method.getName(), allArguments);
MethodInterceptResult result = new MethodInterceptResult();
try {
interceptor.beforeMethod(instanceContext, interceptorContext, result);
} catch (Throwable t) {
logger.error("class[{}] before method[{}] intercept failue:{}", new Object[] {obj.getClass(), methodName, t.getMessage()}, t);
logger.error("class[{}] before method[{}] intercept failue:{}",
new Object[]{obj.getClass(), method.getName(), t.getMessage()}, t);
}
if (!result.isContinue()) {
return result._ret();
......@@ -37,14 +51,16 @@ public class ClassInstanceMethodsInterceptor {
try {
interceptor.handleMethodException(t, instanceContext, interceptorContext, ret);
} catch (Throwable t2) {
logger.error("class[{}] handle method[{}] exception failue:{}", new Object[] {obj.getClass(), methodName, t2.getMessage()}, t2);
logger.error("class[{}] handle method[{}] exception failue:{}",
new Object[]{obj.getClass(), method.getName(), t2.getMessage()}, t2);
}
throw t;
} finally {
try {
ret = interceptor.afterMethod(instanceContext, interceptorContext, ret);
} catch (Throwable t) {
logger.error("class[{}] after method[{}] intercept failue:{}", new Object[] {obj.getClass(), methodName, t.getMessage()}, t);
logger.error("class[{}] after method[{}] intercept failue:{}",
new Object[]{obj.getClass(), method.getName(), t.getMessage()}, t);
}
}
return ret;
......
......@@ -2,6 +2,13 @@ package com.ai.cloud.skywalking.plugin.interceptor.enhance;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/**
* 类静态方法拦截、控制器
......@@ -17,13 +24,14 @@ public class ClassStaticMethodsInterceptor {
this.interceptor = interceptor;
}
public Object intercept(Class<?> clazz, Object[] allArguments, String methodName, OriginCall zuper) throws Exception {
MethodInvokeContext interceptorContext = new MethodInvokeContext(methodName, allArguments);
@RuntimeType
public Object intercept(@Origin Class<?> clazz, @AllArguments Object[] allArguments, @Origin Method method, @SuperCall Callable<?> zuper) throws Exception {
MethodInvokeContext interceptorContext = new MethodInvokeContext(method.getName(), allArguments);
MethodInterceptResult result = new MethodInterceptResult();
try {
interceptor.beforeMethod(interceptorContext, result);
} catch (Throwable t) {
logger.error("class[{}] before static method[{}] intercept failue:{}", new Object[] {clazz, methodName, t.getMessage()}, t);
logger.error("class[{}] before static method[{}] intercept failue:{}", new Object[] {clazz, method.getName(), t.getMessage()}, t);
}
if (!result.isContinue()) {
return result._ret();
......@@ -36,14 +44,14 @@ public class ClassStaticMethodsInterceptor {
try {
interceptor.handleMethodException(t, interceptorContext, ret);
} catch (Throwable t2) {
logger.error("class[{}] handle static method[{}] exception failue:{}", new Object[] {clazz, methodName, t2.getMessage()}, t2);
logger.error("class[{}] handle static method[{}] exception failue:{}", new Object[] {clazz, method.getName(), t2.getMessage()}, t2);
}
throw t;
} finally {
try {
ret = interceptor.afterMethod(interceptorContext, ret);
} catch (Throwable t) {
logger.error("class[{}] after static method[{}] intercept failue:{}", new Object[] {clazz, methodName, t.getMessage()}, t);
logger.error("class[{}] after static method[{}] intercept failue:{}", new Object[] {clazz, method.getName(), t.getMessage()}, t);
}
}
return ret;
......
package com.ai.cloud.skywalking.plugin.interceptor.enhance;
import com.ai.cloud.skywalking.logging.LogManager;
import com.ai.cloud.skywalking.logging.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by xin on 16/7/26.
*/
public class OriginCallCodeGenerator {
private static Logger logger = LogManager.getLogger(OriginCallCodeGenerator.class);
private static String staticMethodOriginCallCode;
private static String instanceMethodOriginCallCode;
static {
try {
instanceMethodOriginCallCode = loadInstanceMethodOriginCallCode();
staticMethodOriginCallCode = loadStaticMethodOriginCallCode();
} catch (Exception e) {
}
}
private static String loadInstanceMethodOriginCallCode() throws IOException {
return loadCodeSegment("/instance_method_call_origin_code.conf");
}
private static String loadStaticMethodOriginCallCode() throws IOException {
return loadCodeSegment("/static_method_call_origin_code.conf");
}
private static String loadCodeSegment(String fileName) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(OriginCallCodeGenerator.class.getResourceAsStream(fileName)));
StringBuilder code = new StringBuilder();
String codeSegment;
while ((codeSegment = bufferedReader.readLine()) != null) {
code.append(codeSegment);
}
return code.toString();
}
public static String generateInstanceMethodOriginCallCode(String originObject, String methodName) {
return instanceMethodOriginCallCode.toString().replaceAll("%origin_object%", originObject).replaceAll("%method_name%", methodName);
}
public static String generateStaticMethodOriginCallCode(String className, String methodName) {
return staticMethodOriginCallCode.toString().replaceAll("%class_name%", className).replaceAll("%method_name%", methodName);
}
}
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import javassist.CtMethod;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.any;
public class AnyMethodsMatcher extends ExclusiveObjectDefaultMethodsMatcher {
......@@ -8,14 +11,13 @@ public class AnyMethodsMatcher extends ExclusiveObjectDefaultMethodsMatcher {
super("any method");
}
@Override
public String toString() {
return getMethodMatchDescribe();
public ElementMatcher.Junction<MethodDescription> match() {
return any();
}
@Override
public boolean matchMethod(CtMethod ctMethod) {
return true;
public String toString() {
return getMethodMatchDescribe();
}
}
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import javassist.CtMethod;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.not;
public abstract class ExclusiveObjectDefaultMethodsMatcher extends MethodMatcher {
private static final MethodMatcher[] EXCLUSIVE_DEFAULT_METHOD_NAME =
new MethodMatcher[] {new SimpleMethodMatcher(Modifier.Public, "finalize", 0), new SimpleMethodMatcher(Modifier.Public, "wait", long.class, int.class),
new SimpleMethodMatcher(Modifier.Public, "wait", long.class), new SimpleMethodMatcher(Modifier.Public, "wait", 0),
new SimpleMethodMatcher(Modifier.Public, "equals", Object.class), new SimpleMethodMatcher(Modifier.Public, "toString", 0),
new SimpleMethodMatcher(Modifier.Public, "hashCode", 0), new SimpleMethodMatcher(Modifier.Public, "getClass", 0),
new SimpleMethodMatcher(Modifier.Public, "clone", 0), new SimpleMethodMatcher(Modifier.Public, "notify", 0),
new SimpleMethodMatcher(Modifier.Public, "notifyAll", 0)};
private static final MethodMatcher[] EXCLUSIVE_DEFAULT_METHOD_NAME = new MethodMatcher[]{
new SimpleMethodMatcher(Modifier.Public, "finalize", 0),
new SimpleMethodMatcher(Modifier.Public, "wait", long.class, int.class),
new SimpleMethodMatcher(Modifier.Public, "wait", long.class),
new SimpleMethodMatcher(Modifier.Public, "wait", 0),
new SimpleMethodMatcher(Modifier.Public, "equals", Object.class),
new SimpleMethodMatcher(Modifier.Public, "toString", 0),
new SimpleMethodMatcher(Modifier.Public, "hashCode", 0),
new SimpleMethodMatcher(Modifier.Public, "getClass", 0),
new SimpleMethodMatcher(Modifier.Public, "clone", 0),
new SimpleMethodMatcher(Modifier.Public, "notify", 0),
new SimpleMethodMatcher(Modifier.Public, "notifyAll", 0)
};
public ExclusiveObjectDefaultMethodsMatcher(String methodMatchDescribe) {
super(methodMatchDescribe);
}
@Override
public boolean match(CtMethod ctMethod) {
return this.matchMethod(ctMethod) && excludeObjectDefaultMethod(ctMethod);
public ElementMatcher.Junction<MethodDescription> buildMatcher() {
return this.match().and(excludeObjectDefaultMethod());
}
protected boolean excludeObjectDefaultMethod(CtMethod ctMethod) {
protected ElementMatcher.Junction<MethodDescription> excludeObjectDefaultMethod() {
ElementMatcher.Junction<MethodDescription> exclusiveMatcher = null;
for (MethodMatcher methodMatcher : EXCLUSIVE_DEFAULT_METHOD_NAME) {
if (methodMatcher.match(ctMethod)) {
return false;
if (exclusiveMatcher == null) {
exclusiveMatcher = methodMatcher.buildMatcher();
continue;
}
exclusiveMatcher = exclusiveMatcher.or(methodMatcher.buildMatcher());
}
return true;
return not(exclusiveMatcher);
}
public abstract boolean matchMethod(CtMethod ctMethod);
public abstract ElementMatcher.Junction<MethodDescription> match();
}
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import javassist.CtMethod;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static net.bytebuddy.matcher.ElementMatchers.not;
public class MethodsExclusiveMatcher extends ExclusiveObjectDefaultMethodsMatcher {
private List<MethodMatcher> matchers = new ArrayList<MethodMatcher>();
......@@ -24,24 +27,29 @@ public class MethodsExclusiveMatcher extends ExclusiveObjectDefaultMethodsMatche
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("exclude following method(s): ");
int idx = 1;
for (MethodMatcher methodMatcher : matchers) {
stringBuilder.append(idx++ + "." + methodMatcher.toString() + ". ");
public ElementMatcher.Junction<MethodDescription> match() {
ElementMatcher.Junction<MethodDescription> result = null;
for (MethodMatcher matcher : matchers) {
if (result == null) {
result = matcher.buildMatcher();
continue;
}
result = result.or(matcher.buildMatcher());
}
return stringBuilder.toString();
return not(result);
}
@Override
public boolean matchMethod(CtMethod ctMethod) {
boolean result = false;
public String toString() {
StringBuilder stringBuilder = new StringBuilder("exclude following method(s): ");
int idx = 1;
for (MethodMatcher methodMatcher : matchers) {
if (methodMatcher.match(ctMethod)) {
result = result || result;
}
stringBuilder.append(idx++ + "." + methodMatcher.toString() + ". ");
}
return !result;
return stringBuilder.toString();
}
}
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import javassist.CtMethod;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import static net.bytebuddy.matcher.ElementMatchers.any;
public class PrivateMethodMatcher extends MethodMatcher {
public PrivateMethodMatcher() {
......@@ -9,8 +13,8 @@ public class PrivateMethodMatcher extends MethodMatcher {
}
@Override
public boolean match(CtMethod ctMethod) {
return java.lang.reflect.Modifier.isPrivate(ctMethod.getModifiers());
public ElementMatcher.Junction<MethodDescription> buildMatcher() {
return any().and(ElementMatchers.<MethodDescription>isPrivate());
}
@Override
......
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import static net.bytebuddy.matcher.ElementMatchers.named;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import javassist.CtMethod;
import javassist.NotFoundException;
public class SimpleMethodMatcher extends MethodMatcher {
......@@ -31,42 +33,10 @@ public class SimpleMethodMatcher extends MethodMatcher {
super(modifier, methodMatchDescribe, argTypeArray);
}
@Override
public boolean match(CtMethod ctMethod) {
int result = 1;
try {
result <<= matchArgTypeArrayIfNecessary(ctMethod);
result <<= matchArgNumIfNecessary(ctMethod);
result <<= matchModifierIfNecessary(ctMethod);
return result == 1 ? true : false;
} catch (Exception e) {
return false;
}
}
private int matchModifierIfNecessary(CtMethod ctMethod) {
if (getModifier() != null) {
return getModifier().getValue() == ctMethod.getModifiers() ? 0 : 1;
}
return 0;
}
private int matchArgNumIfNecessary(CtMethod ctMethod) throws NotFoundException {
if (getArgNum() > -1) {
return getArgNum() == ctMethod.getParameterTypes().length ? 0 : 1;
}
return 0;
}
private int matchArgTypeArrayIfNecessary(CtMethod ctMethod) throws NotFoundException {
if (getArgTypeArray() != null) {
for (int i = 0; i < getArgTypeArray().length; i++) {
if (!getArgTypeArray()[i].getName().equals(ctMethod.getParameterTypes()[i].getName())) {
return 1;
}
}
}
return 0;
@Override
public ElementMatcher.Junction<MethodDescription> buildMatcher() {
ElementMatcher.Junction<MethodDescription> matcher = named(getMethodMatchDescribe());
return mergeArgumentsIfNecessary(matcher);
}
}
......@@ -37,13 +37,7 @@ public final class ContextGenerator {
spanData = new Span(TraceIdGenerator.generate(), Config.SkyWalking.APPLICATION_CODE, Config.SkyWalking.USER_ID);
} else {
// 如果不为空,则将当前的Context存放到上下文
Span previousSpanData = CurrentThreadSpanStack.peek();
if (previousSpanData == null){
spanData = new Span(context.getTraceId(), context.getParentLevel(), context.getLevelId(), Config.SkyWalking.APPLICATION_CODE, Config.SkyWalking.USER_ID);
}else{
spanData = new Span(previousSpanData.getTraceId(), Config.SkyWalking.APPLICATION_CODE, Config.SkyWalking.USER_ID);
spanData.setParentLevel(previousSpanData.getParentLevel() + "." + previousSpanData.getLevelId());
}
spanData = new Span(context.getTraceId(), context.getParentLevel(), context.getLevelId(), Config.SkyWalking.APPLICATION_CODE, Config.SkyWalking.USER_ID);
}
spanData.setStartDate(System.currentTimeMillis());
......
new com.ai.cloud.skywalking.plugin.interceptor.enhance.OriginCall(%origin_object%){
private Object _this;
public com.ai.cloud.skywalking.plugin.interceptor.enhance.OriginCall(Object _this){
this._this = _this;
}
public Object call(){
return _this.%method_name%($$);
}
}
new com.ai.cloud.skywalking.plugin.interceptor.enhance.OriginCall(){
public Object call(){
return %class_name%.%method_name%($$);
}
}
new Origin
......@@ -15,7 +15,7 @@ public class SDKGeneratedDataTest {
@Test
public void traceTreeAssertTest() {
Config.Consumer.MAX_CONSUMER = 0;
Span testSpan = new Span("1.0b.1465224457414.7e57f54.22905.61.2691", "", 0, "sample-application", "5");
Span testSpan = new Span("1.0b.1465224457414.7e57f54.22905.61.2691", "", 0, "test-application", "5");
RequestSpan requestSpan =
RequestSpan.RequestSpanBuilder.newBuilder(testSpan).viewPoint("http://hire.asiainfo.com/Aisse-Mobile-Web/aisseWorkPage/submitReimbursement").build();
ContextBuffer.save(requestSpan);
......
......@@ -9,8 +9,8 @@ import com.ai.cloud.skywalking.plugin.PluginBootstrap;
public class ExclusionMatcherTest extends TestCase{
@Test
public void testMatcher() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InterruptedException {
//new PluginBootstrap().start();
TestMatcherClass testMatcherClass = (TestMatcherClass) Class.forName("sample.ai.cloud.matcher.TestMatcherClass").newInstance();
new PluginBootstrap().start();
TestMatcherClass testMatcherClass = (TestMatcherClass) Class.forName("test.ai.cloud.matcher.TestMatcherClass").newInstance();
testMatcherClass.set();
testMatcherClass.seta("a");
......
......@@ -11,7 +11,7 @@ import com.ai.cloud.skywalking.plugin.interceptor.matcher.PrivateMethodMatcher;
public class TestMatcherDefine extends ClassInstanceMethodsEnhancePluginDefine {
@Override
public String enhanceClassName() {
return "sample.ai.cloud.matcher.TestMatcherClass";
return "test.ai.cloud.matcher.TestMatcherClass";
}
@Override
......
......@@ -12,13 +12,13 @@ public class PluginMainTest {
IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException, ClassNotFoundException {
TracingBootstrap
.main(new String[] { "sample.ai.cloud.plugin.PluginMainTest" });
.main(new String[] { "test.ai.cloud.plugin.PluginMainTest" });
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
long start = System.currentTimeMillis();
BeInterceptedClass inst = (BeInterceptedClass) Class.forName("sample.ai.cloud.plugin.BeInterceptedClass").newInstance();
BeInterceptedClass inst = (BeInterceptedClass) Class.forName("test.ai.cloud.plugin.BeInterceptedClass").newInstance();
inst.printabc();
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
......
......@@ -10,18 +10,18 @@ public class TestAroundInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void onConstruct(EnhancedClassInstanceContext context, ConstructorInvokeContext interceptorContext) {
context.set("sample.key", "123");
context.set("test.key", "123");
System.out.println("onConstruct, args size=" + interceptorContext.allArguments().length);
}
@Override
public void beforeMethod(EnhancedClassInstanceContext context, InstanceMethodInvokeContext interceptorContext, MethodInterceptResult result) {
System.out.println("beforeMethod : " + context.get("sample.key", String.class));
System.out.println("beforeMethod : " + context.get("test.key", String.class));
}
@Override
public Object afterMethod(EnhancedClassInstanceContext context, InstanceMethodInvokeContext interceptorContext, Object ret) {
System.out.println("afterMethod: " + context.get("sample.key", String.class));
System.out.println("afterMethod: " + context.get("test.key", String.class));
return ret;
}
......
......@@ -10,7 +10,7 @@ public class TestInterceptorDefine extends ClassEnhancePluginDefine {
@Override
public String enhanceClassName() {
return "sample.ai.cloud.plugin.BeInterceptedClass";
return "test.ai.cloud.plugin.BeInterceptedClass";
}
@Override
......
......@@ -8,7 +8,7 @@ import com.ai.cloud.skywalking.protocol.common.SpanType;
public class SerializeTest {
public static void main(String[] args) throws InterruptedException {
while (true) {
Span spandata = new Span("1.0b.1461060884539.7d6d06e.22489.1271.103", "", 0, "sample-application", "test");
Span spandata = new Span("1.0b.1461060884539.7d6d06e.22489.1271.103", "", 0, "test-application", "test");
spandata.setSpanType(SpanType.LOCAL);
spandata.setStartDate(System.currentTimeMillis() - 1000 * 60);
AckSpan requestSpan = new AckSpan(spandata);
......
......@@ -15,7 +15,7 @@ public class DubboConsumer {
@Test
public void test() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbo.consumer.DubboConsumer"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.test.dubbo.consumer.DubboConsumer"});
}
public static void main(String[] args) throws InterruptedException {
......@@ -23,7 +23,7 @@ public class DubboConsumer {
IDubboInterA dubboInterA = context.getBean(IDubboInterA.class);
dubboInterA.doBusiness("AAAAA");
RequestSpanAssert.assertEquals(new String[][]{
{"0", "dubbo://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.sample.dubbo.interfaces.IDubboInterA.doBusiness(String)", ""}
{"0", "dubbo://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.test.dubbo.interfaces.IDubboInterA.doBusiness(String)", ""}
});
}
}
......@@ -11,7 +11,7 @@ public class DubboStart {
@Test
public void test() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbo.impl.DubboStart"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.test.dubbo.impl.DubboStart"});
}
public static void main(String[] args) throws InterruptedException {
......
......@@ -20,7 +20,7 @@ public class DubboxRestConsumer {
@Test
public void test() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap.main(new String[] {"com.ai.cloud.skywalking.plugin.sample.dubbox283.consumer.DubboxRestConsumer"});
TracingBootstrap.main(new String[] {"com.ai.cloud.skywalking.plugin.test.dubbox283.consumer.DubboxRestConsumer"});
}
public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
......@@ -29,6 +29,6 @@ public class DubboxRestConsumer {
IDubboxRestInterA dubboxRestInterA = context.getBean(IDubboxRestInterA.class);
dubboxRestInterA.doBusiness(new DubboxRestInterAParameter("AAAAA"));
RequestSpanAssert.assertEquals(new String[][] {
{"0", "rest://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.sample.dubbox283.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
{"0", "rest://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.test.dubbox283.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
}
}
......@@ -12,7 +12,7 @@ public class DubboxRestStart {
@Test
public void test() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbox283.consumer.DubboxRestStart"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.test.dubbox283.consumer.DubboxRestStart"});
}
public static void main(String[] args) throws InterruptedException {
......
......@@ -19,7 +19,7 @@ public class DubboxRestConsumer {
@Test
public void test() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap.main(new String[] {"com.ai.cloud.skywalking.plugin.sample.dubbox284.consumer.DubboxRestConsumer"});
TracingBootstrap.main(new String[] {"com.ai.cloud.skywalking.plugin.test.dubbox284.consumer.DubboxRestConsumer"});
}
public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
......@@ -27,6 +27,6 @@ public class DubboxRestConsumer {
IDubboxRestInterA dubboxRestInterA = context.getBean(IDubboxRestInterA.class);
dubboxRestInterA.doBusiness(new DubboxRestInterAParameter("AAAAA"));
RequestSpanAssert.assertEquals(new String[][] {
{"0", "rest://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.sample.dubbox284.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
{"0", "rest://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.test.dubbox284.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
}
}
......@@ -12,7 +12,7 @@ public class DubboxRestStart {
@Test
public void test() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbox284.consumer.DubboxRestStart"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.test.dubbox284.consumer.DubboxRestStart"});
}
public static void main(String[] args) throws InterruptedException {
......
......@@ -15,7 +15,7 @@ public class JDBCPluginDefine extends BootPluginDefine {
private static Logger logger = LogManager.getLogger(JDBCPluginDefine.class);
@Override
protected byte[] boot() throws BootException {
protected void boot() throws BootException {
try {
Class<?> classes = Class.forName("java.sql.DriverInfo");
Object traceDriverInfo = newDriverInfoInstance(classes);
......@@ -31,8 +31,6 @@ public class JDBCPluginDefine extends BootPluginDefine {
e);
TracingDriver.registerDriver();
}
return null;
}
private Object newDriverInfoInstance(Class<?> classes) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {
......
......@@ -10,7 +10,7 @@ import java.sql.SQLException;
*/
public class TestMyDriver {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("sample.ai.cloud.skywalking.plugin.drivermanger.MyDriver");
Class.forName("test.ai.cloud.skywalking.plugin.drivermanger.MyDriver");
String url = "jdbc:oracle:thin:@10.1.130.239:1521:ora";
Connection con = DriverManager.getConnection(url, "edc_export", "edc_export");
con.setAutoCommit(false);
......
......@@ -18,7 +18,7 @@ public class H2JDBCTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:" + H2JDBCTest.class.getResource("/") + "sample.db";
String url = "jdbc:h2:" + H2JDBCTest.class.getResource("/") + "test.db";
Connection con = DriverManager.getConnection(url);
con.setAutoCommit(false);
......@@ -28,9 +28,9 @@ public class H2JDBCTest {
con.commit();
con.close();
RequestSpanAssert.assertEquals(
new String[][]{{"0", "jdbc:h2:" +H2JDBCTest.class.getResource("/") + "sample.db" + "(null)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?"},
{"0", "jdbc:h2:" +H2JDBCTest.class.getResource("/") + "sample.db" + "(null)", "connection.commit"},
{"0", "jdbc:h2:" +H2JDBCTest.class.getResource("/") + "sample.db" + "(null)", "connection.close"},}, true);
new String[][]{{"0", "jdbc:h2:" +H2JDBCTest.class.getResource("/") + "test.db" + "(null)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?"},
{"0", "jdbc:h2:" +H2JDBCTest.class.getResource("/") + "test.db" + "(null)", "connection.commit"},
{"0", "jdbc:h2:" +H2JDBCTest.class.getResource("/") + "test.db" + "(null)", "connection.close"},}, true);
}
}
......@@ -14,12 +14,12 @@ public class MysqlJDBCTest {
@Test
public void testMySqlJDBC() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap.main(new String[] {"sample.ai.cloud.skywalking.plugin.mysql.MysqlJDBCTest"});
TracingBootstrap.main(new String[] {"test.ai.cloud.skywalking.plugin.mysql.MysqlJDBCTest"});
}
public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {
Class.forName("com.mysql.jdbc.Driver");
String url = "tracing:jdbc:mysql://127.0.0.1:3306/sample?user=root&password=root";
String url = "tracing:jdbc:mysql://127.0.0.1:3306/test?user=root&password=root";
Connection con = DriverManager.getConnection(url);
con.setAutoCommit(false);
......@@ -29,9 +29,9 @@ public class MysqlJDBCTest {
con.commit();
con.close();
RequestSpanAssert.assertEquals(
new String[][] {{"0", "jdbc:mysql://127.0.0.1:3306/sample?user=root&password=root(null)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?"},
{"0", "jdbc:mysql://127.0.0.1:3306/sample?user=root&password=root(null)", "connection.commit"},
{"0", "jdbc:mysql://127.0.0.1:3306/sample?user=root&password=root(null)", "connection.close"},}, true);
new String[][] {{"0", "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root(null)", "preaparedStatement.executeUpdate:select 1 from dual where 1=?"},
{"0", "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root(null)", "connection.commit"},
{"0", "jdbc:mysql://127.0.0.1:3306/test?user=root&password=root(null)", "connection.close"},}, true);
}
......
......@@ -20,7 +20,7 @@ public class OracleJDBCTest {
NoSuchMethodException, ClassNotFoundException,
IllegalAccessException {
TracingBootstrap
.main(new String[]{"sample.ai.cloud.skywalking.plugin.oracle.OracleJDBCTest"});
.main(new String[]{"test.ai.cloud.skywalking.plugin.oracle.OracleJDBCTest"});
}
public static void main(String[] args) throws ClassNotFoundException,
......
......@@ -52,7 +52,7 @@
<groupId>com.ai.cloud</groupId>
<artifactId>skywalking-auth</artifactId>
<version>${project.version}</version>
<scope>sample</scope>
<scope>test</scope>
</dependency>
-->
<dependency>
......
#Generated by Maven
#Mon Jul 25 22:41:11 CST 2016
version=1.0-Final
groupId=com.ai.cloud
artifactId=tomcat-7.x-8.x-plugin
com/ai/cloud/skywalking/plugin/tomcat78x/TomcatPluginInterceptor.class
com/ai/cloud/skywalking/plugin/tomcat78x/WebBuriedPointType.class
com/ai/cloud/skywalking/plugin/tomcat78x/define/TomcatPluginDefine.class
/Users/xin/workbench/sky-walking/skywalking-collector/skywalking-sdk-plugin/tomcat-7.x-8.x-plugin/src/main/java/com/ai/cloud/skywalking/plugin/tomcat78x/TomcatPluginInterceptor.java
/Users/xin/workbench/sky-walking/skywalking-collector/skywalking-sdk-plugin/tomcat-7.x-8.x-plugin/src/main/java/com/ai/cloud/skywalking/plugin/tomcat78x/define/TomcatPluginDefine.java
/Users/xin/workbench/sky-walking/skywalking-collector/skywalking-sdk-plugin/tomcat-7.x-8.x-plugin/src/main/java/com/ai/cloud/skywalking/plugin/tomcat78x/WebBuriedPointType.java
......@@ -28,7 +28,7 @@
<groupId>com.ai.cloud</groupId>
<artifactId>skywalking-auth</artifactId>
<version>${project.version}</version>
<scope>sample</scope>
<scope>test</scope>
</dependency>
-->
<dependency>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册