DEV Community

Query Filter
Query Filter

Posted on

bridge52

package comet.agent;

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 {
    // CRITICAL: Must be public and static to avoid synthetic accessors (access$000)
    public static final ConcurrentHashMap<String, Stats> metrics = new ConcurrentHashMap<>();
    public static final Set<String> targetClassSet = new CopyOnWriteArraySet<>();
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void agentmain(String agentArgs, Instrumentation inst) {
        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];
        }

        loadClasses(configPath);
        startReporter(interval, outputDir);

        new AgentBuilder.Default()
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .type(typeDescription -> targetClassSet.contains(typeDescription.getName()))
            .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);
    }

    public static void loadClasses(String path) {
        try {
            List<String> lines = Files.readAllLines(Paths.get(path));
            for (String line : lines) {
                if (!line.trim().isEmpty()) {
                    targetClassSet.add(line.trim());
                }
            }
        } catch (Exception e) {
            System.err.println("PROFILER: Could not read config: " + path);
        }
    }

    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;

            // Use Fully Qualified Name to avoid any ambiguity in the target class
            comet.agent.ProfilerAgent.Stats s = comet.agent.ProfilerAgent.metrics.get(methodName);
            if (s == null) {
                comet.agent.ProfilerAgent.metrics.putIfAbsent(methodName, new comet.agent.ProfilerAgent.Stats());
                s = comet.agent.ProfilerAgent.metrics.get(methodName);
            }
            if (s != null) {
                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_combined_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");
                }

                final int[] tally = {0};
                metrics.forEach((method, stats) -> {
                    long c = stats.count.sumThenReset();
                    long t = stats.totalTime.sumThenReset();
                    if (c > 0) {
                        tally[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: Flush @ " + timestamp + ". Captured: " + tally[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, seconds, seconds, TimeUnit.SECONDS);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)