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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. pluginWrapper.setPluginState(PluginState.UNLOADED);
  265. plugins.remove(pluginId);
  266. getResolvedPlugins().remove(pluginWrapper);
  267. getUnresolvedPlugins().remove(pluginWrapper);
  268. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  269. // remove the classloader
  270. Map<String, ClassLoader> pluginClassLoaders = getPluginClassLoaders();
  271. if (pluginClassLoaders.containsKey(pluginId)) {
  272. ClassLoader classLoader = pluginClassLoaders.remove(pluginId);
  273. if (classLoader instanceof Closeable) {
  274. try {
  275. ((Closeable) classLoader).close();
  276. } catch (IOException e) {
  277. throw new PluginRuntimeException(e, "Cannot close classloader");
  278. }
  279. }
  280. }
  281. return true;
  282. }
  283. @Override
  284. public boolean deletePlugin(String pluginId) {
  285. checkPluginId(pluginId);
  286. PluginWrapper pluginWrapper = getPlugin(pluginId);
  287. // stop the plugin if it's started
  288. PluginState pluginState = stopPlugin(pluginId);
  289. if (PluginState.STARTED == pluginState) {
  290. log.error("Failed to stop plugin '{}' on delete", pluginId);
  291. return false;
  292. }
  293. // get an instance of plugin before the plugin is unloaded
  294. // for reason see https://github.com/pf4j/pf4j/issues/309
  295. Plugin plugin = pluginWrapper.getPlugin();
  296. if (!unloadPlugin(pluginId)) {
  297. log.error("Failed to unload plugin '{}' on delete", pluginId);
  298. return false;
  299. }
  300. // notify the plugin as it's deleted
  301. plugin.delete();
  302. return pluginRepository.deletePluginPath(pluginWrapper.getPluginPath());
  303. }
  304. /**
  305. * Start all active plugins.
  306. */
  307. @Override
  308. public void startPlugins() {
  309. for (PluginWrapper pluginWrapper : resolvedPlugins) {
  310. PluginState pluginState = pluginWrapper.getPluginState();
  311. if ((PluginState.DISABLED != pluginState) && (PluginState.STARTED != pluginState)) {
  312. try {
  313. log.info("Start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  314. pluginWrapper.getPlugin().start();
  315. pluginWrapper.setPluginState(PluginState.STARTED);
  316. pluginWrapper.setFailedException(null);
  317. startedPlugins.add(pluginWrapper);
  318. } catch (Exception | LinkageError e) {
  319. pluginWrapper.setPluginState(PluginState.FAILED);
  320. pluginWrapper.setFailedException(e);
  321. log.error("Unable to start plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()), e);
  322. } finally {
  323. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  324. }
  325. }
  326. }
  327. }
  328. /**
  329. * Start the specified plugin and its dependencies.
  330. */
  331. @Override
  332. public PluginState startPlugin(String pluginId) {
  333. checkPluginId(pluginId);
  334. PluginWrapper pluginWrapper = getPlugin(pluginId);
  335. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  336. PluginState pluginState = pluginWrapper.getPluginState();
  337. if (PluginState.STARTED == pluginState) {
  338. log.debug("Already started plugin '{}'", getPluginLabel(pluginDescriptor));
  339. return PluginState.STARTED;
  340. }
  341. if (!resolvedPlugins.contains(pluginWrapper)) {
  342. log.warn("Cannot start an unresolved plugin '{}'", getPluginLabel(pluginDescriptor));
  343. return pluginState;
  344. }
  345. if (PluginState.DISABLED == pluginState) {
  346. // automatically enable plugin on manual plugin start
  347. if (!enablePlugin(pluginId)) {
  348. return pluginState;
  349. }
  350. }
  351. for (PluginDependency dependency : pluginDescriptor.getDependencies()) {
  352. // start dependency only if it marked as required (non-optional) or if it optional and loaded
  353. if (!dependency.isOptional() || plugins.containsKey(dependency.getPluginId())) {
  354. startPlugin(dependency.getPluginId());
  355. }
  356. }
  357. log.info("Start plugin '{}'", getPluginLabel(pluginDescriptor));
  358. pluginWrapper.getPlugin().start();
  359. pluginWrapper.setPluginState(PluginState.STARTED);
  360. startedPlugins.add(pluginWrapper);
  361. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  362. return pluginWrapper.getPluginState();
  363. }
  364. /**
  365. * Stop all active plugins.
  366. */
  367. @Override
  368. public void stopPlugins() {
  369. // stop started plugins in reverse order
  370. Collections.reverse(startedPlugins);
  371. Iterator<PluginWrapper> itr = startedPlugins.iterator();
  372. while (itr.hasNext()) {
  373. PluginWrapper pluginWrapper = itr.next();
  374. PluginState pluginState = pluginWrapper.getPluginState();
  375. if (PluginState.STARTED == pluginState) {
  376. try {
  377. log.info("Stop plugin '{}'", getPluginLabel(pluginWrapper.getDescriptor()));
  378. pluginWrapper.getPlugin().stop();
  379. pluginWrapper.setPluginState(PluginState.STOPPED);
  380. itr.remove();
  381. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  382. } catch (PluginRuntimeException e) {
  383. log.error(e.getMessage(), e);
  384. }
  385. } else {
  386. // do nothing
  387. log.debug("Plugin '{}' is not started, nothing to stop", getPluginLabel(pluginWrapper.getDescriptor()));
  388. }
  389. }
  390. }
  391. /**
  392. * Stop the specified plugin and it's dependents.
  393. */
  394. @Override
  395. public PluginState stopPlugin(String pluginId) {
  396. return stopPlugin(pluginId, true);
  397. }
  398. /**
  399. * Stop the specified plugin and it's dependents.
  400. *
  401. * @param pluginId the pluginId of the plugin to stop
  402. * @param stopDependents if true, stop dependents
  403. * @return the plugin state after stopping
  404. */
  405. protected PluginState stopPlugin(String pluginId, boolean stopDependents) {
  406. checkPluginId(pluginId);
  407. // test for started plugin
  408. if (!checkPluginState(pluginId, PluginState.STARTED)) {
  409. // do nothing
  410. log.debug("Plugin '{}' is not started, nothing to stop", getPluginLabel(pluginId));
  411. return getPlugin(pluginId).getPluginState();
  412. }
  413. if (stopDependents) {
  414. List<String> dependents = dependencyResolver.getDependents(pluginId);
  415. while (!dependents.isEmpty()) {
  416. String dependent = dependents.remove(0);
  417. stopPlugin(dependent, false);
  418. dependents.addAll(0, dependencyResolver.getDependents(dependent));
  419. }
  420. }
  421. log.info("Stop plugin '{}'", getPluginLabel(pluginId));
  422. PluginWrapper pluginWrapper = getPlugin(pluginId);
  423. pluginWrapper.getPlugin().stop();
  424. pluginWrapper.setPluginState(PluginState.STOPPED);
  425. getStartedPlugins().remove(pluginWrapper);
  426. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, PluginState.STOPPED));
  427. return PluginState.STOPPED;
  428. }
  429. /**
  430. * Check if the plugin exists in the list of plugins.
  431. *
  432. * @param pluginId the pluginId to check
  433. * @throws PluginNotFoundException if the plugin does not exist
  434. */
  435. protected void checkPluginId(String pluginId) {
  436. if (!plugins.containsKey(pluginId)) {
  437. throw new PluginNotFoundException(pluginId);
  438. }
  439. }
  440. /**
  441. * Check if the plugin state is equals with the value passed for parameter {@code pluginState}.
  442. *
  443. * @param pluginId the pluginId to check
  444. * @return {@code true} if the plugin state is equals with the value passed for parameter {@code pluginState}, otherwise {@code false}
  445. */
  446. protected boolean checkPluginState(String pluginId, PluginState pluginState) {
  447. return getPlugin(pluginId).getPluginState() == pluginState;
  448. }
  449. @Override
  450. public boolean disablePlugin(String pluginId) {
  451. checkPluginId(pluginId);
  452. PluginWrapper pluginWrapper = getPlugin(pluginId);
  453. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  454. PluginState pluginState = pluginWrapper.getPluginState();
  455. if (PluginState.DISABLED == pluginState) {
  456. log.debug("Already disabled plugin '{}'", getPluginLabel(pluginDescriptor));
  457. return true;
  458. } else if (PluginState.STARTED == pluginState) {
  459. if (PluginState.STOPPED == stopPlugin(pluginId)) {
  460. log.error("Failed to stop plugin '{}' on disable", getPluginLabel(pluginDescriptor));
  461. return false;
  462. }
  463. }
  464. pluginWrapper.setPluginState(PluginState.DISABLED);
  465. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  466. pluginStatusProvider.disablePlugin(pluginId);
  467. log.info("Disabled plugin '{}'", getPluginLabel(pluginDescriptor));
  468. return true;
  469. }
  470. @Override
  471. public boolean enablePlugin(String pluginId) {
  472. checkPluginId(pluginId);
  473. PluginWrapper pluginWrapper = getPlugin(pluginId);
  474. if (!isPluginValid(pluginWrapper)) {
  475. log.warn("Plugin '{}' can not be enabled", getPluginLabel(pluginWrapper.getDescriptor()));
  476. return false;
  477. }
  478. PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor();
  479. PluginState pluginState = pluginWrapper.getPluginState();
  480. if (PluginState.DISABLED != pluginState) {
  481. log.debug("Plugin '{}' is not disabled", getPluginLabel(pluginDescriptor));
  482. return true;
  483. }
  484. pluginStatusProvider.enablePlugin(pluginId);
  485. pluginWrapper.setPluginState(PluginState.CREATED);
  486. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  487. log.info("Enabled plugin '{}'", getPluginLabel(pluginDescriptor));
  488. return true;
  489. }
  490. /**
  491. * Get the {@link ClassLoader} for plugin.
  492. */
  493. @Override
  494. public ClassLoader getPluginClassLoader(String pluginId) {
  495. return pluginClassLoaders.get(pluginId);
  496. }
  497. @SuppressWarnings("rawtypes")
  498. @Override
  499. public List<Class<?>> getExtensionClasses(String pluginId) {
  500. List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
  501. List<Class<?>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
  502. for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
  503. Class<?> c = extensionWrapper.getDescriptor().extensionClass;
  504. extensionClasses.add(c);
  505. }
  506. return extensionClasses;
  507. }
  508. @Override
  509. public <T> List<Class<? extends T>> getExtensionClasses(Class<T> type) {
  510. return getExtensionClasses(extensionFinder.find(type));
  511. }
  512. @Override
  513. public <T> List<Class<? extends T>> getExtensionClasses(Class<T> type, String pluginId) {
  514. return getExtensionClasses(extensionFinder.find(type, pluginId));
  515. }
  516. @Override
  517. public <T> List<T> getExtensions(Class<T> type) {
  518. return getExtensions(extensionFinder.find(type));
  519. }
  520. @Override
  521. public <T> List<T> getExtensions(Class<T> type, String pluginId) {
  522. return getExtensions(extensionFinder.find(type, pluginId));
  523. }
  524. @Override
  525. @SuppressWarnings("unchecked")
  526. public List getExtensions(String pluginId) {
  527. List<ExtensionWrapper> extensionsWrapper = extensionFinder.find(pluginId);
  528. List extensions = new ArrayList<>(extensionsWrapper.size());
  529. for (ExtensionWrapper extensionWrapper : extensionsWrapper) {
  530. try {
  531. extensions.add(extensionWrapper.getExtension());
  532. } catch (PluginRuntimeException e) {
  533. log.error("Cannot retrieve extension", e);
  534. }
  535. }
  536. return extensions;
  537. }
  538. @Override
  539. public Set<String> getExtensionClassNames(String pluginId) {
  540. return extensionFinder.findClassNames(pluginId);
  541. }
  542. @Override
  543. public ExtensionFactory getExtensionFactory() {
  544. return extensionFactory;
  545. }
  546. public PluginLoader getPluginLoader() {
  547. return pluginLoader;
  548. }
  549. @Override
  550. public Path getPluginsRoot() {
  551. return pluginsRoots.stream()
  552. .findFirst()
  553. .orElseThrow(() -> new IllegalStateException("pluginsRoots have not been initialized, yet."));
  554. }
  555. public List<Path> getPluginsRoots() {
  556. return Collections.unmodifiableList(pluginsRoots);
  557. }
  558. @Override
  559. public RuntimeMode getRuntimeMode() {
  560. if (runtimeMode == null) {
  561. // retrieves the runtime mode from system
  562. String modeAsString = System.getProperty(MODE_PROPERTY_NAME, RuntimeMode.DEPLOYMENT.toString());
  563. runtimeMode = RuntimeMode.byName(modeAsString);
  564. }
  565. return runtimeMode;
  566. }
  567. @Override
  568. public PluginWrapper whichPlugin(Class<?> clazz) {
  569. ClassLoader classLoader = clazz.getClassLoader();
  570. for (PluginWrapper plugin : resolvedPlugins) {
  571. if (plugin.getPluginClassLoader() == classLoader) {
  572. return plugin;
  573. }
  574. }
  575. return null;
  576. }
  577. @Override
  578. public synchronized void addPluginStateListener(PluginStateListener listener) {
  579. pluginStateListeners.add(listener);
  580. }
  581. @Override
  582. public synchronized void removePluginStateListener(PluginStateListener listener) {
  583. pluginStateListeners.remove(listener);
  584. }
  585. public String getVersion() {
  586. return Pf4jInfo.VERSION;
  587. }
  588. protected abstract PluginRepository createPluginRepository();
  589. protected abstract PluginFactory createPluginFactory();
  590. protected abstract ExtensionFactory createExtensionFactory();
  591. protected abstract PluginDescriptorFinder createPluginDescriptorFinder();
  592. protected abstract ExtensionFinder createExtensionFinder();
  593. protected abstract PluginStatusProvider createPluginStatusProvider();
  594. protected abstract PluginLoader createPluginLoader();
  595. protected abstract VersionManager createVersionManager();
  596. protected PluginDescriptorFinder getPluginDescriptorFinder() {
  597. return pluginDescriptorFinder;
  598. }
  599. protected PluginFactory getPluginFactory() {
  600. return pluginFactory;
  601. }
  602. protected Map<String, ClassLoader> getPluginClassLoaders() {
  603. return pluginClassLoaders;
  604. }
  605. protected void initialize() {
  606. plugins = new HashMap<>();
  607. pluginClassLoaders = new HashMap<>();
  608. unresolvedPlugins = new ArrayList<>();
  609. resolvedPlugins = new ArrayList<>();
  610. startedPlugins = new ArrayList<>();
  611. pluginStateListeners = new ArrayList<>();
  612. if (pluginsRoots.isEmpty()) {
  613. pluginsRoots.addAll(createPluginsRoot());
  614. }
  615. pluginRepository = createPluginRepository();
  616. pluginFactory = createPluginFactory();
  617. extensionFactory = createExtensionFactory();
  618. pluginDescriptorFinder = createPluginDescriptorFinder();
  619. extensionFinder = createExtensionFinder();
  620. pluginStatusProvider = createPluginStatusProvider();
  621. pluginLoader = createPluginLoader();
  622. versionManager = createVersionManager();
  623. dependencyResolver = new DependencyResolver(versionManager);
  624. resolveRecoveryStrategy = ResolveRecoveryStrategy.THROW_EXCEPTION;
  625. }
  626. /**
  627. * Add the possibility to override the plugins roots.
  628. * If a {@link #PLUGINS_DIR_PROPERTY_NAME} system property is defined than this method returns that roots.
  629. * If {@link #getRuntimeMode()} returns {@link RuntimeMode#DEVELOPMENT} than {@link #DEVELOPMENT_PLUGINS_DIR}
  630. * is returned else this method returns {@link #DEFAULT_PLUGINS_DIR}.
  631. *
  632. * @return the plugins root
  633. */
  634. protected List<Path> createPluginsRoot() {
  635. String pluginsDir = System.getProperty(PLUGINS_DIR_PROPERTY_NAME);
  636. if (pluginsDir != null && !pluginsDir.isEmpty()) {
  637. return Arrays.stream(pluginsDir.split(","))
  638. .map(String::trim)
  639. .map(Paths::get)
  640. .collect(Collectors.toList());
  641. }
  642. pluginsDir = isDevelopment() ? DEVELOPMENT_PLUGINS_DIR : DEFAULT_PLUGINS_DIR;
  643. return Collections.singletonList(Paths.get(pluginsDir));
  644. }
  645. /**
  646. * Check if this plugin is valid (satisfies "requires" param) for a given system version.
  647. *
  648. * @param pluginWrapper the plugin to check
  649. * @return true if plugin satisfies the "requires" or if requires was left blank
  650. */
  651. protected boolean isPluginValid(PluginWrapper pluginWrapper) {
  652. String requires = pluginWrapper.getDescriptor().getRequires().trim();
  653. if (!isExactVersionAllowed() && requires.matches("^\\d+\\.\\d+\\.\\d+$")) {
  654. // If exact versions are not allowed in requires, rewrite to >= expression
  655. requires = ">=" + requires;
  656. }
  657. if (systemVersion.equals("0.0.0") || versionManager.checkVersionConstraint(systemVersion, requires)) {
  658. return true;
  659. }
  660. log.warn("Plugin '{}' requires a minimum system version of {}, and you have {}",
  661. getPluginLabel(pluginWrapper.getDescriptor()),
  662. requires,
  663. getSystemVersion());
  664. return false;
  665. }
  666. /**
  667. * Check if the plugin is disabled.
  668. *
  669. * @param pluginId the pluginId to check
  670. * @return true if the plugin is disabled, otherwise false
  671. */
  672. protected boolean isPluginDisabled(String pluginId) {
  673. return pluginStatusProvider.isPluginDisabled(pluginId);
  674. }
  675. /**
  676. * It resolves the plugins by checking the dependencies.
  677. * It also checks for cyclic dependencies, missing dependencies and wrong versions of the dependencies.
  678. *
  679. * @throws PluginRuntimeException if something goes wrong
  680. */
  681. protected void resolvePlugins() {
  682. DependencyResolver.Result result = resolveDependencies();
  683. List<String> sortedPlugins = result.getSortedPlugins();
  684. // move plugins from "unresolved" to "resolved"
  685. for (String pluginId : sortedPlugins) {
  686. PluginWrapper pluginWrapper = plugins.get(pluginId);
  687. if (unresolvedPlugins.remove(pluginWrapper)) {
  688. PluginState pluginState = pluginWrapper.getPluginState();
  689. if (pluginState != PluginState.DISABLED) {
  690. pluginWrapper.setPluginState(PluginState.RESOLVED);
  691. }
  692. resolvedPlugins.add(pluginWrapper);
  693. log.info("Plugin '{}' resolved", getPluginLabel(pluginWrapper.getDescriptor()));
  694. firePluginStateEvent(new PluginStateEvent(this, pluginWrapper, pluginState));
  695. }
  696. }
  697. }
  698. /**
  699. * Fire a plugin state event.
  700. * This method is called when a plugin is loaded, started, stopped, etc.
  701. *
  702. * @param event the plugin state event
  703. */
  704. protected synchronized void firePluginStateEvent(PluginStateEvent event) {
  705. if (event.getPluginState() == event.getOldState()) {
  706. // ignore events without state change
  707. return;
  708. }
  709. for (PluginStateListener listener : pluginStateListeners) {
  710. log.trace("Fire '{}' to '{}'", event, listener);
  711. listener.pluginStateChanged(event);
  712. }
  713. }
  714. /**
  715. * Load the plugin from the specified path.
  716. *
  717. * @param pluginPath the path to the plugin
  718. * @return the loaded plugin
  719. * @throws PluginAlreadyLoadedException if the plugin is already loaded
  720. * @throws InvalidPluginDescriptorException if the plugin is invalid
  721. */
  722. protected PluginWrapper loadPluginFromPath(Path pluginPath) {
  723. // Test for plugin path duplication
  724. String pluginId = idForPath(pluginPath);
  725. if (pluginId != null) {
  726. throw new PluginAlreadyLoadedException(pluginId, pluginPath);
  727. }
  728. // Retrieve and validate the plugin descriptor
  729. PluginDescriptorFinder pluginDescriptorFinder = getPluginDescriptorFinder();
  730. log.debug("Use '{}' to find plugins descriptors", pluginDescriptorFinder);
  731. log.debug("Finding plugin descriptor for plugin '{}'", pluginPath);
  732. PluginDescriptor pluginDescriptor = pluginDescriptorFinder.find(pluginPath);
  733. validatePluginDescriptor(pluginDescriptor);
  734. // Check there are no loaded plugins with the retrieved id
  735. pluginId = pluginDescriptor.getPluginId();
  736. if (plugins.containsKey(pluginId)) {
  737. PluginWrapper loadedPlugin = getPlugin(pluginId);
  738. throw new PluginRuntimeException("There is an already loaded plugin ({}) "
  739. + "with the same id ({}) as the plugin at path '{}'. Simultaneous loading "
  740. + "of plugins with the same PluginId is not currently supported.\n"
  741. + "As a workaround you may include PluginVersion and PluginProvider "
  742. + "in PluginId.",
  743. loadedPlugin, pluginId, pluginPath);
  744. }
  745. log.debug("Found descriptor {}", pluginDescriptor);
  746. String pluginClassName = pluginDescriptor.getPluginClass();
  747. log.debug("Class '{}' for plugin '{}'", pluginClassName, pluginPath);
  748. // load plugin
  749. log.debug("Loading plugin '{}'", pluginPath);
  750. ClassLoader pluginClassLoader = getPluginLoader().loadPlugin(pluginPath, pluginDescriptor);
  751. log.debug("Loaded plugin '{}' with class loader '{}'", pluginPath, pluginClassLoader);
  752. PluginWrapper pluginWrapper = createPluginWrapper(pluginDescriptor, pluginPath, pluginClassLoader);
  753. // test for disabled plugin
  754. if (isPluginDisabled(pluginDescriptor.getPluginId())) {
  755. log.info("Plugin '{}' is disabled", pluginPath);
  756. pluginWrapper.setPluginState(PluginState.DISABLED);
  757. }
  758. // validate the plugin
  759. if (!isPluginValid(pluginWrapper)) {
  760. log.warn("Plugin '{}' is invalid and it will be disabled", pluginPath);
  761. pluginWrapper.setPluginState(PluginState.DISABLED);
  762. }
  763. log.debug("Created wrapper '{}' for plugin '{}'", pluginWrapper, pluginPath);
  764. pluginId = pluginDescriptor.getPluginId();
  765. // add plugin to the list with plugins
  766. plugins.put(pluginId, pluginWrapper);
  767. getUnresolvedPlugins().add(pluginWrapper);
  768. // add plugin class loader to the list with class loaders
  769. getPluginClassLoaders().put(pluginId, pluginClassLoader);
  770. return pluginWrapper;
  771. }
  772. /**
  773. * Creates the plugin wrapper.
  774. * <p>
  775. * Override this if you want to prevent plugins having full access to the plugin manager.
  776. *
  777. * @param pluginDescriptor the plugin descriptor
  778. * @param pluginPath the path to the plugin
  779. * @param pluginClassLoader the class loader for the plugin
  780. * @return the plugin wrapper
  781. */
  782. protected PluginWrapper createPluginWrapper(PluginDescriptor pluginDescriptor, Path pluginPath, ClassLoader pluginClassLoader) {
  783. // create the plugin wrapper
  784. log.debug("Creating wrapper for plugin '{}'", pluginPath);
  785. PluginWrapper pluginWrapper = new PluginWrapper(this, pluginDescriptor, pluginPath, pluginClassLoader);
  786. pluginWrapper.setPluginFactory(getPluginFactory());
  787. return pluginWrapper;
  788. }
  789. /**
  790. * Tests for already loaded plugins on given path.
  791. *
  792. * @param pluginPath the path to investigate
  793. * @return id of plugin or null if not loaded
  794. */
  795. protected String idForPath(Path pluginPath) {
  796. for (PluginWrapper plugin : plugins.values()) {
  797. if (plugin.getPluginPath().equals(pluginPath)) {
  798. return plugin.getPluginId();
  799. }
  800. }
  801. return null;
  802. }
  803. /**
  804. * Override this to change the validation criteria.
  805. *
  806. * @param descriptor the plugin descriptor to validate
  807. * @throws InvalidPluginDescriptorException if validation fails
  808. */
  809. protected void validatePluginDescriptor(PluginDescriptor descriptor) {
  810. if (StringUtils.isNullOrEmpty(descriptor.getPluginId())) {
  811. throw new InvalidPluginDescriptorException("Field 'id' cannot be empty");
  812. }
  813. if (descriptor.getVersion() == null) {
  814. throw new InvalidPluginDescriptorException("Field 'version' cannot be empty");
  815. }
  816. }
  817. /**
  818. * Check if the exact version in requires is allowed.
  819. *
  820. * @return true if exact versions in requires is allowed
  821. */
  822. public boolean isExactVersionAllowed() {
  823. return exactVersionAllowed;
  824. }
  825. /**
  826. * Set to true to allow requires expression to be exactly x.y.z.
  827. * The default is false, meaning that using an exact version x.y.z will
  828. * implicitly mean the same as &gt;=x.y.z
  829. *
  830. * @param exactVersionAllowed set to true or false
  831. */
  832. public void setExactVersionAllowed(boolean exactVersionAllowed) {
  833. this.exactVersionAllowed = exactVersionAllowed;
  834. }
  835. @Override
  836. public VersionManager getVersionManager() {
  837. return versionManager;
  838. }
  839. /**
  840. * The plugin label is used in logging, and it's a string in format {@code pluginId@pluginVersion}.
  841. *
  842. * @param pluginDescriptor the plugin descriptor
  843. * @return the plugin label
  844. */
  845. protected String getPluginLabel(PluginDescriptor pluginDescriptor) {
  846. return pluginDescriptor.getPluginId() + "@" + pluginDescriptor.getVersion();
  847. }
  848. /**
  849. * Shortcut for {@code getPluginLabel(getPlugin(pluginId).getDescriptor())}.
  850. *
  851. * @param pluginId the pluginId
  852. * @return the plugin label
  853. */
  854. protected String getPluginLabel(String pluginId) {
  855. return getPluginLabel(getPlugin(pluginId).getDescriptor());
  856. }
  857. @SuppressWarnings("unchecked")
  858. protected <T> List<Class<? extends T>> getExtensionClasses(List<ExtensionWrapper<T>> extensionsWrapper) {
  859. List<Class<? extends T>> extensionClasses = new ArrayList<>(extensionsWrapper.size());
  860. for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
  861. Class<T> c = (Class<T>) extensionWrapper.getDescriptor().extensionClass;
  862. extensionClasses.add(c);
  863. }
  864. return extensionClasses;
  865. }
  866. protected <T> List<T> getExtensions(List<ExtensionWrapper<T>> extensionsWrapper) {
  867. List<T> extensions = new ArrayList<>(extensionsWrapper.size());
  868. for (ExtensionWrapper<T> extensionWrapper : extensionsWrapper) {
  869. try {
  870. extensions.add(extensionWrapper.getExtension());
  871. } catch (PluginRuntimeException e) {
  872. log.error("Cannot retrieve extension", e);
  873. }
  874. }
  875. return extensions;
  876. }
  877. protected DependencyResolver.Result resolveDependencies() {
  878. // retrieves the plugins descriptors
  879. List<PluginDescriptor> descriptors = plugins.values().stream()
  880. .map(PluginWrapper::getDescriptor)
  881. .collect(Collectors.toList());
  882. DependencyResolver.Result result = dependencyResolver.resolve(descriptors);
  883. if (result.isOK()) {
  884. return result;
  885. }
  886. if (result.hasCyclicDependency()) {
  887. // cannot recover from cyclic dependency
  888. throw new DependencyResolver.CyclicDependencyException();
  889. }
  890. List<String> notFoundDependencies = result.getNotFoundDependencies();
  891. if (result.hasNotFoundDependencies() && resolveRecoveryStrategy.equals(ResolveRecoveryStrategy.THROW_EXCEPTION)) {
  892. throw new DependencyResolver.DependenciesNotFoundException(notFoundDependencies);
  893. }
  894. List<DependencyResolver.WrongDependencyVersion> wrongVersionDependencies = result.getWrongVersionDependencies();
  895. if (result.hasWrongVersionDependencies() && resolveRecoveryStrategy.equals(ResolveRecoveryStrategy.THROW_EXCEPTION)) {
  896. throw new DependencyResolver.DependenciesWrongVersionException(wrongVersionDependencies);
  897. }
  898. List<PluginDescriptor> resolvedDescriptors = new ArrayList<>(descriptors);
  899. for (String notFoundDependency : notFoundDependencies) {
  900. List<String> dependents = dependencyResolver.getDependents(notFoundDependency);
  901. dependents.forEach(dependent -> resolvedDescriptors.removeIf(descriptor -> descriptor.getPluginId().equals(dependent)));
  902. }
  903. for (DependencyResolver.WrongDependencyVersion wrongVersionDependency : wrongVersionDependencies) {
  904. resolvedDescriptors.removeIf(descriptor -> descriptor.getPluginId().equals(wrongVersionDependency.getDependencyId()));
  905. }
  906. List<PluginDescriptor> unresolvedDescriptors = new ArrayList<>(descriptors);
  907. unresolvedDescriptors.removeAll(resolvedDescriptors);
  908. for (PluginDescriptor unresolvedDescriptor : unresolvedDescriptors) {
  909. unloadPlugin(unresolvedDescriptor.getPluginId(), false);
  910. }
  911. return resolveDependencies();
  912. }
  913. /**
  914. * Retrieve the strategy for handling the recovery of a plugin resolve (load) failure.
  915. * Default is {@link ResolveRecoveryStrategy#THROW_EXCEPTION}.
  916. *
  917. * @return the strategy
  918. */
  919. protected final ResolveRecoveryStrategy getResolveRecoveryStrategy() {
  920. return resolveRecoveryStrategy;
  921. }
  922. /**
  923. * Set the strategy for handling the recovery of a plugin resolve (load) failure.
  924. *
  925. * @param resolveRecoveryStrategy the strategy
  926. */
  927. protected void setResolveRecoveryStrategy(ResolveRecoveryStrategy resolveRecoveryStrategy) {
  928. Objects.requireNonNull(resolveRecoveryStrategy, "resolveRecoveryStrategy cannot be null");
  929. this.resolveRecoveryStrategy = resolveRecoveryStrategy;
  930. }
  931. /**
  932. * Strategy for handling the recovery of a plugin that could not be resolved
  933. * (loaded) due to a dependency problem.
  934. */
  935. public enum ResolveRecoveryStrategy {
  936. /**
  937. * Throw an exception when a resolve (load) failure occurs.
  938. */
  939. THROW_EXCEPTION,
  940. /**
  941. * Ignore the plugin with the resolve (load) failure and continue.
  942. * The plugin with problems will be removed/unloaded from the plugins list.
  943. */
  944. IGNORE_PLUGIN_AND_CONTINUE
  945. }
  946. }