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

View File

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

View File

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

View File

@ -86,6 +86,7 @@ public class AgentClassLoader extends ClassLoader {
super(parent); super(parent);
File agentDictionary = AgentPackagePath.getPath(); File agentDictionary = AgentPackagePath.getPath();
classpath = new LinkedList<>(); classpath = new LinkedList<>();
// 2.1加载插件目录
Config.Plugin.MOUNT.forEach(mountFolder -> classpath.add(new File(agentDictionary, mountFolder))); 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 { public static void premain(String agentArgs, Instrumentation instrumentation) throws PluginException {
final PluginFinder pluginFinder; final PluginFinder pluginFinder;
try { try {
// 1.加载配置
SnifferConfigInitializer.initializeCoreConfig(agentArgs); SnifferConfigInitializer.initializeCoreConfig(agentArgs);
} catch (Exception e) { } catch (Exception e) {
// try to resolve a new logger, and use the new logger to write the error log here // 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 { try {
// 2.加载插件
pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins()); pluginFinder = new PluginFinder(new PluginBootstrap().loadPlugins());
} catch (AgentPackageNotFoundException ape) { } catch (AgentPackageNotFoundException ape) {
LOGGER.error(ape, "Locate agent.jar failure. Shutting down."); LOGGER.error(ape, "Locate agent.jar failure. Shutting down.");
@ -102,6 +104,7 @@ public class SkyWalkingAgent {
} }
try { try {
// 注入增强字节码
installClassTransformer(instrumentation, pluginFinder); installClassTransformer(instrumentation, pluginFinder);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e, "Skywalking agent installed class transformer failure."); LOGGER.error(e, "Skywalking agent installed class transformer failure.");
@ -133,12 +136,14 @@ public class SkyWalkingAgent {
JDK9ModuleExporter.EdgeClasses edgeClasses = new JDK9ModuleExporter.EdgeClasses(); JDK9ModuleExporter.EdgeClasses edgeClasses = new JDK9ModuleExporter.EdgeClasses();
try { try {
// 增强BootStrap类
agentBuilder = BootstrapInstrumentBoost.inject(pluginFinder, instrumentation, agentBuilder, edgeClasses); agentBuilder = BootstrapInstrumentBoost.inject(pluginFinder, instrumentation, agentBuilder, edgeClasses);
} catch (Exception e) { } catch (Exception e) {
throw new Exception("SkyWalking agent inject bootstrap instrumentation failure. Shutting down.", e); throw new Exception("SkyWalking agent inject bootstrap instrumentation failure. Shutting down.", e);
} }
try { try {
// 兼容jdk9+
agentBuilder = JDK9ModuleExporter.openReadEdge(instrumentation, agentBuilder, edgeClasses); agentBuilder = JDK9ModuleExporter.openReadEdge(instrumentation, agentBuilder, edgeClasses);
} catch (Exception e) { } catch (Exception e) {
throw new Exception("SkyWalking agent open read edge in JDK 9+ failure. Shutting down.", 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 JavaModule javaModule,
final ProtectionDomain protectionDomain) { final ProtectionDomain protectionDomain) {
LoadedLibraryCollector.registerURLClassLoader(classLoader); LoadedLibraryCollector.registerURLClassLoader(classLoader);
// 过滤匹配的插件
List<AbstractClassEnhancePluginDefine> pluginDefines = pluginFinder.find(typeDescription); List<AbstractClassEnhancePluginDefine> pluginDefines = pluginFinder.find(typeDescription);
if (pluginDefines.size() > 0) { if (pluginDefines.size() > 0) {
DynamicType.Builder<?> newBuilder = builder; 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-protocol</module>
<module>apm-sniffer</module> <module>apm-sniffer</module>
<module>apm-application-toolkit</module> <module>apm-application-toolkit</module>
<module>debug-demo</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
@ -390,66 +391,66 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <!-- <plugin>-->
<artifactId>maven-checkstyle-plugin</artifactId> <!-- <artifactId>maven-checkstyle-plugin</artifactId>-->
<version>${maven-checkstyle-plugin.version}</version> <!-- <version>${maven-checkstyle-plugin.version}</version>-->
<configuration> <!-- <configuration>-->
<configLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/checkStyle.xml</configLocation> <!-- <configLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/checkStyle.xml</configLocation>-->
<headerLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/CHECKSTYLE_HEAD</headerLocation> <!-- <headerLocation>${maven.multiModuleProjectDirectory}/apm-checkstyle/CHECKSTYLE_HEAD</headerLocation>-->
<encoding>UTF-8</encoding> <!-- <encoding>UTF-8</encoding>-->
<consoleOutput>true</consoleOutput> <!-- <consoleOutput>true</consoleOutput>-->
<includeTestSourceDirectory>true</includeTestSourceDirectory> <!-- <includeTestSourceDirectory>true</includeTestSourceDirectory>-->
<failOnViolation>${checkstyle.fails.on.error}</failOnViolation> <!-- <failOnViolation>${checkstyle.fails.on.error}</failOnViolation>-->
<sourceDirectories> <!-- <sourceDirectories>-->
<sourceDirectory>${project.build.sourceDirectory}</sourceDirectory> <!-- <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>-->
<sourceDirectory>${project.build.testSourceDirectory}</sourceDirectory> <!-- <sourceDirectory>${project.build.testSourceDirectory}</sourceDirectory>-->
<sourceDirectory>scenarios/resttemplate-6.x-scenario</sourceDirectory> <!--<sourceDirectory>scenarios/resttemplate-6.x-scenario</sourceDirectory>-->
</sourceDirectories> <!-- </sourceDirectories>-->
<resourceIncludes> <!-- <resourceIncludes>-->
**/*.properties, <!-- **/*.properties,-->
**/*.sh, <!-- **/*.sh,-->
**/*.bat, <!-- **/*.bat,-->
**/*.yml, <!-- **/*.yml,-->
**/*.yaml, <!-- **/*.yaml,-->
**/*.xml <!-- **/*.xml-->
</resourceIncludes> <!-- </resourceIncludes>-->
<resourceExcludes> <!-- <resourceExcludes>-->
**/.asf.yaml, <!-- **/.asf.yaml,-->
**/.github/**, <!-- **/.github/**,-->
**/skywalking-agent-version.properties <!-- **/skywalking-agent-version.properties-->
</resourceExcludes> <!-- </resourceExcludes>-->
<excludes> <!-- <excludes>-->
**/target/generated-test-sources/**, <!-- **/target/generated-test-sources/**,-->
org/apache/skywalking/apm/network/register/v2/**/*.java, <!-- org/apache/skywalking/apm/network/register/v2/**/*.java,-->
org/apache/skywalking/apm/network/common/**/*.java, <!-- org/apache/skywalking/apm/network/common/**/*.java,-->
org/apache/skywalking/apm/network/servicemesh/**/*.java, <!-- org/apache/skywalking/apm/network/servicemesh/**/*.java,-->
org/apache/skywalking/apm/network/language/**/*.java, <!-- org/apache/skywalking/apm/network/language/**/*.java,-->
org/apache/skywalking/oap/server/core/remote/grpc/proto/*.java, <!-- org/apache/skywalking/oap/server/core/remote/grpc/proto/*.java,-->
org/apache/skywalking/oal/rt/grammar/*.java, <!-- org/apache/skywalking/oal/rt/grammar/*.java,-->
org/apache/skywalking/oap/server/exporter/grpc/*.java, <!-- org/apache/skywalking/oap/server/exporter/grpc/*.java,-->
org/apache/skywalking/oap/server/configuration/service/*.java, <!-- org/apache/skywalking/oap/server/configuration/service/*.java,-->
**/jmh_generated/*_jmhType*.java, <!-- **/jmh_generated/*_jmhType*.java,-->
**/jmh_generated/*_jmhTest.java, <!-- **/jmh_generated/*_jmhTest.java,-->
net/bytebuddy/**, <!-- net/bytebuddy/**,-->
<!-- Exclude compiling auxiliary classes in WebSphere Liberty plugin--> <!-- &lt;!&ndash; Exclude compiling auxiliary classes in WebSphere Liberty plugin&ndash;&gt;-->
com/ibm/websphere/servlet/request/IRequest.java, <!-- com/ibm/websphere/servlet/request/IRequest.java,-->
com/ibm/ws/webcontainer/async/CompleteRunnable.java, <!-- com/ibm/ws/webcontainer/async/CompleteRunnable.java,-->
com/ibm/ws/webcontainer/async/DispatchRunnable.java <!-- com/ibm/ws/webcontainer/async/DispatchRunnable.java-->
</excludes> <!-- </excludes>-->
<propertyExpansion> <!-- <propertyExpansion>-->
import.control=${maven.multiModuleProjectDirectory}/apm-checkstyle/importControl.xml <!-- import.control=${maven.multiModuleProjectDirectory}/apm-checkstyle/importControl.xml-->
</propertyExpansion> <!-- </propertyExpansion>-->
</configuration> <!-- </configuration>-->
<executions> <!-- <executions>-->
<execution> <!-- <execution>-->
<id>validate</id> <!-- <id>validate</id>-->
<phase>process-sources</phase> <!-- <phase>process-sources</phase>-->
<goals> <!-- <goals>-->
<goal>check</goal> <!-- <goal>check</goal>-->
</goals> <!-- </goals>-->
</execution> <!-- </execution>-->
</executions> <!-- </executions>-->
</plugin> <!-- </plugin>-->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>