-
-
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
Open
sahibamittal
wants to merge
8
commits into
main
Choose a base branch
from
Issue-1862-PluginManager-for-plugins-from-JARs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
71d5c62
Isolated plugin loader in progress
sahibamittal a1a3302
Improve plugin classloader isolation and resource handling
sahibamittal b1aef58
Add tests for external plugin loading in PluginManager
sahibamittal 5b92185
Refactor plugin classloader
sahibamittal f217422
Update PluginManagerExternalPluginTest.java
sahibamittal fb84037
Test WIP
sahibamittal 9136493
Update PluginManager.java
sahibamittal ff5f6d4
Merge branch 'main' into Issue-1862-PluginManager-for-plugins-from-JARs
sahibamittal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
126 changes: 126 additions & 0 deletions
126
apiserver/src/main/java/org/dependencytrack/plugin/PluginIsolatedClassLoader.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,8 +36,14 @@ | |
| import org.jspecify.annotations.Nullable; | ||
| import org.slf4j.MDC; | ||
|
|
||
| import java.io.IOException; | ||
| import java.io.Closeable; | ||
| 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; | ||
|
|
@@ -51,10 +57,12 @@ | |
| import java.util.SequencedMap; | ||
| import java.util.Set; | ||
| import java.util.TreeSet; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import java.util.concurrent.locks.ReentrantLock; | ||
| import java.util.function.Function; | ||
| import java.util.regex.Pattern; | ||
| import java.util.stream.Stream; | ||
|
|
||
| import static java.util.Objects.requireNonNull; | ||
| import static org.dependencytrack.common.MdcKeys.MDC_EXTENSION; | ||
|
|
@@ -89,6 +97,12 @@ public class PluginManager implements Closeable { | |
| private final AtomicBoolean closed = new AtomicBoolean(); | ||
| 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; | ||
|
|
||
| public PluginManager( | ||
| Config config, | ||
| Function<String, @Nullable String> secretResolver, | ||
|
|
@@ -293,11 +307,70 @@ private void loadPluginsLocked(Collection<Plugin> plugins) { | |
| } | ||
| } | ||
|
|
||
| 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." | ||
| ); | ||
|
|
||
| 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(Plugin plugin) { | ||
| final Collection<? extends ExtensionFactory<? extends ExtensionPoint>> extensionFactories = plugin.extensionFactories(); | ||
| if (extensionFactories == null || extensionFactories.isEmpty()) { | ||
|
|
@@ -527,6 +600,7 @@ public void close() { | |
| lock.lock(); | ||
| try { | ||
| unloadPluginsLocked(); | ||
| closeExternalPluginLoaders(); | ||
| defaultFactoryByExtensionPointClass.clear(); | ||
| configRegistryByExtensionIdentity.clear(); | ||
| factoryByExtensionIdentity.clear(); | ||
|
|
@@ -535,6 +609,7 @@ public void close() { | |
| factoriesByPlugin.clear(); | ||
| pluginByExtensionIdentity.clear(); | ||
| loadedPluginByClass.clear(); | ||
| pluginClassToClassLoader.clear(); | ||
| } finally { | ||
| lock.unlock(); | ||
| } | ||
|
|
@@ -584,4 +659,25 @@ private void unloadPlugin(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); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The 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
java.*.