DEV Community

Query Filter
Query Filter

Posted on

bridge42

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;
import java.util.jar.JarFile;

public class ProfilerAgent {
    private static final String METRICS_KEY = "comet.agent.global.metrics";
    private static final String SEEN_KEY = "comet.agent.global.seen";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // Global Map Retrieval: Forces the System and Bootstrap loaders to share one instance
    @SuppressWarnings("unchecked")
    public static ConcurrentHashMap<String, Stats> getGlobalMetrics() {
        if (System.getProperties().get(METRICS_KEY) == null) {
            System.getProperties().put(METRICS_KEY, new ConcurrentHashMap<String, Stats>());
        }
        return (ConcurrentHashMap<String, Stats>) System.getProperties().get(METRICS_KEY);
    }

    @SuppressWarnings("unchecked")
    public static Set<String> getGlobalSeenMethods() {
        if (System.getProperties().get(SEEN_KEY) == null) {
            System.getProperties().put(SEEN_KEY, Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()));
        }
        return (Set<String>) System.getProperties().get(SEEN_KEY);
    }

    public static void agentmain(String agentArgs, Instrumentation inst) {
        System.out.println("PROFILER: Starting AgentMain...");
        try {
            File agentJar = new File(ProfilerAgent.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            if (agentJar.exists()) {
                inst.appendToBootstrapClassLoaderSearch(new JarFile(agentJar));
                System.out.println("PROFILER: Injected " + agentJar.getName() + " into Bootstrap path.");
            }
        } catch (Exception e) {
            System.err.println("PROFILER: Injection failed: " + e.getMessage());
        }
        premain(agentArgs, inst);
    }

    public static void premain(String agentArgs, Instrumentation inst) {
        String outputDir = "build/profiler-results";
        List<String> targetClasses = loadClasses("profiler_targets.txt");

        // Ensure directory exists
        new File(outputDir).mkdirs();
        startReporter(60, outputDir);

        new AgentBuilder.Default()
            .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
            .with(new AgentBuilder.CircularityLock() {
                private final ThreadLocal<Boolean> lock = new ThreadLocal<Boolean>() {
                    @Override protected Boolean initialValue() { return false; }
                };
                @Override public boolean acquire() { if (lock.get()) return false; lock.set(true); return true; }
                @Override public void release() { lock.set(false); }
            })
            .ignore(ElementMatchers.none())
            .type(builder -> {
                String name = builder.getName();
                if (name.startsWith("comet.agent.") || name.startsWith("net.bytebuddy.")) return false;
                return targetClasses.contains(name);
            })
            .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) { return Collections.emptyList(); }
    }

    public static class ProfilerAdvice {
        @Advice.OnMethodEnter
        static long enter(@Advice.Origin("#t.#m") String methodName) {
            // Access via global getter to ensure single-instance across ClassLoaders
            if (comet.agent.ProfilerAgent.getGlobalSeenMethods().add(methodName)) {
                System.out.println(">>> HEARTBEAT: First call in " + methodName);
                System.out.flush();
            }
            return System.nanoTime();
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class)
        static void exit(@Advice.Enter long start, @Advice.Origin("#t.#m") String methodName) {
            if (start == 0L) return;
            long duration = System.nanoTime() - start;

            ConcurrentHashMap<String, Stats> metrics = comet.agent.ProfilerAgent.getGlobalMetrics();
            Stats s = metrics.get(methodName);
            if (s == null) {
                metrics.putIfAbsent(methodName, new comet.agent.ProfilerAgent.Stats());
                s = metrics.get(methodName);
            }
            s.record(duration);
        }
    }

    public static class Stats implements Serializable {
        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, String outputDir) {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            String timestamp = sdf.format(new Date());
            File csvFile = new File(outputDir, "profiler-report.csv");
            ConcurrentHashMap<String, Stats> metrics = getGlobalMetrics();

            try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)))) {
                if (csvFile.length() == 0) {
                    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]++;
                        pw.printf("%s,%s,%d,%.4f,%.2f%n", timestamp, method, c, (t/(double)c)/1000000.0, t/1000000.0);
                    }
                });
                pw.flush();
                System.out.println("PROFILER: Flushed " + tally[0] + " methods to " + csvFile.getAbsolutePath());
                System.out.flush();
            } catch (Exception e) { e.printStackTrace(); }
        }, seconds, seconds, TimeUnit.SECONDS);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)