Debian Codegraph @

prometheus_client/multiprocess.py

raw symbols SCIP
1 from collections import defaultdict
2 import glob
3 import json
4 import os
5 import warnings
6
7 from .metrics import Gauge
8 from .metrics_core import Metric
9 from .mmap_dict import MmapedDict
10 from .samples import Sample
11 from .utils import floatToGoString
12
13 try: # Python3
14 FileNotFoundError
15 except NameError: # Python >= 2.5
16 FileNotFoundError = IOError
17
18
19 class MultiProcessCollector:
20 """Collector for files for multi-process mode."""
21
22 def __init__(self, registry, path=None):
23 if path is None:
24 # This deprecation warning can go away in a few releases when removing the compatibility
25 if 'prometheus_multiproc_dir' in os.environ and 'PROMETHEUS_MULTIPROC_DIR' not in os.environ:
26 os.environ['PROMETHEUS_MULTIPROC_DIR'] = os.environ['prometheus_multiproc_dir']
27 warnings.warn("prometheus_multiproc_dir variable has been deprecated in favor of the upper case naming PROMETHEUS_MULTIPROC_DIR", DeprecationWarning)
28 path = os.environ.get('PROMETHEUS_MULTIPROC_DIR')
29 if not path or not os.path.isdir(path):
30 raise ValueError('env PROMETHEUS_MULTIPROC_DIR is not set or not a directory')
31 self._path = path
32 if registry:
33 registry.register(self)
34
35 @staticmethod
36 def merge(files, accumulate=True):
37 """Merge metrics from given mmap files.
38
39 By default, histograms are accumulated, as per prometheus wire format.
40 But if writing the merged data back to mmap files, use
41 accumulate=False to avoid compound accumulation.
42 """
43 metrics = MultiProcessCollector._read_metrics(files)
44 return MultiProcessCollector._accumulate_metrics(metrics, accumulate)
45
46 @staticmethod
47 def _read_metrics(files):
48 metrics = {}
49 key_cache = {}
50
51 def _parse_key(key):
52 val = key_cache.get(key)
53 if not val:
54 metric_name, name, labels, help_text = json.loads(key)
55 labels_key = tuple(sorted(labels.items()))
56 val = key_cache[key] = (metric_name, name, labels, labels_key, help_text)
57 return val
58
59 for f in files:
60 parts = os.path.basename(f).split('_')
61 typ = parts[0]
62 try:
63 file_values = MmapedDict.read_all_values_from_file(f)
64 except FileNotFoundError:
65 if typ == 'gauge' and parts[1].startswith('live'):
66 # Files for 'live*' gauges can be deleted between the glob of collect
67 # and now (via a mark_process_dead call) so don't fail if
68 # the file is missing
69 continue
70 raise
71 for key, value, timestamp, _ in file_values:
72 metric_name, name, labels, labels_key, help_text = _parse_key(key)
73
74 metric = metrics.get(metric_name)
75 if metric is None:
76 metric = Metric(metric_name, help_text, typ)
77 metrics[metric_name] = metric
78
79 if typ == 'gauge':
80 pid = parts[2][:-3]
81 metric._multiprocess_mode = parts[1]
82 metric.add_sample(name, labels_key + (('pid', pid),), value, timestamp)
83 else:
84 # The duplicates and labels are fixed in the next for.
85 metric.add_sample(name, labels_key, value)
86 return metrics
87
88 @staticmethod
89 def _accumulate_metrics(metrics, accumulate):
90 for metric in metrics.values():
91 samples = defaultdict(float)
92 sample_timestamps = defaultdict(float)
93 buckets = defaultdict(lambda: defaultdict(float))
94 samples_setdefault = samples.setdefault
95 for s in metric.samples:
96 name, labels, value, timestamp, exemplar = s
97 if metric.type == 'gauge':
98 without_pid_key = (name, tuple(l for l in labels if l[0] != 'pid'))
99 if metric._multiprocess_mode in ('min', 'livemin'):
100 current = samples_setdefault(without_pid_key, value)
101 if value < current:
102 samples[without_pid_key] = value
103 elif metric._multiprocess_mode in ('max', 'livemax'):
104 current = samples_setdefault(without_pid_key, value)
105 if value > current:
106 samples[without_pid_key] = value
107 elif metric._multiprocess_mode in ('sum', 'livesum'):
108 samples[without_pid_key] += value
109 elif metric._multiprocess_mode in ('mostrecent', 'livemostrecent'):
110 current_timestamp = sample_timestamps[without_pid_key]
111 timestamp = float(timestamp or 0)
112 if current_timestamp < timestamp:
113 samples[without_pid_key] = value
114 sample_timestamps[without_pid_key] = timestamp
115 else: # all/liveall
116 samples[(name, labels)] = value
117
118 elif metric.type == 'histogram':
119 # A for loop with early exit is faster than a genexpr
120 # or a listcomp that ends up building unnecessary things
121 for l in labels:
122 if l[0] == 'le':
123 bucket_value = float(l[1])
124 # _bucket
125 without_le = tuple(l for l in labels if l[0] != 'le')
126 buckets[without_le][bucket_value] += value
127 break
128 else: # did not find the `le` key
129 # _sum/_count
130 samples[(name, labels)] += value
131 else:
132 # Counter and Summary.
133 samples[(name, labels)] += value
134
135 # Accumulate bucket values.
136 if metric.type == 'histogram':
137 for labels, values in buckets.items():
138 acc = 0.0
139 for bucket, value in sorted(values.items()):
140 sample_key = (
141 metric.name + '_bucket',
142 labels + (('le', floatToGoString(bucket)),),
143 )
144 if accumulate:
145 acc += value
146 samples[sample_key] = acc
147 else:
148 samples[sample_key] = value
149 if accumulate:
150 samples[(metric.name + '_count', labels)] = acc
151
152 # Convert to correct sample format.
153 metric.samples = [Sample(name_, dict(labels), value) for (name_, labels), value in samples.items()]
154 return metrics.values()
155
156 def collect(self):
157 files = glob.glob(os.path.join(self._path, '*.db'))
158 return self.merge(files, accumulate=True)
159
160
161 _LIVE_GAUGE_MULTIPROCESS_MODES = {m for m in Gauge._MULTIPROC_MODES if m.startswith('live')}
162
163
164 def mark_process_dead(pid, path=None):
165 """Do bookkeeping for when one process dies in a multi-process setup."""
166 if path is None:
167 path = os.environ.get('PROMETHEUS_MULTIPROC_DIR', os.environ.get('prometheus_multiproc_dir'))
168 for mode in _LIVE_GAUGE_MULTIPROCESS_MODES:
169 for f in glob.glob(os.path.join(path, f'gauge_{mode}_{pid}.db')):
170 os.remove(f)