Search in sources :

Example 36 with AeronArchive

use of io.aeron.archive.client.AeronArchive in project Aeron by real-logic.

the class ReplayedBasicSubscriber method findLatestRecording.

private static long findLatestRecording(final AeronArchive archive) {
    final MutableLong lastRecordingId = new MutableLong();
    final RecordingDescriptorConsumer consumer = (controlSessionId, correlationId, recordingId, startTimestamp, stopTimestamp, startPosition, stopPosition, initialTermId, segmentFileLength, termBufferLength, mtuLength, sessionId, streamId, strippedChannel, originalChannel, sourceIdentity) -> lastRecordingId.set(recordingId);
    final long fromRecordingId = 0L;
    final int recordCount = 100;
    final int foundCount = archive.listRecordingsForUri(fromRecordingId, recordCount, CHANNEL, STREAM_ID, consumer);
    if (foundCount == 0) {
        throw new IllegalStateException("no recordings found");
    }
    return lastRecordingId.get();
}
Also used : MutableLong(org.agrona.collections.MutableLong) Subscription(io.aeron.Subscription) RecordingDescriptorConsumer(io.aeron.archive.client.RecordingDescriptorConsumer) SampleConfiguration(io.aeron.samples.SampleConfiguration) AeronArchive(io.aeron.archive.client.AeronArchive) ChannelUri(io.aeron.ChannelUri) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FragmentHandler(io.aeron.logbuffer.FragmentHandler) SamplesUtil(io.aeron.samples.SamplesUtil) SigInt(org.agrona.concurrent.SigInt) MutableLong(org.agrona.collections.MutableLong) RecordingDescriptorConsumer(io.aeron.archive.client.RecordingDescriptorConsumer)

Example 37 with AeronArchive

use of io.aeron.archive.client.AeronArchive in project Aeron by real-logic.

the class RecordedBasicPublisher method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if the thread sleep delay is interrupted.
 */
public static void main(final String[] args) throws InterruptedException {
    System.out.println("Publishing to " + CHANNEL + " on stream id " + STREAM_ID);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    // Create a unique response stream id so not to clash with other archive clients.
    final AeronArchive.Context archiveCtx = new AeronArchive.Context().controlResponseStreamId(AeronArchive.Configuration.controlResponseStreamId() + 1);
    try (AeronArchive archive = AeronArchive.connect(archiveCtx)) {
        archive.startRecording(CHANNEL, STREAM_ID, SourceLocation.LOCAL);
        try (Publication publication = archive.context().aeron().addPublication(CHANNEL, STREAM_ID)) {
            final IdleStrategy idleStrategy = YieldingIdleStrategy.INSTANCE;
            // Wait for recording to have started before publishing.
            final CountersReader counters = archive.context().aeron().countersReader();
            int counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId());
            while (CountersReader.NULL_COUNTER_ID == counterId) {
                if (!running.get()) {
                    return;
                }
                idleStrategy.idle();
                counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId());
            }
            final long recordingId = RecordingPos.getRecordingId(counters, counterId);
            System.out.println("Recording started: recordingId = " + recordingId);
            for (int i = 0; i < NUMBER_OF_MESSAGES && running.get(); i++) {
                final String message = "Hello World! " + i;
                final byte[] messageBytes = message.getBytes();
                BUFFER.putBytes(0, messageBytes);
                System.out.print("Offering " + i + "/" + NUMBER_OF_MESSAGES + " - ");
                final long result = publication.offer(BUFFER, 0, messageBytes.length);
                checkResult(result);
                final String errorMessage = archive.pollForErrorResponse();
                if (null != errorMessage) {
                    throw new IllegalStateException(errorMessage);
                }
                Thread.sleep(TimeUnit.SECONDS.toMillis(1));
            }
            idleStrategy.reset();
            while (counters.getCounterValue(counterId) < publication.position()) {
                if (!RecordingPos.isActive(counters, counterId, recordingId)) {
                    throw new IllegalStateException("recording has stopped unexpectedly: " + recordingId);
                }
                idleStrategy.idle();
            }
        } finally {
            System.out.println("Done sending.");
            archive.stopRecording(CHANNEL, STREAM_ID);
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Publication(io.aeron.Publication) AeronArchive(io.aeron.archive.client.AeronArchive) CountersReader(org.agrona.concurrent.status.CountersReader)

Example 38 with AeronArchive

use of io.aeron.archive.client.AeronArchive in project aeron by real-logic.

the class RecordingLogTest method shouldIgnoreInvalidMidSnapshotInRecoveryPlan.

@Test
void shouldIgnoreInvalidMidSnapshotInRecoveryPlan() {
    final int serviceCount = 1;
    try (RecordingLog recordingLog = new RecordingLog(tempDir, true)) {
        recordingLog.appendSnapshot(1, 1L, 0, 777L, 0, 0);
        recordingLog.appendSnapshot(2, 1L, 0, 777L, 0, SERVICE_ID);
        recordingLog.appendSnapshot(3, 1L, 0, 888L, 0, 0);
        recordingLog.appendSnapshot(4, 1L, 0, 888L, 0, SERVICE_ID);
        recordingLog.appendSnapshot(5, 1L, 0, 999L, 0, 0);
        recordingLog.appendSnapshot(6, 1L, 0, 999L, 0, SERVICE_ID);
        recordingLog.invalidateEntry(1L, 2);
        recordingLog.invalidateEntry(1L, 3);
    }
    try (RecordingLog recordingLog = new RecordingLog(tempDir, true)) {
        final AeronArchive mockArchive = mock(AeronArchive.class);
        final RecordingLog.RecoveryPlan recoveryPlan = recordingLog.createRecoveryPlan(mockArchive, serviceCount, Aeron.NULL_VALUE);
        assertEquals(2, recoveryPlan.snapshots.size());
        assertEquals(SERVICE_ID, recoveryPlan.snapshots.get(0).serviceId);
        assertEquals(6L, recoveryPlan.snapshots.get(0).recordingId);
        assertEquals(0, recoveryPlan.snapshots.get(1).serviceId);
        assertEquals(5L, recoveryPlan.snapshots.get(1).recordingId);
    }
}
Also used : AeronArchive(io.aeron.archive.client.AeronArchive) Test(org.junit.jupiter.api.Test)

Example 39 with AeronArchive

use of io.aeron.archive.client.AeronArchive in project aeron by real-logic.

the class ClusteredServiceAgent method onTakeSnapshot.

private long onTakeSnapshot(final long logPosition, final long leadershipTermId) {
    try (AeronArchive archive = AeronArchive.connect(ctx.archiveContext().clone());
        ExclusivePublication publication = aeron.addExclusivePublication(ctx.snapshotChannel(), ctx.snapshotStreamId())) {
        final String channel = ChannelUri.addSessionId(ctx.snapshotChannel(), publication.sessionId());
        archive.startRecording(channel, ctx.snapshotStreamId(), LOCAL, true);
        final CountersReader counters = aeron.countersReader();
        final int counterId = awaitRecordingCounter(publication.sessionId(), counters, archive);
        final long recordingId = RecordingPos.getRecordingId(counters, counterId);
        snapshotState(publication, logPosition, leadershipTermId);
        checkForClockTick();
        archive.checkForErrorResponse();
        service.onTakeSnapshot(publication);
        awaitRecordingComplete(recordingId, publication.position(), counters, counterId, archive);
        return recordingId;
    } catch (final ArchiveException ex) {
        if (ex.errorCode() == ArchiveException.STORAGE_SPACE) {
            throw new AgentTerminationException(ex);
        }
        throw ex;
    }
}
Also used : ArchiveException(io.aeron.archive.client.ArchiveException) AeronArchive(io.aeron.archive.client.AeronArchive) CountersReader(org.agrona.concurrent.status.CountersReader)

Example 40 with AeronArchive

use of io.aeron.archive.client.AeronArchive in project aeron by real-logic.

the class ArchiveTest method shouldRecoverRecordingWithNonZeroStartPosition.

@Test
public void shouldRecoverRecordingWithNonZeroStartPosition() {
    final MediaDriver.Context driverCtx = new MediaDriver.Context().dirDeleteOnStart(true).threadingMode(ThreadingMode.SHARED);
    final Archive.Context archiveCtx = new Archive.Context().threadingMode(SHARED);
    long resultingPosition;
    final int initialPosition = DataHeaderFlyweight.HEADER_LENGTH * 9;
    final long recordingId;
    try (ArchivingMediaDriver ignore = ArchivingMediaDriver.launch(driverCtx.clone(), archiveCtx.clone());
        AeronArchive archive = AeronArchive.connect()) {
        final int termLength = 128 * 1024;
        final int initialTermId = 29;
        final String channel = new ChannelUriStringBuilder().media(CommonContext.IPC_MEDIA).initialPosition(initialPosition, initialTermId, termLength).build();
        final Publication publication = archive.addRecordedExclusivePublication(channel, 1);
        final DirectBuffer buffer = new UnsafeBuffer("Hello World".getBytes(StandardCharsets.US_ASCII));
        while ((resultingPosition = publication.offer(buffer)) <= 0) {
            Tests.yield();
        }
        final Aeron aeron = archive.context().aeron();
        int counterId;
        final int sessionId = publication.sessionId();
        final CountersReader countersReader = aeron.countersReader();
        while (Aeron.NULL_VALUE == (counterId = RecordingPos.findCounterIdBySession(countersReader, sessionId))) {
            Tests.yield();
        }
        recordingId = RecordingPos.getRecordingId(countersReader, counterId);
        while (countersReader.getCounterValue(counterId) < resultingPosition) {
            Tests.yield();
        }
    }
    try (Catalog catalog = openCatalog(archiveCtx)) {
        final Catalog.CatalogEntryProcessor catalogEntryProcessor = (recordingDescriptorOffset, headerEncoder, headerDecoder, descriptorEncoder, descriptorDecoder) -> descriptorEncoder.stopPosition(Aeron.NULL_VALUE);
        assertTrue(catalog.forEntry(recordingId, catalogEntryProcessor));
    }
    final Archive.Context archiveCtxClone = archiveCtx.clone();
    final MediaDriver.Context driverCtxClone = driverCtx.clone();
    try (ArchivingMediaDriver ignore = ArchivingMediaDriver.launch(driverCtxClone, archiveCtxClone);
        AeronArchive archive = AeronArchive.connect()) {
        assertEquals(initialPosition, archive.getStartPosition(recordingId));
        assertEquals(resultingPosition, archive.getStopPosition(recordingId));
    } finally {
        archiveCtxClone.deleteDirectory();
        driverCtxClone.deleteDirectory();
    }
}
Also used : Context(io.aeron.archive.Archive.Context) CommonContext(io.aeron.CommonContext) RecordingSubscriptionDescriptorConsumer(io.aeron.archive.client.RecordingSubscriptionDescriptorConsumer) IntConsumer(java.util.function.IntConsumer) LOCAL(io.aeron.archive.codecs.SourceLocation.LOCAL) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ChannelUriStringBuilder(io.aeron.ChannelUriStringBuilder) AeronArchive(io.aeron.archive.client.AeronArchive) DEDICATED(io.aeron.archive.ArchiveThreadingMode.DEDICATED) Publication(io.aeron.Publication) MediaDriver(io.aeron.driver.MediaDriver) ManyToOneConcurrentLinkedQueue(org.agrona.concurrent.ManyToOneConcurrentLinkedQueue) AuthorisationServiceSupplier(io.aeron.security.AuthorisationServiceSupplier) InterruptingTestCallback(io.aeron.test.InterruptingTestCallback) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) InterruptAfter(io.aeron.test.InterruptAfter) CountDownLatch(java.util.concurrent.CountDownLatch) TruncateRecordingRequestDecoder(io.aeron.archive.codecs.TruncateRecordingRequestDecoder) EXCLUDE(org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE) DataHeaderFlyweight(io.aeron.protocol.DataHeaderFlyweight) DirectBuffer(org.agrona.DirectBuffer) Mockito.mock(org.mockito.Mockito.mock) Tests(io.aeron.test.Tests) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) CountersReader(org.agrona.concurrent.status.CountersReader) EnumSource(org.junit.jupiter.params.provider.EnumSource) ArrayList(java.util.ArrayList) SystemEpochClock(org.agrona.concurrent.SystemEpochClock) Context(io.aeron.archive.Archive.Context) FrameDescriptor(io.aeron.logbuffer.FrameDescriptor) ValueSource(org.junit.jupiter.params.provider.ValueSource) RecordingPos(io.aeron.archive.status.RecordingPos) Aeron(io.aeron.Aeron) FileStore(java.nio.file.FileStore) SHARED(io.aeron.archive.ArchiveThreadingMode.SHARED) AeronArchive.segmentFileBasePosition(io.aeron.archive.client.AeronArchive.segmentFileBasePosition) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) CommonContext(io.aeron.CommonContext) Checksum(io.aeron.archive.checksum.Checksum) LogBufferDescriptor(io.aeron.logbuffer.LogBufferDescriptor) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MIN_CAPACITY(io.aeron.archive.Catalog.MIN_CAPACITY) ArchiveException(io.aeron.archive.client.ArchiveException) ThreadingMode(io.aeron.driver.ThreadingMode) Assertions(org.junit.jupiter.api.Assertions) AeronArchive(io.aeron.archive.client.AeronArchive) ChannelUriStringBuilder(io.aeron.ChannelUriStringBuilder) Publication(io.aeron.Publication) AeronArchive(io.aeron.archive.client.AeronArchive) Aeron(io.aeron.Aeron) CountersReader(org.agrona.concurrent.status.CountersReader) DirectBuffer(org.agrona.DirectBuffer) MediaDriver(io.aeron.driver.MediaDriver) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) Context(io.aeron.archive.Archive.Context) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

AeronArchive (io.aeron.archive.client.AeronArchive)54 Test (org.junit.jupiter.api.Test)28 MediaDriver (io.aeron.driver.MediaDriver)26 File (java.io.File)17 Aeron (io.aeron.Aeron)14 CommonContext (io.aeron.CommonContext)12 Context (io.aeron.archive.Archive.Context)12 InterruptAfter (io.aeron.test.InterruptAfter)12 Tests (io.aeron.test.Tests)12 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)12 Archive (io.aeron.archive.Archive)10 ArchiveException (io.aeron.archive.client.ArchiveException)10 CountersReader (org.agrona.concurrent.status.CountersReader)10 Publication (io.aeron.Publication)8 FileStore (java.nio.file.FileStore)8 CountDownLatch (java.util.concurrent.CountDownLatch)8 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)8 UnsafeBuffer (org.agrona.concurrent.UnsafeBuffer)8 ChannelUriStringBuilder (io.aeron.ChannelUriStringBuilder)7 DEDICATED (io.aeron.archive.ArchiveThreadingMode.DEDICATED)6