net.bytebuddy.asm.Advice Java Examples

The following examples show how to use net.bytebuddy.asm.Advice. 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: SpecialAgentAgent.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit
public static void exit(final @Advice.Argument(0) ClassLoader classLoader, final @Advice.Argument(1) String arg, @Advice.Return(readOnly=false, typing=Typing.DYNAMIC) Enumeration<URL> returned) {
  try {
    String classpath = System.getProperty("java.class.path");
    final int index = classpath.indexOf("/opentracing-api-");
    final int start = classpath.lastIndexOf(File.pathSeparatorChar, index);
    final int end = classpath.indexOf(File.pathSeparatorChar, index);
    classpath = classpath.substring(start + 1, end != -1 ? end : classpath.length());
    if (!classpath.endsWith(".jar") && !classpath.endsWith("/"))
      classpath += "/";

    try (final RuleClassLoader ruleClassLoader = new RuleClassLoader(null, null, null, new File(classpath))) {
      returned = ruleClassLoader.getResources(arg); // Why is findResources(arg) not returning expected results?
      returned.hasMoreElements(); // For some reason, if I don't call this, the returned value does not have any elements!!!!
    }

    if (logger.isLoggable(Level.FINEST))
      logger.finest("<<<<<<< Agent#findResources(" + (classLoader == null ? "null" : classLoader.getClass().getName() + "@" + Integer.toString(System.identityHashCode(classLoader), 16)) + "," + arg + "): " + returned);
  }
  catch (final Throwable t) {
    logger.log(Level.SEVERE, "<><><><> AgentAgent.FindResources#exit", t);
  }
}
 
Example #2
Source File: AllowancesByteBuddyTransformer.java    From BlockHound with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter
static BlockHoundRuntime.State onEnter(
        @AllowancesByteBuddyTransformer.AllowedArgument boolean allowed
) {
    BlockHoundRuntime.State previous = BlockHoundRuntime.STATE.get();
    if (previous == null) {
        return null;
    }

    if (previous.isAllowed() == allowed) {
        // if we won't change the flag, return `null` and skip the `onExit` part
        return null;
    }

    // Otherwise, set to `allowed` and reset to `!allowed` in `onExit`
    previous.setAllowed(allowed);
    return previous;
}
 
Example #3
Source File: ClientCallImplInstrumentation.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onEnter(@Advice.This ClientCall<?, ?> clientCall,
                            @Advice.Argument(0) ClientCall.Listener<?> listener,
                            @Advice.Argument(1) Metadata headers,
                            @Advice.Local("span") Span span) {

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

    ElasticApmAgent.ensureInstrumented(listener.getClass(), RESPONSE_LISTENER_INSTRUMENTATIONS);

    GrpcHelper helper = grpcHelperManager.getForClassLoaderOfClass(ClientCall.class);
    if (helper != null) {
        span = helper.clientCallStartEnter(clientCall, listener, headers);
    }

}
 
Example #4
Source File: BootLoaderAgent.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Advice.OnMethodExit
public static void exit(final @Advice.Argument(0) JarFile arg) {
  try {
    if (jarFiles == null) {
      jarFiles = new JarFile[] {arg};
    }
    else {
      final int len = jarFiles.length;
      final JarFile[] temp = new JarFile[len + 1];
      System.arraycopy(jarFiles, 0, temp, 0, len);
      temp[len] = arg;
      jarFiles = temp;
    }
  }
  catch (final Throwable t) {
    log("<><><><> BootLoaderAgent.AppendToBootstrap#exit", t, DefaultLevel.SEVERE);
  }
}
 
Example #5
Source File: CodeTemplates.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Advice.OnMethodExit
static void $$_hibernate_getDirtyAttributes(
		@Advice.This ExtendedSelfDirtinessTracker self,
		@Advice.Return(readOnly = false) String[] returned,
		@Advice.FieldValue(value = EnhancerConstants.TRACKER_FIELD_NAME, readOnly = false) DirtyTracker $$_hibernate_tracker,
		@Advice.FieldValue(value = EnhancerConstants.TRACKER_COLLECTION_NAME, readOnly = false) CollectionTracker $$_hibernate_collectionTracker) {
	if ( $$_hibernate_collectionTracker == null ) {
		returned = ( $$_hibernate_tracker == null ) ? new String[0] : $$_hibernate_tracker.get();
	}
	else {
		if ( $$_hibernate_tracker == null ) {
			$$_hibernate_tracker = new SimpleFieldTracker();
		}
		self.$$_hibernate_getCollectionFieldDirtyNames( $$_hibernate_tracker );
		returned = $$_hibernate_tracker.get();
	}
}
 
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) {
        return;
    }

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

    helper.exitServerListenerMethod(thrown, listener, transaction, true);
}
 
Example #7
Source File: ApacheHttpClientInstrumentation.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 CloseableHttpResponse response,
                                  @Advice.Local("span") @Nullable Span span,
                                  @Advice.Thrown @Nullable Throwable t) {
    if (span != null) {
        try {
            if (response != null && response.getStatusLine() != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                span.getContext().getHttp().withStatusCode(statusCode);
            }
            span.captureException(t);
        } finally {
            span.deactivate().end();
        }
    }
}
 
Example #8
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 #9
Source File: SpanContextInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
public static void toTraceId(@Advice.FieldValue(value = "traceContext", typing = Assigner.Typing.DYNAMIC) @Nullable AbstractSpan<?> traceContext,
                             @Advice.Return(readOnly = false) String spanId) {
    if (traceContext != null) {
        spanId = traceContext.getTraceContext().getId().toString();
    }
}
 
Example #10
Source File: FutureInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@VisibleForAdvice
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void onEnter(@Advice.This Object thiz, @Nullable @Advice.Local("context") AbstractSpan<?> context) {
    context = promisesToContext.remove(thiz);
    if (tracer != null && context != null) {
        tracer.activate(context);
        // decrements the reference we incremented to avoid that the parent context gets recycled before the promise is run
        // because we have activated it, we can be sure it doesn't get recycled until we deactivate in the OnMethodExit advice
        context.decrementReferences();
    }
}
 
Example #11
Source File: JsfLifecycleInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("Duplicates")
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void createExecuteSpan(@Advice.Argument(0) javax.faces.context.FacesContext facesContext,
                                     @Advice.Local("span") Span span) {
    if (tracer != null) {
        final AbstractSpan<?> parent = tracer.getActive();
        if (parent == null) {
            return;
        }
        if (parent instanceof Span) {
            Span parentSpan = (Span)parent;
            if (SPAN_SUBTYPE.equals(parentSpan.getSubtype()) && SPAN_ACTION.equals(parentSpan.getAction())) {
                return;
            }
        }
        Transaction transaction = tracer.currentTransaction();
        if (transaction != null) {
            try {
                javax.faces.context.ExternalContext externalContext = facesContext.getExternalContext();
                if (externalContext != null) {
                    transaction.withName(externalContext.getRequestServletPath(), PRIO_HIGH_LEVEL_FRAMEWORK);
                    String pathInfo = externalContext.getRequestPathInfo();
                    if (pathInfo != null) {
                        transaction.appendToName(pathInfo, PRIO_HIGH_LEVEL_FRAMEWORK);
                    }
                }
                transaction.setFrameworkName(FRAMEWORK_NAME);
            } catch (Exception e) {
                // do nothing- rely on the default servlet name logic
            }
        }
        span = parent.createSpan()
            .withType(SPAN_TYPE)
            .withSubtype(SPAN_SUBTYPE)
            .withAction(SPAN_ACTION)
            .withName("JSF Execute");
        span.activate();
    }
}
 
Example #12
Source File: CodeTemplates.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Advice.OnMethodExit
static void exit(@Advice.This CompositeOwner self, @FieldName String fieldName, @FieldValue Object field) {
	if ( field != null ) {
		( (CompositeTracker) field ).$$_hibernate_setOwner( fieldName, self );
	}
	self.$$_hibernate_trackChange( fieldName );
}
 
Example #13
Source File: CodeTemplates.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Advice.OnMethodEnter
static void $$_hibernate_trackChange(
		@Advice.Argument(0) String name,
		@Advice.FieldValue(value = EnhancerConstants.TRACKER_FIELD_NAME, readOnly = false) DirtyTracker $$_hibernate_tracker) {
	if ( $$_hibernate_tracker == null ) {
		$$_hibernate_tracker = new SimpleFieldTracker();
	}
	$$_hibernate_tracker.add( name );
}
 
Example #14
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 #15
Source File: AbstractLoggerErrorCapturingInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void logEnter(@Advice.Argument(1) Throwable exception,
                            @Advice.Local("nested") boolean nested,
                            @Advice.Origin Class<?> clazz,
                            @Advice.Local("error") @Nullable ErrorCapture error) {
    if (tracer == null) {
        return;
    }
    nested = nestedThreadLocal.get();
    if (!nested) {
        error = tracer.captureException(exception, tracer.getActive(), clazz.getClassLoader()).activate();
        nestedThreadLocal.set(Boolean.TRUE);
    }
}
 
Example #16
Source File: JmsMessageProducerInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
@Nullable
public static Span startSpan(@Advice.Argument(0) final Destination destination,
                             @Advice.Argument(1) final Message message) {
    //noinspection ConstantConditions - the Advice must be invoked only if the BaseJmsInstrumentation constructor was invoked
    JmsInstrumentationHelper<Destination, Message, MessageListener> helper =
        jmsInstrHelperManager.getForClassLoaderOfClass(MessageProducer.class);
    if (helper != null) {
        return helper.startJmsSendSpan(destination, message);
    }
    return null;
}
 
Example #17
Source File: AbstractLoggerErrorCapturingInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
public static void logExit(@Advice.Local("nested") boolean nested,
                           @Advice.Local("error") @Nullable ErrorCapture error) {
    if (error != null) {
        error.deactivate().end();
    }
    if (!nested) {
        nestedThreadLocal.set(Boolean.FALSE);
    }
}
 
Example #18
Source File: Lettuce5StopSpanInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void beforeComplete(@Advice.This RedisCommand command) {
    if (!command.isDone() && !command.isCancelled()) {
        Span span = commandToSpan.remove(command);
        if (span != null) {
            logger.debug("Command#cancel");
            span.end();
        }
    }
}
 
Example #19
Source File: ClassLoaderAgent.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
    @Advice.OnMethodExit(onThrowable = ClassNotFoundException.class)
    public static void exit(final @Advice.This ClassLoader thiz, final @Advice.Argument(0) String name, @Advice.Return(readOnly=false, typing=Typing.DYNAMIC) Class<?> returned, @Advice.Thrown(readOnly = false, typing = Typing.DYNAMIC) ClassNotFoundException thrown) {
      if (returned != null || isExcluded(thiz))
        return;

      final Set<String> visited;
      if (!(visited = mutex.get()).add(name))
        return;

      try {
        final Class<?> bootstrapClass = BootProxyClassLoader.INSTANCE.loadClassOrNull(name, false);
        if (bootstrapClass != null) {
//          log(">>>>>>>> BootLoader#loadClassOrNull(\"" + name + "\"): " + bootstrapClass, null, DefaultLevel.FINEST);

          returned = bootstrapClass;
          thrown = null;
          return;
        }

        final byte[] bytecode = SpecialAgent.findClass(thiz, name);
        if (bytecode == null)
          return;

//        log("<<<<<<<< defineClass(\"" + name + "\")", null, DefaultLevel.FINEST);

        if (defineClass == null)
          defineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class, ProtectionDomain.class);

        returned = (Class<?>)defineClass.invoke(thiz, name, bytecode, 0, bytecode.length, null);
        thrown = null;
      }
      catch (final Throwable t) {
        log("<><><><> ClassLoaderAgent.LoadClass#exit(\"" + name + "\")", t, DefaultLevel.SEVERE);
      }
      finally {
        visited.remove(name);
      }
    }
 
Example #20
Source File: AlibabaResponseCallbackInstrumentation.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.Thrown Throwable thrown,
                           @Nullable @Advice.Local("span") AbstractSpan<?> span,
                           @Nullable @Advice.Argument(0) Object response) {
    if (span == null) {
        return;
    }
    if (response instanceof Result) {
        span.captureException(((Result) response).getException());
    }
    span.captureException(thrown).deactivate().end();
}
 
Example #21
Source File: StatementInstrumentation.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.This Statement statement,
                                  @Advice.Enter @Nullable Span span,
                                  @Advice.Thrown @Nullable Throwable t) {

    if (span == null) {
        return;
    }

    span.captureException(t)
        .deactivate()
        .end();
}
 
Example #22
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 #23
Source File: AbstractSpanInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@VisibleForAdvice
@Advice.OnMethodEnter(suppress = Throwable.class)
public static void setType(@Advice.FieldValue(value = "span", typing = Assigner.Typing.DYNAMIC) AbstractSpan<?> context,
                           @Advice.Argument(0) String type) {
    if (context instanceof Transaction) {
        ((Transaction) context).withType(type);
    } else if (context instanceof Span) {
        ((Span) context).setType(type, null, null);
    }
}
 
Example #24
Source File: CodeTemplates.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Advice.OnMethodEnter
static void enter(@FieldValue Collection<?> field, @Advice.Argument(0) Collection<?> argument, @MappedBy String mappedBy) {
	if ( field != null && Hibernate.isPropertyInitialized( field, mappedBy ) ) {
		Object[] array = field.toArray();
		for ( int i = 0; i < array.length; i++ ) {
			if ( argument == null || !argument.contains( array[i] ) ) {
				setterNull( array[i], null );
			}
		}
	}
}
 
Example #25
Source File: ExecutorInstrumentation.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public DynamicType.Builder<?> transform(
    DynamicType.Builder<?> builder,
    TypeDescription typeDescription,
    ClassLoader classLoader,
    JavaModule module) {
  return builder.visit(Advice.to(Execute.class).on(named("execute")));
}
 
Example #26
Source File: AbstractSpanInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@VisibleForAdvice
@Advice.OnMethodExit(suppress = Throwable.class)
public static void captureException(@Advice.FieldValue(value = "span", typing = Assigner.Typing.DYNAMIC) AbstractSpan<?> context,
                                    @Advice.Argument(0) Throwable t,
                                    @Advice.Return(readOnly = false) String errorId) {
    errorId = context.captureExceptionAndGetErrorId(t);
}
 
Example #27
Source File: ElasticApmApiInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@VisibleForAdvice
@Advice.OnMethodExit(suppress = Throwable.class)
private static void doStartTransaction(@Advice.Origin Class<?> clazz, @Advice.Return(readOnly = false) Object transaction) {
    if (tracer != null) {
        transaction = tracer.startRootTransaction(clazz.getClassLoader());
        if (transaction != null) {
            ((Transaction) transaction).setFrameworkName(FRAMEWORK_NAME);
        }
    }
}
 
Example #28
Source File: ElasticApmApiInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@VisibleForAdvice
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void captureException(@Advice.Origin Class<?> clazz, @Advice.Argument(0) @Nullable Throwable e) {
    if (tracer != null) {
        tracer.captureAndReportException(e, clazz.getClassLoader());
    }
}
 
Example #29
Source File: JmsMessageProducerInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void afterSend(@Advice.Enter @Nullable final Span span,
                             @Advice.Thrown final Throwable throwable) {

    if (span != null) {
        span.captureException(throwable);
        span.deactivate().end();
    }
}
 
Example #30
Source File: CaptureSpanInstrumentation.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 onMethodExit(@Nullable @Advice.Local("span") Span span,
                                @Advice.Thrown Throwable t) {
    if (span != null) {
        span.captureException(t)
            .deactivate()
            .end();
    }
}