Search in sources :

Example 36 with FragmentHandler

use of io.aeron.logbuffer.FragmentHandler 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 37 with FragmentHandler

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

the class Ping method main.

/**
 * Main method for launching the process.
 *
 * @param args passed to the process.
 * @throws InterruptedException if the thread is interrupted.
 */
public static void main(final String[] args) throws InterruptedException {
    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context ctx = new Aeron.Context().availableImageHandler(Ping::availablePongImageHandler);
    final FragmentHandler fragmentHandler = new FragmentAssembler(Ping::pongHandler);
    if (EMBEDDED_MEDIA_DRIVER) {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }
    System.out.println("Publishing Ping at " + PING_CHANNEL + " on stream id " + PING_STREAM_ID);
    System.out.println("Subscribing Pong at " + PONG_CHANNEL + " on stream id " + PONG_STREAM_ID);
    System.out.println("Message length of " + MESSAGE_LENGTH + " bytes");
    System.out.println("Using exclusive publications " + EXCLUSIVE_PUBLICATIONS);
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(PONG_CHANNEL, PONG_STREAM_ID);
        Publication publication = EXCLUSIVE_PUBLICATIONS ? aeron.addExclusivePublication(PING_CHANNEL, PING_STREAM_ID) : aeron.addPublication(PING_CHANNEL, PING_STREAM_ID)) {
        System.out.println("Waiting for new image from Pong...");
        LATCH.await();
        System.out.println("Warming up... " + WARMUP_NUMBER_OF_ITERATIONS + " iterations of " + WARMUP_NUMBER_OF_MESSAGES + " messages");
        for (int i = 0; i < WARMUP_NUMBER_OF_ITERATIONS; i++) {
            roundTripMessages(fragmentHandler, publication, subscription, WARMUP_NUMBER_OF_MESSAGES);
            Thread.yield();
        }
        Thread.sleep(100);
        final ContinueBarrier barrier = new ContinueBarrier("Execute again?");
        do {
            HISTOGRAM.reset();
            System.out.println("Pinging " + NUMBER_OF_MESSAGES + " messages");
            roundTripMessages(fragmentHandler, publication, subscription, NUMBER_OF_MESSAGES);
            System.out.println("Histogram of RTT latencies in microseconds.");
            HISTOGRAM.outputPercentileDistribution(System.out, 1000.0);
        } while (barrier.await());
    }
    CloseHelper.close(driver);
}
Also used : MediaDriver(io.aeron.driver.MediaDriver) FragmentHandler(io.aeron.logbuffer.FragmentHandler) ContinueBarrier(org.agrona.console.ContinueBarrier)

Example 38 with FragmentHandler

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

the class ClusterNodeRestartTest method launchService.

private void launchService(final AtomicLong msgCounter) {
    final ClusteredService service = new StubClusteredService() {

        private int nextCorrelationId = 0;

        private int counterValue = 0;

        public void onStart(final Cluster cluster, final Image snapshotImage) {
            super.onStart(cluster, snapshotImage);
            if (null != snapshotImage) {
                final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> {
                    nextCorrelationId = buffer.getInt(offset);
                    offset += SIZE_OF_INT;
                    counterValue = buffer.getInt(offset);
                    offset += SIZE_OF_INT;
                    serviceState.set(buffer.getStringAscii(offset));
                };
                while (true) {
                    final int fragments = snapshotImage.poll(fragmentHandler, 1);
                    if (fragments == 1 || snapshotImage.isEndOfStream()) {
                        break;
                    }
                    idleStrategy.idle();
                }
            }
        }

        public void onSessionMessage(final ClientSession session, final long timestamp, final DirectBuffer buffer, final int offset, final int length, final Header header) {
            final int sentValue = buffer.getInt(offset + MESSAGE_VALUE_OFFSET);
            assertEquals(counterValue, sentValue);
            counterValue++;
            serviceState.set(Integer.toString(counterValue));
            msgCounter.getAndIncrement();
            if (TIMER_MESSAGE_LENGTH == length) {
                final long correlationId = serviceCorrelationId(nextCorrelationId++);
                final long deadlineMs = timestamp + buffer.getLong(offset + TIMER_MESSAGE_DELAY_OFFSET);
                while (!cluster.scheduleTimer(correlationId, deadlineMs)) {
                    idleStrategy.idle();
                }
            }
        }

        public void onTakeSnapshot(final ExclusivePublication snapshotPublication) {
            final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer();
            int length = 0;
            buffer.putInt(length, nextCorrelationId);
            length += SIZE_OF_INT;
            buffer.putInt(length, counterValue);
            length += SIZE_OF_INT;
            length += buffer.putStringAscii(length, Integer.toString(counterValue));
            snapshotPublication.offer(buffer, 0, length);
        }
    };
    container = ClusteredServiceContainer.launch(new ClusteredServiceContainer.Context().clusteredService(service).terminationHook(ClusterTests.NOOP_TERMINATION_HOOK).errorHandler(ClusterTests.errorHandler(0)));
}
Also used : ClusterTests(io.aeron.test.cluster.ClusterTests) AeronCluster(io.aeron.cluster.client.AeronCluster) BeforeEach(org.junit.jupiter.api.BeforeEach) StubClusteredService(io.aeron.test.cluster.StubClusteredService) AtomicCounter(org.agrona.concurrent.status.AtomicCounter) ClusteredServiceContainer(io.aeron.cluster.service.ClusteredServiceContainer) io.aeron.test(io.aeron.test) CountersReader(org.agrona.concurrent.status.CountersReader) CLUSTER_MEMBERS(io.aeron.cluster.ClusterTestConstants.CLUSTER_MEMBERS) ClusteredService(io.aeron.cluster.service.ClusteredService) SIZE_OF_INT(org.agrona.BitUtil.SIZE_OF_INT) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) SIZE_OF_LONG(org.agrona.BitUtil.SIZE_OF_LONG) Publication(io.aeron.Publication) ArchiveThreadingMode(io.aeron.archive.ArchiveThreadingMode) CloseHelper(org.agrona.CloseHelper) ExclusivePublication(io.aeron.ExclusivePublication) PrintStream(java.io.PrintStream) MediaDriver(io.aeron.driver.MediaDriver) Image(io.aeron.Image) Archive(io.aeron.archive.Archive) ExpandableArrayBuffer(org.agrona.ExpandableArrayBuffer) File(java.io.File) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Cluster(io.aeron.cluster.service.Cluster) AfterEach(org.junit.jupiter.api.AfterEach) Header(io.aeron.logbuffer.Header) ClientSession(io.aeron.cluster.service.ClientSession) ThreadingMode(io.aeron.driver.ThreadingMode) Assertions(org.junit.jupiter.api.Assertions) INGRESS_ENDPOINTS(io.aeron.cluster.ClusterTestConstants.INGRESS_ENDPOINTS) FragmentHandler(io.aeron.logbuffer.FragmentHandler) DirectBuffer(org.agrona.DirectBuffer) Mockito.mock(org.mockito.Mockito.mock) AeronCluster(io.aeron.cluster.client.AeronCluster) Cluster(io.aeron.cluster.service.Cluster) StubClusteredService(io.aeron.test.cluster.StubClusteredService) ClusteredService(io.aeron.cluster.service.ClusteredService) ExclusivePublication(io.aeron.ExclusivePublication) Image(io.aeron.Image) ExpandableArrayBuffer(org.agrona.ExpandableArrayBuffer) DirectBuffer(org.agrona.DirectBuffer) Header(io.aeron.logbuffer.Header) FragmentHandler(io.aeron.logbuffer.FragmentHandler) ClientSession(io.aeron.cluster.service.ClientSession) StubClusteredService(io.aeron.test.cluster.StubClusteredService) ClusteredServiceContainer(io.aeron.cluster.service.ClusteredServiceContainer)

Example 39 with FragmentHandler

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

the class SessionSpecificPublicationTest method shouldNotAddPublicationWithSameSessionUntilLingerCompletes.

@ParameterizedTest
@MethodSource("data")
@InterruptAfter(20)
@SlowTest
void shouldNotAddPublicationWithSameSessionUntilLingerCompletes(final ChannelUriStringBuilder builder) {
    final DirectBuffer msg = new UnsafeBuffer(new byte[8]);
    final String channel = builder.sessionId(SESSION_ID_1).build();
    final String subscriptionChannel = "ipc".equals(builder.media()) ? channel : SPY_PREFIX + channel;
    final Publication publication1 = aeron.addPublication(channel, STREAM_ID);
    final Subscription subscription = aeron.addSubscription(subscriptionChannel, STREAM_ID);
    final int positionLimitId = publication1.positionLimitId();
    assertEquals(CountersReader.RECORD_ALLOCATED, aeron.countersReader().getCounterState(positionLimitId));
    while (publication1.offer(msg) < 0) {
        Tests.yieldingIdle("Failed to offer message");
    }
    publication1.close();
    assertThrows(RegistrationException.class, () -> {
        aeron.addPublication(channel, STREAM_ID);
        fail("Exception should have been thrown due lingering publication keeping session id active");
    });
    final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> {
    };
    while (subscription.poll(fragmentHandler, 10) <= 0) {
        Tests.yieldingIdle("Failed to drain message");
    }
    subscription.close();
    while (CountersReader.RECORD_ALLOCATED == aeron.countersReader().getCounterState(positionLimitId)) {
        Tests.yieldingIdle("Publication never cleaned up");
    }
    aeron.addPublication(channel, STREAM_ID);
}
Also used : DirectBuffer(org.agrona.DirectBuffer) MediaDriver(io.aeron.driver.MediaDriver) ErrorHandler(org.agrona.ErrorHandler) RegistrationException(io.aeron.exceptions.RegistrationException) io.aeron.test(io.aeron.test) CountersReader(org.agrona.concurrent.status.CountersReader) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) CommonContext(io.aeron.CommonContext) LogBufferDescriptor(io.aeron.logbuffer.LogBufferDescriptor) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ThreadingMode(io.aeron.driver.ThreadingMode) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Assertions(org.junit.jupiter.api.Assertions) FragmentHandler(io.aeron.logbuffer.FragmentHandler) TestMediaDriver(io.aeron.test.driver.TestMediaDriver) CloseHelper(org.agrona.CloseHelper) DirectBuffer(org.agrona.DirectBuffer) MethodSource(org.junit.jupiter.params.provider.MethodSource) Mockito.mock(org.mockito.Mockito.mock) FragmentHandler(io.aeron.logbuffer.FragmentHandler) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 40 with FragmentHandler

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

the class SpecifiedPositionPublicationTest method shouldStartAtSpecifiedPositionForPublications.

@InterruptAfter(5)
@ParameterizedTest
@CsvSource({ CommonContext.IPC_CHANNEL + ",true", "aeron:udp?endpoint=localhost:24325,true", CommonContext.IPC_CHANNEL + ",false", "aeron:udp?endpoint=localhost:24325,false" })
void shouldStartAtSpecifiedPositionForPublications(final String initialUri, final boolean exclusive) {
    final MediaDriver.Context context = new MediaDriver.Context().dirDeleteOnStart(true).ipcPublicationTermWindowLength(LogBufferDescriptor.TERM_MIN_LENGTH).threadingMode(ThreadingMode.SHARED);
    final DirectBuffer msg = new UnsafeBuffer(new byte[64]);
    final int termLength = 1 << 16;
    final int initialTermId = randomWatcher.random().nextInt();
    final int activeTermId = initialTermId + randomWatcher.random().nextInt(Integer.MAX_VALUE);
    final int positionBitsToShift = LogBufferDescriptor.positionBitsToShift(termLength);
    final int termOffset = randomWatcher.random().nextInt(termLength) & -FrameDescriptor.FRAME_ALIGNMENT;
    final long startPosition = LogBufferDescriptor.computePosition(activeTermId, termOffset, positionBitsToShift, initialTermId);
    final PositionCalculator positionCalculator = new PositionCalculator(startPosition, termLength, termOffset);
    final long nextPosition = positionCalculator.addMessage(DataHeaderFlyweight.HEADER_LENGTH + msg.capacity());
    final String channel = new ChannelUriStringBuilder(initialUri).initialPosition(startPosition, initialTermId, termLength).build();
    final int streamId = 1001;
    final Function<Aeron, Publication> publicationSupplier = exclusive ? (a) -> a.addExclusivePublication(channel, streamId) : (a) -> a.addPublication(channel, streamId);
    try (TestMediaDriver mediaDriver = TestMediaDriver.launch(context, testWatcher);
        Aeron aeron = Aeron.connect(new Aeron.Context().aeronDirectoryName(mediaDriver.aeronDirectoryName()));
        Subscription subscription = aeron.addSubscription(initialUri, streamId);
        Publication publication = publicationSupplier.apply(aeron)) {
        Tests.awaitConnected(subscription);
        Tests.awaitConnected(publication);
        assertEquals(startPosition, publication.position());
        Tests.await(() -> publication.offer(msg) > 0);
        assertEquals(nextPosition, publication.position());
        final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> assertEquals(nextPosition, header.position());
        Tests.await(() -> subscription.poll(fragmentHandler, 1) == 1);
    } finally {
        context.deleteDirectory();
    }
}
Also used : FrameDescriptor(io.aeron.logbuffer.FrameDescriptor) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) MediaDriver(io.aeron.driver.MediaDriver) SystemTestWatcher(io.aeron.test.SystemTestWatcher) Tests(io.aeron.test.Tests) CsvSource(org.junit.jupiter.params.provider.CsvSource) RegistrationException(io.aeron.exceptions.RegistrationException) RandomWatcher(io.aeron.test.RandomWatcher) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) Function(java.util.function.Function) LogBufferDescriptor(io.aeron.logbuffer.LogBufferDescriptor) InterruptAfter(io.aeron.test.InterruptAfter) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ThreadingMode(io.aeron.driver.ThreadingMode) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) DataHeaderFlyweight(io.aeron.protocol.DataHeaderFlyweight) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) FragmentHandler(io.aeron.logbuffer.FragmentHandler) TestMediaDriver(io.aeron.test.driver.TestMediaDriver) DirectBuffer(org.agrona.DirectBuffer) TestMediaDriver(io.aeron.test.driver.TestMediaDriver) DirectBuffer(org.agrona.DirectBuffer) MediaDriver(io.aeron.driver.MediaDriver) TestMediaDriver(io.aeron.test.driver.TestMediaDriver) FragmentHandler(io.aeron.logbuffer.FragmentHandler) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) InterruptAfter(io.aeron.test.InterruptAfter) CsvSource(org.junit.jupiter.params.provider.CsvSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

FragmentHandler (io.aeron.logbuffer.FragmentHandler)70 MediaDriver (io.aeron.driver.MediaDriver)50 InterruptAfter (io.aeron.test.InterruptAfter)44 UnsafeBuffer (org.agrona.concurrent.UnsafeBuffer)42 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)42 Tests (io.aeron.test.Tests)40 Test (org.junit.jupiter.api.Test)40 InterruptingTestCallback (io.aeron.test.InterruptingTestCallback)36 TestMediaDriver (io.aeron.test.driver.TestMediaDriver)36 RegisterExtension (org.junit.jupiter.api.extension.RegisterExtension)36 SystemTestWatcher (io.aeron.test.SystemTestWatcher)34 ThreadingMode (io.aeron.driver.ThreadingMode)30 AfterEach (org.junit.jupiter.api.AfterEach)30 CloseHelper (org.agrona.CloseHelper)28 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)28 MutableInteger (org.agrona.collections.MutableInteger)22 DirectBuffer (org.agrona.DirectBuffer)20 Assertions (org.junit.jupiter.api.Assertions)20 TimeUnit (java.util.concurrent.TimeUnit)18 MethodSource (org.junit.jupiter.params.provider.MethodSource)18