使用 Byte-Buddy 的 Java 代理不起作用 [英] Java Agent using Byte-Buddy doesn't work

查看:109
本文介绍了使用 Byte-Buddy 的 Java 代理不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要你的帮助来找出我的实现有什么问题...

I need your help in finding what's wrong with my implementation...

我正在尝试使用字节伙伴实现一个简单的 JVM 运行时分析器.一般来说,我需要的是每个方法调用都将记录在我在单独对象中管理的堆栈中.

I'm trying to implement a simple JVM runtime profiler using byte-buddy. In general, what I need is that every method call will be logged in a stack which I manage in a separate object.

在阅读了几篇文章后,我明白最好使用Advise"方法而不是MethodDelegation",这是我得出的结论:

After reading several posts, I understood that it's better to use the "Advise" approach instead of "MethodDelegation", and here's what I came out with:

Agent.java:

Agent.java:

package com.panaya.java.agent;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Agent {
    private static List<Pattern> pkgIncl = new ArrayList<Pattern>();
    private static List<Pattern> pkgExcl = new ArrayList<Pattern>();

    private static void initMatcherPatterns(String argument) {
        if (argument == null) {
            System.out.println("Missing configuration argument");
            return;
        }

        System.out.println("Argument is: " + argument);

        String[] tokens = argument.split(";");

        if (tokens.length < 1) {
            System.out.println("Missing delimeter ;");
            return;
        }

        for (String token : tokens) {
            String[] args = token.split("=");
            if (args.length < 2) {
                System.out.println("Missing argument delimeter =:" + token);
                return;
            }

            String argtype = args[0];

            if (!argtype.equals("incl") && !argtype.equals("excl")) {
                System.out.println("Wrong argument: " + argtype);
                return;
            }

            String[] patterns = args[1].split(",");

            for (String pattern : patterns) {
                Pattern p = null;
                System.out.println("Compiling " + argtype + " pattern:" + pattern + "$");
                try {
                    p = Pattern.compile(pattern + "$");
                } catch (PatternSyntaxException pse) {
                    System.out.println("pattern: " + pattern + " not valid, ignoring");
                }
                if (argtype.equals("incl"))
                    pkgIncl.add(p);
                else
                    pkgExcl.add(p);
            }
        }

    }

    private static boolean isShouldInstrumentClass(String className) {
        System.out.println("Testing " + className + " for match.");
        boolean match = false;
        String name = className.replace("/", ".");

        for (Pattern p : pkgIncl) {
            Matcher m = p.matcher(name);
            if (m.matches()) {

                match = true;
                break;
            }
        }

        for (Pattern p : pkgExcl) {
            Matcher m = p.matcher(name);
            if (m.matches()) {

                match = false;
                break;
            }
        }

        if (match) {
            System.out.println("Class " + name + "should be instrumented.");
        } else {
            System.out.println("Skipping class: " + name);
        }
        return match;
    }

    public static void premain(String agentArgument, Instrumentation instrumentation) {
        System.out.println("Premain started");
        try {
            initMatcherPatterns(agentArgument);

            new AgentBuilder.Default()
                    .with(AgentBuilder.TypeStrategy.Default.REBASE)
                    .type(new AgentBuilder.RawMatcher() {
                        public boolean matches(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, Class<?> aClass, ProtectionDomain protectionDomain) {
                            return isShouldInstrumentClass(typeDescription.getActualName());
                        }
                    })
                    .transform((builder, typeDescription, classLoader) -> builder
                            .visit(Advice.to(ProfilingAdvice.class)
                                    .on(ElementMatchers.any()))).installOn(instrumentation);

        } catch (RuntimeException e) {
            System.out.println("Exception instrumenting code : " + e);
            e.printStackTrace();
        }

    }
}

和 ProfilingAdvice.java:

And ProfilingAdvice.java:

package com.panaya.java.agent;

import com.panaya.java.profiler.MethodStackCollector;
import net.bytebuddy.asm.Advice;

public class ProfilingAdvice {
    @Advice.OnMethodEnter
    public static void enter(@Advice.Origin("#t.#m") String signature) {
        System.out.println("OnEnter :" + signature);
        try {
            MethodStackCollector.getInstance().push(signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Advice.OnMethodExit
    public static void exit(@Advice.Return long value) {
        System.out.println("OnExit - value = " + value);
        try {
            MethodStackCollector.getInstance().pop();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

出于某种原因,ProfilingAdvice 类中的进入"和退出"方法根本没有被调用.

For some reason, the "enter" and "exit" methods in ProfilingAdvice class, aren't invoked at all.

我做错了什么?

谢谢,艾拉德.

推荐答案

我尝试了您的示例,并在将退出建议减少到打印命令和您的匹配器以仅匹配某些类 foo.Bar 之后:

I tried your example and after reducing the exit advice to the print commands and your matcher to only match some class foo.Bar:

package foo;
public class Bar {
  public long qux() { return 0L; }
}

仪器工作没有问题.我觉得你的 Advice 匹配器指定 any() 而你的 ProfilingAdvice 需要 long 返回类型有点可疑.您是否尝试只打印到控制台,而您的建议中没有任何注释?

the instrumentation works without problem. I find it a bit fishy that your Advice matcher specifies any() while your ProfilingAdvice requires a long return type. Did you try only printing to the console without any annotations in your advice?

您可以通过设置调试此类问题:

You can debug such issues by settting:

new AgentBuilder.Default()
   .with(AgentBuilder.Listener.StreamWriting.toSystemOut());

检测过程中的潜在错误被打印到控制台.

where potential errors during the instrumentation are printed to the console.

这篇关于使用 Byte-Buddy 的 Java 代理不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆