Search in sources :

Example 41 with Subscription

use of io.aeron.Subscription 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 42 with Subscription

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

the class SimpleSubscriber method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 */
public static void main(final String[] args) {
    // Maximum number of message fragments to receive during a single 'poll' operation
    final int fragmentLimitCount = 10;
    // The channel (an endpoint identifier) to receive messages from
    final String channel = "aeron:udp?endpoint=localhost:40123";
    // A unique identifier for a stream within a channel. Stream ID 0 is reserved
    // for internal use and should not be used by applications.
    final int streamId = 10;
    System.out.println("Subscribing to " + channel + " on stream id " + streamId);
    final AtomicBoolean running = new AtomicBoolean(true);
    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));
    // dataHandler method is called for every new datagram received
    final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> {
        final byte[] data = new byte[length];
        buffer.getBytes(offset, data);
        System.out.printf("Received message (%s) to stream %d from session %x term id %x term offset %d (%d@%d)%n", new String(data), streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset);
        // Received the intended message, time to exit the program
        running.set(false);
    };
    // Create a context, needed for client connection to media driver
    // A separate media driver process need to run prior to running this application
    final Aeron.Context ctx = new Aeron.Context();
    // clean up resources when this try block is finished.
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(channel, streamId)) {
        final IdleStrategy idleStrategy = new BackoffIdleStrategy(100, 10, TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100));
        // Try to read the data from subscriber
        while (running.get()) {
            // poll delivers messages to the dataHandler as they arrive
            // and returns number of fragments read, or 0
            // if no data is available.
            final int fragmentsRead = subscription.poll(fragmentHandler, fragmentLimitCount);
            // Give the IdleStrategy a chance to spin/yield/sleep to reduce CPU
            // use if no messages were received.
            idleStrategy.idle(fragmentsRead);
        }
        System.out.println("Shutting down...");
    }
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) Aeron(io.aeron.Aeron) Subscription(io.aeron.Subscription) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FragmentHandler(io.aeron.logbuffer.FragmentHandler) SigInt(org.agrona.concurrent.SigInt) IdleStrategy(org.agrona.concurrent.IdleStrategy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) FragmentHandler(io.aeron.logbuffer.FragmentHandler) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron)

Example 43 with Subscription

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

the class EmbeddedThroughput method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if the thread is interrupted during linger.
 */
public static void main(final String[] args) throws InterruptedException {
    loadPropertiesFiles(args);
    final RateReporter reporter = new RateReporter(TimeUnit.SECONDS.toNanos(1), EmbeddedThroughput::printRate);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    final AtomicBoolean running = new AtomicBoolean(true);
    try (MediaDriver mediaDriver = MediaDriver.launch();
        Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(mediaDriver.aeronDirectoryName()));
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID);
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID)) {
        executor.execute(reporter);
        executor.execute(() -> SamplesUtil.subscriberLoop(rateReporterHandler(reporter), FRAGMENT_COUNT_LIMIT, running).accept(subscription));
        final ContinueBarrier barrier = new ContinueBarrier("Execute again?");
        final IdleStrategy idleStrategy = SampleConfiguration.newIdleStrategy();
        do {
            System.out.format("%nStreaming %,d messages of payload length %d bytes to %s on stream id %d%n", NUMBER_OF_MESSAGES, MESSAGE_LENGTH, CHANNEL, STREAM_ID);
            printingActive = true;
            long backPressureCount = 0;
            for (long i = 0; i < NUMBER_OF_MESSAGES; i++) {
                OFFER_BUFFER.putLong(0, i);
                idleStrategy.reset();
                while (publication.offer(OFFER_BUFFER, 0, MESSAGE_LENGTH, null) < 0) {
                    backPressureCount++;
                    idleStrategy.idle();
                }
            }
            System.out.println("Done streaming. backPressureRatio=" + ((double) backPressureCount / NUMBER_OF_MESSAGES));
            if (LINGER_TIMEOUT_MS > 0) {
                System.out.println("Lingering for " + LINGER_TIMEOUT_MS + " milliseconds...");
                Thread.sleep(LINGER_TIMEOUT_MS);
            }
            printingActive = false;
        } while (barrier.await());
        running.set(false);
        reporter.halt();
        executor.shutdown();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaDriver(io.aeron.driver.MediaDriver) IdleStrategy(org.agrona.concurrent.IdleStrategy) ExecutorService(java.util.concurrent.ExecutorService) ConcurrentPublication(io.aeron.ConcurrentPublication) Publication(io.aeron.Publication) ContinueBarrier(org.agrona.console.ContinueBarrier) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron)

Example 44 with Subscription

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

the class EmbeddedExclusiveSpiedThroughput method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if interrupted during linger.
 */
public static void main(final String[] args) throws InterruptedException {
    loadPropertiesFiles(args);
    final RateReporter reporter = new RateReporter(TimeUnit.SECONDS.toNanos(1), EmbeddedExclusiveSpiedThroughput::printRate);
    final ExecutorService executor = Executors.newFixedThreadPool(2);
    final AtomicBoolean running = new AtomicBoolean(true);
    final MediaDriver.Context ctx = new MediaDriver.Context().spiesSimulateConnection(true);
    try (MediaDriver mediaDriver = MediaDriver.launch(ctx);
        Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(mediaDriver.aeronDirectoryName()));
        Subscription subscription = aeron.addSubscription(CommonContext.SPY_PREFIX + CHANNEL, STREAM_ID);
        ExclusivePublication publication = aeron.addExclusivePublication(CHANNEL, STREAM_ID)) {
        executor.execute(reporter);
        executor.execute(() -> SamplesUtil.subscriberLoop(rateReporterHandler(reporter), FRAGMENT_COUNT_LIMIT, running).accept(subscription));
        final ContinueBarrier barrier = new ContinueBarrier("Execute again?");
        final IdleStrategy idleStrategy = SampleConfiguration.newIdleStrategy();
        do {
            System.out.format("%nStreaming %,d messages of payload length %d bytes to %s on stream id %d%n", NUMBER_OF_MESSAGES, MESSAGE_LENGTH, CHANNEL, STREAM_ID);
            printingActive = true;
            long backPressureCount = 0;
            for (long i = 0; i < NUMBER_OF_MESSAGES; i++) {
                OFFER_BUFFER.putLong(0, i);
                idleStrategy.reset();
                while (publication.offer(OFFER_BUFFER, 0, MESSAGE_LENGTH, null) < 0) {
                    backPressureCount++;
                    idleStrategy.idle();
                }
            }
            System.out.println("Done streaming. backPressureRatio=" + ((double) backPressureCount / NUMBER_OF_MESSAGES));
            if (LINGER_TIMEOUT_MS > 0) {
                System.out.println("Lingering for " + LINGER_TIMEOUT_MS + " milliseconds...");
                Thread.sleep(LINGER_TIMEOUT_MS);
            }
            printingActive = false;
        } while (barrier.await());
        running.set(false);
        reporter.halt();
        executor.shutdown();
    }
}
Also used : CommonContext(io.aeron.CommonContext) IdleStrategy(org.agrona.concurrent.IdleStrategy) ContinueBarrier(org.agrona.console.ContinueBarrier) ExclusivePublication(io.aeron.ExclusivePublication) Aeron(io.aeron.Aeron) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaDriver(io.aeron.driver.MediaDriver) ExecutorService(java.util.concurrent.ExecutorService) Subscription(io.aeron.Subscription)

Example 45 with Subscription

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

the class EmbeddedPingPong method startPong.

private static Thread startPong(final Aeron aeron) {
    return new Thread(() -> {
        System.out.println("Subscribing Ping at " + PING_CHANNEL + " on stream id " + PING_STREAM_ID);
        System.out.println("Publishing Pong at " + PONG_CHANNEL + " on stream id " + PONG_STREAM_ID);
        try (Subscription pingSubscription = aeron.addSubscription(PING_CHANNEL, PING_STREAM_ID);
            Publication pongPublication = EXCLUSIVE_PUBLICATIONS ? aeron.addExclusivePublication(PONG_CHANNEL, PONG_STREAM_ID) : aeron.addPublication(PONG_CHANNEL, PONG_STREAM_ID)) {
            final BufferClaim bufferClaim = new BufferClaim();
            final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> pingHandler(bufferClaim, pongPublication, buffer, offset, length, header);
            while (RUNNING.get()) {
                PING_HANDLER_IDLE_STRATEGY.idle(pingSubscription.poll(fragmentHandler, FRAME_COUNT_LIMIT));
            }
            System.out.println("Shutting down...");
        }
    });
}
Also used : MediaDriver(io.aeron.driver.MediaDriver) Aeron(io.aeron.Aeron) Subscription(io.aeron.Subscription) Image(io.aeron.Image) SystemUtil.loadPropertiesFiles(org.agrona.SystemUtil.loadPropertiesFiles) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FragmentAssembler(io.aeron.FragmentAssembler) BufferUtil(org.agrona.BufferUtil) org.agrona.concurrent(org.agrona.concurrent) BitUtil(org.agrona.BitUtil) TimeUnit(java.util.concurrent.TimeUnit) Histogram(org.HdrHistogram.Histogram) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadingMode(io.aeron.driver.ThreadingMode) io.aeron.logbuffer(io.aeron.logbuffer) ContinueBarrier(org.agrona.console.ContinueBarrier) Publication(io.aeron.Publication) DirectBuffer(org.agrona.DirectBuffer) Publication(io.aeron.Publication) Subscription(io.aeron.Subscription)

Aggregations

Subscription (io.aeron.Subscription)55 Aeron (io.aeron.Aeron)28 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 Publication (io.aeron.Publication)19 MediaDriver (io.aeron.driver.MediaDriver)16 IdleStrategy (org.agrona.concurrent.IdleStrategy)13 FragmentAssembler (io.aeron.FragmentAssembler)12 ContinueBarrier (org.agrona.console.ContinueBarrier)10 FragmentHandler (io.aeron.logbuffer.FragmentHandler)8 TimeUnit (java.util.concurrent.TimeUnit)6 BackoffIdleStrategy (org.agrona.concurrent.BackoffIdleStrategy)5 Test (org.junit.jupiter.api.Test)5 Context (io.aeron.archive.client.AeronArchive.Context)4 io.aeron.logbuffer (io.aeron.logbuffer)4 ExecutorService (java.util.concurrent.ExecutorService)4 SigInt (org.agrona.concurrent.SigInt)4 InOrder (org.mockito.InOrder)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 DirectBuffer (org.agrona.DirectBuffer)3 CommonContext (io.aeron.CommonContext)2