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.

AbstractPluginManager.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /*
  2. * Copyright (C) 2012-present the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.pf4j;
  17. import org.pf4j.util.StringUtils;
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import java.io.Closeable;
  21. import java.io.IOException;
  22. import java.nio.file.Files;
  23. import java.nio.file.Path;
  24. import java.nio.file.Paths;
  25. import java.util.ArrayList;
  26. import java.util.Collections;
  27. import java.util.HashMap;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Map;
  31. import java.util.Set;
  32. /**
  33. * This class implements the boilerplate plugin code that any {@link PluginManager}
  34. * implementation would have to support.
  35. * It helps cut the noise out of the subclass that handles plugin management.
  36. *
  37. * <p>This class is not thread-safe.
  38. *
  39. * @author Decebal Suiu
  40. */
  41. public abstract class AbstractPluginManager implements PluginManager {
  42. private static final Logger log = LoggerFactory.getLogger(AbstractPluginManager.class);
  43. public static final String PLUGINS_DIR_PROPERTY_NAME = "pf4j.pluginsDir";
  44. public static final String MODE_PROPERTY_NAME = "pf4j.mode";
  45. public static final String DEFAULT_PLUGINS_DIR = "plugins";
  46. public static final String DEVELOPMENT_PLUGINS_DIR = "../plugins";
  47. protected Path pluginsRoot;
  48. protected ExtensionFinder extensionFinder;
  49. protected PluginDescriptorFinder pluginDescriptorFinder;
  50. /**
  51. * A map of plugins this manager is responsible for (the key is the 'pluginId').
  52. */
  53. protected Map<String, PluginWrapper> plugins;
  54. /**
  55. * A map of plugin class loaders (the key is the 'pluginId').
  56. */
  57. protected Map<String, ClassLoader> pluginClassLoaders;
  58. /**
  59. * A list with unresolved plugins (unresolved dependency).
  60. */
  61. protected List<PluginWrapper> unresolvedPlugins;
  62. /**
  63. * A list with all resolved plugins (resolved dependency).
  64. */
  65. protected List<PluginWrapper> resolvedPlugins;
  66. /**
  67. * A list with started plugins.
  68. */
  69. protected List<PluginWrapper> startedPlugins;
  70. /**
  71. * The registered {@link PluginStateListener}s.
  72. */
  73. protected List<PluginStateListener> pluginStateListeners;
  74. /**
  75. * Cache value for the runtime mode.
  76. * No need to re-read it because it wont change at runtime.
  77. */
  78. protected RuntimeMode runtimeMode;
  79. /**
  80. * The system version used for comparisons to the plugin requires attribute.
  81. */
  82. protected String systemVersion = "0.0.0";
  83. protected PluginRepository pluginRepository;
  84. protected PluginFactory pluginFactory;
  85. protected ExtensionFactory extensionFactory;
  86. protected PluginStatusProvider pluginStatusProvider;
  87. protected DependencyResolver dependencyResolver;
  88. protected PluginLoader pluginLoader;
  89. protected boolean exactVersionAllowed = false;
  90. protected VersionManager versionManager;
  91. /**
  92. * The plugins root is supplied by {@code System.getProperty("pf4j.pluginsDir", "plugins")}.
  93. */
  94. public AbstractPluginManager() {
  95. initialize();
  96. }
  97. /**
  98. * Constructs {@code AbstractPluginManager} with the given plugins root.
  99. *
  100. * @param pluginsRoot the root to search for plugins
  101. */
  102. public AbstractPluginManager(Path pluginsRoot) {
  103. this.pluginsRoot = pluginsRoot;
  104. initialize();
  105. }
  106. @Override
  107. public void setSystemVersion(String version) {
  108. systemVersion = version;
  109. }
  110. @Override
  111. public String getSystemVersion() {
  112. return systemVersion;
  113. }
  114. /**
  115. * Returns a copy of plugins.
  116. */
  117. @Override
  118. public List<PluginWrapper> getPlugins() {
  119. return new ArrayList<>(plugins.values());
  120. }
  121. /**
  122. * Returns a copy of plugins with that state.
  123. */
  124. @Override
  125. public List<PluginWrapper> getPlugins(PluginState pluginState) {
  126. List<PluginWrapper> plugins = new ArrayList<>();
  127. for (PluginWrapper plugin : getPlugins()) {
  128. if (pluginState.equals(plugin.getPluginState())) {
  129. plugins.add(plugin);
  130. }
  131. }
  132. return plugins;
  133. }
  134. @Override
  135. public List<PluginWrapper> getResolvedPlugins() {
  136. return resolvedPlugins;
  137. }
  138. @Override
  139. public List<PluginWrapper> getUnresolvedPlugins() {
  140. return unresolvedPlugins;
  141. }
  142. @Override
  143. public List<PluginWrapper> getStartedPlugins() {
  144. return startedPlugins;
  145. }
  146. @Override
  147. public PluginWrapper getPlugin(String pluginId) {
  148. return plugins.get(pluginId);
  149. }
  150. @Override
  151. public String loadPlugin(Path pluginPath) {
  152. if ((pluginPath == null) || Files.notExists(pluginPath)) {
  153. throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginPath));
  154. }
  155. log.debug("Loading plugin from '{}'", pluginPath);
  156. PluginWrapper pluginWrapper = loadPluginFromPath(pluginPath);
  157. // try to resolve the loaded plugin together with other possible plugins that depend on this plugin
  158. resolvePlugins();
  159. return pluginWrapper.getDescriptor().getPluginId();
  160. }
  161. /**
  162. * Load plugins.
  163. */
  164. @Override
  165. public void loadPlugins() {
  166. log.debug("Lookup plugins in '{}'", pluginsRoot);
  167. // check for plugins root
  168. if (Files.notExists(pluginsRoot) || !Files.isDirectory(pluginsRoot)) {
  169. log.warn("No '{}' root", pluginsRoot);
  170. return;
  171. }
  172. // get all plugin paths from repository
  173. List<Path> pluginPaths = pluginRepository.getPluginPaths();
  174. // check for no plugins
  175. if (pluginPaths.isEmpty()) {
  176. log.info("No plugins");
  177. return;
  178. }
  179. log.debug("Found {} possible plugins: {}", pluginPaths.size(), pluginPaths);
  180. // load plugins from plugin paths
  181. for (Path pluginPath : pluginPaths) {
  182. try {
  183. loadPluginFromPath(pluginPath);
  184. } catch (PluginRuntimeException e) {
  185. log.error(e.getMessage(), e);
  186. }
  187. }
  188. // resolve plugins
  189. try {
  190. resolvePlugins();
  191. } catch (PluginRuntimeException e) {
  192. log.error(e.getMessage(), e);
  193. }
  194. }
  195. /**
  196. * Unload all plugins
  197. */
  198. @Override
  199. public void unloadPlugins() {
  200. // wrap resolvedPlugins in new list because of concurrent modification
  201. for (PluginWrapper pluginWrapper : new ArrayList<>(resolvedPlugins)) {
  202. unloadPlugin(pluginWrapper.getPluginId());
  203. }
  204. }
  205. /**
  206. * Unload the specified plugin and it's dependents.
  207. */
  208. @Override
  209. public boolean unloadPlugin(String pluginId) {
  210. return unloadPlugin(pluginId, true);
  211. }
  212. protected boolean unloadPlugin(String pluginId, boolean unloadDependents) {
  213. try {
  214. if (unloadDependents) {
  215. List<String> dependents = dependencyResolver.getDependents(pluginId);
  216. while (!dependents.isEmpty()) {
  217. String dependent = dependents.remove(0);
  218. unloadPlugin(dependent, false);
  219. dependents.addAll(0, dependencyResolver.getDependents(dependent));
  220. }
  221. }
  222. PluginState pluginState = stopPlugin(pluginId, false);
  223. if (PluginState.STARTED == pluginState) {
  224. return false;
  225. }
  226. PluginWrapper pluginWrapper = getPlugin(pluginId);
  227. log.info("Unload plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  228. // remove the plugin
  229. plugins.remove(pluginId);
  230. getResolvedPlugins().remove(pluginWrapper);
  231. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  232. // remove the classloader
  233. Map<String, ClassLoader> pluginClassLoaders = getPluginClassLoaders();
  234. if (pluginClassLoaders.containsKey(pluginId)) {
  235. ClassLoader classLoader = pluginClassLoaders.remove(pluginId);
  236. if (classLoader instanceof Closeable) {
  237. try {
  238. ((Closeable) classLoader).close();
  239. } catch (IOException e) {
  240. throw new PluginRuntimeException(e, "Cannot close classloader");
  241. }
  242. }
  243. }
  244. return true;
  245. } catch (IllegalArgumentException e) {
  246. // ignore not found exceptions because this method is recursive
  247. }
  248. return false;
  249. }
  250. @Override
  251. public boolean deletePlugin(String pluginId) {
  252. checkPluginId(pluginId);
  253. PluginWrapper pluginWrapper = getPlugin(pluginId);
  254. // stop the plugin if it's started
  255. PluginState pluginState = stopPlugin(pluginId);
  256. if (PluginState.STARTED == pluginState) {
  257. log.error("Failed to stop plugin '{}' on delete", pluginId);
  258. return false;
  259. }
  260. // get an instance of plugin before the plugin is unloaded
  261. // for reason see https://github.com/pf4j/pf4j/issues/309
  262. Plugin plugin = pluginWrapper.getPlugin();
  263. if (!unloadPlugin(pluginId)) {
  264. log.error("Failed to unload plugin '{}' on delete", pluginId);
  265. return false;
  266. }
  267. // notify the plugin as it's deleted
  268. plugin.delete();
  269. Path pluginPath = pluginWrapper.getPluginPath();
  270. return pluginRepository.deletePluginPath(pluginPath);
  271. }
  272. /**
  273. * Start all active plugins.
  274. */
  275. @Override
  276. public void startPlugins() {
  277. for (PluginWrapper pluginWrapper : resolvedPlugins) {
  278. PluginState pluginState = pluginWrapper.getPluginState();
  279. if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) {
  280. try {
  281. log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  282. pluginWrapper.getPlugin().start();
  283. pluginWrapper.setPluginState(PluginState.STARTED);
  284. pluginWrapper.setFailedException(null);
  285. startedPlugins.add(pluginWrapper);
  286. } catch (Exception | LinkageError e) {
  287. pluginWrapper.setPluginState(PluginState.FAILED);
  288. pluginWrapper.setFailedException(e);
  289. log.error("Unable to start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()), e);
  290. } finally {
  291. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  292. }
  293. }
  294. }
  295. }
  296. /**
  297. * Start the specified plugin and its dependencies.
  298. */
  299. @Override
  300. public PluginState startPlugin(String pluginId) {
  301. checkPluginId(pluginId);
  302. PluginWrapper pluginWrapper = getPlugin(pluginId);
  303. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  304. PluginState pluginState = pluginWrapper.getPluginState();
  305. if (PluginState.STARTED == pluginState) {
  306. log.debug("Already started plugin '{}'", getPluginLabel(pluginDescriptor));
  307. return PluginState.STARTED;
  308. }
  309. if (!resolvedPlugins.contains(pluginWrapper)) {
  310. log.warn("Cannot start an unresolved plugin '{}'", getPluginLabel(pluginDescriptor));
  311. return pluginState;
  312. }
  313. if (PluginState.DISABLED == pluginState) {
  314. // automatically enable plugin on manual plugin start
  315. if (!enablePlugin(pluginId)) {
  316. return pluginState;
  317. }
  318. }
  319. for (PluginDependency dependency : pluginDescriptor.getDependencies()) {
  320. // start dependency only if it marked as required (non optional) or if it optional and loaded
  321. if (!dependency.isOptional() || plugins.containsKey(dependency.getPluginId())) {
  322. startPlugin(dependency.getPluginId());
  323. }
  324. }
  325. log.info("Start plugin '{}'", getPluginLabel(pluginDescriptor));
  326. pluginWrapper.getPlugin().start();
  327. pluginWrapper.setPluginState(PluginState.STARTED);
  328. startedPlugins.add(pluginWrapper);
  329. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  330. return pluginWrapper.getPluginState();
  331. }
  332. /**
  333. * Stop all active plugins.
  334. */
  335. @Override
  336. public void stopPlugins() {
  337. // stop started plugins in reverse order
  338. Collections.reverse(startedPlugins);
  339. Iterator<PluginWrapper> itr = startedPlugins.iterator();
  340. while (itr.hasNext()) {
  341. PluginWrapper pluginWrapper = itr.next();
  342. PluginState pluginState = pluginWrapper.getPluginState();
  343. if (PluginState.STARTED == pluginState) {
  344. try {
  345. log.info("Stop plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  346. pluginWrapper.getPlugin().stop();
  347. pluginWrapper.setPluginState(PluginState.STOPPED);
  348. itr.remove();
  349. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  350. } catch (PluginRuntimeException e) {
  351. log.error(e.getMessage(), e);
  352. }
  353. }
  354. }
  355. }
  356. /**
  357. * Stop the specified plugin and it's dependents.
  358. */
  359. @Override
  360. public PluginState stopPlugin(String pluginId) {
  361. return stopPlugin(pluginId, true);
  362. }
  363. protected PluginState stopPlugin(String pluginId, boolean stopDependents) {
  364. checkPluginId(pluginId);
  365. PluginWrapper pluginWrapper = getPlugin(pluginId);
  366. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  367. PluginState pluginState = pluginWrapper.getPluginState();
  368. if (PluginState.STOPPED == pluginState) {
  369. log.debug("Already stopped plugin '{}'", getPluginLabel(pluginDescriptor));
  370. return PluginState.STOPPED;
  371. }
  372. // test for disabled plugin
  373. if (PluginState.DISABLED == pluginState) {
  374. // do nothing
  375. return pluginState;
  376. }
  377. if (stopDependents) {
  378. List<String> dependents = dependencyResolver.getDependents(pluginId);
  379. while (!dependents.isEmpty()) {
  380. String dependent = dependents.remove(0);
  381. stopPlugin(dependent, false);
  382. dependents.addAll(0, dependencyResolver.getDependents(dependent));
  383. }
  384. }
  385. log.info("Stop plugin '{}'", getPluginLabel(pluginDescriptor));
  386. pluginWrapper.getPlugin().stop();
  387. pluginWrapper.setPluginState(PluginState.STOPPED);
  388. startedPlugins.remove(pluginWrapper);
  389. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  390. return pluginWrapper.getPluginState();
  391. }
  392. protected void checkPluginId(String pluginId) {
  393. if (!plugins.containsKey(pluginId)) {
  394. throw new IllegalArgumentException(String.format("Unknown pluginId %s", pluginId));
  395. }
  396. }
  397. @Override
  398. public boolean disablePlugin(String pluginId) {
  399. checkPluginId(pluginId);
  400. PluginWrapper pluginWrapper = getPlugin(pluginId);
  401. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  402. PluginState pluginState = pluginWrapper.getPluginState();
  403. if (PluginState.DISABLED == pluginState) {
  404. log.debug("Already disabled plugin '{}'", getPluginLabel(pluginDescriptor));
  405. return true;
  406. }
  407. if (PluginState.STOPPED == stopPlugin(pluginId)) {
  408. pluginWrapper.setPluginState(PluginState.DISABLED);
  409. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, PluginState.STOPPED));
  410. pluginStatusProvider.disablePlugin(pluginId);
  411. log.info("Disabled plugin '{}'", getPluginLabel(pluginDescriptor));
  412. return true;
  413. }
  414. return false;
  415. }
  416. @Override
  417. public boolean enablePlugin(String pluginId) {
  418. checkPluginId(pluginId);
  419. PluginWrapper pluginWrapper = getPlugin(pluginId);
  420. if (!isPluginValid(pluginWrapper)) {
  421. log.warn("Plugin '{}' can not be enabled", getPluginLabel(pluginWrapper.getDescriptor()));
  422. return false;
  423. }
  424. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  425. PluginState pluginState = pluginWrapper.getPluginState();
  426. if (PluginState.DISABLED != pluginState) {
  427. log.debug("Plugin '{}' is not disabled", getPluginLabel(pluginDescriptor));
  428. return true;
  429. }
  430. pluginStatusProvider.enablePlugin(pluginId);
  431. pluginWrapper.setPluginState(PluginState.CREATED);
  432. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  433. log.info("Enabled plugin '{}'", getPluginLabel(pluginDescriptor));
  434. return true;
  435. }
  436. /**
  437. * Get the {@link ClassLoader} for plugin.
  438. */
  439. @Override
  440. public ClassLoader getPluginClassLoader(String pluginId) {
  441. return pluginClassLoaders.get(pluginId);
  442. }
  443. @SuppressWarnings("rawtypes")
  444. @Override
  445. public List<Class<?>> getExtensionClasses(String pluginId) {
  446. List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
  447. List<Class<?>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
  448. for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
  449. Class<?> c = extensionWrapper.getDescriptor().extensionClass;
  450. extensionClasses.add(c);
  451. }
  452. return extensionClasses;
  453. }
  454. @Override
  455. public <T> List<Class<? extends T>> getExtensionClasses(Class<T> type) {
  456. return getExtensionClasses(extensionFinder.find(type));
  457. }
  458. @Override
  459. public <T> List<Class<? extends T>> getExtensionClasses(Class<T> type, String pluginId) {
  460. return getExtensionClasses(extensionFinder.find(type, pluginId));
  461. }
  462. @Override
  463. public <T> List<T> getExtensions(Class<T> type) {
  464. return getExtensions(extensionFinder.find(type));
  465. }
  466. @Override
  467. public <T> List<T> getExtensions(Class<T> type, String pluginId) {
  468. return getExtensions(extensionFinder.find(type, pluginId));
  469. }
  470. @Override
  471. @SuppressWarnings("unchecked")
  472. public List getExtensions(String pluginId) {
  473. List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
  474. List extensions = new ArrayList<>(extensionsWrapper.size());
  475. for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
  476. try {
  477. extensions.add(extensionWrapper.getExtension());
  478. } catch (PluginRuntimeException e) {
  479. log.error("Cannot retrieve extension", e);
  480. }
  481. }
  482. return extensions;
  483. }
  484. @Override
  485. public Set<String> getExtensionClassNames(String pluginId) {
  486. return extensionFinder.findClassNames(pluginId);
  487. }
  488. @Override
  489. public ExtensionFactory getExtensionFactory() {
  490. return extensionFactory;
  491. }
  492. public PluginLoader getPluginLoader() {
  493. return pluginLoader;
  494. }
  495. public Path getPluginsRoot() {
  496. return pluginsRoot;
  497. }
  498. @Override
  499. public RuntimeMode getRuntimeMode() {
  500. if (runtimeMode == null) {
  501. // retrieves the runtime mode from system
  502. String modeAsString = System.getProperty(MODE_PROPERTY_NAME, RuntimeMode.DEPLOYMENT.toString());
  503. runtimeMode = RuntimeMode.byName(modeAsString);
  504. }
  505. return runtimeMode;
  506. }
  507. @Override
  508. public PluginWrapper whichPlugin(Class<?> clazz) {
  509. ClassLoader classLoader = clazz.getClassLoader();
  510. for (PluginWrapper plugin : resolvedPlugins) {
  511. if (plugin.getPluginClassLoader() == classLoader) {
  512. return plugin;
  513. }
  514. }
  515. return null;
  516. }
  517. @Override
  518. public synchronized void addPluginStateListener(PluginStateListener listener) {
  519. pluginStateListeners.add(listener);
  520. }
  521. @Override
  522. public synchronized void removePluginStateListener(PluginStateListener listener) {
  523. pluginStateListeners.remove(listener);
  524. }
  525. public String getVersion() {
  526. String version = null;
  527. Package pf4jPackage = PluginManager.class.getPackage();
  528. if (pf4jPackage != null) {
  529. version = pf4jPackage.getImplementationVersion();
  530. if (version == null) {
  531. version = pf4jPackage.getSpecificationVersion();
  532. }
  533. }
  534. return (version != null) ? version : "0.0.0";
  535. }
  536. protected abstract PluginRepository createPluginRepository();
  537. protected abstract PluginFactory createPluginFactory();
  538. protected abstract ExtensionFactory createExtensionFactory();
  539. protected abstract PluginDescriptorFinder createPluginDescriptorFinder();
  540. protected abstract ExtensionFinder createExtensionFinder();
  541. protected abstract PluginStatusProvider createPluginStatusProvider();
  542. protected abstract PluginLoader createPluginLoader();
  543. protected abstract VersionManager createVersionManager();
  544. protected PluginDescriptorFinder getPluginDescriptorFinder() {
  545. return pluginDescriptorFinder;
  546. }
  547. protected PluginFactory getPluginFactory() {
  548. return pluginFactory;
  549. }
  550. protected Map<String, ClassLoader> getPluginClassLoaders() {
  551. return pluginClassLoaders;
  552. }
  553. protected void initialize() {
  554. plugins = new HashMap<>();
  555. pluginClassLoaders = new HashMap<>();
  556. unresolvedPlugins = new ArrayList<>();
  557. resolvedPlugins = new ArrayList<>();
  558. startedPlugins = new ArrayList<>();
  559. pluginStateListeners = new ArrayList<>();
  560. if (pluginsRoot == null) {
  561. pluginsRoot = createPluginsRoot();
  562. }
  563. pluginRepository = createPluginRepository();
  564. pluginFactory = createPluginFactory();
  565. extensionFactory = createExtensionFactory();
  566. pluginDescriptorFinder = createPluginDescriptorFinder();
  567. extensionFinder = createExtensionFinder();
  568. pluginStatusProvider = createPluginStatusProvider();
  569. pluginLoader = createPluginLoader();
  570. versionManager = createVersionManager();
  571. dependencyResolver = new DependencyResolver(versionManager);
  572. }
  573. /**
  574. * Add the possibility to override the plugins root.
  575. * If a {@link #PLUGINS_DIR_PROPERTY_NAME} system property is defined than this method returns that root.
  576. * If {@link #getRuntimeMode()} returns {@link RuntimeMode#DEVELOPMENT} than {@link #DEVELOPMENT_PLUGINS_DIR}
  577. * is returned else this method returns {@link #DEFAULT_PLUGINS_DIR}.
  578. *
  579. * @return the plugins root
  580. */
  581. protected Path createPluginsRoot() {
  582. String pluginsDir = System.getProperty(PLUGINS_DIR_PROPERTY_NAME);
  583. if (pluginsDir == null) {
  584. pluginsDir = isDevelopment() ? DEVELOPMENT_PLUGINS_DIR : DEFAULT_PLUGINS_DIR;
  585. }
  586. return Paths.get(pluginsDir);
  587. }
  588. /**
  589. * Check if this plugin is valid (satisfies "requires" param) for a given system version.
  590. *
  591. * @param pluginWrapper the plugin to check
  592. * @return true if plugin satisfies the "requires" or if requires was left blank
  593. */
  594. protected boolean isPluginValid(PluginWrapper pluginWrapper) {
  595. String requires = pluginWrapper.getDescriptor().getRequires().trim();
  596. if (!isExactVersionAllowed() && requires.matches("^\\d+\\.\\d+\\.\\d+$")) {
  597. // If exact versions are not allowed in requires, rewrite to >= expression
  598. requires = ">=" + requires;
  599. }
  600. if (systemVersion.equals("0.0.0") || versionManager.checkVersionConstraint(systemVersion, requires)) {
  601. return true;
  602. }
  603. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  604. log.warn("Plugin '{}' requires a minimum system version of {}, and you have {}",
  605. getPluginLabel(pluginDescriptor),
  606. pluginWrapper.getDescriptor().getRequires(),
  607. getSystemVersion());
  608. return false;
  609. }
  610. protected boolean isPluginDisabled(String pluginId) {
  611. return pluginStatusProvider.isPluginDisabled(pluginId);
  612. }
  613. protected void resolvePlugins() {
  614. // retrieves the plugins descriptors
  615. List<PluginDescriptor> descriptors = new ArrayList<>();
  616. for (PluginWrapper plugin : plugins.values()) {
  617. descriptors.add(plugin.getDescriptor());
  618. }
  619. DependencyResolver.Result result = dependencyResolver.resolve(descriptors);
  620. if (result.hasCyclicDependency()) {
  621. throw new DependencyResolver.CyclicDependencyException();
  622. }
  623. List<String> notFoundDependencies = result.getNotFoundDependencies();
  624. if (!notFoundDependencies.isEmpty()) {
  625. throw new DependencyResolver.DependenciesNotFoundException(notFoundDependencies);
  626. }
  627. List<DependencyResolver.WrongDependencyVersion> wrongVersionDependencies = result.getWrongVersionDependencies();
  628. if (!wrongVersionDependencies.isEmpty()) {
  629. throw new DependencyResolver.DependenciesWrongVersionException(wrongVersionDependencies);
  630. }
  631. List<String> sortedPlugins = result.getSortedPlugins();
  632. // move plugins from "unresolved" to "resolved"
  633. for (String pluginId : sortedPlugins) {
  634. PluginWrapper pluginWrapper = plugins.get(pluginId);
  635. if (unresolvedPlugins.remove(pluginWrapper)) {
  636. PluginState pluginState = pluginWrapper.getPluginState();
  637. if (pluginState != PluginState.DISABLED) {
  638. pluginWrapper.setPluginState(PluginState.RESOLVED);
  639. }
  640. resolvedPlugins.add(pluginWrapper);
  641. log.info("Plugin '{}' resolved", getPluginLabel(pluginWrapper.getDescriptor()));
  642. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  643. }
  644. }
  645. }
  646. protected synchronized void firePluginStateEvent(PluginStateEvent event) {
  647. for (PluginStateListener listener : pluginStateListeners) {
  648. log.trace("Fire '{}' to '{}'", event, listener);
  649. listener.pluginStateChanged(event);
  650. }
  651. }
  652. protected PluginWrapper loadPluginFromPath(Path pluginPath) {
  653. // Test for plugin path duplication
  654. String pluginId = idForPath(pluginPath);
  655. if (pluginId != null) {
  656. throw new PluginAlreadyLoadedException(pluginId, pluginPath);
  657. }
  658. // Retrieve and validate the plugin descriptor
  659. PluginDescriptorFinder pluginDescriptorFinder = getPluginDescriptorFinder();
  660. log.debug("Use '{}' to find plugins descriptors", pluginDescriptorFinder);
  661. log.debug("Finding plugin descriptor for plugin '{}'", pluginPath);
  662. PluginDescriptor pluginDescriptor = pluginDescriptorFinder.find(pluginPath);
  663. validatePluginDescriptor(pluginDescriptor);
  664. // Check there are no loaded plugins with the retrieved id
  665. pluginId = pluginDescriptor.getPluginId();
  666. if (plugins.containsKey(pluginId)) {
  667. PluginWrapper loadedPlugin = getPlugin(pluginId);
  668. throw new PluginRuntimeException("There is an already loaded plugin ({}) "
  669. + "with the same id ({}) as the plugin at path '{}'. Simultaneous loading "
  670. + "of plugins with the same PluginId is not currently supported.\n"
  671. + "As a workaround you may include PluginVersion and PluginProvider "
  672. + "in PluginId.",
  673. loadedPlugin, pluginId, pluginPath);
  674. }
  675. log.debug("Found descriptor {}", pluginDescriptor);
  676. String pluginClassName = pluginDescriptor.getPluginClass();
  677. log.debug("Class '{}' for plugin '{}'", pluginClassName, pluginPath);
  678. // load plugin
  679. log.debug("Loading plugin '{}'", pluginPath);
  680. ClassLoader pluginClassLoader = getPluginLoader().loadPlugin(pluginPath, pluginDescriptor);
  681. log.debug("Loaded plugin '{}' with class loader '{}'", pluginPath, pluginClassLoader);
  682. // create the plugin wrapper
  683. log.debug("Creating wrapper for plugin '{}'", pluginPath);
  684. PluginWrapper pluginWrapper = new PluginWrapper(this, pluginDescriptor, pluginPath, pluginClassLoader);
  685. pluginWrapper.setPluginFactory(getPluginFactory());
  686. // test for disabled plugin
  687. if (isPluginDisabled(pluginDescriptor.getPluginId())) {
  688. log.info("Plugin '{}' is disabled", pluginPath);
  689. pluginWrapper.setPluginState(PluginState.DISABLED);
  690. }
  691. // validate the plugin
  692. if (!isPluginValid(pluginWrapper)) {
  693. log.warn("Plugin '{}' is invalid and it will be disabled", pluginPath);
  694. pluginWrapper.setPluginState(PluginState.DISABLED);
  695. }
  696. log.debug("Created wrapper '{}' for plugin '{}'", pluginWrapper, pluginPath);
  697. pluginId = pluginDescriptor.getPluginId();
  698. // add plugin to the list with plugins
  699. plugins.put(pluginId, pluginWrapper);
  700. getUnresolvedPlugins().add(pluginWrapper);
  701. // add plugin class loader to the list with class loaders
  702. getPluginClassLoaders().put(pluginId, pluginClassLoader);
  703. return pluginWrapper;
  704. }
  705. /**
  706. * Tests for already loaded plugins on given path.
  707. *
  708. * @param pluginPath the path to investigate
  709. * @return id of plugin or null if not loaded
  710. */
  711. protected String idForPath(Path pluginPath) {
  712. for (PluginWrapper plugin : plugins.values()) {
  713. if (plugin.getPluginPath().equals(pluginPath)) {
  714. return plugin.getPluginId();
  715. }
  716. }
  717. return null;
  718. }
  719. /**
  720. * Override this to change the validation criteria.
  721. *
  722. * @param descriptor the plugin descriptor to validate
  723. * @throws PluginRuntimeException if validation fails
  724. */
  725. protected void validatePluginDescriptor(PluginDescriptor descriptor) {
  726. if (StringUtils.isNullOrEmpty(descriptor.getPluginId())) {
  727. throw new PluginRuntimeException("Field 'id' cannot be empty");
  728. }
  729. if (descriptor.getVersion() == null) {
  730. throw new PluginRuntimeException("Field 'version' cannot be empty");
  731. }
  732. }
  733. /**
  734. * @return true if exact versions in requires is allowed
  735. */
  736. public boolean isExactVersionAllowed() {
  737. return exactVersionAllowed;
  738. }
  739. /**
  740. * Set to true to allow requires expression to be exactly x.y.z.
  741. * The default is false, meaning that using an exact version x.y.z will
  742. * implicitly mean the same as >=x.y.z
  743. *
  744. * @param exactVersionAllowed set to true or false
  745. */
  746. public void setExactVersionAllowed(boolean exactVersionAllowed) {
  747. this.exactVersionAllowed = exactVersionAllowed;
  748. }
  749. @Override
  750. public VersionManager getVersionManager() {
  751. return versionManager;
  752. }
  753. /**
  754. * The plugin label is used in logging and it's a string in format {@code pluginId@pluginVersion}.
  755. */
  756. protected String getPluginLabel(PluginDescriptor pluginDescriptor) {
  757. return pluginDescriptor.getPluginId() + "@" + pluginDescriptor.getVersion();
  758. }
  759. @SuppressWarnings("unchecked")
  760. protected <T> List<Class<? extends T>> getExtensionClasses(List<ExtensionWrapper<T>> extensionsWrapper) {
  761. List<Class<? extends T>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
  762. for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
  763. Class<T> c = (Class<T>) extensionWrapper.getDescriptor().extensionClass;
  764. extensionClasses.add(c);
  765. }
  766. return extensionClasses;
  767. }
  768. protected <T> List<T> getExtensions(List<ExtensionWrapper<T>> extensionsWrapper) {
  769. List<T> extensions = new ArrayList<>(extensionsWrapper.size());
  770. for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
  771. try {
  772. extensions.add(extensionWrapper.getExtension());
  773. } catch (PluginRuntimeException e) {
  774. log.error("Cannot retrieve extension", e);
  775. }
  776. }
  777. return extensions;
  778. }
  779. }