-
-
Notifications
You must be signed in to change notification settings - Fork 35
Issue 1862 : Extend PluginManager to support loading of plugins from JARs #1538
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 6 commits
71d5c62
a1a3302
b1aef58
5b92185
f217422
fb84037
9136493
ff5f6d4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| /* | ||
| * This file is part of Dependency-Track. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| * | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| * Copyright (c) OWASP Foundation. All Rights Reserved. | ||
| */ | ||
| package org.dependencytrack.plugin; | ||
|
|
||
| import java.io.IOException; | ||
| import java.net.URL; | ||
| import java.net.URLClassLoader; | ||
| import java.util.Enumeration; | ||
| import java.util.List; | ||
| import java.util.Objects; | ||
|
|
||
| /** | ||
| * Child-first classloader with configurable shared package prefixes. | ||
| */ | ||
| public final class PluginIsolatedClassLoader extends URLClassLoader { | ||
|
|
||
| private final ClassLoader hostClassLoader; | ||
| private final List<String> sharedPackagePrefixes; | ||
|
|
||
| /** | ||
| * @param urls URLs pointing to plugin JAR(s). | ||
| * @param hostClassLoader classloader to supply shared API classes. | ||
| * @param sharedPackagePrefixes list of package prefixes that must be loaded from host. | ||
| */ | ||
| public PluginIsolatedClassLoader(final URL[] urls, final ClassLoader hostClassLoader, final List<String> sharedPackagePrefixes) { | ||
| super(urls, null); | ||
| this.hostClassLoader = Objects.requireNonNull(hostClassLoader, "hostClassLoader"); | ||
| this.sharedPackagePrefixes = List.copyOf(Objects.requireNonNull(sharedPackagePrefixes, "sharedPackagePrefixes")); | ||
| } | ||
|
|
||
| private boolean isShared(final String className) { | ||
| for (final String prefix : sharedPackagePrefixes) { | ||
| if (className.startsWith(prefix)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| @Override | ||
| protected synchronized Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { | ||
| // delegate to host | ||
| if (isShared(name)) { | ||
| return hostClassLoader.loadClass(name); | ||
| } | ||
|
|
||
| Class<?> loaded = findLoadedClass(name); | ||
| if (loaded != null) { | ||
| if (resolve) { | ||
| resolveClass(loaded); | ||
| } | ||
| return loaded; | ||
| } | ||
|
|
||
| // Try to load from plugin JAR | ||
| try { | ||
| Class<?> clazz = findClass(name); | ||
| if (resolve) { | ||
| resolveClass(clazz); | ||
| } | ||
| return clazz; | ||
| } catch (ClassNotFoundException ignored) { | ||
| } | ||
|
|
||
| // Fallback to host classloader | ||
| return hostClassLoader.loadClass(name); | ||
| } | ||
|
|
||
| @Override | ||
| public URL getResource(final String name) { | ||
| final String dotted = name.replace('/', '.'); | ||
| for (final String prefix : sharedPackagePrefixes) { | ||
| if (dotted.startsWith(prefix)) { | ||
| return hostClassLoader.getResource(name); | ||
| } | ||
| } | ||
|
|
||
| final URL url = findResource(name); | ||
| if (url != null) { | ||
| return url; | ||
| } | ||
| return hostClassLoader.getResource(name); | ||
| } | ||
|
|
||
| @Override | ||
| public Enumeration<URL> getResources(final String name) throws IOException { | ||
| final Enumeration<URL> pluginResources = findResources(name); | ||
| final Enumeration<URL> hostResources = hostClassLoader.getResources(name); | ||
|
|
||
| return new Enumeration<>() { | ||
| @Override | ||
| public boolean hasMoreElements() { | ||
| return pluginResources.hasMoreElements() || hostResources.hasMoreElements(); | ||
| } | ||
|
|
||
| @Override | ||
| public URL nextElement() { | ||
| if (pluginResources.hasMoreElements()) { | ||
| return pluginResources.nextElement(); | ||
| } | ||
| return hostResources.nextElement(); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| @Override | ||
| public void close() throws IOException { | ||
| super.close(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -32,7 +32,13 @@ | |
| import org.dependencytrack.plugin.api.storage.ExtensionKVStore; | ||
| import org.slf4j.MDC; | ||
|
|
||
| import java.io.IOException; | ||
| import java.lang.reflect.Modifier; | ||
| import java.net.URL; | ||
| import java.net.URLClassLoader; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.Paths; | ||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.Collections; | ||
|
|
@@ -48,8 +54,10 @@ | |
| import java.util.ServiceLoader; | ||
| import java.util.Set; | ||
| import java.util.TreeSet; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.locks.ReentrantLock; | ||
| import java.util.regex.Pattern; | ||
| import java.util.stream.Stream; | ||
|
|
||
| import static org.dependencytrack.common.MdcKeys.MDC_EXTENSION; | ||
| import static org.dependencytrack.common.MdcKeys.MDC_EXTENSION_NAME; | ||
|
|
@@ -83,6 +91,12 @@ public class PluginManager { | |
| private final Comparator<ExtensionFactory<?>> factoryComparator; | ||
| private final ReentrantLock lock; | ||
|
|
||
| // Map of each plugin class to its ClassLoader | ||
| private final Map<Class<?>, ClassLoader> pluginClassToClassLoader = new ConcurrentHashMap<>(); | ||
| private final Map<ClassLoader, Path> externalPluginLoaders = new ConcurrentHashMap<>(); | ||
| private boolean externalPluginsEnabled = false; | ||
| private Path externalPluginDir; | ||
|
|
||
| private PluginManager() { | ||
| this.loadedPluginByClass = new LinkedHashMap<>(); | ||
| this.pluginByExtensionIdentity = new HashMap<>(); | ||
|
|
@@ -244,11 +258,71 @@ private void loadPluginsLocked() { | |
| } | ||
| } | ||
|
|
||
| if (externalPluginsEnabled) { | ||
| LOGGER.info("Discovering external plugins in: %s".formatted(externalPluginDir)); | ||
| loadExternalPlugins(externalPluginDir); | ||
| } else { | ||
| LOGGER.info("External plugin loading disabled — skipping external scan."); | ||
| } | ||
|
|
||
| determineDefaultExtensions(); | ||
|
|
||
| assertRequiredExtensionPoints(); | ||
| } | ||
|
|
||
| private void loadExternalPlugins(final Path externalPluginDir) { | ||
| try (Stream<Path> jars = Files.list(externalPluginDir) | ||
| .filter(path -> path.toString().endsWith(".jar"))) { | ||
| jars.forEach(this::loadExternalPluginJar); | ||
| } catch (IOException e) { | ||
| LOGGER.warn("Failed to scan external plugin directory: %s".formatted(externalPluginDir), e); | ||
| } | ||
| } | ||
|
|
||
| private void loadExternalPluginJar(final Path jarPath) { | ||
| try (var ignoredMdcPlugin = MDC.putCloseable(MDC_PLUGIN, jarPath.getFileName().toString())) { | ||
|
|
||
| final URL jarUrl = jarPath.toUri().toURL(); | ||
|
|
||
| // Host classloader to load the Plugin API | ||
| final ClassLoader hostClassLoader = Plugin.class.getClassLoader(); | ||
|
|
||
| // Shared package prefixes | ||
| final List<String> sharedPackages = List.of( | ||
| "org.dependencytrack.plugin.api.", | ||
| "org.dependencytrack.plugin." | ||
|
sahibamittal marked this conversation as resolved.
Outdated
|
||
| ); | ||
|
Comment on lines
+340
to
+342
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be moved to the plugin classloader itself - no need to re-define this for every JAR again. Also have a look at the references I linked in DependencyTrack/hyades#1862. There are more packages that should be shared, for example those of the Java standard library under |
||
|
|
||
| final PluginIsolatedClassLoader loader = new PluginIsolatedClassLoader( | ||
| new URL[]{ jarUrl }, hostClassLoader, sharedPackages); | ||
|
|
||
| externalPluginLoaders.put(loader, jarPath); | ||
| final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); | ||
|
|
||
| try { | ||
| Thread.currentThread().setContextClassLoader(loader); | ||
|
|
||
| final ServiceLoader<Plugin> pluginServiceLoader = ServiceLoader.load(Plugin.class, loader); | ||
| for (final Plugin plugin : pluginServiceLoader) { | ||
| try (var ignored = MDC.putCloseable(MDC_PLUGIN, plugin.getClass().getName())) { | ||
| LOGGER.debug("Loading external plugin %s".formatted(plugin.getClass().getName())); | ||
| loadExtensionsForPlugin(plugin); | ||
| loadedPluginByClass.put(plugin.getClass(), plugin); | ||
|
|
||
| // Map the plugin class to its loader for unloading | ||
| pluginClassToClassLoader.put(plugin.getClass(), loader); | ||
| LOGGER.info("External plugin loaded successfully: %s".formatted(plugin.getClass().getName())); | ||
| } | ||
| } | ||
| } finally { | ||
| Thread.currentThread().setContextClassLoader(contextClassLoader); | ||
| } | ||
|
|
||
| } catch (Exception e) { | ||
| LOGGER.error("Failed to load external plugin from JAR %s".formatted(jarPath), e); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should probably |
||
| } | ||
| } | ||
|
|
||
| private void loadExtensionsForPlugin(final Plugin plugin) { | ||
| final Collection<? extends ExtensionFactory<? extends ExtensionPoint>> extensionFactories = plugin.extensionFactories(); | ||
| if (extensionFactories == null || extensionFactories.isEmpty()) { | ||
|
|
@@ -433,13 +507,15 @@ void unloadPlugins() { | |
| lock.lock(); | ||
| try { | ||
| unloadPluginsLocked(); | ||
| closeExternalPluginLoaders(); | ||
| defaultFactoryByExtensionPointClass.clear(); | ||
| factoryByExtensionIdentity.clear(); | ||
| extensionNamesByExtensionPointClass.clear(); | ||
| specByExtensionPointClass.clear(); | ||
| factoriesByPlugin.clear(); | ||
| pluginByExtensionIdentity.clear(); | ||
| loadedPluginByClass.clear(); | ||
| pluginClassToClassLoader.clear(); | ||
| } finally { | ||
| lock.unlock(); | ||
| } | ||
|
|
@@ -485,4 +561,25 @@ private void unloadPlugin(final Plugin plugin) { | |
| } | ||
| } | ||
|
|
||
| private void closeExternalPluginLoaders() { | ||
| // Close all external loaders if any | ||
| for (ClassLoader loader : new ArrayList<>(externalPluginLoaders.keySet())) { | ||
| try { | ||
| if (loader instanceof PluginIsolatedClassLoader) { | ||
| ((PluginIsolatedClassLoader) loader).close(); | ||
| } else if (loader instanceof URLClassLoader) { | ||
| ((URLClassLoader) loader).close(); | ||
| } | ||
| } catch (IOException e) { | ||
| LOGGER.warn("Failed to close plugin classloader for %s: %s".formatted(externalPluginLoaders.get(loader), e.getMessage())); | ||
| } finally { | ||
| externalPluginLoaders.remove(loader); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public void setExternalPluginConfig(boolean enabled, String directory) { | ||
| this.externalPluginsEnabled = enabled; | ||
| this.externalPluginDir = Paths.get(directory); | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.