Search in sources :

Example 1 with BridgeServiceManager

use of com.sun.messaging.bridge.api.BridgeServiceManager in project openmq by eclipse-ee4j.

the class BrokerStateHandler method prepareShutdown.

private void prepareShutdown(boolean failover, boolean force, BrokerAddress excludedBroker) {
    // prepared = true;
    BridgeServiceManager bridgeManager = Globals.getBridgeServiceManager();
    if (bridgeManager != null) {
        try {
            Globals.getLogger().log(Logger.INFO, Globals.getBrokerResources().I_STOP_BRIDGE_SERVICE_MANAGER);
            bridgeManager.stop();
            Globals.setBridgeServiceManager(null);
            Globals.getLogger().log(Logger.INFO, Globals.getBrokerResources().I_STOPPED_BRIDGE_SERVICE_MANAGER);
        } catch (Throwable t) {
            logger.logStack(Logger.WARNING, Globals.getBrokerResources().W_STOP_BRIDGE_SERVICE_MANAGER_FAILED, t);
        }
    }
    if (Globals.getMemManager() != null) {
        Globals.getMemManager().stopManagement();
    }
    // First stop creating new destinations
    if (excludedBroker == null) {
        Globals.getDestinationList().shutdown();
    }
    // Next, close all the connections with clustered brokers
    // so that we don't get stuck processing remote events..
    // XXX - tell cluster whether or not failover should happen
    Globals.getClusterBroadcast().stopClusterIO(failover, force, excludedBroker);
}
Also used : BridgeServiceManager(com.sun.messaging.bridge.api.BridgeServiceManager)

Example 2 with BridgeServiceManager

use of com.sun.messaging.bridge.api.BridgeServiceManager in project openmq by eclipse-ee4j.

the class Broker method exitBroker.

/**
 * @param exitVM whether to exit VM If false, System.exit() is performed.
 */
private void exitBroker(int status, String reason, BrokerEvent.Type type, Throwable thr, boolean triggerFailover, boolean exitVM) {
    Globals.getLogger().log(Logger.DEBUG, "Broker exiting with status=" + status + " because " + reason);
    BridgeServiceManager bridgeManager = Globals.getBridgeServiceManager();
    if (bridgeManager != null && !Globals.isNucleusManagedBroker()) {
        try {
            Globals.getLogger().log(Logger.INFO, Globals.getBrokerResources().I_STOP_BRIDGE_SERVICE_MANAGER);
            bridgeManager.stop();
            Globals.setBridgeServiceManager(null);
            Globals.getLogger().log(Logger.INFO, Globals.getBrokerResources().I_STOPPED_BRIDGE_SERVICE_MANAGER);
        } catch (Throwable t) {
            logger.logStack(Logger.WARNING, Globals.getBrokerResources().W_STOP_BRIDGE_SERVICE_MANAGER_FAILED, t);
        }
    }
    // take a copy of bkrEvtListener as we may null it during the course of this method
    BrokerEventListener tempListener = bkrEvtListener;
    if (bkrEvtListener != null) {
        BrokerEvent event = new BrokerEvent(this, type, reason);
        bkrEvtListener.exitRequested(event, thr);
    }
    // Perform an orderly broker shutdown unless we're in-process,
    // or are going to halt, in which case we want to exit as quickly as possible
    destroyBroker(!exitVM, triggerFailover);
    if (exitVM) {
        if (shutdownHook != null) {
            shutdownHook.setTriggerFailover(triggerFailover);
        }
        System.exit(status);
    }
    // if we're still here we didn't exit the broker
    if (type == BrokerEvent.Type.RESTART) {
        // don't attempt to restart an embedded broker
        if (!runningInProcess) {
            // we want to restart, so tell the listener
            if (tempListener != null) {
                BrokerEvent event = new BrokerEvent(this, type, "Broker restart");
                tempListener.brokerEvent(event);
            }
        }
    }
}
Also used : BrokerEvent(com.sun.messaging.jmq.jmsservice.BrokerEvent) BridgeServiceManager(com.sun.messaging.bridge.api.BridgeServiceManager) BrokerEventListener(com.sun.messaging.jmq.jmsservice.BrokerEventListener)

Example 3 with BridgeServiceManager

use of com.sun.messaging.bridge.api.BridgeServiceManager in project openmq by eclipse-ee4j.

the class Broker method _start.

private int _start(boolean inProcess, Properties propsFromCommandLine, boolean initOnly, Throwable failStartThrowable) throws OutOfMemoryError, IllegalStateException, IllegalArgumentException {
    try {
        setIsInProcess(inProcess);
        // initialize the Global properties if any arguments are passed in
        // read properties (including passwords) from standard input (used when the broker is managed by JMSRA)
        Properties propsFromStdin = null;
        if (propsFromCommandLine != null && propsFromCommandLine.containsKey(Globals.IMQ + ".readstdin.enabled")) {
            propsFromStdin = readPropertiesFromStandardInput();
        }
        // Combine any properties specified using command-line parameters with any properties read from standard input
        // The properties loaded from standard input have precedence and so are loaded second
        Properties combinedProps = new Properties();
        if (propsFromCommandLine != null) {
            combinedProps.putAll(propsFromCommandLine);
        }
        if (propsFromStdin != null) {
            combinedProps.putAll(propsFromStdin);
        }
        Globals.init(combinedProps, clearProps, saveProps);
        if (!removeInstance) {
            BrokerStateHandler.setShuttingDown(false);
            BrokerStateHandler.setShutdownStarted(false);
        }
        haltLogString = Globals.getBrokerResources().getKString(BrokerResources.W_HALT_BROKER);
        logger = Globals.getLogger();
        String configdir = Globals.getInstanceDir();
        File f = new File(configdir);
        // 
        if (!f.exists()) {
            // check parent directory
            while (!f.exists()) {
                // loop up looking for the parent
                f = f.getParentFile();
                if (f == null) {
                    // now where else to go
                    break;
                }
                if (!f.exists()) {
                    continue;
                }
                if (!f.canWrite() || !f.canRead()) {
                    String emsg = rb.getKString(rb.E_CAN_NOT_WRITE, f, Globals.getConfigName());
                    if (!silent) {
                        printErr(emsg);
                    }
                    if (failStartThrowable != null) {
                        failStartThrowable.initCause(new Exception(emsg));
                    }
                    return (BrokerExitCode.NO_PERMISSION_ON_INSTANCE);
                }
            }
        } else if (!f.canWrite() || !f.canRead()) {
            String emsg = rb.getKString(rb.E_CAN_NOT_WRITE, f, Globals.getConfigName());
            if (!silent) {
                System.err.println(emsg);
            }
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception(emsg));
            }
            return (BrokerExitCode.NO_PERMISSION_ON_INSTANCE);
        }
        // OF CREATING AN INSTANCE BEFORE THIS CHECK
        if (removeInstance) {
            removeInstance();
        }
        // if a password file is specified, read it
        try {
            parsePassfile();
        } catch (IOException ex) {
            logger.log(Logger.FORCE, rb.E_OPTION_VALID_ERROR, ex);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(ex);
            }
            return (1);
        }
        // Initialize any possible debug settings
        try {
            com.sun.messaging.jmq.util.Debug.setDebug(Globals.getConfig(), Globals.IMQ + ".debug.");
        } catch (Exception e) {
            logger.log(Logger.WARNING, rb.W_BAD_DEBUG_CLASS, e);
        }
        // Initialize any diag settings
        try {
            com.sun.messaging.jmq.util.DiagManager.registerClasses(Globals.getConfig(), Globals.IMQ + ".diag.");
        } catch (Exception e) {
            logger.log(Logger.WARNING, rb.W_BAD_DIAG_CLASS, e);
        }
        BrokerConfig conf = Globals.getConfig();
        try {
            checkBrokerConfig(conf);
        } catch (Exception e) {
            logger.logToAll(logger.ERROR, e.getMessage());
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return 1;
        }
        if (!Globals.isJMSRAManagedSpecified() && Globals.isJMSRAManagedBroker()) {
            String emsg = Globals.getBrokerResources().getKString(BrokerResources.E_START_JMSRA_MANAGED_BROKER_NONMANAGED);
            logger.log(Logger.ERROR, emsg);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception(emsg));
            }
            return (1);
        }
        if (Globals.isJMSRAManagedBroker()) {
            try {
                conf.updateBooleanProperty(Globals.JMSRA_MANAGED_PROPERTY, true, true);
            } catch (Exception e) {
                logger.logStack(Logger.ERROR, Globals.getBrokerResources().getKString(BrokerResources.E_SET_BROKER_CONFIG_PROPERTY, Globals.JMSRA_MANAGED_PROPERTY + "=true", e.getMessage()), e);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(e);
                }
                return (1);
            }
        }
        CoreLifecycleSpi coreLifecycle = Globals.getCoreLifecycle();
        String banner = version.getBanner(false, Version.MINI_COPYRIGHT) + rb.getString(rb.I_JAVA_VERSION) + System.getProperty("java.version") + " " + System.getProperty("java.vendor") + " " + System.getProperty("java.home");
        logger.logToAll(Logger.INFO, rb.NL + banner);
        // Check to see if we have a version mismatch
        if (!version.isProductValid()) {
            // not valid - display an error
            // 
            String emsg = rb.getKString(BrokerResources.E_INVALID_PRODUCT_VERSION);
            logger.log(Logger.ERROR, emsg);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception(emsg));
            }
            return (1);
        }
        try {
            initializePasswdFile();
        } catch (IOException ex) {
            if (failStartThrowable != null) {
                failStartThrowable.initCause(ex);
            }
            return (1);
        }
        if (initOnly) {
            logger.log(Logger.INFO, BrokerResources.I_INIT_DONE);
            return 0;
        }
        try {
            AccessController.setSecurityManagerIfneed();
        } catch (Exception e) {
            logger.logStack(Logger.ERROR, e.getMessage(), e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return (1);
        }
        if (!MQAuthenticator.authenticateCMDUserIfset()) {
            logger.log(Logger.INFO, BrokerResources.I_SHUTDOWN_BROKER);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception("MQAuthenticator failed"));
            }
            return (1);
        }
        // For printing out VM heap info
        DiagManager.register(new VMDiagnostics());
        if (Version.compareVersions(System.getProperty("java.specification.version"), MIN_JAVA_VERSION, true) < 0) {
            String emsg = rb.getKString(rb.E_BAD_JAVA_VERSION, System.getProperty("java.specification.version"), MIN_JAVA_VERSION);
            logger.logToAll(Logger.ERROR, emsg);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception(emsg));
            }
            return (1);
        }
        String hostname = conf.getProperty(Globals.IMQ + ".hostname");
        // Save value of imq.hostname. This may be null which is OK
        Globals.setHostname(hostname);
        /*
             * In a variety of places we need to know the name of the host the broker is running on, and its IP address. Typically
             * you get this by calling getLocalHost(). But if the broker is running on a multihomed machine, you may want to control
             * which interface (and IP address) the broker uses. Therefore we support the imq.hostname property to let the user
             * configure this.
             */
        if (hostname == null || hostname.equals(Globals.HOSTNAME_ALL)) {
            // No hostname specified. Get local host
            try {
                InetAddress ia = InetAddress.getLocalHost();
                Globals.setBrokerInetAddress(ia);
            } catch (UnknownHostException e) {
                logger.log(Logger.ERROR, rb.E_NO_LOCALHOST, e);
                logger.log(Logger.INFO, rb.M_BROKER_EXITING);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(e);
                }
                return (1);
            }
        } else {
            // machine. Look up the address now so we have its IP
            try {
                InetAddress ia = InetAddress.getByName(hostname);
                Globals.setBrokerInetAddress(ia);
            } catch (UnknownHostException e) {
                logger.log(Logger.ERROR, rb.getString(rb.E_BAD_HOSTNAME_PROP, hostname, Globals.IMQ + ".hostname"), e);
                logger.log(Logger.INFO, rb.M_BROKER_EXITING);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(e);
                }
                return (1);
            }
        }
        /*
             * Do the same thing for JMX hostname. On a multihome system, we may want to designate different IP addresses for the
             * broker and for JMX traffic. A new property imq.jmx.hostname is created for this. By default, it will be set to
             * whatever value imq.hostname is set to.
             */
        String jmxHostname = conf.getProperty(Globals.IMQ + ".jmx.hostname");
        // Save value of imq.jmx.hostname. This may be null which is OK
        Globals.setJMXHostname(jmxHostname);
        /*
             * Only check for the case where the JMX hostname is specified. If it is not, it will default to whatever value is
             * configured for the broker hostname (imq.hostname).
             */
        if (jmxHostname != null && !jmxHostname.equals(Globals.HOSTNAME_ALL)) {
            // machine. Look up the address now so we have its IP
            try {
                InetAddress ia = InetAddress.getByName(jmxHostname);
                Globals.setJMXInetAddress(ia);
            } catch (UnknownHostException e) {
                logger.log(Logger.ERROR, rb.getString(rb.E_BAD_HOSTNAME_PROP, hostname, Globals.IMQ + ".jmx.hostname"), e);
                logger.log(Logger.INFO, rb.M_BROKER_EXITING);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(e);
                }
                return (1);
            }
        }
        try {
            logger.logToAll(Logger.INFO, "   IMQ_HOME=" + new File(Globals.getJMQ_HOME()).getCanonicalPath());
            logger.logToAll(Logger.INFO, "IMQ_VARHOME=" + new File(Globals.getJMQ_VAR_HOME()).getCanonicalPath());
        } catch (IOException e) {
        }
        logger.logToAll(Logger.INFO, System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + " " + Globals.getBrokerHostName() + " " + "(" + Runtime.getRuntime().availableProcessors() + " cpu) " + System.getProperty("user.name"));
        try {
            // Log ulimit -n values
            Rlimit.Limits limits = Rlimit.get(Rlimit.RLIMIT_NOFILE);
            logger.logToAll(Logger.INFO, rb.getString(rb.I_NOFILES), ((limits.current == Rlimit.RLIM_INFINITY) ? "unlimited" : String.valueOf(limits.current)), ((limits.maximum == Rlimit.RLIM_INFINITY) ? "unlimited" : String.valueOf(limits.maximum)));
        } catch (Exception e) {
        // This is OK. It just means we can't log ulimit values on
        // this platform.
        }
        // Log JVM heap size information
        logger.logToAll(Logger.INFO, rb.getString(rb.I_JAVA_HEAP), Long.toString(Runtime.getRuntime().maxMemory() / 1024), Long.toString(Runtime.getRuntime().totalMemory() / 1024));
        // Start of logging of the various sets of properties that have been supplied in various ways
        // log the actual broker command-line arguments
        logger.logToAll(Logger.INFO, rb.getString(rb.I_BROKER_ARGS), (propsFromCommandLine == null ? "" : propsFromCommandLine.get("BrokerArgs")));
        // if the broker is non-embedded and started by JMSRA
        // log any properties read from standard input
        logProperties("JMSRA BrokerProps: ", propsFromStdin);
        // log any properties supplied programmatically
        if (embeddedBrokerStartupMessages != null) {
            for (String thisMessage : embeddedBrokerStartupMessages) {
                // Log the embeddedBrokerStartupMessages here
                // These are typically used to log broker properties configured on an embedded broker
                // which is why we perform this logging at this point.
                // However they can also be used to log other information passed by the code that started the embedded broker
                logger.logToAll(Logger.INFO, thisMessage);
            }
        }
        // log all properties specified on the command line either explicity or via command-line arguments
        logProperties(rb.getString(rb.I_BROKER_PROPERTIES), propsFromCommandLine);
        if (inProcess) {
            logger.logToAll(Logger.INFO, rb.getString(rb.I_INPROCESS_BROKER));
        }
        // set up out of memory handler
        Globals.setGlobalErrorHandler(this);
        // Get admin key from the key file if any. This is only used by
        // the nt service to handle shutdown.
        String key = getAdminKey(adminKeyFile);
        String propname = Globals.IMQ + ".adminkey";
        if (key == null || key.length() == 0) {
            // Make sure property is not set
            conf.remove(propname);
        } else {
            try {
                conf.updateProperty(propname, key);
            } catch (Exception e) {
            }
        }
        /*
             * Hawk HA : retrieve ha properties and brokerid
             */
        boolean isHA = Globals.getHAEnabled();
        String brokerid = Globals.getBrokerID();
        String clusterid = Globals.getClusterID();
        if (Globals.getHAEnabled()) {
            if (brokerid == null) {
                String emsg = rb.getKString(rb.E_BID_MUST_BE_SET);
                logger.logToAll(Logger.ERROR, emsg);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(new Exception(emsg));
                }
                return (1);
            }
            logger.log(Logger.INFO, BrokerResources.I_RUNNING_IN_HA, brokerid, clusterid);
        } else if (brokerid != null) {
            logger.log(Logger.INFO, BrokerResources.I_STARTING_WITH_BID, brokerid);
        }
        PortMapper pm = Globals.getPortMapper();
        if (pm == null || (pm.getServerSocket() == null && pm.isDoBind() && Globals.getPUService() == null)) {
            // PortMapper failed to bind to port. Port is probably already
            // in use. An error message has already been logged so just exit
            String emsg = rb.getString(rb.E_PORTMAPPER_START);
            logger.logToAll(logger.ERROR, emsg);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception(emsg));
            }
            return (1);
        }
        /*
             * Store MQAddress in Globals so it can be accessed when needed One place this is used is the "brokerAddress" property
             * of monitoring messages.
             */
        MQAddress addr = null;
        try {
            addr = BrokerMQAddress.createAddress(Globals.getBrokerHostName(), pm.getPort());
        } catch (Exception e) {
            logger.logStack(Logger.INFO, BrokerResources.E_CANNOT_CREATE_MQADDRESS, "[" + Globals.getBrokerHostName() + "]:" + pm.getPort(), e);
        }
        boolean NO_CLUSTER;
        try {
            NO_CLUSTER = Globals.initClusterManager(addr);
            if (NO_CLUSTER) {
                logger.log(Logger.WARNING, BrokerResources.I_USING_NOCLUSTER);
            }
        } catch (Exception e) {
            logger.logStack(Logger.ERROR, BrokerResources.E_INITING_CLUSTER, e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return (1);
        }
        if (Globals.useMasterBroker() && Globals.dynamicChangeMasterBrokerEnabled() && !Globals.isJMSRAManagedBroker()) {
            if (Globals.isMasterBrokerSpecified()) {
                String emsg = Globals.getBrokerResources().getKString(BrokerResources.X_CLUSTER_NO_CMDLINE_MASTERBROKER_WHEN_DYNAMIC, ClusterManager.CONFIG_SERVER, Globals.DYNAMIC_CHANGE_MASTERBROKER_ENABLED_PROP + "=true");
                logger.log(Logger.ERROR, emsg);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(new Exception(emsg));
                }
                return (1);
            }
        }
        pm.updateProperties();
        if (pm.isDoBind()) {
            if (Globals.getPUService() == null) {
                // start the PortMapper thread
                Thread portMapperThread = new MQThread(pm, "JMQPortMapper");
                portMapperThread.setDaemon(true);
                portMapperThread.start();
            } else {
                try {
                    pm.startPUService();
                } catch (Exception e) {
                    logger.logStack(logger.ERROR, e.getMessage(), e);
                    if (failStartThrowable != null) {
                        failStartThrowable.initCause(e);
                    }
                    return (1);
                }
            }
        }
        // Try to acquire the lock file. This makes sure no other copy
        // of the broker is running in the same instance directory as
        // we are.
        LockFile lf = null;
        try {
            lf = LockFile.getLock(conf.getProperty(Globals.JMQ_VAR_HOME_PROPERTY), Globals.getConfigName(), (pm.getHostname() == null || pm.getHostname().equals("") ? Globals.getMQAddress().getHostName() : pm.getMQAddress().getHostName()), pm.getPort(), Globals.getUseFileLockForLockFile());
        } catch (Exception e) {
            Object[] msgargs = { LockFile.getLockFilePath(conf.getProperty(Globals.JMQ_VAR_HOME_PROPERTY), Globals.getConfigName()), e.toString(), Globals.getConfigName() };
            logger.logStack(Logger.ERROR, rb.E_LOCKFILE_EXCEPTION, msgargs, e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return (1);
        }
        // Make sure we got the lock
        if (!lf.isMyLock()) {
            Object[] msgargs = { lf.getFilePath(), lf.getHost() + ":" + lf.getPort(), Globals.getConfigName() };
            String emsg = rb.getKString(rb.E_LOCKFILE_INUSE, msgargs);
            logger.log(Logger.ERROR, emsg);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(new Exception(emsg));
            }
            return (1);
        }
        // audit logging for reset store
        if (resetStore) {
            Globals.getAuditSession().storeOperation(null, null, MQAuditSession.RESET_STORE);
            if (isHA) {
                logger.log(Logger.WARNING, BrokerResources.W_HA_NO_RESET);
            }
        }
        // interests to destinations
        try {
            // logging
            Globals.isMinimumPersist();
            store = Globals.getStore();
        } catch (BrokerException ex) {
            logger.logStack(Logger.ERROR, BrokerResources.E_PERSISTENT_OPEN, ex);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(ex);
            }
            return (1);
        }
        if (Globals.useSharedConfigRecord()) {
            try {
                Globals.getStore().getShareConfigChangeStore();
            } catch (BrokerException ex) {
                logger.logStack(Logger.ERROR, BrokerResources.E_SHARECC_STORE_OPEN, ex);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(ex);
                }
                return (1);
            }
        }
        BridgeServiceManager bridgeManager = null;
        if (BridgeBaseContextAdapter.bridgeEnabled() && !Globals.isNucleusManagedBroker()) {
            logger.log(Logger.INFO, BrokerResources.I_INIT_BRIDGE_SERVICE_MANAGER);
            try {
                Class c = Class.forName(BridgeBaseContextAdapter.getManagerClass());
                bridgeManager = (BridgeServiceManager) c.getDeclaredConstructor().newInstance();
                bridgeManager.init(new BridgeBaseContextAdapter(this, resetStore));
            } catch (Throwable t) {
                bridgeManager = null;
                logger.logStack(Logger.WARNING, Globals.getBrokerResources().getKString(BrokerResources.W_INIT_BRIDGE_SERVICE_MANAGER_FAILED), t);
            }
        }
        HAMonitorService haMonitor = null;
        if (Globals.getHAEnabled()) {
            try {
                String cname = "com.sun.messaging.jmq.jmsserver" + ".cluster.manager.ha.HAMonitorServiceImpl";
                if (Globals.getHAEnabled()) {
                    logger.log(Logger.INFO, BrokerResources.I_STARTING_MONITOR);
                    if (Globals.isNucleusManagedBroker()) {
                        haMonitor = Globals.getHabitat().getService(HAMonitorService.class, cname);
                        if (haMonitor == null) {
                            throw new BrokerException("Class " + cname + " not found");
                        }
                        haMonitor.init(Globals.getClusterID(), Globals.getMQAddress(), resetTakeoverThenExit);
                    } else {
                        Class c = Class.forName(cname);
                        Class[] paramTypes = { String.class, MQAddress.class, Boolean.class };
                        Object[] paramArgs = { Globals.getClusterID(), Globals.getMQAddress(), Boolean.valueOf(resetTakeoverThenExit) };
                        Constructor cons = c.getConstructor(paramTypes);
                        haMonitor = (HAMonitorService) cons.newInstance(paramArgs);
                    }
                    if (resetTakeoverThenExit) {
                        return (0);
                    }
                } else {
                    if (Globals.isNucleusManagedBroker()) {
                        haMonitor = Globals.getHabitat().getService(HAMonitorService.class, cname);
                        if (haMonitor == null) {
                            throw new BrokerException("Class " + cname + " not found");
                        }
                    } else {
                        Class c = Class.forName(cname);
                        haMonitor = (HAMonitorService) c.getDeclaredConstructor().newInstance();
                    }
                }
                Globals.setHAMonitorService(haMonitor);
            } catch (Exception ex) {
                logger.logStack(Logger.ERROR, BrokerResources.E_ERROR_STARTING_MONITOR, ex);
                if (ex instanceof StoreBeingTakenOverException) {
                    if (failStartThrowable != null) {
                        failStartThrowable.initCause(ex);
                    }
                    return (BrokerStateHandler.getRestartCode());
                }
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(ex);
                }
                return (1);
            }
            if (Globals.getHAEnabled()) {
                logger.log(Logger.INFO, BrokerResources.I_STARTING_HEARTBEAT);
                try {
                    Class c = Class.forName("com.sun.messaging.jmq.jmsserver" + ".multibroker.heartbeat.HeartbeatService");
                    Object hbs = c.getDeclaredConstructor().newInstance();
                    Globals.registerHeartbeatService(hbs);
                } catch (Exception e) {
                    logger.logStack(Logger.ERROR, BrokerResources.E_ERROR_STARTING_HB, e);
                    if (failStartThrowable != null) {
                        failStartThrowable.initCause(e);
                    }
                    return (1);
                }
            }
        }
        try {
            store.addPartitionListener(Globals.getClusterManager());
            store.partitionsReady();
        } catch (Exception e) {
            logger.logStack(Logger.ERROR, e.getMessage(), e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return (1);
        }
        if (NO_CLUSTER) {
            mbus = new com.sun.messaging.jmq.jmsserver.cluster.api.NoCluster();
            logger.log(Logger.FORCE, Globals.getBrokerResources().getKString(BrokerResources.I_FEATURE_UNAVAILABLE, Globals.getBrokerResources().getString(BrokerResources.M_CLUSTER_SERVICE_FEATURE)));
        } else {
            try {
                String cname = CLUSTER_BROADCASTER_SERVICE_NAME;
                if (Globals.isNucleusManagedBroker()) {
                    mbus = Globals.getHabitat().getService(ClusterBroadcast.class, cname);
                    if (mbus == null) {
                        String emsg = "Failed to init cluster service because class " + cname + " not found";
                        if (Globals.getHAEnabled() || Globals.getClusterManager().getConfigBrokerCount() > 0) {
                            logger.log(Logger.ERROR, emsg);
                            if (failStartThrowable != null) {
                                failStartThrowable.initCause(new Exception(emsg));
                            }
                            return (1);
                        } else {
                            throw new BrokerException(emsg);
                        }
                    }
                    mbus.init(DEFAULT_CLUSTER_VERSION);
                } else {
                    Class c = Class.forName(cname);
                    Class[] paramTypes = { Integer.class };
                    Constructor cons = c.getConstructor(paramTypes);
                    Object[] paramArgs = { Integer.valueOf(DEFAULT_CLUSTER_VERSION) };
                    mbus = (ClusterBroadcast) cons.newInstance(paramArgs);
                }
            } catch (ClassNotFoundException cnfe) {
                logger.logStack(Logger.DEBUG, BrokerResources.E_INTERNAL_BROKER_ERROR, "unable to use cluster broadcaster", cnfe);
                logger.log(Logger.WARNING, BrokerResources.I_USING_NOCLUSTER + ": " + cnfe);
                mbus = new com.sun.messaging.jmq.jmsserver.cluster.api.NoCluster();
            } catch (InvocationTargetException ite) {
                Throwable ex = ite.getCause();
                if (ex instanceof InvocationTargetException) {
                    ex = ex.getCause();
                }
                if (!(ex instanceof LoopbackAddressException)) {
                    logger.logStack(Logger.INFO, BrokerResources.X_INTERNAL_EXCEPTION, ex.getMessage(), ex);
                }
                logger.log(Logger.WARNING, BrokerResources.I_USING_NOCLUSTER);
                mbus = new com.sun.messaging.jmq.jmsserver.cluster.api.NoCluster();
            } catch (Exception ex) {
                logger.logStack(Logger.WARNING, "Unable to use cluster broadcaster", ex);
                logger.log(Logger.WARNING, BrokerResources.I_USING_NOCLUSTER);
                mbus = new com.sun.messaging.jmq.jmsserver.cluster.api.NoCluster();
            }
        }
        Globals.setClusterBroadcast(mbus);
        Globals.setMyAddress(mbus.getMyAddress());
        /*
             * HANDLE LDAP PROPERTIES XXX - this is not the cleanest way to handle this technically it should be better integrated
             * with the authentication interfaces ... but I'm close to code freeze XXX-REVISIT racer 4/10/02
             */
        String type = Globals.getConfig().getProperty(AccessController.PROP_AUTHENTICATION_TYPE);
        if (type != null) {
            String userrep = Globals.getConfig().getProperty(AccessController.PROP_AUTHENTICATION_PREFIX + type + AccessController.PROP_USER_REPOSITORY_SUFFIX);
            if (userrep.equals("ldap")) {
                String DN = Globals.getConfig().getProperty(AccessController.PROP_USER_REPOSITORY_PREFIX + userrep + ".principal");
                String pwd = Globals.getConfig().getProperty(AccessController.PROP_USER_REPOSITORY_PREFIX + userrep + ".password");
                if (DN != null && DN.trim().length() > 0) {
                    // we have a DN
                    if (pwd == null || pwd.trim().length() == 0) {
                        int retry = 0;
                        Password pw = null;
                        boolean setProp = pwd == null || pwd.equals("");
                        while ((pwd == null || pwd.trim().equals("")) && retry < 5) {
                            pw = new Password();
                            if (pw.echoPassword()) {
                                System.err.println(Globals.getBrokerResources().getString(BrokerResources.W_ECHO_PASSWORD));
                            }
                            System.err.print(Globals.getBrokerResources().getString(BrokerResources.M_ENTER_KEY_LDAP, DN));
                            System.err.flush();
                            pwd = pw.getPassword();
                            // Limit the number of times we try
                            // reading the passwd.
                            // If the VM is run in the background
                            // the readLine()
                            // will always return null and
                            // we'd get stuck in the loop
                            retry++;
                        }
                        if (pwd == null || pwd.trim().equals("")) {
                            logger.log(Logger.WARNING, BrokerResources.W_NO_LDAP_PASSWD, pwd);
                            Globals.getConfig().put(AccessController.PROP_USER_REPOSITORY_PREFIX + userrep + ".principal", "");
                        } else if (setProp) {
                            Globals.getConfig().put(AccessController.PROP_USER_REPOSITORY_PREFIX + userrep + ".password", pwd);
                        }
                    }
                }
            }
        }
        ConnectionManager cmgr = new ConnectionManager();
        Globals.setConnectionManager(cmgr);
        // get the persisted data
        try {
            coreLifecycle.getDestinationList().addPartitionListener(Globals.getClusterManager());
            coreLifecycle.initDestinations();
            coreLifecycle.initSubscriptions();
            BrokerMonitor.init();
        } catch (BrokerException ex) {
            logger.logStack(Logger.ERROR, BrokerResources.E_UNABLE_TO_RETRIEVE_DATA, ex);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(ex);
            }
            return 1;
        }
        // Initialize the JMX Agent
        try {
            Class.forName("javax.management.MBeanServer");
            Agent agent = new Agent();
            Globals.setAgent(agent);
            agent.start();
        } catch (Exception e) {
            logger.log(Logger.WARNING, "JMX classes not present - JMX Agent is not created.");
        }
        /*
             * Check if we should support old (pre 3.0.1SP2) selector type conversions (which violated the JMS spec).
             */
        Selector.setConvertTypes(conf.getBooleanProperty(Globals.IMQ + ".selector.convertTypes", false));
        /*
             * By default the selector code short circuits boolean expression evaluation. This is a back door to disable that in
             * case there is a flaw in the implementation.
             */
        Selector.setShortCircuit(conf.getBooleanProperty(Globals.IMQ + ".selector.shortCircuit", true));
        /*
             * When shortCircuit is true, by default at selector compile time do additional test for shortCircuit
             */
        Selector.setShortCircuitCompileTimeTest(conf.getBooleanProperty(Globals.IMQ + ".selector.shortCircuitCompileTimeTest", true));
        // create the handlers - these handle the message processing
        pktrtr = new PacketRouter();
        // set up the admin packet router
        admin_pktrtr = new PacketRouter();
        AdminDataHandler admin_datahdrl = new AdminDataHandler();
        Globals.setProtocol(new ProtocolImpl(pktrtr));
        try {
            coreLifecycle.initHandlers(pktrtr, cmgr, admin_pktrtr, admin_datahdrl);
        } catch (Exception e) {
            logger.logStack(Logger.ERROR, e.getMessage(), e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return 1;
        }
        try {
            PacketRouter pkr = new PacketRouter();
            CoreLifecycleSpi clc = Globals.getCorePlugin(CoreLifecycleSpi.CHMP);
            if (clc != null) {
                Class.forName("com.oracle.coherence.patterns.messaging.DefaultMessagingSession");
                clc.initHandlers(pkr, cmgr, null, null);
            }
        } catch (Exception e) {
            logger.logStack(Logger.ERROR, e.getMessage(), e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return 1;
        }
        // The admin message handlers may need to locate standard packet
        // handlers, so we give it a reference to the PacketRouter.
        admin_datahdrl.setPacketRouter(admin_pktrtr);
        PacketRouter[] routers = { pktrtr, admin_pktrtr };
        Globals.setPacketRouters(routers);
        if (Globals.useSharedConfigRecord()) {
            try {
                mbus.syncChangeRecordOnStartup();
            } catch (Exception e) {
                logger.logStack(Logger.ERROR, rb.getKString(rb.E_SHARCC_SYNC_ON_STARTUP_FAILED, Globals.getClusterID(), e.getMessage()), e);
                if (failStartThrowable != null) {
                    failStartThrowable.initCause(e);
                }
                return (1);
            }
        }
        TLSProtocol.init();
        ServiceManager sm = new ServiceManager(cmgr);
        Globals.setServiceManager(sm);
        sm.updateServiceList(sm.getAllActiveServiceNames(), ServiceType.ADMIN, false);
        /*
             * Check if we need to pause the normal services until MessageBus syncs with the config server. The services will be
             * resumed by the MessageManager when it gets a notification from the MessageBus
             */
        if (mbus.waitForConfigSync()) {
            sm.updateServiceList(sm.getAllActiveServiceNames(), ServiceType.NORMAL, true);
            if (Globals.nowaitForMasterBroker()) {
                sm.addServiceRestriction(ServiceType.NORMAL, ServiceRestriction.NO_SYNC_WITH_MASTERBROKER);
                logger.log(Logger.WARNING, rb.I_MBUS_LIMITEDJMS);
                try {
                    sm.resumeAllActiveServices(ServiceType.NORMAL, true);
                } catch (BrokerException e) {
                    logger.logStack(Logger.ERROR, e.getMessage(), e);
                }
            } else {
                logger.log(Logger.WARNING, rb.I_MBUS_PAUSING);
            }
        } else {
            sm.updateServiceList(sm.getAllActiveServiceNames(), ServiceType.NORMAL, false, /* dont pause */
            true);
        }
        // OK, create the BrokerStateHandler
        Globals.setBrokerStateHandler(new BrokerStateHandler());
        // provide an option not to add shutdown hook.
        // This makes it easier to test restarts after ungraceful exits
        boolean noShutdownHook = Boolean.getBoolean(Globals.IMQ + ".noShutdownHook");
        if (inProcess || noShutdownHook || (shutdownHook = addBrokerShutdownHook()) == null) {
            // Couldn't add shutdown hook. Probably because running against 1.2
            logger.log(Logger.DEBUG, rb.I_NO_SHUTDOWN_HOOK);
        } else {
            logger.log(Logger.DEBUG, rb.I_SHUTDOWN_HOOK);
        }
        // start the memory manager
        if (!inProcess) {
            Globals.getMemManager().startManagement();
        } else {
            Globals.setMemMgrOn(false);
        }
        // Initialize the metric manager. This is the module that
        // generates performance data reports
        MetricManager mm = new MetricManager();
        Globals.setMetricManager(mm);
        mm.setParameters(Globals.getConfig());
        /*
             * Set the list of properties that must be matched before accepting connections from other brokers.
             */
        Properties matchProps = new Properties();
        matchProps.setProperty(Globals.USE_FILELOCK_FOR_LOCKFILE_PROP, String.valueOf(Globals.getUseFileLockForLockFile()));
        matchProps.setProperty(Globals.IMQ + ".autocreate.queue", Globals.getConfig().getProperty(Globals.IMQ + ".autocreate.queue", "false"));
        matchProps.setProperty(Globals.IMQ + ".autocreate.topic", Globals.getConfig().getProperty(Globals.IMQ + ".autocreate.topic", "false"));
        // 
        // "imq.queue.deliverypolicy" was used as one of the
        // "matchProps" in the 3.0.1 clusters. So even if this
        // property is now obsolete we still need to pretend that it
        // exists for cluster protocol compatibility..
        // 
        int active = Queue.getDefaultMaxActiveConsumers();
        int failover = Queue.getDefaultMaxFailoverConsumers();
        if (active == 1 && failover == 0) {
            matchProps.setProperty(Globals.IMQ + ".queue.deliverypolicy", "single");
        }
        if (active == 1 && failover != 0) {
            matchProps.setProperty(Globals.IMQ + ".queue.deliverypolicy", "failover");
        }
        if ((active == Queue.UNLIMITED || active > 1) && failover == 0) {
            matchProps.setProperty(Globals.IMQ + ".queue.deliverypolicy", "round-robin");
        }
        if (Globals.getClusterID() != null) {
            matchProps.setProperty(Globals.IMQ + ".cluster.clusterid", Globals.getClusterID());
        }
        if (isHA) {
            // must true
            matchProps.setProperty(Globals.IMQ + ".cluster.ha", Globals.getConfig().getProperty(Globals.IMQ + ".cluster.ha"));
            matchProps.setProperty(StoreManager.STORE_TYPE_PROP, Globals.getConfig().getProperty(StoreManager.STORE_TYPE_PROP));
            if (Globals.getJDBCHAEnabled()) {
                matchProps.setProperty(Globals.IMQ + ".cluster.monitor.interval", String.valueOf(haMonitor.getMonitorInterval()));
                matchProps.setProperty(Globals.IMQ + ".cluster.heartbeat.class", Globals.getConfig().getProperty(Globals.IMQ + ".cluster.heartbeat.class"));
            }
            matchProps.setProperty(Globals.IMQ + ".service.activelist", Globals.getConfig().getProperty(Globals.IMQ + ".service.activelist"));
            matchProps.setProperty(Globals.IMQ + ".bridge.enabled", Globals.getConfig().getProperty(Globals.IMQ + ".bridge.enabled", "false"));
        } else if (Globals.isNewTxnLogEnabled()) {
            matchProps.setProperty(StoreManager.NEW_TXNLOG_ENABLED_PROP, "true");
        }
        if (Globals.getConfig().getProperty(Globals.AUTOCLUSTER_BROKERMAP_CLASS_PROP) != null) {
            matchProps.setProperty(Globals.AUTOCLUSTER_BROKERMAP_CLASS_PROP, Globals.getConfig().getProperty(Globals.AUTOCLUSTER_BROKERMAP_CLASS_PROP));
        }
        if (Globals.getClusterManager().getMasterBroker() != null && Globals.nowaitForMasterBroker()) {
            matchProps.setProperty(Globals.NOWAIT_MASTERBROKER_PROP, "true");
        }
        if (Globals.useMasterBroker()) {
            if (Globals.dynamicChangeMasterBrokerEnabled()) {
                matchProps.setProperty(Globals.DYNAMIC_CHANGE_MASTERBROKER_ENABLED_PROP, "true");
            }
        }
        if (Globals.useSharedConfigRecord()) {
            matchProps.setProperty(Globals.NO_MASTERBROKER_PROP, "true");
        }
        try {
            Map props = Globals.getStore().getClusterMatchProperties();
            Map.Entry<String, String> pair = null;
            Iterator<Map.Entry<String, String>> itr = props.entrySet().iterator();
            while (itr.hasNext()) {
                pair = itr.next();
                matchProps.setProperty(pair.getKey(), pair.getValue());
            }
        } catch (Exception e) {
            logger.logStack(logger.ERROR, e.getMessage(), e);
            if (failStartThrowable != null) {
                failStartThrowable.initCause(e);
            }
            return (1);
        }
        mbus.setMatchProps(matchProps);
        /*
             * Start talking to other brokers now that all the handlers are initialized and ready to process callbacks from
             * MessageBus
             */
        mbus.startClusterIO();
        /**
         * services are up and running (although we may be paused)
         */
        startupComplete = true;
        // audit logging of broker startup
        Globals.getAuditSession().brokerOperation(null, null, MQAuditSession.BROKER_STARTUP);
        Object[] sargs = { Globals.getConfigName() + "@" + (pm.getHostname() == null || pm.getHostname().equals("") ? Globals.getMQAddress().getHostName() : pm.getMQAddress().getHostName()) + ":" + pm.getPort() };
        logger.logToAll(Logger.INFO, rb.I_BROKER_READY, sargs);
        // Load MQ Mbeans in JMX agent
        Agent agent = Globals.getAgent();
        if (agent != null) {
            agent.loadMBeans();
        }
        if (BridgeBaseContextAdapter.bridgeEnabled() && bridgeManager != null) {
            try {
                logger.log(Logger.INFO, Globals.getBrokerResources().I_START_BRIDGE_SERVICE_MANAGER);
                bridgeManager.start();
                Globals.setBridgeServiceManager(bridgeManager);
                logger.log(Logger.INFO, Globals.getBrokerResources().I_STARTED_BRIDGE_SERVICE_MANAGER);
            } catch (Throwable t) {
                logger.logStack(Logger.WARNING, Globals.getBrokerResources().W_START_BRIDGE_SERVICE_MANAGER_FAILED, t);
            }
        }
    } catch (OutOfMemoryError err) {
        Globals.handleGlobalError(err, rb.getKString(rb.M_LOW_MEMORY_STARTUP), Integer.valueOf(1));
        if (failStartThrowable != null) {
            failStartThrowable.initCause(err);
        }
        return (1);
    }
    if (diagInterval > 0) {
        MQTimer timer = Globals.getTimer();
        int _interval = diagInterval * 1000;
        timer.schedule(new BrokerDiagTask(), _interval, _interval);
    } else if (diagInterval == 0) {
        logger.log(Logger.INFO, DiagManager.allToString());
    }
    // started OK
    return 0;
}
Also used : PacketRouter(com.sun.messaging.jmq.jmsserver.data.PacketRouter) MQThread(com.sun.messaging.jmq.util.MQThread) com.sun.messaging.jmq.jmsserver.cluster.api(com.sun.messaging.jmq.jmsserver.cluster.api) Agent(com.sun.messaging.jmq.jmsserver.management.agent.Agent) Rlimit(com.sun.messaging.jmq.util.Rlimit) AdminDataHandler(com.sun.messaging.jmq.jmsserver.data.handlers.admin.AdminDataHandler) CoreLifecycleSpi(com.sun.messaging.jmq.jmsserver.plugin.spi.CoreLifecycleSpi) MQTimer(com.sun.messaging.jmq.util.timer.MQTimer) BridgeServiceManager(com.sun.messaging.bridge.api.BridgeServiceManager) BridgeServiceManager(com.sun.messaging.bridge.api.BridgeServiceManager) Password(com.sun.messaging.jmq.util.Password) MQThread(com.sun.messaging.jmq.util.MQThread)

Example 4 with BridgeServiceManager

use of com.sun.messaging.bridge.api.BridgeServiceManager in project openmq by eclipse-ee4j.

the class HelloHandler method handle.

@Override
public boolean handle(IMQConnection con, Packet cmd_msg, Hashtable cmd_props) {
    if (DEBUG) {
        logger.log(Logger.DEBUG, this.getClass().getName() + ": " + "Got Hello: " + cmd_props);
    }
    Packet reply = new Packet(con.useDirectBuffers());
    reply.setPacketType(PacketType.OBJECT_MESSAGE);
    Hashtable props = new Hashtable();
    props.put(MessageType.JMQ_MESSAGE_TYPE, Integer.valueOf(MessageType.HELLO_REPLY));
    props.put(MessageType.JMQ_INSTANCE_NAME, Globals.getConfigName());
    props.put(MessageType.JMQ_STATUS, Integer.valueOf(Status.OK));
    try {
        if (cmd_msg.getDestination().equals(MessageType.JMQ_BRIDGE_ADMIN_DEST)) {
            BridgeServiceManager bsm = null;
            if (!Globals.bridgeEnabled()) {
                String emsg = rb.getKString(rb.W_BRIDGE_SERVICE_NOT_ENABLED);
                logger.log(Logger.WARNING, emsg);
                props.put(MessageType.JMQ_STATUS, Integer.valueOf(Status.UNAVAILABLE));
                props.put(MessageType.JMQ_ERROR_STRING, emsg);
            } else {
                bsm = Globals.getBridgeServiceManager();
                if (bsm == null || !bsm.isRunning()) {
                    String emsg = rb.getKString(rb.W_BRIDGE_SERVICE_MANAGER_NOT_RUNNING);
                    logger.log(Logger.WARNING, emsg);
                    props.put(MessageType.JMQ_STATUS, Integer.valueOf(Status.UNAVAILABLE));
                    props.put(MessageType.JMQ_ERROR_STRING, emsg);
                } else {
                    reply.setReplyTo(bsm.getAdminDestinationName());
                    reply.setReplyToClass(bsm.getAdminDestinationClassName());
                }
            }
        }
    } catch (Exception e) {
        String emsg = "XXXI18N in processing admin message: " + e.getMessage();
        logger.logStack(Logger.ERROR, emsg, e);
        props.put(MessageType.JMQ_STATUS, Integer.valueOf(Status.ERROR));
        props.put(MessageType.JMQ_ERROR_STRING, emsg);
    }
    reply.setProperties(props);
    parent.sendReply(con, cmd_msg, reply);
    return true;
}
Also used : Hashtable(java.util.Hashtable) BridgeServiceManager(com.sun.messaging.bridge.api.BridgeServiceManager)

Aggregations

BridgeServiceManager (com.sun.messaging.bridge.api.BridgeServiceManager)4 com.sun.messaging.jmq.jmsserver.cluster.api (com.sun.messaging.jmq.jmsserver.cluster.api)1 PacketRouter (com.sun.messaging.jmq.jmsserver.data.PacketRouter)1 AdminDataHandler (com.sun.messaging.jmq.jmsserver.data.handlers.admin.AdminDataHandler)1 Agent (com.sun.messaging.jmq.jmsserver.management.agent.Agent)1 CoreLifecycleSpi (com.sun.messaging.jmq.jmsserver.plugin.spi.CoreLifecycleSpi)1 BrokerEvent (com.sun.messaging.jmq.jmsservice.BrokerEvent)1 BrokerEventListener (com.sun.messaging.jmq.jmsservice.BrokerEventListener)1 MQThread (com.sun.messaging.jmq.util.MQThread)1 Password (com.sun.messaging.jmq.util.Password)1 Rlimit (com.sun.messaging.jmq.util.Rlimit)1 MQTimer (com.sun.messaging.jmq.util.timer.MQTimer)1 Hashtable (java.util.Hashtable)1