提交未提交代码

This commit is contained in:
ascrutae 2016-07-26 09:37:59 +08:00
parent 7ac79a3eeb
commit f08ca13a15
51 changed files with 500 additions and 472 deletions

View File

@ -17,8 +17,6 @@
<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>
@ -85,10 +83,6 @@
</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>

View File

@ -1,23 +1,35 @@
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();
}
}

View File

@ -1,7 +1,55 @@
package com.ai.cloud.skywalking.agent.transformer;
/**
* Created by xin on 16/7/24.
*/
public class PluginsTransformer {
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;
}
}

View File

@ -26,12 +26,6 @@
<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>

View File

@ -1,6 +1,8 @@
package com.ai.cloud.skywalking.plugin;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
public interface IPlugin {
public void define() throws PluginException;
byte[] define() throws PluginException;
}

View File

@ -3,54 +3,57 @@ 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 net.bytebuddy.pool.TypePool;
import com.ai.cloud.skywalking.plugin.interceptor.enhance.ClassEnhancePluginDefine;
import javassist.ClassPool;
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 TypePool CLASS_TYPE_POOL = null;
public static ClassPool CLASS_TYPE_POOL = null;
public void start() {
public Map<String, ClassEnhancePluginDefine> loadPlugins() {
if (!AuthDesc.isAuth()) {
return;
return null;
}
CLASS_TYPE_POOL = TypePool.Default.ofClassPath();
CLASS_TYPE_POOL = ClassPool.getDefault();
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;
return new HashMap<String, ClassEnhancePluginDefine>();
}
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();
plugin.define();
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);
}
} 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;
}
}

View File

@ -29,7 +29,7 @@ public class TracingBootstrap {
try {
PluginBootstrap bootstrap = new PluginBootstrap();
bootstrap.start();
bootstrap.loadPlugins();
} catch (Throwable t) {
logger.error("PluginBootstrap start failure.", t);
}

View File

@ -1,6 +1,6 @@
package com.ai.cloud.skywalking.plugin.boot;
import com.ai.cloud.skywalking.plugin.PluginException;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
public class BootException extends PluginException {
private static final long serialVersionUID = 8618884011525098003L;

View File

@ -1,15 +1,15 @@
package com.ai.cloud.skywalking.plugin.boot;
import com.ai.cloud.skywalking.plugin.IPlugin;
import com.ai.cloud.skywalking.plugin.PluginException;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
public abstract class BootPluginDefine implements IPlugin {
@Override
public void define() throws PluginException {
this.boot();
public byte[] define() throws PluginException {
return this.boot();
}
protected abstract void boot() throws BootException;
protected abstract byte[] boot() throws BootException;
}

View File

@ -1,7 +1,12 @@
package com.ai.cloud.skywalking.plugin.exception;
/**
* Created by xin on 16/7/25.
*/
public class EnhanceClassEmptyException {
public class EnhanceClassEmptyException extends PluginException{
public EnhanceClassEmptyException(String message) {
super(message);
}
public EnhanceClassEmptyException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@ -1,7 +1,8 @@
package com.ai.cloud.skywalking.plugin.exception;
/**
* Created by xin on 16/7/25.
*/
public class EnhanceClassNotFoundException {
public class EnhanceClassNotFoundException extends PluginException{
public EnhanceClassNotFoundException(String message) {
super(message);
}
}

View File

@ -3,5 +3,8 @@ package com.ai.cloud.skywalking.plugin.exception;
/**
* Created by xin on 16/7/25.
*/
public class WitnessClassesCannotFound {
public class WitnessClassesCannotFound extends PluginException {
public WitnessClassesCannotFound(String message) {
super(message);
}
}

View File

@ -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.PluginException;
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.protocol.util.StringUtil;
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 javassist.ClassPool;
import javassist.CtClass;
import static com.ai.cloud.skywalking.plugin.PluginBootstrap.CLASS_TYPE_POOL;
@ -17,64 +17,58 @@ public abstract class AbstractClassEnhancePluginDefine implements IPlugin {
private static Logger logger = LogManager.getLogger(AbstractClassEnhancePluginDefine.class);
@Override
public void define() throws PluginException {
public byte[] 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);
return;
logger.warn("classname of being intercepted is not defined by {}.", interceptorDefineClassName);
throw new EnhanceClassEmptyException("class name of being is not deined by " + interceptorDefineClassName);
}
logger.debug("prepare to enhance class {} by {}.",
enhanceOriginClassName, interceptorDefineClassName);
logger.debug("prepare to enhance class {} by {}.", enhanceOriginClassName, interceptorDefineClassName);
Resolution resolution = CLASS_TYPE_POOL.describe(enhanceOriginClassName);
if (!resolution.isResolved()) {
logger.warn("class {} can't be resolved, enhance by {} failue.",
enhanceOriginClassName, interceptorDefineClassName);
return;
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.");
}
/**
* find witness classes for enhance class
*/
String[] witnessClasses = witnessClasses();
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;
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) {
}
}
}
/**
* find origin class source code for interceptor
*/
DynamicType.Builder<?> newClassBuilder = new ByteBuddy()
.rebase(resolution.resolve(),
ClassFileLocator.ForClassLoader.ofClassPath());
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);
return enhance(ctClass);
}
protected abstract DynamicType.Builder<?> enhance(String enhanceOriginClassName, DynamicType.Builder<?> newClassBuilder) throws PluginException;
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.");
}
}
protected abstract byte[] enhance(CtClass ctClass) throws PluginException;
/**
* 返回要被增强的类应当返回类全名
@ -89,7 +83,7 @@ public abstract class AbstractClassEnhancePluginDefine implements IPlugin {
*
* @return
*/
protected String[] witnessClasses(){
return new String[]{};
protected String[] witnessClasses() {
return new String[] {};
}
}

View File

@ -1,6 +1,6 @@
package com.ai.cloud.skywalking.plugin.interceptor;
import com.ai.cloud.skywalking.plugin.PluginException;
import com.ai.cloud.skywalking.plugin.exception.PluginException;
public class EnhanceException extends PluginException {
private static final long serialVersionUID = -2234782755784217255L;

View File

@ -1,9 +1,6 @@
package com.ai.cloud.skywalking.plugin.interceptor;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.*;
import javassist.CtMethod;
public abstract class MethodMatcher {
@ -45,48 +42,29 @@ 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));
}
if (argNum > -1) {
matcher = matcher.and(takesArguments(argNum));
}
if (modifier != null) {
matcher = matcher.and(modifier.elementMatcher());
}
return matcher;
}
public abstract boolean match(CtMethod ctMethod);
public enum Modifier {
Public, Default, Private, Protected;
Public(0x00000001),
Default(0x00000000),
Private(0x00000002),
Protected(0x00000004);
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();
}
private int value;
Modifier(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
@ -94,7 +72,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) {
@ -105,11 +83,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());
}
}

View File

@ -2,37 +2,27 @@ 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;
}
@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);
}
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);
}
}
}
}

View File

@ -1,182 +1,129 @@
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 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.exception.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);
private static Logger logger = LogManager.getLogger(ClassEnhancePluginDefine.class);
public static final String contextAttrName = "_$EnhancedClassInstanceContext";
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;
}
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);
}
}
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. ");
}
return ctClass.toBytecode();
} catch (Exception e) {
throw new PluginException("Can not compile the class", e);
}
}
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))));
private void enhanceClass(CtClass ctClass, CtMethod method) throws CannotCompileException, NotFoundException {
boolean isMatch = false;
for (MethodMatcher methodMatcher : getStaticMethodsMatchers()) {
if (methodMatcher.match(method)) {
isMatch = true;
break;
}
}
ClassInstanceMethodsInterceptor classMethodInterceptor = new ClassInstanceMethodsInterceptor(
interceptor);
if (isMatch) {
// 修改方法名,
String methodName = method.getName();
String newMethodName = methodName + "_$SkywalkingEnhance";
method.setName(newMethodName);
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;
}
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) + ");}");
matcher = matcher.or(methodMatcher.buildMatcher());
ctClass.addMethod(newMethod);
}
}
}
/**
* exclude static methods.
*/
matcher = matcher.and(not(ElementMatchers.isStatic()));
newClassBuilder = newClassBuilder.method(matcher).intercept(
MethodDelegation.to(classMethodInterceptor));
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));
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);
// 初始化构造函数
CtConstructor[] constructors = ctClass.getDeclaredConstructors();
for (CtConstructor constructor : constructors) {
constructor.insertAfter(" new " + ClassConstructorInterceptor.class.getName() + "(new " + getInstanceMethodsInterceptor().getClass().getName() + "()).intercept($0,$0."
+ contextAttrName + ",$args);");
}
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;
}
boolean isMatch = false;
for (MethodMatcher methodMatcher : getInstanceMethodsMatchers()) {
if (methodMatcher.match(method)) {
isMatch = true;
break;
}
}
matcher = matcher.or(methodMatcher.buildMatcher());
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 + ");}");
/**
* restrict static methods.
*/
matcher = matcher.and(ElementMatchers.isStatic());
newClassBuilder = newClassBuilder.method(matcher).intercept(
MethodDelegation.to(classMethodInterceptor));
ctClass.addMethod(newMethod);
}
}
return newClassBuilder;
}
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getStaticMethodsMatchers();
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getInstanceMethodsMatchers();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部保持单例
*
* @return
*/
protected abstract StaticMethodsAroundInterceptor getStaticMethodsInterceptor();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部保持单例
*
* @return
*/
protected abstract InstanceMethodsAroundInterceptor getInstanceMethodsInterceptor();
/**
* 返回需要被增强的方法列表
*
* @return
*/
protected abstract MethodMatcher[] getStaticMethodsMatchers();
/**
* 返回增强拦截器的实现<br/>
* 每个拦截器在同一个被增强类的内部保持单例
*
* @return
*/
protected abstract StaticMethodsAroundInterceptor getStaticMethodsInterceptor();
}

View File

@ -3,10 +3,6 @@ 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;
/**
* 类方法拦截控制器
@ -14,8 +10,7 @@ import java.util.concurrent.Callable;
* @author wusheng
*/
public class ClassInstanceMethodsInterceptor {
private static Logger logger = LogManager
.getLogger(ClassInstanceMethodsInterceptor.class);
private static Logger logger = LogManager.getLogger(ClassInstanceMethodsInterceptor.class);
private InstanceMethodsAroundInterceptor interceptor;
@ -23,22 +18,13 @@ public class ClassInstanceMethodsInterceptor {
this.interceptor = interceptor;
}
@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);
public Object intercept(Object obj, Object[] allArguments, String methodName, OriginCall zuper, EnhancedClassInstanceContext instanceContext) throws Exception {
InstanceMethodInvokeContext interceptorContext = new InstanceMethodInvokeContext(obj, methodName, 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(), method.getName(), t.getMessage()}, t);
logger.error("class[{}] before method[{}] intercept failue:{}", new Object[] {obj.getClass(), methodName, t.getMessage()}, t);
}
if (!result.isContinue()) {
return result._ret();
@ -51,16 +37,14 @@ public class ClassInstanceMethodsInterceptor {
try {
interceptor.handleMethodException(t, instanceContext, interceptorContext, ret);
} catch (Throwable t2) {
logger.error("class[{}] handle method[{}] exception failue:{}",
new Object[]{obj.getClass(), method.getName(), t2.getMessage()}, t2);
logger.error("class[{}] handle method[{}] exception failue:{}", new Object[] {obj.getClass(), methodName, 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(), method.getName(), t.getMessage()}, t);
logger.error("class[{}] after method[{}] intercept failue:{}", new Object[] {obj.getClass(), methodName, t.getMessage()}, t);
}
}
return ret;

View File

@ -2,13 +2,6 @@ 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;
/**
* 类静态方法拦截控制器
@ -24,14 +17,13 @@ public class ClassStaticMethodsInterceptor {
this.interceptor = interceptor;
}
@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);
public Object intercept(Class<?> clazz, Object[] allArguments, String methodName, OriginCall zuper) throws Exception {
MethodInvokeContext interceptorContext = new MethodInvokeContext(methodName, allArguments);
MethodInterceptResult result = new MethodInterceptResult();
try {
interceptor.beforeMethod(interceptorContext, result);
} catch (Throwable t) {
logger.error("class[{}] before static method[{}] intercept failue:{}", new Object[] {clazz, method.getName(), t.getMessage()}, t);
logger.error("class[{}] before static method[{}] intercept failue:{}", new Object[] {clazz, methodName, t.getMessage()}, t);
}
if (!result.isContinue()) {
return result._ret();
@ -44,14 +36,14 @@ public class ClassStaticMethodsInterceptor {
try {
interceptor.handleMethodException(t, interceptorContext, ret);
} catch (Throwable t2) {
logger.error("class[{}] handle static method[{}] exception failue:{}", new Object[] {clazz, method.getName(), t2.getMessage()}, t2);
logger.error("class[{}] handle static method[{}] exception failue:{}", new Object[] {clazz, methodName, 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, method.getName(), t.getMessage()}, t);
logger.error("class[{}] after static method[{}] intercept failue:{}", new Object[] {clazz, methodName, t.getMessage()}, t);
}
}
return ret;

View File

@ -1,7 +1,51 @@
package com.ai.cloud.skywalking.plugin.interceptor.enhance;
/**
* Created by xin on 16/7/26.
*/
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;
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);
}
}

View File

@ -1,9 +1,6 @@
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.any;
import javassist.CtMethod;
public class AnyMethodsMatcher extends ExclusiveObjectDefaultMethodsMatcher {
@ -11,13 +8,14 @@ public class AnyMethodsMatcher extends ExclusiveObjectDefaultMethodsMatcher {
super("any method");
}
@Override
public ElementMatcher.Junction<MethodDescription> match() {
return any();
}
@Override
public String toString() {
return getMethodMatchDescribe();
}
@Override
public boolean matchMethod(CtMethod ctMethod) {
return true;
}
}

View File

@ -1,51 +1,37 @@
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import static net.bytebuddy.matcher.ElementMatchers.not;
import javassist.CtMethod;
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 ElementMatcher.Junction<MethodDescription> buildMatcher() {
return this.match().and(excludeObjectDefaultMethod());
public boolean match(CtMethod ctMethod) {
return this.matchMethod(ctMethod) && excludeObjectDefaultMethod(ctMethod);
}
protected ElementMatcher.Junction<MethodDescription> excludeObjectDefaultMethod() {
ElementMatcher.Junction<MethodDescription> exclusiveMatcher = null;
protected boolean excludeObjectDefaultMethod(CtMethod ctMethod) {
for (MethodMatcher methodMatcher : EXCLUSIVE_DEFAULT_METHOD_NAME) {
if (exclusiveMatcher == null) {
exclusiveMatcher = methodMatcher.buildMatcher();
continue;
if (methodMatcher.match(ctMethod)) {
return false;
}
exclusiveMatcher = exclusiveMatcher.or(methodMatcher.buildMatcher());
}
return not(exclusiveMatcher);
return true;
}
public abstract ElementMatcher.Junction<MethodDescription> match();
public abstract boolean matchMethod(CtMethod ctMethod);
}

View File

@ -1,15 +1,12 @@
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import javassist.CtMethod;
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>();
@ -26,30 +23,25 @@ public class MethodsExclusiveMatcher extends ExclusiveObjectDefaultMethodsMatche
this.matchers.addAll(Arrays.asList(matchers));
}
@Override
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 not(result);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("exclude following method(s): ");
int idx = 1;
for (MethodMatcher methodMatcher : matchers) {
stringBuilder.append(idx++ + "." + methodMatcher.toString() + ". ");
stringBuilder.append(idx++ + "." + methodMatcher.toString() + ". ");
}
return stringBuilder.toString();
}
@Override
public boolean matchMethod(CtMethod ctMethod) {
boolean result = false;
for (MethodMatcher methodMatcher : matchers) {
if (methodMatcher.match(ctMethod)) {
result = result || result;
}
}
return !result;
}
}

View File

@ -1,11 +1,7 @@
package com.ai.cloud.skywalking.plugin.interceptor.matcher;
import com.ai.cloud.skywalking.plugin.interceptor.MethodMatcher;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import static net.bytebuddy.matcher.ElementMatchers.any;
import javassist.CtMethod;
public class PrivateMethodMatcher extends MethodMatcher {
public PrivateMethodMatcher() {
@ -13,8 +9,8 @@ public class PrivateMethodMatcher extends MethodMatcher {
}
@Override
public ElementMatcher.Junction<MethodDescription> buildMatcher() {
return any().and(ElementMatchers.<MethodDescription>isPrivate());
public boolean match(CtMethod ctMethod) {
return java.lang.reflect.Modifier.isPrivate(ctMethod.getModifiers());
}
@Override

View File

@ -1,10 +1,8 @@
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 {
@ -33,10 +31,42 @@ public class SimpleMethodMatcher extends MethodMatcher {
super(modifier, methodMatchDescribe, argTypeArray);
}
@Override
public ElementMatcher.Junction<MethodDescription> buildMatcher() {
ElementMatcher.Junction<MethodDescription> matcher = named(getMethodMatchDescribe());
return mergeArgumentsIfNecessary(matcher);
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;
}
}

View File

@ -37,7 +37,13 @@ public final class ContextGenerator {
spanData = new Span(TraceIdGenerator.generate(), Config.SkyWalking.APPLICATION_CODE, Config.SkyWalking.USER_ID);
} else {
// 如果不为空则将当前的Context存放到上下文
spanData = new Span(context.getTraceId(), context.getParentLevel(), context.getLevelId(), Config.SkyWalking.APPLICATION_CODE, Config.SkyWalking.USER_ID);
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.setStartDate(System.currentTimeMillis());

View File

@ -0,0 +1,11 @@
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%($$);
}
}

View File

@ -1 +1,6 @@
new Origin
new com.ai.cloud.skywalking.plugin.interceptor.enhance.OriginCall(){
public Object call(){
return %class_name%.%method_name%($$);
}
}

View File

@ -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, "test-application", "5");
Span testSpan = new Span("1.0b.1465224457414.7e57f54.22905.61.2691", "", 0, "sample-application", "5");
RequestSpan requestSpan =
RequestSpan.RequestSpanBuilder.newBuilder(testSpan).viewPoint("http://hire.asiainfo.com/Aisse-Mobile-Web/aisseWorkPage/submitReimbursement").build();
ContextBuffer.save(requestSpan);

View File

@ -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("test.ai.cloud.matcher.TestMatcherClass").newInstance();
//new PluginBootstrap().start();
TestMatcherClass testMatcherClass = (TestMatcherClass) Class.forName("sample.ai.cloud.matcher.TestMatcherClass").newInstance();
testMatcherClass.set();
testMatcherClass.seta("a");

View File

@ -11,7 +11,7 @@ import com.ai.cloud.skywalking.plugin.interceptor.matcher.PrivateMethodMatcher;
public class TestMatcherDefine extends ClassInstanceMethodsEnhancePluginDefine {
@Override
public String enhanceClassName() {
return "test.ai.cloud.matcher.TestMatcherClass";
return "sample.ai.cloud.matcher.TestMatcherClass";
}
@Override

View File

@ -12,13 +12,13 @@ public class PluginMainTest {
IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException, ClassNotFoundException {
TracingBootstrap
.main(new String[] { "test.ai.cloud.plugin.PluginMainTest" });
.main(new String[] { "sample.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("test.ai.cloud.plugin.BeInterceptedClass").newInstance();
BeInterceptedClass inst = (BeInterceptedClass) Class.forName("sample.ai.cloud.plugin.BeInterceptedClass").newInstance();
inst.printabc();
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");

View File

@ -10,18 +10,18 @@ public class TestAroundInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void onConstruct(EnhancedClassInstanceContext context, ConstructorInvokeContext interceptorContext) {
context.set("test.key", "123");
context.set("sample.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("test.key", String.class));
System.out.println("beforeMethod : " + context.get("sample.key", String.class));
}
@Override
public Object afterMethod(EnhancedClassInstanceContext context, InstanceMethodInvokeContext interceptorContext, Object ret) {
System.out.println("afterMethod: " + context.get("test.key", String.class));
System.out.println("afterMethod: " + context.get("sample.key", String.class));
return ret;
}

View File

@ -10,7 +10,7 @@ public class TestInterceptorDefine extends ClassEnhancePluginDefine {
@Override
public String enhanceClassName() {
return "test.ai.cloud.plugin.BeInterceptedClass";
return "sample.ai.cloud.plugin.BeInterceptedClass";
}
@Override

View File

@ -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, "test-application", "test");
Span spandata = new Span("1.0b.1461060884539.7d6d06e.22489.1271.103", "", 0, "sample-application", "test");
spandata.setSpanType(SpanType.LOCAL);
spandata.setStartDate(System.currentTimeMillis() - 1000 * 60);
AckSpan requestSpan = new AckSpan(spandata);

View File

@ -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.test.dubbo.consumer.DubboConsumer"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.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.test.dubbo.interfaces.IDubboInterA.doBusiness(String)", ""}
{"0", "dubbo://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.sample.dubbo.interfaces.IDubboInterA.doBusiness(String)", ""}
});
}
}

View File

@ -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.test.dubbo.impl.DubboStart"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbo.impl.DubboStart"});
}
public static void main(String[] args) throws InterruptedException {

View File

@ -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.test.dubbox283.consumer.DubboxRestConsumer"});
TracingBootstrap.main(new String[] {"com.ai.cloud.skywalking.plugin.sample.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.test.dubbox283.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
{"0", "rest://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.sample.dubbox283.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
}
}

View File

@ -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.test.dubbox283.consumer.DubboxRestStart"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbox283.consumer.DubboxRestStart"});
}
public static void main(String[] args) throws InterruptedException {

View File

@ -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.test.dubbox284.consumer.DubboxRestConsumer"});
TracingBootstrap.main(new String[] {"com.ai.cloud.skywalking.plugin.sample.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.test.dubbox284.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
{"0", "rest://127.0.0.1:20880/com.ai.cloud.skywalking.plugin.sample.dubbox284.interfaces.IDubboxRestInterA.doBusiness(DubboxRestInterAParameter)", ""}});
}
}

View File

@ -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.test.dubbox284.consumer.DubboxRestStart"});
.main(new String[]{"com.ai.cloud.skywalking.plugin.sample.dubbox284.consumer.DubboxRestStart"});
}
public static void main(String[] args) throws InterruptedException {

View File

@ -15,7 +15,7 @@ public class JDBCPluginDefine extends BootPluginDefine {
private static Logger logger = LogManager.getLogger(JDBCPluginDefine.class);
@Override
protected void boot() throws BootException {
protected byte[] boot() throws BootException {
try {
Class<?> classes = Class.forName("java.sql.DriverInfo");
Object traceDriverInfo = newDriverInfoInstance(classes);
@ -31,6 +31,8 @@ public class JDBCPluginDefine extends BootPluginDefine {
e);
TracingDriver.registerDriver();
}
return null;
}
private Object newDriverInfoInstance(Class<?> classes) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException {

View File

@ -10,7 +10,7 @@ import java.sql.SQLException;
*/
public class TestMyDriver {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("test.ai.cloud.skywalking.plugin.drivermanger.MyDriver");
Class.forName("sample.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);

View File

@ -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("/") + "test.db";
String url = "jdbc:h2:" + H2JDBCTest.class.getResource("/") + "sample.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("/") + "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);
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);
}
}

View File

@ -14,12 +14,12 @@ public class MysqlJDBCTest {
@Test
public void testMySqlJDBC() throws InvocationTargetException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException {
TracingBootstrap.main(new String[] {"test.ai.cloud.skywalking.plugin.mysql.MysqlJDBCTest"});
TracingBootstrap.main(new String[] {"sample.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/test?user=root&password=root";
String url = "tracing:jdbc:mysql://127.0.0.1:3306/sample?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/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);
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);
}

View File

@ -20,7 +20,7 @@ public class OracleJDBCTest {
NoSuchMethodException, ClassNotFoundException,
IllegalAccessException {
TracingBootstrap
.main(new String[]{"test.ai.cloud.skywalking.plugin.oracle.OracleJDBCTest"});
.main(new String[]{"sample.ai.cloud.skywalking.plugin.oracle.OracleJDBCTest"});
}
public static void main(String[] args) throws ClassNotFoundException,

View File

@ -52,7 +52,7 @@
<groupId>com.ai.cloud</groupId>
<artifactId>skywalking-auth</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<scope>sample</scope>
</dependency>
-->
<dependency>

View File

@ -0,0 +1,5 @@
#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

View File

@ -0,0 +1,3 @@
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

View File

@ -0,0 +1,3 @@
/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

View File

@ -28,7 +28,7 @@
<groupId>com.ai.cloud</groupId>
<artifactId>skywalking-auth</artifactId>
<version>${project.version}</version>
<scope>test</scope>
<scope>sample</scope>
</dependency>
-->
<dependency>