001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.store.jdbc.adapter;
018
019import java.io.IOException;
020import java.sql.PreparedStatement;
021import java.sql.ResultSet;
022import java.sql.SQLException;
023
024import org.apache.activemq.store.jdbc.DefaultDatabaseLocker;
025import org.apache.activemq.store.jdbc.JDBCPersistenceAdapter;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029/**
030 * Represents an exclusive lock on a database to avoid multiple brokers running
031 * against the same logical database.
032 * 
033 * @org.apache.xbean.XBean element="transact-database-locker"
034 * 
035 */
036public class TransactDatabaseLocker extends DefaultDatabaseLocker {
037    private static final Logger LOG = LoggerFactory.getLogger(TransactDatabaseLocker.class);
038    
039    public TransactDatabaseLocker() {
040    }
041    
042    public TransactDatabaseLocker(JDBCPersistenceAdapter persistenceAdapter) throws IOException {
043        setPersistenceAdapter(persistenceAdapter);
044    }
045    
046    @Override
047    public void start() throws Exception {
048        stopping = false;
049
050        LOG.info("Attempting to acquire the exclusive lock to become the Master broker");
051        PreparedStatement statement = null;
052        while (true) {
053            try {
054                connection = dataSource.getConnection();
055                connection.setAutoCommit(false);
056                String sql = statements.getLockCreateStatement();
057                statement = connection.prepareStatement(sql);
058                if (statement.getMetaData() != null) {
059                    ResultSet rs = statement.executeQuery();
060                    // if not already locked the statement below blocks until lock acquired
061                    rs.next();
062                } else {
063                    statement.execute();
064                }
065                break;
066            } catch (Exception e) {
067                if (stopping) {
068                    throw new Exception("Cannot start broker as being asked to shut down. Interrupted attempt to acquire lock: " + e, e);
069                }
070
071                if (exceptionHandler != null) {
072                    try {
073                        exceptionHandler.handle(e);
074                    } catch (Throwable handlerException) {
075                        LOG.error("The exception handler " + exceptionHandler.getClass().getCanonicalName() + " threw this exception: " + handlerException
076                                + " while trying to handle this excpetion: " + e, handlerException);
077                    }
078
079                } else {
080                    LOG.error("Failed to acquire lock: " + e, e);
081                }
082            } finally {
083
084                if (null != statement) {
085                    try {
086                        statement.close();
087                    } catch (SQLException e1) {
088                        LOG.warn("Caught while closing statement: " + e1, e1);
089                    }
090                    statement = null;
091                }
092            }
093
094            LOG.debug("Sleeping for " + lockAcquireSleepInterval + " milli(s) before trying again to get the lock...");
095            try {
096                Thread.sleep(lockAcquireSleepInterval);
097            } catch (InterruptedException ie) {
098                LOG.warn("Master lock retry sleep interrupted", ie);
099            }
100        }
101
102        LOG.info("Becoming the master on dataSource: " + dataSource);
103    }
104
105}