一、什么是Javaagent
Javaagent是一个在Java应用程序启动时运行的程序,可以在不修改原始代码的情况下,对目标应用程序进行修改和增强。
Javaagent通过将提供的字节码转换器织入到目标应用程序的类加载器中来实现这种修改。
Javaagent可以用于很多方面,例如:性能监控、代码跟踪、JVM安全等。
二、Javaagent的使用方法
使用Javaagent需要在启动应用程序时,将Javaagent指定为启动参数。具体方法如下:
java -javaagent:/path/to/agent.jar -jar yourapp.jar
其中,/path/to/agent.jar为Javaagent的路径。在运行目标应用程序时,Java虚拟机会自动下载并加载Javaagent。
三、Javaagent的应用场景
1. 性能监控
Javaagent可以在目标应用程序中注入跟踪代码,用于监控应用程序的性能指标,例如:
1.1 监控方法调用次数
通过在方法调用前后记录时间戳,并统计方法调用次数,即可得到该方法的平均调用时间和总调用次数。
public class MethodCountAgent { private static final ConcurrentHashMap<String, AtomicLong> methodCountMap = new ConcurrentHashMap<String, AtomicLong>(); public static void premain(String agentArgs) { new AgentBuilder.Default().type(ElementMatchers.any()) .transform((builder, typeDescription, classLoader, module) -> builder .method(ElementMatchers.any()) .intercept(Advice.to(CountMethodAdvise.class))) .installOnBytecodeArtifact(); } public static class CountMethodAdvise { @Advice.OnMethodEnter public static void enter(@Advice.Origin Method method) { AtomicLong count = methodCountMap.get(method.getName()); if (count == null) { count = new AtomicLong(0L); methodCountMap.put(method.getName(), count); } count.incrementAndGet(); } @Advice.OnMethodExit(onThrowable = Throwable.class) public static void exit(@Advice.Origin Method method) { // do nothing } } }
1.2 监控方法执行时间
可以在方法调用前后记录时间戳,然后计算时间差值,即可得到方法的执行时间。
public class MethodTimeAgent { private static final ConcurrentHashMap<String, LongAdder> methodTimeMap = new ConcurrentHashMap<String, LongAdder>(); public static void premain(String agentArgs) { new AgentBuilder.Default().type(ElementMatchers.any()) .transform((builder, typeDescription, classLoader, module) -> builder .method(ElementMatchers.any()) .intercept(Advice.to(TimeMethodAdvise.class))) .installOnBytecodeArtifact(); } public static class TimeMethodAdvise { private static final ThreadLocal<Long> THREAD_LOCAL = new ThreadLocal<>(); @Advice.OnMethodEnter public static void enter() { THREAD_LOCAL.set(System.currentTimeMillis()); } @Advice.OnMethodExit(onThrowable = Throwable.class) public static void exit(@Advice.Origin Method method) { long startTime = THREAD_LOCAL.get(); long endTime = System.currentTimeMillis(); String methodName = method.getName(); LongAdder timeAdder = methodTimeMap.get(methodName); if (timeAdder == null) { timeAdder = new LongAdder(); methodTimeMap.put(methodName, timeAdder); } timeAdder.add(endTime - startTime); } } }
1.3 监控方法调用链
可以在方法调用前后记录方法名和时间戳,并将这些信息保存在线程上下文中或者日志文件中,即可得到方法调用链信息。
public class MethodTraceAgent { public static void premain(String agentArgs) { new AgentBuilder.Default().type(ElementMatchers.any()) .transform((builder, typeDescription, classLoader, module) -> builder .method(ElementMatchers.any()) .intercept(Advice.to(TraceMethodAdvise.class))) .installOnBytecodeArtifact(); } public static class TraceMethodAdvise { private static final ThreadLocal<LinkedList<String>> THREAD_LOCAL = ThreadLocal.withInitial(LinkedList::new); @Advice.OnMethodEnter public static void enter(@Advice.Origin Method method, @Advice.Local("methodStack") LinkedList<String> methodStack) { methodStack.addFirst(method.getName() + "<" + System.currentTimeMillis() + ">"); } @Advice.OnMethodExit(onThrowable = Throwable.class) public static void exit(@Advice.Origin Method method, @Advice.Local("methodStack") LinkedList<String> methodStack) { String poppedMethod = methodStack.removeFirst(); String methodName = method.getName(); int start = poppedMethod.length() - methodName.length() - 1; String currentMethod = poppedMethod.substring(0, start); System.out.println("Call " + currentMethod + " -> " + methodName); } @SuppressWarnings("unused") @Advice.OnMethodExit(onThrowable = Throwable.class) public static void exit(@Advice.Origin Method method) { // do nothing } @SuppressWarnings("unused") @Advice.OnMethodEnter public static void enter(@Advice.Origin Method method) { // do nothing } } }
2. JMX监控
Javaagent可以注入MBean服务,用于Java管理扩展(JMX)监控,以监控应用程序的性能指标。
public class MetricAgent { public static void premain(String agentArgs) { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName("com.example:type=Metric"); mBeanServer.registerMBean(new Metric(), objectName); new AgentBuilder.Default().type(ElementMatchers.any()) .transform((builder, typeDescription, classLoader, module) -> builder .method(ElementMatchers.any()) .intercept(Advice.to(MetricAdvise.class))) .installOnBytecodeArtifact(); } public static class Metric { // ... } public static class MetricAdvise { // ... } }
3. 特定应用场景
Javaagent可用于特定应用场景,例如:
3.1 改变类的行为
Javaagent可以使用字节码增强技术,来修改类的行为。例如,可以用Javaagent修改String类,使其在执行equals时,不区分大小写。
public class StringEqualsAgent { public static void premain(String agentArgs) { new AgentBuilder.Default().type(ElementMatchers.named("java.lang.String")) .transform((builder, typeDescription, classLoader, module) -> builder .defineMethod("equalsIgnoreCase", boolean.class, Visibility.PUBLIC) .withParameters(String.class) .intercept(MethodDelegation.to(StringEqualsIgnoreCase.class))) .installOnBytecodeArtifact(); } public static class StringEqualsIgnoreCase { @SuppressWarnings("unused") @RuntimeType public static boolean equalsIgnoreCase( @This Object thiz, @AllArguments Object[] arguments) { String anotherString = (String) arguments[0]; if (thiz instanceof String) { String thisString = (String) thiz; return thisString.equalsIgnoreCase(anotherString); } return false; } } }
3.2 拒绝反射机制的访问
Javaagent也可用于增强JVM的安全性。例如,可以拒绝应用程序通过反射机制访问java.lang.Runtime的exec()方法。
public class RuntimeAccessAgent { public static void premain(String agentArgs) { new AgentBuilder.Default().type(ElementMatchers.any()) .transform((builder, typeDescription, classLoader, module) -> builder .method(ElementMatchers.named("exec")) .intercept(MethodDelegation.to(RejectRuntimeAccess.class))) .installOnBytecodeArtifact(); } public static class RejectRuntimeAccess { @SuppressWarnings("unused") @RuntimeType public static Process exec(@This Object thiz, @AllArguments Object[] arguments) { throw new SecurityException("Javaagent rejected Runtime.exec()"); } } }
四、总结
Javaagent可以对Java应用程序进行监控、增强和安全管理等操作,不需要修改应用程序代码。
在大型生产环境中,Javaagent通常与监控系统结合使用,用于实时监控应用程序的性能和行为,并对问题进行分析和诊断。