1. 程式人生 > 實用技巧 >Skywalking系列部落格6-手把手教你編寫Skywalking外掛

Skywalking系列部落格6-手把手教你編寫Skywalking外掛

前置知識

在正式進入編寫環節之前,建議先花一點時間瞭解下javaagent(這是JDK 5引入的一個玩意兒,最好了解下其工作原理);另外,Skywalking用到了byte-buddy(一個動態操作二進位制碼的庫),所以最好也熟悉下。

當然不瞭解關係也不大,一般不影響你玩轉Skywalking。

術語

Span:可理解為一次方法呼叫,一個程式塊的呼叫,或一次RPC/資料庫訪問。只要是一個具有完整時間週期的程式訪問,都可以被認為是一個span。SkyWalking Span 物件中的重要屬性

屬性 名稱 備註
component 元件 外掛的元件名稱,如:Lettuce,詳見:ComponentsDefine.Class。
tag 標籤 k-v結構,關鍵標籤,key詳見:Tags.Class。
peer 對端資源 用於拓撲圖,若DB元件,需記錄叢集資訊。
operationName 操作名稱 若span=0,operationName將會搜尋的下拉列表。
layer 顯示 在鏈路頁顯示,詳見SpanLayer.Class。

Trace:呼叫鏈,通過歸屬於其的Span來隱性的定義。一條Trace可被認為是一個由多個Span組成的有向無環圖(DAG圖),在SkyWalking鏈路模組你可以看到,Trace又由多個歸屬於其的trace segment組成。

Trace segment:Segment是SkyWalking中的一個概念,它應該包括單個OS程序中每個請求的所有範圍,通常是基於語言的單執行緒。由多個歸屬於本執行緒操作的Span組成。

TIPS

Skywalking的這幾個術語和Spring Cloud Sleuth類似,借鑑自谷歌的Dapper。我在 《Spring Cloud Alibaba微服務從入門到進階》 課程中有詳細剖析呼叫鏈的實現原理,並且用資料庫做了通俗的類比,本文不再贅述。

核心API

詳見 http://www.itmuch.com/books/skywalking/guides/Java-Plugin-Development-Guide.html

文章有非常詳細的描述。

實戰

本文以監控 org.apache.commons.lang3.StringUtils.replace 為例,手把手教你編寫Skywalking外掛。

依賴

首先,建立一個Maven專案,Pom.xml如下。

<?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>com.itmuch.skywalking</groupId>
    <artifactId>apm-string-replace-plugin</artifactId>
    <packaging>jar</packaging>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <skywalking.version>6.6.0</skywalking.version>
        <shade.package>org.apache.skywalking.apm.dependencies</shade.package>
        <shade.net.bytebuddy.source>net.bytebuddy</shade.net.bytebuddy.source>
        <shade.net.bytebuddy.target>${shade.package}.${shade.net.bytebuddy.source}</shade.net.bytebuddy.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.skywalking</groupId>
            <artifactId>apm-agent-core</artifactId>
            <version>${skywalking.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.skywalking</groupId>
            <artifactId>apm-util</artifactId>
            <version>${skywalking.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>false</shadedArtifactAttached>
                            <createDependencyReducedPom>true</createDependencyReducedPom>
                            <createSourcesJar>true</createSourcesJar>
                            <shadeSourcesContent>true</shadeSourcesContent>
                            <relocations>
                                <relocation>
                                    <pattern>${shade.net.bytebuddy.source}</pattern>
                                    <shadedPattern>${shade.net.bytebuddy.target}</shadedPattern>
                                </relocation>
                            </relocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>6</source>
                    <target>6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

這個Pom.xml中,除如下依賴以外,其他都得照抄,不管你開發什麼框架的Skywalking外掛,否則無法正常構建外掛!!

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
  <scope>provided</scope>
</dependency>

編寫Instrumentation類

public class StringReplaceInstrumentation extends ClassInstanceMethodsEnhancePluginDefine {
    @Override
    protected ClassMatch enhanceClass() {
        // 指定想要監控的類
        return NameMatch.byName("org.apache.commons.lang3.StringUtils");
    }

    @Override
    public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
        return new ConstructorInterceptPoint[0];
    }

    @Override
    public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
        // 指定想要監控的例項方法,每個例項方法對應一個InstanceMethodsInterceptPoint
        return new InstanceMethodsInterceptPoint[0];
    }

    @Override
    public StaticMethodsInterceptPoint[] getStaticMethodsInterceptPoints() {
        // 指定想要監控的靜態方法,每一個方法對應一個StaticMethodsInterceptPoint
        return new StaticMethodsInterceptPoint[]{
            new StaticMethodsInterceptPoint() {
                @Override
                public ElementMatcher<MethodDescription> getMethodsMatcher() {
                    // 靜態方法名稱
                    return ElementMatchers.named("replace");
                }

                @Override
                public String getMethodsInterceptor() {
                    // 該靜態方法的監控攔截器類名全路徑
                    return "com.itmuch.skywalking.plugin.stringreplace.StringReplaceInterceptor";
                }

                @Override
                public boolean isOverrideArgs() {
                    return false;
                }
            }
        };
    }
}

編寫攔截器

public class StringReplaceInterceptor implements StaticMethodsAroundInterceptor {
    @Override
    public void beforeMethod(Class aClass, Method method, Object[] argumentsTypes, Class<?>[] classes, MethodInterceptResult methodInterceptResult) {
        // 建立span(監控的開始),本質上是往ThreadLocal物件裡面設值
        AbstractSpan span = ContextManager.createLocalSpan("replace");

        /*
         * 可用ComponentsDefine工具類指定Skywalking官方支援的元件
         * 也可自己new OfficialComponent或者Component
         * 不過在Skywalking的控制檯上不會被識別,只會顯示N/A
         */
        span.setComponent(ComponentsDefine.TOMCAT);

        span.tag(new StringTag(1000, "params"), argumentsTypes[0].toString());
        // 指定該呼叫的layer,layer是個列舉
        span.setLayer(SpanLayer.CACHE);
    }

    @Override
    public Object afterMethod(Class aClass, Method method, Object[] objects, Class<?>[] classes, Object o) {
        String retString = (String) o;
        // 啟用span,本質上是讀取ThreadLocal物件
        AbstractSpan span = ContextManager.activeSpan();
        // 狀態碼,任意寫,Tags也是個Skywalking的工具類,用來比較方便地操作tag
        Tags.STATUS_CODE.set(span, "20000");

        // 停止span(監控的結束),本質上是清理ThreadLocal物件
        ContextManager.stopSpan();
        return retString;
    }

    @Override
    public void handleMethodException(Class aClass, Method method, Object[] objects, Class<?>[] classes, Throwable throwable) {
        AbstractSpan activeSpan = ContextManager.activeSpan();
        
        // 記錄日誌
        activeSpan.log(throwable);
        activeSpan.errorOccurred();
    }
}

編寫配置檔案

建立resources/skywalking-plugin.def ,內容如下:

# Key=value的形式
# key隨便寫;value是Instrumentation類的包名類名全路徑
my-string-replace-
plugin=org.apache.skywalking.apm.plugin.stringreplace.define.StringReplaceInstrumentation

構建

mvn clean install

構建完成後,到target目錄中,找到JAR包(非 origin-xxx.jar 、非xxx-source.jar ),扔到 agent/plugins 目錄裡面去,即可啟動。

外掛除錯

外掛的編寫可能不是一步到位的,有時候可能會報點錯什麼的。如果想要Debug自己的外掛,那麼需要將你的外掛程式碼和接入Java Agent的專案(也就是你配置了-javaagent啟動的專案)扔到同一個工作空間內,可以這麼玩:

  • 使用IDEA,開啟接入Java Agent的專案
  • 找到File->New->Module from Exisiting Sources…,引入你的外掛原始碼即可。

測試與監控效果

想辦法讓你接入Java Agent的專案,呼叫到如下程式碼

String replace = StringUtils.replace("oldString", "old","replaced");
System.out.println(replace);

之後,就可以看到類似如下的圖啦:

寫在最後

本文只是弄了一個簡單的例子,講解外掛編寫的套路。總的來說,外掛編寫還是非常順利的,單純程式碼的層面,很少會遇到坑;但搜遍各種搜尋引擎,竟然沒有一篇手把手的文章…而且也沒有文章講解依賴該如何引入、Maven外掛如何引入。於是只好參考Skywalking官方外掛的寫法,引入依賴和Maven外掛了,這塊反倒是費了點時間。

此外,如果你想真正掌握乃至精通skywalking外掛編寫,最好的辦法,還是閱讀官方的外掛程式碼,詳見:https://github.com/apache/skywalking/tree/master/apm-sniffer/apm-sdk-plugin ,隨便挑兩款看一下就知道怎麼玩了。我在學習過程中參考的外掛程式碼有:

  • apm-feign-default-http-9.x-plugin
  • apm-jdbc-commons

參考文件

本文首發

http://www.itmuch.com/skywalking/write-plugin/

本文由部落格一文多發平臺 OpenWrite 釋出!