фикс доки, добавление динамичных карточек мониторинга сервера
This commit is contained in:
1 parent
96fdbeb3df
commit
18744b7807
14 files changed
+716
-74
No files matched your search
@@ -0,0 +1,100 @@
|
||||
"""Serve the built site and proxy the host metrics without exposing its token."""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.error import URLError
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def validate_metrics(data):
|
||||
"""Validate upstream JSON and forward only the fields the UI needs."""
|
||||
def number(value, maximum):
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or not 0 <= value <= maximum:
|
||||
raise ValueError('Invalid metric')
|
||||
return value
|
||||
|
||||
sampled = datetime.fromisoformat(data['sampled_at'])
|
||||
if sampled.tzinfo is None or not -5 <= (datetime.now(timezone.utc) - sampled).total_seconds() <= 20:
|
||||
raise ValueError('Stale metric')
|
||||
result = {'sampled_at': sampled.isoformat(), 'cpu': {'percent': number(data['cpu']['percent'], 100)}}
|
||||
for key in ('memory', 'disk'):
|
||||
metric = data[key]
|
||||
total = number(metric['total_bytes'], 2 ** 63)
|
||||
if not total:
|
||||
raise ValueError('Empty capacity')
|
||||
result[key] = {'percent': number(metric['percent'], 100),
|
||||
'used_bytes': number(metric['used_bytes'], total), 'total_bytes': total}
|
||||
path = data['disk']['path']
|
||||
if not isinstance(path, str) or len(path) > 4096:
|
||||
raise ValueError('Invalid disk path')
|
||||
result['disk']['path'] = path
|
||||
return result
|
||||
|
||||
|
||||
def make_handler(metrics_url='', token='', directory=None):
|
||||
opener = build_opener(ProxyHandler({}), NoRedirect())
|
||||
|
||||
class Handler(SimpleHTTPRequestHandler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, directory=str(directory or ROOT / 'dist'), **kwargs)
|
||||
|
||||
def do_GET(self):
|
||||
if urlsplit(self.path).path != '/api/metrics':
|
||||
return super().do_GET()
|
||||
if not metrics_url or not token:
|
||||
return self.send_json(503, {'error': 'metrics_not_configured'})
|
||||
try:
|
||||
request = Request(metrics_url, headers={'Authorization': f'Bearer {token}', 'Accept': 'application/json'})
|
||||
with opener.open(request, timeout=3) as response:
|
||||
raw = response.read(16385)
|
||||
if len(raw) > 16384:
|
||||
raise ValueError('Response too large')
|
||||
data = validate_metrics(json.loads(raw))
|
||||
except (URLError, OSError, ValueError, KeyError, TypeError, OverflowError):
|
||||
return self.send_json(502, {'error': 'metrics_unavailable'})
|
||||
return self.send_json(200, data)
|
||||
|
||||
def send_json(self, status, data):
|
||||
body = json.dumps(data, allow_nan=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
def main():
|
||||
metrics_url = os.environ.get('METRICS_URL', '')
|
||||
if metrics_url:
|
||||
parsed = urlsplit(metrics_url)
|
||||
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password:
|
||||
raise SystemExit('METRICS_URL must be an HTTP(S) URL without credentials.')
|
||||
server = ThreadingHTTPServer(
|
||||
(os.environ.get('SITE_BIND', '127.0.0.1'), int(os.environ.get('PORT', '8080'))),
|
||||
make_handler(metrics_url, os.environ.get('METRICS_TOKEN', '')),
|
||||
)
|
||||
print(f'Documentation listening on {server.server_address[0]}:{server.server_address[1]}', flush=True)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user