forked from DataDog/datadogpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetrics.py
More file actions
203 lines (158 loc) · 6.1 KB
/
metrics.py
File metadata and controls
203 lines (158 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# Unless explicitly stated otherwise all files in this repository are licensed under the BSD-3-Clause License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2015-Present Datadog, Inc
"""
Metric roll-up classes.
"""
from collections import defaultdict
import random
import itertools
import threading
from datadog.util.compat import iternext
from datadog.threadstats.constants import MetricType
class Metric(object):
"""
A base metric class that accepts points, slices them into time intervals
and performs roll-ups within those intervals.
"""
def add_point(self, value):
""" Add a point to the given metric. """
raise NotImplementedError()
def flush(self, timestamp, interval):
""" Flush all metrics up to the given timestamp. """
raise NotImplementedError()
class Set(Metric):
""" A set metric. """
stats_tag = "g"
def __init__(self, name, tags, host):
self.name = name
self.tags = tags
self.host = host
self.set = set()
def add_point(self, value):
self.set.add(value)
def flush(self, timestamp, interval):
return [(timestamp, len(self.set), self.name, self.tags, self.host, MetricType.Gauge, interval)]
class Gauge(Metric):
""" A gauge metric. """
stats_tag = "g"
def __init__(self, name, tags, host):
self.name = name
self.tags = tags
self.host = host
self.value = None
def add_point(self, value):
self.value = value
def flush(self, timestamp, interval):
return [(timestamp, self.value, self.name, self.tags, self.host, MetricType.Gauge, interval)]
class Counter(Metric):
""" A metric that tracks a counter value. """
stats_tag = "c"
def __init__(self, name, tags, host):
self.name = name
self.tags = tags
self.host = host
self.count = []
def add_point(self, value):
self.count.append(value)
def flush(self, timestamp, interval):
count = sum(self.count, 0)
return [(timestamp, count / float(interval), self.name, self.tags, self.host, MetricType.Rate, interval)]
class Distribution(Metric):
""" A distribution metric. """
stats_tag = "d"
def __init__(self, name, tags, host):
self.name = name
self.tags = tags
self.host = host
self.value = []
def add_point(self, value):
self.value.append(value)
def flush(self, timestamp, interval):
return [(timestamp, self.value, self.name, self.tags, self.host, MetricType.Distribution, interval)]
class Histogram(Metric):
""" A histogram metric. """
stats_tag = "h"
def __init__(self, name, tags, host):
self.name = name
self.tags = tags
self.host = host
self.max = float("-inf")
self.min = float("inf")
self.sum = []
self.iter_counter = itertools.count()
self.count = iternext(self.iter_counter)
self.sample_size = 1000
self.samples = []
self.percentiles = [0.75, 0.85, 0.95, 0.99]
def add_point(self, value):
self.max = self.max if self.max > value else value
self.min = self.min if self.min < value else value
self.sum.append(value)
if self.count < self.sample_size:
self.samples.append(value)
else:
self.samples[random.randrange(0, self.sample_size)] = value
self.count = iternext(self.iter_counter)
def flush(self, timestamp, interval):
if not self.count:
return []
metrics = [
(timestamp, self.min, "%s.min" % self.name, self.tags, self.host, MetricType.Gauge, interval),
(timestamp, self.max, "%s.max" % self.name, self.tags, self.host, MetricType.Gauge, interval),
(
timestamp,
self.count / float(interval),
"%s.count" % self.name,
self.tags,
self.host,
MetricType.Rate,
interval,
),
(timestamp, self.average(), "%s.avg" % self.name, self.tags, self.host, MetricType.Gauge, interval),
]
length = len(self.samples)
self.samples.sort()
for p in self.percentiles:
val = self.samples[int(round(p * length - 1))]
name = "%s.%spercentile" % (self.name, int(p * 100))
metrics.append((timestamp, val, name, self.tags, self.host, MetricType.Gauge, interval))
return metrics
def average(self):
sum_metrics = sum(self.sum, 0)
return float(sum_metrics) / self.count
class Timing(Histogram):
"""
A timing metric.
Inherit from Histogram to workaround and support it in API mode
"""
stats_tag = "ms"
class MetricsAggregator(object):
"""
A small class to handle the roll-ups of multiple metrics at once.
"""
def __init__(self, roll_up_interval=10):
self._lock = threading.RLock()
self._metrics = defaultdict(lambda: {})
self._roll_up_interval = roll_up_interval
def add_point(self, metric, tags, timestamp, value, metric_class, sample_rate=1, host=None):
# The sample rate is currently ignored for in process stuff
interval = timestamp - timestamp % self._roll_up_interval
key = (metric, host, tuple(sorted(tags)) if tags else None)
with self._lock:
if key not in self._metrics[interval]:
self._metrics[interval][key] = metric_class(metric, tags, host)
self._metrics[interval][key].add_point(value)
def flush(self, timestamp):
""" Flush all metrics up to the given timestamp. """
if timestamp == float("inf"):
interval = float("inf")
else:
interval = timestamp - timestamp % self._roll_up_interval
with self._lock:
past_intervals = [i for i in self._metrics.keys() if i < interval]
metrics = []
for i in past_intervals:
for m in list(self._metrics.pop(i).values()):
metrics += m.flush(i, self._roll_up_interval)
return metrics