Search in sources :

Example 61 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project load-balancer by RestComm.

the class HttpRequestHandler method writeInfoResponse.

private void writeInfoResponse(MessageEvent e) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.setPrettyPrinting().create();
    JsonElement je = gson.toJsonTree(new NodesInfoObject(balancerRunner));
    JsonObject jo = new JsonObject();
    jo.add("Nodes info", je);
    String output = jo.toString();
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    ChannelBuffer buf = ChannelBuffers.copiedBuffer(output, Charset.forName("UTF-8"));
    response.setContent(buf);
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) NodesInfoObject(org.mobicents.tools.sip.balancer.NodesInfoObject) GsonBuilder(com.google.gson.GsonBuilder) JsonElement(com.google.gson.JsonElement) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 62 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project load-balancer by RestComm.

the class HttpRequestHandler method handleHttpRequest.

private void handleHttpRequest(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    String currAddress = e.getRemoteAddress().toString();
    semaphore = semaphoreMap.get(currAddress);
    if (semaphore == null) {
        semaphore = new Semaphore(1);
        Semaphore tempSemaphore = semaphoreMap.putIfAbsent(currAddress, semaphore);
        if (tempSemaphore != null)
            semaphore = tempSemaphore;
    }
    try {
        semaphore.acquire();
    } catch (InterruptedException ex) {
    }
    if (!readingChunks && e.getMessage() instanceof HttpRequest) {
        request = (HttpRequest) e.getMessage();
        if (logger.isDebugEnabled()) {
            logger.debug("Request URI accessed: " + request.getUri() + " channel " + e.getChannel());
        }
        if (HttpChannelAssociations.urlRewriteFilter != null)
            HttpChannelAssociations.urlRewriteFilter.doFilter(request, e);
        AdvancedChannel currentAC = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
        Channel associatedChannel = null;
        if (currentAC != null)
            associatedChannel = currentAC.getChannel();
        InvocationContext invocationContext = balancerRunner.getLatestInvocationContext();
        // SIPNode node = null;
        try {
            // TODO: If WebSocket request, choose a NODE that is able to
            // handle WebSocket requests (has a websocket connector)
            node = invocationContext.balancerAlgorithm.processHttpRequest(request);
        } catch (Exception ex) {
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            logger.warn("Problem in balancer algorithm", ex);
            writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Load Balancer Error: Exception in the balancer algorithm:\n" + sw.toString());
            return;
        }
        if (node == null) {
            if (logger.isInfoEnabled()) {
                logger.info("Service unavailable. No server is available.");
            }
            writeResponse(e, HttpResponseStatus.SERVICE_UNAVAILABLE, IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("500.html")));
            return;
        }
        if (associatedChannel != null && associatedChannel.isConnected()) {
            semaphore.release();
            associatedChannel.write(request);
        } else {
            e.getChannel().getCloseFuture().addListener(new ChannelFutureListener() {

                public void operationComplete(ChannelFuture arg0) throws Exception {
                    closeChannelPair(arg0.getChannel());
                }
            });
            // Start the connection attempt.
            ChannelFuture future = null;
            Set<String> headers = request.getHeaderNames();
            if (headers.contains("Sec-WebSocket-Protocol")) {
                if (request.getHeader("Sec-WebSocket-Protocol").equalsIgnoreCase("sip")) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("New SIP over WebSocket request. WebSocket uri: " + request.getUri());
                        logger.debug("Dispatching WebSocket request to node: " + node.getIp() + " port: " + node.getProperties().get("wsPort"));
                    }
                    wsrequest = true;
                    wsVersion = request.getHeader(Names.SEC_WEBSOCKET_VERSION);
                    websocketServerPipelineFactory = new WebsocketModifyClientPipelineFactory();
                    future = HttpChannelAssociations.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("wsPort"))));
                }
            } else {
                if (!isSecured) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Dispatching HTTP request to node: " + node.getIp() + " port: " + node.getProperties().get("httpPort"));
                    }
                    future = HttpChannelAssociations.inboundBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("httpPort"))));
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Dispatching HTTPS request to node: " + node.getIp() + " port: " + node.getProperties().get("sslPort"));
                    }
                    future = HttpChannelAssociations.inboundSecureBootstrap.connect(new InetSocketAddress(node.getIp(), Integer.parseInt(node.getProperties().get("sslPort"))));
                }
            }
            future.addListener(new ChannelFutureListener() {

                public void operationComplete(ChannelFuture arg0) throws Exception {
                    Channel channel = arg0.getChannel();
                    if (pattern != null && pattern.matcher(request.getUri()).find()) {
                        logger.info("request : " + request.getUri() + " matches to pattern : " + pattern);
                        HttpChannelAssociations.channels.put(new AdvancedChannel(e.getChannel(), true), new AdvancedChannel(channel, true));
                        HttpChannelAssociations.channels.put(new AdvancedChannel(channel, true), new AdvancedChannel(e.getChannel(), true));
                    } else {
                        HttpChannelAssociations.channels.put(new AdvancedChannel(e.getChannel(), false), new AdvancedChannel(channel, false));
                        HttpChannelAssociations.channels.put(new AdvancedChannel(channel, false), new AdvancedChannel(e.getChannel(), false));
                    }
                    if (request.isChunked()) {
                        readingChunks = true;
                    }
                    semaphore.release();
                    channel.write(request);
                    if (wsrequest) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("This is a websocket request, changing the pipeline");
                        }
                        // Modify the Client Pipeline - Phase 1
                        ChannelPipeline p = channel.getPipeline();
                        websocketServerPipelineFactory.upgradeClientPipelineFactoryPhase1(p, wsVersion);
                    }
                    channel.getCloseFuture().addListener(new ChannelFutureListener() {

                        public void operationComplete(ChannelFuture arg0) throws Exception {
                            closeChannelPair(arg0.getChannel());
                        }
                    });
                }
            });
        }
    } else {
        HttpChunk chunk = (HttpChunk) e.getMessage();
        if (chunk.isLast()) {
            readingChunks = false;
        }
        semaphore.release();
        HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel())).getChannel().write(chunk);
        if (logger.isDebugEnabled())
            logger.debug("Send chunked request from : " + e.getChannel().getLocalAddress() + " to : " + e.getChannel().getRemoteAddress() + " capacity : " + chunk.getContent().capacity());
    }
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) Semaphore(java.util.concurrent.Semaphore) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) URISyntaxException(java.net.URISyntaxException) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) StringWriter(java.io.StringWriter) InvocationContext(org.mobicents.tools.sip.balancer.InvocationContext) PrintWriter(java.io.PrintWriter) HttpChunk(org.jboss.netty.handler.codec.http.HttpChunk)

Example 63 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class NettyProducer method openConnection.

protected ChannelFuture openConnection() throws Exception {
    ChannelFuture answer;
    if (isTcp()) {
        // its okay to create a new bootstrap for each new channel
        ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory);
        clientBootstrap.setOption("keepAlive", configuration.isKeepAlive());
        clientBootstrap.setOption("tcpNoDelay", configuration.isTcpNoDelay());
        clientBootstrap.setOption("reuseAddress", configuration.isReuseAddress());
        clientBootstrap.setOption("connectTimeoutMillis", configuration.getConnectTimeout());
        // set any additional netty options
        if (configuration.getOptions() != null) {
            for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                clientBootstrap.setOption(entry.getKey(), entry.getValue());
            }
        }
        // set the pipeline factory, which creates the pipeline for each newly created channels
        clientBootstrap.setPipelineFactory(pipelineFactory);
        answer = clientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new TCP client bootstrap connecting to {}:{} with options: {}", new Object[] { configuration.getHost(), configuration.getPort(), clientBootstrap.getOptions() });
        }
        return answer;
    } else {
        // its okay to create a new bootstrap for each new channel
        ConnectionlessBootstrap connectionlessClientBootstrap = new ConnectionlessBootstrap(datagramChannelFactory);
        connectionlessClientBootstrap.setOption("child.keepAlive", configuration.isKeepAlive());
        connectionlessClientBootstrap.setOption("child.tcpNoDelay", configuration.isTcpNoDelay());
        connectionlessClientBootstrap.setOption("child.reuseAddress", configuration.isReuseAddress());
        connectionlessClientBootstrap.setOption("child.connectTimeoutMillis", configuration.getConnectTimeout());
        connectionlessClientBootstrap.setOption("child.broadcast", configuration.isBroadcast());
        connectionlessClientBootstrap.setOption("sendBufferSize", configuration.getSendBufferSize());
        connectionlessClientBootstrap.setOption("receiveBufferSize", configuration.getReceiveBufferSize());
        // set any additional netty options
        if (configuration.getOptions() != null) {
            for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
            }
        }
        // set the pipeline factory, which creates the pipeline for each newly created channels
        connectionlessClientBootstrap.setPipelineFactory(pipelineFactory);
        // if no one is listen on the port
        if (!configuration.isUdpConnectionlessSending()) {
            answer = connectionlessClientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        } else {
            // bind and store channel so we can close it when stopping
            Channel channel = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
            allChannels.add(channel);
            answer = new SucceededChannelFuture(channel);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}", new Object[] { configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap.getOptions() });
        }
        return answer;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) SucceededChannelFuture(org.jboss.netty.channel.SucceededChannelFuture) ClientBootstrap(org.jboss.netty.bootstrap.ClientBootstrap) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) Map(java.util.Map) ConnectionlessBootstrap(org.jboss.netty.bootstrap.ConnectionlessBootstrap)

Example 64 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class ClientModeTCPNettyServerBootstrapFactory method openChannel.

protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
    // blocking for channel to be done
    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture, configuration.getConnectTimeout());
    }
    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            channelLatch.countDown();
        }
    });
    try {
        channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new CamelException("Interrupted while waiting for " + "connection to " + configuration.getAddress());
    }
    if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
        ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
        if (channelFuture.getCause() != null) {
            cause.initCause(channelFuture.getCause());
        }
        throw cause;
    }
    Channel answer = channelFuture.getChannel();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {}", configuration.getAddress());
    }
    return answer;
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) CamelException(org.apache.camel.CamelException) Channel(org.jboss.netty.channel.Channel) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) CamelException(org.apache.camel.CamelException) ConnectException(java.net.ConnectException) ConnectException(java.net.ConnectException)

Example 65 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project camel by apache.

the class SingleTCPNettyServerBootstrapFactory method doResume.

@Override
protected void doResume() throws Exception {
    if (channel != null) {
        LOG.debug("ServerBootstrap binding to {}:{}", configuration.getHost(), configuration.getPort());
        ChannelFuture future = channel.bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
        future.awaitUninterruptibly();
        if (!future.isSuccess()) {
            // if we cannot bind, the re-create channel
            allChannels.remove(channel);
            channel = serverBootstrap.bind(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
            allChannels.add(channel);
        }
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)122 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)36 Channel (org.jboss.netty.channel.Channel)33 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)29 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)26 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)25 InetSocketAddress (java.net.InetSocketAddress)22 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)22 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)19 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 Test (org.junit.Test)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)8 Test (org.testng.annotations.Test)8 ConnectException (java.net.ConnectException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6