Search in sources :

Example 11 with HABrokerInfo

use of com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo in project openmq by eclipse-ee4j.

the class UpgradeHAStore method upgradeStore.

void upgradeStore(Connection conn) throws BrokerException {
    // log informational messages
    logger.logToAll(Logger.INFO, br.getString(BrokerResources.I_UPGRADE_HASTORE_IN_PROGRESS, String.valueOf(JDBCStore.STORE_VERSION), brokerID));
    DAOFactory daoFactory = dbMgr.getDAOFactory();
    // Check if HA store exists
    int version = -1;
    try {
        VersionDAO verDAO = daoFactory.getVersionDAO();
        version = verDAO.getStoreVersion(conn);
    } catch (BrokerException e) {
    // Assume store doesn't exist
    }
    boolean createStore = false;
    if (version == JDBCStore.STORE_VERSION) {
        // Check if store has been upgraded
        BrokerDAO bkrDAO = daoFactory.getBrokerDAO();
        HABrokerInfo bkrInfo = bkrDAO.getBrokerInfo(conn, brokerID);
        if (bkrInfo != null) {
            String reason = br.getString(BrokerResources.I_HASTORE_ALREADY_UPGRADED, brokerID);
            throw new BrokerException(br.getKString(BrokerResources.E_UPGRADE_HASTORE_FAILED, reason));
        }
    } else if (version == -1) {
        createStore = true;
    } else {
        // Bad version
        String reason = br.getString(BrokerResources.E_BAD_STORE_VERSION, String.valueOf(version), String.valueOf(JDBCStore.STORE_VERSION));
        throw new BrokerException(br.getKString(BrokerResources.E_UPGRADE_HASTORE_FAILED, reason));
    }
    try {
        // create the tables first
        if (createStore) {
            DBTool.createTables(conn);
        }
    } catch (Throwable e) {
        String url = dbMgr.getCreateDBURL();
        if (url == null || url.length() == 0) {
            url = dbMgr.getOpenDBURL();
        }
        String errorMsg = br.getKString(BrokerResources.E_CREATE_DATABASE_TABLE_FAILED, url);
        logger.logToAll(Logger.ERROR, errorMsg, e);
        throw new BrokerException(errorMsg, e);
    }
    try {
        conn.setAutoCommit(false);
        upgradeStoreSessions(conn);
        upgradeDestinations(conn);
        upgradeInterests(conn);
        upgradeMessages(conn);
        upgradeTxns(conn);
        logger.logToAll(Logger.INFO, br.getString(BrokerResources.I_UPGRADE_STORE_DONE));
    } catch (Exception e) {
        // upgrade failed; log message
        logger.logToAll(Logger.ERROR, BrokerResources.I_REMOVE_UPGRADE_HASTORE_DATA, brokerID);
        try {
            // remove all entries associated w/ the broker and return
            DestinationDAO dstDAO = daoFactory.getDestinationDAO();
            dstDAO.deleteAll(conn);
            ConsumerDAO conDAO = daoFactory.getConsumerDAO();
            conDAO.deleteAll(conn);
            MessageDAO msgDAO = daoFactory.getMessageDAO();
            msgDAO.deleteAll(conn);
            TransactionDAO txnDAO = daoFactory.getTransactionDAO();
            txnDAO.deleteAll(conn);
        } catch (Exception ex) {
            logger.logStack(Logger.ERROR, BrokerResources.X_INTERNAL_EXCEPTION, "Failed to clean up after upgrade failed", ex);
        }
        if (e instanceof BrokerException) {
            throw (BrokerException) e;
        } else {
            throw new BrokerException(br.getKString(BrokerResources.E_UPGRADE_HASTORE_FAILED, e.getMessage()), e);
        }
    }
}
Also used : HABrokerInfo(com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo)

Example 12 with HABrokerInfo

use of com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo in project openmq by eclipse-ee4j.

the class Util method checkBeingTakenOver.

public static void checkBeingTakenOver(Connection conn, DBManager dbMgr, Logger logger, java.util.logging.Logger logger_) throws BrokerException {
    if (!Globals.getHAEnabled()) {
        return;
    }
    String brokerID = dbMgr.getBrokerID();
    BrokerDAO dao = dbMgr.getDAOFactory().getBrokerDAO();
    if (dao.isBeingTakenOver(conn, brokerID)) {
        BrokerException be = new StoreBeingTakenOverException(Globals.getBrokerResources().getKString(BrokerResources.E_STORE_BEING_TAKEN_OVER));
        try {
            HABrokerInfo bkrInfo = dao.getBrokerInfo(conn, brokerID);
            String emsg = be.getMessage() + "[" + (bkrInfo == null ? "" + brokerID : bkrInfo.toString()) + "]";
            logger.logStack(Logger.ERROR, emsg, be);
            logExt(logger_, java.util.logging.Level.SEVERE, emsg, be);
        } catch (Throwable t) {
        /* Ignore error */
        }
        throw be;
    }
}
Also used : HABrokerInfo(com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo) BrokerException(com.sun.messaging.jmq.jmsserver.util.BrokerException) StoreBeingTakenOverException(com.sun.messaging.jmq.jmsserver.util.StoreBeingTakenOverException)

Example 13 with HABrokerInfo

use of com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo in project openmq by eclipse-ee4j.

the class MessageDAOImpl method canInsertMsg.

/**
 * Check if a msg can be inserted. A BrokerException is thrown if the msg already exists in the store, the destination
 * doesn't exist, or the specified broker is being taken over by another broker (HA mode).
 *
 * @param conn database connection
 * @param msgID message ID
 * @param dstID destination ID
 * @param brokerID broker ID
 * @throws BrokerException if msg cannot be inserted
 */
protected void canInsertMsg(Connection conn, String msgID, String dstID, String brokerID) throws BrokerException {
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Exception myex = null;
    final String sql = selectCanInsertSQL;
    try {
        pstmt = DBManager.getDBManager().createPreparedStatement(conn, sql);
        pstmt.setString(1, msgID);
        pstmt.setString(2, dstID);
        if (Globals.getHAEnabled()) {
            pstmt.setString(3, brokerID);
        }
        rs = pstmt.executeQuery();
        if (rs.next()) {
            // Make sure msg doesn't exist, i.e. created timestamp == 0
            if (rs.getLong(1) > 0) {
                throw new BrokerException(br.getKString(BrokerResources.E_MSG_EXISTS_IN_STORE, msgID, dstID), Status.CONFLICT);
            }
            // Make sure dst does exist, i.e. created timestamp > 0
            if (rs.getLong(2) == 0) {
                throw new BrokerException(br.getKString(BrokerResources.E_DESTINATION_NOT_FOUND_IN_STORE, dstID), Status.NOT_FOUND);
            }
            // Make sure broker is not being taken over, i.e. state == 0
            if (Globals.getHAEnabled()) {
                if (rs.getInt(3) > 0) {
                    BrokerException be = new StoreBeingTakenOverException(br.getKString(BrokerResources.E_STORE_BEING_TAKEN_OVER));
                    try {
                        DBManager dbMgr = DBManager.getDBManager();
                        BrokerDAO dao = dbMgr.getDAOFactory().getBrokerDAO();
                        HABrokerInfo bkrInfo = dao.getBrokerInfo(conn, dbMgr.getBrokerID());
                        logger.logStack(Logger.ERROR, be.getMessage() + "[" + (bkrInfo == null ? "" + dbMgr.getBrokerID() : bkrInfo.toString()) + "]", be);
                    } catch (Throwable t) {
                    /* Ignore error */
                    }
                    throw be;
                }
            }
        } else {
            // Shouldn't happen
            throw new BrokerException(br.getKString(BrokerResources.X_JDBC_QUERY_FAILED, sql));
        }
    } catch (Exception e) {
        myex = e;
        try {
            if ((conn != null) && !conn.getAutoCommit()) {
                conn.rollback();
            }
        } catch (SQLException rbe) {
            logger.log(Logger.ERROR, BrokerResources.X_DB_ROLLBACK_FAILED + "[" + sql + "]", rbe);
        }
        Exception ex;
        if (e instanceof BrokerException) {
            throw (BrokerException) e;
        } else if (e instanceof SQLException) {
            ex = DBManager.wrapSQLException("[" + sql + "]", (SQLException) e);
        } else {
            ex = e;
        }
        throw new BrokerException(br.getKString(BrokerResources.X_JDBC_QUERY_FAILED, sql), ex);
    } finally {
        Util.close(rs, pstmt, null, myex);
    }
}
Also used : HABrokerInfo(com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo) PacketReadEOFException(com.sun.messaging.jmq.io.PacketReadEOFException) InvalidPacketException(com.sun.messaging.jmq.io.InvalidPacketException)

Example 14 with HABrokerInfo

use of com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo in project openmq by eclipse-ee4j.

the class MySQLMessageDAOImpl method delete.

@Override
public void delete(Connection conn, DestinationUID dstUID, String id, boolean replaycheck) throws BrokerException {
    boolean myConn = false;
    CallableStatement stmt = null;
    Exception myex = null;
    String sql = "{call " + PROC_DELETE + " (?, ?, ?, ?, ?)}";
    try {
        DBManager dbMgr = DBManager.getDBManager();
        if (conn == null) {
            conn = dbMgr.getConnection(false);
            // Set to true since this is our connection
            myConn = true;
        }
        if (fi.FAULT_INJECTION) {
            HashMap fips = new HashMap();
            fips.put(FaultInjection.DST_NAME_PROP, DestinationUID.getUniqueString(dstUID.getName(), dstUID.isQueue()));
            fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_1_8, fips, 2, false);
        }
        if (DEBUG) {
            Globals.getLogger().log(Logger.INFO, "before call " + sql + "(" + id + ")");
        }
        String brokerid = dbMgr.getBrokerID();
        stmt = conn.prepareCall(sql);
        stmt.setString(1, id);
        if (Globals.getHAEnabled()) {
            stmt.setString(2, brokerid);
        } else {
            stmt.setNull(2, Types.VARCHAR);
        }
        stmt.registerOutParameter(3, Types.INTEGER);
        stmt.registerOutParameter(4, Types.INTEGER);
        stmt.registerOutParameter(5, Types.INTEGER);
        stmt.execute();
        int row_affected = stmt.getInt(3);
        int beingTakenOver = stmt.getInt(4);
        int bstate = stmt.getInt(5);
        if (Globals.getHAEnabled() && beingTakenOver != 0) {
            HABrokerInfo binfo = null;
            try {
                binfo = dbMgr.getDAOFactory().getBrokerDAO().getBrokerInfo(conn, brokerid);
            } catch (Exception e) {
            /* ignore */
            }
            throw new StoreBeingTakenOverException(br.getKString(BrokerResources.E_STORE_BEING_TAKEN_OVER) + "[" + BrokerState.getState(bstate).toString() + "]" + binfo);
        }
        if (row_affected == 0) {
            throw new BrokerException(br.getKString(BrokerResources.E_MSG_NOT_FOUND_IN_STORE, id, dstUID), Status.NOT_FOUND);
        }
        if (DEBUG) {
            Globals.getLogger().log(Logger.INFO, "After call " + sql + "(" + id + ")");
        }
        if (myConn) {
            conn.commit();
        }
    } catch (Exception e) {
        myex = e;
        try {
            if ((conn != null) && !conn.getAutoCommit()) {
                conn.rollback();
            }
        } catch (SQLException rbe) {
            logger.log(Logger.ERROR, BrokerResources.X_DB_ROLLBACK_FAILED, rbe);
        }
        Exception ex;
        if (e instanceof BrokerException) {
            throw (BrokerException) e;
        } else if (e instanceof SQLException) {
            ex = CommDBManager.wrapSQLException("[" + sql + "]", (SQLException) e);
        } else {
            ex = e;
        }
        throw new BrokerException("Failed to execute " + sql, ex);
    } finally {
        if (myConn) {
            closeSQLObjects(null, stmt, conn, myex);
        } else {
            closeSQLObjects(null, stmt, null, myex);
        }
    }
}
Also used : HABrokerInfo(com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo) CommDBManager(com.sun.messaging.jmq.jmsserver.persist.jdbc.comm.CommDBManager) HashMap(java.util.HashMap)

Example 15 with HABrokerInfo

use of com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo in project openmq by eclipse-ee4j.

the class DBTool method doRestore.

/*
     * Restore the JDBC store from filebased backup files.
     */
private void doRestore() throws BrokerException {
    if (!Globals.getHAEnabled()) {
        throw new BrokerException(br.getKString(BrokerResources.I_HA_NOT_ENABLE, dbmgr.getBrokerID()));
    }
    // instantiate the file store.
    Properties props = System.getProperties();
    String clusterID = Globals.getClusterID();
    String backupDir = (String) props.get(Globals.IMQ + ".backupdir") + File.separator + clusterID;
    logger.logToAll(Logger.INFO, "Restore persistent store for HA cluster " + clusterID + " from backup dir: " + backupDir);
    final FileStore fileStore = new FileStore(backupDir, false);
    // Brokers table.
    JDBCStore jdbcStore = null;
    try {
        // Re-create the jdbc store
        doRecreate();
        jdbcStore = (JDBCStore) StoreManager.getStore();
        /*
             * For data that are not broker specific, i.e. properties, change records, consumers, brokers, and sessions, we will
             * retrieve those data from the top level directory (a.k.a cluster filestore).
             */
        // Properties table
        List haBrokers = null;
        Properties properties = fileStore.getAllProperties();
        Iterator propItr = properties.entrySet().iterator();
        while (propItr.hasNext()) {
            Map.Entry entry = (Map.Entry) propItr.next();
            String name = (String) entry.getKey();
            if (name.equals(STORE_PROPERTY_HABROKERS)) {
                // Retrieve all HABrokerInfo from a property
                haBrokers = (List) entry.getValue();
            } else {
                jdbcStore.updateProperty(name, entry.getValue(), false);
            }
        }
        propItr = null;
        properties = null;
        if (haBrokers == null || haBrokers.isEmpty()) {
            throw new BrokerException(br.getKString(BrokerResources.X_LOAD_ALL_BROKERINFO_FAILED));
        }
        // Configuration Change Record table
        List<ChangeRecordInfo> records = fileStore.getAllConfigRecords();
        for (int i = 0, len = records.size(); i < len; i++) {
            jdbcStore.storeConfigChangeRecord(records.get(i).getTimestamp(), records.get(i).getRecord(), false);
        }
        records = null;
        // Consumer table
        Consumer[] consumerArray = fileStore.getAllInterests();
        for (int i = 0; i < consumerArray.length; i++) {
            jdbcStore.storeInterest(consumerArray[i], false);
        }
        consumerArray = null;
        // Broker & Session table.
        Iterator bkrItr = haBrokers.iterator();
        while (bkrItr.hasNext()) {
            HABrokerInfo bkrInfo = (HABrokerInfo) bkrItr.next();
            jdbcStore.addBrokerInfo(bkrInfo, false);
        }
        /*
             * For each broker in the cluster, we will retrieve broker specific data, destinations, messages, transactions,
             * acknowledgements from their own filestore (a.k.a broker filestore).
             */
        bkrItr = haBrokers.iterator();
        while (bkrItr.hasNext()) {
            // Backup data for each broker
            HABrokerInfo bkrInfo = (HABrokerInfo) bkrItr.next();
            String brokerID = bkrInfo.getId();
            long sessionID = bkrInfo.getSessionID();
            logger.logToAll(Logger.INFO, "Restore persistent data for broker " + brokerID);
            FileStore bkrFS = null;
            JMSBridgeStore jmsbridgeStore = null;
            try {
                String instanceRootDir = backupDir + File.separator + brokerID;
                bkrFS = new FileStore(instanceRootDir, false);
                // Destination table.
                Destination[] dstArray = bkrFS.getAllDestinations();
                for (int i = 0, len = dstArray.length; i < len; i++) {
                    DestinationUID did = dstArray[i].getDestinationUID();
                    Destination dst = jdbcStore.getDestination(did);
                    if (dst == null) {
                        // Store the destination if not found
                        jdbcStore.storeDestination(dstArray[i], sessionID);
                    }
                }
                // Retrieve messages for each destination.
                for (int i = 0, len = dstArray.length; i < len; i++) {
                    for (Enumeration e = bkrFS.messageEnumeration(dstArray[i]); e.hasMoreElements(); ) {
                        DestinationUID did = dstArray[i].getDestinationUID();
                        Packet message = (Packet) e.nextElement();
                        SysMessageID mid = message.getSysMessageID();
                        // Get interest states for the message; Consumer State table
                        HashMap stateMap = bkrFS.getInterestStates(did, mid);
                        if (stateMap == null || stateMap.isEmpty()) {
                            jdbcStore.storeMessage(did, message, null, null, sessionID, false);
                        } else {
                            int size = stateMap.size();
                            ConsumerUID[] iids = new ConsumerUID[size];
                            int[] states = new int[size];
                            Iterator stateItr = stateMap.entrySet().iterator();
                            int j = 0;
                            while (stateItr.hasNext()) {
                                Map.Entry entry = (Map.Entry) stateItr.next();
                                iids[j] = (ConsumerUID) entry.getKey();
                                states[j] = ((Integer) entry.getValue()).intValue();
                                j++;
                            }
                            jdbcStore.storeMessage(did, message, iids, states, sessionID, false);
                        }
                    }
                }
                // Transaction table
                Collection txnList = bkrFS.getTransactions(brokerID);
                Iterator txnItr = txnList.iterator();
                while (txnItr.hasNext()) {
                    TransactionUID tid = (TransactionUID) txnItr.next();
                    TransactionInfo txnInfo = bkrFS.getTransactionInfo(tid);
                    TransactionAcknowledgement[] txnAck = bkrFS.getTransactionAcks(tid);
                    jdbcStore.storeTransaction(tid, txnInfo, sessionID);
                    for (int i = 0, len = txnAck.length; i < len; i++) {
                        jdbcStore.storeTransactionAck(tid, txnAck[i], false);
                    }
                }
                /**
                 ************************************************
                 * JMSBridge
                 *************************************************
                 */
                Properties bp = new Properties();
                bp.setProperty("instanceRootDir", instanceRootDir);
                bp.setProperty("reset", "false");
                bp.setProperty("logdomain", "imqdbmgr");
                jmsbridgeStore = (JMSBridgeStore) BridgeServiceManager.getExportedService(JMSBridgeStore.class, "JMS", bp);
                if (jmsbridgeStore != null) {
                    List bnames = jmsbridgeStore.getJMSBridges(null);
                    String bname = null;
                    Iterator itr = bnames.iterator();
                    while (itr.hasNext()) {
                        bname = (String) itr.next();
                        jdbcStore.addJMSBridge(bname, true, null);
                    }
                    jmsbridgeStore.closeJMSBridgeStore();
                    jmsbridgeStore = null;
                    bname = null;
                    itr = bnames.iterator();
                    while (itr.hasNext()) {
                        bname = (String) itr.next();
                        bp.setProperty("jmsbridge", bname);
                        if (jmsbridgeStore != null) {
                            jmsbridgeStore.closeJMSBridgeStore();
                            jmsbridgeStore = null;
                        }
                        logger.logToAll(logger.INFO, "Restore JMS bridge " + bname);
                        jmsbridgeStore = (JMSBridgeStore) BridgeServiceManager.getExportedService(JMSBridgeStore.class, "JMS", bp);
                        List xids = jmsbridgeStore.getTMLogRecordKeysByName(bname, null);
                        logger.logToAll(logger.INFO, "\tRestore JMS bridge " + bname + " with " + xids.size() + " TM log records");
                        String xid = null;
                        byte[] lr = null;
                        Iterator itr1 = xids.iterator();
                        while (itr1.hasNext()) {
                            xid = (String) itr1.next();
                            lr = jmsbridgeStore.getTMLogRecord(xid, bname, null);
                            if (lr == null) {
                                logger.logToAll(Logger.INFO, "JMSBridge TM log record not found for " + xid);
                                continue;
                            }
                            jdbcStore.storeTMLogRecord(xid, lr, bname, true, null);
                        }
                    }
                }
            } finally {
                bkrFS.close();
                if (jmsbridgeStore != null) {
                    jmsbridgeStore.closeJMSBridgeStore();
                }
            }
        }
        logger.logToAll(Logger.INFO, "Restore persistent store complete.");
    } catch (Throwable ex) {
        ex.printStackTrace();
        throw new BrokerException(ex.getMessage());
    } finally {
        assert fileStore != null;
        try {
            fileStore.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        StoreManager.releaseStore(true);
    }
}
Also used : Destination(com.sun.messaging.jmq.jmsserver.core.Destination) HABrokerInfo(com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo) Consumer(com.sun.messaging.jmq.jmsserver.core.Consumer) TransactionInfo(com.sun.messaging.jmq.jmsserver.persist.api.TransactionInfo) JMSBridgeStore(com.sun.messaging.bridge.api.JMSBridgeStore) Packet(com.sun.messaging.jmq.io.Packet) TransactionAcknowledgement(com.sun.messaging.jmq.jmsserver.data.TransactionAcknowledgement) ConsumerUID(com.sun.messaging.jmq.jmsserver.core.ConsumerUID) TransactionUID(com.sun.messaging.jmq.jmsserver.data.TransactionUID) FileStore(com.sun.messaging.jmq.jmsserver.persist.file.FileStore) DestinationUID(com.sun.messaging.jmq.jmsserver.core.DestinationUID) SysMessageID(com.sun.messaging.jmq.io.SysMessageID) ChangeRecordInfo(com.sun.messaging.jmq.jmsserver.persist.api.ChangeRecordInfo)

Aggregations

HABrokerInfo (com.sun.messaging.jmq.jmsserver.persist.api.HABrokerInfo)28 HAClusteredBroker (com.sun.messaging.jmq.jmsserver.cluster.api.ha.HAClusteredBroker)6 TakeoverLockException (com.sun.messaging.jmq.jmsserver.persist.api.TakeoverLockException)6 HashMap (java.util.HashMap)5 AutoClusterBrokerMap (com.sun.messaging.jmq.jmsserver.cluster.manager.AutoClusterBrokerMap)4 TransactionUID (com.sun.messaging.jmq.jmsserver.data.TransactionUID)4 Iterator (java.util.Iterator)4 Map (java.util.Map)4 TransactionState (com.sun.messaging.jmq.jmsserver.data.TransactionState)3 BrokerException (com.sun.messaging.jmq.jmsserver.util.BrokerException)3 IOException (java.io.IOException)3 JMSBridgeStore (com.sun.messaging.bridge.api.JMSBridgeStore)2 InvalidPacketException (com.sun.messaging.jmq.io.InvalidPacketException)2 Packet (com.sun.messaging.jmq.io.Packet)2 PacketReadEOFException (com.sun.messaging.jmq.io.PacketReadEOFException)2 SysMessageID (com.sun.messaging.jmq.io.SysMessageID)2 Consumer (com.sun.messaging.jmq.jmsserver.core.Consumer)2 ConsumerUID (com.sun.messaging.jmq.jmsserver.core.ConsumerUID)2 Destination (com.sun.messaging.jmq.jmsserver.core.Destination)2 DestinationUID (com.sun.messaging.jmq.jmsserver.core.DestinationUID)2