Search in sources :

Example 56 with ChannelPipeline

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

the class ClientPipelineFactory method getPipeline.

public ChannelPipeline getPipeline() throws Exception {
    ChannelPipeline pipeline = pipeline();
    pipeline.addLast("decoder", new HttpResponseDecoder());
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
    pipeline.addLast("handler", new HttpResponseHandler(listener));
    return pipeline;
}
Also used : HttpRequestEncoder(org.jboss.netty.handler.codec.http.HttpRequestEncoder) HttpResponseDecoder(org.jboss.netty.handler.codec.http.HttpResponseDecoder) HttpChunkAggregator(org.jboss.netty.handler.codec.http.HttpChunkAggregator) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline)

Example 57 with ChannelPipeline

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

the class HttpClientPipelineFactory method getPipeline.

public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    pipeline.addLast("decoder", new HttpResponseDecoder());
    // Remove the following line if you don't want automatic content decompression.
    // pipeline.addLast("inflater", new HttpContentDecompressor());
    pipeline.addLast("encoder", new HttpRequestEncoder());
    // http://code.google.com/p/commscale/issues/detail?id=5 support for HttpChunks,
    // https://telestax.atlassian.net/browse/LB-8 if commented accessing the RestComm Management console fails, so making the maxContentLength Configurable
    // pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength));
    pipeline.addLast("handler", new HttpResponseHandler(balancerRunner));
    if (isUseSsl) {
        SslConfiguration sslConfig = new SslConfiguration();
        sslConfig.setTrustAll(true);
        sslConfig.setValidateCerts(true);
        sslConfig.setValidatePeerCerts(true);
        SslContextFactory factory = new SslContextFactory(sslConfig);
        SSLEngine sslEngine = factory.newSslEngine();
        sslEngine.setUseClientMode(true);
        pipeline.addFirst("ssl", new SslHandler(sslEngine));
    }
    return pipeline;
}
Also used : SslContextFactory(com.cloudhopper.smpp.ssl.SslContextFactory) SslConfiguration(com.cloudhopper.smpp.ssl.SslConfiguration) SSLEngine(javax.net.ssl.SSLEngine) HttpRequestEncoder(org.jboss.netty.handler.codec.http.HttpRequestEncoder) HttpResponseDecoder(org.jboss.netty.handler.codec.http.HttpResponseDecoder) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) SslHandler(org.jboss.netty.handler.ssl.SslHandler)

Example 58 with ChannelPipeline

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

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

the class HttpResponseHandler method handleHttpResponse.

private void handleHttpResponse(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpChunkTrailer) {
        HttpChunkTrailer chunk = (HttpChunkTrailer) e.getMessage();
        balancerRunner.balancerContext.httpBytesToClient.addAndGet(chunk.getContent().capacity());
        if (chunk.isLast())
            readingChunks = false;
        AdvancedChannel ac = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
        Channel channel = null;
        if (ac != null)
            channel = ac.getChannel();
        if (channel != null) {
            if (logger.isDebugEnabled())
                logger.debug("Send chunked response from : " + e.getChannel().getRemoteAddress() + " to : " + channel.getRemoteAddress() + " capacity : " + chunk.getContent().capacity());
            channel.write(chunk);
        }
    } else if (!readingChunks || !(e.getMessage() instanceof DefaultHttpChunk)) {
        response = (HttpResponse) e.getMessage();
        int stsusCode = response.getStatus().getCode();
        if (stsusCode > 399 && stsusCode < 600) {
            AdvancedChannel ac = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
            if (ac != null && ac.isCheckNeed()) {
                InetSocketAddress address = (InetSocketAddress) e.getChannel().getRemoteAddress();
                InvocationContext invocationContext = balancerRunner.getLatestInvocationContext();
                KeySip keySip = new KeySip(address.getHostString(), address.getPort(), false);
                Node currNode = invocationContext.sipNodeMap(false).get(keySip);
                if (currNode != null) {
                    currNode.setBad(true);
                    String instanseId = currNode.getProperties().get(Protocol.RESTCOMM_INSTANCE_ID);
                    if (instanseId != null)
                        invocationContext.httpNodeMap.get(new KeyHttp(currNode.getProperties().get(Protocol.RESTCOMM_INSTANCE_ID))).setBad(true);
                    logger.error("Error code [" + stsusCode + "] detected in HTTP response. From  node : " + currNode + ". This node will marked as bad.");
                    String currInstanceId = (String) currNode.getProperties().get("Restcomm-Instance-Id");
                    if (currInstanceId != null)
                        logger.warn("Node : " + invocationContext.httpNodeMap.remove(new KeyHttp(currInstanceId)) + " from httpNodeMap");
                    // invocationContext.badSipNodeMap(false).put(keySip, currNode);
                    invocationContext.balancerAlgorithm.nodeRemoved(currNode);
                }
            // TODO CHECK REQUEST AND REMOVE NODE
            }
        }
        updateStatistic(response);
        balancerRunner.balancerContext.httpBytesToClient.addAndGet(response.getContent().capacity());
        if (response.isChunked()) {
            readingChunks = true;
        }
        AdvancedChannel ac = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
        Channel channel = null;
        if (ac != null)
            channel = ac.getChannel();
        if (channel != null) {
            if (logger.isDebugEnabled())
                logger.debug("Send response from : " + e.getChannel().getRemoteAddress() + " to : " + channel.getRemoteAddress() + " capacity : " + response.getContent().capacity());
            channel.write(response);
        }
        Set<String> headers = response.getHeaderNames();
        if (headers.contains("Sec-WebSocket-Protocol")) {
            if (response.getHeader("Sec-WebSocket-Protocol").equalsIgnoreCase("sip")) {
                if (logger.isDebugEnabled()) {
                    logger.debug("WebSocket response");
                }
                wsVersion = response.getHeader(Names.SEC_WEBSOCKET_VERSION);
                // Modify the Server pipeline
                ChannelPipeline p = channel.getPipeline();
                websocketModifyServerPipelineFactory = new WebsocketModifyServerPipelineFactory();
                websocketModifyServerPipelineFactory.upgradeServerPipelineFactory(p, wsVersion);
            }
        }
    } else {
        HttpChunk chunk = (HttpChunk) e.getMessage();
        balancerRunner.balancerContext.httpBytesToClient.addAndGet(chunk.getContent().capacity());
        if (chunk.isLast())
            readingChunks = false;
        AdvancedChannel ac = HttpChannelAssociations.channels.get(new AdvancedChannel(e.getChannel()));
        Channel channel = null;
        if (ac != null)
            channel = ac.getChannel();
        if (channel != null) {
            if (logger.isDebugEnabled())
                logger.debug("Send chunked response from : " + e.getChannel().getRemoteAddress() + " to : " + channel.getRemoteAddress() + " capacity : " + chunk.getContent().capacity());
            channel.write(chunk);
        }
    }
}
Also used : Set(java.util.Set) DefaultHttpChunk(org.jboss.netty.handler.codec.http.DefaultHttpChunk) InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) Node(org.mobicents.tools.heartbeat.api.Node) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) HttpChunkTrailer(org.jboss.netty.handler.codec.http.HttpChunkTrailer) KeySip(org.mobicents.tools.sip.balancer.KeySip) InvocationContext(org.mobicents.tools.sip.balancer.InvocationContext) KeyHttp(org.mobicents.tools.sip.balancer.KeyHttp) DefaultHttpChunk(org.jboss.netty.handler.codec.http.DefaultHttpChunk) HttpChunk(org.jboss.netty.handler.codec.http.HttpChunk)

Example 60 with ChannelPipeline

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

the class HttpServerPipelineFactory method getPipeline.

public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    if (isSecure) {
        SslConfiguration sslConfig = new SslConfiguration();
        sslConfig.setKeyStorePath(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getKeyStore());
        sslConfig.setKeyStorePassword(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getKeyStorePassword());
        sslConfig.setTrustStorePath(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getTrustStore());
        sslConfig.setTrustStorePassword(balancerRunner.balancerContext.lbConfig.getSslConfiguration().getTrustStorePassword());
        String sProtocols = balancerRunner.balancerContext.lbConfig.getSslConfiguration().getTlsClientProtocols();
        String sCipherSuites = balancerRunner.balancerContext.lbConfig.getSslConfiguration().getEnabledCipherSuites();
        if (sProtocols != null) {
            String[] protocols = sProtocols.split(",");
            sslConfig.setIncludeProtocols(protocols);
        }
        if (sCipherSuites != null) {
            String[] cipherSuites = sCipherSuites.split(",");
            sslConfig.setIncludeCipherSuites(cipherSuites);
        }
        SslContextFactory factory = new SslContextFactory(sslConfig);
        SSLEngine sslEngine = factory.newSslEngine();
        sslEngine.setUseClientMode(false);
        pipeline.addLast("ssl", new SslHandler(sslEngine));
    }
    pipeline.addLast("decoder", new HttpRequestDecoder());
    // http://code.google.com/p/commscale/issues/detail?id=5 support for HttpChunks
    // https://telestax.atlassian.net/browse/LB-8 if commented accessing the RestComm Management console fails, so making the maxContentLength Configurable
    // pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    // pipeline.addLast("deflater", new HttpContentCompressor());
    if (balancerRunner.balancerContext.terminateTLSTraffic)
        pipeline.addLast("handler", new HttpRequestHandler(balancerRunner, false));
    else
        pipeline.addLast("handler", new HttpRequestHandler(balancerRunner, isSecure));
    return pipeline;
}
Also used : HttpResponseEncoder(org.jboss.netty.handler.codec.http.HttpResponseEncoder) SslContextFactory(com.cloudhopper.smpp.ssl.SslContextFactory) SslConfiguration(com.cloudhopper.smpp.ssl.SslConfiguration) SSLEngine(javax.net.ssl.SSLEngine) HttpRequestDecoder(org.jboss.netty.handler.codec.http.HttpRequestDecoder) ChannelPipeline(org.jboss.netty.channel.ChannelPipeline) SslHandler(org.jboss.netty.handler.ssl.SslHandler)

Aggregations

ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)165 ServerBootstrap (org.jboss.netty.bootstrap.ServerBootstrap)58 TrackerServer (org.traccar.TrackerServer)43 InetSocketAddress (java.net.InetSocketAddress)37 ChannelPipelineFactory (org.jboss.netty.channel.ChannelPipelineFactory)32 ConnectionlessBootstrap (org.jboss.netty.bootstrap.ConnectionlessBootstrap)26 Channel (org.jboss.netty.channel.Channel)26 SimpleObjectCaptureHandler (com.linkedin.databus2.test.container.SimpleObjectCaptureHandler)24 SocketAddress (java.net.SocketAddress)20 StringEncoder (org.jboss.netty.handler.codec.string.StringEncoder)18 SimpleTestServerConnection (com.linkedin.databus2.test.container.SimpleTestServerConnection)17 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)16 NioServerSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory)16 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)16 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)16 HttpResponseEncoder (org.jboss.netty.handler.codec.http.HttpResponseEncoder)16 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)15 HttpRequestDecoder (org.jboss.netty.handler.codec.http.HttpRequestDecoder)15 StringDecoder (org.jboss.netty.handler.codec.string.StringDecoder)14 LoggingHandler (org.jboss.netty.handler.logging.LoggingHandler)14