Search in sources :

Example 36 with Publication

use of io.aeron.Publication in project nd4j by deeplearning4j.

the class RoutedTransport method init.

@Override
public void init(@NonNull VoidConfiguration voidConfiguration, @NonNull Clipboard clipboard, @NonNull NodeRole role, @NonNull String localIp, int localPort, short shardIndex) {
    this.nodeRole = role;
    this.clipboard = clipboard;
    this.voidConfiguration = voidConfiguration;
    this.shardIndex = shardIndex;
    this.messages = new LinkedBlockingQueue<>();
    // shutdown hook
    super.init(voidConfiguration, clipboard, role, localIp, localPort, shardIndex);
    setProperty("aeron.client.liveness.timeout", "30000000000");
    context = new Aeron.Context().publicationConnectionTimeout(30000000000L).driverTimeoutMs(30000).keepAliveInterval(100000000);
    driver = MediaDriver.launchEmbedded();
    context.aeronDirectoryName(driver.aeronDirectoryName());
    aeron = Aeron.connect(context);
    if (router == null)
        router = new InterleavedRouter();
    // we skip IPs assign process if they were defined externally
    if (port == 0) {
        ip = localIp;
        port = localPort;
    }
    unicastChannelUri = "aeron:udp?endpoint=" + ip + ":" + port;
    subscriptionForClients = aeron.addSubscription(unicastChannelUri, voidConfiguration.getStreamId());
    // clean shut down
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        CloseHelper.quietClose(aeron);
        CloseHelper.quietClose(driver);
        CloseHelper.quietClose(context);
        CloseHelper.quietClose(subscriptionForClients);
    }));
    messageHandlerForClients = new FragmentAssembler((buffer, offset, length, header) -> jointMessageHandler(buffer, offset, length, header));
    /*
            Now, regardless of current role,
             we set up publication channel to each shard
         */
    String shardChannelUri = null;
    String remoteIp = null;
    int remotePort = 0;
    for (String ip : voidConfiguration.getShardAddresses()) {
        if (ip.contains(":")) {
            shardChannelUri = "aeron:udp?endpoint=" + ip;
            String[] split = ip.split(":");
            remoteIp = split[0];
            remotePort = Integer.valueOf(split[1]);
        } else {
            shardChannelUri = "aeron:udp?endpoint=" + ip + ":" + voidConfiguration.getUnicastPort();
            remoteIp = ip;
            remotePort = voidConfiguration.getUnicastPort();
        }
        Publication publication = aeron.addPublication(shardChannelUri, voidConfiguration.getStreamId());
        RemoteConnection connection = RemoteConnection.builder().ip(remoteIp).port(remotePort).publication(publication).locker(new Object()).build();
        shards.add(connection);
    }
    if (nodeRole == NodeRole.SHARD)
        log.info("Initialized as [{}]; ShardIndex: [{}]; Own endpoint: [{}]", nodeRole, shardIndex, unicastChannelUri);
    else
        log.info("Initialized as [{}]; Own endpoint: [{}]", nodeRole, unicastChannelUri);
    switch(nodeRole) {
        case MASTER:
        case BACKUP:
            {
            }
        case SHARD:
            {
                /*
                    For unicast transport we want to have interconnects between all shards first of all, because we know their IPs in advance.
                    But due to design requirements, clients have the same first step, so it's kinda shared for all states :)
                 */
                /*
                    Next step is connections setup for backup nodes.
                    TODO: to be implemented
                 */
                addClient(ip, port);
            }
            break;
        case CLIENT:
            {
            /*
                    For Clients on unicast transport, we either set up connection to single Shard, or to multiple shards
                    But since this code is shared - we don't do anything here
                 */
            }
            break;
        default:
            throw new ND4JIllegalStateException("Unknown NodeRole being passed: " + nodeRole);
    }
    router.init(voidConfiguration, this);
    this.originatorId = HashUtil.getLongHash(this.getIp() + ":" + this.getPort());
}
Also used : java.util(java.util) HashUtil(org.nd4j.linalg.util.HashUtil) FragmentAssembler(io.aeron.FragmentAssembler) org.nd4j.parameterserver.distributed.messages(org.nd4j.parameterserver.distributed.messages) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IntroductionRequestMessage(org.nd4j.parameterserver.distributed.messages.requests.IntroductionRequestMessage) ClientRouter(org.nd4j.parameterserver.distributed.logic.ClientRouter) InterleavedRouter(org.nd4j.parameterserver.distributed.logic.routing.InterleavedRouter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StringUtils(org.nd4j.linalg.io.StringUtils) Publication(io.aeron.Publication) VoidConfiguration(org.nd4j.parameterserver.distributed.conf.VoidConfiguration) RetransmissionHandler(org.nd4j.parameterserver.distributed.logic.RetransmissionHandler) System.setProperty(java.lang.System.setProperty) CloseHelper(org.agrona.CloseHelper) MediaDriver(io.aeron.driver.MediaDriver) Aeron(io.aeron.Aeron) Nd4j(org.nd4j.linalg.factory.Nd4j) NodeRole(org.nd4j.parameterserver.distributed.enums.NodeRole) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) lombok(lombok) LockSupport(java.util.concurrent.locks.LockSupport) Slf4j(lombok.extern.slf4j.Slf4j) Header(io.aeron.logbuffer.Header) ND4JIllegalStateException(org.nd4j.linalg.exception.ND4JIllegalStateException) Clipboard(org.nd4j.parameterserver.distributed.logic.completion.Clipboard) DirectBuffer(org.agrona.DirectBuffer) InterleavedRouter(org.nd4j.parameterserver.distributed.logic.routing.InterleavedRouter) Publication(io.aeron.Publication) ND4JIllegalStateException(org.nd4j.linalg.exception.ND4JIllegalStateException) FragmentAssembler(io.aeron.FragmentAssembler)

Example 37 with Publication

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

the class ClusterNodeRestartTest method launchService.

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

        private int counterValue = 0;

        public void onSessionMessage(final long clusterSessionId, final long correlationId, final long timestampMs, final DirectBuffer buffer, final int offset, final int length, final Header header) {
            final int sentValue = buffer.getInt(offset);
            assertThat(sentValue, is(counterValue));
            counterValue++;
            serviceState.set(Integer.toString(counterValue));
            msgCounter.getAndIncrement();
        }

        public void onTakeSnapshot(final Publication snapshotPublication) {
            final ExpandableArrayBuffer buffer = new ExpandableArrayBuffer();
            int length = 0;
            buffer.putInt(length, counterValue);
            length += SIZE_OF_INT;
            length += buffer.putIntAscii(length, counterValue);
            snapshotPublication.offer(buffer, 0, length);
        }

        public void onLoadSnapshot(final Image snapshotImage) {
            while (true) {
                final int fragments = snapshotImage.poll((buffer, offset, length, header) -> {
                    counterValue = buffer.getInt(offset);
                    final String s = buffer.getStringWithoutLengthAscii(offset + SIZE_OF_INT, length - SIZE_OF_INT);
                    serviceState.set(s);
                }, 1);
                if (fragments == 1) {
                    break;
                }
                TestUtil.checkInterruptedStatus();
                Thread.yield();
            }
        }
    };
    container = null;
    container = ClusteredServiceContainer.launch(new ClusteredServiceContainer.Context().clusteredService(service).terminationHook(() -> {
    }).errorHandler(Throwable::printStackTrace).deleteDirOnStart(initialLaunch));
}
Also used : DirectBuffer(org.agrona.DirectBuffer) Header(io.aeron.logbuffer.Header) Publication(io.aeron.Publication) ClusteredService(io.aeron.cluster.service.ClusteredService) Image(io.aeron.Image) ExpandableArrayBuffer(org.agrona.ExpandableArrayBuffer)

Example 38 with Publication

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

the class ClusterTest method shouldEchoMessagesViaService.

@Test(timeout = 10_000)
public void shouldEchoMessagesViaService() throws InterruptedException {
    final Aeron aeron = client.context().aeron();
    final SessionDecorator sessionDecorator = new SessionDecorator(client.clusterSessionId());
    final Publication publication = client.ingressPublication();
    final ExpandableArrayBuffer msgBuffer = new ExpandableArrayBuffer();
    final long msgCorrelationId = aeron.nextCorrelationId();
    msgBuffer.putStringWithoutLengthAscii(0, MSG);
    final EchoConsumer consumer = new EchoConsumer(client.egressSubscription());
    final Thread thread = new Thread(consumer);
    thread.setName("consumer");
    thread.setDaemon(true);
    thread.start();
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        while (sessionDecorator.offer(publication, msgCorrelationId, msgBuffer, 0, MSG.length()) < 0) {
            TestUtil.checkInterruptedStatus();
            Thread.yield();
        }
    }
    latch.await();
    for (final EchoService service : echoServices) {
        assertThat(service.messageCount(), is(MESSAGE_COUNT));
    }
}
Also used : Publication(io.aeron.Publication) SessionDecorator(io.aeron.cluster.client.SessionDecorator) Aeron(io.aeron.Aeron) ExpandableArrayBuffer(org.agrona.ExpandableArrayBuffer)

Example 39 with Publication

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

the class MultiNodeTest method shouldBecomeFollowerStaticThreeNodeConfigWithElection.

@Test(timeout = 10_000L)
public void shouldBecomeFollowerStaticThreeNodeConfigWithElection() {
    final ClusteredService mockService = mock(ClusteredService.class);
    final ConsensusModule.Context context = new ConsensusModule.Context().clusterMembers(THREE_NODE_MEMBERS).memberStatusChannel("aeron:udp?endpoint=localhost:9020").appointedLeaderId(1);
    try (ConsensusModuleHarness harness = new ConsensusModuleHarness(context, mockService, mockMemberStatusListeners, true, true)) {
        harness.memberStatusPublisher().requestVote(harness.memberStatusPublication(1), 0, 0, 0, 1);
        harness.awaitMemberStatusMessage(1);
        verify(mockMemberStatusListeners[1]).onVote(0, 0, 0, 1, 0, true);
        final int logSessionId = 123456;
        final ChannelUri channelUri = ChannelUri.parse(context.logChannel());
        channelUri.put(CommonContext.ENDPOINT_PARAM_NAME, harness.member(0).logEndpoint());
        channelUri.put(CommonContext.SESSION_ID_PARAM_NAME, Integer.toString(logSessionId));
        final Publication logPublication = harness.aeron().addExclusivePublication(channelUri.toString(), context.logStreamId());
        harness.memberStatusPublisher().commitPosition(harness.memberStatusPublication(1), 0, 0, 1, logSessionId);
        harness.awaitMemberStatusMessage(1);
        verify(mockMemberStatusListeners[1]).onAppendedPosition(0, 0, 0);
        harness.awaitServiceOnStart();
    }
}
Also used : ChannelUri(io.aeron.ChannelUri) Publication(io.aeron.Publication) ClusteredService(io.aeron.cluster.service.ClusteredService) Test(org.junit.Test)

Example 40 with Publication

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

the class EgressPublisher method sendChallenge.

public boolean sendChallenge(final ClusterSession session, final byte[] encodedChallenge) {
    final Publication publication = session.responsePublication();
    if (!publication.isConnected()) {
        return false;
    }
    challengeEncoder.wrapAndApplyHeader(buffer, 0, messageHeaderEncoder).clusterSessionId(session.id()).correlationId(session.lastCorrelationId()).putEncodedChallenge(encodedChallenge, 0, encodedChallenge.length);
    final int length = MessageHeaderEncoder.ENCODED_LENGTH + challengeEncoder.encodedLength();
    int attempts = SEND_ATTEMPTS;
    do {
        final long result = publication.offer(buffer, 0, length);
        if (result > 0) {
            return true;
        }
    } while (--attempts > 0);
    return false;
}
Also used : Publication(io.aeron.Publication)

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