获取agent jar包路径的方法:
findPath();
private static File findPath() throws AgentPackageNotFoundException {
String classResourcePath = AgentPackagePath.class.getName().replaceAll("\.", "/") + ".class";// .../.../.../.../.../AgentPackagePath.class
URL resource = ClassLoader.getSystemClassLoader().getResource(classResourcePath);
// jar:file:/.../.../.../.../.../...jar!/.../.../.../.../.../AgentPackagePath.class
if (resource != null) {
String urlString = resource.toString();
int insidePathIndex = urlString.indexOf('!');
boolean isInJar = insidePathIndex > -1;
if (isInJar) {
urlString = urlString.substring(urlString.indexOf("file:"), insidePathIndex);
// urlString = file:/.../.../.../cat-agent.jar
File agentJarFile = null;
try {
agentJarFile = new File(new URL(urlString).toURI());
} catch (MalformedURLException e) {
...
}
if (agentJarFile.exists()) {
return agentJarFile.getParentFile();
}
} else {
...
}
}
...
}
加载plugin:
public List<AbstractClassEnhancePluginDefine> loadPlugins() throws AgentPackageNotFoundException {
AgentClassLoader.initDefaultLoader();
PluginResourcesResolver resolver = new PluginResourcesResolver();
List<URL> resources = resolver.getResources();
...
...
for (URL pluginUrl : resources) {
try {
PluginCfg.INSTANCE.load(pluginUrl.openStream());
} catch (Throwable t) {
...
}
}
List<PluginDefine> pluginClassList = PluginCfg.INSTANCE.getPluginClassList();
List<AbstractClassEnhancePluginDefine> plugins = new ArrayList<AbstractClassEnhancePluginDefine>();
for (PluginDefine pluginDefine : pluginClassList) {
try {
...
AbstractClassEnhancePluginDefine plugin =
(AbstractClassEnhancePluginDefine)Class.forName(pluginDefine.getDefineClass(),
true,
AgentClassLoader.getDefault())
.newInstance();
plugins.add(plugin);
} catch (Throwable t) {
...
}
}
plugins.addAll(DynamicPluginLoader.INSTANCE.load(AgentClassLoader.getDefault()));
return plugins;
}
public List<URL> getResources() {
......
......
try {
urls = AgentClassLoader.getDefault().getResources("skywalking-plugin.def");
while (urls.hasMoreElements()) {
URL pluginUrl = urls.nextElement();
// pluginUrl = jar:file:/../.../activemq-5.x-plugin...jar!/cat-plugin.def
...
...
...
}
...
} catch (IOException e) {
...
}
return null;
}
// PluginCfg.INSTANCE.load
void load(InputStream input) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String pluginDefine = null;
while ((pluginDefine = reader.readLine()) != null) {
try {
if (pluginDefine == null || pluginDefine.trim().length() == 0 || pluginDefine.startsWith("#")) {
continue;
}
PluginDefine plugin = PluginDefine.build(pluginDefine);
pluginClassList.add(plugin);
} catch (IllegalPluginDefineException e) {
logger.error(e, "Failed to format plugin({}) define.", pluginDefine);
}
}
} finally {
input.close();
}
}