Debian Codegraph @

src/com/google/javascript/jscomp/Tracer.java

raw symbols SCIP
1 /*
2 * Copyright 2002 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Joiner;
21 import com.google.common.base.Preconditions;
22
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31 import java.util.concurrent.CopyOnWriteArrayList;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
34
35 import javax.annotation.Nullable;
36
37 /**
38 * Tracer provides a simple way to trace the handling of a request.
39 *
40 * By timing likely slow points in the code you can quickly pinpoint
41 * why a request is slow.
42 *
43 * <p>Example usage:
44 * <pre>
45 * Tracer.initCurrentThreadTrace(); // must be called in each Thread
46 * Tracer wholeRequest = new Tracer(null, "Request " + params);
47 * try {
48 * ...
49 * t = new Tracer("Database", "getName()");
50 * try {
51 * name = database.getName();
52 * } finally {
53 * t.stop();
54 * }
55 * ...
56 * t = new Tracer(null, "call sendmail");
57 * try {
58 * sendMessage();
59 * } finally {
60 * t.stop();
61 * }
62 * ...
63 * t = new Tracer("Database", "updateinfo()");
64 * try {
65 * database.updateinfo("new info");
66 * } finally {
67 * t.stop();
68 * }
69 * ...
70 * } finally {
71 * if (wholeRequest.stop() > 1000) {
72 * // more than a second, better log
73 * Tracer.logAndClearCurrentThreadTrace();
74 * } else {
75 * Tracer.clearCurrentThreadTrace();
76 * }
77 * }
78 * </pre>
79 *
80 * Now slow requests will produce a report like this:
81 * <pre>
82 * 10.452 Start Request cmd=dostuff
83 * 3 10.455 Start [Database] getName()
84 * 34 10.489 Done 34 ms [Database] getName()
85 * 3 10.491 Start call sendmail
86 * 1042 11.533 Done 1042 ms call sendmail
87 * 0 11.533 Start [Database] updateinfo()
88 * 3 11.536 Done 3 ms [Database] updateinfo()
89 * 64 11.600 Done 1148 ms Request cmd=dostuff
90 * TOTAL Database 2 (37 ms)
91 * </pre>
92 *
93 * If you enabled pretty-printing by calling {@link Tracer#setPrettyPrint},
94 * it will print more easily readable reports that use indentation to visualize
95 * the tracer hierarchy and dynamically adjusts the padding to handle large
96 * durations. Like:
97 * <pre>
98 * 10.452 Start Request cmd=dostuff
99 * 3 10.455 Start | [Database] getName()
100 * 34 10.489 Done 34 ms | [Database] getName()
101 * 3 10.491 Start | call sendmail
102 * 1042 11.533 Done 1042 ms | call sendmail
103 * 0 11.533 Start | [Database] updateinfo()
104 * 3 11.536 Done 3 ms | [Database] updateinfo()
105 * 64 11.600 Done 1148 ms Request cmd=dostuff
106 * TOTAL Database 2 (37 ms)
107 * </pre>
108 * Pretty-printing is an application global setting and should only be called
109 * in the main setup of an application, not in library code.
110 *
111 * Now you can easily see that sendmail is causing your problems, not
112 * the two database calls.
113 *
114 * You can easily add additional tracing statistics to your Trace output by
115 * adding additional tracing statistics. Simply add to your initialization code:
116 * <pre>
117 * Tracer.addTracingStatistic(myTracingStatistic)
118 * </pre>
119 * where myTracingStatistic implements the {@link TracingStatistic} interface.
120 * The class com.google.monitoring.tracing.TracingStatistics contains
121 * several useful statistics such as CPU time, wait time, and memory usage.
122 * If you add your own tracing statistics, the output is not quite as pretty,
123 * but includes additional useful information.
124
125 * <p>If a Trace is given a type (the first argument to the constructor) and
126 * multiple Traces are done on that type then a "TOTAL line will be
127 * produced showing the total number of traces and the sum of the time
128 * ("TOTAL Database 2 (37 ms)" in our example). These traces should be
129 * mutually exclusive or else the sum won't make sense (the time will
130 * be double counted if the second starts before the first ends).
131 *
132 * <p>It is also possible to have a "silent" Tracer which does not appear
133 * in the trace because it was faster than the silence threshold. This
134 * threshold can be set for the for the current ThreadTrace with
135 * setDefaultSilenceThreshold(threshold), or on a per-Tracer basis with
136 * t.stop(threshold). Silent tracers are still counted in the type
137 * totals, so these events are not completely lost.
138 *
139 * <p><b>WARNING:</b> This code makes a big assumption that
140 * everything for a given trace is done within a single thread.
141 * It uses threads to identify requests. It is fine to have multiple
142 * requests traced in multiple simultaneous threads but it is not ok
143 * to have any given request traced in multiple threads. (the results
144 * will be scattered across reports).
145 *
146 * Java objects do not support destructors (as in C++) so Tracer is not robust
147 * when exceptions are thrown. Each Tracer object should be wrapped in a
148 * try/finally block so that if an exception is thrown, the Tracer.stop()
149 * method is guaranteed to be called.
150 *
151 * <p>A thread must call {@link Tracer#initCurrentThreadTrace()} to enable the
152 * Tracer logging, otherwise Tracer does nothing. The requirement to call
153 * {@code initCurrentThreadTrace} avoids the situation where Tracer is called
154 * without the explicit knowledge of the application authors because they
155 * happen to use a class in another package that uses Tracer. If {@link
156 * Tracer#logCurrentThreadTrace} is called without calling {@link
157 * Tracer#initCurrentThreadTrace()}, then a Third Eye WARNING message is logged,
158 * which should help track down the problem.
159 *
160 */
161 final class Tracer {
162 // package-private for access from unit tests
163 static final Logger logger =
164 Logger.getLogger(Tracer.class.getName());
165
166 /**
167 * Whether pretty printing is enabled. This is intended to be set once
168 * at application startup.
169 */
170 private static volatile boolean defaultPrettyPrint;
171
172 /* This list is guaranteed to only increase in length. It contains
173 * a list of additional statistics that the user wants to keep track
174 * of.
175 */
176 private static List<TracingStatistic> extraTracingStatistics =
177 new CopyOnWriteArrayList<TracingStatistic>();
178
179 /** Values returned by extraTracingStatistics */
180 private long[] extraTracingValues;
181
182 /** The type for grouping traces, may be null */
183 private final @Nullable String type;
184
185 /** A comment string for the report */
186 private final String comment;
187
188 /** Start time of the trace */
189 private final long startTimeMs;
190
191 /** Stop time of the trace, non-final */
192 private long stopTimeMs;
193
194 /**
195 * Record our starter thread in order to trap Traces that are started in one
196 * thread and stopped in another
197 */
198 final Thread startThread;
199
200 /**
201 * We limit the number of events in a Trace in order to catch memory
202 * leaks (a thread that keeps logging events and never clears them).
203 * This number is arbitrary and can be increased if necessary (though
204 * if there are more than 1000 events then the Tracer is probably being
205 * misused).
206 */
207 static final int MAX_TRACE_SIZE = 1000;
208
209 /**
210 * For unit testing. Can't use {@link com.google.common.time.Clock} because
211 * this code is in base and has minimal dependencies.
212 */
213 static interface InternalClock {
214 long currentTimeMillis();
215 }
216
217 /**
218 * Default clock that calls through to the system clock. Can be overridden
219 * in unit tests.
220 */
221 static InternalClock clock = new InternalClock() {
222 @Override
223 public long currentTimeMillis() {
224 return System.currentTimeMillis();
225 }
226 };
227
228 /**
229 * Create and start a tracer.
230 * Both type and comment may be null. See class comment for usage.
231 *
232 * @param type The type for totaling
233 * @param comment Comment about this tracer
234 */
235 Tracer(@Nullable String type, @Nullable String comment) {
236 this.type = type;
237 this.comment = comment == null ? "" : comment;
238 startTimeMs = clock.currentTimeMillis();
239 startThread = Thread.currentThread();
240 if (!extraTracingStatistics.isEmpty()) {
241 int size = extraTracingStatistics.size();
242 extraTracingValues = new long[size];
243 int i = 0;
244 for (TracingStatistic tracingStatistic : extraTracingStatistics) {
245 extraTracingValues[i] = tracingStatistic.start(startThread);
246 i++;
247 }
248 }
249
250 ThreadTrace trace = getThreadTrace();
251
252 // Do nothing if the current thread trace wasn't initialized.
253 if (!trace.isInitialized()) {
254 return;
255 }
256
257 // Check if we are creating too many Tracers.
258 if (trace.events.size() >= MAX_TRACE_SIZE) {
259 logger.log(Level.WARNING,
260 "Giant thread trace. Too many Tracers created. "
261 + "Clearing to avoid memory leak.",
262 new Throwable(trace.toString()));
263 trace.truncateEvents();
264 }
265
266 // Check if we forgot to close the Tracers.
267 if (trace.outstandingEvents.size() >= MAX_TRACE_SIZE) {
268 logger.log(Level.WARNING,
269 "Too many outstanding Tracers. Tracer.stop() is missing "
270 + "or Tracer.stop() is not wrapped in a "
271 + "try/finally block. "
272 + "Clearing to avoid memory leak.",
273 new Throwable(trace.toString()));
274 trace.truncateOutstandingEvents();
275 }
276
277 trace.startEvent(this);
278 }
279
280 /**
281 * Create a tracer that isn't summed as part of a total
282 *
283 * @param comment Comment about this tracer
284 */
285 Tracer(String comment) {
286 this(null, comment);
287 }
288
289 /**
290 * Construct a tracer whose type is based on the short name of the object
291 * @param object Object to use as type name
292 * @param comment A comment
293 * @return new Tracer.
294 */
295 static Tracer shortName(Object object, String comment) {
296 if (object == null) {
297 return new Tracer(comment);
298 }
299 return new Tracer(object.getClass().getSimpleName(), comment);
300 }
301
302 /**
303 * Converts 'v' to a string and pads it with up to 16 spaces for
304 * improved alignment.
305 * @param v The value to convert.
306 * @param digits_column_width The desired with of the string.
307 */
308 private static String longToPaddedString(long v, int digits_column_width) {
309 int digit_width = numDigits(v);
310 StringBuilder sb = new StringBuilder();
311 appendSpaces(sb, digits_column_width - digit_width);
312 sb.append(v);
313 return sb.toString();
314 }
315
316 /**
317 * Gets the number of digits in an integer when printed in base 10. Assumes
318 * a positive integer.
319 * @param n The value.
320 * @return The number of digits in the string.
321 */
322 private static int numDigits(long n) {
323 int i = 0;
324 do {
325 i++;
326 n = n / 10;
327 } while (n > 0);
328 return i;
329 }
330
331 /**
332 * Gets a string of spaces of the length specified.
333 * @param sb The string builder to append to.
334 * @param numSpaces The number of spaces in the string.
335 */
336 @VisibleForTesting
337 static void appendSpaces(StringBuilder sb, int numSpaces) {
338 if (numSpaces > 16) {
339 logger.warning("Tracer.appendSpaces called with large numSpaces");
340 // Avoid long loop in case some bug in the caller
341 numSpaces = 16;
342 }
343 while (numSpaces >= 5) {
344 sb.append(" ");
345 numSpaces -= 5;
346 }
347
348 // We know it's less than 5 now
349 switch (numSpaces) {
350 case 1:
351 sb.append(" ");
352 break;
353 case 2:
354 sb.append(" ");
355 break;
356 case 3:
357 sb.append(" ");
358 break;
359 case 4:
360 sb.append(" ");
361 break;
362 }
363 }
364
365 /**
366 * Adds a new tracing statistic to a trace
367 *
368 * @param tracingStatistic to enable a run
369 * @return The index of this statistic (for use with stat.extraInfo()), or
370 * -1 if the statistic is not enabled.
371 */
372 static int addTracingStatistic(TracingStatistic tracingStatistic) {
373 // Check to see if we can enable the tracing statistic before actually
374 // adding it.
375 if (tracingStatistic.enable()) {
376 // No synchronization needed, since this is a copy-on-write array.
377 extraTracingStatistics.add(tracingStatistic);
378 // 99.9% of the time, this will be O(1) and return
379 // extraTracingStatistics.length - 1
380 return extraTracingStatistics.lastIndexOf(tracingStatistic);
381 } else {
382 return -1;
383 }
384 }
385
386 /**
387 * For testing purposes only. These removes all current tracers.
388 * Severe errors can occur if there are any active tracers going on
389 * when this is called.
390 *
391 * The test suite uses this to remove any tracers that it has added.
392 */
393 @VisibleForTesting
394 static void clearTracingStatisticsTestingOnly() {
395 extraTracingStatistics.clear();
396 }
397
398 /**
399 * Stop the trace.
400 * This may only be done once and must be done from the same thread
401 * that started it.
402 * @param silence_threshold Traces for time less than silence_threshold
403 * ms will be left out of the trace report. A value of -1 indicates
404 * that the current ThreadTrace silence_threshold should be used.
405 * @return The time that this trace actually ran
406 */
407 long stop(int silence_threshold) {
408 Preconditions.checkState(Thread.currentThread() == startThread);
409
410 ThreadTrace trace = getThreadTrace();
411 // Do nothing if the thread trace was not initialized.
412 if (!trace.isInitialized()) {
413 return 0;
414 }
415
416 stopTimeMs = clock.currentTimeMillis();
417 if (extraTracingValues != null) {
418 // We use extraTracingValues.length rather than
419 // extraTracingStatistics.size() because a new statistic may
420 // have been added
421 for (int i = 0; i < extraTracingValues.length; i++) {
422 long value = extraTracingStatistics.get(i).stop(startThread);
423 extraTracingValues[i] = value - extraTracingValues[i];
424 }
425 }
426
427 // Do nothing if the thread trace was not initialized.
428 if (!trace.isInitialized()) {
429 return 0;
430 }
431
432 trace.endEvent(this, silence_threshold);
433 return stopTimeMs - startTimeMs;
434 }
435
436 /** Stop the trace using the default silence_threshold
437 *
438 * @return The time that this trace actually ran.
439 */
440 long stop() {
441 return stop(-1);
442 }
443
444 @Override public String toString() {
445 if (type == null) {
446 return comment;
447 } else {
448 return "[" + type + "] " + comment;
449 }
450 }
451
452 static void setDefaultSilenceThreshold(int threshold) {
453 getThreadTrace().defaultSilenceThreshold = threshold;
454 }
455
456 /**
457 * Initialize the trace associated with the current thread by clearing
458 * out any existing trace. There shouldn't be a trace so if one is
459 * found we log it as an error.
460 */
461 static void initCurrentThreadTrace() {
462 ThreadTrace events = getThreadTrace();
463 if (!events.isEmpty()) {
464 logger.log(Level.WARNING,
465 "Non-empty timer log:\n" + events,
466 new Throwable());
467 clearThreadTrace();
468
469 // Grab a new thread trace if we find a previous non-empty ThreadTrace.
470 events = getThreadTrace();
471 }
472
473 // Mark the thread trace as initialized.
474 events.init();
475 }
476
477 static void initCurrentThreadTrace(int default_silence_threshold) {
478 initCurrentThreadTrace();
479 setDefaultSilenceThreshold(default_silence_threshold);
480 }
481
482 /**
483 * Returns a timer report similar to the one described in the class comment.
484 *
485 * @return The timer report as a string
486 */
487 static String getCurrentThreadTraceReport() {
488 return getThreadTrace().toString();
489 }
490
491 /**
492 * Logs a timer report similar to the one described in the class comment.
493 */
494 static void logCurrentThreadTrace() {
495 ThreadTrace trace = getThreadTrace();
496
497 // New threads must call Tracer.initCurrentThreadTrace() before Tracer
498 // statistics are gathered. This is a recent change (Jun 2007) that
499 // prevents spurious Third Eye messages when an application uses a class in
500 // a different package that happens to call Tracer without knowledge of the
501 // application authors.
502 if (!trace.isInitialized()) {
503 logger.log(Level.WARNING,
504 "Tracer log requested for this thread but was not "
505 + "initialized using Tracer.initCurrentThreadTrace().",
506 new Throwable());
507 return;
508 }
509
510 if (!trace.isEmpty()) {
511 logger.log(Level.WARNING, "timers:\n{0}", getCurrentThreadTraceReport());
512 }
513 }
514
515 /**
516 * Throw away any Trace associated with the current thread.
517 */
518 static void clearCurrentThreadTrace() {
519 clearThreadTrace();
520 }
521
522 /**
523 * logCurrentThreadTrace() then clearCurrentThreadTrace()
524 */
525 static void logAndClearCurrentThreadTrace() {
526 logCurrentThreadTrace();
527 clearThreadTrace();
528 }
529
530 /**
531 * Sets whether pretty printing is enabled. See class-level comment. This
532 * only affects tracers created after this is called.
533 * @param enabled Whether to enable pretty printing.
534 */
535 static void setPrettyPrint(boolean enabled) {
536 defaultPrettyPrint = enabled;
537 }
538
539 /** Statistics for a given tracer type */
540 static final class Stat {
541 private int count;
542 private int silent;
543 private int clockTime;
544 private int[] extraInfo;
545
546 /** total count of tracers of a type, including silent
547 *
548 * @return total count of tracers, including silent tracers
549 */
550 int getCount() { return count; }
551
552 /** total count of silent tracers of a type
553 *
554 * @return total count of silent tracers
555 */
556 int getSilentCount() { return silent; }
557
558 /** total time spent in tracers of a type, in ms
559 *
560 * @return total time spent in tracer, in ms
561 */
562 int getTotalTime() { return clockTime; }
563
564 /** total time spent doing additional things that we are clocking */
565 @VisibleForTesting
566 int getExtraInfo(int index) {
567 return index >= extraInfo.length ? 0 : extraInfo[index];
568 }
569
570 }
571
572 /**
573 * This map tracks counts of tracers for each type over all time.
574 */
575 private static @Nullable AtomicTracerStatMap typeToCountMap;
576
577 /**
578 * This map tracks counts of silent tracers for each type over all time.
579 */
580 private static @Nullable AtomicTracerStatMap typeToSilentMap;
581
582 /**
583 * This map tracks time (ms) for each type over all time.
584 */
585 private static @Nullable AtomicTracerStatMap typeToTimeMap;
586
587 /**
588 * This method MUST be called before getTypeToCountMap (and friends)
589 * will return a valid map. This is because computing this information
590 * imposes a synchronization penalty on every Tracer that is stopped.
591 */
592 static synchronized void enableTypeMaps() {
593 if (typeToCountMap == null) {
594 typeToCountMap = new AtomicTracerStatMap();
595 typeToSilentMap = new AtomicTracerStatMap();
596 typeToTimeMap = new AtomicTracerStatMap();
597 }
598 }
599
600 /**
601 * Used for exporting this data via varz. Accesses to this
602 * map must be synchronized on the map. If enableTypeMaps has not
603 * been called, this will return null.
604 */
605 static @Nullable Map<String, Long> getTypeToCountMap() {
606 return typeToCountMap != null ? typeToCountMap.getMap() : null;
607 }
608
609 /**
610 * Used for exporting this data via varz. Accesses to this
611 * map must be synchronized on the map. If enableTypeMaps has not
612 * been called, this will return null.
613 */
614 static @Nullable Map<String, Long> getTypeToSilentMap() {
615 return typeToSilentMap != null ? typeToSilentMap.getMap() : null;
616 }
617
618 /**
619 * Used for exporting this data via varz. Accesses to this
620 * map must be synchronized on the map. If enableTypeMaps has not
621 * been called, this will return null.
622 */
623 static @Nullable Map<String, Long> getTypeToTimeMap() {
624 return typeToTimeMap != null ? typeToTimeMap.getMap() : null;
625 }
626
627 /** Gets the Stat for a tracer type; never returns null */
628 static Stat getStatsForType(String type) {
629 Stat stat = getThreadTrace().stats.get(type);
630 return stat != null ? stat : ZERO_STAT;
631 }
632
633 private static final Stat ZERO_STAT = new Stat();
634
635 /** Return the sec.ms part of time (if time = "20:06:11.566", "11.566") */
636 private static String formatTime(long time) {
637 int sec = (int) ((time / 1000) % 60);
638 int ms = (int) (time % 1000);
639 return String.format("%02d.%03d", sec, ms);
640 }
641
642 /** An event is created every time a Tracer is created or stopped */
643 private static final class Event {
644 boolean isStart; // else is_stop
645 Tracer tracer;
646
647 Event(boolean start, Tracer t) {
648 isStart = start;
649 tracer = t;
650 }
651
652 long eventTime() {
653 return isStart ? tracer.startTimeMs : tracer.stopTimeMs;
654 }
655
656 /**
657 * Converts the event to a formatted string.
658 * @param prevEventTime The time of the previous event which appears at
659 * the left most part of the trace line.
660 * @param indent The indentation to put before the tracer to show the
661 * hierarchy.
662 * @param digitsColWidth How many characters the digits should use.
663 * @return The formatted string.
664 */
665 String toString(long prevEventTime, String indent, int digitsColWidth) {
666 StringBuilder sb = new StringBuilder(120);
667
668 if (prevEventTime == -1) {
669 appendSpaces(sb, digitsColWidth);
670 } else {
671 sb.append(longToPaddedString(
672 eventTime() - prevEventTime, digitsColWidth));
673 }
674
675 sb.append(' ');
676 sb.append(formatTime(eventTime()));
677 if (isStart) {
678 sb.append(" Start ");
679 appendSpaces(sb, digitsColWidth);
680 sb.append(" ");
681 } else {
682 sb.append(" Done ");
683 long delta = tracer.stopTimeMs - tracer.startTimeMs;
684 sb.append(longToPaddedString(delta, digitsColWidth));
685 sb.append(" ms ");
686 if (tracer.extraTracingValues != null) {
687 for (int i = 0; i < tracer.extraTracingValues.length; i++) {
688 delta = tracer.extraTracingValues[i];
689 sb.append(String.format("%4d", delta));
690 sb.append(extraTracingStatistics.get(i).getUnits());
691 sb.append("; ");
692 }
693 }
694 }
695 sb.append(indent);
696 sb.append(tracer.toString());
697 return sb.toString();
698 }
699 }
700
701 /** Stores a thread's Trace */
702 static final class ThreadTrace {
703
704 /** Events taking less than this number of milliseconds are not reported. */
705 int defaultSilenceThreshold; // non-final
706
707 /** The Events corresponding to each startEvent/stopEvent */
708 final ArrayList<Event> events = new ArrayList<Event>();
709
710 /** Tracers that have not had their .stop() called */
711 final HashSet<Tracer> outstandingEvents = new HashSet<Tracer>();
712
713 /** Map from type to Stat object */
714 final Map<String, Stat> stats = new HashMap<String, Stat>();
715
716 /**
717 * True if {@code outstandingEvents} has been cleared because we exceeded
718 * the max trace limit.
719 */
720 boolean isOutstandingEventsTruncated = false;
721
722 /**
723 * True if {@code events} has been cleared because we exceeded the max
724 * trace limit.
725 */
726 boolean isEventsTruncated = false;
727
728 /**
729 * Set to true if {@link Tracer#initCurrentThreadTrace()} was called by
730 * the current thread.
731 */
732 boolean isInitialized = false;
733
734 /**
735 * Whether pretty printing is enabled for the trace.
736 */
737 boolean prettyPrint = false;
738
739 /** Initialize the trace. */
740 void init() {
741 isInitialized = true;
742 }
743
744 /** Is initialized? */
745 boolean isInitialized() {
746 return isInitialized;
747 }
748
749 /**
750 * Called by the constructor {@link Tracer#Tracer(String, String)} to create
751 * a start event.
752 */
753 void startEvent(Tracer t) {
754 events.add(new Event(true, t));
755 boolean notAlreadyOutstanding = outstandingEvents.add(t);
756 Preconditions.checkState(notAlreadyOutstanding);
757 }
758
759 /**
760 * Called by {@link Tracer#stop()} to create a stop event.
761 */
762 void endEvent(Tracer t, int silenceThreshold) {
763 boolean wasOutstanding = outstandingEvents.remove(t);
764 if (!wasOutstanding) {
765 if (isOutstandingEventsTruncated) {
766 // The events stack overflowed and was truncated, so just log a
767 // warning. Otherwise, we get an exception which is extremely
768 // confusing.
769 logger.log(Level.WARNING,
770 "event not found, probably because the event stack "
771 + "overflowed and was truncated",
772 new Throwable());
773 } else {
774 // throw an exception if the event was not found and the events stack
775 // is pristine
776 throw new IllegalStateException();
777 }
778 }
779
780 long elapsed = t.stopTimeMs - t.startTimeMs;
781
782 if (silenceThreshold == -1) { // use default
783 silenceThreshold = defaultSilenceThreshold;
784 }
785
786 if (elapsed < silenceThreshold) {
787 // If this one is silent then we need to remove the start Event
788 boolean removed = false;
789 for (int i = 0; i < events.size(); i++) {
790 Event e = events.get(i);
791 if (e.tracer == t) {
792 Preconditions.checkState(e.isStart);
793 events.remove(i);
794 removed = true;
795 break;
796 }
797 }
798
799 // Only assert if we didn't find the original and the events
800 // weren't truncated.
801 Preconditions.checkState(removed || isEventsTruncated);
802 } else {
803 events.add(new Event(false, t));
804 }
805
806 if (t.type != null) {
807 Stat stat = stats.get(t.type);
808 if (stat == null) {
809 stat = new Stat();
810 if (!extraTracingStatistics.isEmpty()) {
811 stat.extraInfo = new int[extraTracingStatistics.size()];
812 }
813 stats.put(t.type, stat);
814 }
815
816 stat.count++;
817 if (typeToCountMap != null) {
818 typeToCountMap.incrementBy(t.type, 1);
819 }
820
821 stat.clockTime += elapsed;
822 if (typeToTimeMap != null) {
823 typeToTimeMap.incrementBy(t.type, elapsed);
824 }
825
826 if (stat.extraInfo != null && t.extraTracingValues != null) {
827 int overlapLength =
828 Math.min(stat.extraInfo.length, t.extraTracingValues.length);
829 for (int i = 0; i < overlapLength; i++) {
830 stat.extraInfo[i] += t.extraTracingValues[i];
831 AtomicTracerStatMap map =
832 extraTracingStatistics.get(i).getTracingStat();
833 if (map != null) {
834 map.incrementBy(t.type, t.extraTracingValues[i]);
835 }
836 }
837 }
838
839 if (elapsed < silenceThreshold) {
840 stat.silent++;
841 if (typeToSilentMap != null) {
842 typeToSilentMap.incrementBy(t.type, 1);
843 }
844 }
845 }
846 }
847
848 boolean isEmpty() {
849 return events.size() == 0 && outstandingEvents.size() == 0;
850 }
851
852 void truncateOutstandingEvents() {
853 isOutstandingEventsTruncated = true;
854 outstandingEvents.clear();
855 }
856
857 void truncateEvents() {
858 isEventsTruncated = true;
859 events.clear();
860 }
861
862 /** Produces the lovely Trace seen in the class comments */
863 // Nullness checker does not understand that prettyPrint => indent != null
864 @SuppressWarnings("nullness")
865 @Override public String toString() {
866
867 int numDigits = getMaxDigits();
868 StringBuilder sb = new StringBuilder();
869 long etime = -1;
870 LinkedList<String> indent = prettyPrint ? new LinkedList<String>() : null;
871 for (Event e : events) {
872 if (prettyPrint && !e.isStart && !indent.isEmpty()) {
873 indent.pop();
874 }
875 sb.append(" ");
876 if (prettyPrint) {
877 sb.append(e.toString(etime, Joiner.on("").join(indent), numDigits));
878 } else {
879 sb.append(e.toString(etime, "", 4));
880 }
881 etime = e.eventTime();
882 sb.append('\n');
883 if (prettyPrint && e.isStart) {
884 indent.push("| ");
885 }
886 }
887
888 if (outstandingEvents.size() != 0) {
889 long now = clock.currentTimeMillis();
890
891 sb.append(" Unstopped timers:\n");
892 for (Tracer t : outstandingEvents) {
893 sb.append(" ").
894 append(t).
895 append(" (").
896 append(now - t.startTimeMs).
897 append(" ms, started at ").
898 append(formatTime(t.startTimeMs)).
899 append(")\n");
900 }
901 }
902
903 for (String key : stats.keySet()) {
904 Stat stat = stats.get(key);
905 if (stat.count > 1) {
906 sb.append(" TOTAL ").
907 append(key).
908 append(" ").
909 append(stat.count).
910 append(" (").
911 append(stat.clockTime).
912 append(" ms");
913 if (stat.extraInfo != null) {
914 for (int i = 0; i < stat.extraInfo.length; i++) {
915 sb.append("; ");
916 sb.append(stat.extraInfo[i]).
917 append(' ').
918 append(extraTracingStatistics.get(i).getUnits());
919 }
920 }
921 sb.append(")\n");
922 }
923 }
924 return sb.toString();
925 }
926
927 /**
928 * Gets the maximum number of digits that can appear in the tracer output
929 * in the gaps between tracers or the duration of a tracer. This is used
930 * by the pretty printing case so that all of the tracers are aligned.
931 */
932 private int getMaxDigits() {
933 long etime = -1;
934 long max_time = 0;
935 for (Event e : events) {
936 if (etime != -1) {
937 long time = e.eventTime() - etime;
938 max_time = Math.max(max_time, time);
939 }
940 if (!e.isStart) {
941 long time = e.tracer.stopTimeMs - e.tracer.startTimeMs;
942 max_time = Math.max(max_time, time);
943 }
944 etime = e.eventTime();
945 }
946 // Minimum is 3 to preserve an indent even when max is small.
947 return Math.max(3, numDigits(max_time));
948 }
949 }
950
951 /** Holds the ThreadTrace for each thread. */
952 private static ThreadLocal<ThreadTrace> traces =
953 new ThreadLocal<ThreadTrace>();
954
955 /**
956 * Get the ThreadTrace for the current thread, creating one if necessary.
957 */
958 static ThreadTrace getThreadTrace() {
959 ThreadTrace t = traces.get();
960 if (t == null) {
961 t = new ThreadTrace();
962 t.prettyPrint = defaultPrettyPrint;
963 traces.set(t);
964 }
965 return t;
966 }
967
968 /** Remove any ThreadTrace associated with the current thread */
969 static void clearThreadTrace() {
970 traces.remove();
971 }
972
973 /**
974 * A TracingStatistic allows the program to add additional optional
975 * statistics to the trace output.
976 *
977 * The class com.google.monitoring.tracing.TracingStatistics
978 * contains several useful tracing statistics
979 *
980 */
981 static interface TracingStatistic {
982 /**
983 * This method is called at the start of the trace. It should
984 * return a numeric result indicating the amount of the specific
985 * resource in use before the call started
986 * @param thread The current thread
987 * @return A numeric value indicating the amount of the resource
988 * already used.
989 */
990 long start(Thread thread);
991
992 /**
993 * This method is called at the end of the trace. It should
994 * return a numeric result indicating the amount of the specific
995 * resource in use after the call ends. The actual reported result
996 * will be the result end() - start()
997 * @param thread The current thread
998 * @return A numeric value indicating the amount of the resource
999 * currently used.
1000 */
1001 long stop(Thread thread);
1002
1003 /**
1004 * Called when this tracing statistic is first enabled. A return
1005 * value of True indicates that this statistic can successfully
1006 * run in the current JVM.
1007 *
1008 * @return An indication of whether this statistic can be
1009 * implemented in the current JVM.
1010 */
1011 boolean enable();
1012
1013 /** Returns this tracing statistic's trace map.
1014 *
1015 * @return This tracing statistic's trace map.
1016 */
1017 AtomicTracerStatMap getTracingStat();
1018
1019 /** A string that should be appended to the numeric output
1020 * indicating what this is.
1021 *
1022 * @return A string indicating the units of this statistic and what it is.
1023 */
1024 String getUnits();
1025 }
1026
1027 /**
1028 * This class encapsulates a map for keeping track of tracing statistics.
1029 * It allows the caller to atomically increment named fields.
1030 *
1031 */
1032 static final class AtomicTracerStatMap {
1033 private ConcurrentMap<String, Long> map =
1034 new ConcurrentHashMap<String, Long>();
1035
1036 /**
1037 * Atomically increment the specified field by the specified amount.
1038 *
1039 * @param key the name of the field
1040 * @param delta the amount by which to increment the field
1041 */
1042 // Nullness checker is not powerful enough to prove null-safety of
1043 // this method
1044 @SuppressWarnings("nullness")
1045 void incrementBy(String key, long delta) {
1046 // We use a compareAndSet strategy to update the map, which is much
1047 // faster when there isn't too much contention. Look at a value, and
1048 // conditionally update the map if the value hasn't changed.
1049 // If it has changed, repeat.
1050 Long oldValue = map.get(key);
1051 if (oldValue == null) {
1052 // Currently, the slot is empty
1053 oldValue = map.putIfAbsent(key, delta);
1054 if (oldValue == null) {
1055 // The slot was still empty when we set it
1056 return;
1057 } else {
1058 // Someone filled in the slot behind our back. oldValue has
1059 // its current value
1060 }
1061 }
1062 while (true) {
1063 if (map.replace(key, oldValue, oldValue + delta)) {
1064 break;
1065 }
1066 // Nullness checker doesn't understand that this cannot return null.
1067 oldValue = map.get(key);
1068 }
1069 }
1070
1071 /**
1072 * Returns a map of key:value pairs.
1073 */
1074 Map<String, Long> getMap() {
1075 return map;
1076 }
1077 }
1078 }