"""/metrics/history and /metrics/settings: the metrics the metrics service keeps, and its settings.""" import linuxmanager import linuxmanager_metrics from .common import section_change def metrics_history(view): """Answer GET /metrics/history?range= with linuxmanager_metrics.history: the HTTP status and the JSON document. view is hour, the default, day, month or year (linuxmanager_metrics.RANGES). """ if view not in linuxmanager_metrics.RANGES: return 400, {'error': f'range must be one of {", ".join(linuxmanager_metrics.RANGES)}'} try: with linuxmanager_metrics.database(linuxmanager.load_config()) as connection: return 200, linuxmanager_metrics.history(connection, view) except linuxmanager_metrics.DatabaseError as exc: return 500, {'error': str(exc)} except SystemExit as exc: return 500, {'error': str(exc.code)} def metrics_shown(settings): """The metrics section as /metrics/settings shows it: its settings but otlp_password, with otlp_password_set.""" return {**{option: value for option, value in settings.items() if option != 'otlp_password'}, 'otlp_password_set': bool(settings['otlp_password'])} def metrics_settings(method, body): """Answer a /metrics/settings request: the HTTP status and the JSON document. GET /metrics/settings {"settings"}: the metrics section without otlp_password, with otlp_password_set PUT /metrics/settings change any of the settings of the metrics section; an empty or absent otlp_password keeps the current secret, and an empty otlp_username removes it A change is applied by a run of linux-manager-setup, without waiting for it. """ if body == 'invalid' or (body is not None and not isinstance(body, dict)): return 400, {'error': 'the body must be a JSON object'} if method in ('GET', 'HEAD'): try: return 200, {'settings': metrics_shown(linuxmanager.load_config()['metrics'])} except SystemExit as exc: return 500, {'error': str(exc.code)} if method != 'PUT': return 404, {'error': f'no route {method} /metrics/settings'} body = dict(body or {}) if not body.get('otlp_password'): body.pop('otlp_password', None) if body.get('otlp_username') == '': body['otlp_password'] = '' changed = section_change('metrics', body) return changed if isinstance(changed, tuple) else (200, {'settings': metrics_shown(changed)})