Search in sources :

Example 16 with DefaultIdGeneratorFactory

use of org.neo4j.internal.id.DefaultIdGeneratorFactory in project neo4j by neo4j.

the class IdGeneratorMigrator method migrateIdFiles.

private void migrateIdFiles(DatabaseLayout directoryLayout, DatabaseLayout migrationLayout, RecordFormats oldFormat, RecordFormats newFormat, ProgressReporter progress, CursorContext cursorContext) throws IOException {
    // The store .id files needs to be migrated. At this point some of them have been sort-of-migrated, i.e. merely ported
    // to the new format, but just got the highId and nothing else. Regardless we want to do a proper migration here,
    // which not only means creating an empty id file w/ only highId. No, it also means scanning the stores and properly
    // updating its freelist so that from this point no ids will be lost, ever.
    // For every store type: if store is in migrationLayout use that, else use the one from the dbLayout because it will
    // be of the current format already. Then scan it and create the .id file in the migration layout.
    List<StoreType> storesInDbDirectory = new ArrayList<>();
    List<StoreType> storesInMigrationDirectory = new ArrayList<>();
    for (StoreType storeType : StoreType.values()) {
        // See if it exists in migration directory, otherwise it must be in the db directory
        List<StoreType> list = fileSystem.fileExists(migrationLayout.file(storeType.getDatabaseFile())) ? storesInMigrationDirectory : storesInDbDirectory;
        list.add(storeType);
    }
    progress.start(storesInDbDirectory.size() + storesInMigrationDirectory.size());
    // Rebuild the .id files from the legacy stores that haven't been upgraded, i.e. if they remained unchanged
    // Make them end up in upgrade/<store>.id so that they won't overwrite the origin .id file before the upgrade is completed
    IdGeneratorFactory rebuiltIdGeneratorsFromOldStore = new DefaultIdGeneratorFactory(fileSystem, immediate(), directoryLayout.getDatabaseName()) {

        @Override
        public IdGenerator open(PageCache pageCache, Path filename, IdType idType, LongSupplier highIdScanner, long maxId, DatabaseReadOnlyChecker readOnlyChecker, Config config, CursorContext cursorContext, ImmutableSet<OpenOption> openOptions) throws IOException {
            Path redirectedFilename = migrationLayout.databaseDirectory().resolve(filename.getFileName().toString());
            return super.open(pageCache, redirectedFilename, idType, highIdScanner, maxId, readOnlyChecker, config, cursorContext, openOptions);
        }

        @Override
        public IdGenerator create(PageCache pageCache, Path fileName, IdType idType, long highId, boolean throwIfFileExists, long maxId, DatabaseReadOnlyChecker readOnlyChecker, Config config, CursorContext cursorContext, ImmutableSet<OpenOption> openOptions) {
            throw new IllegalStateException("The store file should exist and therefore all calls should be to open, not create");
        }
    };
    startAndTriggerRebuild(directoryLayout, oldFormat, rebuiltIdGeneratorsFromOldStore, storesInDbDirectory, progress, cursorContext);
    // Build the ones from the migration directory, those stores that have been migrated
    // Before doing this we will have to create empty stores for those that are missing, otherwise some of the stores
    // that we need to open will complain because some of their "sub-stores" doesn't exist. They will be empty, it's fine...
    // and we will not read from them at all. They will just sit there and allow their parent store to be opened.
    // We'll remove them after we have built the id files
    IdGeneratorFactory rebuiltIdGeneratorsFromNewStore = new DefaultIdGeneratorFactory(fileSystem, immediate(), migrationLayout.getDatabaseName());
    Set<Path> placeHolderStoreFiles = createEmptyPlaceHolderStoreFiles(migrationLayout, newFormat);
    startAndTriggerRebuild(migrationLayout, newFormat, rebuiltIdGeneratorsFromNewStore, storesInMigrationDirectory, progress, cursorContext);
    for (Path emptyPlaceHolderStoreFile : placeHolderStoreFiles) {
        fileSystem.deleteFile(emptyPlaceHolderStoreFile);
    }
}
Also used : Path(java.nio.file.Path) Config(org.neo4j.configuration.Config) ArrayList(java.util.ArrayList) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) IdGeneratorFactory(org.neo4j.internal.id.IdGeneratorFactory) ScanOnOpenReadOnlyIdGeneratorFactory(org.neo4j.internal.id.ScanOnOpenReadOnlyIdGeneratorFactory) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) CursorContext(org.neo4j.io.pagecache.context.CursorContext) IdType(org.neo4j.internal.id.IdType) StoreType(org.neo4j.kernel.impl.store.StoreType) ImmutableSet(org.eclipse.collections.api.set.ImmutableSet) DatabaseReadOnlyChecker(org.neo4j.configuration.helpers.DatabaseReadOnlyChecker) LongSupplier(java.util.function.LongSupplier) PageCache(org.neo4j.io.pagecache.PageCache)

Example 17 with DefaultIdGeneratorFactory

use of org.neo4j.internal.id.DefaultIdGeneratorFactory in project neo4j by neo4j.

the class RecoveryIT method idGeneratorIsDirty.

private boolean idGeneratorIsDirty(Path path, IdType idType) throws IOException {
    DefaultIdGeneratorFactory idGeneratorFactory = new DefaultIdGeneratorFactory(fileSystem, immediate(), "my db");
    try (IdGenerator idGenerator = idGeneratorFactory.open(pageCache, path, idType, () -> 0L, /*will not be used*/
    10_000, readOnly(), Config.defaults(), NULL, Sets.immutable.empty())) {
        MutableBoolean dirtyOnStartup = new MutableBoolean();
        InvocationHandler invocationHandler = (proxy, method, args) -> {
            if (method.getName().equals("dirtyOnStartup")) {
                dirtyOnStartup.setTrue();
            }
            return null;
        };
        ReporterFactory reporterFactory = new ReporterFactory(invocationHandler);
        idGenerator.consistencyCheck(reporterFactory, NULL);
        return dirtyOnStartup.booleanValue();
    }
}
Also used : LifecycleAdapter(org.neo4j.kernel.lifecycle.LifecycleAdapter) MetaDataStore.getRecord(org.neo4j.kernel.impl.store.MetaDataStore.getRecord) DatabaseReadOnlyChecker.readOnly(org.neo4j.configuration.helpers.DatabaseReadOnlyChecker.readOnly) GraphDatabaseSettings.fail_on_missing_files(org.neo4j.configuration.GraphDatabaseSettings.fail_on_missing_files) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ReporterFactory(org.neo4j.annotations.documented.ReporterFactory) LogFilesBuilder(org.neo4j.kernel.impl.transaction.log.files.LogFilesBuilder) Config(org.neo4j.configuration.Config) DefaultPageCacheTracer(org.neo4j.io.pagecache.tracing.DefaultPageCacheTracer) InternalTransaction(org.neo4j.kernel.impl.coreapi.InternalTransaction) DatabaseLayout(org.neo4j.io.layout.DatabaseLayout) Recovery.performRecovery(org.neo4j.kernel.recovery.Recovery.performRecovery) DEFAULT_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME) GraphDatabaseSettings.logical_log_rotation_threshold(org.neo4j.configuration.GraphDatabaseSettings.logical_log_rotation_threshold) LogCheckPointEvent(org.neo4j.kernel.impl.transaction.tracing.LogCheckPointEvent) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AssertableLogProvider(org.neo4j.logging.AssertableLogProvider) Monitors(org.neo4j.monitoring.Monitors) CHECKPOINT_LOG_VERSION(org.neo4j.kernel.impl.store.MetaDataStore.Position.CHECKPOINT_LOG_VERSION) NULL(org.neo4j.io.pagecache.context.CursorContext.NULL) Transaction(org.neo4j.graphdb.Transaction) Path(java.nio.file.Path) PageCache(org.neo4j.io.pagecache.PageCache) LAST_MISSING_STORE_FILES_RECOVERY_TIMESTAMP(org.neo4j.kernel.impl.store.MetaDataStore.Position.LAST_MISSING_STORE_FILES_RECOVERY_TIMESTAMP) DEFAULT_NAME(org.neo4j.kernel.impl.transaction.log.files.TransactionLogFilesHelper.DEFAULT_NAME) LegacyTransactionLogsLocator(org.neo4j.kernel.impl.storemigration.LegacyTransactionLogsLocator) DatabaseReadOnlyChecker.writable(org.neo4j.configuration.helpers.DatabaseReadOnlyChecker.writable) CompositeDatabaseAvailabilityGuard(org.neo4j.kernel.availability.CompositeDatabaseAvailabilityGuard) RelationshipType.withName(org.neo4j.graphdb.RelationshipType.withName) Instant(java.time.Instant) ArrayUtil(org.neo4j.internal.helpers.ArrayUtil) Services(org.neo4j.service.Services) Neo4jLayoutExtension(org.neo4j.test.extension.Neo4jLayoutExtension) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) Test(org.junit.jupiter.api.Test) IdType(org.neo4j.internal.id.IdType) IndexQueryConstraints.unconstrained(org.neo4j.internal.kernel.api.IndexQueryConstraints.unconstrained) DatabaseStateService(org.neo4j.dbms.DatabaseStateService) INSTANCE(org.neo4j.memory.EmptyMemoryTracker.INSTANCE) ExtensionContext(org.neo4j.kernel.extension.context.ExtensionContext) RandomStringUtils.randomAlphanumeric(org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) MetaDataStore(org.neo4j.kernel.impl.store.MetaDataStore) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) DatabaseStartAbortedException(org.neo4j.dbms.database.DatabaseStartAbortedException) RelationshipType(org.neo4j.graphdb.RelationshipType) IndexDescriptor(org.neo4j.internal.schema.IndexDescriptor) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) DatabaseManagementService(org.neo4j.dbms.api.DatabaseManagementService) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) LogFiles(org.neo4j.kernel.impl.transaction.log.files.LogFiles) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Label(org.neo4j.graphdb.Label) Config.defaults(org.neo4j.configuration.Config.defaults) IndexReadSession(org.neo4j.internal.kernel.api.IndexReadSession) DatabaseTracer(org.neo4j.kernel.impl.transaction.tracing.DatabaseTracer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MINUTES(java.util.concurrent.TimeUnit.MINUTES) Node(org.neo4j.graphdb.Node) IndexType(org.neo4j.graphdb.schema.IndexType) GraphDatabaseSettings.preallocate_logical_logs(org.neo4j.configuration.GraphDatabaseSettings.preallocate_logical_logs) LogPosition(org.neo4j.kernel.impl.transaction.log.LogPosition) PropertyIndexQuery.fulltextSearch(org.neo4j.internal.kernel.api.PropertyIndexQuery.fulltextSearch) TestDatabaseManagementServiceBuilder(org.neo4j.test.TestDatabaseManagementServiceBuilder) GraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService) Inject(org.neo4j.test.extension.Inject) StorageEngineFactory.defaultStorageEngine(org.neo4j.storageengine.api.StorageEngineFactory.defaultStorageEngine) Iterables(org.neo4j.internal.helpers.collection.Iterables) IdGenerator(org.neo4j.internal.id.IdGenerator) GraphDatabaseInternalSettings(org.neo4j.configuration.GraphDatabaseInternalSettings) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) EMPTY(org.neo4j.kernel.database.DatabaseTracers.EMPTY) Sets(org.eclipse.collections.api.factory.Sets) Lifecycle(org.neo4j.kernel.lifecycle.Lifecycle) NullLogProvider.nullLogProvider(org.neo4j.logging.NullLogProvider.nullLogProvider) BASE_TX_LOG_BYTE_OFFSET(org.neo4j.storageengine.api.LogVersionRepository.BASE_TX_LOG_BYTE_OFFSET) DetachedCheckpointAppender(org.neo4j.kernel.impl.transaction.log.checkpoint.DetachedCheckpointAppender) ByteUnit(org.neo4j.io.ByteUnit) LockTracer(org.neo4j.lock.LockTracer) PageCacheExtension(org.neo4j.test.extension.pagecache.PageCacheExtension) Iterables.count(org.neo4j.internal.helpers.collection.Iterables.count) RelationshipValueIndexCursor(org.neo4j.internal.kernel.api.RelationshipValueIndexCursor) ExceptionUtils.getRootCause(org.apache.commons.lang3.exception.ExceptionUtils.getRootCause) IOException(java.io.IOException) Neo4jLayout(org.neo4j.io.layout.Neo4jLayout) DatabaseTracers(org.neo4j.kernel.database.DatabaseTracers) StorageEngineFactory(org.neo4j.storageengine.api.StorageEngineFactory) RecoveryCleanupWorkCollector.immediate(org.neo4j.index.internal.gbptree.RecoveryCleanupWorkCollector.immediate) DefaultFileSystemAbstraction(org.neo4j.io.fs.DefaultFileSystemAbstraction) ExtensionFactory(org.neo4j.kernel.extension.ExtensionFactory) Relationship(org.neo4j.graphdb.Relationship) String.valueOf(java.lang.String.valueOf) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) Clock(java.time.Clock) InvocationHandler(java.lang.reflect.InvocationHandler) ReporterFactory(org.neo4j.annotations.documented.ReporterFactory) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) IdGenerator(org.neo4j.internal.id.IdGenerator) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 18 with DefaultIdGeneratorFactory

use of org.neo4j.internal.id.DefaultIdGeneratorFactory in project neo4j by neo4j.

the class RecoveryIT method shouldForceRecoveryEvenThoughNotSeeminglyRequired.

@Test
void shouldForceRecoveryEvenThoughNotSeeminglyRequired() throws Exception {
    // given
    GraphDatabaseAPI db = createDatabase();
    generateSomeData(db);
    DatabaseLayout layout = db.databaseLayout();
    managementService.shutdown();
    assertFalse(isRecoveryRequired(layout));
    // Make an ID generator, say for the node store, dirty
    DefaultIdGeneratorFactory idGeneratorFactory = new DefaultIdGeneratorFactory(fileSystem, immediate(), "my db");
    try (IdGenerator idGenerator = idGeneratorFactory.open(pageCache, layout.idNodeStore(), IdType.NODE, () -> 0L, /*will not be used*/
    10_000, writable(), Config.defaults(), NULL, Sets.immutable.empty())) {
        // Merely opening a marker will make the backing GBPTree dirty
        idGenerator.marker(NULL).close();
    }
    assertFalse(isRecoveryRequired(layout));
    assertTrue(idGeneratorIsDirty(layout.idNodeStore(), IdType.NODE));
    // when
    MutableBoolean recoveryRunEvenThoughNoCommitsAfterLastCheckpoint = new MutableBoolean();
    RecoveryStartInformationProvider.Monitor monitor = new RecoveryStartInformationProvider.Monitor() {

        @Override
        public void noCommitsAfterLastCheckPoint(LogPosition logPosition) {
            recoveryRunEvenThoughNoCommitsAfterLastCheckpoint.setTrue();
        }
    };
    Monitors monitors = new Monitors();
    monitors.addMonitorListener(monitor);
    Recovery.performRecovery(fileSystem, pageCache, EMPTY, Config.defaults(), layout, defaultStorageEngine(), true, nullLogProvider(), monitors, Iterables.cast(Services.loadAll(ExtensionFactory.class)), Optional.empty(), null, INSTANCE, Clock.systemUTC());
    // then
    assertFalse(idGeneratorIsDirty(layout.idNodeStore(), IdType.NODE));
    assertTrue(recoveryRunEvenThoughNoCommitsAfterLastCheckpoint.booleanValue());
}
Also used : GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) DatabaseLayout(org.neo4j.io.layout.DatabaseLayout) DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) Monitors(org.neo4j.monitoring.Monitors) IdGenerator(org.neo4j.internal.id.IdGenerator) LogPosition(org.neo4j.kernel.impl.transaction.log.LogPosition) Test(org.junit.jupiter.api.Test)

Example 19 with DefaultIdGeneratorFactory

use of org.neo4j.internal.id.DefaultIdGeneratorFactory in project neo4j by neo4j.

the class TransactionRecordStateTest method createStores.

private NeoStores createStores(Config config, RecordFormats formats) {
    idGeneratorFactory = new DefaultIdGeneratorFactory(fs, immediate(), databaseLayout.getDatabaseName());
    var storeFactory = new StoreFactory(databaseLayout, config, idGeneratorFactory, pageCache, fs, formats, NullLogProvider.getInstance(), PageCacheTracer.NULL, writable(), immutable.empty());
    return storeFactory.openAllNeoStores(true);
}
Also used : DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) StoreFactory(org.neo4j.kernel.impl.store.StoreFactory)

Example 20 with DefaultIdGeneratorFactory

use of org.neo4j.internal.id.DefaultIdGeneratorFactory in project neo4j by neo4j.

the class SchemaStorageTest method before.

@BeforeEach
void before() {
    var storeFactory = new StoreFactory(databaseLayout, Config.defaults(), new DefaultIdGeneratorFactory(fs, immediate(), databaseLayout.getDatabaseName()), pageCache, fs, NullLogProvider.getInstance(), PageCacheTracer.NULL, writable());
    neoStores = storeFactory.openNeoStores(true, StoreType.SCHEMA, StoreType.PROPERTY_KEY_TOKEN, StoreType.LABEL_TOKEN, StoreType.RELATIONSHIP_TYPE_TOKEN);
    storage = new SchemaStorage(neoStores.getSchemaStore(), StoreTokens.readOnlyTokenHolders(neoStores, NULL), () -> KernelVersion.LATEST);
}
Also used : DefaultIdGeneratorFactory(org.neo4j.internal.id.DefaultIdGeneratorFactory) StoreFactory(org.neo4j.kernel.impl.store.StoreFactory) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

DefaultIdGeneratorFactory (org.neo4j.internal.id.DefaultIdGeneratorFactory)53 StoreFactory (org.neo4j.kernel.impl.store.StoreFactory)29 BeforeEach (org.junit.jupiter.api.BeforeEach)20 Config (org.neo4j.configuration.Config)18 Test (org.junit.jupiter.api.Test)15 NeoStores (org.neo4j.kernel.impl.store.NeoStores)14 Path (java.nio.file.Path)10 PageCache (org.neo4j.io.pagecache.PageCache)10 NullLogProvider (org.neo4j.logging.NullLogProvider)10 DatabaseLayout (org.neo4j.io.layout.DatabaseLayout)9 CursorContext (org.neo4j.io.pagecache.context.CursorContext)9 IdGeneratorFactory (org.neo4j.internal.id.IdGeneratorFactory)8 IOException (java.io.IOException)7 FileSystemAbstraction (org.neo4j.io.fs.FileSystemAbstraction)6 RecordFormats (org.neo4j.kernel.impl.store.format.RecordFormats)6 TokenHolders (org.neo4j.token.TokenHolders)6 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)5 DatabaseReadOnlyChecker.writable (org.neo4j.configuration.helpers.DatabaseReadOnlyChecker.writable)5 RecoveryCleanupWorkCollector.immediate (org.neo4j.index.internal.gbptree.RecoveryCleanupWorkCollector.immediate)5 ArrayList (java.util.ArrayList)4