Search in sources :

Example 1 with ServerConnectionDebug

use of org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug in project wso2-synapse by wso2.

the class ServerHandler method requestReceived.

/**
 * Process a new incoming request
 * @param conn the connection
 */
public void requestReceived(final NHttpServerConnection conn) {
    HttpContext context = conn.getContext();
    context.setAttribute(NhttpConstants.REQ_ARRIVAL_TIME, System.currentTimeMillis());
    context.setAttribute(NhttpConstants.REQ_FROM_CLIENT_READ_START_TIME, System.currentTimeMillis());
    HttpRequest request = conn.getHttpRequest();
    context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
    context.setAttribute(NhttpConstants.MESSAGE_IN_FLIGHT, "true");
    if (isMessageSizeValidationEnabled) {
        context.setAttribute(NhttpConstants.MESSAGE_SIZE_VALIDATION_SUM, 0);
    }
    // prepare to collect debug information
    conn.getContext().setAttribute(ServerHandler.SERVER_CONNECTION_DEBUG, new ServerConnectionDebug(conn));
    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    try {
        InputStream is;
        // Only create an input buffer and ContentInputStream if the request has content
        if (request instanceof HttpEntityEnclosingRequest) {
            // Mark request as not yet fully read, to detect timeouts from harmless keepalive deaths
            conn.getContext().setAttribute(NhttpConstants.REQUEST_READ, Boolean.FALSE);
            ContentInputBuffer inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator);
            context.setAttribute(REQUEST_SINK_BUFFER, inputBuffer);
            is = new ContentInputStream(inputBuffer);
        } else {
            is = null;
            conn.getContext().removeAttribute(NhttpConstants.REQUEST_READ);
        }
        ContentOutputBuffer outputBuffer = new NhttpSharedOutputBuffer(bufferSize, conn, allocator, socketTimeout);
        context.setAttribute(RESPONSE_SOURCE_BUFFER, outputBuffer);
        OutputStream os = new ContentOutputStream(outputBuffer);
        // create the default response to this request
        ProtocolVersion httpVersion = request.getRequestLine().getProtocolVersion();
        HttpResponse response = responseFactory.newHttpResponse(httpVersion, HttpStatus.SC_OK, context);
        // create a basic HttpEntity using the source channel of the response pipe
        BasicHttpEntity entity = new BasicHttpEntity();
        if (httpVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
            entity.setChunked(true);
        }
        response.setEntity(entity);
        if (metrics != null) {
            metrics.incrementMessagesReceived();
        }
        // hand off processing of the request to a thread off the pool
        ServerWorker worker = new ServerWorker(cfgCtx, scheme.getName(), metrics, conn, this, request, is, response, os, listenerContext.isRestDispatching(), listenerContext.getHttpGetRequestProcessor());
        if (workerPool != null) {
            workerPool.execute(worker);
        } else if (executor != null) {
            Map<String, String> headers = new HashMap<String, String>();
            for (Header header : request.getAllHeaders()) {
                headers.put(header.getName(), header.getValue());
            }
            EvaluatorContext evaluatorContext = new EvaluatorContext(request.getRequestLine().getUri(), headers);
            int priority = parser.parse(evaluatorContext);
            executor.execute(worker, priority);
        }
        // See if the client expects a 100-Continue
        Header expect = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE);
        if (expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue())) {
            HttpResponse ack = new BasicHttpResponse(request.getProtocolVersion(), HttpStatus.SC_CONTINUE, "Continue");
            conn.submitResponse(ack);
            if (log.isDebugEnabled()) {
                log.debug(conn + ": Expect :100 Continue hit, sending ack back to the server");
            }
            return;
        }
    } catch (Exception e) {
        if (metrics != null) {
            metrics.incrementFaultsReceiving();
        }
        handleException("Error processing request received for : " + request.getRequestLine().getUri(), e, conn);
    }
}
Also used : ServerConnectionDebug(org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug) EvaluatorContext(org.apache.synapse.commons.evaluators.EvaluatorContext) ContentInputStream(org.apache.http.nio.entity.ContentInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) IOException(java.io.IOException) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ContentInputStream(org.apache.http.nio.entity.ContentInputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with ServerConnectionDebug

use of org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug in project wso2-synapse by wso2.

the class ServerHandler method outputReady.

/**
 * Process ready output by writing into the channel
 * @param conn the connection being processed
 * @param encoder the content encoder in use
 */
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {
    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();
    ContentOutputBuffer outBuf = (ContentOutputBuffer) context.getAttribute(RESPONSE_SOURCE_BUFFER);
    if (outBuf == null) {
        // fix for SYNAPSE 584. This is a temporaly fix becuase of HTTPCORE-208
        shutdownConnection(conn, false, null);
        return;
    }
    try {
        int bytesWritten = outBuf.produceContent(encoder);
        if (metrics != null && bytesWritten > 0) {
            metrics.incrementBytesSent(bytesWritten);
        }
        if (encoder.isCompleted()) {
            long currentTime = System.currentTimeMillis();
            context.setAttribute(NhttpConstants.RES_TO_CLIENT_WRITE_END_TIME, currentTime);
            context.setAttribute(NhttpConstants.RES_DEPARTURE_TIME, currentTime);
            updateLatencyView(context);
            context.removeAttribute(NhttpConstants.REQ_ARRIVAL_TIME);
            context.removeAttribute(NhttpConstants.REQ_DEPARTURE_TIME);
            context.removeAttribute(NhttpConstants.RES_ARRIVAL_TIME);
            ((ServerConnectionDebug) conn.getContext().getAttribute(SERVER_CONNECTION_DEBUG)).recordResponseCompletionTime();
            Boolean reqRead = (Boolean) conn.getContext().getAttribute(NhttpConstants.REQUEST_READ);
            Boolean forceConnectionClose = (Boolean) conn.getContext().getAttribute(NhttpConstants.FORCE_CONNECTION_CLOSE);
            if (reqRead != null && !reqRead) {
                try {
                    // this is a connection we should not re-use
                    conn.close();
                } catch (Exception ignore) {
                }
            } else if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else if (forceConnectionClose != null && forceConnectionClose) {
                conn.close();
            } else {
                conn.requestInput();
            }
        }
    } catch (IOException e) {
        if (metrics != null) {
            metrics.incrementFaultsSending();
        }
        handleException("I/O Error at outputReady : " + e.getMessage(), e, conn);
    }
}
Also used : ServerConnectionDebug(org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Example 3 with ServerConnectionDebug

use of org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug in project wso2-synapse by wso2.

the class HttpCoreNIOSender method sendAsyncRequest.

/**
 * Send the request message asynchronously to the given EPR
 * @param epr the destination EPR for the message
 * @param msgContext the message being sent
 * @throws AxisFault on error
 */
private void sendAsyncRequest(EndpointReference epr, MessageContext msgContext) throws AxisFault {
    try {
        URL url = new URL(epr.getAddress());
        String scheme = url.getProtocol() != null ? url.getProtocol() : "http";
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equalsIgnoreCase(target.getSchemeName());
        HttpHost proxy = proxyConfig.selectProxy(target);
        msgContext.setProperty(NhttpConstants.PROXY_PROFILE_TARGET_HOST, target.getHostName());
        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }
        Axis2HttpRequest axis2Req = new Axis2HttpRequest(epr, route, msgContext);
        Object timeout = msgContext.getProperty(NhttpConstants.SEND_TIMEOUT);
        if (timeout != null && timeout instanceof Long) {
            axis2Req.setTimeout((int) ((Long) timeout).longValue());
        }
        NHttpClientConnection conn = connpool.getConnection(route);
        // Ensure MessageContext has a ClientConnectionDebug attached before we start streaming
        ServerConnectionDebug scd = (ServerConnectionDebug) msgContext.getProperty(ServerHandler.SERVER_CONNECTION_DEBUG);
        ClientConnectionDebug ccd;
        if (scd != null) {
            ccd = scd.getClientConnectionDebug();
            if (ccd == null) {
                ccd = new ClientConnectionDebug(scd);
                scd.setClientConnectionDebug(ccd);
            }
            ccd.recordRequestStartTime(conn, axis2Req);
            msgContext.setProperty(ClientHandler.CLIENT_CONNECTION_DEBUG, ccd);
        }
        if (conn == null) {
            HttpHost host = route.getProxyHost() != null ? route.getProxyHost() : route.getTargetHost();
            ioReactor.connect(new InetSocketAddress(host.getHostName(), host.getPort()), null, axis2Req, sessionRequestCallback);
            if (log.isDebugEnabled()) {
                log.debug("A new connection established to : " + route);
            }
        } else {
            // reinitialize timeouts for the pooled connection
            conn.setSocketTimeout(socketTimeout);
            try {
                handler.submitRequest(conn, axis2Req);
                if (log.isDebugEnabled()) {
                    log.debug("An existing connection reused to : " + hostname + ":" + port);
                }
            } catch (ConnectionClosedException e) {
                ioReactor.connect(new InetSocketAddress(hostname, port), null, axis2Req, sessionRequestCallback);
                if (log.isDebugEnabled()) {
                    log.debug("A new connection established to : " + hostname + ":" + port);
                }
            }
        }
        try {
            axis2Req.streamMessageContents();
        } catch (AxisFault af) {
            throw af;
        }
    } catch (MalformedURLException e) {
        handleException("Malformed destination EPR : " + epr.getAddress(), e);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) MalformedURLException(java.net.MalformedURLException) ServerConnectionDebug(org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug) InetSocketAddress(java.net.InetSocketAddress) ClientConnectionDebug(org.apache.synapse.transport.nhttp.debug.ClientConnectionDebug) ConnectionClosedException(org.apache.http.ConnectionClosedException) NHttpClientConnection(org.apache.http.nio.NHttpClientConnection) URL(java.net.URL) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpHost(org.apache.http.HttpHost)

Aggregations

ServerConnectionDebug (org.apache.synapse.transport.nhttp.debug.ServerConnectionDebug)3 IOException (java.io.IOException)2 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)2 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 InetSocketAddress (java.net.InetSocketAddress)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 AxisFault (org.apache.axis2.AxisFault)1 ConnectionClosedException (org.apache.http.ConnectionClosedException)1 HttpHost (org.apache.http.HttpHost)1 HttpRoute (org.apache.http.conn.routing.HttpRoute)1 BasicHttpEntity (org.apache.http.entity.BasicHttpEntity)1 NHttpClientConnection (org.apache.http.nio.NHttpClientConnection)1 ContentInputStream (org.apache.http.nio.entity.ContentInputStream)1 ContentOutputStream (org.apache.http.nio.entity.ContentOutputStream)1 EvaluatorContext (org.apache.synapse.commons.evaluators.EvaluatorContext)1 ClientConnectionDebug (org.apache.synapse.transport.nhttp.debug.ClientConnectionDebug)1