轉(zhuǎn):阿里監(jiān)控診斷工具 Arthas 源碼原理分析

2018-10-10 12:55 閱讀:1282次 作者: 來源: 公眾賬號

image

上個月,阿里開源了 **監(jiān)控與診斷 **工具 「 **Arthas **」,一款可用于線上問題分析的利器,短期之內(nèi)收獲了大量關注,在 Twitter 上連 Java 官方的 Twitter 也轉(zhuǎn)發(fā)了,真的很贊。

GitHub 上是這樣自述的:

Arthas 是一款線上監(jiān)控診斷產(chǎn)品,通過全局視角實時查看應用 load、內(nèi)存、gc、線程的狀態(tài)信息,并能在不修改應用代碼的情況下,對業(yè)務問題進行診斷,包括查看方法調(diào)用的出入?yún)?、異常,監(jiān)測方法執(zhí)行耗時,類加載信息等,大大提升線上問題排查效率。

我一般看到感興趣的開源工具,會找?guī)讉€最感興趣的功能點切入,從源碼了解設計與實現(xiàn)原理。對于一些自己了解的實現(xiàn)思路,再從源碼中驗證一下是否是采用相同的實現(xiàn)思路。如果實現(xiàn)和自己想的一樣,可能你會想,啊哈,想到一塊了。如果源碼中是另一種實現(xiàn),你就會想 Cool, 還可以這樣玩。 **仿佛如同在和源碼的作者對話一樣 **。

這次趁著國慶假期看了一些「 ##Arthas」的源碼,大致總結(jié)下。

從源碼的包結(jié)構上,可以看到分為幾個大的 模塊:

  • Agent -- VM 加載的自定義 Agent

  • Client -- Telnet 客戶端實現(xiàn)

  • Core -- Arthas 核心實現(xiàn),包含連接 VM, 解析各類命令等

  • Site -- Arthas 的幫助手冊站點內(nèi)容

我主要看了以下幾個功能:

  • 連接進程

  • 反編譯class,獲取源碼

  • 查詢指定加載的 class

連接進程

連接到指定的進程,是后續(xù)監(jiān)控與診斷的 **基礎 **。只有先 attach 到進程之上,才能獲取 VM 對應的信息,查詢 ClassLoader 加載的類等等。

怎樣連接到進程呢?

用于類似診斷工具的讀者可能都有印象,像 JProfile、 VisualVM 等工具,都會讓你選擇一個要連接到的進程。然后再在指定的 VM 上進行操作。比如查看對應的內(nèi)存分區(qū)信息,內(nèi)存垃圾收集信息,執(zhí)行 BTrace腳本等等。

咱們先來想想,這些可供連接的進程列表,是怎么列出來的呢?

一般可能會是類似 ps aux | grep java這種,或者是使用 Java 提供的工具 jps -lv都可以列出包含進程id的內(nèi)容。我在很早之前的文章里寫過一點 jps 的內(nèi)容( 你可能不知道的幾個java小工具 ),其背后實現(xiàn),是會將本地啟動的所有 Java 進程,以 pid做為文件名存放在Java 的臨時目錄中。這個列表,遍歷這些文件即可得出來。

Arthas 是怎么做的呢?

在啟動腳本 as.sh中,有關于進程列表的代碼如下,實現(xiàn)也是通過 jps然后把Jps自己排除掉:

# check pid
if [ -z ${TARGET_PID} ] && [ ${BATCH_MODE} = false ]; then
    local IFS_backup=$IFS
    IFS=/pre>\n'
    CANDIDATES=($(${JAVA_HOME}/bin/jps -l | grep -v sun.tools.jps.Jps | awk '{print $0}'))

    if [ ${#CANDIDATES[@]} -eq 0 ]; then
        echo "Error: no available java process to attach."
        # recover IFS
        IFS=$IFS_backup
        return 1
    fi

    echo "Found existing java process, please choose one and hit RETURN."

    index=0
    suggest=1
    # auto select tomcat/pandora-boot process
    for process in "${CANDIDATES[@]}"; do
        index=$(($index+1))
        if [ $(echo ${process} | grep -c org.apache.catalina.startup.Bootstrap) -eq 1 ] \
            || [ $(echo ${process} | grep -c com.taobao.pandora.boot.loader.SarLauncher) -eq 1 ]
        then
           suggest=${index}
           break
        fi
    done

選擇好進程之后,就是連接到指定進程了。連接部分在 attach這里

 # attach arthas to target jvm
 # $1 : arthas_local_version
  attach_jvm()
 {
  local arthas_version=$1
     local arthas_lib_dir=${ARTHAS_LIB_DIR}/${arthas_version}/arthas

echo "Attaching to ${TARGET_PID} using version ${1}..."

if [ ${TARGET_IP} = ${DEFAULT_TARGET_IP} ]; then
    ${JAVA_HOME}/bin/java \
        ${ARTHAS_OPTS} ${BOOT_CLASSPATH} ${JVM_OPTS} \
        -jar ${arthas_lib_dir}/arthas-core.jar \
            -pid ${TARGET_PID} \
            -target-ip ${TARGET_IP} \
            -telnet-port ${TELNET_PORT} \
            -http-port ${HTTP_PORT} \
            -core "${arthas_lib_dir}/arthas-core.jar" \
            -agent "${arthas_lib_dir}/arthas-agent.jar"
fi}

對于 JVM 內(nèi)部的 attach 實現(xiàn),

是通過 tools.jar這個包中的 com.sun.tools.attach.VirtualMachine以及 VirtualMachine.attach(pid)這種方式來實現(xiàn)的。

底層則是通過 JVMTI。之前的文章簡單分析過 JVMTI這種技術( 當我們談Debug時,我們在談什么(Debug實現(xiàn)原理) ),在運行前或者運行時,將自定義的 Agent加載并和 VM 進行 **通信 **。

上面具體執(zhí)行的內(nèi)容在 arthas-core.jar的主類中,我們來看具體的內(nèi)容:

private void attachAgent(Configure configure) throws Exception {
    VirtualMachineDescriptor virtualMachineDescriptor = null;
    for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) {
        String pid = descriptor.id();
        if (pid.equals(Integer.toString(configure.getJavaPid()))) {
            virtualMachineDescriptor = descriptor;
        }
    }
    VirtualMachine virtualMachine = null;
    try {
        if (null == virtualMachineDescriptor) { // 使用 attach(String pid) 這種方式
            virtualMachine = VirtualMachine.attach("" + configure.getJavaPid());
        } else {
            virtualMachine = VirtualMachine.attach(virtualMachineDescriptor);
        }

        Properties targetSystemProperties = virtualMachine.getSystemProperties();
        String targetJavaVersion = targetSystemProperties.getProperty("java.specification.version");
        String currentJavaVersion = System.getProperty("java.specification.version");
        if (targetJavaVersion != null && currentJavaVersion != null) {
            if (!targetJavaVersion.equals(currentJavaVersion)) {
                AnsiLog.warn("Current VM java version: {} do not match target VM java version: {}, attach may fail.",
                                currentJavaVersion, targetJavaVersion);
                AnsiLog.warn("Target VM JAVA_HOME is {}, try to set the same JAVA_HOME.",
                                targetSystemProperties.getProperty("java.home"));
            }
        }

        virtualMachine.loadAgent(configure.getArthasAgent(),
                        configure.getArthasCore() + ";" + configure.toString());
    } finally {
        if (null != virtualMachine) {
            virtualMachine.detach();
        }
    }
}

通過 VirtualMachine, 可以attach到當前指定的pid上,或者是通過 VirtualMachineDescriptor實現(xiàn)指定進程的attach,最核心的就是這一句:

   virtualMachine.loadAgent(configure.getArthasAgent(),
                        configure.getArthasCore() + ";" + configure.toString());

這樣,就和指定進程的 VM建立了連接,此時就可以進行通信啦。

類的反編譯實現(xiàn)

我們在問題診斷中,有些時候需要了解當前加載的 class 對應的內(nèi)容,方便確認加載的類是否正確等,一般通過 javap只能顯示類似摘要的內(nèi)容,并不直觀。 在桌面端我們可以通過 jd-gui之類的工具,在命令行里一般可選的不多。

Arthas 則集成了這一功能。

大致的步驟如下:

  1. 通過指定class名稱的內(nèi)容,先進行類的查找

  2. 根據(jù)選項,判斷是否進行Inner Class之類的查找

  3. 進行反編譯

我們來看 Arthas 的實現(xiàn)。

對于 VM 中指定名稱的 class 的查找,我們看下面這幾行代碼:

public void process(CommandProcess process) {
    RowAffect affect = new RowAffect();
    Instrumentation inst = process.session().getInstrumentation();
    Set<Class> matchedClasses = SearchUtils.searchClassOnly(inst, classPattern, isRegEx, code);

    try {
        if (matchedClasses == null || matchedClasses.isEmpty()) {
            processNoMatch(process);
        } else if (matchedClasses.size() > 1) {
            processMatches(process, matchedClasses);
        } else {
            Set<Class> withInnerClasses = SearchUtils.searchClassOnly(inst,  classPattern + "(?!.*\\$\\$Lambda\\$).*", true, code);
            processExactMatch(process, affect, inst, matchedClasses, withInnerClasses);
}

關鍵的查找內(nèi)容,做了封裝,在 SearchUtils里,這里有一個核心的參數(shù): Instrumentation,都是這個哥們給實現(xiàn)的。

  /**
 * 根據(jù)類名匹配,搜已經(jīng)被JVM加載的類
 *
 * @param inst             inst
 * @param classNameMatcher 類名匹配
 * @return 匹配的類集合
 */
public static Set<> searchClass(Instrumentation inst, Matcher classNameMatcher, int limit) {
    for (Class clazz : inst.getAllLoadedClasses()) {
        if (classNameMatcher.matching(clazz.getName())) {
            matches.add(clazz);
        }
    }
    return matches;
}

inst.getAllLoadedClasses(),它才是背后的大玩家。

查找到了 Class 之后,怎么反編譯的呢?

   private String decompileWithCFR(String classPath, Class clazz, String methodName) {
    List<String> options = new ArrayList<String>();
    options.add(classPath);
   //   options.add(clazz.getName());
    if (methodName != null) {
        options.add(methodName);
    }
    options.add(OUTPUTOPTION);
    options.add(DecompilePath);
    options.add(COMMENTS);
    options.add("false");
    String args[] = new String[options.size()];
    options.toArray(args);
    Main.main(args);
    String outputFilePath = DecompilePath + File.separator + Type.getInternalName(clazz) + ".java";
    File outputFile = new File(outputFilePath);
    if (outputFile.exists()) {
        try {
            return FileUtils.readFileToString(outputFile, Charset.defaultCharset());
        } catch (IOException e) {
            logger.error(null, "error read decompile result in: " + outputFilePath, e);
        }
    }

    return null;
}

通過這樣一個方法: decompileWithCFR,所以我們大概了解到反編譯是通過第三方工具「 **CFR **」來實現(xiàn)的。上面的代碼也是拼 Option然后傳給 CFR的 Main方法實現(xiàn),再保存下來。感興趣的朋友可以查詢 benf cfr了解具體用法。

查詢加載類的實現(xiàn)

看過上面反編譯 class 的內(nèi)容之后,我們知道封裝了一個 SearchUtil的類,后面許多地方都會用到,而且上面反編譯也是在查詢到類的之后再進行的。查詢的過程,也是在Instrument的基礎之上,再加上各種匹配規(guī)則過濾,所以更多的具體內(nèi)容不再贅述。

我們發(fā)現(xiàn)上面幾個功能的實現(xiàn)中,有兩個關鍵的東西:

  • VirtualMachine

  • Instrumentation

Arthas 的整體邏輯也是在 Java 的 Instrumentation基礎上來實現(xiàn),所有在加載的類會通過Agent的加載, 通過addTransformer之后,進行增強,然后將對應的Advice織入進去,對于類的查找,方法的查找,都是通過SearchUtil來進行的,通過Instrument的loadAllClass方法將所有的JVM加載的class按名字進行匹配,一致的會進行返回。

Instrumentation 是個好同志! :)

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容