|
| 1 | + |
| 2 | +package org.tron.core.services.ratelimiter; |
| 3 | + |
| 4 | +import io.grpc.ForwardingServerCall; |
| 5 | +import io.grpc.Metadata; |
| 6 | +import io.grpc.ServerCall; |
| 7 | +import io.grpc.ServerCallHandler; |
| 8 | +import io.grpc.ServerInterceptor; |
| 9 | +import io.grpc.Status; |
| 10 | +import io.prometheus.client.Histogram; |
| 11 | +import lombok.extern.slf4j.Slf4j; |
| 12 | +import org.springframework.stereotype.Component; |
| 13 | +import org.tron.common.prometheus.MetricKeys; |
| 14 | +import org.tron.common.prometheus.Metrics; |
| 15 | + |
| 16 | +/** |
| 17 | + * A {@link ServerInterceptor} which sends latency stats about incoming grpc calls to Prometheus. |
| 18 | + */ |
| 19 | +@Slf4j(topic = "metrics") |
| 20 | +@Component |
| 21 | +public class PrometheusInterceptor implements ServerInterceptor { |
| 22 | + |
| 23 | + @Override |
| 24 | + public <R, S> ServerCall.Listener<R> interceptCall( |
| 25 | + ServerCall<R, S> call, Metadata requestMetadata, ServerCallHandler<R, S> next) { |
| 26 | + return next.startCall(new MonitoringServerCall<>(call), requestMetadata); |
| 27 | + } |
| 28 | + |
| 29 | + static class MonitoringServerCall<R, S> extends ForwardingServerCall |
| 30 | + .SimpleForwardingServerCall<R, S> { |
| 31 | + |
| 32 | + private final Histogram.Timer requestTimer; |
| 33 | + |
| 34 | + MonitoringServerCall(ServerCall<R, S> delegate) { |
| 35 | + super(delegate); |
| 36 | + this.requestTimer = Metrics.histogramStartTimer( |
| 37 | + MetricKeys.Histogram.GRPC_SERVICE_LATENCY, getMethodDescriptor().getFullMethodName()); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public void close(Status status, Metadata responseHeaders) { |
| 42 | + Metrics.histogramObserve(requestTimer); |
| 43 | + super.close(status, responseHeaders); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments