keepup-admin 0.1.0__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 keepup-admin might be problematic. Click here for more details.

Files changed (86) hide show
  1. keepup/THIRD-PARTY.md +44 -0
  2. keepup/__init__.py +41 -0
  3. keepup/api_versions.py +100 -0
  4. keepup/audit.py +499 -0
  5. keepup/auth/__init__.py +7 -0
  6. keepup/auth/config.py +128 -0
  7. keepup/auth/dependencies.py +485 -0
  8. keepup/auth/dto/__init__.py +0 -0
  9. keepup/auth/dto/token.py +31 -0
  10. keepup/auth/factory.py +28 -0
  11. keepup/auth/login_throttle.py +151 -0
  12. keepup/auth/oidc.py +245 -0
  13. keepup/auth/oidc_policy.py +111 -0
  14. keepup/auth/oidc_routes.py +288 -0
  15. keepup/auth/panel_session.py +220 -0
  16. keepup/auth/permissions.py +59 -0
  17. keepup/auth/providers/__init__.py +0 -0
  18. keepup/auth/providers/base.py +168 -0
  19. keepup/auth/providers/local.py +180 -0
  20. keepup/auth/routes.py +660 -0
  21. keepup/auth/seed_accounts.py +322 -0
  22. keepup/auth/session_lifetime.py +104 -0
  23. keepup/auth/signing_key.py +138 -0
  24. keepup/auth/websocket.py +86 -0
  25. keepup/cluster.py +634 -0
  26. keepup/db.py +663 -0
  27. keepup/events.py +764 -0
  28. keepup/factory.py +484 -0
  29. keepup/instance.py +46 -0
  30. keepup/integrations.py +260 -0
  31. keepup/locks.py +412 -0
  32. keepup/logging_setup.py +690 -0
  33. keepup/metrics.py +818 -0
  34. keepup/metrics_retention.py +376 -0
  35. keepup/modules.py +572 -0
  36. keepup/notification_bus.py +355 -0
  37. keepup/plugins/__init__.py +9 -0
  38. keepup/plugins/admin.py +246 -0
  39. keepup/plugins/base.py +234 -0
  40. keepup/plugins/enablement.py +184 -0
  41. keepup/plugins/registry.py +171 -0
  42. keepup/plugins/route_mask.py +338 -0
  43. keepup/plugins/routes.py +376 -0
  44. keepup/roles.py +17 -0
  45. keepup/scheduler.py +93 -0
  46. keepup/schema.py +295 -0
  47. keepup/sections.json +104 -0
  48. keepup/settings.py +184 -0
  49. keepup/static/css/aos.css +1 -0
  50. keepup/static/css/main_nebula.css +232 -0
  51. keepup/static/css/main_new.css +852 -0
  52. keepup/static/css/tailwind.css +1 -0
  53. keepup/static/index_nebula.html +293 -0
  54. keepup/static/index_new.html +286 -0
  55. keepup/static/js/aos.js +1 -0
  56. keepup/static/js/feather-icons.js +13 -0
  57. keepup/static/js/main_new.js +1861 -0
  58. keepup/static/js/tailwind.js +83 -0
  59. keepup/static/modules/css/background_tasks.css +233 -0
  60. keepup/static/modules/css/cluster.css +16 -0
  61. keepup/static/modules/css/event_manager.css +386 -0
  62. keepup/static/modules/css/integration_logs.css +33 -0
  63. keepup/static/modules/css/metrics.css +115 -0
  64. keepup/static/modules/css/modules.css +189 -0
  65. keepup/static/modules/css/themes.css +563 -0
  66. keepup/static/modules/css/users.css +278 -0
  67. keepup/static/modules/js/background_tasks.js +657 -0
  68. keepup/static/modules/js/chart.js +14 -0
  69. keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
  70. keepup/static/modules/js/cluster.js +363 -0
  71. keepup/static/modules/js/event_manager.js +979 -0
  72. keepup/static/modules/js/integration_logs.js +767 -0
  73. keepup/static/modules/js/metrics.js +908 -0
  74. keepup/static/modules/js/modules.js +1086 -0
  75. keepup/static/modules/js/themes.js +653 -0
  76. keepup/static/modules/js/users.js +784 -0
  77. keepup/tables.py +302 -0
  78. keepup/themes.py +496 -0
  79. keepup/web.py +182 -0
  80. keepup_admin-0.1.0.dist-info/METADATA +117 -0
  81. keepup_admin-0.1.0.dist-info/RECORD +86 -0
  82. keepup_admin-0.1.0.dist-info/WHEEL +5 -0
  83. keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
  84. keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
  85. keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
  86. keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
keepup/metrics.py ADDED
@@ -0,0 +1,818 @@
1
+ """Metrics of the process and the machine it runs on.
2
+
3
+ Two consumers, one collection: Prometheus scrapes `/metrics`, and the panel
4
+ reads a table of snapshots written by the same pass. They used to be collected
5
+ separately, which is how the table stayed empty while the scrape looked
6
+ healthy.
7
+
8
+ What the collector writes is declared here as names (`METRIC_GROUPS`,
9
+ `SNAPSHOT_METRIC_NAMES`), because a second reader needs them: the retention
10
+ sweep (`keepup/metrics_retention.py`) has to tell a measurement from another
11
+ module's row in the same table.
12
+ """
13
+
14
+ import asyncio
15
+ import logging
16
+ import os
17
+ from datetime import datetime, timedelta
18
+ from typing import Any, Dict, List, Optional, Set, Tuple
19
+
20
+ import psutil
21
+ from fastapi import Depends, HTTPException, Query, status
22
+ from fastapi.responses import Response as FastAPIResponse
23
+ from prometheus_client import CONTENT_TYPE_LATEST, Counter, Gauge, Histogram, REGISTRY, generate_latest
24
+ from pydantic import BaseModel
25
+
26
+ from keepup.auth.dependencies import get_current_admin
27
+ from keepup.db import DatabaseManager, DatabaseManagerV2, db_config
28
+ from keepup.instance import get_instance_id, get_instance_name
29
+ from keepup.roles import ROLE_ADMIN
30
+
31
+ #: What an application may import from this module. Everything else is
32
+ #: internal and may change without notice -- see doc/keepup.md.
33
+ __all__ = [
34
+ "SystemMetricsCollector",
35
+ "metrics_collector",
36
+ "register_metrics_routes",
37
+ "update_metrics_background",
38
+ ]
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ #: How often metrics are refreshed. Fifteen seconds is what the system lived
43
+ #: with and still lives with: that was hard-coded in the background loop. The
44
+ #: number is named here because there used to be two of them -- a configurable
45
+ #: `collection_interval` nobody read, and a constant in the loop that could not
46
+ #: be configured.
47
+ DEFAULT_INTERVAL_SECONDS = 15
48
+ #: How long to wait after an error: no hammering while the cause is still there.
49
+ ERROR_BACKOFF_SECONDS = 30
50
+
51
+ #: Exactly what the collector writes, by the groups metric exclusion works in
52
+ #: (`EXCLUDED_METRIC_GROUPS`). The list lives here rather than on the instance
53
+ #: because it now has two readers: the collector itself and the retention
54
+ #: sweep, which has to tell a measurement from another module's row in the same
55
+ #: table.
56
+ METRIC_GROUPS: Dict[str, List[str]] = {
57
+ 'cpu': [
58
+ 'cpu.percent.total', 'cpu.percent.avg_per_core',
59
+ 'cpu.cores.logical', 'cpu.cores.physical', 'process.cpu.percent'
60
+ ],
61
+ 'ram': [
62
+ 'memory.total', 'memory.available', 'memory.used', 'memory.percent',
63
+ 'memory.free', 'swap.total', 'swap.used', 'swap.percent',
64
+ 'process.memory.rss', 'process.memory.vms'
65
+ ],
66
+ 'disk': [
67
+ 'disk.total', 'disk.used', 'disk.free', 'disk.percent',
68
+ 'disk.read_bytes', 'disk.write_bytes'
69
+ ],
70
+ 'network': ['network.bytes_sent', 'network.bytes_recv'],
71
+ 'process': ['process.threads.count', 'process.open_files'],
72
+ }
73
+
74
+ #: The names the collector writes, as one set -- this is what "a snapshot"
75
+ #: means to the retention sweep.
76
+ SNAPSHOT_METRIC_NAMES: Set[str] = {
77
+ name for names in METRIC_GROUPS.values() for name in names
78
+ }
79
+
80
+
81
+ def _registry_names(metric_name: str) -> Set[str]:
82
+ """The names a metric may already be registered under in Prometheus.
83
+
84
+ Args:
85
+ metric_name: the name the collector uses.
86
+
87
+ Returns:
88
+ Every name to look for, since Counter appends `_total` itself.
89
+ """
90
+ names = {metric_name}
91
+ if metric_name.endswith("_total"):
92
+ names.add(metric_name[: -len("_total")])
93
+ return names
94
+
95
+
96
+ class SystemMetricsCollector:
97
+ """Collects metrics of the process and of the machine.
98
+
99
+ An ordinary object, not a singleton. The singleton solved one problem --
100
+ "let there be one collector in the application" -- and solved it in a way
101
+ that silently lost settings: a second call of the constructor returned the
102
+ first instance and threw the arguments away. Asking for a thirty-second
103
+ interval gave you sixty and said nothing about it.
104
+
105
+ The application's shared collector is the module-level `metrics_collector`
106
+ below; take it by name. Creating your own gives you your own object and
107
+ does not disturb the shared one.
108
+ """
109
+
110
+ _registered_metrics = set()
111
+
112
+ def __init__(self,
113
+ collection_interval: int = DEFAULT_INTERVAL_SECONDS,
114
+ excluded_metrics: Optional[List[str]] = None):
115
+ self.collection_interval = collection_interval
116
+ self.app_instance = os.getenv('APP_INSTANCE', 'main')
117
+ self.excluded_metrics: Set[str] = set(excluded_metrics or [])
118
+
119
+ # Its own copy of the list: excluding a metric edits these lists, and
120
+ # one collector's edit must not reach the retention sweep or the
121
+ # collector next to it.
122
+ self.metric_groups = {group: list(names) for group, names in METRIC_GROUPS.items()}
123
+
124
+ self.prometheus_metrics = self._init_prometheus_metrics()
125
+
126
+ # The processor load of the pass being collected: read once and shared by
127
+ # everything that wants it (see `_cpu_load`).
128
+ self._cpu_load: Optional[Tuple[float, List[float]]] = None
129
+
130
+ logger.info(f"Metrics collector initialized for instance: {self.app_instance}")
131
+ logger.info(f"Excluded metrics: {self.excluded_metrics}")
132
+
133
+ def _init_prometheus_metrics(self) -> Dict:
134
+ """Initialise the Prometheus metrics, tolerating already-registered collectors."""
135
+ metrics = {}
136
+
137
+ metric_definitions = {
138
+ 'cpu_usage_percent': ('cpu_usage_percent', Gauge, 'Current CPU usage percentage', ['instance']),
139
+ 'cpu_usage_per_core_percent': (
140
+ 'cpu_usage_per_core_percent', Gauge, 'CPU usage percentage per core', ['instance', 'core']),
141
+ 'cpu_cores_logical': ('cpu_cores_logical', Gauge, 'Number of logical CPU cores', ['instance']),
142
+ 'cpu_cores_physical': ('cpu_cores_physical', Gauge, 'Number of physical CPU cores', ['instance']),
143
+ 'memory_total_bytes': ('memory_total_bytes', Gauge, 'Total memory in bytes', ['instance']),
144
+ 'memory_available_bytes': ('memory_available_bytes', Gauge, 'Available memory in bytes', ['instance']),
145
+ 'memory_used_bytes': ('memory_used_bytes', Gauge, 'Used memory in bytes', ['instance']),
146
+ 'memory_usage_percent': ('memory_usage_percent', Gauge, 'Memory usage percentage', ['instance']),
147
+ 'memory_free_bytes': ('memory_free_bytes', Gauge, 'Free memory in bytes', ['instance']),
148
+ 'swap_total_bytes': ('swap_total_bytes', Gauge, 'Total swap in bytes', ['instance']),
149
+ 'swap_used_bytes': ('swap_used_bytes', Gauge, 'Used swap in bytes', ['instance']),
150
+ 'swap_usage_percent': ('swap_usage_percent', Gauge, 'Swap usage percentage', ['instance']),
151
+ 'disk_total_bytes': ('disk_total_bytes', Gauge, 'Total disk space in bytes', ['instance']),
152
+ 'disk_used_bytes': ('disk_used_bytes', Gauge, 'Used disk space in bytes', ['instance']),
153
+ 'disk_free_bytes': ('disk_free_bytes', Gauge, 'Free disk space in bytes', ['instance']),
154
+ 'disk_usage_percent': ('disk_usage_percent', Gauge, 'Disk usage percentage', ['instance']),
155
+ 'disk_read_bytes_total': ('disk_read_bytes_total', Gauge, 'Total bytes read from disk', ['instance']),
156
+ 'disk_write_bytes_total': ('disk_write_bytes_total', Gauge, 'Total bytes written to disk', ['instance']),
157
+ 'network_bytes_sent_total': (
158
+ 'network_bytes_sent_total', Gauge, 'Total bytes sent over network', ['instance']),
159
+ 'network_bytes_received_total': (
160
+ 'network_bytes_received_total', Gauge, 'Total bytes received over network', ['instance']),
161
+ 'process_cpu_seconds_total': (
162
+ 'app_process_cpu_seconds_total', Gauge, 'Total CPU time spent by process', ['instance']),
163
+ 'process_memory_rss_bytes': (
164
+ 'process_memory_rss_bytes', Gauge, 'Resident memory size of process', ['instance']),
165
+ 'process_memory_vms_bytes': (
166
+ 'process_memory_vms_bytes', Gauge, 'Virtual memory size of process', ['instance']),
167
+ 'process_threads_count': ('process_threads_count', Gauge, 'Number of threads in process', ['instance']),
168
+ 'process_open_files_count': (
169
+ 'process_open_files_count', Gauge, 'Number of open files by process', ['instance']),
170
+ 'http_requests_total': (
171
+ 'http_requests_total', Counter, 'Total HTTP requests', ['instance', 'method', 'endpoint', 'status']),
172
+ 'http_request_duration_seconds': (
173
+ 'http_request_duration_seconds', Histogram, 'HTTP request duration in seconds',
174
+ ['instance', 'method', 'endpoint']),
175
+ }
176
+
177
+ for key, (metric_name, metric_class, description, labels) in metric_definitions.items():
178
+ try:
179
+ existing_metric = None
180
+
181
+ for collector in list(REGISTRY._collector_to_names.keys()):
182
+ # A counter is registered under the name without
183
+ # `_total`: Counter appends the suffix itself. Matching on
184
+ # the full name alone never found the counter that was
185
+ # already there, creating it a second time failed as a
186
+ # duplicate, and the fallback path registered a metric with
187
+ # a numeric suffix in its name -- rubbish in the registry.
188
+ if hasattr(collector, '_name') and collector._name in _registry_names(metric_name):
189
+ if isinstance(collector, metric_class):
190
+ existing_metric = collector
191
+ break
192
+ else:
193
+ # A different collector type under the same name (ProcessCollector instead of
194
+ # Gauge, say) is dropped from the registry so the right one can be created.
195
+ logger.warning(
196
+ f"Found existing collector {metric_name} of wrong type {type(collector)}, removing it")
197
+ try:
198
+ REGISTRY.unregister(collector)
199
+ except:
200
+ pass
201
+
202
+ if existing_metric:
203
+ metrics[key] = existing_metric
204
+ logger.debug(f"Using existing metric: {metric_name}")
205
+ else:
206
+ if metric_class == Gauge:
207
+ metrics[key] = Gauge(metric_name, description, labels)
208
+ elif metric_class == Counter:
209
+ metrics[key] = Counter(metric_name, description, labels)
210
+ elif metric_class == Histogram:
211
+ metrics[key] = Histogram(metric_name, description, labels)
212
+ logger.debug(f"Created new metric: {metric_name}")
213
+
214
+ except Exception as e:
215
+ logger.warning(f"Error registering metric {metric_name}: {str(e)}")
216
+ # Fall back to a uniquely suffixed name rather than losing the metric entirely.
217
+ try:
218
+ unique_name = f"{metric_name}_{id(self)}"
219
+ if metric_class == Gauge:
220
+ metrics[key] = Gauge(unique_name, description, labels)
221
+ elif metric_class == Counter:
222
+ metrics[key] = Counter(unique_name, description, labels)
223
+ elif metric_class == Histogram:
224
+ metrics[key] = Histogram(unique_name, description, labels)
225
+ logger.debug(f"Created metric with unique name: {unique_name}")
226
+ except:
227
+ pass
228
+
229
+ return metrics
230
+
231
+ def exclude_group(self, group_name: str):
232
+ if group_name in self.metric_groups:
233
+ self.excluded_metrics.update(self.metric_groups[group_name])
234
+ logger.info(f"Excluded metric group '{group_name}': {len(self.metric_groups[group_name])} metrics")
235
+
236
+ def exclude_metric(self, metric_name: str):
237
+ self.excluded_metrics.add(metric_name)
238
+
239
+ def include_group(self, group_name: str):
240
+ if group_name in self.metric_groups:
241
+ for metric in self.metric_groups[group_name]:
242
+ self.excluded_metrics.discard(metric)
243
+
244
+ def should_collect(self, metric_name: str) -> bool:
245
+ return metric_name not in self.excluded_metrics
246
+
247
+ def sample_cpu(self) -> Tuple[float, List[float]]:
248
+ """The processor load since the previous pass: total, and per core.
249
+
250
+ `psutil.cpu_percent(interval=1)` does not measure for a second -- it
251
+ *sleeps* for one, and a coroutine that sleeps like that stops the whole
252
+ event loop with it. A pass asked four times over (here twice, in
253
+ Prometheus twice more), so every collection interval the process stood
254
+ still for four seconds: no requests answered, no sockets served, and, in
255
+ an application with a game in it, every room's step loop stopped dead --
256
+ measured as four-second gaps in rooms that know nothing of each other.
257
+
258
+ With no interval psutil compares against its own previous reading, which
259
+ is exactly what a loop that comes back every few seconds wants, and
260
+ returns at once. The very first reading has nothing to compare against
261
+ and is 0.0 by definition; that is one pass of a process's life.
262
+
263
+ The reading is taken once and kept for the pass: two readings a
264
+ microsecond apart would compare against each other and measure noise.
265
+ """
266
+ total = psutil.cpu_percent(interval=None)
267
+ per_core = psutil.cpu_percent(interval=None, percpu=True)
268
+ # A machine with one core -- and a stand-in in a test -- answers with a number
269
+ # rather than a list, and a list is what everything downstream averages.
270
+ if not isinstance(per_core, (list, tuple)):
271
+ per_core = [float(per_core or 0.0)]
272
+ self._cpu_load = (total, list(per_core))
273
+ return self._cpu_load
274
+
275
+ def cpu_load(self) -> Tuple[float, List[float]]:
276
+ """This pass's reading, taken if the pass has not taken one yet."""
277
+ return self._cpu_load if self._cpu_load is not None else self.sample_cpu()
278
+
279
+ def forget_cpu_load(self) -> None:
280
+ """The pass is over: the next one reads the load again."""
281
+ self._cpu_load = None
282
+
283
+ async def collect_metrics(self) -> Dict[str, float]:
284
+ try:
285
+ metrics = {}
286
+ total_cpu, per_core = self.sample_cpu()
287
+
288
+ if self.should_collect('cpu.percent.total'):
289
+ metrics['cpu.percent.total'] = total_cpu
290
+
291
+ if self.should_collect('cpu.percent.avg_per_core'):
292
+ # An average, not a list: the name promises an average, the
293
+ # snapshot table holds a number, and a list failed the whole
294
+ # batch insert -- together with twenty-four sound values. The
295
+ # per-core breakdown goes to Prometheus, where it has a `core`
296
+ # label of its own.
297
+ if isinstance(per_core, (list, tuple)):
298
+ metrics['cpu.percent.avg_per_core'] = (
299
+ sum(per_core) / len(per_core) if per_core else 0.0)
300
+ else:
301
+ # Not a list means it is already a single number.
302
+ metrics['cpu.percent.avg_per_core'] = float(per_core or 0.0)
303
+
304
+ if self.should_collect('cpu.cores.logical'):
305
+ metrics['cpu.cores.logical'] = psutil.cpu_count(logical=True)
306
+
307
+ if self.should_collect('cpu.cores.physical'):
308
+ metrics['cpu.cores.physical'] = psutil.cpu_count(logical=False)
309
+
310
+ memory = psutil.virtual_memory()
311
+ if self.should_collect('memory.total'):
312
+ metrics['memory.total'] = memory.total
313
+ if self.should_collect('memory.available'):
314
+ metrics['memory.available'] = memory.available
315
+ if self.should_collect('memory.used'):
316
+ metrics['memory.used'] = memory.used
317
+ if self.should_collect('memory.percent'):
318
+ metrics['memory.percent'] = memory.percent
319
+ if self.should_collect('memory.free'):
320
+ metrics['memory.free'] = memory.free
321
+
322
+ swap = psutil.swap_memory()
323
+ if self.should_collect('swap.total'):
324
+ metrics['swap.total'] = swap.total
325
+ if self.should_collect('swap.used'):
326
+ metrics['swap.used'] = swap.used
327
+ if self.should_collect('swap.percent'):
328
+ metrics['swap.percent'] = swap.percent
329
+
330
+ disk_usage = psutil.disk_usage('/')
331
+ disk_io = psutil.disk_io_counters()
332
+
333
+ if self.should_collect('disk.total'):
334
+ metrics['disk.total'] = disk_usage.total
335
+ if self.should_collect('disk.used'):
336
+ metrics['disk.used'] = disk_usage.used
337
+ if self.should_collect('disk.free'):
338
+ metrics['disk.free'] = disk_usage.free
339
+ if self.should_collect('disk.percent'):
340
+ metrics['disk.percent'] = disk_usage.percent
341
+ if self.should_collect('disk.read_bytes') and disk_io:
342
+ metrics['disk.read_bytes'] = disk_io.read_bytes
343
+ if self.should_collect('disk.write_bytes') and disk_io:
344
+ metrics['disk.write_bytes'] = disk_io.write_bytes
345
+
346
+ net_io = psutil.net_io_counters()
347
+ if self.should_collect('network.bytes_sent') and net_io:
348
+ metrics['network.bytes_sent'] = net_io.bytes_sent
349
+ if self.should_collect('network.bytes_recv') and net_io:
350
+ metrics['network.bytes_recv'] = net_io.bytes_recv
351
+
352
+ process = psutil.Process()
353
+ process_memory = process.memory_info()
354
+
355
+ if self.should_collect('process.cpu.percent'):
356
+ metrics['process.cpu.percent'] = process.cpu_percent()
357
+ if self.should_collect('process.memory.rss'):
358
+ metrics['process.memory.rss'] = process_memory.rss
359
+ if self.should_collect('process.memory.vms'):
360
+ metrics['process.memory.vms'] = process_memory.vms
361
+ if self.should_collect('process.threads.count'):
362
+ metrics['process.threads.count'] = process.num_threads()
363
+ if self.should_collect('process.open_files'):
364
+ metrics['process.open_files'] = len(process.open_files()) if hasattr(process, 'open_files') else 0
365
+
366
+ logger.debug(f"Collected {len(metrics)} metrics (excluded {len(self.excluded_metrics)})")
367
+ return metrics
368
+
369
+ except Exception as e:
370
+ logger.error(f"Error collecting system metrics: {str(e)}")
371
+ return {}
372
+
373
+ def save_metrics_to_db(self, metrics: Dict[str, float]):
374
+ """Write a snapshot -- one path for both engines.
375
+
376
+ There used to be two: the `DatabaseManagerV2` pool on PostgreSQL, the
377
+ legacy manager with its own connection on SQLite. A second connection
378
+ to the same file ran into "database is locked", which meant that in
379
+ development snapshots were not saved at all, and the message about it
380
+ went into the log and was lost there.
381
+
382
+ Named parameters are understood by both engines, so branching bought
383
+ nothing here and cost a second way of doing one thing.
384
+
385
+ Args:
386
+ metrics: the values just collected, by metric name.
387
+ """
388
+ try:
389
+ timestamp = datetime.utcnow()
390
+ params_list = [{
391
+ "metric_name": name,
392
+ "metric_value": value,
393
+ "timestamp": timestamp,
394
+ "app_instance": self.app_instance,
395
+ } for name, value in metrics.items()]
396
+
397
+ if not params_list:
398
+ return
399
+
400
+ DatabaseManagerV2.execute_many(
401
+ "INSERT INTO system_metrics (metric_name, metric_value, timestamp, "
402
+ "app_instance) VALUES (:metric_name, :metric_value, :timestamp, "
403
+ ":app_instance)", params_list)
404
+ logger.debug(f"Saved {len(metrics)} system metrics to database")
405
+
406
+ except Exception as e:
407
+ # Metrics are a supporting thing: an application that fell over
408
+ # because it could not record its own load is worse than an
409
+ # application without metrics.
410
+ logger.error(f"Error saving metrics to database: {str(e)}")
411
+
412
+ def update_prometheus_metrics(self):
413
+ try:
414
+ # The pass's own reading, not two more seconds of a standing process.
415
+ total_cpu, cpu_per_core = self.cpu_load()
416
+ self.prometheus_metrics['cpu_usage_percent'].labels(instance=self.app_instance).set(
417
+ total_cpu
418
+ )
419
+
420
+ for i, value in enumerate(cpu_per_core):
421
+ self.prometheus_metrics['cpu_usage_per_core_percent'].labels(
422
+ instance=self.app_instance, core=str(i)
423
+ ).set(value)
424
+
425
+ self.prometheus_metrics['cpu_cores_logical'].labels(instance=self.app_instance).set(
426
+ psutil.cpu_count(logical=True)
427
+ )
428
+ self.prometheus_metrics['cpu_cores_physical'].labels(instance=self.app_instance).set(
429
+ psutil.cpu_count(logical=False)
430
+ )
431
+
432
+ memory = psutil.virtual_memory()
433
+ self.prometheus_metrics['memory_total_bytes'].labels(instance=self.app_instance).set(memory.total)
434
+ self.prometheus_metrics['memory_available_bytes'].labels(instance=self.app_instance).set(memory.available)
435
+ self.prometheus_metrics['memory_used_bytes'].labels(instance=self.app_instance).set(memory.used)
436
+ self.prometheus_metrics['memory_usage_percent'].labels(instance=self.app_instance).set(memory.percent)
437
+ self.prometheus_metrics['memory_free_bytes'].labels(instance=self.app_instance).set(memory.free)
438
+
439
+ swap = psutil.swap_memory()
440
+ self.prometheus_metrics['swap_total_bytes'].labels(instance=self.app_instance).set(swap.total)
441
+ self.prometheus_metrics['swap_used_bytes'].labels(instance=self.app_instance).set(swap.used)
442
+ self.prometheus_metrics['swap_usage_percent'].labels(instance=self.app_instance).set(swap.percent)
443
+
444
+ disk_usage = psutil.disk_usage('/')
445
+ self.prometheus_metrics['disk_total_bytes'].labels(instance=self.app_instance).set(disk_usage.total)
446
+ self.prometheus_metrics['disk_used_bytes'].labels(instance=self.app_instance).set(disk_usage.used)
447
+ self.prometheus_metrics['disk_free_bytes'].labels(instance=self.app_instance).set(disk_usage.free)
448
+ self.prometheus_metrics['disk_usage_percent'].labels(instance=self.app_instance).set(disk_usage.percent)
449
+
450
+ disk_io = psutil.disk_io_counters()
451
+ if disk_io:
452
+ self.prometheus_metrics['disk_read_bytes_total'].labels(instance=self.app_instance).set(
453
+ disk_io.read_bytes)
454
+ self.prometheus_metrics['disk_write_bytes_total'].labels(instance=self.app_instance).set(
455
+ disk_io.write_bytes)
456
+
457
+ net_io = psutil.net_io_counters()
458
+ if net_io:
459
+ self.prometheus_metrics['network_bytes_sent_total'].labels(instance=self.app_instance).set(
460
+ net_io.bytes_sent)
461
+ self.prometheus_metrics['network_bytes_received_total'].labels(instance=self.app_instance).set(
462
+ net_io.bytes_recv)
463
+
464
+ process = psutil.Process()
465
+ self.prometheus_metrics['process_cpu_seconds_total'].labels(instance=self.app_instance).set(
466
+ process.cpu_percent() / 100
467
+ )
468
+
469
+ process_memory = process.memory_info()
470
+ self.prometheus_metrics['process_memory_rss_bytes'].labels(instance=self.app_instance).set(
471
+ process_memory.rss)
472
+ self.prometheus_metrics['process_memory_vms_bytes'].labels(instance=self.app_instance).set(
473
+ process_memory.vms)
474
+ self.prometheus_metrics['process_threads_count'].labels(instance=self.app_instance).set(
475
+ process.num_threads())
476
+
477
+ try:
478
+ self.prometheus_metrics['process_open_files_count'].labels(instance=self.app_instance).set(
479
+ len(process.open_files())
480
+ )
481
+ except:
482
+ self.prometheus_metrics['process_open_files_count'].labels(instance=self.app_instance).set(0)
483
+
484
+ logger.debug(f"Prometheus metrics updated for instance {self.app_instance}")
485
+
486
+ except Exception as e:
487
+ logger.error(f"Error updating Prometheus metrics: {str(e)}")
488
+
489
+
490
+ def get_stats(self) -> Dict:
491
+ return {
492
+ 'collection_interval': self.collection_interval,
493
+ 'app_instance': self.app_instance,
494
+ 'excluded_metrics_count': len(self.excluded_metrics),
495
+ 'excluded_metrics': list(self.excluded_metrics)
496
+ }
497
+
498
+
499
+ metrics_collector = SystemMetricsCollector()
500
+
501
+
502
+ def configure_metrics_collector_from_env(collector: Optional[SystemMetricsCollector] = None):
503
+ """Apply the environment to a collector. Repeatable, no module reload.
504
+
505
+ Configuration by call rather than as a side effect of import: reloading the
506
+ module to reconfigure it rebuilds the classes and discards whatever was
507
+ already taken from it -- patches in tests, references to the previous
508
+ instance, all at once.
509
+
510
+ Args:
511
+ collector: the collector to configure; the shared one when omitted.
512
+ """
513
+ collector = collector if collector is not None else metrics_collector
514
+
515
+ excluded_env = os.getenv('EXCLUDED_METRICS', '')
516
+ if excluded_env:
517
+ excluded_list = [m.strip() for m in excluded_env.split(',')]
518
+ collector.excluded_metrics.update(excluded_list)
519
+
520
+ excluded_groups_env = os.getenv('EXCLUDED_METRIC_GROUPS', '')
521
+ if excluded_groups_env:
522
+ groups = [g.strip() for g in excluded_groups_env.split(',')]
523
+ for group in groups:
524
+ if group in collector.metric_groups:
525
+ collector.exclude_group(group)
526
+
527
+ interval = os.getenv('METRICS_COLLECTION_INTERVAL')
528
+ if interval and interval.isdigit():
529
+ collector.collection_interval = int(interval)
530
+
531
+ return collector
532
+
533
+
534
+ configure_metrics_collector_from_env()
535
+
536
+
537
+ async def update_metrics_background(collector: Optional[SystemMetricsCollector] = None):
538
+ """Collect metrics for as long as the application lives: read, store, publish.
539
+
540
+ One pass and one interval. Collection used to be spread over three places:
541
+ this loop updated Prometheus only, writing to the database was done by a
542
+ method nobody called, and what did write to it was a disabled plugin using
543
+ names of its own. The upshot was an empty snapshot table and an empty
544
+ metrics section in a panel served by a healthy process.
545
+
546
+ The interval comes from the collector: two loops with two intervals are two
547
+ places where collection can stop unnoticed.
548
+
549
+ Args:
550
+ collector: the collector to run; the shared one when omitted.
551
+ """
552
+ collector = collector if collector is not None else metrics_collector
553
+ while True:
554
+ try:
555
+ metrics = await collector.collect_metrics()
556
+ collector.save_metrics_to_db(metrics)
557
+ collector.update_prometheus_metrics()
558
+ collector.forget_cpu_load()
559
+ await asyncio.sleep(collector.collection_interval)
560
+ except asyncio.CancelledError:
561
+ raise
562
+ except Exception as e:
563
+ logger.error(f"Error in metrics background update: {str(e)}")
564
+ await asyncio.sleep(ERROR_BACKOFF_SECONDS)
565
+
566
+
567
+ # --- HTTP surface -------------------------------------------------------------
568
+ #
569
+ # Prometheus scrapes /metrics; the admin panel reads the per-instance figures
570
+ # this module writes to system_metrics, which is how one replica can show the
571
+ # load of all of them.
572
+
573
+
574
+ #: What the panel shows in the summary and under which names it is stored. The
575
+ #: panel used to ask for the names of a disabled plugin (`cpu_usage`,
576
+ #: `ram_usage`, `disk_usage`) that nobody wrote -- and showed nothing while
577
+ #: collection was running.
578
+ #: Summary field -> metric name and the factor to convert by. The factor is
579
+ #: here and not in the panel: the field is called `ram_mb` while memory is
580
+ #: collected in bytes, and the panel would have shown "6430130176 MB" without a
581
+ #: single line of code telling a lie.
582
+ PANEL_METRICS = {
583
+ "cpu_percent": ("cpu.percent.total", 1.0),
584
+ "ram_mb": ("memory.used", 1.0 / (1024 * 1024)),
585
+ "disk_usage": ("disk.percent", 1.0),
586
+ }
587
+
588
+ #: The history in the summary: processor and memory over a day.
589
+ HISTORY_METRICS = {"cpu": "cpu.percent.total", "ram": "memory.percent"}
590
+
591
+ #: How many hours of history the summary shows. Named rather than written into
592
+ #: the call because it gained a second reader: the retention sweep has to keep
593
+ #: its detailed window wider than this period, or a pass would eat the chart.
594
+ PANEL_HISTORY_HOURS = 24
595
+
596
+ #: The freshness window: an instance that has not written metrics for longer
597
+ #: than this counts as unreachable.
598
+ FRESH_WINDOW_MINUTES = 5
599
+
600
+
601
+ def fresh_since(now: Optional[datetime] = None) -> datetime:
602
+ """The edge of the freshness window.
603
+
604
+ Computed here and not in the query: the interval syntax differs between the
605
+ engines, and `CURRENT_TIMESTAMP - INTERVAL '5 minutes'` is a syntax error on
606
+ SQLite -- which meant the summary did not work in development at all.
607
+
608
+ Args:
609
+ now: the moment to measure from; defaults to the current time.
610
+
611
+ Returns:
612
+ The moment before which an instance counts as stale.
613
+ """
614
+ return (now or datetime.utcnow()) - timedelta(minutes=FRESH_WINDOW_MINUTES)
615
+
616
+
617
+ class SystemMetricsResponse(BaseModel):
618
+ """The summary the panel's metrics section reads."""
619
+
620
+ instances: List[Dict[str, Any]]
621
+ historical: Dict[str, List[Dict[str, Any]]]
622
+
623
+
624
+ def get_latest_metric_value(instance_id: str, metric_name: str):
625
+ """An instance's latest value of a metric, or zero.
626
+
627
+ Through named parameters: two variants of one query for two engines are two
628
+ places that can drift apart, and they already had.
629
+
630
+ Args:
631
+ instance_id: the replica to read.
632
+ metric_name: the metric to read.
633
+
634
+ Returns:
635
+ The value, or 0 when there is no row or the read failed.
636
+ """
637
+ try:
638
+ row = DatabaseManagerV2.execute_one(
639
+ "SELECT metric_value FROM system_metrics "
640
+ "WHERE app_instance = :instance AND metric_name = :name "
641
+ "ORDER BY timestamp DESC LIMIT 1",
642
+ {"instance": instance_id, "name": metric_name})
643
+ return float(row["metric_value"]) if row else 0
644
+ except Exception as error:
645
+ # Zero instead of a value: the metrics section must not fail whole
646
+ # because of one row that is not there.
647
+ logger.warning(f"Could not read {metric_name} of {instance_id}: {error}")
648
+ return 0
649
+
650
+
651
+ def get_historical_metrics(metric_name: str, hours: int):
652
+ """A metric's history over a period -- one query for both engines.
653
+
654
+ The boundary is computed here: `INTERVAL` and `datetime('now', ...)` are
655
+ the syntax of different engines, and a query written for one does not run
656
+ on the other.
657
+
658
+ Args:
659
+ metric_name: the metric to read.
660
+ hours: how far back to read.
661
+
662
+ Returns:
663
+ The rows of the history, newest ordering as the query returns them.
664
+ """
665
+ try:
666
+ since = datetime.utcnow() - timedelta(hours=int(hours))
667
+ rows = DatabaseManagerV2.execute(
668
+ "SELECT app_instance, metric_value, timestamp FROM system_metrics "
669
+ "WHERE metric_name = :name AND timestamp > :since ORDER BY timestamp ASC",
670
+ {"name": metric_name, "since": since})
671
+ return [{
672
+ "instance_id": row["app_instance"],
673
+ "metric_value": float(row["metric_value"]),
674
+ "timestamp": row["timestamp"],
675
+ } for row in rows]
676
+ except Exception as error:
677
+ logger.error(f"Error getting historical metrics: {error}")
678
+ return []
679
+
680
+
681
+ def register_metrics_routes(app, public=False):
682
+ """Register the metrics endpoints on the application.
683
+
684
+ Args:
685
+ app: the FastAPI application.
686
+ public: whether /metrics answers without credentials. False by default:
687
+ the collection carries the load of the host, the names of the
688
+ replicas and the shape of the traffic, and a package installed on a
689
+ public address should not hand that out because nobody said not to.
690
+ A deployment whose collector cannot present credentials opens it
691
+ deliberately.
692
+ """
693
+
694
+ if public:
695
+ @app.get("/metrics")
696
+ async def metrics():
697
+ """Prometheus metrics endpoint, scraped by Prometheus."""
698
+ return FastAPIResponse(
699
+ content=generate_latest(),
700
+ media_type=CONTENT_TYPE_LATEST
701
+ )
702
+ else:
703
+ @app.get("/metrics")
704
+ async def metrics(admin: dict = Depends(get_current_admin)):
705
+ """Prometheus metrics endpoint, for a collector that signs in."""
706
+ return FastAPIResponse(
707
+ content=generate_latest(),
708
+ media_type=CONTENT_TYPE_LATEST
709
+ )
710
+ @app.get("/api/admin/metrics/system", response_model=SystemMetricsResponse)
711
+ async def get_system_metrics(admin: dict = Depends(get_current_admin)):
712
+ """Return the current system metrics of every instance."""
713
+ try:
714
+ since = fresh_since()
715
+ instances = DatabaseManagerV2.execute(
716
+ "SELECT DISTINCT app_instance FROM system_metrics "
717
+ "WHERE timestamp > :since ORDER BY app_instance", {"since": since})
718
+
719
+ instances_data = []
720
+ for instance in instances:
721
+ instance_id = instance['app_instance']
722
+
723
+ latest = DatabaseManagerV2.execute_one(
724
+ "SELECT metric_name, metric_value, timestamp FROM system_metrics "
725
+ "WHERE app_instance = :instance AND timestamp > :since "
726
+ "ORDER BY timestamp DESC", {"instance": instance_id, "since": since})
727
+
728
+ instance_data = {
729
+ "instance_id": instance_id,
730
+ "is_online": bool(latest),
731
+ "last_update": latest['timestamp'] if latest else None,
732
+ # The names come from one list: the panel and the
733
+ # collector have to call the same thing by the same name,
734
+ # or the summary is empty while the table is full.
735
+ "current_metrics": {
736
+ field: get_latest_metric_value(instance_id, name) * scale
737
+ for field, (name, scale) in PANEL_METRICS.items()
738
+ } if latest else None
739
+ }
740
+ instances_data.append(instance_data)
741
+
742
+ historical_data = {
743
+ field: get_historical_metrics(name, PANEL_HISTORY_HOURS)
744
+ for field, name in HISTORY_METRICS.items()
745
+ }
746
+
747
+ return SystemMetricsResponse(
748
+ instances=instances_data,
749
+ historical=historical_data
750
+ )
751
+
752
+ except Exception as e:
753
+ logger.error(f"Error getting system metrics: {str(e)}")
754
+ raise HTTPException(status_code=500, detail="Error retrieving system metrics")
755
+ @app.get("/api/admin/metrics/history")
756
+ async def get_historical_metrics_endpoint(
757
+ cpu_hours: int = Query(24, description="Hours of CPU metrics"),
758
+ ram_hours: int = Query(24, description="Hours of RAM metrics"),
759
+ admin: dict = Depends(get_current_admin)
760
+ ):
761
+ """Return the historical values of a metric."""
762
+ try:
763
+ return {
764
+ "cpu": get_historical_metrics("cpu_usage", cpu_hours),
765
+ "ram": get_historical_metrics("ram_usage", ram_hours)
766
+ }
767
+ except Exception as e:
768
+ logger.error(f"Error getting historical metrics: {str(e)}")
769
+ raise HTTPException(status_code=500, detail="Error retrieving historical metrics")
770
+ @app.get("/api/admin/instances/{instance_id}")
771
+ async def get_instance_details(instance_id: str, admin: dict = Depends(get_current_admin)):
772
+ """Return the details of one instance."""
773
+ try:
774
+ instance_info = {
775
+ "instance_id": instance_id,
776
+ "is_online": False,
777
+ "current_metrics": {},
778
+ "recent_events": [],
779
+ "uptime": "Unknown"
780
+ }
781
+
782
+ latest_metric = DatabaseManagerV2.execute_one(
783
+ "SELECT timestamp FROM system_metrics WHERE app_instance = :instance "
784
+ "ORDER BY timestamp DESC LIMIT 1", {"instance": instance_id})
785
+
786
+ if latest_metric:
787
+ instance_info["is_online"] = True
788
+ instance_info["last_update"] = latest_metric['timestamp']
789
+ # The same names as the summary uses: one list for both
790
+ # doors, or they will one day drift apart and the only one to
791
+ # notice will be the person who sees one of them empty and the
792
+ # other full.
793
+ instance_info["current_metrics"] = {
794
+ field: get_latest_metric_value(instance_id, name) * scale
795
+ for field, (name, scale) in PANEL_METRICS.items()
796
+ }
797
+
798
+ return instance_info
799
+
800
+ except Exception as e:
801
+ logger.error(f"Error getting instance details: {str(e)}")
802
+ raise HTTPException(status_code=500, detail="Error retrieving instance details")
803
+ @app.post("/api/admin/instances/{instance_id}/restart")
804
+ async def restart_instance(instance_id: str, admin: dict = Depends(get_current_admin)):
805
+ """TODO: restart an instance -- not actually implemented."""
806
+ logger.info(f"Restart requested for instance: {instance_id} by admin: {admin['username']}")
807
+
808
+ DatabaseManager.execute_commit_only('''
809
+ INSERT INTO system_metrics (metric_name, metric_value, app_instance, tags)
810
+ VALUES (?, ?, ?, ?)
811
+ ''', (
812
+ "instance_restart",
813
+ 1,
814
+ get_instance_id(),
815
+ f"target:{instance_id},admin:{admin['username']}"
816
+ ))
817
+
818
+ return {"success": True, "message": f"Restart command sent for instance {instance_id}"}