Skip to content

Commit bdc336c

Browse files
committed
Upgrade python3-prometheus-client to v0.15.0.
1 parent 61a8d27 commit bdc336c

11 files changed

Lines changed: 227 additions & 45 deletions

File tree

CODE_OF_CONDUCT.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
## Prometheus Community Code of Conduct
1+
# Prometheus Community Code of Conduct
22

3-
Prometheus follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).
3+
Prometheus follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md).

README.md

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ other information about the process for free!
4747
## Installation
4848

4949
```
50-
pip install prometheus_client
50+
pip install prometheus-client
5151
```
5252

5353
This package can be found on
@@ -278,6 +278,18 @@ metadata about the JVM in use is also included. This information is available as
278278
labels on the `python_info` metric. The value of the metric is 1, since it is the
279279
labels that carry information.
280280

281+
### Disabling Default Collector metrics
282+
283+
By default the collected `process`, `gc`, and `platform` collector metrics are exported.
284+
If this information is not helpful, it can be disabled using the following:
285+
```python
286+
import prometheus_client
287+
288+
prometheus_client.REGISTRY.unregister(prometheus_client.GC_COLLECTOR)
289+
prometheus_client.REGISTRY.unregister(prometheus_client.PLATFORM_COLLECTOR)
290+
prometheus_client.REGISTRY.unregister(prometheus_client.PROCESS_COLLECTOR)
291+
```
292+
281293
## Exporting
282294

283295
There are several options for exporting metrics.
@@ -471,6 +483,24 @@ g.set_to_current_time()
471483
push_to_gateway('localhost:9091', job='batchA', registry=registry, handler=my_auth_handler)
472484
```
473485

486+
TLS Auth is also supported when using the push gateway with a special handler.
487+
488+
```python
489+
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
490+
from prometheus_client.exposition import tls_handler
491+
492+
493+
def my_auth_handler(url, method, timeout, headers, data):
494+
certfile = 'client-crt.pem'
495+
keyfile = 'client-key.pem'
496+
return tls_auth_handler(url, method, timeout, headers, data, certfile, keyfile)
497+
498+
registry = CollectorRegistry()
499+
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
500+
g.set_to_current_time()
501+
push_to_gateway('localhost:9091', job='batchA', registry=registry, handler=my_auth_handler)
502+
```
503+
474504
## Bridges
475505

476506
It is also possible to expose metrics to systems other than Prometheus.
@@ -609,14 +639,17 @@ def child_exit(server, worker):
609639

610640
**4. Metrics tuning (Gauge)**:
611641

612-
When `Gauge` metrics are used, additional tuning needs to be performed.
642+
When `Gauge`s are used in multiprocess applications,
643+
you must decide how to handle the metrics reported by each process.
613644
Gauges have several modes they can run in, which can be selected with the `multiprocess_mode` parameter.
614645

615-
- 'all': Default. Return a timeseries per process alive or dead.
616-
- 'liveall': Return a timeseries per process that is still alive.
617-
- 'livesum': Return a single timeseries that is the sum of the values of alive processes.
618-
- 'max': Return a single timeseries that is the maximum of the values of all processes, alive or dead.
619-
- 'min': Return a single timeseries that is the minimum of the values of all processes, alive or dead.
646+
- 'all': Default. Return a timeseries per process (alive or dead), labelled by the process's `pid` (the label is added internally).
647+
- 'min': Return a single timeseries that is the minimum of the values of all processes (alive or dead).
648+
- 'max': Return a single timeseries that is the maximum of the values of all processes (alive or dead).
649+
- 'sum': Return a single timeseries that is the sum of the values of all processes (alive or dead).
650+
651+
Prepend 'live' to the beginning of the mode to return the same result but only considering living processes
652+
(e.g., 'liveall, 'livesum', 'livemax', 'livemin').
620653

621654
```python
622655
from prometheus_client import Gauge

SECURITY.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@
33
The Prometheus security policy, including how to report vulnerabilities, can be
44
found here:
55

6-
https://prometheus.io/docs/operating/security/
6+
<https://prometheus.io/docs/operating/security/>

prometheus_client/exposition.py

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@
55
import os
66
import socket
77
from socketserver import ThreadingMixIn
8+
import ssl
89
import sys
910
import threading
10-
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
11+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
1112
from urllib.error import HTTPError
1213
from urllib.parse import parse_qs, quote_plus, urlparse
1314
from urllib.request import (
14-
build_opener, HTTPHandler, HTTPRedirectHandler, Request,
15+
BaseHandler, build_opener, HTTPHandler, HTTPRedirectHandler, HTTPSHandler,
16+
Request,
1517
)
16-
import warnings
1718
from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer
1819

1920
from .openmetrics import exposition as openmetrics
@@ -247,15 +248,6 @@ def choose_encoder(accept_header: str) -> Tuple[Callable[[CollectorRegistry], by
247248
return generate_latest, CONTENT_TYPE_LATEST
248249

249250

250-
def choose_formatter(accept_header: str) -> Tuple[Callable[[CollectorRegistry], bytes], str]:
251-
warnings.warn(
252-
"choose_formatter is deprecated and will be removed in 0.15.0, please use choose_encoder instead",
253-
DeprecationWarning,
254-
stacklevel=2
255-
)
256-
return choose_encoder(accept_header)
257-
258-
259251
def gzip_accepted(accept_encoding_header: str) -> bool:
260252
accept_encoding_header = accept_encoding_header or ''
261253
for accepted in accept_encoding_header.split(','):
@@ -324,7 +316,7 @@ def _make_handler(
324316
timeout: Optional[float],
325317
headers: Sequence[Tuple[str, str]],
326318
data: bytes,
327-
base_handler: type,
319+
base_handler: Union[BaseHandler, type],
328320
) -> Callable[[], None]:
329321
def handle() -> None:
330322
request = Request(url, data=data)
@@ -399,6 +391,40 @@ def handle():
399391
return handle
400392

401393

394+
def tls_auth_handler(
395+
url: str,
396+
method: str,
397+
timeout: Optional[float],
398+
headers: List[Tuple[str, str]],
399+
data: bytes,
400+
certfile: str,
401+
keyfile: str,
402+
cafile: Optional[str] = None,
403+
protocol: int = ssl.PROTOCOL_TLS_CLIENT,
404+
insecure_skip_verify: bool = False,
405+
) -> Callable[[], None]:
406+
"""Handler that implements an HTTPS connection with TLS Auth.
407+
408+
The default protocol (ssl.PROTOCOL_TLS_CLIENT) will also enable
409+
ssl.CERT_REQUIRED and SSLContext.check_hostname by default. This can be
410+
disabled by setting insecure_skip_verify to True.
411+
412+
Both this handler and the TLS feature on pushgateay are experimental."""
413+
context = ssl.SSLContext(protocol=protocol)
414+
if cafile is not None:
415+
context.load_verify_locations(cafile)
416+
else:
417+
context.load_default_certs()
418+
419+
if insecure_skip_verify:
420+
context.check_hostname = False
421+
context.verify_mode = ssl.CERT_NONE
422+
423+
context.load_cert_chain(certfile=certfile, keyfile=keyfile)
424+
handler = HTTPSHandler(context=context)
425+
return _make_handler(url, method, timeout, headers, data, handler)
426+
427+
402428
def push_to_gateway(
403429
gateway: str,
404430
job: str,

prometheus_client/metrics.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ def f():
346346
d.set_function(lambda: len(my_dict))
347347
"""
348348
_type = 'gauge'
349-
_MULTIPROC_MODES = frozenset(('min', 'max', 'livesum', 'liveall', 'all'))
349+
_MULTIPROC_MODES = frozenset(('all', 'liveall', 'min', 'livemin', 'max', 'livemax', 'sum', 'livesum'))
350350

351351
def __init__(self,
352352
name: str,

prometheus_client/multiprocess.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import warnings
66

7+
from .metrics import Gauge
78
from .metrics_core import Metric
89
from .mmap_dict import MmapedDict
910
from .samples import Sample
@@ -63,8 +64,8 @@ def _parse_key(key):
6364
try:
6465
file_values = MmapedDict.read_all_values_from_file(f)
6566
except FileNotFoundError:
66-
if typ == 'gauge' and parts[1] in ('liveall', 'livesum'):
67-
# Those files can disappear between the glob of collect
67+
if typ == 'gauge' and parts[1].startswith('live'):
68+
# Files for 'live*' gauges can be deleted between the glob of collect
6869
# and now (via a mark_process_dead call) so don't fail if
6970
# the file is missing
7071
continue
@@ -96,15 +97,15 @@ def _accumulate_metrics(metrics, accumulate):
9697
name, labels, value, timestamp, exemplar = s
9798
if metric.type == 'gauge':
9899
without_pid_key = (name, tuple(l for l in labels if l[0] != 'pid'))
99-
if metric._multiprocess_mode == 'min':
100+
if metric._multiprocess_mode in ('min', 'livemin'):
100101
current = samples_setdefault(without_pid_key, value)
101102
if value < current:
102103
samples[without_pid_key] = value
103-
elif metric._multiprocess_mode == 'max':
104+
elif metric._multiprocess_mode in ('max', 'livemax'):
104105
current = samples_setdefault(without_pid_key, value)
105106
if value > current:
106107
samples[without_pid_key] = value
107-
elif metric._multiprocess_mode == 'livesum':
108+
elif metric._multiprocess_mode in ('sum', 'livesum'):
108109
samples[without_pid_key] += value
109110
else: # all/liveall
110111
samples[(name, labels)] = value
@@ -152,11 +153,13 @@ def collect(self):
152153
return self.merge(files, accumulate=True)
153154

154155

156+
_LIVE_GAUGE_MULTIPROCESS_MODES = {m for m in Gauge._MULTIPROC_MODES if m.startswith('live')}
157+
158+
155159
def mark_process_dead(pid, path=None):
156160
"""Do bookkeeping for when one process dies in a multi-process setup."""
157161
if path is None:
158162
path = os.environ.get('PROMETHEUS_MULTIPROC_DIR', os.environ.get('prometheus_multiproc_dir'))
159-
for f in glob.glob(os.path.join(path, f'gauge_livesum_{pid}.db')):
160-
os.remove(f)
161-
for f in glob.glob(os.path.join(path, f'gauge_liveall_{pid}.db')):
162-
os.remove(f)
163+
for mode in _LIVE_GAUGE_MULTIPROCESS_MODES:
164+
for f in glob.glob(os.path.join(path, f'gauge_{mode}_{pid}.db')):
165+
os.remove(f)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
setup(
1010
name="prometheus_client",
11-
version="0.14.1",
11+
version="0.15.0",
1212
author="Brian Brazil",
1313
author_email="brian.brazil@robustperception.io",
1414
description="Python client for the Prometheus monitoring system.",

tests/certs/cert.pem

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIFkzCCA3ugAwIBAgIUWhYKmrh+gF5pZ7Yqj41cWJ2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tdWEfrhPjy2L36o2bEEpPL70qfMCAwEAAaNT
19+
MFEwHQYDVR0OBBYEFJOiGRDrPKW5+qvVZzs+Yu8qPNJnMB8GA1UdIwQYMBaAFJOi
20+
GRDrPKW5+qvVZzs+Yu8qPNJnMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL
21+
BQADggIBALbV73MLFz24tQpC8Ax6vh9okeuc5n2eVOk/ofe2A9DL16IeMyJo8QAG
22+
dK2j+mfZBvPfYYX/Uz596bOLauRKAsXm3ERmPW74nemLE4CiMhod2snIUMbSHrem
23+
6iFLIqGGosncoqHIPJej4sG+XLKsqw8zLzflUSsvNveaHEwt2PSZys37bExADbB5
24+
uj4JU+vEBhagZ6ieZ3hENn3Uj5c46kimXrEStD3chT2PWoLAS4Am6VJyXUtqXQZj
25+
1ef+S+6caCbldaJNfNEVU1jQliJpo0u+EfiF/DqU799xnnoW4D132AxiG0L1jPFr
26+
7GbIme6H2ZbNCZngf6eCbdsoHAGkQZpD3wYFHLmTFDCNmjMJteb3YFMNHyU5eh8C
27+
2bTp4D+pifgFRo3Mc23kuRXiIzyrhg/eOHl+Qi2V8BpXP/7bI27FZXglp9rzhP57
28+
YMfBeoOejRgRHJTeMPhBbEevQyqpb9ecZxpuGV77Pi3S5IA26fe3pZQCHRceufZr
29+
YKWLOCt2jZJ0y9KM4wdVg40yr6BVZqy2OPqDn64q0pAgMHG24XrxxuaFISjgPOgx
30+
bYhhTUG/4Dkb1BWhfEv4EwEf/uDxhHE8k6LoKk3Qb+aOzPr2PKGvW3yBHEFNSmKH
31+
x3SB8xxj/IOiA+em+TLtKd66gG0T0b8cPt037k+D3a0BqC9d2sVs
32+
-----END CERTIFICATE-----

tests/certs/key.pem

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQDGzq/1z9s20DRO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PChpin5J3kNDQ2z/oC3UhyHZBHwWCGj8AOTy+M1HIcVNPzCga
51+
YdxZTB2pN96tqnBm8vyvi81Cdy/x
52+
-----END PRIVATE KEY-----

tests/test_exposition.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
from http.server import BaseHTTPRequestHandler, HTTPServer
2+
import os
23
import threading
34
import time
45
import unittest
5-
import warnings
66

77
import pytest
88

@@ -13,8 +13,8 @@
1313
)
1414
from prometheus_client.core import GaugeHistogramMetricFamily, Timestamp
1515
from prometheus_client.exposition import (
16-
basic_auth_handler, choose_encoder, choose_formatter, default_handler,
17-
MetricsHandler, passthrough_redirect_handler,
16+
basic_auth_handler, choose_encoder, default_handler, MetricsHandler,
17+
passthrough_redirect_handler, tls_auth_handler,
1818
)
1919
import prometheus_client.openmetrics.exposition as openmetrics
2020

@@ -343,6 +343,17 @@ def my_auth_handler(url, method, timeout, headers, data):
343343
self.assertEqual(self.requests[0][0].headers.get('content-type'), CONTENT_TYPE_LATEST)
344344
self.assertEqual(self.requests[0][1], b'# HELP g help\n# TYPE g gauge\ng 0.0\n')
345345

346+
def test_push_with_tls_auth_handler(self):
347+
def my_auth_handler(url, method, timeout, headers, data):
348+
certs_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'certs')
349+
return tls_auth_handler(url, method, timeout, headers, data, os.path.join(certs_dir, "cert.pem"), os.path.join(certs_dir, "key.pem"))
350+
351+
push_to_gateway(self.address, "my_job_with_tls_auth", self.registry, handler=my_auth_handler)
352+
self.assertEqual(self.requests[0][0].command, 'PUT')
353+
self.assertEqual(self.requests[0][0].path, '/metrics/job/my_job_with_tls_auth')
354+
self.assertEqual(self.requests[0][0].headers.get('content-type'), CONTENT_TYPE_LATEST)
355+
self.assertEqual(self.requests[0][1], b'# HELP g help\n# TYPE g gauge\ng 0.0\n')
356+
346357
def test_push_with_redirect_handler(self):
347358
def my_redirect_handler(url, method, timeout, headers, data):
348359
return passthrough_redirect_handler(url, method, timeout, headers, data)
@@ -468,13 +479,5 @@ def test_choose_encoder():
468479
assert choose_encoder(openmetrics.CONTENT_TYPE_LATEST) == (openmetrics.generate_latest, openmetrics.CONTENT_TYPE_LATEST)
469480

470481

471-
def test_choose_formatter():
472-
with warnings.catch_warnings(record=True) as w:
473-
assert choose_formatter('') == (generate_latest, CONTENT_TYPE_LATEST)
474-
assert len(w) == 1
475-
assert issubclass(w[-1].category, DeprecationWarning)
476-
assert "choose_formatter is deprecated" in str(w[-1].message)
477-
478-
479482
if __name__ == '__main__':
480483
unittest.main()

0 commit comments

Comments
 (0)