Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/content/multiprocess/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ This comes with a number of limitations:
- Info and Enum metrics do not work
- The pushgateway cannot be used
- Gauges cannot use the `pid` label
- Exemplars are not supported
- Remove and Clear of labels are currently not supported in multiprocess mode.

Exemplars are supported for counters and histograms. They are kept in
`*.exemplars` files next to the per-process metric files, and when several
processes recorded an exemplar for the same series, the most recent one is
exposed. These files need to be wiped together with the rest of the directory.

There's several steps to getting this working:

**1. Deployment**:
Expand Down
132 changes: 132 additions & 0 deletions prometheus_client/mmap_dict.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import math
import mmap
import os
import struct
Expand Down Expand Up @@ -147,6 +148,137 @@ def close(self):
self._f = None


# Exemplar labels are limited to 128 characters in total. A character takes at
# most 4 bytes in UTF-8 and 6 bytes once a control character is escaped in
# JSON, so this leaves room for the quoting and separators as well.
_EXEMPLAR_LABELS_SIZE = 1200
_pack_exemplar_header = struct.Struct(b'qddi4x').pack
_unpack_exemplar_header = struct.Struct(b'qddi4x').unpack_from
_EXEMPLAR_HEADER_SIZE = struct.calcsize(b'qddi4x')
_ENTRY_TAIL_SIZE = _EXEMPLAR_HEADER_SIZE + _EXEMPLAR_LABELS_SIZE
_pack_long = struct.Struct(b'q').pack


def _read_all_exemplars(data, used=0):
"""Yield (key, labels, value, timestamp, pos). No locking is performed.

Entries that are being written while they are read are skipped.
"""

if used <= 0:
used = _unpack_integer(data, 0)[0]

pos = 8
while pos < used:
encoded_len = _unpack_integer(data, pos)[0]
if encoded_len + pos > used:
raise RuntimeError('Read beyond file size detected, file is corrupted.')
pos += 4
encoded_key = data[pos:pos + encoded_len]
pos += encoded_len + (8 - (encoded_len + 4) % 8)
if pos + _ENTRY_TAIL_SIZE > used:
raise RuntimeError('Read beyond file size detected, file is corrupted.')
seq, value, timestamp, labels_len = _unpack_exemplar_header(data, pos)
labels_data = data[pos + _EXEMPLAR_HEADER_SIZE:pos + _EXEMPLAR_HEADER_SIZE + labels_len]
seq_after = _unpack_exemplar_header(data, pos)[0]
entry_pos = pos
pos += _ENTRY_TAIL_SIZE
# An odd or changed sequence number means a writer was in the middle
# of an update, and an entry that was never written has none at all.
if seq <= 0 or seq % 2 or seq != seq_after or labels_len > _EXEMPLAR_LABELS_SIZE:
continue
labels = json.loads(labels_data.decode('utf-8'))
yield encoded_key.decode('utf-8'), labels, value, (None if math.isnan(timestamp) else timestamp), entry_pos


class MmapedExemplarDict:
"""A dict of exemplars, backed by an mmapped file.

The layout follows MmapedDict, with the 8 byte header and the padded utf-8
key in front of every entry. The entries differ in what comes after the
key: an 8 byte sequence number, the exemplar value and timestamp as two
doubles, the byte length of the labels, and a fixed size area holding the
exemplar labels as JSON. Exemplars are replaced as a whole, and every key
is given a slot only once, so the file does not grow with the number of
exemplars written.

The sequence number is odd while an entry is being rewritten, which lets a
reader in another process skip an entry it might see half written.

Not thread safe.
"""

def __init__(self, filename):
self._f = open(filename, 'a+b')
self._fname = filename
capacity = os.fstat(self._f.fileno()).st_size
if capacity == 0:
self._f.truncate(_INITIAL_MMAP_SIZE)
capacity = _INITIAL_MMAP_SIZE
self._capacity = capacity
self._m = mmap.mmap(self._f.fileno(), self._capacity, access=mmap.ACCESS_WRITE)

self._positions = {}
self._used = _unpack_integer(self._m, 0)[0]
if self._used == 0:
self._used = 8
_pack_integer(self._m, 0, self._used)
else:
for key, _, _, _, pos in _read_all_exemplars(self._m, self._used):
self._positions[key] = pos

@staticmethod
def read_all_exemplars_from_file(filename):
with open(filename, 'rb') as infp:
data = infp.read(mmap.PAGESIZE)
if not data:
return iter(())
used = _unpack_integer(data, 0)[0]
if used > len(data):
data += infp.read(used - len(data))
return ((k, labels, v, ts) for k, labels, v, ts, _ in _read_all_exemplars(data, used))

def _init_entry(self, key):
"""Reserve the slot of a key. Lock must be held by caller."""
encoded = key.encode('utf-8')
padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8))
entry = struct.pack(f'i{len(padded)}s'.encode(), len(encoded), padded) + bytes(_ENTRY_TAIL_SIZE)
while self._used + len(entry) > self._capacity:
self._capacity *= 2
self._f.truncate(self._capacity)
self._m = mmap.mmap(self._f.fileno(), self._capacity)
self._m[self._used:self._used + len(entry)] = entry
self._used += len(entry)
_pack_integer(self._m, 0, self._used)
self._positions[key] = self._used - _ENTRY_TAIL_SIZE

def write_exemplar(self, key, labels, value, timestamp):
encoded_labels = json.dumps(labels, ensure_ascii=False).encode('utf-8')
if len(encoded_labels) > _EXEMPLAR_LABELS_SIZE:
raise ValueError('Exemplar labels are too large to be stored')
if key not in self._positions:
self._init_entry(key)
pos = self._positions[key]
seq = _unpack_exemplar_header(self._m, pos)[0]
if seq % 2:
seq += 1
# Mark the entry as being written, fill it in, then publish it.
self._m[pos:pos + 8] = _pack_long(seq + 1)
header = _pack_exemplar_header(
seq + 1, value, math.nan if timestamp is None else timestamp, len(encoded_labels))
self._m[pos + 8:pos + _EXEMPLAR_HEADER_SIZE] = header[8:]
start = pos + _EXEMPLAR_HEADER_SIZE
self._m[start:start + len(encoded_labels)] = encoded_labels
self._m[pos:pos + 8] = _pack_long(seq + 2)

def close(self):
if self._f:
self._m.close()
self._m = None
self._f.close()
self._f = None


def mmap_key(metric_name: str, name: str, labelnames: List[str], labelvalues: List[str], help_text: str) -> str:
"""Format a key for use in the mmap file."""
# ensure labels are in consistent order for identity
Expand Down
41 changes: 34 additions & 7 deletions prometheus_client/multiprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

from .metrics import Gauge
from .metrics_core import Metric
from .mmap_dict import MmapedDict
from .samples import Sample
from .mmap_dict import MmapedDict, MmapedExemplarDict
from .samples import Exemplar, Sample
from .utils import floatToGoString

try: # Python3
Expand All @@ -16,6 +16,9 @@
FileNotFoundError = IOError


_EXEMPLAR_SUFFIX = '.exemplars'


class MultiProcessCollector:
"""Collector for files for multi-process mode."""

Expand All @@ -40,8 +43,29 @@ def merge(files, accumulate=True):
But if writing the merged data back to mmap files, use
accumulate=False to avoid compound accumulation.
"""
metrics = MultiProcessCollector._read_metrics(files)
return MultiProcessCollector._accumulate_metrics(metrics, accumulate)
files = list(files)
exemplar_files = [f for f in files if f.endswith(_EXEMPLAR_SUFFIX)]
db_files = [f for f in files if not f.endswith(_EXEMPLAR_SUFFIX)]
metrics = MultiProcessCollector._read_metrics(db_files)
exemplars = MultiProcessCollector._read_exemplars(exemplar_files)
return MultiProcessCollector._accumulate_metrics(metrics, accumulate, exemplars)

@staticmethod
def _read_exemplars(files):
"""Return the newest exemplar of every sample, keyed by metric name, sample name and labels."""
exemplars = {}
for f in files:
try:
file_exemplars = list(MmapedExemplarDict.read_all_exemplars_from_file(f))
except FileNotFoundError:
continue
for key, exemplar_labels, value, timestamp in file_exemplars:
metric_name, name, labels, _ = json.loads(key)
sample_key = (metric_name, name, tuple(sorted(labels.items())))
current = exemplars.get(sample_key)
if current is None or (current.timestamp or 0) < (timestamp or 0):
exemplars[sample_key] = Exemplar(exemplar_labels, value, timestamp)
return exemplars

@staticmethod
def _read_metrics(files):
Expand Down Expand Up @@ -86,8 +110,9 @@ def _parse_key(key):
return metrics

@staticmethod
def _accumulate_metrics(metrics, accumulate):
for metric in metrics.values():
def _accumulate_metrics(metrics, accumulate, exemplars=None):
exemplars = exemplars or {}
for metric_name, metric in metrics.items():
samples = defaultdict(lambda: defaultdict(float))
sample_timestamps = defaultdict(lambda: defaultdict(float))
buckets = defaultdict(lambda: defaultdict(float))
Expand Down Expand Up @@ -163,11 +188,13 @@ def _accumulate_metrics(metrics, accumulate):
metric.samples = []
for _, samples_by_labels in samples.items():
for (name_, labels), value in samples_by_labels.items():
metric.samples.append(Sample(name_, dict(labels), value))
exemplar = exemplars.get((metric_name, name_, tuple(sorted(labels))))
metric.samples.append(Sample(name_, dict(labels), value, None, exemplar))
return metrics.values()

def collect(self):
files = glob.glob(os.path.join(self._path, '*.db'))
files += glob.glob(os.path.join(self._path, '*' + _EXEMPLAR_SUFFIX))
return self.merge(files, accumulate=True)


Expand Down
33 changes: 28 additions & 5 deletions prometheus_client/values.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Callable, List
import warnings

from .mmap_dict import mmap_key, MmapedDict
from .mmap_dict import mmap_key, MmapedDict, MmapedExemplarDict

_multi_process_cleanups: List[Callable[[], None]] = []

Expand Down Expand Up @@ -54,6 +54,7 @@ def MultiProcessValue(process_identifier=os.getpid):
Using a different function than the default 'os.getpid' is at your own risk.
"""
files = {}
exemplar_files = {}
values = []
pid = {'value': process_identifier()}
# Use a single global lock when in multi-processing mode
Expand All @@ -65,6 +66,9 @@ def cleanup():
for f in files.values():
f.close()
files.clear()
for f in exemplar_files.values():
f.close()
exemplar_files.clear()
values.clear()
_multi_process_cleanups.append(cleanup)

Expand Down Expand Up @@ -99,6 +103,7 @@ def __reset(self):
self._file = files[file_prefix]
self._key = mmap_key(metric_name, name, labelnames, labelvalues, help_text)
self._value, self._timestamp = self._file.read_value(self._key)
self._exemplar = None

def __check_for_pid_change(self):
actual_pid = process_identifier()
Expand All @@ -108,6 +113,9 @@ def __check_for_pid_change(self):
for f in files.values():
f.close()
files.clear()
for f in exemplar_files.values():
f.close()
exemplar_files.clear()
for value in values:
value.__reset()

Expand All @@ -126,24 +134,39 @@ def set(self, value, timestamp=None):
self._file.write_value(self._key, self._value, self._timestamp)

def set_exemplar(self, exemplar):
# TODO: Implement exemplars for multiprocess mode.
return
with lock:
self.__check_for_pid_change()
typ = self._params[0]
if typ not in exemplar_files:
filename = os.path.join(
os.environ.get('PROMETHEUS_MULTIPROC_DIR'),
'{}_{}.exemplars'.format(typ, pid['value']))
exemplar_files[typ] = MmapedExemplarDict(filename)
timestamp = exemplar.timestamp
exemplar_files[typ].write_exemplar(
self._key, dict(exemplar.labels), exemplar.value,
None if timestamp is None else float(timestamp))
self._exemplar = exemplar

def get(self):
with lock:
self.__check_for_pid_change()
return self._value

def get_exemplar(self):
# TODO: Implement exemplars for multiprocess mode.
return None
with lock:
self.__check_for_pid_change()
return self._exemplar

@classmethod
def close_all_files(cls):
with lock:
for f in files.values():
f.close()
files.clear()
for f in exemplar_files.values():
f.close()
exemplar_files.clear()
values.clear()

return MmapedValue
Expand Down
Loading