如何構建一個開源的javaagent項目

前情提要

目前項目使用的agent 是在skywalking 上進行改造擴展的,但由於skywalking 的版本也是需要週期性更新的,這樣會導致在合併的時候非常噁心人,所以準備從skywalking agent 中將改造的插件功能剝離出來。

先說下獨立功能有幾個組件,
大概訪問流程是這樣的 ui --> proxy --> agent

  • ui 負責命令交互,數據展示等

  • proxy 負責通道維護,數據分揀

  • agent 負責應用數據監控抓取

所以在我們剝離出來後也會有三個項目 ui、proxy、agent,由此大家可以看出了,基本上大部分apm 大概都是這樣的流程。

此次說明的重點不是三個項目的實現,而是通過maven 進行工程的初始化構造。平時我們開發的項目無非是打出一個jar 或者war來進行項目部署。
但因爲我們這一套apm 是一個整體,爲了方便維護迭代,我們將其進行整合打包,先看下完成後整體的結構

在這裏插入圖片描述

先大概說明下目錄的用途

  • agent-dist 打包後存放agent 的目錄

  • agent-proxy-dist 打包後存放proxy的目錄

  • arthas-dis 因爲我們agent 支持arthas 的所有命令集,所有需要arthas的依賴

  • config agent的配置文件

  • cubic-agent agent 源碼

  • cubic-core agent core 源碼

  • cubic-proxy 代理源碼

  • cubic-ui ui 源碼

  • scripts 打包腳本

其實整個項目沒有多麼負責,整個核心的點只有幾個:

  1. 構建一個基礎agent 項目
  2. 通過maven 插件maven-shade-plugin 進行打包 和 package名稱的修改 ,用來防止和應用jar 衝突
  3. 通過 maven maven-antrun-plugin 進行部署包的整理

下面我們就來講解下整個流程

構建

1、父項目

首先需要一個父項目來包含管理整個項目組,如果你使用IDEA 右鍵可以很簡單的構建一個maven 項目,刪除掉其src 目錄後我們來看下pom 的依賴,很簡單不多說了

<?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>matrix.cubic</groupId>
   <artifactId>cubic</artifactId>
   <packaging>pom</packaging>
   <version>1.0-SNAPSHOT</version>
   <modules>
       <module>cubic-agent</module>
       <module>cubic-core</module>
       <module>cubic-proxy</module>
   </modules>

   <properties>
       <java.version>1.8</java.version>
   </properties>


   <dependencyManagement>
       <dependencies>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-dependencies</artifactId>
               <version>2.2.5.RELEASE</version>
               <type>pom</type>
               <scope>import</scope>
           </dependency>
           <dependency>
               <groupId>matrix.cubic</groupId>
               <artifactId>cubic-core</artifactId>
               <version>1.0-SNAPSHOT</version>
           </dependency>


           <dependency>
               <groupId>com.google.guava</groupId>
               <artifactId>guava</artifactId>
               <version>20.0</version>
           </dependency>
           <dependency>
               <groupId>org.apache.commons</groupId>
               <artifactId>commons-lang3</artifactId>
               <version>3.9</version>
           </dependency>

           <dependency>
               <groupId>io.netty</groupId>
               <artifactId>netty-all</artifactId>
               <version>4.1.45.Final</version>
           </dependency>
           <dependency>
               <groupId>com.google.code.gson</groupId>
               <artifactId>gson</artifactId>
               <version>2.8.6</version>
           </dependency>

       </dependencies>
   </dependencyManagement>


   <build>
       <pluginManagement>
           <plugins>
               <plugin>
                   <groupId>org.apache.maven.plugins</groupId>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <version>3.6.1</version>
                   <configuration>
                       <source>${java.version}</source>
                       <target>${java.version}</target>
                   </configuration>
               </plugin>
           </plugins>
       </pluginManagement>
   </build>

</project>

2、構建基礎agent

當前agent 我分爲了兩個簡單的包,cubic-core 包含了所有的核心代碼,cubic-agent 只是包含了一個啓動類,你可以根據自己需求創建。

其實打包的核心都在pom ,代碼編寫反而不是重點了。

來看下cubic-core的 pom

<?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">
   <parent>
       <artifactId>cubic</artifactId>
       <groupId>matrix.cubic</groupId>
       <version>1.0-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>

   <artifactId>cubic-core</artifactId>

   <properties>
       <shade.package>com.matrix.cubic.agent.core.dependencies</shade.package>
       <shade.com.google.source>com.google</shade.com.google.source>
       <shade.com.google.target>${shade.package}.${shade.com.google.source}</shade.com.google.target>
       <shade.io.grpc.source>io.grpc</shade.io.grpc.source>
       <shade.io.grpc.target>${shade.package}.${shade.io.grpc.source}</shade.io.grpc.target>
       <shade.io.netty.source>io.netty</shade.io.netty.source>
       <shade.io.netty.target>${shade.package}.${shade.io.netty.source}</shade.io.netty.target>
       <shade.org.apache.commons.source>org.apache.commons</shade.org.apache.commons.source>
       <shade.org.apache.commons.target>${shade.package}.${shade.org.apache.commons.source}</shade.org.apache.commons.target>
   </properties>
   <dependencies>
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-api</artifactId>
           <version>1.7.30</version>
       </dependency>
       <dependency>
           <groupId>com.google.guava</groupId>
           <artifactId>guava</artifactId>
       </dependency>
       <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-lang3</artifactId>
       </dependency>
       <dependency>
           <groupId>commons-net</groupId>
           <artifactId>commons-net</artifactId>
           <version>3.6</version>
       </dependency>
       <dependency>
           <groupId>com.sun</groupId>
           <artifactId>linux-tools</artifactId>
           <version>1.8</version>
       </dependency>
       <dependency>
           <groupId>io.netty</groupId>
           <artifactId>netty-all</artifactId>
       </dependency>
       <dependency>
           <groupId>com.google.code.gson</groupId>
           <artifactId>gson</artifactId>
       </dependency>

   </dependencies>

   <build>
       <plugins>
           <plugin>
               <artifactId>maven-shade-plugin</artifactId>
               <executions>
                   <execution>
                       <phase>package</phase>
                       <goals>
                           <goal>shade</goal>
                       </goals>
                       <configuration>
                           <artifactSet>
                               <excludes>
                                   <exclude>net.bytebuddy:byte-buddy:jar:</exclude>
                                   <exclude>com.google.errorprone:error_prone_annotations:jar:</exclude>
                                   <exclude>com.google.code.findbugs:jsr305:jar:</exclude>
                                   <exclude>com.google.android:annotations:jar:</exclude>
                                   <exclude>com.google.api.grpc:proto-google-common-protos:jar:</exclude>
                                   <exclude>org.checkerframework:checker-compat-qual:jar:</exclude>
                                   <exclude>org.codehaus.mojo:animal-sniffer-annotations:jar:</exclude>
                               </excludes>
                           </artifactSet>
                           <relocations>
                               <relocation>
                                   <pattern>${shade.com.google.source}</pattern>
                                   <shadedPattern>${shade.com.google.target}</shadedPattern>
                               </relocation>
                               <relocation>
                                   <pattern>${shade.io.grpc.source}</pattern>
                                   <shadedPattern>${shade.io.grpc.target}</shadedPattern>
                               </relocation>
                               <relocation>
                                   <pattern>${shade.io.netty.source}</pattern>
                                   <shadedPattern>${shade.io.netty.target}</shadedPattern>
                               </relocation>
                               <relocation>
                                   <pattern>${shade.org.apache.commons.source}</pattern>
                                   <shadedPattern>${shade.org.apache.commons.target}</shadedPattern>
                               </relocation>
                           </relocations>
                           <filters>
                               <filter>
                                   <artifact>com.google.protobuf:protobuf-java</artifact>
                                   <excludes>
                                       <exclude>google/protobuf/*.proto</exclude>
                                       <exclude>google/protobuf/compiler/*.proto</exclude>
                                   </excludes>
                               </filter>
                           </filters>
                           <transformers>
                               <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                           </transformers>
                       </configuration>
                   </execution>
               </executions>
           </plugin>
       </plugins>
   </build>
</project>

總覽全部,核心點還是maven 這幾個插件,下面結合實際簡單介紹下

maven-shade-plugin

這個插件就一個功能,就是幫你創建一個jar包,插件核心點有兩個

  • 選擇內容

  • 類重定位

這裏的打包其實是把我們的依賴都打進去了,來看個jar 解壓後的截圖,比如我們依賴了slf4j,如圖:

在這裏插入圖片描述

選擇內容

簡單來說就是我們希望哪些依賴打入jar ,哪些依賴排除。

  1. 標籤 -》 進行配置,支持兩種操作include和exclude
  2. 配置格式:groupId:artifactId[[:type]:classifier],至少包含groupid和artifactid,type和類名可選
  3. 支持’*’ 和 ‘?’執行通配符匹配

舉例:

<plugin>
               <artifactId>maven-shade-plugin</artifactId>
               <executions>
                   <execution>
                       <phase>package</phase>
                       <goals>
                           <goal>shade</goal>
                       </goals>
                       <configuration>
                           <artifactSet>
                               <excludes>
                                   <exclude>net.bytebuddy:byte-buddy:jar:</exclude>
                                   <exclude>com.google.errorprone:error_prone_annotations:jar:</exclude>
                                   <exclude>com.google.code.findbugs:jsr305:jar:</exclude>
                                   <exclude>com.google.android:annotations:jar:</exclude>
                                   <exclude>com.google.api.grpc:proto-google-common-protos:jar:</exclude>
                                   <exclude>org.checkerframework:checker-compat-qual:jar:</exclude>
                                   <exclude>org.codehaus.mojo:animal-sniffer-annotations:jar:</exclude>
                               </excludes>
                           </artifactSet>
                       </configuration>
                   </execution>
               </executions>
           </plugin>

類的重定位

因爲寫agent 和組件不像寫代碼,agent會給很多應用使用,每個應用的情況都是不相同的,比如你引入的fastjson和對方的版本不一直導致的使用衝突,這種問題其實還是很噁心人的,也噁心了開發組。

所爲爲了避免這種情況,我們就可以使用此插件給我們依賴的開源包變一個package路徑,這樣就不再會有衝突了(因爲classloader 加載一個類是通過package +class name確定唯一的)

上例子:

通過例子我們可以看出,將com.google 的package 改成了com.matrix.cubic.agent.core.dependencies.com.google,有興趣的可以自己看下編譯後的class

 <plugin>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                           
                            <relocations>
                                <relocation>
                                    <pattern>com.google</pattern>
                                    <shadedPattern>com.matrix.cubic.agent.core.dependencies.com.google</shadedPattern>
                                </relocation>
                                
                            </relocations>
                         
                        </configuration>
                    </execution>
                </executions>
            </plugin>

打包cubic-agent

通過上面的一通操作,agent-core的核心代碼已經打包完畢了,前面提過在cubic-agent 裏面其實是依賴了cubic-core,並且只包含了一個啓動類,真要變成一個可加載的agent 還需要在cubic-agent裏面進行處理下。

核心啓動類:

 public static void premain(String agentArgs, Instrumentation instrumentation) {
        System.out.println("add agent");
        CubicConfInitalizer.initConfig();
 
//        instrumentation.addTransformer(new DefineTransformer(), true);
 
        AgentNettyClient client = new AgentNettyClient();
        client.start();
 
        Runtime.getRuntime()
                .addShutdownHook(new Thread(client::destroyAndSync, "cubic agent shutdown thread"));
    }

cubic-agent pom

<?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">
   <parent>
       <artifactId>cubic</artifactId>
       <groupId>matrix.cubic</groupId>
       <version>1.0-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>

   <artifactId>cubic-agent</artifactId>

   <dependencies>
       <dependency>
           <groupId>matrix.cubic</groupId>
           <artifactId>cubic-core</artifactId>
       </dependency>
   </dependencies>

   <properties>
       <premain.class>com.matrix.agent.MatrixAgent</premain.class>
       <can.redefine.classes>true</can.redefine.classes>
       <can.retransform.classes>true</can.retransform.classes>
   </properties>
   <build>
       <finalName>cubic-agent</finalName>

       <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>
                           <transformers>
                               <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                   <manifestEntries>
                                       <Premain-Class>${premain.class}</Premain-Class>
                                       <Can-Redefine-Classes>${can.redefine.classes}</Can-Redefine-Classes>
                                       <Can-Retransform-Classes>${can.retransform.classes}</Can-Retransform-Classes>
                                   </manifestEntries>
                               </transformer>
                           </transformers>
                           <artifactSet>
                               <excludes>
                                   <exclude>*:gson</exclude>
                                   <exclude>io.grpc:*</exclude>
                                   <exclude>io.netty:*</exclude>
                                   <exclude>com.google.*:*</exclude>
                                   <exclude>com.google.guava:guava</exclude>
                               </excludes>
                           </artifactSet>

                           <filters>
                               <filter>
                                   <artifact>net.bytebuddy:byte-buddy</artifact>
                                   <excludes>
                                       <exclude>META-INF/versions/9/module-info.class</exclude>
                                   </excludes>
                               </filter>
                           </filters>
                       </configuration>
                   </execution>
               </executions>
           </plugin>

           <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-compiler-plugin</artifactId>
           </plugin>
           <plugin>
               <artifactId>maven-antrun-plugin</artifactId>
               <executions>
                   <execution>
                       <id>clean</id>
                       <phase>clean</phase>
                       <goals>
                           <goal>run</goal>
                       </goals>
                       <configuration>
                           <tasks>
                               <echo>${project.basedir}</echo>
                               <delete dir="${project.basedir}/../agent-dist" />
                           </tasks>
                       </configuration>
                   </execution>
                   <execution>
                       <id>package</id>
                       <phase>package</phase>
                       <goals>
                           <goal>run</goal>
                       </goals>
                       <configuration>
                           <tasks>
                               <mkdir dir="${project.basedir}/../agent-dist" />
                               <copy file="${project.build.directory}/cubic-agent.jar" tofile="${project.basedir}/../agent-dist/cubic-agent.jar" overwrite="true" />
                               <mkdir dir="${project.basedir}/../agent-dist/config" />
                               <mkdir dir="${project.basedir}/../agent-dist/logs" />
                               <copydir src="${project.basedir}/../config" dest="${project.basedir}/../agent-dist/config" forceoverwrite="true" />
                               <copydir src="${project.basedir}/../arthas-dist" dest="${project.basedir}/../agent-dist/arthas" forceoverwrite="true" />
                           </tasks>
                       </configuration>
                   </execution>
               </executions>
           </plugin>
       </plugins>

   </build>

</project>

通過pom可以發現重點是 maven-shade-plugin 和maven-antrun-plugin 兩個插件
maven-shade-plugin 這裏用於打造一個可執行的jar ,其實就是將一些基礎信息寫入到jar包的MANIFEST.MF 中,

核心點如下

                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <manifestEntries>
                                        <Premain-Class>${premain.class}</Premain-Class>
                                        <Can-Redefine-Classes>${can.redefine.classes}</Can-Redefine-Classes>
                                        <Can-Retransform-Classes>${can.retransform.classes}</Can-Retransform-Classes>
                                    </manifestEntries>
                                </transformer>
                            </transformers>

maven-antrun-plugin 用來做一些搬運的工作,截取一部分核心內容

  • 整體的過程就是:

  • 創建一個agent-dist 文件夾

  • 將我們cubic-agent 項目打包後的jar 拷貝到agent-dist下

  • 創建agent-dist/config 文件夾

  • 創建agent-dist/logs 文件夾

  • 將agent config 拷貝到agent-dist/config 下

  • 拷貝arthas-dist 目錄到agent-dist/arthas下

     <configuration>
                             <tasks>
                                 <mkdir dir="${project.basedir}/../agent-dist" />
                                 <copy file="${project.build.directory}/cubic-agent.jar" tofile="${project.basedir}/../agent-dist/cubic-agent.jar" overwrite="true" />
                                 <mkdir dir="${project.basedir}/../agent-dist/config" />
                                 <mkdir dir="${project.basedir}/../agent-dist/logs" />
                                 <copydir src="${project.basedir}/../config" dest="${project.basedir}/../agent-dist/config" forceoverwrite="true" />
                                 <copydir src="${project.basedir}/../arthas-dist" dest="${project.basedir}/../agent-dist/arthas" forceoverwrite="true" />
                             </tasks>
                         </configuration
    

至此爲止我們的agent 就打包完畢並且放到我們定義的地方了,後面proxy 是一個標準的spring boot 項目,使用的也是
maven-antrun-plugin進行的整合。

3、編寫打包腳本

最後就是簡單的寫下build.sh 打包腳本就可以執行了,有興趣的同學也可以搞下mvnw

#!/bin/bash

cd "${0%/*}"
cd ..

mvn -v
if [ $? -ne 0 ]; then
   echo "command mvn not found, Install the maven before executing the script!"
   exit 0;
fi

#打包agent
echo "================ starting to build cubic agent ================"
mvn clean package  -Dmaven.test.skip -Denforcer.skip=true
echo "================ building cubic agent finished ================"




總結:

  • 至此我們就創建了一個方便維護的agent 項目模板,剩下的就是開心的寫代碼了。

  • 其中的關鍵點就是兩個插件maven-shade-plugin 和 maven-antrun-plugin,有興趣可以通讀下文檔,很強大的

  • 其中agent 的寫法到不是重點了,有興趣的話再寫一個,推薦看下skywalking agent 擴展性真不錯

  • 放下此文代碼庫 https://gitee.com/sanjiankethree/cubic.git

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章