PluginManager.java 19.3 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1
/**
2

Matt Tucker's avatar
Matt Tucker committed
3
 * $RCSfile$
4

Matt Tucker's avatar
Matt Tucker committed
5
 * $Revision$
6

Matt Tucker's avatar
Matt Tucker committed
7
 * $Date$
8

Matt Tucker's avatar
Matt Tucker committed
9
 *
10

Matt Tucker's avatar
Matt Tucker committed
11
 * Copyright (C) 2004 Jive Software. All rights reserved.
12

Matt Tucker's avatar
Matt Tucker committed
13
 *
14

Matt Tucker's avatar
Matt Tucker committed
15
 * This software is published under the terms of the GNU Public License (GPL),
16

Matt Tucker's avatar
Matt Tucker committed
17
 * a copy of which is included in this distribution.
18

Matt Tucker's avatar
Matt Tucker committed
19 20 21 22
 */

package org.jivesoftware.messenger.container;

23
import org.dom4j.Attribute;
Matt Tucker's avatar
Matt Tucker committed
24 25 26
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
27 28 29 30 31
import org.jivesoftware.admin.AdminConsole;
import org.jivesoftware.messenger.XMPPServer;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.Version;
Matt Tucker's avatar
Matt Tucker committed
32

33 34 35 36
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.InputStream;
Matt Tucker's avatar
Matt Tucker committed
37 38 39 40
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
41 42 43
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipFile;
Matt Tucker's avatar
Matt Tucker committed
44 45

/**
Matt Tucker's avatar
Matt Tucker committed
46
 * Loads and manages plugins. The <tt>plugins</tt> directory is monitored for any
47 48 49 50 51
 * new plugins, and they are dynamically loaded.<p>
 * 
 * An instance of this class can be obtained using:
 *
 * <tt>XMPPServer.getInstance().getPluginManager()</tt>
Matt Tucker's avatar
Matt Tucker committed
52
 *
Matt Tucker's avatar
Matt Tucker committed
53
 * @see Plugin
54
 * @see org.jivesoftware.messenger.XMPPServer#getPluginManager()
Matt Tucker's avatar
Matt Tucker committed
55 56 57 58 59
 * @author Matt Tucker
 */
public class PluginManager {

    private File pluginDirectory;
Matt Tucker's avatar
Matt Tucker committed
60
    private Map<String,Plugin> plugins;
Matt Tucker's avatar
Matt Tucker committed
61
    private Map<Plugin,PluginClassLoader> classloaders;
62
    private Map<Plugin,File> pluginDirs;
Matt Tucker's avatar
Matt Tucker committed
63 64 65
    private boolean setupMode = !(Boolean.valueOf(JiveGlobals.getXMLProperty("setup")).booleanValue());
    private ScheduledExecutorService executor = null;

Matt Tucker's avatar
Matt Tucker committed
66 67 68 69 70
    /**
     * Constructs a new plugin manager.
     *
     * @param pluginDir the plugin directory.
     */
Matt Tucker's avatar
Matt Tucker committed
71
    public PluginManager(File pluginDir) {
Matt Tucker's avatar
Matt Tucker committed
72
        this.pluginDirectory = pluginDir;
73
        plugins = new HashMap<String,Plugin>();
74
        pluginDirs = new HashMap<Plugin,File>();
Matt Tucker's avatar
Matt Tucker committed
75
        classloaders = new HashMap<Plugin,PluginClassLoader>();
Matt Tucker's avatar
Matt Tucker committed
76 77 78 79 80 81
    }

    /**
     * Starts plugins and the plugin monitoring service.
     */
    public void start() {
Matt Tucker's avatar
Matt Tucker committed
82
        executor = new ScheduledThreadPoolExecutor(1);
83
        executor.scheduleWithFixedDelay(new PluginMonitor(), 0, 10, TimeUnit.SECONDS);
Matt Tucker's avatar
Matt Tucker committed
84 85 86 87 88 89 90 91 92 93 94
    }

    /**
     * Shuts down all running plugins.
     */
    public void shutdown() {
        // Stop the plugin monitoring service.
        if (executor != null) {
            executor.shutdown();
        }
        // Shutdown all installed plugins.
Matt Tucker's avatar
Matt Tucker committed
95
        for (Plugin plugin : plugins.values()) {
96
            plugin.destroyPlugin();
Matt Tucker's avatar
Matt Tucker committed
97
        }
Matt Tucker's avatar
Matt Tucker committed
98
        plugins.clear();
99
        pluginDirs.clear();
100
        classloaders.clear();
Matt Tucker's avatar
Matt Tucker committed
101 102 103 104 105 106 107 108 109
    }

    /**
     * Returns a Collection of all installed plugins.
     *
     * @return a Collection of all installed plugins.
     */
    public Collection<Plugin> getPlugins() {
        return Collections.unmodifiableCollection(plugins.values());
Matt Tucker's avatar
Matt Tucker committed
110 111
    }

112 113
    /**
     * Returns a plugin by name or <tt>null</tt> if a plugin with that name does not
114
     * exist. The name is the name of the directory that the plugin is in such as
115 116 117 118 119 120 121 122 123
     * "broadcast".
     *
     * @param name the name of the plugin.
     * @return the plugin.
     */
    public Plugin getPlugin(String name) {
        return plugins.get(name);
    }

124 125 126 127 128 129 130 131 132 133
    /**
     * Returns the plugin's directory.
     *
     * @param plugin the plugin.
     * @return the plugin's directory.
     */
    public File getPluginDirectory(Plugin plugin) {
        return pluginDirs.get(plugin);
    }

Matt Tucker's avatar
Matt Tucker committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    /**
     * Loads a plug-in module into the container. Loading consists of the
     * following steps:<ul>
     *
     *      <li>Add all jars in the <tt>lib</tt> dir (if it exists) to the class loader</li>
     *      <li>Add all files in <tt>classes</tt> dir (if it exists) to the class loader</li>
     *      <li>Locate and load <tt>module.xml</tt> into the context</li>
     *      <li>For each jive.module entry, load the given class as a module and start it</li>
     *
     * </ul>
     *
     * @param pluginDir the plugin directory.
     */
    private void loadPlugin(File pluginDir) {
        // Only load the admin plugin during setup mode.
        if (setupMode && !(pluginDir.getName().equals("admin"))) {
            return;
        }
        Log.debug("Loading plugin " + pluginDir.getName());
Matt Tucker's avatar
Matt Tucker committed
153
        Plugin plugin = null;
Matt Tucker's avatar
Matt Tucker committed
154
        try {
Matt Tucker's avatar
Matt Tucker committed
155 156
            File pluginConfig = new File(pluginDir, "plugin.xml");
            if (pluginConfig.exists()) {
Matt Tucker's avatar
Matt Tucker committed
157 158
                SAXReader saxReader = new SAXReader();
                Document pluginXML = saxReader.read(pluginConfig);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
                // See if the plugin specifies a version of Jive Messenger
                // required to run.
                Element minServerVersion = (Element)pluginXML.selectSingleNode(
                        "/plugin/minServerVersion");
                if (minServerVersion != null) {
                    String requiredVersion = minServerVersion.getTextTrim();
                    Version version = XMPPServer.getInstance().getServerInfo().getVersion();
                    String hasVersion = version.getMajor() + "." + version.getMinor() + "." +
                            version.getMicro();
                    if (hasVersion.compareTo(requiredVersion) < 0) {
                        String msg = "Ignoring plugin " + pluginDir.getName() + ": requires " +
                                "server version " + requiredVersion;
                        Log.warn(msg);
                        System.out.println(msg);
                        return;
                    }
                }
Matt Tucker's avatar
Matt Tucker committed
176
                PluginClassLoader pluginLoader = new PluginClassLoader(pluginDir);
Matt Tucker's avatar
Matt Tucker committed
177
                String className = pluginXML.selectSingleNode("/plugin/class").getText();
Matt Tucker's avatar
Matt Tucker committed
178
                plugin = (Plugin)pluginLoader.loadClass(className).newInstance();
179
                plugin.initializePlugin(this, pluginDir);
Matt Tucker's avatar
Matt Tucker committed
180
                plugins.put(pluginDir.getName(), plugin);
181
                pluginDirs.put(plugin, pluginDir);
Matt Tucker's avatar
Matt Tucker committed
182
                classloaders.put(plugin, pluginLoader);
183
                // Load any JSP's defined by the plugin.
184
                File webXML = new File(pluginDir, "web" + File.separator + "WEB-INF" + File.separator + "web.xml");
185
                if (webXML.exists()) {
Matt Tucker's avatar
Matt Tucker committed
186
                    PluginServlet.registerServlets(this, plugin, webXML);
187
                }
Matt Tucker's avatar
Matt Tucker committed
188 189 190
                // If there a <adminconsole> section defined, register it.
                Element adminElement = (Element)pluginXML.selectSingleNode("/plugin/adminconsole");
                if (adminElement != null) {
Matt Tucker's avatar
Matt Tucker committed
191 192 193 194 195 196 197 198 199 200 201
                    // If global images are specified, override their URL.
                    Element imageEl = (Element)adminElement.selectSingleNode(
                            "/plugin/adminconsole/global/logo-image");
                    if (imageEl != null) {
                        imageEl.setText("plugins/" + pluginDir.getName() + "/" + imageEl.getText());
                    }
                    imageEl = (Element)adminElement.selectSingleNode(
                            "/plugin/adminconsole/global/login-image");
                    if (imageEl != null) {
                        imageEl.setText("plugins/" + pluginDir.getName() + "/" + imageEl.getText());
                    }
Matt Tucker's avatar
Matt Tucker committed
202 203 204 205 206
                    // Modify all the URL's in the XML so that they are passed through
                    // the plugin servlet correctly.
                    List urls = adminElement.selectNodes("//@url");
                    for (int i=0; i<urls.size(); i++) {
                        Attribute attr = (Attribute)urls.get(i);
Bill Lynch's avatar
Bill Lynch committed
207
                        attr.setValue("plugins/" + pluginDir.getName() + "/" + attr.getValue());
Matt Tucker's avatar
Matt Tucker committed
208
                    }
209
                    AdminConsole.addModel(pluginDir.getName(), adminElement);
Matt Tucker's avatar
Matt Tucker committed
210
                }
Matt Tucker's avatar
Matt Tucker committed
211 212
            }
            else {
Matt Tucker's avatar
Matt Tucker committed
213
                Log.warn("Plugin " + pluginDir + " could not be loaded: no plugin.xml file found");
Matt Tucker's avatar
Matt Tucker committed
214 215 216 217 218 219 220
            }
        }
        catch (Exception e) {
            Log.error("Error loading plugin", e);
        }
    }

221
    /**
222
     * Unloads a plugin. The {@link Plugin#destroyPlugin()} method will be called and then
223 224 225 226 227 228 229
     * any resources will be released. The name should be the name of the plugin directory
     * and not the name as given by the plugin meta-data. This method only removes
     * the plugin but does not delete the plugin JAR file. Therefore, if the plugin JAR
     * still exists after this method is called, the plugin will be started again the next
     * time the plugin monitor process runs. This is useful for "restarting" plugins.<p>
     *
     * This method is called automatically when a plugin's JAR file is deleted.
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
     *
     * @param pluginName the name of the plugin to unload.
     */
    public void unloadPlugin(String pluginName) {
        Log.debug("Unloading plugin " + pluginName);
        Plugin plugin = plugins.get(pluginName);
        if (plugin == null) {
            return;
        }
        File webXML = new File(pluginDirectory + File.separator + pluginName +
                File.separator + "web" + File.separator + "web.xml");
        if (webXML.exists()) {
            AdminConsole.removeModel(pluginName);
            PluginServlet.unregisterServlets(webXML);
        }

        PluginClassLoader classLoader = classloaders.get(plugin);
247
        plugin.destroyPlugin();
248 249
        classLoader.destroy();
        plugins.remove(pluginName);
250
        pluginDirs.remove(plugin);
251 252 253
        classloaders.remove(plugin);
    }

Matt Tucker's avatar
Matt Tucker committed
254 255 256 257 258 259 260
    public Class loadClass(String className, Plugin plugin) throws ClassNotFoundException,
            IllegalAccessException, InstantiationException
    {
        PluginClassLoader loader = classloaders.get(plugin);
        return loader.loadClass(className);
    }

261 262 263
    /**
     * Returns the name of a plugin. The value is retrieved from the plugin.xml file
     * of the plugin. If the value could not be found, <tt>null</tt> will be returned.
264
     * Note that this value is distinct from the name of the plugin directory.
265 266 267 268 269
     *
     * @param plugin the plugin.
     * @return the plugin's name.
     */
    public String getName(Plugin plugin) {
Matt Tucker's avatar
Matt Tucker committed
270 271 272 273 274 275 276
        String name = getElementValue(plugin, "/plugin/name");
        if (name != null) {
            return name;
        }
        else {
            return pluginDirs.get(plugin).getName();
        }
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
    }

    /**
     * Returns the description of a plugin. The value is retrieved from the plugin.xml file
     * of the plugin. If the value could not be found, <tt>null</tt> will be returned.
     *
     * @param plugin the plugin.
     * @return the plugin's description.
     */
    public String getDescription(Plugin plugin) {
        return getElementValue(plugin, "/plugin/description");
    }

    /**
     * Returns the author of a plugin. The value is retrieved from the plugin.xml file
     * of the plugin. If the value could not be found, <tt>null</tt> will be returned.
     *
     * @param plugin the plugin.
     * @return the plugin's author.
     */
    public String getAuthor(Plugin plugin) {
        return getElementValue(plugin, "/plugin/author");
    }

    /**
     * Returns the version of a plugin. The value is retrieved from the plugin.xml file
     * of the plugin. If the value could not be found, <tt>null</tt> will be returned.
     *
     * @param plugin the plugin.
     * @return the plugin's version.
     */
    public String getVersion(Plugin plugin) {
        return getElementValue(plugin, "/plugin/version");
    }

    /**
     * Returns the value of an element selected via an xpath expression from
     * a Plugin's plugin.xml file.
     *
     * @param plugin the plugin.
     * @param xpath the xpath expression.
     * @return the value of the element selected by the xpath expression.
     */
    private String getElementValue(Plugin plugin, String xpath) {
        File pluginDir = pluginDirs.get(plugin);
        if (pluginDir == null) {
            return null;
        }
        try {
            File pluginConfig = new File(pluginDir, "plugin.xml");
            if (pluginConfig.exists()) {
                SAXReader saxReader = new SAXReader();
                Document pluginXML = saxReader.read(pluginConfig);
                Element element = (Element)pluginXML.selectSingleNode(xpath);
                if (element != null) {
                    return element.getTextTrim();
                }
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
        return null;
    }

Matt Tucker's avatar
Matt Tucker committed
342 343 344 345 346
    /**
     * A service that monitors the plugin directory for plugins. It periodically
     * checks for new plugin JAR files and extracts them if they haven't already
     * been extracted. Then, any new plugin directories are loaded.
     */
Matt Tucker's avatar
Matt Tucker committed
347
    private class PluginMonitor implements Runnable {
Matt Tucker's avatar
Matt Tucker committed
348 349 350 351 352

        public void run() {
            try {
                File [] jars = pluginDirectory.listFiles(new FileFilter() {
                    public boolean accept(File pathname) {
353 354
                        String fileName = pathname.getName().toLowerCase();
                        return (fileName.endsWith(".jar") || fileName.endsWith(".war"));
Matt Tucker's avatar
Matt Tucker committed
355 356 357 358 359
                    }
                });

                for (int i=0; i<jars.length; i++) {
                    File jarFile = jars[i];
360
                    String pluginName = jarFile.getName().substring(
Matt Tucker's avatar
Matt Tucker committed
361 362
                            0, jarFile.getName().length()-4).toLowerCase();
                    // See if the JAR has already been exploded.
363
                    File dir = new File(pluginDirectory, pluginName);
Matt Tucker's avatar
Matt Tucker committed
364 365
                    // If the JAR hasn't been exploded, do so.
                    if (!dir.exists()) {
366 367 368 369 370 371
                        unzipPlugin(pluginName, jarFile, dir);
                    }
                    // See if the JAR is newer than the directory. If so, the plugin
                    // needs to be unloaded and then reloaded.
                    else if (jarFile.lastModified() > dir.lastModified()) {
                        unloadPlugin(pluginName);
372 373 374
                        // Ask the system to clean up references.
                        System.gc();
                        while (!deleteDir(dir)) {
375
                            Log.error("Error unloading plugin " + pluginName + ". " +
376 377
                                    "Will attempt again momentarily.");
                            Thread.sleep(5000);
Matt Tucker's avatar
Matt Tucker committed
378
                        }
379 380
                        // Now unzip the plugin.
                        unzipPlugin(pluginName, jarFile, dir);
Matt Tucker's avatar
Matt Tucker committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
                    }
                }

                File [] dirs = pluginDirectory.listFiles(new FileFilter() {
                    public boolean accept(File pathname) {
                        return pathname.isDirectory();
                    }
                });

                // Sort the list of directories so that the "admin" plugin is always
                // first in the list.
                Arrays.sort(dirs, new Comparator<File>() {
                    public int compare(File file1, File file2) {
                        if (file1.getName().equals("admin")) {
                            return -1;
                        }
                        else if (file2.getName().equals("admin")) {
                            return 1;
                        }
                        else return file1.compareTo(file2);
                    }
                });

                for (int i=0; i<dirs.length; i++) {
                    File dirFile = dirs[i];
                    // If the plugin hasn't already been started, start it.
                    if (!plugins.containsKey(dirFile.getName())) {
                        loadPlugin(dirFile);
                    }
                }
411

412
                // See if any currently running plugins need to be unloaded
413 414
                // due to its JAR file being deleted (ignore admin plugin).
                if (plugins.size() > jars.length + 1) {
415 416 417
                    // Build a list of plugins to delete first so that the plugins
                    // keyset is modified as we're iterating through it.
                    List<String> toDelete = new ArrayList<String>();
418 419 420 421 422 423
                    for (String pluginName : plugins.keySet()) {
                        if (pluginName.equals("admin")) {
                            continue;
                        }
                        File file = new File(pluginDirectory, pluginName + ".jar");
                        if (!file.exists()) {
424 425 426 427 428 429 430 431 432 433
                            toDelete.add(pluginName);
                        }
                    }
                    for (String pluginName : toDelete) {
                        unloadPlugin(pluginName);
                        System.gc();
                        while (!deleteDir(new File(pluginDirectory, pluginName))) {
                            Log.error("Error unloading plugin " + pluginName + ". " +
                                    "Will attempt again momentarily.");
                            Thread.sleep(5000);
434 435 436
                        }
                    }
                }
Matt Tucker's avatar
Matt Tucker committed
437 438 439 440 441
            }
            catch (Exception e) {
                Log.error(e);
            }
        }
442 443 444 445 446 447 448

        /**
         * Unzips a plugin from a JAR file into a directory. If the JAR file
         * isn't a plugin, this method will do nothing.
         *
         * @param pluginName the name of the plugin.
         * @param file the JAR file
449
         * @param dir the directory to extract the plugin to.
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
         */
        private void unzipPlugin(String pluginName, File file, File dir) {
            try {
                ZipFile zipFile = new JarFile(file);
                // Ensure that this JAR is a plugin.
                if (zipFile.getEntry("plugin.xml") == null) {
                    return;
                }
                dir.mkdir();
                Log.debug("Extracting plugin: " + pluginName);
                for (Enumeration e=zipFile.entries(); e.hasMoreElements(); ) {
                    JarEntry entry = (JarEntry)e.nextElement();
                    File entryFile = new File(dir, entry.getName());
                    // Ignore any manifest.mf entries.
                    if (entry.getName().toLowerCase().endsWith("manifest.mf")) {
                        continue;
                    }
                    if (!entry.isDirectory()) {
                        entryFile.getParentFile().mkdirs();
                        FileOutputStream out = new FileOutputStream(entryFile);
                        InputStream zin = zipFile.getInputStream(entry);
                        byte [] b = new byte[512];
                        int len = 0;
                        while ( (len=zin.read(b))!= -1 ) {
                            out.write(b,0,len);
                        }
                        out.flush();
                        out.close();
                        zin.close();
                    }
                }
481 482
                zipFile.close();
                zipFile = null;
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
            }
            catch (Exception e) {
                Log.error(e);
            }
        }

        /**
         * Deletes a directory.
         */
         public boolean deleteDir(File dir) {
            if (dir.isDirectory()) {
                String[] children = dir.list();
                for (int i=0; i<children.length; i++) {
                    boolean success = deleteDir(new File(dir, children[i]));
                    if (!success) {
                        return false;
                    }
                }
            }
            return dir.delete();
        }
Matt Tucker's avatar
Matt Tucker committed
504 505
    }
}