本文基于 SkyWalking-Java-agent 8.15.0 版本
SkyWalking agent 的入口是 org.apache.skywalking.apm.agent.SkyWalkingAgent
初始化配置的入口:SkyWalkingAgent.premain 方法
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
LogManager.getLogger(SkyWalkingAgent.class)
.error(e, "SkyWalking agent initialized failure. Shutting down.");
return;
} finally {
// refresh logger again after initialization finishes
LOGGER = LogManager.getLogger(SkyWalkingAgent.class);
}
agentArgs:agent的参数。启动agent时,会通过 -javaagent的方式,比如:
- -javaagent:/path/to/agent.jar=agentArgs
- -javaagent:/path/to/agent.jar=k1=v1,k2=v2...
第一个=后面的均为 agentArgs 的参数。agentArgs 使用=将键值拼凑到 jarpath 的后面
-javaagent参数必须在-jar之前
加载配置信息
SnifferConfigInitializer.initializeCoreConfig(agentArgs) 加载agent启动的配置信息。配置信息来自三个地方,分别是:agent参数、系统环境变量、/config/agent.conf。在agent加载配置时,会按照 agent参数 > 系统环境变量 > /config/agent.config 的优先级依次加载配置文件,同时高优先级的配置信息回覆盖低优先级的配置信息。解析后的配置信息会存放在 Properties AGENT_SETTINGS 里面。
解析 /config/agent.conf
// /config/agent.config
try (final InputStreamReader configFileStream = loadConfig()) {
AGENT_SETTINGS.load(configFileStream);
for (String key : AGENT_SETTINGS.stringPropertyNames()) {
String value = (String) AGENT_SETTINGS.get(key);
// 配置值里的占位符替换
// aaa = xxx
// bbb = ${aaa}-yyy => xxx-yyy
AGENT_SETTINGS.put(key, PropertyPlaceholderHelper.INSTANCE.replacePlaceholders(value, AGENT_SETTINGS));
}
} catch (Exception e) {
LOGGER.error(e, "Failed to read the config file, skywalking is going to run in default config.");
}
agent.conf 文件的内容
agent.service_name = crmApp
collector.backend_service = 127.0.0.1:8080
logging.level=info
解析系统环境变量
try {
// 系统环境变量
overrideConfigBySystemProp();
} catch (Exception e) {
LOGGER.error(e, "Failed to read the system properties.");
}
解析agent参数
// agent参数
agentOptions = StringUtil.trim(agentOptions, ',');
if (!StringUtil.isEmpty(agentOptions)) {
try {
agentOptions = agentOptions.trim();
LOGGER.info("Agent options is {}.", agentOptions);
// 解析 agentOptions后,遍历参数并存放到 AGENT_SETTINGS
overrideConfigByAgentOptions(agentOptions);
} catch (Exception e) {
LOGGER.error(e, "Failed to parse the agent options, val is {}.", agentOptions);
}
}