Search in sources :

Example 16 with TransactionFailureException

use of org.neo4j.graphdb.TransactionFailureException in project neo4j-mobile-android by neo4j-contrib.

the class TxManager method buildRecoveryInfo.

private void buildRecoveryInfo(List<NonCompletedTransaction> commitList, List<Xid> rollbackList, Map<Resource, XAResource> resourceMap, Iterator<List<TxLog.Record>> danglingRecordList) {
    while (danglingRecordList.hasNext()) {
        Iterator<TxLog.Record> dListItr = danglingRecordList.next().iterator();
        TxLog.Record startRecord = dListItr.next();
        if (startRecord.getType() != TxLog.TX_START) {
            throw logAndReturn("TM error building recovery info", new TransactionFailureException("First record not a start record, type=" + startRecord.getType()));
        }
        // get branches & commit status
        HashSet<Resource> branchSet = new HashSet<Resource>();
        int markedCommit = -1;
        while (dListItr.hasNext()) {
            TxLog.Record record = dListItr.next();
            if (record.getType() == TxLog.BRANCH_ADD) {
                if (markedCommit != -1) {
                    throw logAndReturn("TM error building recovery info", new TransactionFailureException("Already marked commit " + startRecord));
                }
                branchSet.add(new Resource(record.getBranchId()));
            } else if (record.getType() == TxLog.MARK_COMMIT) {
                if (markedCommit != -1) {
                    throw logAndReturn("TM error building recovery info", new TransactionFailureException("Already marked commit " + startRecord));
                }
                markedCommit = record.getSequenceNumber();
            } else {
                throw logAndReturn("TM error building recovery info", new TransactionFailureException("Illegal record type[" + record.getType() + "]"));
            }
        }
        Iterator<Resource> resourceItr = branchSet.iterator();
        List<Xid> xids = new LinkedList<Xid>();
        while (resourceItr.hasNext()) {
            Resource resource = resourceItr.next();
            if (!resourceMap.containsKey(resource)) {
                resourceMap.put(resource, getXaResource(resource.getResourceId()));
            }
            xids.add(new XidImpl(startRecord.getGlobalId(), resource.getResourceId()));
        }
        if (// this xid needs to be committed
        markedCommit != -1) {
            commitList.add(new NonCompletedTransaction(markedCommit, xids));
        } else {
            rollbackList.addAll(xids);
        }
    }
}
Also used : XAResource(javax.transaction.xa.XAResource) XaResource(org.neo4j.kernel.impl.transaction.xaframework.XaResource) LinkedList(java.util.LinkedList) TransactionFailureException(org.neo4j.graphdb.TransactionFailureException) Xid(javax.transaction.xa.Xid) HashSet(java.util.HashSet)

Example 17 with TransactionFailureException

use of org.neo4j.graphdb.TransactionFailureException in project neo4j-mobile-android by neo4j-contrib.

the class TxManager method init.

@Override
public void init(XaDataSourceManager xaDsManagerToUse) {
    this.xaDsManager = xaDsManagerToUse;
    txThreadMap = new ArrayMap<Thread, TransactionImpl>(5, true, true);
    logSwitcherFileName = txLogDir + separator + "active_tx_log";
    txLog1FileName = "tm_tx_log.1";
    txLog2FileName = "tm_tx_log.2";
    try {
        if (new File(logSwitcherFileName).exists()) {
            FileChannel fc = new RandomAccessFile(logSwitcherFileName, "rw").getChannel();
            byte[] fileName = new byte[256];
            ByteBuffer buf = ByteBuffer.wrap(fileName);
            fc.read(buf);
            fc.close();
            String currentTxLog = txLogDir + separator + UTF8.decode(fileName).trim();
            if (!new File(currentTxLog).exists()) {
                throw logAndReturn("TM startup failure", new TransactionFailureException("Unable to start TM, " + "active tx log file[" + currentTxLog + "] not found."));
            }
            txLog = new TxLog(currentTxLog);
            msgLog.logMessage("TM opening log: " + currentTxLog, true);
        } else {
            if (new File(txLogDir + separator + txLog1FileName).exists() || new File(txLogDir + separator + txLog2FileName).exists()) {
                throw logAndReturn("TM startup failure", new TransactionFailureException("Unable to start TM, " + "no active tx log file found but found either " + txLog1FileName + " or " + txLog2FileName + " file, please set one of them as active or " + "remove them."));
            }
            ByteBuffer buf = ByteBuffer.wrap(txLog1FileName.getBytes("UTF-8"));
            FileChannel fc = new RandomAccessFile(logSwitcherFileName, "rw").getChannel();
            fc.write(buf);
            txLog = new TxLog(txLogDir + separator + txLog1FileName);
            msgLog.logMessage("TM new log: " + txLog1FileName, true);
            fc.force(true);
            fc.close();
        }
        Iterator<List<TxLog.Record>> danglingRecordList = txLog.getDanglingRecords();
        if (danglingRecordList.hasNext()) {
            log.info("Unresolved transactions found, " + "recovery started ...");
            recover(danglingRecordList);
            log.info("Recovery completed, all transactions have been " + "resolved to a consistent state.");
            msgLog.logMessage("Recovery completed, all transactions have been " + "resolved to a consistent state.");
        }
        getTxLog().truncate();
        tmOk = true;
    } catch (IOException e) {
        log.log(Level.SEVERE, "Unable to start TM", e);
        throw logAndReturn("TM startup failure", new TransactionFailureException("Unable to start TM", e));
    }
}
Also used : FileChannel(java.nio.channels.FileChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) TransactionFailureException(org.neo4j.graphdb.TransactionFailureException) RandomAccessFile(java.io.RandomAccessFile) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 18 with TransactionFailureException

use of org.neo4j.graphdb.TransactionFailureException in project neo4j-mobile-android by neo4j-contrib.

the class TxManager method commit.

private void commit(Thread thread, TransactionImpl tx) throws SystemException, HeuristicMixedException, HeuristicRollbackException {
    // mark as commit in log done TxImpl.doCommit()
    Throwable commitFailureCause = null;
    int xaErrorCode = -1;
    if (tx.getResourceCount() == 0) {
        tx.setStatus(Status.STATUS_COMMITTED);
    } else {
        try {
            tx.doCommit();
        } catch (XAException e) {
            xaErrorCode = e.errorCode;
            log.log(Level.SEVERE, "Commit failed, status=" + getTxStatusAsString(tx.getStatus()) + ", errorCode=" + xaErrorCode, e);
            if (tx.getStatus() == Status.STATUS_COMMITTED) {
                // this should never be
                setTmNotOk(e);
                throw logAndReturn("TM error tx commit", new TransactionFailureException("commit threw exception but status is committed?", e));
            }
        } catch (Throwable t) {
            log.log(Level.SEVERE, "Commit failed", t);
            commitFailureCause = t;
        }
    }
    if (tx.getStatus() != Status.STATUS_COMMITTED) {
        try {
            tx.doRollback();
        } catch (Throwable e) {
            log.log(Level.SEVERE, "Unable to rollback transaction. " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", e);
            setTmNotOk(e);
            String commitError;
            if (commitFailureCause != null) {
                commitError = "error in commit: " + commitFailureCause;
            } else {
                commitError = "error code in commit: " + xaErrorCode;
            }
            String rollbackErrorCode = "Uknown error code";
            if (e instanceof XAException) {
                rollbackErrorCode = Integer.toString(((XAException) e).errorCode);
            }
            throw logAndReturn("TM error tx commit", Exceptions.withCause(new HeuristicMixedException("Unable to rollback ---> " + commitError + " ---> error code for rollback: " + rollbackErrorCode), e));
        }
        tx.doAfterCompletion();
        txThreadMap.remove(thread);
        try {
            if (tx.isGlobalStartRecordWritten()) {
                getTxLog().txDone(tx.getGlobalId());
            }
        } catch (IOException e) {
            log.log(Level.SEVERE, "Error writing transaction log", e);
            setTmNotOk(e);
            throw logAndReturn("TM error tx commit", Exceptions.withCause(new SystemException("TM encountered a problem, " + " error writing transaction log"), e));
        }
        tx.setStatus(Status.STATUS_NO_TRANSACTION);
        if (commitFailureCause == null) {
            throw logAndReturn("TM error tx commit", new HeuristicRollbackException("Failed to commit, transaction rolledback ---> " + "error code was: " + xaErrorCode));
        } else {
            throw logAndReturn("TM error tx commit", Exceptions.withCause(new HeuristicRollbackException("Failed to commit, transaction rolledback ---> " + commitFailureCause), commitFailureCause));
        }
    }
    tx.doAfterCompletion();
    txThreadMap.remove(thread);
    try {
        if (tx.isGlobalStartRecordWritten()) {
            getTxLog().txDone(tx.getGlobalId());
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error writing transaction log", e);
        setTmNotOk(e);
        throw logAndReturn("TM error tx commit", Exceptions.withCause(new SystemException("TM encountered a problem, " + " error writing transaction log"), e));
    }
    tx.setStatus(Status.STATUS_NO_TRANSACTION);
}
Also used : TransactionFailureException(org.neo4j.graphdb.TransactionFailureException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) XAException(javax.transaction.xa.XAException) SystemException(javax.transaction.SystemException) HeuristicMixedException(javax.transaction.HeuristicMixedException) IOException(java.io.IOException)

Example 19 with TransactionFailureException

use of org.neo4j.graphdb.TransactionFailureException in project neo4j-mobile-android by neo4j-contrib.

the class TxModule method registerDataSource.

/**
 * Use this method to add data source that can participate in transactions
 * if you don't want a data source configuration file.
 *
 * @param name
 *            The data source name
 * @param className
 *            The (full) class name of class
 * @param resourceId
 *            The resource id identifying datasource
 * @param params
 *            The configuration map for the datasource
 * @throws LifecycleException
 */
public XaDataSource registerDataSource(String dsName, String className, byte[] resourceId, Map<?, ?> params) {
    XaDataSourceManager xaDsMgr = xaDsManager;
    String name = dsName.toLowerCase();
    if (xaDsMgr.hasDataSource(name)) {
        throw new TransactionFailureException("Data source[" + name + "] has already been registered");
    }
    try {
        XaDataSource dataSource = xaDsMgr.create(className, params);
        xaDsMgr.registerDataSource(name, dataSource, resourceId);
        return dataSource;
    } catch (Exception e) {
        throw new TransactionFailureException("Could not create data source [" + name + "], see nested exception for cause of error", e.getCause());
    }
}
Also used : TransactionFailureException(org.neo4j.graphdb.TransactionFailureException) XaDataSource(org.neo4j.kernel.impl.transaction.xaframework.XaDataSource) TransactionFailureException(org.neo4j.graphdb.TransactionFailureException)

Example 20 with TransactionFailureException

use of org.neo4j.graphdb.TransactionFailureException in project neo4j-mobile-android by neo4j-contrib.

the class XaDataSourceManager method getBranchId.

synchronized byte[] getBranchId(XAResource xaResource) {
    if (xaResource instanceof XaResource) {
        byte[] branchId = ((XaResource) xaResource).getBranchId();
        if (branchId != null) {
            return branchId;
        }
    }
    Iterator<Map.Entry<String, XaDataSource>> itr = dataSources.entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, XaDataSource> entry = itr.next();
        XaDataSource dataSource = entry.getValue();
        XAResource resource = dataSource.getXaConnection().getXaResource();
        try {
            if (resource.isSameRM(xaResource)) {
                String name = entry.getKey();
                return sourceIdMapping.get(name);
            }
        } catch (XAException e) {
            throw new TransactionFailureException("Unable to check is same resource", e);
        }
    }
    throw new TransactionFailureException("Unable to find mapping for XAResource[" + xaResource + "]");
}
Also used : XAResource(javax.transaction.xa.XAResource) TransactionFailureException(org.neo4j.graphdb.TransactionFailureException) XAException(javax.transaction.xa.XAException) XaResource(org.neo4j.kernel.impl.transaction.xaframework.XaResource) XaDataSource(org.neo4j.kernel.impl.transaction.xaframework.XaDataSource) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

TransactionFailureException (org.neo4j.graphdb.TransactionFailureException)56 Transaction (org.neo4j.graphdb.Transaction)16 NotFoundException (org.neo4j.graphdb.NotFoundException)9 Test (org.junit.Test)7 ConstraintViolationException (org.neo4j.graphdb.ConstraintViolationException)7 Node (org.neo4j.graphdb.Node)7 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)7 LinkedList (java.util.LinkedList)6 SystemException (javax.transaction.SystemException)6 XAException (javax.transaction.xa.XAException)6 XAResource (javax.transaction.xa.XAResource)6 KernelException (org.neo4j.exceptions.KernelException)6 EntityNotFoundException (org.neo4j.internal.kernel.api.exceptions.EntityNotFoundException)6 InvalidTransactionTypeKernelException (org.neo4j.internal.kernel.api.exceptions.InvalidTransactionTypeKernelException)6 PropertyKeyIdNotFoundKernelException (org.neo4j.internal.kernel.api.exceptions.PropertyKeyIdNotFoundKernelException)6 IllegalTokenNameException (org.neo4j.internal.kernel.api.exceptions.schema.IllegalTokenNameException)6 TokenCapacityExceededKernelException (org.neo4j.internal.kernel.api.exceptions.schema.TokenCapacityExceededKernelException)6 XaDataSource (org.neo4j.kernel.impl.transaction.xaframework.XaDataSource)6 XaResource (org.neo4j.kernel.impl.transaction.xaframework.XaResource)6 IOException (java.io.IOException)5