forked from bentoml/BentoML
/
prometheus.py
479 lines (346 loc) · 17.8 KB
/
prometheus.py
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
from __future__ import annotations
import os
import sys
import typing as t
import logging
from typing import TYPE_CHECKING
from functools import partial
if TYPE_CHECKING:
from prometheus_client.metrics_core import Metric
from ... import external_typing as ext
logger = logging.getLogger(__name__)
class PrometheusClient:
def __init__(
self,
*,
multiproc: bool = True,
multiproc_dir: str | None = None,
):
"""
PrometheusClient is BentoML's own prometheus client that extends the official Python client.
It sets up a multiprocess dir for Prometheus to work in multiprocess mode, which is required
for BentoML to work in production.
.. note::
For Prometheus to behave properly, ``prometheus_client`` must be imported after this client
is called. This has to do with ``prometheus_client`` relies on ``PROMEHEUS_MULTIPROC_DIR``, which
will be set by this client.
"""
if multiproc:
assert multiproc_dir is not None, "multiproc_dir must be provided"
self.multiproc = multiproc
self.multiproc_dir: str | None = multiproc_dir
self._registry = None
self._imported = False
self._pid: int | None = None
@property
def prometheus_client(self):
if self.multiproc and not self._imported:
# step 1: check environment
assert (
"prometheus_client" not in sys.modules
), "prometheus_client is already imported, multiprocessing will not work properly"
assert (
self.multiproc_dir
), f"Invalid prometheus multiproc directory: {self.multiproc_dir}"
assert os.path.isdir(self.multiproc_dir)
os.environ["PROMETHEUS_MULTIPROC_DIR"] = self.multiproc_dir
# step 2:
import prometheus_client
import prometheus_client.parser
import prometheus_client.metrics
import prometheus_client.exposition
import prometheus_client.metrics_core
import prometheus_client.multiprocess
self._imported = True
return prometheus_client
@property
def registry(self):
if self._registry is None:
if self.multiproc:
self._pid = os.getpid()
self._registry = self.prometheus_client.REGISTRY
else:
if self.multiproc:
assert self._pid is not None
assert (
os.getpid() == self._pid
), "The current process's different than the process which the prometheus client gets created"
return self._registry
def __del__(self):
self.mark_process_dead()
def mark_process_dead(self) -> None:
if self.multiproc:
assert self._pid is not None
assert (
os.getpid() == self._pid
), "The current process's different than the process which the prometheus client gets created"
self.prometheus_client.multiprocess.mark_process_dead(self._pid)
def start_http_server(self, port: int, addr: str = "") -> None:
"""
Starts a WSGI server for prometheus metrics as a daemon thread.
Args:
port: Port to listen on.
addr: Address to listen on.
"""
self.prometheus_client.start_http_server(
port=port,
addr=addr,
registry=self.registry,
)
def make_wsgi_app(self) -> ext.WSGIApp:
"""
Create a WSGI app which serves the metrics from a registry.
Returns:
WSGIApp: A WSGI app which serves the metrics from a registry.
"""
return self.prometheus_client.make_wsgi_app(registry=self.registry) # type: ignore (unfinished prometheus types)
def generate_latest(self):
"""
Returns metrics from the registry in latest text format as a string.
This function ensures that multiprocess is setup correctly.
Returns:
str: Metrics in latest text format. Refer to `Exposition format <https://prometheus.io/docs/instrumenting/exposition_formats/#exposition-formats>`_ for details.
"""
if self.multiproc:
registry = self.prometheus_client.CollectorRegistry()
self.prometheus_client.multiprocess.MultiProcessCollector(registry)
return self.prometheus_client.generate_latest(registry)
else:
return self.prometheus_client.generate_latest()
def text_string_to_metric_families(self) -> t.Generator[Metric, None, None]:
"""
Parse Prometheus text format from a unicode string.
Returns:
Generator[Metric, None, None]: A generator of `Metric <https://prometheus.io/docs/concepts/metric_types/>`_ objects.
"""
yield from self.prometheus_client.parser.text_string_to_metric_families(
self.generate_latest().decode("utf-8")
)
@property
def CONTENT_TYPE_LATEST(self) -> str:
"""
Returns:
str: Content type of the latest text format
"""
return self.prometheus_client.CONTENT_TYPE_LATEST
# For all of the documentation for instruments metrics below, we will extend
# upon prometheus_client's documentation, since their code segment aren't rst friendly, and
# not that easy to read.
@property
def Histogram(self):
o = partial(self.prometheus_client.Histogram, registry=self.registry)
o.__doc__ = """
A Histogram tracks the size and number of events in a given bucket.
Histograms are often used to aggregatable calculation of quantiles.
Some notable examples include measuring response latency, request size.
A quick example of a Histogram:
.. code-block:: python
from bentoml.metrics import Histogram
h = Histogram('request_size_bytes', 'Request size (bytes)')
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
h.observe(512) # Observe 512 (bytes)
...
``observe()`` will observe for given amount of time.
Usually, this value are positive or zero. Negative values are accepted but will
prevent current versions of Prometheus from properly detecting counter resets in the `sum of observations <https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations>`_.
Histograms also provide ``time()``, which times a block of code or function, and observe for a given duration amount.
This function can also be used as a context manager.
.. tab-set::
.. tab-item:: Example
.. code-block:: python
from bentoml.metrics import Histogram
REQUEST_TIME = Histogram('response_latency_seconds', 'Response latency (seconds)')
@REQUEST_TIME.time()
def create_response(request):
body = await request.json()
return Response(body)
.. tab-item:: Context Manager
.. code-block:: python
from bentoml.metrics import Histogram
REQUEST_TIME = Histogram('response_latency_seconds', 'Response latency (seconds)')
def create_response(request):
body = await request.json()
with REQUEST_TIME.time():
...
The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds.
See :ref:`configuration guides <guides/configuration:Configuration>` to see how to customize the buckets.
Args:
name (str): The name of the metric.
documentation (str): A documentation string.
labelnames (tuple[str]): A tuple of strings specifying the label names for the metric. Defaults to ``()``.
namespace (str): The namespace of the metric. Defaults to an empty string.
subsystem (str): The subsystem of the metric. Defaults to an empty string.
unit (str): The unit of the metric. Defaults to an empty string.
buckets (list[float]): A list of float representing a bucket. Defaults to ``(.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0, INF)``.
"""
return o
@property
def Counter(self):
o = partial(self.prometheus_client.Counter, registry=self.registry)
o.__doc__ = """
A Counter tracks counts of events or running totals.
.. epigraph::
It is a cumulative metric that represents a single `monotonically increasing counter <https://prometheus.io/docs/concepts/metric_types/#counter>`_ whose value can only increase or be reset to zero on restart.
Some notable examples include counting the number of requests served, tasks completed, or errors.
If you need to go down, uses :func:`bentoml.metrics.Gauge` instead.
A quick example of a Counter:
.. code-block:: python
from bentoml.metrics import Counter
c = Counter('failures', 'Total number of failures requests')
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
if input_data['fail']:
c.inc() # increment by 1 by default
``inc()`` can optionally pass in a ``exemplar``, which is a dictionary of keys and values, defined :github:`here <OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#exemplars>`.
``inc()`` can also increment by any given amount:
.. code-block:: python
c.inc(2.1)
``count_exceptions()`` can be used as both a decorator and context manager to count exceptions raised.
.. tab-set::
.. tab-item:: Decorator
.. code-block:: python
from bentoml.metrics import Counter
c = Counter('failures', 'Total number of failures requests')
@c.count_exceptions()
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
if input_data['acc'] < 0.5:
raise ValueError("Given data is not accurate.")
.. tab-item:: Context Manager
.. code-block:: python
from bentoml.metrics import Histogram
c = Counter('failures', 'Total number of failures requests')
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
with c.count_exceptions():
if input_data['acc'] < 0.5:
raise ValueError("Given data is not accurate.")
with c.count_exceptions(RuntimeError):
if input_data['output'] is None:
raise RuntimeError("Given pre-processing logic is invalid")
``count_exceptions()`` will optionally take in an exception to only track specific exceptions.
.. code-block:: python
...
with c.count_exceptions(RuntimeError):
if input_data['output'] is None:
raise RuntimeError("Given pre-processing logic is invalid")
Args:
name (str): The name of the metric.
documentation (str): A documentation string.
labelnames (tuple[str]): A tuple of strings specifying the label names for the metric. Defaults to ``()``.
namespace (str): The namespace of the metric. Defaults to an empty string.
subsystem (str): The subsystem of the metric. Defaults to an empty string.
unit (str): The unit of the metric. Defaults to an empty string.
"""
return o
@property
def Summary(self):
o = partial(self.prometheus_client.Summary, registry=self.registry)
o.__doc__ = """
A Summary tracks the size and `samples observations (usually things like request durations and response sizes).`.
While it also provides a total count of observations and a sum of all observed values,
it calculates configurable quantiles over a sliding time window.
Notable examples include request latency and response size.
A quick example of a Summary:
.. code-block:: python
from bentoml.metrics import Summary
s = Summary('request_size_bytes', 'Request size (bytes)')
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
s.observe(512) # Observe 512 (bytes)
...
``observe()`` will observe for given amount of time.
Usually, this value are positive or zero. Negative values are accepted but will
prevent current versions of Prometheus from properly detecting counter resets in the `sum of observations <https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations>`_.
Similar to :meth:`bentoml.metrics.Histogram`, ``time()`` can also be used as a decorator or context manager.
.. tab-set::
.. tab-item:: Example
.. code-block:: python
from bentoml.metrics import Histogram
s = Summary('response_latency_seconds', 'Response latency (seconds)')
@s.time()
def create_response(request):
body = await request.json()
return Response(body)
.. tab-item:: Context Manager
.. code-block:: python
from bentoml.metrics import Histogram
s = Summary('response_latency_seconds', 'Response latency (seconds)')
def create_response(request):
body = await request.json()
with s.time():
...
Args:
name (str): The name of the metric.
documentation (str): A documentation string.
labelnames (tuple[str]): A tuple of strings specifying the label names for the metric. Defaults to ``()``.
namespace (str): The namespace of the metric. Defaults to an empty string.
subsystem (str): The subsystem of the metric. Defaults to an empty string.
unit (str): The unit of the metric. Defaults to an empty string.
"""
return o
@property
def Gauge(self):
o = partial(self.prometheus_client.Gauge, registry=self.registry)
o.__doc__ = """
A Gauge represents a single numerical value that can arbitrarily go up and down.
Gauges are typically used to for report instantaneous values like temperatures or current memory usage.
One can think of Gauge as a :meth:`bentoml.metrics.Counter` that can go up and down.
Notable examples include in-progress requests, number of item in a queue, and free memory.
A quick example of a Gauge:
.. code-block:: python
from bentoml.metrics import Gauge
g = Gauge('inprogress_request', 'Request inprogress')
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
g.inc() # increment by 1 by default
g.dec(10) # decrement by any given value
g.set(0) # set to a given value
...
.. note::
By default, ``inc()`` and ``dec()`` will increment and decrement by 1 respectively.
Gauge also provide ``track_inprogress()``, to track inprogress object.
This function can also be used as either a context manager or a decorator.
.. tab-set::
.. tab-item:: Example
.. code-block:: python
from bentoml.metrics import Gauge
g = Gauge('inprogress_request', 'Request inprogress')
@svc.api(input=JSON(), output=JSON())
@g.track_inprogress()
def predict(input_data: dict[str, str]):
...
.. tab-item:: Context Manager
.. code-block:: python
from bentoml.metrics import Gauge
g = Gauge('inprogress_request', 'Request inprogress')
@svc.api(input=JSON(), output=JSON())
def predict(input_data: dict[str, str]):
with g.track_inprogress():
...
The gauge will increment when the context is entered and decrement when the context is exited.
Args:
name (str): The name of the metric.
documentation (str): A documentation string.
labelnames (tuple[str]): A tuple of strings specifying the label names for the metric. Defaults to ``()``.
namespace (str): The namespace of the metric. Defaults to an empty string.
subsystem (str): The subsystem of the metric. Defaults to an empty string.
unit (str): The unit of the metric. Defaults to an empty string.
multiprocess_mode (str): The multiprocess mode of the metric. Defaults to ``all``. Available options
are (``all``, ``min``, ``max``, ``livesum``, ``liveall``)
"""
return o
@property
def Info(self):
raise RuntimeError("Info is not supported in Prometheus multiprocess mode.")
@property
def Enum(self):
raise RuntimeError("Enum is not supported in Prometheus multiprocess mode.")
@property
def Metric(self):
"""
A Metric family and its samples.
This is a base class to be used by instrumentation client. Custom collectors should use ``bentoml.metrics.metrics_core.GaugeMetricFamily``, ``bentoml.metrics.metrics_core.CounterMetricFamily``, ``bentoml.metrics.metrics_core.SummaryMetricFamily`` instead.
"""
return partial(self.prometheus_client.Metric, registry=self.registry)