agent源码注释

This commit is contained in:
kazusa 2025-07-18 18:09:33 +08:00
parent b7139d6b80
commit 9ec0eb009f
9 changed files with 128 additions and 61 deletions

View File

@ -97,7 +97,7 @@ public class SnifferConfigInitializer {
LOGGER.error(e, "Failed to parse the agent options, val is {}.", agentOptions);
}
}
// 加载核心配置
initializeConfig(Config.class);
// reconfigure logger after config initialization
configureLogger();
@ -105,6 +105,7 @@ public class SnifferConfigInitializer {
setAgentVersion();
// 服务名配置,可通过集群+命名空间进行隔离
if (StringUtil.isEmpty(Config.Agent.SERVICE_NAME)) {
throw new ExceptionInInitializerError("`agent.service_name` is missing.");
} else {

View File

@ -83,6 +83,7 @@ public abstract class AbstractClassEnhancePluginDefine {
/**
* find witness classes for enhance class
*/
// 校验见证类是否在classpath中,见证类依赖于应用程序的classpath,如果见证类不存在则不进行增强
String[] witnessClasses = witnessClasses();
if (witnessClasses != null) {
for (String witnessClass : witnessClasses) {
@ -92,6 +93,8 @@ public abstract class AbstractClassEnhancePluginDefine {
}
}
}
// 校验见证方法是否在classpath中,见证方法依赖于应用程序的classpath,如果见证方法不存在则不进行增强
// 同名的见证方法可能存在于多个版本的应用程序中,因此需要校验所有见证方法是否存在
List<WitnessMethod> witnessMethods = witnessMethods();
if (!CollectionUtil.isEmpty(witnessMethods)) {
for (WitnessMethod witnessMethod : witnessMethods) {

View File

@ -40,8 +40,11 @@ import static net.bytebuddy.matcher.ElementMatchers.not;
* AbstractClassEnhancePluginDefine} list.
*/
public class PluginFinder {
// 按类名匹配的插件
private final Map<String, LinkedList<AbstractClassEnhancePluginDefine>> nameMatchDefine = new HashMap<String, LinkedList<AbstractClassEnhancePluginDefine>>();
// 按类结构信息匹配的插件
private final List<AbstractClassEnhancePluginDefine> signatureMatchDefine = new ArrayList<AbstractClassEnhancePluginDefine>();
// 增强引导类的插件
private final List<AbstractClassEnhancePluginDefine> bootstrapClassMatchDefine = new ArrayList<AbstractClassEnhancePluginDefine>();
private static boolean IS_PLUGIN_INIT_COMPLETED = false;

View File

@ -86,6 +86,7 @@ public class AgentClassLoader extends ClassLoader {
super(parent);
File agentDictionary = AgentPackagePath.getPath();
classpath = new LinkedList<>();
// 2.1加载插件目录
Config.Plugin.MOUNT.forEach(mountFolder -> classpath.add(new File(agentDictionary, mountFolder)));
}

View File

@ -75,6 +75,7 @@ public class SkyWalkingAgent {
public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException {
final PluginFinder pluginFinder;
try {
// 1.加载配置
SnifferConfigInitializer.initializeCoreConfig(agentArgs);
} catch (Exception e) {
// try to resolve a new logger, and use the new logger to write the error log here
@ -92,6 +93,7 @@ public class SkyWalkingAgent {
}
try {
// 2.加载插件
pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins());
} catch (AgentPackageNotFoundException ape) {
LOGGER.error(ape, "Locate agent.jar failure. Shutting down.");
@ -102,6 +104,7 @@ public class SkyWalkingAgent {
}
try {
// 注入增强字节码
installClassTransformer(instrumentation, pluginFinder);
} catch (Exception e) {
LOGGER.error(e, "Skywalking agent installed class transformer failure.");
@ -133,12 +136,14 @@ public class SkyWalkingAgent {
JDK9ModuleExporter.EdgeClasses edgeClasses = new JDK9ModuleExporter.EdgeClasses();
try {
// 增强BootStrap类
agentBuilder = BootstrapInstrumentBoost.inject(pluginFinder, instrumentation, agentBuilder, edgeClasses);
} catch (Exception e) {
throw new Exception("SkyWalking agent inject bootstrap instrumentation failure. Shutting down.", e);
}
try {
// 兼容jdk9+
agentBuilder = JDK9ModuleExporter.openReadEdge(instrumentation, agentBuilder, edgeClasses);
} catch (Exception e) {
throw new Exception("SkyWalking agent open read edge in JDK 9+ failure. Shutting down.", e);
@ -185,6 +190,7 @@ public class SkyWalkingAgent {
final JavaModule javaModule,
final ProtectionDomain protectionDomain) {
LoadedLibraryCollector.registerURLClassLoader(classLoader);
// 过滤匹配的插件
List<AbstractClassEnhancePluginDefine> pluginDefines = pluginFinder.find(typeDescription);
if (pluginDefines.size() > 0) {
DynamicType.Builder<?> newBuilder = builder;

View File

@ -0,0 +1,11 @@
package org.apache.skywalking.apm.agent.test;
/**
* @author Wen
* @date 2025/7/17 16:18
*/
public class DemoApplication {
public static void main(String[] args) {
System.out.println(1);
}
}

20
debug-demo/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<?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>
<parent>
<groupId>org.apache.skywalking</groupId>
<artifactId>java-agent</artifactId>
<version>9.5.0-SNAPSHOT</version>
</parent>
<artifactId>debug-demo</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,21 @@
package org.apache.skywalking;
/**
* @author Wen
* @date 2025/7/17 18:02
*/
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) {
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
// to see how IntelliJ IDEA suggests fixing it.
System.out.printf("Hello and welcome!");
for (int i = 1; i <= 5; i++) {
//TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
// for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
System.out.println("i = " + i);
}
}
}

121
pom.xml
View File

@ -36,6 +36,7 @@
<module>apm-protocol</module>
<module>apm-sniffer</module>
<module>apm-application-toolkit</module>
<module>debug-demo</module>
</modules>
<packaging>pom</packaging>
@ -390,66 +391,66 @@
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${maven-checkstyle-plugin.version}</version>
<configuration>
<configLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/checkStyle.xml</configLocation>
<headerLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/CHECKSTYLE_HEAD</headerLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
<failOnViolation>${checkstyle.fails.on.error}</failOnViolation>
<sourceDirectories>
<sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
<sourceDirectory>${project.build.testSourceDirectory}</sourceDirectory>
<sourceDirectory>scenarios/resttemplate-6.x-scenario</sourceDirectory>
</sourceDirectories>
<resourceIncludes>
**/*.properties,
**/*.sh,
**/*.bat,
**/*.yml,
**/*.yaml,
**/*.xml
</resourceIncludes>
<resourceExcludes>
**/.asf.yaml,
**/.github/**,
**/skywalking-agent-version.properties
</resourceExcludes>
<excludes>
**/target/generated-test-sources/**,
org/apache/skywalking/apm/network/register/v2/**/*.java,
org/apache/skywalking/apm/network/common/**/*.java,
org/apache/skywalking/apm/network/servicemesh/**/*.java,
org/apache/skywalking/apm/network/language/**/*.java,
org/apache/skywalking/oap/server/core/remote/grpc/proto/*.java,
org/apache/skywalking/oal/rt/grammar/*.java,
org/apache/skywalking/oap/server/exporter/grpc/*.java,
org/apache/skywalking/oap/server/configuration/service/*.java,
**/jmh_generated/*_jmhType*.java,
**/jmh_generated/*_jmhTest.java,
net/bytebuddy/**,
<!-- Exclude compiling auxiliary classes in WebSphere Liberty plugin-->
com/ibm/websphere/servlet/request/IRequest.java,
com/ibm/ws/webcontainer/async/CompleteRunnable.java,
com/ibm/ws/webcontainer/async/DispatchRunnable.java
</excludes>
<propertyExpansion>
import.control=${maven.multiModuleProjectDirectory}/apm-checkstyle/importControl.xml
</propertyExpansion>
</configuration>
<executions>
<execution>
<id>validate</id>
<phase>process-sources</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- <plugin>-->
<!-- <artifactId>maven-checkstyle-plugin</artifactId>-->
<!-- <version>${maven-checkstyle-plugin.version}</version>-->
<!-- <configuration>-->
<!-- <configLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/checkStyle.xml</configLocation>-->
<!-- <headerLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/CHECKSTYLE_HEAD</headerLocation>-->
<!-- <encoding>UTF-8</encoding>-->
<!-- <consoleOutput>true</consoleOutput>-->
<!-- <includeTestSourceDirectory>true</includeTestSourceDirectory>-->
<!-- <failOnViolation>${checkstyle.fails.on.error}</failOnViolation>-->
<!-- <sourceDirectories>-->
<!-- <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>-->
<!-- <sourceDirectory>${project.build.testSourceDirectory}</sourceDirectory>-->
<!--<sourceDirectory>scenarios/resttemplate-6.x-scenario</sourceDirectory>-->
<!-- </sourceDirectories>-->
<!-- <resourceIncludes>-->
<!-- **/*.properties,-->
<!-- **/*.sh,-->
<!-- **/*.bat,-->
<!-- **/*.yml,-->
<!-- **/*.yaml,-->
<!-- **/*.xml-->
<!-- </resourceIncludes>-->
<!-- <resourceExcludes>-->
<!-- **/.asf.yaml,-->
<!-- **/.github/**,-->
<!-- **/skywalking-agent-version.properties-->
<!-- </resourceExcludes>-->
<!-- <excludes>-->
<!-- **/target/generated-test-sources/**,-->
<!-- org/apache/skywalking/apm/network/register/v2/**/*.java,-->
<!-- org/apache/skywalking/apm/network/common/**/*.java,-->
<!-- org/apache/skywalking/apm/network/servicemesh/**/*.java,-->
<!-- org/apache/skywalking/apm/network/language/**/*.java,-->
<!-- org/apache/skywalking/oap/server/core/remote/grpc/proto/*.java,-->
<!-- org/apache/skywalking/oal/rt/grammar/*.java,-->
<!-- org/apache/skywalking/oap/server/exporter/grpc/*.java,-->
<!-- org/apache/skywalking/oap/server/configuration/service/*.java,-->
<!-- **/jmh_generated/*_jmhType*.java,-->
<!-- **/jmh_generated/*_jmhTest.java,-->
<!-- net/bytebuddy/**,-->
<!-- &lt;!&ndash; Exclude compiling auxiliary classes in WebSphere Liberty plugin&ndash;&gt;-->
<!-- com/ibm/websphere/servlet/request/IRequest.java,-->
<!-- com/ibm/ws/webcontainer/async/CompleteRunnable.java,-->
<!-- com/ibm/ws/webcontainer/async/DispatchRunnable.java-->
<!-- </excludes>-->
<!-- <propertyExpansion>-->
<!-- import.control=${maven.multiModuleProjectDirectory}/apm-checkstyle/importControl.xml-->
<!-- </propertyExpansion>-->
<!-- </configuration>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <id>validate</id>-->
<!-- <phase>process-sources</phase>-->
<!-- <goals>-->
<!-- <goal>check</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>