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

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