8000 Alternative implementation. · prometheus/client_python@529022e · GitHub
[go: up one dir, main page]

Skip to content

Commit 529022e

Browse files
btimbycsmarchbanks
authored andcommitted
Alternative implementation.
Signed-off-by: Ben Timby <btimby@gmail.com>
1 parent f8f9191 commit 529022e

File tree

5 files changed

+19
-16
lines changed

5 files changed

+19
-16
lines changed

prometheus_client/metrics.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
from threading import RLock
23
import time
34
import types
45
from typing import (
@@ -15,7 +16,7 @@
1516
)
1617
from .registry import Collector, CollectorRegistry, REGISTRY
1718
from .samples import Exemplar, Sample
18-
from .utils import floatToGoString, INF, Lock
19+
from .utils import floatToGoString, INF
1920

2021
T = TypeVar('T', bound='MetricWrapperBase')
2122
F = TypeVar("F", bound=Callable[..., Any])
@@ -143,7 +144,7 @@ def __init__(self: T,
143144

144145
if self._is_parent():
145146
# Prepare the fields needed for child metrics.
146-
self._lock = Lock()
147+
self._lock = RLock()
147148
self._metrics: Dict[Sequence[str], T] = {}
148149

149150
if self._is_observable():
@@ -696,7 +697,7 @@ class Info(MetricWrapperBase):
696697

697698
def _metric_init(self):
698699
self._labelname_set = set(self._labelnames)
699-
self._lock = Lock()
700+
self._lock = RLock()
700701
self._value = {}
701702

702703
def info(self, val: Dict[str, str]) -> None:
@@ -758,7 +759,7 @@ def __init__(self,
758759

759760
def _metric_init(self) -> None:
760761
self._value = 0
761-
self._lock = Lock()
762+
self._lock = RLock()
762763

763764
def state(self, state: str) -> None:
764765
"""Set enum metric state."""

prometheus_client/registry.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from abc import ABC, abstractmethod
22
import copy
3+
from threading import RLock
34
from typing import Dict, Iterable, List, Optional
45

56
from .metrics_core import Metric
6-
from .utils import Lock
77

88

99
# Ideally this would be a Protocol, but Protocols are only available in Python >= 3.8.
@@ -30,7 +30,7 @@ def __init__(self, auto_describe: bool = False, target_info: Optional[Dict[str,
3030
self._collector_to_names: Dict[Collector, List[str]] = {}
3131
self._names_to_collectors: Dict[str, Collector] = {}
3232
self._auto_describe = auto_describe
33-
self._lock = Lock()
33+
self._lock = RLock()
3434
self._target_info: Optional[Dict[str, str]] = {}
3535
self.set_target_info(target_info)
3636

prometheus_client/utils.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import math
2-
from threading import _PyRLock # type: ignore[attr-defined]
32

43
INF = float("inf")
54
MINUS_INF = float("-inf")
@@ -23,8 +22,3 @@ def floatToGoString(d):
2322
mantissa = f'{s[0]}.{s[1:dot]}{s[dot + 1:]}'.rstrip('0.')
2423
return f'{mantissa}e+0{dot - 1}'
2524
return s
26-
27-
28-
class Lock(_PyRLock):
29-
def locked(self):
30-
return bool(self._count)

prometheus_client/values.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import os
2+
from threading import RLock
23
import warnings
34

45
from .mmap_dict import mmap_key, MmapedDict
5-
from .utils import Lock
66

77

88
class MutexValue:
@@ -13,7 +13,7 @@ class MutexValue:
1313
def __init__(self, typ, metric_name, name, labelnames, labelvalues, help_text, **kwargs):
1414
self._value = 0.0
1515
self._exemplar = None
16-
self._lock = Lock()
16+
self._lock = RLock()
1717

1818
def inc(self, amount):
1919
with self._lock:
@@ -50,7 +50,7 @@ def MultiProcessValue(process_identifier=os.getpid):
5050
# Use a single global lock when in multi-processing mode
5151
# as we presume this means there is no threading going on.
5252
# This avoids the need to also have mutexes in __MmapDict.
53-
lock = Lock()
53+
lock = RLock()
5454

5555
class MmapedValue:
5656
"""A float protected by a mutex backed by a per-process mmaped file."""

tests/test_core.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@
1616
from prometheus_client.metrics import _get_use_created
1717

1818

19+
def is_locked(lock):
20+
"Tries to obtain a lock, returns True on success, False on failure."
21+
locked = lock.acquire(blocking=False)
22+
if locked:
23+
lock.release()
24+
return not locked
25+
26+
1927
def assert_not_observable(fn, *args, **kwargs):
2028
"""
2129
Assert that a function call falls with a ValueError exception containing
@@ -963,7 +971,7 @@ def test_restricted_registry_does_not_yield_while_locked(self):
963971
m = Metric('target', 'Target metadata', 'info')
964972
m.samples = [Sample('target_info', {'foo': 'bar'}, 1)]
965973
for _ in registry.restricted_registry(['target_info', 's_sum']).collect():
966-
self.assertFalse(registry._lock.locked())
974+
self.assertFalse(is_locked(registry._lock))
967975

968976

969977
if __name__ == '__main__':

0 commit comments

Comments
 (0)
0