use of java.time.Clock in project neo4j by neo4j.
the class DelayedBufferTest method shouldHandleTheWholeWorkloadShebang.
@Test
public void shouldHandleTheWholeWorkloadShebang() throws Throwable {
// GIVEN
final int size = 1_000;
final long bufferTime = 3;
VerifyingConsumer consumer = new VerifyingConsumer(size);
final Clock clock = Clocks.systemClock();
Supplier<Long> chunkThreshold = clock::millis;
Predicate<Long> safeThreshold = time -> clock.millis() - bufferTime >= time;
final DelayedBuffer<Long> buffer = new DelayedBuffer<>(chunkThreshold, safeThreshold, 10, consumer);
MaintenanceThread maintenance = new MaintenanceThread(buffer, 5);
Race adders = new Race();
final int numberOfAdders = 20;
final byte[] offeredIds = new byte[size];
for (int i = 0; i < numberOfAdders; i++) {
final int finalI = i;
adders.addContestant(new Runnable() {
@Override
public void run() {
for (int j = 0; j < size; j++) {
if (j % numberOfAdders == finalI) {
buffer.offer(j);
offeredIds[j] = 1;
parkNanos(MILLISECONDS.toNanos(current().nextInt(2)));
}
}
}
});
}
// WHEN (multi-threadded) offering of ids
adders.go();
// ... ensuring the test is sane itself (did we really offer all these IDs?)
for (int i = 0; i < size; i++) {
assertEquals("ID " + i, (byte) 1, offeredIds[i]);
}
maintenance.halt();
buffer.close();
// THEN
consumer.assertHaveOnlySeenRange(0, size - 1);
}
use of java.time.Clock in project neo4j by neo4j.
the class RotationTimerFactoryTest method testTimer.
@Test
public void testTimer() throws Exception {
// GIVEN
Clock fixedClock = Clock.fixed(Instant.ofEpochMilli(10000), ZoneOffset.UTC);
// WHEN
RotationTimerFactory timerFactory = new RotationTimerFactory(fixedClock, 1000);
RotationTimerFactory.RotationTimer timer = timerFactory.createTimer();
RotationTimerFactory.RotationTimer anotherTimer = timerFactory.createTimer();
// THEN
Assert.assertFalse(timer.isTimedOut());
Assert.assertEquals(0, timer.getElapsedTimeMillis());
Assert.assertNotSame("Factory should construct different timers", timer, anotherTimer);
// WHEN
FakeClock fakeClock = Clocks.fakeClock();
RotationTimerFactory fakeTimerFactory = new RotationTimerFactory(fakeClock, 1000);
RotationTimerFactory.RotationTimer fakeTimer = fakeTimerFactory.createTimer();
fakeClock.forward(1001, TimeUnit.MILLISECONDS);
Assert.assertTrue(fakeTimer.isTimedOut());
Assert.assertEquals(1001, fakeTimer.getElapsedTimeMillis());
}
use of java.time.Clock in project neo4j by neo4j.
the class AvailabilityGuardTest method givenAccessGuardWithConditionWhenShutdownThenInstantlyDenyAccess.
@Test
public void givenAccessGuardWithConditionWhenShutdownThenInstantlyDenyAccess() throws Exception {
// Given
Clock clock = Mockito.mock(Clock.class);
final AvailabilityGuard availabilityGuard = new AvailabilityGuard(clock, NullLog.getInstance());
availabilityGuard.require(REQUIREMENT_1);
// When
availabilityGuard.shutdown();
// Then
assertFalse(availabilityGuard.isAvailable(1000));
verifyZeroInteractions(clock);
}
use of java.time.Clock in project neo4j by neo4j.
the class BoltKernelExtension method newInstance.
@Override
public Lifecycle newInstance(KernelContext context, Dependencies dependencies) throws Throwable {
Config config = dependencies.config();
GraphDatabaseService gdb = dependencies.db();
GraphDatabaseAPI api = (GraphDatabaseAPI) gdb;
LogService logService = dependencies.logService();
Clock clock = dependencies.clock();
Log log = logService.getInternalLog(WorkerFactory.class);
LifeSupport life = new LifeSupport();
JobScheduler scheduler = dependencies.scheduler();
InternalLoggerFactory.setDefaultFactory(new Netty4LoggerFactory(logService.getInternalLogProvider()));
Authentication authentication = authentication(dependencies.authManager(), dependencies.userManagerSupplier());
BoltFactory boltFactory = life.add(new BoltFactoryImpl(api, dependencies.usageData(), logService, dependencies.txBridge(), authentication, dependencies.sessionTracker(), config));
WorkerFactory workerFactory = createWorkerFactory(boltFactory, scheduler, dependencies, logService, clock);
List<ProtocolInitializer> connectors = config.enabledBoltConnectors().stream().map((connConfig) -> {
ListenSocketAddress listenAddress = config.get(connConfig.listen_address);
AdvertisedSocketAddress advertisedAddress = config.get(connConfig.advertised_address);
SslContext sslCtx;
boolean requireEncryption;
final BoltConnector.EncryptionLevel encryptionLevel = config.get(connConfig.encryption_level);
switch(encryptionLevel) {
case REQUIRED:
// Encrypted connections are mandatory, a self-signed certificate may be generated.
requireEncryption = true;
sslCtx = createSslContext(config, log, advertisedAddress);
break;
case OPTIONAL:
// Encrypted connections are optional, a self-signed certificate may be generated.
requireEncryption = false;
sslCtx = createSslContext(config, log, advertisedAddress);
break;
case DISABLED:
// Encryption is turned off, no self-signed certificate will be generated.
requireEncryption = false;
sslCtx = null;
break;
default:
// In the unlikely event that we happen to fall through to the default option here,
// there is a mismatch between the BoltConnector.EncryptionLevel enum and the options
// handled in this switch statement. In this case, we'll log a warning and default to
// disabling encryption, since this mirrors the functionality introduced in 3.0.
log.warn(format("Unhandled encryption level %s - assuming DISABLED.", encryptionLevel.name()));
requireEncryption = false;
sslCtx = null;
break;
}
final Map<Long, BiFunction<Channel, Boolean, BoltProtocol>> versions = newVersions(logService, workerFactory);
return new SocketTransport(listenAddress, sslCtx, requireEncryption, logService.getInternalLogProvider(), versions);
}).collect(toList());
if (connectors.size() > 0 && !config.get(GraphDatabaseSettings.disconnected)) {
life.add(new NettyServer(scheduler.threadFactory(boltNetworkIO), connectors));
log.info("Bolt Server extension loaded.");
for (ProtocolInitializer connector : connectors) {
logService.getUserLog(WorkerFactory.class).info("Bolt enabled on %s.", connector.address());
}
}
return life;
}
use of java.time.Clock in project neo4j by neo4j.
the class NeoStoreDataSource method buildTransactionLogs.
private NeoStoreTransactionLogModule buildTransactionLogs(File storeDir, Config config, LogProvider logProvider, JobScheduler scheduler, FileSystemAbstraction fileSystemAbstraction, StorageEngine storageEngine, LogEntryReader<ReadableClosablePositionAwareChannel> logEntryReader, SynchronizedArrayIdOrderingQueue legacyIndexTransactionOrdering, TransactionIdStore transactionIdStore, LogVersionRepository logVersionRepository) {
TransactionMetadataCache transactionMetadataCache = new TransactionMetadataCache(100_000);
LogHeaderCache logHeaderCache = new LogHeaderCache(1000);
final PhysicalLogFiles logFiles = new PhysicalLogFiles(storeDir, PhysicalLogFile.DEFAULT_NAME, fileSystemAbstraction);
final PhysicalLogFile logFile = life.add(new PhysicalLogFile(fileSystemAbstraction, logFiles, config.get(GraphDatabaseSettings.logical_log_rotation_threshold), transactionIdStore::getLastCommittedTransactionId, logVersionRepository, physicalLogMonitor, logHeaderCache));
final PhysicalLogFileInformation.LogVersionToTimestamp logInformation = version -> {
LogPosition position = LogPosition.start(version);
try (ReadableLogChannel channel = logFile.getReader(position)) {
LogEntry entry;
while ((entry = logEntryReader.readLogEntry(channel)) != null) {
if (entry instanceof LogEntryStart) {
return entry.<LogEntryStart>as().getTimeWritten();
}
}
}
return -1;
};
final LogFileInformation logFileInformation = new PhysicalLogFileInformation(logFiles, logHeaderCache, transactionIdStore::getLastCommittedTransactionId, logInformation);
if (config.get(GraphDatabaseFacadeFactory.Configuration.ephemeral)) {
config = config.withDefaults(stringMap(GraphDatabaseSettings.keep_logical_logs.name(), "1 files"));
}
String pruningConf = config.get(GraphDatabaseSettings.keep_logical_logs);
LogPruneStrategy logPruneStrategy = fromConfigValue(fs, logFileInformation, logFiles, pruningConf);
final LogPruning logPruning = new LogPruningImpl(logPruneStrategy, logProvider);
final LogRotation logRotation = new LogRotationImpl(monitors.newMonitor(LogRotation.Monitor.class), logFile, databaseHealth);
final TransactionAppender appender = life.add(new BatchingTransactionAppender(logFile, logRotation, transactionMetadataCache, transactionIdStore, legacyIndexTransactionOrdering, databaseHealth));
final LogicalTransactionStore logicalTransactionStore = new PhysicalLogicalTransactionStore(logFile, transactionMetadataCache, logEntryReader);
int txThreshold = config.get(GraphDatabaseSettings.check_point_interval_tx);
final CountCommittedTransactionThreshold countCommittedTransactionThreshold = new CountCommittedTransactionThreshold(txThreshold);
long timeMillisThreshold = config.get(GraphDatabaseSettings.check_point_interval_time);
TimeCheckPointThreshold timeCheckPointThreshold = new TimeCheckPointThreshold(timeMillisThreshold, clock);
CheckPointThreshold threshold = CheckPointThresholds.or(countCommittedTransactionThreshold, timeCheckPointThreshold);
final CheckPointerImpl checkPointer = new CheckPointerImpl(transactionIdStore, threshold, storageEngine, logPruning, appender, databaseHealth, logProvider, tracers.checkPointTracer, ioLimiter, storeCopyCheckPointMutex);
long recurringPeriod = Math.min(timeMillisThreshold, TimeUnit.SECONDS.toMillis(10));
CheckPointScheduler checkPointScheduler = new CheckPointScheduler(checkPointer, scheduler, recurringPeriod, databaseHealth);
life.add(checkPointer);
life.add(checkPointScheduler);
return new NeoStoreTransactionLogModule(logicalTransactionStore, logFileInformation, logFiles, logFile, logRotation, checkPointer, appender, legacyIndexTransactionOrdering);
}
Aggregations