Skip to content

Commit eb6c724

Browse files
authored
Merge pull request #15 from faucetsdn/v0.20.0
Upgrade python3-prometheus-client to v0.20.0.
2 parents 9f79306 + cf24669 commit eb6c724

File tree

9 files changed

+68
-5
lines changed

9 files changed

+68
-5
lines changed

docs/content/exporting/http/_index.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,15 @@ start_http_server(8000)
1818

1919
Visit [http://localhost:8000/](http://localhost:8000/) to view the metrics.
2020

21+
The function will return the HTTP server and thread objects, which can be used
22+
to shutdown the server gracefully:
23+
24+
```python
25+
server, t = start_http_server(8000)
26+
server.shutdown()
27+
t.join()
28+
```
29+
2130
To add Prometheus exposition to an existing HTTP server, see the `MetricsHandler` class
2231
which provides a `BaseHTTPRequestHandler`. It also serves as a simple example of how
2332
to write a custom endpoint.

docs/content/instrumenting/_index.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,8 @@ on how to use them.
1313
By default counters, histograms, and summaries export an additional series
1414
suffixed with `_created` and a value of the unix timestamp for when the metric
1515
was created. If this information is not helpful, it can be disabled by setting
16-
the environment variable `PROMETHEUS_DISABLE_CREATED_SERIES=True`.
16+
the environment variable `PROMETHEUS_DISABLE_CREATED_SERIES=True` or in code:
17+
```python
18+
from prometheus_client import disable_created_metrics
19+
disable_created_metrics()
20+
```

docs/content/multiprocess/_index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ This comes with a number of limitations:
1818
- The pushgateway cannot be used
1919
- Gauges cannot use the `pid` label
2020
- Exemplars are not supported
21+
- Remove and Clear of labels are currently not supported in multiprocess mode.
2122

2223
There's several steps to getting this working:
2324

prometheus_client/exposition.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def _get_best_family(address, port):
154154
# binding an ipv6 address is requested.
155155
# This function is based on what upstream python did for http.server
156156
# in https://github.com/python/cpython/pull/11767
157-
infos = socket.getaddrinfo(address, port)
157+
infos = socket.getaddrinfo(address, port, type=socket.SOCK_STREAM, flags=socket.AI_PASSIVE)
158158
family, _, _, _, sockaddr = next(iter(infos))
159159
return family, sockaddr[0]
160160

@@ -210,7 +210,7 @@ def start_wsgi_server(
210210
client_capath: Optional[str] = None,
211211
protocol: int = ssl.PROTOCOL_TLS_SERVER,
212212
client_auth_required: bool = False,
213-
) -> None:
213+
) -> Tuple[WSGIServer, threading.Thread]:
214214
"""Starts a WSGI server for prometheus metrics as a daemon thread."""
215215

216216
class TmpServer(ThreadingWSGIServer):
@@ -226,6 +226,8 @@ class TmpServer(ThreadingWSGIServer):
226226
t.daemon = True
227227
t.start()
228228

229+
return httpd, t
230+
229231

230232
start_http_server = start_wsgi_server
231233

prometheus_client/metrics.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
Any, Callable, Dict, Iterable, List, Literal, Optional, Sequence, Tuple,
77
Type, TypeVar, Union,
88
)
9+
import warnings
910

1011
from . import values # retain this import style for testability
1112
from .context_managers import ExceptionCounter, InprogressTracker, Timer
@@ -210,6 +211,11 @@ def labels(self: T, *labelvalues: Any, **labelkwargs: Any) -> T:
210211
return self._metrics[labelvalues]
211212

212213
def remove(self, *labelvalues: Any) -> None:
214+
if 'prometheus_multiproc_dir' in os.environ or 'PROMETHEUS_MULTIPROC_DIR' in os.environ:
215+
warnings.warn(
216+
"Removal of labels has not been implemented in multi-process mode yet.",
217+
UserWarning)
218+
213219
if not self._labelnames:
214220
raise ValueError('No label names were set when constructing %s' % self)
215221

@@ -222,6 +228,10 @@ def remove(self, *labelvalues: Any) -> None:
222228

223229
def clear(self) -> None:
224230
"""Remove all labelsets from the metric"""
231+
if 'prometheus_multiproc_dir' in os.environ or 'PROMETHEUS_MULTIPROC_DIR' in os.environ:
232+
warnings.warn(
233+
"Clearing labels has not been implemented in multi-process mode yet",
234+
UserWarning)
225235
with self._lock:
226236
self._metrics = {}
227237

@@ -282,6 +292,12 @@ def f():
282292
# Count only one type of exception
283293
with c.count_exceptions(ValueError):
284294
pass
295+
296+
You can also reset the counter to zero in case your logical "process" restarts
297+
without restarting the actual python process.
298+
299+
c.reset()
300+
285301
"""
286302
_type = 'counter'
287303

@@ -300,6 +316,11 @@ def inc(self, amount: float = 1, exemplar: Optional[Dict[str, str]] = None) -> N
300316
_validate_exemplar(exemplar)
301317
self._value.set_exemplar(Exemplar(exemplar, amount, time.time()))
302318

319+
def reset(self) -> None:
320+
"""Reset the counter to zero. Use this when a logical process restarts without restarting the actual python process."""
321+
self._value.set(0)
322+
self._created = time.time()
323+
303324
def count_exceptions(self, exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = Exception) -> ExceptionCounter:
304325
"""Count exceptions in a block of code or function.
305326

prometheus_client/openmetrics/exposition.py

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

44
from ..utils import floatToGoString
55

6-
CONTENT_TYPE_LATEST = 'application/openmetrics-text; version=0.0.1; charset=utf-8'
6+
CONTENT_TYPE_LATEST = 'application/openmetrics-text; version=1.0.0; charset=utf-8'
77
"""Content type of the latest OpenMetrics text format"""
88

99

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.19.0",
11+
version="0.20.0",
1212
author="Brian Brazil",
1313
author_email="brian.brazil@robustperception.io",
1414
description="Python client for the Prometheus monitoring system.",

tests/test_core.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ def test_increment(self):
4343
self.counter.inc(7)
4444
self.assertEqual(8, self.registry.get_sample_value('c_total'))
4545

46+
def test_reset(self):
47+
self.counter.inc()
48+
self.assertNotEqual(0, self.registry.get_sample_value('c_total'))
49+
created = self.registry.get_sample_value('c_created')
50+
time.sleep(0.05)
51+
self.counter.reset()
52+
self.assertEqual(0, self.registry.get_sample_value('c_total'))
53+
created_after_reset = self.registry.get_sample_value('c_created')
54+
self.assertLess(created, created_after_reset)
55+
4656
def test_repr(self):
4757
self.assertEqual(repr(self.counter), "prometheus_client.metrics.Counter(c)")
4858

tests/test_multiprocess.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,22 @@ def test_missing_gauge_file_during_merge(self):
381381
os.path.join(self.tempdir, 'gauge_livesum_9999999.db'),
382382
]))
383383

384+
def test_remove_clear_warning(self):
385+
os.environ['PROMETHEUS_MULTIPROC_DIR'] = self.tempdir
386+
with warnings.catch_warnings(record=True) as w:
387+
values.ValueClass = get_value_class()
388+
registry = CollectorRegistry()
389+
collector = MultiProcessCollector(registry)
390+
counter = Counter('c', 'help', labelnames=['label'], registry=None)
391+
counter.labels('label').inc()
392+
counter.remove('label')
393+
counter.clear()
394+
assert os.environ['PROMETHEUS_MULTIPROC_DIR'] == self.tempdir
395+
assert issubclass(w[0].category, UserWarning)
396+
assert "Removal of labels has not been implemented" in str(w[0].message)
397+
assert issubclass(w[-1].category, UserWarning)
398+
assert "Clearing labels has not been implemented" in str(w[-1].message)
399+
384400

385401
class TestMmapedDict(unittest.TestCase):
386402
def setUp(self):

0 commit comments

Comments
 (0)