001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.metrics2.lib;
020
021import static org.apache.hadoop.metrics2.lib.Interns.info;
022
023import java.io.IOException;
024import java.util.Map;
025import java.util.concurrent.TimeUnit;
026
027import org.apache.commons.lang.StringUtils;
028import org.apache.hadoop.hbase.classification.InterfaceAudience;
029import org.apache.hadoop.metrics2.MetricHistogram;
030import org.apache.hadoop.metrics2.MetricsExecutor;
031import org.apache.hadoop.metrics2.MetricsInfo;
032import org.apache.hadoop.metrics2.MetricsRecordBuilder;
033import org.apache.hadoop.metrics2.util.MetricQuantile;
034import org.apache.hadoop.metrics2.util.MetricSampleQuantiles;
035
036import com.google.common.annotations.VisibleForTesting;
037
038/**
039 * Watches a stream of long values, maintaining online estimates of specific quantiles with provably
040 * low error bounds. This is particularly useful for accurate high-percentile (e.g. 95th, 99th)
041 * latency metrics.
042 */
043@InterfaceAudience.Private
044public class MetricMutableQuantiles extends MutableMetric implements MetricHistogram {
045
046  static final MetricQuantile[] quantiles = {new MetricQuantile(0.50, 0.050),
047      new MetricQuantile(0.75, 0.025), new MetricQuantile(0.90, 0.010),
048      new MetricQuantile(0.95, 0.005), new MetricQuantile(0.99, 0.001)};
049
050  private final MetricsInfo numInfo;
051  private final MetricsInfo[] quantileInfos;
052  private final int interval;
053
054  private MetricSampleQuantiles estimator;
055  private long previousCount = 0;
056  private MetricsExecutor executor;
057
058
059  @VisibleForTesting
060  protected Map<MetricQuantile, Long> previousSnapshot = null;
061
062  /**
063   * Instantiates a new {@link MetricMutableQuantiles} for a metric that rolls itself over on the
064   * specified time interval.
065   *
066   * @param name        of the metric
067   * @param description long-form textual description of the metric
068   * @param sampleName  type of items in the stream (e.g., "Ops")
069   * @param valueName   type of the values
070   * @param interval    rollover interval (in seconds) of the estimator
071   */
072  public MetricMutableQuantiles(String name, String description, String sampleName,
073                                String valueName, int interval) {
074    String ucName = StringUtils.capitalize(name);
075    String usName = StringUtils.capitalize(sampleName);
076    String uvName = StringUtils.capitalize(valueName);
077    String desc = StringUtils.uncapitalize(description);
078    String lsName = StringUtils.uncapitalize(sampleName);
079    String lvName = StringUtils.uncapitalize(valueName);
080
081    numInfo = info(ucName + "Num" + usName, String.format(
082        "Number of %s for %s with %ds interval", lsName, desc, interval));
083    // Construct the MetricsInfos for the quantiles, converting to percentiles
084    quantileInfos = new MetricsInfo[quantiles.length];
085    String nameTemplate = "%s%dthPercentile%dsInterval%s";
086    String descTemplate = "%d percentile %s with %d second interval for %s";
087    for (int i = 0; i < quantiles.length; i++) {
088      int percentile = (int) (100 * quantiles[i].quantile);
089      quantileInfos[i] = info(String.format(nameTemplate, ucName, percentile, interval, uvName),
090          String.format(descTemplate, percentile, lvName, interval, desc));
091    }
092
093    estimator = new MetricSampleQuantiles(quantiles);
094    executor = new MetricsExecutorImpl();
095    this.interval = interval;
096    executor.getExecutor().scheduleAtFixedRate(new RolloverSample(this),
097        interval,
098        interval,
099        TimeUnit.SECONDS);
100  }
101
102  @Override
103  public synchronized void snapshot(MetricsRecordBuilder builder, boolean all) {
104    if (all || changed()) {
105      builder.addGauge(numInfo, previousCount);
106      for (int i = 0; i < quantiles.length; i++) {
107        long newValue = 0;
108        // If snapshot is null, we failed to update since the window was empty
109        if (previousSnapshot != null) {
110          newValue = previousSnapshot.get(quantiles[i]);
111        }
112        builder.addGauge(quantileInfos[i], newValue);
113      }
114      if (changed()) {
115        clearChanged();
116      }
117    }
118  }
119
120  public synchronized void add(long value) {
121    estimator.insert(value);
122  }
123
124  public int getInterval() {
125    return interval;
126  }
127
128  /** Runnable used to periodically roll over the internal {@link org.apache.hadoop.metrics2.util.MetricSampleQuantiles} every interval. */
129  private static class RolloverSample implements Runnable {
130
131    MetricMutableQuantiles parent;
132
133    public RolloverSample(MetricMutableQuantiles parent) {
134      this.parent = parent;
135    }
136
137    @Override
138    public void run() {
139      synchronized (parent) {
140        try {
141          parent.previousCount = parent.estimator.getCount();
142          parent.previousSnapshot = parent.estimator.snapshot();
143        } catch (IOException e) {
144          // Couldn't get a new snapshot because the window was empty
145          parent.previousCount = 0;
146          parent.previousSnapshot = null;
147        }
148        parent.estimator.clear();
149      }
150      parent.setChanged();
151    }
152
153  }
154}