use of org.neo4j.kernel.impl.transaction.TransactionStats in project neo4j by neo4j.
the class AppsIT method canTerminateAnActiveCommand.
@Test
public void canTerminateAnActiveCommand() throws Exception {
TransactionStats txStats = db.getDependencyResolver().resolveDependency(TransactionStats.class);
assertEquals(0, txStats.getNumberOfActiveTransactions());
Serializable clientId = shellClient.getId();
Future<?> result = ForkJoinPool.commonPool().submit(() -> {
try {
while (txStats.getNumberOfActiveTransactions() == 0) {
Thread.sleep(10);
}
assertEquals(1, txStats.getNumberOfActiveTransactions());
shellServer.terminate(clientId);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
executeCommandExpectingException("FOREACH(i IN range(0, " + Integer.MAX_VALUE + ") | CREATE ());", "has been terminated");
assertNull(result.get());
}
use of org.neo4j.kernel.impl.transaction.TransactionStats in project neo4j by neo4j.
the class SwitchToSlaveCopyThenBranchTest method newSwitchToSlaveSpy.
@SuppressWarnings("unchecked")
private SwitchToSlaveCopyThenBranch newSwitchToSlaveSpy(PageCache pageCacheMock, StoreCopyClient storeCopyClient) throws IOException {
ClusterMembers clusterMembers = mock(ClusterMembers.class);
ClusterMember master = mock(ClusterMember.class);
when(master.getStoreId()).thenReturn(storeId);
when(master.getHARole()).thenReturn(HighAvailabilityModeSwitcher.MASTER);
when(master.hasRole(eq(HighAvailabilityModeSwitcher.MASTER))).thenReturn(true);
when(master.getInstanceId()).thenReturn(new InstanceId(1));
when(clusterMembers.getMembers()).thenReturn(asList(master));
Dependencies resolver = new Dependencies();
resolver.satisfyDependencies(requestContextFactory, clusterMembers, mock(TransactionObligationFulfiller.class), mock(OnlineBackupKernelExtension.class), mock(IndexConfigStore.class), mock(TransactionCommittingResponseUnpacker.class), mock(DataSourceManager.class), mock(StoreLockerLifecycleAdapter.class), mock(FileSystemWatcherService.class));
NeoStoreDataSource dataSource = mock(NeoStoreDataSource.class);
when(dataSource.getStoreId()).thenReturn(storeId);
TransactionStats transactionCounters = mock(TransactionStats.class);
when(transactionCounters.getNumberOfActiveTransactions()).thenReturn(0L);
Response<HandshakeResult> response = mock(Response.class);
when(response.response()).thenReturn(new HandshakeResult(42, 2));
when(masterClient.handshake(anyLong(), any(StoreId.class))).thenReturn(response);
when(masterClient.getProtocolVersion()).thenReturn(MasterClient.CURRENT);
TransactionIdStore transactionIdStoreMock = mock(TransactionIdStore.class);
// note that the checksum (the second member of the array) is the same as the one in the handshake mock above
when(transactionIdStoreMock.getLastCommittedTransaction()).thenReturn(new TransactionId(42, 42, 42));
MasterClientResolver masterClientResolver = mock(MasterClientResolver.class);
when(masterClientResolver.instantiate(anyString(), anyInt(), anyString(), any(Monitors.class), any(StoreId.class), any(LifeSupport.class))).thenReturn(masterClient);
return spy(new SwitchToSlaveCopyThenBranch(new File(""), NullLogService.getInstance(), configMock(), resolver, mock(HaIdGeneratorFactory.class), mock(DelegateInvocationHandler.class), mock(ClusterMemberAvailability.class), requestContextFactory, pullerFactory, masterClientResolver, mock(SwitchToSlave.Monitor.class), storeCopyClient, Suppliers.singleton(dataSource), Suppliers.singleton(transactionIdStoreMock), slave -> {
SlaveServer server = mock(SlaveServer.class);
InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved("localhost", 42);
when(server.getSocketAddress()).thenReturn(inetSocketAddress);
return server;
}, updatePuller, pageCacheMock, mock(Monitors.class), transactionCounters));
}
use of org.neo4j.kernel.impl.transaction.TransactionStats in project neo4j by neo4j.
the class HighAvailabilityMemberStateMachineTest method whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient.
@Test
public void whenHAModeSwitcherSwitchesToSlaveTheOtherModeSwitcherDoNotGetTheOldMasterClient() throws Throwable {
InstanceId me = new InstanceId(1);
StoreId storeId = newStoreIdForCurrentVersion();
HighAvailabilityMemberContext context = mock(HighAvailabilityMemberContext.class);
when(context.getMyId()).thenReturn(me);
AvailabilityGuard guard = mock(AvailabilityGuard.class);
ObservedClusterMembers members = mock(ObservedClusterMembers.class);
ClusterMember masterMember = mock(ClusterMember.class);
when(masterMember.getHARole()).thenReturn("master");
when(masterMember.hasRole("master")).thenReturn(true);
when(masterMember.getInstanceId()).thenReturn(new InstanceId(2));
when(masterMember.getStoreId()).thenReturn(storeId);
ClusterMember self = new ClusterMember(me);
when(members.getMembers()).thenReturn(Arrays.asList(self, masterMember));
when(members.getCurrentMember()).thenReturn(self);
DependencyResolver dependencyResolver = mock(DependencyResolver.class);
FileSystemAbstraction fs = mock(FileSystemAbstraction.class);
when(fs.fileExists(any(File.class))).thenReturn(true);
when(dependencyResolver.resolveDependency(FileSystemAbstraction.class)).thenReturn(fs);
when(dependencyResolver.resolveDependency(Monitors.class)).thenReturn(new Monitors());
NeoStoreDataSource dataSource = mock(NeoStoreDataSource.class);
when(dataSource.getDependencyResolver()).thenReturn(dependencyResolver);
when(dataSource.getStoreId()).thenReturn(storeId);
when(dependencyResolver.resolveDependency(NeoStoreDataSource.class)).thenReturn(dataSource);
when(dependencyResolver.resolveDependency(TransactionIdStore.class)).thenReturn(new DeadSimpleTransactionIdStore());
when(dependencyResolver.resolveDependency(ObservedClusterMembers.class)).thenReturn(members);
UpdatePuller updatePuller = mock(UpdatePuller.class);
when(updatePuller.tryPullUpdates()).thenReturn(true);
when(dependencyResolver.resolveDependency(UpdatePuller.class)).thenReturn(updatePuller);
ClusterMemberAvailability clusterMemberAvailability = mock(ClusterMemberAvailability.class);
final TriggerableClusterMemberEvents events = new TriggerableClusterMemberEvents();
Election election = mock(Election.class);
HighAvailabilityMemberStateMachine stateMachine = new HighAvailabilityMemberStateMachine(context, guard, members, events, election, NullLogProvider.getInstance());
ClusterMembers clusterMembers = new ClusterMembers(members, stateMachine);
when(dependencyResolver.resolveDependency(ClusterMembers.class)).thenReturn(clusterMembers);
stateMachine.init();
stateMachine.start();
final DelegateInvocationHandler<Master> handler = new DelegateInvocationHandler<>(Master.class);
MasterClientResolver masterClientResolver = mock(MasterClientResolver.class);
MasterClient masterClient = mock(MasterClient.class);
when(masterClient.getProtocolVersion()).thenReturn(MasterClient214.PROTOCOL_VERSION);
when(masterClient.handshake(anyLong(), any(StoreId.class))).thenReturn(new Response<HandshakeResult>(new HandshakeResult(0, 42), storeId, mock(ResourceReleaser.class)) {
@Override
public void accept(Handler handler) throws IOException {
}
@Override
public boolean hasTransactionsToBeApplied() {
return false;
}
});
when(masterClient.toString()).thenReturn("TheExpectedMasterClient!");
when(masterClientResolver.instantiate(anyString(), anyInt(), anyString(), any(Monitors.class), any(StoreId.class), any(LifeSupport.class))).thenReturn(masterClient);
final CountDownLatch latch = new CountDownLatch(2);
final AtomicBoolean switchedSuccessfully = new AtomicBoolean();
SwitchToSlave.Monitor monitor = new SwitchToSlave.Monitor() {
@Override
public void switchToSlaveCompleted(boolean wasSuccessful) {
switchedSuccessfully.set(wasSuccessful);
latch.countDown();
}
};
Config config = Config.embeddedDefaults(Collections.singletonMap(ClusterSettings.server_id.name(), me.toString()));
TransactionStats transactionCounters = mock(TransactionStats.class);
when(transactionCounters.getNumberOfActiveTransactions()).thenReturn(0L);
PageCache pageCacheMock = mock(PageCache.class);
PagedFile pagedFileMock = mock(PagedFile.class);
when(pagedFileMock.getLastPageId()).thenReturn(1L);
when(pageCacheMock.map(any(File.class), anyInt())).thenReturn(pagedFileMock);
TransactionIdStore transactionIdStoreMock = mock(TransactionIdStore.class);
when(transactionIdStoreMock.getLastCommittedTransaction()).thenReturn(new TransactionId(0, 0, 0));
SwitchToSlaveCopyThenBranch switchToSlave = new SwitchToSlaveCopyThenBranch(new File(""), NullLogService.getInstance(), mock(FileSystemAbstraction.class), config, dependencyResolver, mock(HaIdGeneratorFactory.class), handler, mock(ClusterMemberAvailability.class), mock(RequestContextFactory.class), mock(PullerFactory.class, RETURNS_MOCKS), Iterables.empty(), masterClientResolver, monitor, new StoreCopyClient.Monitor.Adapter(), Suppliers.singleton(dataSource), Suppliers.singleton(transactionIdStoreMock), slave -> {
SlaveServer mock = mock(SlaveServer.class);
when(mock.getSocketAddress()).thenReturn(new InetSocketAddress("localhost", 123));
return mock;
}, updatePuller, pageCacheMock, mock(Monitors.class), transactionCounters);
ComponentSwitcherContainer switcherContainer = new ComponentSwitcherContainer();
HighAvailabilityModeSwitcher haModeSwitcher = new HighAvailabilityModeSwitcher(switchToSlave, mock(SwitchToMaster.class), election, clusterMemberAvailability, mock(ClusterClient.class), storeSupplierMock(), me, switcherContainer, neoStoreDataSourceSupplierMock(), NullLogService.getInstance());
haModeSwitcher.init();
haModeSwitcher.start();
haModeSwitcher.listeningAt(URI.create("http://localhost:12345"));
stateMachine.addHighAvailabilityMemberListener(haModeSwitcher);
final AtomicReference<Master> ref = new AtomicReference<>(null);
//noinspection unchecked
AbstractComponentSwitcher<Object> otherModeSwitcher = new AbstractComponentSwitcher<Object>(mock(DelegateInvocationHandler.class)) {
@Override
protected Object getSlaveImpl() {
Master master = handler.cement();
ref.set(master);
latch.countDown();
return null;
}
@Override
protected Object getMasterImpl() {
return null;
}
};
switcherContainer.add(otherModeSwitcher);
// When
events.switchToSlave(me);
// Then
latch.await();
assertTrue("mode switch failed", switchedSuccessfully.get());
Master actual = ref.get();
// let's test the toString()s since there are too many wrappers of proxies
assertEquals(masterClient.toString(), actual.toString());
stateMachine.stop();
stateMachine.shutdown();
haModeSwitcher.stop();
haModeSwitcher.shutdown();
}
use of org.neo4j.kernel.impl.transaction.TransactionStats in project neo4j by neo4j.
the class TransactionIT method executing_single_statement_in_new_transaction_and_failing_to_read_the_output_should_interrupt.
@Test
public void executing_single_statement_in_new_transaction_and_failing_to_read_the_output_should_interrupt() throws Exception {
// given
long initialNodes = countNodes();
TransactionStats txMonitor = ((GraphDatabaseAPI) graphdb()).getDependencyResolver().resolveDependency(TransactionStats.class);
long initialTerminations = txMonitor.getNumberOfTerminatedTransactions();
// when sending a request and aborting in the middle of receiving the result
Socket socket = new Socket("localhost", 7474);
PrintStream out = new PrintStream(socket.getOutputStream());
String output = quotedJson("{ 'statements': [ { 'statement': 'WITH * UNWIND range(0, 9999) AS i CREATE (n {i: i}) RETURN n' } ] " + "}").get();
out.print("POST /db/data/transaction/commit HTTP/1.1\r\n");
out.print("Host: localhost:7474\r\n");
out.print("Content-type: application/json; charset=utf-8\r\n");
out.print("Content-length: " + output.getBytes().length + "\r\n");
out.print("\r\n");
out.print(output);
out.print("\r\n");
InputStream inputStream = socket.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int numRead = 0;
while (numRead < 300) {
numRead += reader.read(new char[300]);
}
socket.close();
try (Transaction ignored = graphdb().beginTx()) {
assertEquals(initialNodes, countNodes());
}
// then soon the transaction should have been terminated
long endTime = System.currentTimeMillis() + 5000;
long additionalTerminations = 0;
while (true) {
additionalTerminations = txMonitor.getNumberOfTerminatedTransactions() - initialTerminations;
if (additionalTerminations > 0 || System.currentTimeMillis() > endTime) {
break;
}
Thread.sleep(100);
}
assertEquals(1, additionalTerminations);
}
use of org.neo4j.kernel.impl.transaction.TransactionStats in project neo4j by neo4j.
the class SwitchToSlaveBranchThenCopyTest method newSwitchToSlaveSpy.
@SuppressWarnings("unchecked")
private SwitchToSlaveBranchThenCopy newSwitchToSlaveSpy(PageCache pageCacheMock, StoreCopyClient storeCopyClient) throws IOException {
ClusterMembers clusterMembers = mock(ClusterMembers.class);
ClusterMember master = mock(ClusterMember.class);
when(master.getStoreId()).thenReturn(storeId);
when(master.getHARole()).thenReturn(HighAvailabilityModeSwitcher.MASTER);
when(master.hasRole(eq(HighAvailabilityModeSwitcher.MASTER))).thenReturn(true);
when(master.getInstanceId()).thenReturn(new InstanceId(1));
when(clusterMembers.getMembers()).thenReturn(singletonList(master));
Dependencies resolver = new Dependencies();
resolver.satisfyDependencies(requestContextFactory, clusterMembers, mock(TransactionObligationFulfiller.class), mock(OnlineBackupKernelExtension.class), mock(IndexConfigStore.class), mock(TransactionCommittingResponseUnpacker.class), mock(DataSourceManager.class), mock(StoreLockerLifecycleAdapter.class), mock(FileSystemWatcherService.class));
NeoStoreDataSource dataSource = mock(NeoStoreDataSource.class);
when(dataSource.getStoreId()).thenReturn(storeId);
TransactionStats transactionCounters = mock(TransactionStats.class);
when(transactionCounters.getNumberOfActiveTransactions()).thenReturn(0L);
Response<HandshakeResult> response = mock(Response.class);
when(response.response()).thenReturn(new HandshakeResult(42, 2));
when(masterClient.handshake(anyLong(), any(StoreId.class))).thenReturn(response);
when(masterClient.getProtocolVersion()).thenReturn(MasterClient320.PROTOCOL_VERSION);
TransactionIdStore transactionIdStoreMock = mock(TransactionIdStore.class);
// note that the checksum (the second member of the array) is the same as the one in the handshake mock above
when(transactionIdStoreMock.getLastCommittedTransaction()).thenReturn(new TransactionId(42, 42, 42));
MasterClientResolver masterClientResolver = mock(MasterClientResolver.class);
when(masterClientResolver.instantiate(anyString(), anyInt(), anyString(), any(Monitors.class), any(StoreId.class), any(LifeSupport.class))).thenReturn(masterClient);
return spy(new SwitchToSlaveBranchThenCopy(new File(""), NullLogService.getInstance(), configMock(), resolver, mock(HaIdGeneratorFactory.class), mock(DelegateInvocationHandler.class), mock(ClusterMemberAvailability.class), requestContextFactory, pullerFactory, masterClientResolver, mock(SwitchToSlave.Monitor.class), storeCopyClient, Suppliers.singleton(dataSource), Suppliers.singleton(transactionIdStoreMock), slave -> {
SlaveServer server = mock(SlaveServer.class);
InetSocketAddress inetSocketAddress = InetSocketAddress.createUnresolved("localhost", 42);
when(server.getSocketAddress()).thenReturn(inetSocketAddress);
return server;
}, updatePuller, pageCacheMock, mock(Monitors.class), transactionCounters));
}
Aggregations