Search in sources :

Example 56 with Channel

use of org.jboss.netty.channel.Channel in project graphdb by neo4j-attic.

the class Client method sendRequest.

protected <R> Response<R> sendRequest(RequestType<M> type, SlaveContext context, Serializer serializer, Deserializer<R> deserializer) {
    Triplet<Channel, ChannelBuffer, ByteBuffer> channelContext = null;
    try {
        // Send 'em over the wire
        channelContext = getChannel();
        Channel channel = channelContext.first();
        channelContext.second().clear();
        ChunkingChannelBuffer chunkingBuffer = new ChunkingChannelBuffer(channelContext.second(), channel, Protocol.MAX_FRAME_LENGTH);
        chunkingBuffer.writeByte(type.id());
        writeContext(type, context, chunkingBuffer);
        serializer.write(chunkingBuffer, channelContext.third());
        chunkingBuffer.done();
        // Read the response
        @SuppressWarnings("unchecked") BlockingReadHandler<ChannelBuffer> reader = (BlockingReadHandler<ChannelBuffer>) channel.getPipeline().get("blockingHandler");
        final Triplet<Channel, ChannelBuffer, ByteBuffer> finalChannelContext = channelContext;
        DechunkingChannelBuffer dechunkingBuffer = new DechunkingChannelBuffer(reader, DEFAULT_READ_RESPONSE_TIMEOUT_SECONDS) {

            @Override
            protected ChannelBuffer readNext() {
                ChannelBuffer result = super.readNext();
                if (result == null) {
                    channelPool.dispose(finalChannelContext);
                    throw new ComException("Channel has been closed");
                }
                return result;
            }
        };
        R response = deserializer.read(dechunkingBuffer, channelContext.third());
        StoreId storeId = readStoreId(dechunkingBuffer, channelContext.third());
        if (shouldCheckStoreId(type)) {
            assertCorrectStoreId(storeId);
        }
        TransactionStream txStreams = readTransactionStreams(dechunkingBuffer);
        return new Response<R>(response, storeId, txStreams);
    } catch (ClosedChannelException e) {
        channelPool.dispose(channelContext);
        throw new ComException(e);
    } catch (IOException e) {
        throw new ComException(e);
    } catch (InterruptedException e) {
        throw new ComException(e);
    } catch (Exception e) {
        throw new ComException(e);
    } finally {
        releaseChannel();
    }
}
Also used : BlockingReadHandler(org.jboss.netty.handler.queue.BlockingReadHandler) ClosedChannelException(java.nio.channels.ClosedChannelException) Channel(org.jboss.netty.channel.Channel) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) StoreId(org.neo4j.kernel.impl.nioneo.store.StoreId)

Example 57 with Channel

use of org.jboss.netty.channel.Channel in project graphdb by neo4j-attic.

the class Server method checkForDeadChannels.

private void checkForDeadChannels() {
    synchronized (connectedSlaveChannels) {
        Collection<Channel> channelsToRemove = new ArrayList<Channel>();
        for (Map.Entry<Channel, SlaveContext> entry : connectedSlaveChannels.entrySet()) {
            if (!channelIsOpen(entry.getKey())) {
                msgLog.logMessage("Found dead channel " + entry.getKey() + ", " + entry.getValue());
                finishOffConnection(entry.getKey(), entry.getValue());
                msgLog.logMessage("Removed " + entry.getKey() + ", " + entry.getValue());
                channelsToRemove.add(entry.getKey());
            }
        }
        for (Channel channel : channelsToRemove) {
            connectedSlaveChannels.remove(channel);
            channelBuffers.remove(channel);
            partialRequests.remove(channel);
        }
    }
}
Also used : Channel(org.jboss.netty.channel.Channel) ArrayList(java.util.ArrayList) HashMap(java.util.HashMap) Map(java.util.Map)

Example 58 with Channel

use of org.jboss.netty.channel.Channel 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 59 with Channel

use of org.jboss.netty.channel.Channel in project neo4j by neo4j.

the class Server method start.

@Override
public void start() throws Throwable {
    String className = getClass().getSimpleName();
    ExecutorService bossExecutor = newCachedThreadPool(daemon("Boss-" + className));
    ExecutorService workerExecutor = newCachedThreadPool(daemon("Worker-" + className));
    bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(bossExecutor, workerExecutor, config.getMaxConcurrentTransactions()));
    bootstrap.setPipelineFactory(this);
    PortRangeSocketBinder portRangeSocketBinder = new PortRangeSocketBinder(bootstrap);
    try {
        Connection connection = portRangeSocketBinder.bindToFirstAvailablePortInRange(config.getServerAddress());
        Channel channel = connection.getChannel();
        socketAddress = connection.getSocketAddress();
        channelGroup = new DefaultChannelGroup();
        channelGroup.add(channel);
        msgLog.info(className + " communication server started and bound to " + socketAddress);
    } catch (Exception ex) {
        msgLog.error("Failed to bind server to " + socketAddress, ex);
        bootstrap.releaseExternalResources();
        targetCallExecutor.shutdownNow();
        unfinishedTransactionExecutor.shutdownNow();
        silentChannelExecutor.shutdownNow();
        throw new IOException(ex);
    }
}
Also used : DefaultChannelGroup(org.jboss.netty.channel.group.DefaultChannelGroup) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) Channel(org.jboss.netty.channel.Channel) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) IOException(java.io.IOException) ServerBootstrap(org.jboss.netty.bootstrap.ServerBootstrap) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException)

Example 60 with Channel

use of org.jboss.netty.channel.Channel in project neo4j by neo4j.

the class IdleChannelReaperTest method shouldNotCloseAChannelThatHasBeenIdleForMoreThanHalfThresholdButIsStillOpenConnectedAndBound.

@Test
public void shouldNotCloseAChannelThatHasBeenIdleForMoreThanHalfThresholdButIsStillOpenConnectedAndBound() {
    // given
    FakeClock clock = Clocks.fakeClock();
    ChannelCloser channelCloser = mock(ChannelCloser.class);
    IdleChannelReaper idleChannelReaper = new IdleChannelReaper(channelCloser, NO_LOGGING, clock, THRESHOLD);
    Channel channel = mock(Channel.class);
    idleChannelReaper.add(channel, dummyRequestContext());
    when(channel.isOpen()).thenReturn(true);
    when(channel.isConnected()).thenReturn(true);
    when(channel.isBound()).thenReturn(true);
    // when
    clock.forward(THRESHOLD / 2 + 10, TimeUnit.MILLISECONDS);
    idleChannelReaper.run();
    // then
    verifyNoMoreInteractions(channelCloser);
}
Also used : FakeClock(org.neo4j.time.FakeClock) Channel(org.jboss.netty.channel.Channel) Test(org.junit.Test)

Aggregations

Channel (org.jboss.netty.channel.Channel)187 InetSocketAddress (java.net.InetSocketAddress)57 Test (org.junit.Test)52 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)40 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)37 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)34 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)34 SocketAddress (java.net.SocketAddress)33 ChannelFuture (org.jboss.netty.channel.ChannelFuture)33 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)30 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)27 Test (org.testng.annotations.Test)23 ConditionCheck (com.linkedin.databus2.test.ConditionCheck)22 IOException (java.io.IOException)21 SimpleObjectCaptureHandler (com.linkedin.databus2.test.container.SimpleObjectCaptureHandler)19 Logger (org.apache.log4j.Logger)19 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)17 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)16 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)16 ArrayList (java.util.ArrayList)14