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

AbstractPluginManager.java 32KB

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