packagecomet.agent;importnet.bytebuddy.agent.builder.AgentBuilder;importnet.bytebuddy.asm.Advice;importnet.bytebuddy.description.type.TypeDescription;importnet.bytebuddy.dynamic.DynamicType;importnet.bytebuddy.matcher.ElementMatchers;importnet.bytebuddy.utility.JavaModule;importjava.lang.instrument.Instrumentation;importjava.io.*;importjava.nio.file.*;importjava.util.*;importjava.util.concurrent.*;importjava.util.concurrent.atomic.LongAdder;importjava.text.SimpleDateFormat;importjava.util.jar.JarFile;publicclassProfilerAgent{// MUST BE PUBLIC: To be seen by instrumented classespublicstaticfinalConcurrentHashMap<String,Stats>metrics=newConcurrentHashMap<>();privatestaticfinalSimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");publicstaticvoidagentmain(StringagentArgs,Instrumentationinst){try{FileagentJar=newFile(ProfilerAgent.class.getProtectionDomain().getCodeSource().getLocation().toURI());if(agentJar.exists()){inst.appendToBootstrapClassLoaderSearch(newJarFile(agentJar));}}catch(Exceptione){System.err.println("PROFILER: Bootstrap injection failed: "+e.getMessage());}premain(agentArgs,inst);}publicstaticvoidpremain(StringagentArgs,Instrumentationinst){List<String>targetClasses=loadClasses("profiler_targets.txt");startReporter(60,".");newAgentBuilder.Default().with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)// Manual Circularity Lock to avoid the "Symbol Not Found" error.with(newAgentBuilder.CircularityLock(){privatefinalThreadLocal<Boolean>lock=newThreadLocal<Boolean>(){@OverrideprotectedBooleaninitialValue(){returnfalse;}};@Overridepublicbooleanacquire(){if(lock.get())returnfalse;lock.set(true);returntrue;}@Overridepublicvoidrelease(){lock.set(false);}}).ignore(ElementMatchers.none()).type(builder->{Stringname=builder.getName();if(name.startsWith("comet.agent.")||name.startsWith("net.bytebuddy."))returnfalse;returntargetClasses.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);}privatestaticList<String>loadClasses(Stringpath){try{returnFiles.readAllLines(Paths.get(path));}catch(Exceptione){returnCollections.emptyList();}}publicstaticclassProfilerAdvice{// MUST BE PUBLIC: This was causing your "tried to access field" crashpublicstaticfinalSet<String>seenMethods=Collections.newSetFromMap(newConcurrentHashMap<String,Boolean>());@Advice.OnMethodEnterstaticlongenter(@Advice.Origin("#t.#m")StringmethodName){// Use absolute path so the inlined code knows exactly where to lookif(comet.agent.ProfilerAgent.ProfilerAdvice.seenMethods.add(methodName)){System.out.println(">>> HEARTBEAT: First call in "+methodName);System.out.flush();}returnSystem.nanoTime();}@Advice.OnMethodExit(onThrowable=Throwable.class)staticvoidexit(@Advice.Enterlongstart,@Advice.Origin("#t.#m")StringmethodName){if(start==0L)return;longduration=System.nanoTime()-start;// Use absolute paths for metrics and Statscomet.agent.ProfilerAgent.Statss=comet.agent.ProfilerAgent.metrics.get(methodName);if(s==null){comet.agent.ProfilerAgent.metrics.putIfAbsent(methodName,newcomet.agent.ProfilerAgent.Stats());s=comet.agent.ProfilerAgent.metrics.get(methodName);}s.record(duration);}}// MUST BE PUBLICpublicstaticclassStats{publicfinalLongAddercount=newLongAdder();publicfinalLongAddertotalTime=newLongAdder();publicvoidrecord(longnanos){count.increment();totalTime.add(nanos);}}privatestaticvoidstartReporter(intseconds,StringoutputDir){Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()->{Stringtimestamp=sdf.format(newDate());FilecsvFile=newFile(outputDir,"profiler_report.csv");try(PrintWriterpw=newPrintWriter(newBufferedWriter(newFileWriter(csvFile,true)))){metrics.forEach((method,stats)->{longc=stats.count.sumThenReset();longt=stats.totalTime.sumThenReset();if(c>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: Report flushed at "+timestamp);System.out.flush();}catch(Exceptione){e.printStackTrace();}},seconds,seconds,TimeUnit.SECONDS);}}
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)