1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.omid.tso;
19
20 import org.apache.phoenix.thirdparty.com.google.common.base.Stopwatch;
21 import org.apache.phoenix.thirdparty.com.google.common.base.Throwables;
22 import org.apache.omid.metrics.MetricsRegistry;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import javax.annotation.concurrent.NotThreadSafe;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29
30 import static org.apache.omid.metrics.MetricsUtils.name;
31 import java.util.concurrent.TimeUnit;
32
33 @NotThreadSafe
34 public class MonitoringContextImpl implements MonitoringContext{
35
36 private static final Logger LOG = LoggerFactory.getLogger(MonitoringContextImpl.class);
37
38 private volatile boolean flag;
39 private Map<String, Long> elapsedTimeMsMap = new ConcurrentHashMap<>();
40 private Map<String, Stopwatch> timers = new ConcurrentHashMap<>();
41 private MetricsRegistry metrics;
42
43 public MonitoringContextImpl(MetricsRegistry metrics) {
44 this.metrics = metrics;
45 }
46
47 public void timerStart(String name) {
48 Stopwatch stopwatch = Stopwatch.createStarted();
49 timers.put(name, stopwatch);
50 }
51
52 public void timerStop(String name) {
53 if (flag) {
54 LOG.warn("timerStop({}) called after publish. Measurement was ignored. {}", name, Throwables.getStackTraceAsString(new Exception()));
55 return;
56 }
57 Stopwatch activeStopwatch = timers.get(name);
58 if (activeStopwatch == null) {
59 throw new IllegalStateException(
60 String.format("There is no %s timer in the %s monitoring context.", name, this));
61 }
62 activeStopwatch.stop();
63 elapsedTimeMsMap.put(name, activeStopwatch.elapsed(TimeUnit.NANOSECONDS));
64 timers.remove(name);
65 }
66
67 public void publish() {
68 flag = true;
69 for (Map.Entry<String, Long> entry : elapsedTimeMsMap.entrySet()) {
70 metrics.timer(name("tso", entry.getKey())).update(entry.getValue());
71 }
72 }
73
74 }