Search in sources :

Example 36 with AsyncListener

use of javax.servlet.AsyncListener in project pinpoint by naver.

the class ServletRequestImplStartAsyncInterceptor method doInAfterTrace.

@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    if (validate(target, result, throwable)) {
        final AsyncContext asyncContext = (AsyncContext) result;
        final AsyncListener asyncListener = new WeblogicAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }
    recorder.recordServiceType(WeblogicConstants.WEBLOGIC_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
Also used : AsyncListener(javax.servlet.AsyncListener) WeblogicAsyncListener(com.navercorp.pinpoint.plugin.weblogic.WeblogicAsyncListener) AsyncContext(javax.servlet.AsyncContext) WeblogicAsyncListener(com.navercorp.pinpoint.plugin.weblogic.WeblogicAsyncListener)

Example 37 with AsyncListener

use of javax.servlet.AsyncListener in project pinpoint by naver.

the class RequestStartAsyncInterceptor method after.

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }
    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }
    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        if (validate(target, result, throwable)) {
            com.navercorp.pinpoint.bootstrap.context.AsyncContext nextAsyncContext = recorder.recordNextAsyncContext(true);
            // Add async listener
            final AsyncContext asyncContext = (AsyncContext) result;
            final AsyncListener asyncListener = new TomcatAsyncListener(this.traceContext, nextAsyncContext);
            asyncContext.addListener(asyncListener);
            // Set AsyncContext, AsyncListener
            final HttpServletRequest request = (HttpServletRequest) target;
            request.setAttribute(com.navercorp.pinpoint.bootstrap.context.AsyncContext.class.getName(), nextAsyncContext);
            request.setAttribute(TomcatConstants.TOMCAT_SERVLET_REQUEST_TRACE, asyncListener);
            if (isDebug) {
                logger.debug("Add async listener {}", asyncListener);
            }
        }
        recorder.recordServiceType(TomcatConstants.TOMCAT_METHOD);
        recorder.recordApi(descriptor);
        recorder.recordException(throwable);
    } catch (Throwable t) {
        logger.warn("Failed to AFTER process. {}", t.getMessage(), t);
    } finally {
        trace.traceBlockEnd();
    }
}
Also used : TomcatAsyncListener(com.navercorp.pinpoint.plugin.tomcat.TomcatAsyncListener) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) AsyncContext(javax.servlet.AsyncContext) Trace(com.navercorp.pinpoint.bootstrap.context.Trace) HttpServletRequest(javax.servlet.http.HttpServletRequest) AsyncListener(javax.servlet.AsyncListener) TomcatAsyncListener(com.navercorp.pinpoint.plugin.tomcat.TomcatAsyncListener)

Example 38 with AsyncListener

use of javax.servlet.AsyncListener in project pinpoint by naver.

the class HttpServletRequestImplStartAsyncInterceptor method doInAfterTrace.

@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    if (validate(target, result, throwable)) {
        final AsyncContext asyncContext = (AsyncContext) result;
        final AsyncListener asyncListener = new UndertowAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }
    recorder.recordServiceType(UndertowServletConstants.UNDERTOW_SERVLET_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
Also used : AsyncListener(javax.servlet.AsyncListener) UndertowAsyncListener(com.navercorp.pinpoint.plugin.undertowservlet.UndertowAsyncListener) AsyncContext(javax.servlet.AsyncContext) UndertowAsyncListener(com.navercorp.pinpoint.plugin.undertowservlet.UndertowAsyncListener)

Example 39 with AsyncListener

use of javax.servlet.AsyncListener in project rest.li by linkedin.

the class AbstractAsyncR2StreamServlet method service.

@Override
public void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext ctx = req.startAsync(req, resp);
    ctx.setTimeout(_timeout);
    final WrappedAsyncContext wrappedCtx = new WrappedAsyncContext(ctx);
    final AsyncEventIOHandler ioHandler = new AsyncEventIOHandler(req.getInputStream(), resp.getOutputStream(), req.getRemoteAddr(), wrappedCtx, MAX_BUFFERED_CHUNKS, _logServletExceptions);
    final RequestContext requestContext = ServletHelper.readRequestContext(req);
    final StreamRequest streamRequest;
    try {
        streamRequest = ServletHelper.readFromServletRequest(req, ioHandler);
    } catch (URISyntaxException e) {
        ServletHelper.writeToServletError(resp, RestStatus.BAD_REQUEST, e.toString());
        wrappedCtx.complete();
        return;
    }
    final AtomicBoolean startedResponding = new AtomicBoolean(false);
    ctx.addListener(new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            LOG.error("Server timeout for request: " + formatURI(req.getRequestURI()));
            if (startedResponding.compareAndSet(false, true)) {
                LOG.info("Returning server timeout response");
                ServletHelper.writeToServletError(resp, RestStatus.INTERNAL_SERVER_ERROR, "Server timeout");
            } else {
                req.setAttribute(ASYNC_IOEXCEPTION, new ServletException("Server timeout"));
            }
            ioHandler.exitLoop();
            wrappedCtx.complete();
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
        // Nothing to do here
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            LOG.error("Server error for request: " + formatURI(req.getRequestURI()));
            if (startedResponding.compareAndSet(false, true)) {
                LOG.info("Returning server error response");
                ServletHelper.writeToServletError(resp, RestStatus.INTERNAL_SERVER_ERROR, "Server error");
            } else {
                req.setAttribute(ASYNC_IOEXCEPTION, new ServletException("Server error"));
            }
            ioHandler.exitLoop();
            wrappedCtx.complete();
        }

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            Object exception = req.getAttribute(ASYNC_IOEXCEPTION);
            if (exception != null) {
                throw new IOException((Throwable) exception);
            }
        }
    });
    final TransportCallback<StreamResponse> callback = new TransportCallback<StreamResponse>() {

        @Override
        public void onResponse(final TransportResponse<StreamResponse> response) {
            if (startedResponding.compareAndSet(false, true)) {
                ctx.start(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            StreamResponse streamResponse = ServletHelper.writeResponseHeadersToServletResponse(response, resp);
                            streamResponse.getEntityStream().setReader(ioHandler);
                            ioHandler.loop();
                        } catch (Exception e) {
                            req.setAttribute(ASYNC_IOEXCEPTION, e);
                            wrappedCtx.complete();
                        }
                    }
                });
            } else {
                LOG.error("Dropped a response; this is mostly like because that AsyncContext timeout or error had already happened");
            }
        }
    };
    // we have to use a new thread and let this thread return to pool. otherwise the timeout won't start
    ctx.start(new Runnable() {

        @Override
        public void run() {
            try {
                getDispatcher().handleRequest(streamRequest, requestContext, callback);
                ioHandler.loop();
            } catch (Exception e) {
                req.setAttribute(ASYNC_IOEXCEPTION, e);
                wrappedCtx.complete();
            }
        }
    });
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) AsyncContext(javax.servlet.AsyncContext) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) TransportResponse(com.linkedin.r2.transport.common.bridge.common.TransportResponse) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsyncListener(javax.servlet.AsyncListener) RequestContext(com.linkedin.r2.message.RequestContext)

Example 40 with AsyncListener

use of javax.servlet.AsyncListener in project druid by druid-io.

the class SegmentListerResource method applyDataSegmentChangeRequests.

/**
 * This endpoint is used by HttpLoadQueuePeon to assign segment load/drop requests batch. This endpoint makes the
 * client wait till one of the following events occur. Note that this is implemented using async IO so no jetty
 * threads are held while in wait.
 *
 * (1) Given timeout elapses.
 * (2) Some load/drop request completed.
 *
 * It returns a map of "load/drop request -> SUCCESS/FAILED/PENDING status" for each request in the batch.
 */
@POST
@Path("/changeRequests")
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
public void applyDataSegmentChangeRequests(@QueryParam("timeout") long timeout, List<DataSegmentChangeRequest> changeRequestList, @Context final HttpServletRequest req) throws IOException {
    if (loadDropRequestHandler == null) {
        sendErrorResponse(req, HttpServletResponse.SC_NOT_FOUND, "load/drop handler is not available.");
        return;
    }
    if (timeout <= 0) {
        sendErrorResponse(req, HttpServletResponse.SC_BAD_REQUEST, "timeout must be positive.");
        return;
    }
    if (changeRequestList == null || changeRequestList.isEmpty()) {
        sendErrorResponse(req, HttpServletResponse.SC_BAD_REQUEST, "No change requests provided.");
        return;
    }
    final ResponseContext context = createContext(req.getHeader("Accept"));
    final ListenableFuture<List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus>> future = loadDropRequestHandler.processBatch(changeRequestList);
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.addListener(new AsyncListener() {

        @Override
        public void onComplete(AsyncEvent event) {
        }

        @Override
        public void onTimeout(AsyncEvent event) {
            // HTTP 204 NO_CONTENT is sent to the client.
            future.cancel(true);
            event.getAsyncContext().complete();
        }

        @Override
        public void onError(AsyncEvent event) {
        }

        @Override
        public void onStartAsync(AsyncEvent event) {
        }
    });
    Futures.addCallback(future, new FutureCallback<List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus>>() {

        @Override
        public void onSuccess(List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus> result) {
            try {
                HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
                response.setStatus(HttpServletResponse.SC_OK);
                context.inputMapper.writerWithType(HttpLoadQueuePeon.RESPONSE_ENTITY_TYPE_REF).writeValue(asyncContext.getResponse().getOutputStream(), result);
                asyncContext.complete();
            } catch (Exception ex) {
                log.debug(ex, "Request timed out or closed already.");
            }
        }

        @Override
        public void onFailure(Throwable th) {
            try {
                HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
                if (th instanceof IllegalArgumentException) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, th.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, th.getMessage());
                }
                asyncContext.complete();
            } catch (Exception ex) {
                log.debug(ex, "Request timed out or closed already.");
            }
        }
    });
    asyncContext.setTimeout(timeout);
}
Also used : SegmentLoadDropHandler(org.apache.druid.server.coordination.SegmentLoadDropHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) AsyncEvent(javax.servlet.AsyncEvent) IOException(java.io.IOException) AsyncListener(javax.servlet.AsyncListener) List(java.util.List) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Aggregations

AsyncListener (javax.servlet.AsyncListener)45 AsyncContext (javax.servlet.AsyncContext)32 AsyncEvent (javax.servlet.AsyncEvent)30 IOException (java.io.IOException)28 HttpServletResponse (javax.servlet.http.HttpServletResponse)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ServletException (javax.servlet.ServletException)12 Test (org.junit.Test)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 CountDownLatch (java.util.concurrent.CountDownLatch)5 HttpServlet (javax.servlet.http.HttpServlet)5 OutputStream (java.io.OutputStream)4 Socket (java.net.Socket)3 URISyntaxException (java.net.URISyntaxException)3 CyclicBarrier (java.util.concurrent.CyclicBarrier)3 Request (org.eclipse.jetty.server.Request)3 Locker (org.eclipse.jetty.util.thread.Locker)3 RequestContext (com.linkedin.r2.message.RequestContext)2 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)2 TransportResponse (com.linkedin.r2.transport.common.bridge.common.TransportResponse)2