Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
100
{ @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestTransactionImpl.java
101
public class TestManualAcquireLock extends AbstractNeo4jTestCase { private Worker worker; @Before public void doBefore() throws Exception { worker = new Worker(); } @After public void doAfter() throws Exception { worker.close(); } @Test public void releaseReleaseManually() throws Exception { String key = "name"; Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Worker worker = new Worker(); Lock nodeLock = tx.acquireWriteLock( node ); worker.beginTx(); try { worker.setProperty( node, key, "ksjd" ); fail( "Shouldn't be able to grab it" ); } catch ( Exception e ) { } nodeLock.release(); worker.setProperty( node, key, "yo" ); worker.finishTx(); } @Test public void canOnlyReleaseOnce() throws Exception { Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Lock nodeLock = tx.acquireWriteLock( node ); nodeLock.release(); try { nodeLock.release(); fail( "Shouldn't be able to release more than once" ); } catch ( IllegalStateException e ) { // Good } } @Test public void makeSureNodeStaysLockedEvenAfterManualRelease() throws Exception { String key = "name"; Node node = getGraphDb().createNode(); Transaction tx = newTransaction(); Lock nodeLock = tx.acquireWriteLock( node ); node.setProperty( key, "value" ); nodeLock.release(); Worker worker = new Worker(); worker.beginTx(); try { worker.setProperty( node, key, "ksjd" ); fail( "Shouldn't be able to grab it" ); } catch ( Exception e ) { } commit(); tx.success(); tx.finish(); worker.finishTx(); } private class State { private final GraphDatabaseService graphDb; private Transaction tx; public State( GraphDatabaseService graphDb ) { this.graphDb = graphDb; } } private class Worker extends OtherThreadExecutor<State> { public Worker() { super( "other thread", new State( getGraphDb() ) ); } void beginTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx = state.graphDb.beginTx(); return null; } } ); } void finishTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } ); } void setProperty( final Node node, final String key, final Object value ) throws Exception { execute( new WorkerCommand<State, Object>() { @Override public Object doWork( State state ) { node.setProperty( key, value ); return null; } }, 200, MILLISECONDS ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
102
public class TestTransactionImpl { @Test public void shouldBeAbleToAccessAllExceptionsOccurringInSynchronizationsBeforeCompletion() throws IllegalStateException, RollbackException { TxManager mockedTxManager = mock( TxManager.class ); TransactionImpl tx = new TransactionImpl( getNewGlobalId( DEFAULT_SEED, 0 ), mockedTxManager, ForceMode.forced, TransactionStateFactory.noStateFactory( new DevNullLoggingService() ), new SystemOutLogging().getMessagesLog( TxManager.class ) ); // Evil synchronizations final RuntimeException firstException = new RuntimeException( "Ex1" ); Synchronization meanSync1 = new Synchronization() { @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } }; final RuntimeException secondException = new RuntimeException( "Ex1" ); Synchronization meanSync2 = new Synchronization() { @Override public void beforeCompletion() { throw secondException; } @Override public void afterCompletion( int status ) { } }; tx.registerSynchronization( meanSync1 ); tx.registerSynchronization( meanSync2 ); tx.doBeforeCompletion(); assertThat( tx.getRollbackCause(), is( instanceOf( MultipleCauseException.class ) ) ); MultipleCauseException error = (MultipleCauseException) tx.getRollbackCause(); assertThat( error.getCause(), is( (Throwable) firstException ) ); assertThat( error.getCauses().size(), is( 2 ) ); assertThat( error.getCauses().get( 0 ), is( (Throwable) firstException ) ); assertThat( error.getCauses().get( 1 ), is( (Throwable) secondException ) ); } @Test public void shouldNotThrowMultipleCauseIfOnlyOneErrorOccursInBeforeCompletion() throws IllegalStateException, RollbackException { TxManager mockedTxManager = mock( TxManager.class ); TransactionImpl tx = new TransactionImpl( getNewGlobalId( DEFAULT_SEED, 0 ), mockedTxManager, ForceMode.forced, TransactionStateFactory.noStateFactory( new DevNullLoggingService() ), new SystemOutLogging().getMessagesLog( TxManager.class ) ); // Evil synchronizations final RuntimeException firstException = new RuntimeException( "Ex1" ); Synchronization meanSync1 = new Synchronization() { @Override public void beforeCompletion() { throw firstException; } @Override public void afterCompletion( int status ) { } }; tx.registerSynchronization( meanSync1 ); tx.doBeforeCompletion(); assertThat( tx.getRollbackCause(), is( (Throwable) firstException ) ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestTransactionImpl.java
103
public class StressThread extends Thread { private final Random rand = new Random( currentTimeMillis() ); private final Object READ = new Object(); private final Object WRITE = new Object(); private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final Object resource; private final CountDownLatch startSignal; private final Transaction tx = mock( Transaction.class ); private Exception error; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, Object resource, CountDownLatch startSignal ) { super(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.resource = resource; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<Object>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); if ( f < readWriteRatio ) { lm.getReadLock( resource, tx ); lockStack.push( READ ); } else { lm.getWriteLock( resource, tx ); lockStack.push( WRITE ); } } while ( --depth > 0 ); while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resource, tx ); } else { lm.releaseWriteLock( resource , tx ); } } } catch ( DeadlockDetectedException e ) { } finally { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resource, tx ); } else { lm.releaseWriteLock( resource , tx ); } } } } } catch ( Exception e ) { error = e; } } @Override public String toString() { return this.name; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestRWLock.java
104
public class TestRWLock { private LockManagerImpl lm; @Before public void before() throws Exception { lm = new LockManagerImpl( new RagManager() ); } @Test public void testSingleThread() throws Exception { Transaction tx = mock( Transaction.class ); try { lm.getReadLock( null, tx ); fail( "Null parameter should throw exception" ); } catch ( Exception e ) { // good } try { lm.getWriteLock( null, tx ); fail( "Null parameter should throw exception" ); } catch ( Exception e ) { // good } try { lm.releaseReadLock( null, tx ); fail( "Null parameter should throw exception" ); } catch ( Exception e ) { // good } try { lm.releaseWriteLock( null, tx ); fail( "Null parameter should throw exception" ); } catch ( Exception e ) { // good } Object entity = new Object(); try { lm.releaseWriteLock( entity, tx ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } try { lm.releaseReadLock( entity, tx ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } lm.getReadLock( entity, tx ); try { lm.releaseWriteLock( entity, tx ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } lm.releaseReadLock( entity, tx ); lm.getWriteLock( entity, tx ); try { lm.releaseReadLock( entity, tx ); fail( "Invalid release should throw exception" ); } catch ( Exception e ) { // good } lm.releaseWriteLock( entity, tx ); lm.getReadLock( entity, tx ); lm.getWriteLock( entity, tx ); lm.releaseWriteLock( entity, tx ); lm.releaseReadLock( entity, tx ); lm.getWriteLock( entity, tx ); lm.getReadLock( entity, tx ); lm.releaseReadLock( entity, tx ); lm.releaseWriteLock( entity, tx ); for ( int i = 0; i < 10; i++ ) { if ( (i % 2) == 0 ) { lm.getWriteLock( entity, tx ); } else { lm.getReadLock( entity, tx ); } } for ( int i = 9; i >= 0; i-- ) { if ( (i % 2) == 0 ) { lm.releaseWriteLock( entity , tx ); } else { lm.releaseReadLock( entity, tx ); } } } @Test public void testMultipleThreads() { LockWorker t1 = new LockWorker( "T1", lm ); LockWorker t2 = new LockWorker( "T2", lm ); LockWorker t3 = new LockWorker( "T3", lm ); LockWorker t4 = new LockWorker( "T4", lm ); ResourceObject r1 = newResourceObject( "R1" ); try { t1.getReadLock( r1, true ); t2.getReadLock( r1, true ); t3.getReadLock( r1, true ); Future<Void> t4Wait = t4.getWriteLock( r1, false ); t3.releaseReadLock( r1 ); t2.releaseReadLock( r1 ); assertTrue( !t4Wait.isDone() ); t1.releaseReadLock( r1 ); // now we can wait for write lock since it can be acquired // get write lock t4.awaitFuture( t4Wait ); t4.getReadLock( r1, true ); t4.getReadLock( r1, true ); // put readlock in queue Future<Void> t1Wait = t1.getReadLock( r1, false ); t4.getReadLock( r1, true ); t4.releaseReadLock( r1 ); t4.getWriteLock( r1, true ); t4.releaseWriteLock( r1 ); assertTrue( !t1Wait.isDone() ); t4.releaseWriteLock( r1 ); // get read lock t1.awaitFuture( t1Wait ); t4.releaseReadLock( r1 ); // t4 now has 1 readlock and t1 one readlock // let t1 drop readlock and t4 get write lock t4Wait = t4.getWriteLock( r1, false ); t1.releaseReadLock( r1 ); t4.awaitFuture( t4Wait ); t4.releaseReadLock( r1 ); t4.releaseWriteLock( r1 ); t4.getWriteLock( r1, true ); t1Wait = t1.getReadLock( r1, false ); Future<Void> t2Wait = t2.getReadLock( r1, false ); Future<Void> t3Wait = t3.getReadLock( r1, false ); t4.getReadLock( r1, true ); t4.releaseWriteLock( r1 ); t1.awaitFuture( t1Wait ); t2.awaitFuture( t2Wait ); t3.awaitFuture( t3Wait ); t1Wait = t1.getWriteLock( r1, false ); t2.releaseReadLock( r1 ); t4.releaseReadLock( r1 ); t3.releaseReadLock( r1 ); t1.awaitFuture( t1Wait ); t1.releaseWriteLock( r1 ); t2.getReadLock( r1, true ); t1.releaseReadLock( r1 ); t2.getWriteLock( r1, true ); t2.releaseWriteLock( r1 ); t2.releaseReadLock( r1 ); } catch ( Exception e ) { File file = new LockWorkFailureDump( getClass() ).dumpState( lm, new LockWorker[] { t1, t2, t3, t4 } ); throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e ); } } public class StressThread extends Thread { private final Random rand = new Random( currentTimeMillis() ); private final Object READ = new Object(); private final Object WRITE = new Object(); private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final Object resource; private final CountDownLatch startSignal; private final Transaction tx = mock( Transaction.class ); private Exception error; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, Object resource, CountDownLatch startSignal ) { super(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.resource = resource; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<Object>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); if ( f < readWriteRatio ) { lm.getReadLock( resource, tx ); lockStack.push( READ ); } else { lm.getWriteLock( resource, tx ); lockStack.push( WRITE ); } } while ( --depth > 0 ); while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resource, tx ); } else { lm.releaseWriteLock( resource , tx ); } } } catch ( DeadlockDetectedException e ) { } finally { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resource, tx ); } else { lm.releaseWriteLock( resource , tx ); } } } } } catch ( Exception e ) { error = e; } } @Override public String toString() { return this.name; } } @Test public void testStressMultipleThreads() throws Exception { ResourceObject r1 = new ResourceObject( "R1" ); StressThread stressThreads[] = new StressThread[100]; CountDownLatch startSignal = new CountDownLatch( 1 ); for ( int i = 0; i < 100; i++ ) { stressThreads[i] = new StressThread( "Thread" + i, 100, 9, 0.50f, r1, startSignal ); } for ( int i = 0; i < 100; i++ ) { stressThreads[i].start(); } startSignal.countDown(); long end = currentTimeMillis() + SECONDS.toMillis( 20 ); boolean anyAlive = true; while ( (anyAlive = anyAliveAndAllWell( stressThreads )) && currentTimeMillis() < end ) { sleepALittle(); } assertFalse( anyAlive ); for ( StressThread stressThread : stressThreads ) if ( stressThread.error != null ) throw stressThread.error; } private void sleepALittle() { try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { Thread.interrupted(); } } private boolean anyAliveAndAllWell( StressThread[] stressThreads ) { for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) return false; if ( stressThread.isAlive() ) return true; } return false; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestRWLock.java
105
{ @Override public Object doWork( State state ) { node.setProperty( key, value ); return null; } }, 200, MILLISECONDS );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
106
{ @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
107
{ @Override public Void doWork( State state ) { state.tx = state.graphDb.beginTx(); return null; } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
108
private class Worker extends OtherThreadExecutor<State> { public Worker() { super( "other thread", new State( getGraphDb() ) ); } void beginTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx = state.graphDb.beginTx(); return null; } } ); } void finishTx() throws Exception { execute( new WorkerCommand<State, Void>() { @Override public Void doWork( State state ) { state.tx.success(); state.tx.finish(); return null; } } ); } void setProperty( final Node node, final String key, final Object value ) throws Exception { execute( new WorkerCommand<State, Object>() { @Override public Object doWork( State state ) { node.setProperty( key, value ); return null; } }, 200, MILLISECONDS ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestManualAcquireLock.java
109
public static class Adapter implements Monitor { @Override public void txStarted( Xid xid ) { } @Override public void txCommitted( Xid xid ) { } @Override public void txRolledBack( Xid xid ) { } @Override public void txManagerStopped() { } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
110
private class TxHook implements javax.transaction.Synchronization { boolean gotBefore = false; boolean gotAfter = false; int statusBefore = -1; int statusAfter = -1; Transaction txBefore = null; Transaction txAfter = null; public void beforeCompletion() { try { statusBefore = tm.getStatus(); txBefore = tm.getTransaction(); gotBefore = true; } catch ( Exception e ) { throw new RuntimeException( "" + e ); } } public void afterCompletion( int status ) { try { statusAfter = status; txAfter = tm.getTransaction(); assertTrue( status == tm.getStatus() ); gotAfter = true; } catch ( Exception e ) { throw new RuntimeException( "" + e ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
111
public class TestDeadlockDetection { @Test public void testDeadlockDetection() throws Exception { ResourceObject r1 = newResourceObject( "R1" ); ResourceObject r2 = newResourceObject( "R2" ); ResourceObject r3 = newResourceObject( "R3" ); ResourceObject r4 = newResourceObject( "R4" ); PlaceboTm tm = new PlaceboTm( null, null ); LockManager lm = new LockManagerImpl( new RagManager() ); tm.setLockManager( lm ); LockWorker t1 = new LockWorker( "T1", lm ); LockWorker t2 = new LockWorker( "T2", lm ); LockWorker t3 = new LockWorker( "T3", lm ); LockWorker t4 = new LockWorker( "T4", lm ); try { t1.getReadLock( r1, true ); t1.getReadLock( r4, true ); t2.getReadLock( r2, true ); t2.getReadLock( r3, true ); t3.getReadLock( r3, true ); t3.getWriteLock( r1, false ); // t3-r1-t1 // T3 t2.getWriteLock( r4, false ); // t2-r4-t1 t1.getWriteLock( r2, true ); assertTrue( t1.isLastGetLockDeadLock() ); // t1-r2-t2-r4-t1 // resolve and try one more time t1.releaseReadLock( r4 ); // will give r4 to t2 t1.getWriteLock( r2, false ); // t1-r2-t2 t2.releaseReadLock( r2 ); // will give r2 to t1 t1.getWriteLock( r4, false ); // t1-r4-t2 // T1 // dead lock t2.getWriteLock( r2, true ); // T2 assertTrue( t2.isLastGetLockDeadLock() ); // t2-r2-t3-r1-t1-r4-t2 or t2-r2-t1-r4-t2 t2.releaseWriteLock( r4 ); // give r4 to t1 t1.releaseWriteLock( r4 ); t2.getReadLock( r4, true ); t1.releaseWriteLock( r2 ); t1.getReadLock( r2, true ); t1.releaseReadLock( r1 ); // give r1 to t3 t3.getReadLock( r2, true ); t3.releaseWriteLock( r1 ); t1.getReadLock( r1, true ); // give r1->t1 t1.getWriteLock( r4, false ); t3.getWriteLock( r1, false ); t4.getReadLock( r2, true ); // deadlock t2.getWriteLock( r2, true ); assertTrue( t2.isLastGetLockDeadLock() ); // t2-r2-t3-r1-t1-r4-t2 // resolve t2.releaseReadLock( r4 ); t1.releaseWriteLock( r4 ); t1.releaseReadLock( r1 ); t2.getReadLock( r4, true ); // give r1 to t3 t3.releaseWriteLock( r1 ); t1.getReadLock( r1, true ); // give r1 to t1 t1.getWriteLock( r4, false ); t3.releaseReadLock( r2 ); t3.getWriteLock( r1, false ); // cleanup t2.releaseReadLock( r4 ); // give r4 to t1 t1.releaseWriteLock( r4 ); t1.releaseReadLock( r1 ); // give r1 to t3 t3.releaseWriteLock( r1 ); t1.releaseReadLock( r2 ); t4.releaseReadLock( r2 ); t2.releaseReadLock( r3 ); t3.releaseReadLock( r3 ); // -- special case... t1.getReadLock( r1, true ); t2.getReadLock( r1, true ); t1.getWriteLock( r1, false ); // t1->r1-t1&t2 t2.getWriteLock( r1, true ); assertTrue( t2.isLastGetLockDeadLock() ); // t2->r1->t1->r1->t2 t2.releaseReadLock( r1 ); t1.releaseReadLock( r1 ); t1.releaseWriteLock( r1 ); } catch ( Exception e ) { File file = new LockWorkFailureDump( getClass() ).dumpState( lm, new LockWorker[] { t1, t2, t3, t4 } ); throw new RuntimeException( "Failed, forensics information dumped to " + file.getAbsolutePath(), e ); } } public static class StressThread extends Thread { private static final Object READ = new Object(); private static final Object WRITE = new Object(); private static ResourceObject resources[] = new ResourceObject[10]; private final Random rand = new Random( currentTimeMillis() ); static { for ( int i = 0; i < resources.length; i++ ) resources[i] = new ResourceObject( "RX" + i ); } private final CountDownLatch startSignal; private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final LockManager lm; private volatile Exception error; private final Transaction tx = mock( Transaction.class ); public volatile Long startedWaiting = null; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, LockManager lm, CountDownLatch startSignal ) { super(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.lm = lm; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<Object>(); java.util.Stack<ResourceObject> resourceStack = new java.util.Stack<ResourceObject>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); int n = rand.nextInt( resources.length ); if ( f < readWriteRatio ) { startedWaiting = currentTimeMillis(); lm.getReadLock( resources[n], tx ); startedWaiting = null; lockStack.push( READ ); } else { startedWaiting = currentTimeMillis(); lm.getWriteLock( resources[n], tx ); startedWaiting = null; lockStack.push( WRITE ); } resourceStack.push( resources[n] ); } while ( --depth > 0 ); } catch ( DeadlockDetectedException e ) { // This is good } finally { releaseAllLocks( lockStack, resourceStack ); } } } catch ( Exception e ) { error = e; } } private void releaseAllLocks( Stack<Object> lockStack, Stack<ResourceObject> resourceStack ) { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resourceStack.pop(), tx ); } else { lm.releaseWriteLock( resourceStack.pop(), tx ); } } } @Override public String toString() { return this.name; } } @Test public void testStressMultipleThreads() throws Exception { /* This test starts a bunch of threads, and randomly takes read or write locks on random resources. No thread should wait more than five seconds for a lock - if it does, we consider it a failure. Successful outcomes are when threads either finish with all their lock taking and releasing, or are terminated with a DeadlockDetectedException. */ for ( int i = 0; i < StressThread.resources.length; i++ ) { StressThread.resources[i] = new ResourceObject( "RX" + i ); } StressThread stressThreads[] = new StressThread[50]; PlaceboTm tm = new PlaceboTm( null, null ); LockManager lm = new LockManagerImpl( new RagManager() ); tm.setLockManager( lm ); CountDownLatch startSignal = new CountDownLatch( 1 ); for ( int i = 0; i < stressThreads.length; i++ ) { int numberOfIterations = 100; int depthCount = 10; float readWriteRatio = 0.80f; stressThreads[i] = new StressThread( "T" + i, numberOfIterations, depthCount, readWriteRatio, lm, startSignal ); } for ( Thread thread : stressThreads ) { thread.start(); } startSignal.countDown(); while ( anyAliveAndAllWell( stressThreads ) ) { throwErrorsIfAny( stressThreads ); sleepALittle(); } } private String diagnostics( StressThread culprit, StressThread[] stressThreads, long waited ) { StringBuilder builder = new StringBuilder(); for ( StressThread stressThread : stressThreads ) { if ( stressThread.isAlive() ) { if ( stressThread == culprit ) { builder.append( "This is the thread that waited too long. It waited: " ).append( waited ).append( " milliseconds" ); } for ( StackTraceElement element : stressThread.getStackTrace() ) { builder.append( element.toString() ).append( "\n" ); } } builder.append( "\n" ); } return builder.toString(); } private void throwErrorsIfAny( StressThread[] stressThreads ) throws Exception { for ( StressThread stressThread : stressThreads ) { if ( stressThread.error != null ) { throw stressThread.error; } } } private void sleepALittle() { try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) { Thread.interrupted(); } } private boolean anyAliveAndAllWell( StressThread[] stressThreads ) { for ( StressThread stressThread : stressThreads ) { if ( stressThread.isAlive() ) { Long startedWaiting = stressThread.startedWaiting; if ( startedWaiting != null ) { long waitingTime = currentTimeMillis() - startedWaiting; if ( waitingTime > 5000 ) { fail( "One of the threads waited far too long. Diagnostics: \n" + diagnostics( stressThread, stressThreads, waitingTime) ); } } return true; } } return false; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestDeadlockDetection.java
112
public class SimpleTxHook implements Synchronization { private volatile boolean gotBefore, gotAfter; @Override public void beforeCompletion() { gotBefore = true; } @Override public void afterCompletion( int status ) { gotAfter = true; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
113
{ @Override public Object doWork( Void state ) { try { tm.begin(); tm.getTransaction().registerSynchronization( hook ); return null; } catch ( Exception e ) { throw new RuntimeException( e ); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
114
{ @Override public Object doWork( Void state ) { try { tm.rollback(); } catch ( Exception e ) { throw new RuntimeException( e ); } return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
115
{ @Override public Object doWork( Void state ) { try { tm.commit(); } catch ( Exception e ) { throw new RuntimeException( e ); } return null; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
116
public class TestJtaCompliance extends AbstractNeo4jTestCase { public class SimpleTxHook implements Synchronization { private volatile boolean gotBefore, gotAfter; @Override public void beforeCompletion() { gotBefore = true; } @Override public void afterCompletion( int status ) { gotAfter = true; } } // the TransactionManager to use when testing for JTA compliance private TransactionManager tm; private XaDataSourceManager xaDsMgr; private KernelHealth kernelHealth; @Before public void setUpFramework() { getTransaction().finish(); tm = getGraphDbAPI().getDependencyResolver().resolveDependency( TransactionManager.class ); kernelHealth = getGraphDbAPI().getDependencyResolver().resolveDependency( KernelHealth.class ); xaDsMgr = getGraphDbAPI().getDependencyResolver().resolveDependency( XaDataSourceManager.class ); java.util.Map<String,String> map1 = new java.util.HashMap<String,String>(); map1.put( "store_dir", "target/var" ); java.util.Map<String,String> map2 = new java.util.HashMap<>(); map2.put( "store_dir", "target/var" ); try { xaDsMgr.registerDataSource( new OtherDummyXaDataSource( "fakeRes1", UTF8.encode( "0xDDDDDE" ), new FakeXAResource( "XAResource1" ) )); xaDsMgr.registerDataSource( new OtherDummyXaDataSource( "fakeRes2", UTF8.encode( "0xDDDDDF" ), new FakeXAResource( "XAResource2" ) )); } catch ( Exception e ) { e.printStackTrace(); } try { // make sure were not in transaction tm.commit(); } catch ( Exception e ) { } Transaction tx = null; try { tx = tm.getTransaction(); } catch ( Exception e ) { throw new RuntimeException( "Unknown state of TM" ); } if ( tx != null ) { throw new RuntimeException( "We're still in transaction" ); } } @After public void tearDownFramework() { xaDsMgr.unregisterDataSource( "fakeRes1" ); xaDsMgr.unregisterDataSource( "fakeRes2" ); try { if ( tm.getTransaction() == null ) { try { tm.begin(); } catch ( Exception e ) { } } } catch ( SystemException e ) { e.printStackTrace(); } } /** * o Tests that tm.begin() starts a global transaction and associates the * calling thread with that transaction. o Tests that after commit is * invoked transaction is completed and a repeating call to commit/rollback * results in an exception. * * TODO: check if commit is restricted to the thread that started the * transaction, if not, do some testing. */ @Test public void testBeginCommit() throws Exception { tm.begin(); assertTrue( tm.getTransaction() != null ); tm.commit(); // drop current transaction assertEquals( Status.STATUS_NO_TRANSACTION, tm.getStatus() ); try { tm.rollback(); fail( "rollback() should throw an exception -> " + "STATUS_NO_TRANSACTION" ); } catch ( IllegalStateException e ) { // good } try { tm.commit(); fail( "commit() should throw an exception -> " + "STATUS_NO_TRANSACTION" ); } catch ( IllegalStateException e ) { // good } } /** * o Tests that after rollback is invoked the transaction is completed and a * repeating call to rollback/commit results in an exception. * * TODO: check if rollback is restricted to the thread that started the * transaction, if not, do some testing. */ @Test public void testBeginRollback() throws Exception { tm.begin(); assertTrue( tm.getTransaction() != null ); tm.rollback(); // drop current transaction assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION ); try { tm.commit(); fail( "commit() should throw an exception -> " + "STATUS_NO_TRANSACTION" ); } catch ( IllegalStateException e ) { // good } try { tm.rollback(); fail( "rollback() should throw an exception -> " + "STATUS_NO_TRANSACTION" ); } catch ( IllegalStateException e ) { // good } } /** * o Tests that suspend temporarily suspends the transaction associated with * the calling thread. o Tests that resume reinstate the transaction with * the calling thread. o Tests that an invalid transaction passed to resume * won't be associated with the calling thread. o Tests that XAResource.end * is invoked with TMSUSPEND when transaction is suspended. o Tests that * XAResource.start is invoked with TMRESUME when transaction is resumed. * * TODO: o Test that resume throws an exception if the transaction is * already associated with another thread. o Test if a suspended thread may * be resumed by another thread. */ @Test public void testSuspendResume() throws Exception { tm.begin(); Transaction tx = tm.getTransaction(); FakeXAResource res = new FakeXAResource( "XAResource1" ); tx.enlistResource( res ); // suspend assertTrue( tm.suspend() == tx ); tx.delistResource( res, XAResource.TMSUSPEND ); MethodCall calls[] = res.getAndRemoveMethodCalls(); assertEquals( 2, calls.length ); assertEquals( "start", calls[0].getMethodName() ); Object args[] = calls[0].getArgs(); assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); assertEquals( "end", calls[1].getMethodName() ); args = calls[1].getArgs(); assertEquals( XAResource.TMSUSPEND, ((Integer) args[1]).intValue() ); // resume tm.resume( tx ); tx.enlistResource( res ); calls = res.getAndRemoveMethodCalls(); assertEquals( 1, calls.length ); assertEquals( "start", calls[0].getMethodName() ); args = calls[0].getArgs(); assertEquals( XAResource.TMRESUME, ((Integer) args[1]).intValue() ); assertTrue( tm.getTransaction() == tx ); tx.delistResource( res, XAResource.TMSUCCESS ); tm.commit(); tm.resume( tx ); assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION ); assertTrue( tm.getTransaction() == null ); // tm.resume( my fake implementation of transaction ); // assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION ); // assertTrue( tm.getTransaction() == null ); } /** * o Tests two-phase commits with two different fake XAResource * implementations so a branch is created within the same global * transaction. */ @Test public void test2PhaseCommits1() throws Exception { tm.begin(); FakeXAResource res1 = new FakeXAResource( "XAResource1" ); FakeXAResource res2 = new FakeXAResource( "XAResource2" ); // enlist two different resources and verify that the start method // is invoked with correct flags // res1 tm.getTransaction().enlistResource( res1 ); MethodCall calls1[] = res1.getAndRemoveMethodCalls(); assertEquals( 1, calls1.length ); assertEquals( "start", calls1[0].getMethodName() ); // res2 tm.getTransaction().enlistResource( res2 ); MethodCall calls2[] = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); assertEquals( "start", calls2[0].getMethodName() ); // verify Xid Object args[] = calls1[0].getArgs(); Xid xid1 = (Xid) args[0]; assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); args = calls2[0].getArgs(); Xid xid2 = (Xid) args[0]; assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); // should have same global transaction id byte globalTxId1[] = xid1.getGlobalTransactionId(); byte globalTxId2[] = xid2.getGlobalTransactionId(); assertTrue( globalTxId1.length == globalTxId2.length ); for ( int i = 0; i < globalTxId1.length; i++ ) { assertEquals( globalTxId1[i], globalTxId2[i] ); } byte branch1[] = xid1.getBranchQualifier(); byte branch2[] = xid2.getBranchQualifier(); // make sure a different branch was created if ( branch1.length == branch2.length ) { boolean same = true; for ( int i = 0; i < branch1.length; i++ ) { if ( branch1[i] != branch2[i] ) { same = false; break; } } assertTrue( !same ); } // verify delist of resource tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS ); calls2 = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS ); calls1 = res1.getAndRemoveMethodCalls(); // res1 assertEquals( 1, calls1.length ); assertEquals( "end", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // res2 assertEquals( 1, calls2.length ); assertEquals( "end", calls2[0].getMethodName() ); args = calls2[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // verify proper prepare/commit tm.commit(); calls1 = res1.getAndRemoveMethodCalls(); calls2 = res2.getAndRemoveMethodCalls(); // res1 assertEquals( 2, calls1.length ); assertEquals( "prepare", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); assertEquals( "commit", calls1[1].getMethodName() ); args = calls1[1].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); assertEquals( false, ((Boolean) args[1]).booleanValue() ); // res2 assertEquals( 2, calls2.length ); assertEquals( "prepare", calls2[0].getMethodName() ); args = calls2[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); assertEquals( "commit", calls2[1].getMethodName() ); args = calls2[1].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); assertEquals( false, ((Boolean) args[1]).booleanValue() ); } /** * o Tests that two enlistments of same resource (according to the * isSameRM() method) only receive one set of prepare/commit calls. */ @Test public void test2PhaseCommits2() throws Exception { tm.begin(); FakeXAResource res1 = new FakeXAResource( "XAResource1" ); FakeXAResource res2 = new FakeXAResource( "XAResource1" ); // enlist two (same) resources and verify that the start method // is invoked with correct flags // res1 tm.getTransaction().enlistResource( res1 ); MethodCall calls1[] = res1.getAndRemoveMethodCalls(); assertEquals( 1, calls1.length ); assertEquals( "start", calls1[0].getMethodName() ); // res2 tm.getTransaction().enlistResource( res2 ); MethodCall calls2[] = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); assertEquals( "start", calls2[0].getMethodName() ); // make sure we get a two-phase commit FakeXAResource res3 = new FakeXAResource( "XAResource2" ); tm.getTransaction().enlistResource( res3 ); // verify Xid and flags Object args[] = calls1[0].getArgs(); Xid xid1 = (Xid) args[0]; assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); args = calls2[0].getArgs(); Xid xid2 = (Xid) args[0]; assertEquals( XAResource.TMJOIN, ((Integer) args[1]).intValue() ); assertTrue( xid1.equals( xid2 ) ); assertTrue( xid2.equals( xid1 ) ); // verify delist of resource tm.getTransaction().delistResource( res3, XAResource.TMSUCCESS ); tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS ); calls2 = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS ); calls1 = res1.getAndRemoveMethodCalls(); // res1 assertEquals( 1, calls1.length ); assertEquals( "end", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // res2 assertEquals( 1, calls2.length ); assertEquals( "end", calls2[0].getMethodName() ); args = calls2[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // verify proper prepare/commit tm.commit(); calls1 = res1.getAndRemoveMethodCalls(); calls2 = res2.getAndRemoveMethodCalls(); // res1 assertEquals( 2, calls1.length ); assertEquals( "prepare", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( args[0].equals( xid1 ) ); assertEquals( "commit", calls1[1].getMethodName() ); args = calls1[1].getArgs(); assertTrue( args[0].equals( xid1 ) ); assertEquals( false, ((Boolean) args[1]).booleanValue() ); // res2 assertEquals( 0, calls2.length ); } /** * o Tests that multiple enlistments receive rollback calls properly. */ @Test public void testRollback1() throws Exception { tm.begin(); FakeXAResource res1 = new FakeXAResource( "XAResource1" ); FakeXAResource res2 = new FakeXAResource( "XAResource2" ); // enlist two different resources and verify that the start method // is invoked with correct flags // res1 tm.getTransaction().enlistResource( res1 ); MethodCall calls1[] = res1.getAndRemoveMethodCalls(); assertEquals( 1, calls1.length ); assertEquals( "start", calls1[0].getMethodName() ); // res2 tm.getTransaction().enlistResource( res2 ); MethodCall calls2[] = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); assertEquals( "start", calls2[0].getMethodName() ); // verify Xid Object args[] = calls1[0].getArgs(); Xid xid1 = (Xid) args[0]; assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); args = calls2[0].getArgs(); Xid xid2 = (Xid) args[0]; assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); // should have same global transaction id byte globalTxId1[] = xid1.getGlobalTransactionId(); byte globalTxId2[] = xid2.getGlobalTransactionId(); assertTrue( globalTxId1.length == globalTxId2.length ); for ( int i = 0; i < globalTxId1.length; i++ ) { assertEquals( globalTxId1[i], globalTxId2[i] ); } byte branch1[] = xid1.getBranchQualifier(); byte branch2[] = xid2.getBranchQualifier(); // make sure a different branch was created if ( branch1.length == branch2.length ) { boolean same = true; for ( int i = 0; i < branch1.length; i++ ) { if ( branch1[i] != branch2[i] ) { same = false; break; } } assertTrue( !same ); } // verify delist of resource tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS ); calls2 = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS ); calls1 = res1.getAndRemoveMethodCalls(); // res1 assertEquals( 1, calls1.length ); assertEquals( "end", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // res2 assertEquals( 1, calls2.length ); assertEquals( "end", calls2[0].getMethodName() ); args = calls2[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // verify proper rollback tm.rollback(); calls1 = res1.getAndRemoveMethodCalls(); calls2 = res2.getAndRemoveMethodCalls(); // res1 assertEquals( 1, calls1.length ); assertEquals( "rollback", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); // res2 assertEquals( 1, calls2.length ); assertEquals( "rollback", calls2[0].getMethodName() ); args = calls2[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); } /* * o Tests that multiple enlistments of same (according to isSameRM() * method) only receive one set of rollback calls. */ @Test public void testRollback2() throws Exception { tm.begin(); FakeXAResource res1 = new FakeXAResource( "XAResource1" ); FakeXAResource res2 = new FakeXAResource( "XAResource1" ); // enlist two (same) resources and verify that the start method // is invoked with correct flags // res1 tm.getTransaction().enlistResource( res1 ); MethodCall calls1[] = res1.getAndRemoveMethodCalls(); assertEquals( 1, calls1.length ); assertEquals( "start", calls1[0].getMethodName() ); // res2 tm.getTransaction().enlistResource( res2 ); MethodCall calls2[] = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); assertEquals( "start", calls2[0].getMethodName() ); // verify Xid and flags Object args[] = calls1[0].getArgs(); Xid xid1 = (Xid) args[0]; assertEquals( XAResource.TMNOFLAGS, ((Integer) args[1]).intValue() ); args = calls2[0].getArgs(); Xid xid2 = (Xid) args[0]; assertEquals( XAResource.TMJOIN, ((Integer) args[1]).intValue() ); assertTrue( xid1.equals( xid2 ) ); assertTrue( xid2.equals( xid1 ) ); // verify delist of resource tm.getTransaction().delistResource( res2, XAResource.TMSUCCESS ); calls2 = res2.getAndRemoveMethodCalls(); assertEquals( 1, calls2.length ); tm.getTransaction().delistResource( res1, XAResource.TMSUCCESS ); calls1 = res1.getAndRemoveMethodCalls(); // res1 assertEquals( 1, calls1.length ); assertEquals( "end", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // res2 assertEquals( 1, calls2.length ); assertEquals( "end", calls2[0].getMethodName() ); args = calls2[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid2 ) ); assertEquals( XAResource.TMSUCCESS, ((Integer) args[1]).intValue() ); // verify proper prepare/commit tm.rollback(); calls1 = res1.getAndRemoveMethodCalls(); calls2 = res2.getAndRemoveMethodCalls(); // res1 assertEquals( 1, calls1.length ); assertEquals( "rollback", calls1[0].getMethodName() ); args = calls1[0].getArgs(); assertTrue( ((Xid) args[0]).equals( xid1 ) ); // res2 assertEquals( 0, calls2.length ); } /** * o Tests if nested transactions are supported * * TODO: if supported, do some testing :) */ @Test public void testNestedTransactions() throws Exception { assertTrue( tm.getTransaction() == null ); tm.begin(); Transaction txParent = tm.getTransaction(); assertTrue( txParent != null ); try { tm.begin(); // ok supported // some tests that might be valid for true nested support // Transaction txChild = tm.getTransaction(); // assertTrue( txChild != txParent ); // tm.commit(); // assertTrue( txParent == tm.getTransaction() ); } catch ( NotSupportedException e ) { // well no nested transactions } tm.commit(); assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION ); } private class TxHook implements javax.transaction.Synchronization { boolean gotBefore = false; boolean gotAfter = false; int statusBefore = -1; int statusAfter = -1; Transaction txBefore = null; Transaction txAfter = null; public void beforeCompletion() { try { statusBefore = tm.getStatus(); txBefore = tm.getTransaction(); gotBefore = true; } catch ( Exception e ) { throw new RuntimeException( "" + e ); } } public void afterCompletion( int status ) { try { statusAfter = status; txAfter = tm.getTransaction(); assertTrue( status == tm.getStatus() ); gotAfter = true; } catch ( Exception e ) { throw new RuntimeException( "" + e ); } } } /** * o Tests that beforeCompletion and afterCompletion are invoked. o Tests * that the call is made in the same transaction context. o Tests status in * before and after methods depending on commit/rollback. * * NOTE: Not sure if the check of Status is correct according to * specification. */ @Test public void testTransactionHook() throws Exception { // test for commit tm.begin(); Transaction tx = tm.getTransaction(); TxHook txHook = new TxHook(); tx.registerSynchronization( txHook ); assertEquals( false, txHook.gotBefore ); assertEquals( false, txHook.gotAfter ); tm.commit(); assertEquals( true, txHook.gotBefore ); assertEquals( true, txHook.gotAfter ); assertTrue( tx == txHook.txBefore ); assertTrue( tx == txHook.txAfter ); assertEquals( Status.STATUS_ACTIVE, txHook.statusBefore ); assertEquals( Status.STATUS_COMMITTED, txHook.statusAfter ); // test for rollback tm.begin(); tx = tm.getTransaction(); txHook = new TxHook(); tx.registerSynchronization( txHook ); assertEquals( false, txHook.gotBefore ); assertEquals( false, txHook.gotAfter ); tm.rollback(); assertEquals( true, txHook.gotBefore ); assertEquals( true, txHook.gotAfter ); assertTrue( tx == txHook.txBefore ); assertTrue( tx == txHook.txAfter ); assertEquals( Status.STATUS_MARKED_ROLLBACK, txHook.statusBefore ); assertEquals( Status.STATUS_ROLLEDBACK, txHook.statusAfter ); } /** * Tests that the correct status is returned from TM. * * TODO: Implement a FakeXAResource to check: STATUS_COMMITTING * STATUS_PREPARED STATUS_PREPEARING STATUS_ROLLING_BACK */ @Test public void testStatus() throws Exception { assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION ); tm.begin(); assertTrue( tm.getStatus() == Status.STATUS_ACTIVE ); tm.getTransaction().setRollbackOnly(); assertTrue( tm.getStatus() == Status.STATUS_MARKED_ROLLBACK ); tm.rollback(); assertTrue( tm.getStatus() == Status.STATUS_NO_TRANSACTION ); } @Test public void shouldCallAfterCompletionsEvenOnCommitWhenTmNotOK() throws Exception { shouldCallAfterCompletionsEvenOnCloseWhenTmNotOK( commitTransaction() ); } @Test public void shouldCallAfterCompletionsEvenOnRollbackWhenTmNotOK() throws Exception { shouldCallAfterCompletionsEvenOnCloseWhenTmNotOK( rollbackTransaction() ); } private void shouldCallAfterCompletionsEvenOnCloseWhenTmNotOK( WorkerCommand<Void, Object> finish ) throws Exception { // GIVEN a transaction T1 SimpleTxHook hook = new SimpleTxHook(); OtherThreadExecutor<Void> t1 = new OtherThreadExecutor<Void>( "T1", null ); t1.execute( beginTransaction( hook ) ); // and a tx manager going in to a bad state tm.begin(); FakeXAResource resource = new FailingFakeXAResource( "XAResource1", true ); tm.getTransaction().enlistResource( resource ); try { tm.commit(); fail( "Should have failed commit" ); } catch ( Exception e ) { // YEY } // WHEN T1 tries to commit try { t1.execute( finish ); fail( "Should've failed" ); } catch ( Exception e ) { // YO } // THEN after completions should be called kernelHealth.healed(); assertTrue( hook.gotAfter ); } private WorkerCommand<Void, Object> commitTransaction() { return new WorkerCommand<Void, Object>() { @Override public Object doWork( Void state ) { try { tm.commit(); } catch ( Exception e ) { throw new RuntimeException( e ); } return null; } }; } private WorkerCommand<Void, Object> rollbackTransaction() { return new WorkerCommand<Void, Object>() { @Override public Object doWork( Void state ) { try { tm.rollback(); } catch ( Exception e ) { throw new RuntimeException( e ); } return null; } }; } private WorkerCommand<Void, Object> beginTransaction( final Synchronization hook ) { return new WorkerCommand<Void, Object>() { @Override public Object doWork( Void state ) { try { tm.begin(); tm.getTransaction().registerSynchronization( hook ); return null; } catch ( Exception e ) { throw new RuntimeException( e ); } } }; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestJtaCompliance.java
117
private static class VerificationLogHook extends LogHookAdapter<LogEntry> { private final Set<Xid> startXids = new HashSet<>(); @Override public boolean accept( LogEntry item ) { if ( item instanceof LogEntry.Start ) assertTrue( startXids.add( ((LogEntry.Start) item).getXid() ) ); return true; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestInjectMultipleStartEntries.java
118
public class TestInjectMultipleStartEntries { @Test public void fail_prepare_two_phase_transaction_should_not_yield_two_start_log_entries() throws Exception { // GIVEN // -- a database with one additional data source and some initial data GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ).newImpermanentDatabase( storeDir ); XaDataSourceManager xaDs = db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ); XaDataSource additionalDs = new OtherDummyXaDataSource( "dummy", "dummy".getBytes(), new FakeXAResource( "dummy" ) ); xaDs.registerDataSource( additionalDs ); Node node = createNodeWithOneRelationshipToIt( db ); // WHEN // -- doing a transaction involving both data sources and fails in prepare phase // due to invalid transaction data deleteNodeButNotItsRelationshipsInATwoPhaseTransaction( db, additionalDs, node ); db.shutdown(); // THEN // -- the logical log should only contain unique start entries after this transaction filterNeostoreLogicalLog( fs.get(), new File( storeDir, LOGICAL_LOG_DEFAULT_NAME + ".v0" ), new VerificationLogHook() ); } private final String storeDir = "dir"; @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private static class VerificationLogHook extends LogHookAdapter<LogEntry> { private final Set<Xid> startXids = new HashSet<>(); @Override public boolean accept( LogEntry item ) { if ( item instanceof LogEntry.Start ) assertTrue( startXids.add( ((LogEntry.Start) item).getXid() ) ); return true; } } private void deleteNodeButNotItsRelationshipsInATwoPhaseTransaction( GraphDatabaseAPI db, XaDataSource additionalDs, Node node ) throws Exception { Transaction tx = db.beginTx(); DependencyResolver dependencyResolver = db.getDependencyResolver(); TransactionManager transactionManager = dependencyResolver.resolveDependency(TransactionManager.class); additionalDs.getXaConnection().enlistResource( transactionManager.getTransaction() ); node.delete(); tx.success(); try { tx.finish(); fail( "This transaction shouldn't be successful" ); } catch ( TransactionFailureException e ) { // Good } } private Node createNodeWithOneRelationshipToIt( GraphDatabaseService db ) { Transaction tx = db.beginTx(); try { Node node = db.createNode(); node.createRelationshipTo( db.createNode(), MyRelTypes.TEST ); tx.success(); return node; } finally { tx.finish(); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestInjectMultipleStartEntries.java
119
public static class StressThread extends Thread { private static final Object READ = new Object(); private static final Object WRITE = new Object(); private static ResourceObject resources[] = new ResourceObject[10]; private final Random rand = new Random( currentTimeMillis() ); static { for ( int i = 0; i < resources.length; i++ ) resources[i] = new ResourceObject( "RX" + i ); } private final CountDownLatch startSignal; private final String name; private final int numberOfIterations; private final int depthCount; private final float readWriteRatio; private final LockManager lm; private volatile Exception error; private final Transaction tx = mock( Transaction.class ); public volatile Long startedWaiting = null; StressThread( String name, int numberOfIterations, int depthCount, float readWriteRatio, LockManager lm, CountDownLatch startSignal ) { super(); this.name = name; this.numberOfIterations = numberOfIterations; this.depthCount = depthCount; this.readWriteRatio = readWriteRatio; this.lm = lm; this.startSignal = startSignal; } @Override public void run() { try { startSignal.await(); java.util.Stack<Object> lockStack = new java.util.Stack<Object>(); java.util.Stack<ResourceObject> resourceStack = new java.util.Stack<ResourceObject>(); for ( int i = 0; i < numberOfIterations; i++ ) { try { int depth = depthCount; do { float f = rand.nextFloat(); int n = rand.nextInt( resources.length ); if ( f < readWriteRatio ) { startedWaiting = currentTimeMillis(); lm.getReadLock( resources[n], tx ); startedWaiting = null; lockStack.push( READ ); } else { startedWaiting = currentTimeMillis(); lm.getWriteLock( resources[n], tx ); startedWaiting = null; lockStack.push( WRITE ); } resourceStack.push( resources[n] ); } while ( --depth > 0 ); } catch ( DeadlockDetectedException e ) { // This is good } finally { releaseAllLocks( lockStack, resourceStack ); } } } catch ( Exception e ) { error = e; } } private void releaseAllLocks( Stack<Object> lockStack, Stack<ResourceObject> resourceStack ) { while ( !lockStack.isEmpty() ) { if ( lockStack.pop() == READ ) { lm.releaseReadLock( resourceStack.pop(), tx ); } else { lm.releaseWriteLock( resourceStack.pop(), tx ); } } } @Override public String toString() { return this.name; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TestDeadlockDetection.java
120
public class TxManager extends AbstractTransactionManager implements Lifecycle { public interface Monitor { void txStarted( Xid xid ); void txCommitted( Xid xid ); void txRolledBack( Xid xid ); void txManagerStopped(); public static class Adapter implements Monitor { @Override public void txStarted( Xid xid ) { } @Override public void txCommitted( Xid xid ) { } @Override public void txRolledBack( Xid xid ) { } @Override public void txManagerStopped() { } } } private ThreadLocalWithSize<TransactionImpl> txThreadMap; // private ThreadLocalWithSize<TransactionImpl> txThreadMap = new ThreadLocalWithSize<>(); private final File txLogDir; private File logSwitcherFileName = null; private String txLog1FileName = "tm_tx_log.1"; private String txLog2FileName = "tm_tx_log.2"; private final int maxTxLogRecordCount = 1000; private final AtomicInteger eventIdentifierCounter = new AtomicInteger( 0 ); private final Map<RecoveredBranchInfo, Boolean> branches = new HashMap<>(); private volatile TxLog txLog = null; private final AtomicInteger startedTxCount = new AtomicInteger( 0 ); private final AtomicInteger comittedTxCount = new AtomicInteger( 0 ); private final AtomicInteger rolledBackTxCount = new AtomicInteger( 0 ); private int peakConcurrentTransactions = 0; private final StringLogger log; private final XaDataSourceManager xaDataSourceManager; private final FileSystemAbstraction fileSystem; private TxManager.TxManagerDataSourceRegistrationListener dataSourceRegistrationListener; private Throwable recoveryError; private final TransactionStateFactory stateFactory; private final Factory<byte[]> xidGlobalIdFactory; private final KernelHealth kernelHealth; private final Monitors monitors; private final Monitor monitor; public TxManager( File txLogDir, XaDataSourceManager xaDataSourceManager, StringLogger log, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory, Factory<byte[]> xidGlobalIdFactory, KernelHealth kernelHealth, Monitors monitors ) { this( txLogDir, xaDataSourceManager, log, fileSystem, stateFactory, new Monitor.Adapter(), xidGlobalIdFactory, kernelHealth, monitors ); } public TxManager( File txLogDir, XaDataSourceManager xaDataSourceManager, StringLogger log, FileSystemAbstraction fileSystem, TransactionStateFactory stateFactory, Monitor monitor, Factory<byte[]> xidGlobalIdFactory, KernelHealth kernelHealth, Monitors monitors ) { this.txLogDir = txLogDir; this.xaDataSourceManager = xaDataSourceManager; this.fileSystem = fileSystem; this.log = log; this.stateFactory = stateFactory; this.monitor = monitor; this.xidGlobalIdFactory = xidGlobalIdFactory; this.kernelHealth = kernelHealth; this.monitors = monitors; } int getNextEventIdentifier() { return eventIdentifierCounter.incrementAndGet(); } private <E extends Exception> E logAndReturn( String msg, E exception ) { try { log.error( msg, exception ); return exception; } catch ( Throwable t ) { return exception; } } private volatile boolean recovered = false; @Override public void init() { } @Override public synchronized void start() throws Throwable { txThreadMap = new ThreadLocalWithSize<>(); openLog(); findPendingDatasources(); dataSourceRegistrationListener = new TxManagerDataSourceRegistrationListener(); xaDataSourceManager.addDataSourceRegistrationListener( dataSourceRegistrationListener ); } private void findPendingDatasources() { try { Iterable<List<TxLog.Record>> danglingRecordList = txLog.getDanglingRecords(); for ( List<TxLog.Record> tx : danglingRecordList ) { for ( TxLog.Record rec : tx ) { if ( rec.getType() == TxLog.BRANCH_ADD ) { RecoveredBranchInfo branchId = new RecoveredBranchInfo( rec.getBranchId()) ; if ( branches.containsKey( branchId ) ) { continue; } branches.put( branchId, false ); } } } } catch ( IOException e ) { throw logAndReturn( "Failed to start transaction manager: Unable to recover pending branches.", new TransactionFailureException( "Unable to start TM", e ) ); } } @Override public synchronized void stop() { recovered = false; xaDataSourceManager.removeDataSourceRegistrationListener( dataSourceRegistrationListener ); closeLog(); monitor.txManagerStopped(); } @Override public void shutdown() throws Throwable { } synchronized TxLog getTxLog() throws IOException { if ( txLog.getRecordCount() > maxTxLogRecordCount ) { if ( txLog.getName().endsWith( txLog1FileName ) ) { txLog.switchToLogFile( new File( txLogDir, txLog2FileName )); changeActiveLog( txLog2FileName ); } else if ( txLog.getName().endsWith( txLog2FileName ) ) { txLog.switchToLogFile( new File( txLogDir, txLog1FileName )); changeActiveLog( txLog1FileName ); } else { setTmNotOk( new Exception( "Unknown active tx log file[" + txLog.getName() + "], unable to switch." ) ); final IOException ex = new IOException( "Unknown txLogFile[" + txLog.getName() + "] not equals to either [" + txLog1FileName + "] or [" + txLog2FileName + "]" ); throw logAndReturn( "TM error accessing log file", ex ); } } return txLog; } private void closeLog() { if ( txLog != null ) { try { txLog.close(); txLog = null; recovered = false; } catch ( IOException e ) { log.error( "Unable to close tx log[" + txLog.getName() + "]", e ); } } log.info( "TM shutting down" ); } private void changeActiveLog( String newFileName ) throws IOException { // change active log StoreChannel fc = fileSystem.open( logSwitcherFileName, "rw" ); ByteBuffer buf = ByteBuffer.wrap( UTF8.encode( newFileName ) ); fc.truncate( 0 ); fc.write( buf ); fc.force( true ); fc.close(); } synchronized void setTmNotOk( Throwable cause ) { kernelHealth.panic( cause ); } @Override public void begin() throws NotSupportedException, SystemException { begin( ForceMode.forced ); } @Override public void begin( ForceMode forceMode ) throws NotSupportedException, SystemException { assertTmOk(); TransactionImpl tx = txThreadMap.get(); if ( tx != null ) { throw logAndReturn( "TM error tx begin", new NotSupportedException( "Nested transactions not supported. Thread: " + Thread.currentThread() ) ); } tx = new TransactionImpl( xidGlobalIdFactory.newInstance(), this, forceMode, stateFactory, log ); txThreadMap.set( tx ); int concurrentTxCount = txThreadMap.size(); if ( concurrentTxCount > peakConcurrentTransactions ) { peakConcurrentTransactions = concurrentTxCount; } startedTxCount.incrementAndGet(); monitor.txStarted( new XidImpl( tx.getGlobalId(), new byte[0] ) ); // start record written on resource enlistment } private void assertTmOk() throws SystemException { if ( !recovered ) { throw new SystemException( "TxManager not recovered" ); } kernelHealth.assertHealthy( SystemException.class ); } // called when a resource gets enlisted void writeStartRecord( byte globalId[] ) throws SystemException { try { getTxLog().txStart( globalId ); } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing start record", Exceptions.withCause( new SystemException( "TM " + "encountered a problem, " + " error writing transaction log," ), e ) ); } } @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, IllegalStateException, SystemException { TransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Not in transaction. Thread: " + Thread.currentThread() ) ); } boolean successful = false; try { assertTmOk(); if ( tx.getStatus() != Status.STATUS_ACTIVE && tx.getStatus() != Status.STATUS_MARKED_ROLLBACK ) { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ) ); } tx.doBeforeCompletion(); // delist resources? if ( tx.getStatus() == Status.STATUS_ACTIVE ) { comittedTxCount.incrementAndGet(); commit( tx ); } else if ( tx.getStatus() == Status.STATUS_MARKED_ROLLBACK ) { rolledBackTxCount.incrementAndGet(); rollbackCommit( tx ); } else { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ) ); } successful = true; } finally { // Call after completion as a safety net tx.doAfterCompletion(); monitor.txCommitted( new XidImpl( tx.getGlobalId(), new byte[0] ) ); txThreadMap.remove(); if ( successful ) { tx.finish( true ); } else { try { tx.finish( false ); } catch ( RuntimeException e ) { log.error( "Failed to commit transaction, and was then subsequently unable to " + "finish the failed tx.", e ); } } } } private void commit( TransactionImpl tx ) throws SystemException, HeuristicMixedException, HeuristicRollbackException { // mark as commit in log done TxImpl.doCommit() Throwable commitFailureCause = null; int xaErrorCode = -1; /* * The attempt to commit and the corresponding rollback in case of failure happens under the same lock. * This is necessary for a transaction to be able to cleanup its state in case it fails to commit * without any other transaction coming in and disrupting things. Hooks will be called under this * lock in case of rollback but not if commit succeeds, which should be ok throughput wise. There is * some performance degradation related to this, since now we hold a lock over commit() for * (potentially) all resource managers, while without this monitor each commit() on each * XaResourceManager locks only that. */ if ( tx.getResourceCount() == 0 ) { tx.setStatus( Status.STATUS_COMMITTED ); } else { try { tx.doCommit(); } catch ( CommitNotificationFailedException e ) { // Let this pass through. Catching this exception here will still have the exception // propagate out to the user (wrapped in a TransactionFailureException), but will not // set this transaction manager in "not OK" state. // At the time of adding this, this approach was chosen over throwing an XAException // with a specific error code since no error code seemed suitable. log.warn( "Commit notification failed: " + e ); } catch ( XAException e ) { // Behold, the error handling decision maker of great power. // // The thinking behind the code below is that there are certain types of errors that we understand, // and know that we can safely roll back after they occur. An example would be a user trying to delete // a node that still has relationships. For these errors, we keep a whitelist (the switch below), // and roll back when they occur. // // For *all* errors that we don't know exactly what they mean, we panic and run around in circles. // Other errors could involve out of disk space (can't recover) or out of memory (can't recover) // or anything else. The point is that there is no way for us to trust the state of the system any // more, so we set transaction manager to not ok and expect the user to fix the problem and do recovery. switch(e.errorCode) { // These are error states that we can safely recover from /* * User tried to delete a node that still had relationships, or in some other way violated * data model constraints. */ case XAException.XA_RBINTEGRITY: /* * A network error occurred. */ case XAException.XA_HEURCOM: xaErrorCode = e.errorCode; commitFailureCause = e; log.error( "Commit failed, status=" + getTxStatusAsString( tx.getStatus() ) + ", errorCode=" + xaErrorCode, e ); break; // Error codes where we are not *certain* that we still know the state of the system default: setTmNotOk( e ); throw logAndReturn("TM error tx commit",new TransactionFailureException( "commit threw exception", e )); } } catch ( Throwable t ) { setTmNotOk( t ); // this should never be throw logAndReturn("Commit failed for " + tx, new TransactionFailureException( "commit threw exception but status is committed?", t )); } } if ( tx.getStatus() != Status.STATUS_COMMITTED ) { try { tx.doRollback(); } catch ( Throwable e ) { setTmNotOk( e ); String commitError = commitFailureCause != null ? "error in commit: " + commitFailureCause : "error code in commit: " + xaErrorCode; String rollbackErrorCode = "Unknown error code"; if ( e instanceof XAException ) { rollbackErrorCode = Integer.toString( ((XAException) e).errorCode ); } throw logAndReturn( "Unable to rollback transaction "+ tx +". " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", Exceptions.withCause( new HeuristicMixedException( "Unable to rollback "+tx+" ---> " + commitError + " ---> error code for rollback: " + rollbackErrorCode ), e ) ); } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, while committing transaction " + tx + ", 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 "+ tx +" rolled back ---> " + "error code was: " + xaErrorCode ) ); } else { throw logAndReturn( "TM error tx commit", Exceptions.withCause( new HeuristicRollbackException( "Failed to commit transaction "+ tx +", transaction rolled back ---> " + commitFailureCause ), commitFailureCause ) ); } } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, " + " error writing transaction log for "+ tx ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); } private void rollbackCommit( TransactionImpl tx ) throws HeuristicMixedException, RollbackException, SystemException { try { tx.doRollback(); } catch ( XAException e ) { setTmNotOk( e ); throw logAndReturn( "Unable to rollback marked transaction. " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery: " + tx, Exceptions.withCause( new HeuristicMixedException( "Unable to rollback " + tx + " ---> error code for rollback: " + e.errorCode ), e ) ); } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, error writing transaction log" ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); RollbackException rollbackException = new RollbackException( "Failed to commit, transaction rolled back" ); ExceptionCauseSetter.setCause( rollbackException, tx.getRollbackCause() ); throw rollbackException; } @Override public void rollback() throws IllegalStateException, SystemException { TransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw logAndReturn( "TM error tx commit", new IllegalStateException( "Not in transaction. Thread: " + Thread.currentThread() ) ); } try { assertTmOk(); if ( tx.getStatus() == Status.STATUS_ACTIVE || tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_PREPARING ) { tx.setStatus( Status.STATUS_MARKED_ROLLBACK ); tx.doBeforeCompletion(); // delist resources? try { rolledBackTxCount.incrementAndGet(); tx.doRollback(); } catch ( XAException e ) { setTmNotOk( e ); throw logAndReturn( "Unable to rollback marked or active transaction "+ tx +". " + "Some resources may be commited others not. " + "Neo4j kernel should be SHUTDOWN for " + "resource maintance and transaction recovery ---->", Exceptions.withCause( new SystemException( "Unable to rollback " + tx + " ---> error code for rollback: " + e.errorCode ), e ) ); } tx.doAfterCompletion(); try { if ( tx.isGlobalStartRecordWritten() ) { getTxLog().txDone( tx.getGlobalId() ); } } catch ( IOException e ) { setTmNotOk( e ); throw logAndReturn( "Error writing transaction log for " + tx, Exceptions.withCause( new SystemException( "TM encountered a problem, " + " error writing transaction log" ), e ) ); } tx.setStatus( Status.STATUS_NO_TRANSACTION ); } else { throw new IllegalStateException( "Tx status is: " + getTxStatusAsString( tx.getStatus() ) ); } } finally { // Call after completion as a safety net tx.doAfterCompletion(); txThreadMap.remove(); tx.finish( false ); } monitor.txRolledBack( new XidImpl( tx.getGlobalId(), new byte[0] ) ); } @Override public int getStatus() { TransactionImpl tx = txThreadMap.get(); if ( tx != null ) { return tx.getStatus(); } return Status.STATUS_NO_TRANSACTION; } @Override public Transaction getTransaction() throws SystemException { // It's pretty important that we check the tmOk state here. This method is called from getForceMode // which in turn is called from XaResourceManager.commit(Xid, boolean) and so on all the way up to // TxManager.commit(Thread, TransactionImpl), wherein the monitor lock on TxManager is held! // It's very important that we check the tmOk state, during commit, while holding the lock on the // TxManager, as we could otherwise get into a situation where a transaction crashes the database // during commit, while another makes it past the check and then procedes to rotate the log, making // the crashed transaction unrecoverable. assertTmOk(); return txThreadMap.get(); } @Override public void resume( Transaction tx ) throws IllegalStateException, SystemException { assertTmOk(); Transaction associatedTx = txThreadMap.get(); if ( associatedTx != null ) { throw new ThreadAssociatedWithOtherTransactionException( Thread.currentThread(), associatedTx, tx ); } TransactionImpl txImpl = (TransactionImpl) tx; if ( txImpl.getStatus() != Status.STATUS_NO_TRANSACTION ) { if ( txImpl.isActive() ) { throw new TransactionAlreadyActiveException( Thread.currentThread(), tx ); } txImpl.markAsActive(); txThreadMap.set( txImpl ); } } @Override public Transaction suspend() throws SystemException { assertTmOk(); // check for ACTIVE/MARKED_ROLLBACK? TransactionImpl tx = txThreadMap.get(); if ( tx != null ) { txThreadMap.remove(); tx.markAsSuspended(); } // OK to return null here according to the JTA spec (at least 1.1) return tx; } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { assertTmOk(); TransactionImpl tx = txThreadMap.get(); if ( tx == null ) { throw new IllegalStateException( "Not in transaction. Thread: " + Thread.currentThread() ); } tx.setRollbackOnly(); } @Override public void setTransactionTimeout( int seconds ) throws SystemException { assertTmOk(); // ... } private void openLog() { logSwitcherFileName = new File( txLogDir, "active_tx_log"); txLog1FileName = "tm_tx_log.1"; txLog2FileName = "tm_tx_log.2"; try { if ( fileSystem.fileExists( logSwitcherFileName ) ) { StoreChannel fc = fileSystem.open( logSwitcherFileName, "rw" ); byte fileName[] = new byte[256]; ByteBuffer buf = ByteBuffer.wrap( fileName ); fc.read( buf ); fc.close(); File currentTxLog = new File( txLogDir, UTF8.decode( fileName ).trim()); if ( !fileSystem.fileExists( currentTxLog ) ) { throw logAndReturn( "TM startup failure", new TransactionFailureException( "Unable to start TM, " + "active tx log file[" + currentTxLog + "] not found." ) ); } txLog = new TxLog( currentTxLog, fileSystem, monitors ); log.info( "TM opening log: " + currentTxLog ); } else { if ( fileSystem.fileExists( new File( txLogDir, txLog1FileName )) || fileSystem.fileExists( new File( txLogDir, txLog2FileName ) )) { 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" ) ); StoreChannel fc = fileSystem.open( logSwitcherFileName, "rw" ); fc.write( buf ); txLog = new TxLog( new File( txLogDir, txLog1FileName), fileSystem, monitors ); log.info( "TM new log: " + txLog1FileName ); fc.force( true ); fc.close(); } } catch ( IOException e ) { throw logAndReturn( "TM startup failure", new TransactionFailureException( "Unable to start TM", e ) ); } } @Override public void doRecovery() { if ( txLog == null ) { openLog(); } if ( recovered ) { return; } try { // Assuming here that the last datasource to register is the Neo one // Do recovery on start - all Resources should be registered by now Iterable<List<TxLog.Record>> knownDanglingRecordList = txLog.getDanglingRecords(); boolean danglingRecordsFound = knownDanglingRecordList.iterator().hasNext(); if ( danglingRecordsFound ) { log.info( "Unresolved transactions found in " + txLog.getName() + ", recovery started... " ); } // Recover DataSources. Always call due to some internal state using it as a trigger. xaDataSourceManager.recover( knownDanglingRecordList.iterator() ); if ( danglingRecordsFound ) { log.info( "Recovery completed, all transactions have been " + "resolved to a consistent state." ); } getTxLog().truncate(); recovered = true; kernelHealth.healed(); } catch ( Throwable t ) { setTmNotOk( t ); recoveryError = t; } } byte[] getBranchId( XAResource xaRes ) { if ( xaRes instanceof XaResource ) { byte branchId[] = ((XaResource) xaRes).getBranchId(); if ( branchId != null ) { return branchId; } } return xaDataSourceManager.getBranchId( xaRes ); } String getTxStatusAsString( int status ) { switch ( status ) { case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; case Status.STATUS_PREPARING: return "STATUS_PREPARING"; case Status.STATUS_PREPARED: return "STATUS_PREPARED"; case Status.STATUS_COMMITTING: return "STATUS_COMMITING"; case Status.STATUS_COMMITTED: return "STATUS_COMMITED"; case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; default: return "STATUS_UNKNOWN(" + status + ")"; } } /** * @return The current transaction's event identifier or -1 if no * transaction is currently running. */ @Override public int getEventIdentifier() { TransactionImpl tx; try { tx = (TransactionImpl) getTransaction(); } catch ( SystemException e ) { throw new RuntimeException( e ); } if ( tx != null ) { return tx.getEventIdentifier(); } return -1; } @Override public ForceMode getForceMode() { try { // The call to getTransaction() is important. See the comment in getTransaction(). return ((TransactionImpl)getTransaction()).getForceMode(); } catch ( SystemException e ) { throw new RuntimeException( e ); } } @Override public Throwable getRecoveryError() { return recoveryError; } public int getStartedTxCount() { return startedTxCount.get(); } public int getCommittedTxCount() { return comittedTxCount.get(); } public int getRolledbackTxCount() { return rolledBackTxCount.get(); } public int getActiveTxCount() { return txThreadMap.size(); } public int getPeakConcurrentTxCount() { return peakConcurrentTransactions; } @Override public TransactionState getTransactionState() { Transaction tx; try { tx = getTransaction(); } catch ( SystemException e ) { throw new RuntimeException( e ); } return tx != null ? ((TransactionImpl)tx).getState() : TransactionState.NO_STATE; } private class TxManagerDataSourceRegistrationListener implements DataSourceRegistrationListener { @Override public void registeredDataSource( XaDataSource ds ) { branches.put( new RecoveredBranchInfo( ds.getBranchId() ), true ); boolean everythingRegistered = true; for ( boolean dsRegistered : branches.values() ) { everythingRegistered &= dsRegistered; } if ( everythingRegistered ) { doRecovery(); } } @Override public void unregisteredDataSource( XaDataSource ds ) { branches.put( new RecoveredBranchInfo( ds.getBranchId() ), false ); boolean everythingUnregistered = true; for ( boolean dsRegistered : branches.values() ) { everythingUnregistered &= !dsRegistered; } if ( everythingUnregistered ) { closeLog(); } } } /* * We use a hash map to store the branch ids. byte[] however does not offer a useful implementation of equals() or * hashCode(), so we need a wrapper that does that. */ private static final class RecoveredBranchInfo { final byte[] branchId; private RecoveredBranchInfo( byte[] branchId ) { this.branchId = branchId; } @Override public int hashCode() { return Arrays.hashCode( branchId ); } @Override public boolean equals( Object obj ) { if ( obj == null || obj.getClass() != RecoveredBranchInfo.class ) { return false; } return Arrays.equals( branchId, ( ( RecoveredBranchInfo )obj ).branchId ); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
121
public abstract class AbstractTestBase { private static GraphDatabaseService graphdb; @BeforeClass public static void beforeSuite() { graphdb = new TestGraphDatabaseFactory().newImpermanentDatabase(); } @AfterClass public static void afterSuite() { graphdb.shutdown(); graphdb = null; } protected static Node getNode( long id ) { return graphdb.getNodeById( id ); } protected static Transaction beginTx() { return graphdb.beginTx(); } protected interface Representation<T> { String represent( T item ); } protected static final class RelationshipRepresentation implements Representation<Relationship> { private final Representation<? super Node> nodes; private final Representation<? super Relationship> rel; public RelationshipRepresentation( Representation<? super Node> nodes, Representation<? super Relationship> rel ) { this.nodes = nodes; this.rel = rel; } public String represent( Relationship item ) { return nodes.represent( item.getStartNode() ) + " " + rel.represent( item ) + " " + nodes.represent( item.getEndNode() ); } } protected static <T> void expect( Iterable<? extends T> items, Representation<T> representation, String... expected ) { expect( items, representation, new HashSet<String>( Arrays.asList( expected ) ) ); } protected static <T> void expect( Iterable<? extends T> items, Representation<T> representation, Set<String> expected ) { Transaction tx = beginTx(); try { for ( T item : items ) { String repr = representation.represent( item ); assertTrue( repr + " not expected ", expected.remove( repr ) ); } tx.success(); } finally { tx.finish(); } if ( !expected.isEmpty() ) { fail( "The exepected elements " + expected + " were not returned." ); } } }
false
community_graph-algo_src_test_java_common_AbstractTestBase.java
122
private static final class RecoveredBranchInfo { final byte[] branchId; private RecoveredBranchInfo( byte[] branchId ) { this.branchId = branchId; } @Override public int hashCode() { return Arrays.hashCode( branchId ); } @Override public boolean equals( Object obj ) { if ( obj == null || obj.getClass() != RecoveredBranchInfo.class ) { return false; } return Arrays.equals( branchId, ( ( RecoveredBranchInfo )obj ).branchId ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
123
{ @Override public boolean matchesSafely( LogEntry.Start entry ) { return entry != null && entry.getIdentifier() == identifier && entry.getMasterId() == masterId && entry.getLocalId() == localId; } @Override public void describeTo( Description description ) { description.appendText( "Start[" + identifier + ",xid=<Any Xid>,master=" + masterId + ",me=" + localId + ",time=<Any Date>]" ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_LogMatchers.java
124
{ @Override public void checkOperation( OperationType operationType, File onFile, int bytesWrittenTotal, int bytesWrittenThisCall, long channelPosition ) throws IOException { if ( !broken.get() && bytesWrittenTotal == 4 ) { broken.set( true ); throw new IOException( "IOException after which this buffer should not be used" ); } if ( broken.get() && channelPosition == 0 ) { throw new IOException( "This exception should never happen" ); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestDirectMappedLogBuffer.java
125
public class TestDirectMappedLogBuffer { class FileChannelWithChoppyDisk extends StoreFileChannel { ByteBuffer buff = ByteBuffer.allocate(1024); private int chunkSize; public FileChannelWithChoppyDisk(int writeThisMuchAtATime) { super( (FileChannel) null ); this.chunkSize = writeThisMuchAtATime; } @Override public int write( ByteBuffer byteBuffer, long l ) throws IOException { int bytesToWrite = chunkSize > (byteBuffer.limit() - byteBuffer.position()) ? byteBuffer.limit() - byteBuffer.position() : chunkSize; buff.position( (int)l ); // Remember original limit int originalLimit = byteBuffer.limit(); // Set limit to not be bigger than chunk size byteBuffer.limit(byteBuffer.position() + bytesToWrite); // Write buff.put( byteBuffer ); // Restore limit byteBuffer.limit(originalLimit); return bytesToWrite; } @Override public long position() throws IOException { return buff.position(); } @Override public StoreFileChannel position( long l ) throws IOException { buff.position( (int) l ); return this; } @Override public long size() throws IOException { return buff.capacity(); } @Override public StoreFileChannel truncate( long l ) throws IOException { throw new UnsupportedOperationException(); } @Override public void force( boolean b ) throws IOException { } } @Test public void shouldHandleDiskThatWritesOnlyTwoBytesAtATime() throws Exception { // Given FileChannelWithChoppyDisk mockChannel = new FileChannelWithChoppyDisk(/* that writes */2/* bytes at a time */); LogBuffer writeBuffer = new DirectMappedLogBuffer( mockChannel, new Monitors().newMonitor( ByteCounterMonitor.class ) ); // When writeBuffer.put( new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16} ); writeBuffer.writeOut(); // Then assertThat(mockChannel.buff.position( ), is(16)); } @Test(expected = IOException.class) public void shouldFailIfUnableToWriteASingleByte() throws Exception { // Given FileChannelWithChoppyDisk mockChannel = new FileChannelWithChoppyDisk(/* that writes */0/* bytes at a time */); LogBuffer writeBuffer = new DirectMappedLogBuffer( mockChannel, new Monitors().newMonitor( ByteCounterMonitor.class ) ); // When writeBuffer.put( new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16} ); writeBuffer.writeOut(); // Then expect an IOException } @Test @Ignore("This test demonstrates a way in which DirectMappedLogBuffer can fail. In particular, using DMLB after an" + "IOException can cause corruption in the underlying file channel. However, it is wrong to use DMLB after" + "such an error anyway, so this not something requiring fixing.") public void logBufferWritesContentsTwiceOnFailure() throws Exception { /* * The guard will throw an exception before writing the fifth byte. We will catch that and try to continue * writing. If that operation leads to writing to position 0 again then this is obviously an error (as we * will be overwriting the stuff we wrote before the exception) and so we must fail. */ final AtomicBoolean broken = new AtomicBoolean( false ); FileSystemGuard guard = new FileSystemGuard() { @Override public void checkOperation( OperationType operationType, File onFile, int bytesWrittenTotal, int bytesWrittenThisCall, long channelPosition ) throws IOException { if ( !broken.get() && bytesWrittenTotal == 4 ) { broken.set( true ); throw new IOException( "IOException after which this buffer should not be used" ); } if ( broken.get() && channelPosition == 0 ) { throw new IOException( "This exception should never happen" ); } } }; BreakableFileSystemAbstraction fs = new BreakableFileSystemAbstraction( new EphemeralFileSystemAbstraction(), guard ); DirectMappedLogBuffer buffer = new DirectMappedLogBuffer( fs.create( new File( "log" ) ), new Monitors().newMonitor( ByteCounterMonitor.class ) ); buffer.putInt( 1 ).putInt( 2 ).putInt( 3 ); try { buffer.writeOut(); } catch ( IOException e ) { e.printStackTrace(); } buffer.writeOut(); } @Test public void testMonitoringBytesWritten() throws Exception { Monitors monitors = new Monitors(); ByteCounterMonitor monitor = monitors.newMonitor( ByteCounterMonitor.class ); DirectMappedLogBuffer buffer = new DirectMappedLogBuffer( new FileChannelWithChoppyDisk( 100 ), monitor ); final AtomicLong bytesWritten = new AtomicLong(); monitors.addMonitorListener( new ByteCounterMonitor() { @Override public void bytesWritten( long numberOfBytes ) { bytesWritten.addAndGet( numberOfBytes ); } @Override public void bytesRead( long numberOfBytes ) { } } ); buffer.put( (byte) 1 ); assertEquals( 0, bytesWritten.get() ); buffer.force(); assertEquals( 1, bytesWritten.get() ); buffer.putShort( (short) 1 ); assertEquals( 1, bytesWritten.get() ); buffer.force(); assertEquals( 3, bytesWritten.get() ); buffer.putInt( 1 ); assertEquals( 3, bytesWritten.get() ); buffer.force(); assertEquals( 7, bytesWritten.get() ); buffer.putLong( 1 ); assertEquals( 7, bytesWritten.get() ); buffer.force(); assertEquals( 15, bytesWritten.get() ); buffer.putFloat( 1 ); assertEquals( 15, bytesWritten.get() ); buffer.force(); assertEquals( 19, bytesWritten.get() ); buffer.putDouble( 1 ); assertEquals( 19, bytesWritten.get() ); buffer.force(); assertEquals( 27, bytesWritten.get() ); buffer.put( new byte[]{ 1, 2, 3 } ); assertEquals( 27, bytesWritten.get() ); buffer.force(); assertEquals( 30, bytesWritten.get() ); buffer.put( new char[] { '1', '2', '3'} ); assertEquals( 30, bytesWritten.get() ); buffer.force(); assertEquals( 36, bytesWritten.get() ); buffer.force(); assertEquals( 36, bytesWritten.get() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestDirectMappedLogBuffer.java
126
{ @Override public boolean accept( LogEntry item ) { return item instanceof LogEntry.Done; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestApplyTransactions.java
127
{ @Override public boolean accept( LogEntry item ) { return !(item instanceof LogEntry.Done); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestApplyTransactions.java
128
{ @Override public void run() { db1.shutdown(); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestApplyTransactions.java
129
public class TestApplyTransactions { @Test public void testCommittedTransactionReceivedAreForcedToLog() throws Exception { /* GIVEN * Create a tx on a db (as if the master), extract that, apply on dest (as if pullUpdate on slave). * Let slave crash uncleanly. */ File baseStoreDir = new File( "base" ); File originStoreDir = new File( baseStoreDir, "origin" ); File destStoreDir = new File( baseStoreDir, "destination" ); GraphDatabaseAPI origin = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fs.get() ) .newImpermanentDatabase( originStoreDir.getPath() ); Transaction tx = origin.beginTx(); origin.createNode(); tx.success(); tx.finish(); XaDataSource originNeoDataSource = xaDs( origin ); int latestTxId = (int) originNeoDataSource.getLastCommittedTxId(); InMemoryLogBuffer theTx = new InMemoryLogBuffer(); originNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); final GraphDatabaseAPI dest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fs.get() ) .newImpermanentDatabase( destStoreDir.getPath() ); XaDataSource destNeoDataSource = xaDs( dest ); destNeoDataSource.applyCommittedTransaction( latestTxId, theTx ); origin.shutdown(); EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( dest ) ); /* * Open crashed db, try to extract the transaction it reports as latest. It should be there. */ GraphDatabaseAPI newDest = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( snapshot ) .newImpermanentDatabase( destStoreDir.getPath() ); destNeoDataSource = newDest.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); latestTxId = (int) destNeoDataSource.getLastCommittedTxId(); theTx = new InMemoryLogBuffer(); long extractedTxId = destNeoDataSource.getLogExtractor( latestTxId, latestTxId ).extractNext( theTx ); assertEquals( latestTxId, extractedTxId ); } private XaDataSource xaDs( GraphDatabaseAPI origin ) { return origin.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); } @Test public void verifyThatRecoveredTransactionsHaveTheirDoneRecordsWrittenInOrder() throws IOException { XaDataSource ds; File archivedLogFilename; File originStoreDir = new File( new File( "base" ), "origin" ); String logicalLogFilename = "logicallog"; final GraphDatabaseAPI db1 = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ) .newImpermanentDatabaseBuilder( originStoreDir.getPath() ) .setConfig( InternalAbstractGraphDatabase.Configuration.logical_log, logicalLogFilename ) .newGraphDatabase(); for ( int i = 0; i < 100; i++ ) { Transaction tx = db1.beginTx(); db1.createNode(); tx.success(); tx.finish(); } ds = xaDs( db1 ); archivedLogFilename = ds.getFileName( ds.getCurrentLogVersion() ); fs.snapshot( new Runnable() { @Override public void run() { db1.shutdown(); } } ); removeDoneEntriesFromLog( new File( archivedLogFilename.getParent(), logicalLogFilename + ".1" ) ); GraphDatabaseAPI db2 = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ) .newImpermanentDatabaseBuilder( originStoreDir.getPath() ) .setConfig( InternalAbstractGraphDatabase.Configuration.logical_log, logicalLogFilename ) .newGraphDatabase(); ds = xaDs( db2 ); archivedLogFilename = ds.getFileName( ds.getCurrentLogVersion() ); db2.shutdown(); List<LogEntry> logEntries = filterDoneEntries( logEntries( fs.get(), archivedLogFilename ) ); String errorMessage = "DONE entries should be in order: " + logEntries; int prev = 0; for ( LogEntry entry : logEntries ) { int current = entry.getIdentifier(); assertThat( errorMessage, current, greaterThan( prev ) ); prev = current; } } private void removeDoneEntriesFromLog( File archivedLogFilename ) throws IOException { LogTestUtils.LogHook<LogEntry> doneEntryFilter = new LogTestUtils.LogHookAdapter<LogEntry>() { @Override public boolean accept( LogEntry item ) { return !(item instanceof LogEntry.Done); } }; EphemeralFileSystemAbstraction fsa = fs.get(); File tempFile = filterNeostoreLogicalLog( fsa, archivedLogFilename, doneEntryFilter ); fsa.deleteFile( archivedLogFilename ); fsa.renameFile( tempFile, archivedLogFilename ); } private List<LogEntry> filterDoneEntries( List<LogEntry> logEntries ) { Predicate<? super LogEntry> doneEntryPredicate = new Predicate<LogEntry>() { @Override public boolean accept( LogEntry item ) { return item instanceof LogEntry.Done; } }; return Iterables.toList( Iterables.filter( doneEntryPredicate, logEntries ) ); } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestApplyTransactions.java
130
{ @Override public boolean isValid( TransactionInfo txInfo ) { return true; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_RecoveryVerifier.java
131
public class RecoveryVerificationException extends RuntimeException { public RecoveryVerificationException( int identifier, long txId ) { super( "Recovered transaction with identifier:" + identifier + ", txId:" + txId + " was recovered, but didn't verify correctly" ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_RecoveryVerificationException.java
132
public class ReadPastEndException extends Exception { public ReadPastEndException() { super(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_ReadPastEndException.java
133
class PartialTransactionCopier { private final ByteBuffer sharedBuffer; private final XaCommandFactory commandFactory; private final StringLogger log; private final LogExtractor.LogPositionCache positionCache; private final LogExtractor.LogLoader logLoader; private final ArrayMap<Integer,LogEntry.Start> xidIdentMap; private final ByteCounterMonitor monitor; PartialTransactionCopier( ByteBuffer sharedBuffer, XaCommandFactory commandFactory, StringLogger log, LogExtractor.LogPositionCache positionCache, LogExtractor.LogLoader logLoader, ArrayMap<Integer, LogEntry.Start> xidIdentMap, ByteCounterMonitor monitor ) { this.sharedBuffer = sharedBuffer; this.commandFactory = commandFactory; this.log = log; this.positionCache = positionCache; this.logLoader = logLoader; this.xidIdentMap = xidIdentMap; this.monitor = monitor; } public void copy( StoreChannel sourceLog, LogBuffer targetLog, long targetLogVersion ) throws IOException { boolean foundFirstActiveTx = false; Map<Integer,LogEntry.Start> startEntriesEncountered = new HashMap<Integer,LogEntry.Start>(); for ( LogEntry entry = null; (entry = LogIoUtils.readEntry( sharedBuffer, sourceLog, commandFactory )) != null; ) { Integer identifier = entry.getIdentifier(); boolean isActive = xidIdentMap.get( identifier ) != null; if ( !foundFirstActiveTx && isActive ) { foundFirstActiveTx = true; } if ( foundFirstActiveTx ) { if ( entry instanceof LogEntry.Start ) { LogEntry.Start startEntry = (LogEntry.Start) entry; startEntriesEncountered.put( identifier, startEntry ); startEntry.setStartPosition( targetLog.getFileChannelPosition() ); // If the transaction is active then update it with the new one if ( isActive ) xidIdentMap.put( identifier, startEntry ); } else if ( entry instanceof LogEntry.Commit ) { LogEntry.Commit commitEntry = (LogEntry.Commit) entry; LogEntry.Start startEntry = startEntriesEncountered.get( identifier ); if ( startEntry == null ) { // Fetch from log extractor instead (all entries except done records, which will be copied from the source). startEntry = fetchTransactionBulkFromLogExtractor( commitEntry.getTxId(), targetLog ); startEntriesEncountered.put( identifier, startEntry ); } else { LogExtractor.TxPosition oldPos = positionCache.getStartPosition( commitEntry.getTxId() ); LogExtractor.TxPosition newPos = positionCache.cacheStartPosition( commitEntry.getTxId(), startEntry, targetLogVersion ); log.logMessage( "Updated tx " + ((LogEntry.Commit) entry ).getTxId() + " from " + oldPos + " to " + newPos ); } } if ( startEntriesEncountered.containsKey( identifier ) ) { LogIoUtils.writeLogEntry( entry, targetLog ); } } } } private LogEntry.Start fetchTransactionBulkFromLogExtractor( long txId, LogBuffer target ) throws IOException { LogExtractor extractor = new LogExtractor( positionCache, logLoader, commandFactory, txId, txId ); InMemoryLogBuffer tempBuffer = new InMemoryLogBuffer(); extractor.extractNext( tempBuffer ); ByteBuffer localBuffer = newLogReaderBuffer(); for ( LogEntry readEntry = null; (readEntry = LogIoUtils.readEntry( localBuffer, tempBuffer, commandFactory )) != null; ) { if ( readEntry instanceof LogEntry.Commit ) { break; } LogIoUtils.writeLogEntry( readEntry, target ); } return extractor.getLastStartEntry(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_PartialTransactionCopier.java
134
public class NullLogBuffer implements LogBuffer { public static final LogBuffer INSTANCE = new NullLogBuffer(); private NullLogBuffer() {} @Override public LogBuffer put( byte b ) throws IOException { return this; } @Override public LogBuffer putShort( short b ) throws IOException { return this; } @Override public LogBuffer putInt( int i ) throws IOException { return this; } @Override public LogBuffer putLong( long l ) throws IOException { return this; } @Override public LogBuffer putFloat( float f ) throws IOException { return this; } @Override public LogBuffer putDouble( double d ) throws IOException { return this; } @Override public LogBuffer put( byte[] bytes ) throws IOException { return this; } @Override public LogBuffer put( char[] chars ) throws IOException { return this; } @Override public void writeOut() throws IOException {} @Override public void force() throws IOException {} @Override public long getFileChannelPosition() throws IOException { throw new UnsupportedOperationException(); } @Override public StoreChannel getFileChannel() { throw new UnsupportedOperationException(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_NullLogBuffer.java
135
public class NoSuchTransactionException extends MissingLogDataException { public NoSuchTransactionException( long missingTxId ) { this( missingTxId, null ); } public NoSuchTransactionException( long missingTxId, String additionalInformation ) { super( combinedMessage( missingTxId, additionalInformation ) ); } private static String combinedMessage( long missingTxId, String additionalInformation ) { String result = "Unable to find transaction " + missingTxId + " in any of my logical logs"; if ( additionalInformation != null ) result += ": " + additionalInformation; return result; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_NoSuchTransactionException.java
136
public class NoSuchLogVersionException extends MissingLogDataException { private long version; public NoSuchLogVersionException( long version ) { super( "No such log version: '" + version + "'. This means we encountered a log file that we expected " + "to find was missing. If you are unable to start the database due to this problem, please make " + "sure that the correct logical log files are in the database directory." ); this.version = version; } public long getVersion() { return version; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_NoSuchLogVersionException.java
137
public class NoOpLogicalLog extends XaLogicalLog { public NoOpLogicalLog( Logging logging ) { super( null, null, null, null, null, new Monitors(), logging, null, null, null, 10000l, null ); } @Override synchronized void open() throws IOException { super.open(); //To change body of overridden methods use File | Settings | File Templates. } @Override public boolean scanIsComplete() { return true; } @Override public synchronized int start( Xid xid, int masterId, int myId, long highestKnownCommittedTx ) { return 0; } @Override public synchronized void writeStartEntry( int identifier ) throws XAException { } @Override synchronized LogEntry.Start getStartEntry( int identifier ) { return null; } @Override public synchronized void prepare( int identifier ) throws XAException { } @Override public synchronized void commitOnePhase( int identifier, long txId, ForceMode forceMode ) throws XAException { } @Override public synchronized void done( int identifier ) throws XAException { } @Override synchronized void doneInternal( int identifier ) throws IOException { } @Override public synchronized void commitTwoPhase( int identifier, long txId, ForceMode forceMode ) throws XAException { } @Override public synchronized void writeCommand( XaCommand command, int identifier ) throws IOException { } @Override public synchronized void close() throws IOException { } @Override void reset() { super.reset(); //To change body of overridden methods use File | Settings | File Templates. } @Override void registerTxIdentifier( int identifier ) { } @Override void unregisterTxIdentifier() { } @Override public int getCurrentTxIdentifier() { return 0; } @Override public ReadableByteChannel getLogicalLog( long version ) throws IOException { return null; } @Override public ReadableByteChannel getLogicalLog( long version, long position ) throws IOException { return null; } @Override public synchronized ReadableByteChannel getPreparedTransaction( int identifier ) throws IOException { return null; } @Override public synchronized void getPreparedTransaction( int identifier, LogBuffer targetBuffer ) throws IOException { } @Override public LogExtractor getLogExtractor( long startTxId, long endTxIdHint ) throws IOException { return null; } @Override public synchronized Pair<Integer, Long> getMasterForCommittedTransaction( long txId ) throws IOException { return null; } @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { return null; } @Override public long getLogicalLogLength( long version ) { return 0l; } @Override public boolean hasLogicalLog( long version ) { return false; } @Override public boolean deleteLogicalLog( long version ) { return false; } @Override protected LogDeserializer getLogDeserializer( ReadableByteChannel byteChannel ) { return null; } @Override public synchronized void applyTransactionWithoutTxId( ReadableByteChannel byteChannel, long nextTxId, ForceMode forceMode ) throws IOException { } @Override public synchronized void applyTransaction( ReadableByteChannel byteChannel ) throws IOException { } @Override public synchronized long rotate() throws IOException { return 0l; } @Override public void setAutoRotateLogs( boolean autoRotate ) { } @Override public boolean isLogsAutoRotated() { return false; } @Override public void setLogicalLogTargetSize( long size ) { } @Override public long getLogicalLogTargetSize() { return 0l; } @Override public File getFileName( long version ) { return null; } @Override public File getBaseFileName() { return null; } @Override public Pattern getHistoryFileNamePattern() { return null; } @Override public boolean wasNonClean() { return false; } @Override public long getHighestLogVersion() { return 0l; } @Override public Long getFirstCommittedTxId( long version ) { return 0l; } @Override public long getLastCommittedTxId() { return 0l; } @Override public Long getFirstStartRecordTimestamp( long version ) throws IOException { return 0l; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_NoOpLogicalLog.java
138
public class MissingLogDataException extends IOException { public MissingLogDataException() { super(); } public MissingLogDataException( String message, Throwable cause ) { super( message, cause ); } public MissingLogDataException( String message ) { super( message ); } public MissingLogDataException( Throwable cause ) { super( cause ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_MissingLogDataException.java
139
{ private int size; @Override public boolean reached( File file, long version, LogLoader source ) { size += fileSystem.getFileSize( file ); return size >= maxSize; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
140
public static class FileSizePruneStrategy extends AbstractPruneStrategy { private final int maxSize; public FileSizePruneStrategy( FileSystemAbstraction fileystem, int maxSizeBytes ) { super( fileystem ); this.maxSize = maxSizeBytes; } @Override protected Threshold newThreshold() { return new Threshold() { private int size; @Override public boolean reached( File file, long version, LogLoader source ) { size += fileSystem.getFileSize( file ); return size >= maxSize; } }; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
141
{ int nonEmptyLogCount = 0; @Override public boolean reached( File file, long version, LogLoader source ) { return ++nonEmptyLogCount >= maxNonEmptyLogCount; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
142
private static class FileCountPruneStrategy extends AbstractPruneStrategy { private final int maxNonEmptyLogCount; public FileCountPruneStrategy( FileSystemAbstraction fileSystem, int maxNonEmptyLogCount ) { super( fileSystem ); this.maxNonEmptyLogCount = maxNonEmptyLogCount; } @Override protected Threshold newThreshold() { return new Threshold() { int nonEmptyLogCount = 0; @Override public boolean reached( File file, long version, LogLoader source ) { return ++nonEmptyLogCount >= maxNonEmptyLogCount; } }; } @Override public String toString() { return getClass().getSimpleName() + "[max:" + maxNonEmptyLogCount + "]"; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
143
private abstract static class AbstractPruneStrategy implements LogPruneStrategy { protected final FileSystemAbstraction fileSystem; AbstractPruneStrategy( FileSystemAbstraction fileSystem ) { this.fileSystem = fileSystem; } @Override public void prune( LogLoader source ) { if ( source.getHighestLogVersion() == 0 ) return; long upper = source.getHighestLogVersion()-1; Threshold threshold = newThreshold(); boolean exceeded = false; while ( upper >= 0 ) { File file = source.getFileName( upper ); if ( !fileSystem.fileExists( file ) ) // There aren't logs to prune anything. Just return return; if ( fileSystem.getFileSize( file ) > LogIoUtils.LOG_HEADER_SIZE && threshold.reached( file, upper, source ) ) { exceeded = true; break; } upper--; } if ( !exceeded ) return; // Find out which log is the earliest existing (lower bound to prune) long lower = upper; while ( fileSystem.fileExists( source.getFileName( lower-1 ) ) ) lower--; // The reason we delete from lower to upper is that if it crashes in the middle // we can be sure that no holes are created for ( long version = lower; version < upper; version++ ) fileSystem.deleteFile( source.getFileName( version ) ); } /** * @return a {@link Threshold} which if returning {@code false} states that the log file * is within the threshold and doesn't need to be pruned. The first time it returns * {@code true} it says that the threshold has been reached and the log file it just * returned {@code true} for should be kept, but all previous logs should be pruned. */ protected abstract Threshold newThreshold(); }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
144
{ @Override public void prune( LogLoader source ) { // Don't prune logs at all. } @Override public String toString() { return "NO_PRUNING"; } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogPruneStrategies.java
145
{ @Override public void bytesWritten( long numberOfBytes ) { bytesWritten.addAndGet( numberOfBytes ); } @Override public void bytesRead( long numberOfBytes ) { } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestDirectMappedLogBuffer.java
146
class FileChannelWithChoppyDisk extends StoreFileChannel { ByteBuffer buff = ByteBuffer.allocate(1024); private int chunkSize; public FileChannelWithChoppyDisk(int writeThisMuchAtATime) { super( (FileChannel) null ); this.chunkSize = writeThisMuchAtATime; } @Override public int write( ByteBuffer byteBuffer, long l ) throws IOException { int bytesToWrite = chunkSize > (byteBuffer.limit() - byteBuffer.position()) ? byteBuffer.limit() - byteBuffer.position() : chunkSize; buff.position( (int)l ); // Remember original limit int originalLimit = byteBuffer.limit(); // Set limit to not be bigger than chunk size byteBuffer.limit(byteBuffer.position() + bytesToWrite); // Write buff.put( byteBuffer ); // Restore limit byteBuffer.limit(originalLimit); return bytesToWrite; } @Override public long position() throws IOException { return buff.position(); } @Override public StoreFileChannel position( long l ) throws IOException { buff.position( (int) l ); return this; } @Override public long size() throws IOException { return buff.capacity(); } @Override public StoreFileChannel truncate( long l ) throws IOException { throw new UnsupportedOperationException(); } @Override public void force( boolean b ) throws IOException { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestDirectMappedLogBuffer.java
147
public class TestLogPruneStrategy { @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private EphemeralFileSystemAbstraction FS; private File directory; @Before public void before() { FS = fs.get(); directory = TargetDirectory.forTest( FS, getClass() ).cleanDirectory( "prune" ); } @Test public void noPruning() throws Exception { MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.NO_PRUNING ); for ( int i = 0; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, log.getHighestLogVersion()-1 ); } assertEquals( 100, log.getHighestLogVersion() ); } @Test public void pruneByFileCountWhereAllContainsFilesTransactions() throws Exception { int fileCount = 5; MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, fileCount ) ); for ( int i = 0; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); long from = Math.max( 0, log.getHighestLogVersion()-fileCount ); assertLogsRangeExists( log, from, log.getHighestLogVersion()-1 ); } } @Test public void pruneByFileCountWhereSomeAreEmpty() throws Exception { MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, 3 ) ); // v0 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, 0 ); // v1 empty log.rotate(); assertLogsRangeExists( log, 0, 1, empty( 1 ) ); // v2 empty log.rotate(); assertLogsRangeExists( log, 0, 2, empty( 1, 2 ) ); // v3 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, 3, empty( 1, 2 ) ); // v4 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 0, 4, empty( 1, 2 ) ); // v5 empty log.rotate(); assertLogsRangeExists( log, 0, 5, empty( 1, 2, 5 ) ); // v6 with transactions in it log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 3, 6, empty( 5 ) ); } @Test public void pruneByFileSize() throws Exception { int maxSize = MAX_LOG_SIZE*5; MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.totalFileSize( FS, maxSize ) ); for ( int i = 0; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); assertTrue( log.getTotalSizeOfAllExistingLogFiles() < (maxSize+MAX_LOG_SIZE) ); } } @Test public void pruneByTransactionCount() throws Exception { MockedLogLoader log = new MockedLogLoader( 10000, LogPruneStrategies.transactionCount( FS, 1000 ) ); for ( int i = 1; i < 100; i++ ) { log.addTransactionsUntilRotationHappens(); int avg = (int)(log.getLastCommittedTxId()/i); assertTrue( log.getTotalTransactionCountOfAllExistingLogFiles() < avg*(i+1 /*+1 here is because the whole log which a transaction spills over in is kept also*/) ); } } @Test public void pruneByTransactionTimeSpan() throws Exception { /* * T: -----------------------------------------> * 0 ======= * 1 ======== * 2 ============ * A ======= * KEEP <----------------------> * * Prune 0 in the example above */ int seconds = 1; int millisToKeep = (int) (SECONDS.toMillis( seconds ) / 10); MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.transactionTimeSpan( FS, millisToKeep, MILLISECONDS ) ); long end = System.currentTimeMillis() + SECONDS.toMillis( seconds ); long lastTimestamp = System.currentTimeMillis(); while ( true ) { lastTimestamp = System.currentTimeMillis(); if ( log.addTransaction( 15, lastTimestamp ) ) { assertLogRangeByTimestampExists( log, millisToKeep, lastTimestamp ); if ( System.currentTimeMillis() > end ) { break; } } } } @Test public void makeSureOneLogStaysEvenWhenZeroFilesIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, 0 ) ) ); } @Test public void makeSureOneLogStaysEvenWhenZeroSpaceIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.totalFileSize( FS, 0 ) ) ); } @Test public void makeSureOneLogStaysEvenWhenZeroTransactionsIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.transactionCount( FS, 0 ) ) ); } @Test public void makeSureOneLogStaysEvenWhenZeroTimeIsConfigured() throws Exception { makeSureOneLogStaysEvenWhenZeroConfigured( new MockedLogLoader( LogPruneStrategies.transactionTimeSpan( FS, 0, SECONDS ) ) ); } private void makeSureOneLogStaysEvenWhenZeroConfigured( MockedLogLoader mockedLogLoader ) throws Exception { MockedLogLoader log = new MockedLogLoader( LogPruneStrategies.nonEmptyFileCount( FS, 0 ) ); log.rotate(); assertLogsRangeExists( log, 0, 0, empty( 0 ) ); log.rotate(); assertLogsRangeExists( log, 0, 1, empty( 0, 1 ) ); log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 2, 2, empty() ); log.addTransactionsUntilRotationHappens(); assertLogsRangeExists( log, 3, 3, empty() ); } private void assertLogRangeByTimestampExists( MockedLogLoader log, int millisToKeep, long lastTimestamp ) { long lowerLimit = lastTimestamp - millisToKeep; for ( long version = log.getHighestLogVersion() - 1; version >= 0; version-- ) { Long firstTimestamp = log.getFirstStartRecordTimestamp( version+1 ); if ( firstTimestamp == null ) { break; } assertTrue( "Log " + version + " should've been deleted by now. first of " + (version+1) + ":" + firstTimestamp + ", highestVersion:" + log.getHighestLogVersion() + ", lowerLimit:" + lowerLimit + ", timestamp:" + lastTimestamp, firstTimestamp >= lowerLimit ); } } private void assertLogsRangeExists( MockedLogLoader log, long from, long to ) { assertLogsRangeExists( log, from, to, empty() ); } private void assertLogsRangeExists( MockedLogLoader log, long from, long to, Set<Long> empty ) { assertTrue( log.getHighestLogVersion() >= to ); for ( long i = 0; i < from; i++ ) { assertFalse( "Log v" + i + " shouldn't exist when highest version is " + log.getHighestLogVersion() + " and prune strategy " + log.pruning, FS.fileExists( log.getFileName( i ) ) ); } for ( long i = from; i <= to; i++ ) { File file = log.getFileName( i ); assertTrue( "Log v" + i + " should exist when highest version is " + log.getHighestLogVersion() + " and prune strategy " + log.pruning, FS.fileExists( file ) ); if ( empty.contains( i ) ) { assertEquals( "Log v" + i + " should be empty", LogIoUtils.LOG_HEADER_SIZE, FS.getFileSize( file ) ); empty.remove( i ); } else { assertTrue( "Log v" + i + " should be at least size " + log.getLogSize(), FS.getFileSize( file ) >= log.getLogSize() ); } } assertTrue( "Expected to find empty logs: " + empty, empty.isEmpty() ); } private Set<Long> empty( long... items ) { Set<Long> result = new HashSet<Long>(); for ( long item : items ) { result.add( item ); } return result; } private static final int MAX_LOG_SIZE = 1000; private static final byte[] RESOURCE_XID = new byte[] { 5,6,7,8,9 }; /** * A subset of what XaLogicaLog is. It's a LogLoader, add transactions to it's active log file, * and also rotate when max file size is reached. It uses the real xa command * serialization/deserialization so it's only the {@link LogLoader} aspect that is mocked. */ private class MockedLogLoader implements LogLoader { private long version; private long tx; private final File baseFile; private final ByteBuffer activeBuffer; private final int identifier = 1; private final LogPruneStrategy pruning; private final Map<Long, Long> lastCommittedTxs = new HashMap<Long, Long>(); private final Map<Long, Long> timestamps = new HashMap<Long, Long>(); private final int logSize; MockedLogLoader( LogPruneStrategy pruning ) { this( MAX_LOG_SIZE, pruning ); } MockedLogLoader( int logSize, LogPruneStrategy pruning ) { this.logSize = logSize; this.pruning = pruning; activeBuffer = ByteBuffer.allocate( logSize*10 ); baseFile = new File( directory, "log" ); clearAndWriteHeader(); } public int getLogSize() { return logSize; } private void clearAndWriteHeader() { activeBuffer.clear(); LogIoUtils.writeLogHeader( activeBuffer, version, tx ); // Because writeLogHeader does flip() activeBuffer.limit( activeBuffer.capacity() ); activeBuffer.position( LogIoUtils.LOG_HEADER_SIZE ); } @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { throw new UnsupportedOperationException(); } @Override public long getHighestLogVersion() { return version; } @Override public File getFileName( long version ) { File file = new File( baseFile + ".v" + version ); return file; } /** * @param date start record date. * @return whether or not this caused a rotation to happen. * @throws IOException */ public boolean addTransaction( int commandSize, long date ) throws IOException { InMemoryLogBuffer tempLogBuffer = new InMemoryLogBuffer(); XidImpl xid = new XidImpl( getNewGlobalId( DEFAULT_SEED, 0 ), RESOURCE_XID ); LogIoUtils.writeStart( tempLogBuffer, identifier, xid, -1, -1, date, Long.MAX_VALUE ); LogIoUtils.writeCommand( tempLogBuffer, identifier, new TestXaCommand( commandSize ) ); LogIoUtils.writeCommit( false, tempLogBuffer, identifier, ++tx, date ); LogIoUtils.writeDone( tempLogBuffer, identifier ); tempLogBuffer.read( activeBuffer ); if ( !timestamps.containsKey( version ) ) { timestamps.put( version, date ); // The first tx timestamp for this version } boolean rotate = (activeBuffer.capacity() - activeBuffer.remaining()) >= logSize; if ( rotate ) { rotate(); } return rotate; } /** * @return the total size of the previous log (currently {@link #getHighestLogVersion()}-1 */ public void addTransactionsUntilRotationHappens() throws IOException { int size = 10; while ( true ) { if ( addTransaction( size, System.currentTimeMillis() ) ) { return; } size = Math.max( 10, (size + 7)%100 ); } } public void rotate() throws IOException { lastCommittedTxs.put( version, tx ); writeBufferToFile( activeBuffer, getFileName( version++ ) ); pruning.prune( this ); clearAndWriteHeader(); } private void writeBufferToFile( ByteBuffer buffer, File fileName ) throws IOException { StoreChannel channel = null; try { buffer.flip(); channel = FS.open( fileName, "rw" ); channel.write( buffer ); } finally { if ( channel != null ) { channel.close(); } } } public int getTotalSizeOfAllExistingLogFiles() { int size = 0; for ( long version = getHighestLogVersion()-1; version >= 0; version-- ) { File file = getFileName( version ); if ( FS.fileExists( file ) ) { size += FS.getFileSize( file ); } else { break; } } return size; } public int getTotalTransactionCountOfAllExistingLogFiles() { if ( getHighestLogVersion() == 0 ) { return 0; } long upper = getHighestLogVersion()-1; long lower = upper; while ( lower >= 0 ) { File file = getFileName( lower-1 ); if ( !FS.fileExists( file ) ) { break; } else { lower--; } } return (int) (getLastCommittedTxId() - getFirstCommittedTxId( lower )); } @Override public Long getFirstCommittedTxId( long version ) { return lastCommittedTxs.get( version ); } @Override public Long getFirstStartRecordTimestamp( long version ) { return timestamps.get( version ); } @Override public long getLastCommittedTxId() { return tx; } } private static class TestXaCommand extends XaCommand { private final int totalSize; public TestXaCommand( int totalSize ) { this.totalSize = totalSize; } @Override public void execute() { // Do nothing } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.putInt( totalSize ); buffer.put( new byte[totalSize-4/*size of the totalSize integer*/] ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
148
public class TestXaLogicalLogFiles { @Test public void shouldDetectLegacyLogs() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when( fs.fileExists( new File( "logical_log.active" ) )).thenReturn( false ); when(fs.fileExists(new File("logical_log"))).thenReturn(true); when(fs.fileExists(new File("logical_log.1"))).thenReturn(false); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.LEGACY_WITHOUT_LOG_ROTATION)); } @Test public void shouldDetectNoActiveFile() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(false); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.NO_ACTIVE_FILE)); } @Test public void shouldDetectLog1Active() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG1 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn( fc ); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.LOG_1_ACTIVE)); } @Test public void shouldDetectLog2Active() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(false); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG2 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.LOG_2_ACTIVE)); } @Test public void shouldDetectCleanShutdown() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(false); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.CLEAN ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.CLEAN)); } @Test public void shouldDetectDualLog1() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG1 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.DUAL_LOGS_LOG_1_ACTIVE)); } @Test public void shouldDetectDualLog2() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( XaLogicalLogTokens.LOG2 ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); assertThat(files.determineState(), is(XaLogicalLogFiles.State.DUAL_LOGS_LOG_2_ACTIVE)); } @Test(expected=IllegalStateException.class) public void shouldThrowIllegalStateExceptionOnUnrecognizedActiveContent() throws Exception { FileSystemAbstraction fs = mock(FileSystemAbstraction.class); when(fs.fileExists(new File("logical_log.active"))).thenReturn(true); when(fs.fileExists(new File("logical_log"))).thenReturn(false); when(fs.fileExists(new File("logical_log.1"))).thenReturn(true); when(fs.fileExists(new File("logical_log.2"))).thenReturn(true); StoreChannel fc = mockedStoreChannel( ';' ); when(fs.open(eq(new File("logical_log.active")), anyString())).thenReturn(fc); XaLogicalLogFiles files = new XaLogicalLogFiles(new File("logical_log"), fs); files.determineState(); } private StoreChannel mockedStoreChannel( char c ) throws IOException { return new MockedFileChannel(ByteBuffer.allocate(4).putChar(c).array()); } private static class MockedFileChannel extends StoreFileChannel { private ByteBuffer bs; public MockedFileChannel(byte [] bs) { super( (FileChannel) null ); this.bs = ByteBuffer.wrap(bs); } @Override public long position() throws IOException { return bs.position(); } @Override public int read(ByteBuffer buffer) throws IOException { int start = bs.position(); buffer.put(bs); return bs.position() - start; } @Override public void close() throws IOException { } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestXaLogicalLogFiles.java
149
public abstract class XaCommand { private boolean isRecovered = false; /** * Default implementation of rollback that does nothing. This method is not * to undo any work done by the {@link #execute} method. Commands in a * {@link XaTransaction} are either all rolled back or all executed, they're * not linked together as usual execute/rollback methods. * <p> * Since a command only is in memory nothing has been made persistent so * rollback usually don't have to do anything. Sometimes however a command * needs to acquire resources when created (since the application thinks it * has done the work when the command is created). For example, if a command * creates some entity that has a primary id we need to generate that id * upon command creation. But if the command is rolled back we should * release that id. This is the place to do just that. */ public void rollback() { }; /** * Executes the command and makes it persistent. This method must succeed, * any protests about this command not being able to execute should be done * before execution of any command within the transaction. */ public abstract void execute(); /** * When a command is added to a transaction (usually when it is created) it * must be written to the {@link XaLogicalLog}. This method should write * all the data that is needed to re-create the command (see * {@link XaCommandFactory}). * <p> * Write the data to the <CODE>fileChannel</CODE>, you can use the * <CODE>buffer</CODE> supplied or create your own buffer since its capacity * is very small (137 bytes or something). Acccess to writing commands is * synchronized, only one command will be written at a time so if you need * to write larger data sets the commands can share the same buffer. * <p> * Don't throw an <CODE>IOException</CODE> to imply something is wrong * with the command. An exception should only be thrown here if there is a * real IO failure. If something is wrong with this command it should have * been detected when it was created. * <p> * Don't <CODE>force</CODE>, <CODE>position</CODE> or anything except * normal forward <CODE>write</CODE> with the file channel. * * @param fileChannel * The channel to the {@link XaLogicalLog} * @param buffer * A small byte buffer that can be used to write command data * @throws IOException * In case of *real* IO failure */ public abstract void writeToFile( LogBuffer buffer ) throws IOException; /** * If this command is created by the command factory during a recovery scan * of the logical log this method will be called to mark the command as a * "recovered command". */ protected void setRecovered() { isRecovered = true; } /** * Returns wether or not this is a "recovered command". * * @return <CODE>true</CODE> if command was created during a recovery else * <CODE>false</CODE> is returned */ public boolean isRecovered() { return isRecovered; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_XaCommand.java
150
{ public long generate( XaDataSource dataSource, int identifier ) throws XAException { return dataSource.getLastCommittedTxId() + 1; } public int getCurrentMasterId() { return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER; } public int getMyId() { return XaLogicalLog.MASTER_ID_REPRESENTING_NO_MASTER; } @Override public void committed( XaDataSource dataSource, int identifier, long txId, Integer externalAuthor ) { } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TxIdGenerator.java
151
private static class CommandVisitor implements CommandRecordVisitor { private final int localId; private final Visitor visitor; public CommandVisitor( int localId, Visitor visitor ) { this.localId = localId; this.visitor = visitor; } @Override public void visitNode( NodeRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteNode( localId, record.getId() ); } else { visitor.visitUpdateNode( localId, record ); } } @Override public void visitRelationship( RelationshipRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteRelationship( localId, record.getId() ); } else { visitor.visitUpdateRelationship( localId, record ); } } @Override public void visitProperty( PropertyRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteProperty( localId, record.getId() ); } else { visitor.visitUpdateProperty( localId, record ); } } @Override public void visitRelationshipTypeToken( RelationshipTypeTokenRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteRelationshipTypeToken( localId, record.getId() ); } else { visitor.visitUpdateRelationshipTypeToken( localId, record ); } } @Override public void visitLabelToken( LabelTokenRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteLabelToken( localId, record.getId() ); } else { visitor.visitUpdateLabelToken( localId, record ); } } @Override public void visitPropertyKeyToken( PropertyKeyTokenRecord record ) { if ( !record.inUse() ) { visitor.visitDeletePropertyKeyToken( localId, record.getId() ); } else { visitor.visitUpdatePropertyKeyToken( localId, record ); } } @Override public void visitNeoStore( NeoStoreRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteNeoStore( localId, record.getId() ); } else { visitor.visitUpdateNeoStore( localId, record ); } } @Override public void visitSchemaRule( Collection<DynamicRecord> records ) { if ( ! records.isEmpty() ) { DynamicRecord first = records.iterator().next(); if ( !first.inUse() ) { visitor.visitDeleteSchemaRule( localId, records, first.getId() ); } else { visitor.visitUpdateSchemaRule( localId, records ); } } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionReader.java
152
{ @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( null, null, byteChannel, buffer ); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionReader.java
153
public class TransactionReader { public interface Visitor { void visitStart( int localId, byte[] globalTransactionId, int masterId, int myId, long startTimestamp ); void visitPrepare( int localId, long prepareTimestamp ); void visitCommit( int localId, boolean twoPhase, long txId, long commitTimestamp ); void visitDone( int localId ); void visitUpdateNode( int localId, NodeRecord node ); void visitDeleteNode( int localId, long node ); void visitUpdateRelationship( int localId, RelationshipRecord node ); void visitDeleteRelationship( int localId, long node ); void visitUpdateProperty( int localId, PropertyRecord node ); void visitDeleteProperty( int localId, long node ); void visitUpdateRelationshipTypeToken( int localId, RelationshipTypeTokenRecord node ); void visitDeleteRelationshipTypeToken( int localId, int node ); void visitUpdateLabelToken( int localId, LabelTokenRecord node ); void visitDeleteLabelToken( int localId, int node ); void visitUpdatePropertyKeyToken( int localId, PropertyKeyTokenRecord node ); void visitDeletePropertyKeyToken( int localId, int node ); void visitUpdateNeoStore( int localId, NeoStoreRecord node ); void visitDeleteNeoStore( int localId, long node ); void visitDeleteSchemaRule( int localId, Collection<DynamicRecord> records, long id ); void visitUpdateSchemaRule( int localId, Collection<DynamicRecord> records ); } private static final XaCommandFactory COMMAND_FACTORY = new XaCommandFactory() { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( null, null, byteChannel, buffer ); } }; private final ByteBuffer buffer = ByteBuffer.wrap( new byte[256] ); public void read( ReadableByteChannel source, Visitor visitor ) throws IOException { for ( LogEntry entry; null != (entry = readEntry( source )); ) { if ( entry instanceof LogEntry.Command ) { Command command = (Command) ((LogEntry.Command) entry).getXaCommand(); command.accept( new CommandVisitor( entry.getIdentifier(), visitor ) ); } else if ( entry instanceof LogEntry.Start ) { LogEntry.Start start = (LogEntry.Start) entry; visitor.visitStart( start.getIdentifier(), start.getXid().getGlobalTransactionId(), start.getMasterId(), start.getLocalId(), start.getTimeWritten() ); } else if ( entry instanceof LogEntry.Prepare ) { LogEntry.Prepare prepare = (LogEntry.Prepare) entry; visitor.visitPrepare( prepare.getIdentifier(), prepare.getTimeWritten() ); } else if ( entry instanceof LogEntry.OnePhaseCommit ) { LogEntry.OnePhaseCommit commit = (LogEntry.OnePhaseCommit) entry; visitor.visitCommit( commit.getIdentifier(), false, commit.getTxId(), commit.getTimeWritten() ); } else if ( entry instanceof LogEntry.TwoPhaseCommit ) { LogEntry.TwoPhaseCommit commit = (LogEntry.TwoPhaseCommit) entry; visitor.visitCommit( commit.getIdentifier(), true, commit.getTxId(), commit.getTimeWritten() ); } else if ( entry instanceof LogEntry.Done ) { LogEntry.Done done = (LogEntry.Done) entry; visitor.visitDone( done.getIdentifier() ); } } } private LogEntry readEntry( ReadableByteChannel source ) throws IOException { return LogIoUtils.readEntry( buffer, source, COMMAND_FACTORY ); } private static class CommandVisitor implements CommandRecordVisitor { private final int localId; private final Visitor visitor; public CommandVisitor( int localId, Visitor visitor ) { this.localId = localId; this.visitor = visitor; } @Override public void visitNode( NodeRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteNode( localId, record.getId() ); } else { visitor.visitUpdateNode( localId, record ); } } @Override public void visitRelationship( RelationshipRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteRelationship( localId, record.getId() ); } else { visitor.visitUpdateRelationship( localId, record ); } } @Override public void visitProperty( PropertyRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteProperty( localId, record.getId() ); } else { visitor.visitUpdateProperty( localId, record ); } } @Override public void visitRelationshipTypeToken( RelationshipTypeTokenRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteRelationshipTypeToken( localId, record.getId() ); } else { visitor.visitUpdateRelationshipTypeToken( localId, record ); } } @Override public void visitLabelToken( LabelTokenRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteLabelToken( localId, record.getId() ); } else { visitor.visitUpdateLabelToken( localId, record ); } } @Override public void visitPropertyKeyToken( PropertyKeyTokenRecord record ) { if ( !record.inUse() ) { visitor.visitDeletePropertyKeyToken( localId, record.getId() ); } else { visitor.visitUpdatePropertyKeyToken( localId, record ); } } @Override public void visitNeoStore( NeoStoreRecord record ) { if ( !record.inUse() ) { visitor.visitDeleteNeoStore( localId, record.getId() ); } else { visitor.visitUpdateNeoStore( localId, record ); } } @Override public void visitSchemaRule( Collection<DynamicRecord> records ) { if ( ! records.isEmpty() ) { DynamicRecord first = records.iterator().next(); if ( !first.inUse() ) { visitor.visitDeleteSchemaRule( localId, records, first.getId() ); } else { visitor.visitUpdateSchemaRule( localId, records ); } } } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionReader.java
154
public class TransactionMonitorTest { @Test public void shouldCountCommittedTransactions() throws Exception { GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase(); Monitors monitors = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency( Monitors.class ); EideticTransactionMonitor monitor = new EideticTransactionMonitor(); monitors.addMonitorListener( monitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); Transaction tx = db.beginTx(); db.createNode(); tx.success(); tx.finish(); assertEquals( 1, monitor.getCommitCount() ); assertEquals( 0, monitor.getInjectOnePhaseCommitCount() ); assertEquals( 0, monitor.getInjectTwoPhaseCommitCount() ); } @Test public void shouldNotCountRolledBackTransactions() throws Exception { GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase(); Monitors monitors = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency( Monitors.class ); EideticTransactionMonitor monitor = new EideticTransactionMonitor(); monitors.addMonitorListener( monitor, XaResourceManager.class.getName(), NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); Transaction tx = db.beginTx(); db.createNode(); tx.failure(); tx.finish(); assertEquals( 0, monitor.getCommitCount() ); assertEquals( 0, monitor.getInjectOnePhaseCommitCount() ); assertEquals( 0, monitor.getInjectTwoPhaseCommitCount() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionMonitorTest.java
155
public abstract class TransactionInterceptorProvider extends Service { private final String name; public TransactionInterceptorProvider( String name ) { super( name ); this.name = name; } /** * Returns the name of this provider * * @return The name of this provider */ public final String name() { return name; } /** * Creates a TransactionInterceptor with the given datasource and options. * It is possible for this method to return null, signifying that the * options passed did not allow for instantiation. * * @param ds The datasource the TransactionInterceptor will communicate with * @param options An object that can be the options to instantiate the * interceptor with - e.g "false" to prevent instantiation * @return An implementation of TransactionInterceptor or null if the * options say so. */ public abstract TransactionInterceptor create( XaDataSource ds, String options, DependencyResolver dependencyResolver ); /** * Creates a TransactionInterceptor with the given datasource and options * and the given TransactionInterceptor as the next in the chain. * It is possible for this method to return null, signifying that the * options passed did not allow for instantiation. * * @param ds The datasource the TransactionInterceptor will communicate with * @param options An object that can be the options to instantiate the * interceptor with - e.g "false" to prevent instantiation * @param next The next interceptor in the chain - can be null * @return An implementation of TransactionInterceptor or null if the * options say so. */ public abstract TransactionInterceptor create( TransactionInterceptor next, XaDataSource ds, String options, DependencyResolver dependencyResolver ); }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionInterceptorProvider.java
156
public class TransactionInfo implements Comparable<TransactionInfo> { private final int identifier; private final boolean trueForOnePhase; private final long txId; private final int master; private final long checksum; public TransactionInfo( int identifier, boolean trueForOnePhase, long txId, int master, long checksum ) { super(); this.identifier = identifier; this.trueForOnePhase = trueForOnePhase; this.txId = txId; this.master = master; this.checksum = checksum; } public int getIdentifier() { return identifier; } public boolean isOnePhase() { return trueForOnePhase; } public long getTxId() { return txId; } public int getMaster() { return master; } public long getChecksum() { return checksum; } @Override public int hashCode() { return identifier; } @Override public boolean equals( Object obj ) { return obj instanceof TransactionInfo && ((TransactionInfo)obj).identifier == identifier; } @Override public int compareTo( TransactionInfo o ) { return Long.valueOf( txId ).compareTo( Long.valueOf( o.txId ) ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_TransactionInfo.java
157
private static class MockedFileChannel extends StoreFileChannel { private ByteBuffer bs; public MockedFileChannel(byte [] bs) { super( (FileChannel) null ); this.bs = ByteBuffer.wrap(bs); } @Override public long position() throws IOException { return bs.position(); } @Override public int read(ByteBuffer buffer) throws IOException { int start = bs.position(); buffer.put(bs); return bs.position() - start; } @Override public void close() throws IOException { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestXaLogicalLogFiles.java
158
public class TestUpgradeOneDotFourToFiveIT { private static final File PATH = new File( "target/test-data/upgrade-1.4-5" ); @BeforeClass public static void doBefore() throws Exception { deleteRecursively( PATH ); } @Test( expected=IllegalLogFormatException.class ) public void cannotRecoverNoncleanShutdownDbWithOlderLogFormat() throws Exception { copyRecursively( findDatabaseDirectory( getClass(), "non-clean-1.4.2-db" ), PATH ); KernelHealth kernelHealth = mock( KernelHealth.class ); XaLogicalLog log = new XaLogicalLog( resourceFile(), null, null, null, defaultFileSystemAbstraction(), new Monitors(), new DevNullLoggingService(), LogPruneStrategies.NO_PRUNING, TransactionStateFactory.noStateFactory( new DevNullLoggingService() ), kernelHealth, 25 * 1024 * 1024, ALLOW_ALL ); log.open(); fail( "Shouldn't be able to start" ); } protected File resourceFile() { return new File( PATH, "nioneo_logical.log" ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestUpgradeOneDotFourToFiveIT.java
159
private class MockedLogLoader implements LogLoader { private long version; private long tx; private final File baseFile; private final ByteBuffer activeBuffer; private final int identifier = 1; private final LogPruneStrategy pruning; private final Map<Long, Long> lastCommittedTxs = new HashMap<Long, Long>(); private final Map<Long, Long> timestamps = new HashMap<Long, Long>(); private final int logSize; MockedLogLoader( LogPruneStrategy pruning ) { this( MAX_LOG_SIZE, pruning ); } MockedLogLoader( int logSize, LogPruneStrategy pruning ) { this.logSize = logSize; this.pruning = pruning; activeBuffer = ByteBuffer.allocate( logSize*10 ); baseFile = new File( directory, "log" ); clearAndWriteHeader(); } public int getLogSize() { return logSize; } private void clearAndWriteHeader() { activeBuffer.clear(); LogIoUtils.writeLogHeader( activeBuffer, version, tx ); // Because writeLogHeader does flip() activeBuffer.limit( activeBuffer.capacity() ); activeBuffer.position( LogIoUtils.LOG_HEADER_SIZE ); } @Override public ReadableByteChannel getLogicalLogOrMyselfCommitted( long version, long position ) throws IOException { throw new UnsupportedOperationException(); } @Override public long getHighestLogVersion() { return version; } @Override public File getFileName( long version ) { File file = new File( baseFile + ".v" + version ); return file; } /** * @param date start record date. * @return whether or not this caused a rotation to happen. * @throws IOException */ public boolean addTransaction( int commandSize, long date ) throws IOException { InMemoryLogBuffer tempLogBuffer = new InMemoryLogBuffer(); XidImpl xid = new XidImpl( getNewGlobalId( DEFAULT_SEED, 0 ), RESOURCE_XID ); LogIoUtils.writeStart( tempLogBuffer, identifier, xid, -1, -1, date, Long.MAX_VALUE ); LogIoUtils.writeCommand( tempLogBuffer, identifier, new TestXaCommand( commandSize ) ); LogIoUtils.writeCommit( false, tempLogBuffer, identifier, ++tx, date ); LogIoUtils.writeDone( tempLogBuffer, identifier ); tempLogBuffer.read( activeBuffer ); if ( !timestamps.containsKey( version ) ) { timestamps.put( version, date ); // The first tx timestamp for this version } boolean rotate = (activeBuffer.capacity() - activeBuffer.remaining()) >= logSize; if ( rotate ) { rotate(); } return rotate; } /** * @return the total size of the previous log (currently {@link #getHighestLogVersion()}-1 */ public void addTransactionsUntilRotationHappens() throws IOException { int size = 10; while ( true ) { if ( addTransaction( size, System.currentTimeMillis() ) ) { return; } size = Math.max( 10, (size + 7)%100 ); } } public void rotate() throws IOException { lastCommittedTxs.put( version, tx ); writeBufferToFile( activeBuffer, getFileName( version++ ) ); pruning.prune( this ); clearAndWriteHeader(); } private void writeBufferToFile( ByteBuffer buffer, File fileName ) throws IOException { StoreChannel channel = null; try { buffer.flip(); channel = FS.open( fileName, "rw" ); channel.write( buffer ); } finally { if ( channel != null ) { channel.close(); } } } public int getTotalSizeOfAllExistingLogFiles() { int size = 0; for ( long version = getHighestLogVersion()-1; version >= 0; version-- ) { File file = getFileName( version ); if ( FS.fileExists( file ) ) { size += FS.getFileSize( file ); } else { break; } } return size; } public int getTotalTransactionCountOfAllExistingLogFiles() { if ( getHighestLogVersion() == 0 ) { return 0; } long upper = getHighestLogVersion()-1; long lower = upper; while ( lower >= 0 ) { File file = getFileName( lower-1 ); if ( !FS.fileExists( file ) ) { break; } else { lower--; } } return (int) (getLastCommittedTxId() - getFirstCommittedTxId( lower )); } @Override public Long getFirstCommittedTxId( long version ) { return lastCommittedTxs.get( version ); } @Override public Long getFirstStartRecordTimestamp( long version ) { return timestamps.get( version ); } @Override public long getLastCommittedTxId() { return tx; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
160
private static class CommandFactory extends XaCommandFactory { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( null, null, byteChannel, buffer ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestTxTimestamps.java
161
public class TestTxTimestamps { private final EphemeralFileSystemAbstraction fileSystem = new EphemeralFileSystemAbstraction(); private GraphDatabaseAPI db; @Before public void doBefore() throws Exception { db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fileSystem ).newImpermanentDatabaseBuilder(). setConfig( GraphDatabaseSettings.keep_logical_logs, Settings.TRUE ).newGraphDatabase(); } @After public void doAfter() throws Exception { db.shutdown(); } @Test public void doIt() throws Exception { long[] expectedStartTimestamps = new long[10]; long[] expectedCommitTimestamps = new long[expectedStartTimestamps.length]; for ( int i = 0; i < expectedStartTimestamps.length; i++ ) { Transaction tx = db.beginTx(); expectedStartTimestamps[i] = System.currentTimeMillis(); Node node = db.createNode(); node.setProperty( "name", "Mattias " + i ); tx.success(); tx.finish(); expectedCommitTimestamps[i] = System.currentTimeMillis(); } db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getNeoStoreDataSource().rotateLogicalLog(); ByteBuffer buffer = ByteBuffer.allocate( 1024*500 ); StoreChannel channel = fileSystem.open( new File( db.getStoreDir(), NeoStoreXaDataSource.LOGICAL_LOG_DEFAULT_NAME + ".v0" ), "r" ); try { XaCommandFactory commandFactory = new CommandFactory(); LogIoUtils.readLogHeader( buffer, channel, true ); int foundTxCount = 0; skipFirstTransaction( buffer, channel, commandFactory ); // Since it's the property index transaction for (LogEntry entry; (entry = LogIoUtils.readEntry( buffer, channel, commandFactory )) != null; ) { if ( entry instanceof LogEntry.Start ) { long diff = ((LogEntry.Start) entry).getTimeWritten()-expectedStartTimestamps[foundTxCount]; long exp = expectedCommitTimestamps[foundTxCount] - expectedStartTimestamps[foundTxCount]; assertTrue( diff + " <= " + exp, diff <= exp ); } else if ( entry instanceof LogEntry.Commit ) { long diff = ((LogEntry.Commit) entry).getTimeWritten()-expectedCommitTimestamps[foundTxCount]; long exp = expectedCommitTimestamps[foundTxCount] - expectedStartTimestamps[foundTxCount]; assertTrue( diff + " <= " + exp, diff <= exp ); foundTxCount++; } } assertEquals( expectedCommitTimestamps.length, foundTxCount ); } finally { channel.close(); } } private void skipFirstTransaction( ByteBuffer buffer, StoreChannel channel, XaCommandFactory commandFactory ) throws IOException { for (LogEntry entry; (entry = LogIoUtils.readEntry( buffer, channel, commandFactory )) != null; ) if ( entry instanceof Commit ) break; } private static class CommandFactory extends XaCommandFactory { @Override public XaCommand readCommand( ReadableByteChannel byteChannel, ByteBuffer buffer ) throws IOException { return Command.readCommand( null, null, byteChannel, buffer ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestTxTimestamps.java
162
public class TestTxEntries { private final Random random = new Random(); private final long refTime = System.currentTimeMillis(); private final int refId = 1; private final int refMaster = 1; private final int refMe = 1; private final long startPosition = 1000; private final String storeDir = "dir"; @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); /* * Starts a JVM, executes a tx that fails on prepare and rollbacks, * triggering a bug where an extra start entry for that tx is written * in the xa log. */ @Test public void testStartEntryWrittenOnceOnRollback() throws Exception { final GraphDatabaseService db = new TestGraphDatabaseFactory().setFileSystem( fs.get() ).newImpermanentDatabase( storeDir ); createSomeTransactions( db ); EphemeralFileSystemAbstraction snapshot = fs.snapshot( shutdownDb( db ) ); new TestGraphDatabaseFactory().setFileSystem( snapshot ).newImpermanentDatabase( storeDir ).shutdown(); } @Test public void startEntryShouldBeUniqueIfEitherValueChanges() throws Exception { // Positive Xid hashcode assertCorrectChecksumEquality( randomXid( Boolean.TRUE ) ); // Negative Xid hashcode assertCorrectChecksumEquality( randomXid( Boolean.FALSE ) ); } private void assertCorrectChecksumEquality( Xid refXid ) { Start ref = new Start( refXid, refId, refMaster, refMe, startPosition, refTime, 0l ); assertChecksumsEquals( ref, new Start( refXid, refId, refMaster, refMe, startPosition, refTime, 0l ) ); // Different Xids assertChecksumsNotEqual( ref, new Start( randomXid( null ), refId, refMaster, refMe, startPosition, refTime, 0l ) ); // Different master assertChecksumsNotEqual( ref, new Start( refXid, refId, refMaster+1, refMe, startPosition, refTime, 0l ) ); // Different me assertChecksumsNotEqual( ref, new Start( refXid, refId, refMaster, refMe+1, startPosition, refTime, 0l ) ); } private void assertChecksumsNotEqual( Start ref, Start other ) { assertFalse( ref.getChecksum() == other.getChecksum() ); } private void assertChecksumsEquals( Start ref, Start other ) { assertEquals( ref.getChecksum(), other.getChecksum() ); } private Xid randomXid( Boolean trueForPositive ) { while ( true ) { Xid xid = new XidImpl( randomBytes(), randomBytes() ); if ( trueForPositive == null || xid.hashCode() > 0 == trueForPositive.booleanValue() ) { return xid; } } } private byte[] randomBytes() { byte[] bytes = new byte[random.nextInt( 10 )+5]; for ( int i = 0; i < bytes.length; i++ ) { bytes[i] = (byte) random.nextInt( 255 ); } return bytes; } private void createSomeTransactions( GraphDatabaseService db ) { Transaction tx = db.beginTx(); Node node1 = db.createNode(); Node node2 = db.createNode(); node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "relType1" ) ); tx.success(); tx.finish(); tx = db.beginTx(); node1.delete(); tx.success(); try { // Will throw exception, causing the tx to be rolledback. tx.finish(); } catch ( Exception nothingToSeeHereMoveAlong ) { // InvalidRecordException coming, node1 has rels } /* * The damage has already been done. The following just makes sure * the corrupting tx is flushed to disk, since we will exit * uncleanly. */ tx = db.beginTx(); node1.setProperty( "foo", "bar" ); tx.success(); tx.finish(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestTxEntries.java
163
public class TestStandaloneLogExtractor { @Test public void testRecreateCleanDbFromStandaloneExtractor() throws Exception { run( true, 1 ); } @Test public void testRecreateUncleanDbFromStandaloneExtractor() throws Exception { run( false, 2 ); } private void run( boolean cleanShutdown, int nr ) throws Exception { EphemeralFileSystemAbstraction fileSystem = new EphemeralFileSystemAbstraction(); String storeDir = "source" + nr; GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory(). setFileSystem( fileSystem ). newImpermanentDatabase( storeDir ); createSomeTransactions( db ); DbRepresentation rep = DbRepresentation.of( db ); EphemeralFileSystemAbstraction snapshot; if ( cleanShutdown ) { db.shutdown(); snapshot = fileSystem.snapshot(); } else { snapshot = fileSystem.snapshot(); db.shutdown(); } GraphDatabaseAPI newDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory(). setFileSystem( snapshot ). newImpermanentDatabase( storeDir ); XaDataSource ds = newDb.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getNeoStoreDataSource(); LogExtractor extractor = LogExtractor.from( snapshot, new File( storeDir ), new Monitors().newMonitor( ByteCounterMonitor.class ) ); long expectedTxId = 2; while ( true ) { InMemoryLogBuffer buffer = new InMemoryLogBuffer(); long txId = extractor.extractNext( buffer ); assertEquals( expectedTxId++, txId ); /* first tx=2 * 1 tx for relationship type * 1 tx for property index * 1 for the first tx * 5 additional tx + 1 tx for the other property index * ==> 11 */ if ( expectedTxId == 11 ) { expectedTxId = -1; } if ( txId == -1 ) { break; } ds.applyCommittedTransaction( txId, buffer ); } DbRepresentation newRep = DbRepresentation.of( newDb ); newDb.shutdown(); assertEquals( rep, newRep ); fileSystem.shutdown(); } private void createSomeTransactions( GraphDatabaseAPI db ) throws IOException { try ( BatchTransaction tx = beginBatchTx( db ) ) { Node node = db.createNode(); node.setProperty( "name", "First" ); Node otherNode = db.createNode(); node.createRelationshipTo( otherNode, MyRelTypes.TEST ); tx.intermediaryCommit(); db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ) .getNeoStoreDataSource().rotateLogicalLog(); for ( int i = 0; i < 5; i++ ) { db.createNode().setProperty( "type", i ); tx.intermediaryCommit(); } } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestStandaloneLogExtractor.java
164
{ int doneRecordCount = 0; @Override public boolean accept( LogEntry item ) { //System.out.println(item); if( item instanceof LogEntry.Done) { doneRecordCount++; // Accept everything except the second done record we find if( doneRecordCount == 2) { brokenTxIdentifier.set( item.getIdentifier() ); return false; } } // Not a done record, not our concern return true; } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestPartialTransactionCopier.java
165
public class TestPartialTransactionCopier { @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); @SuppressWarnings( "unchecked" ) @Test public void shouldCopyRunningTransactionsToNewLog() throws Exception { // Given int masterId = -1; int meId = -1; String storeDir = "dir"; // I have a log with a transaction in the middle missing a "DONE" record Pair<File, Integer> broken = createBrokenLogFile( storeDir ); File brokenLogFile = broken.first(); Integer brokenTxIdentifier = broken.other(); // And I've read the log header on that broken file StoreChannel brokenLog = fs.get().open( brokenLogFile, "rw" ); ByteBuffer buffer = allocate( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 ); readLogHeader( buffer, brokenLog, true ); // And I have an awesome partial transaction copier PartialTransactionCopier copier = new PartialTransactionCopier( buffer, new CommandFactory(), StringLogger.DEV_NULL, new LogExtractor.LogPositionCache(), null, createXidMapWithOneStartEntry( masterId, /*txId=*/brokenTxIdentifier ), new Monitors().newMonitor( ByteCounterMonitor.class ) ); // When File newLogFile = new File( "new.log" ); copier.copy( brokenLog, createNewLogWithHeader( newLogFile ), 1 ); // Then assertThat( logEntries( fs.get(), newLogFile ), containsExactly( startEntry( brokenTxIdentifier, masterId, meId ), nodeCommandEntry( brokenTxIdentifier, /*nodeId=*/1 ), onePhaseCommitEntry( brokenTxIdentifier, /*txid=*/3 ), // Missing done entry startEntry( 5, masterId, meId ), nodeCommandEntry( 5, /*nodeId=*/2), onePhaseCommitEntry( 5, /*txid=*/4 ), doneEntry( 5 ), startEntry( 6, masterId, meId ), nodeCommandEntry( 6, /*nodeId=*/3 ), onePhaseCommitEntry( 6, /*txid=*/5 ), doneEntry( 6 ) )); } private ArrayMap<Integer, LogEntry.Start> createXidMapWithOneStartEntry( int masterId, Integer brokenTxId ) { ArrayMap<Integer, LogEntry.Start> xidentMap = new ArrayMap<Integer, LogEntry.Start>(); xidentMap.put( brokenTxId, new LogEntry.Start( null, brokenTxId, masterId, 3, 4, 5, 6 ) ); return xidentMap; } private LogBuffer createNewLogWithHeader( File newLogFile ) throws IOException { StoreChannel newLog = fs.get().open( newLogFile, "rw" ); LogBuffer newLogBuffer = new DirectLogBuffer( newLog, allocate( 10000 ) ); ByteBuffer buf = allocate( 100 ); writeLogHeader( buf, 1, /* we don't care about this */ 4 ); newLogBuffer.getFileChannel().write( buf ); return newLogBuffer; } private Pair<File, Integer> createBrokenLogFile( String storeDir ) throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory() .setFileSystem( fs.get() ).newImpermanentDatabase( storeDir ); for ( int i = 0; i < 4; i++ ) { Transaction tx = db.beginTx(); db.createNode(); tx.success(); tx.finish(); } db.shutdown(); // Remove the DONE record from the second transaction final AtomicInteger brokenTxIdentifier = new AtomicInteger(); LogHookAdapter<LogEntry> filter = new LogTestUtils.LogHookAdapter<LogEntry>() { int doneRecordCount = 0; @Override public boolean accept( LogEntry item ) { //System.out.println(item); if( item instanceof LogEntry.Done) { doneRecordCount++; // Accept everything except the second done record we find if( doneRecordCount == 2) { brokenTxIdentifier.set( item.getIdentifier() ); return false; } } // Not a done record, not our concern return true; } }; File brokenLogFile = filterNeostoreLogicalLog( fs.get(), new File( storeDir, "nioneo_logical.log.v0"), filter ); return Pair.of( brokenLogFile, brokenTxIdentifier.get() ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestPartialTransactionCopier.java
166
{ @Override protected FileSystemAbstraction createFileSystemAbstraction() { return (fs = super.createFileSystemAbstraction()); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruning.java
167
public class TestLogPruning { private GraphDatabaseAPI db; private FileSystemAbstraction fs; @After public void after() throws Exception { if ( db != null ) { db.shutdown(); } } @Test public void noPruning() throws Exception { newDb( "true" ); for ( int i = 0; i < 100; i++ ) { doTransaction(); rotate(); assertEquals( i+1, logCount() ); } } @Test public void pruneByFileSize() throws Exception { // Given int size = 1050; newDb( size + " size" ); doTransaction(); rotate(); long sizeOfOneLog = fs.getFileSize( neoDataSource() .getXaContainer().getLogicalLog().getFileName( 0 ) ); int filesNeededToExceedPruneLimit = (int) Math.ceil( (double) size / (double) sizeOfOneLog ); // When for ( int i = 1; i < filesNeededToExceedPruneLimit*2; i++ ) { doTransaction(); rotate(); // Then assertEquals( Math.min( i+1, filesNeededToExceedPruneLimit ), logCount() ); } } private NeoStoreXaDataSource neoDataSource() { return db.getDependencyResolver().resolveDependency( XaDataSourceManager.class ).getNeoStoreDataSource(); } @Test public void pruneByFileCount() throws Exception { int logsToKeep = 5; newDb( logsToKeep + " files" ); for ( int i = 0; i < logsToKeep*2; i++ ) { doTransaction(); rotate(); assertEquals( Math.min( i+1, logsToKeep ), logCount() ); } } @Test public void pruneByTransactionCount() throws Exception { int transactionsToKeep = 100; int txsPerLog = transactionsToKeep/10; newDb( transactionsToKeep + " txs" ); for ( int i = 0; i < transactionsToKeep/txsPerLog*3; i++ ) { for ( int j = 0; j < txsPerLog; j++ ) { doTransaction(); } rotate(); assertEquals( Math.min( i+1, transactionsToKeep/txsPerLog ), logCount() ); } } private GraphDatabaseAPI newDb( String logPruning ) { GraphDatabaseAPI db = new ImpermanentGraphDatabase( stringMap( keep_logical_logs.name(), logPruning ) ) { @Override protected FileSystemAbstraction createFileSystemAbstraction() { return (fs = super.createFileSystemAbstraction()); } }; this.db = db; return db; } private void doTransaction() { Transaction tx = db.beginTx(); try { db.createNode(); tx.success(); } finally { tx.finish(); } } private void rotate() throws Exception { neoDataSource().rotateLogicalLog(); } private int logCount() { XaLogicalLog log = neoDataSource().getXaContainer().getLogicalLog(); int count = 0; for ( long i = log.getHighestLogVersion()-1; i >= 0; i-- ) { if ( fs.fileExists( log.getFileName( i ) ) ) { count++; } else { break; } } return count; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruning.java
168
private static class TestXaCommand extends XaCommand { private final int totalSize; public TestXaCommand( int totalSize ) { this.totalSize = totalSize; } @Override public void execute() { // Do nothing } @Override public void writeToFile( LogBuffer buffer ) throws IOException { buffer.putInt( totalSize ); buffer.put( new byte[totalSize-4/*size of the totalSize integer*/] ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_TestLogPruneStrategy.java
169
{ @Override public boolean matchesSafely( LogEntry.OnePhaseCommit onePC ) { return onePC != null && onePC.getIdentifier() == identifier && onePC.getTxId() == txId; } @Override public void describeTo( Description description ) { description.appendText( String.format( "1PC[%d, txId=%d, <Any Date>],", identifier, txId ) ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_LogMatchers.java
170
{ @Override public boolean matchesSafely( Iterable<LogEntry> item ) { Iterator<LogEntry> actualEntries = item.iterator(); for ( Matcher<? extends LogEntry> matcher : matchers ) { if ( actualEntries.hasNext() ) { LogEntry next = actualEntries.next(); if ( !matcher.matches( next ) ) { // Wrong! return false; } } else { // Too few actual entries! return false; } } if ( actualEntries.hasNext() ) { // Too many actual entries! return false; } // All good in the hood :) return true; } @Override public void describeTo( Description description ) { for ( Matcher<? extends LogEntry> matcher : matchers ) { description.appendDescriptionOf( matcher ).appendText( ",\n" ); } } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_LogMatchers.java
171
private class TxManagerDataSourceRegistrationListener implements DataSourceRegistrationListener { @Override public void registeredDataSource( XaDataSource ds ) { branches.put( new RecoveredBranchInfo( ds.getBranchId() ), true ); boolean everythingRegistered = true; for ( boolean dsRegistered : branches.values() ) { everythingRegistered &= dsRegistered; } if ( everythingRegistered ) { doRecovery(); } } @Override public void unregisteredDataSource( XaDataSource ds ) { branches.put( new RecoveredBranchInfo( ds.getBranchId() ), false ); boolean everythingUnregistered = true; for ( boolean dsRegistered : branches.values() ) { everythingUnregistered &= !dsRegistered; } if ( everythingUnregistered ) { closeLog(); } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_TxManager.java
172
public class LogIoUtils { private static final short CURRENT_FORMAT_VERSION = ( LogEntry.CURRENT_VERSION ) & 0xFF; static final int LOG_HEADER_SIZE = 16; public static long[] readLogHeader( FileSystemAbstraction fileSystem, File file ) throws IOException { StoreChannel channel = fileSystem.open( file, "r" ); try { return readLogHeader( ByteBuffer.allocateDirect( 100*1000 ), channel, true ); } finally { channel.close(); } } public static long[] readLogHeader( ByteBuffer buffer, ReadableByteChannel channel, boolean strict ) throws IOException { buffer.clear(); buffer.limit( LOG_HEADER_SIZE ); if ( channel.read( buffer ) != LOG_HEADER_SIZE ) { if ( strict ) { throw new IOException( "Unable to read log version and last committed tx" ); } return null; } buffer.flip(); long version = buffer.getLong(); long previousCommittedTx = buffer.getLong(); long logFormatVersion = ( version >> 56 ) & 0xFF; if ( CURRENT_FORMAT_VERSION != logFormatVersion ) { throw new IllegalLogFormatException( CURRENT_FORMAT_VERSION, logFormatVersion ); } version = version & 0x00FFFFFFFFFFFFFFL; return new long[] { version, previousCommittedTx }; } public static ByteBuffer writeLogHeader( ByteBuffer buffer, long logVersion, long previousCommittedTxId ) { buffer.clear(); buffer.putLong( logVersion | ( ( (long) CURRENT_FORMAT_VERSION ) << 56 ) ); buffer.putLong( previousCommittedTxId ); buffer.flip(); return buffer; } public static LogEntry readEntry( ByteBuffer buffer, ReadableByteChannel channel, XaCommandFactory cf ) throws IOException { try { return readLogEntry( buffer, channel, cf ); } catch ( ReadPastEndException e ) { return null; } } public static LogEntry readLogEntry( ByteBuffer buffer, ReadableByteChannel channel, XaCommandFactory cf ) throws IOException, ReadPastEndException { byte entry = readNextByte( buffer, channel ); switch ( entry ) { case LogEntry.TX_START: return readTxStartEntry( buffer, channel ); case LogEntry.TX_PREPARE: return readTxPrepareEntry( buffer, channel ); case LogEntry.TX_1P_COMMIT: return readTxOnePhaseCommitEntry( buffer, channel ); case LogEntry.TX_2P_COMMIT: return readTxTwoPhaseCommitEntry( buffer, channel ); case LogEntry.COMMAND: return readTxCommandEntry( buffer, channel, cf ); case LogEntry.DONE: return readTxDoneEntry( buffer, channel ); case LogEntry.EMPTY: return null; default: throw new IOException( "Unknown entry[" + entry + "]" ); } } private static LogEntry.Start readTxStartEntry( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { byte globalIdLength = readNextByte( buf, channel ); byte branchIdLength = readNextByte( buf, channel ); byte globalId[] = new byte[globalIdLength]; readIntoBufferAndFlip( ByteBuffer.wrap( globalId ), channel, globalIdLength ); byte branchId[] = new byte[branchIdLength]; readIntoBufferAndFlip( ByteBuffer.wrap( branchId ), channel, branchIdLength ); int identifier = readNextInt( buf, channel ); @SuppressWarnings("unused") int formatId = readNextInt( buf, channel ); int masterId = readNextInt( buf, channel ); int myId = readNextInt( buf, channel ); long timeWritten = readNextLong( buf, channel ); long latestCommittedTxWhenStarted = readNextLong( buf, channel ); // re-create the transaction Xid xid = new XidImpl( globalId, branchId ); return new LogEntry.Start( xid, identifier, masterId, myId, -1, timeWritten, latestCommittedTxWhenStarted ); } private static LogEntry.Prepare readTxPrepareEntry( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return new LogEntry.Prepare( readNextInt( buf, channel ), readNextLong( buf, channel ) ); } private static LogEntry.OnePhaseCommit readTxOnePhaseCommitEntry( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return new LogEntry.OnePhaseCommit( readNextInt( buf, channel ), readNextLong( buf, channel ), readNextLong( buf, channel ) ); } private static LogEntry.Done readTxDoneEntry( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return new LogEntry.Done( readNextInt( buf, channel ) ); } private static LogEntry.TwoPhaseCommit readTxTwoPhaseCommitEntry( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return new LogEntry.TwoPhaseCommit( readNextInt( buf, channel ), readNextLong( buf, channel ), readNextLong( buf, channel ) ); } private static LogEntry.Command readTxCommandEntry( ByteBuffer buf, ReadableByteChannel channel, XaCommandFactory cf ) throws IOException, ReadPastEndException { int identifier = readNextInt( buf, channel ); XaCommand command = cf.readCommand( channel, buf ); if ( command == null ) { return null; } return new LogEntry.Command( identifier, command ); } public static void writeLogEntry( LogEntry entry, LogBuffer buffer ) throws IOException { if ( entry instanceof LogEntry.Command ) { writeCommand( buffer, entry.getIdentifier(), ((LogEntry.Command) entry).getXaCommand() ); } else if ( entry instanceof LogEntry.Start ) { writeStart( buffer, entry.getIdentifier(), ( (LogEntry.Start) entry ).getXid(), ((LogEntry.Start) entry).getMasterId(), ((LogEntry.Start) entry).getLocalId(), ((LogEntry.Start) entry).getTimeWritten(), ((LogEntry.Start) entry).getLastCommittedTxWhenTransactionStarted() ); } else if ( entry instanceof LogEntry.Done ) { writeDone( buffer, entry.getIdentifier() ); } else if ( entry instanceof LogEntry.OnePhaseCommit ) { LogEntry.Commit commit = (LogEntry.Commit) entry; writeCommit( false, buffer, commit.getIdentifier(), commit.getTxId(), ((LogEntry.OnePhaseCommit) entry).getTimeWritten() ); } else if ( entry instanceof LogEntry.Prepare ) { writePrepare( buffer, entry.getIdentifier(), ((LogEntry.Prepare) entry).getTimeWritten() ); } else if ( entry instanceof LogEntry.TwoPhaseCommit ) { LogEntry.Commit commit = (LogEntry.Commit) entry; writeCommit( true, buffer, commit.getIdentifier(), commit.getTxId(), ((LogEntry.TwoPhaseCommit) entry).getTimeWritten() ); } } public static void writePrepare( LogBuffer buffer, int identifier, long timeWritten ) throws IOException { buffer.put( LogEntry.TX_PREPARE ).putInt( identifier ).putLong( timeWritten ); } public static void writeCommit( boolean twoPhase, LogBuffer buffer, int identifier, long txId, long timeWritten ) throws IOException { buffer.put( twoPhase ? LogEntry.TX_2P_COMMIT : LogEntry.TX_1P_COMMIT ) .putInt( identifier ).putLong( txId ).putLong( timeWritten ); } public static void writeDone( LogBuffer buffer, int identifier ) throws IOException { buffer.put( LogEntry.DONE ).putInt( identifier ); } public static void writeDone( ByteBuffer buffer, int identifier ) { buffer.put( LogEntry.DONE ).putInt( identifier ); } public static void writeStart( LogBuffer buffer, int identifier, Xid xid, int masterId, int myId, long timeWritten, long latestCommittedTxWhenStarted ) throws IOException { byte globalId[] = xid.getGlobalTransactionId(); byte branchId[] = xid.getBranchQualifier(); int formatId = xid.getFormatId(); buffer.put( LogEntry.TX_START ) .put( (byte) globalId.length ) .put( (byte) branchId.length ) .put( globalId ).put( branchId ) .putInt( identifier ) .putInt( formatId ) .putInt( masterId ) .putInt( myId ) .putLong( timeWritten ) .putLong( latestCommittedTxWhenStarted ); } public static void writeCommand( LogBuffer buffer, int identifier, XaCommand command ) throws IOException { buffer.put( LogEntry.COMMAND ).putInt( identifier ); command.writeToFile( buffer ); } private static int readNextInt( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return readIntoBufferAndFlip( buf, channel, 4 ).getInt(); } private static long readNextLong( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return readIntoBufferAndFlip( buf, channel, 8 ).getLong(); } public static byte readNextByte( ByteBuffer buf, ReadableByteChannel channel ) throws IOException, ReadPastEndException { return readIntoBufferAndFlip( buf, channel, 1 ).get(); } private static ByteBuffer readIntoBufferAndFlip( ByteBuffer buf, ReadableByteChannel channel, int numberOfBytes ) throws IOException, ReadPastEndException { buf.clear(); buf.limit( numberOfBytes ); if ( channel.read( buf ) != buf.limit() ) { throw new ReadPastEndException(); } buf.flip(); return buf; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogIoUtils.java
173
public class EideticTransactionMonitor implements TransactionMonitor { private int commitCount; private int injectOnePhaseCommitCount; private int injectTwoPhaseCommitCount; @Override public void transactionCommitted( Xid xid, boolean recovered ) { commitCount++; } @Override public void injectOnePhaseCommit( Xid xid ) { injectOnePhaseCommitCount++; } @Override public void injectTwoPhaseCommit( Xid xid ) { injectTwoPhaseCommitCount++; } public int getCommitCount() { return commitCount; } public int getInjectOnePhaseCommitCount() { return injectOnePhaseCommitCount; } public int getInjectTwoPhaseCommitCount() { return injectTwoPhaseCommitCount; } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_xaframework_EideticTransactionMonitor.java
174
public class DirectMappedLogBuffer implements LogBuffer { // 500k static final int BUFFER_SIZE = 1024 * 512; private final StoreChannel fileChannel; private final ByteBuffer byteBuffer; private long bufferStartPosition; private final ByteCounterMonitor monitor; public DirectMappedLogBuffer( StoreChannel fileChannel, ByteCounterMonitor monitor ) throws IOException { this.fileChannel = fileChannel; this.monitor = monitor; bufferStartPosition = fileChannel.position(); byteBuffer = ByteBuffer.allocateDirect( BUFFER_SIZE ); } private void ensureCapacity( int plusSize ) throws IOException { if (( BUFFER_SIZE - byteBuffer.position() ) < plusSize ) { writeOut(); } assert BUFFER_SIZE - byteBuffer.position() >= plusSize : "after writing out buffer, position is " + byteBuffer.position() + " and requested size is " + plusSize; } public LogBuffer put( byte b ) throws IOException { ensureCapacity( 1 ); byteBuffer.put( b ); return this; } public LogBuffer putShort( short s ) throws IOException { ensureCapacity( 2 ); byteBuffer.putShort( s ); return this; } public LogBuffer putInt( int i ) throws IOException { ensureCapacity( 4 ); byteBuffer.putInt( i ); return this; } public LogBuffer putLong( long l ) throws IOException { ensureCapacity( 8 ); byteBuffer.putLong( l ); return this; } public LogBuffer putFloat( float f ) throws IOException { ensureCapacity( 4 ); byteBuffer.putFloat( f ); return this; } public LogBuffer putDouble( double d ) throws IOException { ensureCapacity( 8 ); byteBuffer.putDouble( d ); return this; } public LogBuffer put( byte[] bytes ) throws IOException { put( bytes, 0 ); return this; } private void put( byte[] bytes, int offset ) throws IOException { int bytesToWrite = bytes.length - offset; if ( bytesToWrite > BUFFER_SIZE ) { bytesToWrite = BUFFER_SIZE; } ensureCapacity( bytesToWrite ); byteBuffer.put( bytes, offset, bytesToWrite ); offset += bytesToWrite; if ( offset < bytes.length ) { put( bytes, offset ); } } public LogBuffer put( char[] chars ) throws IOException { put( chars, 0 ); return this; } private void put( char[] chars, int offset ) throws IOException { int charsToWrite = chars.length - offset; if ( charsToWrite * 2 > BUFFER_SIZE ) { charsToWrite = BUFFER_SIZE / 2; } ensureCapacity( charsToWrite * 2 ); int oldPos = byteBuffer.position(); byteBuffer.asCharBuffer().put( chars, offset, charsToWrite ); byteBuffer.position( oldPos + ( charsToWrite * 2 ) ); offset += charsToWrite; if ( offset < chars.length ) { put( chars, offset ); } } @Override public void writeOut() throws IOException { byteBuffer.flip(); // We use .clear() to reset this buffer, so position will always be 0 long expectedEndPosition = bufferStartPosition + byteBuffer.limit(); long bytesWritten; while((bufferStartPosition += (bytesWritten = fileChannel.write( byteBuffer, bufferStartPosition ))) < expectedEndPosition) { if( bytesWritten <= 0 ) { throw new IOException( "Unable to write to disk, reported bytes written was " + bytesWritten ); } } monitor.bytesWritten( bytesWritten ); byteBuffer.clear(); } public void force() throws IOException { writeOut(); fileChannel.force( false ); } public long getFileChannelPosition() { if ( byteBuffer != null ) { return bufferStartPosition + byteBuffer.position(); } return bufferStartPosition; } public StoreChannel getFileChannel() { return fileChannel; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_DirectMappedLogBuffer.java
175
public class DirectLogBuffer implements LogBuffer { private final StoreChannel fileChannel; private final ByteBuffer buffer; public DirectLogBuffer( StoreChannel fileChannel, ByteBuffer buffer ) { if ( fileChannel == null || buffer == null ) { throw new IllegalArgumentException( "Null argument" ); } if ( buffer.capacity() < 8 ) { throw new IllegalArgumentException( "Capacity less then 8" ); } this.fileChannel = fileChannel; this.buffer = buffer; } public LogBuffer put( byte b ) throws IOException { buffer.clear(); buffer.put( b ); return flipAndWrite(); } public LogBuffer putShort( short s ) throws IOException { buffer.clear(); buffer.putShort( s ); return flipAndWrite(); } public LogBuffer putInt( int i ) throws IOException { buffer.clear(); buffer.putInt( i ); return flipAndWrite(); } public LogBuffer putLong( long l ) throws IOException { buffer.clear(); buffer.putLong( l ); return flipAndWrite(); } public LogBuffer putFloat( float f ) throws IOException { buffer.clear(); buffer.putFloat( f ); return flipAndWrite(); } public LogBuffer putDouble( double d ) throws IOException { buffer.clear(); buffer.putDouble( d ); return flipAndWrite(); } private LogBuffer flipAndWrite() throws IOException { buffer.flip(); fileChannel.write( buffer ); return this; } public LogBuffer put( byte[] bytes ) throws IOException { fileChannel.write( ByteBuffer.wrap( bytes ) ); return this; } public LogBuffer put( char[] chars ) throws IOException { int position = 0; do { buffer.clear(); int leftToWrite = chars.length - position; if ( leftToWrite * 2 < buffer.capacity() ) { buffer.asCharBuffer().put( chars, position, leftToWrite ); buffer.limit( leftToWrite * 2); fileChannel.write( buffer ); position += leftToWrite; } else { int length = buffer.capacity() / 2; buffer.asCharBuffer().put( chars, position, length ); buffer.limit( length * 2 ); fileChannel.write( buffer ); position += length; } } while ( position < chars.length ); return this; } @Override public void writeOut() throws IOException { // Nothing to do, since the data is always written in the put... methods. } public void force() throws IOException { fileChannel.force( false ); } public long getFileChannelPosition() throws IOException { return fileChannel.position(); } public StoreChannel getFileChannel() { return fileChannel; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_DirectLogBuffer.java
176
{ @Override public long nextSequenceId() { return 1; } @Override public long nextRandomLong() { return 14; // soo random } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_XidImplTest.java
177
public class XidImplTest { @Test public void fixedSeedDifferentLocalIdShouldMakeUnequal() throws Exception { // WHEN byte[] globalIdZero = getNewGlobalId( fixedSeed, 0 ); byte[] globalIdOne = getNewGlobalId( fixedSeed, 1 ); // THEN assertFalse( Arrays.equals( globalIdZero, globalIdOne ) ); } @Test public void fixedSeedSameLocalIdShouldMakeEqual() throws Exception { // WHEN byte[] globalIdZero = getNewGlobalId( fixedSeed, 0 ); byte[] otherGlobalIdZero = getNewGlobalId( fixedSeed, 0 ); // THEN assertTrue( Arrays.equals( globalIdZero, otherGlobalIdZero ) ); } @Test public void defaultSeedDifferentLocalIdShouldMakeUnequal() throws Exception { // WHEN byte[] globalIdZero = getNewGlobalId( DEFAULT_SEED, 0 ); byte[] globalIdOne = getNewGlobalId( DEFAULT_SEED, 1 ); // THEN assertFalse( Arrays.equals( globalIdZero, globalIdOne ) ); } @Test public void defaultSeedSameLocalIdShouldMakeUnequal() throws Exception { // WHEN byte[] globalIdZero = getNewGlobalId( DEFAULT_SEED, 0 ); byte[] otherGlobalIdZero = getNewGlobalId( DEFAULT_SEED, 0 ); // THEN assertFalse( Arrays.equals( globalIdZero, otherGlobalIdZero ) ); } @Test public void shouldProduceShortXidToStringForOldGlobalIdFormat() throws Exception { // GIVEN XidImpl xid = new XidImpl( shorten( getNewGlobalId( DEFAULT_SEED, 10 ), 4 ), "test".getBytes() ); // WHEN String toString = xid.toString(); // THEN assertThat( toString, CoreMatchers.containsString( "NEOKERNL" ) ); assertEquals( 2, occurencesOf( '|', toString ) ); } @Test public void shouldProduceLongerXidToStringForNewGlobalIdFormat() throws Exception { // GIVEN XidImpl xid = new XidImpl( getNewGlobalId( DEFAULT_SEED, 10 ), "test".getBytes() ); // WHEN String toString = xid.toString(); // THEN assertThat( toString, CoreMatchers.containsString( "NEOKERNL" ) ); assertEquals( 3, occurencesOf( '|', toString ) ); } private byte[] shorten( byte[] newGlobalId, int byHowMuch ) { return copyOf( newGlobalId, newGlobalId.length-byHowMuch ); } private int occurencesOf( char c, String inString ) { int count = 0; for ( int i = 0; i < inString.length(); i++ ) { if ( c == inString.charAt( i ) ) { count++; } } return count; } /* * The fixed seed is not a normal seed, it mimics many seed instances having the exact same start condition, * for example if two database instances would start and by chance get the same seed. */ private final XidImpl.Seed fixedSeed = new XidImpl.Seed() { @Override public long nextSequenceId() { return 1; } @Override public long nextRandomLong() { return 14; // soo random } }; }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_XidImplTest.java
178
{ private long nextSequenceId = 0; private final Random r = new Random(); @Override public synchronized long nextSequenceId() { return nextSequenceId++; } @Override public long nextRandomLong() { return r.nextLong(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XidImpl.java
179
public class XidImpl implements Xid { interface Seed { long nextRandomLong(); long nextSequenceId(); } public static final Seed DEFAULT_SEED = new Seed() { private long nextSequenceId = 0; private final Random r = new Random(); @Override public synchronized long nextSequenceId() { return nextSequenceId++; } @Override public long nextRandomLong() { return r.nextLong(); } }; // Neo4j ('N' 'E' 'O') format identifier private static final int FORMAT_ID = 0x4E454E31; private static final byte INSTANCE_ID[] = new byte[] { 'N', 'E', 'O', 'K', 'E', 'R', 'N', 'L', '\0' }; // INSTANCE_ID + millitime(long) + seqnumber(long) private final byte globalId[]; // branchId assumes Xid.MAXBQUALSIZE >= 4 private final byte branchId[]; /** * Generates a new global id byte[] for use as one part that makes up a Xid. A global id is made up of: * - INSTANCE_ID: fixed number of bytes and content * - 8b: current time millis * - 8b: sequence id, incremented for each new generated global id * - 4b: local id, an id fixed for and local to the instance generating this global id * * resourceId.length = 4, unique for each XAResource * @param localId * @return */ public static byte[] getNewGlobalId( Seed seed, int localId ) { byte globalId[] = Arrays.copyOf( INSTANCE_ID, INSTANCE_ID.length + 20 ); wrap( globalId, INSTANCE_ID.length, 20 ) .putLong( seed.nextRandomLong() ) .putLong( seed.nextSequenceId() ) .putInt( localId ); return globalId; } static boolean isThisTm( byte globalId[] ) { if ( globalId.length < INSTANCE_ID.length ) { return false; } for ( int i = 0; i < INSTANCE_ID.length; i++ ) { if ( globalId[i] != INSTANCE_ID[i] ) { return false; } } return true; } public XidImpl( byte globalId[], byte resourceId[] ) { if ( globalId.length > Xid.MAXGTRIDSIZE ) { throw new IllegalArgumentException( "GlobalId length to long: " + globalId.length + ". Max is " + Xid.MAXGTRIDSIZE ); } if ( resourceId.length > Xid.MAXBQUALSIZE ) { throw new IllegalArgumentException( "BranchId (resource id) to long, " + resourceId.length ); } this.globalId = globalId; this.branchId = resourceId; } @Override public byte[] getGlobalTransactionId() { return globalId.clone(); } @Override public byte[] getBranchQualifier() { return branchId.clone(); } @Override public int getFormatId() { return FORMAT_ID; } @Override public boolean equals( Object o ) { if ( !(o instanceof Xid) ) { return false; } return Arrays.equals( globalId, ((Xid) o).getGlobalTransactionId() ) && Arrays.equals( branchId, ((Xid) o).getBranchQualifier() ); } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { int calcHash = 0; for ( int i = 0; i < 3 && i < globalId.length; i++ ) { calcHash += globalId[globalId.length - i - 1] << i * 8; } if ( branchId.length > 0 ) { calcHash += branchId[0] << 3 * 8; } hashCode = 3217 * calcHash; } return hashCode; } @Override public String toString() { StringBuffer buf = new StringBuffer( "GlobalId[" ); int baseLength = INSTANCE_ID.length + 8 + 8; if ( globalId.length == baseLength || globalId.length == baseLength+4 ) { for ( int i = 0; i < INSTANCE_ID.length - 1; i++ ) { buf.append( (char) globalId[i] ); } ByteBuffer byteBuf = ByteBuffer.wrap( globalId ); byteBuf.position( INSTANCE_ID.length ); long time = byteBuf.getLong(); long sequence = byteBuf.getLong(); buf.append( '|' ); buf.append( time ); buf.append( '|' ); buf.append( sequence ); /* MP 2013-11-27: 4b added to the globalId, consisting of the serverId value. This if-statement * keeps things backwards compatible and nice. */ if ( byteBuf.hasRemaining() ) { buf.append( '|' ).append( byteBuf.getInt() ); } } else { buf.append( "UNKNOWN_ID" ); } buf.append( "], BranchId[ " ); for ( int i = 0; i < branchId.length; i++ ) { buf.append( branchId[i] + " " ); } buf.append( "]" ); return buf.toString(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XidImpl.java
180
private static class Resource { private byte resourceId[] = null; Resource( byte resourceId[] ) { if ( resourceId == null || resourceId.length == 0 ) { throw new IllegalArgumentException( "Illegal resourceId" ); } this.resourceId = resourceId; } byte[] getResourceId() { return resourceId; } @Override public boolean equals( Object o ) { if ( !(o instanceof Resource) ) { return false; } byte otherResourceId[] = ((Resource) o).getResourceId(); if ( resourceId.length != otherResourceId.length ) { return false; } for ( int i = 0; i < resourceId.length; i++ ) { if ( resourceId[i] != otherResourceId[i] ) { return false; } } return true; } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { int calcHash = 0; for ( int i = 0; i < resourceId.length; i++ ) { calcHash += resourceId[i] << i * 8; } hashCode = 3217 * calcHash; } return hashCode; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
181
private static class NonCompletedTransaction implements Comparable<NonCompletedTransaction> { private int seqNr = -1; private List<Xid> xidList = null; NonCompletedTransaction( int seqNr, List<Xid> xidList ) { this.seqNr = seqNr; this.xidList = xidList; } int getSequenceNumber() { return seqNr; } Xid[] getXids() { return xidList.toArray( new Xid[xidList.size()] ); } @Override public String toString() { return "NonCompletedTx[" + seqNr + "," + xidList + "]"; } @Override public int compareTo( NonCompletedTransaction nct ) { return getSequenceNumber() - nct.getSequenceNumber(); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
182
{ @Override public void notify( DataSourceRegistrationListener listener ) { listener.unregisteredDataSource( dataSource ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
183
{ @Override public void notify( DataSourceRegistrationListener listener ) { listener.registeredDataSource( dataSource ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
184
private static class PlaceboTransaction implements Transaction { @Override public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException { } @Override public boolean delistResource( XAResource xaRes, int flag ) throws IllegalStateException, SystemException { return true; } @Override public boolean enlistResource( XAResource xaRes ) throws IllegalStateException, RollbackException, SystemException { return true; } @Override public int getStatus() throws SystemException { return Status.STATUS_ACTIVE; } @Override public void registerSynchronization( Synchronization synch ) throws IllegalStateException, RollbackException, SystemException { } @Override public void rollback() throws IllegalStateException, SystemException { } @Override public void setRollbackOnly() throws IllegalStateException, SystemException { } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_PlaceboTm.java
185
{ @Override public boolean accept( XaDataSource item ) { return item.getName().equals( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); } } );
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
186
{ @Override public void registeredDataSource( XaDataSource ds ) { if ( filter.accept( ds ) ) { listener.registeredDataSource( ds ); } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( filter.accept( ds ) ) { listener.unregisteredDataSource( ds ); } } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
187
public class XaDataSourceManager implements Lifecycle { // key = data source name, value = data source private final Map<String, XaDataSource> dataSources = new HashMap<String, XaDataSource>(); // key = branchId, value = data source private final Map<String, XaDataSource> branchIdMapping = new HashMap<String, XaDataSource>(); // key = data source name, value = branchId private final Map<String, byte[]> sourceIdMapping = new HashMap<String, byte[]>(); private Iterable<DataSourceRegistrationListener> dsRegistrationListeners = Listeners.newListeners(); private LifeSupport life = new LifeSupport(); private final StringLogger msgLog; private boolean isShutdown = false; public XaDataSourceManager( StringLogger msgLog ) { this.msgLog = msgLog; } public static DataSourceRegistrationListener filterListener( final DataSourceRegistrationListener listener, final Predicate<XaDataSource> filter ) { return new DataSourceRegistrationListener() { @Override public void registeredDataSource( XaDataSource ds ) { if ( filter.accept( ds ) ) { listener.registeredDataSource( ds ); } } @Override public void unregisteredDataSource( XaDataSource ds ) { if ( filter.accept( ds ) ) { listener.unregisteredDataSource( ds ); } } }; } public static DataSourceRegistrationListener neoStoreListener( DataSourceRegistrationListener listener ) { return filterListener( listener, new Predicate<XaDataSource>() { @Override public boolean accept( XaDataSource item ) { return item.getName().equals( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); } } ); } public void addDataSourceRegistrationListener( DataSourceRegistrationListener listener ) { if ( life.getStatus().equals( LifecycleStatus.STARTED ) ) { try { for ( XaDataSource ds : dataSources.values() ) { listener.registeredDataSource( ds ); } } catch ( Throwable t ) { msgLog.logMessage( "Failed when notifying registering listener", t ); } } dsRegistrationListeners = Listeners.addListener( listener, dsRegistrationListeners ); } public void removeDataSourceRegistrationListener( DataSourceRegistrationListener dataSourceRegistrationListener ) { dsRegistrationListeners = Listeners.removeListener( dataSourceRegistrationListener, dsRegistrationListeners ); } @Override public void init() throws Throwable { if (dsRegistrationListeners == null) { dsRegistrationListeners = Listeners.newListeners(); } } @Override public void start() throws Throwable { life = new LifeSupport(); for ( XaDataSource ds : dataSources.values() ) { life.add( ds ); } life.start(); for ( DataSourceRegistrationListener listener : dsRegistrationListeners ) { try { for ( XaDataSource ds : dataSources.values() ) { listener.registeredDataSource( ds ); } } catch ( Throwable t ) { msgLog.logMessage( "Failed when notifying registering listener", t ); } } } @Override public void stop() throws Throwable { life.stop(); } @Override public void shutdown() throws Throwable { dsRegistrationListeners = null; life.shutdown(); dataSources.clear(); branchIdMapping.clear(); sourceIdMapping.clear(); isShutdown = true; } /** * Returns the {@link org.neo4j.kernel.impl.transaction.xaframework.XaDataSource} * registered as <CODE>name</CODE>. If no data source is registered with * that name <CODE>null</CODE> is returned. * * @param name the name of the data source */ public XaDataSource getXaDataSource( String name ) { if ( isShutdown ) { throw new IllegalStateException( "XaDataSourceManager has been shut down." ); } return dataSources.get( name ); } /** * Used to access the Neo DataSource. This should be replaced with * DataSource registration listeners instead, since this DataSource is not * always guaranteed to return anything (in HA case). */ @Deprecated public NeoStoreXaDataSource getNeoStoreDataSource() { return (NeoStoreXaDataSource) getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME ); } /** * Public for testing purpose. Do not use. */ public synchronized void registerDataSource( final XaDataSource dataSource ) { dataSources.put( dataSource.getName(), dataSource ); branchIdMapping.put( UTF8.decode( dataSource.getBranchId() ), dataSource ); sourceIdMapping.put( dataSource.getName(), dataSource.getBranchId() ); life.add( dataSource ); if ( life.getStatus().equals( LifecycleStatus.STARTED ) ) { Listeners.notifyListeners( dsRegistrationListeners, new Listeners.Notification<DataSourceRegistrationListener>() { @Override public void notify( DataSourceRegistrationListener listener ) { listener.registeredDataSource( dataSource ); } } ); } } /** * Public for testing purpose. Do not use. */ public synchronized void unregisterDataSource( String name ) { final XaDataSource dataSource = dataSources.get( name ); if ( dataSource == null ) { return; } dataSources.remove( name ); branchIdMapping.remove( UTF8.decode( dataSource.getBranchId() ) ); sourceIdMapping.remove( name ); Listeners.notifyListeners( dsRegistrationListeners, new Listeners.Notification<DataSourceRegistrationListener>() { @Override public void notify( DataSourceRegistrationListener listener ) { listener.unregisteredDataSource( dataSource ); } } ); life.remove( dataSource ); // No need for shutdown, removing does that } synchronized byte[] getBranchId( XAResource xaResource ) { if ( xaResource instanceof XaResource ) { byte branchId[] = ((XaResource) xaResource).getBranchId(); if ( branchId != null ) { return branchId; } } for ( Map.Entry<String, XaDataSource> entry : dataSources.entrySet() ) { 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 + "]" ); } private XaDataSource getDataSource( byte branchId[] ) { XaDataSource dataSource = branchIdMapping.get( UTF8.decode( branchId ) ); if ( dataSource == null ) { throw new TransactionFailureException( "No mapping found for branchId[0x" + UTF8.decode( branchId ) + "]" ); } return dataSource; } // not thread safe public Collection<XaDataSource> getAllRegisteredDataSources() { return dataSources.values(); } /** * Recover all datasources */ public void recover( Iterator<List<TxLog.Record>> knownDanglingRecordList ) { // contains NonCompletedTransaction that needs to be committed List<NonCompletedTransaction> commitList = new ArrayList<NonCompletedTransaction>(); // contains Xids that should be rolledback final List<Xid> rollbackList = new LinkedList<Xid>(); // key = Resource(branchId) value = XAResource final Map<Resource, XaDataSource> resourceMap = new HashMap<Resource, XaDataSource>(); buildRecoveryInfo( commitList, rollbackList, resourceMap, knownDanglingRecordList ); // invoke recover on all xa resources found final List<Xid> recoveredXidsList = new LinkedList<Xid>(); try { for ( XaDataSource xaDataSource : dataSources.values() ) { XAResource xaRes = xaDataSource.getXaConnection().getXaResource(); Xid xids[] = xaRes.recover( XAResource.TMNOFLAGS ); for ( Xid xid : xids ) { if ( XidImpl.isThisTm( xid.getGlobalTransactionId() ) ) { // linear search if ( rollbackList.contains( xid ) ) { msgLog.logMessage( "TM: Found pre commit " + xid + " rolling back ... ", true ); rollbackList.remove( xid ); xaRes.rollback( xid ); } else { Resource resource = new Resource( xid.getBranchQualifier() ); if ( !resourceMap.containsKey( resource ) ) { resourceMap.put( resource, xaDataSource ); } recoveredXidsList.add( xid ); } } else { msgLog.warn( "Unknown xid: " + xid ); } } } // sort the commit list after sequence number Collections.sort( commitList ); // go through and commit for ( NonCompletedTransaction nct : commitList ) { int seq = nct.getSequenceNumber(); Xid xids[] = nct.getXids(); msgLog.debug( "Marked as commit tx-seq[" + seq + "] branch length: " + xids.length ); for ( Xid xid : xids ) { if ( !recoveredXidsList.contains( xid ) ) { msgLog.debug( "Tx-seq[" + seq + "][" + xid + "] not found in recovered xid list, " + "assuming already committed" ); continue; } recoveredXidsList.remove( xid ); Resource resource = new Resource( xid.getBranchQualifier() ); if ( !resourceMap.containsKey( resource ) ) { final TransactionFailureException ex = new TransactionFailureException( "Couldn't find XAResource for " + xid ); throw logAndReturn( "TM: recovery error", ex ); } msgLog.debug( "TM: Committing tx " + xid ); resourceMap.get( resource ).getXaConnection().getXaResource().commit( xid, false ); } } // rollback the rest for ( Xid xid : recoveredXidsList ) { Resource resource = new Resource( xid.getBranchQualifier() ); if ( !resourceMap.containsKey( resource ) ) { final TransactionFailureException ex = new TransactionFailureException( "Couldn't find XAResource for " + xid ); throw logAndReturn( "TM: recovery error", ex ); } msgLog.debug( "TM: no match found for " + xid + " removing" ); resourceMap.get( resource ).getXaConnection().getXaResource().rollback( xid ); } if ( rollbackList.size() > 0 ) { msgLog.debug( "TxLog contained unresolved " + "xids that needed rollback. They couldn't be matched to " + "any of the XAResources recover list. " + "Assuming " + rollbackList.size() + " transactions already rolled back." ); } // Rotate the logs of the participated data sources, making sure that // done-records are written so that even if the tm log gets truncated, // which it will be after this recovery, that transaction information // doesn't get lost. for ( XaDataSource participant : MapUtil.reverse( resourceMap ).keySet() ) { participant.recoveryCompleted(); participant.rotateLogicalLog(); } // For all data source that didn't actively participate in recovery // notify them that recovery process has completed. for ( XaDataSource ds : allOtherDataSources( resourceMap.values() ) ) { ds.recoveryCompleted(); } } catch ( IOException | XAException e ) { throw logAndReturn( "TM: recovery failed", new TransactionFailureException( "Recovery failed.", e ) ); } } private Collection<XaDataSource> allOtherDataSources( Collection<XaDataSource> recoveredDataSources ) { Collection<XaDataSource> dataSources = new HashSet<>( this.dataSources.values() ); dataSources.removeAll( recoveredDataSources ); return dataSources; } private void buildRecoveryInfo( List<NonCompletedTransaction> commitList, List<Xid> rollbackList, Map<Resource, XaDataSource> 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, getDataSource( resource.getResourceId() ) ); } xids.add( new XidImpl( startRecord.getGlobalId(), resource.getResourceId() ) ); } if ( markedCommit != -1 ) // this xid needs to be committed { commitList.add( new NonCompletedTransaction( markedCommit, xids ) ); } else { rollbackList.addAll( xids ); } } } private <E extends Exception> E logAndReturn( String msg, E exception ) { try { msgLog.logMessage( msg, exception, true ); return exception; } catch ( Throwable t ) { return exception; } } public void rotateLogicalLogs() { for ( XaDataSource dataSource : dataSources.values() ) { try { dataSource.rotateLogicalLog(); } catch ( IOException e ) { msgLog.logMessage( "Couldn't rotate logical log for " + dataSource.getName(), e ); } } } private static class NonCompletedTransaction implements Comparable<NonCompletedTransaction> { private int seqNr = -1; private List<Xid> xidList = null; NonCompletedTransaction( int seqNr, List<Xid> xidList ) { this.seqNr = seqNr; this.xidList = xidList; } int getSequenceNumber() { return seqNr; } Xid[] getXids() { return xidList.toArray( new Xid[xidList.size()] ); } @Override public String toString() { return "NonCompletedTx[" + seqNr + "," + xidList + "]"; } @Override public int compareTo( NonCompletedTransaction nct ) { return getSequenceNumber() - nct.getSequenceNumber(); } } private static class Resource { private byte resourceId[] = null; Resource( byte resourceId[] ) { if ( resourceId == null || resourceId.length == 0 ) { throw new IllegalArgumentException( "Illegal resourceId" ); } this.resourceId = resourceId; } byte[] getResourceId() { return resourceId; } @Override public boolean equals( Object o ) { if ( !(o instanceof Resource) ) { return false; } byte otherResourceId[] = ((Resource) o).getResourceId(); if ( resourceId.length != otherResourceId.length ) { return false; } for ( int i = 0; i < resourceId.length; i++ ) { if ( resourceId[i] != otherResourceId[i] ) { return false; } } return true; } private volatile int hashCode = 0; @Override public int hashCode() { if ( hashCode == 0 ) { int calcHash = 0; for ( int i = 0; i < resourceId.length; i++ ) { calcHash += resourceId[i] << i * 8; } hashCode = 3217 * calcHash; } return hashCode; } } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_XaDataSourceManager.java
188
public class UserTransactionImpl extends BaseSpringTransactionImpl implements UserTransaction { public UserTransactionImpl( GraphDatabaseAPI neo4j) { super( neo4j ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_UserTransactionImpl.java
189
FakeXAResource externalResource = new FakeXAResource("BananaStorageFacility"){ @Override public void rollback( Xid xid ) { super.rollback(xid); externalResourceWasRolledBack.set( true ); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_UseJOTMAsTxManagerIT.java
190
{ @Override public Object beforeCommit( TransactionData data ) throws Exception { throw new RuntimeException("LURING!"); } @Override public void afterCommit( TransactionData data, Object state ) { } @Override public void afterRollback( TransactionData data, Object state ) { } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_UseJOTMAsTxManagerIT.java
191
public class UseJOTMAsTxManagerIT { private final TransactionEventHandler<Object> failsBeforeCommitTransactionHandler = new TransactionEventHandler<Object>() { @Override public Object beforeCommit( TransactionData data ) throws Exception { throw new RuntimeException("LURING!"); } @Override public void afterCommit( TransactionData data, Object state ) { } @Override public void afterRollback( TransactionData data, Object state ) { } }; // TODO: This is meant to be a documented test case. /** * To use JOTM, you need to add both the jotm-core as a dependency, but also * the j2ee spec: * * <dependency> <groupId>geronimo-spec</groupId> * <artifactId>geronimo-spec-j2ee</artifactId> <version>1.4-rc4</version> * </dependency> * * Then create a transaction manager service that Neo4j can consume, see * {@link JOTMTransactionManager}, and a provider of that service that Neo4j * can use to create the service provider, * {@link JOTMTransactionManager$Provider}. * * The provider should be listed in META-INF/services/ * * With that in place, tell neo4j to use JOTM by passing in the appropriate * config setting, see below. */ @Test public void shouldStartWithJOTM() { Map<String, String> config = new HashMap<>(); config.put( GraphDatabaseSettings.tx_manager_impl.name(), JOTMTransactionManager.NAME ); GraphDatabaseAPI db = null; try { db = new ImpermanentGraphDatabase( config ); assertThat( txManager( db ), is( instanceOf( JOTMTransactionManager.class ) ) ); Transaction tx = db.beginTx(); Node node = null; try { node = db.createNode(); tx.success(); } finally { tx.finish(); } tx = db.beginTx(); try { assertThat( db.getNodeById( node.getId() ), is( node ) ); } finally { tx.finish(); } } finally { if ( db != null ) { db.shutdown(); } } } @Test public void shouldHandleFailingCommitWithExternalDataSourceGracefully() throws Exception { Map<String, String> config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.tx_manager_impl.name(), JOTMTransactionManager.NAME ); GraphDatabaseAPI db = null; final AtomicBoolean externalResourceWasRolledBack = new AtomicBoolean(false); try { db = new ImpermanentGraphDatabase( config ); // Fail onBeforeCommit db.registerTransactionEventHandler( failsBeforeCommitTransactionHandler ); Transaction outerTx = db.beginTx(); // Add an external data source FakeXAResource externalResource = new FakeXAResource("BananaStorageFacility"){ @Override public void rollback( Xid xid ) { super.rollback(xid); externalResourceWasRolledBack.set( true ); } }; txManager( db ).getTransaction().enlistResource( externalResource ); try { db.createNode(); Transaction innerTx = db.beginTx(); try { db.createNode(); innerTx.success(); } finally { innerTx.finish(); } outerTx.success(); } finally { outerTx.finish(); } fail("Transaction should have failed."); } catch(TransactionFailureException e) { // ok! } finally { if ( db != null ) { db.shutdown(); } } // Phew.. assertThat( externalResourceWasRolledBack.get(), is( true ) ); } @Test public void shouldSupportRollbacks() throws Exception { Map<String, String> config = new HashMap<>(); config.put( GraphDatabaseSettings.tx_manager_impl.name(), JOTMTransactionManager.NAME ); GraphDatabaseAPI neo4j = null; try { neo4j = new ImpermanentGraphDatabase( config ); txManager( neo4j ).begin(); neo4j.createNode(); txManager( neo4j ).rollback(); } finally { if ( neo4j != null ) { neo4j.shutdown(); } } } @Ignore( "When going through Jotm object and UserTransaction we've got no control over begin() which creates the TransactionState object" ) @Test public void shouldSupportRollbacksFromUserTransaction() throws Exception { Map<String, String> config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.tx_manager_impl.name(), JOTMTransactionManager.NAME ); GraphDatabaseAPI neo4j = null; try { neo4j = new ImpermanentGraphDatabase( config ); Jotm jotm = ((JOTMTransactionManager) txManager( neo4j )).getJotmTxManager(); UserTransaction userTx = jotm.getUserTransaction(); userTx.begin(); neo4j.createNode(); userTx.rollback(); } finally { if ( neo4j != null ) { neo4j.shutdown(); } } } private TransactionManager txManager( GraphDatabaseAPI db ) { return db.getDependencyResolver().resolveDependency( TransactionManager.class ); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_UseJOTMAsTxManagerIT.java
192
{ private final AtomicInteger id = new AtomicInteger(); @Override public byte[] newInstance() { return ("test" + id.incrementAndGet()).getBytes(); } };
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TxManagerTest.java
193
public class TxManagerTest { @Test public void settingTmNotOkShouldAttachCauseToSubsequentErrors() throws Exception { // Given XaDataSourceManager mockXaManager = mock( XaDataSourceManager.class ); File txLogDir = TargetDirectory.forTest( fs.get(), getClass() ).cleanDirectory( "log" ); KernelHealth kernelHealth = new KernelHealth( panicGenerator, logging ); TxManager txm = new TxManager( txLogDir, mockXaManager, DEV_NULL, fs.get(), null, null, kernelHealth, monitors ); txm.doRecovery(); // Make the txm move to an ok state String msg = "These kinds of throwables, breaking our transaction managers, are why we can't have nice things."; // When txm.setTmNotOk( new Throwable( msg ) ); // Then try { txm.begin(); fail( "Should have thrown SystemException." ); } catch ( SystemException topLevelException ) { assertThat( "TM should forward a cause.", topLevelException.getCause(), is( Throwable.class ) ); assertThat( "Cause should be the original cause", topLevelException.getCause().getMessage(), is( msg ) ); } } @Test public void shouldNotSetTmNotOKForFailureInCommitted() throws Throwable { /* * I.e. when the commit has been done and the TxIdGenerator#committed method is called and fails, * it should not put the TM in not OK state. However that exception should still be propagated to * the user. */ // GIVEN File directory = TargetDirectory.forTest( fs.get(), getClass() ).cleanDirectory( "dir" ); TransactionStateFactory stateFactory = new TransactionStateFactory( logging ); TxIdGenerator txIdGenerator = mock( TxIdGenerator.class ); doThrow( RuntimeException.class ).when( txIdGenerator ) .committed( any( XaDataSource.class ), anyInt(), anyLong(), any( Integer.class ) ); stateFactory.setDependencies( mock( LockManager.class ), mock( NodeManager.class ), mock( RemoteTxHook.class ), txIdGenerator ); XaDataSourceManager xaDataSourceManager = life.add( new XaDataSourceManager( DEV_NULL ) ); KernelHealth kernelHealth = new KernelHealth( panicGenerator, logging ); AbstractTransactionManager txManager = life.add( new TxManager( directory, xaDataSourceManager, logging.getMessagesLog( TxManager.class ), fs.get(), stateFactory, xidFactory, kernelHealth, monitors ) ); XaFactory xaFactory = new XaFactory( new Config(), txIdGenerator, txManager, fs.get(), monitors, logging, ALWAYS_VALID, NO_PRUNING, kernelHealth ); DummyXaDataSource dataSource = new DummyXaDataSource( UTF8.encode( "0xDDDDDE" ), "dummy", xaFactory, stateFactory, new File( directory, "log" ) ); xaDataSourceManager.registerDataSource( dataSource ); life.start(); txManager.doRecovery(); // WHEN txManager.begin(); dataSource.getXaConnection().enlistResource( txManager.getTransaction() ); txManager.commit(); // THEN tx manager should still work here assertThat( logging.toString(), containsString( "Commit notification failed" ) ); doNothing().when( txIdGenerator ) .committed( any( XaDataSource.class ), anyInt(), anyLong(), any( Integer.class ) ); txManager.begin(); txManager.rollback(); // and of course kernel should be healthy kernelHealth.assertHealthy( AssertionError.class ); } @Rule public EphemeralFileSystemRule fs = new EphemeralFileSystemRule(); private final KernelPanicEventGenerator panicGenerator = new KernelPanicEventGenerator( new KernelEventHandlers(StringLogger.DEV_NULL) ); private final Monitors monitors = new Monitors(); private final Logging logging = new BufferingLogging(); private final Factory<byte[]> xidFactory = new Factory<byte[]>() { private final AtomicInteger id = new AtomicInteger(); @Override public byte[] newInstance() { return ("test" + id.incrementAndGet()).getBytes(); } }; private final LifeSupport life = new LifeSupport(); @After public void after() { life.shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_transaction_TxManagerTest.java
194
forced { @Override public void force( LogBuffer buffer ) throws IOException { buffer.force(); } },
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_ForceMode.java
195
unforced { @Override public void force( LogBuffer buffer ) throws IOException { buffer.writeOut(); } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_ForceMode.java
196
InjectedTransactionValidator ALLOW_ALL = new InjectedTransactionValidator(){ @Override public void assertInjectionAllowed( long lastCommittedTxWhenTransactionStarted ) throws XAException { // Always ok. } };
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_InjectedTransactionValidator.java
197
public static class OnePhaseCommit extends Commit { OnePhaseCommit( int identifier, long txId, long timeWritten ) { super( identifier, txId, timeWritten, "1PC" ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogEntry.java
198
public static class TxPosition { final long version; final int masterId; final int identifier; final long position; final long checksum; public TxPosition( long version, int masterId, int identifier, long position, long checksum ) { this.version = version; this.masterId = masterId; this.identifier = identifier; this.position = position; this.checksum = checksum; } public boolean earlierThan( TxPosition other ) { if ( version < other.version ) return true; if ( version > other.version ) return false; return position < other.position; } @Override public String toString() { return "TxPosition[version:" + version + ", pos:" + position + "]"; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogExtractor.java
199
public static class LogPositionCache { private final LruCache<Long, TxPosition> txStartPositionCache = new LruCache<Long, TxPosition>( "Tx start position cache", 10000 ); private final LruCache<Long /*log version*/, Long /*last committed tx*/> logHeaderCache = new LruCache<Long, Long>( "Log header cache", 1000 ); public void clear() { logHeaderCache.clear(); txStartPositionCache.clear(); } public TxPosition positionOf( long txId ) { return txStartPositionCache.get( txId ); } public void putHeader( long logVersion, long previousLogLastCommittedTx ) { logHeaderCache.put( logVersion, previousLogLastCommittedTx ); } public Long getHeader( long logVersion ) { return logHeaderCache.get( logVersion ); } public void putStartPosition( long txId, TxPosition position ) { txStartPositionCache.put( txId, position ); } public TxPosition getStartPosition( long txId ) { return txStartPositionCache.get( txId ); } public synchronized TxPosition cacheStartPosition( long txId, LogEntry.Start startEntry, long logVersion ) { if ( startEntry.getStartPosition() == -1 ) { throw new RuntimeException( "StartEntry.position is " + startEntry.getStartPosition() ); } TxPosition result = new TxPosition( logVersion, startEntry.getMasterId(), startEntry.getIdentifier(), startEntry.getStartPosition(), startEntry.getChecksum() ); putStartPosition( txId, result ); return result; } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_transaction_xaframework_LogExtractor.java