예제 #1
0
 /**
  * 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();
 }
예제 #2
0
 protected void logException(Exchange exchange, Throwable throwable) {
   if (tracer.isTraceExceptions()) {
     if (tracer.isLogStackTrace()) {
       logger.process(exchange, throwable);
     } else {
       logger.process(exchange, ", Exception: " + throwable.toString());
     }
   }
 }
예제 #3
0
  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();
    }
  }
예제 #4
0
 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();
 }
예제 #5
0
  /**
   * 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;
  }
예제 #6
0
 /**
  * @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));
 }
예제 #7
0
 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();
 }
예제 #8
0
 /** 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;
 }
예제 #9
0
 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;
 }
예제 #10
0
파일: Txn.java 프로젝트: bungaca/abstools
 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);
 }
예제 #11
0
 /**
  * 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);
 }
예제 #12
0
 /**
  * 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);
 }
예제 #13
0
 public long getTracerMinMethodTime() {
   return Tracer.getMinMethodTime();
 }
예제 #14
0
 public void filterTrace(boolean decision) {
   tracer
       .getHandler()
       .markTraceFlags(0, decision ? TraceMarker.SUBMIT_TRACE : TraceMarker.DROP_TRACE);
 }
예제 #15
0
 public void newFlags(int flags) {
   tracer.getHandler().markTraceFlags(0, flags);
 }
예제 #16
0
 /** Returns whether exchanges coming out of processors should be traced */
 public boolean shouldTraceOutExchanges() {
   return tracer.isTraceOutExchanges();
 }
예제 #17
0
 /**
  * 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()));
   }
 }
예제 #18
0
 /**
  * Configures tracer output.
  *
  * @param output trace processing object
  */
 public void output(ZorkaAsyncThread<SymbolicRecord> output) {
   tracer.addOutput(output);
 }
예제 #19
0
 public void setTraceSpyMethods(boolean tsm) {
   tracer.setTraceSpyMethods(tsm);
 }
예제 #20
0
  @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;
  }
예제 #21
0
 /** 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));
 }
예제 #22
0
 public void setTracerMaxTraceRecords(long maxRecords) {
   Tracer.setMaxTraceRecords((int) maxRecords);
 }
예제 #23
0
 public int getTracerMaxTraceRecords() {
   return Tracer.getMaxTraceRecords();
 }
예제 #24
0
 /** Returns true if the given exchange should be logged when an exception was thrown */
 protected boolean shouldLogException(Exchange exchange) {
   return tracer.isTraceExceptions();
 }
예제 #25
0
 public boolean isTraceSpyMethods() {
   return tracer.isTraceSpyMethods();
 }
예제 #26
0
 public void traceBegin(String name, long minimumTraceTime, int flags) {
   TraceBuilder traceBuilder = tracer.getHandler();
   traceBuilder.traceBegin(symbolRegistry.symbolId(name), System.currentTimeMillis(), flags);
   traceBuilder.setMinimumTraceTime(minimumTraceTime);
 }
예제 #27
0
 public void clearOutputs() {
   tracer.clearOutputs();
 }
예제 #28
0
 public boolean isInTrace(String traceName) {
   return tracer.getHandler().isInTrace(symbolRegistry.symbolId(traceName));
 }
예제 #29
0
 public void include(SpyMatcher... matchers) {
   for (SpyMatcher matcher : matchers) {
     log.info(ZorkaLogger.ZAG_CONFIG, "Tracer include: " + matcher);
     tracer.include(matcher);
   }
 }
예제 #30
0
 /**
  * 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);
 }