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.

PluginFileHandler.java 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*
  2. * Copyright (c) 2006-2015 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.commandline.CommandLineOptionsModule.Directory;
  24. import com.dmdirc.commandline.CommandLineOptionsModule.DirectoryType;
  25. import com.google.common.collect.ArrayListMultimap;
  26. import com.google.common.collect.Multimap;
  27. import java.io.IOException;
  28. import java.nio.file.FileVisitOption;
  29. import java.nio.file.Files;
  30. import java.nio.file.Path;
  31. import java.util.Collection;
  32. import java.util.Collections;
  33. import java.util.HashSet;
  34. import java.util.Map;
  35. import java.util.Set;
  36. import java.util.concurrent.CopyOnWriteArrayList;
  37. import java.util.function.Function;
  38. import java.util.stream.Collectors;
  39. import javax.inject.Inject;
  40. import javax.inject.Singleton;
  41. import org.slf4j.Logger;
  42. import org.slf4j.LoggerFactory;
  43. import static com.dmdirc.util.LogUtils.USER_ERROR;
  44. /**
  45. * Locates and tracks plugin files on disk.
  46. */
  47. @Singleton
  48. public class PluginFileHandler {
  49. private static final Logger LOG = LoggerFactory.getLogger(PluginFileHandler.class);
  50. private final Path directory;
  51. private final Collection<PluginMetaData> knownPlugins = new CopyOnWriteArrayList<>();
  52. @Inject
  53. public PluginFileHandler(
  54. @Directory(DirectoryType.PLUGINS) final Path directory) {
  55. this.directory = directory;
  56. }
  57. /**
  58. * Finds all plugin files on disk, loads their metadata, and validates them.
  59. *
  60. * @param manager The plugin manager to pass to new metadata instances.
  61. * @return Collection of valid plugins.
  62. */
  63. public Set<PluginMetaData> refresh(final PluginManager manager) {
  64. applyUpdates();
  65. final Set<PluginMetaData> metadata = findAllPlugins(manager);
  66. // Deal with plugins that had errors
  67. metadata.stream().filter(PluginMetaData::hasErrors).forEach(this::reportErrors);
  68. metadata.removeIf(PluginMetaData::hasErrors);
  69. final Set<PluginMetaData> newPlugins = getValidPlugins(metadata);
  70. knownPlugins.clear();
  71. knownPlugins.addAll(newPlugins);
  72. return newPlugins;
  73. }
  74. /**
  75. * Gets the collection of known plugins.
  76. *
  77. * @return A cached collection of plugins (no disk I/O will be performed).
  78. */
  79. public Collection<PluginMetaData> getKnownPlugins() {
  80. return Collections.unmodifiableCollection(knownPlugins);
  81. }
  82. /**
  83. * Recursively scans the plugin directory and attempts to apply any available updates.
  84. */
  85. private void applyUpdates() {
  86. try {
  87. Files.walk(directory, FileVisitOption.FOLLOW_LINKS)
  88. .filter(p -> p.getFileName().toString().endsWith(".jar.update"))
  89. .forEach(this::applyUpdate);
  90. } catch (IOException ex) {
  91. LOG.warn(USER_ERROR, "Unable to apply plugin updates", ex);
  92. }
  93. }
  94. /**
  95. * Attempts to apply an update located at the specified path. Pending updates named
  96. * '*.jar.update' will be renamed to '*.jar' (unless the original couldn't be deleted).
  97. *
  98. * @param path The path of the pending update to apply.
  99. */
  100. private void applyUpdate(final Path path) {
  101. final Path target = path.getParent()
  102. .resolve(path.getFileName().toString().replaceAll("\\.update$", ""));
  103. try {
  104. Files.deleteIfExists(target);
  105. Files.move(path, target);
  106. } catch (IOException ex) {
  107. LOG.warn(USER_ERROR, "Unable to apply update to {}", path, ex);
  108. }
  109. }
  110. /**
  111. * Finds all plugins on disk with loadable metadata.
  112. *
  113. * @param manager The plugin manager to pass to new metadata instances.
  114. * @return Collection of all plugins with loadable metadata.
  115. */
  116. private Set<PluginMetaData> findAllPlugins(final PluginManager manager) {
  117. try {
  118. return Files.walk(directory, FileVisitOption.FOLLOW_LINKS)
  119. .filter(p -> p.getFileName().toString().endsWith(".jar"))
  120. .map(Path::toAbsolutePath)
  121. .map(path -> getMetaData(path, manager))
  122. .collect(Collectors.toSet());
  123. } catch (IOException ex) {
  124. LOG.error(USER_ERROR, "Unable to read plugin directory.", ex);
  125. return Collections.emptySet();
  126. }
  127. }
  128. /**
  129. * Attempts to get the metadata for a plugin at the specified path.
  130. *
  131. * @param path The path of the plugin to get metadata from.
  132. * @param manager The plugin manager to pass to new metadata instances.
  133. * @return The metadata for the given plugin.
  134. */
  135. private PluginMetaData getMetaData(final Path path, final PluginManager manager) {
  136. final PluginMetaData metaData = new PluginMetaData(manager, path);
  137. metaData.load();
  138. return metaData;
  139. }
  140. /**
  141. * Reports any errors present in the metadata to the event bus.
  142. *
  143. * @param pluginMetaData The metadata to read errors from.
  144. */
  145. private void reportErrors(final PluginMetaData pluginMetaData) {
  146. LOG.warn(USER_ERROR, "Error reading plugin metadata for plugin {}: {}",
  147. pluginMetaData.getPluginPath(), pluginMetaData.getErrors());
  148. }
  149. /**
  150. * Gets all services defined for the given plugins.
  151. *
  152. * @param metadata The metadata to retrieve services from.
  153. * @return A multimap of service types to their implementations.
  154. */
  155. private Multimap<String, String> getServices(final Collection<PluginMetaData> metadata) {
  156. final Multimap<String, String> services = ArrayListMultimap.create();
  157. // Normal services
  158. metadata.stream()
  159. .map(PluginMetaData::getServices)
  160. .flatMap(Collection::stream)
  161. .map(service -> service.split(" ", 2))
  162. .forEach(pair -> services.put(pair[1], pair[0]));
  163. // Exports
  164. metadata.stream()
  165. .map(PluginMetaData::getExports)
  166. .flatMap(Collection::stream)
  167. .map(exportName -> exportName.split(" "))
  168. .map(parts -> parts.length > 4 ? parts[4] : parts[0])
  169. .forEach(name -> services.put("export", name));
  170. return services;
  171. }
  172. /**
  173. * Validates each plugin using a {@link PluginMetaDataValidator}, and returns those found to
  174. * be valid.
  175. *
  176. * @param metadata The collection of metadata to validate.
  177. * @return The collection of metadata that passed validation.
  178. */
  179. private Set<PluginMetaData> getValidPlugins(final Collection<PluginMetaData> metadata) {
  180. // Collect a map by name
  181. final Map<String, PluginMetaData> metaDataByName = metadata.stream()
  182. .collect(Collectors.toMap(PluginMetaData::getName, Function.identity()));
  183. // Collect up services
  184. final Multimap<String, String> services = getServices(metadata);
  185. // Validate each in turn
  186. final Set<PluginMetaData> res = new HashSet<>();
  187. for (PluginMetaData target : metadata) {
  188. final PluginMetaDataValidator validator = new PluginMetaDataValidator(target);
  189. final Collection<String> results = validator.validate(metaDataByName, services);
  190. if (results.isEmpty()) {
  191. res.add(target);
  192. } else {
  193. LOG.warn(USER_ERROR, "Plugin validation failed for {}: {}",
  194. target.getPluginPath(), results);
  195. }
  196. }
  197. return res;
  198. }
  199. }