Java Code Examples for org.agrona.concurrent.status.CountersReader#getCounterValue()

The following examples show how to use org.agrona.concurrent.status.CountersReader#getCounterValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Tests.java    From aeron with Apache License 2.0 6 votes vote down vote up
public static void awaitCounterDelta(
    final CountersReader reader,
    final int counterId,
    final long initialValue,
    final long delta)
{
    final long expectedValue = initialValue + delta;
    final Supplier<String> counterMessage = () ->
        "Timed out waiting for counter '" + reader.getCounterLabel(counterId) +
        "' to increase to at least " + expectedValue;

    while (reader.getCounterValue(counterId) < expectedValue)
    {
        wait(SLEEP_1_MS, counterMessage);
    }
}
 
Example 2
Source File: ClusteredServiceAgent.java    From aeron with Apache License 2.0 6 votes vote down vote up
private void awaitRecordingComplete(
    final long recordingId,
    final long position,
    final CountersReader counters,
    final int counterId,
    final AeronArchive archive)
{
    idleStrategy.reset();
    do
    {
        idle();

        if (!RecordingPos.isActive(counters, counterId, recordingId))
        {
            throw new ClusterException("recording has stopped unexpectedly: " + recordingId);
        }

        archive.checkForErrorResponse();
    }
    while (counters.getCounterValue(counterId) < position);
}
 
Example 3
Source File: TestNode.java    From aeron with Apache License 2.0 6 votes vote down vote up
long appendPosition()
{
    final long recordingId = consensusModule().context().recordingLog().findLastTermRecordingId();
    if (RecordingPos.NULL_RECORDING_ID == recordingId)
    {
        fail("no recording for last term");
    }

    final CountersReader countersReader = countersReader();
    final int counterId = RecordingPos.findCounterIdByRecording(countersReader, recordingId);
    if (NULL_VALUE == counterId)
    {
        fail("recording not active " + recordingId);
    }

    return countersReader.getCounterValue(counterId);
}
 
Example 4
Source File: IndexedReplicatedRecording.java    From aeron with Apache License 2.0 6 votes vote down vote up
static void awaitPosition(final CountersReader counters, final int counterId, final long position)
    throws InterruptedException
{
    while (counters.getCounterValue(counterId) < position)
    {
        if (counters.getCounterState(counterId) != CountersReader.RECORD_ALLOCATED)
        {
            throw new IllegalStateException("count not active: " + counterId);
        }

        Thread.yield();
        if (Thread.interrupted())
        {
            throw new InterruptedException();
        }
    }
}
 
Example 5
Source File: Common.java    From aeron with Apache License 2.0 5 votes vote down vote up
static void awaitPosition(final CountersReader counters, final int counterId, final long position)
{
    while (counters.getCounterValue(counterId) < position)
    {
        if (counters.getCounterState(counterId) != CountersReader.RECORD_ALLOCATED)
        {
            throw new IllegalStateException("count not active: " + counterId);
        }

        Tests.yield();
    }
}
 
Example 6
Source File: DriverNameResolverTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void awaitCounterValue(final String name, final int counterId, final long expectedValue)
{
    final CountersReader countersReader = clients.get(name).countersReader();
    final Supplier<String> messageSupplier =
        () -> "Counter value: " + countersReader.getCounterValue(counterId) + ", expected: " + expectedValue;

    while (countersReader.getCounterValue(counterId) != expectedValue)
    {
        Tests.wait(SLEEP_50_MS, messageSupplier);
    }
}
 
Example 7
Source File: TaggedFlowControlSystemTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void shouldHandleSenderLimitCorrectlyWithMinGroupSize()
{
    final String publisherUri = "aeron:udp?endpoint=224.20.30.39:24326|interface=localhost|fc=tagged,g:123/1";
    final String groupSubscriberUri = "aeron:udp?endpoint=224.20.30.39:24326|interface=localhost|gtag=123";
    final String subscriberUri = "aeron:udp?endpoint=224.20.30.39:24326|interface=localhost";

    driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500));

    launch();

    publication = clientA.addPublication(publisherUri, STREAM_ID);

    final CountersReader countersReader = clientA.countersReader();

    final int senderLimitCounterId = HeartbeatTimestamp.findCounterIdByRegistrationId(
        countersReader, SenderLimit.SENDER_LIMIT_TYPE_ID, publication.registrationId);
    final long currentSenderLimit = countersReader.getCounterValue(senderLimitCounterId);

    subscriptionA = clientA.addSubscription(subscriberUri, STREAM_ID);

    awaitConnectionAndStatusMessages(countersReader, subscriptionA);

    assertEquals(currentSenderLimit, countersReader.getCounterValue(senderLimitCounterId));

    subscriptionB = clientB.addSubscription(groupSubscriberUri, STREAM_ID);

    while (currentSenderLimit == countersReader.getCounterValue(senderLimitCounterId))
    {
        Tests.sleep(1);
    }
}
 
Example 8
Source File: MinFlowControlSystemTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void shouldHandleSenderLimitCorrectlyWithMinGroupSize()
{
    final String publisherUri = "aeron:udp?endpoint=224.20.30.39:24326|interface=localhost|fc=tagged,g:123/1";
    final String groupSubscriberUri = "aeron:udp?endpoint=224.20.30.39:24326|interface=localhost|gtag=123";
    final String subscriberUri = "aeron:udp?endpoint=224.20.30.39:24326|interface=localhost";

    driverBContext.imageLivenessTimeoutNs(TimeUnit.MILLISECONDS.toNanos(500));

    launch();

    subscriptionA = clientA.addSubscription(subscriberUri, STREAM_ID);
    publication = clientA.addPublication(publisherUri, STREAM_ID);

    final CountersReader countersReader = clientA.countersReader();

    final int senderLimitCounterId = HeartbeatTimestamp.findCounterIdByRegistrationId(
        countersReader, SenderLimit.SENDER_LIMIT_TYPE_ID, publication.registrationId);
    final long currentSenderLimit = countersReader.getCounterValue(senderLimitCounterId);

    awaitConnectionAndStatusMessages(countersReader, subscriptionA);
    assertEquals(currentSenderLimit, countersReader.getCounterValue(senderLimitCounterId));

    subscriptionB = clientB.addSubscription(groupSubscriberUri, STREAM_ID);

    while (currentSenderLimit == countersReader.getCounterValue(senderLimitCounterId))
    {
        Tests.sleep(1);
    }
}
 
Example 9
Source File: ConsensusModuleAgent.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void awaitRecordingComplete(
    final long recordingId, final long position, final CountersReader counters, final int counterId)
{
    idleStrategy.reset();
    while (counters.getCounterValue(counterId) < position)
    {
        idle();

        if (!RecordingPos.isActive(counters, counterId, recordingId))
        {
            throw new ClusterException("recording has stopped unexpectedly: " + recordingId);
        }
    }
}
 
Example 10
Source File: LocalSocketAddressStatus.java    From aeron with Apache License 2.0 5 votes vote down vote up
/**
 * Find the list of currently bound local sockets.
 *
 * @param countersReader  for the connected driver.
 * @param channelStatus   value for the channel which aggregates the transports.
 * @param channelStatusId identity of the counter for the channel which aggregates the transports.
 * @return the list of active bound local socket addresses.
 */
public static List<String> findAddresses(
    final CountersReader countersReader, final long channelStatus, final int channelStatusId)
{
    if (channelStatus != ChannelEndpointStatus.ACTIVE)
    {
        return Collections.emptyList();
    }

    final ArrayList<String> bindings = new ArrayList<>(2);
    final DirectBuffer buffer = countersReader.metaDataBuffer();

    for (int i = 0, size = countersReader.maxCounterId(); i < size; i++)
    {
        if (countersReader.getCounterState(i) == RECORD_ALLOCATED &&
            countersReader.getCounterTypeId(i) == LOCAL_SOCKET_ADDRESS_STATUS_TYPE_ID)
        {
            final int recordOffset = CountersReader.metaDataOffset(i);
            final int keyIndex = recordOffset + CountersReader.KEY_OFFSET;

            if (channelStatusId == buffer.getInt(keyIndex + CHANNEL_STATUS_ID_OFFSET) &&
                ChannelEndpointStatus.ACTIVE == countersReader.getCounterValue(i))
            {
                final int length = buffer.getInt(keyIndex + LOCAL_SOCKET_ADDRESS_LENGTH_OFFSET);
                if (length > 0)
                {
                    bindings.add(buffer.getStringWithoutLengthAscii(
                        keyIndex + LOCAL_SOCKET_ADDRESS_STRING_OFFSET, length));
                }
            }
        }
    }

    return bindings;
}
 
Example 11
Source File: ArchiveCreator.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static void awaitPosition(final CountersReader counters, final int counterId, final long position)
{
    while (counters.getCounterValue(counterId) < position)
    {
        if (counters.getCounterState(counterId) != CountersReader.RECORD_ALLOCATED)
        {
            throw new IllegalStateException("count not active: " + counterId);
        }

        Thread.yield();
        checkInterruptStatus();
    }
}
 
Example 12
Source File: EmbeddedReplayThroughput.java    From aeron with Apache License 2.0 5 votes vote down vote up
private void awaitRecordingComplete(final long position, final IdleStrategy idleStrategy)
{
    final CountersReader counters = aeron.countersReader();
    final int counterId = RecordingPos.findCounterIdBySession(counters, publicationSessionId);

    idleStrategy.reset();
    while (counters.getCounterValue(counterId) < position)
    {
        idleStrategy.idle();
    }
}
 
Example 13
Source File: ArchiveTest.java    From aeron with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldRecoverRecordingWithNonZeroStartPosition()
{
    final MediaDriver.Context driverCtx = new MediaDriver.Context()
        .dirDeleteOnStart(true)
        .threadingMode(ThreadingMode.SHARED);
    final Context archiveCtx = new 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 =
            (headerEncoder, headerDecoder, descriptorEncoder, descriptorDecoder) ->
            descriptorEncoder.stopPosition(Aeron.NULL_VALUE);

        assertTrue(catalog.forEntry(recordingId, catalogEntryProcessor));
    }

    final 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();
    }
}
 
Example 14
Source File: RecordedBasicPublisher.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception
{
    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);
        }
    }
}
 
Example 15
Source File: EmbeddedRecordingThroughput.java    From aeron with Apache License 2.0 4 votes vote down vote up
public long streamMessagesForRecording()
{
    try (ExclusivePublication publication = aeron.addExclusivePublication(CHANNEL, STREAM_ID))
    {
        final IdleStrategy idleStrategy = YieldingIdleStrategy.INSTANCE;
        while (!publication.isConnected())
        {
            idleStrategy.idle();
        }

        final long startNs = System.nanoTime();
        final UnsafeBuffer buffer = this.buffer;

        for (long i = 0; i < NUMBER_OF_MESSAGES; i++)
        {
            buffer.putLong(0, i);

            idleStrategy.reset();
            while (publication.offer(buffer, 0, MESSAGE_LENGTH) < 0)
            {
                idleStrategy.idle();
            }
        }

        final long stopPosition = publication.position();
        final CountersReader counters = aeron.countersReader();
        final int counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId());

        idleStrategy.reset();
        while (counters.getCounterValue(counterId) < stopPosition)
        {
            idleStrategy.idle();
        }

        final long durationMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        final double dataRate = (stopPosition * 1000.0d / durationMs) / MEGABYTE;
        final double recordingMb = stopPosition / MEGABYTE;
        final long msgRate = (NUMBER_OF_MESSAGES / durationMs) * 1000L;

        System.out.printf(
            "Recorded %.02f MB @ %.02f MB/s - %,d msg/sec - %d byte payload + 32 byte header%n",
            recordingMb, dataRate, msgRate, MESSAGE_LENGTH);

        return RecordingPos.getRecordingId(counters, counterId);
    }
}