io.micrometer.core.instrument.Timer.Sample Java Examples

The following examples show how to use io.micrometer.core.instrument.Timer.Sample. 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: EndpointMetricsFilter.java    From syndesis with Apache License 2.0 6 votes vote down vote up
/**
 * Called after the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    Sample sample = (Sample) requestContext.getProperty(TIMING_SAMPLE);
    if (sample != null) {
        Timer timer = Timer
            .builder("http.server.requests")
            // no way to access the exception
            .tag("exception", "")
            .tag("outcome", computeOutcome(responseContext))
            .tag("method", getMethod(requestContext))
            .tag("status", getStatus(responseContext))
            .tag("uri", getUri())
            .publishPercentileHistogram()
            .maximumExpectedValue(Duration.ofSeconds(10))
            .register(registry);
        sample.stop(timer);
    }
}
 
Example #2
Source File: GatewayMetricsFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private void endTimerRespectingCommit(ServerWebExchange exchange, Sample sample) {

		ServerHttpResponse response = exchange.getResponse();
		if (response.isCommitted()) {
			endTimerInner(exchange, sample);
		}
		else {
			response.beforeCommit(() -> {
				endTimerInner(exchange, sample);
				return Mono.empty();
			});
		}
	}
 
Example #3
Source File: NoopBasedMetrics.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void reportTelemetry(
        final MetricsTags.EndpointType type,
        final String tenantId,
        final TenantObject tenantObject,
        final ProcessingOutcome outcome,
        final MetricsTags.QoS qos,
        final int payloadSize,
        final Sample timer) {
}
 
Example #4
Source File: NoopBasedMetrics.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void reportTelemetry(
        final MetricsTags.EndpointType type,
        final String tenantId,
        final TenantObject tenantObject,
        final ProcessingOutcome outcome,
        final MetricsTags.QoS qos,
        final int payloadSize,
        final MetricsTags.TtdStatus ttdStatus,
        final Sample timer) {
}
 
Example #5
Source File: NoopBasedMetrics.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void reportCommand(
        final Direction direction,
        final String tenantId,
        final TenantObject tenantObject,
        final ProcessingOutcome outcome,
        final int payloadSize,
        final Sample timer) {
}
 
Example #6
Source File: MicrometerBasedMetrics.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void reportTelemetry(
        final MetricsTags.EndpointType type,
        final String tenantId,
        final TenantObject tenantObject,
        final ProcessingOutcome outcome,
        final MetricsTags.QoS qos,
        final int payloadSize,
        final Sample timer) {
    reportTelemetry(type, tenantId, tenantObject, outcome, qos, payloadSize, MetricsTags.TtdStatus.NONE, timer);
}
 
Example #7
Source File: MicrometerBasedMetrics.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void reportCommand(
        final Direction direction,
        final String tenantId,
        final TenantObject tenantObject,
        final ProcessingOutcome outcome,
        final int payloadSize,
        final Sample timer) {

    Objects.requireNonNull(direction);
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(outcome);
    Objects.requireNonNull(timer);

    if (payloadSize < 0) {
        throw new IllegalArgumentException("payload size must not be negative");
    }

    final Tags tags = Tags.of(direction.asTag())
            .and(MetricsTags.getTenantTag(tenantId))
            .and(outcome.asTag());

    timer.stop(this.registry.timer(METER_COMMANDS_RECEIVED, tags));

    // record payload size
    DistributionSummary.builder(METER_COMMANDS_PAYLOAD)
        .baseUnit("bytes")
        .minimumExpectedValue(0L)
        .tags(tags)
        .register(this.registry)
        .record(ServiceBaseUtils.calculatePayloadSize(payloadSize, tenantObject));

    updateLastSeenTimestamp(tenantId);
}
 
Example #8
Source File: GatewayMetricsFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	Sample sample = Timer.start(meterRegistry);

	return chain.filter(exchange)
			.doOnSuccess(aVoid -> endTimerRespectingCommit(exchange, sample))
			.doOnError(throwable -> endTimerRespectingCommit(exchange, sample));
}
 
Example #9
Source File: CoapContext.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new context for a CoAP request.
 *
 * @param request The CoAP exchange representing the request.
 * @param timer The object to use for measuring the time it takes to process the request.
 * @return The context.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public static CoapContext fromRequest(final CoapExchange request, final Sample timer) {
    Objects.requireNonNull(request);
    Objects.requireNonNull(timer);

    final CoapContext result = new CoapContext(request);
    result.timer = timer;
    return result;
}
 
Example #10
Source File: GatewayMetricsFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private void endTimerInner(ServerWebExchange exchange, Sample sample) {
	Tags tags = compositeTagsProvider.apply(exchange);

	if (log.isTraceEnabled()) {
		log.trace("gateway.requests tags: " + tags);
	}
	sample.stop(meterRegistry.timer("gateway.requests", tags));
}
 
Example #11
Source File: MetricsCircuitBreakerListener.java    From riptide with MIT License 5 votes vote down vote up
private void on(final State to) {
    final State from = state.getAndSet(to);
    final Sample last = sample.getAndSet(start(registry));

    if (from != CLOSED) {
        last.stop(registry.timer(metricName, tags(from)));
    }
}
 
Example #12
Source File: MicrometerRSocket.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Payload> requestResponse(Payload payload) {
  return Mono.defer(
      () -> {
        Sample sample = requestResponse.start();

        return delegate
            .requestResponse(payload)
            .doFinally(signalType -> requestResponse.accept(sample, signalType));
      });
}
 
Example #13
Source File: MicrometerRSocket.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(Sample sample, SignalType signalType) {
  switch (signalType) {
    case CANCEL:
      sample.stop(cancel);
      break;
    case ON_COMPLETE:
      sample.stop(onComplete);
      break;
    case ON_ERROR:
      sample.stop(onError);
      break;
  }
}
 
Example #14
Source File: EndpointMetricsFilter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Called after the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    Sample sample = (Sample) requestContext.getProperty(TIMING_SAMPLE);
    if (sample != null) {
        List<Tag> tags = new ArrayList<Tag>();
        tags.add(Tag.of("method", getMethod(requestContext)));
        tags.add(Tag.of("status", getStatus(responseContext)));
        tags.add(Tag.of("uri", getUri()));
        sample.stop(registry.timer("http.meta.requests", tags));
    }
}
 
Example #15
Source File: MicrometerRSocket.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
Sample start() {
  return Timer.start(meterRegistry);
}
 
Example #16
Source File: MicrometerBasedMetricsTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that arbitrary telemetry messages with or without a QoS
 * can be reported successfully.
 *
 * @param registry The registry that the tests should be run against.
 */
@ParameterizedTest
@MethodSource("registries")
public void testReportTelemetryWithOptionalQos(final MeterRegistry registry) {

    final MicrometerBasedMetrics metrics = new MicrometerBasedMetrics(registry, mock(Vertx.class));

    // GIVEN a sample
    final Sample sample = metrics.startTimer();

    // WHEN reporting a telemetry message with a QoS of AT_LEAST_ONCE
    // and no TTD
    metrics.reportTelemetry(
            MetricsTags.EndpointType.TELEMETRY,
            "tenant",
            TenantObject.from("tenant", true),
            MetricsTags.ProcessingOutcome.FORWARDED,
            MetricsTags.QoS.AT_LEAST_ONCE,
            1024,
            MetricsTags.TtdStatus.NONE,
            sample);

    // THEN the meter can be found in the registry with the tags that have a known value
    final Tags expectedTags = Tags.of(MetricsTags.EndpointType.TELEMETRY.asTag())
            .and(MetricsTags.getTenantTag("tenant"))
            .and(MetricsTags.ProcessingOutcome.FORWARDED.asTag())
            .and(MetricsTags.QoS.AT_LEAST_ONCE.asTag());
    assertNotNull(registry.find(MicrometerBasedMetrics.METER_MESSAGES_RECEIVED).tags(expectedTags).timer());

    // and reporting another telemetry message with no QoS but with a TTD status succeeds

    final Sample otherSample = metrics.startTimer();

    metrics.reportTelemetry(
            MetricsTags.EndpointType.TELEMETRY,
            "tenant",
            TenantObject.from("tenant", true),
            MetricsTags.ProcessingOutcome.FORWARDED,
            MetricsTags.QoS.UNKNOWN,
            1024,
            MetricsTags.TtdStatus.EXPIRED,
            otherSample);
}
 
Example #17
Source File: MicrometerBasedMetrics.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public final void reportTelemetry(
        final MetricsTags.EndpointType type,
        final String tenantId,
        final TenantObject tenantObject,
        final MetricsTags.ProcessingOutcome outcome,
        final MetricsTags.QoS qos,
        final int payloadSize,
        final MetricsTags.TtdStatus ttdStatus,
        final Sample timer) {

    Objects.requireNonNull(type);
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(outcome);
    Objects.requireNonNull(qos);
    Objects.requireNonNull(ttdStatus);
    Objects.requireNonNull(timer);

    if (type != MetricsTags.EndpointType.TELEMETRY && type != MetricsTags.EndpointType.EVENT) {
        throw new IllegalArgumentException("invalid type, must be either telemetry or event");
    } else if (payloadSize < 0) {
        throw new IllegalArgumentException("payload size must not be negative");
    }

    final Tags tags = Tags.of(type.asTag())
            .and(MetricsTags.getTenantTag(tenantId))
            .and(outcome.asTag())
            .and(qos.asTag())
            .and(ttdStatus.asTag());

    timer.stop(this.registry.timer(METER_MESSAGES_RECEIVED, tags));

    // record payload size
    DistributionSummary.builder(METER_MESSAGES_PAYLOAD)
        .baseUnit("bytes")
        .minimumExpectedValue(0L)
        .tags(tags)
        .register(this.registry)
        .record(ServiceBaseUtils.calculatePayloadSize(payloadSize, tenantObject));

    updateLastSeenTimestamp(tenantId);
}
 
Example #18
Source File: MicrometerBasedMetrics.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Sample startTimer() {
    return Timer.start(registry);
}
 
Example #19
Source File: EndpointMetricsFilter.java    From syndesis with Apache License 2.0 4 votes vote down vote up
/**
 * Called before the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    Sample sample = Timer.start(registry);
    requestContext.setProperty(TIMING_SAMPLE, sample);
}
 
Example #20
Source File: NoopBasedMetrics.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public Sample startTimer() {
    return null;
}
 
Example #21
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<ProtocolAdapterCommandConsumer> createCommandConsumer(
        final ProtonSender sender,
        final ResourceIdentifier sourceAddress,
        final Device authenticatedDevice,
        final Span span) {

    final Handler<CommandContext> commandHandler = commandContext -> {

        final Sample timer = metrics.startTimer();
        addMicrometerSample(commandContext, timer);
        Tags.COMPONENT.set(commandContext.getCurrentSpan(), getTypeName());
        final Command command = commandContext.getCommand();
        final Future<TenantObject> tenantTracker = getTenantConfiguration(sourceAddress.getTenantId(),
                commandContext.getTracingContext());

        tenantTracker.compose(tenantObject -> {
            if (!command.isValid()) {
                return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "malformed command message"));
            }
            if (!sender.isOpen()) {
                return Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE,
                        "sender link is not open"));
            }
            return checkMessageLimit(tenantObject, command.getPayloadSize(), commandContext.getTracingContext());
        }).compose(success -> {
            onCommandReceived(tenantTracker.result(), sender, commandContext);
            return Future.succeededFuture();
        }).otherwise(failure -> {
            if (failure instanceof ClientErrorException) {
                commandContext.reject(getErrorCondition(failure));
            } else {
                commandContext.release();
            }
            metrics.reportCommand(
                    command.isOneWay() ? Direction.ONE_WAY : Direction.REQUEST,
                    sourceAddress.getTenantId(),
                    tenantTracker.result(),
                    ProcessingOutcome.from(failure),
                    command.getPayloadSize(),
                    timer);
            return null;
        });
    };
    if (authenticatedDevice != null && !authenticatedDevice.getDeviceId().equals(sourceAddress.getResourceId())) {
        // gateway scenario
        return getCommandConsumerFactory().createCommandConsumer(sourceAddress.getTenantId(),
                sourceAddress.getResourceId(), authenticatedDevice.getDeviceId(), commandHandler, null, span.context());
    } else {
        return getCommandConsumerFactory().createCommandConsumer(sourceAddress.getTenantId(),
                sourceAddress.getResourceId(), commandHandler, null, span.context());
    }
}
 
Example #22
Source File: AbstractVertxBasedHttpProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Sample getMicrometerSample(final RoutingContext ctx) {
    return ctx.get(KEY_MICROMETER_SAMPLE);
}
 
Example #23
Source File: AbstractVertxBasedMqttProtocolAdapter.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private Future<ProtocolAdapterCommandConsumer> createCommandConsumer(final MqttEndpoint mqttEndpoint,
        final CommandSubscription sub, final CommandSubscriptionsManager<T> cmdHandler, final Span span) {

    final Handler<CommandContext> commandHandler = commandContext -> {

        Tags.COMPONENT.set(commandContext.getCurrentSpan(), getTypeName());
        final Sample timer = metrics.startTimer();
        final Command command = commandContext.getCommand();
        final Future<TenantObject> tenantTracker = getTenantConfiguration(sub.getTenant(),
                commandContext.getTracingContext());

        tenantTracker.compose(tenantObject -> {
            if (!command.isValid()) {
                return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "malformed command message"));
            }
            return checkMessageLimit(tenantObject, command.getPayloadSize(), commandContext.getTracingContext());
        }).compose(success -> {
            addMicrometerSample(commandContext, timer);
            onCommandReceived(tenantTracker.result(), mqttEndpoint, sub, commandContext, cmdHandler);
            return Future.succeededFuture();
        }).otherwise(failure -> {
            if (failure instanceof ClientErrorException) {
                commandContext.reject(getErrorCondition(failure));
            } else {
                commandContext.release();
            }
            metrics.reportCommand(
                    command.isOneWay() ? Direction.ONE_WAY : Direction.REQUEST,
                    sub.getTenant(),
                    tenantTracker.result(),
                    ProcessingOutcome.from(failure),
                    command.getPayloadSize(),
                    timer);
            return null;
        });
    };
    if (sub.isGatewaySubscriptionForSpecificDevice()) {
        // gateway scenario
        return getCommandConsumerFactory().createCommandConsumer(sub.getTenant(), sub.getDeviceId(),
                sub.getAuthenticatedDeviceId(), commandHandler, null, span.context());
    } else {
        return getCommandConsumerFactory().createCommandConsumer(sub.getTenant(), sub.getDeviceId(), commandHandler,
                null, span.context());
    }
}
 
Example #24
Source File: EndpointMetricsFilter.java    From syndesis with Apache License 2.0 4 votes vote down vote up
/**
 * Called before the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    Sample sample = Timer.start(registry);
    requestContext.setProperty(TIMING_SAMPLE, sample);
}
 
Example #25
Source File: Metrics.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Reports a command &amp; control message being transferred to/from a device.
 * <p> 
 * The payload size of the message is calculated based on the configured 
 * minimum message size and the calculated size is reported. 
 * <p>
 * The configured minimum message size is retrieved from the tenant 
 * configuration object.
 *
 * @param direction The command message's direction.
 * @param tenantId The tenant that the device belongs to.
 * @param tenantObject The tenant configuration object or {@code null}.
 * @param outcome The outcome of processing the message.
 * @param payloadSize The number of bytes contained in the message's payload.
 * @param timer The timer indicating the amount of time used
 *              for processing the message.
 * @throws NullPointerException if any of the parameters except the tenant object are {@code null}.
 * @throws IllegalArgumentException if payload size is negative.
 */
void reportCommand(
        MetricsTags.Direction direction,
        String tenantId,
        TenantObject tenantObject,
        MetricsTags.ProcessingOutcome outcome,
        int payloadSize,
        Sample timer);
 
Example #26
Source File: Metrics.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Reports a telemetry message or event received from a device.
 * <p> 
 * The payload size of the message is calculated based on the configured 
 * minimum message size and the calculated size is reported. 
 * <p>
 * The configured minimum message size is retrieved from the tenant 
 * configuration object.
 *
 * @param type The type of message received, e.g. <em>telemetry</em> or <em>event</em>.
 * @param tenantId The tenant that the device belongs to.
 * @param tenantObject The tenant configuration object or {@code null}.
 * @param outcome The outcome of processing the message.
 * @param qos The delivery semantics used for sending the message downstream.
 * @param payloadSize The number of bytes contained in the message's payload.
 * @param ttdStatus The outcome of processing the TTD value contained in the message.
 * @param timer The timer indicating the amount of time used
 *              for processing the message.
 * @throws NullPointerException if any of the parameters except the tenant object are {@code null}.
 * @throws IllegalArgumentException if type is neither telemetry nor event or
 *                    if payload size is negative.
 */
void reportTelemetry(
        MetricsTags.EndpointType type,
        String tenantId,
        TenantObject tenantObject,
        MetricsTags.ProcessingOutcome outcome,
        MetricsTags.QoS qos,
        int payloadSize,
        MetricsTags.TtdStatus ttdStatus,
        Sample timer);
 
Example #27
Source File: Metrics.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Reports a telemetry message or event received from a device. 
 * <p> 
 * The payload size of the message is calculated based on the configured 
 * minimum message size and the calculated size is reported. 
 * <p>
 * The configured minimum message size is retrieved from the tenant 
 * configuration object.
 *
 * @param type The type of message received, e.g. <em>telemetry</em> or <em>event</em>.
 * @param tenantId The tenant that the device belongs to.
 * @param tenantObject The tenant configuration object or {@code null}.
 * @param outcome The outcome of processing the message.
 * @param qos The delivery semantics used for sending the message downstream.
 * @param payloadSize The number of bytes contained in the message's payload.
 * @param timer The timer indicating the amount of time used
 *              for processing the message.
 * @throws NullPointerException if any of the parameters except the tenant object are {@code null}.
 * @throws IllegalArgumentException if type is neither telemetry nor event or
 *                    if payload size is negative.
 */
void reportTelemetry(
        MetricsTags.EndpointType type,
        String tenantId,
        TenantObject tenantObject,
        MetricsTags.ProcessingOutcome outcome,
        MetricsTags.QoS qos,
        int payloadSize,
        Sample timer);
 
Example #28
Source File: Metrics.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Starts a new timer.
 *
 * @return The newly created timer.
 */
Sample startTimer();
 
Example #29
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Adds a Micrometer sample to a command context.
 *
 * @param ctx The context to add the sample to.
 * @param sample The sample.
 * @throws NullPointerException if ctx is {@code null}.
 */
protected static final void addMicrometerSample(final CommandContext ctx, final Sample sample) {
    Objects.requireNonNull(ctx);
    ctx.put(KEY_MICROMETER_SAMPLE, sample);
}
 
Example #30
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Gets the timer used to track the processing of a command message.
 *
 * @param ctx The command context to extract the sample from.
 * @return The sample or {@code null} if the context does not
 *         contain a sample.
 * @throws NullPointerException if ctx is {@code null}.
 */
protected static final Sample getMicrometerSample(final CommandContext ctx) {
    Objects.requireNonNull(ctx);
    return ctx.get(KEY_MICROMETER_SAMPLE);
}