Java Agent (JVM Instrumentation 机制) 极简教程

本文介绍了JavaAgent的基本概念,它是一个在main方法执行前的拦截器,可以用于热部署、线上诊断等场景。文章详细讲解了如何编写JavaAgent,包括创建MANIFEST.MF文件、指定启动类,以及如何通过VM参数或Attach方式加载Agent。通过示例展示了如何将Agent逻辑绑定到目标JVM进程上,实现动态干预程序行为。
摘要由CSDN通过智能技术生成

Java Agent 简介

Java 代理 (agent) 是在你的main方法前的一个拦截器 (interceptor),也就是在main方法执行之前,执行agent的代码。

agent 的代码与你的main方法在同一个JVM中运行,并被同一个system classloader装载,被同一的安全策略 (security policy) 和上下文 (context) 所管理。

Java Agent 这个技术,对于大多数同学来说都比较陌生,但是多多少少又接触过,实际上,我们平时用的很多工具,都是基于Java Agent实现的,例如常见的热部署JRebel,各种线上诊断工具(btrace, greys),还有阿里开源的线上诊断工具 arthas。

其实Java Agent一点都不神秘,也是一个Jar包,只是启动方式和普通Jar包有所不同,对于普通的Jar包,通过指定类的main函数进行启动,但是Java Agent并不能单独启动,必须依附在一个Java应用程序运行,有点像寄生虫的感觉。

如何动手写一个Java Agent ?

因为Java Agent的特殊性,需要一些特殊的配置,在 META-INF 目录下创建MANIFEST.MF 文件

并在 MANIFEST.MF 文件中指定Agent的启动类:

Manifest-Version: 1.0
Premain-Class: org.example.App
Archiver-Version: Plexus Archiver
Built-By: jack
Agent-Class: org.example.App
Created-By: Apache Maven 3.2.5
Build-Jdk: 1.8.0_40

为什么要指定 Agent-Class 和 Premain-Class ?

这里需要解释下为什么要指定 Agent-Class 和 Premain-Class ?

在加载Java Agent之后,会找到 Agent-Class 或者 Premain-Class 指定的类,并运行对应的 agentmain 或者 premain 方法。

/**
 * 以vm参数的方式载入,在Java程序的main方法执行之前执行
 */
public static void premain(String agentArgs, Instrumentation inst);
/**
 * 以Attach的方式载入,在Java程序启动后执行
 */
public static void agentmain(String agentArgs, Instrumentation inst);

这个执行流程如下图所示:

如果不想手动创建 MANIFEST.MF 文件,也可以通过Maven配置,在打包的时候自动生成,具体配置参考:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>java-agent-demo</artifactId>
    <version>1.0</version>

    <name>java-agent-demo</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <packaging>jar</packaging>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Premain-Class>org.example.App</Premain-Class>
                                        <Agent-Class>org.example.App</Agent-Class>
                                        <Can-Redefine-Classes>true</Can-Redefine-Classes>
                                    </manifestEntries>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

目标 JVM 进程的代码

import java.lang.management.ManagementFactory;

import static java.lang.Thread.sleep;


/**
 * @author: Jack
 * 2021/4/12 上午10:59
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        // get name representing the running Java virtual machine.
        String name = ManagementFactory.getRuntimeMXBean().getName();
        System.out.println(name);
        // get pid
        String pid = name.split("@")[0];
        System.out.println("Pid:" + pid);

        while (true) {
            sleep(2000);
            System.out.println("Hello World");
        }
    }
}

这里打印出PID,方便接下来的 VM attach 动作。

如何把切面逻辑绑定到目标 JVM 进程上?

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

import java.io.IOException;

import static java.lang.Thread.sleep;

/**
 * @author: Jack
 * 2021/4/12 上午11:07
 */
public class AgentAttach {

    public static void main(String[] args) throws IOException, AttachNotSupportedException, InterruptedException {
        // 85355 表示目标进程的PID
        VirtualMachine virtualMachine = VirtualMachine.attach("85355");
        // 指定Java Agent的jar包路径
        try {

            while (true) {
                virtualMachine.loadAgent("/Users/jack/youzan/java-agent-demo/target/java-agent-demo-1.0.jar", "Agent");
                sleep(3000);
            }

        } catch (AgentLoadException e) {
            e.printStackTrace();
        } catch (AgentInitializationException e) {
            e.printStackTrace();
        }finally {
            virtualMachine.detach();
        }

    }
}

运行效果

Hello World
agentmain Hello Agent
Hello World
agentmain Hello Agent
Hello World
Hello World
agentmain Hello Agent
Hello World
agentmain Hello Agent
Hello World
Hello World
agentmain Hello Agent
Hello World
agentmain Hello Agent
Hello World
Hello World
agentmain Hello Agent
Hello World
agentmain Hello Agent
Hello World
Hello World
agentmain Hello Agent
.......

参考资料

https://blog.csdn.net/qq_43171869/article/details/83477163https://blog.csdn.net/qyongkang/article/details/7799603

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光剑书架上的书

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值