|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | + proxy.py |
| 4 | + ~~~~~~~~ |
| 5 | + ⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on |
| 6 | + Network monitoring, controls & Application development, testing, debugging. |
| 7 | +
|
| 8 | + :copyright: (c) 2013-present by Abhinav Singh and contributors. |
| 9 | + :license: BSD, see LICENSE for more details. |
| 10 | +""" |
| 11 | +import os |
| 12 | +import glob |
| 13 | +from typing import Any, Dict |
| 14 | +from pathlib import Path |
| 15 | +from multiprocessing.synchronize import Lock |
| 16 | + |
| 17 | +from ...core.event import EventQueue, EventSubscriber, eventNames |
| 18 | +from ...common.constants import DEFAULT_METRICS_DIRECTORY_PATH |
| 19 | + |
| 20 | + |
| 21 | +class MetricsStorage: |
| 22 | + |
| 23 | + def __init__(self, lock: Lock) -> None: |
| 24 | + self._lock = lock |
| 25 | + |
| 26 | + def get_counter(self, name: str) -> float: |
| 27 | + with self._lock: |
| 28 | + return self._get_counter(name) |
| 29 | + |
| 30 | + def _get_counter(self, name: str) -> float: |
| 31 | + path = os.path.join(DEFAULT_METRICS_DIRECTORY_PATH, f'{name}.counter') |
| 32 | + if not os.path.exists(path): |
| 33 | + return 0 |
| 34 | + return float(Path(path).read_text(encoding='utf-8').strip()) |
| 35 | + |
| 36 | + def incr_counter(self, name: str, by: float = 1.0) -> None: |
| 37 | + with self._lock: |
| 38 | + self._incr_counter(name, by) |
| 39 | + |
| 40 | + def _incr_counter(self, name: str, by: float = 1.0) -> None: |
| 41 | + current = self._get_counter(name) |
| 42 | + path = os.path.join(DEFAULT_METRICS_DIRECTORY_PATH, f'{name}.counter') |
| 43 | + Path(path).write_text(str(current + by), encoding='utf-8') |
| 44 | + |
| 45 | + def get_gauge(self, name: str) -> float: |
| 46 | + with self._lock: |
| 47 | + return self._get_gauge(name) |
| 48 | + |
| 49 | + def _get_gauge(self, name: str) -> float: |
| 50 | + path = os.path.join(DEFAULT_METRICS_DIRECTORY_PATH, f'{name}.gauge') |
| 51 | + if not os.path.exists(path): |
| 52 | + return 0 |
| 53 | + return float(Path(path).read_text(encoding='utf-8').strip()) |
| 54 | + |
| 55 | + def set_gauge(self, name: str, value: float) -> None: |
| 56 | + """Stores a single values.""" |
| 57 | + with self._lock: |
| 58 | + self._set_gauge(name, value) |
| 59 | + |
| 60 | + def _set_gauge(self, name: str, value: float) -> None: |
| 61 | + path = os.path.join(DEFAULT_METRICS_DIRECTORY_PATH, f'{name}.gauge') |
| 62 | + with open(path, 'w', encoding='utf-8') as g: |
| 63 | + g.write(str(value)) |
| 64 | + |
| 65 | + |
| 66 | +class MetricsEventSubscriber: |
| 67 | + |
| 68 | + def __init__(self, event_queue: EventQueue, metrics_lock: Lock) -> None: |
| 69 | + """Aggregates metric events pushed by proxy.py core and plugins. |
| 70 | +
|
| 71 | + 1) Metrics are stored and managed by multiprocessing safe MetricsStorage |
| 72 | + 2) Collection must be done via MetricsWebServerPlugin endpoint |
| 73 | + """ |
| 74 | + self.storage = MetricsStorage(metrics_lock) |
| 75 | + self.subscriber = EventSubscriber( |
| 76 | + event_queue, |
| 77 | + callback=lambda event: MetricsEventSubscriber.callback(self.storage, event), |
| 78 | + ) |
| 79 | + |
| 80 | + def setup(self) -> None: |
| 81 | + self._setup_metrics_directory() |
| 82 | + self.subscriber.setup() |
| 83 | + |
| 84 | + def shutdown(self) -> None: |
| 85 | + self.subscriber.shutdown() |
| 86 | + |
| 87 | + def __enter__(self) -> 'MetricsEventSubscriber': |
| 88 | + self.setup() |
| 89 | + return self |
| 90 | + |
| 91 | + def __exit__(self, *args: Any) -> None: |
| 92 | + self.shutdown() |
| 93 | + |
| 94 | + @staticmethod |
| 95 | + def callback(storage: MetricsStorage, event: Dict[str, Any]) -> None: |
| 96 | + if event['event_name'] == eventNames.WORK_STARTED: |
| 97 | + storage.incr_counter('work_started') |
| 98 | + elif event['event_name'] == eventNames.REQUEST_COMPLETE: |
| 99 | + storage.incr_counter('request_complete') |
| 100 | + elif event['event_name'] == eventNames.WORK_FINISHED: |
| 101 | + storage.incr_counter('work_finished') |
| 102 | + else: |
| 103 | + print('Unhandled', event) |
| 104 | + |
| 105 | + def _setup_metrics_directory(self) -> None: |
| 106 | + os.makedirs(DEFAULT_METRICS_DIRECTORY_PATH, exist_ok=True) |
| 107 | + patterns = ['*.counter', '*.gauge'] |
| 108 | + for pattern in patterns: |
| 109 | + files = glob.glob(os.path.join(DEFAULT_METRICS_DIRECTORY_PATH, pattern)) |
| 110 | + for file_path in files: |
| 111 | + try: |
| 112 | + os.remove(file_path) |
| 113 | + except OSError as e: |
| 114 | + print(f'Error deleting file {file_path}: {e}') |
0 commit comments