Upgrade async-profiler to 4.6 (#3281)

This commit is contained in:
hengyunabc authored and GitHub committed 2026-10-23 19:04:38 +08:00
1 parent 5fe5f06897
commit 2b6d0e59bd
14 files changed
+247 -30

No files matched your search

+4 -4
View File
@@ -21,7 +21,7 @@ jobs:
distribution: "zulu"
cache: "maven"
- name: Build with Maven
run: mvn -V -ntp clean install -P full verify
run: ./mvnw -V -ntp clean install -P full verify
windows_build:
runs-on: windows-2022
@@ -37,7 +37,7 @@ jobs:
distribution: "zulu"
cache: "maven"
- name: Build with Maven
run: mvn -V -ntp clean install -P full
run: ./mvnw.cmd -V -ntp clean install -P full
macos_build:
runs-on: ${{ matrix.os }}
@@ -56,7 +56,7 @@ jobs:
distribution: "zulu"
cache: "maven"
- name: Build with Maven
run: mvn -V -ntp clean install -P full
run: ./mvnw -V -ntp clean install -P full
telnet_stop_leak_it:
runs-on: ubuntu-latest
@@ -72,7 +72,7 @@ jobs:
- name: Install expect/telnet
run: sudo apt-get update && sudo apt-get install -y expect telnet
- name: Build packaging
run: mvn -V -ntp clean install -P full -DskipTests
run: ./mvnw -V -ntp clean install -P full -DskipTests
- name: Run telnet stop leak test
run: python3 integration-test/telnet-stop-leak/run_telnet_stop_leak_test.py --iterations 10 --warmup 2 --threshold 5 --work-dir integration-test/telnet-stop-leak/work
- name: Upload artifacts on failure
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -590,7 +590,7 @@ public class ProfilerCommand extends AnnotatedCommand {
}
/**
* https://github.com/async-profiler/async-profiler/blob/v4.4/src/arguments.cpp
* https://github.com/async-profiler/async-profiler/blob/v4.6/src/arguments.cpp
*/
public enum ProfilerAction {
// start, resume, stop, dump, status, meminfo, list,
@@ -833,8 +833,11 @@ public class ProfilerCommand extends AnnotatedCommand {
} else if (ProfilerAction.version.equals(profilerAction)) {
String result = asyncProfiler.execute("version=full");
appendExecuteResult(process, result);
} else if (ProfilerAction.meminfo.equals(profilerAction)) {
// 上游已用 metrics 替代 meminfo,保留 Arthas action 以兼容终端、HTTP 和 MCP 调用方。
String result = asyncProfiler.execute("metrics");
appendExecuteResult(process, result);
} else if (ProfilerAction.status.equals(profilerAction)
|| ProfilerAction.meminfo.equals(profilerAction)
|| ProfilerAction.list.equals(profilerAction)) {
String result = asyncProfiler.execute(profilerAction.toString());
appendExecuteResult(process, result);
@@ -37,6 +37,7 @@ public class ProfilerTool extends AbstractArthasTool {
+ "- start: 开始采样,如 action=start, event=cpu\n"
+ "- stop: 停止并输出文件,如 action=stop, format=flamegraph, file=/tmp/result.html\n"
+ "- status/list/actions: 查看状态/支持事件/支持动作\n"
+ "- meminfo: 查看 profiler 内存等指标,输出为 Prometheus 格式\n"
+ "- execute: 直接传递 async-profiler agent 兼容参数,如 action=execute, actionArg=\"stop,file=/tmp/result.html\""
)
public String profiler(
@@ -201,7 +201,7 @@ public class AsyncProfiler implements AsyncProfilerMXBean {
@Override
public String dumpCollapsed(Counter counter) {
try {
return execute0("collapsed," + counter.name().toLowerCase());
return execute0("collapsed," + (counter == Counter.SAMPLES ? "samples" : "total"));
} catch (IOException e) {
throw new IllegalStateException(e);
}
@@ -242,12 +242,13 @@ public class AsyncProfiler implements AsyncProfilerMXBean {
* <p>
* This API is UNSTABLE and might change or be removed in the next version of async-profiler.
*
* @param counter Which counter to use for aggregation
* @return OTLP representation of the profile
*/
@Override
public byte[] dumpOtlp() {
public byte[] dumpOtlp(Counter counter) {
try {
return execute1("otlp");
return execute1("otlp," + (counter == Counter.SAMPLES ? "samples" : "total"));
} catch (IOException e) {
throw new IllegalStateException(e);
}
@@ -31,5 +31,5 @@ public interface AsyncProfilerMXBean {
String dumpCollapsed(Counter counter);
String dumpTraces(int maxTraces);
String dumpFlat(int maxMethods);
byte[] dumpOtlp();
byte[] dumpOtlp(Counter counter);
}
@@ -1,5 +1,12 @@
/**
* This package is from https://github.com/async-profiler/async-profiler/
* tag v4.4 commit 86adc1605af84a48fc6d78871927ced2e3c02f0f
* tag v4.6 commit 557276c2950c14a5ad7073e2bef5a16616309247
*
* <p>Arthas 仅集成命令使用的 AsyncProfiler、AsyncProfilerMXBean、Counter 和 Events,
* 不引入独立的 Agent 入口或 Recording/Span API;常规采样、火焰图和 JFR 输出不依赖它们。
* 4.6 已修复加载 native 库时主动初始化 Recording 导致的类加载器泄漏和死锁,
* 但显式使用 Recording 仍会建立 JNI 全局引用;如需引入 Span API,须重新验证 ArthasClassloader 的释放。
* 参见 <a href="https://github.com/async-profiler/async-profiler/issues/1811">#1811</a> 和
* <a href="https://github.com/async-profiler/async-profiler/issues/1818">#1818</a>。
*/
package one.profiler;
@@ -0,0 +1,44 @@
package com.taobao.arthas.core.command.monitor200;
import java.lang.reflect.Field;
import com.taobao.arthas.core.command.model.ProfilerModel;
import com.taobao.arthas.core.shell.command.CommandProcess;
import one.profiler.AsyncProfiler;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ProfilerCommandTest {
@Test
void shouldKeepMeminfoActionWhileReturningNativeMetrics() throws Exception {
AsyncProfiler profiler = mock(AsyncProfiler.class);
String metrics = "mem_calltracestorage_kb 10244\nsamples_total 42\n";
when(profiler.execute("metrics")).thenReturn(metrics);
Field field = ProfilerCommand.class.getDeclaredField("profiler");
field.setAccessible(true);
Object previous = field.get(null);
field.set(null, profiler);
try {
CommandProcess process = mock(CommandProcess.class);
ProfilerCommand command = new ProfilerCommand();
command.setAction("meminfo");
command.process(process);
ArgumentCaptor<ProfilerModel> result = ArgumentCaptor.forClass(ProfilerModel.class);
verify(process).appendResult(result.capture());
assertEquals("meminfo", result.getValue().getAction());
assertEquals(metrics, result.getValue().getExecuteResult());
verify(profiler).execute("metrics");
verify(profiler, never()).execute("meminfo");
verify(process).end();
} finally {
field.set(null, previous);
}
}
}
@@ -47,7 +47,7 @@ class ProfilerMarkdownTest {
}
@Test
void shouldExposeOnlySupportedAsyncProfiler44Actions() {
void shouldExposeOnlySupportedAsyncProfilerActions() {
Assertions.assertThat(ProfilerCommand.ProfilerAction.values())
.extracting(Enum::name)
.contains("start", "resume", "stop", "dump", "status", "meminfo", "list", "version")
@@ -0,0 +1,141 @@
package com.taobao.arthas.core.command.monitor200;
import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import one.profiler.AsyncProfiler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class ProfilerNativeTest {
@TempDir
Path output;
@Test
void shouldReleaseClassLoaderAfterLoading() throws Exception {
runProbe("version");
}
@Test
void shouldProfileAndReleaseClassLoader() throws Exception {
runProbe("profile");
}
private void runProbe(String mode) throws Exception {
String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
String arch = System.getProperty("os.arch");
String library = null;
if (os.contains("mac")) {
library = "libasyncProfiler-mac.dylib";
} else if (os.contains("linux")) {
if (arch.equals("amd64") || arch.equals("x86_64")) {
library = "libasyncProfiler-linux-x64.so";
} else if (arch.equals("aarch64") || arch.equals("arm64")) {
library = "libasyncProfiler-linux-arm64.so";
}
}
assumeTrue(library != null, "No bundled async-profiler library for " + os + "/" + arch);
File classes = new File(AsyncProfiler.class.getProtectionDomain().getCodeSource().getLocation().toURI());
File root = classes.getParentFile().getParentFile().getParentFile();
File nativeLibrary = new File(root, "async-profiler/" + library);
assertTrue(nativeLibrary.isFile(), nativeLibrary.toString());
File testClasses = new File(Probe.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path log = output.resolve("probe.log");
// 独立 JVM 隔离 native 状态;解释执行和 Serial GC 使类加载器回收检查不受 JIT 局部变量存活影响。
Process process = new ProcessBuilder(new File(System.getProperty("java.home"), "bin/java").getPath(),
"-Xint", "-Xmx128m", "-XX:+UseSerialGC", "-cp", testClasses.getPath(), Probe.class.getName(),
classes.getPath(), nativeLibrary.getPath(), output.toString(), mode)
.redirectErrorStream(true).redirectOutput(log.toFile()).start();
try {
assertTrue(process.waitFor(30, TimeUnit.SECONDS), "Profiler probe timed out: " + log);
assertEquals(0, process.exitValue(), new String(Files.readAllBytes(log), StandardCharsets.UTF_8));
} finally {
process.destroyForcibly();
}
}
public static class Probe {
public static void main(String[] args) throws Exception {
WeakReference<ClassLoader> loader = profile(args);
for (int i = 0; i < 30 && loader.get() != null; i++) {
System.gc();
System.runFinalization();
Thread.sleep(100);
}
require(loader.get() == null, "Profiler class loader was retained");
}
private static WeakReference<ClassLoader> profile(String[] args) throws Exception {
try (URLClassLoader loader = new URLClassLoader(new URL[] {new File(args[0]).toURI().toURL()}, null)) {
Class<?> api = Class.forName("one.profiler.AsyncProfiler", true, loader);
Object profiler = api.getMethod("getInstance", String.class).invoke(null, args[1]);
require("4.6".equals(api.getMethod("getVersion").invoke(profiler)), "Unexpected profiler version");
if ("profile".equals(args[3])) {
Method execute = api.getMethod("execute", String.class);
Thread.currentThread().setName("arthas-profiler-test");
execute.invoke(profiler, "start,event=wall,interval=1ms,ithread=arthas-profiler-test");
try {
workload();
require((Long) api.getMethod("getSamples").invoke(profiler) > 0, "No wall samples");
require(((String) execute.invoke(profiler, "metrics")).contains("mem_calltracestorage_kb "),
"Missing memory metrics");
Class<?> counter = loader.loadClass("one.profiler.Counter");
for (Object value : counter.getEnumConstants()) {
String collapsed = (String) api.getMethod("dumpCollapsed", counter).invoke(profiler, value);
require(collapsed.contains("workload"), "Missing workload in collapsed output: " + collapsed);
byte[] otlp = (byte[]) api.getMethod("dumpOtlp", counter).invoke(profiler, value);
require(otlp.length > 0, "Empty OTLP output");
}
File html = new File(args[2], "profile.html");
execute.invoke(profiler, "dump,flamegraph,file=" + html);
String flamegraph = new String(Files.readAllBytes(html.toPath()), StandardCharsets.UTF_8);
require(flamegraph.contains("workload") && flamegraph.contains("id='treeview'"),
"Missing samples or tree view in HTML");
} finally {
api.getMethod("stop").invoke(profiler);
}
File jfr = new File(args[2], "profile.jfr");
execute.invoke(profiler, "start,event=wall,interval=1ms,jfr,file=" + jfr);
try {
workload();
} finally {
api.getMethod("stop").invoke(profiler);
}
byte[] recording = Files.readAllBytes(jfr.toPath());
require(recording.length > 4 && recording[0] == 'F' && recording[1] == 'L'
&& recording[2] == 'R' && recording[3] == 0, "Invalid JFR output");
require(((String) execute.invoke(profiler, "status")).contains("not active"),
"Profiler did not stop");
}
return new WeakReference<ClassLoader>(loader);
}
}
private static void workload() {
long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(300);
while (System.nanoTime() < end) {
Math.sqrt(System.nanoTime());
}
}
private static void require(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
}
}
+19 -9
View File
@@ -10,6 +10,8 @@
`profiler` 命令的格式基本与上游项目 [async-profiler](https://github.com/async-profiler/async-profiler) 保持一致,详细的使用方式可参考上游项目的 README、Github Disscussions 以及其他文档资料。
当前内置 async-profiler 4.6,提供 Linux x64、Linux arm64 和 macOS x64/arm64 原生库;macOS 需要 11 或更高版本。
## 参数说明
| 参数名称 | 参数说明 |
@@ -50,13 +52,11 @@ $ profiler status
## 查看 profiler 自身的内存占用
启动采样后,`meminfo` 调用 async-profiler 的 `metrics` action,返回 Prometheus 格式的指标。内存指标以 KB 为单位,例如(节选):
```
$ profiler meminfo
Call trace storage: 10244 KB
Dictionaries: 72 KB
Code cache: 12890 KB
------------------------------
Total: 23206 KB
mem_calltracestorage_kb 10244
```
## 停止 profiler
@@ -65,6 +65,8 @@ Call trace storage: 10244 KB
默认情况下,结果是 [Flame Graph](https://github.com/BrendanGregg/FlameGraph) 格式的 `html` 文件,也可以用 `-o` 或 `--format` 参数指定其他内容格式,包括 flat、traces、collapsed、flamegraph、tree、jfr、md。
async-profiler 4.6 的 HTML 同时包含火焰图和调用树,可以在页面中切换;`--format tree` 默认显示调用树。
### 生成 LLM 友好的 Markdown 报告
当 `--format md`(或 `md=N`)时,Arthas 会基于 async-profiler 的 `collapsed` 输出生成结构化的 Markdown,便于直接复制到 LLM 或在终端里 grep。报告包含:
@@ -199,7 +201,7 @@ OK
比如开始采样:
```bash
profiler execute 'start,framebuf=5000000'
profiler execute 'start,event=cpu,interval=1ms'
```
停止采样,并保存到指定文件里:
@@ -208,7 +210,16 @@ profiler execute 'start,framebuf=5000000'
profiler execute 'stop,file=/tmp/result.html'
```
具体的格式参考: [arguments.cpp](https://github.com/async-profiler/async-profiler/blob/v4.4/src/arguments.cpp#L52)
具体的格式参考:[ProfilerOptions.md](https://github.com/async-profiler/async-profiler/blob/v4.6/docs/ProfilerOptions.md) 中的 Agent options,以及 [arguments.cpp](https://github.com/async-profiler/async-profiler/blob/v4.6/src/arguments.cpp)。
从 async-profiler 4.6 开始,`filter` 不再接受线程 ID。wall 采样可通过 `ithread`/`xthread` 按线程名称包含或排除线程,例如:
```bash
profiler execute 'start,event=wall,ithread=http-*,xthread=*acceptor*'
profiler stop
```
无参数的 `filter` 供 Java API 的 `AsyncProfiler.addThread()` 使用。4.6 也移除了 async-profiler 内嵌的 HTTP 服务;通过 Arthas 的 3658 端口查看结果的方式不变。
## 查看所有支持的 action
@@ -221,8 +232,7 @@ Supported Actions: [resume, dumpCollapsed, getSamples, start, list, version, exe
```bash
$ profiler version
async-profiler 4.4
Copyright The async-profiler authors
4.6
```
## 配置 Java 栈深度
+19 -9
View File
@@ -10,6 +10,8 @@ The basic usage of the `profiler` command is `profiler action [actionArg]`
The arguments of `profiler` command basically keeps consistent with upstream project [async-profiler](https://github.com/async-profiler/async-profiler), you can refer to its README, Github Discussions and other documentations for further information of usage.
Arthas bundles async-profiler 4.6 native libraries for Linux x64, Linux arm64, and macOS x64/arm64. macOS 11 or later is required.
## Supported Options
| Name | Specification |
@@ -50,13 +52,11 @@ Can view which `event` and sampling time.
## View profiler memory usage
After starting profiling, use `meminfo` to invoke async-profiler's `metrics` action and return metrics in Prometheus format. Memory values are in KB, for example (excerpt):
```
$ profiler meminfo
Call trace storage: 10244 KB
Dictionaries: 72 KB
Code cache: 12890 KB
------------------------------
Total: 23206 KB
mem_calltracestorage_kb 10244
```
## Stop profiler
@@ -65,6 +65,8 @@ Call trace storage: 10244 KB
By default, the result file is `html` file in [Flame Graph](https://github.com/BrendanGregg/FlameGraph) format. You can also specify other format with the `-o` or `--format` parameter, including flat, traces, collapsed, flamegraph, tree, jfr, md:
In async-profiler 4.6, the HTML contains both a flame graph and a call tree, with a toggle to switch between them. `--format tree` displays the call tree initially.
### Generate LLM-friendly Markdown report
When `--format md` (or `md=N`) is specified, Arthas generates a structured Markdown report based on async-profiler `collapsed` output, which is easy to copy/paste to an LLM or grep in terminal. The report includes:
@@ -199,7 +201,7 @@ The `dump` action saves profiling result to default file or specified file, but
For example, start sampling:
```bash
profiler execute 'start,framebuf=5000000'
profiler execute 'start,event=cpu,interval=1ms'
```
Stop sampling and save to the specified file:
@@ -208,7 +210,16 @@ Stop sampling and save to the specified file:
profiler execute 'stop,file=/tmp/result.html'
```
Specific format reference: [arguments.cpp](https://github.com/async-profiler/async-profiler/blob/v4.4/src/arguments.cpp#L52)
For the supported syntax, see the Agent options in [ProfilerOptions.md](https://github.com/async-profiler/async-profiler/blob/v4.6/docs/ProfilerOptions.md) and [arguments.cpp](https://github.com/async-profiler/async-profiler/blob/v4.6/src/arguments.cpp).
Since async-profiler 4.6, `filter` no longer accepts thread IDs. For wall clock sampling, use `ithread`/`xthread` to include or exclude threads by name, for example:
```bash
profiler execute 'start,event=wall,ithread=http-*,xthread=*acceptor*'
profiler stop
```
The bare `filter` option is intended for the Java API's `AsyncProfiler.addThread()`. Version 4.6 also removes async-profiler's embedded HTTP server; viewing results through Arthas on port 3658 continues to work.
## View all supported actions
@@ -221,8 +232,7 @@ Supported Actions: [resume, dumpCollapsed, getSamples, start, list, version, exe
```bash
$ profiler version
async-profiler 4.4
Copyright The async-profiler authors
4.6
```
## Configure Java stack depth