1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.metrics;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.apache.hadoop.metrics.MetricsRecord;
23 import org.apache.hadoop.metrics.util.MetricsBase;
24 import org.apache.hadoop.metrics.util.MetricsRegistry;
25 import org.apache.hadoop.util.StringUtils;
26
27
28
29
30
31 public class MetricsRate extends MetricsBase {
32 private static final Log LOG = LogFactory.getLog("org.apache.hadoop.hbase.metrics");
33
34 private int value;
35 private float prevRate;
36 private long ts;
37
38 public MetricsRate(final String name, final MetricsRegistry registry,
39 final String description) {
40 super(name, description);
41 this.value = 0;
42 this.prevRate = 0;
43 this.ts = System.currentTimeMillis();
44 registry.add(name, this);
45 }
46
47 public MetricsRate(final String name, final MetricsRegistry registry) {
48 this(name, registry, NO_DESCRIPTION);
49 }
50
51 public synchronized void inc(final int incr) {
52 value += incr;
53 }
54
55 public synchronized void inc() {
56 value++;
57 }
58
59 public synchronized void intervalHeartBeat() {
60 long now = System.currentTimeMillis();
61 long diff = (now-ts) / 1000;
62 if (diff < 1){
63
64
65 return;
66 }
67 this.prevRate = (float)value / diff;
68 this.value = 0;
69 this.ts = now;
70 }
71
72 @Override
73 public synchronized void pushMetric(final MetricsRecord mr) {
74 intervalHeartBeat();
75 try {
76 mr.setMetric(getName(), getPreviousIntervalValue());
77 } catch (Exception e) {
78 LOG.info("pushMetric failed for " + getName() + "\n" +
79 StringUtils.stringifyException(e));
80 }
81 }
82
83 public synchronized float getPreviousIntervalValue() {
84 return this.prevRate;
85 }
86 }