You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PluginLoader.java 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2018 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.core.platform;
  21. import com.google.common.annotations.VisibleForTesting;
  22. import com.google.common.base.Strings;
  23. import java.io.Closeable;
  24. import java.util.Collection;
  25. import java.util.HashMap;
  26. import java.util.Map;
  27. import org.apache.commons.lang.SystemUtils;
  28. import org.sonar.api.Plugin;
  29. import org.sonar.api.utils.log.Loggers;
  30. import org.sonar.updatecenter.common.Version;
  31. import static java.util.Arrays.asList;
  32. /**
  33. * Loads the plugin JAR files by creating the appropriate classloaders and by instantiating
  34. * the entry point classes as defined in manifests. It assumes that JAR files are compatible with current
  35. * environment (minimal sonarqube version, compatibility between plugins, ...):
  36. * <ul>
  37. * <li>server verifies compatibility of JARs before deploying them at startup (see ServerPluginRepository)</li>
  38. * <li>batch loads only the plugins deployed on server (see BatchPluginRepository)</li>
  39. * </ul>
  40. * <p/>
  41. * Plugins have their own isolated classloader, inheriting only from API classes.
  42. * Some plugins can extend a "base" plugin, sharing the same classloader.
  43. * <p/>
  44. * This class is stateless. It does not keep pointers to classloaders and {@link org.sonar.api.Plugin}.
  45. */
  46. public class PluginLoader {
  47. private static final String[] DEFAULT_SHARED_RESOURCES = {"org/sonar/plugins", "com/sonar/plugins", "com/sonarsource/plugins"};
  48. private static final Version COMPATIBILITY_MODE_MAX_VERSION = Version.create("5.2");
  49. private final PluginJarExploder jarExploder;
  50. private final PluginClassloaderFactory classloaderFactory;
  51. public PluginLoader(PluginJarExploder jarExploder, PluginClassloaderFactory classloaderFactory) {
  52. this.jarExploder = jarExploder;
  53. this.classloaderFactory = classloaderFactory;
  54. }
  55. public Map<String, Plugin> load(Map<String, PluginInfo> infoByKeys) {
  56. Collection<PluginClassLoaderDef> defs = defineClassloaders(infoByKeys);
  57. Map<PluginClassLoaderDef, ClassLoader> classloaders = classloaderFactory.create(defs);
  58. return instantiatePluginClasses(classloaders);
  59. }
  60. /**
  61. * Defines the different classloaders to be created. Number of classloaders can be
  62. * different than number of plugins.
  63. */
  64. @VisibleForTesting
  65. Collection<PluginClassLoaderDef> defineClassloaders(Map<String, PluginInfo> infoByKeys) {
  66. Map<String, PluginClassLoaderDef> classloadersByBasePlugin = new HashMap<>();
  67. for (PluginInfo info : infoByKeys.values()) {
  68. String baseKey = basePluginKey(info, infoByKeys);
  69. PluginClassLoaderDef def = classloadersByBasePlugin.get(baseKey);
  70. if (def == null) {
  71. def = new PluginClassLoaderDef(baseKey);
  72. classloadersByBasePlugin.put(baseKey, def);
  73. }
  74. ExplodedPlugin explodedPlugin = jarExploder.explode(info);
  75. def.addFiles(asList(explodedPlugin.getMain()));
  76. def.addFiles(explodedPlugin.getLibs());
  77. def.addMainClass(info.getKey(), info.getMainClass());
  78. for (String defaultSharedResource : DEFAULT_SHARED_RESOURCES) {
  79. def.getExportMask().addInclusion(String.format("%s/%s/api/", defaultSharedResource, info.getKey()));
  80. }
  81. // The plugins that extend other plugins can only add some files to classloader.
  82. // They can't change metadata like ordering strategy or compatibility mode.
  83. if (Strings.isNullOrEmpty(info.getBasePlugin())) {
  84. def.setSelfFirstStrategy(info.isUseChildFirstClassLoader());
  85. Version minSqVersion = info.getMinimalSqVersion();
  86. boolean compatibilityMode = minSqVersion != null && minSqVersion.compareToIgnoreQualifier(COMPATIBILITY_MODE_MAX_VERSION) < 0;
  87. if (compatibilityMode) {
  88. Loggers.get(getClass()).warn("API compatibility mode is no longer supported. In case of error, plugin {} [{}] should package its dependencies.",
  89. info.getName(), info.getKey());
  90. }
  91. }
  92. }
  93. return classloadersByBasePlugin.values();
  94. }
  95. /**
  96. * Instantiates collection of {@link org.sonar.api.Plugin} according to given metadata and classloaders
  97. *
  98. * @return the instances grouped by plugin key
  99. * @throws IllegalStateException if at least one plugin can't be correctly loaded
  100. */
  101. @VisibleForTesting
  102. Map<String, Plugin> instantiatePluginClasses(Map<PluginClassLoaderDef, ClassLoader> classloaders) {
  103. // instantiate plugins
  104. Map<String, Plugin> instancesByPluginKey = new HashMap<>();
  105. for (Map.Entry<PluginClassLoaderDef, ClassLoader> entry : classloaders.entrySet()) {
  106. PluginClassLoaderDef def = entry.getKey();
  107. ClassLoader classLoader = entry.getValue();
  108. // the same classloader can be used by multiple plugins
  109. for (Map.Entry<String, String> mainClassEntry : def.getMainClassesByPluginKey().entrySet()) {
  110. String pluginKey = mainClassEntry.getKey();
  111. String mainClass = mainClassEntry.getValue();
  112. try {
  113. instancesByPluginKey.put(pluginKey, (Plugin) classLoader.loadClass(mainClass).newInstance());
  114. } catch (UnsupportedClassVersionError e) {
  115. throw new IllegalStateException(String.format("The plugin [%s] does not support Java %s",
  116. pluginKey, SystemUtils.JAVA_VERSION_TRIMMED), e);
  117. } catch (Throwable e) {
  118. throw new IllegalStateException(String.format(
  119. "Fail to instantiate class [%s] of plugin [%s]", mainClass, pluginKey), e);
  120. }
  121. }
  122. }
  123. return instancesByPluginKey;
  124. }
  125. public void unload(Collection<Plugin> plugins) {
  126. for (Plugin plugin : plugins) {
  127. ClassLoader classLoader = plugin.getClass().getClassLoader();
  128. if (classLoader instanceof Closeable && classLoader != classloaderFactory.baseClassLoader()) {
  129. try {
  130. ((Closeable) classLoader).close();
  131. } catch (Exception e) {
  132. Loggers.get(getClass()).error("Fail to close classloader " + classLoader.toString(), e);
  133. }
  134. }
  135. }
  136. }
  137. /**
  138. * Get the root key of a tree of plugins. For example if plugin C depends on B, which depends on A, then
  139. * B and C must be attached to the classloader of A. The method returns A in the three cases.
  140. */
  141. static String basePluginKey(PluginInfo plugin, Map<String, PluginInfo> allPluginsPerKey) {
  142. String base = plugin.getKey();
  143. String parentKey = plugin.getBasePlugin();
  144. while (!Strings.isNullOrEmpty(parentKey)) {
  145. PluginInfo parentPlugin = allPluginsPerKey.get(parentKey);
  146. base = parentPlugin.getKey();
  147. parentKey = parentPlugin.getBasePlugin();
  148. }
  149. return base;
  150. }
  151. }