BootstrapContainer.java 19.8 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1
/**
Matt Tucker's avatar
Matt Tucker committed
2 3 4 5
 * $RCSfile$
 * $Revision$
 * $Date$
 *
Matt Tucker's avatar
Matt Tucker committed
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
Matt Tucker's avatar
Matt Tucker committed
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10
 */
Matt Tucker's avatar
Matt Tucker committed
11

Matt Tucker's avatar
Matt Tucker committed
12 13 14 15
package org.jivesoftware.messenger.container.spi;

import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.messenger.container.*;
16
import org.jivesoftware.util.*;
Matt Tucker's avatar
Matt Tucker committed
17 18 19
import org.jivesoftware.messenger.JiveGlobals;
import org.jivesoftware.messenger.auth.UnauthorizedException;

Matt Tucker's avatar
Matt Tucker committed
20
import java.io.*;
Matt Tucker's avatar
Matt Tucker committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;

/**
 * <p>The initial container that hosts all other modules (and containers).</p>
 * <p/>
 * <p>The boostrap container operates in a similar manner to the basic container
 * but alters the standard module layout for better packaging of server.
Matt Tucker's avatar
Matt Tucker committed
35 36 37
 * Notice that the bootstrap server runs from the messengerHome directory whether
 * the server is run in standalone mode (messengerHome == server directory) or
 * as a web-app (messengerHome == setting in messenger_init.xml).</p>
Matt Tucker's avatar
Matt Tucker committed
38 39 40 41
 * <p/>
 * <p>Bootstrap systems should have a directory layout that looks like:</p>
 * <p/>
 * <ul>
Matt Tucker's avatar
Matt Tucker committed
42
 * <li>conf - Contains configuration information for the server as a whole
Matt Tucker's avatar
Matt Tucker committed
43
 * <ul>
Matt Tucker's avatar
Matt Tucker committed
44
 * <li>jive-messenger.xml - The bootstrap configuration file.</li>
Matt Tucker's avatar
Matt Tucker committed
45 46
 * </ul>
 * </li>
Matt Tucker's avatar
Matt Tucker committed
47
 * <li>logs - The root directory for log files</li>
Matt Tucker's avatar
Matt Tucker committed
48
 * <li>security - The security keystores for the server (if any)</li>
Matt Tucker's avatar
Matt Tucker committed
49
 * <li>plugins - The module directory for loading server modules</li>
Matt Tucker's avatar
Matt Tucker committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
 * </li>
 * <p/>
 * <p>Note that the root lib directory is NOT part
 * of the container's responsibilties. The jars in that
 * directory are loaded by the ServerStarter in standalone mode, or by the
 * web-app server from the WAR or web-app/WEB-INF/lib directory
 * when deployed into an app server.</p>
 *
 * @author Derek DeMoro
 * @author Iain Shigeoka
 */
public abstract class BootstrapContainer implements Container, ServiceLookupProvider {

    /**
     * <p>Obtain the full class names of the setup server modules.</p>
     * <p/>
     * <p>Setup modules are required for the setup admin UI and should
     * be the minimum subset that will allow the setup to proceed.</p>
     *
     * @return An array of the full class names of the modules to load
     */
    protected abstract String[] getSetupModuleNames();

    /**
     * <p>Obtain the full class names of the boot server modules.</p>
     * <p/>
     * <p>Boot modules are required for the runtime behavior of the server
     * and MUST not depend on other modules (including other boot modules).
     * These are the bootstrap modules that enable other modules to startup
     * without worrying about startup dependencies.</p>
     *
     * @return An array of the full class names of the modules to load
     */
    protected abstract String[] getBootModuleNames();

    /**
     * <p>Obtain the full class names of the core server modules.</p>
     * <p/>
     * <p>These modules are a core part of the standard runtime service
     * profile. They often depend on the boot modules for proper operation.</p>
     *
     * @return An array of the full class names of the modules to load
     */
    protected abstract String[] getCoreModuleNames();

    /**
     * <p>Obtain the full class names of the standard server modules.</p>
     * <p/>
     * <p>These modules are part of the standard runtime server
     * profile. They often depend on the boot and core modules for proper
     * operation.</p>
     *
     * @return An array of the full class names of the modules to load
     */
    protected abstract String[] getStandardModuleNames();

    /**
107
     * The lookup for the bootstrap container.
Matt Tucker's avatar
Matt Tucker committed
108 109
     */
    private ServiceLookup lookup;
110

Matt Tucker's avatar
Matt Tucker committed
111
    /**
112
     * The registration of the service with itself.
Matt Tucker's avatar
Matt Tucker committed
113 114 115 116 117 118
     */
    private ServiceRegistration containerRegistration;

    /**
     * All modules loaded by this container
     */
Matt Tucker's avatar
Matt Tucker committed
119
    private List<Module> modules = new ArrayList<Module>();
Matt Tucker's avatar
Matt Tucker committed
120 121

    /**
Matt Tucker's avatar
Matt Tucker committed
122
     * Location of the messengerHome directory. All configuration files should be
Matt Tucker's avatar
Matt Tucker committed
123 124
     * located here.
     */
Matt Tucker's avatar
Matt Tucker committed
125
    private File messengerHome;
Matt Tucker's avatar
Matt Tucker committed
126 127 128 129 130 131 132 133
    private ClassLoader loader;

    /**
     * True if in setup mode
     */
    private boolean setupMode = true;

    private static final String STARTER_CLASSNAME =
Matt Tucker's avatar
Matt Tucker committed
134
            "org.jivesoftware.messenger.starter.ServerStarter";
Matt Tucker's avatar
Matt Tucker committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148
    private static final String WRAPPER_CLASSNAME =
            "org.tanukisoftware.wrapper.WrapperManager";

    /**
     * Construct the server bootstrap server.
     * <p/>
     * the server could not be started
     */
    public BootstrapContainer() {
        ServiceLookupFactory.setLookupProvider(this);
        start();
    }

    /**
149
     * Starts the container.
Matt Tucker's avatar
Matt Tucker committed
150 151 152
     */
    private void start() {
        try {
153 154
            locateMessenger();
            if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
Matt Tucker's avatar
Matt Tucker committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
                setupMode = false;
            }

            if (isStandAlone()) {
                Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
            }

            lookup = new ServiceLookupImpl();
            ServiceItem serverItem = new ServiceItem(null, this, null);
            containerRegistration = lookup.register(serverItem);

            loader = Thread.currentThread().getContextClassLoader();

            if (setupMode) {
                loadCorePlugins(getSetupModuleNames());
            }
            else {
                verifyDataSource();
                loadCorePlugins(getBootModuleNames());
                loadCorePlugins(getCoreModuleNames());
                loadCorePlugins(getStandardModuleNames());
            }
            startCorePlugins();
            loadPlugins(setupMode);
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.error(e);
            System.out.println(LocaleUtils.getLocalizedString("startup.error"));
            shutdownContainer();
        }
    }

    public boolean isRestartable() {
        boolean restartable = false;
        try {
            restartable = Class.forName(WRAPPER_CLASSNAME) != null;
        }
        catch (ClassNotFoundException e) {
            restartable = false;
        }
        return restartable;
    }


    public boolean isStandAlone() {
        boolean standalone = false;
        try {
            standalone = Class.forName(STARTER_CLASSNAME) != null;
        }
        catch (ClassNotFoundException e) {
            standalone = false;
        }
        return standalone;
    }

    /**
     * Verify that the database is accessible.
     */
    private void verifyDataSource() {
        java.sql.Connection conn = null;
        try {
            conn = DbConnectionManager.getConnection();
218
            PreparedStatement stmt = conn.prepareStatement("SELECT count(*) FROM jiveID");
Matt Tucker's avatar
Matt Tucker committed
219
            ResultSet rs = stmt.executeQuery();
220
            rs.next();
Matt Tucker's avatar
Matt Tucker committed
221
            rs.close();
222
            stmt.close();
Matt Tucker's avatar
Matt Tucker committed
223 224
        }
        catch (Exception e) {
225
            System.err.println("Database setup or configuration error: " +
Matt Tucker's avatar
Matt Tucker committed
226
                    "Please verify your database settings and check the " +
Matt Tucker's avatar
Matt Tucker committed
227
                    "logs/error.log file for detailed error messages.");
Matt Tucker's avatar
Matt Tucker committed
228 229 230 231 232
            Log.error("Database could not be accessed", e);
            throw new IllegalArgumentException();
        }
        finally {
            if (conn != null) {
233 234
                try { conn.close(); }
                catch (SQLException e) { Log.error(e); }
Matt Tucker's avatar
Matt Tucker committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            }
        }
    }

    /**
     * Load plugins that are integrated with the core server.
     * <p/>
     *
     */
    private void loadCorePlugins(String[] modules) {
        for (int i = 0; i < modules.length; i++) {
            Module mod = null;
            boolean isInitialized = false;
            try {
                Class modClass = loader.loadClass(modules[i]);
                mod = (Module)modClass.newInstance();
251
                mod.initialize(this);
Matt Tucker's avatar
Matt Tucker committed
252 253 254 255
                isInitialized = true;
                this.modules.add(mod);
            }
            catch (Exception e) {
256
                e.printStackTrace();
Matt Tucker's avatar
Matt Tucker committed
257 258 259 260 261 262 263 264 265 266
                if (isInitialized) {
                    mod.stop();
                    mod.destroy();
                }
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }

    /**
Matt Tucker's avatar
Matt Tucker committed
267
     * <p>Following the loading and initialization of all the plugins
Matt Tucker's avatar
Matt Tucker committed
268 269 270 271
     * this method is called to iterate through the known modules and
     * start them.</p>
     */
    private void startCorePlugins() {
Matt Tucker's avatar
Matt Tucker committed
272
        for (Module module : modules) {
Matt Tucker's avatar
Matt Tucker committed
273 274
            boolean started = false;
            try {
Matt Tucker's avatar
Matt Tucker committed
275
                module.start();
Matt Tucker's avatar
Matt Tucker committed
276 277
            }
            catch (Exception e) {
Matt Tucker's avatar
Matt Tucker committed
278 279 280
                if (started && module != null) {
                    module.stop();
                    module.destroy();
Matt Tucker's avatar
Matt Tucker committed
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
                }
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }

    /**
     * Makes a best effort attempt to shutdown the server
     */
    private void shutdownContainer() {
        // Unregister the container first
        if (containerRegistration != null) {
            containerRegistration.cancel();
            containerRegistration = null;
        }
        // Now get all modules and stop and destroy them
        Iterator loadedModules = modules.iterator();
        while (loadedModules.hasNext()) {
            Module mod = (Module)loadedModules.next();
            mod.stop();
            mod.destroy();
        }
        modules.clear();
        // TODO: hack to allow safe stopping
        Log.info("Jive Messenger stopped");
    }

    /**
     * Loads the plugins for the container.
     *
     * @param setupMode True if starting in setup mode.
     */
    private void loadPlugins(boolean setupMode) {
Matt Tucker's avatar
Matt Tucker committed
314
        File pluginDir = new File(messengerHome + "/plugins");
Matt Tucker's avatar
Matt Tucker committed
315 316 317 318
        if (pluginDir.exists()) {
            File[] plugins = pluginDir.listFiles();
            for (int i = 0; i < plugins.length; i++) {
                if (plugins[i].isDirectory()) {
319
                    // Only load admin plugin if in setup mode.
320 321 322 323 324 325
                    if (setupMode) {
                        if ("admin".equals(plugins[i].getName())) {
                            loadPlugin(plugins[i]);
                        }
                    }
                    else {
Matt Tucker's avatar
Matt Tucker committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
                        loadPlugin(plugins[i]);
                    }
                }
            }
        }
        else {
            Log.info("startup.missing-plugins");
        }
    }

    /**
     * Loads a plug-in module into the container. Loading consists of the
     * following steps:
     * <p/>
     * <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 root directory for the plug-in
     */
    private void loadPlugin(File pluginDir) {
        Module mod = null;
        try {
            File moduleConfig = new File(pluginDir, "module.xml");
            if (moduleConfig.exists()) {
354
                XMLProperties moduleProps = new XMLProperties(moduleConfig);
Matt Tucker's avatar
Matt Tucker committed
355
                JiveModuleLoader modLoader = new JiveModuleLoader(pluginDir.toString());
356 357
                mod = modLoader.loadModule(moduleProps.getProperty("module"));
                mod.initialize(this);
Matt Tucker's avatar
Matt Tucker committed
358 359 360 361
                mod.start();
                this.modules.add(mod);
            }
            else {
Matt Tucker's avatar
Matt Tucker committed
362
                Log.warn("Plugin " + pluginDir +
Matt Tucker's avatar
Matt Tucker committed
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
                        " not loaded: no module.xml configuration file found");
            }
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
    }

    public boolean isSetupMode() {
        return setupMode;
    }

    public ServiceLookup getServiceLookup() throws UnauthorizedException {
        return lookup;
    }

    public Object startService(Class service) throws UnauthorizedException {
        Object instance = lookup.lookup(service);
        if (instance == null) {
382 383 384
            if (service.getName().equals("org.jivesoftware.messenger.user.UserManager")) {
                loadCorePlugins(new String[]{
                    "org.jivesoftware.messenger.user.spi.UserManagerImpl"});
Matt Tucker's avatar
Matt Tucker committed
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 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
                instance = lookup.lookup(service);
            }
        }
        return instance;
    }

    public void stopService(Class service) throws UnauthorizedException {
        Iterator modIter = modules.iterator();
        while (modIter.hasNext()) {
            Object mod = modIter.next();
            if (mod.getClass().isAssignableFrom(service)) {
                modIter.remove();
                ((Module)mod).stop();
                ((Module)mod).destroy();
            }
        }
    }

    public Entry getLocalServerAttribute() throws UnauthorizedException {
        return new Entry() {
        };
    }

    /**
     * <p>Restarts the container and all it's modules.</p>
     */
    public void restart() {
        if (isStandAlone() && isRestartable()) {
            try {
                Class wrapperClass = Class.forName(WRAPPER_CLASSNAME);
                Method restartMethod = wrapperClass.getMethod("restart", (Class)null);
                restartMethod.invoke(null, (Class)null);
            }
            catch (Exception e) {
                Log.error("Could not restart container", e);
            }
        }
    }

    public void stop() throws UnauthorizedException {
        // Only do a system exit if we're running standalone
        if (isStandAlone()) {
            // if we're in a wrapper, we have to tell the wrapper to shut us down
            if (isRestartable()) {
                try {
                    Class wrapperClass = Class.forName(WRAPPER_CLASSNAME);
                    Method stopMethod = wrapperClass.getMethod("stop",
                            new Class[]{Integer.TYPE});
433
                    stopMethod.invoke(null, new Object[]{0});
Matt Tucker's avatar
Matt Tucker committed
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 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 481 482 483 484 485 486
                }
                catch (Exception e) {
                    Log.error("Could not stop container", e);
                }
            }
            else {
                shutdownContainer();
                Thread shutdownThread = new ShutdownThread();
                shutdownThread.setDaemon(true);
                shutdownThread.start();
            }
        }
    }

    /**
     * <p>A thread to ensure the server shuts down no matter what.</p>
     * <p>Spawned when stop() is called in standalone mode, we wait a few
     * seconds then call system exit().</p>
     *
     * @author Iain Shigeoka
     */
    private class ShutdownThread extends Thread {
        /**
         * <p>Shuts down the JVM after a 5 second delay.</p>
         */
        public void run() {
            try {
                Thread.sleep(5000);
                // No matter what, we make sure it's dead
                System.exit(0);
            }
            catch (InterruptedException e) {
            }

        }
    }

    /**
     * <p>A thread to ensure the server shuts down no matter what.</p>
     * <p>Spawned when stop() is called in standalone mode, we wait a few
     * seconds then call system exit().</p>
     *
     * @author Iain Shigeoka
     */
    private class ShutdownHookThread extends Thread {
        /**
         * <p>Logs the server shutdown.</p>
         */
        public void run() {
            if (containerRegistration != null) {
                shutdownContainer();
            }
            Log.info("Server halted");
487
            System.err.println("Server halted");
Matt Tucker's avatar
Matt Tucker committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        }
    }

    /**
     * Verifies that the given home guess is a real Messenger home directory.
     * We do the verification by checking for the Messenger config file in
     * the config dir of jiveHome.
     *
     * @param homeGuess      a guess at the path to the home directory.
     * @param jiveConfigName the name of the config file to check.
     * @return a file pointing to the home directory or null if the
     *         home directory guess was wrong.
     * @throws FileNotFoundException if there was a problem with the home
     *                               directory provided
     */
503
    private File verifyHome(String homeGuess, String jiveConfigName) throws FileNotFoundException {
Matt Tucker's avatar
Matt Tucker committed
504 505 506 507 508 509
        File realHome = null;
        File guess = new File(homeGuess);
        File configFileGuess = new File(guess, jiveConfigName);
        if (configFileGuess.exists()) {
            realHome = guess;
        }
510 511
        File forumsHome = new File(guess, jiveConfigName);
        if (!forumsHome.exists()) {
Matt Tucker's avatar
Matt Tucker committed
512 513
            throw new FileNotFoundException();
        }
514 515 516 517 518 519 520

        try{
            return new File(realHome.getCanonicalPath());
        }
        catch(Exception ex){
           throw new FileNotFoundException();
        }
Matt Tucker's avatar
Matt Tucker committed
521 522 523 524 525 526 527
    }

    /**
     * <p>Retrieve the jive home for the container.</p>
     *
     * @throws FileNotFoundException If jiveHome could not be located
     */
528
    private void locateMessenger() throws FileNotFoundException {
Matt Tucker's avatar
Matt Tucker committed
529
        String jiveConfigName = "conf" + File.separator + "jive-messenger.xml";
Matt Tucker's avatar
Matt Tucker committed
530
        // First, try to load it jiveHome as a system property.
Matt Tucker's avatar
Matt Tucker committed
531 532
        if (messengerHome == null) {
            String homeProperty = System.getProperty("messengerHome");
Matt Tucker's avatar
Matt Tucker committed
533 534
            try {
                if (homeProperty != null) {
Matt Tucker's avatar
Matt Tucker committed
535
                    messengerHome = verifyHome(homeProperty, jiveConfigName);
Matt Tucker's avatar
Matt Tucker committed
536 537 538
                }
            }
            catch (FileNotFoundException fe) {
Matt Tucker's avatar
Matt Tucker committed
539

Matt Tucker's avatar
Matt Tucker committed
540 541 542
            }
        }

543 544
        // If we still don't have messengerHome, let's assume this is standalone
        // and just look for messengerHome in a standard sub-dir location and verify
Matt Tucker's avatar
Matt Tucker committed
545
        // by looking for the config file
Matt Tucker's avatar
Matt Tucker committed
546
        if (messengerHome == null) {
Matt Tucker's avatar
Matt Tucker committed
547
            try {
Matt Tucker's avatar
Matt Tucker committed
548
                messengerHome = verifyHome("..", jiveConfigName).getCanonicalFile();
Matt Tucker's avatar
Matt Tucker committed
549 550 551
            }
            catch (FileNotFoundException fe) {
            }
Matt Tucker's avatar
Matt Tucker committed
552 553
            catch (IOException ie) {
            }
Matt Tucker's avatar
Matt Tucker committed
554 555
        }

Matt Tucker's avatar
Matt Tucker committed
556 557
        // If messengerHome is still null, no outside process has set it and
        // we have to attempt to load the value from messenger_init.xml,
Matt Tucker's avatar
Matt Tucker committed
558
        // which must be in the classpath.
Matt Tucker's avatar
Matt Tucker committed
559
        if (messengerHome == null) {
Matt Tucker's avatar
Matt Tucker committed
560 561
            InputStream in = null;
            try {
Matt Tucker's avatar
Matt Tucker committed
562
                in = getClass().getResourceAsStream("/messenger_init.xml");
Matt Tucker's avatar
Matt Tucker committed
563 564 565 566 567 568
                if (in != null) {
                    Document doc = XPPReader.parseDocument(new InputStreamReader(in),
                            this.getClass());
                    String path = doc.getRootElement().getText();
                    try {
                        if (path != null) {
Matt Tucker's avatar
Matt Tucker committed
569
                            messengerHome = verifyHome(path,
Matt Tucker's avatar
Matt Tucker committed
570 571 572 573
                                    jiveConfigName);
                        }
                    }
                    catch (FileNotFoundException fe) {
Matt Tucker's avatar
Matt Tucker committed
574
                        fe.printStackTrace();
Matt Tucker's avatar
Matt Tucker committed
575 576 577 578
                    }
                }
            }
            catch (Exception e) {
Matt Tucker's avatar
Matt Tucker committed
579
                System.err.println("Error loading messenger_init.xml to find messengerHome.");
Matt Tucker's avatar
Matt Tucker committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
                e.printStackTrace();
            }
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                }
                catch (Exception e) {
                    System.err.println("Could not close open connection");
                    e.printStackTrace();
                }
            }
        }

Matt Tucker's avatar
Matt Tucker committed
595 596
        if (messengerHome == null) {
            System.err.println("Could not locate messengerHome");
Matt Tucker's avatar
Matt Tucker committed
597 598 599
            throw new FileNotFoundException();
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
600
            JiveGlobals.messengerHome = messengerHome.toString();
Matt Tucker's avatar
Matt Tucker committed
601 602 603
        }
    }
}