Search in sources :

Example 6 with Message

use of org.neo4j.cluster.com.message.Message in project neo4j by neo4j.

the class HeartbeatStateTest method shouldIgnoreSuspicionsForOurselves.

@Test
public void shouldIgnoreSuspicionsForOurselves() throws Throwable {
    // Given
    InstanceId instanceId = new InstanceId(1);
    HeartbeatState heartbeat = HeartbeatState.heartbeat;
    ClusterConfiguration configuration = new ClusterConfiguration("whatever", NullLogProvider.getInstance(), "cluster://1", "cluster://2");
    configuration.joined(instanceId, URI.create("cluster://1"));
    configuration.joined(new InstanceId(2), URI.create("cluster://2"));
    Config config = mock(Config.class);
    when(config.get(ClusterSettings.max_acceptors)).thenReturn(10);
    MultiPaxosContext context = new MultiPaxosContext(instanceId, iterable(new ElectionRole("coordinator")), configuration, Mockito.mock(Executor.class), NullLogProvider.getInstance(), Mockito.mock(ObjectInputStreamFactory.class), Mockito.mock(ObjectOutputStreamFactory.class), Mockito.mock(AcceptorInstanceStore.class), Mockito.mock(Timeouts.class), mock(ElectionCredentialsProvider.class), config);
    HeartbeatContext heartbeatContext = context.getHeartbeatContext();
    Message received = Message.internal(HeartbeatMessage.suspicions, new HeartbeatMessage.SuspicionsState(asSet(iterable(instanceId))));
    received.setHeader(Message.FROM, "cluster://2").setHeader(Message.INSTANCE_ID, "2");
    // When
    heartbeat.handle(heartbeatContext, received, mock(MessageHolder.class));
    // Then
    assertThat(heartbeatContext.getSuspicionsOf(instanceId).size(), equalTo(0));
}
Also used : LearnerMessage(org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.LearnerMessage) Message(org.neo4j.cluster.com.message.Message) InstanceId(org.neo4j.cluster.InstanceId) Config(org.neo4j.kernel.configuration.Config) Timeouts(org.neo4j.cluster.timeout.Timeouts) ClusterConfiguration(org.neo4j.cluster.protocol.cluster.ClusterConfiguration) ElectionRole(org.neo4j.cluster.protocol.election.ElectionRole) MessageHolder(org.neo4j.cluster.com.message.MessageHolder) Executor(java.util.concurrent.Executor) DelayedDirectExecutor(org.neo4j.cluster.DelayedDirectExecutor) ElectionCredentialsProvider(org.neo4j.cluster.protocol.election.ElectionCredentialsProvider) MultiPaxosContext(org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.context.MultiPaxosContext) ObjectInputStreamFactory(org.neo4j.cluster.protocol.atomicbroadcast.ObjectInputStreamFactory) ObjectOutputStreamFactory(org.neo4j.cluster.protocol.atomicbroadcast.ObjectOutputStreamFactory) AcceptorInstanceStore(org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.AcceptorInstanceStore) Test(org.junit.Test)

Example 7 with Message

use of org.neo4j.cluster.com.message.Message in project neo4j by neo4j.

the class StateMachinesTest method shouldAlwaysAddItsInstanceIdToOutgoingMessages.

@Test
public void shouldAlwaysAddItsInstanceIdToOutgoingMessages() throws Exception {
    InstanceId me = new InstanceId(42);
    final List<Message> sentOut = new LinkedList<Message>();
    /*
         * Lots of setup required. Must have a sender that keeps messages so we can see what the machine sent out.
         * We must have the StateMachines actually delegate the incoming message and retrieve the generated outgoing.
         * That means we need an actual StateMachine with a registered MessageType. And most of those are void
         * methods, which means lots of Answer objects.
         */
    // Given
    MessageSender sender = mock(MessageSender.class);
    // The sender, which adds messages outgoing to the list above.
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            sentOut.addAll((Collection<? extends Message>) invocation.getArguments()[0]);
            return null;
        }
    }).when(sender).process(Matchers.<List<Message<? extends MessageType>>>any());
    StateMachines stateMachines = new StateMachines(NullLogProvider.getInstance(), mock(StateMachines.Monitor.class), mock(MessageSource.class), sender, mock(Timeouts.class), mock(DelayedDirectExecutor.class), new Executor() {

        @Override
        public void execute(Runnable command) {
            command.run();
        }
    }, me);
    // The state machine, which has a TestMessage message type and simply adds a TO header to the messages it
    // is handed to handle.
    StateMachine machine = mock(StateMachine.class);
    when(machine.getMessageType()).then(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return TestMessage.class;
        }
    });
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Message message = (Message) invocation.getArguments()[0];
            MessageHolder holder = (MessageHolder) invocation.getArguments()[1];
            message.setHeader(Message.TO, "to://neverland");
            holder.offer(message);
            return null;
        }
    }).when(machine).handle(any(Message.class), any(MessageHolder.class));
    stateMachines.addStateMachine(machine);
    // When
    stateMachines.process(Message.internal(TestMessage.message1));
    // Then
    assertEquals("StateMachines should not make up messages from thin air", 1, sentOut.size());
    Message sent = sentOut.get(0);
    assertTrue("StateMachines should add the instance-id header", sent.hasHeader(Message.INSTANCE_ID));
    assertEquals("StateMachines should add instance-id header that has the correct value", me.toString(), sent.getHeader(Message.INSTANCE_ID));
}
Also used : Message(org.neo4j.cluster.com.message.Message) MessageSender(org.neo4j.cluster.com.message.MessageSender) Timeouts(org.neo4j.cluster.timeout.Timeouts) StateMachine(org.neo4j.cluster.statemachine.StateMachine) MessageSource(org.neo4j.cluster.com.message.MessageSource) LinkedList(java.util.LinkedList) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) MessageHolder(org.neo4j.cluster.com.message.MessageHolder) Executor(java.util.concurrent.Executor) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Collection(java.util.Collection) MessageType(org.neo4j.cluster.com.message.MessageType) Test(org.junit.Test)

Example 8 with Message

use of org.neo4j.cluster.com.message.Message in project neo4j by neo4j.

the class NetworkReceiverTest method testMessageReceivedOriginFix.

@Test
public void testMessageReceivedOriginFix() throws Exception {
    LogProvider logProvider = mock(LogProvider.class);
    when(logProvider.getLog(NetworkReceiver.class)).thenReturn(mock(Log.class));
    NetworkReceiver networkReceiver = new NetworkReceiver(mock(NetworkReceiver.Monitor.class), mock(NetworkReceiver.Configuration.class), logProvider);
    // This defines where message is coming from
    final InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", PORT);
    final Channel channel = mock(Channel.class);
    when(channel.getLocalAddress()).thenReturn(inetSocketAddress);
    when(channel.getRemoteAddress()).thenReturn(inetSocketAddress);
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.getChannel()).thenReturn(channel);
    final Message message = Message.to(new MessageType() {

        @Override
        public String name() {
            return "test";
        }
    }, new URI("cluster://anywhere"));
    MessageEvent messageEvent = mock(MessageEvent.class);
    when(messageEvent.getRemoteAddress()).thenReturn(inetSocketAddress);
    when(messageEvent.getMessage()).thenReturn(message);
    when(messageEvent.getChannel()).thenReturn(channel);
    // the original FROM header should be ignored
    message.setHeader(Message.FROM, "cluster://someplace:1234");
    networkReceiver.new MessageReceiver().messageReceived(ctx, messageEvent);
    assertEquals("FROM header should have been changed to visible ip address: " + message.getHeader(Message.FROM), "cluster://127.0.0.1:1234", message.getHeader(Message.FROM));
}
Also used : Message(org.neo4j.cluster.com.message.Message) Log(org.neo4j.logging.Log) InetSocketAddress(java.net.InetSocketAddress) MessageEvent(org.jboss.netty.channel.MessageEvent) Channel(org.jboss.netty.channel.Channel) ChannelHandlerContext(org.jboss.netty.channel.ChannelHandlerContext) URI(java.net.URI) LogProvider(org.neo4j.logging.LogProvider) MessageType(org.neo4j.cluster.com.message.MessageType) Test(org.junit.Test)

Example 9 with Message

use of org.neo4j.cluster.com.message.Message in project neo4j by neo4j.

the class MessageArgumentMatcher method matches.

@Override
public boolean matches(Object message) {
    if (message == null || !(message instanceof Message)) {
        return false;
    }
    if (message == this) {
        return true;
    }
    Message toMatchAgainst = (Message) message;
    boolean toMatches = to == null ? true : to.toString().equals(toMatchAgainst.getHeader(Message.TO));
    boolean fromMatches = from == null ? true : from.toString().equals(toMatchAgainst.getHeader(Message.FROM));
    boolean typeMatches = theMessageType == null ? true : theMessageType == toMatchAgainst.getMessageType();
    boolean payloadMatches = payload == null ? true : payload.equals(toMatchAgainst.getPayload());
    boolean headersMatch = true;
    for (String header : headers) {
        headersMatch = headersMatch && matchHeaderAndValue(header, toMatchAgainst.getHeader(header));
    }
    return fromMatches && toMatches && typeMatches && payloadMatches && headersMatch;
}
Also used : Message(org.neo4j.cluster.com.message.Message)

Example 10 with Message

use of org.neo4j.cluster.com.message.Message in project neo4j by neo4j.

the class NetworkMock method tick.

public int tick() {
    // Deliver messages whose delivery time has passed
    now += tickDuration;
    //       logger.debug( "tick:"+now );
    Iterator<MessageDelivery> iter = messageDeliveries.iterator();
    while (iter.hasNext()) {
        MessageDelivery messageDelivery = iter.next();
        if (messageDelivery.getMessageDeliveryTime() <= now) {
            long delay = strategy.messageDelay(messageDelivery.getMessage(), messageDelivery.getServer().getServer().boundAt().toString());
            if (delay != NetworkLatencyStrategy.LOST) {
                messageDelivery.getServer().process(messageDelivery.getMessage());
            }
            iter.remove();
        }
    }
    // Check and trigger timeouts
    for (TestProtocolServer testServer : participants.values()) {
        testServer.tick(now);
    }
    // Get all sent messages from all test servers
    List<Message> messages = new ArrayList<Message>();
    for (TestProtocolServer testServer : participants.values()) {
        testServer.sendMessages(messages);
    }
    // Now send them and figure out latency
    for (Message message : messages) {
        String to = message.getHeader(Message.TO);
        long delay = 0;
        if (message.getHeader(Message.TO).equals(message.getHeader(Message.FROM))) {
            log.debug("Sending message to itself; zero latency");
        } else {
            delay = strategy.messageDelay(message, to);
        }
        if (delay == NetworkLatencyStrategy.LOST) {
            log.debug("Send message to " + to + " was lost");
        } else {
            TestProtocolServer server = participants.get(to);
            log.debug("Send to " + to + ": " + message);
            messageDeliveries.add(new MessageDelivery(now + delay, message, server));
        }
    }
    Iterator<Pair<Future<?>, Runnable>> waiters = futureWaiter.iterator();
    while (waiters.hasNext()) {
        Pair<Future<?>, Runnable> next = waiters.next();
        if (next.first().isDone()) {
            next.other().run();
            waiters.remove();
        }
    }
    return messageDeliveries.size();
}
Also used : Message(org.neo4j.cluster.com.message.Message) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) Pair(org.neo4j.helpers.collection.Pair)

Aggregations

Message (org.neo4j.cluster.com.message.Message)24 Test (org.junit.Test)22 MessageHolder (org.neo4j.cluster.com.message.MessageHolder)21 InstanceId (org.neo4j.cluster.InstanceId)14 MessageType (org.neo4j.cluster.com.message.MessageType)12 ClusterConfiguration (org.neo4j.cluster.protocol.cluster.ClusterConfiguration)9 URI (java.net.URI)8 ArrayList (java.util.ArrayList)7 ClusterContext (org.neo4j.cluster.protocol.cluster.ClusterContext)6 AtomicBroadcastMessage (org.neo4j.cluster.protocol.atomicbroadcast.multipaxos.AtomicBroadcastMessage)5 ClusterMessage (org.neo4j.cluster.protocol.cluster.ClusterMessage)5 Executor (java.util.concurrent.Executor)4 Timeouts (org.neo4j.cluster.timeout.Timeouts)4 LinkedList (java.util.LinkedList)3 Mockito.doAnswer (org.mockito.Mockito.doAnswer)3 InvocationOnMock (org.mockito.invocation.InvocationOnMock)3 Answer (org.mockito.stubbing.Answer)3 DelayedDirectExecutor (org.neo4j.cluster.DelayedDirectExecutor)3 ObjectInputStreamFactory (org.neo4j.cluster.protocol.atomicbroadcast.ObjectInputStreamFactory)3 ObjectOutputStreamFactory (org.neo4j.cluster.protocol.atomicbroadcast.ObjectOutputStreamFactory)3