Search in sources :

Example 16 with PagedFile

use of org.neo4j.io.pagecache.PagedFile 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();
}
Also used : FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) MasterClient(org.neo4j.kernel.ha.com.slave.MasterClient) InetSocketAddress(java.net.InetSocketAddress) DeadSimpleTransactionIdStore(org.neo4j.kernel.impl.transaction.DeadSimpleTransactionIdStore) AvailabilityGuard(org.neo4j.kernel.AvailabilityGuard) ObservedClusterMembers(org.neo4j.kernel.ha.cluster.member.ObservedClusterMembers) RequestContextFactory(org.neo4j.kernel.ha.com.RequestContextFactory) PageCache(org.neo4j.io.pagecache.PageCache) HighAvailabilityModeSwitcher(org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcher) DeadSimpleTransactionIdStore(org.neo4j.kernel.impl.transaction.DeadSimpleTransactionIdStore) TransactionIdStore(org.neo4j.kernel.impl.transaction.log.TransactionIdStore) InstanceId(org.neo4j.cluster.InstanceId) NeoStoreDataSource(org.neo4j.kernel.NeoStoreDataSource) DelegateInvocationHandler(org.neo4j.kernel.ha.DelegateInvocationHandler) DelegateInvocationHandler(org.neo4j.kernel.ha.DelegateInvocationHandler) DependencyResolver(org.neo4j.graphdb.DependencyResolver) TransactionId(org.neo4j.kernel.impl.store.TransactionId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Monitors(org.neo4j.kernel.monitoring.Monitors) PagedFile(org.neo4j.io.pagecache.PagedFile) File(java.io.File) HaIdGeneratorFactory(org.neo4j.kernel.ha.id.HaIdGeneratorFactory) HandshakeResult(org.neo4j.kernel.ha.com.master.HandshakeResult) Config(org.neo4j.kernel.configuration.Config) ClusterMemberAvailability(org.neo4j.cluster.member.ClusterMemberAvailability) ClusterMembers(org.neo4j.kernel.ha.cluster.member.ClusterMembers) ObservedClusterMembers(org.neo4j.kernel.ha.cluster.member.ObservedClusterMembers) SlaveServer(org.neo4j.kernel.ha.com.slave.SlaveServer) ClusterMember(org.neo4j.kernel.ha.cluster.member.ClusterMember) ClusterClient(org.neo4j.cluster.client.ClusterClient) StoreId(org.neo4j.kernel.impl.store.StoreId) AbstractComponentSwitcher(org.neo4j.kernel.ha.cluster.modeswitch.AbstractComponentSwitcher) UpdatePuller(org.neo4j.kernel.ha.UpdatePuller) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) PullerFactory(org.neo4j.kernel.ha.PullerFactory) PagedFile(org.neo4j.io.pagecache.PagedFile) ComponentSwitcherContainer(org.neo4j.kernel.ha.cluster.modeswitch.ComponentSwitcherContainer) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Election(org.neo4j.cluster.protocol.election.Election) MasterClientResolver(org.neo4j.kernel.ha.com.slave.MasterClientResolver) Master(org.neo4j.kernel.ha.com.master.Master) TransactionStats(org.neo4j.kernel.impl.transaction.TransactionStats) Test(org.junit.Test)

Example 17 with PagedFile

use of org.neo4j.io.pagecache.PagedFile in project neo4j by neo4j.

the class StoreCopyServer method flushStoresAndStreamStoreFiles.

/**
     * Trigger store flush (checkpoint) and write {@link NeoStoreDataSource#listStoreFiles(boolean) store files} to the
     * given {@link StoreWriter}.
     *
     * @param triggerName name of the component asks for store files.
     * @param writer store writer to write files to.
     * @param includeLogs <code>true</code> if transaction logs should be copied, <code>false</code> otherwise.
     * @return a {@link RequestContext} specifying at which point the store copy started.
     */
public RequestContext flushStoresAndStreamStoreFiles(String triggerName, StoreWriter writer, boolean includeLogs) {
    try {
        ThrowingAction<IOException> checkPointAction = () -> {
            monitor.startTryCheckPoint();
            checkPointer.tryCheckPoint(new SimpleTriggerInfo(triggerName));
            monitor.finishTryCheckPoint();
        };
        // Copy the store files
        long lastAppliedTransaction;
        try (Resource lock = mutex.storeCopy(checkPointAction);
            ResourceIterator<StoreFileMetadata> files = dataSource.listStoreFiles(includeLogs)) {
            lastAppliedTransaction = checkPointer.lastCheckPointedTransactionId();
            monitor.startStreamingStoreFiles();
            ByteBuffer temporaryBuffer = ByteBuffer.allocateDirect((int) ByteUnit.mebiBytes(1));
            while (files.hasNext()) {
                StoreFileMetadata meta = files.next();
                File file = meta.file();
                int recordSize = meta.recordSize();
                // Read from paged file if mapping exists. Otherwise read through file system.
                // A file is mapped if it is a store, and we have a running database, which will be the case for
                // both online backup, and when we are the master of an HA cluster.
                final Optional<PagedFile> optionalPagedFile = pageCache.getExistingMapping(file);
                if (optionalPagedFile.isPresent()) {
                    try (PagedFile pagedFile = optionalPagedFile.get()) {
                        long fileSize = pagedFile.fileSize();
                        try (ReadableByteChannel fileChannel = pagedFile.openReadableByteChannel()) {
                            doWrite(writer, temporaryBuffer, file, recordSize, fileChannel, fileSize);
                        }
                    }
                } else {
                    try (ReadableByteChannel fileChannel = fileSystem.open(file, "r")) {
                        long fileSize = fileSystem.getFileSize(file);
                        doWrite(writer, temporaryBuffer, file, recordSize, fileChannel, fileSize);
                    }
                }
            }
        } finally {
            monitor.finishStreamingStoreFiles();
        }
        return anonymous(lastAppliedTransaction);
    } catch (IOException e) {
        throw new ServerFailureException(e);
    }
}
Also used : ReadableByteChannel(java.nio.channels.ReadableByteChannel) ServerFailureException(org.neo4j.com.ServerFailureException) PagedFile(org.neo4j.io.pagecache.PagedFile) Resource(org.neo4j.graphdb.Resource) IOException(java.io.IOException) StoreFileMetadata(org.neo4j.storageengine.api.StoreFileMetadata) ByteBuffer(java.nio.ByteBuffer) SimpleTriggerInfo(org.neo4j.kernel.impl.transaction.log.checkpoint.SimpleTriggerInfo) PagedFile(org.neo4j.io.pagecache.PagedFile) FileUtils.getMostCanonicalFile(org.neo4j.io.fs.FileUtils.getMostCanonicalFile) File(java.io.File)

Example 18 with PagedFile

use of org.neo4j.io.pagecache.PagedFile in project neo4j by neo4j.

the class SwitchToSlaveBranchThenCopyTest method mockPageCache.

private PageCache mockPageCache() throws IOException {
    PageCache pageCacheMock = mock(PageCache.class);
    PagedFile pagedFileMock = mock(PagedFile.class);
    when(pagedFileMock.getLastPageId()).thenReturn(1L);
    when(pageCacheMock.map(any(File.class), anyInt())).thenThrow(new IOException()).thenThrow(new IOException()).thenReturn(pagedFileMock);
    return pageCacheMock;
}
Also used : PagedFile(org.neo4j.io.pagecache.PagedFile) IOException(java.io.IOException) PagedFile(org.neo4j.io.pagecache.PagedFile) File(java.io.File) PageCache(org.neo4j.io.pagecache.PageCache)

Example 19 with PagedFile

use of org.neo4j.io.pagecache.PagedFile in project neo4j by neo4j.

the class SwitchToSlaveBranchThenCopyTest method newSwitchToSlaveSpy.

private SwitchToSlaveBranchThenCopy newSwitchToSlaveSpy() throws Exception {
    PageCache pageCacheMock = mock(PageCache.class);
    PagedFile pagedFileMock = mock(PagedFile.class);
    when(pagedFileMock.getLastPageId()).thenReturn(1L);
    when(pageCacheMock.map(any(File.class), anyInt())).thenReturn(pagedFileMock);
    when(pageCacheMock.streamFilesRecursive(any(File.class))).thenReturn(Stream.empty());
    StoreCopyClient storeCopyClient = mock(StoreCopyClient.class);
    return newSwitchToSlaveSpy(pageCacheMock, storeCopyClient);
}
Also used : PagedFile(org.neo4j.io.pagecache.PagedFile) StoreCopyClient(org.neo4j.com.storecopy.StoreCopyClient) PagedFile(org.neo4j.io.pagecache.PagedFile) File(java.io.File) PageCache(org.neo4j.io.pagecache.PageCache)

Example 20 with PagedFile

use of org.neo4j.io.pagecache.PagedFile in project neo4j by neo4j.

the class SwitchToSlaveCopyThenBranchTest method mockPageCache.

private PageCache mockPageCache() throws IOException {
    PageCache pageCacheMock = mock(PageCache.class);
    PagedFile pagedFileMock = mock(PagedFile.class);
    when(pagedFileMock.getLastPageId()).thenReturn(1L);
    when(pageCacheMock.map(any(File.class), anyInt())).thenThrow(new IOException()).thenThrow(new IOException()).thenReturn(pagedFileMock);
    return pageCacheMock;
}
Also used : PagedFile(org.neo4j.io.pagecache.PagedFile) IOException(java.io.IOException) PagedFile(org.neo4j.io.pagecache.PagedFile) File(java.io.File) PageCache(org.neo4j.io.pagecache.PageCache)

Aggregations

PagedFile (org.neo4j.io.pagecache.PagedFile)39 File (java.io.File)23 PageCursor (org.neo4j.io.pagecache.PageCursor)20 Test (org.junit.Test)16 IOException (java.io.IOException)13 PageCache (org.neo4j.io.pagecache.PageCache)10 ByteBuffer (java.nio.ByteBuffer)8 PageCacheTest (org.neo4j.io.pagecache.PageCacheTest)7 DelegatingStoreChannel (org.neo4j.graphdb.mockfs.DelegatingStoreChannel)5 FileSystemAbstraction (org.neo4j.io.fs.FileSystemAbstraction)5 StoreChannel (org.neo4j.io.fs.StoreChannel)5 NoSuchFileException (java.nio.file.NoSuchFileException)4 DelegatingPagedFile (org.neo4j.io.pagecache.DelegatingPagedFile)3 DelegatingPageCursor (org.neo4j.io.pagecache.impl.DelegatingPageCursor)3 ConfigurablePageCursorTracerSupplier (org.neo4j.io.pagecache.tracing.ConfigurablePageCursorTracerSupplier)3 RecordingPageCacheTracer (org.neo4j.io.pagecache.tracing.recording.RecordingPageCacheTracer)3 Evict (org.neo4j.io.pagecache.tracing.recording.RecordingPageCacheTracer.Evict)3 RecordingPageCursorTracer (org.neo4j.io.pagecache.tracing.recording.RecordingPageCursorTracer)3 Fault (org.neo4j.io.pagecache.tracing.recording.RecordingPageCursorTracer.Fault)3 TransactionId (org.neo4j.kernel.impl.store.TransactionId)3