首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java Agent (JVM Instrumentation 机制) 极简教程

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

作者头像
一个会写诗的程序员
发布2021-04-15 10:15:54
7.8K0
发布2021-04-15 10:15:54
举报

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/83477163 https://blog.csdn.net/qyongkang/article/details/7799603

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Java Agent 简介
  • 如何动手写一个Java Agent ?
  • 为什么要指定 Agent-Class 和 Premain-Class ?
  • 目标 JVM 进程的代码
  • 如何把切面逻辑绑定到目标 JVM 进程上?
  • 运行效果
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档