instrumentationbyte-buddy

byte-buddy: class declared within builder.visit(Advice.to is not invoked


Aim of my application is to capture the Classes, Methods and its parameters loaded. Below declared is the premain and the implementation within class Interceptor.class should print the methodname, classname etc.,However, the class Interceptor is not invoked/executed. Please assist to understand the issue here.

    public static void premain(String agentArgs, Instrumentation instrumentation) {
    new AgentBuilder.Default()
                .with(AgentBuilder.Listener.StreamWriting.toSystemOut())
                .type(ElementMatchers.any())
                .transform((builder, typeDescription, classLoader, module) -> builder
                .visit(Advice.to(Interceptor.class).on(ElementMatchers.any()))
                )
                .installOn(instrumentation);

    // Register a ClassFileTransformer to handle retransformations (if supported)
        ClassFileTransformer classFileTransformer = new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                                    ProtectionDomain protectionDomain, byte[] classfileBuffer) {
                // Perform additional transformations for specific classes here
                return classfileBuffer;
            }
        };

        // Check if retransformations are supported before adding the transformer
        if (instrumentation.isRetransformClassesSupported()) {
            instrumentation.addTransformer(classFileTransformer, true);
        }
    }
public static class Interceptor {
        @Advice.OnMethodEnter
        public static void onMethodEnter(@Advice.Origin String origin,
                                         @Advice.AllArguments Object[] args,
                                         @Advice.Origin("#t") String className,
                                         @Advice.Origin("#m") String methodName
                                         ) {
            System.out.println("Origin:"+origin+" args:"+args);
            if(args != null) {
                for(int i =0 ; i < args.length ; i++){
                    System.out.println("Argument: " + i + " is " + args[i]);
                }
            }
            System.out.println("Origin :" + origin);
            System.out.println("ClassName :" + className);
            System.out.println("MethodName :"+methodName);
        }
    }

Compiled the premain and built a jar file. Then attached the jarfile as javaagent to an application running on K8s. Expecting the Interceptor class to print the classname, method name, etc however in vain.


Solution

  • You can register an AgentBuilder.Listener to see if any exceptions occur. Also, you should register an AgentBuilder.RetransformationStrategy for retransformation.