Search in sources :

Example 61 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project bagheera by mozilla-metrics.

the class RootResponse method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object msg = e.getMessage();
    if (msg instanceof HttpMessage) {
        HttpRequest request = (HttpRequest) msg;
        if (ROOT_PATH.equals(request.getUri()) || request.getUri().isEmpty()) {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            ChannelFuture future = e.getChannel().write(response);
            future.addListener(ChannelFutureListener.CLOSE);
        } else {
            Channels.fireMessageReceived(ctx, request, e.getRemoteAddress());
        }
    } else {
        ctx.sendUpstream(e);
    }
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpMessage(org.jboss.netty.handler.codec.http.HttpMessage)

Example 62 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest 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 HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project load-balancer by RestComm.

the class HttpRequestHandler method addRegex.

private boolean addRegex(MessageEvent e) {
    String regex = getUrlParameters(((HttpRequest) e.getMessage()).getUri()).get("regex");
    String ip = getUrlParameters(((HttpRequest) e.getMessage()).getUri()).get("ip");
    String port = getUrlParameters(((HttpRequest) e.getMessage()).getUri()).get("port");
    boolean isIpV6 = false;
    if (ip != null)
        isIpV6 = LbUtils.isValidInet6Address(ip);
    logger.info("regex : " + regex + " IP :" + ip);
    if (regex != null && ip != null && port != null) {
        KeySip keySip = new KeySip(ip, Integer.parseInt(port), isIpV6);
        if (balancerRunner.balancerContext.regexMap == null) {
            balancerRunner.balancerContext.regexMap = new ConcurrentHashMap<String, KeySip>();
            balancerRunner.balancerContext.regexMap.put(regex, keySip);
            return true;
        } else {
            balancerRunner.balancerContext.regexMap.put(regex, keySip);
            return true;
        }
    } else if (regex != null) {
        KeySip keySip = balancerRunner.balancerContext.regexMap.remove(regex);
        if (keySip != null) {
            logger.info("regex removed from map : " + regex);
            return true;
        } else {
            logger.info("regex did not remove from map : " + regex);
            return false;
        }
    } else
        return false;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) KeySip(org.mobicents.tools.sip.balancer.KeySip)

Example 64 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project load-balancer by RestComm.

the class HttpRequestHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object msg = e.getMessage();
    if (msg instanceof WebSocketFrame) {
        handleWebSocketFrame(ctx, e);
    } else if (msg instanceof HttpRequest) {
        request = (HttpRequest) e.getMessage();
        Integer apiPort = balancerRunner.balancerContext.lbConfig.getCommonConfiguration().getStatisticPort();
        if (apiPort != null) {
            try {
                URI uri = new URI(request.getUri());
                if (((InetSocketAddress) ctx.getChannel().getLocalAddress()).getPort() == apiPort) {
                    String currUriPath = uri.getPath().toLowerCase();
                    switch(currUriPath) {
                        case "/lbnoderegex":
                            if (addRegex(e))
                                writeResponse(e, HttpResponseStatus.OK, "Regex set");
                            else
                                writeResponse(e, HttpResponseStatus.BAD_REQUEST, "Regex NOT set, use : 127.0.0.1:2006/lbnoderegex?regex=(.*)(\\d+)(.*)&ip=127.0.0.1&port=5060");
                            return;
                        case "/lbloglevel":
                            changeLogLevel(e);
                            writeResponse(e, HttpResponseStatus.OK, "Log level changed");
                            return;
                        case "/lbstat":
                            writeStatisticResponse(e);
                            return;
                        case "/lbinfo":
                            writeInfoResponse(e);
                            return;
                        case "/lbstop":
                            if (!balancerRunner.balancerContext.securityRequired || (balancerRunner.balancerContext.securityRequired && checkCredentials(e))) {
                                writeResponse(e, HttpResponseStatus.LOCKED, IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("bye.html")));
                                new GracefulShutdown(balancerRunner).start();
                            } else {
                                writeResponse(e, HttpResponseStatus.UNAUTHORIZED, "Authorization required : Incorrect login or password" + " request example : 127.0.0.1:2006/lbstop?login=daddy&password=123456");
                            }
                            return;
                        default:
                            writeResponse(e, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Server error");
                            return;
                    }
                }
            } catch (URISyntaxException e1) {
            // ignore exception
            }
        }
    }
    if (balancerRunner.balancerContext.lbConfig.getHttpConfiguration().getHttpsPort() != null && (((InetSocketAddress) ctx.getChannel().getLocalAddress()).getPort() == balancerRunner.balancerContext.lbConfig.getHttpConfiguration().getHttpPort())) {
        // redirect http request send 3xx response
        sendRedirectResponse(e, request);
        return;
    }
    if (msg instanceof HttpRequest) {
        balancerRunner.balancerContext.httpRequests.incrementAndGet();
        balancerRunner.balancerContext.httpRequestsProcessedByMethod.get(request.getMethod().getName()).incrementAndGet();
    }
    balancerRunner.balancerContext.httpBytesToServer.addAndGet(request.getContent().capacity());
    String telestaxHeader = request.headers().get("TelestaxProxy");
    if (telestaxHeader != null && telestaxHeader.equalsIgnoreCase("true")) {
        balancerRunner.getLatestInvocationContext().balancerAlgorithm.proxyMessage(ctx, e);
    } else {
        handleHttpRequest(ctx, e);
    }
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) InetSocketAddress(java.net.InetSocketAddress) JsonObject(com.google.gson.JsonObject) StatisticObject(org.mobicents.tools.sip.balancer.StatisticObject) NodesInfoObject(org.mobicents.tools.sip.balancer.NodesInfoObject) TextWebSocketFrame(org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame) WebSocketFrame(org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) GracefulShutdown(org.mobicents.tools.sip.balancer.GracefulShutdown)

Example 65 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project load-balancer by RestComm.

the class Client method createRequest.

private HttpRequest createRequest(String packetType, Packet packet) {
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    ChannelBuffer buf = ChannelBuffers.copiedBuffer(getStringFromJson(packetType, packet), Charset.forName("UTF-8"));
    request.setHeader(HttpHeaders.Names.CONTENT_TYPE, APPLICATION_JSON);
    request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buf.readableBytes());
    request.setContent(buf);
    return request;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) DefaultHttpRequest(org.jboss.netty.handler.codec.http.DefaultHttpRequest) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Aggregations

HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)136 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)69 Channel (org.jboss.netty.channel.Channel)47 Test (org.junit.Test)47 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)46 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)43 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)31 ChannelFuture (org.jboss.netty.channel.ChannelFuture)26 List (java.util.List)19 ArrayList (java.util.ArrayList)17 Map (java.util.Map)17 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)17 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)17 InetSocketAddress (java.net.InetSocketAddress)14 ChannelHandlerContext (org.jboss.netty.channel.ChannelHandlerContext)13 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)13 SimpleHttpResponseHandler (com.linkedin.databus.core.test.netty.SimpleHttpResponseHandler)12 SimpleTestHttpClient (com.linkedin.databus.core.test.netty.SimpleTestHttpClient)12 Configuration (org.apache.hadoop.conf.Configuration)12 YarnConfiguration (org.apache.hadoop.yarn.conf.YarnConfiguration)12