View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
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   * Publishes a rate based on a counter - you increment the counter each
29   * time an event occurs (eg: an RPC call) and this publishes a rate.
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    private synchronized void intervalHeartBeat() {
60      long now = System.currentTimeMillis();
61      long diff = (now-ts)/1000;
62      if (diff == 0) diff = 1; // sigh this is crap.
63      this.prevRate = (float)value / diff;
64      this.value = 0;
65      this.ts = now;
66    }
67  
68    @Override
69    public synchronized void pushMetric(final MetricsRecord mr) {
70      intervalHeartBeat();
71      try {
72        mr.setMetric(getName(), getPreviousIntervalValue());
73      } catch (Exception e) {
74        LOG.info("pushMetric failed for " + getName() + "\n" +
75            StringUtils.stringifyException(e));
76      }
77    }
78  
79    public synchronized float getPreviousIntervalValue() {
80      return this.prevRate;
81    }
82  }