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 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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.Arrays;
  27. import java.util.Collections;
  28. import java.util.HashMap;
  29. import java.util.Iterator;
  30. import java.util.List;
  31. import java.util.Map;
  32. import java.util.Objects;
  33. import java.util.Set;
  34. import java.util.stream.Collectors;
  35. /**
  36. * This class implements the boilerplate plugin code that any {@link PluginManager}
  37. * implementation would have to support.
  38. * It helps cut the noise out of the subclass that handles plugin management.
  39. * <p>
  40. * This class is not thread-safe.
  41. *
  42. * @author Decebal Suiu
  43. */
  44. public abstract class AbstractPluginManager implements PluginManager {
  45. private static final Logger log = LoggerFactory.getLogger(AbstractPluginManager.class);
  46. public static final String PLUGINS_DIR_PROPERTY_NAME = "pf4j.pluginsDir";
  47. public static final String MODE_PROPERTY_NAME = "pf4j.mode";
  48. public static final String DEFAULT_PLUGINS_DIR = "plugins";
  49. public static final String DEVELOPMENT_PLUGINS_DIR = "../plugins";
  50. protected final List<Path> pluginsRoots = new ArrayList<>();
  51. protected ExtensionFinder extensionFinder;
  52. protected PluginDescriptorFinder pluginDescriptorFinder;
  53. /**
  54. * A map of plugins this manager is responsible for (the key is the 'pluginId').
  55. */
  56. protected Map<String, PluginWrapper> plugins;
  57. /**
  58. * A map of plugin class loaders (the key is the 'pluginId').
  59. */
  60. protected Map<String, ClassLoader> pluginClassLoaders;
  61. /**
  62. * A list with unresolved plugins (unresolved dependency).
  63. */
  64. protected List<PluginWrapper> unresolvedPlugins;
  65. /**
  66. * A list with all resolved plugins (resolved dependency).
  67. */
  68. protected List<PluginWrapper> resolvedPlugins;
  69. /**
  70. * A list with started plugins.
  71. */
  72. protected List<PluginWrapper> startedPlugins;
  73. /**
  74. * The registered {@link PluginStateListener}s.
  75. */
  76. protected List<PluginStateListener> pluginStateListeners;
  77. /**
  78. * Cache value for the runtime mode.
  79. * No need to re-read it because it won't change at runtime.
  80. */
  81. protected RuntimeMode runtimeMode;
  82. /**
  83. * The system version used for comparisons to the plugin requires attribute.
  84. */
  85. protected String systemVersion = "0.0.0";
  86. protected PluginRepository pluginRepository;
  87. protected PluginFactory pluginFactory;
  88. protected ExtensionFactory extensionFactory;
  89. protected PluginStatusProvider pluginStatusProvider;
  90. protected DependencyResolver dependencyResolver;
  91. protected PluginLoader pluginLoader;
  92. protected boolean exactVersionAllowed = false;
  93. protected VersionManager versionManager;
  94. protected ResolveRecoveryStrategy resolveRecoveryStrategy;
  95. /**
  96. * The plugins roots are supplied as comma-separated list by {@code System.getProperty("pf4j.pluginsDir", "plugins")}.
  97. */
  98. protected AbstractPluginManager() {
  99. initialize();
  100. }
  101. /**
  102. * Constructs {@code AbstractPluginManager} with the given plugins roots.
  103. *
  104. * @param pluginsRoots the roots to search for plugins
  105. */
  106. protected AbstractPluginManager(Path... pluginsRoots) {
  107. this(Arrays.asList(pluginsRoots));
  108. }
  109. /**
  110. * Constructs {@code AbstractPluginManager} with the given plugins roots.
  111. *
  112. * @param pluginsRoots the roots to search for plugins
  113. */
  114. protected AbstractPluginManager(List<Path> pluginsRoots) {
  115. this.pluginsRoots.addAll(pluginsRoots);
  116. initialize();
  117. }
  118. @Override
  119. public void setSystemVersion(String version) {
  120. systemVersion = version;
  121. }
  122. @Override
  123. public String getSystemVersion() {
  124. return systemVersion;
  125. }
  126. /**
  127. * Returns a copy of plugins.
  128. */
  129. @Override
  130. public List<PluginWrapper> getPlugins() {
  131. return new ArrayList<>(plugins.values());
  132. }
  133. /**
  134. * Returns a copy of plugins with that state.
  135. */
  136. @Override
  137. public List<PluginWrapper> getPlugins(PluginState pluginState) {
  138. return getPlugins().stream()
  139. .filter(plugin -> pluginState.equals(plugin.getPluginState()))
  140. .collect(Collectors.toList());
  141. }
  142. @Override
  143. public List<PluginWrapper> getResolvedPlugins() {
  144. return resolvedPlugins;
  145. }
  146. @Override
  147. public List<PluginWrapper> getUnresolvedPlugins() {
  148. return unresolvedPlugins;
  149. }
  150. @Override
  151. public List<PluginWrapper> getStartedPlugins() {
  152. return startedPlugins;
  153. }
  154. @Override
  155. public PluginWrapper getPlugin(String pluginId) {
  156. return plugins.get(pluginId);
  157. }
  158. /**
  159. * Load a plugin.
  160. *
  161. * @param pluginPath the plugin location
  162. * @return the pluginId of the loaded plugin as specified in its {@linkplain PluginDescriptor metadata}
  163. * @throws IllegalArgumentException if the plugin location does not exist
  164. * @throws PluginRuntimeException if something goes wrong
  165. */
  166. @Override
  167. public String loadPlugin(Path pluginPath) {
  168. if ((pluginPath == null) || Files.notExists(pluginPath)) {
  169. throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginPath));
  170. }
  171. log.debug("Loading plugin from '{}'", pluginPath);
  172. PluginWrapper pluginWrapper = loadPluginFromPath(pluginPath);
  173. // try to resolve the loaded plugin together with other possible plugins that depend on this plugin
  174. resolvePlugins();
  175. return pluginWrapper.getDescriptor().getPluginId();
  176. }
  177. /**
  178. * Load plugins.
  179. */
  180. @Override
  181. public void loadPlugins() {
  182. log.debug("Lookup plugins in '{}'", pluginsRoots);
  183. // check for plugins roots
  184. if (pluginsRoots.isEmpty()) {
  185. log.warn("No plugins roots configured");
  186. return;
  187. }
  188. pluginsRoots.forEach(path -> {
  189. if (Files.notExists(path) || !Files.isDirectory(path)) {
  190. log.warn("No '{}' root", path);
  191. }
  192. });
  193. // get all plugin paths from repository
  194. List<Path> pluginPaths = pluginRepository.getPluginPaths();
  195. // check for no plugins
  196. if (pluginPaths.isEmpty()) {
  197. log.info("No plugins");
  198. return;
  199. }
  200. log.debug("Found {} possible plugins: {}", pluginPaths.size(), pluginPaths);
  201. // load plugins from plugin paths
  202. for (Path pluginPath : pluginPaths) {
  203. try {
  204. loadPluginFromPath(pluginPath);
  205. } catch (PluginRuntimeException e) {
  206. log.error("Cannot load plugin '{}'", pluginPath, e);
  207. }
  208. }
  209. resolvePlugins();
  210. }
  211. /**
  212. * Unload all plugins
  213. */
  214. @Override
  215. public void unloadPlugins() {
  216. // wrap resolvedPlugins in new list because of concurrent modification
  217. for (PluginWrapper pluginWrapper : new ArrayList<>(resolvedPlugins)) {
  218. unloadPlugin(pluginWrapper.getPluginId());
  219. }
  220. }
  221. /**
  222. * Unload the specified plugin and it's dependents.
  223. *
  224. * @param pluginId the pluginId of the plugin to unload
  225. * @return true if the plugin was unloaded, otherwise false
  226. */
  227. @Override
  228. public boolean unloadPlugin(String pluginId) {
  229. return unloadPlugin(pluginId, true);
  230. }
  231. /**
  232. * Unload the specified plugin and it's dependents.
  233. *
  234. * @param pluginId the pluginId of the plugin to unload
  235. * @param unloadDependents if true, unload dependents
  236. * @return true if the plugin was unloaded, otherwise false
  237. */
  238. protected boolean unloadPlugin(String pluginId, boolean unloadDependents) {
  239. if (unloadDependents) {
  240. List<String> dependents = dependencyResolver.getDependents(pluginId);
  241. while (!dependents.isEmpty()) {
  242. String dependent = dependents.remove(0);
  243. unloadPlugin(dependent, false);
  244. dependents.addAll(0, dependencyResolver.getDependents(dependent));
  245. }
  246. }
  247. if (!plugins.containsKey(pluginId)) {
  248. // nothing to do
  249. return false;
  250. }
  251. PluginWrapper pluginWrapper = getPlugin(pluginId);
  252. PluginState pluginState;
  253. try {
  254. pluginState = stopPlugin(pluginId, false);
  255. if (PluginState.STARTED == pluginState) {
  256. return false;
  257. }
  258. log.info("Unload plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  259. } catch (Exception e) {
  260. log.error("Cannot stop plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()), e);
  261. pluginState = PluginState.FAILED;
  262. }
  263. // remove the plugin
  264. plugins.remove(pluginId);
  265. getResolvedPlugins().remove(pluginWrapper);
  266. getUnresolvedPlugins().remove(pluginWrapper);
  267. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  268. // remove the classloader
  269. Map<String, ClassLoader> pluginClassLoaders = getPluginClassLoaders();
  270. if (pluginClassLoaders.containsKey(pluginId)) {
  271. ClassLoader classLoader = pluginClassLoaders.remove(pluginId);
  272. if (classLoader instanceof Closeable) {
  273. try {
  274. ((Closeable) classLoader).close();
  275. } catch (IOException e) {
  276. throw new PluginRuntimeException(e, "Cannot close classloader");
  277. }
  278. }
  279. }
  280. return true;
  281. }
  282. @Override
  283. public boolean deletePlugin(String pluginId) {
  284. checkPluginId(pluginId);
  285. PluginWrapper pluginWrapper = getPlugin(pluginId);
  286. // stop the plugin if it's started
  287. PluginState pluginState = stopPlugin(pluginId);
  288. if (PluginState.STARTED == pluginState) {
  289. log.error("Failed to stop plugin '{}' on delete", pluginId);
  290. return false;
  291. }
  292. // get an instance of plugin before the plugin is unloaded
  293. // for reason see https://github.com/pf4j/pf4j/issues/309
  294. Plugin plugin = pluginWrapper.getPlugin();
  295. if (!unloadPlugin(pluginId)) {
  296. log.error("Failed to unload plugin '{}' on delete", pluginId);
  297. return false;
  298. }
  299. // notify the plugin as it's deleted
  300. plugin.delete();
  301. return pluginRepository.deletePluginPath(pluginWrapper.getPluginPath());
  302. }
  303. /**
  304. * Start all active plugins.
  305. */
  306. @Override
  307. public void startPlugins() {
  308. for (PluginWrapper pluginWrapper : resolvedPlugins) {
  309. PluginState pluginState = pluginWrapper.getPluginState();
  310. if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) {
  311. try {
  312. log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  313. pluginWrapper.getPlugin().start();
  314. pluginWrapper.setPluginState(PluginState.STARTED);
  315. pluginWrapper.setFailedException(null);
  316. startedPlugins.add(pluginWrapper);
  317. } catch (Exception | LinkageError e) {
  318. pluginWrapper.setPluginState(PluginState.FAILED);
  319. pluginWrapper.setFailedException(e);
  320. log.error("Unable to start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()), e);
  321. } finally {
  322. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  323. }
  324. }
  325. }
  326. }
  327. /**
  328. * Start the specified plugin and its dependencies.
  329. */
  330. @Override
  331. public PluginState startPlugin(String pluginId) {
  332. checkPluginId(pluginId);
  333. PluginWrapper pluginWrapper = getPlugin(pluginId);
  334. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  335. PluginState pluginState = pluginWrapper.getPluginState();
  336. if (PluginState.STARTED == pluginState) {
  337. log.debug("Already started plugin '{}'", getPluginLabel(pluginDescriptor));
  338. return PluginState.STARTED;
  339. }
  340. if (!resolvedPlugins.contains(pluginWrapper)) {
  341. log.warn("Cannot start an unresolved plugin '{}'", getPluginLabel(pluginDescriptor));
  342. return pluginState;
  343. }
  344. if (PluginState.DISABLED == pluginState) {
  345. // automatically enable plugin on manual plugin start
  346. if (!enablePlugin(pluginId)) {
  347. return pluginState;
  348. }
  349. }
  350. for (PluginDependency dependency : pluginDescriptor.getDependencies()) {
  351. // start dependency only if it marked as required (non-optional) or if it optional and loaded
  352. if (!dependency.isOptional() || plugins.containsKey(dependency.getPluginId())) {
  353. startPlugin(dependency.getPluginId());
  354. }
  355. }
  356. log.info("Start plugin '{}'", getPluginLabel(pluginDescriptor));
  357. pluginWrapper.getPlugin().start();
  358. pluginWrapper.setPluginState(PluginState.STARTED);
  359. startedPlugins.add(pluginWrapper);
  360. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  361. return pluginWrapper.getPluginState();
  362. }
  363. /**
  364. * Stop all active plugins.
  365. */
  366. @Override
  367. public void stopPlugins() {
  368. // stop started plugins in reverse order
  369. Collections.reverse(startedPlugins);
  370. Iterator<PluginWrapper> itr = startedPlugins.iterator();
  371. while (itr.hasNext()) {
  372. PluginWrapper pluginWrapper = itr.next();
  373. PluginState pluginState = pluginWrapper.getPluginState();
  374. if (PluginState.STARTED == pluginState) {
  375. try {
  376. log.info("Stop plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  377. pluginWrapper.getPlugin().stop();
  378. pluginWrapper.setPluginState(PluginState.STOPPED);
  379. itr.remove();
  380. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  381. } catch (PluginRuntimeException e) {
  382. log.error(e.getMessage(), e);
  383. }
  384. } else {
  385. // do nothing
  386. log.debug("Plugin '{}' is not started, nothing to stop", getPluginLabel(pluginWrapper.getDescriptor()));
  387. }
  388. }
  389. }
  390. /**
  391. * Stop the specified plugin and it's dependents.
  392. */
  393. @Override
  394. public PluginState stopPlugin(String pluginId) {
  395. return stopPlugin(pluginId, true);
  396. }
  397. /**
  398. * Stop the specified plugin and it's dependents.
  399. *
  400. * @param pluginId the pluginId of the plugin to stop
  401. * @param stopDependents if true, stop dependents
  402. * @return the plugin state after stopping
  403. */
  404. protected PluginState stopPlugin(String pluginId, boolean stopDependents) {
  405. checkPluginId(pluginId);
  406. // test for started plugin
  407. if (!checkPluginState(pluginId, PluginState.STARTED)) {
  408. // do nothing
  409. log.debug("Plugin '{}' is not started, nothing to stop", getPluginLabel(pluginId));
  410. return getPlugin(pluginId).getPluginState();
  411. }
  412. if (stopDependents) {
  413. List<String> dependents = dependencyResolver.getDependents(pluginId);
  414. while (!dependents.isEmpty()) {
  415. String dependent = dependents.remove(0);
  416. stopPlugin(dependent, false);
  417. dependents.addAll(0, dependencyResolver.getDependents(dependent));
  418. }
  419. }
  420. log.info("Stop plugin '{}'", getPluginLabel(pluginId));
  421. PluginWrapper pluginWrapper = getPlugin(pluginId);
  422. pluginWrapper.getPlugin().stop();
  423. pluginWrapper.setPluginState(PluginState.STOPPED);
  424. getStartedPlugins().remove(pluginWrapper);
  425. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, PluginState.STOPPED));
  426. return PluginState.STOPPED;
  427. }
  428. /**
  429. * Check if the plugin exists in the list of plugins.
  430. *
  431. * @param pluginId the pluginId to check
  432. * @throws PluginNotFoundException if the plugin does not exist
  433. */
  434. protected void checkPluginId(String pluginId) {
  435. if (!plugins.containsKey(pluginId)) {
  436. throw new PluginNotFoundException(pluginId);
  437. }
  438. }
  439. /**
  440. * Check if the plugin state is equals with the value passed for parameter {@code pluginState}.
  441. *
  442. * @param pluginId the pluginId to check
  443. * @return {@code true} if the plugin state is equals with the value passed for parameter {@code pluginState}, otherwise {@code false}
  444. */
  445. protected boolean checkPluginState(String pluginId, PluginState pluginState) {
  446. return getPlugin(pluginId).getPluginState() == pluginState;
  447. }
  448. @Override
  449. public boolean disablePlugin(String pluginId) {
  450. checkPluginId(pluginId);
  451. PluginWrapper pluginWrapper = getPlugin(pluginId);
  452. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  453. PluginState pluginState = pluginWrapper.getPluginState();
  454. if (PluginState.DISABLED == pluginState) {
  455. log.debug("Already disabled plugin '{}'", getPluginLabel(pluginDescriptor));
  456. return true;
  457. } else if (PluginState.STARTED == pluginState) {
  458. if (PluginState.STOPPED == stopPlugin(pluginId)) {
  459. log.error("Failed to stop plugin '{}' on disable", getPluginLabel(pluginDescriptor));
  460. return false;
  461. }
  462. }
  463. pluginWrapper.setPluginState(PluginState.DISABLED);
  464. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  465. pluginStatusProvider.disablePlugin(pluginId);
  466. log.info("Disabled plugin '{}'", getPluginLabel(pluginDescriptor));
  467. return true;
  468. }
  469. @Override
  470. public boolean enablePlugin(String pluginId) {
  471. checkPluginId(pluginId);
  472. PluginWrapper pluginWrapper = getPlugin(pluginId);
  473. if (!isPluginValid(pluginWrapper)) {
  474. log.warn("Plugin '{}' can not be enabled", getPluginLabel(pluginWrapper.getDescriptor()));
  475. return false;
  476. }
  477. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  478. PluginState pluginState = pluginWrapper.getPluginState();
  479. if (PluginState.DISABLED != pluginState) {
  480. log.debug("Plugin '{}' is not disabled", getPluginLabel(pluginDescriptor));
  481. return true;
  482. }
  483. pluginStatusProvider.enablePlugin(pluginId);
  484. pluginWrapper.setPluginState(PluginState.CREATED);
  485. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  486. log.info("Enabled plugin '{}'", getPluginLabel(pluginDescriptor));
  487. return true;
  488. }
  489. /**
  490. * Get the {@link ClassLoader} for plugin.
  491. */
  492. @Override
  493. public ClassLoader getPluginClassLoader(String pluginId) {
  494. return pluginClassLoaders.get(pluginId);
  495. }
  496. @SuppressWarnings("rawtypes")
  497. @Override
  498. public List<Class<?>> getExtensionClasses(String pluginId) {
  499. List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
  500. List<Class<?>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
  501. for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
  502. Class<?> c = extensionWrapper.getDescriptor().extensionClass;
  503. extensionClasses.add(c);
  504. }
  505. return extensionClasses;
  506. }
  507. @Override
  508. public <T> List<Class<? extends T>> getExtensionClasses(Class<T> type) {
  509. return getExtensionClasses(extensionFinder.find(type));
  510. }
  511. @Override
  512. public <T> List<Class<? extends T>> getExtensionClasses(Class<T> type, String pluginId) {
  513. return getExtensionClasses(extensionFinder.find(type, pluginId));
  514. }
  515. @Override
  516. public <T> List<T> getExtensions(Class<T> type) {
  517. return getExtensions(extensionFinder.find(type));
  518. }
  519. @Override
  520. public <T> List<T> getExtensions(Class<T> type, String pluginId) {
  521. return getExtensions(extensionFinder.find(type, pluginId));
  522. }
  523. @Override
  524. @SuppressWarnings("unchecked")
  525. public List getExtensions(String pluginId) {
  526. List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
  527. List extensions = new ArrayList<>(extensionsWrapper.size());
  528. for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
  529. try {
  530. extensions.add(extensionWrapper.getExtension());
  531. } catch (PluginRuntimeException e) {
  532. log.error("Cannot retrieve extension", e);
  533. }
  534. }
  535. return extensions;
  536. }
  537. @Override
  538. public Set<String> getExtensionClassNames(String pluginId) {
  539. return extensionFinder.findClassNames(pluginId);
  540. }
  541. @Override
  542. public ExtensionFactory getExtensionFactory() {
  543. return extensionFactory;
  544. }
  545. public PluginLoader getPluginLoader() {
  546. return pluginLoader;
  547. }
  548. @Override
  549. public Path getPluginsRoot() {
  550. return pluginsRoots.stream()
  551. .findFirst()
  552. .orElseThrow(() -> new IllegalStateException("pluginsRoots have not been initialized, yet."));
  553. }
  554. public List<Path> getPluginsRoots() {
  555. return Collections.unmodifiableList(pluginsRoots);
  556. }
  557. @Override
  558. public RuntimeMode getRuntimeMode() {
  559. if (runtimeMode == null) {
  560. // retrieves the runtime mode from system
  561. String modeAsString = System.getProperty(MODE_PROPERTY_NAME, RuntimeMode.DEPLOYMENT.toString());
  562. runtimeMode = RuntimeMode.byName(modeAsString);
  563. }
  564. return runtimeMode;
  565. }
  566. @Override
  567. public PluginWrapper whichPlugin(Class<?> clazz) {
  568. ClassLoader classLoader = clazz.getClassLoader();
  569. for (PluginWrapper plugin : resolvedPlugins) {
  570. if (plugin.getPluginClassLoader() == classLoader) {
  571. return plugin;
  572. }
  573. }
  574. return null;
  575. }
  576. @Override
  577. public synchronized void addPluginStateListener(PluginStateListener listener) {
  578. pluginStateListeners.add(listener);
  579. }
  580. @Override
  581. public synchronized void removePluginStateListener(PluginStateListener listener) {
  582. pluginStateListeners.remove(listener);
  583. }
  584. public String getVersion() {
  585. return Pf4jInfo.VERSION;
  586. }
  587. protected abstract PluginRepository createPluginRepository();
  588. protected abstract PluginFactory createPluginFactory();
  589. protected abstract ExtensionFactory createExtensionFactory();
  590. protected abstract PluginDescriptorFinder createPluginDescriptorFinder();
  591. protected abstract ExtensionFinder createExtensionFinder();
  592. protected abstract PluginStatusProvider createPluginStatusProvider();
  593. protected abstract PluginLoader createPluginLoader();
  594. protected abstract VersionManager createVersionManager();
  595. protected PluginDescriptorFinder getPluginDescriptorFinder() {
  596. return pluginDescriptorFinder;
  597. }
  598. protected PluginFactory getPluginFactory() {
  599. return pluginFactory;
  600. }
  601. protected Map<String, ClassLoader> getPluginClassLoaders() {
  602. return pluginClassLoaders;
  603. }
  604. protected void initialize() {
  605. plugins = new HashMap<>();
  606. pluginClassLoaders = new HashMap<>();
  607. unresolvedPlugins = new ArrayList<>();
  608. resolvedPlugins = new ArrayList<>();
  609. startedPlugins = new ArrayList<>();
  610. pluginStateListeners = new ArrayList<>();
  611. if (pluginsRoots.isEmpty()) {
  612. pluginsRoots.addAll(createPluginsRoot());
  613. }
  614. pluginRepository = createPluginRepository();
  615. pluginFactory = createPluginFactory();
  616. extensionFactory = createExtensionFactory();
  617. pluginDescriptorFinder = createPluginDescriptorFinder();
  618. extensionFinder = createExtensionFinder();
  619. pluginStatusProvider = createPluginStatusProvider();
  620. pluginLoader = createPluginLoader();
  621. versionManager = createVersionManager();
  622. dependencyResolver = new DependencyResolver(versionManager);
  623. resolveRecoveryStrategy = ResolveRecoveryStrategy.THROW_EXCEPTION;
  624. }
  625. /**
  626. * Add the possibility to override the plugins roots.
  627. * If a {@link #PLUGINS_DIR_PROPERTY_NAME} system property is defined than this method returns that roots.
  628. * If {@link #getRuntimeMode()} returns {@link RuntimeMode#DEVELOPMENT} than {@link #DEVELOPMENT_PLUGINS_DIR}
  629. * is returned else this method returns {@link #DEFAULT_PLUGINS_DIR}.
  630. *
  631. * @return the plugins root
  632. */
  633. protected List<Path> createPluginsRoot() {
  634. String pluginsDir = System.getProperty(PLUGINS_DIR_PROPERTY_NAME);
  635. if (pluginsDir != null && !pluginsDir.isEmpty()) {
  636. return Arrays.stream(pluginsDir.split(","))
  637. .map(String::trim)
  638. .map(Paths::get)
  639. .collect(Collectors.toList());
  640. }
  641. pluginsDir = isDevelopment() ? DEVELOPMENT_PLUGINS_DIR : DEFAULT_PLUGINS_DIR;
  642. return Collections.singletonList(Paths.get(pluginsDir));
  643. }
  644. /**
  645. * Check if this plugin is valid (satisfies "requires" param) for a given system version.
  646. *
  647. * @param pluginWrapper the plugin to check
  648. * @return true if plugin satisfies the "requires" or if requires was left blank
  649. */
  650. protected boolean isPluginValid(PluginWrapper pluginWrapper) {
  651. String requires = pluginWrapper.getDescriptor().getRequires().trim();
  652. if (!isExactVersionAllowed() && requires.matches("^\\d+\\.\\d+\\.\\d+$")) {
  653. // If exact versions are not allowed in requires, rewrite to >= expression
  654. requires = ">=" + requires;
  655. }
  656. if (systemVersion.equals("0.0.0") || versionManager.checkVersionConstraint(systemVersion, requires)) {
  657. return true;
  658. }
  659. log.warn("Plugin '{}' requires a minimum system version of {}, and you have {}",
  660. getPluginLabel(pluginWrapper.getDescriptor()),
  661. requires,
  662. getSystemVersion());
  663. return false;
  664. }
  665. /**
  666. * Check if the plugin is disabled.
  667. *
  668. * @param pluginId the pluginId to check
  669. * @return true if the plugin is disabled, otherwise false
  670. */
  671. protected boolean isPluginDisabled(String pluginId) {
  672. return pluginStatusProvider.isPluginDisabled(pluginId);
  673. }
  674. /**
  675. * It resolves the plugins by checking the dependencies.
  676. * It also checks for cyclic dependencies, missing dependencies and wrong versions of the dependencies.
  677. *
  678. * @throws PluginRuntimeException if something goes wrong
  679. */
  680. protected void resolvePlugins() {
  681. DependencyResolver.Result result = resolveDependencies();
  682. List<String> sortedPlugins = result.getSortedPlugins();
  683. // move plugins from "unresolved" to "resolved"
  684. for (String pluginId : sortedPlugins) {
  685. PluginWrapper pluginWrapper = plugins.get(pluginId);
  686. if (unresolvedPlugins.remove(pluginWrapper)) {
  687. PluginState pluginState = pluginWrapper.getPluginState();
  688. if (pluginState != PluginState.DISABLED) {
  689. pluginWrapper.setPluginState(PluginState.RESOLVED);
  690. }
  691. resolvedPlugins.add(pluginWrapper);
  692. log.info("Plugin '{}' resolved", getPluginLabel(pluginWrapper.getDescriptor()));
  693. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  694. }
  695. }
  696. }
  697. /**
  698. * Fire a plugin state event.
  699. * This method is called when a plugin is loaded, started, stopped, etc.
  700. *
  701. * @param event the plugin state event
  702. */
  703. protected synchronized void firePluginStateEvent(PluginStateEvent event) {
  704. for (PluginStateListener listener : pluginStateListeners) {
  705. log.trace("Fire '{}' to '{}'", event, listener);
  706. listener.pluginStateChanged(event);
  707. }
  708. }
  709. /**
  710. * Load the plugin from the specified path.
  711. *
  712. * @param pluginPath the path to the plugin
  713. * @return the loaded plugin
  714. * @throws PluginAlreadyLoadedException if the plugin is already loaded
  715. * @throws InvalidPluginDescriptorException if the plugin is invalid
  716. */
  717. protected PluginWrapper loadPluginFromPath(Path pluginPath) {
  718. // Test for plugin path duplication
  719. String pluginId = idForPath(pluginPath);
  720. if (pluginId != null) {
  721. throw new PluginAlreadyLoadedException(pluginId, pluginPath);
  722. }
  723. // Retrieve and validate the plugin descriptor
  724. PluginDescriptorFinder pluginDescriptorFinder = getPluginDescriptorFinder();
  725. log.debug("Use '{}' to find plugins descriptors", pluginDescriptorFinder);
  726. log.debug("Finding plugin descriptor for plugin '{}'", pluginPath);
  727. PluginDescriptor pluginDescriptor = pluginDescriptorFinder.find(pluginPath);
  728. validatePluginDescriptor(pluginDescriptor);
  729. // Check there are no loaded plugins with the retrieved id
  730. pluginId = pluginDescriptor.getPluginId();
  731. if (plugins.containsKey(pluginId)) {
  732. PluginWrapper loadedPlugin = getPlugin(pluginId);
  733. throw new PluginRuntimeException("There is an already loaded plugin ({}) "
  734. + "with the same id ({}) as the plugin at path '{}'. Simultaneous loading "
  735. + "of plugins with the same PluginId is not currently supported.\n"
  736. + "As a workaround you may include PluginVersion and PluginProvider "
  737. + "in PluginId.",
  738. loadedPlugin, pluginId, pluginPath);
  739. }
  740. log.debug("Found descriptor {}", pluginDescriptor);
  741. String pluginClassName = pluginDescriptor.getPluginClass();
  742. log.debug("Class '{}' for plugin '{}'", pluginClassName, pluginPath);
  743. // load plugin
  744. log.debug("Loading plugin '{}'", pluginPath);
  745. ClassLoader pluginClassLoader = getPluginLoader().loadPlugin(pluginPath, pluginDescriptor);
  746. log.debug("Loaded plugin '{}' with class loader '{}'", pluginPath, pluginClassLoader);
  747. PluginWrapper pluginWrapper = createPluginWrapper(pluginDescriptor, pluginPath, pluginClassLoader);
  748. // test for disabled plugin
  749. if (isPluginDisabled(pluginDescriptor.getPluginId())) {
  750. log.info("Plugin '{}' is disabled", pluginPath);
  751. pluginWrapper.setPluginState(PluginState.DISABLED);
  752. }
  753. // validate the plugin
  754. if (!isPluginValid(pluginWrapper)) {
  755. log.warn("Plugin '{}' is invalid and it will be disabled", pluginPath);
  756. pluginWrapper.setPluginState(PluginState.DISABLED);
  757. }
  758. log.debug("Created wrapper '{}' for plugin '{}'", pluginWrapper, pluginPath);
  759. pluginId = pluginDescriptor.getPluginId();
  760. // add plugin to the list with plugins
  761. plugins.put(pluginId, pluginWrapper);
  762. getUnresolvedPlugins().add(pluginWrapper);
  763. // add plugin class loader to the list with class loaders
  764. getPluginClassLoaders().put(pluginId, pluginClassLoader);
  765. return pluginWrapper;
  766. }
  767. /**
  768. * Creates the plugin wrapper.
  769. * <p>
  770. * Override this if you want to prevent plugins having full access to the plugin manager.
  771. *
  772. * @param pluginDescriptor the plugin descriptor
  773. * @param pluginPath the path to the plugin
  774. * @param pluginClassLoader the class loader for the plugin
  775. * @return the plugin wrapper
  776. */
  777. protected PluginWrapper createPluginWrapper(PluginDescriptor pluginDescriptor, Path pluginPath, ClassLoader pluginClassLoader) {
  778. // create the plugin wrapper
  779. log.debug("Creating wrapper for plugin '{}'", pluginPath);
  780. PluginWrapper pluginWrapper = new PluginWrapper(this, pluginDescriptor, pluginPath, pluginClassLoader);
  781. pluginWrapper.setPluginFactory(getPluginFactory());
  782. return pluginWrapper;
  783. }
  784. /**
  785. * Tests for already loaded plugins on given path.
  786. *
  787. * @param pluginPath the path to investigate
  788. * @return id of plugin or null if not loaded
  789. */
  790. protected String idForPath(Path pluginPath) {
  791. for (PluginWrapper plugin : plugins.values()) {
  792. if (plugin.getPluginPath().equals(pluginPath)) {
  793. return plugin.getPluginId();
  794. }
  795. }
  796. return null;
  797. }
  798. /**
  799. * Override this to change the validation criteria.
  800. *
  801. * @param descriptor the plugin descriptor to validate
  802. * @throws InvalidPluginDescriptorException if validation fails
  803. */
  804. protected void validatePluginDescriptor(PluginDescriptor descriptor) {
  805. if (StringUtils.isNullOrEmpty(descriptor.getPluginId())) {
  806. throw new InvalidPluginDescriptorException("Field 'id' cannot be empty");
  807. }
  808. if (descriptor.getVersion() == null) {
  809. throw new InvalidPluginDescriptorException("Field 'version' cannot be empty");
  810. }
  811. }
  812. /**
  813. * Check if the exact version in requires is allowed.
  814. *
  815. * @return true if exact versions in requires is allowed
  816. */
  817. public boolean isExactVersionAllowed() {
  818. return exactVersionAllowed;
  819. }
  820. /**
  821. * Set to true to allow requires expression to be exactly x.y.z.
  822. * The default is false, meaning that using an exact version x.y.z will
  823. * implicitly mean the same as &gt;=x.y.z
  824. *
  825. * @param exactVersionAllowed set to true or false
  826. */
  827. public void setExactVersionAllowed(boolean exactVersionAllowed) {
  828. this.exactVersionAllowed = exactVersionAllowed;
  829. }
  830. @Override
  831. public VersionManager getVersionManager() {
  832. return versionManager;
  833. }
  834. /**
  835. * The plugin label is used in logging, and it's a string in format {@code pluginId@pluginVersion}.
  836. *
  837. * @param pluginDescriptor the plugin descriptor
  838. * @return the plugin label
  839. */
  840. protected String getPluginLabel(PluginDescriptor pluginDescriptor) {
  841. return pluginDescriptor.getPluginId() + "@" + pluginDescriptor.getVersion();
  842. }
  843. /**
  844. * Shortcut for {@code getPluginLabel(getPlugin(pluginId).getDescriptor())}.
  845. *
  846. * @param pluginId the pluginId
  847. * @return the plugin label
  848. */
  849. protected String getPluginLabel(String pluginId) {
  850. return getPluginLabel(getPlugin(pluginId).getDescriptor());
  851. }
  852. @SuppressWarnings("unchecked")
  853. protected <T> List<Class<? extends T>> getExtensionClasses(List<ExtensionWrapper<T>> extensionsWrapper) {
  854. List<Class<? extends T>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
  855. for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
  856. Class<T> c = (Class<T>) extensionWrapper.getDescriptor().extensionClass;
  857. extensionClasses.add(c);
  858. }
  859. return extensionClasses;
  860. }
  861. protected <T> List<T> getExtensions(List<ExtensionWrapper<T>> extensionsWrapper) {
  862. List<T> extensions = new ArrayList<>(extensionsWrapper.size());
  863. for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
  864. try {
  865. extensions.add(extensionWrapper.getExtension());
  866. } catch (PluginRuntimeException e) {
  867. log.error("Cannot retrieve extension", e);
  868. }
  869. }
  870. return extensions;
  871. }
  872. protected DependencyResolver.Result resolveDependencies() {
  873. // retrieves the plugins descriptors
  874. List<PluginDescriptor> descriptors = plugins.values().stream()
  875. .map(PluginWrapper::getDescriptor)
  876. .collect(Collectors.toList());
  877. DependencyResolver.Result result = dependencyResolver.resolve(descriptors);
  878. if (result.isOK()) {
  879. return result;
  880. }
  881. if (result.hasCyclicDependency()) {
  882. // cannot recover from cyclic dependency
  883. throw new DependencyResolver.CyclicDependencyException();
  884. }
  885. List<String> notFoundDependencies = result.getNotFoundDependencies();
  886. if (result.hasNotFoundDependencies() && resolveRecoveryStrategy.equals(ResolveRecoveryStrategy.THROW_EXCEPTION)) {
  887. throw new DependencyResolver.DependenciesNotFoundException(notFoundDependencies);
  888. }
  889. List<DependencyResolver.WrongDependencyVersion> wrongVersionDependencies = result.getWrongVersionDependencies();
  890. if (result.hasWrongVersionDependencies() && resolveRecoveryStrategy.equals(ResolveRecoveryStrategy.THROW_EXCEPTION)) {
  891. throw new DependencyResolver.DependenciesWrongVersionException(wrongVersionDependencies);
  892. }
  893. List<PluginDescriptor> resolvedDescriptors = new ArrayList<>(descriptors);
  894. for (String notFoundDependency : notFoundDependencies) {
  895. List<String> dependents = dependencyResolver.getDependents(notFoundDependency);
  896. dependents.forEach(dependent -> resolvedDescriptors.removeIf(descriptor -> descriptor.getPluginId().equals(dependent)));
  897. }
  898. for (DependencyResolver.WrongDependencyVersion wrongVersionDependency : wrongVersionDependencies) {
  899. resolvedDescriptors.removeIf(descriptor -> descriptor.getPluginId().equals(wrongVersionDependency.getDependencyId()));
  900. }
  901. List<PluginDescriptor> unresolvedDescriptors = new ArrayList<>(descriptors);
  902. unresolvedDescriptors.removeAll(resolvedDescriptors);
  903. for (PluginDescriptor unresolvedDescriptor : unresolvedDescriptors) {
  904. unloadPlugin(unresolvedDescriptor.getPluginId(), false);
  905. }
  906. return resolveDependencies();
  907. }
  908. /**
  909. * Retrieve the strategy for handling the recovery of a plugin resolve (load) failure.
  910. * Default is {@link ResolveRecoveryStrategy#THROW_EXCEPTION}.
  911. *
  912. * @return the strategy
  913. */
  914. protected final ResolveRecoveryStrategy getResolveRecoveryStrategy() {
  915. return resolveRecoveryStrategy;
  916. }
  917. /**
  918. * Set the strategy for handling the recovery of a plugin resolve (load) failure.
  919. *
  920. * @param resolveRecoveryStrategy the strategy
  921. */
  922. protected void setResolveRecoveryStrategy(ResolveRecoveryStrategy resolveRecoveryStrategy) {
  923. Objects.requireNonNull(resolveRecoveryStrategy, "resolveRecoveryStrategy cannot be null");
  924. this.resolveRecoveryStrategy = resolveRecoveryStrategy;
  925. }
  926. /**
  927. * Strategy for handling the recovery of a plugin that could not be resolved
  928. * (loaded) due to a dependency problem.
  929. */
  930. public enum ResolveRecoveryStrategy {
  931. /**
  932. * Throw an exception when a resolve (load) failure occurs.
  933. */
  934. THROW_EXCEPTION,
  935. /**
  936. * Ignore the plugin with the resolve (load) failure and continue.
  937. * The plugin with problems will be removed/unloaded from the plugins list.
  938. */
  939. IGNORE_PLUGIN_AND_CONTINUE
  940. }
  941. }