001package io.prometheus.client;
002
003import java.io.Closeable;
004import java.util.ArrayList;
005import java.util.Collections;
006import java.util.List;
007import java.util.Map;
008
009/**
010 * Histogram metric, to track distributions of events.
011 * <p>
012 * Example of uses for Histograms include:
013 * <ul>
014 *  <li>Response latency</li>
015 *  <li>Request size</li>
016 * </ul>
017 * <p>
018 * <em>Note:</em> Each bucket is one timeseries. Many buckets and/or many dimensions with labels
019 * can produce large amount of time series, that may cause performance problems.
020 *
021 * <p>
022 * The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds.
023 * <p>
024 * Example Histograms:
025 * <pre>
026 * {@code
027 *   class YourClass {
028 *     static final Histogram requestLatency = Histogram.build()
029 *         .name("requests_latency_seconds").help("Request latency in seconds.").register();
030 *
031 *     void processRequest(Request req) {
032 *        Histogram.Timer requestTimer = requestLatency.startTimer();
033 *        try {
034 *          // Your code here.
035 *        } finally {
036 *          requestTimer.observeDuration();
037 *        }
038 *     }
039 *
040 *     // Or if using Java 8 lambdas.
041 *     void processRequestLambda(Request req) {
042 *        requestLatency.time(() -> {
043 *          // Your code here.
044 *        });
045 *     }
046 *   }
047 * }
048 * </pre>
049 * <p>
050 * You can choose your own buckets:
051 * <pre>
052 * {@code
053 *     static final Histogram requestLatency = Histogram.build()
054 *         .buckets(.01, .02, .03, .04)
055 *         .name("requests_latency_seconds").help("Request latency in seconds.").register();
056 * }
057 * </pre>
058 * {@link Histogram.Builder#linearBuckets(double, double, int) linearBuckets} and
059 * {@link Histogram.Builder#exponentialBuckets(double, double, int) exponentialBuckets}
060 * offer easy ways to set common bucket patterns.
061 */
062public class Histogram extends SimpleCollector<Histogram.Child> implements Collector.Describable {
063  private final double[] buckets;
064
065  Histogram(Builder b) {
066    super(b);
067    buckets = b.buckets;
068    initializeNoLabelsChild();
069  }
070
071  public static class Builder extends SimpleCollector.Builder<Builder, Histogram> {
072    private double[] buckets = new double[]{.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10};
073
074    @Override
075    public Histogram create() {
076      for (int i = 0; i < buckets.length - 1; i++) {
077        if (buckets[i] >= buckets[i + 1]) {
078          throw new IllegalStateException("Histogram buckets must be in increasing order: "
079              + buckets[i] + " >= " + buckets[i + 1]);
080        }
081      }
082      if (buckets.length == 0) {
083          throw new IllegalStateException("Histogram must have at least one bucket.");
084      }
085      for (String label: labelNames) {
086        if (label.equals("le")) {
087            throw new IllegalStateException("Histogram cannot have a label named 'le'.");
088        }
089      }
090
091      // Append infinity bucket if it's not already there.
092      if (buckets[buckets.length - 1] != Double.POSITIVE_INFINITY) {
093        double[] tmp = new double[buckets.length + 1];
094        System.arraycopy(buckets, 0, tmp, 0, buckets.length);
095        tmp[buckets.length] = Double.POSITIVE_INFINITY;
096        buckets = tmp;
097      }
098      dontInitializeNoLabelsChild = true;
099      return new Histogram(this);
100    }
101
102    /**
103      * Set the upper bounds of buckets for the histogram.
104      */
105    public Builder buckets(double... buckets) {
106      this.buckets = buckets;
107      return this;
108    }
109
110    /**
111      * Set the upper bounds of buckets for the histogram with a linear sequence.
112      */
113    public Builder linearBuckets(double start, double width, int count) {
114      buckets = new double[count];
115      for (int i = 0; i < count; i++){
116        buckets[i] = start + i*width;
117      }
118      return this;
119    }
120    /**
121      * Set the upper bounds of buckets for the histogram with an exponential sequence.
122      */
123    public Builder exponentialBuckets(double start, double factor, int count) {
124      buckets = new double[count];
125      for (int i = 0; i < count; i++) {
126        buckets[i] = start * Math.pow(factor, i);
127      }
128      return this;
129    }
130
131  }
132
133  /**
134   *  Return a Builder to allow configuration of a new Histogram. Ensures required fields are provided.
135   *
136   *  @param name The name of the metric
137   *  @param help The help string of the metric
138   */
139  public static Builder build(String name, String help) {
140    return new Builder().name(name).help(help);
141  }
142
143  /**
144   *  Return a Builder to allow configuration of a new Histogram.
145   */
146  public static Builder build() {
147    return new Builder();
148  }
149
150  @Override
151  protected Child newChild() {
152    return new Child(buckets);
153  }
154
155  /**
156   * Represents an event being timed.
157   */
158  public static class Timer implements Closeable {
159    private final Child child;
160    private final long start;
161    private Timer(Child child, long start) {
162      this.child = child;
163      this.start = start;
164    }
165    /**
166     * Observe the amount of time in seconds since {@link Child#startTimer} was called.
167     * @return Measured duration in seconds since {@link Child#startTimer} was called.
168     */
169    public double observeDuration() {
170        double elapsed = SimpleTimer.elapsedSecondsFromNanos(start, SimpleTimer.defaultTimeProvider.nanoTime());
171        child.observe(elapsed);
172        return elapsed;
173    }
174
175    /**
176     * Equivalent to calling {@link #observeDuration()}.
177     */
178    @Override
179    public void close() {
180      observeDuration();
181    }
182  }
183
184  /**
185   * The value of a single Histogram.
186   * <p>
187   * <em>Warning:</em> References to a Child become invalid after using
188   * {@link SimpleCollector#remove} or {@link SimpleCollector#clear}.
189   */
190  public static class Child {
191
192    /**
193     * Executes runnable code (i.e. a Java 8 Lambda) and observes a duration of how long it took to run.
194     *
195     * @param timeable Code that is being timed
196     * @return Measured duration in seconds for timeable to complete.
197     */
198    public double time(Runnable timeable) {
199      Timer timer = startTimer();
200
201      double elapsed;
202      try {
203        timeable.run();
204      } finally {
205        elapsed = timer.observeDuration();
206      }
207      return elapsed;
208    }
209
210    public static class Value {
211      public final double sum;
212      public final double[] buckets;
213
214      public Value(double sum, double[] buckets) {
215        this.sum = sum;
216        this.buckets = buckets;
217      }
218    }
219
220    private Child(double[] buckets) {
221      upperBounds = buckets;
222      cumulativeCounts = new DoubleAdder[buckets.length];
223      for (int i = 0; i < buckets.length; ++i) {
224        cumulativeCounts[i] = new DoubleAdder();
225      }
226    }
227    private final double[] upperBounds;
228    private final DoubleAdder[] cumulativeCounts;
229    private final DoubleAdder sum = new DoubleAdder();
230
231
232    /**
233     * Observe the given amount.
234     */
235    public void observe(double amt) {
236      for (int i = 0; i < upperBounds.length; ++i) {
237        // The last bucket is +Inf, so we always increment.
238        if (amt <= upperBounds[i]) {
239          cumulativeCounts[i].add(1);
240          break;
241        }
242      }
243      sum.add(amt);
244    }
245    /**
246     * Start a timer to track a duration.
247     * <p>
248     * Call {@link Timer#observeDuration} at the end of what you want to measure the duration of.
249     */
250    public Timer startTimer() {
251      return new Timer(this, SimpleTimer.defaultTimeProvider.nanoTime());
252    }
253    /**
254     * Get the value of the Histogram.
255     * <p>
256     * <em>Warning:</em> The definition of {@link Value} is subject to change.
257     */
258    public Value get() {
259      double[] buckets = new double[cumulativeCounts.length];
260      double acc = 0;
261      for (int i = 0; i < cumulativeCounts.length; ++i) {
262        acc += cumulativeCounts[i].sum();
263        buckets[i] = acc;
264      }
265      return new Value(sum.sum(), buckets);
266    }
267  }
268
269  // Convenience methods.
270  /**
271   * Observe the given amount on the histogram with no labels.
272   */
273  public void observe(double amt) {
274    noLabelsChild.observe(amt);
275  }
276  /**
277   * Start a timer to track a duration on the histogram with no labels.
278   * <p>
279   * Call {@link Timer#observeDuration} at the end of what you want to measure the duration of.
280   */
281  public Timer startTimer() {
282    return noLabelsChild.startTimer();
283  }
284
285  /**
286   * Executes runnable code (i.e. a Java 8 Lambda) and observes a duration of how long it took to run.
287   *
288   * @param timeable Code that is being timed
289   * @return Measured duration in seconds for timeable to complete.
290   */
291  public double time(Runnable timeable){
292    return noLabelsChild.time(timeable);
293  }
294
295  @Override
296  public List<MetricFamilySamples> collect() {
297    List<MetricFamilySamples.Sample> samples = new ArrayList<MetricFamilySamples.Sample>();
298    for(Map.Entry<List<String>, Child> c: children.entrySet()) {
299      Child.Value v = c.getValue().get();
300      List<String> labelNamesWithLe = new ArrayList<String>(labelNames);
301      labelNamesWithLe.add("le");
302      for (int i = 0; i < v.buckets.length; ++i) {
303        List<String> labelValuesWithLe = new ArrayList<String>(c.getKey());
304        labelValuesWithLe.add(doubleToGoString(buckets[i]));
305        samples.add(new MetricFamilySamples.Sample(fullname + "_bucket", labelNamesWithLe, labelValuesWithLe, v.buckets[i]));
306      }
307      samples.add(new MetricFamilySamples.Sample(fullname + "_count", labelNames, c.getKey(), v.buckets[buckets.length-1]));
308      samples.add(new MetricFamilySamples.Sample(fullname + "_sum", labelNames, c.getKey(), v.sum));
309    }
310
311    return familySamplesList(Type.HISTOGRAM, samples);
312  }
313
314  @Override
315  public List<MetricFamilySamples> describe() {
316    return Collections.singletonList(
317            new MetricFamilySamples(fullname, Type.HISTOGRAM, help, Collections.<MetricFamilySamples.Sample>emptyList()));
318  }
319
320  double[] getBuckets() {
321    return buckets;
322  }
323
324
325}