Java Code Examples for net.bytebuddy.asm.Advice#Local

The following examples show how to use net.bytebuddy.asm.Advice#Local . 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: ApacheMonitorFilterAdvice.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onExitFilterInvoke(@Advice.Argument(1) Invocation invocation,
                                      @Advice.Return Result result,
                                      @Nullable @Advice.Local("span") final Span span,
                                      @Advice.Thrown Throwable t,
                                      @Nullable @Advice.Local("transaction") Transaction transaction) {

    RpcContext context = RpcContext.getContext();
    AbstractSpan<?> actualSpan = context.isConsumerSide() ? span : transaction;
    if (actualSpan == null) {
        return;
    }

    actualSpan.deactivate();
    if (result instanceof AsyncRpcResult) {
        AsyncCallbackCreator callbackCreator = asyncCallbackCreatorClassManager.getForClassLoaderOfClass(Result.class);
        if (callbackCreator == null) {
            actualSpan.end();
            return;
        }
        context.set(DubboTraceHelper.SPAN_KEY, actualSpan);
        result.whenCompleteWithContext(callbackCreator.create(actualSpan));
    } else {
        actualSpan.end();
    }
}
 
Example 2
Source File: OkHttp3ClientInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onAfterExecute(@Advice.Return @Nullable okhttp3.Response response,
                                  @Advice.Local("span") @Nullable Span span,
                                  @Advice.Thrown @Nullable Throwable t) {
    if (span != null) {
        try {
            if (response != null) {
                int statusCode = response.code();
                span.getContext().getHttp().withStatusCode(statusCode);
            }
            span.captureException(t);
        } finally {
            span.deactivate().end();
        }
    }
}
 
Example 3
Source File: ScheduledTransactionNameInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void setTransactionName(@SimpleMethodSignature String signature, @Advice.Origin Class<?> clazz, @Advice.Local("transaction") Transaction transaction) {
    if (tracer != null) {
        AbstractSpan<?> active = tracer.getActive();
        if (active == null) {
            transaction = tracer.startRootTransaction(clazz.getClassLoader());
            if (transaction != null) {
                transaction.withName(signature)
                    .withType("scheduled")
                    .activate();
            }

        } else {
            logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active);
        }
    }
}
 
Example 4
Source File: SpringRestTemplateInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void afterExecute(@Advice.Return @Nullable ClientHttpResponse clientHttpResponse,
                                 @Advice.Local("span") @Nullable Span span,
                                 @Advice.Thrown @Nullable Throwable t) throws IOException {
    if (span != null) {
        try {
            if (clientHttpResponse != null) {
                int statusCode = clientHttpResponse.getRawStatusCode();
                span.getContext().getHttp().withStatusCode(statusCode);
            }
            span.captureException(t);
        } finally {
            span.deactivate().end();
        }
    }
}
 
Example 5
Source File: CaptureSpanInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void onMethodEnter(
    @SimpleMethodSignatureOffsetMappingFactory.SimpleMethodSignature String signature,
    @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureSpan", method = "value") String spanName,
    @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureSpan", method = "type") String type,
    @Nullable @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureSpan", method = "subtype") String subtype,
    @Nullable @AnnotationValueOffsetMappingFactory.AnnotationValueExtractor(annotationClassName = "co.elastic.apm.api.CaptureSpan", method = "action") String action,
    @Advice.Local("span") Span span) {
    if (tracer != null) {
        final AbstractSpan<?> parent = tracer.getActive();
        if (parent != null) {
            span = parent.createSpan();
            span.setType(type, subtype, action);
            span.withName(spanName.isEmpty() ? signature : spanName)
                .activate();
        } else {
            logger.debug("Not creating span for {} because there is no currently active span.", signature);
        }
    }

}
 
Example 6
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onExit(@Advice.Thrown @Nullable Throwable thrown,
                           @Advice.This ServerCall.Listener<?> listener,
                           @Advice.Local("transaction") @Nullable Transaction transaction) {

    if (null == tracer || grpcHelperManager == null || transaction == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    helper.exitServerListenerMethod(thrown, listener, transaction, false);
}
 
Example 7
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onEnter(@Advice.This ServerCall.Listener<?> listener,
                            @Advice.Local("transaction") Transaction transaction) {

    if (null == tracer || grpcHelperManager == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    transaction = helper.enterServerListenerMethod(listener);
}
 
Example 8
Source File: Lettuce34StartSpanInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void beforeDispatch(@Nullable @Advice.Argument(0) RedisCommand command, @Advice.Local("span") Span span) throws Exception {
    if (command != null) {
        span = RedisSpanUtils.createRedisSpan(command.getType().toString());
        if (span != null) {
            commandToSpan.put(command, span);
        }
    }
}
 
Example 9
Source File: Lettuce5StartSpanInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void beforeDispatch(@Nullable @Advice.Argument(0) RedisCommand<?, ?, ?> command, @Advice.Local("span") Span span) throws Exception {
    if (command != null) {
        span = RedisSpanUtils.createRedisSpan(command.getType().name());
        if (span != null) {
            commandToSpan.put(command, span);
        }
    }
}
 
Example 10
Source File: ElasticsearchClientSyncInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onBeforeExecute(@Advice.Argument(0) Request request,
                                    @Advice.Local("span") Span span,
                                    @Advice.Local("helper") ElasticsearchRestClientInstrumentationHelper<HttpEntity, Response, ResponseListener> helper) {

    helper = esClientInstrHelperManager.getForClassLoaderOfClass(Request.class);
    if (helper != null) {
        span = helper.createClientSpan(request.getMethod(), request.getEndpoint(), request.getEntity());
    }
}
 
Example 11
Source File: ChannelInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onEnter(@Advice.This Channel channel,
                            @Advice.Argument(0) MethodDescriptor<?, ?> method,
                            @Advice.Local("span") Span span) {

    if (tracer == null || grpcHelperManager == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ClientCall.class);
    if (helper != null) {
        span = helper.startSpan(tracer.getActive(), method, channel.authority());
    }

}
 
Example 12
Source File: LegacyApacheHttpClientInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onBeforeExecute(@Advice.Argument(0) HttpHost host,
                                    @Advice.Argument(1) HttpRequest request,
                                    @Advice.Local("span") Span span) {
    if (tracer == null || tracer.getActive() == null) {
        return;
    }
    final AbstractSpan<?> parent = tracer.getActive();
    String method;
    if (request instanceof HttpUriRequest) {
        HttpUriRequest uriRequest = (HttpUriRequest) request;
        span = HttpClientHelper.startHttpClientSpan(parent, uriRequest.getMethod(), uriRequest.getURI(), host.getHostName());
        TextHeaderSetter<HttpRequest> headerSetter = headerSetterHelperClassManager.getForClassLoaderOfClass(HttpRequest.class);
        TextHeaderGetter<HttpRequest> headerGetter = headerGetterHelperClassManager.getForClassLoaderOfClass(HttpRequest.class);
        if (span != null) {
            span.activate();
            if (headerSetter != null) {
                span.propagateTraceContext(request, headerSetter);
            }
        } else if (headerGetter != null && !TraceContext.containsTraceContextTextHeaders(request, headerGetter)
            && headerSetter != null && parent != null) {
            // re-adds the header on redirects
            parent.propagateTraceContext(request, headerSetter);
        }

    }
}
 
Example 13
Source File: AlibabaMonitorFilterAdvice.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void onEnterFilterInvoke(@Advice.Argument(1) Invocation invocation,
                                       @Advice.Local("span") Span span,
                                       @Advice.Local("apiClazz") Class<?> apiClazz,
                                       @Advice.Local("transaction") Transaction transaction) {
    RpcContext context = RpcContext.getContext();
    AlibabaDubboAttachmentHelper helper = helperManager.getForClassLoaderOfClass(Invocation.class);
    if (helper == null || tracer == null) {
        return;
    }
    // for consumer side, just create span, more information will be collected in provider side
    AbstractSpan<?> active = tracer.getActive();
    if (context.isConsumerSide() && active != null) {
        span = DubboTraceHelper.createConsumerSpan(tracer, invocation.getInvoker().getInterface(),
            invocation.getMethodName(), context.getRemoteAddress());
        if (span != null) {
            span.propagateTraceContext(invocation, helper);
        }
    } else if (active == null) {
        // for provider side
        transaction = tracer.startChildTransaction(invocation, helper, Invocation.class.getClassLoader());
        if (transaction != null) {
            transaction.activate();
            DubboTraceHelper.fillTransaction(transaction, invocation.getInvoker().getInterface(), invocation.getMethodName());
        }
    }

}
 
Example 14
Source File: OkHttp3ClientAsyncInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onBeforeEnqueue(@Advice.Origin Class<? extends Call> clazz,
                                    @Advice.FieldValue(value = "originalRequest", typing = Assigner.Typing.DYNAMIC, readOnly = false) @Nullable okhttp3.Request originalRequest,
                                    @Advice.Argument(value = 0, readOnly = false) @Nullable Callback callback,
                                    @Advice.Local("span") Span span) {
    if (tracer == null || tracer.getActive() == null || callbackWrapperCreator == null) {
        return;
    }

    final WrapperCreator<Callback> wrapperCreator = callbackWrapperCreator.getForClassLoaderOfClass(clazz);
    if (originalRequest == null || callback == null || wrapperCreator == null) {
        return;
    }

    final AbstractSpan<?> parent = tracer.getActive();

    okhttp3.Request request = originalRequest;
    HttpUrl url = request.url();
    span = HttpClientHelper.startHttpClientSpan(parent, request.method(), url.toString(), url.scheme(),
        OkHttpClientHelper.computeHostName(url.host()), url.port());
    if (span != null) {
        span.activate();
        if (headerSetterHelperManager != null) {
            TextHeaderSetter<Request.Builder> headerSetter = headerSetterHelperManager.getForClassLoaderOfClass(Request.class);
            if (headerSetter != null) {
                Request.Builder builder = originalRequest.newBuilder();
                span.propagateTraceContext(builder, headerSetter);
                originalRequest = builder.build();
            }
        }
        callback = wrapperCreator.wrap(callback, span);
    }
}
 
Example 15
Source File: ApacheHttpAsyncClientInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
public static void onAfterExecute(@Advice.Local("span") @Nullable Span span,
                                  @Advice.Local("wrapped") boolean wrapped,
                                  @Advice.Thrown @Nullable Throwable t) {
    if (span != null) {
        // Deactivate in this thread. Span will be ended and reported by the listener
        span.deactivate();

        if (!wrapped) {
            // Listener is not wrapped- we need to end the span so to avoid leak and report error if occurred during method invocation
            span.captureException(t);
            span.end();
        }
    }
}
 
Example 16
Source File: ServerCallListenerInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onEnter(@Advice.This ServerCall.Listener<?> listener,
                            @Advice.Local("transaction") Transaction transaction) {

    if (null == tracer || grpcHelperManager == null) {
        return;
    }

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ServerCall.Listener.class);
    if (helper == null) {
        return;
    }

    transaction = helper.enterServerListenerMethod(listener);
}
 
Example 17
Source File: JobTransactionNameAdvice.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void setTransactionName(@Advice.Argument(value = 0) @Nullable JobExecutionContext context,
                                       @SimpleMethodSignature String signature, @Advice.Origin Class<?> clazz, @Advice.Local("transaction") Transaction transaction) {
    if (ElasticApmInstrumentation.tracer != null) {
        AbstractSpan<?> active = ElasticApmInstrumentation.tracer.getActive();
        if (context == null) {
            logger.warn("Cannot correctly name transaction for method {} because JobExecutionContext is null", signature);
            transaction = ElasticApmInstrumentation.tracer.startRootTransaction(clazz.getClassLoader());
            if (transaction != null) {
                transaction.withName(signature)
                    .withType(JobTransactionNameInstrumentation.TRANSACTION_TYPE)
                    .activate();
            }
        } else if (active == null) {
            transaction = ElasticApmInstrumentation.tracer.startRootTransaction(clazz.getClassLoader());
            if (transaction != null) {
                transaction.withName(context.getJobDetail().getKey().toString())
                    .withType(JobTransactionNameInstrumentation.TRANSACTION_TYPE)
                    .activate();
            }
        } else {
            logger.debug("Not creating transaction for method {} because there is already a transaction running ({})", signature, active);
        }
        if (transaction != null) {
            transaction.setFrameworkName("Quartz");
            transaction.setFrameworkVersion(VersionUtils.getVersion(JobExecutionContext.class, "org.quartz-scheduler", "quartz"));
        }
    }
}
 
Example 18
Source File: AbstractAsyncHttpClientInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onAfterExecute(@Advice.Local("span") @Nullable Span span,
                                   @Advice.Argument(value = 1) AsyncHandler<?> asyncHandler,
                                   @Advice.Thrown @Nullable Throwable t) {
    if (span != null) {
        span.deactivate();
        if (t != null) {
            handlerSpanMap.remove(asyncHandler);
            span.captureException(t).end();
        }
    }
}
 
Example 19
Source File: ClientCallImplInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class, onThrowable = Throwable.class)
private static void onExit(@Advice.Argument(0) ClientCall.Listener<?> listener,
                           @Advice.Thrown @Nullable Throwable thrown,
                           @Advice.Local("span") @Nullable Span span) {

    if (span == null) {
        return;
    }
    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ClientCall.class);
    if (helper != null) {
        helper.clientCallStartExit(listener, thrown);
    }
}
 
Example 20
Source File: KafkaProducerHeadersInstrumentation.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unused", "DuplicatedCode", "ParameterCanBeLocal"})
@Advice.OnMethodEnter(suppress = Throwable.class)
@Nullable
public static Span beforeSend(@Advice.FieldValue("apiVersions") final ApiVersions apiVersions,
                              @Advice.Argument(0) final ProducerRecord record,
                              @Advice.Local("helper") @Nullable KafkaInstrumentationHelper<Callback, ProducerRecord, KafkaProducer> helper,
                              @Nullable @Advice.Argument(value = 1, readOnly = false) Callback callback) {
    if (tracer == null) {
        return null;
    }
    Span span = null;

    //noinspection ConstantConditions
    helper = kafkaInstrHelperManager.getForClassLoaderOfClass(KafkaProducer.class);

    if (helper != null) {
        span = helper.onSendStart(record);
    }
    if (span == null) {
        return null;
    }

    // Avoid adding headers to records sent to a version older than 0.11.0 - see specifications in
    // https://kafka.apache.org/0110/documentation.html#messageformat
    if (apiVersions.maxUsableProduceMagic() >= RecordBatch.MAGIC_VALUE_V2 && headersSupported) {
        try {
            //noinspection ConstantConditions
            KafkaInstrumentationHeadersHelper<ConsumerRecord, ProducerRecord> kafkaInstrumentationHelper =
                kafkaInstrHeadersHelperManager.getForClassLoaderOfClass(KafkaProducer.class);
            if (kafkaInstrumentationHelper != null) {
                kafkaInstrumentationHelper.setOutgoingTraceContextHeaders(span, record);
            }
        } catch (final IllegalStateException e) {
            // headers are in a read-only state
            logger.debug("Failed to add header to Kafka record {}, probably to headers' read-only state.", record);
        }
    }

    //noinspection UnusedAssignment
    callback = helper.wrapCallback(callback, span);
    return span;
}