monitoring-app 1.1.84__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of monitoring-app might be problematic. Click here for more details.
- monitoring_app/VERSION +1 -0
- monitoring_app/__init__.py +16 -0
- monitoring_app/admin/__init__.py +1 -0
- monitoring_app/admin/app.py +238 -0
- monitoring_app/admin/audit.py +219 -0
- monitoring_app/admin/dashboard/__init__.py +1 -0
- monitoring_app/admin/dashboard/alert_insights.py +75 -0
- monitoring_app/admin/dashboard/alerts.py +230 -0
- monitoring_app/admin/dashboard/batch_insights.py +1576 -0
- monitoring_app/admin/dashboard/log_summary.py +181 -0
- monitoring_app/admin/deploy_ui.py +88 -0
- monitoring_app/admin/deps.py +375 -0
- monitoring_app/admin/entities_context.py +309 -0
- monitoring_app/admin/entities_manager.py +150 -0
- monitoring_app/admin/platform_users/__init__.py +1 -0
- monitoring_app/admin/platform_users/approvals.py +222 -0
- monitoring_app/admin/platform_users/export.py +1515 -0
- monitoring_app/admin/platform_users/idc.py +1741 -0
- monitoring_app/admin/platform_users/offboard.py +610 -0
- monitoring_app/admin/platform_users/platform_api.py +956 -0
- monitoring_app/admin/routes/__init__.py +1 -0
- monitoring_app/admin/routes/approvals.py +183 -0
- monitoring_app/admin/routes/auth.py +428 -0
- monitoring_app/admin/routes/batches.py +271 -0
- monitoring_app/admin/routes/dashboard.py +250 -0
- monitoring_app/admin/routes/entities.py +265 -0
- monitoring_app/admin/routes/idc_users.py +240 -0
- monitoring_app/admin/routes/logs.py +130 -0
- monitoring_app/admin/routes/platform_users.py +879 -0
- monitoring_app/admin/routes/servers.py +220 -0
- monitoring_app/admin/routes/settings.py +604 -0
- monitoring_app/admin/routes/system.py +123 -0
- monitoring_app/admin/routes/users.py +162 -0
- monitoring_app/admin/security/__init__.py +1 -0
- monitoring_app/admin/security/login.py +306 -0
- monitoring_app/admin/security/login_errors.py +59 -0
- monitoring_app/admin/security/saml.py +400 -0
- monitoring_app/admin/security/users.py +523 -0
- monitoring_app/admin/servers/__init__.py +1 -0
- monitoring_app/admin/servers/log_analysis.py +342 -0
- monitoring_app/admin/servers/manager.py +112 -0
- monitoring_app/admin/servers/processes.py +405 -0
- monitoring_app/admin/servers/registry.py +370 -0
- monitoring_app/admin/servers/utilization.py +481 -0
- monitoring_app/admin/servers/utilization_manager.py +142 -0
- monitoring_app/admin/status_source.py +76 -0
- monitoring_app/admin/ui_landing.py +35 -0
- monitoring_app/admin_static/.base-href +1 -0
- monitoring_app/admin_static/index.html +12 -0
- monitoring_app/admin_static/main-ZCCHZ626.js +94 -0
- monitoring_app/admin_static/polyfills-25SJBI4S.js +2 -0
- monitoring_app/admin_static/styles-YEZDZ3Y6.css +1 -0
- monitoring_app/cli.py +220 -0
- monitoring_app/config/__init__.py +1 -0
- monitoring_app/config/credentials.py +497 -0
- monitoring_app/config/entities.py +337 -0
- monitoring_app/config/env_editor.py +529 -0
- monitoring_app/config/envfile.py +53 -0
- monitoring_app/config/legacy.py +288 -0
- monitoring_app/config/paths.py +82 -0
- monitoring_app/config/policy.py +498 -0
- monitoring_app/config/schema.py +335 -0
- monitoring_app/config/settings.py +941 -0
- monitoring_app/ctl.py +106 -0
- monitoring_app/data/.env.example +146 -0
- monitoring_app/integrations/__init__.py +1 -0
- monitoring_app/integrations/inferyx_api.py +2052 -0
- monitoring_app/integrations/mongodb.py +706 -0
- monitoring_app/monitor/__init__.py +1 -0
- monitoring_app/monitor/engine.py +3311 -0
- monitoring_app/monitor/logs.py +333 -0
- monitoring_app/monitor/schedule.py +236 -0
- monitoring_app/monitor/targets.py +202 -0
- monitoring_app/notify/__init__.py +1 -0
- monitoring_app/notify/chat.py +201 -0
- monitoring_app/notify/mail.py +58 -0
- monitoring_app/service.py +239 -0
- monitoring_app/store/__init__.py +1 -0
- monitoring_app/store/alerts.py +519 -0
- monitoring_app/store/approvals.py +407 -0
- monitoring_app/store/console.py +33 -0
- monitoring_app/store/consolidate.py +114 -0
- monitoring_app/store/secrets.py +482 -0
- monitoring_app/store/sqlite.py +96 -0
- monitoring_app/version_info.py +62 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/CHANGELOG.md +326 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/DEPLOYMENT.md +416 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/USER_GUIDE.md +130 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/auth.policy.example +78 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/entities.policy.example +34 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/monitoring-app.service.example +28 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/nginx.conf.example +100 -0
- monitoring_app-1.1.84.data/data/share/monitoring-app/release.sh +601 -0
- monitoring_app-1.1.84.dist-info/METADATA +224 -0
- monitoring_app-1.1.84.dist-info/RECORD +99 -0
- monitoring_app-1.1.84.dist-info/WHEEL +5 -0
- monitoring_app-1.1.84.dist-info/entry_points.txt +6 -0
- monitoring_app-1.1.84.dist-info/licenses/LICENSE +7 -0
- monitoring_app-1.1.84.dist-info/top_level.txt +1 -0
monitoring_app/VERSION
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
1.1.84
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Inferyx pipeline batch monitor — API polling and email alerts."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version('monitoring-app')
|
|
7
|
+
except PackageNotFoundError:
|
|
8
|
+
__version__ = '1.0.0'
|
|
9
|
+
|
|
10
|
+
__all__ = ['__version__']
|
|
11
|
+
|
|
12
|
+
# Old installs set PIPELINE_* variables (systemd unit, shell). Map them to
|
|
13
|
+
# MONITORING_APP_* before any settings are read. See config/legacy.py.
|
|
14
|
+
from monitoring_app.config.legacy import adopt_legacy_process_env as _adopt_legacy_env
|
|
15
|
+
|
|
16
|
+
_adopt_legacy_env()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Admin web UI API for runtime .env and batch CSV management."""
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""FastAPI application for admin UI.
|
|
2
|
+
|
|
3
|
+
This module only builds the FastAPI app (middleware, error handlers, startup)
|
|
4
|
+
and registers the routers in ``admin/routes/``. Keep its import path stable:
|
|
5
|
+
the service starts ``python -m <package>.admin.app``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import secrets
|
|
14
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
15
|
+
from fastapi.exception_handlers import http_exception_handler, request_validation_exception_handler
|
|
16
|
+
from fastapi.exceptions import RequestValidationError
|
|
17
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
18
|
+
from fastapi.responses import JSONResponse
|
|
19
|
+
from monitoring_app.config.policy import load_policy
|
|
20
|
+
from monitoring_app.version_info import get_package_version
|
|
21
|
+
from monitoring_app.admin.routes.approvals import register_approval_routes
|
|
22
|
+
from monitoring_app.admin.deps import ( # noqa: F401
|
|
23
|
+
_SECURITY_HEADERS,
|
|
24
|
+
_SKIP_REQUEST_LOG,
|
|
25
|
+
_cors_origins,
|
|
26
|
+
_ensure_monitor_root,
|
|
27
|
+
_log_request_failure,
|
|
28
|
+
_require_console_admin,
|
|
29
|
+
_set_auth_cookie,
|
|
30
|
+
_write_audit,
|
|
31
|
+
get_policy,
|
|
32
|
+
logger,
|
|
33
|
+
require_auth,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
from monitoring_app.admin.routes import auth, users, settings, batches, dashboard, logs, platform_users, idc_users, entities, servers, system
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
app = FastAPI(title='Inferyx Monitoring Admin API', version=get_package_version())
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@app.on_event('startup')
|
|
43
|
+
def _attach_monitor_file_log() -> None:
|
|
44
|
+
# Before any request: move tables to their owning database (older releases kept
|
|
45
|
+
# console users in alerts.db; an empty console.db would allow first-admin sign-up).
|
|
46
|
+
try:
|
|
47
|
+
from monitoring_app.store.consolidate import consolidate
|
|
48
|
+
|
|
49
|
+
consolidate(policy=load_policy())
|
|
50
|
+
except Exception:
|
|
51
|
+
logger.exception('Database layout upgrade failed')
|
|
52
|
+
try:
|
|
53
|
+
from monitoring_app.monitor.logs import attach_monitor_file_log, monitor_log_retention_days, resolve_monitor_log_path
|
|
54
|
+
|
|
55
|
+
policy = load_policy()
|
|
56
|
+
|
|
57
|
+
attach_monitor_file_log(
|
|
58
|
+
str(resolve_monitor_log_path(policy)),
|
|
59
|
+
retention_days=monitor_log_retention_days(policy),
|
|
60
|
+
)
|
|
61
|
+
logger.info('Admin API writing monitor log')
|
|
62
|
+
except Exception:
|
|
63
|
+
logger.exception('Could not attach monitor log file')
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
from monitoring_app.admin.platform_users.export import start_platform_user_export_scheduler
|
|
67
|
+
|
|
68
|
+
start_platform_user_export_scheduler()
|
|
69
|
+
except Exception:
|
|
70
|
+
logger.exception('Could not start platform user export scheduler')
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@app.middleware('http')
|
|
74
|
+
async def add_security_headers(request: Request, call_next):
|
|
75
|
+
response = await call_next(request)
|
|
76
|
+
for name, value in _SECURITY_HEADERS.items():
|
|
77
|
+
response.headers.setdefault(name, value)
|
|
78
|
+
if request.url.path.startswith('/api/'):
|
|
79
|
+
response.headers.setdefault('Cache-Control', 'no-store')
|
|
80
|
+
return response
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@app.middleware('http')
|
|
84
|
+
async def log_ui_actions(request: Request, call_next):
|
|
85
|
+
"""Write button/save actions to monitor.log so `tail -f` shows them."""
|
|
86
|
+
path = request.url.path
|
|
87
|
+
skip = request.method == 'OPTIONS' or any(path.endswith(suffix) for suffix in _SKIP_REQUEST_LOG)
|
|
88
|
+
response = await call_next(request)
|
|
89
|
+
if skip:
|
|
90
|
+
return response
|
|
91
|
+
if request.method in ('POST', 'PUT', 'DELETE') and 200 <= response.status_code < 400:
|
|
92
|
+
logger.info('UI %s %s → %s', request.method, path, response.status_code)
|
|
93
|
+
return response
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@app.exception_handler(HTTPException)
|
|
97
|
+
async def log_http_exception(request: Request, exc: HTTPException):
|
|
98
|
+
_log_request_failure(request, exc.status_code, exc.detail)
|
|
99
|
+
return await http_exception_handler(request, exc)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@app.exception_handler(RequestValidationError)
|
|
103
|
+
async def log_validation_exception(request: Request, exc: RequestValidationError):
|
|
104
|
+
_log_request_failure(request, 422, exc.errors())
|
|
105
|
+
return await request_validation_exception_handler(request, exc)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@app.exception_handler(Exception)
|
|
109
|
+
async def log_unhandled_exception(request: Request, exc: Exception):
|
|
110
|
+
if isinstance(exc, (HTTPException, RequestValidationError)):
|
|
111
|
+
raise exc
|
|
112
|
+
crash = f'{type(exc).__name__}: {exc}'
|
|
113
|
+
error_id = secrets.token_hex(4)
|
|
114
|
+
logger.exception('UI %s %s crashed [%s]: %s', request.method, request.url.path, error_id, exc)
|
|
115
|
+
_log_request_failure(request, 500, {'errors': [f'{crash} [{error_id}]']})
|
|
116
|
+
# Internal details (paths, SQL, hostnames) stay in the server log only.
|
|
117
|
+
return JSONResponse(
|
|
118
|
+
status_code=500,
|
|
119
|
+
content={'detail': {'errors': [f'Request failed — internal error (reference {error_id}). See monitor log.']}},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@app.middleware('http')
|
|
124
|
+
async def ui_enabled_middleware(request: Request, call_next):
|
|
125
|
+
policy = load_policy()
|
|
126
|
+
if request.url.path.startswith('/api/') and request.url.path not in (
|
|
127
|
+
'/api/health',
|
|
128
|
+
'/api/ui/status',
|
|
129
|
+
'/api/auth/providers',
|
|
130
|
+
'/api/branding',
|
|
131
|
+
'/api/system/version',
|
|
132
|
+
'/api/auth/saml/aws_idc/metadata',
|
|
133
|
+
):
|
|
134
|
+
if not policy.ui_enabled and not request.url.path.startswith('/api/auth/'):
|
|
135
|
+
return JSONResponse(status_code=503, content={'detail': 'Admin UI is disabled'})
|
|
136
|
+
response = await call_next(request)
|
|
137
|
+
return response
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
register_approval_routes(
|
|
141
|
+
app,
|
|
142
|
+
get_policy=get_policy,
|
|
143
|
+
require_auth=require_auth,
|
|
144
|
+
_require_console_admin=_require_console_admin,
|
|
145
|
+
_write_audit=_write_audit,
|
|
146
|
+
_set_auth_cookie=_set_auth_cookie,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
for _router in (auth.router, users.router, settings.router, batches.router, dashboard.router, logs.router, platform_users.router, idc_users.router, entities.router, servers.router, system.router):
|
|
151
|
+
app.include_router(_router)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
if _cors_origins:
|
|
155
|
+
_cors_wildcard = '*' in _cors_origins
|
|
156
|
+
app.add_middleware(
|
|
157
|
+
CORSMiddleware,
|
|
158
|
+
allow_origins=['*'] if _cors_wildcard else _cors_origins,
|
|
159
|
+
allow_credentials=not _cors_wildcard,
|
|
160
|
+
allow_methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
|
161
|
+
allow_headers=['Content-Type', 'X-CSRF-Token', 'X-Requested-With'],
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def build_cli_parser() -> argparse.ArgumentParser:
|
|
166
|
+
parser = argparse.ArgumentParser(
|
|
167
|
+
prog='monitoring-app-admin',
|
|
168
|
+
description='Inferyx Monitoring Admin API (FastAPI + OAuth)',
|
|
169
|
+
)
|
|
170
|
+
parser.add_argument(
|
|
171
|
+
'--host',
|
|
172
|
+
default=os.getenv('MONITORING_APP_ADMIN_HOST', '127.0.0.1'),
|
|
173
|
+
help='Bind address (default: 127.0.0.1, or MONITORING_APP_ADMIN_HOST)',
|
|
174
|
+
)
|
|
175
|
+
parser.add_argument(
|
|
176
|
+
'--port',
|
|
177
|
+
type=int,
|
|
178
|
+
default=int(os.getenv('MONITORING_APP_ADMIN_PORT', '8090')),
|
|
179
|
+
help='Bind port (default: 8090, or MONITORING_APP_ADMIN_PORT)',
|
|
180
|
+
)
|
|
181
|
+
parser.add_argument(
|
|
182
|
+
'--version',
|
|
183
|
+
action='version',
|
|
184
|
+
version=f'%(prog)s {get_package_version()}',
|
|
185
|
+
)
|
|
186
|
+
return parser
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def main(argv: list[str] | None = None) -> None:
|
|
190
|
+
try:
|
|
191
|
+
import uvicorn
|
|
192
|
+
except ImportError:
|
|
193
|
+
logger.error('Admin dependencies missing — run: pip install --upgrade monitoring-app')
|
|
194
|
+
raise SystemExit(1) from None
|
|
195
|
+
|
|
196
|
+
args = build_cli_parser().parse_args(argv)
|
|
197
|
+
|
|
198
|
+
logging.basicConfig(
|
|
199
|
+
level=logging.INFO,
|
|
200
|
+
format='%(asctime)s %(levelname)s %(name)s: %(message)s',
|
|
201
|
+
)
|
|
202
|
+
log_file = os.environ.get('MONITORING_APP_LOG_FILE', '').strip()
|
|
203
|
+
if log_file:
|
|
204
|
+
from monitoring_app.monitor.logs import attach_monitor_file_log
|
|
205
|
+
|
|
206
|
+
attach_monitor_file_log(log_file)
|
|
207
|
+
try:
|
|
208
|
+
_ensure_monitor_root()
|
|
209
|
+
get_package_version.cache_clear()
|
|
210
|
+
version = get_package_version()
|
|
211
|
+
policy = load_policy()
|
|
212
|
+
from monitoring_app.config.paths import resolve_work_dir
|
|
213
|
+
from monitoring_app.config.settings import auto_migrate_on_startup
|
|
214
|
+
|
|
215
|
+
auto_migrate_on_startup(resolve_work_dir(policy))
|
|
216
|
+
except Exception:
|
|
217
|
+
logger.exception('Admin API startup failed — check auth.policy and pip install monitoring-app[admin]')
|
|
218
|
+
raise SystemExit(1) from None
|
|
219
|
+
|
|
220
|
+
if policy.read_session_secret() == 'dev-insecure-change-me':
|
|
221
|
+
logger.warning(
|
|
222
|
+
'Using default session secret — set MONITORING_APP_ADMIN_SESSION_SECRET for production',
|
|
223
|
+
)
|
|
224
|
+
logger.info('Starting Inferyx Monitoring Admin API v%s on %s:%s', version, args.host, args.port)
|
|
225
|
+
try:
|
|
226
|
+
uvicorn.run(
|
|
227
|
+
'monitoring_app.admin.app:app',
|
|
228
|
+
host=args.host,
|
|
229
|
+
port=args.port,
|
|
230
|
+
reload=False,
|
|
231
|
+
)
|
|
232
|
+
except Exception:
|
|
233
|
+
logger.exception('Admin API exited with an error')
|
|
234
|
+
raise SystemExit(1) from None
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
if __name__ == '__main__':
|
|
238
|
+
main()
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Append-only admin audit log (JSON Lines) with optional retention cleanup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
from datetime import datetime, timedelta, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
_CONTROL_CHARS = re.compile(r'[\x00-\x1f\x7f]')
|
|
14
|
+
_logger = logging.getLogger(__name__)
|
|
15
|
+
_LAST_CLEANUP: dict[str, float] = {}
|
|
16
|
+
_CLEANUP_EVERY_SEC = 12 * 3600
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _now_iso() -> str:
|
|
20
|
+
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _sanitize_field(value: str, *, max_len: int = 320) -> str:
|
|
24
|
+
cleaned = _CONTROL_CHARS.sub('', value).strip()
|
|
25
|
+
return cleaned[:max_len]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _parse_entry_timestamp(raw: object) -> datetime | None:
|
|
29
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
30
|
+
return None
|
|
31
|
+
text = raw.strip()
|
|
32
|
+
try:
|
|
33
|
+
if text.endswith('Z'):
|
|
34
|
+
text = text[:-1] + '+00:00'
|
|
35
|
+
dt = datetime.fromisoformat(text)
|
|
36
|
+
if dt.tzinfo is None:
|
|
37
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
38
|
+
return dt.astimezone(timezone.utc)
|
|
39
|
+
except ValueError:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _positive_days(raw: object, default: int = 30) -> int:
|
|
44
|
+
"""Parse a day count. 0 means keep forever. Invalid values fall back to default."""
|
|
45
|
+
text = str(raw or '').strip()
|
|
46
|
+
if not text:
|
|
47
|
+
return default
|
|
48
|
+
match = re.match(r'^(\d+)', text)
|
|
49
|
+
if not match:
|
|
50
|
+
return default
|
|
51
|
+
return max(0, int(match.group(1)))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def audit_retention_days(env_file: str | Path | None = None) -> int:
|
|
55
|
+
"""Days to keep audit entries (0 = keep forever). Prefers .env file, then process env."""
|
|
56
|
+
raw = ''
|
|
57
|
+
if env_file:
|
|
58
|
+
try:
|
|
59
|
+
from monitoring_app.config.env_editor import parse_env_file
|
|
60
|
+
|
|
61
|
+
_lines, values = parse_env_file(Path(env_file))
|
|
62
|
+
raw = (values.get('MONITORING_APP_AUDIT_RETENTION_DAYS') or '').strip()
|
|
63
|
+
except Exception: # noqa: BLE001
|
|
64
|
+
raw = ''
|
|
65
|
+
if not raw:
|
|
66
|
+
raw = os.getenv('MONITORING_APP_AUDIT_RETENTION_DAYS', '30').strip()
|
|
67
|
+
return _positive_days(raw, 30)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cleanup_audit(
|
|
71
|
+
log_path: str,
|
|
72
|
+
*,
|
|
73
|
+
retention_days: int | None = None,
|
|
74
|
+
env_file: str | Path | None = None,
|
|
75
|
+
) -> int:
|
|
76
|
+
"""Drop audit JSON lines older than retention. Returns number of removed entries.
|
|
77
|
+
|
|
78
|
+
Non-JSON lines (e.g. if path accidentally points at a mixed log) are preserved.
|
|
79
|
+
"""
|
|
80
|
+
days = (
|
|
81
|
+
max(0, int(retention_days))
|
|
82
|
+
if retention_days is not None
|
|
83
|
+
else audit_retention_days(env_file)
|
|
84
|
+
)
|
|
85
|
+
if days <= 0:
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
path = Path(log_path)
|
|
89
|
+
if not path.is_file():
|
|
90
|
+
return 0
|
|
91
|
+
# Never treat the rotating monitor log as the audit file.
|
|
92
|
+
if path.name.lower().startswith('monitor.log'):
|
|
93
|
+
_logger.warning('Audit cleanup skipped — path looks like monitor.log: %s', path)
|
|
94
|
+
return 0
|
|
95
|
+
now = datetime.now(timezone.utc).timestamp()
|
|
96
|
+
last = _LAST_CLEANUP.get(str(path))
|
|
97
|
+
if last and (now - last) < _CLEANUP_EVERY_SEC:
|
|
98
|
+
return 0
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
lines = path.read_text(encoding='utf-8').splitlines()
|
|
102
|
+
except OSError as exc:
|
|
103
|
+
_logger.warning('Audit cleanup skipped (read failed): %s', exc)
|
|
104
|
+
return 0
|
|
105
|
+
|
|
106
|
+
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
|
107
|
+
kept: list[str] = []
|
|
108
|
+
removed = 0
|
|
109
|
+
for line in lines:
|
|
110
|
+
stripped = line.strip()
|
|
111
|
+
if not stripped:
|
|
112
|
+
continue
|
|
113
|
+
try:
|
|
114
|
+
payload = json.loads(stripped)
|
|
115
|
+
except json.JSONDecodeError:
|
|
116
|
+
kept.append(line)
|
|
117
|
+
continue
|
|
118
|
+
if not isinstance(payload, dict):
|
|
119
|
+
kept.append(line)
|
|
120
|
+
continue
|
|
121
|
+
ts = _parse_entry_timestamp(payload.get('timestamp'))
|
|
122
|
+
# Keep undated lines. Only drop entries older than the retention window.
|
|
123
|
+
if ts is not None and ts < cutoff:
|
|
124
|
+
removed += 1
|
|
125
|
+
continue
|
|
126
|
+
kept.append(json.dumps(payload, ensure_ascii=False))
|
|
127
|
+
|
|
128
|
+
if removed <= 0:
|
|
129
|
+
_LAST_CLEANUP[str(path)] = now
|
|
130
|
+
return 0
|
|
131
|
+
# Keep the file intact if cleanup would drop everything including recent rows.
|
|
132
|
+
if not kept:
|
|
133
|
+
_logger.warning('Audit cleanup skipped — would remove all %s entries', removed)
|
|
134
|
+
return 0
|
|
135
|
+
|
|
136
|
+
text = '\n'.join(kept)
|
|
137
|
+
if text:
|
|
138
|
+
text += '\n'
|
|
139
|
+
try:
|
|
140
|
+
fd, tmp_name = tempfile.mkstemp(prefix='.admin-audit-', dir=str(path.parent))
|
|
141
|
+
tmp_path = Path(tmp_name)
|
|
142
|
+
try:
|
|
143
|
+
with open(fd, 'w', encoding='utf-8') as handle:
|
|
144
|
+
handle.write(text)
|
|
145
|
+
tmp_path.replace(path)
|
|
146
|
+
finally:
|
|
147
|
+
if tmp_path.exists():
|
|
148
|
+
tmp_path.unlink(missing_ok=True)
|
|
149
|
+
except OSError as exc:
|
|
150
|
+
_logger.warning('Audit cleanup skipped (write failed): %s', exc)
|
|
151
|
+
return 0
|
|
152
|
+
_LAST_CLEANUP[str(path)] = now
|
|
153
|
+
_logger.info(
|
|
154
|
+
'Audit cleanup removed %s entr%s older than %s day(s); kept %s',
|
|
155
|
+
removed,
|
|
156
|
+
'y' if removed == 1 else 'ies',
|
|
157
|
+
days,
|
|
158
|
+
len(kept),
|
|
159
|
+
)
|
|
160
|
+
return removed
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def write_audit(
|
|
164
|
+
log_path: str,
|
|
165
|
+
*,
|
|
166
|
+
actor: str,
|
|
167
|
+
action: str,
|
|
168
|
+
detail: dict | None = None,
|
|
169
|
+
env_file: str | Path | None = None,
|
|
170
|
+
) -> None:
|
|
171
|
+
path = Path(log_path)
|
|
172
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
173
|
+
entry = {
|
|
174
|
+
'timestamp': _now_iso(),
|
|
175
|
+
'actor': _sanitize_field(actor),
|
|
176
|
+
'action': _sanitize_field(action, max_len=64),
|
|
177
|
+
'detail': detail or {},
|
|
178
|
+
}
|
|
179
|
+
with path.open('a', encoding='utf-8') as handle:
|
|
180
|
+
handle.write(json.dumps(entry, ensure_ascii=False) + '\n')
|
|
181
|
+
try:
|
|
182
|
+
cleanup_audit(log_path, env_file=env_file)
|
|
183
|
+
except Exception as exc: # noqa: BLE001 — never fail the caller on cleanup
|
|
184
|
+
_logger.debug('Audit cleanup after write failed: %s', exc)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def read_audit(
|
|
188
|
+
log_path: str,
|
|
189
|
+
limit: int = 100,
|
|
190
|
+
*,
|
|
191
|
+
env_file: str | Path | None = None,
|
|
192
|
+
entity_id: str | None = None,
|
|
193
|
+
) -> list[dict]:
|
|
194
|
+
safe_limit = max(1, min(int(limit), 500))
|
|
195
|
+
path = Path(log_path)
|
|
196
|
+
if not path.is_file():
|
|
197
|
+
return []
|
|
198
|
+
|
|
199
|
+
entity_key = str(entity_id or '').strip()
|
|
200
|
+
lines = path.read_text(encoding='utf-8').splitlines()
|
|
201
|
+
entries: list[dict] = []
|
|
202
|
+
for line in lines:
|
|
203
|
+
line = line.strip()
|
|
204
|
+
if not line:
|
|
205
|
+
continue
|
|
206
|
+
try:
|
|
207
|
+
payload = json.loads(line)
|
|
208
|
+
except json.JSONDecodeError:
|
|
209
|
+
continue
|
|
210
|
+
if isinstance(payload, dict) and payload.get('action'):
|
|
211
|
+
if entity_key:
|
|
212
|
+
detail = payload.get('detail') or {}
|
|
213
|
+
if not isinstance(detail, dict):
|
|
214
|
+
continue
|
|
215
|
+
if str(detail.get('entity_id') or '').strip() != entity_key:
|
|
216
|
+
continue
|
|
217
|
+
entries.append(payload)
|
|
218
|
+
entries.reverse()
|
|
219
|
+
return entries[:safe_limit]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Dashboard data: status rows, alert summary and charts, batch log summaries."""
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Alert counts and chart series for the dashboard (events come from alerts.db)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from monitoring_app.admin.dashboard.batch_insights import _advance, _calendar_windows, _current_chart_args
|
|
9
|
+
|
|
10
|
+
_ISSUES = ('failed', 'missed', 'no_data')
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _empty_alerts() -> dict[str, int]:
|
|
14
|
+
return {key: 0 for key in _ISSUES}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _count_alerts(
|
|
18
|
+
events: list[dict[str, Any]],
|
|
19
|
+
start: datetime.datetime,
|
|
20
|
+
end: datetime.datetime,
|
|
21
|
+
) -> dict[str, int]:
|
|
22
|
+
counts = _empty_alerts()
|
|
23
|
+
for event in events:
|
|
24
|
+
when = event.get('when')
|
|
25
|
+
issue = event.get('issue')
|
|
26
|
+
if isinstance(when, datetime.datetime) and issue in counts and start <= when < end:
|
|
27
|
+
counts[issue] += 1
|
|
28
|
+
return counts
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _alert_series(events: list[dict[str, Any]], kind: str) -> list[dict[str, Any]]:
|
|
32
|
+
starts, label_fn, step = _current_chart_args(kind)
|
|
33
|
+
series = []
|
|
34
|
+
for start in starts:
|
|
35
|
+
end = _advance(start, step)
|
|
36
|
+
point = {'date': label_fn(start), **_empty_alerts(), 'completed': 0}
|
|
37
|
+
counts = _count_alerts(events, start, end)
|
|
38
|
+
point.update(counts)
|
|
39
|
+
series.append(point)
|
|
40
|
+
return series
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def alert_dashboard_payload(events: list[dict[str, Any]]) -> dict[str, Any]:
|
|
44
|
+
windows = _calendar_windows()
|
|
45
|
+
periods = {
|
|
46
|
+
key: _count_alerts(events, start, end)
|
|
47
|
+
for key, (start, end) in windows.items()
|
|
48
|
+
}
|
|
49
|
+
rows = sorted(events, key=lambda item: item['when'], reverse=True)[:200]
|
|
50
|
+
return {
|
|
51
|
+
'current': periods['now'],
|
|
52
|
+
'periods': {
|
|
53
|
+
'day': periods['day'],
|
|
54
|
+
'week': periods['week'],
|
|
55
|
+
'month': periods['month'],
|
|
56
|
+
'quarter': periods['quarter'],
|
|
57
|
+
'year': periods['year'],
|
|
58
|
+
},
|
|
59
|
+
'charts': {
|
|
60
|
+
'daily': _alert_series(events, 'day'),
|
|
61
|
+
'weekly': _alert_series(events, 'week'),
|
|
62
|
+
'monthly': _alert_series(events, 'month'),
|
|
63
|
+
'quarterly': _alert_series(events, 'quarter'),
|
|
64
|
+
'yearly': _alert_series(events, 'year'),
|
|
65
|
+
},
|
|
66
|
+
'rows': [
|
|
67
|
+
{'name': row['name'], 'issue': row['issue'], 'at': row['at']}
|
|
68
|
+
for row in rows
|
|
69
|
+
],
|
|
70
|
+
'meta': {'alert_count': len(events)},
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def empty_alert_dashboard() -> dict[str, Any]:
|
|
75
|
+
return alert_dashboard_payload([])
|