|
| 1 | +import logging |
| 2 | +import re |
| 3 | +from typing import Iterable, Dict, List |
| 4 | +from sams.core import Config |
| 5 | +from .base_listener import Listener as BaseListener |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | + |
| 10 | +class Listener(BaseListener): |
| 11 | + """ |
| 12 | + Listener for Prometheus output. |
| 13 | + """ |
| 14 | + def __init__(self, |
| 15 | + class_path: str, |
| 16 | + config: Config, |
| 17 | + samplers: List): |
| 18 | + super().__init__(class_path, |
| 19 | + config, |
| 20 | + samplers) |
| 21 | + self.static_map = self.config.get([self.class_path, "static_map"], {}) |
| 22 | + self.map = self.config.get([self.class_path, "map"], {}) |
| 23 | + self.metrics = self.config.get([self.class_path, "metrics"], {}) |
| 24 | + |
| 25 | + @staticmethod |
| 26 | + def _nested_getitem(dct: Dict, keys: Iterable) -> Dict: |
| 27 | + """ Fetches an item from nested dictionaries. |
| 28 | + If any of the keys in `keys` is missing, this method |
| 29 | + returns `None`.""" |
| 30 | + for key in keys: |
| 31 | + if key in dct: |
| 32 | + dct = dct[key] |
| 33 | + else: |
| 34 | + return None |
| 35 | + return dct |
| 36 | + |
| 37 | + def _flatten_dict(self, dct, base='') -> List: |
| 38 | + """ Recursively flattens a dictionary into a list-of-dictionaries, |
| 39 | + with each dictionary in the list possessing the entries `'match'` |
| 40 | + and `'value'`.""" |
| 41 | + out = [] |
| 42 | + for key in dct.keys(): |
| 43 | + nb = "/".join([base, key]) |
| 44 | + if key in dct and isinstance(dct[key], dict): |
| 45 | + out = out + self._flatten_dict(dct[key], base=nb) |
| 46 | + else: |
| 47 | + out = out + [{"match": nb, "value": dct[key]}] |
| 48 | + return out |
| 49 | + |
| 50 | + @property |
| 51 | + def encoded_data(self) -> bytes: |
| 52 | + """ The most recent data from attached samplers, |
| 53 | + formatted, compiled and encoded to UTF-8 format. """ |
| 54 | + data = self._get_all_samples() |
| 55 | + # Then match config with entries and create flattened, compiled data |
| 56 | + compiled_data = dict() |
| 57 | + for match_set in self._get_matching_entries(data): |
| 58 | + self._compile_data(data, |
| 59 | + compiled_data, |
| 60 | + *match_set) |
| 61 | + # Parse & encode compiled data into bytestring. |
| 62 | + return self._get_bytestring(compiled_data) |
| 63 | + |
| 64 | + def _get_all_samples(self) -> Dict: |
| 65 | + """ Returns compilation of all most recent samples |
| 66 | + as a dictionary ``{sample['id']: sample[v'alue']}`` |
| 67 | + Skips ``None`` entries. |
| 68 | + """ |
| 69 | + data = dict() |
| 70 | + for sampler in self.samplers: |
| 71 | + if sampler.most_recent_sample is not None: |
| 72 | + for s in sampler.most_recent_sample: |
| 73 | + # if id repeated, update data dictionary |
| 74 | + if s['id'] in data: |
| 75 | + data[s['id']].update(s['data']) |
| 76 | + else: |
| 77 | + data.update({s['id']: s['data']}) |
| 78 | + return data |
| 79 | + |
| 80 | + def _get_matching_entries(self, |
| 81 | + data: Dict) -> Iterable: |
| 82 | + flat_dictionary = self._flatten_dict(data) |
| 83 | + logger.debug(f'Flat dictionary: {flat_dictionary}') |
| 84 | + for d in flat_dictionary: |
| 85 | + for metric, destination in self.metrics.items(): |
| 86 | + reg = re.compile(metric) |
| 87 | + m = reg.match(d['match']) |
| 88 | + logger.debug(f'Metric matches: {m}') |
| 89 | + if m is not None: |
| 90 | + yield (str(d['value']), |
| 91 | + destination, |
| 92 | + m.groupdict()) |
| 93 | + |
| 94 | + @staticmethod |
| 95 | + def _get_bytestring(compiled_data: Dict) -> bytes: |
| 96 | + """ Takes the compiled data, parses entry names, and |
| 97 | + turns it into a Prometheus-formatted bytestring, |
| 98 | + ready to be sent over socket. """ |
| 99 | + helped = dict() |
| 100 | + metric_re = re.compile(r'^(\S+){') |
| 101 | + formatted_data = [] |
| 102 | + for m in sorted(compiled_data.keys()): |
| 103 | + logger.debug(f'Data key: {m}') |
| 104 | + match = metric_re.match(m) |
| 105 | + # Check if key is in config |
| 106 | + if match is None: |
| 107 | + continue |
| 108 | + if match.group(1) not in helped: |
| 109 | + helped[match.group(1)] = True |
| 110 | + formatted_data.append(f'# HELP {match.group(1):s} Job Usage Metrics') |
| 111 | + formatted_data.append(f'# TYPE {match.group(1):s} gauge') |
| 112 | + v = compiled_data[m] |
| 113 | + formatted_data.append(f'{m} {str(v)}') |
| 114 | + data_bytestring = '\n'.join(formatted_data).encode('utf-8') |
| 115 | + return data_bytestring |
| 116 | + |
| 117 | + def _compile_data(self, |
| 118 | + in_data: Dict, |
| 119 | + out_data: Dict, |
| 120 | + value, |
| 121 | + destination: str, |
| 122 | + extra_mappings: Dict) -> None: |
| 123 | + """ Subroutine method that updates `out_data` |
| 124 | + with entries from `in_data` based on the provided |
| 125 | + mappings. """ |
| 126 | + # static_map is per-node, constant metadata |
| 127 | + d = self.static_map.copy() |
| 128 | + d.update(extra_mappings) |
| 129 | + # Get per-job metadata |
| 130 | + for k, v in self.map.items(): |
| 131 | + m = self._nested_getitem(in_data, v.split('/')) |
| 132 | + if m is None: |
| 133 | + logger.warning(f'map: {k}: {v} is missing') |
| 134 | + return |
| 135 | + d[k] = m |
| 136 | + try: |
| 137 | + # Parse metadata into output string |
| 138 | + dest = destination % d |
| 139 | + except Exception as e: |
| 140 | + logger.error(e) |
| 141 | + return |
| 142 | + if len(value) == 0: |
| 143 | + logger.warning(f'{dest} got no metric') |
| 144 | + # Store output string as key and data as value |
| 145 | + out_data[dest] = value |
| 146 | + logger.debug(f'Storing {dest} = {str(value)}') |
0 commit comments