Java Code Examples for io.perfmark.PerfMark#stopTask()

The following examples show how to use io.perfmark.PerfMark#stopTask() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseZuulFilterRunner.java    From zuul with Apache License 2.0 6 votes vote down vote up
protected final void invokeNextStage(final O zuulMesg) {
    if (nextStage != null) {
        PerfMark.startTask(getClass().getName(), "invokeNextStage");
        try {
            addPerfMarkTags(zuulMesg);
            nextStage.filter(zuulMesg);
        } finally {
            PerfMark.stopTask(getClass().getName(), "invokeNextStage");
        }
    } else {
        //Next stage is Netty channel handler
        PerfMark.startTask(getClass().getName(), "fireChannelRead");
        try {
            addPerfMarkTags(zuulMesg);
            getChannelHandlerContext(zuulMesg).fireChannelRead(zuulMesg);
        } finally {
            PerfMark.stopTask(getClass().getName(), "fireChannelRead");
        }
    }
}
 
Example 2
Source File: BaseZuulFilterRunner.java    From zuul with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(O outMesg) {
    boolean stopped = false;
    PerfMark.startTask(filter.filterName(), "onNextAsync");
    try {
        PerfMark.linkIn(onNextLinkOut.get());
        addPerfMarkTags(inMesg);
        recordFilterCompletion(SUCCESS, filter, startTime, inMesg, snapshot);
        if (outMesg == null) {
            outMesg = filter.getDefaultOutput(inMesg);
        }
        stopped = true;
        PerfMark.stopTask(filter.filterName(), "onNextAsync");
        resumeInBindingContext(outMesg, filter.filterName());
    }
    catch (Exception e) {
        decrementConcurrency();
        handleException(inMesg, filter.filterName(), e);
    } finally {
        if (!stopped) {
            PerfMark.stopTask(filter.filterName(), "onNextAsync");
        }
    }
}
 
Example 3
Source File: NettyServerHandler.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private void onDataRead(int streamId, ByteBuf data, int padding, boolean endOfStream)
    throws Http2Exception {
  flowControlPing().onDataRead(data.readableBytes(), padding);
  try {
    NettyServerStream.TransportState stream = serverStream(requireHttp2Stream(streamId));
    PerfMark.startTask("NettyServerHandler.onDataRead", stream.tag());
    try {
      stream.inboundDataReceived(data, endOfStream);
    } finally {
      PerfMark.stopTask("NettyServerHandler.onDataRead", stream.tag());
    }
  } catch (Throwable e) {
    logger.log(Level.WARNING, "Exception in onDataRead()", e);
    // Throw an exception that will get handled by onStreamError.
    throw newStreamException(streamId, e);
  }
}
 
Example 4
Source File: OkHttpClientStream.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public void writeHeaders(Metadata metadata, byte[] payload) {
  PerfMark.startTask("OkHttpClientStream$Sink.writeHeaders");
  String defaultPath = "/" + method.getFullMethodName();
  if (payload != null) {
    useGet = true;
    defaultPath += "?" + BaseEncoding.base64().encode(payload);
  }
  try {
    synchronized (state.lock) {
      state.streamReady(metadata, defaultPath);
    }
  } finally {
    PerfMark.stopTask("OkHttpClientStream$Sink.writeHeaders");
  }
}
 
Example 5
Source File: ServerImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void messagesAvailable(final MessageProducer producer) {
  PerfMark.startTask("ServerStreamListener.messagesAvailable", tag);
  final Link link = PerfMark.linkOut();

  final class MessagesAvailable extends ContextRunnable {

    MessagesAvailable() {
      super(context);
    }

    @Override
    public void runInContext() {
      PerfMark.startTask("ServerCallListener(app).messagesAvailable", tag);
      PerfMark.linkIn(link);
      try {
        getListener().messagesAvailable(producer);
      } catch (Throwable t) {
        internalClose(t);
        throw t;
      } finally {
        PerfMark.stopTask("ServerCallListener(app).messagesAvailable", tag);
      }
    }
  }

  try {
    callExecutor.execute(new MessagesAvailable());
  } finally {
    PerfMark.stopTask("ServerStreamListener.messagesAvailable", tag);
  }
}
 
Example 6
Source File: ServerCallImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(RespT message) {
  PerfMark.startTask("ServerCall.sendMessage", tag);
  try {
    sendMessageInternal(message);
  } finally {
    PerfMark.stopTask("ServerCall.sendMessage", tag);
  }
}
 
Example 7
Source File: NettyServerStream.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void writeFrame(WritableBuffer frame, boolean flush, final int numMessages) {
  PerfMark.startTask("NettyServerStream$Sink.writeFrame");
  try {
    writeFrameInternal(frame, flush, numMessages);
  } finally {
    PerfMark.stopTask("NettyServerStream$Sink.writeFrame");
  }
}
 
Example 8
Source File: AbstractStream.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Called to request the given number of messages from the deframer. May be called from any
 * thread.
 */
private void requestMessagesFromDeframer(final int numMessages) {
  if (deframer instanceof ThreadOptimizedDeframer) {
    PerfMark.startTask("AbstractStream.request");
    try {
      deframer.request(numMessages);
    } finally {
      PerfMark.stopTask("AbstractStream.request");
    }
    return;
  }
  final Link link = PerfMark.linkOut();
  class RequestRunnable implements Runnable {
    @Override public void run() {
      PerfMark.startTask("AbstractStream.request");
      PerfMark.linkIn(link);
      try {
        deframer.request(numMessages);
      } catch (Throwable t) {
        deframeFailed(t);
      } finally {
        PerfMark.stopTask("AbstractStream.request");
      }
    }
  }

  runOnTransportThread(new RequestRunnable());
}
 
Example 9
Source File: MigratingThreadDeframer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void request(final int numMessages) {
  class RequestOp implements Op {
    @Override public void run(boolean isDeframerOnTransportThread) {
      if (isDeframerOnTransportThread) {
        final Link link = PerfMark.linkOut();
        // We may not be currently on the transport thread, so jump over to it and then do the
        // necessary processing
        transportExecutor.runOnTransportThread(new Runnable() {
          @Override public void run() {
            PerfMark.startTask("MigratingThreadDeframer.request");
            PerfMark.linkIn(link);
            try {
              // Since processing continues from transport thread while this runnable was
              // enqueued, the state may have changed since we ran runOnTransportThread. So we
              // must make sure deframerOnTransportThread==true
              requestFromTransportThread(numMessages);
            } finally {
              PerfMark.stopTask("MigratingThreadDeframer.request");
            }
          }
        });
        return;
      }
      PerfMark.startTask("MigratingThreadDeframer.request");
      try {
        deframer.request(numMessages);
      } catch (Throwable t) {
        appListener.deframeFailed(t);
        deframer.close(); // unrecoverable state
      } finally {
        PerfMark.stopTask("MigratingThreadDeframer.request");
      }
    }
  }

  runWhereAppropriate(new RequestOp(), false);
}
 
Example 10
Source File: ZuulFilterChainRunner.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
protected void resume(final T inMesg) {
    PerfMark.startTask(getClass().getSimpleName(), "resume");
    try {
        final AtomicInteger runningFilterIdx = getRunningFilterIndex(inMesg);
        runningFilterIdx.incrementAndGet();
        runFilters(inMesg, runningFilterIdx);
    } finally {
        PerfMark.stopTask(getClass().getSimpleName(), "resume");
    }
}
 
Example 11
Source File: AsyncSink.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void flush() throws IOException {
  if (closed) {
    throw new IOException("closed");
  }
  PerfMark.startTask("AsyncSink.flush");
  try {
    synchronized (lock) {
      if (flushEnqueued) {
        return;
      }
      flushEnqueued = true;
    }
    serializingExecutor.execute(new WriteRunnable() {
      final Link link = PerfMark.linkOut();
      @Override
      public void doRun() throws IOException {
        PerfMark.startTask("WriteRunnable.runFlush");
        PerfMark.linkIn(link);
        Buffer buf = new Buffer();
        try {
          synchronized (lock) {
            buf.write(buffer, buffer.size());
            flushEnqueued = false;
          }
          sink.write(buf, buf.size());
          sink.flush();
        } finally {
          PerfMark.stopTask("WriteRunnable.runFlush");
        }
      }
    });
  } finally {
    PerfMark.stopTask("AsyncSink.flush");
  }
}
 
Example 12
Source File: ServerImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void closed(final Status status) {
  PerfMark.startTask("ServerStreamListener.closed", tag);
  try {
    closedInternal(status);
  } finally {
    PerfMark.stopTask("ServerStreamListener.closed", tag);
  }
}
 
Example 13
Source File: ZuulEndPointRunner.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final HttpRequestMessage zuulReq) {
    if (zuulReq.getContext().isCancelled()) {
        PerfMark.event(getClass().getName(), "filterCancelled");
        zuulReq.disposeBufferedBody();
        logger.debug("Request was cancelled, UUID {}", zuulReq.getContext().getUUID());
        return;
    }

    final String endpointName = getEndPointName(zuulReq.getContext());
    PerfMark.startTask(getClass().getName(), "filter");
    try {
        Preconditions.checkNotNull(zuulReq, "input message");
        addPerfMarkTags(zuulReq);

        final ZuulFilter<HttpRequestMessage, HttpResponseMessage> endpoint = getEndpoint(endpointName, zuulReq);
        logger.debug("Got endpoint {}, UUID {}", endpoint.filterName(), zuulReq.getContext().getUUID());
        setEndpoint(zuulReq, endpoint);
        final HttpResponseMessage zuulResp = filter(endpoint, zuulReq);

        if ((zuulResp != null)&&(! (endpoint instanceof ProxyEndpoint))) {
            //EdgeProxyEndpoint calls invokeNextStage internally
            logger.debug("Endpoint calling invokeNextStage, UUID {}", zuulReq.getContext().getUUID());
            invokeNextStage(zuulResp);
        }
    }
    catch (Exception ex) {
        handleException(zuulReq, endpointName, ex);
    } finally {
        PerfMark.stopTask(getClass().getName(), "filter");
    }
}
 
Example 14
Source File: PerfMarkUtil.java    From perfmark with Apache License 2.0 5 votes vote down vote up
public static <E extends Exception> void recordTask(
    String taskName, Tag tag, CheckedRunnable<E> cmd) throws E {
  PerfMark.startTask(taskName, tag);
  try {
    cmd.run();
  } finally {
    PerfMark.stopTask(taskName, tag);
  }
}
 
Example 15
Source File: ClientCallImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void halfClose() {
  PerfMark.startTask("ClientCall.halfClose", tag);
  try {
    halfCloseInternal();
  } finally {
    PerfMark.stopTask("ClientCall.halfClose", tag);
  }
}
 
Example 16
Source File: ClientCallImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(ReqT message) {
  PerfMark.startTask("ClientCall.sendMessage", tag);
  try {
    sendMessageInternal(message);
  } finally {
    PerfMark.stopTask("ClientCall.sendMessage", tag);
  }
}
 
Example 17
Source File: ZuulEndPointRunner.java    From zuul with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final HttpRequestMessage zuulReq, final HttpContent chunk) {
    if (zuulReq.getContext().isCancelled()) {
        chunk.release();
        return;
    }

    String endpointName = "-";
    PerfMark.startTask(getClass().getName(), "filterChunk");
    try {
        addPerfMarkTags(zuulReq);
        ZuulFilter<HttpRequestMessage, HttpResponseMessage> endpoint = Preconditions.checkNotNull(
                getEndpoint(zuulReq), "endpoint");
        endpointName = endpoint.filterName();

        final HttpContent newChunk = endpoint.processContentChunk(zuulReq, chunk);
        if (newChunk != null) {
            //Endpoints do not directly forward content chunks to next stage in the filter chain.
            zuulReq.bufferBodyContents(newChunk);

            //deallocate original chunk if necessary
            if (newChunk != chunk) {
                chunk.release();
            }

            if (isFilterAwaitingBody(zuulReq) && zuulReq.hasCompleteBody() && !(endpoint instanceof ProxyEndpoint)) {
                //whole body has arrived, resume filter chain
                invokeNextStage(filter(endpoint, zuulReq));
            }
        }
    }
    catch (Exception ex) {
        handleException(zuulReq, endpointName, ex);
    } finally {
        PerfMark.stopTask(getClass().getName(), "filterChunk");
    }
}
 
Example 18
Source File: PerfMarkUtil.java    From perfmark with Apache License 2.0 4 votes vote down vote up
@MustBeClosed
public static TaskRecorder recordTask(String taskName) {
  PerfMark.startTask(taskName);
  return () -> PerfMark.stopTask(taskName);
}
 
Example 19
Source File: ClientCallImpl.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public void headersRead(final Metadata headers) {
  PerfMark.startTask("ClientStreamListener.headersRead", tag);
  final Link link = PerfMark.linkOut();

  final class HeadersRead extends ContextRunnable {
    HeadersRead() {
      super(context);
    }

    @Override
    public void runInContext() {
      PerfMark.startTask("ClientCall$Listener.headersRead", tag);
      PerfMark.linkIn(link);
      try {
        runInternal();
      } finally {
        PerfMark.stopTask("ClientCall$Listener.headersRead", tag);
      }
    }

    private void runInternal() {
      if (closed) {
        return;
      }
      try {
        observer.onHeaders(headers);
      } catch (Throwable t) {
        Status status =
            Status.CANCELLED.withCause(t).withDescription("Failed to read headers");
        stream.cancel(status);
        close(status, new Metadata());
      }
    }
  }

  try {
    callExecutor.execute(new HeadersRead());
  } finally {
    PerfMark.stopTask("ClientStreamListener.headersRead", tag);
  }
}
 
Example 20
Source File: NettyServerHandler.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers)
    throws Http2Exception {
  try {

    // Remove the leading slash of the path and get the fully qualified method name
    CharSequence path = headers.path();

    if (path == null) {
      respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED,
          "Expected path but is missing");
      return;
    }

    if (path.charAt(0) != '/') {
      respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED,
          String.format("Expected path to start with /: %s", path));
      return;
    }

    String method = path.subSequence(1, path.length()).toString();

    // Verify that the Content-Type is correct in the request.
    CharSequence contentType = headers.get(CONTENT_TYPE_HEADER);
    if (contentType == null) {
      respondWithHttpError(
          ctx, streamId, 415, Status.Code.INTERNAL, "Content-Type is missing from the request");
      return;
    }
    String contentTypeString = contentType.toString();
    if (!GrpcUtil.isGrpcContentType(contentTypeString)) {
      respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL,
          String.format("Content-Type '%s' is not supported", contentTypeString));
      return;
    }

    if (!HTTP_METHOD.contentEquals(headers.method())) {
      respondWithHttpError(ctx, streamId, 405, Status.Code.INTERNAL,
          String.format("Method '%s' is not supported", headers.method()));
      return;
    }

    if (!teWarningLogged && !TE_TRAILERS.contentEquals(headers.get(TE_HEADER))) {
      logger.warning(String.format("Expected header TE: %s, but %s is received. This means "
              + "some intermediate proxy may not support trailers",
          TE_TRAILERS, headers.get(TE_HEADER)));
      teWarningLogged = true;
    }

    // The Http2Stream object was put by AbstractHttp2ConnectionHandler before calling this
    // method.
    Http2Stream http2Stream = requireHttp2Stream(streamId);

    Metadata metadata = Utils.convertHeaders(headers);
    StatsTraceContext statsTraceCtx =
        StatsTraceContext.newServerContext(streamTracerFactories, method, metadata);

    NettyServerStream.TransportState state = new NettyServerStream.TransportState(
        this,
        ctx.channel().eventLoop(),
        http2Stream,
        maxMessageSize,
        statsTraceCtx,
        transportTracer,
        method);

    PerfMark.startTask("NettyServerHandler.onHeadersRead", state.tag());
    try {
      String authority = getOrUpdateAuthority((AsciiString) headers.authority());
      NettyServerStream stream = new NettyServerStream(
          ctx.channel(),
          state,
          attributes,
          authority,
          statsTraceCtx,
          transportTracer);
      transportListener.streamCreated(stream, method, metadata);
      state.onStreamAllocated();
      http2Stream.setProperty(streamKey, state);
    } finally {
      PerfMark.stopTask("NettyServerHandler.onHeadersRead", state.tag());
    }
  } catch (Exception e) {
    logger.log(Level.WARNING, "Exception in onHeadersRead()", e);
    // Throw an exception that will get handled by onStreamError.
    throw newStreamException(streamId, e);
  }
}