前置知識
在正式進(jìn)入編寫環(huán)節(jié)之前,建議先花一點(diǎn)時(shí)間了解下javaagent(這是JDK 5引入的一個(gè)玩意兒,最好了解下其工作原理);另外,Skywalking用到了byte-buddy(一個(gè)動(dòng)態(tài)操作二進(jìn)制碼的庫),所以最好也熟悉下。
當(dāng)然不了解關(guān)系也不大,一般不影響你玩轉(zhuǎn)Skywalking。
術(shù)語
Span:可理解為一次方法調(diào)用,一個(gè)程序塊的調(diào)用,或一次RPC/數(shù)據(jù)庫訪問。只要是一個(gè)具有完整時(shí)間周期的程序訪問,都可以被認(rèn)為是一個(gè)span。SkyWalking Span 對象中的重要屬性
| 屬性 | 名稱 | 備注 |
|---|---|---|
| component | 組件 | 插件的組件名稱,如:Lettuce,詳見:ComponentsDefine.Class。 |
| tag | 標(biāo)簽 | k-v結(jié)構(gòu),關(guān)鍵標(biāo)簽,key詳見:Tags.Class。 |
| peer | 對端資源 | 用于拓?fù)鋱D,若DB組件,需記錄集群信息。 |
| operationName | 操作名稱 | 若span=0,operationName將會(huì)搜索的下拉列表。 |
| layer | 顯示 | 在鏈路頁顯示,詳見SpanLayer.Class。 |
Trace:調(diào)用鏈,通過歸屬于其的Span來隱性的定義。一條Trace可被認(rèn)為是一個(gè)由多個(gè)Span組成的有向無環(huán)圖(DAG圖),在SkyWalking鏈路模塊你可以看到,Trace又由多個(gè)歸屬于其的trace segment組成。
Trace segment:Segment是SkyWalking中的一個(gè)概念,它應(yīng)該包括單個(gè)OS進(jìn)程中每個(gè)請求的所有范圍,通常是基于語言的單線程。由多個(gè)歸屬于本線程操作的Span組成。
TIPS
Skywalking的這幾個(gè)術(shù)語和Spring Cloud Sleuth類似,借鑒自谷歌的Dapper。我在 《Spring Cloud Alibaba微服務(wù)從入門到進(jìn)階》 課程中有詳細(xì)剖析調(diào)用鏈的實(shí)現(xiàn)原理,并且用數(shù)據(jù)庫做了通俗的類比,本文不再贅述。
核心API
詳見 http://www.itmuch.com/books/skywalking/guides/Java-Plugin-Development-Guide.html 文章有非常詳細(xì)的描述。
實(shí)戰(zhàn)
本文以監(jiān)控 org.apache.commons.lang3.StringUtils.replace 為例,手把手教你編寫Skywalking插件。
依賴
首先,創(chuàng)建一個(gè)Maven項(xiàng)目,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>
這個(gè)Pom.xml中,除如下依賴以外,其他都得照抄,不管你開發(fā)什么框架的Skywalking插件,否則無法正常構(gòu)建插件!!
<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() {
// 指定想要監(jiān)控的類
return NameMatch.byName("org.apache.commons.lang3.StringUtils");
}
@Override
public ConstructorInterceptPoint[] getConstructorsInterceptPoints() {
return new ConstructorInterceptPoint[0];
}
@Override
public InstanceMethodsInterceptPoint[] getInstanceMethodsInterceptPoints() {
// 指定想要監(jiān)控的實(shí)例方法,每個(gè)實(shí)例方法對應(yīng)一個(gè)InstanceMethodsInterceptPoint
return new InstanceMethodsInterceptPoint[0];
}
@Override
public StaticMethodsInterceptPoint[] getStaticMethodsInterceptPoints() {
// 指定想要監(jiān)控的靜態(tài)方法,每一個(gè)方法對應(yīng)一個(gè)StaticMethodsInterceptPoint
return new StaticMethodsInterceptPoint[]{
new StaticMethodsInterceptPoint() {
@Override
public ElementMatcher<MethodDescription> getMethodsMatcher() {
// 靜態(tài)方法名稱
return ElementMatchers.named("replace");
}
@Override
public String getMethodsInterceptor() {
// 該靜態(tài)方法的監(jiān)控?cái)r截器類名全路徑
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) {
// 創(chuàng)建span(監(jiān)控的開始),本質(zhì)上是往ThreadLocal對象里面設(shè)值
AbstractSpan span = ContextManager.createLocalSpan("replace");
/*
* 可用ComponentsDefine工具類指定Skywalking官方支持的組件
* 也可自己new OfficialComponent或者Component
* 不過在Skywalking的控制臺上不會(huì)被識別,只會(huì)顯示N/A
*/
span.setComponent(ComponentsDefine.TOMCAT);
span.tag(new StringTag(1000, "params"), argumentsTypes[0].toString());
// 指定該調(diào)用的layer,layer是個(gè)枚舉
span.setLayer(SpanLayer.CACHE);
}
@Override
public Object afterMethod(Class aClass, Method method, Object[] objects, Class<?>[] classes, Object o) {
String retString = (String) o;
// 激活span,本質(zhì)上是讀取ThreadLocal對象
AbstractSpan span = ContextManager.activeSpan();
// 狀態(tài)碼,任意寫,Tags也是個(gè)Skywalking的工具類,用來比較方便地操作tag
Tags.STATUS_CODE.set(span, "20000");
// 停止span(監(jiān)控的結(jié)束),本質(zhì)上是清理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();
}
}
編寫配置文件
創(chuàng)建resources/skywalking-plugin.def ,內(nèi)容如下:
# Key=value的形式
# key隨便寫;value是Instrumentation類的包名類名全路徑
my-string-replace-
plugin=org.apache.skywalking.apm.plugin.stringreplace.define.StringReplaceInstrumentation
構(gòu)建
mvn clean install
構(gòu)建完成后,到target目錄中,找到JAR包(非 origin-xxx.jar 、非xxx-source.jar ),扔到 agent/plugins 目錄里面去,即可啟動(dòng)。
插件調(diào)試
插件的編寫可能不是一步到位的,有時(shí)候可能會(huì)報(bào)點(diǎn)錯(cuò)什么的。如果想要Debug自己的插件,那么需要將你的插件代碼和接入Java Agent的項(xiàng)目(也就是你配置了-javaagent啟動(dòng)的項(xiàng)目)扔到同一個(gè)工作空間內(nèi),可以這么玩:
- 使用IDEA,打開接入Java Agent的項(xiàng)目
- 找到File->New->Module from Exisiting Sources…,引入你的插件源碼即可。

測試與監(jiān)控效果
想辦法讓你接入Java Agent的項(xiàng)目,調(diào)用到如下代碼
String replace = StringUtils.replace("oldString", "old","replaced");
System.out.println(replace);

之后,就可以看到類似如下的圖啦:
寫在最后
本文只是弄了一個(gè)簡單的例子,講解插件編寫的套路。總的來說,插件編寫還是非常順利的,單純代碼的層面,很少會(huì)遇到坑;但搜遍各種搜索引擎,竟然沒有一篇手把手的文章…而且也沒有文章講解依賴該如何引入、Maven插件如何引入。于是只好參考Skywalking官方插件的寫法,引入依賴和Maven插件了,這塊反倒是費(fèi)了點(diǎn)時(shí)間。
此外,如果你想真正掌握乃至精通skywalking插件編寫,最好的辦法,還是閱讀官方的插件代碼,詳見:https://github.com/apache/skywalking/tree/master/apm-sniffer/apm-sdk-plugin ,隨便挑兩款看一下就知道怎么玩了。我在學(xué)習(xí)過程中參考的插件代碼有:
- apm-feign-default-http-9.x-plugin
- apm-jdbc-commons
參考文檔
本文首發(fā)
http://www.itmuch.com/skywalking/write-plugin/
本文由博客一文多發(fā)平臺 OpenWrite 發(fā)布!