diff --git a/DATABASE.md b/DATABASE.md index 596756d..5db5da4 100644 --- a/DATABASE.md +++ b/DATABASE.md @@ -23,8 +23,8 @@ what the app actually creates. |---|---| | **File** | `DATABASE_PATH`, default `../data/homelab-manager.sqlite` (relative to `server/`; `/app/data/...` in Docker). The folder is created if missing. | | **Foreign keys** | Switched on for every connection (`PRAGMA foreign_keys = ON`), so the `ON DELETE` rules below are enforced. | -| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0053`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. | -| **Tables** | 62 application tables, plus drizzle's own `__drizzle_migrations`. | +| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0054`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. | +| **Tables** | 64 application tables, plus drizzle's own `__drizzle_migrations`. | **Not in the database, but beside it in the data folder:** the backups of the database itself (`backups/homelab-manager-….sqlite`, taken daily and on request; see [BACKUP.md](BACKUP.md)), and, only while a restore is waiting or has just happened, `restore-pending.sqlite` / `restore-pending.json` and `restore-result.json`. @@ -44,7 +44,7 @@ what the app actually creates. - Dates without a time (`secrets.expiry_date`, `domains.expires_at`) are `YYYY-MM-DD`. - **JSON columns** are `TEXT` holding JSON; see [what's inside](#whats-stored-inside-the-json-columns). - **Enumerations** (roles, types) are plain text — SQLite doesn't enforce the allowed values; the app does. -- **Indexes:** besides primary keys and the unique ones listed per table, a few plain indexes serve the tables that are read by range or by what they are about: `endpoint_results`, `heartbeat_pings`, `server_metrics`, `ha_readings` and `storage_samples` (by owner and time), `restore_tests`, `renewals`, `update_runs`, `patch_plan_runs`, `alert_incidents`, `incident_notes`, `alert_tickets`, `runbooks` and `status_items`. The other tables have a few thousand rows at most and need none. +- **Indexes:** besides primary keys and the unique ones listed per table, a few plain indexes serve the tables that are read by range or by what they are about: `endpoint_results`, `heartbeat_pings`, `server_metrics`, `ha_readings`, `ups_readings` and `storage_samples` (by owner and time), `restore_tests`, `renewals`, `update_runs`, `patch_plan_runs`, `alert_incidents`, `incident_notes`, `alert_tickets`, `runbooks` and `status_items`. The other tables have a few thousand rows at most and need none. ## How the tables relate @@ -66,6 +66,8 @@ erDiagram storage_series ||--o{ storage_samples : "cascade" integrations ||--o{ ha_entities : "cascade" integrations ||--o{ ha_readings : "cascade" + integrations ||--o| ups_state : "cascade" + integrations ||--o{ ups_readings : "cascade" users ||--o{ todos : "assignee (set null)" servers ||--o{ network_server_links : "cascade" integration_credentials ||--o{ dns_providers : "credential (set null)" @@ -813,6 +815,36 @@ A numeric value of a watched entity at a moment, for the chart: one at most ever | `at` | text NOT NULL | ISO. | | `value` | real NOT NULL | | +#### `ups_state` + +How a UPS (an integration of type `ups`) is right now, one row each, replaced at every read (every minute). `integration_id` is the primary key and a foreign key with **cascade**. + +| Column | Type | Notes | +|---|---|---| +| `integration_id` | integer PK | → `integrations.id`. | +| `model`, `manufacturer` | text | As the UPS says. | +| `status_text` | text NOT NULL | The UPS's own words (`OL CHRG`, `on battery, battery normal`). | +| `on_battery`, `low_battery`, `replace_battery`, `overload` | bool NOT NULL, default 0 | Mains power lost; battery nearly empty; battery to be replaced; overloaded. | +| `charge`, `load_percent` | real | Percent. | +| `runtime_seconds` | integer | How long the battery would last at the present load. | +| `input_voltage`, `output_voltage` | real | Volts. | +| `on_battery_since` | text | ISO; when mains power was lost, kept until it is back. | +| `updated_at` | text NOT NULL | ISO; the last read that worked. | + +How the last read went (and when it last worked) is in `settings` under the internal key `upsSync`, like the Home Assistant sync's. + +#### `ups_readings` + +A UPS at a moment, for the charts: one every five minutes, and every minute while it runs on battery (or when that changes), deleted after 35 days. `integration_id` is a foreign key with **cascade**; (`integration_id`, `at`) is indexed. + +| Column | Type | Notes | +|---|---|---| +| `id` | integer PK | | +| `at` | text NOT NULL | ISO. | +| `charge`, `load_percent`, `input_voltage` | real | | +| `runtime_seconds` | integer | | +| `on_battery` | bool NOT NULL, default 0 | | + #### `alert_rules` Limits of the administrator's own (Monitoring → Alert rules), judged for the servers they cover on the health pass; what they find is ordinary health conditions keyed `rule::server:[:]`. @@ -1130,7 +1162,7 @@ settings, and aren't part of the app's settings object: |---|---| | a **server** | Its `scheduled_tasks`, `server_links`, `server_ports`, `server_metrics`, `server_metrics_rollup`, `update_runs` and `network_server_links` are deleted with it. Port forwards that pointed at it stay, with `server_id` cleared. Things that refer to it by id only (notes, to-do items, endpoint checks, heartbeats, alert rules, dependencies, runbooks, maintenance windows) stay, pointing at nothing — see below. | | a **DNS provider** | Its cached zones and records are deleted. | -| an **integration** | What was read from it is deleted with it: UniFi devices, networks and server links, Home Assistant watched entities and readings, and the history of its storage pools (`storage_series`, `storage_samples`). | +| an **integration** | What was read from it is deleted with it: UniFi devices, networks and server links, Home Assistant watched entities and readings, a UPS's state and readings, and the history of its storage pools (`storage_series`, `storage_samples`). | | an **endpoint check**, a **heartbeat**, an **incident**, a **patch plan**, a **share link**, an **event webhook** | Their results and summaries (`endpoint_results`, `_hourly`, `_daily`), pings, notes, runs, status-page items and delivery log (`webhook_deliveries`). | | an **integration** or **DNS provider** | The credential row it used is deleted by the app (not by the database). | | an **integration** used for alert tickets | `alert_tickets.integration_id` is cleared; the history stays. | @@ -1187,6 +1219,7 @@ are deleted), and `notification_queue` is emptied each time the quiet-hours dige | `endpoint_hourly`, `endpoint_daily` | 120 days, and 800 days | | `storage_samples` | 400 days (a pool not reported for 30 days is deleted with its readings) | | `ha_readings` | 35 days | +| `ups_readings` | 35 days | | `heartbeat_pings` | 14 days | | `alert_incidents`, `incident_notes` | 400 days after the incident resolved | | `webhook_deliveries` | the newest 100 per webhook, and 14 days | diff --git a/INTEGRATIONS.md b/INTEGRATIONS.md index 83860f8..917a824 100644 --- a/INTEGRATIONS.md +++ b/INTEGRATIONS.md @@ -6,10 +6,10 @@ Homelab Manager (Integrations → Add integration, or DNS → Add provider). All credentials are entered in-app and encrypted at rest — nothing is read from environment variables. -Every adapter listed here except UniFi, Nginx Proxy Manager and Home Assistant performs write actions (starting/stopping +Every adapter listed here except UniFi, Nginx Proxy Manager, Home Assistant and the UPS performs write actions (starting/stopping things, editing DNS records, etc.), not just reads — a read-only credential will fail as soon as you use one of those actions, even if -the dashboard views themselves load fine. (UniFi, Nginx Proxy Manager and Home Assistant only ever read.) +the dashboard views themselves load fine. (UniFi, Nginx Proxy Manager, Home Assistant and the UPS only ever read.) ## Integrations @@ -276,6 +276,26 @@ the dashboard views themselves load fine. (UniFi, Nginx Proxy Manager and Home A - A service reached at a server's address (the integration's URL) is offered as a suggested dependency on that server. - **Not verified against a live Home Assistant** — built from its published REST API and tried against a pretend one. Every field is read defensively. If a read fails, the **Diagnostic Log** has what it answered. +### UPS (NUT or SNMP) + +- **Config fields:** the **host** (the machine running NUT's `upsd`, or the UPS's own network card), a checkbox to read it **over SNMP instead of NUT**, and optionally the **port** (3493 for NUT, 161 for SNMP), the UPS's **name** on the NUT + server (the first one it lists when blank) and the SNMP **read community** (`public` when blank; stored encrypted). +- **Required access:** read only. **NUT:** `upsd` must listen on an address this server can reach (`LISTEN` in `upsd.conf`; the default is only the machine itself) and, if `upsd.users`/`ACL` limit who may ask, allow + this host. Only `LIST UPS` and `LIST VAR ` are sent — no command, no login. **SNMP:** version 2c, a `GET` of the standard UPS-MIB (RFC 1628, `1.3.6.1.2.1.33`), which most UPSs and their network cards answer; + APC-only or other private objects are not used. **Nothing is ever set.** The host is checked like an endpoint check's: not this machine itself, not the cloud metadata address; your own network is fine. +- **What it does:** every **minute** the UPS is read and stored — its state, and a point for the charts (every five minutes, and every minute while on battery; kept 35 days): battery charge, runtime left, load, mains + voltage in and out, model and maker. **Monitoring → UPS** shows it, with the history and the times mains power was lost. + - **Alerts** (category *Monitoring*, source *UPS*; announced and recovered like the other health problems, held back by maintenance on the integration): **mains power has failed — running on battery** (critical; + NUT `OB`, SNMP output source *on battery*), **the battery is nearly empty** (critical; NUT `LB`, SNMP battery low or depleted), **the UPS asks for its battery to be replaced** (warning; NUT `RB`), and **a load of 90 % + or more, or an overload** (warning; NUT `OVER`). + - **It is a node in the dependency map** (`integration:`): say what it powers under **Map → Dependencies**. While it runs on battery it counts as *down*, so servers that go offline with it are folded under its + alert (which says "also takes down …") instead of each being announced. The UPS page lists what needs it in the **order to shut it down** — what nothing else needs first, then what that needed — so nothing is + switched off while something that depends on it is still running. + - If the UPS cannot be read for five minutes its alerts are neither raised nor cleared, the Alerts page says it could not check, and the integration is raised as failing like any other. + - `/metrics` has `homelab_ups_on_battery`, `homelab_ups_battery_charge_percent`, `homelab_ups_runtime_seconds`, `homelab_ups_load_percent` and `homelab_ups_input_volts` for each UPS that was read lately. +- **Not verified against a real UPS** — NUT's protocol and the UPS-MIB are as published, and both readers are tried against pretend servers. Some UPSs leave out objects (the page then shows a dash), and some + network cards number the load or voltage tables differently; if a value is missing, the **Diagnostic Log** has what was asked and answered. + ## DNS providers ### Cloudflare diff --git a/README.md b/README.md index 81197d1..5d78ad6 100644 --- a/README.md +++ b/README.md @@ -885,6 +885,12 @@ alert — a UPS battery, a freezer's temperature, a pump — not all of them. Ea An entity that has been *unavailable* (or has gone missing) for 15 minutes is an alert too. If Home Assistant cannot be read for twenty minutes its entities are neither raised nor cleared, and the Alerts page says it could not check. Nothing is ever sent to Home Assistant. Neither integration has been tried against the real thing — see INTEGRATIONS.md. +**A UPS** (Monitoring → UPS). Add an integration of type *UPS*: the address of the machine running NUT (`upsd`), or of the UPS's network card with *SNMP* ticked (version 2c, the standard UPS-MIB). Every minute the app reads it — battery +charge, how long it would last, the load, the mains voltage — and the UPS page draws them over time and lists when mains power was lost. **Mains power lost** is a critical alert and a notification (so is a battery nearly empty; +a battery to be replaced and a load of 90 % are warnings). The UPS is also a **node in the dependency map**: say what it powers, and while it runs on battery it counts as *down*, so the servers that go offline with it are +folded under its alert ("also takes down …") instead of each being announced; the page lists what is on it in the **order to shut it down**, so nothing is switched off while something that needs it is still running. The app only +reads — it never sends a command to the UPS. Not tried against a real UPS; see INTEGRATIONS.md. + **Alert rules of your own.** **Monitoring → Alert rules** (administrators write them, everyone sees them) is for limits the built-in checks do not have: *CPU above 90% for 15 minutes*, *memory above 85%*, *a disk above 80%* (every disk, or the one you name), *a disk warmer than 55 °C*. A rule says what to watch, above or below what, for how long (a reading in the history every 10–15 minutes; every reading in that time has to be past the limit, so a dip starts the count again), how serious it is and which servers it covers (all, one, or those with a tag). **Try it now** shows which servers it would be raised on right now before it is saved. diff --git a/ROLES.md b/ROLES.md index 95651ac..7399bd9 100644 --- a/ROLES.md +++ b/ROLES.md @@ -45,6 +45,7 @@ page's own top-level link. | Heartbeats | `/heartbeats` | ✅ | ✅ | ✅ | | Uptime Kuma | `/uptime-kuma` | ✅ | ✅ | ✅ | | Home Assistant | `/home-assistant` | ✅ | ✅ | ✅ | +| UPS | `/ups` | ✅ | ✅ | ✅ | | **Automation** | | | | | | Semaphore | `/semaphore` | ✅ | ✅ | ✅ | | Gitea | `/gitea` | ✅ | ✅ | ✅ | @@ -124,6 +125,7 @@ even further, to admin only: - **Proxy hosts** (Network → Proxy hosts): everyone signed in sees what Nginx Proxy Manager serves; **Read now** needs operator; adding the integration (its login) is an administrator's job. - **Home Assistant** (Monitoring → Home Assistant): everyone signed in sees what is watched, its state and history; choosing what to watch, its limits, stopping and **Read now** need operator (the list of all entities is read live, so only operators see it); adding the integration (its token) is an administrator's job. +- **UPS** (Monitoring → UPS): everyone signed in sees each UPS, its history and what is on it; adding one (its address and SNMP community) is an administrator's job, like any integration, and what it powers is written in the dependency map. - **Endpoints**: everyone sees the checks and how they are doing; adding, changing and removing one is administrator-only (each makes the server connect somewhere); that includes the value a check judges and the header (a token) it sends, whose value is never shown again to anyone; *Check now* needs operator. - **Restore tests**: everyone sees them on the Backup coverage page; recording one needs operator; removing one is administrator-only. diff --git a/docs/MONITORING.md b/docs/MONITORING.md index 9a081d1..cafc4a7 100644 --- a/docs/MONITORING.md +++ b/docs/MONITORING.md @@ -47,6 +47,7 @@ Three ideas run through everything: | **Proxmox**, **Synology** | The health pass **reads** them: node and storage usage, volume and disk status. | Every **15 minutes** | | **UniFi** | A sync **reads** devices, networks, Wi-Fi names and clients and keeps them. | Every **5 minutes** | | **Home Assistant** | A sync **reads** the entities you chose to watch and keeps their state and a history. | Every **5 minutes** | +| **UPS** (NUT or SNMP) | A sync **reads** each UPS and keeps its state and a history. | Every **minute** | | **Nginx Proxy Manager** | **Read** when its page is opened and by the alert check, at most once a minute. | On demand, cached 1 minute | | **Semaphore**, **Gitea** | The automation check **reads** the latest run of each template or workflow. | Every **15 minutes** | | **Endpoint checks** (web address, TCP port, TLS certificate) | The app **asks** each one itself. | Each check has its own interval (**5 minutes** by default); the scheduler looks **every minute** for the ones that are due | @@ -128,6 +129,7 @@ Every threshold here is a default; where it can be changed, the place is named. | **Endpoint check failing / certificate running out** | See [below](#endpoint-checks-and-heartbeats) | | per check | | **Heartbeat late / failed** | See [below](#endpoint-checks-and-heartbeats) | | per heartbeat | | **Home Assistant / Nginx Proxy Manager** | An entity unavailable 15 minutes or past your limit; a certificate in use ending within 14 days, or a host NPM cannot set up | | Home Assistant page | +| **UPS** | Mains power lost (critical); battery nearly empty (critical); battery to be replaced; load of 90 % or more (warning) | | UPS page; [INTEGRATIONS.md](../INTEGRATIONS.md#ups-nut-or-snmp) | | **Your own rules** | [Below](#your-own-alert-rules) | | Monitoring → Alert rules | ## Your own alert rules @@ -185,7 +187,7 @@ using credentials an administrator enters under *Integrations*; what each needs restart starts the count again. A *down* notification goes out at the threshold and a *recovered* one on the next success. The moments are written to the audit log, and they feed the uptime record on the integration's page. - **When an integration cannot be read, what it reported is held, not cleared.** A Proxmox node that cannot be read does not make its storage alerts disappear (or appear); the Alerts page says it could not check. - The synced ones (UniFi, Home Assistant) are only judged while their last good read is recent (**20 minutes**). + The synced ones (UniFi, Home Assistant) are only judged while their last good read is recent (**20 minutes**; a UPS, **5**). - **An integration can explain other alerts.** A service that stops answering because the integration it needs is failing is folded under it ([Dependencies](#dependencies-one-outage-one-alert)). ## Forecasts @@ -280,6 +282,7 @@ hand, a config file edited — is not something the app can see. | Uptime of servers and integrations | The last weeks, worked out from the moments each stopped and resumed (in the audit log) | one figure a day | | Proxmox storage and Synology volume use | **400 days**, one reading an hour | | | Home Assistant watched numbers | **35 days**, one reading every few minutes | | +| A UPS's charge, load and mains voltage | **35 days**, one reading every five minutes (every minute on battery) | | | Incidents | **400 days** after they resolve | | | Messages sent to event webhooks | The last **100 per webhook**, none older than **14 days** — see [WEBHOOKS.md](WEBHOOKS.md#the-delivery-log-and-sending-again) | | | The audit log and the Diagnostic Log | Until automatic purging is switched on under *Settings → Data* (then 90 days by default, configurable) | | @@ -297,7 +300,7 @@ switched on). The last two are listed at the top as needing a look. Nothing ther | **Dashboard**, **My work**, the menu badge | What needs attention now; what is yours | | **Alerts** (Now · History · Noise) | Every alert, with acknowledge, snooze, silence; the incident record; what keeps coming back | | A **server's page** | Its figures, history, health, ports, tasks, notes, jobs, what it runs on and what runs on it | -| **Endpoints**, **Heartbeats**, **Proxmox**, **Synology**, **Network devices**, **Home Assistant**, **Proxy hosts** | Each source's own view | +| **Endpoints**, **Heartbeats**, **Proxmox**, **Synology**, **Network devices**, **Home Assistant**, **UPS**, **Proxy hosts** | Each source's own view | | **Weekly digest** and **monthly report** | The week and the month in one message | | **`/metrics`** → Prometheus, Grafana | [PROMETHEUS-GRAFANA.md](PROMETHEUS-GRAFANA.md) | | **Read API** (`/api/v1`) | [API.md](API.md) | diff --git a/docs/PROMETHEUS-GRAFANA.md b/docs/PROMETHEUS-GRAFANA.md index 5d2a4ae..41febd5 100644 --- a/docs/PROMETHEUS-GRAFANA.md +++ b/docs/PROMETHEUS-GRAFANA.md @@ -292,6 +292,8 @@ All gauges. The same table is checked by a test against what `/metrics` really s | `homelab_endpoint_response_milliseconds` | `name`, `kind` | How long it took to answer the last time. | | `homelab_endpoint_value` | `name`, `kind` | The number a value check last read from the answer (checks that judge a value only, and only when it is a number). | | `homelab_endpoint_certificate_days_left` | `name`, `kind` | Days until the certificate it shows expires (negative once it has). | +| `homelab_ups_on_battery` | `name` | 1 if the UPS has lost mains power and runs on its battery, else 0; left out for a UPS that has not been read in the last five minutes. | +| `homelab_ups_battery_charge_percent`, `homelab_ups_runtime_seconds`, `homelab_ups_load_percent`, `homelab_ups_input_volts` | `name` | How full the battery is, how long it would last at the present load, how much of its capacity the load uses, and the mains voltage it sees — each left out when the UPS does not say. | | `homelab_heartbeat_up` | `name` | 1 if the job has reported in time and not said it failed, else 0; switched-off heartbeats are left out. | | `homelab_heartbeat_last_ping_timestamp_seconds` | `name` | When the job last reported that it finished (Unix time). | | `homelab_heartbeat_last_duration_seconds` | `name` | How long the job said its last run took (only when it sent `/start`). | diff --git a/server/drizzle/0054_green_beast.sql b/server/drizzle/0054_green_beast.sql new file mode 100644 index 0000000..dc32d77 --- /dev/null +++ b/server/drizzle/0054_green_beast.sql @@ -0,0 +1,31 @@ +CREATE TABLE `ups_readings` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `integration_id` integer NOT NULL, + `at` text NOT NULL, + `charge` real, + `runtime_seconds` integer, + `load_percent` real, + `input_voltage` real, + `on_battery` integer DEFAULT false NOT NULL, + FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE INDEX `ups_readings_lookup_idx` ON `ups_readings` (`integration_id`,`at`);--> statement-breakpoint +CREATE TABLE `ups_state` ( + `integration_id` integer PRIMARY KEY NOT NULL, + `model` text, + `manufacturer` text, + `status_text` text NOT NULL, + `on_battery` integer DEFAULT false NOT NULL, + `low_battery` integer DEFAULT false NOT NULL, + `replace_battery` integer DEFAULT false NOT NULL, + `overload` integer DEFAULT false NOT NULL, + `charge` real, + `runtime_seconds` integer, + `load_percent` real, + `input_voltage` real, + `output_voltage` real, + `on_battery_since` text, + `updated_at` text NOT NULL, + FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade +); diff --git a/server/drizzle/meta/0054_snapshot.json b/server/drizzle/meta/0054_snapshot.json new file mode 100644 index 0000000..c805d7e --- /dev/null +++ b/server/drizzle/meta/0054_snapshot.json @@ -0,0 +1,6157 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "849e0879-5465-4840-aaad-805ed46e942b", + "prevId": "7b8dbc1b-c579-41ef-ae52-3aa3b9043b7c", + "tables": { + "alert_acks": { + "name": "alert_acks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "''" + }, + "assignee_user_id": { + "name": "assignee_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assignee_name": { + "name": "assignee_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "acked_by": { + "name": "acked_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "acked_at": { + "name": "acked_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "until": { + "name": "until", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "alert_acks_key_idx": { + "name": "alert_acks_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "alert_acks_assignee_user_id_users_id_fk": { + "name": "alert_acks_assignee_user_id_users_id_fk", + "tableFrom": "alert_acks", + "tableTo": "users", + "columnsFrom": [ + "assignee_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alert_incidents": { + "name": "alert_incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "peak_severity": { + "name": "peak_severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "link": { + "name": "link", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_name": { + "name": "target_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "caused_by": { + "name": "caused_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "opened_at": { + "name": "opened_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "missing_since": { + "name": "missing_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "escalated_step": { + "name": "escalated_step", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "escalated_at": { + "name": "escalated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "alert_incidents_key_idx": { + "name": "alert_incidents_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": false + }, + "alert_incidents_opened_idx": { + "name": "alert_incidents_opened_idx", + "columns": [ + "opened_at" + ], + "isUnique": false + }, + "alert_incidents_target_idx": { + "name": "alert_incidents_target_idx", + "columns": [ + "target_type", + "target_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alert_rules": { + "name": "alert_rules", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "mount": { + "name": "mount", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "operator": { + "name": "operator", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'above'" + }, + "threshold": { + "name": "threshold", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "for_minutes": { + "name": "for_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'warning'" + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alert_snoozes": { + "name": "alert_snoozes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_id": { + "name": "alert_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "condition_key": { + "name": "condition_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "until": { + "name": "until", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snoozed_by": { + "name": "snoozed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "snoozed_at": { + "name": "snoozed_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "alert_snoozes_alert_idx": { + "name": "alert_snoozes_alert_idx", + "columns": [ + "alert_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alert_tickets": { + "name": "alert_tickets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seen_count": { + "name": "seen_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ticket_number": { + "name": "ticket_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "grouped": { + "name": "grouped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ticketed_at": { + "name": "ticketed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cleared_at": { + "name": "cleared_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "alert_tickets_key_idx": { + "name": "alert_tickets_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": false + } + }, + "foreignKeys": { + "alert_tickets_integration_id_integrations_id_fk": { + "name": "alert_tickets_integration_id_integrations_id_fk", + "tableFrom": "alert_tickets", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "api_tokens": { + "name": "api_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "api_tokens_token_hash_unique": { + "name": "api_tokens_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": { + "api_tokens_user_id_users_id_fk": { + "name": "api_tokens_user_id_users_id_fk", + "tableFrom": "api_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assets": { + "name": "assets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "manufacturer": { + "name": "manufacturer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "serial": { + "name": "serial", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purchase_date": { + "name": "purchase_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purchase_price": { + "name": "purchase_price", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warranty_until": { + "name": "warranty_until", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "end_of_support": { + "name": "end_of_support", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "replacement_cost": { + "name": "replacement_cost", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rack_unit": { + "name": "rack_unit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_watts": { + "name": "power_watts", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_label": { + "name": "actor_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "audit_log_actor_user_id_users_id_fk": { + "name": "audit_log_actor_user_id_users_id_fk", + "tableFrom": "audit_log", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "consistency_ignores": { + "name": "consistency_ignores", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "consistency_ignores_key_unique": { + "name": "consistency_ignores_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dependencies": { + "name": "dependencies", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "from_type": { + "name": "from_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "from_id": { + "name": "from_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_type": { + "name": "to_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_id": { + "name": "to_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "dependencies_edge_idx": { + "name": "dependencies_edge_idx", + "columns": [ + "from_type", + "from_id", + "to_type", + "to_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "diag_log": { + "name": "diag_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation": { + "name": "operation", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latency_ms": { + "name": "latency_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_providers": { + "name": "dns_providers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_type": { + "name": "provider_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "dns_providers_credential_id_integration_credentials_id_fk": { + "name": "dns_providers_credential_id_integration_credentials_id_fk", + "tableFrom": "dns_providers", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_records_cache": { + "name": "dns_records_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_id": { + "name": "record_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ttl": { + "name": "ttl", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxied": { + "name": "proxied", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "dns_records_cache_provider_id_dns_providers_id_fk": { + "name": "dns_records_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_records_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_zones_cache": { + "name": "dns_zones_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_name": { + "name": "zone_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "synced_at": { + "name": "synced_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "dns_zones_cache_provider_zone_idx": { + "name": "dns_zones_cache_provider_zone_idx", + "columns": [ + "provider_id", + "zone_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "dns_zones_cache_provider_id_dns_providers_id_fk": { + "name": "dns_zones_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_zones_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "domains": { + "name": "domains", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'manual'" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "registrar": { + "name": "registrar", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lookup_source": { + "name": "lookup_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_ok_at": { + "name": "last_checked_ok_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "domains_name_unique": { + "name": "domains_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_checks": { + "name": "endpoint_checks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expect_status": { + "name": "expect_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "keyword": { + "name": "keyword", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "insecure": { + "name": "insecure", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "value_path": { + "name": "value_path", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "value_op": { + "name": "value_op", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "value_expected": { + "name": "value_expected", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "value_unit": { + "name": "value_unit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "header_name": { + "name": "header_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "header_value": { + "name": "header_value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_value": { + "name": "last_value", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "interval_minutes": { + "name": "interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "timeout_seconds": { + "name": "timeout_seconds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 10 + }, + "failures_before_alert": { + "name": "failures_before_alert", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 2 + }, + "warn_days": { + "name": "warn_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 14 + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_ok": { + "name": "last_ok", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_message": { + "name": "last_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_response_ms": { + "name": "last_response_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cert_expires_at": { + "name": "cert_expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "consecutive_failures": { + "name": "consecutive_failures", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "last_change_at": { + "name": "last_change_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_daily": { + "name": "endpoint_daily", + "columns": { + "check_id": { + "name": "check_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "day": { + "name": "day", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_sum": { + "name": "ms_sum", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_count": { + "name": "ms_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "endpoint_daily_check_id_endpoint_checks_id_fk": { + "name": "endpoint_daily_check_id_endpoint_checks_id_fk", + "tableFrom": "endpoint_daily", + "tableTo": "endpoint_checks", + "columnsFrom": [ + "check_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "endpoint_daily_check_id_day_pk": { + "columns": [ + "check_id", + "day" + ], + "name": "endpoint_daily_check_id_day_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_hourly": { + "name": "endpoint_hourly", + "columns": { + "check_id": { + "name": "check_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hour": { + "name": "hour", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "total": { + "name": "total", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_sum": { + "name": "ms_sum", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_count": { + "name": "ms_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ms_max": { + "name": "ms_max", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "endpoint_hourly_check_id_endpoint_checks_id_fk": { + "name": "endpoint_hourly_check_id_endpoint_checks_id_fk", + "tableFrom": "endpoint_hourly", + "tableTo": "endpoint_checks", + "columnsFrom": [ + "check_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "endpoint_hourly_check_id_hour_pk": { + "columns": [ + "check_id", + "hour" + ], + "name": "endpoint_hourly_check_id_hour_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "endpoint_results": { + "name": "endpoint_results", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "check_id": { + "name": "check_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ms": { + "name": "ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "endpoint_results_check_idx": { + "name": "endpoint_results_check_idx", + "columns": [ + "check_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "endpoint_results_check_id_endpoint_checks_id_fk": { + "name": "endpoint_results_check_id_endpoint_checks_id_fk", + "tableFrom": "endpoint_results", + "tableTo": "endpoint_checks", + "columnsFrom": [ + "check_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "event_webhooks": { + "name": "event_webhooks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_result": { + "name": "last_result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ha_entities": { + "name": "ha_entities", + "columns": { + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_name": { + "name": "friendly_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "device_class": { + "name": "device_class", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_changed": { + "name": "last_changed", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "unavailable_since": { + "name": "unavailable_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "ha_entities_integration_id_integrations_id_fk": { + "name": "ha_entities_integration_id_integrations_id_fk", + "tableFrom": "ha_entities", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "ha_entities_integration_id_entity_id_pk": { + "columns": [ + "integration_id", + "entity_id" + ], + "name": "ha_entities_integration_id_entity_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ha_readings": { + "name": "ha_readings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "ha_readings_lookup_idx": { + "name": "ha_readings_lookup_idx", + "columns": [ + "integration_id", + "entity_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "ha_readings_integration_id_integrations_id_fk": { + "name": "ha_readings_integration_id_integrations_id_fk", + "tableFrom": "ha_readings", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ha_watched": { + "name": "ha_watched", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "above": { + "name": "above", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "below": { + "name": "below", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "ha_watched_unique": { + "name": "ha_watched_unique", + "columns": [ + "integration_id", + "entity_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "ha_watched_integration_id_integrations_id_fk": { + "name": "ha_watched_integration_id_integrations_id_fk", + "tableFrom": "ha_watched", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "heartbeat_pings": { + "name": "heartbeat_pings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "heartbeat_id": { + "name": "heartbeat_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "heartbeat_pings_idx": { + "name": "heartbeat_pings_idx", + "columns": [ + "heartbeat_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "heartbeat_pings_heartbeat_id_heartbeats_id_fk": { + "name": "heartbeat_pings_heartbeat_id_heartbeats_id_fk", + "tableFrom": "heartbeat_pings", + "tableTo": "heartbeats", + "columnsFrom": [ + "heartbeat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "heartbeats": { + "name": "heartbeats", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "period_minutes": { + "name": "period_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grace_minutes": { + "name": "grace_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 10 + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_ping_at": { + "name": "last_ping_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_status": { + "name": "last_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_message": { + "name": "last_message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_duration_ms": { + "name": "last_duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_start_at": { + "name": "last_start_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ping_count": { + "name": "ping_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "heartbeats_token_unique": { + "name": "heartbeats_token_unique", + "columns": [ + "token" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_notes": { + "name": "incident_notes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "incident_id": { + "name": "incident_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "author": { + "name": "author", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "incident_notes_incident_idx": { + "name": "incident_notes_incident_idx", + "columns": [ + "incident_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "incident_notes_incident_id_alert_incidents_id_fk": { + "name": "incident_notes_incident_id_alert_incidents_id_fk", + "tableFrom": "incident_notes", + "tableTo": "alert_incidents", + "columnsFrom": [ + "incident_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integration_credentials": { + "name": "integration_credentials", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encrypted_secret": { + "name": "encrypted_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integrations": { + "name": "integrations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "integrations_credential_id_integration_credentials_id_fk": { + "name": "integrations_credential_id_integration_credentials_id_fk", + "tableFrom": "integrations", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ipam_entries": { + "name": "ipam_entries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "vendor": { + "name": "vendor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "ipam_entries_ip_address_unique": { + "name": "ipam_entries_ip_address_unique", + "columns": [ + "ip_address" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_aliases": { + "name": "maintenance_aliases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "address": { + "name": "address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "maintenance_aliases_unique_idx": { + "name": "maintenance_aliases_unique_idx", + "columns": [ + "address", + "target_type", + "target_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_schedules": { + "name": "maintenance_schedules", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "targets": { + "name": "targets", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "days": { + "name": "days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_windows": { + "name": "maintenance_windows", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ends_at": { + "name": "ends_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "metrics_tokens": { + "name": "metrics_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "metrics_tokens_token_hash_unique": { + "name": "metrics_tokens_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "network_devices": { + "name": "network_devices", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_name": { + "name": "site_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "ip": { + "name": "ip", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mac": { + "name": "mac", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "uptime_seconds": { + "name": "uptime_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "firmware": { + "name": "firmware", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "firmware_updatable": { + "name": "firmware_updatable", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "uplink_external_id": { + "name": "uplink_external_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "offline_since": { + "name": "offline_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_online_at": { + "name": "last_online_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "network_devices_unique": { + "name": "network_devices_unique", + "columns": [ + "integration_id", + "external_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "network_devices_integration_id_integrations_id_fk": { + "name": "network_devices_integration_id_integrations_id_fk", + "tableFrom": "network_devices", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "network_segments": { + "name": "network_segments", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_id": { + "name": "external_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "site_name": { + "name": "site_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "vlan_id": { + "name": "vlan_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "subnet": { + "name": "subnet", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "security": { + "name": "security", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "network_name": { + "name": "network_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "network_segments_unique": { + "name": "network_segments_unique", + "columns": [ + "integration_id", + "kind", + "external_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "network_segments_integration_id_integrations_id_fk": { + "name": "network_segments_integration_id_integrations_id_fk", + "tableFrom": "network_segments", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "network_server_links": { + "name": "network_server_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "device_external_id": { + "name": "device_external_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_mac": { + "name": "client_mac", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "wired": { + "name": "wired", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "network_server_links_unique": { + "name": "network_server_links_unique", + "columns": [ + "integration_id", + "server_id", + "client_mac" + ], + "isUnique": true + } + }, + "foreignKeys": { + "network_server_links_integration_id_integrations_id_fk": { + "name": "network_server_links_integration_id_integrations_id_fk", + "tableFrom": "network_server_links", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "network_server_links_server_id_servers_id_fk": { + "name": "network_server_links_server_id_servers_id_fk", + "tableFrom": "network_server_links", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notes": { + "name": "notes", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "notes_target_idx": { + "name": "notes_target_idx", + "columns": [ + "target_type", + "target_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_queue": { + "name": "notification_queue", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "audience": { + "name": "audience", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "patch_plan_runs": { + "name": "patch_plan_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "plan_id": { + "name": "plan_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "plan_name": { + "name": "plan_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "trigger": { + "name": "trigger", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "started_by": { + "name": "started_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "items": { + "name": "items", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "patch_plan_runs_plan_idx": { + "name": "patch_plan_runs_plan_idx", + "columns": [ + "plan_id", + "started_at" + ], + "isUnique": false + }, + "patch_plan_runs_status_idx": { + "name": "patch_plan_runs_status_idx", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "patch_plan_runs_plan_id_patch_plans_id_fk": { + "name": "patch_plan_runs_plan_id_patch_plans_id_fk", + "tableFrom": "patch_plan_runs", + "tableTo": "patch_plans", + "columnsFrom": [ + "plan_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "patch_plans": { + "name": "patch_plans", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "days": { + "name": "days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "server_ids": { + "name": "server_ids", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_id": { + "name": "template_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_name": { + "name": "template_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "limit_from": { + "name": "limit_from", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'name'" + }, + "stop_on_failure": { + "name": "stop_on_failure", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "only_with_updates": { + "name": "only_with_updates", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "silence_dependents": { + "name": "silence_dependents", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "window_minutes": { + "name": "window_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 90 + }, + "last_run_date": { + "name": "last_run_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "port_forwards": { + "name": "port_forwards", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_port": { + "name": "external_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "destination": { + "name": "destination", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "internal_port": { + "name": "internal_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "port_forwards_server_id_servers_id_fk": { + "name": "port_forwards_server_id_servers_id_fk", + "tableFrom": "port_forwards", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "push_subscriptions": { + "name": "push_subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "endpoint": { + "name": "endpoint", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "p256dh": { + "name": "p256dh", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth": { + "name": "auth", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_success_at": { + "name": "last_success_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "min_severity": { + "name": "min_severity", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "categories": { + "name": "categories", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "push_subscriptions_endpoint_unique": { + "name": "push_subscriptions_endpoint_unique", + "columns": [ + "endpoint" + ], + "isUnique": true + } + }, + "foreignKeys": { + "push_subscriptions_user_id_users_id_fk": { + "name": "push_subscriptions_user_id_users_id_fk", + "tableFrom": "push_subscriptions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "renewals": { + "name": "renewals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "from_date": { + "name": "from_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "to_date": { + "name": "to_date", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "renewals_at_idx": { + "name": "renewals_at_idx", + "columns": [ + "at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "restore_tests": { + "name": "restore_tests", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "subject_key": { + "name": "subject_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tested_at": { + "name": "tested_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tested_by": { + "name": "tested_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "restore_tests_subject_idx": { + "name": "restore_tests_subject_idx", + "columns": [ + "subject_key", + "tested_at" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runbooks": { + "name": "runbooks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "runbooks_target_idx": { + "name": "runbooks_target_idx", + "columns": [ + "target_type", + "target_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "scheduled_tasks": { + "name": "scheduled_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'agent'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schedule_expression": { + "name": "schedule_expression", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_metadata": { + "name": "raw_metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_stale": { + "name": "is_stale", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "scheduled_tasks_server_id_servers_id_fk": { + "name": "scheduled_tasks_server_id_servers_id_fk", + "tableFrom": "scheduled_tasks", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "secrets": { + "name": "secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'generic'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expiry_date": { + "name": "expiry_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warn_days": { + "name": "warn_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 30 + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_host": { + "name": "check_host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_port": { + "name": "check_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_links": { + "name": "server_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "server_links_server_id_servers_id_fk": { + "name": "server_links_server_id_servers_id_fk", + "tableFrom": "server_links", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_metrics": { + "name": "server_metrics", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "server_metrics_lookup_idx": { + "name": "server_metrics_lookup_idx", + "columns": [ + "server_id", + "metric", + "recorded_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "server_metrics_server_id_servers_id_fk": { + "name": "server_metrics_server_id_servers_id_fk", + "tableFrom": "server_metrics", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_metrics_rollup": { + "name": "server_metrics_rollup", + "columns": { + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "grain": { + "name": "grain", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sum": { + "name": "sum", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "n": { + "name": "n", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "min": { + "name": "min", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "max": { + "name": "max", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "server_metrics_rollup_server_id_servers_id_fk": { + "name": "server_metrics_rollup_server_id_servers_id_fk", + "tableFrom": "server_metrics_rollup", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "server_metrics_rollup_server_id_metric_grain_at_pk": { + "columns": [ + "server_id", + "metric", + "grain", + "at" + ], + "name": "server_metrics_rollup_server_id_metric_grain_at_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_ports": { + "name": "server_ports", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "open": { + "name": "open", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "last_seen_open_at": { + "name": "last_seen_open_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "server_ports_unique": { + "name": "server_ports_unique", + "columns": [ + "server_id", + "port", + "protocol" + ], + "isUnique": true + } + }, + "foreignKeys": { + "server_ports_server_id_servers_id_fk": { + "name": "server_ports_server_id_servers_id_fk", + "tableFrom": "server_ports", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "servers": { + "name": "servers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hostname": { + "name": "hostname", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_type": { + "name": "os_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'linux'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "api_token_hash": { + "name": "api_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "api_token_prefix": { + "name": "api_token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ip_addresses": { + "name": "ip_addresses", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_model": { + "name": "cpu_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_cores": { + "name": "cpu_cores", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_load_percent": { + "name": "cpu_load_percent", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_total_bytes": { + "name": "mem_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_used_bytes": { + "name": "mem_used_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disks": { + "name": "disks", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "listening_ports": { + "name": "listening_ports", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_port_scan": { + "name": "last_port_scan", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_integration_id": { + "name": "proxmox_integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_node": { + "name": "proxmox_node", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_guest_type": { + "name": "proxmox_guest_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_vmid": { + "name": "proxmox_vmid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hide_proxmox_link": { + "name": "hide_proxmox_link", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "parent_server_id": { + "name": "parent_server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "no_parent": { + "name": "no_parent", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "pending_updates": { + "name": "pending_updates", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_pending_since": { + "name": "updates_pending_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_health": { + "name": "host_health", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_diagnostics": { + "name": "agent_diagnostics", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "port_baseline": { + "name": "port_baseline", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_id": { + "name": "os_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_name": { + "name": "os_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_version": { + "name": "os_version", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hw_manufacturer": { + "name": "hw_manufacturer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hw_model": { + "name": "hw_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hw_serial": { + "name": "hw_serial", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "thresholds": { + "name": "thresholds", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_version": { + "name": "agent_version", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "servers_proxmox_integration_id_integrations_id_fk": { + "name": "servers_proxmox_integration_id_integrations_id_fk", + "tableFrom": "servers", + "tableTo": "integrations", + "columnsFrom": [ + "proxmox_integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "share_links": { + "name": "share_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'summary'" + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'wall'" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "share_links_token_hash_unique": { + "name": "share_links_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "status_items": { + "name": "status_items", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "link_id": { + "name": "link_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "monitor_id": { + "name": "monitor_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "status_items_link_idx": { + "name": "status_items_link_idx", + "columns": [ + "link_id", + "position" + ], + "isUnique": false + } + }, + "foreignKeys": { + "status_items_link_id_share_links_id_fk": { + "name": "status_items_link_id_share_links_id_fk", + "tableFrom": "status_items", + "tableTo": "share_links", + "columnsFrom": [ + "link_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "storage_samples": { + "name": "storage_samples", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "series_id": { + "name": "series_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "storage_samples_series_idx": { + "name": "storage_samples_series_idx", + "columns": [ + "series_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "storage_samples_series_id_storage_series_id_fk": { + "name": "storage_samples_series_id_storage_series_id_fk", + "tableFrom": "storage_samples", + "tableTo": "storage_series", + "columnsFrom": [ + "series_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "storage_series": { + "name": "storage_series", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latest_percent": { + "name": "latest_percent", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_bytes": { + "name": "used_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "total_bytes": { + "name": "total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "storage_series_key_idx": { + "name": "storage_series_key_idx", + "columns": [ + "integration_id", + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "storage_series_integration_id_integrations_id_fk": { + "name": "storage_series_integration_id_integrations_id_fk", + "tableFrom": "storage_series", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tag_definitions": { + "name": "tag_definitions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "tag_definitions_name_unique": { + "name": "tag_definitions_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "todos": { + "name": "todos", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "due_date": { + "name": "due_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assignee_user_id": { + "name": "assignee_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "assignee_name": { + "name": "assignee_name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "done_at": { + "name": "done_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "done_by": { + "name": "done_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "todos_assignee_user_id_users_id_fk": { + "name": "todos_assignee_user_id_users_id_fk", + "tableFrom": "todos", + "tableTo": "users", + "columnsFrom": [ + "assignee_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "update_runs": { + "name": "update_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_id": { + "name": "template_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "template_name": { + "name": "template_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "host_limit": { + "name": "host_limit", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_status": { + "name": "task_status", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "window_id": { + "name": "window_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "window_created": { + "name": "window_created", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_by": { + "name": "started_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_ended_at": { + "name": "task_ended_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host_reported_at": { + "name": "host_reported_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "finished_at": { + "name": "finished_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_before": { + "name": "updates_before", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_after": { + "name": "updates_after", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "reboot_required": { + "name": "reboot_required", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "poll_errors": { + "name": "poll_errors", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": { + "update_runs_server_idx": { + "name": "update_runs_server_idx", + "columns": [ + "server_id", + "started_at" + ], + "isUnique": false + }, + "update_runs_status_idx": { + "name": "update_runs_status_idx", + "columns": [ + "status" + ], + "isUnique": false + } + }, + "foreignKeys": { + "update_runs_server_id_servers_id_fk": { + "name": "update_runs_server_id_servers_id_fk", + "tableFrom": "update_runs", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ups_readings": { + "name": "ups_readings", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "at": { + "name": "at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "charge": { + "name": "charge", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "runtime_seconds": { + "name": "runtime_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "load_percent": { + "name": "load_percent", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input_voltage": { + "name": "input_voltage", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "on_battery": { + "name": "on_battery", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + } + }, + "indexes": { + "ups_readings_lookup_idx": { + "name": "ups_readings_lookup_idx", + "columns": [ + "integration_id", + "at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "ups_readings_integration_id_integrations_id_fk": { + "name": "ups_readings_integration_id_integrations_id_fk", + "tableFrom": "ups_readings", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ups_state": { + "name": "ups_state", + "columns": { + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "manufacturer": { + "name": "manufacturer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status_text": { + "name": "status_text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "on_battery": { + "name": "on_battery", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "low_battery": { + "name": "low_battery", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "replace_battery": { + "name": "replace_battery", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "overload": { + "name": "overload", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "charge": { + "name": "charge", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "runtime_seconds": { + "name": "runtime_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "load_percent": { + "name": "load_percent", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "input_voltage": { + "name": "input_voltage", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "output_voltage": { + "name": "output_voltage", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "on_battery_since": { + "name": "on_battery_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "ups_state_integration_id_integrations_id_fk": { + "name": "ups_state_integration_id_integrations_id_fk", + "tableFrom": "ups_state", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "oidc_sub": { + "name": "oidc_sub", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'viewer'" + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_login_at": { + "name": "last_login_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "favorites": { + "name": "favorites", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_looked_at": { + "name": "last_looked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "groups": { + "name": "groups", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dashboard_layout": { + "name": "dashboard_layout", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "picture_url": { + "name": "picture_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_oidc_sub_unique": { + "name": "users_oidc_sub_unique", + "columns": [ + "oidc_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "webhook_deliveries": { + "name": "webhook_deliveries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "webhook_id": { + "name": "webhook_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "delivery_id": { + "name": "delivery_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "retry_of": { + "name": "retry_of", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "webhook_deliveries_webhook_idx": { + "name": "webhook_deliveries_webhook_idx", + "columns": [ + "webhook_id", + "created_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "webhook_deliveries_webhook_id_event_webhooks_id_fk": { + "name": "webhook_deliveries_webhook_id_event_webhooks_id_fk", + "tableFrom": "webhook_deliveries", + "tableTo": "event_webhooks", + "columnsFrom": [ + "webhook_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 607d6a9..4336173 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -379,6 +379,13 @@ "when": 1792609540216, "tag": "0053_dashing_stark_industries", "breakpoints": true + }, + { + "idx": 54, + "version": "6", + "when": 1792610229172, + "tag": "0054_green_beast", + "breakpoints": true } ] } \ No newline at end of file diff --git a/server/src/app.ts b/server/src/app.ts index 6ff0826..8f7c9bd 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -55,6 +55,7 @@ import { storageRouter } from "./routes/storage.js"; import { dataUsageRouter } from "./routes/dataUsage.js"; import { alertActionsRouter } from "./routes/alertActions.js"; import { homeAssistantRouter } from "./routes/homeAssistant.js"; +import { upsRouter } from "./routes/ups.js"; import { publicApiRouter } from "./routes/publicApi.js"; import { generatorRouter } from "./routes/generator.js"; import { alertTicketsRouter } from "./routes/alertTickets.js"; @@ -184,6 +185,7 @@ export function createApp() { app.use("/api/storage", storageRouter); app.use("/api/data-usage", dataUsageRouter); app.use("/api/home-assistant", homeAssistantRouter); + app.use("/api/ups", upsRouter); app.use("/api/todos", todosRouter); app.use("/api/notes", notesRouter); app.use("/api/generator", generatorRouter); diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 23791b0..df2883f 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -552,6 +552,7 @@ export const integrationTypes = [ "unifi", "npm", "homeassistant", + "ups", ] as const; export type IntegrationType = (typeof integrationTypes)[number]; @@ -1158,6 +1159,48 @@ export const haReadings = sqliteTable( (t) => [index("ha_readings_lookup_idx").on(t.integrationId, t.entityId, t.at)], ); +// ─── UPS ──────────────────────────────────────────────────────────────────── + +// How a UPS (an integration of type "ups", read over NUT or SNMP by services/upsSync.ts) is right now: one row each, replaced at every read. `updatedAt` is the last +// read that worked; `onBatterySince` is when mains power was lost, kept until it is back. +export const upsState = sqliteTable("ups_state", { + integrationId: integer("integration_id") + .primaryKey() + .references(() => integrations.id, { onDelete: "cascade" }), + model: text("model"), + manufacturer: text("manufacturer"), + statusText: text("status_text").notNull(), + onBattery: integer("on_battery", { mode: "boolean" }).notNull().default(false), + lowBattery: integer("low_battery", { mode: "boolean" }).notNull().default(false), + replaceBattery: integer("replace_battery", { mode: "boolean" }).notNull().default(false), + overload: integer("overload", { mode: "boolean" }).notNull().default(false), + charge: real("charge"), + runtimeSeconds: integer("runtime_seconds"), + loadPercent: real("load_percent"), + inputVoltage: real("input_voltage"), + outputVoltage: real("output_voltage"), + onBatterySince: text("on_battery_since"), // ISO + updatedAt: text("updated_at").notNull(), // ISO +}); + +// A UPS at a moment, for the charts: one every five minutes, and every minute while it runs on battery. Kept 35 days. +export const upsReadings = sqliteTable( + "ups_readings", + { + id: integer("id").primaryKey({ autoIncrement: true }), + integrationId: integer("integration_id") + .notNull() + .references(() => integrations.id, { onDelete: "cascade" }), + at: text("at").notNull(), // ISO + charge: real("charge"), + runtimeSeconds: integer("runtime_seconds"), + loadPercent: real("load_percent"), + inputVoltage: real("input_voltage"), + onBattery: integer("on_battery", { mode: "boolean" }).notNull().default(false), + }, + (t) => [index("ups_readings_lookup_idx").on(t.integrationId, t.at)], +); + // ─── Notes and the to-do list ─────────────────────────────────────────────── // Free-form notes about a server or a network device — what is it, where does it sit, what did I do to it last time — one text per thing, drawn with the same small diff --git a/server/src/index.ts b/server/src/index.ts index bc78470..f18bcd1 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -27,6 +27,7 @@ import { initFlapMonitor } from "./services/flapMonitor.js"; import { initSnoozeMonitor } from "./services/snoozeMonitor.js"; import { initUnifiSync } from "./services/unifiSync.js"; import { initHomeAssistantSync } from "./services/homeAssistantSync.js"; +import { initUpsSync } from "./services/upsSync.js"; import { backfillMetricRollups } from "./services/serverMetrics.js"; import { backfillEndpointHourly } from "./services/endpointChecks.js"; import { initSelfBackupScheduler } from "./services/selfBackupScheduler.js"; @@ -75,6 +76,7 @@ initFlapMonitor(); initSnoozeMonitor(); initUnifiSync(); initHomeAssistantSync(); +initUpsSync(); // The hourly and daily figures are built from what is already kept, once, the first time after they were added (in the background: nothing waits for it). void Promise.all([backfillMetricRollups(), backfillEndpointHourly()]).catch((err) => console.error("[history] couldn't build the hourly and daily figures:", err)); diff --git a/server/src/integrations/fieldSchemas.ts b/server/src/integrations/fieldSchemas.ts index e76efec..bcacad1 100644 --- a/server/src/integrations/fieldSchemas.ts +++ b/server/src/integrations/fieldSchemas.ts @@ -99,6 +99,13 @@ export const INTEGRATION_FIELDS: Partial; @@ -53,6 +54,8 @@ export function createIntegrationAdapter(type: IntegrationType, config: Integrat return createNpmAdapter(config as any); case "homeassistant": return createHomeAssistantAdapter(config as any); + case "ups": + return createUpsAdapter(config as any); default: throw new Error(`Integration type "${type}" is not implemented yet`); } diff --git a/server/src/integrations/ups/adapter.ts b/server/src/integrations/ups/adapter.ts new file mode 100644 index 0000000..46ecd6e --- /dev/null +++ b/server/src/integrations/ups/adapter.ts @@ -0,0 +1,40 @@ +/** + * UPS adapter. Config: host; optional: port, snmp (read over SNMP instead of NUT), upsName (NUT), community (SNMP). + * + * A UPS is read, never controlled: NUT's `LIST VAR` or an SNMP GET of the UPS-MIB. What it says is the same either way (integrations/ups/types.ts). + */ +import { withDiagLogging } from "../../services/diagLog.js"; +import { NUT_PORT, readNut } from "./nut.js"; +import { readSnmp, SNMP_PORT } from "./snmp.js"; +import type { UpsConfig, UpsReading } from "./types.js"; + +export interface UpsAdapter { + ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>; + read(): Promise; +} + +const truthy = (v: unknown) => v === true || v === "true"; + +/** The port in the config, or the protocol's own. */ +export function portOf(config: UpsConfig): number { + const asked = Number(config.port); + return Number.isInteger(asked) && asked >= 1 && asked <= 65535 ? asked : truthy(config.snmp) ? SNMP_PORT : NUT_PORT; +} + +export function createUpsAdapter(config: UpsConfig): UpsAdapter { + const host = String(config.host ?? "").trim(); + async function read(): Promise { + if (!host) throw new Error("no host given"); + return truthy(config.snmp) ? readSnmp(host, portOf(config), (config.community || "public").toString()) : readNut(host, portOf(config), config.upsName?.toString().trim() || null); + } + async function ping() { + const start = Date.now(); + try { + await read(); + return { ok: true, latencyMs: Date.now() - start }; + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) }; + } + } + return withDiagLogging("ups", { ping, read }); +} diff --git a/server/src/integrations/ups/nut.ts b/server/src/integrations/ups/nut.ts new file mode 100644 index 0000000..f47fd68 --- /dev/null +++ b/server/src/integrations/ups/nut.ts @@ -0,0 +1,116 @@ +/** + * Network UPS Tools: `upsd` answers a short text protocol on TCP port 3493 and needs no login to read. `LIST VAR ` gives every variable the driver has + * (`battery.charge`, `ups.status`, …) between a BEGIN and an END line; `LIST UPS` names the UPSs it knows. Only reading is done here — never a command. + */ +import net from "node:net"; +import { resolveTarget } from "../../utils/networkGuard.js"; +import type { UpsReading } from "./types.js"; + +export const NUT_PORT = 3493; +const TIMEOUT_MS = 5000; + +/** `VAR ups battery.charge "100"` lines into a map; anything else in the text is ignored. */ +export function parseNutVars(text: string): Record { + const out: Record = {}; + for (const line of text.split(/\r?\n/)) { + const m = /^VAR\s+\S+\s+(\S+)\s+"((?:[^"\\]|\\.)*)"\s*$/.exec(line); + if (m) out[m[1]] = m[2].replace(/\\(.)/g, "$1"); + } + return out; +} + +/** The names in an answer to `LIST UPS`. */ +export function parseNutUpsNames(text: string): string[] { + const out: string[] = []; + for (const line of text.split(/\r?\n/)) { + const m = /^UPS\s+(\S+)\s/.exec(line); + if (m) out.push(m[1]); + } + return out; +} + +const num = (v: string | undefined): number | null => { + if (v === undefined || v.trim() === "") return null; + const n = Number(v); + return Number.isFinite(n) ? n : null; +}; + +/** The variables of one UPS as what the app keeps. `ups.status` is a list of flags: OL online, OB on battery, LB low battery, RB replace battery, OVER overload. */ +export function interpretNut(vars: Record): UpsReading { + const status = (vars["ups.status"] ?? "").trim(); + const flags = new Set(status.split(/\s+/).filter(Boolean)); + return { + model: vars["device.model"] || vars["ups.model"] || null, + manufacturer: vars["device.mfr"] || vars["ups.mfr"] || null, + statusText: status || "unknown", + onBattery: flags.has("OB"), + lowBattery: flags.has("LB"), + replaceBattery: flags.has("RB"), + overload: flags.has("OVER"), + charge: num(vars["battery.charge"]), + runtimeSeconds: num(vars["battery.runtime"]), + loadPercent: num(vars["ups.load"]), + inputVoltage: num(vars["input.voltage"]), + outputVoltage: num(vars["output.voltage"]), + }; +} + +/** Sends the commands one after the other on one connection, each answered by a BEGIN … END block (or an ERR line), and returns the answers. */ +function ask(host: string, port: number, commands: string[]): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect({ host, port }); + const answers: string[] = []; + let buffer = ""; + let index = 0; + let finished = false; + const done = (err: Error | null) => { + if (finished) return; + finished = true; + // After a good answer the connection is closed politely (LOGOUT is already sent); after a bad one it is simply dropped. + if (err) socket.destroy(); + else { + socket.end(); + setTimeout(() => socket.destroy(), 200).unref(); + } + if (err) reject(err); + else resolve(answers); + }; + socket.setTimeout(TIMEOUT_MS, () => done(new Error(`no answer within ${TIMEOUT_MS / 1000} s`))); + socket.on("error", (err: NodeJS.ErrnoException) => done(new Error(err.code === "ECONNREFUSED" ? `nothing is listening on port ${port} — is upsd running, and does it listen on this address (LISTEN in upsd.conf)?` : err.message))); + socket.on("close", () => done(new Error("the connection closed before the answer was complete"))); + socket.on("connect", () => socket.write(`${commands[0]}\n`)); + socket.on("data", (chunk) => { + buffer += chunk.toString("utf8"); + for (;;) { + const err = /^ERR\s+(.*)$/m.exec(buffer); + if (err) return done(new Error(`upsd says ${err[1].trim()}`)); + const end = /^END LIST .*$/m.exec(buffer); + if (!end) return; + const cut = end.index + end[0].length; + answers.push(buffer.slice(0, cut)); + buffer = buffer.slice(cut); + index++; + if (index >= commands.length) { + socket.write("LOGOUT\n"); + return done(null); + } + socket.write(`${commands[index]}\n`); + } + }); + }); +} + +/** Asks the NUT server about one UPS: `upsName`, or the first it lists when none is given. */ +export async function readNut(host: string, port: number, upsName: string | null): Promise { + const address = await resolveTarget(host, { allowPrivate: true }); + let name = upsName; + if (!name) { + const [list] = await ask(address, port, ["LIST UPS"]); + name = parseNutUpsNames(list)[0] ?? null; + if (!name) throw new Error("the NUT server lists no UPS"); + } + const [vars] = await ask(address, port, [`LIST VAR ${name}`]); + const parsed = parseNutVars(vars); + if (Object.keys(parsed).length === 0) throw new Error(`the NUT server gave no variables for “${name}”`); + return interpretNut(parsed); +} diff --git a/server/src/integrations/ups/snmp.ts b/server/src/integrations/ups/snmp.ts new file mode 100644 index 0000000..a4e9f66 --- /dev/null +++ b/server/src/integrations/ups/snmp.ts @@ -0,0 +1,240 @@ +/** + * SNMP, version 2c, only as far as asking for a few values: one GET request over UDP (port 161) naming the objects of the standard UPS-MIB (RFC 1628), which most UPSs + * and their network cards answer. Hand-written, because a GET is a few dozen lines of BER and a whole SNMP library is far more than is needed (and nothing is ever set). + */ +import dgram from "node:dgram"; +import net from "node:net"; +import { resolveTarget } from "../../utils/networkGuard.js"; +import type { UpsReading } from "./types.js"; + +export const SNMP_PORT = 161; +const TIMEOUT_MS = 2500; +const TRIES = 2; + +// ─── BER ──────────────────────────────────────────────────────────────────── + +const lengthBytes = (n: number): number[] => (n < 0x80 ? [n] : n < 0x100 ? [0x81, n] : [0x82, n >> 8, n & 0xff]); + +function tlv(tag: number, content: number[] | Buffer): Buffer { + const body = Buffer.from(content); + return Buffer.concat([Buffer.from([tag, ...lengthBytes(body.length)]), body]); +} + +function encodeInt(n: number): Buffer { + const bytes: number[] = []; + let v = n; + do { + bytes.unshift(v & 0xff); + v = Math.floor(v / 256); + } while (v > 0); + if (bytes[0] & 0x80) bytes.unshift(0); + return tlv(0x02, bytes); +} + +/** "1.3.6.1.2.1.33.1.2.4.0" into its BER form. */ +export function encodeOid(oid: string): Buffer { + const parts = oid.split(".").map(Number); + const bytes: number[] = [parts[0] * 40 + parts[1]]; + for (const p of parts.slice(2)) { + const chunk = [p & 0x7f]; + let v = Math.floor(p / 128); + while (v > 0) { + chunk.unshift((v & 0x7f) | 0x80); + v = Math.floor(v / 128); + } + bytes.push(...chunk); + } + return tlv(0x06, bytes); +} + +/** A GET request for these objects, from this community, under this request id. */ +export function buildGet(community: string, requestId: number, oids: string[]): Buffer { + const varbinds = oids.map((o) => tlv(0x30, Buffer.concat([encodeOid(o), tlv(0x05, [])]))); + const pdu = tlv(0xa0, Buffer.concat([encodeInt(requestId), encodeInt(0), encodeInt(0), tlv(0x30, Buffer.concat(varbinds))])); + return tlv(0x30, Buffer.concat([encodeInt(1), tlv(0x04, Buffer.from(community, "utf8")), pdu])); +} + +interface Node { + tag: number; + value: Buffer; +} + +/** The TLVs one after the other in `buf`. */ +function children(buf: Buffer): Node[] { + const out: Node[] = []; + let i = 0; + while (i < buf.length) { + const tag = buf[i++]; + let len = buf[i++]; + if (len === undefined) throw new Error("the answer is cut short"); + if (len & 0x80) { + const n = len & 0x7f; + if (n === 0 || n > 3) throw new Error("the answer has a length that can't be read"); + len = 0; + for (let k = 0; k < n; k++) len = len * 256 + buf[i++]; + } + if (i + len > buf.length) throw new Error("the answer is cut short"); + out.push({ tag, value: buf.subarray(i, i + len) }); + i += len; + } + return out; +} + +function decodeUint(buf: Buffer): number { + let n = 0; + for (const b of buf) n = n * 256 + b; + return n; +} + +function decodeInt(buf: Buffer): number { + if (buf.length === 0) return 0; + let v = 0; + for (const b of buf) v = v * 256 + b; + // two's complement + return buf[0] & 0x80 ? v - 2 ** (8 * buf.length) : v; +} + +function decodeOid(buf: Buffer): string { + if (buf.length === 0) return ""; + const parts = [Math.floor(buf[0] / 40), buf[0] % 40]; + let v = 0; + for (const b of buf.subarray(1)) { + v = v * 128 + (b & 0x7f); + if (!(b & 0x80)) { + parts.push(v); + v = 0; + } + } + return parts.join("."); +} + +export type SnmpValue = number | string | null; + +export interface SnmpAnswer { + requestId: number; + /** 0 when the agent had no complaint. */ + errorStatus: number; + /** Object → its value; null where the agent has no such object. */ + values: Map; +} + +/** An answer to a GET: its request id and each object's value. Throws if it isn't one. */ +export function parseResponse(packet: Buffer): SnmpAnswer { + const [message] = children(packet); + if (!message || message.tag !== 0x30) throw new Error("that isn't an SNMP message"); + const [, , pdu] = children(message.value); + if (!pdu || pdu.tag !== 0xa2) throw new Error("that isn't an answer to a request"); + const [id, errorStatus, , bindings] = children(pdu.value); + const values = new Map(); + for (const vb of children(bindings.value)) { + const [oid, value] = children(vb.value); + let v: SnmpValue; + switch (value.tag) { + case 0x02: + v = decodeInt(value.value); + break; + case 0x41: // counter32 + case 0x42: // gauge32 + case 0x43: // timeticks + case 0x46: // counter64 + v = decodeUint(value.value); + break; + case 0x04: + v = value.value.toString("utf8").replace(/\0+$/, "").trim(); + break; + default: + // null, noSuchObject, noSuchInstance, endOfMibView, or something not needed: there is no value here + v = null; + } + values.set(decodeOid(oid.value), v); + } + return { requestId: decodeInt(id.value), errorStatus: decodeInt(errorStatus.value), values }; +} + +// ─── The UPS-MIB ──────────────────────────────────────────────────────────── + +const B = "1.3.6.1.2.1.33.1"; +export const OIDS = { + manufacturer: `${B}.1.1.0`, + model: `${B}.1.2.0`, + batteryStatus: `${B}.2.1.0`, // 1 unknown, 2 normal, 3 low, 4 depleted + secondsOnBattery: `${B}.2.2.0`, + minutesRemaining: `${B}.2.3.0`, + chargeRemaining: `${B}.2.4.0`, + inputVoltage: `${B}.3.3.1.3.1`, + outputSource: `${B}.4.1.0`, // 3 normal, 4 bypass, 5 battery, 6 booster, 7 reducer + outputVoltage: `${B}.4.4.1.2.1`, + outputLoad: `${B}.4.4.1.5.1`, +} as const; + +const asNumber = (v: SnmpValue | undefined): number | null => (typeof v === "number" ? v : typeof v === "string" && v !== "" && Number.isFinite(Number(v)) ? Number(v) : null); +const asText = (v: SnmpValue | undefined): string | null => (typeof v === "string" && v !== "" ? v : null); + +const SOURCES: Record = { 1: "other", 2: "no output", 3: "normal", 4: "bypass", 5: "on battery", 6: "booster", 7: "reducer" }; +const BATTERY: Record = { 1: "battery unknown", 2: "battery normal", 3: "battery low", 4: "battery depleted" }; + +/** The objects of the UPS-MIB, as what the app keeps. */ +export function interpretSnmp(values: Map): UpsReading { + const get = (oid: string) => values.get(oid); + const source = asNumber(get(OIDS.outputSource)); + const battery = asNumber(get(OIDS.batteryStatus)); + const secondsOn = asNumber(get(OIDS.secondsOnBattery)); + const minutes = asNumber(get(OIDS.minutesRemaining)); + const onBattery = source === 5 || (source === null && secondsOn !== null && secondsOn > 0); + const text = [source !== null ? (SOURCES[source] ?? `source ${source}`) : null, battery !== null ? (BATTERY[battery] ?? null) : null].filter(Boolean).join(", "); + return { + model: asText(get(OIDS.model)), + manufacturer: asText(get(OIDS.manufacturer)), + statusText: text || "unknown", + onBattery, + lowBattery: battery === 3 || battery === 4, + replaceBattery: false, + overload: false, + charge: asNumber(get(OIDS.chargeRemaining)), + runtimeSeconds: minutes !== null ? minutes * 60 : null, + loadPercent: asNumber(get(OIDS.outputLoad)), + inputVoltage: asNumber(get(OIDS.inputVoltage)), + outputVoltage: asNumber(get(OIDS.outputVoltage)), + }; +} + +/** One request and its answer over UDP, tried a second time when nothing comes back. */ +function exchange(address: string, port: number, request: Buffer, requestId: number): Promise { + const type = net.isIP(address) === 6 ? "udp6" : "udp4"; + return new Promise((resolve, reject) => { + const socket = dgram.createSocket(type); + let tries = 0; + let timer: ReturnType; + const finish = (err: Error | null, answer?: SnmpAnswer) => { + clearTimeout(timer); + socket.close(); + if (err) reject(err); + else resolve(answer!); + }; + const send = () => { + tries++; + socket.send(request, port, address, (err) => err && finish(err)); + timer = setTimeout(() => (tries < TRIES ? send() : finish(new Error(`no answer within ${(TIMEOUT_MS * TRIES) / 1000} s — is SNMP on, and is the community right?`))), TIMEOUT_MS); + }; + socket.on("error", (err) => finish(err)); + socket.on("message", (msg) => { + try { + const answer = parseResponse(msg); + if (answer.requestId === requestId) finish(null, answer); + } catch { + // something else arriving on this port: ignored + } + }); + send(); + }); +} + +export async function readSnmp(host: string, port: number, community: string): Promise { + const address = await resolveTarget(host, { allowPrivate: true }); + const requestId = 1 + Math.floor(Math.random() * 0x7ffffff0); + const answer = await exchange(address, port, buildGet(community, requestId, Object.values(OIDS)), requestId); + if (answer.errorStatus !== 0) throw new Error(`the device refused the request (error ${answer.errorStatus})`); + const known = [...answer.values.values()].filter((v) => v !== null).length; + if (known === 0) throw new Error("the device answers, but has none of the standard UPS objects (UPS-MIB)"); + return interpretSnmp(answer.values); +} diff --git a/server/src/integrations/ups/types.ts b/server/src/integrations/ups/types.ts new file mode 100644 index 0000000..90c2d91 --- /dev/null +++ b/server/src/integrations/ups/types.ts @@ -0,0 +1,34 @@ +/** What a UPS says about itself, the same whichever way it was asked (NUT or SNMP). Anything it doesn't say is null. */ +export interface UpsReading { + model: string | null; + manufacturer: string | null; + /** The UPS's own words for how it is ("OL CHRG", "on battery"), to show. */ + statusText: string; + /** Mains power is gone and it is running from its battery. */ + onBattery: boolean; + /** The battery is nearly empty: shut things down now. */ + lowBattery: boolean; + /** The UPS asks for its battery to be replaced. */ + replaceBattery: boolean; + /** It is carrying more than it can. */ + overload: boolean; + /** Battery charge, percent. */ + charge: number | null; + /** How long the battery would last at the present load. */ + runtimeSeconds: number | null; + /** How much of its capacity the load uses, percent. */ + loadPercent: number | null; + inputVoltage: number | null; + outputVoltage: number | null; +} + +export interface UpsConfig { + host: string; + port?: string; + /** Read over SNMP (version 2c) instead of NUT. */ + snmp?: boolean | string; + /** NUT: the UPS's name on that server; the first one it lists when left blank. */ + upsName?: string; + /** SNMP: the read community; "public" when left blank. */ + community?: string; +} diff --git a/server/src/routes/integrations.ts b/server/src/routes/integrations.ts index 722f3d8..0c4977b 100644 --- a/server/src/routes/integrations.ts +++ b/server/src/routes/integrations.ts @@ -27,6 +27,7 @@ import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../ import { getSourceStatus } from "../services/integrationHealthMonitor.js"; import { removeIntegrationData, syncUnifiIntegration } from "../services/unifiSync.js"; import { removeHomeAssistantData, syncHomeAssistant } from "../services/homeAssistantSync.js"; +import { forgetUps, syncUps } from "../services/upsSync.js"; import { invalidateAlertsCache } from "../services/alerts.js"; import { asyncHandler } from "../utils/asyncHandler.js"; import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js"; @@ -127,6 +128,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) // A new UniFi controller is read at once, so its equipment is there when the person opens the page (not waited for: a slow controller must not slow this). if (type === "unifi") void syncUnifiIntegration(created.id).then(() => invalidateAlertsCache()); if (type === "homeassistant") void syncHomeAssistant(created.id).then(() => invalidateAlertsCache()); + if (type === "ups") void syncUps(created.id).then(() => invalidateAlertsCache()); res.status(201).json({ integration: { @@ -229,6 +231,7 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, if (updated.type === "unifi" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUnifiIntegration(updated.id).then(() => invalidateAlertsCache()); if (updated.type === "homeassistant" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncHomeAssistant(updated.id).then(() => invalidateAlertsCache()); + if (updated.type === "ups" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUps(updated.id).then(() => invalidateAlertsCache()); res.json({ integration: { @@ -307,6 +310,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, if (existing.type === "unifi") await removeIntegrationData(id); if (existing.type === "homeassistant") await removeHomeAssistantData(id); + if (existing.type === "ups") await forgetUps(id); await db.delete(integrations).where(eq(integrations.id, id)); if (existing.credentialId) { await db.delete(integrationCredentials).where(eq(integrationCredentials.id, existing.credentialId)); diff --git a/server/src/routes/ups.ts b/server/src/routes/ups.ts new file mode 100644 index 0000000..0092163 --- /dev/null +++ b/server/src/routes/ups.ts @@ -0,0 +1,77 @@ +import { Router } from "express"; +import { and, asc, eq, gte } from "drizzle-orm"; +import { db } from "../db/client.js"; +import { integrations, upsReadings, upsState } from "../db/schema.js"; +import { requireAuth } from "../auth/middleware.js"; +import { loadGraph } from "../services/dependencies.js"; +import { bucketUps, isUpsFresh, READING_KEEP_DAYS, shutdownOrder, upsProblems, upsSyncStatuses } from "../services/upsSync.js"; +import { asyncHandler } from "../utils/asyncHandler.js"; + +export const upsRouter = Router(); +upsRouter.use(requireAuth); + +const DAY_MS = 86_400_000; +const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN); + +const isSnmp = (config: string | null) => { + try { + const c = config ? (JSON.parse(config) as Record) : {}; + return c.snmp === true || c.snmp === "true"; + } catch { + return false; + } +}; + +/** Every UPS, how it is now, and what is on it in the order to shut it down. Everyone signed in can see it, like the other pages made of stored readings. */ +upsRouter.get("/", asyncHandler(async (_req, res) => { + const [rows, states, statuses, graph] = await Promise.all([ + db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled, config: integrations.config }).from(integrations).where(eq(integrations.type, "ups")).orderBy(integrations.name), + db.select().from(upsState), + upsSyncStatuses(), + loadGraph(), + ]); + const now = new Date(); + const byId = new Map(states.map((s) => [s.integrationId, s])); + res.json({ + ups: rows.map((r) => { + const state = byId.get(r.id) ?? null; + const status = statuses[r.id] ?? null; + const fresh = isUpsFresh(status ?? undefined, now.getTime()); + const { order, looped } = shutdownOrder(graph.edges, `integration:${r.id}`); + return { + id: r.id, + name: r.name, + enabled: r.enabled, + protocol: isSnmp(r.config) ? "snmp" : "nut", + status, + fresh, + state, + problems: state && fresh ? upsProblems(r.id, r.name, state, now) : [], + // What needs this UPS, directly or through something else, in the order to shut it down (step 1 first). + carries: order.map((o) => { + const [type, id] = o.key.split(":"); + return { key: o.key, type, id: Number(id), name: graph.names.get(o.key) ?? o.key, step: o.step }; + }), + orderLooped: looped, + }; + }), + }); +})); + +/** One UPS's charge, load and mains voltage over time (readings are kept 35 days). */ +upsRouter.get("/:id/history", asyncHandler(async (req, res) => { + const id = idOf(req.params.id); + if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); + const [row] = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).where(eq(integrations.id, id)).limit(1); + if (!row || row.type !== "ups") return res.status(404).json({ error: "not_found" }); + const asked = Number(req.query.days); + const days = Number.isFinite(asked) ? Math.min(READING_KEEP_DAYS, Math.max(1, Math.round(asked))) : 7; + const to = Date.now(); + const from = to - days * DAY_MS; + const rows = await db + .select() + .from(upsReadings) + .where(and(eq(upsReadings.integrationId, id), gte(upsReadings.at, new Date(from).toISOString()))) + .orderBy(asc(upsReadings.at)); + res.json({ ups: { id: row.id, name: row.name }, days, ...bucketUps(rows, from, to, 200) }); +})); diff --git a/server/src/services/alerts.ts b/server/src/services/alerts.ts index 7b43bc9..19c58e0 100644 --- a/server/src/services/alerts.ts +++ b/server/src/services/alerts.ts @@ -72,6 +72,7 @@ const SOURCES: Record = { unifi: { label: "UniFi", link: "/network/devices" }, npm: { label: "Nginx Proxy Manager", link: "/proxy-hosts" }, homeassistant: { label: "Home Assistant", link: "/home-assistant" }, + ups: { label: "UPS", link: "/ups" }, secrets: { label: "Secrets", link: "/secrets" }, domains: { label: "Domains", link: "/dns?view=domains" }, endpoint: { label: "Endpoint", link: "/endpoints" }, @@ -100,6 +101,8 @@ function originOfConditionKey(key: string): { type: string; id: number | null; c if (m) return { type: "synology", id: Number(m[1]), category: "disk" }; m = /^automation:(semaphore|gitea):(\d+):/.exec(key); if (m) return { type: m[1], id: Number(m[2]), category: "automation" }; + m = /^ups-(?:battery|low|replace|load):(\d+)$/.exec(key); + if (m) return { type: "ups", id: Number(m[1]), category: "monitoring" }; return { type: "server", id: null, category: "disk" }; } @@ -213,22 +216,23 @@ export async function collectAlerts(): Promise { const offlineMatch = /^offline:(server|device):(\d+)$/.exec(c.key); const offlineNode = offlineMatch ? `${offlineMatch[1]}:${offlineMatch[2]}` : undefined; const parentOf = offlineNode ? cover.cause.get(offlineNode) : undefined; + const upsOnBattery = /^ups-battery:(\d+)$/.exec(c.key); push({ causedBy: parentOf !== undefined ? { name: cover.graph.names.get(parentOf) ?? parentOf, alertId: alertIdOfNode(parentOf, cover.graph) ?? undefined } : undefined, - affects: offlineNode ? cover.taken.get(offlineNode)?.sort((a, b) => a.localeCompare(b)) : undefined, + affects: offlineNode ? cover.taken.get(offlineNode)?.sort((a, b) => a.localeCompare(b)) : upsOnBattery ? cover.taken.get(`integration:${upsOnBattery[1]}`)?.sort((a, b) => a.localeCompare(b)) : undefined, category: origin.category, severity: c.severity ?? "warning", type: origin.type, message: c.message, key: c.key, - link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : c.key.startsWith("rule:") ? "?view=history" : ""}` : origin.type === "unifi" ? "/network/devices" : undefined, + link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : c.key.startsWith("rule:") ? "?view=history" : ""}` : origin.type === "unifi" ? "/network/devices" : origin.type === "ups" ? "/ups" : undefined, silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject), }); } // Integrations the check couldn't read this time. (A whole-integration entry covers its nodes, so skip those.) if (held.has("server:rules")) cannotCheck("Alert rules", "couldn't be judged — see the server log", "Server and storage health"); for (const h of held) { - const m = /^(proxmox|synology|unifi):(\d+)(?::(.+))?$/.exec(h); + const m = /^(proxmox|synology|unifi|ups):(\d+)(?::(.+))?$/.exec(h); if (!m || (m[3] && held.has(`${m[1]}:${m[2]}`))) continue; const row = intById.get(Number(m[2])); cannotCheck(`${SOURCES[m[1]].label} “${row?.name ?? `#${m[2]}`}”${m[3] ? ` (node ${m[3]})` : ""}`, "couldn't be read — see the Diagnostic Log", "Server and storage health"); diff --git a/server/src/services/dataUsage.ts b/server/src/services/dataUsage.ts index d05b02f..93ee181 100644 --- a/server/src/services/dataUsage.ts +++ b/server/src/services/dataUsage.ts @@ -36,6 +36,7 @@ export const HISTORY: Record = { heartbeat_pings: { time: "at", keep: 14 }, storage_samples: { time: "at", keep: 400, note: "one reading an hour of each Proxmox storage and Synology volume" }, ha_readings: { time: "at", keep: 35, note: "the watched Home Assistant numbers" }, + ups_readings: { time: "at", keep: 35, note: "a UPS's charge, load and mains voltage" }, alert_incidents: { time: "resolved_at", keep: 400, where: "resolved_at IS NOT NULL", note: "trimmed 400 days after an incident resolved" }, webhook_deliveries: { time: "created_at", keep: 14, note: "the last 100 per webhook, and none older than two weeks" }, audit_log: { time: "created_at", keep: "log", note: "who did what" }, diff --git a/server/src/services/dependencies.ts b/server/src/services/dependencies.ts index b357155..446d321 100644 --- a/server/src/services/dependencies.ts +++ b/server/src/services/dependencies.ts @@ -7,7 +7,7 @@ * device each is connected through, as a UniFi controller says), plus the dependencies written here. Servers, network devices and integrations are the things * that can be down and be needed. (DNS providers raise no alerts of their own, so there is * nothing to fold.) An integration is judged per kind of service, as its health is: it is folded only if every enabled instance of that - * kind is explained. + * kind is explained. A UPS is down while it runs on battery (services/upsSync.ts). */ import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; @@ -15,6 +15,7 @@ import { dependencies, integrations, networkDevices, networkServerLinks, servers import { getInternalFlag } from "./settingsStore.js"; import { listActiveWindows } from "./maintenance.js"; import { loadParentRows, resolveParents, type ParentLink } from "./serverParents.js"; +import { upsOnBatteryIds } from "./upsSync.js"; /** Where the health monitor keeps the problems it is announcing; read here so a service's alert can tell a server it needs is down. */ export const HEALTH_STATE_FLAG = "healthActiveConditions"; @@ -180,6 +181,8 @@ export function alertIdOfNode(key: string, graph: Graph): string | null { if (m[1] === "server") return `offline:offline:server:${m[2]}`; if (m[1] === "device") return `offline:offline:device:${m[2]}`; const row = graph.intRows.find((r) => r.id === Number(m[2])); + // A UPS is "down" for the map while it runs on battery, and its alert is the one about that. + if (row?.type === "ups") return `monitoring:ups-battery:${row.id}`; return row ? `integration:failing:${row.type}` : null; } @@ -229,6 +232,8 @@ export async function dependencyCover(offlineServerIds: Iterable, failin for (const id of offlineDeviceIds) down.add(nodeKey("device", id)); const failing = new Set(failingTypes); for (const [type, ids] of graph.instances) if (failing.has(type)) for (const id of ids) down.add(nodeKey("integration", id)); + // A UPS running on battery counts as down: whatever it carries is about to follow it, and is folded under its alert if it does. + for (const id of await upsOnBatteryIds()) if (graph.names.has(nodeKey("integration", id))) down.add(nodeKey("integration", id)); const cause = coveredNodes(down, graph.edges); const taken = new Map(); for (const [child, parent] of cause) taken.set(parent, [...(taken.get(parent) ?? []), graph.names.get(child) ?? child]); diff --git a/server/src/services/healthMonitor.ts b/server/src/services/healthMonitor.ts index bd618d0..51f6443 100644 --- a/server/src/services/healthMonitor.ts +++ b/server/src/services/healthMonitor.ts @@ -1,6 +1,6 @@ import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; -import { integrations, networkDevices, serverPorts, servers } from "../db/schema.js"; +import { integrations, networkDevices, serverPorts, servers, upsState } from "../db/schema.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { createProxmoxAdapter, type ProxmoxNodeStats } from "../integrations/proxmox/adapter.js"; import { createSynologyAdapter, type SynologyStorageInfo } from "../integrations/synology/adapter.js"; @@ -17,6 +17,7 @@ import { parseJson, type AgentPort } from "./agentPorts.js"; import { diskLimit, parseThresholds, type ServerThresholds } from "./serverThresholds.js"; import { computeRuleFindings, findingKey, listRules, type RuleFinding } from "./alertRules.js"; import { recordStorageSamples } from "./storageHistory.js"; +import { isUpsFresh, upsProblems, upsSyncStatuses, type UpsStateRow } from "./upsSync.js"; const STATE_FLAG = HEALTH_STATE_FLAG; /** After a restart the agents haven't had a chance to report yet (they run every 15 min), so server-derived conditions are held rather than judged. */ @@ -63,11 +64,18 @@ export interface UnifiSnapshot { integrationName: string; devices: { id: number; name: string; kind: string; model: string | null; state: string; offlineSince: string | null }[]; } +/** One UPS as last read, only offered while that reading is recent enough to be believed. */ +export interface UpsSnapshot { + integrationId: number; + integrationName: string; + state: UpsStateRow; +} export interface HealthSnapshot { servers: ServerSnapshot[]; proxmox: ProxmoxSnapshot[]; synology: SynologySnapshot[]; unifi?: UnifiSnapshot[]; + ups?: UpsSnapshot[]; /** What the administrator's own alert rules find on the servers (services/alertRules.ts). */ rules?: RuleFinding[]; } @@ -183,6 +191,11 @@ export function evaluateHealth(snapshot: HealthSnapshot, thresholds: Thresholds, } } + // A UPS that has lost mains power, is nearly empty, wants a new battery or is overloaded. + for (const u of snapshot.ups ?? []) { + for (const p of upsProblems(u.integrationId, u.integrationName, u.state, new Date(now))) out.push({ key: p.key, source: `ups:${u.integrationId}`, message: p.message, severity: p.severity }); + } + for (const px of snapshot.proxmox) { const seenShared = new Set(); for (const node of px.nodes) { @@ -395,6 +408,21 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel } } + // UPSs are read by their own pass every minute; what is judged here is what that pass stored, and only while it is recent. + const upsRows = rows.filter((r) => r.type === "ups"); + if (upsRows.length > 0) { + const statuses = await upsSyncStatuses(); + const nowMs = Date.now(); + for (const row of upsRows) { + const [state] = await db.select().from(upsState).where(eq(upsState.integrationId, row.id)).limit(1); + if (!state || !isUpsFresh(statuses[row.id], nowMs)) { + held.add(`ups:${row.id}`); + continue; + } + (snapshot.ups ??= []).push({ integrationId: row.id, integrationName: row.name, state }); + } + } + for (const row of rows) { if (row.type !== "proxmox" && row.type !== "synology") continue; try { @@ -494,7 +522,8 @@ export async function runHealthCheck(now: number = Date.now()): Promise<{ added: // A host's message says what else it takes with it. const added = announced.map((c) => { const m = /^offline:(server|device):(\d+)$/.exec(c.key); - const children = m ? cover.taken.get(`${m[1]}:${m[2]}`) : undefined; + const ups = /^ups-battery:(\d+)$/.exec(c.key); + const children = m ? cover.taken.get(`${m[1]}:${m[2]}`) : ups ? cover.taken.get(`integration:${ups[1]}`) : undefined; return children?.length ? { ...c, message: `${c.message} — also takes down ${alsoList(children)}` } : c; }); diff --git a/server/src/services/maintenance.ts b/server/src/services/maintenance.ts index 091edb6..63a09b0 100644 --- a/server/src/services/maintenance.ts +++ b/server/src/services/maintenance.ts @@ -37,6 +37,8 @@ export function subjectOfConditionKey(key: string): string | null { if (m) return `integration:${m[1]}`; m = /^automation:(?:semaphore|gitea):(\d+):/.exec(key); if (m) return `integration:${m[1]}`; + m = /^ups-(?:battery|low|replace|load):(\d+)$/.exec(key); + if (m) return `integration:${m[1]}`; return null; } diff --git a/server/src/services/metrics.ts b/server/src/services/metrics.ts index f792175..8d7f0a4 100644 --- a/server/src/services/metrics.ts +++ b/server/src/services/metrics.ts @@ -3,8 +3,10 @@ * severity, integrations, maintenance, things that expire. It reads what the app already knows — nothing here calls out to a server or an * integration on its own, so a scrape every fifteen seconds costs a few database reads (the alerts are the app's own minute-old result). */ +import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; -import { assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers } from "../db/schema.js"; +import { assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers, upsState } from "../db/schema.js"; +import { isUpsFresh, upsSyncStatuses } from "./upsSync.js"; import { latestTests } from "./restoreTests.js"; import { heartbeatState, parseStamp } from "./heartbeats.js"; import { env } from "../env.js"; @@ -56,6 +58,25 @@ class Exposition { } } +/** Each UPS, for /metrics: whether it is on battery, how full the battery is, how long it would last and how loaded it is. */ +async function addUpsMetrics(out: Exposition, now: Date) { + const fresh = new Set(); + const nowMs = now.getTime(); + const statuses = await upsSyncStatuses(); + for (const [id, s] of Object.entries(statuses)) if (isUpsFresh(s, nowMs)) fresh.add(Number(id)); + const names = new Map((await db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "ups"))).map((r) => [r.id, r])); + for (const s of await db.select().from(upsState)) { + const row = names.get(s.integrationId); + if (!row || !row.enabled || !fresh.has(s.integrationId)) continue; + const labels = { name: row.name }; + out.add("homelab_ups_on_battery", "gauge", "1 if the UPS has lost mains power and runs on its battery, else 0.", s.onBattery ? 1 : 0, labels); + if (s.charge !== null) out.add("homelab_ups_battery_charge_percent", "gauge", "How full the UPS's battery is.", s.charge, labels); + if (s.runtimeSeconds !== null) out.add("homelab_ups_runtime_seconds", "gauge", "How long the UPS's battery would last at the present load.", s.runtimeSeconds, labels); + if (s.loadPercent !== null) out.add("homelab_ups_load_percent", "gauge", "How much of its capacity the UPS's load uses.", s.loadPercent, labels); + if (s.inputVoltage !== null) out.add("homelab_ups_input_volts", "gauge", "The mains voltage the UPS sees.", s.inputVoltage, labels); + } +} + /** Endpoint checks and restore tests, for /metrics. */ async function addEndpointMetrics(out: Exposition, now: Date) { for (const c of await db.select().from(endpointChecks)) { @@ -217,6 +238,7 @@ export async function buildMetrics(now: Date = new Date()): Promise { out.add("homelab_scrape_duration_seconds", "gauge", "How long building this answer took.", (Date.now() - started) / 1000); out.add("homelab_scrape_timestamp_seconds", "gauge", "When this answer was built, as a Unix time.", nowSec); await addEndpointMetrics(out, now); + await addUpsMetrics(out, now); await addHeartbeatMetrics(out, now); return out.toString(); } diff --git a/server/src/services/upsSync.ts b/server/src/services/upsSync.ts new file mode 100644 index 0000000..dad10d8 --- /dev/null +++ b/server/src/services/upsSync.ts @@ -0,0 +1,280 @@ +/** + * Keeps what each UPS says up to date: every minute the UPS integrations are read (NUT or SNMP — integrations/ups), the state is stored, and a reading is added to the + * history (every five minutes, and every minute while it runs on battery). The page, the charts, the alerts and the dependency map are built from what is stored, so + * none of them talks to a UPS, and one that can't be reached costs only how fresh they are. + * + * What makes an alert: mains power lost (the UPS runs on battery), a nearly empty battery, a battery to be replaced, and a load near its capacity. While a UPS is on + * battery it counts as *down* in the dependency map, so the servers that go offline with it are folded under its alert instead of each being announced. + */ +import { and, desc, eq, gte, lt } from "drizzle-orm"; +import { db } from "../db/client.js"; +import { integrations, upsReadings, upsState } from "../db/schema.js"; +import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; +import { createUpsAdapter } from "../integrations/ups/adapter.js"; +import type { UpsReading } from "../integrations/ups/types.js"; +import { getInternalFlag, setInternalFlag } from "./settingsStore.js"; + +export const SYNC_INTERVAL_MS = 60_000; +/** After this long without a good read, what is stored is no longer believed: alerts for it are held rather than judged. */ +export const STALE_AFTER_MS = 5 * 60_000; +export const READING_KEEP_DAYS = 35; +const READING_GAP_MS = 5 * 60_000 - 20_000; +/** A load this high (percent of capacity) is a warning. */ +export const OVERLOAD_PERCENT = 90; +const STATUS_FLAG = "upsSync"; + +export interface UpsSyncStatus { + /** The last read that worked (kept when a later one failed). */ + at: string; + ok: boolean; + error: string | null; +} + +async function readStatuses(): Promise> { + try { + const raw = await getInternalFlag(STATUS_FLAG); + return raw ? (JSON.parse(raw) as Record) : {}; + } catch { + return {}; + } +} + +export async function upsSyncStatuses(): Promise> { + return Object.fromEntries(Object.entries(await readStatuses()).map(([k, v]) => [Number(k), v])); +} + +export function isUpsFresh(status: UpsSyncStatus | undefined, nowMs: number): boolean { + return !!status && status.ok && nowMs - Date.parse(status.at) <= STALE_AFTER_MS; +} + +export type UpsStateRow = typeof upsState.$inferSelect; + +/** Writes down one read: the state (with when mains power was lost, kept until it is back) and, when it is time, a point in the history. */ +export async function storeReading(integrationId: number, r: UpsReading, now: Date = new Date()): Promise { + const nowIso = now.toISOString(); + const [before] = await db.select().from(upsState).where(eq(upsState.integrationId, integrationId)).limit(1); + const onBatterySince = r.onBattery ? (before?.onBattery && before.onBatterySince ? before.onBatterySince : nowIso) : null; + const values = { + model: r.model, + manufacturer: r.manufacturer, + statusText: r.statusText, + onBattery: r.onBattery, + lowBattery: r.lowBattery, + replaceBattery: r.replaceBattery, + overload: r.overload, + charge: r.charge, + runtimeSeconds: r.runtimeSeconds, + loadPercent: r.loadPercent, + inputVoltage: r.inputVoltage, + outputVoltage: r.outputVoltage, + onBatterySince, + updatedAt: nowIso, + }; + await db.insert(upsState).values({ integrationId, ...values }).onConflictDoUpdate({ target: upsState.integrationId, set: values }); + + // Every minute while on battery (that is when it matters), and when it changes; otherwise every five. + const [newest] = await db.select({ at: upsReadings.at }).from(upsReadings).where(eq(upsReadings.integrationId, integrationId)).orderBy(desc(upsReadings.at)).limit(1); + const changed = !before || before.onBattery !== r.onBattery; + if (changed || r.onBattery || !newest || now.getTime() - Date.parse(newest.at) >= READING_GAP_MS) { + await db.insert(upsReadings).values({ integrationId, at: nowIso, charge: r.charge, runtimeSeconds: r.runtimeSeconds, loadPercent: r.loadPercent, inputVoltage: r.inputVoltage, onBattery: r.onBattery }); + } + await db.delete(upsReadings).where(and(eq(upsReadings.integrationId, integrationId), lt(upsReadings.at, new Date(now.getTime() - READING_KEEP_DAYS * 86_400_000).toISOString()))); +} + +/** Reads one UPS and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */ +export async function syncUps(integrationId: number, now: Date = new Date(), read?: (config: Record) => Promise): Promise { + let status: UpsSyncStatus; + try { + const loaded = await loadIntegrationConfig(integrationId); + if (!loaded || loaded.integration.type !== "ups") throw new Error("not a UPS integration"); + const reading = await (read ? read(loaded.config) : createUpsAdapter(loaded.config as never).read()); + await storeReading(integrationId, reading, now); + status = { at: now.toISOString(), ok: true, error: null }; + } catch (err) { + const previous = (await readStatuses())[String(integrationId)]; + status = { at: previous?.at ?? now.toISOString(), ok: false, error: err instanceof Error ? err.message : String(err) }; + console.error(`[ups] couldn't read integration ${integrationId}:`, status.error); + } + try { + const all = await readStatuses(); + all[String(integrationId)] = status; + await setInternalFlag(STATUS_FLAG, JSON.stringify(all)); + } catch (err) { + console.error("[ups] couldn't record the result:", err); + } + return status; +} + +export async function syncAllUps(now: Date = new Date()): Promise> { + const rows = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "ups"), eq(integrations.enabled, true))); + const out: Record = {}; + for (const r of rows) out[r.id] = await syncUps(r.id, now); + return out; +} + +/** Forgets how a UPS's last read went when it is removed (its state and history go with its row). */ +export async function forgetUps(integrationId: number): Promise { + const all = await readStatuses(); + if (String(integrationId) in all) { + delete all[String(integrationId)]; + await setInternalFlag(STATUS_FLAG, JSON.stringify(all)); + } +} + +/** The ids of the UPSs that are running on battery, as last read and believed: they count as down in the dependency map. */ +export async function upsOnBatteryIds(now: Date = new Date()): Promise { + try { + const rows = await db + .select({ id: upsState.integrationId }) + .from(upsState) + .innerJoin(integrations, eq(integrations.id, upsState.integrationId)) + .where(and(eq(upsState.onBattery, true), eq(integrations.enabled, true), gte(upsState.updatedAt, new Date(now.getTime() - STALE_AFTER_MS).toISOString()))); + return rows.map((r) => r.id); + } catch (err) { + console.error("[ups] couldn't tell which are on battery:", err); + return []; + } +} + +// ─── What is wrong ────────────────────────────────────────────────────────── + +export interface UpsProblem { + key: string; + kind: "battery" | "low" | "replace" | "load"; + severity: "critical" | "warning"; + message: string; +} + +const minutesWords = (seconds: number) => { + const m = Math.max(1, Math.round(seconds / 60)); + return m < 120 ? `${m} min` : `${Math.round(m / 60)} h`; +}; +const since = (iso: string, now: Date) => { + const m = Math.max(0, Math.floor((now.getTime() - Date.parse(iso)) / 60_000)); + return m < 1 ? "less than a minute" : m < 120 ? `${m} min` : `${Math.round(m / 60)} h`; +}; + +/** Pure: what is wrong with one UPS, from what is stored for it. */ +export function upsProblems(id: number, name: string, s: Pick, now: Date): UpsProblem[] { + const out: UpsProblem[] = []; + const left = s.runtimeSeconds !== null ? `${minutesWords(s.runtimeSeconds)} left` : null; + const charge = s.charge !== null ? `${Math.round(s.charge)} %` : null; + if (s.onBattery) { + const detail = [s.onBatterySince ? `for ${since(s.onBatterySince, now)}` : null, left, charge].filter(Boolean).join(", "); + out.push({ key: `ups-battery:${id}`, kind: "battery", severity: "critical", message: `${name}: mains power has failed — running on battery${detail ? ` (${detail})` : ""}` }); + } + if (s.lowBattery) { + out.push({ key: `ups-low:${id}`, kind: "low", severity: "critical", message: `${name}: the battery is nearly empty${[charge, left].filter(Boolean).length ? ` (${[charge, left].filter(Boolean).join(", ")})` : ""} — shut down what it carries` }); + } + if (s.replaceBattery) out.push({ key: `ups-replace:${id}`, kind: "replace", severity: "warning", message: `${name}: the UPS asks for its battery to be replaced` }); + if (s.overload || (s.loadPercent !== null && s.loadPercent >= OVERLOAD_PERCENT)) { + out.push({ key: `ups-load:${id}`, kind: "load", severity: "warning", message: `${name} is carrying ${s.loadPercent !== null ? `${Math.round(s.loadPercent)} % of` : "more than"} what it can` }); + } + return out; +} + +// ─── What is on it, and in what order to shut it down ─────────────────────── + +/** + * Pure: everything that needs `key` (directly or through others), in the order to shut it down — what nothing else needs first, then what that needed, and so on, so + * nothing is switched off while something that depends on it is still running. Each comes with its step (1 = first). `looped` is set if the order could not be settled + * because some of them need each other. + */ +export function shutdownOrder(edges: Map, key: string): { order: { key: string; step: number }[]; looped: boolean } { + const reverse = new Map(); + for (const [from, tos] of edges) for (const to of tos) reverse.set(to, [...(reverse.get(to) ?? []), from]); + const set = new Set(); + const queue = [key]; + while (queue.length > 0) { + for (const d of reverse.get(queue.shift()!) ?? []) { + if (d === key || set.has(d)) continue; + set.add(d); + queue.push(d); + } + } + // A node's step is one more than the latest step of anything in the set that needs it. + const step = new Map(); + let looped = false; + const visiting = new Set(); + const stepOf = (n: string): number => { + if (step.has(n)) return step.get(n)!; + if (visiting.has(n)) { + looped = true; + return 1; + } + visiting.add(n); + const above = (reverse.get(n) ?? []).filter((d) => set.has(d)); + const s = above.length === 0 ? 1 : 1 + Math.max(...above.map(stepOf)); + visiting.delete(n); + step.set(n, s); + return s; + }; + for (const n of set) stepOf(n); + return { order: [...set].map((k) => ({ key: k, step: step.get(k) ?? 1 })).sort((a, b) => a.step - b.step || a.key.localeCompare(b.key)), looped }; +} + +// ─── History ──────────────────────────────────────────────────────────────── + +export interface UpsPoint { + /** ISO. */ + t: string; + charge: number | null; + runtimeSeconds: number | null; + loadPercent: number | null; + inputVoltage: number | null; + /** It was on battery at some time in this stretch. */ + onBattery: boolean; +} + +type ReadingRow = { at: string; charge: number | null; runtimeSeconds: number | null; loadPercent: number | null; inputVoltage: number | null; onBattery: boolean }; + +/** Pure: readings into at most `maxPoints` equal slices of [from, to] (each the average of what it holds), and the stretches spent on battery. */ +export function bucketUps(rows: ReadingRow[], from: number, to: number, maxPoints: number): { points: UpsPoint[]; onBatteryPeriods: { from: string; to: string; ongoing: boolean }[] } { + const size = Math.max((to - from) / maxPoints, 1); + const buckets = new Map; onBattery: boolean }>(); + for (const r of rows) { + const t = Date.parse(r.at); + if (t < from || t > to) continue; + const key = Math.min(maxPoints - 1, Math.floor((t - from) / size)); + const b = buckets.get(key) ?? { t: 0, n: 0, sums: { charge: { sum: 0, n: 0 }, runtimeSeconds: { sum: 0, n: 0 }, loadPercent: { sum: 0, n: 0 }, inputVoltage: { sum: 0, n: 0 } }, onBattery: false }; + b.t += t; + b.n += 1; + b.onBattery ||= r.onBattery; + for (const k of ["charge", "runtimeSeconds", "loadPercent", "inputVoltage"] as const) { + const v = r[k]; + if (v !== null) { + b.sums[k].sum += v; + b.sums[k].n += 1; + } + } + buckets.set(key, b); + } + const avg = (x: { sum: number; n: number }) => (x.n === 0 ? null : Math.round((x.sum / x.n) * 10) / 10); + const points = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([, b]) => ({ t: new Date(b.t / b.n).toISOString(), charge: avg(b.sums.charge), runtimeSeconds: avg(b.sums.runtimeSeconds), loadPercent: avg(b.sums.loadPercent), inputVoltage: avg(b.sums.inputVoltage), onBattery: b.onBattery })); + // A stretch on battery runs from the first reading that says so to the first that says it is back. + const periods: { from: string; to: string; ongoing: boolean }[] = []; + let start: string | null = null; + let last: string | null = null; + for (const r of [...rows].sort((a, b) => a.at.localeCompare(b.at))) { + if (r.onBattery) { + start ??= r.at; + last = r.at; + } else if (start !== null) { + periods.push({ from: start, to: r.at, ongoing: false }); + start = null; + } + } + // One still going has no end yet: it runs to the last reading that says it is on battery, and says so. + if (start !== null && last !== null) periods.push({ from: start, to: last, ongoing: true }); + return { points, onBatteryPeriods: periods }; +} + +let timer: ReturnType | null = null; + +export function initUpsSync(): void { + if (timer) return; + const pass = () => void syncAllUps().catch((err) => console.error("[ups] pass failed:", err)); + timer = setInterval(pass, SYNC_INTERVAL_MS); + setTimeout(pass, 9_000); + console.log(`[ups] reading UPSs every ${SYNC_INTERVAL_MS / 1000} seconds`); +} diff --git a/server/test/ups.test.ts b/server/test/ups.test.ts new file mode 100644 index 0000000..ee34083 --- /dev/null +++ b/server/test/ups.test.ts @@ -0,0 +1,539 @@ +/** + * A UPS: what NUT and SNMP say and how it is read, what is stored and when a history point is added, what is wrong with it, the order to shut down what it carries, + * its place in the dependency map (down while on battery, so what goes offline with it is folded under its alert), and the page's and /metrics' view of it. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import dgram from "node:dgram"; +import net from "node:net"; +import { createServer as createHttpServer, type Server } from "node:http"; +import { mkdtempSync, rmSync } from "node:fs"; +import { networkInterfaces, tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AddressInfo } from "node:net"; + +const dir = mkdtempSync(join(tmpdir(), "hm-ups-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); +process.env.HEALTH_STARTUP_GRACE_MS = "0"; + +const express = (await import("express")).default; +const { db } = await import("../src/db/client.js"); +const { users, servers, integrations, dependencies, upsState, upsReadings } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const nut = await import("../src/integrations/ups/nut.js"); +const snmp = await import("../src/integrations/ups/snmp.js"); +const { createUpsAdapter, portOf } = await import("../src/integrations/ups/adapter.js"); +const ups = await import("../src/services/upsSync.js"); +const { evaluateHealth, collectSnapshot } = await import("../src/services/healthMonitor.js"); +const { subjectOfConditionKey } = await import("../src/services/maintenance.js"); +const deps = await import("../src/services/dependencies.js"); +const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); +const { upsRouter } = await import("../src/routes/ups.js"); +const { buildMetrics } = await import("../src/services/metrics.js"); +const { setInternalFlag } = await import("../src/services/settingsStore.js"); +const { eq } = await import("drizzle-orm"); + +await runMigrations(); + +/** An address of this machine that isn't loopback (UPS addresses are checked like the endpoint checks'), if it has one. */ +function lanAddress(): string | null { + for (const list of Object.values(networkInterfaces())) { + for (const i of list ?? []) if (i.family === "IPv4" && !i.internal && !i.address.startsWith("169.254.")) return i.address; + } + return null; +} +const LAN = lanAddress(); + +const NOW = new Date("2026-10-20T12:00:00Z"); +const MIN = 60_000; +const at = (min: number) => new Date(NOW.getTime() - min * MIN).toISOString(); + +const VARS = { + "device.mfr": "APC", + "device.model": "Smart-UPS 1500", + "ups.status": "OL CHRG", + "battery.charge": "97", + "battery.runtime": "2040", + "ups.load": "34", + "input.voltage": "231.4", + "output.voltage": "230.0", +}; + +describe("what NUT says", () => { + const text = `BEGIN LIST VAR ups\r\n${Object.entries(VARS).map(([k, v]) => `VAR ups ${k} "${v}"`).join("\r\n")}\r\nVAR ups ups.firmware "a \\"quoted\\" word"\r\nEND LIST VAR ups\r\n`; + + test("the variables, with their quotes", () => { + const vars = nut.parseNutVars(text); + assert.equal(vars["battery.charge"], "97"); + assert.equal(vars["ups.firmware"], 'a "quoted" word'); + assert.deepEqual(nut.parseNutVars("ERR UNKNOWN-UPS\n"), {}); + }); + + test("the names of the UPSs it knows", () => { + assert.deepEqual(nut.parseNutUpsNames('BEGIN LIST UPS\nUPS rack "In the rack"\nUPS desk "Under the desk"\nEND LIST UPS\n'), ["rack", "desk"]); + }); + + test("online, on battery, low, to be replaced and overloaded", () => { + const r = nut.interpretNut(nut.parseNutVars(text)); + assert.deepEqual([r.model, r.manufacturer, r.onBattery, r.lowBattery, r.charge, r.runtimeSeconds, r.loadPercent, r.inputVoltage, r.outputVoltage], ["Smart-UPS 1500", "APC", false, false, 97, 2040, 34, 231.4, 230]); + const flags = (s: string) => nut.interpretNut({ "ups.status": s }); + assert.deepEqual([flags("OB DISCHRG").onBattery, flags("OB DISCHRG").lowBattery], [true, false]); + assert.deepEqual([flags("OB DISCHRG LB").onBattery, flags("OB DISCHRG LB").lowBattery], [true, true]); + assert.equal(flags("OL RB").replaceBattery, true); + assert.equal(flags("OL OVER").overload, true); + const empty = nut.interpretNut({}); + assert.deepEqual([empty.statusText, empty.charge, empty.model, empty.onBattery], ["unknown", null, null, false]); + }); +}); + +describe("asking a NUT server", { skip: LAN === null && "this machine has no address other than loopback" }, () => { + let server: net.Server; + let port = 0; + const seen: string[] = []; + + before(async () => { + server = net.createServer((socket) => { + let buf = ""; + socket.on("error", () => {}); + socket.on("data", (d) => { + buf += d.toString(); + let i; + while ((i = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, i).trim(); + buf = buf.slice(i + 1); + seen.push(line); + if (line === "LIST UPS") socket.write('BEGIN LIST UPS\nUPS rack "The rack"\nEND LIST UPS\n'); + else if (line === "LIST VAR rack") socket.write(`BEGIN LIST VAR rack\n${Object.entries(VARS).map(([k, v]) => `VAR rack ${k} "${v}"`).join("\n")}\nEND LIST VAR rack\n`); + else if (line.startsWith("LIST VAR")) socket.write("ERR UNKNOWN-UPS\n"); + else if (line === "LOGOUT") socket.end("OK Goodbye\n"); + } + }); + }); + await new Promise((r) => server.listen(0, "0.0.0.0", r)); + port = (server.address() as AddressInfo).port; + }); + after(() => server.close()); + + test("it reads the named UPS, or the first one listed when none is named", async () => { + const named = await nut.readNut(LAN!, port, "rack"); + assert.deepEqual([named.model, named.charge, named.onBattery], ["Smart-UPS 1500", 97, false]); + seen.length = 0; + const first = await nut.readNut(LAN!, port, null); + assert.equal(first.manufacturer, "APC"); + assert.deepEqual(seen.filter((l) => l !== "LOGOUT").slice(0, 2), ["LIST UPS", "LIST VAR rack"]); + }); + + test("an unknown UPS, a closed port and an address it won't ask say so", async () => { + await assert.rejects(nut.readNut(LAN!, port, "nope"), /upsd says UNKNOWN-UPS/); + await assert.rejects(nut.readNut(LAN!, 1, "rack"), /nothing is listening on port 1/); + await assert.rejects(nut.readNut("127.0.0.1", port, "rack")); + }); + + test("the adapter takes its port from the config, or the protocol's own, and pings", async () => { + assert.deepEqual([portOf({ host: "x" }), portOf({ host: "x", snmp: true }), portOf({ host: "x", snmp: "true", port: "1161" }), portOf({ host: "x", port: "bad" })], [3493, 161, 1161, 3493]); + const ok = await createUpsAdapter({ host: LAN!, port: String(port), upsName: "rack" }).ping(); + assert.equal(ok.ok, true); + const bad = await createUpsAdapter({ host: LAN!, port: String(port), upsName: "nope" }).ping(); + assert.deepEqual([bad.ok, /UNKNOWN-UPS/.test(bad.error ?? "")], [false, true]); + }); +}); + +// ─── SNMP, with a small agent of the test's own ───────────────────────────── + +/** Just enough BER to answer a GET: the test's own encoder, so what is checked is not the code's. */ +const len = (n: number) => (n < 128 ? [n] : [0x81, n]); +const t = (tag: number, body: number[]) => [tag, ...len(body.length), ...body]; +const int = (n: number) => t(0x02, [n >> 24 & 0xff, n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff]); +const oidBytes = (oid: string) => { + const p = oid.split(".").map(Number); + const out = [p[0] * 40 + p[1]]; + for (const n of p.slice(2)) out.push(...(n < 128 ? [n] : [(n >> 7) | 0x80, n & 0x7f])); + return t(0x06, out); +}; +/** The request id and the objects asked for, read straight from the bytes. */ +function readRequest(buf: Buffer): { id: number; community: string; oids: string[] } { + let i = 2; // 30 len + if (buf[1] & 0x80) i = 2 + (buf[1] & 0x7f); + const tlv = () => { + const tag = buf[i++]; + let l = buf[i++]; + if (l & 0x80) { + const n = l & 0x7f; + l = 0; + for (let k = 0; k < n; k++) l = l * 256 + buf[i++]; + } + const start = i; + i += l; + return { tag, start, end: i }; + }; + tlv(); // version + const com = tlv(); + const community = buf.subarray(com.start, com.end).toString(); + const pdu = tlv(); + i = pdu.start; + const rid = tlv(); + let id = 0; + for (let k = rid.start; k < rid.end; k++) id = id * 256 + buf[k]; + tlv(); + tlv(); + const list = tlv(); + i = list.start; + const oids: string[] = []; + while (i < list.end) { + const vb = tlv(); + const save = i; + i = vb.start; + const o = tlv(); + const bytes = buf.subarray(o.start, o.end); + const parts = [Math.floor(bytes[0] / 40), bytes[0] % 40]; + let v = 0; + for (const b of bytes.subarray(1)) { + v = v * 128 + (b & 0x7f); + if (!(b & 0x80)) { + parts.push(v); + v = 0; + } + } + oids.push(parts.join(".")); + i = save; + } + return { id, community, oids }; +} + +describe("what SNMP says", () => { + test("an object id is written as the standard says", () => { + assert.deepEqual([...snmp.encodeOid("1.3.6.1.2.1.33.1.2.4.0")], [0x06, 0x0a, 0x2b, 0x06, 0x01, 0x02, 0x01, 0x21, 0x01, 0x02, 0x04, 0x00]); + assert.deepEqual([...snmp.encodeOid("1.3.6.1.4.1.318.1")], [0x06, 0x08, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x3e, 0x01], "318 takes two bytes"); + }); + + test("a request names the community, an id and the objects", () => { + const req = snmp.buildGet("public", 123456, [snmp.OIDS.chargeRemaining, snmp.OIDS.outputSource]); + assert.equal(req[0], 0x30); + assert.deepEqual(readRequest(req), { id: 123456, community: "public", oids: [snmp.OIDS.chargeRemaining, snmp.OIDS.outputSource] }); + }); + + /** An answer as an agent would write it. */ + const answer = (id: number, binds: [string, number[]][]) => Buffer.from(t(0x30, [...int(1), ...t(0x04, [...Buffer.from("public")]), ...t(0xa2, [...int(id), ...int(0), ...int(0), ...t(0x30, binds.flatMap(([o, v]) => t(0x30, [...oidBytes(o), ...v])))])])); + + test("an answer's numbers, text, counters and objects the device doesn't have", () => { + const parsed = snmp.parseResponse( + answer(77, [ + [snmp.OIDS.chargeRemaining, int(87)], + [snmp.OIDS.model, t(0x04, [...Buffer.from("Back-UPS ES 700")])], + [snmp.OIDS.secondsOnBattery, t(0x42, [0x01, 0x2c])], + [snmp.OIDS.outputLoad, t(0x80, [])], + [snmp.OIDS.inputVoltage, int(-5)], + ]), + ); + assert.deepEqual([parsed.requestId, parsed.errorStatus], [77, 0]); + assert.deepEqual([parsed.values.get(snmp.OIDS.chargeRemaining), parsed.values.get(snmp.OIDS.model), parsed.values.get(snmp.OIDS.secondsOnBattery), parsed.values.get(snmp.OIDS.outputLoad), parsed.values.get(snmp.OIDS.inputVoltage)], [87, "Back-UPS ES 700", 300, null, -5]); + assert.throws(() => snmp.parseResponse(Buffer.from([0x30, 0x03, 0x02, 0x01])), /cut short|isn't/); + assert.throws(() => snmp.parseResponse(Buffer.from("not snmp at all"))); + }); + + test("the UPS-MIB: on mains, on battery, low", () => { + const m = (entries: [string, number | string | null][]) => new Map(entries); + const mains = snmp.interpretSnmp(m([[snmp.OIDS.outputSource, 3], [snmp.OIDS.batteryStatus, 2], [snmp.OIDS.chargeRemaining, 100], [snmp.OIDS.minutesRemaining, 42], [snmp.OIDS.outputLoad, 18], [snmp.OIDS.model, "SMX1500"], [snmp.OIDS.manufacturer, "APC"]])); + assert.deepEqual([mains.onBattery, mains.lowBattery, mains.charge, mains.runtimeSeconds, mains.loadPercent, mains.model, mains.statusText], [false, false, 100, 2520, 18, "SMX1500", "normal, battery normal"]); + const out = snmp.interpretSnmp(m([[snmp.OIDS.outputSource, 5], [snmp.OIDS.batteryStatus, 3]])); + assert.deepEqual([out.onBattery, out.lowBattery, out.statusText], [true, true, "on battery, battery low"]); + assert.equal(snmp.interpretSnmp(m([[snmp.OIDS.secondsOnBattery, 90]])).onBattery, true, "no output source, but seconds on battery"); + assert.equal(snmp.interpretSnmp(m([])).statusText, "unknown"); + }); + + describe("asking an agent", { skip: LAN === null && "this machine has no address other than loopback" }, () => { + let agent: dgram.Socket; + let port = 0; + let community = "public"; + let silent = false; + let values: [string, number[]][] = []; + + before(async () => { + agent = dgram.createSocket("udp4"); + agent.on("message", (msg, rinfo) => { + if (silent) return; + const req = readRequest(msg); + if (req.community !== community) return; // a wrong community gets no answer + const binds = req.oids.map((o) => [o, values.find(([k]) => k === o)?.[1] ?? t(0x80, [])] as [string, number[]]); + agent.send(answer(req.id, binds), rinfo.port, rinfo.address); + }); + await new Promise((r) => agent.bind(0, "0.0.0.0", r)); + port = agent.address().port; + }); + after(() => agent.close()); + + test("it reads the UPS", async () => { + values = [[snmp.OIDS.outputSource, int(5)], [snmp.OIDS.batteryStatus, int(2)], [snmp.OIDS.chargeRemaining, int(64)], [snmp.OIDS.minutesRemaining, int(18)], [snmp.OIDS.model, t(0x04, [...Buffer.from("Eaton 5P")])]]; + const r = await snmp.readSnmp(LAN!, port, "public"); + assert.deepEqual([r.onBattery, r.charge, r.runtimeSeconds, r.model], [true, 64, 1080, "Eaton 5P"]); + const viaAdapter = await createUpsAdapter({ host: LAN!, snmp: true, port: String(port) }).read(); + assert.equal(viaAdapter.charge, 64, "the adapter reads over SNMP when asked, with the community public when none is given"); + }); + + test("a device with none of the UPS objects is said not to be a UPS", async () => { + values = []; + await assert.rejects(snmp.readSnmp(LAN!, port, "public"), /none of the standard UPS objects/); + }); + }); + + test("an address it won't ask is refused before anything is sent", async () => { + await assert.rejects(snmp.readSnmp("127.0.0.1", 161, "public")); + }); +}); + +// ─── Stored, judged and drawn ─────────────────────────────────────────────── + +describe("what is stored", () => { + let id = 0; + const reading = (extra: Partial = {}) => ({ model: "SMX", manufacturer: "APC", statusText: "OL", onBattery: false, lowBattery: false, replaceBattery: false, overload: false, charge: 100, runtimeSeconds: 1800, loadPercent: 30, inputVoltage: 230, outputVoltage: 230, ...extra }); + + before(async () => { + id = (await db.insert(integrations).values({ type: "ups", name: "Rack UPS", baseUrl: "", config: JSON.stringify({ host: "nut.lan" }) }).returning({ id: integrations.id }))[0].id; + }); + + test("the state is replaced at each read, and when mains power was lost is kept until it is back", async () => { + await ups.storeReading(id, reading(), new Date(NOW.getTime() - 30 * MIN)); + let [s] = await db.select().from(upsState).where(eq(upsState.integrationId, id)); + assert.deepEqual([s.onBattery, s.onBatterySince, s.charge], [false, null, 100]); + await ups.storeReading(id, reading({ onBattery: true, statusText: "OB DISCHRG", charge: 95 }), new Date(NOW.getTime() - 10 * MIN)); + await ups.storeReading(id, reading({ onBattery: true, statusText: "OB DISCHRG", charge: 80 }), new Date(NOW.getTime() - 5 * MIN)); + [s] = await db.select().from(upsState).where(eq(upsState.integrationId, id)); + assert.deepEqual([s.onBattery, s.onBatterySince, s.charge, s.statusText], [true, at(10), 80, "OB DISCHRG"]); + await ups.storeReading(id, reading({ charge: 82 }), NOW); + [s] = await db.select().from(upsState).where(eq(upsState.integrationId, id)); + assert.deepEqual([s.onBattery, s.onBatterySince], [false, null]); + }); + + test("a point is added to the history every five minutes, every minute on battery, and when it changes", async () => { + const rows = await db.select().from(upsReadings).where(eq(upsReadings.integrationId, id)).orderBy(upsReadings.at); + // 30 min ago (first), 10 and 5 min ago (on battery), now (back on mains: a change) + assert.deepEqual(rows.map((r) => r.at), [at(30), at(10), at(5), NOW.toISOString()]); + await ups.storeReading(id, reading(), new Date(NOW.getTime() + 1 * MIN)); + await ups.storeReading(id, reading(), new Date(NOW.getTime() + 3 * MIN)); + assert.equal((await db.select().from(upsReadings).where(eq(upsReadings.integrationId, id))).length, 4, "mains, a minute and three minutes later: nothing new"); + await ups.storeReading(id, reading(), new Date(NOW.getTime() + 6 * MIN)); + assert.equal((await db.select().from(upsReadings).where(eq(upsReadings.integrationId, id))).length, 5); + }); + + test("history older than 35 days is dropped", async () => { + await db.insert(upsReadings).values({ integrationId: id, at: new Date(NOW.getTime() - 40 * 86_400_000).toISOString(), charge: 100, onBattery: false }); + await ups.storeReading(id, reading(), new Date(NOW.getTime() + 12 * MIN)); + assert.equal((await db.select().from(upsReadings).where(eq(upsReadings.integrationId, id))).every((r) => Date.parse(r.at) > NOW.getTime() - 36 * 86_400_000), true); + }); + + test("a read that fails is said so, and keeps when the last good one was", async () => { + const ok = await ups.syncUps(id, new Date(NOW.getTime() + 20 * MIN), async () => reading({ charge: 99 })); + assert.deepEqual([ok.ok, ok.at], [true, new Date(NOW.getTime() + 20 * MIN).toISOString()]); + const failed = await ups.syncUps(id, new Date(NOW.getTime() + 25 * MIN), async () => { + throw new Error("no answer within 5 s"); + }); + assert.deepEqual([failed.ok, failed.error, failed.at], [false, "no answer within 5 s", ok.at]); + const statuses = await ups.upsSyncStatuses(); + assert.equal(statuses[id].ok, false); + assert.equal(ups.isUpsFresh(ok, Date.parse(ok.at) + 4 * MIN), true); + assert.equal(ups.isUpsFresh(ok, Date.parse(ok.at) + 6 * MIN), false, "after five minutes it is no longer believed"); + assert.equal(ups.isUpsFresh(failed, Date.parse(ok.at)), false, "and a failed read is never fresh"); + const wrong = await ups.syncUps(999999, NOW, async () => reading()); + assert.equal(wrong.ok, false); + }); + + test("the history is bucketed into averages and the stretches on battery are found", () => { + const rows = [ + { at: at(60), charge: 100, runtimeSeconds: 1800, loadPercent: 30, inputVoltage: 230, onBattery: false }, + { at: at(50), charge: 100, runtimeSeconds: 1800, loadPercent: 40, inputVoltage: 230, onBattery: false }, + { at: at(40), charge: 90, runtimeSeconds: 1200, loadPercent: 35, inputVoltage: 0, onBattery: true }, + { at: at(35), charge: 70, runtimeSeconds: 800, loadPercent: 35, inputVoltage: 0, onBattery: true }, + { at: at(30), charge: 70, runtimeSeconds: 800, loadPercent: 35, inputVoltage: 231, onBattery: false }, + { at: at(5), charge: 98, runtimeSeconds: null, loadPercent: null, inputVoltage: 231, onBattery: true }, + ]; + const r = ups.bucketUps(rows, NOW.getTime() - 61 * MIN, NOW.getTime(), 2); + assert.equal(r.points.length, 2); + assert.deepEqual([r.points[0].loadPercent, r.points[0].onBattery, r.points[1].onBattery], [35, true, true]); + assert.deepEqual(r.onBatteryPeriods, [{ from: at(40), to: at(30), ongoing: false }, { from: at(5), to: at(5), ongoing: true }], "one that ended, and one still going"); + assert.deepEqual(ups.bucketUps([], 0, 10, 5), { points: [], onBatteryPeriods: [] }); + }); +}); + +describe("what is wrong", () => { + const base = { onBattery: false, lowBattery: false, replaceBattery: false, overload: false, charge: 100, runtimeSeconds: 1800, loadPercent: 30, onBatterySince: null as string | null }; + const keys = (s: Partial) => ups.upsProblems(7, "Rack UPS", { ...base, ...s }, NOW).map((p) => p.key); + + test("nothing is wrong with a UPS on mains", () => { + assert.deepEqual(keys({}), []); + }); + + test("mains power lost says for how long, how much is left and how full the battery is", () => { + const [p] = ups.upsProblems(7, "Rack UPS", { ...base, onBattery: true, onBatterySince: at(4), charge: 84, runtimeSeconds: 1380 }, NOW); + assert.deepEqual([p.key, p.severity, p.kind], ["ups-battery:7", "critical", "battery"]); + assert.equal(p.message, "Rack UPS: mains power has failed — running on battery (for 4 min, 23 min left, 84 %)"); + assert.match(ups.upsProblems(7, "U", { ...base, onBattery: true, charge: null, runtimeSeconds: null }, NOW)[0].message, /^U: mains power has failed — running on battery$/, "with nothing more to say it says no more"); + }); + + test("a nearly empty battery, one to be replaced, and a load near the limit are each their own", () => { + assert.deepEqual(keys({ onBattery: true, lowBattery: true }), ["ups-battery:7", "ups-low:7"]); + assert.deepEqual(keys({ replaceBattery: true }), ["ups-replace:7"]); + assert.deepEqual(keys({ loadPercent: 89 }), []); + assert.deepEqual(keys({ loadPercent: 90 }), ["ups-load:7"]); + assert.deepEqual(keys({ overload: true, loadPercent: null }), ["ups-load:7"]); + assert.equal(ups.upsProblems(7, "R", { ...base, replaceBattery: true }, NOW)[0].severity, "warning"); + }); +}); + +describe("what it carries", () => { + test("what nothing else needs is shut down first, then what that needed, so nothing goes while something still depends on it", () => { + // guest → host → ups; nas → ups; app → guest, nas + const edges = new Map([ + ["server:host", ["integration:1"]], + ["server:nas", ["integration:1"]], + ["server:guest", ["server:host"]], + ["server:app", ["server:guest", "server:nas"]], + ["server:other", ["integration:2"]], + ]); + const { order, looped } = ups.shutdownOrder(edges, "integration:1"); + assert.equal(looped, false); + assert.deepEqual(order.map((o) => [o.key, o.step]), [["server:app", 1], ["server:guest", 2], ["server:nas", 2], ["server:host", 3]]); + assert.deepEqual(ups.shutdownOrder(edges, "integration:2").order, [{ key: "server:other", step: 1 }]); + assert.deepEqual(ups.shutdownOrder(edges, "integration:9"), { order: [], looped: false }); + }); + + test("things that need each other don't hang it", () => { + const edges = new Map([["server:a", ["integration:1", "server:b"]], ["server:b", ["server:a"]]]); + const r = ups.shutdownOrder(edges, "integration:1"); + assert.equal(r.looped, true); + assert.equal(r.order.length, 2); + }); +}); + +describe("in the map, in alerts, in the health pass and on the page", () => { + let upsId = 0; + let hostId = 0; + let guestId = 0; + let aloneId = 0; + let app: Server; + let base = ""; + const state = (extra: Partial = {}) => ({ integrationId: upsId, model: "SMX", manufacturer: "APC", statusText: "OB DISCHRG", onBattery: true, lowBattery: false, replaceBattery: false, overload: false, charge: 71, runtimeSeconds: 1500, loadPercent: 44, inputVoltage: 0, outputVoltage: 230, onBatterySince: at(6), updatedAt: new Date().toISOString(), ...extra }); + + before(async () => { + await db.insert(users).values([{ oidcSub: "viewer", name: "Vic", role: "viewer" }]); + upsId = (await db.insert(integrations).values({ type: "ups", name: "Cupboard UPS", baseUrl: "", config: JSON.stringify({ host: "nut.lan" }) }).returning({ id: integrations.id }))[0].id; + const gone = new Date(Date.now() - 3 * 3_600_000).toISOString(); + const mk = async (name: string, lastSeenAt: string) => (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: name, lastSeenAt }).returning({ id: servers.id }))[0].id; + hostId = await mk("pve", gone); + guestId = await mk("wiki", gone); + aloneId = await mk("printer", gone); + await db.insert(dependencies).values([ + { fromType: "server", fromId: hostId, toType: "integration", toId: upsId }, + { fromType: "server", fromId: guestId, toType: "server", toId: hostId }, + ]); + await db.insert(upsState).values(state()); + await setInternalFlag("upsSync", JSON.stringify({ [upsId]: { at: new Date().toISOString(), ok: true, error: null } })); + + const a = express(); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub: "viewer" } }; + next(); + }); + a.use("/api/ups", upsRouter); + app = await new Promise((resolve) => { + const s = a.listen(0, "127.0.0.1", () => resolve(s)); + }); + base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/ups`; + }); + after(() => { + app.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + test("a UPS on battery is down, so the servers that go offline with it are folded under it", async () => { + assert.deepEqual(await ups.upsOnBatteryIds(), [upsId]); + const cover = await deps.dependencyCover([hostId, guestId, aloneId], []); + assert.equal(cover.cause.get(`server:${hostId}`), `integration:${upsId}`); + assert.equal(cover.cause.get(`server:${guestId}`), `integration:${upsId}`, "through the host it runs on"); + assert.equal(cover.cause.has(`server:${aloneId}`), false, "one that doesn't need it stands alone"); + assert.deepEqual((cover.taken.get(`integration:${upsId}`) ?? []).sort(), ["pve", "wiki"]); + assert.equal(deps.alertIdOfNode(`integration:${upsId}`, cover.graph), `monitoring:ups-battery:${upsId}`); + // Back on mains, it stops explaining anything. + await db.update(upsState).set({ onBattery: false }).where(eq(upsState.integrationId, upsId)); + assert.deepEqual(await ups.upsOnBatteryIds(), []); + assert.equal((await deps.dependencyCover([hostId], [])).cause.size, 0); + // And a reading that is no longer believed doesn't either. + await db.update(upsState).set({ onBattery: true, updatedAt: at(30) }).where(eq(upsState.integrationId, upsId)); + assert.deepEqual(await ups.upsOnBatteryIds(), []); + await db.update(upsState).set({ updatedAt: new Date().toISOString() }).where(eq(upsState.integrationId, upsId)); + }); + + test("the health pass judges it from what is stored, and holds it when the last read is old", async () => { + let { snapshot, held } = await collectSnapshot(); + assert.deepEqual(snapshot.ups?.map((u) => u.integrationName), ["Cupboard UPS"]); + assert.equal(held.has(`ups:${upsId}`), false); + const list = evaluateHealth(snapshot, { serverOfflineMinutes: 60, diskUsagePercent: 90 }, Date.now(), { skipServers: true }); + const c = list.find((x) => x.key === `ups-battery:${upsId}`)!; + assert.deepEqual([c.severity, c.source], ["critical", `ups:${upsId}`]); + assert.match(c.message, /Cupboard UPS: mains power has failed/); + assert.equal(subjectOfConditionKey(c.key), `integration:${upsId}`, "maintenance on it silences its alerts"); + for (const k of ["ups-low", "ups-replace", "ups-load"]) assert.equal(subjectOfConditionKey(`${k}:${upsId}`), `integration:${upsId}`); + await setInternalFlag("upsSync", JSON.stringify({ [upsId]: { at: at(30), ok: true, error: null } })); + ({ snapshot, held } = await collectSnapshot()); + assert.deepEqual([snapshot.ups ?? [], held.has(`ups:${upsId}`)], [[], true]); + await setInternalFlag("upsSync", JSON.stringify({ [upsId]: { at: new Date().toISOString(), ok: true, error: null } })); + }); + + test("the Alerts page shows it, with what goes down with it, and the offline servers say it is why", async () => { + invalidateAlertsCache(); + const report = await getAlerts(true); + const a = report.alerts.find((x) => x.id === `monitoring:ups-battery:${upsId}`)!; + assert.ok(a, "the alert is there"); + assert.deepEqual([a.severity, a.category, a.source, a.link, a.target?.type, a.target?.id], ["critical", "monitoring", "UPS", "/ups", "integration", upsId]); + assert.deepEqual((a.affects ?? []).sort(), ["pve", "wiki"]); + const host = report.alerts.find((x) => x.id === `offline:offline:server:${hostId}`)!; + assert.deepEqual([host.causedBy?.name, host.causedBy?.alertId, host.silenced], ["Cupboard UPS", `monitoring:ups-battery:${upsId}`, true]); + const alone = report.alerts.find((x) => x.id === `offline:offline:server:${aloneId}`)!; + assert.equal(alone.causedBy, undefined); + }); + + test("the page lists each UPS, how it is, what is on it in shutdown order, and its history", async () => { + const res = await fetch(base, { headers: { connection: "close" } }); + assert.equal(res.status, 200, "everyone signed in can look"); + const body = (await res.json()) as any; + const u = body.ups.find((x: any) => x.id === upsId); + assert.deepEqual([u.name, u.protocol, u.fresh, u.state.onBattery, u.state.charge], ["Cupboard UPS", "nut", true, true, 71]); + assert.deepEqual(u.problems.map((p: any) => p.key), [`ups-battery:${upsId}`]); + assert.deepEqual(u.carries.map((c: any) => [c.name, c.step, c.type]), [["wiki", 1, "server"], ["pve", 2, "server"]]); + assert.equal(JSON.stringify(body).includes("nut.lan"), false, "no address leaves the server"); + const hist = (await (await fetch(`${base}/${upsId}/history?days=1`, { headers: { connection: "close" } })).json()) as any; + assert.equal(hist.ups.name, "Cupboard UPS"); + assert.ok(Array.isArray(hist.points) && Array.isArray(hist.onBatteryPeriods)); + assert.equal((await fetch(`${base}/999/history`, { headers: { connection: "close" } })).status, 404); + assert.equal((await fetch(`${base}/abc/history`, { headers: { connection: "close" } })).status, 400); + }); + + test("/metrics carries it while it is believed, and not after", async () => { + let text = await buildMetrics(); + assert.match(text, /homelab_ups_on_battery\{name="Cupboard UPS"\} 1/); + assert.match(text, /homelab_ups_battery_charge_percent\{name="Cupboard UPS"\} 71/); + assert.match(text, /homelab_ups_runtime_seconds\{name="Cupboard UPS"\} 1500/); + await setInternalFlag("upsSync", JSON.stringify({ [upsId]: { at: at(30), ok: true, error: null } })); + text = await buildMetrics(); + assert.doesNotMatch(text, /homelab_ups_on_battery/); + }); + + test("a UPS is added through the integrations form like any other, with its host the only thing needed", async () => { + const { INTEGRATION_FIELDS, validateIntegrationConfig, splitIntegrationConfig } = await import("../src/integrations/fieldSchemas.js"); + assert.ok(INTEGRATION_FIELDS.ups); + assert.deepEqual(validateIntegrationConfig("ups", {}), ["host"]); + assert.deepEqual(validateIntegrationConfig("ups", { host: "nut.lan" }), []); + const { secretFields, nonSecretFields } = splitIntegrationConfig("ups", { host: "nut.lan", snmp: true, community: "s3cret", upsName: "rack" }); + assert.deepEqual([Object.keys(secretFields), Object.keys(nonSecretFields).sort()], [["community"], ["host", "snmp", "upsName"]]); + }); +}); + +// keep the unused-import checker quiet about the helper servers this file declares for readability +void createHttpServer; diff --git a/web/src/App.tsx b/web/src/App.tsx index 994a67b..3515208 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -10,6 +10,7 @@ import NetworkDevices from "./pages/NetworkDevices"; import ProxyHosts from "./pages/ProxyHosts"; import AlertRules from "./pages/AlertRules"; import HomeAssistant from "./pages/HomeAssistant"; +import Ups from "./pages/Ups"; import MyWorkPage from "./pages/MyWork"; import ApiTokens from "./pages/ApiTokens"; import Todo from "./pages/Todo"; @@ -154,6 +155,7 @@ function Shelled({ user }: { user: CurrentUser }) { } /> } /> } /> + } /> } /> } /> } /> diff --git a/web/src/api/client.ts b/web/src/api/client.ts index de18d47..a570d3e 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -1430,6 +1430,45 @@ export interface HaWatchedEntity { entity: { friendlyName: string | null; state: string; value: number | null; unit: string | null; deviceClass: string | null; lastChanged: string | null; unavailableSince: string | null; updatedAt: string } | null; } +/** One UPS: how it is now, what is wrong, and what is on it in the order to shut it down. */ +export interface UpsInfo { + id: number; + name: string; + enabled: boolean; + protocol: "nut" | "snmp"; + /** How the last read went; `at` is the last one that worked. */ + status: { at: string; ok: boolean; error: string | null } | null; + /** The last good read is recent enough to be believed. */ + fresh: boolean; + state: { + model: string | null; + manufacturer: string | null; + statusText: string; + onBattery: boolean; + lowBattery: boolean; + replaceBattery: boolean; + overload: boolean; + charge: number | null; + runtimeSeconds: number | null; + loadPercent: number | null; + inputVoltage: number | null; + outputVoltage: number | null; + onBatterySince: string | null; + updatedAt: string; + } | null; + problems: { key: string; kind: "battery" | "low" | "replace" | "load"; severity: "critical" | "warning"; message: string }[]; + /** Everything that needs this UPS, directly or through something else; step 1 is shut down first. */ + carries: { key: string; type: "server" | "integration" | "device"; id: number; name: string; step: number }[]; + orderLooped: boolean; +} + +export interface UpsHistory { + ups: { id: number; name: string }; + days: number; + points: { t: string; charge: number | null; runtimeSeconds: number | null; loadPercent: number | null; inputVoltage: number | null; onBattery: boolean }[]; + onBatteryPeriods: { from: string; to: string; ongoing: boolean }[]; +} + export interface HaOverview { integrations: { id: number; name: string; enabled: boolean; status: HaSyncStatus | null; fresh: boolean; watched: HaWatchedEntity[]; problems: IntegrationProblem[] }[]; } @@ -1933,7 +1972,7 @@ export interface ManualTaskInput { enabled?: boolean; } -export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant"; +export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant" | "ups"; export interface IntegrationField { key: string; @@ -2453,6 +2492,10 @@ export const api = { create: (label: string) => request<{ token: MetricsToken; secret: string }>("/api/metrics-tokens", { method: "POST", body: JSON.stringify({ label }) }), remove: (id: number) => request(`/api/metrics-tokens/${id}`, { method: "DELETE" }), }, + ups: { + list: () => request<{ ups: UpsInfo[] }>("/api/ups"), + history: (id: number, days: number) => request(`/api/ups/${id}/history?days=${days}`), + }, eventWebhooks: { list: () => request<{ webhooks: EventWebhook[]; events: WebhookEventName[] }>("/api/event-webhooks"), create: (data: { label: string; url: string; secret?: string; events: WebhookEventName[] }) => request<{ webhook: EventWebhook }>("/api/event-webhooks", { method: "POST", body: JSON.stringify(data) }), diff --git a/web/src/components/CommandPalette.tsx b/web/src/components/CommandPalette.tsx index b1b6af1..ccbb122 100644 --- a/web/src/components/CommandPalette.tsx +++ b/web/src/components/CommandPalette.tsx @@ -46,6 +46,7 @@ const INTEGRATION_TYPE_LABELS: Record = { unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", + ups: "UPS", }; const DNS_PROVIDER_LABELS: Record = { diff --git a/web/src/components/IntegrationEditForm.tsx b/web/src/components/IntegrationEditForm.tsx index 500e49c..2cbfbb3 100644 --- a/web/src/components/IntegrationEditForm.tsx +++ b/web/src/components/IntegrationEditForm.tsx @@ -17,6 +17,7 @@ const TYPE_LABELS: Record = { unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", + ups: "UPS", }; export default function IntegrationEditForm({ diff --git a/web/src/components/IntegrationForm.tsx b/web/src/components/IntegrationForm.tsx index ed8b499..26d7265 100644 --- a/web/src/components/IntegrationForm.tsx +++ b/web/src/components/IntegrationForm.tsx @@ -16,6 +16,7 @@ const TYPE_LABELS: Record = { unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", + ups: "UPS", }; export default function IntegrationForm({ onCreated, onCancel }: { onCreated: () => void; onCancel: () => void }) { diff --git a/web/src/components/WallView.tsx b/web/src/components/WallView.tsx index 6fa2ed3..3cead5e 100644 --- a/web/src/components/WallView.tsx +++ b/web/src/components/WallView.tsx @@ -18,6 +18,7 @@ const TYPE_LABELS: Record = { unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", + ups: "UPS", }; export type WallLevel = "critical" | "warning" | "ok" | "unsure"; diff --git a/web/src/layout/nav.tsx b/web/src/layout/nav.tsx index 0c025f6..cd447af 100644 --- a/web/src/layout/nav.tsx +++ b/web/src/layout/nav.tsx @@ -7,6 +7,7 @@ import { IconRouter, IconArrowsSplit2, IconHome2, + IconBatteryCharging, IconAdjustmentsAlt, IconChecklist, IconListDetails, @@ -116,6 +117,7 @@ export const NAV: NavEntry[] = [ { to: "/heartbeats", label: "Heartbeats", icon: }, { to: "/uptime-kuma", label: "Uptime Kuma", icon: }, { to: "/home-assistant", label: "Home Assistant", icon: }, + { to: "/ups", label: "UPS", icon: }, ], }, { diff --git a/web/src/pages/Integrations.tsx b/web/src/pages/Integrations.tsx index d84d881..9562924 100644 --- a/web/src/pages/Integrations.tsx +++ b/web/src/pages/Integrations.tsx @@ -28,6 +28,7 @@ const TYPE_LABELS: Record = { unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", + ups: "UPS", }; /** The page each kind of integration gets once it is connected. */ @@ -45,6 +46,7 @@ const TYPE_PAGES: Record = { unifi: "/network/devices", npm: "/proxy-hosts", homeassistant: "/home-assistant", + ups: "/ups", }; /** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */ diff --git a/web/src/pages/Ups.tsx b/web/src/pages/Ups.tsx new file mode 100644 index 0000000..428472c --- /dev/null +++ b/web/src/pages/Ups.tsx @@ -0,0 +1,265 @@ +import { useEffect, useMemo, useState } from "react"; +import { Link } from "react-router-dom"; +import { api, type CurrentUser, type UpsHistory, type UpsInfo } from "../api/client"; +import EmptyState from "../components/EmptyState"; +import RangeSelect from "../components/RangeSelect"; +import TimeAgo from "../components/TimeAgo"; +import TimeChart from "../components/TimeChart"; +import { BlockSkeleton } from "../components/Skeleton"; +import { ErrorNotice } from "../components/Notice"; +import { useChartRange } from "../utils/chartRanges"; +import { readableError } from "../utils/errors"; + +const minutes = (seconds: number) => { + const m = Math.max(0, Math.round(seconds / 60)); + return m < 120 ? `${m} min` : `${Math.round(m / 60)} h`; +}; +const lasting = (fromIso: string, toIso: string) => minutes((Date.parse(toIso) - Date.parse(fromIso)) / 1000); + +function Badge({ u }: { u: UpsInfo }) { + const s = u.state; + if (!s) return Not read yet; + if (!u.fresh) return Can’t be read; + if (s.onBattery && s.lowBattery) return On battery — nearly empty; + if (s.onBattery) return On battery; + if (s.lowBattery) return Battery low; + return On mains power; +} + +function Tile({ label, value, sub, bar }: { label: string; value: string; sub?: string; bar?: { percent: number; color: string } }) { + return ( +
+
+
+
{label}
+
{value}
+ {bar && ( + +
+
+ ); +} + +const linkOf = (c: UpsInfo["carries"][number]) => (c.type === "server" ? `/servers/${c.id}` : c.type === "device" ? "/network/devices" : "/integrations"); + +/** Charge, load and mains voltage over time, from what is kept (up to 35 days), with the times mains power was lost. */ +function History({ id, name }: { id: number; name: string }) { + const [days, setDays] = useChartRange(7); + const shown = Math.min(days, 30); + const [history, setHistory] = useState(null); + const [error, setError] = useState(null); + const [to, setTo] = useState(() => Date.now()); + + useEffect(() => { + let alive = true; + api.ups + .history(id, shown) + .then((res) => { + if (!alive) return; + setHistory(res); + setTo(Date.now()); + setError(null); + }) + .catch((err) => alive && setError(readableError(err))); + return () => { + alive = false; + }; + }, [id, shown]); + + const from = to - shown * 86_400_000; + const series = (key: "charge" | "loadPercent" | "inputVoltage", label: string, color: string) => [{ name: label, color, points: (history?.points ?? []).flatMap((p) => (p[key] === null ? [] : [{ t: p.t, v: p[key] as number }])) }]; + const charge = useMemo(() => series("charge", "Battery charge", "#2fb344"), [history]); + const load = useMemo(() => series("loadPercent", "Load", "#4299e1"), [history]); + const volts = useMemo(() => series("inputVoltage", "Mains voltage", "#ae3ec9"), [history]); + const hasVolts = volts[0].points.length > 0; + + return ( +
+
+

History

+
+ +
+
+ + {!history && !error && } + {history && ( + <> +
Battery charge
+
+ +
+
Load
+
+ +
+ {hasVolts && ( + <> +
Mains voltage (V)
+
+ `${Math.round(v)} V`} /> +
+ + )} +
Mains power lost
+ {history.onBatteryPeriods.length === 0 ? ( +
Not at all in the last {shown === 1 ? "24 hours" : `${shown} days`}.
+ ) : ( +
    + {[...history.onBatteryPeriods].reverse().map((p) => ( +
  • + — {p.ongoing ? `still on battery (${lasting(p.from, new Date().toISOString())} so far)` : `for ${lasting(p.from, p.to)}`} +
  • + ))} +
+ )} + + )} +
+ ); +} + +function UpsCard({ u }: { u: UpsInfo }) { + const s = u.state; + const chargeColor = s?.charge == null ? "#9aa0a6" : s.charge < 20 ? "#e05252" : s.charge < 50 ? "#f59f00" : "#2fb344"; + const steps = new Map(); + for (const c of u.carries) steps.set(c.step, [...(steps.get(c.step) ?? []), c]); + + return ( +
+
+
+

+ {u.name} +

+ {s && (s.model || s.manufacturer) &&
{[s.manufacturer, s.model].filter(Boolean).join(" ")} · read over {u.protocol === "snmp" ? "SNMP" : "NUT"}
} +
+ {!u.enabled && Switched off} +
+
+ {u.status && !u.status.ok && ( +
+
+ Couldn’t be read: {u.status.error}.{s ? <> What is shown is from . : null} +
+
+ )} + {u.problems.length > 0 && ( +
+
+ {u.problems.map((p) => ( +
{p.message}
+ ))} +
+
+ )} + {s ? ( +
+ + + = 90 ? "#e05252" : "#4299e1" }} sub="of what it can carry" /> + +
+ ) : ( + !u.status &&
Not read yet — the first read happens within a minute of adding it.
+ )} + +
+
+ +
+
+

On this UPS

+ {u.carries.length === 0 ? ( + + Say which servers it powers in the dependency map, and they are listed here in the order to shut them down, and folded under this UPS’s alert if they go offline with it. + + } + /> + ) : ( + <> +
In the order to shut them down — nothing is switched off while something that needs it is still running.
+
    + {[...steps.entries()].map(([step, items]) => ( +
  1. + + {step} + +
    + {items.map((c) => ( + + {c.name} + + ))} +
    +
  2. + ))} +
+ {u.orderLooped &&
Some of these need each other, so their order here is only a guess.
} +
+ While this UPS runs on battery it counts as down in the dependency map: servers that go offline with it are folded under its alert instead of each being announced. +
+ + )} +
+
+
+
+ ); +} + +/** Each UPS the app reads (over NUT or SNMP): how it is, what is wrong, how long it would last, and what is on it in the order to shut it down. */ +export default function Ups({ user }: { user: CurrentUser }) { + const [list, setList] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + const load = () => + api.ups + .list() + .then((r) => { + setList(r.ups); + setError(null); + }) + .catch((err) => setError(readableError(err))); + load(); + const t = setInterval(load, 30_000); + return () => clearInterval(t); + }, []); + + return ( + <> +

UPS

+

+ The battery backups the app reads (over NUT or SNMP): whether mains power is there, how much battery is left and for how long, and what each one carries. Mains power lost is a critical alert and a notification; while it lasts, what + goes offline with the UPS is folded under it. +

+ + {list === null && !error && } + {list?.length === 0 && ( +
+
+ + Add an integration of type UPS: the address of the machine running NUT (upsd), or of the UPS’s network card for SNMP. The app only reads it. + + } + action={user.role === "admin" ? { label: "Add an integration", to: "/integrations" } : undefined} + /> +
+
+ )} + {list?.map((u) => )} + + ); +} diff --git a/web/src/pages/settings/BadgeSettings.tsx b/web/src/pages/settings/BadgeSettings.tsx index e44a56c..e21909f 100644 --- a/web/src/pages/settings/BadgeSettings.tsx +++ b/web/src/pages/settings/BadgeSettings.tsx @@ -26,6 +26,7 @@ const INTEGRATION_NAMES: Record = { unifi: "UniFi", npm: "Nginx Proxy Manager", homeassistant: "Home Assistant", + ups: "UPS", }; function ColorList({