forked from alibaba/transmittable-thread-local
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TtlTransformer.java
142 lines (124 loc) · 5.89 KB
/
TtlTransformer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package com.alibaba.ttl.threadpool.agent;
import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.TtlRunnable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
/**
* @author Jerry Lee (oldratlee at gmail dot com)
* @since 0.9.0
*/
public class TtlTransformer implements ClassFileTransformer {
private static final Logger logger = Logger.getLogger(TtlTransformer.class.getName());
private static final String RUNNABLE_CLASS_NAME = "java.lang.Runnable";
private static final String CALLABLE_CLASS_NAME = "java.util.concurrent.Callable";
private static final String TTL_RUNNABLE_CLASS_NAME = TtlRunnable.class.getName();
private static final String TTL_CALLABLE_CLASS_NAME = TtlCallable.class.getName();
private static final String THREAD_POOL_CLASS_FILE = "java.util.concurrent.ThreadPoolExecutor".replace('.', '/');
private static final String SCHEDULER_CLASS_FILE = "java.util.concurrent.ScheduledThreadPoolExecutor".replace('.', '/');
private static final String TIMER_TASK_CLASS_FILE = "java.util.TimerTask".replace('.', '/');
private static final byte[] EMPTY_BYTE_ARRAY = {};
private static String toClassName(String classFile) {
return classFile.replace('/', '.');
}
@Override
public byte[] transform(ClassLoader loader, String classFile, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classFileBuffer) throws IllegalClassFormatException {
try {
// Lambda has no class file, no need to transform, just return.
if(classFile == null) {
return EMPTY_BYTE_ARRAY;
}
final String className = toClassName(classFile);
if (THREAD_POOL_CLASS_FILE.equals(classFile) || SCHEDULER_CLASS_FILE.equals(classFile)) {
logger.info("Transforming class " + className);
CtClass clazz = getCtClass(classFileBuffer, loader);
for (CtMethod method : clazz.getDeclaredMethods()) {
updateMethod(clazz, method);
}
return clazz.toBytecode();
} else if (TIMER_TASK_CLASS_FILE.equals(classFile)) {
CtClass clazz = getCtClass(classFileBuffer, loader);
while (true) {
String name = clazz.getSuperclass().getName();
if (Object.class.getName().equals(name)) {
break;
}
if (TIMER_TASK_CLASS_FILE.equals(name)) {
logger.info("Transforming class " + className);
// FIXME add code here
return EMPTY_BYTE_ARRAY;
}
}
}
} catch (Throwable t) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
t.printStackTrace(printWriter);
String msg = "Fail to transform class " + classFile + ", cause: " + stringWriter.toString();
logger.severe(msg);
throw new IllegalStateException(msg, t);
}
return EMPTY_BYTE_ARRAY;
}
private CtClass getCtClass(byte[] classFileBuffer, ClassLoader classLoader) throws IOException {
ClassPool classPool = new ClassPool(true);
if (null != classLoader) {
classPool.appendClassPath(new LoaderClassPath(classLoader));
}
CtClass clazz = classPool.makeClass(new ByteArrayInputStream(classFileBuffer), false);
clazz.defrost();
return clazz;
}
static final Set<String> updateMethodNames = new HashSet<String>();
static {
updateMethodNames.add("execute");
updateMethodNames.add("submit");
updateMethodNames.add("schedule");
updateMethodNames.add("scheduleAtFixedRate");
updateMethodNames.add("scheduleWithFixedDelay");
}
static void updateMethod(CtClass clazz, CtMethod method) throws NotFoundException, CannotCompileException {
if (!updateMethodNames.contains(method.getName())) {
return;
}
if (method.getDeclaringClass() != clazz) {
return;
}
final int modifiers = method.getModifiers();
if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers)) {
return;
}
CtClass[] parameterTypes = method.getParameterTypes();
StringBuilder insertCode = new StringBuilder();
for (int i = 0; i < parameterTypes.length; i++) {
CtClass paraType = parameterTypes[i];
if (RUNNABLE_CLASS_NAME.equals(paraType.getName())) {
String code = String.format("$%d = %s.get($%d, false, true);", i + 1, TTL_RUNNABLE_CLASS_NAME, i + 1);
logger.info("insert code before method " + method + " of class " + method.getDeclaringClass().getName() + ": " + code);
insertCode.append(code);
} else if (CALLABLE_CLASS_NAME.equals(paraType.getName())) {
String code = String.format("$%d = %s.get($%d, false, true);", i + 1, TTL_CALLABLE_CLASS_NAME, i + 1);
logger.info("insert code before method " + method + " of class " + method.getDeclaringClass().getName() + ": " + code);
insertCode.append(code);
}
}
if (insertCode.length() > 0) {
method.insertBefore(insertCode.toString());
}
}
}