DEV Community

Query Filter
Query Filter

Posted on

bridge35

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.matcher.ElementMatchers;
import java.lang.instrument.Instrumentation;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.LongAdder;
import java.text.SimpleDateFormat;

public class ProfilerAgent {
    public static final ConcurrentHashMap<String, Stats> metrics = new ConcurrentHashMap<>();
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void agentmain(String agentArgs, Instrumentation inst) {
        System.out.println("PROFILER: Dynamic attach successful.");
        premain(agentArgs, inst);
    }

    public static void premain(String agentArgs, Instrumentation inst) {
        String configPath = "profiler_targets.txt";
        int interval = 60;
        String outputDir = ".";

        if (agentArgs != null && !agentArgs.isEmpty()) {
            String[] parts = agentArgs.split(";");
            if (parts.length > 0) configPath = parts[0];
            if (parts.length > 1) interval = Integer.parseInt(parts[1]);
            if (parts.length > 2) outputDir = parts[2];
        }

        List<String> targetClasses = loadClasses(configPath);
        startReporter(interval, outputDir);

        new AgentBuilder.Default()
            // CRITICAL: Allows modification of classes already in memory
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .type(ElementMatchers.any()) // We filter inside the loop or via specific matchers
            .and(builder -> {
                // Only match classes in your config list
                return targetClasses.stream().anyMatch(name -> builder.getName().equals(name.trim()));
            })
            .transform((builder, typeDescription, classLoader, module) -> 
                builder.method(ElementMatchers.any()
                    .and(ElementMatchers.not(ElementMatchers.isAbstract()))
                    .and(ElementMatchers.not(ElementMatchers.isNative())))
                .intercept(Advice.to(ProfilerAdvice.class))
            )
            .installOn(inst);
    }

    private static List<String> loadClasses(String path) {
        try { return Files.readAllLines(Paths.get(path)); }
        catch (Exception e) { 
            System.err.println("Could not read config: " + path);
            return Collections.emptyList(); 
        }
    }

    public static class ProfilerAdvice {
        @Advice.OnMethodEnter
        static long enter() {
            return System.nanoTime();
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class)
        static void exit(@Advice.Enter long start, @Advice.Origin("#t.#m") String methodName) {
            long duration = System.nanoTime() - start;
            Stats s = ProfilerAgent.metrics.get(methodName);
            if (s == null) {
                ProfilerAgent.metrics.putIfAbsent(methodName, new Stats());
                s = ProfilerAgent.metrics.get(methodName);
            }
            s.record(duration);
        }
    }

    public static class Stats {
        public final LongAdder count = new LongAdder();
        public final LongAdder totalTime = new LongAdder();
        public void record(long nanos) {
            count.increment();
            totalTime.add(nanos);
        }
    }

    private static void startReporter(int seconds, final String outputDir) {
        File csvFile = new File(outputDir, "profiler_report.csv");
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            String timestamp = sdf.format(new Date());
            boolean writeHeader = !csvFile.exists() || csvFile.length() == 0;

            try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)))) {
                if (writeHeader) {
                    pw.println("Timestamp,Method,Calls,Avg_MS,Total_MS");
                }
                metrics.forEach((method, stats) -> {
                    long c = stats.count.sumThenReset();
                    long t = stats.totalTime.sumThenReset();
                    if (c > 0) {
                        double avgMs = (t / (double) c) / 1_000_000.0;
                        double totalMs = t / 1_000_000.0;
                        pw.printf("%s,%s,%d,%.4f,%.2f%n", timestamp, method, c, avgMs, totalMs);
                    }
                });
                System.out.println("PROFILER: Report flushed at " + timestamp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, seconds, seconds, TimeUnit.SECONDS);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)