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.

PluginInfo.java 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. /*
  2. * Copyright (c) 2006-2014 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.plugins;
  23. import com.dmdirc.config.ConfigFileBackedConfigProvider;
  24. import com.dmdirc.config.InvalidIdentityFileException;
  25. import com.dmdirc.events.PluginLoadedEvent;
  26. import com.dmdirc.events.PluginUnloadedEvent;
  27. import com.dmdirc.interfaces.config.ConfigProvider;
  28. import com.dmdirc.interfaces.config.IdentityController;
  29. import com.dmdirc.logger.ErrorLevel;
  30. import com.dmdirc.logger.Logger;
  31. import com.dmdirc.util.SimpleInjector;
  32. import com.dmdirc.util.resourcemanager.ResourceManager;
  33. import com.dmdirc.util.validators.ValidationResponse;
  34. import com.google.common.eventbus.EventBus;
  35. import java.io.File;
  36. import java.io.IOException;
  37. import java.io.InputStream;
  38. import java.util.ArrayList;
  39. import java.util.Collection;
  40. import java.util.Collections;
  41. import java.util.HashMap;
  42. import java.util.List;
  43. import java.util.Map;
  44. import java.util.Timer;
  45. import java.util.TimerTask;
  46. import java.util.TreeMap;
  47. import javax.inject.Provider;
  48. import org.slf4j.LoggerFactory;
  49. import dagger.ObjectGraph;
  50. /**
  51. * Stores plugin metadata and handles loading of plugin resources.
  52. */
  53. public class PluginInfo implements Comparable<PluginInfo>, ServiceProvider {
  54. private static final org.slf4j.Logger log = LoggerFactory.getLogger(PluginInfo.class);
  55. /** The metadata for this plugin. */
  56. private final PluginMetaData metaData;
  57. /** The initialiser to use for the injector. */
  58. private final Provider<PluginInjectorInitialiser> injectorInitialiser;
  59. /** The object graph to pass to plugins for DI purposes. */
  60. private final ObjectGraph objectGraph;
  61. /** The controller to add and remove settings from. */
  62. private final IdentityController identityController;
  63. /** Filename for this plugin (taken from URL). */
  64. private final String filename;
  65. /** The actual Plugin from this jar. */
  66. private Plugin plugin;
  67. /** The classloader used for this Plugin. */
  68. private PluginClassLoader pluginClassLoader;
  69. /** The resource manager used by this pluginInfo. */
  70. private ResourceManager resourceManager;
  71. /** Is this plugin only loaded temporarily? */
  72. private boolean tempLoaded;
  73. /** List of classes this plugin has. */
  74. private final List<String> myClasses = new ArrayList<>();
  75. /** Last Error Message. */
  76. private String lastError = "No Error";
  77. /** Are we trying to load? */
  78. private boolean isLoading;
  79. /** List of services we provide. */
  80. private final List<Service> provides = new ArrayList<>();
  81. /** List of children of this plugin. */
  82. private final List<PluginInfo> children = new ArrayList<>();
  83. /** Map of exports. */
  84. private final Map<String, ExportInfo> exports = new HashMap<>();
  85. /** List of configuration providers. */
  86. private final List<ConfigProvider> configProviders = new ArrayList<>();
  87. /** Event bus to post plugin loaded events to. */
  88. private final EventBus eventBus;
  89. /**
  90. * Create a new PluginInfo.
  91. *
  92. * @param metadata The plugin's metadata information
  93. * @param injectorInitialiser The initialiser to use for the plugin's injector.
  94. * @param eventBus Event bus to post event loaded events on.
  95. * @param identityController The identity controller to add and remove settings from.
  96. * @param objectGraph The object graph to give to plugins for DI purposes.
  97. *
  98. * @throws PluginException if there is an error loading the Plugin
  99. */
  100. public PluginInfo(
  101. final PluginMetaData metadata,
  102. final Provider<PluginInjectorInitialiser> injectorInitialiser,
  103. final EventBus eventBus,
  104. final IdentityController identityController,
  105. final ObjectGraph objectGraph) throws PluginException {
  106. this.injectorInitialiser = injectorInitialiser;
  107. this.objectGraph = objectGraph;
  108. this.eventBus = eventBus;
  109. this.identityController = identityController;
  110. this.filename = new File(metadata.getPluginUrl().getPath()).getName();
  111. this.metaData = metadata;
  112. ResourceManager res;
  113. try {
  114. res = getResourceManager();
  115. } catch (IOException ioe) {
  116. lastError = "Error with resourcemanager: " + ioe.getMessage();
  117. throw new PluginException("Plugin " + filename + " failed to load. " + lastError, ioe);
  118. }
  119. updateClassList(res);
  120. if (!myClasses.contains(metadata.getMainClass())) {
  121. lastError = "main class file (" + metadata.getMainClass() + ") not found in jar.";
  122. throw new PluginException("Plugin " + filename + " failed to load. " + lastError);
  123. }
  124. updateProvides();
  125. getDefaults();
  126. }
  127. public PluginMetaData getMetaData() {
  128. return metaData;
  129. }
  130. public String getFilename() {
  131. return filename;
  132. }
  133. public Plugin getPlugin() {
  134. return plugin;
  135. }
  136. public PluginClassLoader getPluginClassLoader() {
  137. return pluginClassLoader;
  138. }
  139. public String getLastError() {
  140. return lastError;
  141. }
  142. /**
  143. * Updates the list of known classes within this plugin from the specified resource manager.
  144. *
  145. * @param res Resource manager to use to read the plugin contents.
  146. */
  147. private void updateClassList(final ResourceManager res) {
  148. myClasses.clear();
  149. for (final String classfilename : res.getResourcesStartingWith("")) {
  150. final String classname = classfilename.replace('/', '.');
  151. if (classname.endsWith(".class")) {
  152. myClasses.add(classname.substring(0, classname.length() - 6));
  153. }
  154. }
  155. }
  156. /**
  157. * Retrieves the injector used to inject parameters into this plugin's methods.
  158. *
  159. * @return The injector used for this plugin
  160. */
  161. public SimpleInjector getInjector() {
  162. final SimpleInjector injector;
  163. final SimpleInjector[] parents = new SimpleInjector[metaData.getParent() == null ? 0 : 1];
  164. final Plugin[] plugins = new Plugin[parents.length];
  165. if (metaData.getParent() != null) {
  166. final PluginInfo parent = metaData.getManager()
  167. .getPluginInfoByName(metaData.getParent());
  168. parents[0] = parent.getInjector();
  169. plugins[0] = parent.getPlugin();
  170. }
  171. injector = new SimpleInjector(parents);
  172. for (Plugin parentPlugin : plugins) {
  173. injector.addParameter(parentPlugin);
  174. }
  175. // TODO: This should be switched to using a full DI framework.
  176. injector.addParameter(PluginInfo.class, this);
  177. injector.addParameter(PluginMetaData.class, metaData);
  178. injectorInitialiser.get().initialise(injector);
  179. return injector;
  180. }
  181. /**
  182. * Gets the {@link ObjectGraph} that should be used when loading this plugin.
  183. *
  184. * <p>
  185. * Where this plugin has a parent which returns a non-null graph from
  186. * {@link Plugin#getObjectGraph()} that object graph will be used unmodified. Otherwise, the
  187. * global object graph will be used.
  188. *
  189. * @return An {@link ObjectGraph} to be used.
  190. */
  191. protected ObjectGraph getObjectGraph() {
  192. if (metaData.getParent() != null) {
  193. final PluginInfo parentInfo = metaData.getManager()
  194. .getPluginInfoByName(metaData.getParent());
  195. Plugin parent = parentInfo.getPlugin();
  196. ObjectGraph parentGraph = parent.getObjectGraph();
  197. if (parentGraph != null) {
  198. return parentGraph;
  199. }
  200. }
  201. return objectGraph;
  202. }
  203. /**
  204. * Get the licence for this plugin if it exists.
  205. *
  206. * @return An InputStream for the licence of this plugin, or null if no licence found.
  207. *
  208. * @throws IOException if there is an error with the ResourceManager.
  209. */
  210. public Map<String, InputStream> getLicenceStreams() throws IOException {
  211. final TreeMap<String, InputStream> licences = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
  212. licences.putAll(getResourceManager().getResourcesStartingWithAsInputStreams(
  213. "META-INF/licences/"));
  214. return licences;
  215. }
  216. /**
  217. * Get the defaults, formatters and icons for this plugin.
  218. */
  219. private void getDefaults() {
  220. final ConfigProvider defaults = identityController.getAddonSettings();
  221. log.trace("{}: Using domain '{}'",
  222. new Object[]{metaData.getName(), getDomain()});
  223. for (Map.Entry<String, String> entry : metaData.getDefaultSettings().entrySet()) {
  224. final String key = entry.getKey();
  225. final String value = entry.getValue();
  226. defaults.setOption(getDomain(), key, value);
  227. }
  228. for (Map.Entry<String, String> entry : metaData.getFormatters().entrySet()) {
  229. final String key = entry.getKey();
  230. final String value = entry.getValue();
  231. defaults.setOption("formatter", key, value);
  232. }
  233. for (Map.Entry<String, String> entry : metaData.getIcons().entrySet()) {
  234. final String key = entry.getKey();
  235. final String value = entry.getValue();
  236. defaults.setOption("icon", key, value);
  237. }
  238. }
  239. /**
  240. * Try get the identities for this plugin. This will unload any identities previously loaded by
  241. * this plugin.
  242. */
  243. private void loadIdentities() {
  244. try {
  245. final Map<String, InputStream> identityStreams = getResourceManager()
  246. .getResourcesStartingWithAsInputStreams("META-INF/identities/");
  247. unloadIdentities();
  248. for (Map.Entry<String, InputStream> entry : identityStreams.entrySet()) {
  249. final String name = entry.getKey();
  250. final InputStream stream = entry.getValue();
  251. if (name.endsWith("/") || stream == null) {
  252. // Don't try to load folders or null streams
  253. continue;
  254. }
  255. synchronized (configProviders) {
  256. try {
  257. final ConfigProvider configProvider = new ConfigFileBackedConfigProvider(
  258. stream, false);
  259. identityController.addConfigProvider(configProvider);
  260. configProviders.add(configProvider);
  261. } catch (final InvalidIdentityFileException ex) {
  262. Logger.userError(ErrorLevel.MEDIUM,
  263. "Error with identity file '" + name
  264. + "' in plugin '" + metaData.getName() + "'", ex);
  265. }
  266. }
  267. }
  268. } catch (final IOException ioe) {
  269. Logger.userError(ErrorLevel.MEDIUM, "Error finding identities in plugin '"
  270. + metaData.getName() + "'", ioe);
  271. }
  272. }
  273. /**
  274. * Unload any identities loaded by this plugin.
  275. */
  276. private void unloadIdentities() {
  277. synchronized (configProviders) {
  278. for (ConfigProvider identity : configProviders) {
  279. identityController.removeConfigProvider(identity);
  280. }
  281. configProviders.clear();
  282. }
  283. }
  284. /**
  285. * Update provides list.
  286. */
  287. private void updateProvides() {
  288. // Remove us from any existing provides lists.
  289. synchronized (provides) {
  290. for (Service service : provides) {
  291. service.delProvider(this);
  292. }
  293. provides.clear();
  294. }
  295. // Get services provided by this plugin
  296. final Collection<String> providesList = metaData.getServices();
  297. if (providesList != null) {
  298. for (String item : providesList) {
  299. final String[] bits = item.split(" ");
  300. final String name = bits[0];
  301. final String type = bits.length > 1 ? bits[1] : "misc";
  302. if (!name.equalsIgnoreCase("any") && !type.equalsIgnoreCase("export")) {
  303. final Service service = metaData.getManager().getService(type, name, true);
  304. synchronized (provides) {
  305. service.addProvider(this);
  306. provides.add(service);
  307. }
  308. }
  309. }
  310. }
  311. updateExports();
  312. }
  313. /**
  314. * Called when the plugin is updated using the updater. Reloads metaData and updates the list of
  315. * files.
  316. */
  317. public void pluginUpdated() {
  318. try {
  319. // Force a new resourcemanager just incase.
  320. updateClassList(getResourceManager(true));
  321. updateMetaData();
  322. updateProvides();
  323. getDefaults();
  324. } catch (IOException ioe) {
  325. Logger.userError(ErrorLevel.MEDIUM, "There was an error updating "
  326. + metaData.getName(), ioe);
  327. }
  328. }
  329. /**
  330. * Try to reload the metaData from the plugin.config file. If this fails, the old data will be
  331. * used still.
  332. *
  333. * @return true if metaData was reloaded ok, else false.
  334. */
  335. private boolean updateMetaData() {
  336. metaData.load();
  337. return !metaData.hasErrors();
  338. }
  339. /**
  340. * Gets a resource manager for this plugin
  341. *
  342. * @return The resource manager for this plugin
  343. *
  344. * @throws IOException if there is any problem getting a ResourceManager for this plugin
  345. */
  346. public ResourceManager getResourceManager() throws IOException {
  347. return getResourceManager(false);
  348. }
  349. /**
  350. * Get the resource manager for this plugin
  351. *
  352. * @return The resource manager for this plugin
  353. *
  354. * @param forceNew Force a new resource manager rather than using the old one.
  355. *
  356. * @throws IOException if there is any problem getting a ResourceManager for this plugin
  357. * @since 0.6
  358. */
  359. public synchronized ResourceManager getResourceManager(final boolean forceNew) throws
  360. IOException {
  361. if (resourceManager == null || forceNew) {
  362. resourceManager = ResourceManager.getResourceManager("jar://" + metaData.getPluginUrl().
  363. getPath());
  364. // Clear the resourcemanager in 10 seconds to stop us holding the file open
  365. new Timer(filename + "-resourcemanagerTimer").schedule(new TimerTask() {
  366. /** {@inheritDoc} */
  367. @Override
  368. public void run() {
  369. resourceManager = null;
  370. }
  371. }, 10000);
  372. }
  373. return resourceManager;
  374. }
  375. /** {@inheritDoc} */
  376. @Override
  377. public final boolean isActive() {
  378. return isLoaded();
  379. }
  380. /** {@inheritDoc} */
  381. @Override
  382. public void activateServices() {
  383. loadPlugin();
  384. }
  385. /** {@inheritDoc} */
  386. @Override
  387. public String getProviderName() {
  388. return "Plugin: " + metaData.getFriendlyName() + " ("
  389. + metaData.getName() + " / " + getFilename() + ")";
  390. }
  391. /** {@inheritDoc} */
  392. @Override
  393. public List<Service> getServices() {
  394. synchronized (provides) {
  395. return new ArrayList<>(provides);
  396. }
  397. }
  398. /**
  399. * Is this plugin loaded?
  400. *
  401. * @return True if the plugin is currently (non-temporarily) loaded, false otherwise
  402. */
  403. public boolean isLoaded() {
  404. return plugin != null && !tempLoaded;
  405. }
  406. /**
  407. * Is this plugin temporarily loaded?
  408. *
  409. * @return True if this plugin is currently temporarily loaded, false otherwise
  410. */
  411. public boolean isTempLoaded() {
  412. return plugin != null && tempLoaded;
  413. }
  414. /**
  415. * Try to Load the plugin files temporarily.
  416. */
  417. public void loadPluginTemp() {
  418. if (isLoaded() || isTempLoaded()) {
  419. // Already loaded, don't do anything
  420. return;
  421. }
  422. tempLoaded = true;
  423. loadPlugin();
  424. }
  425. /**
  426. * Load any required plugins or services.
  427. *
  428. * @return True if all requirements have been satisfied, false otherwise
  429. */
  430. protected boolean loadRequirements() {
  431. return loadRequiredPlugins() && loadRequiredServices();
  432. }
  433. /**
  434. * Attempts to load all services that are required by this plugin.
  435. *
  436. * @return True iff all required services were found and satisfied
  437. */
  438. protected boolean loadRequiredServices() {
  439. final ServiceManager manager = metaData.getManager();
  440. for (String serviceInfo : metaData.getRequiredServices()) {
  441. final String[] parts = serviceInfo.split(" ", 2);
  442. if ("any".equals(parts[0])) {
  443. Service best = null;
  444. boolean found = false;
  445. for (Service service : manager.getServicesByType(parts[1])) {
  446. if (service.isActive()) {
  447. found = true;
  448. break;
  449. }
  450. best = service;
  451. }
  452. if (!found && best != null) {
  453. found = best.activate();
  454. }
  455. if (!found) {
  456. return false;
  457. }
  458. } else {
  459. final Service service = manager.getService(parts[1], parts[0]);
  460. if (service == null || !service.activate()) {
  461. return false;
  462. }
  463. }
  464. }
  465. return true;
  466. }
  467. /**
  468. * Attempts to load all plugins that are required by this plugin.
  469. *
  470. * @return True if all required plugins were found and loaded
  471. */
  472. protected boolean loadRequiredPlugins() {
  473. final String required = metaData.getRequirements().get("plugins");
  474. if (required != null) {
  475. for (String pluginName : required.split(",")) {
  476. final String[] data = pluginName.split(":");
  477. if (!data[0].trim().isEmpty() && !loadRequiredPlugin(data[0])) {
  478. return false;
  479. }
  480. }
  481. }
  482. if (metaData.getParent() != null) {
  483. return loadRequiredPlugin(metaData.getParent());
  484. }
  485. return true;
  486. }
  487. /**
  488. * Attempts to load the specified required plugin.
  489. *
  490. * @param name The name of the plugin to be loaded
  491. *
  492. * @return True if the plugin was found and loaded, false otherwise
  493. */
  494. protected boolean loadRequiredPlugin(final String name) {
  495. log.info("Loading required plugin '{}' for plugin {}",
  496. new Object[]{name, metaData.getName()});
  497. final PluginInfo pi = metaData.getManager().getPluginInfoByName(name);
  498. if (pi == null) {
  499. return false;
  500. }
  501. if (tempLoaded) {
  502. pi.loadPluginTemp();
  503. } else {
  504. pi.loadPlugin();
  505. }
  506. return true;
  507. }
  508. /**
  509. * Load the plugin files.
  510. */
  511. public void loadPlugin() {
  512. if (isLoaded() || isLoading) {
  513. lastError = "Not Loading: (" + isLoaded() + "||" + isLoading + ")";
  514. return;
  515. }
  516. updateProvides();
  517. if (isTempLoaded()) {
  518. tempLoaded = false;
  519. if (!loadRequirements()) {
  520. tempLoaded = true;
  521. lastError = "Unable to satisfy dependencies for " + metaData.getName();
  522. return;
  523. }
  524. try {
  525. plugin.load(this, getObjectGraph());
  526. plugin.onLoad();
  527. } catch (LinkageError | Exception e) {
  528. lastError = "Error in onLoad for " + metaData.getName() + ":"
  529. + e.getMessage();
  530. Logger.appError(ErrorLevel.MEDIUM, lastError, e);
  531. unloadPlugin();
  532. }
  533. } else {
  534. isLoading = true;
  535. if (!loadRequirements()) {
  536. isLoading = false;
  537. lastError = "Unable to satisfy dependencies for " + metaData.getName();
  538. return;
  539. }
  540. loadIdentities();
  541. loadClass(metaData.getMainClass());
  542. if (isLoaded()) {
  543. //TODO plugin loading shouldnt be done from here, event bus shouldn't be here.
  544. eventBus.post(new PluginLoadedEvent(this));
  545. }
  546. isLoading = false;
  547. }
  548. }
  549. /**
  550. * Add the given Plugin as a child of this plugin.
  551. *
  552. * @param child Child to add
  553. */
  554. public void addChild(final PluginInfo child) {
  555. children.add(child);
  556. }
  557. /**
  558. * Remove the given Plugin as a child of this plugin.
  559. *
  560. * @param child Child to remove
  561. */
  562. public void delChild(final PluginInfo child) {
  563. children.remove(child);
  564. }
  565. /**
  566. * Returns a list of this plugin's children.
  567. *
  568. * @return List of child plugins
  569. */
  570. public List<PluginInfo> getChildren() {
  571. return Collections.unmodifiableList(children);
  572. }
  573. /**
  574. * Checks if this plugin has any children.
  575. *
  576. * @return true iff this plugin has children
  577. */
  578. public boolean hasChildren() {
  579. return !children.isEmpty();
  580. }
  581. /**
  582. * Initialises this plugin's classloader.
  583. */
  584. private void initialiseClassLoader() {
  585. if (pluginClassLoader == null) {
  586. final PluginClassLoader[] loaders = new PluginClassLoader[metaData.getParent() == null
  587. ? 0 : 1];
  588. if (metaData.getParent() != null) {
  589. final String parentName = metaData.getParent();
  590. final PluginInfo parent = metaData.getManager()
  591. .getPluginInfoByName(parentName);
  592. parent.addChild(this);
  593. loaders[0] = parent.getPluginClassLoader();
  594. if (loaders[0] == null) {
  595. // Not loaded? Try again...
  596. parent.loadPlugin();
  597. loaders[0] = parent.getPluginClassLoader();
  598. if (loaders[0] == null) {
  599. lastError = "Unable to get classloader from required parent '" + parentName
  600. + "' for " + metaData.getName();
  601. return;
  602. }
  603. }
  604. }
  605. pluginClassLoader = new PluginClassLoader(this, metaData.getManager().
  606. getGlobalClassLoader(), loaders);
  607. }
  608. }
  609. /**
  610. * Load the given classname.
  611. *
  612. * @param classname Class to load
  613. */
  614. private void loadClass(final String classname) {
  615. try {
  616. initialiseClassLoader();
  617. // Don't reload a class if its already loaded.
  618. if (pluginClassLoader.isClassLoaded(classname, true)) {
  619. lastError = "Classloader says we are already loaded.";
  620. return;
  621. }
  622. final Class<?> clazz = pluginClassLoader.loadClass(classname);
  623. if (clazz == null) {
  624. lastError = "Class '" + classname + "' was not able to load.";
  625. return;
  626. }
  627. // Only try and construct the main class, anything else should be constructed
  628. // by the plugin itself.
  629. if (classname.equals(metaData.getMainClass())) {
  630. final Object temp = getInjector().createInstance(clazz);
  631. if (temp instanceof Plugin) {
  632. final ValidationResponse prerequisites = ((Plugin) temp).checkPrerequisites();
  633. if (prerequisites.isFailure()) {
  634. if (!tempLoaded) {
  635. lastError = "Prerequisites for plugin not met. ('"
  636. + filename + ":" + metaData.getMainClass()
  637. + "' -> '" + prerequisites.getFailureReason() + "') ";
  638. Logger.userError(ErrorLevel.LOW, lastError);
  639. }
  640. } else {
  641. plugin = (Plugin) temp;
  642. log.debug("{}: Setting domain '{}'",
  643. new Object[]{metaData.getName(), getDomain()});
  644. plugin.setDomain(getDomain());
  645. if (!tempLoaded) {
  646. try {
  647. plugin.load(this, getObjectGraph());
  648. plugin.onLoad();
  649. } catch (LinkageError | Exception e) {
  650. lastError = "Error in onLoad for "
  651. + metaData.getName() + ":" + e.getMessage();
  652. Logger.appError(ErrorLevel.MEDIUM, lastError, e);
  653. unloadPlugin();
  654. }
  655. }
  656. }
  657. }
  658. }
  659. } catch (ClassNotFoundException cnfe) {
  660. lastError = "Class not found ('" + filename + ":" + classname + ":"
  661. + classname.equals(metaData.getMainClass()) + "') - "
  662. + cnfe.getMessage();
  663. Logger.userError(ErrorLevel.LOW, lastError, cnfe);
  664. } catch (NoClassDefFoundError ncdf) {
  665. lastError = "Unable to instantiate plugin ('" + filename + ":"
  666. + classname + ":"
  667. + classname.equals(metaData.getMainClass())
  668. + "') - Unable to find class: " + ncdf.getMessage();
  669. Logger.userError(ErrorLevel.LOW, lastError, ncdf);
  670. } catch (VerifyError ve) {
  671. lastError = "Unable to instantiate plugin ('" + filename + ":"
  672. + classname + ":"
  673. + classname.equals(metaData.getMainClass())
  674. + "') - Incompatible: " + ve.getMessage();
  675. Logger.userError(ErrorLevel.LOW, lastError, ve);
  676. } catch (IllegalArgumentException ex) {
  677. lastError = "Unable to instantiate class for plugin " + metaData.getName()
  678. + ": " + classname;
  679. Logger.appError(ErrorLevel.LOW, lastError, ex);
  680. }
  681. }
  682. /**
  683. * Gets the configuration domain that should be used by this plugin.
  684. *
  685. * @return The configuration domain to use.
  686. */
  687. public String getDomain() {
  688. return "plugin-" + metaData.getName();
  689. }
  690. /**
  691. * Unload the plugin if possible.
  692. */
  693. public void unloadPlugin() {
  694. unloadPlugin(false);
  695. }
  696. /**
  697. * Can this plugin be unloaded? Will return false if: - The plugin is persistent (all its
  698. * classes are loaded into the global class loader) - The plugin isn't currently loaded - The
  699. * metadata key "unloadable" is set to false, no or 0
  700. *
  701. * @return true if plugin can be unloaded
  702. */
  703. public boolean isUnloadable() {
  704. return !isPersistent() && (isTempLoaded() || isLoaded())
  705. && metaData.isUnloadable();
  706. }
  707. /**
  708. * Unload the plugin if possible.
  709. *
  710. * @param parentUnloading is our parent already unloading? (if so, don't call delChild)
  711. */
  712. private void unloadPlugin(final boolean parentUnloading) {
  713. if (isUnloadable()) {
  714. if (!isTempLoaded()) {
  715. // Unload all children
  716. for (PluginInfo child : children) {
  717. child.unloadPlugin(true);
  718. }
  719. // Delete ourself as a child of our parent.
  720. if (!parentUnloading) {
  721. if (metaData.getParent() != null) {
  722. final PluginInfo pi = metaData.getManager()
  723. .getPluginInfoByName(metaData.getParent());
  724. if (pi != null) {
  725. pi.delChild(this);
  726. }
  727. }
  728. }
  729. // Now unload ourself
  730. try {
  731. plugin.onUnload();
  732. } catch (Exception | LinkageError e) {
  733. lastError = "Error in onUnload for " + metaData.getName()
  734. + ":" + e + " - " + e.getMessage();
  735. Logger.appError(ErrorLevel.MEDIUM, lastError, e);
  736. }
  737. //TODO plugin unloading shouldnt be done from here, event bus shouldn't be here.
  738. eventBus.post(new PluginUnloadedEvent(this));
  739. synchronized (provides) {
  740. for (Service service : provides) {
  741. service.delProvider(this);
  742. }
  743. provides.clear();
  744. }
  745. }
  746. unloadIdentities();
  747. tempLoaded = false;
  748. plugin = null;
  749. pluginClassLoader = null;
  750. }
  751. }
  752. /**
  753. * Get the list of Classes
  754. *
  755. * @return Classes this plugin has
  756. */
  757. public List<String> getClassList() {
  758. return Collections.unmodifiableList(myClasses);
  759. }
  760. /**
  761. * Is this a persistent plugin?
  762. *
  763. * @return true if persistent, else false
  764. */
  765. public boolean isPersistent() {
  766. return metaData.getPersistentClasses().contains("*");
  767. }
  768. /**
  769. * Does this plugin contain any persistent classes?
  770. *
  771. * @return true if this plugin contains any persistent classes, else false
  772. */
  773. public boolean hasPersistent() {
  774. return !metaData.getPersistentClasses().isEmpty();
  775. }
  776. /**
  777. * Get a list of all persistent classes in this plugin
  778. *
  779. * @return List of all persistent classes in this plugin
  780. */
  781. public Collection<String> getPersistentClasses() {
  782. if (isPersistent()) {
  783. return getClassList();
  784. } else {
  785. return metaData.getPersistentClasses();
  786. }
  787. }
  788. /**
  789. * Is this a persistent class?
  790. *
  791. * @param classname class to check persistence of
  792. *
  793. * @return true if file (or whole plugin) is persistent, else false
  794. */
  795. public boolean isPersistent(final String classname) {
  796. return isPersistent() || metaData.getPersistentClasses().contains(classname);
  797. }
  798. /**
  799. * String Representation of this plugin
  800. *
  801. * @return String Representation of this plugin
  802. */
  803. @Override
  804. public String toString() {
  805. return metaData.getFriendlyName() + " - " + filename;
  806. }
  807. /** {@inheritDoc} */
  808. @Override
  809. public int compareTo(final PluginInfo o) {
  810. return toString().compareTo(o.toString());
  811. }
  812. /**
  813. * Update exports list.
  814. */
  815. private void updateExports() {
  816. exports.clear();
  817. // Get exports provided by this plugin
  818. final Collection<String> exportsList = metaData.getExports();
  819. for (String item : exportsList) {
  820. final String[] bits = item.split(" ");
  821. if (bits.length > 2) {
  822. final String methodName = bits[0];
  823. final String methodClass = bits[2];
  824. final String serviceName = bits.length > 4 ? bits[4] : bits[0];
  825. // Add a provides for this
  826. final Service service = metaData.getManager().
  827. getService("export", serviceName, true);
  828. synchronized (provides) {
  829. service.addProvider(this);
  830. provides.add(service);
  831. }
  832. // Add is as an export
  833. exports.put(serviceName, new ExportInfo(methodName, methodClass, this));
  834. }
  835. }
  836. }
  837. /** {@inheritDoc} */
  838. @Override
  839. public ExportedService getExportedService(final String name) {
  840. if (exports.containsKey(name)) {
  841. return exports.get(name).getExportedService();
  842. } else {
  843. return null;
  844. }
  845. }
  846. /**
  847. * Does this plugin export the specified service?
  848. *
  849. * @param name Name of the service to check
  850. *
  851. * @return true iff the plugin exports the service
  852. */
  853. public boolean hasExportedService(final String name) {
  854. return exports.containsKey(name);
  855. }
  856. }