Search in sources :

Example 61 with Publication

use of io.aeron.Publication in project Aeron by real-logic.

the class RecordingDescriptorCollectorTest method createRecordings.

private void createRecordings(final AeronArchive aeronArchive, final int numRecordings) {
    final UnsafeBuffer message = new UnsafeBuffer("this is some data".getBytes());
    for (int i = 0; i < numRecordings; i++) {
        try (Publication publication = aeronArchive.addRecordedPublication("aeron:ipc?ssc=true", 10000 + i)) {
            long expectedPosition;
            while ((expectedPosition = publication.offer(message, 0, message.capacity())) < 0) {
                Tests.yield();
            }
            long recordingId;
            while ((recordingId = aeronArchive.findLastMatchingRecording(0, "aeron:ipc", publication.streamId(), publication.sessionId())) == Aeron.NULL_VALUE) {
                Tests.yield();
            }
            while (expectedPosition < aeronArchive.getRecordingPosition(recordingId)) {
                Tests.yield();
            }
        }
    }
}
Also used : Publication(io.aeron.Publication) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer)

Example 62 with Publication

use of io.aeron.Publication 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 63 with Publication

use of io.aeron.Publication in project aeron by real-logic.

the class AeronArchiveTest method closeOwningAeronClient.

@Test
void closeOwningAeronClient() {
    final long controlSessionId = 42;
    final Aeron.Context aeronContext = mock(Aeron.Context.class);
    when(aeronContext.nanoClock()).thenReturn(SystemNanoClock.INSTANCE);
    when(aeron.context()).thenReturn(aeronContext);
    final IllegalMonitorStateException aeronException = new IllegalMonitorStateException("aeron closed");
    doThrow(aeronException).when(aeron).close();
    final Publication publication = mock(Publication.class);
    when(publication.isConnected()).thenReturn(true);
    doThrow(new IllegalStateException("publication is closed")).when(publication).close();
    final Subscription subscription = mock(Subscription.class);
    when(controlResponsePoller.subscription()).thenReturn(subscription);
    doThrow(new IndexOutOfBoundsException("subscription")).when(subscription).close();
    when(archiveProxy.publication()).thenReturn(publication);
    final IndexOutOfBoundsException closeSessionException = new IndexOutOfBoundsException();
    when(archiveProxy.closeSession(controlSessionId)).thenThrow(closeSessionException);
    final Context context = new Context().aeron(aeron).idleStrategy(NoOpIdleStrategy.INSTANCE).messageTimeoutNs(100).lock(NoOpLock.INSTANCE).errorHandler(errorHandler).ownsAeronClient(true);
    final AeronArchive aeronArchive = new AeronArchive(context, controlResponsePoller, archiveProxy, controlSessionId);
    final IllegalMonitorStateException ex = assertThrows(IllegalMonitorStateException.class, aeronArchive::close);
    assertSame(aeronException, ex);
    final InOrder inOrder = inOrder(errorHandler);
    inOrder.verify(errorHandler).onError(closeSessionException);
    inOrder.verifyNoMoreInteractions();
}
Also used : Context(io.aeron.archive.client.AeronArchive.Context) InOrder(org.mockito.InOrder) Publication(io.aeron.Publication) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron) Test(org.junit.jupiter.api.Test)

Example 64 with Publication

use of io.aeron.Publication in project aeron by real-logic.

the class AeronArchiveTest method closeNotOwningAeronClient.

@Test
void closeNotOwningAeronClient() {
    final long controlSessionId = 42;
    final Aeron.Context aeronContext = mock(Aeron.Context.class);
    when(aeronContext.nanoClock()).thenReturn(SystemNanoClock.INSTANCE);
    when(aeron.context()).thenReturn(aeronContext);
    doThrow(new IllegalMonitorStateException("aeron closed")).when(aeron).close();
    final Publication publication = mock(Publication.class);
    when(publication.isConnected()).thenReturn(true);
    final IllegalStateException publicationException = new IllegalStateException("publication is closed");
    doThrow(publicationException).when(publication).close();
    final Subscription subscription = mock(Subscription.class);
    when(controlResponsePoller.subscription()).thenReturn(subscription);
    final IndexOutOfBoundsException subscriptionException = new IndexOutOfBoundsException("subscription");
    doThrow(subscriptionException).when(subscription).close();
    when(archiveProxy.publication()).thenReturn(publication);
    final IndexOutOfBoundsException closeSessionException = new IndexOutOfBoundsException();
    when(archiveProxy.closeSession(controlSessionId)).thenThrow(closeSessionException);
    final Context context = new Context().aeron(aeron).idleStrategy(NoOpIdleStrategy.INSTANCE).messageTimeoutNs(100).lock(NoOpLock.INSTANCE).errorHandler(errorHandler).ownsAeronClient(false);
    final AeronArchive aeronArchive = new AeronArchive(context, controlResponsePoller, archiveProxy, controlSessionId);
    aeronArchive.close();
    final InOrder inOrder = inOrder(errorHandler);
    inOrder.verify(errorHandler).onError(closeSessionException);
    inOrder.verify(errorHandler).onError(publicationException);
    inOrder.verify(errorHandler).onError(subscriptionException);
    inOrder.verifyNoMoreInteractions();
}
Also used : Context(io.aeron.archive.client.AeronArchive.Context) InOrder(org.mockito.InOrder) Publication(io.aeron.Publication) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron) Test(org.junit.jupiter.api.Test)

Example 65 with Publication

use of io.aeron.Publication in project aeron by real-logic.

the class BasicPublisher 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);
    // If configured to do so, create an embedded media driver within this application rather
    // than relying on an external one.
    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context ctx = new Aeron.Context();
    if (EMBEDDED_MEDIA_DRIVER) {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }
    // clean up resources when this try block is finished
    try (Aeron aeron = Aeron.connect(ctx);
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID)) {
        final UnsafeBuffer buffer = new UnsafeBuffer(BufferUtil.allocateDirectAligned(256, 64));
        for (long i = 0; i < NUMBER_OF_MESSAGES; i++) {
            System.out.print("Offering " + i + "/" + NUMBER_OF_MESSAGES + " - ");
            final int length = buffer.putStringWithoutLengthAscii(0, "Hello World! " + i);
            final long result = publication.offer(buffer, 0, length);
            if (result > 0) {
                System.out.println("yay!");
            } else if (result == Publication.BACK_PRESSURED) {
                System.out.println("Offer failed due to back pressure");
            } else if (result == Publication.NOT_CONNECTED) {
                System.out.println("Offer failed because publisher is not connected to a subscriber");
            } else if (result == Publication.ADMIN_ACTION) {
                System.out.println("Offer failed because of an administration action in the system");
            } else if (result == Publication.CLOSED) {
                System.out.println("Offer failed because publication is closed");
                break;
            } else if (result == Publication.MAX_POSITION_EXCEEDED) {
                System.out.println("Offer failed due to publication reaching its max position");
                break;
            } else {
                System.out.println("Offer failed due to unknown reason: " + result);
            }
            if (!publication.isConnected()) {
                System.out.println("No active subscribers detected");
            }
            Thread.sleep(TimeUnit.SECONDS.toMillis(1));
        }
        System.out.println("Done sending.");
        if (LINGER_TIMEOUT_MS > 0) {
            System.out.println("Lingering for " + LINGER_TIMEOUT_MS + " milliseconds...");
            Thread.sleep(LINGER_TIMEOUT_MS);
        }
    }
    CloseHelper.close(driver);
}
Also used : MediaDriver(io.aeron.driver.MediaDriver) Publication(io.aeron.Publication) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) Aeron(io.aeron.Aeron)

Aggregations

Publication (io.aeron.Publication)71 Aeron (io.aeron.Aeron)37 Test (org.junit.jupiter.api.Test)30 CountersReader (org.agrona.concurrent.status.CountersReader)24 InterruptAfter (io.aeron.test.InterruptAfter)22 MediaDriver (io.aeron.driver.MediaDriver)21 Subscription (io.aeron.Subscription)19 File (java.io.File)14 UnsafeBuffer (org.agrona.concurrent.UnsafeBuffer)12 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)11 ChannelUriStringBuilder (io.aeron.ChannelUriStringBuilder)10 AeronArchive (io.aeron.archive.client.AeronArchive)10 ThreadingMode (io.aeron.driver.ThreadingMode)10 InterruptingTestCallback (io.aeron.test.InterruptingTestCallback)10 Tests (io.aeron.test.Tests)10 ContinueBarrier (org.agrona.console.ContinueBarrier)10 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)10 FragmentAssembler (io.aeron.FragmentAssembler)9 CloseHelper (org.agrona.CloseHelper)9 DirectBuffer (org.agrona.DirectBuffer)9