Search in sources :

Example 86 with Channel

use of org.jboss.netty.channel.Channel in project opentsdb by OpenTSDB.

the class ConnectionManager method exceptionCaught.

@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) {
    final Throwable cause = e.getCause();
    final Channel chan = ctx.getChannel();
    if (cause instanceof ClosedChannelException) {
        exceptions_closed.incrementAndGet();
        LOG.warn("Attempt to write to closed channel " + chan);
        return;
    }
    if (cause instanceof IOException) {
        final String message = cause.getMessage();
        if ("Connection reset by peer".equals(message)) {
            exceptions_reset.incrementAndGet();
            return;
        } else if ("Connection timed out".equals(message)) {
            exceptions_timeout.incrementAndGet();
            // and Java managed to do something *far* worse.  That's quite a feat.
            return;
        } else if (cause instanceof ConnectionRefusedException) {
            connections_rejected.incrementAndGet();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Refusing connection from " + chan, e.getCause());
            }
            chan.close();
            return;
        }
    }
    if (cause instanceof CodecEmbedderException) {
        // payload was not compressed as it was announced to be
        LOG.warn("Http codec error : " + cause.getMessage());
        e.getChannel().close();
        return;
    }
    exceptions_unknown.incrementAndGet();
    LOG.error("Unexpected exception from downstream for " + chan, cause);
    e.getChannel().close();
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) CodecEmbedderException(org.jboss.netty.handler.codec.embedder.CodecEmbedderException) Channel(org.jboss.netty.channel.Channel) IOException(java.io.IOException)

Example 87 with Channel

use of org.jboss.netty.channel.Channel in project cdap by caskdata.

the class NettyRouter method bootstrapServer.

private void bootstrapServer(final ChannelUpstreamHandler connectionTracker) throws ServiceBindException {
    ExecutorService serverBossExecutor = createExecutorService(serverBossThreadPoolSize, "router-server-boss-thread-%d");
    ExecutorService serverWorkerExecutor = createExecutorService(serverWorkerThreadPoolSize, "router-server-worker-thread-%d");
    serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(serverBossExecutor, serverWorkerExecutor));
    serverBootstrap.setOption("backlog", serverConnectionBacklog);
    serverBootstrap.setOption("child.bufferFactory", new DirectChannelBufferFactory());
    // Setup the pipeline factory
    serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline pipeline = Channels.pipeline();
            if (isSSLEnabled()) {
                // Add SSLHandler is SSL is enabled
                pipeline.addLast("ssl", sslHandlerFactory.create());
            }
            pipeline.addLast("tracker", connectionTracker);
            pipeline.addLast("http-response-encoder", new HttpResponseEncoder());
            pipeline.addLast("http-decoder", new HttpRequestDecoder());
            pipeline.addLast("http-status-request-handler", new HttpStatusRequestHandler());
            if (securityEnabled) {
                pipeline.addLast("access-token-authenticator", new SecurityAuthenticationHttpHandler(realm, tokenValidator, configuration, accessTokenTransformer, discoveryServiceClient));
            }
            // for now there's only one hardcoded rule, but if there will be more, we may want it generic and configurable
            pipeline.addLast("http-request-handler", new HttpRequestHandler(clientBootstrap, serviceLookup, ImmutableList.<ProxyRule>of()));
            return pipeline;
        }
    });
    // Start listening on ports.
    ImmutableMap.Builder<Integer, String> serviceMapBuilder = ImmutableMap.builder();
    for (Map.Entry<String, Integer> forward : serviceToPortMap.entrySet()) {
        int port = forward.getValue();
        String service = forward.getKey();
        String boundService = serviceLookup.getService(port);
        if (boundService != null) {
            LOG.warn("Port {} is already configured to service {}, ignoring forward for service {}", port, boundService, service);
            continue;
        }
        InetSocketAddress bindAddress = new InetSocketAddress(hostname, port);
        LOG.info("Starting Netty Router for service {} on address {}...", service, bindAddress);
        try {
            Channel channel = serverBootstrap.bind(bindAddress);
            InetSocketAddress boundAddress = (InetSocketAddress) channel.getLocalAddress();
            serviceMapBuilder.put(boundAddress.getPort(), service);
            channelGroup.add(channel);
            // Update service map
            serviceLookup.updateServiceMap(serviceMapBuilder.build());
            LOG.info("Started Netty Router for service {} on address {}.", service, boundAddress);
        } catch (ChannelException e) {
            if ((Throwables.getRootCause(e) instanceof BindException)) {
                throw new ServiceBindException("Router", hostname.getCanonicalHostName(), port, e);
            }
            throw e;
        }
    }
}
Also used : ServiceBindException(co.cask.cdap.common.ServiceBindException) HttpRequestHandler(co.cask.cdap.gateway.router.handlers.HttpRequestHandler) InetSocketAddress(java.net.InetSocketAddress) SecurityAuthenticationHttpHandler(co.cask.cdap.gateway.router.handlers.SecurityAuthenticationHttpHandler) HttpStatusRequestHandler(co.cask.cdap.gateway.router.handlers.HttpStatusRequestHandler) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) ChannelException(org.jboss.netty.channel.ChannelException) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) Channel(org.jboss.netty.channel.Channel) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) DirectChannelBufferFactory(org.jboss.netty.buffer.DirectChannelBufferFactory) ServerBootstrap(org.jboss.netty.bootstrap.ServerBootstrap) ChannelException(org.jboss.netty.channel.ChannelException) BindException(java.net.BindException) ServiceBindException(co.cask.cdap.common.ServiceBindException) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) ImmutableMap(com.google.common.collect.ImmutableMap) HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 88 with Channel

use of org.jboss.netty.channel.Channel in project cdap by caskdata.

the class IdleEventProcessor method channelIdle.

@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
    if (IdleState.ALL_IDLE == e.getState()) {
        if (requestInProgress) {
            LOG.trace("Request is in progress, so not closing channel.");
        } else {
            // No data has been sent or received for a while. Close channel.
            Channel channel = ctx.getChannel();
            channel.close();
            LOG.trace("No data has been sent or received for channel '{}' for more than the configured idle timeout. " + "Closing the channel. Local Address: {}, Remote Address: {}", channel, channel.getLocalAddress(), channel.getRemoteAddress());
        }
    }
}
Also used : Channel(org.jboss.netty.channel.Channel)

Example 89 with Channel

use of org.jboss.netty.channel.Channel in project opennms by OpenNMS.

the class TcpOutputStrategyTest method setUpClass.

@BeforeClass
public static void setUpClass() {
    // Setup a quick Netty TCP server that decodes the protobuf messages
    // and appends these to a list when received
    ChannelFactory factory = new NioServerSocketChannelFactory();
    ServerBootstrap bootstrap = new ServerBootstrap(factory);
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

        public ChannelPipeline getPipeline() {
            return Channels.pipeline(new ProtobufDecoder(PerformanceDataReadings.getDefaultInstance()), new PerfDataServerHandler());
        }
    });
    Channel channel = bootstrap.bind(new InetSocketAddress(0));
    InetSocketAddress addr = (InetSocketAddress) channel.getLocalAddress();
    // Point the TCP exporter to our server
    System.setProperty("org.opennms.rrd.tcp.host", addr.getHostString());
    System.setProperty("org.opennms.rrd.tcp.port", Integer.toString(addr.getPort()));
    // Always use queueing during these tests
    System.setProperty("org.opennms.rrd.usequeue", Boolean.TRUE.toString());
    // Use the temporary folder as the base directory
    System.setProperty("rrd.base.dir", tempFolder.getRoot().getAbsolutePath());
}
Also used : NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) ProtobufDecoder(org.jboss.netty.handler.codec.protobuf.ProtobufDecoder) NioServerSocketChannelFactory(org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory) ChannelFactory(org.jboss.netty.channel.ChannelFactory) ChannelPipelineFactory(org.jboss.netty.channel.ChannelPipelineFactory) ServerBootstrap(org.jboss.netty.bootstrap.ServerBootstrap) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) BeforeClass(org.junit.BeforeClass)

Example 90 with Channel

use of org.jboss.netty.channel.Channel in project dubbo by alibaba.

the class NettyClient method doConnect.

protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // Close old channel
                // copy reference
                Channel oldChannel = NettyClient.this.channel;
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + " client-side timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        if (!isConnected()) {
            future.cancel();
        }
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Channel(org.jboss.netty.channel.Channel) RemotingException(com.alibaba.dubbo.remoting.RemotingException)

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