logging: add more tests for fatal log messages
[folly.git] / folly / stats / TimeseriesHistogram.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <string>
20 #include <folly/stats/Histogram.h>
21 #include <folly/stats/MultiLevelTimeSeries.h>
22
23 namespace folly {
24
25 /*
26  * TimeseriesHistogram tracks data distributions as they change over time.
27  *
28  * Specifically, it is a bucketed histogram with different value ranges assigned
29  * to each bucket.  Within each bucket is a MultiLevelTimeSeries from
30  * 'folly/stats/MultiLevelTimeSeries.h'. This means that each bucket contains a
31  * different set of data for different historical time periods, and one can
32  * query data distributions over different trailing time windows.
33  *
34  * For example, this can answer questions: "What is the data distribution over
35  * the last minute? Over the last 10 minutes?  Since I last cleared this
36  * histogram?"
37  *
38  * The class can also estimate percentiles and answer questions like: "What was
39  * the 99th percentile data value over the last 10 minutes?"
40  *
41  * Note: that depending on the size of your buckets and the smoothness
42  * of your data distribution, the estimate may be way off from the actual
43  * value.  In particular, if the given percentile falls outside of the bucket
44  * range (i.e. your buckets range in 0 - 100,000 but the 99th percentile is
45  * around 115,000) this estimate may be very wrong.
46  *
47  * The memory usage for a typical histogram is roughly 3k * (# of buckets).  All
48  * insertion operations are amortized O(1), and all queries are O(# of buckets).
49  */
50 template <
51     class T,
52     class CT = LegacyStatsClock<std::chrono::seconds>,
53     class C = folly::MultiLevelTimeSeries<T, CT>>
54 class TimeseriesHistogram {
55  private:
56    // NOTE: T must be equivalent to _signed_ numeric type for our math.
57    static_assert(std::numeric_limits<T>::is_signed, "");
58
59  public:
60   // Values to be inserted into container
61   using ValueType = T;
62   // The container type we use internally for each bucket
63   using ContainerType = C;
64   // Clock, duration, and time point types
65   using Clock = CT;
66   using Duration = typename Clock::duration;
67   using TimePoint = typename Clock::time_point;
68
69   /*
70    * Create a TimeSeries histogram and initialize the bucketing and levels.
71    *
72    * The buckets are created by chopping the range [min, max) into pieces
73    * of size bucketSize, with the last bucket being potentially shorter.  Two
74    * additional buckets are always created -- the "under" bucket for the range
75    * (-inf, min) and the "over" bucket for the range [max, +inf).
76    *
77    * @param bucketSize the width of each bucket
78    * @param min the smallest value for the bucket range.
79    * @param max the largest value for the bucket range
80    * @param defaultContainer a pre-initialized timeseries with the desired
81    *                         number of levels and their durations.
82    */
83   TimeseriesHistogram(ValueType bucketSize, ValueType min, ValueType max,
84                       const ContainerType& defaultContainer);
85
86   /* Return the bucket size of each bucket in the histogram. */
87   ValueType getBucketSize() const { return buckets_.getBucketSize(); }
88
89   /* Return the min value at which bucketing begins. */
90   ValueType getMin() const { return buckets_.getMin(); }
91
92   /* Return the max value at which bucketing ends. */
93   ValueType getMax() const { return buckets_.getMax(); }
94
95   /* Return the number of levels of the Timeseries object in each bucket */
96   size_t getNumLevels() const {
97     return buckets_.getByIndex(0).numLevels();
98   }
99
100   /* Return the number of buckets */
101   size_t getNumBuckets() const {
102     return buckets_.getNumBuckets();
103   }
104
105   /*
106    * Return the threshold of the bucket for the given index in range
107    * [0..numBuckets).  The bucket will have range [thresh, thresh + bucketSize)
108    * or [thresh, max), whichever is shorter.
109    */
110   ValueType getBucketMin(size_t bucketIdx) const {
111     return buckets_.getBucketMin(bucketIdx);
112   }
113
114   /* Return the actual timeseries in the given bucket (for reading only!) */
115   const ContainerType& getBucket(size_t bucketIdx) const {
116     return buckets_.getByIndex(bucketIdx);
117   }
118
119   /* Total count of values at the given timeseries level (all buckets). */
120   uint64_t count(size_t level) const {
121     uint64_t total = 0;
122     for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
123       total += buckets_.getByIndex(b).count(level);
124     }
125     return total;
126   }
127
128   /* Total count of values added during the given interval (all buckets). */
129   uint64_t count(TimePoint start, TimePoint end) const {
130     uint64_t total = 0;
131     for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
132       total += buckets_.getByIndex(b).count(start, end);
133     }
134     return total;
135   }
136
137   /* Total sum of values at the given timeseries level (all buckets). */
138   ValueType sum(size_t level) const {
139     ValueType total = ValueType();
140     for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
141       total += buckets_.getByIndex(b).sum(level);
142     }
143     return total;
144   }
145
146   /* Total sum of values added during the given interval (all buckets). */
147   ValueType sum(TimePoint start, TimePoint end) const {
148     ValueType total = ValueType();
149     for (size_t b = 0; b < buckets_.getNumBuckets(); ++b) {
150       total += buckets_.getByIndex(b).sum(start, end);
151     }
152     return total;
153   }
154
155   /* Average of values at the given timeseries level (all buckets). */
156   template <typename ReturnType = double>
157   ReturnType avg(size_t level) const {
158     auto total = ValueType();
159     uint64_t nsamples = 0;
160     computeAvgData(&total, &nsamples, level);
161     return folly::detail::avgHelper<ReturnType>(total, nsamples);
162   }
163
164   /* Average of values added during the given interval (all buckets). */
165   template <typename ReturnType = double>
166   ReturnType avg(TimePoint start, TimePoint end) const {
167     auto total = ValueType();
168     uint64_t nsamples = 0;
169     computeAvgData(&total, &nsamples, start, end);
170     return folly::detail::avgHelper<ReturnType>(total, nsamples);
171   }
172
173   /*
174    * Rate at the given timeseries level (all buckets).
175    * This is the sum of all values divided by the time interval (in seconds).
176    */
177   template <typename ReturnType = double>
178   ReturnType rate(size_t level) const {
179     auto total = ValueType();
180     Duration elapsed(0);
181     computeRateData(&total, &elapsed, level);
182     return folly::detail::rateHelper<ReturnType, Duration, Duration>(
183         total, elapsed);
184   }
185
186   /*
187    * Rate for the given interval (all buckets).
188    * This is the sum of all values divided by the time interval (in seconds).
189    */
190   template <typename ReturnType = double>
191   ReturnType rate(TimePoint start, TimePoint end) const {
192     auto total = ValueType();
193     Duration elapsed(0);
194     computeRateData(&total, &elapsed, start, end);
195     return folly::detail::rateHelper<ReturnType, Duration, Duration>(
196         total, elapsed);
197   }
198
199   /*
200    * Update every underlying timeseries object with the given timestamp. You
201    * must call this directly before querying to ensure that the data in all
202    * buckets is decayed properly.
203    */
204   void update(TimePoint now);
205
206   /* clear all the data from the histogram. */
207   void clear();
208
209   /* Add a value into the histogram with timestamp 'now' */
210   void addValue(TimePoint now, const ValueType& value);
211   /* Add a value the given number of times with timestamp 'now' */
212   void addValue(TimePoint now, const ValueType& value, uint64_t times);
213
214   /*
215    * Add all of the values from the specified histogram.
216    *
217    * All of the values will be added to the current time-slot.
218    *
219    * One use of this is for thread-local caching of frequently updated
220    * histogram data.  For example, each thread can store a thread-local
221    * Histogram that is updated frequently, and only add it to the global
222    * TimeseriesHistogram once a second.
223    */
224   void addValues(TimePoint now, const folly::Histogram<ValueType>& values);
225
226   /*
227    * Return an estimate of the value at the given percentile in the histogram
228    * in the given timeseries level.  The percentile is estimated as follows:
229    *
230    * - We retrieve a count of the values in each bucket (at the given level)
231    * - We determine via the counts which bucket the given percentile falls in.
232    * - We assume the average value in the bucket is also its median
233    * - We then linearly interpolate within the bucket, by assuming that the
234    *   distribution is uniform in the two value ranges [left, median) and
235    *   [median, right) where [left, right) is the bucket value range.
236    *
237    * Caveats:
238    * - If the histogram is empty, this always returns ValueType(), usually 0.
239    * - For the 'under' and 'over' special buckets, their range is unbounded
240    *   on one side.  In order for the interpolation to work, we assume that
241    *   the average value in the bucket is equidistant from the two edges of
242    *   the bucket.  In other words, we assume that the distance between the
243    *   average and the known bound is equal to the distance between the average
244    *   and the unknown bound.
245    */
246   ValueType getPercentileEstimate(double pct, size_t level) const;
247   /*
248    * Return an estimate of the value at the given percentile in the histogram
249    * in the given historical interval.  Please see the documentation for
250    * getPercentileEstimate(double pct, size_t level) for the explanation of the
251    * estimation algorithm.
252    */
253   ValueType getPercentileEstimate(double pct, TimePoint start, TimePoint end)
254       const;
255
256   /*
257    * Return the bucket index that the given percentile falls into (in the
258    * given timeseries level).  This index can then be used to retrieve either
259    * the bucket threshold, or other data from inside the bucket.
260    */
261   size_t getPercentileBucketIdx(double pct, size_t level) const;
262   /*
263    * Return the bucket index that the given percentile falls into (in the
264    * given historical interval).  This index can then be used to retrieve either
265    * the bucket threshold, or other data from inside the bucket.
266    */
267   size_t getPercentileBucketIdx(double pct, TimePoint start, TimePoint end)
268       const;
269
270   /* Get the bucket threshold for the bucket containing the given pct. */
271   ValueType getPercentileBucketMin(double pct, size_t level) const {
272     return getBucketMin(getPercentileBucketIdx(pct, level));
273   }
274   /* Get the bucket threshold for the bucket containing the given pct. */
275   ValueType getPercentileBucketMin(double pct, TimePoint start, TimePoint end)
276       const {
277     return getBucketMin(getPercentileBucketIdx(pct, start, end));
278   }
279
280   /*
281    * Print out serialized data from all buckets at the given level.
282    * Format is: BUCKET [',' BUCKET ...]
283    * Where: BUCKET == bucketMin ':' count ':' avg
284    */
285   std::string getString(size_t level) const;
286
287   /*
288    * Print out serialized data for all buckets in the historical interval.
289    * For format, please see getString(size_t level).
290    */
291   std::string getString(TimePoint start, TimePoint end) const;
292
293   /*
294    * Legacy APIs that accept a Duration parameters rather than TimePoint.
295    *
296    * These treat the Duration as relative to the clock epoch.
297    * Prefer using the correct TimePoint-based APIs instead.  These APIs will
298    * eventually be deprecated and removed.
299    */
300   void update(Duration now) {
301     update(TimePoint(now));
302   }
303   void addValue(Duration now, const ValueType& value) {
304     addValue(TimePoint(now), value);
305   }
306   void addValue(Duration now, const ValueType& value, uint64_t times) {
307     addValue(TimePoint(now), value, times);
308   }
309   void addValues(Duration now, const folly::Histogram<ValueType>& values) {
310     addValues(TimePoint(now), values);
311   }
312
313  private:
314   typedef ContainerType Bucket;
315   struct CountFromLevel {
316     explicit CountFromLevel(size_t level) : level_(level) {}
317
318     uint64_t operator()(const ContainerType& bucket) const {
319       return bucket.count(level_);
320     }
321
322    private:
323     size_t level_;
324   };
325   struct CountFromInterval {
326     explicit CountFromInterval(TimePoint start, TimePoint end)
327         : start_(start), end_(end) {}
328
329     uint64_t operator()(const ContainerType& bucket) const {
330       return bucket.count(start_, end_);
331     }
332
333    private:
334     TimePoint start_;
335     TimePoint end_;
336   };
337
338   struct AvgFromLevel {
339     explicit AvgFromLevel(size_t level) : level_(level) {}
340
341     ValueType operator()(const ContainerType& bucket) const {
342       return bucket.template avg<ValueType>(level_);
343     }
344
345    private:
346     size_t level_;
347   };
348
349   template <typename ReturnType>
350   struct AvgFromInterval {
351     explicit AvgFromInterval(TimePoint start, TimePoint end)
352         : start_(start), end_(end) {}
353
354     ReturnType operator()(const ContainerType& bucket) const {
355       return bucket.template avg<ReturnType>(start_, end_);
356     }
357
358    private:
359     TimePoint start_;
360     TimePoint end_;
361   };
362
363   /*
364    * Special logic for the case of only one unique value registered
365    * (this can happen when clients don't pick good bucket ranges or have
366    * other bugs).  It's a lot easier for clients to track down these issues
367    * if they are getting the correct value.
368    */
369   void maybeHandleSingleUniqueValue(const ValueType& value);
370
371   void computeAvgData(ValueType* total, uint64_t* nsamples, size_t level) const;
372   void computeAvgData(
373       ValueType* total,
374       uint64_t* nsamples,
375       TimePoint start,
376       TimePoint end) const;
377   void computeRateData(ValueType* total, Duration* elapsed, size_t level) const;
378   void computeRateData(
379       ValueType* total,
380       Duration* elapsed,
381       TimePoint start,
382       TimePoint end) const;
383
384   folly::detail::HistogramBuckets<ValueType, ContainerType> buckets_;
385   bool haveNotSeenValue_;
386   bool singleUniqueValue_;
387   ValueType firstValue_;
388 };
389 }  // folly