/** * This will return a series of bytecode instructions which can be used to compare one method with * another. debug info like local var declarations and line numbers are ignored, so the focus is * on the content. */ public static List getMethodBytecode(final String methodName, final byte[] bytes) { final Tracer visit = new Tracer(methodName); final ClassReader classReader = new ClassReader(bytes); classReader.accept(visit, ClassReader.SKIP_DEBUG); final TraceMethodVisitor trace = visit.getTrace(); return trace.getText(); }
protected void logException(Exchange exchange, Throwable throwable) { if (tracer.isTraceExceptions()) { if (tracer.isLogStackTrace()) { logger.process(exchange, throwable); } else { logger.process(exchange, ", Exception: " + throwable.toString()); } } }
public static void premain(String args, Instrumentation inst) throws Exception { try { String[] agentArgs; if (args == null) agentArgs = new String[] {""}; else agentArgs = args.split(","); if (!agentArgs[0].equals("instrumenting")) jarFileName = agentArgs[0]; BaseClassTransformer rct = null; rct = new BaseClassTransformer(); if (agentArgs[0].equals("instrumenting")) { initVMClasses = new HashSet<String>(); for (Class<?> c : inst.getAllLoadedClasses()) { ((Set<String>) initVMClasses).add(c.getName()); } } if (!agentArgs[0].equals("instrumenting")) { inst.addTransformer(rct); Tracer.setLocals(new CounterThreadLocal()); Tracer.overrideAll(true); for (Class<?> c : inst.getAllLoadedClasses()) { try { if (c.isInterface()) continue; if (c.isArray()) continue; byte[] bytes = rct.getBytes(c.getName()); if (bytes == null) { continue; } inst.redefineClasses(new ClassDefinition[] {new ClassDefinition(c, bytes)}); } catch (Throwable e) { synchronized (System.err) { System.err.println("" + c + " failed..."); e.printStackTrace(); } } } Runtime.getRuntime() .addShutdownHook( new Thread() { public void run() { Tracer.mark(); try { PrintStream ps = new PrintStream("bailout.txt"); ps.println("Bailouts: " + Tracer.getBailoutCount()); ps.close(); } catch (Exception e) { } Tracer.unmark(); } }); if ("true".equals(System.getProperty("bci.observerOn"))) Tracer.overrideAll(false); } } catch (Exception e) { e.printStackTrace(); } }
public TraceInterceptor( ProcessorDefinition<?> node, Processor target, TraceFormatter formatter, Tracer tracer) { super(target); this.tracer = tracer; this.node = node; this.formatter = formatter; this.logger = tracer.getLogger(this); if (tracer.getFormatter() != null) { this.formatter = tracer.getFormatter(); } this.traceHandlers = tracer.getTraceHandlers(); }
/** * Compiles the input file and generates the output class file. * * @param fullFilePath input .java file path. * @return class file path. */ public static String compileFile(File fullFilePath) throws IOException { Preconditions.checkArgument(fullFilePath != null && fullFilePath.isFile()); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); Preconditions.checkNotNull(compiler); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnit = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(fullFilePath)); List<String> args = Arrays.asList("-Xlint:none"); boolean result = compiler.getTask(null, fileManager, diagnostics, args, null, compilationUnit).call(); String msg = ""; if (!result) { for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { msg += String.format( "Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getMessage(null)); } tracer.err(msg); } fileManager.close(); return msg; }
/** * @param traceName * @param attrName * @param tag * @param value */ public void newTraceAttr(String traceName, String attrName, String tag, Object value) { tracer .getHandler() .newAttr( symbolRegistry.symbolId(traceName), symbolRegistry.symbolId(attrName), new TaggedValue(symbolRegistry.symbolId(tag), value)); }
public String listIncludes() { StringBuilder sb = new StringBuilder(); for (SpyMatcher sm : tracer.getMatcherSet().getMatchers()) { sb.append(sm.hasFlags(SpyMatcher.EXCLUDE_MATCH) ? "excl: " : "incl: "); sb.append(sm); sb.append("\n"); } return sb.toString(); }
/** Returns true if the given node should be logged in the trace list */ protected boolean shouldLogNode(ProcessorDefinition<?> node) { if (node == null) { return false; } if (!tracer.isTraceInterceptors() && (node instanceof InterceptStrategy)) { return false; } return true; }
public byte[] getBytes(String className) { try { Tracer.mark(); String realName = className.replace(".", "/"); realName += ".class"; JarEntry je = jf.getJarEntry(realName); InputStream is = jf.getInputStream(je); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buff = new byte[4096]; while (is.available() > 0) { int read = is.read(buff); baos.write(buff, 0, read); } is.close(); return baos.toByteArray(); } catch (Exception e) { } finally { Tracer.unmark(); } return null; }
protected void hook799(int numReadLocks, int numWriteLocks, boolean openCursors) throws DatabaseException { Tracer.trace( Level.FINE, envImpl, "Abort:id = " + id + " numWriteLocks= " + numWriteLocks + " numReadLocks= " + numReadLocks + " openCursors= " + openCursors); original(numReadLocks, numWriteLocks, openCursors); }
/** * Sets maximum number of records that will be stored in a single trace. This setting prevents * agent from overrunning memory when instrumented code has very long (and complex) execution * path. After maximum number is reached, all remaining records will be discarded but numbers of * calls and errors of discarded methods will be reflected in summary data. * * @param maxRecords maximum numbner of trace records */ public void setTracerMaxTraceRecords(int maxRecords) { Tracer.setMaxTraceRecords(maxRecords); }
/** * Sets minimum traced method execution time. Methods that took less time will be discarded from * traces and will only reflect in summary call/error counters. * * @param methodTime minimum execution time (in nanoseconds, 250 microseconds by default) */ public void setTracerMinMethodTime(long methodTime) { Tracer.setMinMethodTime(methodTime); }
public long getTracerMinMethodTime() { return Tracer.getMinMethodTime(); }
public void filterTrace(boolean decision) { tracer .getHandler() .markTraceFlags(0, decision ? TraceMarker.SUBMIT_TRACE : TraceMarker.DROP_TRACE); }
public void newFlags(int flags) { tracer.getHandler().markTraceFlags(0, flags); }
/** Returns whether exchanges coming out of processors should be traced */ public boolean shouldTraceOutExchanges() { return tracer.isTraceOutExchanges(); }
/** * Adds matching method to tracer. * * @param matchers spy matcher objects (created using spy.byXxxx() functions) */ public void include(String... matchers) { for (String matcher : matchers) { log.info(ZorkaLogger.ZAG_CONFIG, "Tracer include: " + matcher); tracer.include(SpyMatcher.fromString(matcher.toString())); } }
/** * Configures tracer output. * * @param output trace processing object */ public void output(ZorkaAsyncThread<SymbolicRecord> output) { tracer.addOutput(output); }
public void setTraceSpyMethods(boolean tsm) { tracer.setTraceSpyMethods(tsm); }
@Override public boolean process(final Exchange exchange, final AsyncCallback callback) { // do not trace if tracing is disabled if (!tracer.isEnabled() || (routeContext != null && !routeContext.isTracing())) { return processor.process(exchange, callback); } // interceptor will also trace routes supposed only for TraceEvents so we need to skip // logging TraceEvents to avoid infinite looping if (exchange.getProperty(Exchange.TRACE_EVENT, false, Boolean.class)) { // but we must still process to allow routing of TraceEvents to eg a JPA endpoint return processor.process(exchange, callback); } final boolean shouldLog = shouldLogNode(node) && shouldLogExchange(exchange); // whether we should trace it or not, some nodes should be skipped as they are abstract // intermediate steps for instance related to on completion boolean trace = true; boolean sync = true; // okay this is a regular exchange being routed we might need to log and trace try { // before if (shouldLog) { // traced holds the information about the current traced route path if (exchange.getUnitOfWork() != null) { TracedRouteNodes traced = exchange.getUnitOfWork().getTracedRouteNodes(); if (node instanceof OnCompletionDefinition || node instanceof OnExceptionDefinition) { // skip any of these as its just a marker definition trace = false; } else if (ProcessorDefinitionHelper.isFirstChildOfType( OnCompletionDefinition.class, node)) { // special for on completion tracing traceOnCompletion(traced, exchange); } else if (ProcessorDefinitionHelper.isFirstChildOfType( OnExceptionDefinition.class, node)) { // special for on exception traceOnException(traced, exchange); } else if (ProcessorDefinitionHelper.isFirstChildOfType(CatchDefinition.class, node)) { // special for do catch traceDoCatch(traced, exchange); } else if (ProcessorDefinitionHelper.isFirstChildOfType(FinallyDefinition.class, node)) { // special for do finally traceDoFinally(traced, exchange); } else if (ProcessorDefinitionHelper.isFirstChildOfType( AggregateDefinition.class, node)) { // special for aggregate traceAggregate(traced, exchange); } else { // regular so just add it traced.addTraced(new DefaultRouteNode(node, super.getProcessor())); } } else { LOG.trace("Cannot trace as this Exchange does not have an UnitOfWork: {}", exchange); } } // log and trace the processor Object state = null; if (shouldLog && trace) { logExchange(exchange); // either call the in or generic trace method depending on OUT has been enabled or not if (tracer.isTraceOutExchanges()) { state = traceExchangeIn(exchange); } else { traceExchange(exchange); } } final Object traceState = state; // special for interceptor where we need to keep booking how far we have routed in the // intercepted processors if (node.getParent() instanceof InterceptDefinition && exchange.getUnitOfWork() != null) { TracedRouteNodes traced = exchange.getUnitOfWork().getTracedRouteNodes(); traceIntercept((InterceptDefinition) node.getParent(), traced, exchange); } // process the exchange sync = processor.process( exchange, new AsyncCallback() { @Override public void done(boolean doneSync) { try { // after (trace out) if (shouldLog && tracer.isTraceOutExchanges()) { logExchange(exchange); traceExchangeOut(exchange, traceState); } } catch (Throwable e) { // some exception occurred in trace logic if (shouldLogException(exchange)) { logException(exchange, e); } exchange.setException(e); } finally { // ensure callback is always invoked callback.done(doneSync); } } }); } catch (Throwable e) { // some exception occurred in trace logic if (shouldLogException(exchange)) { logException(exchange, e); } exchange.setException(e); } return sync; }
/** Returns true if the given exchange should be logged in the trace list */ protected boolean shouldLogExchange(Exchange exchange) { return tracer.isEnabled() && (tracer.getTraceFilter() == null || tracer.getTraceFilter().matches(exchange)); }
public void setTracerMaxTraceRecords(long maxRecords) { Tracer.setMaxTraceRecords((int) maxRecords); }
public int getTracerMaxTraceRecords() { return Tracer.getMaxTraceRecords(); }
/** Returns true if the given exchange should be logged when an exception was thrown */ protected boolean shouldLogException(Exchange exchange) { return tracer.isTraceExceptions(); }
public boolean isTraceSpyMethods() { return tracer.isTraceSpyMethods(); }
public void traceBegin(String name, long minimumTraceTime, int flags) { TraceBuilder traceBuilder = tracer.getHandler(); traceBuilder.traceBegin(symbolRegistry.symbolId(name), System.currentTimeMillis(), flags); traceBuilder.setMinimumTraceTime(minimumTraceTime); }
public void clearOutputs() { tracer.clearOutputs(); }
public boolean isInTrace(String traceName) { return tracer.getHandler().isInTrace(symbolRegistry.symbolId(traceName)); }
public void include(SpyMatcher... matchers) { for (SpyMatcher matcher : matchers) { log.info(ZorkaLogger.ZAG_CONFIG, "Tracer include: " + matcher); tracer.include(matcher); } }
/** * Adds trace attribute to trace record immediately. This is useful for programmatic attribute * setting. * * @param attrName attribute name * @param value attribute value */ public void newAttr(String attrName, Object value) { tracer.getHandler().newAttr(-1, symbolRegistry.symbolId(attrName), value); }