Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat: container-level checks (Docker health, exit codes, inventory, image drift, memory trends)
karloks2005fe7081e2aae7
diff --git a/README.md b/README.mdindex fa35de2..00ce730 100644--- a/README.md+++ b/README.md@@ -26,14 +26,18 @@ for what every component can touch and the limits of each protection.- **Container details**: containers sit in a collapsible list per server, sorted byname, with problems (unhealthy, restarting, stopped) shown even when it's closed.Open a container to see CPU, memory used/limit, processes, network and disk I/O,- uptime, ports, health status and CPU/memory history.+ uptime, ports, health status and CPU/memory history. Stopped containers show how+ they ended (exit code, or "out of memory"), and a **Recent changes** list shows+ containers that appeared, disappeared or came up on a different image.- **System health per server**: reboots, OOM-killer activity, kernel fault flags,clock synchronisation and pending reboots, plus (with the optional system helper)whether the last shutdown was clean and which process the OOM killer stopped.- **Incidents with sensible alert rules**: disk (with per-mount overrides), inodes,memory, swap, load per CPU core, container restart loops, failing healthchecks,- reboots and crashes, OOM kills, kernel faults, unsynchronised clocks and servers- that stop reporting. One incident per problem, opened only after a sustained+ reboots and crashes, OOM kills, kernel faults, unsynchronised clocks, an+ unreachable or slow Docker daemon, containers that crash or are killed for running+ out of memory, containers that vanish or change image, possible memory leaks, and+ servers that stop reporting. One incident per problem, opened only after a sustainedbreach where that makes sense and resolved automatically when it clears.Thresholds are editable by admins.- **Add servers with one command and one click**: click **Connect a server**, run@@ -420,6 +424,14 @@ stops firing.| 5-minute load per CPU core | 1.5× / 2× | warning / critical || Container restart loop | 3 restarts within 30 minutes | critical || Container healthcheck `unhealthy` | – | critical |+| Container exited with an error | within 60 minutes of exiting | warning |+| Container killed by the kernel for running out of memory | within 60 minutes | critical |+| Container stopped by a signal (exit 137 or 143, usually `docker stop`) | within 60 minutes | info |+| Container no longer present | stays open 60 minutes | info |+| Container running a different image build | stays open 60 minutes | info |+| Possible memory leak (steady climb over 12 hours) | 10 MB/h and 20% growth | warning |+| Docker unreachable (after it worked before) | 3 check-ins in a row | critical |+| Docker slow to list containers | over 2000 ms, 3 check-ins in a row | warning || Server stopped reporting | 3 missed check-ins | critical || Host rebooted | stays open 60 minutes | info (critical after an unclean shutdown) || OOM killer fired | stays open 60 minutes | warning (critical at 3 or more) |@@ -427,6 +439,14 @@ stops firing.| Clock not synchronised | 3 check-ins in a row | warning || Reboot required | – | info |+Container exits, removals and image changes are noticed by comparing each check-in+with the previous one, matching containers **by name** (Compose recreates them with+new IDs). Nothing is reported on a server's first check-in or when Docker was+unreachable (an empty list is not proof that everything vanished), and churn is+capped so containers that come and go constantly can't flood the database. A leak is+only flagged when hourly memory averages rise along a straight line without a+restart; caches and warm-up can look similar, so treat it as a prompt to look.+Host rules (disk, inodes, memory, swap, load) open an incident only after**3 check-ins in a row** breach the threshold, so a brief spike is ignored. Anopen incident stays open while the latest value is still over the warning@@ -436,7 +456,9 @@ the same number of check-ins.<diagram - Incident lifecycle for a host rule as a timeline of check-ins: value crosses the warning threshold → after 3 check-ins in a row a WARNING incident opens → stays over critical for 3 check-ins → escalates to CRITICAL → drops under warning → RESOLVED; show a single spike that opens nothing>Admins can change every threshold, the number of check-ins in a row, how long-reboot and OOM incidents stay open, and **per-mount disk thresholds** under+event incidents (reboots, OOM kills, container exits, removals and image changes)+stay open, the slow-Docker limit, the memory-leak window and sensitivity, and+**per-mount disk thresholds** under**Admin → Alerts**. A per-mount override replaces the default disk thresholds forthat mount path on every server. Changes apply from each server's next check-inand are recorded in the audit log.@@ -564,7 +586,9 @@ from the backend's response to each report.- **Collector privileges.** In the Compose installs the collector has no Dockersocket, drops all capabilities and has a read-only filesystem. Only the Dockerproxy mounts the socket; it has no network, answers three read-only requests and- strips environment variables from what it returns. The collector still mounts `/`+ strips environment variables, labels, mounts and error text from what it returns.+ Everything a collector reports about containers is validated again by the backend+ (types, ranges, lengths, counts) before it is stored. The collector still mounts `/`read-only; without capabilities it can't read other users' private files through it.- **Collector endpoints are not public.** On the server stack the public listenerreturns 404 for register, poll, enroll and ingest; they exist only on the@@ -668,9 +692,10 @@ Tables are created on backend startup (`Base.metadata.create_all`), and newcolumns are added with `ALTER TABLE ... IF NOT EXISTS` in the startup hook in`src/backend/main.py`. Each check-in stores one row in `host_metrics` (which alsocarries the boot ID, OOM counter, kernel flags, clock state and last shutdown), one-per filesystem in `mount_metrics` and one per container in `container_metrics`, all-with the same timestamp. `system_events` holds reboots, OOM kills and kernel-messages, `join_tokens` the hashed single-use tokens, and per-mount disk+per filesystem in `mount_metrics` and one per container in `container_metrics` (which+also records the exit code, out-of-memory flag, finish time and image ID), all with the+same timestamp. `system_events` holds reboots, OOM kills, kernel messages and container+changes (appeared, removed, image changed), `join_tokens` the hashed single-use tokens, and per-mount diskthresholds live in `app_settings`. `docker/postgres/init/01_create_users.sql` initialisesthe `users` table on a fresh volume.diff --git a/SECURITY.md b/SECURITY.mdindex 8eff3af..c043dc6 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -55,8 +55,11 @@ compose files the collector **does not mount the socket**. A separate `docker-pr`GET /containers/<id>/stats?stream=false`. Everything else (other endpoints, other methods, extraquery parameters, encoded or padded paths) gets a 403 and is logged. Matching is literal against thewhole request target, with no decoding.-- It cuts the answers down to the fields the collector uses. Container inspect output includes each- container's environment variables, which are often secrets; they never leave the proxy.+- It cuts the answers down to a fixed list of fields. For container inspect that is the ID, name,+ restart count, image name and ID, state, health, exit code, out-of-memory flag, start and finish+ times, and published ports. Container inspect output includes each container's environment+ variables (often secrets), labels, mounts and Docker's free-text error message; none of them leave+ the proxy. Adding a field means changing the proxy and its tests on purpose.- It runs with all capabilities dropped, a read-only filesystem and `no-new-privileges`, with nonetwork at all. It listens on a Unix socket (mode 0660) in a volume that only the collector shares.- It is one standard-library file, `src/agent/docker_proxy.py`, built from this repository. Review it@@ -147,6 +150,22 @@ What this still depends on:admin still has to approve them; ingest additionally needs a server's token.- Rotating a collector token means re-adding that server.+## Container data is untrusted++A compromised collector controls everything it reports about containers, so the backend never trusts+it: each record is reduced to known fields of the right type (text made printable and capped, numbers+range-checked, timestamps parsed strictly, image IDs matched against `sha256:` plus 64 hex characters),+and anything unexpected becomes "unknown", which never raises an incident. At most 500 containers are+accepted per check-in, names are capped at 128 characters so they can't break incident keys, and+container changes (appeared, removed, image changed) are capped per check-in and per hour with a single+notice, so churn can't flood the database. The hourly memory-trend analysis is bounded too (100+containers and 300,000 samples per server). Container changes are shown in their own list so a burst of+them can't push reboots or OOM kills out of the System row.++What the collector deliberately does not ask Docker for: `/info`, `/events`, logs, images, exec or any+write. Checking registries for newer images would need outbound network access and is tracked+separately (#38) as an opt-in, isolated component rather than part of the collector or proxy.+## Other exposure to be aware of- The collector mounts the host filesystem read-only at `/hostfs` to read disk usage and a fewdiff --git a/TESTS.md b/TESTS.mdindex 2b2de9f..1b6bc6d 100644--- a/TESTS.md+++ b/TESTS.md@@ -4,8 +4,8 @@ Vexion ships with an automated test suite. This page explains how to run it, whacovers (and what it doesn't), and what every single test is for, so you can decidewhether a failure matters before you upgrade or change your setup.-- **302 test cases** from 179 test functions (some functions run once per input).-- **About 15 seconds** to run. No Docker, PostgreSQL, Redis, network or root access needed.+- **413 test cases** from 234 test functions (some functions run once per input).+- **About 15 to 20 seconds** to run. No Docker, PostgreSQL, Redis, network or root access needed.- **Safe to run next to a live install.** The tests use a throwaway in-memory databaseand fakes; they never touch your running containers or your data. (Two collectortests read this machine's `/proc` and root filesystem, read-only.)@@ -35,7 +35,7 @@ pytestA healthy run ends with a line like:```text-302 passed, 3 warnings in 14.1s+413 passed, 3 warnings in 17.0s```The warnings are harmless notices from the libraries (FastAPI deprecating the@@ -126,6 +126,7 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai| [`test_collector_mounts.py`](#test_collector_mountspy) | 1 | Which filesystems the collector reports. || [`test_container_detail.py`](#test_container_detailpy) | 5 | Per-container details and parsing of Docker's stats. || [`test_conversations.py`](#test_conversationspy) | 1 | Deleting one assistant conversation leaves the others alone. |+| [`test_container_checks.py`](#test_container_checkspy) | 111 | Docker health, container exit codes, inventory and image changes, memory-leak trends, and the validation of everything a collector sends about containers. || [`test_dashboard_host.py`](#test_dashboard_hostpy) | 8 | The "this machine" logic, history charts, container list and incident counts. || [`test_docker_proxy.py`](#test_docker_proxypy) | 91 | The read-only Docker proxy: what it allows, refuses and hides. || [`test_enrollment.py`](#test_enrollmentpy) | 10 | Enrollment keys, collector credentials and offline-server detection. |@@ -184,7 +185,7 @@ The incident engine and the container rules.| `test_unhealthy_container_alerts_once_and_resolves` | A container whose Docker healthcheck fails opens one critical incident, however many check-ins repeat it, and it closes when the container is healthy again. || `test_restart_loop_alerts_once_when_count_climbs` | A container whose restart count keeps rising within the window opens a restart-loop incident that reports how many restarts happened. || `test_restart_loop_ignores_old_restarts_and_status_alone` | A large restart count from long ago, or a single "restarting" sample, is not treated as a loop. |-| `test_removed_container_alert_resolves_when_others_report` | If a container disappears and other containers still report, its incident resolves. |+| `test_removed_container_alert_resolves_when_others_report` | If an unhealthy container disappears and others still report, its unhealthy incident resolves and only the informational "no longer present" notice remains. || `test_empty_container_list_keeps_container_alerts` | If a check-in has no containers at all (Docker unreachable), existing container incidents stay open instead of being wrongly closed. || `test_container_sync_leaves_other_rules_alone` | Updating container incidents never touches other incidents, such as "server offline". || `test_overview_lists_critical_first_with_hostname_and_true_count` | The dashboard's incident list shows the most severe first, includes the server name, and reports the true total even when the list is capped. |@@ -245,6 +246,102 @@ Accounts, passwords, first-run protection and the cross-site check.|---|---|| `test_conversation_records_are_independent_for_safe_deletion` | Deleting one assistant conversation removes only its own messages and audit entries and leaves other conversations untouched. |+### test_container_checks.py++Container-level checks: Docker health, how containers ended, what appeared or+disappeared, image changes, and memory-leak trends. A large part of this file tests the+validation of container data, because everything a collector reports is untrusted input.++**Docker health (collector side)**++| Test | What it checks |+|---|---|+| `test_a_host_without_docker_is_not_configured_not_broken` | A host with no Docker socket is reported as *not configured*, not as a failure. |+| `test_a_configured_but_missing_proxy_socket_is_unreachable` | If the Docker proxy is configured but its socket is missing, that is a failure (reason *missing*). |+| `test_a_stale_socket_nobody_listens_on_is_reported_as_refused` | A socket file left behind by a stopped proxy is reported as *refused*. |+| `test_failures_map_to_a_fixed_vocabulary_never_raw_text` *(7 inputs)* | Errors become one of five fixed reasons (timeout, refused, missing, denied, error); raw error text is never sent. |+| `test_a_working_daemon_reports_ok_with_its_latency` | A working Docker reports `ok` and how long listing containers took. |+| `test_a_daemon_error_during_listing_is_unreachable` | A Docker error while listing containers is reported as unreachable, with no containers. |+| `test_one_container_vanishing_mid_collection_does_not_fail_the_rest` | A container removed between listing and inspecting is skipped without failing the others. |+| `test_when_nothing_can_be_inspected_the_daemon_is_failing_not_empty` | If containers are listed but none can be inspected, Docker is treated as failing rather than empty. |++**Exit status and image ID (collector side)**++| Test | What it checks |+|---|---|+| `test_a_stopped_container_reports_how_it_ended` | A stopped container reports its exit code, whether it was out-of-memory killed, when it finished (to the second) and its image ID. |+| `test_a_running_container_does_not_report_a_stale_exit_status` | A running container never reports the exit status of an earlier run. |+| `test_malformed_exit_details_become_unknown` *(10 inputs)* | Strings, booleans, out-of-range or fractional exit codes, a non-boolean OOM flag and impossible finish times all become *unknown*. |+| `test_only_a_well_formed_image_id_is_passed_on` *(8 inputs)* | Only a real `sha256:` plus 64 hex characters image ID is passed on; tags, short or malformed values are dropped. |++**Docker health incidents (backend side)**++| Test | What it checks |+|---|---|+| `test_docker_unreachable_alerts_only_after_it_worked_and_only_when_sustained` | A critical incident opens after Docker worked before and then fails several check-ins in a row, and resolves when it recovers. |+| `test_a_host_that_never_had_working_docker_never_alerts` | A host that never had working Docker, or has none, never gets an incident. |+| `test_an_open_docker_alert_survives_the_purge_of_the_samples_that_proved_it_worked` | An open incident stays open even after retention deletes the old samples that showed Docker once worked. |+| `test_slow_docker_warns_when_sustained_and_clears_when_fast` | Slow container listings over the threshold, several times in a row, raise a warning that clears when Docker is fast again. |+| `test_missing_docker_data_from_old_collectors_never_alerts` | Collectors that send no Docker status never trigger Docker incidents. |+| `test_malformed_docker_fields_are_dropped` | Unknown status values, free-text reasons and absurd latencies are discarded. |++**Exit-code incidents (backend side)**++| Test | What it checks |+|---|---|+| `test_stopped_containers_are_classified_by_how_they_ended` *(5 inputs)* | Exit code 1 and 127 give a warning (127 explained as "command not found"), 137 and 143 an informational notice (usually a deliberate stop), and an out-of-memory kill is critical. |+| `test_clean_exits_unknown_and_running_containers_never_alert` *(5 inputs)* | Clean exits (0), unknown exit codes or times, and running or merely created containers never raise an incident. |+| `test_an_old_exit_is_not_an_incident_and_a_restart_clears_it` | An exit older than the event window raises nothing, and a container that runs again clears its incident. |++**What a collector may send about containers**++| Test | What it checks |+|---|---|+| `test_unusable_container_records_are_dropped` *(11 inputs)* | Records that are not objects, or lack a usable ID or status, are dropped. |+| `test_container_text_is_made_printable_and_bounded` | Control characters are replaced and every text field is trimmed and capped (names at 128 characters). |+| `test_a_missing_name_falls_back_to_the_container_id` | A container without a name is shown by the start of its ID. |+| `test_numeric_fields_must_be_real_in_range_numbers` *(9 inputs)* | Strings, booleans, NaN, infinity, negative or absurdly large values become *unknown* instead of being stored. |+| `test_sane_numbers_pass_through` | Normal values are stored unchanged. |+| `test_finish_times_must_be_exact_recent_utc_timestamps` *(9 inputs)* | Only exact UTC timestamps between the year 2000 and a few minutes from now are accepted. |+| `test_a_valid_finish_time_becomes_an_aware_datetime` | A valid finish time is stored as a timezone-aware date. |+| `test_unknown_fields_are_not_passed_to_the_database` | Extra fields (including attempts to set `id`, `server_id` or `time`) are ignored. |+| `test_the_api_schema_already_refuses_container_entries_that_are_not_objects` | The API itself rejects container lists with non-object entries. |+| `test_hostile_container_records_never_break_ingest_or_other_data` | Odd records are cleaned or dropped, and the host's own numbers in the same check-in are still recorded. |+| `test_no_more_than_500_containers_are_accepted_per_check_in` | At most 500 containers are stored per check-in. |+| `test_the_longest_container_name_still_fits_every_incident_key` | Even the longest allowed name keeps every incident key within the database limit, so a crafted name cannot make check-ins fail. |++**Inventory changes and image drift**++| Test | What it checks |+|---|---|+| `test_the_first_check_in_is_only_a_baseline` | The first report creates no events. |+| `test_new_and_missing_containers_are_recorded` | Containers that appeared or disappeared since the last check-in are recorded. |+| `test_a_removed_container_opens_an_informational_incident_that_clears_with_the_window` | A removed container opens an informational incident that clears after the event window. |+| `test_a_container_that_comes_back_clears_its_removal_incident` | A container that returns clears its removal incident. |+| `test_containers_are_matched_by_name_so_recreation_is_not_a_change` | Recreating a container (new ID, same name, same image) is not reported. |+| `test_an_empty_list_never_looks_like_everything_vanished_or_reappeared` | An empty list (Docker unreachable) neither removes everything nor makes everything look new when it returns. |+| `test_a_changed_image_is_recorded_and_raises_an_informational_incident` | A container that comes up on a different image build is recorded with the short IDs, and raises an informational incident. |+| `test_the_same_image_or_an_unknown_one_is_not_a_change` | The same image, or an unknown image ID on either side, is not a change. |+| `test_a_burst_of_changes_is_capped_per_check_in_with_one_notice` | A burst of changes records at most 10 events per check-in plus a single notice. |+| `test_sustained_churn_is_capped_per_hour` | Containers constantly coming and going cannot flood the database: events are capped per hour with one notice. |+| `test_container_changes_have_their_own_list_and_do_not_crowd_the_system_row` | Container changes appear in the Containers section, not in the System row, so they cannot push reboots out of it. |+| `test_the_container_change_list_is_bounded` | The dashboard's container-change list is capped at 15 rows. |+| `test_container_events_follow_the_normal_retention` | Container change events are deleted with the other old data after the retention period. |++**Memory-leak trends**++| Test | What it checks |+|---|---|+| `test_steady_growth_is_flagged_as_a_possible_leak` | A container whose memory rises steadily over the window gets a warning with the rate and, when a memory limit is set, the time until it is reached. |+| `test_flat_noisy_and_sawtooth_memory_is_not_a_leak` | Flat, noisy or repeatedly rising-and-falling memory is not flagged. |+| `test_a_restart_or_recreation_in_the_window_resets_the_trend` | A restart or recreation inside the window disqualifies the trend, since it resets memory. |+| `test_too_little_history_or_a_slow_or_proportionally_small_rise_is_not_flagged` | Missing data, a rise below the MB-per-hour minimum, or a tiny proportional rise on a large container are not flagged. |+| `test_containers_that_are_not_running_now_are_not_analysed` | Containers that are not running now are skipped. |+| `test_the_flag_clears_when_the_growth_stops` | The warning clears on the next hourly analysis once growth stops. |+| `test_analysis_is_bounded_to_100_containers_per_server` | At most 100 containers per server are analysed. |+| `test_a_fit_needs_distinct_points` | The straight-line fit refuses degenerate input and computes slope and fit quality correctly. |+| `test_the_new_thresholds_have_safe_defaults_and_are_validated` | The new thresholds (slow Docker, leak window, rate and growth) have safe defaults, and out-of-range, fractional, text or boolean values are rejected. |+### test_dashboard_host.py| Test | What it checks |@@ -268,7 +365,7 @@ tested hardest (91 cases). If any of these fail, do not run the proxy until it i| `test_the_three_read_requests_are_allowed` *(5 inputs)* | The exact requests the collector needs (list containers, inspect one, one stats snapshot) are allowed. || `test_only_get_is_allowed` *(8 inputs)* | Every method except GET (POST, PUT, DELETE, PATCH, HEAD, OPTIONS, lowercase `get`, CONNECT) is refused. || `test_everything_else_is_refused` *(63 inputs)* | Everything outside the allow-list is refused: other endpoints (`/info`, images, exec, start, kill, export, archive, logs), extra or changed query strings, path traversal, encoded or padded paths, injected line breaks, odd container IDs. |-| `test_inspect_output_drops_environment_and_everything_unneeded` | The container description is cut down to the needed fields; environment variables (often secrets), mounts, labels and host configuration never leave the proxy. |+| `test_inspect_output_drops_environment_and_everything_unneeded` | The container description is cut down to the needed fields (including exit code, out-of-memory flag, finish time and image ID); environment variables (often secrets), mounts, labels, host configuration and Docker's free-text error message never leave the proxy. || `test_list_and_stats_output_are_cut_down` | The same filtering applies to the container list and stats. || `test_unexpected_upstream_shapes_do_not_crash_the_filters` *(7 inputs)* | Strange or malformed answers from Docker don't crash the proxy. || `test_collector_works_through_the_proxy_and_never_sees_secrets` | End to end: the real collector gets correct container data through the proxy and no secret reaches it. |diff --git a/src/agent/collector.py b/src/agent/collector.pyindex 33190bc..60b98cc 100644--- a/src/agent/collector.py+++ b/src/agent/collector.py@@ -18,6 +18,7 @@ import http.clientimport jsonimport osimport platform+import reimport socketimport timeimport urllib.error@@ -342,22 +343,58 @@ def _docker_request(socket_path: str, endpoint: str) -> Any:return json.loads(body or b"null")-def collect_containers(socket_path: str | None = None) -> list[dict[str, Any]]:+_IMAGE_ID = re.compile(r"sha256:[0-9a-f]{64}")+_DOCKER_TIME = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")+# Containers that have stopped (or are between restarts) carry a meaningful exit status.+_STOPPED = {"exited", "dead", "restarting"}+++def _docker_time(value: Any) -> str | None:+ """Docker's nanosecond timestamp cut to whole seconds, or None for the "never" value (year 1)."""+ match = _DOCKER_TIME.match(value) if isinstance(value, str) else None+ return f"{match.group(0)}Z" if match and int(match.group(0)[:4]) >= 2000 else None+++def _docker_failure_reason(error: BaseException) -> str:+ """A coarse, fixed-vocabulary reason, never the raw error text."""+ if isinstance(error, TimeoutError):+ return "timeout"+ if isinstance(error, ConnectionRefusedError):+ return "refused"+ if isinstance(error, FileNotFoundError):+ return "missing"+ if isinstance(error, PermissionError):+ return "denied"+ return "error"+++def collect_containers(socket_path: str | None = None, info: dict[str, Any] | None = None) -> list[dict[str, Any]]:+ """Every container with its state and usage. ``info`` receives how long listing them took."""# The read-only proxy is preferred: it keeps the Docker socket, which is root on the host, out of this container.socket_path = socket_path or os.getenv("HOMELAB_DOCKER_HOST") or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")if not Path(socket_path).exists():return []+ listing_started = time.monotonic()containers = _docker_request(socket_path, "/containers/json?all=1")+ if info is not None:+ info["latency_ms"] = int((time.monotonic() - listing_started) * 1000)result = []for item in containers:container_id = item.get("Id", "")if not container_id:continue- detail = _docker_request(socket_path, f"/containers/{container_id}/json")+ try:+ detail = _docker_request(socket_path, f"/containers/{container_id}/json")+ except (OSError, ValueError, http.client.HTTPException):+ # A container removed between listing and inspecting it must not fail the whole collection.+ continuestate = detail.get("State") or {}status = state.get("Status") or item.get("State") or "unknown"health = (state.get("Health") or {}).get("Status")usage_stats = _container_usage(socket_path, container_id) if status == "running" else {}+ stopped = str(status).lower() in _STOPPED+ exit_code = state.get("ExitCode")+ image_id = detail.get("Image")result.append({"container_id": container_id,"name": (detail.get("Name") or (item.get("Names") or [container_id[:12]])[0]).lstrip("/"),@@ -367,11 +404,40 @@ def collect_containers(socket_path: str | None = None) -> list[dict[str, Any]]:"healthcheck_status": health,"started_at": state.get("StartedAt") if status == "running" else None,"ports": _format_ports((detail.get("NetworkSettings") or {}).get("Ports")),+ "exit_code": exit_code if stopped and isinstance(exit_code, int) and not isinstance(exit_code, bool) and -1 <= exit_code <= 65535 else None,+ "oom_killed": state.get("OOMKilled") if stopped and isinstance(state.get("OOMKilled"), bool) else None,+ "finished_at": _docker_time(state.get("FinishedAt")) if stopped else None,+ "image_id": image_id if isinstance(image_id, str) and _IMAGE_ID.fullmatch(image_id) else None,**usage_stats,})+ if containers and not result:+ # Listing worked but nothing could be inspected: the daemon is failing, not empty.+ raise OSError("no container could be inspected")return result+def collect_docker(socket_path: str | None = None) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ """Containers plus a verdict on the Docker API: ``ok``, ``unreachable`` or ``not_configured``.++ "No Docker on this host" is not an error, and an empty list is not proof of a problem, so the+ backend only alerts on ``unreachable`` for a host that had Docker working before.+ """+ explicit = socket_path or os.getenv("HOMELAB_DOCKER_HOST")+ target = explicit or os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")+ if not Path(target).exists():+ # A proxy that is configured but missing is a failure; a host that simply has no Docker socket is not.+ if explicit:+ return [], {"docker_status": "unreachable", "docker_reason": "missing", "docker_latency_ms": None}+ return [], {"docker_status": "not_configured", "docker_reason": None, "docker_latency_ms": None}+ info: dict[str, Any] = {}+ try:+ containers = collect_containers(target, info)+ except (OSError, ValueError, http.client.HTTPException) as error:+ print(f"Docker metrics unavailable ({type(error).__name__}); sending host metrics only", flush=True)+ return [], {"docker_status": "unreachable", "docker_reason": _docker_failure_reason(error), "docker_latency_ms": info.get("latency_ms")}+ return containers, {"docker_status": "ok", "docker_reason": None, "docker_latency_ms": info.get("latency_ms")}++def _format_ports(ports: dict[str, Any] | None) -> str | None:mappings = []for container_port, bindings in (ports or {}).items():@@ -571,11 +637,8 @@ def run_collector() -> None:started = time.monotonic()try:server, host = collect_host()- try:- containers = collect_containers()- except (OSError, ValueError, http.client.HTTPException) as docker_error:- containers = []- print(f"Docker metrics unavailable ({type(docker_error).__name__}); sending host metrics only", flush=True)+ containers, docker = collect_docker()+ host.update(docker)response = send_payload(api_url, server_id, token, {"server": server, "host": host, "containers": containers})interval = max(15, int(response.get("interval_seconds", interval)))print(f"Sent host metrics and {len(containers)} container records; next check in {interval}s", flush=True)diff --git a/src/agent/docker_proxy.py b/src/agent/docker_proxy.pyindex c79b812..1725d15 100644--- a/src/agent/docker_proxy.py+++ b/src/agent/docker_proxy.py@@ -56,9 +56,10 @@ def project_inspect(data: Any) -> dict[str, Any]:network = data.get("NetworkSettings") if isinstance(data.get("NetworkSettings"), dict) else {}config = data.get("Config") if isinstance(data.get("Config"), dict) else {}return {- **_pick(data, ("Id", "Name", "RestartCount")),+ # Image is the ID of the image the container runs. State.Error is free text, so it stays out.+ **_pick(data, ("Id", "Name", "RestartCount", "Image")),"Config": _pick(config, ("Image",)),- "State": {**_pick(state, ("Status", "StartedAt")), "Health": _pick(health, ("Status",))},+ "State": {**_pick(state, ("Status", "StartedAt", "ExitCode", "OOMKilled", "FinishedAt")), "Health": _pick(health, ("Status",))},"NetworkSettings": _pick(network, ("Ports",)),}diff --git a/src/backend/main.py b/src/backend/main.pyindex a969647..bd295ba 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import mathimport reimport hashlibimport secrets@@ -43,7 +44,7 @@ from .config import (SESSION_COOKIE_SECURE,SESSION_TTL_SECONDS,)-from .rules import DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX+from .rules import DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIXfrom .rate_limit import enforce_ip_limit, enforce_login_limit, enforce_register_limit, reset_limitsfrom ..agent.service import delete_agent_conversation, send_agent_message@@ -194,8 +195,11 @@ def startup_event():for column, column_type in (("boot_id", "VARCHAR(64)"), ("oom_kill_total", "INTEGER"), ("kernel_tainted", "INTEGER"),("ntp_synced", "BOOLEAN"), ("reboot_required", "BOOLEAN"), ("last_shutdown", "VARCHAR(16)"),+ ("docker_status", "VARCHAR(16)"), ("docker_reason", "VARCHAR(16)"), ("docker_latency_ms", "INTEGER"),):connection.execute(text(f"ALTER TABLE host_metrics ADD COLUMN IF NOT EXISTS {column} {column_type}"))+ for column, column_type in (("exit_code", "INTEGER"), ("oom_killed", "BOOLEAN"), ("finished_at", "TIMESTAMP WITH TIME ZONE"), ("image_id", "VARCHAR(80)")):+ connection.execute(text(f"ALTER TABLE container_metrics ADD COLUMN IF NOT EXISTS {column} {column_type}"))connection.execute(text("ALTER TABLE system_events ADD COLUMN IF NOT EXISTS event_key VARCHAR(128)"))connection.execute(text("ALTER TABLE pending_collectors ADD COLUMN IF NOT EXISTS join_token_id INTEGER REFERENCES join_tokens(id) ON DELETE SET NULL"))connection.execute(text("CREATE INDEX IF NOT EXISTS ix_system_events_event_key ON system_events (event_key)"))@@ -546,7 +550,7 @@ def recent_system_events(db, since: datetime) -> dict[int, list[dict]]:OOM kills out of the list. Every other kind stays one row per occurrence."""result: dict[int, list[dict]] = {}- for event in db.query(SystemEvent).filter(SystemEvent.time >= since, SystemEvent.kind != "kernel_error").order_by(SystemEvent.time.desc()):+ for event in db.query(SystemEvent).filter(SystemEvent.time >= since, SystemEvent.kind != "kernel_error", SystemEvent.kind.notin_(CONTAINER_EVENT_KINDS)).order_by(SystemEvent.time.desc()):rows = result.setdefault(event.server_id, [])if len(rows) < SYSTEM_EVENTS_SHOWN:rows.append({"time": event.time.isoformat(), "first_time": event.time.isoformat(), "kind": event.kind, "detail": event.detail, "count": 1})@@ -566,6 +570,22 @@ def recent_system_events(db, since: datetime) -> dict[int, list[dict]]:return result+CONTAINER_EVENTS_SHOWN = 15+++def recent_container_events(db, since: datetime) -> dict[int, list[dict]]:+ """Each server's recent container changes (appeared, removed, image changed), newest first.++ Kept apart from the System row so a burst of container churn can't push reboots or OOM kills out of it.+ """+ result: dict[int, list[dict]] = {}+ for event in db.query(SystemEvent).filter(SystemEvent.time >= since, SystemEvent.kind.in_(CONTAINER_EVENT_KINDS)).order_by(SystemEvent.time.desc()):+ rows = result.setdefault(event.server_id, [])+ if len(rows) < CONTAINER_EVENTS_SHOWN:+ rows.append({"time": event.time.isoformat(), "kind": event.kind, "detail": event.detail})+ return result++@app.get("/monitoring/overview")def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):# Servers belong to the install: everyone signed in can view them, only admins manage them.@@ -575,6 +595,7 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_Calert_counts = dict(db.query(IncidentAlert.server_id, func.count()).filter(IncidentAlert.status == "active").group_by(IncidentAlert.server_id).all())since = datetime.now(timezone.utc) - timedelta(days=7)events = recent_system_events(db, since)+ container_events = recent_container_events(db, since)result = []for server in servers:metric = db.query(HostMetric).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc()).first()@@ -586,10 +607,11 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_C"check_interval_seconds": server.check_interval_seconds, "is_dashboard_host": server.is_dashboard_host,"active_alert_count": alert_counts.get(server.id, 0),"last_seen_at": server.last_seen_at.isoformat() if server.last_seen_at else None,- "host": ({key: getattr(metric, key) for key in ("time", "cpu_utilization_pct", "load_1m", "load_5m", "load_15m", "ram_used_gb", "ram_available_gb", "ram_pct", "swap_pct", "disk_usage_pct", "disk_inodes_pct", "net_bytes_sent_mb", "net_bytes_recv_mb", "system_uptime_seconds", "oom_kill_total", "kernel_tainted", "ntp_synced", "reboot_required", "last_shutdown")} if metric else None),+ "host": ({key: getattr(metric, key) for key in ("time", "cpu_utilization_pct", "load_1m", "load_5m", "load_15m", "ram_used_gb", "ram_available_gb", "ram_pct", "swap_pct", "disk_usage_pct", "disk_inodes_pct", "net_bytes_sent_mb", "net_bytes_recv_mb", "system_uptime_seconds", "oom_kill_total", "kernel_tainted", "ntp_synced", "reboot_required", "last_shutdown", "docker_status", "docker_reason", "docker_latency_ms")} if metric else None),+ "container_events": container_events.get(server.id, []),"system_events": events.get(server.id, []),"mounts": [{key: getattr(m, key) for key in ("mount", "fs_type", "total_gb", "used_gb", "used_pct", "inodes_pct")} for m in mounts],- "containers": [{"container_id": c.container_id, "name": c.name, "image": c.image, "status": c.status, "restart_count": c.restart_count, "cpu_pct": c.cpu_pct, "memory_used_mb": c.memory_used_mb, "memory_pct": c.memory_pct, "healthcheck_status": c.healthcheck_status, "time": c.time.isoformat()} for c in latest.values()],+ "containers": [{"container_id": c.container_id, "name": c.name, "image": c.image, "status": c.status, "restart_count": c.restart_count, "cpu_pct": c.cpu_pct, "memory_used_mb": c.memory_used_mb, "memory_pct": c.memory_pct, "healthcheck_status": c.healthcheck_status, "exit_code": c.exit_code, "oom_killed": c.oom_killed, "finished_at": c.finished_at.isoformat() if c.finished_at else None, "time": c.time.isoformat()} for c in latest.values()],})active_alerts = db.query(IncidentAlert).filter(IncidentAlert.status == "active")# Most severe first, then newest.@@ -930,6 +952,15 @@ def mark_offline_servers(db, now: datetime | None = None) -> int:METRICS_PURGE_INTERVAL_SECONDS = 3600+def analyze_memory_trends(db, now: datetime | None = None) -> None:+ """Hourly: flag containers whose memory climbs steadily, and clear flags that no longer hold."""+ now = now or datetime.now(timezone.utc)+ thresholds = get_alert_thresholds(db)+ for server in db.query(Server).all():+ sync_alerts(db, server.id, TREND_RULE_PREFIX, memory_trend_rules(db, server.id, thresholds, now), now)+ db.commit()++def _offline_watch_loop() -> None:last_metrics_purge: float | None = Nonewhile True:@@ -940,6 +971,7 @@ def _offline_watch_loop() -> None:purge_stale_pending(db)if last_metrics_purge is None or time.monotonic() - last_metrics_purge >= METRICS_PURGE_INTERVAL_SECONDS:purge_old_metrics(db)+ analyze_memory_trends(db)last_metrics_purge = time.monotonic()except Exception as exc: # keep the watcher alive through transient DB errorsprint(f"Offline watch failed: {type(exc).__name__}: {exc}", flush=True)@@ -1002,6 +1034,72 @@ def record_helper_events(db, server_id: int, raw, now: datetime) -> None:db.add(SystemEvent(server_id=server_id, time=time, kind=kind, detail=detail, event_key=key))+DOCKER_STATUSES = {"ok", "unreachable", "not_configured"}+DOCKER_REASON_CODES = {"timeout", "refused", "missing", "denied", "error"}+MAX_CONTAINERS_PER_CHECKIN = 500+# Names end up inside incident keys (255 characters, with a prefix and suffix), so they are kept well under that.+MAX_CONTAINER_NAME = 128+_IMAGE_ID = re.compile(r"sha256:[0-9a-f]{64}")+_CONTAINER_FLOATS = ("cpu_pct", "memory_used_mb", "memory_pct", "memory_limit_mb", "net_rx_mb", "net_tx_mb", "block_read_mb", "block_write_mb")+_CONTAINER_TEXT = {"image": 255, "started_at": 64, "ports": 512, "healthcheck_status": 64}+++def _printable(text: str, limit: int) -> str:+ """Trim surrounding whitespace, replace control characters, and cap the length."""+ return "".join(char if char.isprintable() else "?" for char in text.strip())[:limit].strip()+++def _whole_number(value, low: int, high: int) -> int | None:+ return value if isinstance(value, int) and not isinstance(value, bool) and low <= value <= high else None+++def _clean_container(raw, now: datetime) -> dict | None:+ """One container record reduced to known fields of the right type and size, or None if unusable.++ Everything here comes from a collector, so nothing is trusted: text is made printable and bounded,+ numbers are range-checked, and anything unexpected becomes None (unknown, which never alerts).+ """+ if not isinstance(raw, dict) or not isinstance(raw.get("container_id"), str) or not isinstance(raw.get("status"), str):+ return None+ container_id, status = _printable(raw["container_id"], 128), _printable(raw["status"], 64).lower()+ if not container_id or not status:+ return None+ name = raw.get("name")+ clean: dict = {"container_id": container_id, "status": status, "name": (_printable(name, MAX_CONTAINER_NAME) if isinstance(name, str) else "") or container_id[:12]}+ for key, limit in _CONTAINER_TEXT.items():+ clean[key] = (_printable(raw[key], limit) or None) if isinstance(raw.get(key), str) else None+ clean["restart_count"] = _whole_number(raw.get("restart_count"), 0, 10**9) or 0+ clean["pids"] = _whole_number(raw.get("pids"), 0, 10**9)+ for key in _CONTAINER_FLOATS:+ value = raw.get(key)+ clean[key] = float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and 0 <= value <= 1e12 else None+ clean["exit_code"] = _whole_number(raw.get("exit_code"), -1, 65535)+ clean["oom_killed"] = raw["oom_killed"] if isinstance(raw.get("oom_killed"), bool) else None+ clean["image_id"] = raw["image_id"] if isinstance(raw.get("image_id"), str) and _IMAGE_ID.fullmatch(raw["image_id"]) else None+ clean["finished_at"] = None+ if isinstance(raw.get("finished_at"), str):+ try:+ finished = datetime.strptime(raw["finished_at"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)+ clean["finished_at"] = finished if datetime(2000, 1, 1, tzinfo=timezone.utc) <= finished <= now + timedelta(minutes=5) else None+ except ValueError:+ pass+ return clean+++def record_container_events(db, server_id: int, events: list[tuple[str, str, str]], now: datetime) -> None:+ """Store container changes, with hard caps so churn (CI containers coming and going) can't flood the table."""+ if not events:+ return+ since = now - timedelta(hours=1)+ recent = db.query(func.count(SystemEvent.id)).filter(SystemEvent.server_id == server_id, SystemEvent.kind.in_(CONTAINER_EVENT_KINDS), SystemEvent.time >= since).scalar() or 0+ allowed = events[:max(0, min(MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR - recent))]+ for kind, detail, name in allowed:+ db.add(SystemEvent(server_id=server_id, time=now, kind=kind, detail=detail[:512], event_key=name[:128]))+ dropped = len(events) - len(allowed)+ if dropped and not db.query(SystemEvent.id).filter(SystemEvent.server_id == server_id, SystemEvent.kind == "container_notice", SystemEvent.time >= since).first():+ db.add(SystemEvent(server_id=server_id, time=now, kind="container_notice", detail=f"{dropped} more container changes were not recorded (too many at once)"))++def _clean_system_fields(fields: dict) -> None:"""Drop system-state values of the wrong type; a collector reports None when it can't tell."""for key, kind in (("oom_kill_total", int), ("kernel_tainted", int), ("ntp_synced", bool), ("reboot_required", bool)):@@ -1009,6 +1107,12 @@ def _clean_system_fields(fields: dict) -> None:fields[key] = Noneif "last_shutdown" in fields and fields["last_shutdown"] not in {"clean", "unclean", "unknown"}:fields["last_shutdown"] = None+ if "docker_status" in fields and fields["docker_status"] not in DOCKER_STATUSES:+ fields["docker_status"] = None+ if "docker_reason" in fields and fields["docker_reason"] not in DOCKER_REASON_CODES:+ fields["docker_reason"] = None+ if "docker_latency_ms" in fields:+ fields["docker_latency_ms"] = _whole_number(fields["docker_latency_ms"], 0, 600_000)if "boot_id" in fields:fields["boot_id"] = fields["boot_id"][:64] if isinstance(fields["boot_id"], str) and fields["boot_id"] else None@@ -1049,14 +1153,16 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |if isinstance(mount, dict) and isinstance(mount.get("mount"), str) and mount["mount"]:allowed = {k: v for k, v in mount.items() if k in MountMetric.__table__.columns.keys() and k not in {"id", "server_id", "time"}}db.add(MountMetric(server_id=server.id, time=now, **allowed))- containers = [c for c in payload.containers if c.get("container_id") and c.get("status")]+ containers = [clean for clean in (_clean_container(raw, now) for raw in payload.containers[:MAX_CONTAINERS_PER_CHECKIN]) if clean]+ # Compare with the previous check-in before this one's rows exist.+ previous_containers = latest_containers(db, server.id, previous.time) if previous else []+ record_container_events(db, server.id, detect_container_events(previous_containers, containers), now)for container in containers:- allowed = {k: v for k, v in container.items() if k in ContainerMetric.__table__.columns.keys() and k not in {"id", "server_id", "time"}}- db.add(ContainerMetric(server_id=server.id, time=now, **allowed))+ db.add(ContainerMetric(server_id=server.id, time=now, **container))db.flush() # the rules read this check-in back from the history tablesthresholds = get_alert_thresholds(db)sync_alerts(db, server.id, HOST_RULE_PREFIX, host_rules(db, server, thresholds, active_rule_keys(db, server.id, HOST_RULE_PREFIX), get_mount_thresholds(db)))- sync_alerts(db, server.id, SYSTEM_RULE_PREFIX, system_rules(db, server, thresholds, now))+ sync_alerts(db, server.id, SYSTEM_RULE_PREFIX, system_rules(db, server, thresholds, now, active_rule_keys(db, server.id, SYSTEM_RULE_PREFIX)))# The collector sends no containers when Docker is unreachable; keep container alerts as they are rather than resolving them all.if containers:sync_alerts(db, server.id, CONTAINER_RULE_PREFIX, container_rules(db, server.id, containers, thresholds, now))diff --git a/src/backend/models.py b/src/backend/models.pyindex ca5a06c..522b246 100644--- a/src/backend/models.py+++ b/src/backend/models.py@@ -178,6 +178,11 @@ class HostMetric(Base):reboot_required: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)# How the previous boot ended (clean | unclean | unknown), from the optional system helper.last_shutdown: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)+ # Whether the collector could reach the Docker API (ok | unreachable | not_configured), why not, and how long+ # listing the containers took. Lets "Docker is down" be told apart from "there are no containers".+ docker_status: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)+ docker_reason: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)+ docker_latency_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)class SystemEvent(Base):@@ -232,6 +237,11 @@ class ContainerMetric(Base):started_at: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)ports: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)healthcheck_status: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)+ # How a stopped container ended, and the ID of the image it runs (to notice it changing).+ exit_code: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ oom_killed: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)+ finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ image_id: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)time: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), index=True, nullable=False)diff --git a/src/backend/rules.py b/src/backend/rules.pyindex 617b19f..509da3c 100644--- a/src/backend/rules.py+++ b/src/backend/rules.py@@ -15,6 +15,7 @@ from .models import ContainerMetric, HostMetric, MountMetric, SystemEventHOST_RULE_PREFIX = "host:"SYSTEM_RULE_PREFIX = "system:"+TREND_RULE_PREFIX = "trend:"DEFAULT_THRESHOLDS: dict[str, float | int] = {"disk_warning_pct": 85, "disk_critical_pct": 95,@@ -25,8 +26,12 @@ DEFAULT_THRESHOLDS: dict[str, float | int] = {# How many check-ins in a row a host metric must breach before an alert opens."sustained_checks": 3,"restart_loop_count": 3, "restart_loop_window_minutes": 30,- # How long a reboot or OOM kill keeps its alert open after it happened.+ # How long a reboot, OOM kill, container exit, removal or image change keeps its incident open after it happened."event_window_minutes": 60,+ # Listing containers slower than this (sustained) means the Docker daemon is struggling.+ "docker_slow_ms": 2000,+ # A container whose memory climbs steadily is flagged as a possible leak; see memory_trend_rules.+ "leak_window_hours": 12, "leak_min_mb_per_hour": 10, "leak_min_growth_pct": 20,}_LIMITS: dict[str, tuple[float, float]] = {@@ -35,8 +40,9 @@ _LIMITS: dict[str, tuple[float, float]] = {"sustained_checks": (1, 20),"restart_loop_count": (1, 100), "restart_loop_window_minutes": (5, 1440),"event_window_minutes": (5, 1440),+ "docker_slow_ms": (100, 60000), "leak_window_hours": (6, 72), "leak_min_mb_per_hour": (1, 10000),}-_INTEGER_KEYS = {"sustained_checks", "restart_loop_count", "restart_loop_window_minutes", "event_window_minutes"}+_INTEGER_KEYS = {"sustained_checks", "restart_loop_count", "restart_loop_window_minutes", "event_window_minutes", "docker_slow_ms", "leak_window_hours"}def validate_thresholds(values: dict, current: dict) -> dict:@@ -235,7 +241,16 @@ def validate_helper_events(raw, now: datetime) -> list[tuple[str, datetime, str,return events-def system_rules(db, server, thresholds: dict, now: datetime) -> dict[str, tuple[str, str, str]]:+DOCKER_REASONS = {+ "timeout": "the Docker API did not answer in time",+ "refused": "the connection to the Docker API was refused",+ "missing": "the Docker API socket does not exist",+ "denied": "access to the Docker API was denied",+ "error": "the Docker API returned an error",+}+++def system_rules(db, server, thresholds: dict, now: datetime, active_keys: frozenset | set = frozenset()) -> dict[str, tuple[str, str, str]]:"""Evaluate the system-state rules (reboots, OOM kills, kernel faults, clock sync, pending reboot)."""sustained = thresholds["sustained_checks"]samples = db.query(HostMetric).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc(), HostMetric.id.desc()).limit(sustained).all()@@ -264,11 +279,76 @@ def system_rules(db, server, thresholds: dict, now: datetime) -> dict[str, tuplefiring[f"{SYSTEM_RULE_PREFIX}kernel"] = (WARNING, f"Kernel on {host} reported faults", f"The kernel has flagged: {', '.join(faults)}. Check dmesg on the host for details; the flag clears after a reboot.")if len(samples) >= sustained and all(sample.ntp_synced is False for sample in samples):firing[f"{SYSTEM_RULE_PREFIX}ntp"] = (WARNING, f"Clock on {host} is not synchronized", "The system clock is not synced to a time source. Drifting clocks break TLS, logs and scheduled jobs. Check that chrony, systemd-timesyncd or ntpd is running.")+ if len(samples) >= sustained and all(sample.docker_status == "unreachable" for sample in samples):+ key = f"{SYSTEM_RULE_PREFIX}docker_unreachable"+ # A host that never had Docker working (or has none) isn't an incident; one that did and lost it is.+ # An already-open alert stays open even after the samples that proved it worked have been purged.+ if key in active_keys or db.query(HostMetric.id).filter(HostMetric.server_id == server.id, HostMetric.docker_status == "ok").first():+ firing[key] = (CRITICAL, f"Docker is unreachable on {host}", f"Container data has stopped updating because {DOCKER_REASONS.get(latest.docker_reason, DOCKER_REASONS['error'])}. Check that the Docker daemon (and the docker-proxy container) is running.")+ elif len(samples) >= sustained and all(sample.docker_status == "ok" and sample.docker_latency_ms is not None and sample.docker_latency_ms > thresholds["docker_slow_ms"] for sample in samples):+ firing[f"{SYSTEM_RULE_PREFIX}docker_slow"] = (WARNING, f"Docker is responding slowly on {host}", f"Listing containers took {latest.docker_latency_ms} ms (limit {thresholds['docker_slow_ms']} ms) for several check-ins in a row. The daemon may be overloaded or the host starved of resources.")if latest.reboot_required:firing[f"{SYSTEM_RULE_PREFIX}reboot_required"] = (INFO, f"{host} needs a reboot", "Installed updates (often a new kernel) only take effect after a restart.")return firing+CONTAINER_EVENT_KINDS = ("container_added", "container_removed", "image_changed", "container_notice")+MAX_CONTAINER_EVENTS_PER_CHECKIN = 10+MAX_CONTAINER_EVENTS_PER_HOUR = 40+# What a stopped container's exit status usually means; 137 and 143 are what `docker stop` / `docker kill` produce.+EXIT_HINTS = {1: "general error", 2: "misuse of a shell command", 126: "command not executable", 127: "command not found",+ 134: "aborted (SIGABRT)", 137: "killed (SIGKILL)", 139: "segmentation fault", 143: "terminated (SIGTERM)"}+STOP_SIGNAL_CODES = {137, 143}+++def _short_image(image_id: str) -> str:+ return image_id.removeprefix("sha256:")[:12]+++def detect_container_events(previous: list, containers: list[dict]) -> list[tuple[str, str, str]]:+ """(kind, detail, container name) for what changed since the previous check-in.++ Containers are matched by name, because Compose recreates them with new IDs. Nothing is reported on+ the first check-in or when either list is empty: an empty list means Docker was unreachable, and+ treating that as "everything vanished" would be a false alarm.+ """+ if not previous or not containers:+ return []+ before = {container.name: container for container in previous}+ after = {container["name"]: container for container in containers}+ events: list[tuple[str, str, str]] = []+ for name in sorted(after.keys() - before.keys()):+ image = (after[name].get("image") or "")[:60]+ events.append(("container_added", f"Container {name} appeared" + (f" ({image})" if image else ""), name))+ for name in sorted(before.keys() - after.keys()):+ events.append(("container_removed", f"Container {name} is no longer present", name))+ for name in sorted(after.keys() & before.keys()):+ old, new = before[name].image_id, after[name].get("image_id")+ if old and new and old != new:+ events.append(("image_changed", f"Container {name} now runs a different image build ({_short_image(old)} to {_short_image(new)})", name))+ return events+++def exit_rule(container: dict, thresholds: dict, now: datetime) -> tuple[str, str, str] | None:+ """Classify a container that has stopped. Unknown values (old collectors, no timestamp) never alert."""+ code, finished = container.get("exit_code"), container.get("finished_at")+ if container.get("status") not in ("exited", "dead") or code is None or finished is None:+ return None+ oom = container.get("oom_killed") is True+ if (code == 0 and not oom) or now - finished > timedelta(minutes=thresholds["event_window_minutes"]):+ return None+ name = container["name"]+ hint = EXIT_HINTS.get(code)+ detail = f"exit code {code}" + (f" ({hint})" if hint else "")+ if oom:+ return (CRITICAL, f"Container {name} was killed for running out of memory",+ f"{name} stopped ({detail}) after the kernel killed it for exceeding its memory. Raise its memory limit or look for a leak.")+ if code in STOP_SIGNAL_CODES:+ return (INFO, f"Container {name} was stopped by a signal",+ f"{name} ended with {detail}, which is what `docker stop` or `docker kill` produce, so this is usually deliberate. If it wasn't, check what stopped it.")+ return (WARNING, f"Container {name} exited with an error", f"{name} stopped with {detail}. Check its logs for the reason.")++def container_rules(db, server_id: int, containers: list[dict], thresholds: dict, now: datetime) -> dict[str, tuple[str, str, str]]:"""Evaluate the container rules for one check-in's container records."""window = thresholds["restart_loop_window_minutes"]@@ -286,6 +366,8 @@ def container_rules(db, server_id: int, containers: list[dict], thresholds: dictfor container in containers:# Compose recreates containers with new IDs but the same name, so key alerts by name.name = container.get("name") or container["container_id"]+ if exit_alert := exit_rule({**container, "name": name}, thresholds, now):+ firing[f"{CONTAINER_RULE_PREFIX}{name}:exit"] = exit_alertrestarts = int(container.get("restart_count") or 0) - earliest.get(container["container_id"], int(container.get("restart_count") or 0))if restarts >= thresholds["restart_loop_count"]:firing[f"{CONTAINER_RULE_PREFIX}{name}:restart_loop"] = (@@ -297,4 +379,91 @@ def container_rules(db, server_id: int, containers: list[dict], thresholds: dictCRITICAL, f"Container {name} is unhealthy",f"The Docker HEALTHCHECK for {name} is failing. Inspect it with: docker inspect --format '{{{{json .State.Health}}}}' {name}",)+ # Removals and image changes are noticed by comparing check-ins (see detect_container_events); the incident+ # stays open for the event window and clears on its own.+ present = {container.get("name") for container in containers}+ since = now - timedelta(minutes=thresholds["event_window_minutes"])+ for event in db.query(SystemEvent).filter(SystemEvent.server_id == server_id, SystemEvent.kind.in_(("container_removed", "image_changed")), SystemEvent.time >= since).order_by(SystemEvent.time.desc()):+ name = event.event_key+ if not name:+ continue+ if event.kind == "container_removed" and name not in present:+ firing[f"{CONTAINER_RULE_PREFIX}{name}:removed"] = (INFO, f"Container {name} is no longer present", f"{name} disappeared from this server. If you removed it on purpose this clears by itself.")+ elif event.kind == "image_changed" and name in present:+ firing[f"{CONTAINER_RULE_PREFIX}{name}:image"] = (INFO, f"Container {name} is running a different image", f"{event.detail}. Expected after an update or rebuild; investigate if you didn't make one.")+ return firing+++MAX_TREND_CONTAINERS = 100+MAX_TREND_ROWS = 300_000+MIN_SAMPLES_PER_BUCKET = 5+MIN_TREND_FIT = 0.9+++def _linear_fit(points: list[tuple[float, float]]) -> tuple[float, float, float] | None:+ """Least-squares (slope, intercept, R squared) for (x, y) points, or None if they don't define a line."""+ n = len(points)+ mean_x, mean_y = sum(x for x, _ in points) / n, sum(y for _, y in points) / n+ spread = sum((x - mean_x) ** 2 for x, _ in points)+ if not spread:+ return None+ slope = sum((x - mean_x) * (y - mean_y) for x, y in points) / spread+ intercept = mean_y - slope * mean_x+ total = sum((y - mean_y) ** 2 for _, y in points)+ residual = sum((y - (intercept + slope * x)) ** 2 for x, y in points)+ return slope, intercept, (1 - residual / total) if total else 0.0+++def memory_trend_rules(db, server_id: int, thresholds: dict, now: datetime) -> dict[str, tuple[str, str, str]]:+ """Flag running containers whose memory climbs steadily as a possible leak.++ Hourly averages over the window must be nearly complete, rise at least ``leak_min_mb_per_hour`` and+ ``leak_min_growth_pct`` along a straight line (R squared at least 0.9), and the container must not+ have restarted or been recreated in the window, since either resets its memory. Work is bounded:+ at most 100 containers and 300,000 samples per server.+ """+ window = thresholds["leak_window_hours"]+ since = now - timedelta(hours=window)+ host_time = db.query(func.max(HostMetric.time)).filter(HostMetric.server_id == server_id).scalar()+ if host_time is None:+ return {}+ current = {+ row.name: row for row in db.query(ContainerMetric)+ .filter(ContainerMetric.server_id == server_id, ContainerMetric.time == host_time, ContainerMetric.status == "running")+ .order_by(ContainerMetric.name).limit(MAX_TREND_CONTAINERS)+ }+ if not current:+ return {}+ samples: dict[str, list] = {}+ for name, time, used, restarts, container_id in (+ db.query(ContainerMetric.name, ContainerMetric.time, ContainerMetric.memory_used_mb, ContainerMetric.restart_count, ContainerMetric.container_id)+ .filter(ContainerMetric.server_id == server_id, ContainerMetric.time >= since, ContainerMetric.name.in_(list(current)), ContainerMetric.memory_used_mb.isnot(None))+ .order_by(ContainerMetric.time).limit(MAX_TREND_ROWS)+ ):+ samples.setdefault(name, []).append((time if time.tzinfo else time.replace(tzinfo=timezone.utc), used, restarts, container_id))++ firing: dict[str, tuple[str, str, str]] = {}+ for name, rows in samples.items():+ if len({row[2] for row in rows}) > 1 or len({row[3] for row in rows}) > 1:+ continue # restarted or recreated: memory was reset, so the trend means nothing+ buckets: dict[int, list[float]] = {}+ for time, used, _restarts, _id in rows:+ buckets.setdefault(int((time - since).total_seconds() // 3600), []).append(used)+ points = [(float(bucket), sum(values) / len(values)) for bucket, values in sorted(buckets.items()) if len(values) >= MIN_SAMPLES_PER_BUCKET]+ if len(points) < max(4, round(window * 0.75)):+ continue+ fit = _linear_fit(points)+ if not fit:+ continue+ slope, intercept, r_squared = fit+ start, end = intercept + slope * points[0][0], intercept + slope * points[-1][0]+ growth = (end - start) / max(start, 1.0) * 100+ if slope < thresholds["leak_min_mb_per_hour"] or growth < thresholds["leak_min_growth_pct"] or r_squared < MIN_TREND_FIT:+ continue+ limit = current[name].memory_limit_mb+ eta = f" At this rate it reaches its {limit:.0f} MB limit in about {(limit - end) / slope:.0f} hours." if limit and limit > end else ""+ firing[f"{TREND_RULE_PREFIX}{name}:memory"] = (+ WARNING, f"Container {name} may have a memory leak",+ f"Memory use rose steadily by about {slope:.1f} MB per hour over the last {window} hours ({start:.0f} MB to {end:.0f} MB).{eta} Caches and warm-up can look like this too, so check whether it keeps growing.",+ )return firingdiff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsxindex d6ebdbe..cc75218 100644--- a/src/frontend/src/App.jsx+++ b/src/frontend/src/App.jsx@@ -631,6 +631,14 @@ function Chevron({ open, className = '' }) {const CONTAINER_SEARCH_MIN = 10const byName = (a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base', numeric: true })+const CONTAINER_EVENT_LABELS = { container_added: 'Added', container_removed: 'Removed', image_changed: 'Image change', container_notice: 'Notice' }+const CONTAINER_EVENT_CLASSES = { container_added: 'text-emerald-300', container_removed: 'text-amber-300', image_changed: 'text-sky-300', container_notice: 'text-[#9aa0a6]' }++function DockerNotice({ host }) {+ const reasons = { timeout: 'it did not answer in time', refused: 'the connection was refused', missing: 'its socket is missing', denied: 'access was denied', error: 'it returned an error' }+ return <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 px-3 py-2.5 text-sm text-amber-200">Docker is unreachable{host.docker_reason ? `: ${reasons[host.docker_reason] || reasons.error}` : ''}. Container data is not updating until it is back.</div>+}+function ContainerSection({ server, open, onToggle }) {const [query, setQuery] = useState('')const containers = [...server.containers].sort(byName)@@ -656,6 +664,18 @@ function ContainerSection({ server, open, onToggle }) {<div className="border-t border-neutral-800 px-3 pb-2">{containers.length > CONTAINER_SEARCH_MIN && <input type="search" value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Filter by name or image" aria-label={`Filter containers on ${server.hostname}`} className="mt-3 w-full rounded-lg border border-neutral-800 bg-[#0d1013] px-3 py-1.5 text-sm text-[#cfcfcf] outline-none focus:border-white/30" />}{shown.length ? <ContainerTable serverId={server.id} containers={shown} /> : <p className="py-3 text-sm text-[#9aa0a6]">No containers match “{query.trim()}”.</p>}+ {server.container_events?.length > 0 && (+ <div className="mt-2 border-t border-neutral-800 pt-3">+ <div className="mb-2 text-xs uppercase tracking-[0.2em] text-[#7f8589]">Recent changes · 7 days</div>+ <ul className="space-y-1.5 pb-1 text-sm">{server.container_events.map((event, index) => (+ <li key={`${event.time}-${event.kind}-${index}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">+ <span className="w-24 shrink-0 text-xs text-[#7f8589]" title={new Date(event.time).toLocaleString()}>{formatAgo(event.time)}</span>+ <span className={`w-24 shrink-0 text-xs font-medium ${CONTAINER_EVENT_CLASSES[event.kind] || 'text-[#cfcfcf]'}`}>{CONTAINER_EVENT_LABELS[event.kind] || event.kind}</span>+ <span className="min-w-0 flex-1 basis-60 break-words text-[#bcbcbc]">{event.detail}</span>+ </li>+ ))}</ul>+ </div>+ )}</div>)}</div>@@ -880,6 +900,7 @@ const refresh = async () => {{!collapsed && <>{metric ? <div className="mt-5 grid grid-cols-2 gap-3 lg:grid-cols-4">{[['CPU', metric.cpu_utilization_pct, '%'], ['RAM', metric.ram_pct, '%'], [fullest ? `Disk · ${fullest.mount}` : 'Disk', fullest?.used_pct, '%'], ['Load (1m)', metric.load_1m, '']].map(([label, value, unit]) => <div key={label} className="rounded-xl bg-[#171b1f] p-3"><div className="truncate text-xs text-[#9aa0a6]" title={label}>{label}</div><div className="mt-1 text-xl font-semibold text-white">{value == null ? '—' : `${Number(value).toFixed(1)}${unit}`}</div></div>)}</div> : <div className="mt-4 rounded-xl bg-[#171b1f] p-4 text-sm text-[#9aa0a6]">Collector has not sent a measurement yet.</div>}{metric && <StorageBars mounts={mounts} thresholds={overview.disk_thresholds} mountThresholds={overview.mount_thresholds} />}+ {metric?.docker_status === 'unreachable' && <DockerNotice host={metric} />}{metric && <SystemSection server={server} open={openSystemLists.has(server.id)} onToggle={() => toggleSystemList(server.id)} />}{server.containers.length > 0 && <ContainerSection server={server} open={openContainerLists.has(server.id)} onToggle={() => toggleContainerList(server.id)} />}<div className="mt-3 text-xs text-[#7f8589]">Last check: {server.last_seen_at ? new Date(server.last_seen_at).toLocaleString() : 'Never'}</div>@@ -1148,7 +1169,8 @@ function formatUptime(startedAt) {}function ContainerStatus({ container }) {- return <span className="whitespace-nowrap"><span className={container.status === 'running' ? 'text-emerald-300' : container.status === 'restarting' ? 'text-red-300' : 'text-amber-300'}>{container.status}</span>{container.healthcheck_status && <span className={HEALTH_CLASSES[container.healthcheck_status] || 'text-[#7f8589]'}> · {container.healthcheck_status}</span>}</span>+ const stopped = container.status === 'exited' || container.status === 'dead'+ return <span className="whitespace-nowrap"><span className={container.status === 'running' ? 'text-emerald-300' : container.status === 'restarting' ? 'text-red-300' : 'text-amber-300'}>{container.status}</span>{stopped && container.exit_code != null && <span className={container.oom_killed ? 'text-red-300' : container.exit_code === 0 ? 'text-[#7f8589]' : 'text-amber-300'}> · {container.oom_killed ? 'out of memory' : `code ${container.exit_code}`}</span>}{container.healthcheck_status && <span className={HEALTH_CLASSES[container.healthcheck_status] || 'text-[#7f8589]'}> · {container.healthcheck_status}</span>}</span>}const formatContainerCpu = (c) => (c.cpu_pct == null ? '—' : `${c.cpu_pct}%`)@@ -1887,9 +1909,21 @@ function IncidentThresholdsSection() {</span></div><label className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">- <span><span className="text-[#bcbcbc]">Reboot and OOM-kill incidents</span><span className="block text-xs text-[#7f8589]">Minutes an incident stays open after the event</span></span>+ <span><span className="text-[#bcbcbc]">Event incidents</span><span className="block text-xs text-[#7f8589]">Minutes an incident stays open after a reboot, OOM kill, container exit, removal or image change</span></span><ThresholdInput label="Event incident window in minutes" value={values?.event_window_minutes} step={1} onChange={set('event_window_minutes')} disabled={loading} /></label>+ <label className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">+ <span><span className="text-[#bcbcbc]">Slow Docker</span><span className="block text-xs text-[#7f8589]">Milliseconds to list containers before Docker counts as slow (sustained)</span></span>+ <ThresholdInput label="Slow Docker threshold in milliseconds" value={values?.docker_slow_ms} step={100} onChange={set('docker_slow_ms')} disabled={loading} />+ </label>+ <div className="flex flex-col gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:py-2.5">+ <span className="shrink-0"><span className="text-[#bcbcbc]">Possible memory leak</span><span className="block text-xs text-[#7f8589]">Warning when a container's memory climbs steadily</span></span>+ <span className="flex flex-wrap items-center gap-2 text-xs text-[#9aa0a6]">+ <ThresholdInput label="Leak window in hours" value={values?.leak_window_hours} step={1} onChange={set('leak_window_hours')} disabled={loading} />h, at least+ <ThresholdInput label="Leak minimum MB per hour" value={values?.leak_min_mb_per_hour} step={1} onChange={set('leak_min_mb_per_hour')} disabled={loading} />MB/h and+ <ThresholdInput label="Leak minimum growth percent" value={values?.leak_min_growth_pct} step={1} onChange={set('leak_min_growth_pct')} disabled={loading} />%+ </span>+ </div><div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm"><div className="flex flex-wrap items-center justify-between gap-2"><span><span className="text-[#bcbcbc]">Disk usage per mount</span><span className="block text-xs text-[#7f8589]">Replaces the default disk thresholds for that mount, on every server</span></span>diff --git a/tests/test_alerts.py b/tests/test_alerts.pyindex d002870..2b8e017 100644--- a/tests/test_alerts.py+++ b/tests/test_alerts.py@@ -91,7 +91,8 @@ def test_removed_container_alert_resolves_when_others_report(db):_ingest(db, [_container("web", health="unhealthy"), _container("db")])_ingest(db, [_container("db")])- assert _active(db) == []+ # The unhealthy incident is gone with the container; what remains is only the informational removal notice.+ assert [(alert.rule_key, alert.severity) for alert in _active(db)] == [("container:web:removed", alerts.INFO)]def test_empty_container_list_keeps_container_alerts(db):diff --git a/tests/test_container_checks.py b/tests/test_container_checks.pynew file mode 100644index 0000000..ae535c0--- /dev/null+++ b/tests/test_container_checks.py@@ -0,0 +1,609 @@+import math+import os+import socket+from datetime import datetime, timedelta, timezone++os.environ.setdefault("DATABASE_URL", "sqlite://")+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from src.agent import collector+from src.backend import alerts, main, rules+from src.backend.models import Base, ContainerMetric, HostMetric, IncidentAlert, Server, SystemEvent, User++TOKEN = "collector-token"+IMAGE_A, IMAGE_B = "sha256:" + "a" * 64, "sha256:" + "b" * 64+++def db():+ engine = create_engine("sqlite://")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin"))+ session.add(Server(id=5, owner_id=1, hostname="nas", check_interval_seconds=60, collector_token_hash=main._hash_secret(TOKEN)))+ session.commit()+ return session+++def _ingest(db, containers=(), **host):+ main.ingest_metrics(main.MetricsIngestRequest(server_id=5, host=host, containers=list(containers)), authorization=f"Bearer {TOKEN}", session_id=None, db=db)+++def _c(name, status="running", **extra):+ return {"container_id": f"id-{name}", "name": name, "status": status, **extra}+++def _stamp(minutes_ago):+ return (datetime.now(timezone.utc) - timedelta(minutes=minutes_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _active(db):+ return {alert.rule_key: alert for alert in db.query(IncidentAlert).filter_by(status="active")}+++def _events(db, *kinds):+ return [(event.kind, event.detail, event.event_key) for event in db.query(SystemEvent).filter(SystemEvent.kind.in_(kinds or rules.CONTAINER_EVENT_KINDS)).order_by(SystemEvent.id)]+++# --- collector: Docker status (#22) -----------------------------------------------------------------++def _clear_docker_env(monkeypatch, tmp_path):+ monkeypatch.delenv("HOMELAB_DOCKER_HOST", raising=False)+ monkeypatch.setenv("DOCKER_SOCKET_PATH", str(tmp_path / "no-such-docker.sock"))+++def test_a_host_without_docker_is_not_configured_not_broken(monkeypatch, tmp_path):+ _clear_docker_env(monkeypatch, tmp_path)++ assert collector.collect_docker() == ([], {"docker_status": "not_configured", "docker_reason": None, "docker_latency_ms": None})+++def test_a_configured_but_missing_proxy_socket_is_unreachable(monkeypatch, tmp_path):+ monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(tmp_path / "proxy.sock"))++ _containers, status = collector.collect_docker()++ assert (status["docker_status"], status["docker_reason"]) == ("unreachable", "missing")+++def test_a_stale_socket_nobody_listens_on_is_reported_as_refused(monkeypatch, tmp_path):+ path = str(tmp_path / "stale.sock")+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ listener.bind(path)+ listener.close() # leaves the socket file behind, like a stopped proxy+ monkeypatch.setenv("HOMELAB_DOCKER_HOST", path)++ containers, status = collector.collect_docker()++ assert containers == [] and (status["docker_status"], status["docker_reason"]) == ("unreachable", "refused")++[email protected]("error, reason", [+ (TimeoutError(), "timeout"), (ConnectionRefusedError(), "refused"), (FileNotFoundError(), "missing"), (PermissionError(), "denied"),+ (OSError("Docker API returned HTTP 502"), "error"), (ValueError("bad json"), "error"), (RuntimeError("secret detail"), "error"),+])+def test_failures_map_to_a_fixed_vocabulary_never_raw_text(error, reason):+ assert collector._docker_failure_reason(error) == reason+++def test_a_working_daemon_reports_ok_with_its_latency(monkeypatch, tmp_path):+ socket_path = tmp_path / "docker.sock"+ socket_path.touch()+ cid = "c" * 64+ answers = {"/containers/json?all=1": [{"Id": cid, "Names": ["/web"]}], f"/containers/{cid}/json": {"Name": "/web", "State": {"Status": "running"}, "Config": {"Image": "nginx"}}}+ monkeypatch.setattr(collector, "_docker_request", lambda path, endpoint: answers.get(endpoint, {}))+ monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))++ containers, status = collector.collect_docker()++ assert [c["name"] for c in containers] == ["web"]+ assert status["docker_status"] == "ok" and isinstance(status["docker_latency_ms"], int) and status["docker_latency_ms"] >= 0+++def test_a_daemon_error_during_listing_is_unreachable(monkeypatch, tmp_path):+ socket_path = tmp_path / "docker.sock"+ socket_path.touch()+ monkeypatch.setattr(collector, "_docker_request", lambda path, endpoint: (_ for _ in ()).throw(OSError("Docker API returned HTTP 502")))+ monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))++ containers, status = collector.collect_docker()++ assert containers == [] and (status["docker_status"], status["docker_reason"]) == ("unreachable", "error")+++def test_one_container_vanishing_mid_collection_does_not_fail_the_rest(monkeypatch, tmp_path):+ socket_path = tmp_path / "docker.sock"+ socket_path.touch()+ a, b = "a" * 64, "b" * 64++ def request(path, endpoint):+ if endpoint == "/containers/json?all=1":+ return [{"Id": a, "Names": ["/gone"]}, {"Id": b, "Names": ["/web"]}]+ if endpoint == f"/containers/{a}/json":+ raise OSError("Docker API returned HTTP 502") # removed between listing and inspecting+ return {"Name": "/web", "State": {"Status": "exited"}}++ monkeypatch.setattr(collector, "_docker_request", request)+ monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))++ containers, status = collector.collect_docker()++ assert [c["name"] for c in containers] == ["web"] and status["docker_status"] == "ok"+++def test_when_nothing_can_be_inspected_the_daemon_is_failing_not_empty(monkeypatch, tmp_path):+ socket_path = tmp_path / "docker.sock"+ socket_path.touch()++ def request(path, endpoint):+ if endpoint == "/containers/json?all=1":+ return [{"Id": "a" * 64, "Names": ["/web"]}]+ raise OSError("Docker API returned HTTP 502")++ monkeypatch.setattr(collector, "_docker_request", request)+ monkeypatch.setenv("HOMELAB_DOCKER_HOST", str(socket_path))++ containers, status = collector.collect_docker()++ assert containers == [] and status["docker_status"] == "unreachable"+++# --- collector: exit status and image ID (#19, #21) -------------------------------------------------++def _collect_one(monkeypatch, tmp_path, **state_and_detail):+ socket_path = tmp_path / "docker.sock"+ socket_path.touch()+ cid = "d" * 64+ detail = {"Name": "/job", "Config": {"Image": "busybox"}, "State": {"Status": "exited"}, **state_and_detail}+ monkeypatch.setattr(collector, "_docker_request", lambda path, endpoint: [{"Id": cid, "Names": ["/job"]}] if "json?all" in endpoint else detail)+ return collector.collect_containers(str(socket_path))[0]+++def test_a_stopped_container_reports_how_it_ended(monkeypatch, tmp_path):+ container = _collect_one(monkeypatch, tmp_path, Image=IMAGE_A, State={"Status": "exited", "ExitCode": 137, "OOMKilled": True, "FinishedAt": "2026-10-04T10:11:12.123456789Z"})++ assert (container["exit_code"], container["oom_killed"], container["finished_at"], container["image_id"]) == (137, True, "2026-10-04T10:11:12Z", IMAGE_A)+++def test_a_running_container_does_not_report_a_stale_exit_status(monkeypatch, tmp_path):+ container = _collect_one(monkeypatch, tmp_path, State={"Status": "running", "ExitCode": 1, "OOMKilled": True, "FinishedAt": "2026-10-04T10:11:12Z"})++ assert (container["exit_code"], container["oom_killed"], container["finished_at"]) == (None, None, None)++[email protected]("state", [+ {"ExitCode": "1"}, {"ExitCode": True}, {"ExitCode": 99999999}, {"ExitCode": -5}, {"ExitCode": 1.5}, {"ExitCode": None},+ {"ExitCode": 1, "OOMKilled": "yes"}, {"ExitCode": 1, "FinishedAt": "0001-01-01T00:00:00Z"}, {"ExitCode": 1, "FinishedAt": "garbage"}, {"ExitCode": 1, "FinishedAt": 12345},+])+def test_malformed_exit_details_become_unknown(monkeypatch, tmp_path, state):+ container = _collect_one(monkeypatch, tmp_path, State={"Status": "exited", **state})++ assert container["exit_code"] in (None, 1) and container["oom_killed"] is None and container["finished_at"] is None++[email protected]("image_id", ["sha256:abc", "nginx:latest", "sha256:" + "G" * 64, "sha256:" + "a" * 65, "", None, 5, ["x"]])+def test_only_a_well_formed_image_id_is_passed_on(monkeypatch, tmp_path, image_id):+ assert _collect_one(monkeypatch, tmp_path, Image=image_id)["image_id"] is None+++# --- backend: Docker health rules (#22) -------------------------------------------------------------++def test_docker_unreachable_alerts_only_after_it_worked_and_only_when_sustained(db):+ _ingest(db, docker_status="ok", docker_latency_ms=20)+ _ingest(db, docker_status="unreachable", docker_reason="refused")+ _ingest(db, docker_status="unreachable", docker_reason="refused")+ assert "system:docker_unreachable" not in _active(db)++ _ingest(db, docker_status="unreachable", docker_reason="refused")+ alert = _active(db)["system:docker_unreachable"]+ assert alert.severity == alerts.CRITICAL and "refused" in alert.description++ _ingest(db, docker_status="ok", docker_latency_ms=15)+ assert "system:docker_unreachable" not in _active(db)+++def test_a_host_that_never_had_working_docker_never_alerts(db):+ for _ in range(5):+ _ingest(db, docker_status="unreachable", docker_reason="missing")+ for _ in range(5):+ _ingest(db, docker_status="not_configured")++ assert not [key for key in _active(db) if "docker" in key]+++def test_an_open_docker_alert_survives_the_purge_of_the_samples_that_proved_it_worked(db):+ _ingest(db, docker_status="ok", docker_latency_ms=10)+ for _ in range(3):+ _ingest(db, docker_status="unreachable", docker_reason="timeout")+ assert "system:docker_unreachable" in _active(db)++ db.query(HostMetric).filter(HostMetric.docker_status == "ok").delete()+ db.commit()+ _ingest(db, docker_status="unreachable", docker_reason="timeout")++ assert "system:docker_unreachable" in _active(db)+++def test_slow_docker_warns_when_sustained_and_clears_when_fast(db):+ for _ in range(2):+ _ingest(db, docker_status="ok", docker_latency_ms=9000)+ assert "system:docker_slow" not in _active(db)+ _ingest(db, docker_status="ok", docker_latency_ms=9000)+ assert _active(db)["system:docker_slow"].severity == alerts.WARNING++ _ingest(db, docker_status="ok", docker_latency_ms=30)+ assert "system:docker_slow" not in _active(db)+++def test_missing_docker_data_from_old_collectors_never_alerts(db):+ for _ in range(5):+ _ingest(db, [_c("web")])++ assert not [key for key in _active(db) if "docker" in key]+++def test_malformed_docker_fields_are_dropped(db):+ from src.backend.models import HostMetric as Host+ _ingest(db, docker_status="<script>", docker_reason="rm -rf /", docker_latency_ms="fast")+ _ingest(db, docker_status="ok", docker_reason="timeout", docker_latency_ms=10**9)++ rows = db.query(Host).order_by(Host.id).all()+ assert [(r.docker_status, r.docker_reason, r.docker_latency_ms) for r in rows] == [(None, None, None), ("ok", "timeout", None)]+++# --- backend: exit codes (#19) ----------------------------------------------------------------------+[email protected]("code, oom, severity, words", [+ (1, False, alerts.WARNING, "exited with an error"),+ (127, False, alerts.WARNING, "command not found"),+ (137, False, alerts.INFO, "stopped by a signal"),+ (143, False, alerts.INFO, "stopped by a signal"),+ (137, True, alerts.CRITICAL, "running out of memory"),+])+def test_stopped_containers_are_classified_by_how_they_ended(db, code, oom, severity, words):+ _ingest(db, [_c("job", "exited", exit_code=code, oom_killed=oom, finished_at=_stamp(5))])++ alert = _active(db)["container:job:exit"]+ assert alert.severity == severity and words in (alert.title + alert.description)++[email protected]("container", [+ _c("job", "exited", exit_code=0, oom_killed=False, finished_at="NOW"),+ _c("job", "exited", exit_code=1, finished_at=None),+ _c("job", "exited", exit_code=None, finished_at="NOW"),+ _c("job", "running", exit_code=1, finished_at="NOW"),+ _c("job", "created", exit_code=1, finished_at="NOW"),+])+def test_clean_exits_unknown_and_running_containers_never_alert(db, container):+ if container.get("finished_at") == "NOW":+ container = {**container, "finished_at": _stamp(5)}+ _ingest(db, [container])++ assert "container:job:exit" not in _active(db)+++def test_an_old_exit_is_not_an_incident_and_a_restart_clears_it(db):+ _ingest(db, [_c("old", "exited", exit_code=1, finished_at=_stamp(60 * 5))])+ assert "container:old:exit" not in _active(db)++ _ingest(db, [_c("job", "exited", exit_code=1, finished_at=_stamp(5))])+ assert "container:job:exit" in _active(db)+ _ingest(db, [_c("job", "running")])+ assert "container:job:exit" not in _active(db)+++# --- backend: what a collector may send about containers --------------------------------------------++def _clean(raw):+ return main._clean_container(raw, datetime.now(timezone.utc))++[email protected]("raw", [None, 5, "x", [], {}, {"container_id": "a"}, {"status": "running"}, {"container_id": 5, "status": "running"}, {"container_id": "a", "status": 5}, {"container_id": "", "status": "running"}, {"container_id": "a", "status": " "}])+def test_unusable_container_records_are_dropped(raw):+ assert _clean(raw) is None+++def test_container_text_is_made_printable_and_bounded():+ clean = _clean({"container_id": "id\x00" + "x" * 500, "status": "RUNNING\n", "name": "web\x1b[31m" + "n" * 600, "image": "i" * 600, "ports": "p" * 2000, "healthcheck_status": "h" * 200, "started_at": "s" * 200})++ assert len(clean["container_id"]) == 128 and len(clean["name"]) == main.MAX_CONTAINER_NAME and len(clean["image"]) == 255 and len(clean["ports"]) == 512+ assert clean["status"] == "running" and "\x1b" not in clean["name"] and "\x00" not in clean["container_id"]+ assert len(clean["healthcheck_status"]) == 64 and len(clean["started_at"]) == 64+++def test_a_missing_name_falls_back_to_the_container_id():+ assert _clean({"container_id": "abcdef0123456789", "status": "running"})["name"] == "abcdef012345"++[email protected]("bad", ["12", True, -1, math.nan, math.inf, 1e13, None, [1], {"a": 1}])+def test_numeric_fields_must_be_real_in_range_numbers(bad):+ clean = _clean({"container_id": "a", "status": "running", "cpu_pct": bad, "memory_used_mb": bad, "pids": bad, "restart_count": bad, "exit_code": bad})++ assert clean["cpu_pct"] is None and clean["memory_used_mb"] is None and clean["pids"] is None and clean["restart_count"] == 0+ assert clean["exit_code"] is None or clean["exit_code"] == -1+++def test_sane_numbers_pass_through():+ clean = _clean({"container_id": "a", "status": "exited", "cpu_pct": 12.5, "memory_pct": 3, "pids": 7, "restart_count": 2, "exit_code": 137, "oom_killed": True, "image_id": IMAGE_A})++ assert (clean["cpu_pct"], clean["memory_pct"], clean["pids"], clean["restart_count"], clean["exit_code"], clean["oom_killed"], clean["image_id"]) == (12.5, 3.0, 7, 2, 137, True, IMAGE_A)++[email protected]("value", ["garbage", "2026-10-04", "2026-10-04T10:11:12", "2026-10-04T10:11:12.5Z", "1999-12-31T23:59:59Z", "2999-01-01T00:00:00Z", 5, None, ["x"]])+def test_finish_times_must_be_exact_recent_utc_timestamps(value):+ assert _clean({"container_id": "a", "status": "exited", "finished_at": value})["finished_at"] is None+++def test_a_valid_finish_time_becomes_an_aware_datetime():+ finished = _clean({"container_id": "a", "status": "exited", "finished_at": "2026-10-04T10:11:12Z"})["finished_at"]++ assert finished == datetime(2026, 10, 4, 10, 11, 12, tzinfo=timezone.utc)+++def test_unknown_fields_are_not_passed_to_the_database():+ clean = _clean({"container_id": "a", "status": "running", "id": 99, "server_id": 7, "time": "now", "evil": "x"})++ assert not {"id", "server_id", "time", "evil"} & clean.keys()+++def test_the_api_schema_already_refuses_container_entries_that_are_not_objects():+ from pydantic import ValidationError+ for junk in ([None], [5], ["x"], [[1]]):+ with pytest.raises(ValidationError):+ main.MetricsIngestRequest(server_id=5, containers=junk)+++def test_hostile_container_records_never_break_ingest_or_other_data(db):+ hostile = [{"container_id": "a" * 1000, "status": "running", "cpu_pct": "NaN", "exit_code": "1", "finished_at": {"x": 1}},+ {"container_id": "ok", "status": "running", "name": "fine", "memory_used_mb": float("inf")},+ {"container_id": "dropped", "status": 5}]+ _ingest(db, hostile, cpu_utilization_pct=12)++ stored = db.query(ContainerMetric).order_by(ContainerMetric.id).all()+ # Unusable records vanish; the odd ones are kept with unusable values turned into "unknown".+ assert [c.name for c in stored] == ["a" * 12, "fine"]+ assert stored[0].cpu_pct is None and stored[0].exit_code is None and stored[0].finished_at is None and stored[1].memory_used_mb is None+ assert db.query(HostMetric).one().cpu_utilization_pct == 12 # the host's own data was still recorded+++def test_no_more_than_500_containers_are_accepted_per_check_in(db):+ _ingest(db, [_c(f"c{number}") for number in range(600)])++ assert db.query(ContainerMetric).count() == main.MAX_CONTAINERS_PER_CHECKIN+++# --- backend: inventory changes and image drift (#16, #21) ------------------------------------------++def test_the_first_check_in_is_only_a_baseline(db):+ _ingest(db, [_c("web", image_id=IMAGE_A), _c("db")])++ assert _events(db) == []+++def test_new_and_missing_containers_are_recorded(db):+ _ingest(db, [_c("web"), _c("db")])+ _ingest(db, [_c("web"), _c("cache", image="redis:7")])++ assert _events(db) == [("container_added", "Container cache appeared (redis:7)", "cache"), ("container_removed", "Container db is no longer present", "db")]+++def test_a_removed_container_opens_an_informational_incident_that_clears_with_the_window(db):+ _ingest(db, [_c("web"), _c("db")])+ _ingest(db, [_c("web")])+ assert _active(db)["container:db:removed"].severity == alerts.INFO++ db.query(SystemEvent).update({"time": datetime.now(timezone.utc) - timedelta(hours=3)})+ db.commit()+ _ingest(db, [_c("web")])++ assert "container:db:removed" not in _active(db)+++def test_a_container_that_comes_back_clears_its_removal_incident(db):+ _ingest(db, [_c("web"), _c("db")])+ _ingest(db, [_c("web")])+ _ingest(db, [_c("web"), _c("db")])++ assert "container:db:removed" not in _active(db)+++def test_containers_are_matched_by_name_so_recreation_is_not_a_change(db):+ _ingest(db, [{"container_id": "old-id", "name": "web", "status": "running", "image_id": IMAGE_A}])+ _ingest(db, [{"container_id": "new-id", "name": "web", "status": "running", "image_id": IMAGE_A}])++ assert _events(db) == []+++def test_an_empty_list_never_looks_like_everything_vanished_or_reappeared(db):+ _ingest(db, [_c("web"), _c("db")])+ _ingest(db, [], docker_status="unreachable", docker_reason="refused")+ _ingest(db, [_c("web"), _c("db")])++ assert _events(db) == []+++def test_a_changed_image_is_recorded_and_raises_an_informational_incident(db):+ _ingest(db, [_c("web", image_id=IMAGE_A)])+ _ingest(db, [_c("web", image_id=IMAGE_B)])++ [(kind, detail, name)] = _events(db)+ assert (kind, name) == ("image_changed", "web") and "aaaaaaaaaaaa to bbbbbbbbbbbb" in detail+ assert _active(db)["container:web:image"].severity == alerts.INFO+++def test_the_same_image_or_an_unknown_one_is_not_a_change(db):+ _ingest(db, [_c("same", image_id=IMAGE_A), _c("unknown")])+ _ingest(db, [_c("same", image_id=IMAGE_A), _c("unknown", image_id=IMAGE_B)])+ _ingest(db, [_c("same", image_id=IMAGE_A), _c("unknown", image_id=None)])++ assert _events(db) == []+++def test_a_burst_of_changes_is_capped_per_check_in_with_one_notice(db):+ _ingest(db, [_c("web")])+ _ingest(db, [_c("web")] + [_c(f"ci-{number}") for number in range(25)])++ kinds = [kind for kind, _detail, _name in _events(db)]+ assert kinds.count("container_added") == rules.MAX_CONTAINER_EVENTS_PER_CHECKIN and kinds.count("container_notice") == 1+++def test_sustained_churn_is_capped_per_hour(db):+ _ingest(db, [_c("web")])+ for round_number in range(10):+ _ingest(db, [_c("web")] + [_c(f"ci-{round_number}-{number}") for number in range(20)])++ kinds = [kind for kind, _detail, _name in _events(db)]+ assert len(kinds) <= rules.MAX_CONTAINER_EVENTS_PER_HOUR + 1 and kinds.count("container_notice") == 1+++def test_container_changes_have_their_own_list_and_do_not_crowd_the_system_row(db, monkeypatch):+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1})+ db.add(SystemEvent(server_id=5, time=datetime.now(timezone.utc) - timedelta(days=2), kind="reboot", detail="The host rebooted"))+ db.commit()+ _ingest(db, [_c("web")])+ _ingest(db, [_c("web")] + [_c(f"ci-{number}") for number in range(8)])++ server = main.monitoring_overview(session_id="s", db=db)["servers"][0]++ assert [event["kind"] for event in server["system_events"]] == ["reboot"]+ assert len(server["container_events"]) == 8 and {event["kind"] for event in server["container_events"]} == {"container_added"}+++def test_the_container_change_list_is_bounded(db, monkeypatch):+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1})+ for number in range(40):+ db.add(SystemEvent(server_id=5, time=datetime.now(timezone.utc) - timedelta(minutes=number), kind="container_added", detail=f"Container c{number} appeared", event_key=f"c{number}"))+ db.commit()++ assert len(main.monitoring_overview(session_id="s", db=db)["servers"][0]["container_events"]) == main.CONTAINER_EVENTS_SHOWN+++def test_container_events_follow_the_normal_retention(db):+ old = datetime.now(timezone.utc) - timedelta(days=40)+ db.add_all([SystemEvent(server_id=5, time=old, kind=kind, detail="x", event_key="x") for kind in rules.CONTAINER_EVENT_KINDS])+ db.commit()++ assert main.purge_old_metrics(db) == len(rules.CONTAINER_EVENT_KINDS)+ assert db.query(SystemEvent).count() == 0+++# --- backend: memory leak trends (#20) --------------------------------------------------------------++def _seed_memory(db, name="app", hours=12, per_hour=6, value=lambda hour: 200 + 20 * hour, restart=0, container_id="cid", limit=None, status="running", skip_hours=()):+ """Samples spread over the window, ending a few minutes before now, plus the check-in that makes them current."""+ now = datetime.now(timezone.utc)+ since = now - timedelta(hours=hours)+ last = None+ for hour in range(hours):+ if hour in skip_hours:+ continue+ for k in range(per_hour):+ last = since + timedelta(minutes=hour * 60 + k * 10 + 5)+ db.add(ContainerMetric(server_id=5, container_id=container_id, name=name, status=status, restart_count=restart, memory_used_mb=float(value(hour + k / per_hour)), memory_limit_mb=limit, time=last))+ db.add(HostMetric(server_id=5, time=last))+ db.commit()+ return now+++def _trend(db, now=None):+ main.analyze_memory_trends(db, now=now)+ return {key: alert for key, alert in _active(db).items() if key.startswith("trend:")}+++def test_steady_growth_is_flagged_as_a_possible_leak(db):+ now = _seed_memory(db, limit=2048.0)++ alert = _trend(db, now)["trend:app:memory"]++ assert alert.severity == alerts.WARNING and "possible" not in alert.title.lower() and "memory leak" in alert.title+ assert "20.0 MB per hour" in alert.description and "2048 MB limit" in alert.description+++def test_flat_noisy_and_sawtooth_memory_is_not_a_leak(db):+ _seed_memory(db, name="flat", value=lambda hour: 300)+ _seed_memory(db, name="sawtooth", value=lambda hour: 200 + 150 * (int(hour) % 3))+ now = _seed_memory(db, name="noisy", value=lambda hour: 300 + (40 if int(hour * 6) % 2 else -40))++ assert _trend(db, now) == {}+++def test_a_restart_or_recreation_in_the_window_resets_the_trend(db):+ _seed_memory(db, name="recreated", container_id="one")+ db.query(ContainerMetric).filter(ContainerMetric.name == "recreated", ContainerMetric.memory_used_mb > 300).update({"container_id": "two"})+ _seed_memory(db, name="restarted")+ db.query(ContainerMetric).filter(ContainerMetric.name == "restarted", ContainerMetric.memory_used_mb > 300).update({"restart_count": 1})+ db.commit()++ assert _trend(db) == {}+++def test_too_little_history_or_a_slow_or_proportionally_small_rise_is_not_flagged(db):+ _seed_memory(db, name="gappy", skip_hours=(1, 2, 3, 4, 5))+ _seed_memory(db, name="slow", value=lambda hour: 200 + 2 * hour)+ now = _seed_memory(db, name="huge", value=lambda hour: 5000 + 12 * hour) # 12 MB/h but only ~2.6% over the window++ assert _trend(db, now) == {}+++def test_containers_that_are_not_running_now_are_not_analysed(db):+ now = _seed_memory(db, status="exited")++ assert _trend(db, now) == {}+++def test_the_flag_clears_when_the_growth_stops(db):+ now = _seed_memory(db)+ assert "trend:app:memory" in _trend(db, now)++ db.query(ContainerMetric).delete()+ db.query(HostMetric).delete()+ db.commit()+ now = _seed_memory(db, value=lambda hour: 300)++ assert _trend(db, now) == {}+++def test_analysis_is_bounded_to_100_containers_per_server(db):+ now = datetime.now(timezone.utc)+ since = now - timedelta(hours=12)+ last = None+ for number in range(120):+ for hour in range(12):+ for k in range(6):+ last = since + timedelta(minutes=hour * 60 + k * 10 + 5)+ db.add(ContainerMetric(server_id=5, container_id=f"id{number}", name=f"app{number:03d}", status="running", restart_count=0, memory_used_mb=float(200 + 20 * (hour + k / 6)), time=last))+ db.add(HostMetric(server_id=5, time=last))+ db.commit()++ assert len(_trend(db, now)) == rules.MAX_TREND_CONTAINERS+++def test_a_fit_needs_distinct_points():+ assert rules._linear_fit([(1.0, 5.0), (1.0, 6.0)]) is None+ slope, intercept, r_squared = rules._linear_fit([(0.0, 10.0), (1.0, 20.0), (2.0, 30.0)])+ assert (round(slope, 6), round(intercept, 6), round(r_squared, 6)) == (10.0, 10.0, 1.0)+++def test_the_new_thresholds_have_safe_defaults_and_are_validated():+ defaults = rules.DEFAULT_THRESHOLDS+ assert (defaults["docker_slow_ms"], defaults["leak_window_hours"], defaults["leak_min_mb_per_hour"], defaults["leak_min_growth_pct"]) == (2000, 12, 10, 20)++ for bad in ({"docker_slow_ms": 50}, {"docker_slow_ms": 70000}, {"docker_slow_ms": 1500.5}, {"leak_window_hours": 5}, {"leak_window_hours": 73}, {"leak_window_hours": 12.5},+ {"leak_min_mb_per_hour": 0}, {"leak_min_mb_per_hour": 10001}, {"leak_min_growth_pct": 0}, {"leak_min_growth_pct": 101}, {"leak_min_growth_pct": "20"}, {"leak_window_hours": True}):+ with pytest.raises(ValueError):+ rules.validate_thresholds(bad, defaults)++ ok = rules.validate_thresholds({"docker_slow_ms": 5000, "leak_window_hours": 24, "leak_min_mb_per_hour": 2.5, "leak_min_growth_pct": 50}, defaults)+ assert (ok["docker_slow_ms"], ok["leak_window_hours"], ok["leak_min_mb_per_hour"], ok["leak_min_growth_pct"]) == (5000, 24, 2.5, 50)+++def test_the_longest_container_name_still_fits_every_incident_key(db):+ name = "n" * 600+ _ingest(db, [_c(name, "exited", exit_code=1, finished_at=_stamp(5), restart_count=0, healthcheck_status="unhealthy")])++ keys = list(_active(db))+ assert keys and max(len(key) for key in keys) < 255diff --git a/tests/test_docker_proxy.py b/tests/test_docker_proxy.pyindex 3bb11c4..5ea57c2 100644--- a/tests/test_docker_proxy.py+++ b/tests/test_docker_proxy.py@@ -12,9 +12,9 @@ CID = "a" * 64SECRET = "SUPER_SECRET_TOKEN_123"INSPECT = {- "Id": CID, "Name": "/web", "RestartCount": 2, "Image": "sha256:abc",+ "Id": CID, "Name": "/web", "RestartCount": 2, "Image": "sha256:" + "ab" * 32,"Config": {"Image": "nginx:1", "Env": [f"DB_PASSWORD={SECRET}"], "Labels": {"k": "v"}, "Cmd": ["nginx"]},- "State": {"Status": "running", "StartedAt": "2026-01-01T00:00:00Z", "Pid": 99, "Health": {"Status": "healthy", "Log": [{"Output": SECRET}]}},+ "State": {"Status": "running", "StartedAt": "2026-01-01T00:00:00Z", "Pid": 99, "ExitCode": 137, "OOMKilled": True, "FinishedAt": "2026-01-02T03:04:05.123456789Z", "Error": f"failed: {SECRET}", "Health": {"Status": "healthy", "Log": [{"Output": SECRET}]}},"NetworkSettings": {"Ports": {"80/tcp": [{"HostIp": "0.0.0.0", "HostPort": "8080"}]}, "SecondaryIPAddresses": None, "Networks": {"x": {"Gateway": "1"}}},"Mounts": [{"Source": "/etc/shadow"}], "HostConfig": {"Privileged": True}, "GraphDriver": {"Data": {}},}@@ -66,8 +66,8 @@ def test_inspect_output_drops_environment_and_everything_unneeded():assert SECRET not in json.dumps(result)assert result == {- "Id": CID, "Name": "/web", "RestartCount": 2, "Config": {"Image": "nginx:1"},- "State": {"Status": "running", "StartedAt": "2026-01-01T00:00:00Z", "Health": {"Status": "healthy"}},+ "Id": CID, "Name": "/web", "RestartCount": 2, "Image": "sha256:" + "ab" * 32, "Config": {"Image": "nginx:1"},+ "State": {"Status": "running", "StartedAt": "2026-01-01T00:00:00Z", "ExitCode": 137, "OOMKilled": True, "FinishedAt": "2026-01-02T03:04:05.123456789Z", "Health": {"Status": "healthy"}},"NetworkSettings": {"Ports": {"80/tcp": [{"HostIp": "0.0.0.0", "HostPort": "8080"}]}},}