Search in sources :

Example 6 with PagedFile

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

the class MetaDataStore method setRecord.

/**
     * Writes a record in a neostore file.
     * This method only works for neostore files of the current version.
     *
     * @param pageCache {@link PageCache} the {@code neostore} file lives in.
     * @param neoStore {@link File} pointing to the neostore.
     * @param position record {@link Position}.
     * @param value value to write in that record.
     * @return the previous value before writing.
     * @throws IOException if any I/O related error occurs.
     */
public static long setRecord(PageCache pageCache, File neoStore, Position position, long value) throws IOException {
    long previousValue = FIELD_NOT_INITIALIZED;
    int pageSize = getPageSize(pageCache);
    try (PagedFile pagedFile = pageCache.map(neoStore, pageSize)) {
        int offset = offset(position);
        try (PageCursor cursor = pagedFile.io(0, PagedFile.PF_SHARED_WRITE_LOCK)) {
            if (cursor.next()) {
                // We're overwriting a record, get the previous value
                cursor.setOffset(offset);
                byte inUse = cursor.getByte();
                long record = cursor.getLong();
                if (inUse == Record.IN_USE.byteValue()) {
                    previousValue = record;
                }
                // Write the value
                cursor.setOffset(offset);
                cursor.putByte(Record.IN_USE.byteValue());
                cursor.putLong(value);
                if (cursor.checkAndClearBoundsFlag()) {
                    MetaDataRecord neoStoreRecord = new MetaDataRecord();
                    neoStoreRecord.setId(position.id);
                    throw new UnderlyingStorageException(buildOutOfBoundsExceptionMessage(neoStoreRecord, 0, offset, RECORD_SIZE, pageSize, neoStore.getAbsolutePath()));
                }
            }
        }
    }
    return previousValue;
}
Also used : PagedFile(org.neo4j.io.pagecache.PagedFile) MetaDataRecord(org.neo4j.kernel.impl.store.record.MetaDataRecord) PageCursor(org.neo4j.io.pagecache.PageCursor)

Example 7 with PagedFile

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

the class ConfigurableStandalonePageCacheFactoryTest method mustAutomaticallyStartEvictionThread.

@Test(timeout = 10000)
public void mustAutomaticallyStartEvictionThread() throws IOException {
    try (FileSystemAbstraction fs = new DelegateFileSystemAbstraction(Jimfs.newFileSystem(jimConfig()))) {
        File file = new File("/a").getCanonicalFile();
        fs.create(file).close();
        try (PageCache cache = ConfigurableStandalonePageCacheFactory.createPageCache(fs);
            PagedFile pf = cache.map(file, 4096);
            PageCursor cursor = pf.io(0, PagedFile.PF_SHARED_WRITE_LOCK)) {
            // If the eviction thread has not been started, then this test will block forever.
            for (int i = 0; i < 10_000; i++) {
                assertTrue(cursor.next());
                cursor.putInt(42);
            }
        }
    }
}
Also used : DelegateFileSystemAbstraction(org.neo4j.io.fs.DelegateFileSystemAbstraction) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) PagedFile(org.neo4j.io.pagecache.PagedFile) DelegateFileSystemAbstraction(org.neo4j.io.fs.DelegateFileSystemAbstraction) PagedFile(org.neo4j.io.pagecache.PagedFile) File(java.io.File) PageCache(org.neo4j.io.pagecache.PageCache) PageCursor(org.neo4j.io.pagecache.PageCursor) Test(org.junit.Test)

Example 8 with PagedFile

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

the class StoreMigrator method moveMigratedFiles.

@Override
public void moveMigratedFiles(File migrationDir, File storeDir, String versionToUpgradeFrom, String versionToUpgradeTo) throws IOException {
    // Move the migrated ones into the store directory
    StoreFile.fileOperation(MOVE, fileSystem, migrationDir, storeDir, StoreFile.currentStoreFiles(), // allow to skip non existent source files
    true, // allow to overwrite target files
    ExistingTargetStrategy.OVERWRITE, StoreFileType.values());
    // move the files with the page cache.
    try {
        Iterable<FileHandle> fileHandles = pageCache.streamFilesRecursive(migrationDir)::iterator;
        for (FileHandle fh : fileHandles) {
            Predicate<StoreFile> predicate = storeFile -> storeFile.fileName(StoreFileType.STORE).equals(fh.getFile().getName());
            if (StreamSupport.stream(StoreFile.currentStoreFiles().spliterator(), false).anyMatch(predicate)) {
                final Optional<PagedFile> optionalPagedFile = pageCache.getExistingMapping(fh.getFile());
                if (optionalPagedFile.isPresent()) {
                    optionalPagedFile.get().close();
                }
                fh.rename(new File(storeDir, fh.getFile().getName()), StandardCopyOption.REPLACE_EXISTING);
            }
        }
    } catch (NoSuchFileException e) {
    //This means that we had no files only present in the page cache, this is fine.
    }
    RecordFormats oldFormat = selectForVersion(versionToUpgradeFrom);
    RecordFormats newFormat = selectForVersion(versionToUpgradeTo);
    boolean movingAwayFromVersionTrailers = oldFormat.hasCapability(VERSION_TRAILERS) && !newFormat.hasCapability(VERSION_TRAILERS);
    if (movingAwayFromVersionTrailers) {
        StoreFile.removeTrailers(versionToUpgradeFrom, fileSystem, storeDir, pageCache.pageSize());
    }
    File neoStore = new File(storeDir, MetaDataStore.DEFAULT_NAME);
    long logVersion = MetaDataStore.getRecord(pageCache, neoStore, Position.LOG_VERSION);
    long lastCommittedTx = MetaDataStore.getRecord(pageCache, neoStore, Position.LAST_TRANSACTION_ID);
    // update or add upgrade id and time and other necessary neostore records
    updateOrAddNeoStoreFieldsAsPartOfMigration(migrationDir, storeDir, versionToUpgradeTo);
    // delete old logs
    legacyLogs.deleteUnusedLogFiles(storeDir);
    if (movingAwayFromVersionTrailers) {
        // write a check point in the log in order to make recovery work in the newer version
        new StoreMigratorCheckPointer(storeDir, fileSystem).checkPoint(logVersion, lastCommittedTx);
    }
}
Also used : PropertyDeduplicator(org.neo4j.kernel.impl.storemigration.legacystore.v21.propertydeduplication.PropertyDeduplicator) Arrays(java.util.Arrays) PageCursor(org.neo4j.io.pagecache.PageCursor) NullLogProvider(org.neo4j.logging.NullLogProvider) StringUtils(org.apache.commons.lang3.StringUtils) UNKNOWN_TX_COMMIT_TIMESTAMP(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.UNKNOWN_TX_COMMIT_TIMESTAMP) COPY(org.neo4j.kernel.impl.storemigration.FileOperation.COPY) SchemaIndexProvider(org.neo4j.kernel.api.index.SchemaIndexProvider) CountsComputer(org.neo4j.kernel.impl.store.CountsComputer) Arrays.asList(java.util.Arrays.asList) BASE_TX_COMMIT_TIMESTAMP(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_COMMIT_TIMESTAMP) Position(org.neo4j.kernel.impl.store.MetaDataStore.Position) Lifespan(org.neo4j.kernel.lifecycle.Lifespan) RecordCursors(org.neo4j.kernel.impl.store.RecordCursors) SilentMigrationProgressMonitor(org.neo4j.kernel.impl.storemigration.monitoring.SilentMigrationProgressMonitor) StandardCharsets(java.nio.charset.StandardCharsets) MetaDataRecordFormat(org.neo4j.kernel.impl.store.format.standard.MetaDataRecordFormat) DELETE(org.neo4j.kernel.impl.storemigration.FileOperation.DELETE) Stream(java.util.stream.Stream) ExecutionSupervisors.withDynamicProcessorAssignment(org.neo4j.unsafe.impl.batchimport.staging.ExecutionSupervisors.withDynamicProcessorAssignment) StoreType(org.neo4j.kernel.impl.store.StoreType) BatchImporter(org.neo4j.unsafe.impl.batchimport.BatchImporter) NodeStore(org.neo4j.kernel.impl.store.NodeStore) StoreFactory(org.neo4j.kernel.impl.store.StoreFactory) Collectors(org.neo4j.unsafe.impl.batchimport.input.Collectors) PagedFile(org.neo4j.io.pagecache.PagedFile) VERSION_TRAILERS(org.neo4j.kernel.impl.store.format.Capability.VERSION_TRAILERS) FormatFamily(org.neo4j.kernel.impl.store.format.FormatFamily) Supplier(java.util.function.Supplier) UNKNOWN_TX_CHECKSUM(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.UNKNOWN_TX_CHECKSUM) BufferedOutputStream(java.io.BufferedOutputStream) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) TransactionId(org.neo4j.kernel.impl.store.TransactionId) StandardV2_2(org.neo4j.kernel.impl.store.format.standard.StandardV2_2) LogPosition(org.neo4j.kernel.impl.transaction.log.LogPosition) StandardV2_1(org.neo4j.kernel.impl.store.format.standard.StandardV2_1) RelationshipStore(org.neo4j.kernel.impl.store.RelationshipStore) StandardV2_0(org.neo4j.kernel.impl.store.format.standard.StandardV2_0) IdMappers(org.neo4j.unsafe.impl.batchimport.cache.idmapping.IdMappers) BiConsumer(java.util.function.BiConsumer) IdGenerators(org.neo4j.unsafe.impl.batchimport.cache.idmapping.IdGenerators) StreamSupport(java.util.stream.StreamSupport) DirectRecordStoreMigrator(org.neo4j.kernel.impl.storemigration.DirectRecordStoreMigrator) CoarseBoundedProgressExecutionMonitor(org.neo4j.unsafe.impl.batchimport.staging.CoarseBoundedProgressExecutionMonitor) StoreFile(org.neo4j.kernel.impl.storemigration.StoreFile) FileOutputStream(java.io.FileOutputStream) RecordFormatSelector.selectForVersion(org.neo4j.kernel.impl.store.format.RecordFormatSelector.selectForVersion) IOException(java.io.IOException) NodeRecordFormat(org.neo4j.kernel.impl.store.format.standard.NodeRecordFormat) LegacyLogs(org.neo4j.kernel.impl.storemigration.legacylogs.LegacyLogs) File(java.io.File) Iterables(org.neo4j.helpers.collection.Iterables) ParallelBatchImporter(org.neo4j.unsafe.impl.batchimport.ParallelBatchImporter) NodeRecord(org.neo4j.kernel.impl.store.record.NodeRecord) Configuration(org.neo4j.unsafe.impl.batchimport.Configuration) BufferedReader(java.io.BufferedReader) MigrationProgressMonitor(org.neo4j.kernel.impl.storemigration.monitoring.MigrationProgressMonitor) RelationshipRecord(org.neo4j.kernel.impl.store.record.RelationshipRecord) StoreUpgrader(org.neo4j.kernel.impl.storemigration.StoreUpgrader) NoSuchFileException(java.nio.file.NoSuchFileException) BASE_TX_LOG_VERSION(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_LOG_VERSION) BASE_TX_CHECKSUM(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_CHECKSUM) PageCache(org.neo4j.io.pagecache.PageCache) InputNode(org.neo4j.unsafe.impl.batchimport.input.InputNode) Predicate(java.util.function.Predicate) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) MOVE(org.neo4j.kernel.impl.storemigration.FileOperation.MOVE) LogService(org.neo4j.kernel.impl.logging.LogService) List(java.util.List) StoreFileType(org.neo4j.kernel.impl.storemigration.StoreFileType) MetaDataStore(org.neo4j.kernel.impl.store.MetaDataStore) Writer(java.io.Writer) Optional(java.util.Optional) Inputs(org.neo4j.unsafe.impl.batchimport.input.Inputs) InputIterable(org.neo4j.unsafe.impl.batchimport.InputIterable) InputRelationship(org.neo4j.unsafe.impl.batchimport.input.InputRelationship) TransactionIdStore(org.neo4j.kernel.impl.transaction.log.TransactionIdStore) InputEntity(org.neo4j.unsafe.impl.batchimport.input.InputEntity) DEFAULT_NAME(org.neo4j.kernel.impl.store.MetaDataStore.DEFAULT_NAME) RecordFormats(org.neo4j.kernel.impl.store.format.RecordFormats) CustomIOConfigValidator(org.neo4j.kernel.impl.util.CustomIOConfigValidator) AdditionalInitialIds(org.neo4j.unsafe.impl.batchimport.AdditionalInitialIds) NeoStores(org.neo4j.kernel.impl.store.NeoStores) StorePropertyCursor(org.neo4j.kernel.impl.api.store.StorePropertyCursor) CountsTracker(org.neo4j.kernel.impl.store.counts.CountsTracker) ExistingTargetStrategy(org.neo4j.kernel.impl.storemigration.ExistingTargetStrategy) PhysicalLogFiles(org.neo4j.kernel.impl.transaction.log.PhysicalLogFiles) RelationshipRecordFormat(org.neo4j.kernel.impl.store.format.standard.RelationshipRecordFormat) OutputStream(java.io.OutputStream) Config(org.neo4j.kernel.configuration.Config) ReadOnlyIdGeneratorFactory(org.neo4j.kernel.impl.store.id.ReadOnlyIdGeneratorFactory) LockService(org.neo4j.kernel.impl.locking.LockService) FileHandle(org.neo4j.io.pagecache.FileHandle) CapabilityType(org.neo4j.kernel.impl.store.format.CapabilityType) PrimitiveRecord(org.neo4j.kernel.impl.store.record.PrimitiveRecord) FIELD_NOT_PRESENT(org.neo4j.kernel.impl.store.format.standard.MetaDataRecordFormat.FIELD_NOT_PRESENT) StoreMigratorCheckPointer(org.neo4j.kernel.impl.storemigration.StoreMigratorCheckPointer) ExecutionMonitor(org.neo4j.unsafe.impl.batchimport.staging.ExecutionMonitor) BASE_TX_LOG_BYTE_OFFSET(org.neo4j.kernel.impl.transaction.log.TransactionIdStore.BASE_TX_LOG_BYTE_OFFSET) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) PagedFile(org.neo4j.io.pagecache.PagedFile) FileHandle(org.neo4j.io.pagecache.FileHandle) NoSuchFileException(java.nio.file.NoSuchFileException) RecordFormats(org.neo4j.kernel.impl.store.format.RecordFormats) StoreFile(org.neo4j.kernel.impl.storemigration.StoreFile) PagedFile(org.neo4j.io.pagecache.PagedFile) StoreFile(org.neo4j.kernel.impl.storemigration.StoreFile) File(java.io.File) StoreMigratorCheckPointer(org.neo4j.kernel.impl.storemigration.StoreMigratorCheckPointer)

Example 9 with PagedFile

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

the class KeyValueStoreFileFormat method open.

/**
     * Opens an existing store file.
     *
     * @param fs    the file system which holds the store file.
     * @param path  the location in the file system where the store file resides.
     * @param pages the page cache to use for opening the store file.
     * @return the opened store file.
     */
private KeyValueStoreFile open(FileSystemAbstraction fs, File path, PageCache pages) throws IOException {
    ByteBuffer buffer = ByteBuffer.wrap(new byte[maxSize * 4]);
    try (StoreChannel file = fs.open(path, "r")) {
        while (buffer.hasRemaining()) {
            int bytes = file.read(buffer);
            if (bytes == -1) {
                break;
            }
        }
    }
    buffer.flip();
    // compute the key sizes
    int keySize = 0;
    while (buffer.hasRemaining() && buffer.get() == 0) {
        if (++keySize > maxSize) {
            throw new IOException("Invalid header, key size too large.");
        }
    }
    // compute the value size
    // start at 1, since we've seen the first non-zero byte
    int valueSize = 1;
    for (int zeros = 0; zeros <= keySize; zeros++) {
        if (!buffer.hasRemaining()) {
            throw new IOException("Invalid value size: " + valueSize);
        }
        if (buffer.get() != 0) {
            zeros = 0;
        }
        if (++valueSize - keySize > maxSize) {
            throw new IOException("Invalid header, value size too large.");
        }
    }
    // we read in the next zero-key
    valueSize -= keySize;
    // compute a page size that aligns with the <key,value>-tuple size
    int pageSize = pageSize(pages, keySize, valueSize);
    // read the store metadata
    {
        BigEndianByteArrayBuffer formatSpecifier = new BigEndianByteArrayBuffer(new byte[valueSize]);
        writeFormatSpecifier(formatSpecifier);
        PagedFile file = pages.map(path, pageSize);
        try {
            BigEndianByteArrayBuffer key = new BigEndianByteArrayBuffer(new byte[keySize]);
            BigEndianByteArrayBuffer value = new BigEndianByteArrayBuffer(new byte[valueSize]);
            // the first value is the format identifier, pass it along
            buffer.position(keySize);
            buffer.limit(keySize + valueSize);
            value.dataFrom(buffer);
            MetadataCollector metadata = metadata(formatSpecifier, pageSize, keySize, valueSize);
            // scan and catalogue all entries in the file
            KeyValueStoreFile.scanAll(file, 0, metadata, key, value);
            KeyValueStoreFile storeFile = new KeyValueStoreFile(file, keySize, valueSize, metadata);
            file = null;
            return storeFile;
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }
}
Also used : PagedFile(org.neo4j.io.pagecache.PagedFile) StoreChannel(org.neo4j.io.fs.StoreChannel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer)

Example 10 with PagedFile

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

the class AbstractRecordFormatTest method verifyWriteAndRead.

private <R extends AbstractBaseRecord> void verifyWriteAndRead(Supplier<RecordFormat<R>> formatSupplier, Supplier<Generator<R>> generatorSupplier, Supplier<RecordKey<R>> keySupplier) throws IOException {
    // GIVEN
    try (PagedFile storeFile = pageCache.map(new File("store-" + name.getMethodName()), PAGE_SIZE, CREATE)) {
        RecordFormat<R> format = formatSupplier.get();
        RecordKey<R> key = keySupplier.get();
        Generator<R> generator = generatorSupplier.get();
        int recordSize = format.getRecordSize(new IntStoreHeader(DATA_SIZE));
        BatchingIdSequence idSequence = new BatchingIdSequence(random.nextBoolean() ? idSureToBeOnTheNextPage(PAGE_SIZE, recordSize) : 10);
        // WHEN
        long time = currentTimeMillis();
        long endTime = time + TEST_TIME;
        long i = 0;
        for (; i < TEST_ITERATIONS && currentTimeMillis() < endTime; i++) {
            R written = generator.get(recordSize, format, i % 5);
            R read = format.newRecord();
            try {
                writeRecord(written, format, storeFile, recordSize, idSequence);
                readAndVerifyRecord(written, read, format, key, storeFile, recordSize);
                idSequence.reset();
            } catch (Throwable t) {
                Exceptions.setMessage(t, t.getMessage() + " : written:" + written + ", read:" + read + ", seed:" + random.seed() + ", iteration:" + i);
                throw t;
            }
        }
    }
}
Also used : BatchingIdSequence(org.neo4j.unsafe.impl.batchimport.store.BatchingIdSequence) PagedFile(org.neo4j.io.pagecache.PagedFile) IntStoreHeader(org.neo4j.kernel.impl.store.IntStoreHeader) PagedFile(org.neo4j.io.pagecache.PagedFile) File(java.io.File)

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