Search in sources :

Example 16 with Message

use of org.jgroups.Message in project camel by apache.

the class JGroupsComponentWithChannelPropertiesTest method shouldConsumeMulticastedMessage.

@Test
public void shouldConsumeMulticastedMessage() throws Exception {
    // Given
    MockEndpoint mockEndpoint = getMockEndpoint("mock:default");
    mockEndpoint.setExpectedMessageCount(1);
    mockEndpoint.expectedBodiesReceived(MESSAGE);
    // When
    Message message = new Message(null, MESSAGE);
    message.setSrc(null);
    clientChannel.send(message);
    // Then
    mockEndpoint.assertIsSatisfied();
}
Also used : Message(org.jgroups.Message) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Test(org.junit.Test)

Example 17 with Message

use of org.jgroups.Message in project camel by apache.

the class JGroupsProducerTest method doPreSetup.

// Fixture setup
@Override
protected void doPreSetup() throws Exception {
    super.doPreSetup();
    channel = new JChannel();
    channel.setReceiver(new ReceiverAdapter() {

        @Override
        public void receive(Message msg) {
            messageReceived = msg.getObject();
        }
    });
    channel.connect(CLUSTER_NAME);
}
Also used : JChannel(org.jgroups.JChannel) Message(org.jgroups.Message) ReceiverAdapter(org.jgroups.ReceiverAdapter)

Example 18 with Message

use of org.jgroups.Message in project wildfly by wildfly.

the class JChannelFactory method createChannel.

@Override
public Channel createChannel(String id) throws Exception {
    JChannel channel = new JChannel(false);
    ProtocolStack stack = new ProtocolStack();
    channel.setProtocolStack(stack);
    stack.addProtocol(this.configuration.getTransport().createProtocol());
    stack.addProtocols(this.configuration.getProtocols().stream().map(ProtocolConfiguration::createProtocol).collect(Collectors.toList()));
    RelayConfiguration relay = this.configuration.getRelay();
    if (relay != null) {
        stack.addProtocol(relay.createProtocol());
    }
    // Add implicit FORK to the top of the stack
    FORK fork = new FORK();
    fork.setUnknownForkHandler(new UnknownForkHandler() {

        private final short id = ClassConfigurator.getProtocolId(RequestCorrelator.class);

        @Override
        public Object handleUnknownForkStack(Message message, String forkStackId) {
            return this.handle(message);
        }

        @Override
        public Object handleUnknownForkChannel(Message message, String forkChannelId) {
            return this.handle(message);
        }

        private Object handle(Message message) {
            Header header = (Header) message.getHeader(this.id);
            // If this is a request expecting a response, don't leave the requester hanging - send an identifiable response on which it can filter
            if ((header != null) && (header.type == Header.REQ) && header.rspExpected()) {
                Message response = message.makeReply().setFlag(message.getFlags()).clearFlag(Message.Flag.RSVP, Message.Flag.SCOPED);
                response.putHeader(FORK.ID, message.getHeader(FORK.ID));
                response.putHeader(this.id, new Header(Header.RSP, header.req_id, header.corrId));
                response.setBuffer(UNKNOWN_FORK_RESPONSE.array());
                channel.down(new Event(Event.MSG, response));
            }
            return null;
        }
    });
    stack.addProtocol(fork);
    stack.init();
    channel.setName(this.configuration.getNodeName());
    TransportConfiguration.Topology topology = this.configuration.getTransport().getTopology();
    if (topology != null) {
        channel.addAddressGenerator(new TopologyAddressGenerator(topology));
    }
    return channel;
}
Also used : JChannel(org.jgroups.JChannel) FORK(org.jgroups.protocols.FORK) Message(org.jgroups.Message) TransportConfiguration(org.wildfly.clustering.jgroups.spi.TransportConfiguration) UnknownForkHandler(org.jgroups.fork.UnknownForkHandler) ProtocolConfiguration(org.wildfly.clustering.jgroups.spi.ProtocolConfiguration) Header(org.jgroups.blocks.RequestCorrelator.Header) ProtocolStack(org.jgroups.stack.ProtocolStack) RelayConfiguration(org.wildfly.clustering.jgroups.spi.RelayConfiguration) Event(org.jgroups.Event)

Example 19 with Message

use of org.jgroups.Message in project wildfly by wildfly.

the class ChannelCommandDispatcher method submitOnCluster.

@Override
public <R> Map<Node, Future<R>> submitOnCluster(Command<R, ? super C> command, Node... excludedNodes) throws CommandDispatcherException {
    Map<Node, Future<R>> results = new ConcurrentHashMap<>();
    FutureListener<RspList<R>> listener = future -> {
        try {
            future.get().keySet().stream().map(address -> this.factory.createNode(address)).forEach(node -> results.remove(node));
        } catch (CancellationException e) {
        } catch (ExecutionException e) {
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    };
    Message message = this.createMessage(command);
    RequestOptions options = this.createRequestOptions(excludedNodes);
    try {
        Future<? extends Map<Address, Rsp<R>>> futureResponses = this.dispatcher.castMessageWithFuture(null, message, options, listener);
        Set<Node> excluded = (excludedNodes != null) ? new HashSet<>(Arrays.asList(excludedNodes)) : Collections.<Node>emptySet();
        for (Address address : this.dispatcher.getChannel().getView().getMembers()) {
            Node node = this.factory.createNode(address);
            if (!excluded.contains(node)) {
                Future<R> future = new Future<R>() {

                    @Override
                    public boolean cancel(boolean mayInterruptIfRunning) {
                        return futureResponses.cancel(mayInterruptIfRunning);
                    }

                    @Override
                    public R get() throws InterruptedException, ExecutionException {
                        Map<Address, Rsp<R>> responses = futureResponses.get();
                        Rsp<R> response = responses.get(address);
                        if (response == null) {
                            throw new CancellationException();
                        }
                        return createCommandResponse(response).get();
                    }

                    @Override
                    public R get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                        Map<Address, Rsp<R>> responses = futureResponses.get(timeout, unit);
                        Rsp<R> response = responses.get(address);
                        if (response == null) {
                            throw new CancellationException();
                        }
                        return createCommandResponse(response).get();
                    }

                    @Override
                    public boolean isCancelled() {
                        return futureResponses.isCancelled();
                    }

                    @Override
                    public boolean isDone() {
                        return futureResponses.isDone();
                    }
                };
                results.put(node, future);
            }
        }
        return results;
    } catch (Exception e) {
        throw new CommandDispatcherException(e);
    }
}
Also used : Arrays(java.util.Arrays) Rsp(org.jgroups.util.Rsp) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) FutureListener(org.jgroups.util.FutureListener) HashSet(java.util.HashSet) CommandDispatcher(org.wildfly.clustering.dispatcher.CommandDispatcher) Command(org.wildfly.clustering.dispatcher.Command) Future(java.util.concurrent.Future) RspFilter(org.jgroups.blocks.RspFilter) RequestOptions(org.jgroups.blocks.RequestOptions) Map(java.util.Map) RspList(org.jgroups.util.RspList) Address(org.jgroups.Address) NodeFactory(org.wildfly.clustering.group.NodeFactory) CancellationException(java.util.concurrent.CancellationException) ResponseMode(org.jgroups.blocks.ResponseMode) CommandResponse(org.wildfly.clustering.dispatcher.CommandResponse) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Addressable(org.wildfly.clustering.server.Addressable) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Message(org.jgroups.Message) Node(org.wildfly.clustering.group.Node) CommandDispatcherException(org.wildfly.clustering.dispatcher.CommandDispatcherException) Collections(java.util.Collections) MessageDispatcher(org.jgroups.blocks.MessageDispatcher) Message(org.jgroups.Message) Address(org.jgroups.Address) RequestOptions(org.jgroups.blocks.RequestOptions) CommandDispatcherException(org.wildfly.clustering.dispatcher.CommandDispatcherException) Node(org.wildfly.clustering.group.Node) RspList(org.jgroups.util.RspList) Rsp(org.jgroups.util.Rsp) TimeoutException(java.util.concurrent.TimeoutException) CancellationException(java.util.concurrent.CancellationException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) CommandDispatcherException(org.wildfly.clustering.dispatcher.CommandDispatcherException) CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ExecutionException(java.util.concurrent.ExecutionException)

Example 20 with Message

use of org.jgroups.Message in project geode by apache.

the class JGroupsMessenger method send.

private Set<InternalDistributedMember> send(DistributionMessage msg, boolean reliably) {
    // perform the same jgroups messaging as in 8.2's GMSMembershipManager.send() method
    // BUT: when marshalling messages we need to include the version of the product and
    // localAddress at the beginning of the message. These should be used in the receiver
    // code to create a versioned input stream, read the sender address, then read the message
    // and set its sender address
    DMStats theStats = services.getStatistics();
    NetView oldView = this.view;
    if (!myChannel.isConnected()) {
        logger.info("JGroupsMessenger channel is closed - messaging is not possible");
        throw new DistributedSystemDisconnectedException("Distributed System is shutting down");
    }
    filterOutgoingMessage(msg);
    // the message's processor if necessary
    if ((msg instanceof DirectReplyMessage) && msg.isDirectAck() && msg.getProcessorId() <= 0) {
        ((DirectReplyMessage) msg).registerProcessor();
    }
    InternalDistributedMember[] destinations = msg.getRecipients();
    boolean allDestinations = msg.forAll();
    boolean useMcast = false;
    if (services.getConfig().getTransport().isMcastEnabled()) {
        if (msg.getMulticast() || allDestinations) {
            useMcast = services.getManager().isMulticastAllowed();
        }
    }
    if (logger.isDebugEnabled() && reliably) {
        String recips = useMcast ? "multicast" : Arrays.toString(msg.getRecipients());
        logger.debug("sending via JGroups: [{}] recipients: {}", msg, recips);
    }
    JGAddress local = this.jgAddress;
    if (useMcast) {
        long startSer = theStats.startMsgSerialization();
        Message jmsg = createJGMessage(msg, local, Version.CURRENT_ORDINAL);
        theStats.endMsgSerialization(startSer);
        Exception problem;
        try {
            jmsg.setTransientFlag(TransientFlag.DONT_LOOPBACK);
            if (!reliably) {
                jmsg.setFlag(Message.Flag.NO_RELIABILITY);
            }
            theStats.incSentBytes(jmsg.getLength());
            logger.trace("Sending JGroups message: {}", jmsg);
            myChannel.send(jmsg);
        } catch (Exception e) {
            logger.debug("caught unexpected exception", e);
            Throwable cause = e.getCause();
            if (cause instanceof ForcedDisconnectException) {
                problem = (Exception) cause;
            } else {
                problem = e;
            }
            if (services.getShutdownCause() != null) {
                Throwable shutdownCause = services.getShutdownCause();
                // problem.
                if (shutdownCause instanceof ForcedDisconnectException) {
                    problem = (Exception) shutdownCause;
                } else {
                    Throwable ne = problem;
                    while (ne.getCause() != null) {
                        ne = ne.getCause();
                    }
                    ne.initCause(services.getShutdownCause());
                }
            }
            final String channelClosed = LocalizedStrings.GroupMembershipService_CHANNEL_CLOSED.toLocalizedString();
            // services.getManager().membershipFailure(channelClosed, problem);
            throw new DistributedSystemDisconnectedException(channelClosed, problem);
        }
    } else // useMcast
    {
        // ! useMcast
        int len = destinations.length;
        // explicit list of members
        List<GMSMember> calculatedMembers;
        // == calculatedMembers.len
        int calculatedLen;
        if (len == 1 && destinations[0] == DistributionMessage.ALL_RECIPIENTS) {
            // send to all
            // Grab a copy of the current membership
            NetView v = services.getJoinLeave().getView();
            // Construct the list
            calculatedLen = v.size();
            calculatedMembers = new LinkedList<GMSMember>();
            for (int i = 0; i < calculatedLen; i++) {
                InternalDistributedMember m = (InternalDistributedMember) v.get(i);
                calculatedMembers.add((GMSMember) m.getNetMember());
            }
        } else // send to all
        {
            // send to explicit list
            calculatedLen = len;
            calculatedMembers = new LinkedList<GMSMember>();
            for (int i = 0; i < calculatedLen; i++) {
                calculatedMembers.add((GMSMember) destinations[i].getNetMember());
            }
        }
        // send to explicit list
        Int2ObjectOpenHashMap<Message> messages = new Int2ObjectOpenHashMap<>();
        long startSer = theStats.startMsgSerialization();
        boolean firstMessage = true;
        for (GMSMember mbr : calculatedMembers) {
            short version = mbr.getVersionOrdinal();
            if (!messages.containsKey(version)) {
                Message jmsg = createJGMessage(msg, local, version);
                messages.put(version, jmsg);
                if (firstMessage) {
                    theStats.incSentBytes(jmsg.getLength());
                    firstMessage = false;
                }
            }
        }
        theStats.endMsgSerialization(startSer);
        Collections.shuffle(calculatedMembers);
        int i = 0;
        for (GMSMember mbr : calculatedMembers) {
            JGAddress to = new JGAddress(mbr);
            short version = mbr.getVersionOrdinal();
            Message jmsg = messages.get(version);
            Exception problem = null;
            try {
                Message tmp = (i < (calculatedLen - 1)) ? jmsg.copy(true) : jmsg;
                if (!reliably) {
                    jmsg.setFlag(Message.Flag.NO_RELIABILITY);
                }
                tmp.setDest(to);
                tmp.setSrc(this.jgAddress);
                logger.trace("Unicasting to {}", to);
                myChannel.send(tmp);
            } catch (Exception e) {
                problem = e;
            }
            if (problem != null) {
                Throwable cause = services.getShutdownCause();
                if (cause != null) {
                    // problem.
                    if (cause instanceof ForcedDisconnectException) {
                        problem = (Exception) cause;
                    } else {
                        Throwable ne = problem;
                        while (ne.getCause() != null) {
                            ne = ne.getCause();
                        }
                        ne.initCause(cause);
                    }
                }
                final String channelClosed = LocalizedStrings.GroupMembershipService_CHANNEL_CLOSED.toLocalizedString();
                // services.getManager().membershipFailure(channelClosed, problem);
                throw new DistributedSystemDisconnectedException(channelClosed, problem);
            }
        }
    // send individually
    }
    // (i.e., left the view), we signal it here.
    if (msg.forAll()) {
        return Collections.emptySet();
    }
    Set<InternalDistributedMember> result = new HashSet<>();
    NetView newView = this.view;
    if (newView != null && newView != oldView) {
        for (InternalDistributedMember d : destinations) {
            if (!newView.contains(d)) {
                logger.debug("messenger: member has left the view: {}  view is now {}", d, newView);
                result.add(d);
            }
        }
    }
    return result;
}
Also used : Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) DMStats(org.apache.geode.distributed.internal.DMStats) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) DistributionMessage(org.apache.geode.distributed.internal.DistributionMessage) JoinRequestMessage(org.apache.geode.distributed.internal.membership.gms.messages.JoinRequestMessage) DirectReplyMessage(org.apache.geode.internal.cache.DirectReplyMessage) JoinResponseMessage(org.apache.geode.distributed.internal.membership.gms.messages.JoinResponseMessage) LocalizedMessage(org.apache.geode.internal.logging.log4j.LocalizedMessage) Message(org.jgroups.Message) HighPriorityDistributionMessage(org.apache.geode.distributed.internal.HighPriorityDistributionMessage) ForcedDisconnectException(org.apache.geode.ForcedDisconnectException) GMSMember(org.apache.geode.distributed.internal.membership.gms.GMSMember) NetView(org.apache.geode.distributed.internal.membership.NetView) MemberShunnedException(org.apache.geode.internal.tcp.MemberShunnedException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ForcedDisconnectException(org.apache.geode.ForcedDisconnectException) GemFireIOException(org.apache.geode.GemFireIOException) SystemConnectException(org.apache.geode.SystemConnectException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) DirectReplyMessage(org.apache.geode.internal.cache.DirectReplyMessage) InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) HashSet(java.util.HashSet)

Aggregations

Message (org.jgroups.Message)26 Test (org.junit.Test)11 DistributionMessage (org.apache.geode.distributed.internal.DistributionMessage)7 JoinRequestMessage (org.apache.geode.distributed.internal.membership.gms.messages.JoinRequestMessage)7 JoinResponseMessage (org.apache.geode.distributed.internal.membership.gms.messages.JoinResponseMessage)7 Event (org.jgroups.Event)7 IOException (java.io.IOException)6 MembershipTest (org.apache.geode.test.junit.categories.MembershipTest)6 SerialAckedMessage (org.apache.geode.distributed.internal.SerialAckedMessage)5 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)5 InstallViewMessage (org.apache.geode.distributed.internal.membership.gms.messages.InstallViewMessage)5 LeaveRequestMessage (org.apache.geode.distributed.internal.membership.gms.messages.LeaveRequestMessage)5 CancellationException (java.util.concurrent.CancellationException)4 ExecutionException (java.util.concurrent.ExecutionException)4 TimeoutException (java.util.concurrent.TimeoutException)4 NetView (org.apache.geode.distributed.internal.membership.NetView)4 RequestOptions (org.jgroups.blocks.RequestOptions)3 CommandDispatcherException (org.wildfly.clustering.dispatcher.CommandDispatcherException)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 UnknownHostException (java.net.UnknownHostException)2