The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Security updates on every server: unattended-upgrades, reboot at night without calls (PR 1966)
Janika34368563280
diff --git a/ops/server/README.md b/ops/server/README.mdindex 24d1be74..36c6e325 100644--- a/ops/server/README.md+++ b/ops/server/README.md@@ -1,6 +1,6 @@# Server setup around the install-What a production server needs besides `docker compose`: alerts by email, disk and memory checks, the nightly backup with its checks, and firewalls in front of Docker's published ports. One command installs it all; run it again after an update (it changes only what differs and keeps the settings).+What a production server needs besides `docker compose`: alerts by email, disk and memory checks, the nightly backup with its checks, security updates with a reboot at a quiet moment, and firewalls in front of Docker's published ports. One command installs it all; run it again after an update (it changes only what differs and keeps the settings).```shsudo ops/server/setup.sh --alert-to [email protected] --label prod@@ -25,6 +25,9 @@ sudo ops/server/setup.sh --dry-run # shows every file it would change, touche| With separate voice servers, where a voice link runs: starts it again once WireGuard is up or restarted (`PartOf=wg-quick@<interface>`); only with an active voice-link firewall | `systemd/[email protected]` | when `wg-quick@<interface>` starts || On a voice server (an `agent` and no `api` among the compose services): its agent worker is healthy (registered with voice server 1's LiveKit) and not idle; email after 2 failures in a row and when back, with `--push-url` also a phone push. The main server's `/v1/health` does not see one voice server fail while another worker checks in | `bin/linedesk-agent-check` | every 2 minutes || With SIP over TLS (`docker-compose.sip-tls.yml` among the compose files): LiveKit SIP reads a renewed certificate (`scripts/deploy.sh --sip-cert`: a restart at a moment without calls, at most 10 minutes of waiting, else the next day); email when the certificate is missing or ends within 14 days | `systemd/linedesk-sip-cert.service` | daily |+| Security updates: unattended-upgrades installs what Ubuntu's security pocket (and ESM's, with Ubuntu Pro) offers, every day; nothing from `-updates` or other repositories (Docker's own packages, Tailscale: by hand). Dependencies an upgrade leaves unused and old kernels are removed. `docker.io`, `containerd` and `runc` from Ubuntu are never upgraded automatically (that restarts Docker and ends every call). needrestart then restarts the services that still use an old library, without asking, except Docker, containerd and WireGuard. apt never reboots by itself | `etc/unattended-upgrades.conf` (`/etc/apt/apt.conf.d/52linedesk-unattended-upgrades`), `etc/needrestart.conf` (`/etc/needrestart/conf.d/linedesk.conf`), `apt-daily*.timer` | daily (Ubuntu's apt timers) |+| Reboot after an update that needs it (`/var/run/reboot-required`: a new kernel, libc, systemd): only inside the window (`--reboot-window 03:30-05:00`, the default, in the server's time zone, usually UTC; `--reboot-tz America/New_York` for another; a window may cross midnight; `off`: never), only when no call is live and no deploy or apt/dpkg run is going on; else it tries again 10 minutes later, inside the window. Live calls (`linedesk-live-calls`, the same signal `scripts/deploy.sh` waits on): the database's live calls where Postgres runs; on a voice server LiveKit's rooms with a caller (on a further voice server: voice server 1's LiveKit, so it waits until no call runs on any voice server); when it cannot tell, it waits. Every decision is in the journal (`journalctl -u linedesk-reboot-if-needed`). After 7 days without a chance, one alert a day until it rebooted | `bin/linedesk-reboot-if-needed`, `bin/linedesk-live-calls`, `systemd/linedesk-reboot-if-needed.*` | every 10 minutes |+| The update state as one JSON line: `sudo linedesk-updates` (`{"host", "security_upgradable", "upgradable", "reboot_required", "reboot_required_since", "unattended_last_run", "kernel_running", "kernel_newest_installed", "uptime_s"}`), from apt's cache and files only (it fetches and changes nothing) | `bin/linedesk-updates` | by hand || `--harden-ssh`: keys only, no root login, 3 tries (refuses unless a sudo user with a full SSH key exists; checks `sshd -t` first and `sshd -T` after) | `etc/sshd-hardening.conf` | || `--ufw`: only SSH reaches the host's own services (Docker's published ports go past ufw; the firewalls above cover them) | | |diff --git a/ops/server/bin/linedesk-live-calls b/ops/server/bin/linedesk-live-callsnew file mode 100755index 00000000..86e4e1b4--- /dev/null+++ b/ops/server/bin/linedesk-live-calls@@ -0,0 +1,58 @@+#!/bin/bash+# Prints the number of calls in progress on this server's stack and exits 0; prints nothing and exits 1 when it cannot+# tell (the stack is down, the database or LiveKit does not answer). Callers treat "cannot tell" as busy.+# The same signal scripts/deploy.sh (live_calls) waits on before it recreates the call services; change both together:+# - where postgres runs (a single server, the app server with separate voice servers): live calls in the database, the+# query linedesk-capacity also uses;+# - on a voice server (no postgres): LiveKit's rooms with a caller in them (a phone leg or a browser; not the agent or+# egress), asked with the agent's LiveKit settings: in the running agent, or, on a media server without an agent+# (docker-compose.no-agent.yml), in a one-off container of the agent's image (never pulled here). On voice server 1+# that is its own LiveKit; on a further voice server (only an agent) it is voice server 1's LiveKit, so every call of the voice+# servers counts, not only this server's: a reboot there waits until no call runs anywhere. Rooms older than 3+# hours and rooms made before the running LiveKit started are leftovers (deploy.sh, LIN-413) and do not count.+set -u+[ -r /etc/linedesk/ops.env ] && . /etc/linedesk/ops.env+app=${LINEDESK_APP_DIR:?set LINEDESK_APP_DIR in /etc/linedesk/ops.env}+cd "$app" || exit 1++services=$(timeout 30 docker compose ps --status running --format '{{.Service}}' 2>/dev/null) || exit 1+has() { grep -qx "$1" <<<"$services"; }++if has postgres; then+ # shellcheck disable=SC2016 # the variables are the postgres container's own+ n=$(echo "select count(*) from calls where status = 'live'" |+ timeout 30 docker compose exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tA' 2>/dev/null |+ tr -d '[:space:]')+elif has agent || has livekit; then+ started=0+ livekit=$(timeout 30 docker compose ps -q livekit 2>/dev/null | head -1)+ # Only with a container: `date -d ""` would give today's midnight and drop every call that started before it.+ [ -z "$livekit" ] ||+ started=$(date -d "$(timeout 30 docker inspect -f '{{.State.StartedAt}}' "$livekit" 2>/dev/null)" +%s 2>/dev/null) || started=0+ agent=$(timeout 30 docker compose ps -q agent 2>/dev/null | head -1)+ node() {+ if [ -n "$agent" ]; then+ timeout 30 docker exec -i "$agent" node - 2>/dev/null+ else+ timeout 60 docker compose run --rm --no-deps --pull never -T --entrypoint node agent - 2>/dev/null+ fi+ }+ n=$({ echo "const LIVEKIT_STARTED = ${started:-0}"; cat <<'JS'; } | node | tr -d '[:space:]'+setTimeout(() => process.exit(0), 20000).unref()+const { RoomServiceClient } = require("livekit-server-sdk")+const rooms = new RoomServiceClient(process.env.LIVEKIT_URL.replace(/^ws/, "http"), process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET)+const CALLER_KINDS = new Set([0, 3]) // ParticipantInfo_Kind STANDARD (browser), SIP (phone)+const now = Date.now() / 1000+// Any error rejects the whole count, so nothing is printed: never a 0 by mistake.+rooms.listRooms()+ .then((all) => all.filter((r) => r.numParticipants > 0 && now - Number(r.creationTime) < 3 * 3600 &&+ Number(r.creationTime) >= LIVEKIT_STARTED))+ .then((open) => Promise.all(open.map((r) => rooms.listParticipants(r.name).then((ps) => ps.some((p) => CALLER_KINDS.has(p.kind))))))+ .then((live) => console.log(live.filter(Boolean).length), () => {})+JS+)+else+ exit 1+fi+[[ ${n:-} =~ ^[0-9]+$ ]] || exit 1+echo "$n"diff --git a/ops/server/bin/linedesk-reboot-if-needed b/ops/server/bin/linedesk-reboot-if-needednew file mode 100755index 00000000..8dc72a6d--- /dev/null+++ b/ops/server/bin/linedesk-reboot-if-needed@@ -0,0 +1,132 @@+#!/bin/bash+# Reboots the server after an update that needs it (a new kernel or libc: /var/run/reboot-required), at a quiet moment:+# only inside the nightly window and only when no call is live (linedesk-live-calls) and no deploy or apt run is going on.+# Runs every 10 minutes (linedesk-reboot-if-needed.timer), so inside the window it tries again every 10 minutes. Every+# decision goes to the journal (journalctl -u linedesk-reboot-if-needed). When a reboot has waited 7 days, one alert a+# day until it happened (calls every night, or a "live" call that never ended: check the calls table).+# Settings in /etc/linedesk/ops.env (setup.sh --reboot-window, --reboot-tz):+# LINEDESK_REBOOT_WINDOW HH:MM-HH:MM (default 03:30-05:00; may cross midnight, 23:30-01:00), or off: never reboot+# LINEDESK_REBOOT_TZ the window's time zone (e.g. America/New_York); empty: the server's own (usually UTC)+set -u+# Stand-ins for the tests (scripts/server-updates.test.sh, never as root): the commands it calls, the files and the+# clock. As root (the timer) they are ignored, so nothing in the environment chooses what root runs.+if [ "$(id -u)" = 0 ]; then+ unset LINEDESK_LIVE_CALLS_CMD LINEDESK_ALERT_CMD LINEDESK_REBOOT_CMD LINEDESK_APT_BUSY_CMD LINEDESK_NOW \+ LINEDESK_REBOOT_FLAG LINEDESK_REBOOT_HOLD+fi+[ -r /etc/linedesk/ops.env ] && . /etc/linedesk/ops.env+app=${LINEDESK_APP_DIR:?set LINEDESK_APP_DIR in /etc/linedesk/ops.env}+window=${LINEDESK_REBOOT_WINDOW:-03:30-05:00}+tz=${LINEDESK_REBOOT_TZ:-}+dir=${STATE_DIRECTORY:-/var/lib/linedesk-reboot}+flag=${LINEDESK_REBOOT_FLAG:-/var/run/reboot-required}+alert_after=604800 # 7 days+live_calls=${LINEDESK_LIVE_CALLS_CMD:-/usr/local/sbin/linedesk-live-calls}+alert=${LINEDESK_ALERT_CMD:-/usr/local/sbin/linedesk-alert-text}+reboot_cmd=${LINEDESK_REBOOT_CMD:-systemctl reboot}+apt_busy_cmd=${LINEDESK_APT_BUSY_CMD:-apt_busy}+hold=${LINEDESK_REBOOT_HOLD:-840} # seconds the deploy lock stays held after asking for the reboot+now=${LINEDESK_NOW:-$(date +%s)}+mkdir -p "$dir"++say() { echo "$*"; }++# Minutes since midnight of "HH:MM" (00:00 to 23:59), or nothing.+minutes() { [[ $1 =~ ^([01][0-9]|2[0-3]):([0-5][0-9])$ ]] && echo $((10#${BASH_REMATCH[1]} * 60 + 10#${BASH_REMATCH[2]})); }++# Whether the clock (in the window's time zone) is inside the window; exits 2 on a broken setting.+in_window() {+ local start end cur+ start=$(minutes "${window%-*}") end=$(minutes "${window#*-}")+ [ -n "$start" ] && [ -n "$end" ] && [ "$start" != "$end" ] ||+ { say "LINEDESK_REBOOT_WINDOW is '$window', not HH:MM-HH:MM or off: no reboot"; exit 2; }+ if [ -n "$tz" ] && [ ! -f "/usr/share/zoneinfo/$tz" ]; then+ say "LINEDESK_REBOOT_TZ is '$tz', not a time zone of this server: no reboot"+ exit 2+ fi+ if [ -n "$tz" ]; then+ cur=$(minutes "$(TZ=$tz date -d "@$now" +%H:%M)")+ else+ cur=$(minutes "$(date -d "@$now" +%H:%M)")+ fi+ if [ "$start" -lt "$end" ]; then+ [ "$cur" -ge "$start" ] && [ "$cur" -lt "$end" ]+ else # across midnight+ [ "$cur" -ge "$start" ] || [ "$cur" -lt "$end" ]+ fi+}++# apt or dpkg is running (apt's daily jobs, unattended-upgrades, a run by hand): never reboot in the middle of an+# upgrade. dpkg's locks are fcntl locks, which flock cannot see: fuser shows who holds them.+apt_busy() {+ local unit state+ fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock /var/lib/apt/lists/lock >/dev/null 2>&1 && return 0+ for unit in apt-daily.service apt-daily-upgrade.service; do+ state=$(systemctl show -p ActiveState --value "$unit" 2>/dev/null)+ case $state in active | activating | deactivating | reloading) return 0 ;; esac+ done+ return 1+}++if [ ! -e "$flag" ]; then+ rm -f "$dir/alerted"+ say "no reboot needed"+ exit 0+fi+since=$(stat -c %Y "$flag")+pkgs=$(tr '\n' ' ' <"$flag.pkgs" 2>/dev/null | head -c 300)+waiting="reboot needed since $(date -u -d "@$since" '+%Y-%m-%d %H:%M UTC') (for: ${pkgs:-?})"++# Waited too long: one alert a day.+if [ $((now - since)) -ge "$alert_after" ]; then+ last=$(cat "$dir/alerted" 2>/dev/null || echo 0)+ [[ $last =~ ^[0-9]+$ ]] || last=0+ if [ $((now - last)) -ge 86400 ]; then+ days=$(((now - since) / 86400))+ if $alert "Reboot for updates waiting for $days days" "$(hostname) needs a reboot for security updates and found no quiet moment in its window ($window${tz:+ $tz}) for $days days: $waiting. Check the calls (a call that stays live blocks it) and journalctl -u linedesk-reboot-if-needed, or reboot it by hand at a moment without calls."; then+ echo "$now" >"$dir/alerted"+ say "$waiting; waited $days days: alert sent"+ else+ say "$waiting; waited $days days: the alert could not be sent"+ fi+ fi+fi++if [ "$window" = off ]; then+ say "$waiting; automatic reboots are off (LINEDESK_REBOOT_WINDOW=off)"+ exit 0+fi+if ! in_window; then+ say "$waiting; outside the window $window${tz:+ $tz}"+ exit 0+fi+if $apt_busy_cmd; then+ say "$waiting; apt is running: not now"+ exit 0+fi+# A deploy holds the receiver's lock (deploy.lock next to app/) while it runs; this holds it until the reboot, so no+# deploy starts in between. Only an existing plain file: root never creates it (the receiver's user could then not+# open it) and never opens a link or a FIFO the receiver's user put there.+lock=$(dirname "$app")/deploy.lock+if [ -L "$lock" ] || { [ -e "$lock" ] && [ ! -f "$lock" ]; }; then+ say "$waiting; $lock is not a plain file: not rebooting (check it)"+ exit 1+fi+if [ -f "$lock" ]; then+ exec 9<"$lock"+ flock -n 9 || { say "$waiting; a deploy is running: not now"; exit 0; }+fi+calls=$($live_calls 2>/dev/null)+if ! [[ $calls =~ ^[0-9]+$ ]]; then+ say "$waiting; cannot tell whether calls are live: not now"+ exit 0+fi+if [ "$calls" -gt 0 ]; then+ say "$waiting; $calls live calls: not now"+ exit 0+fi+say "$waiting; no live calls, inside the window $window${tz:+ $tz}: rebooting now"+$reboot_cmd || { say "the reboot command failed"; exit 1; }+# systemctl reboot returns once the reboot is queued: keep the deploy lock until shutdown ends this script, so no+# waiting deploy starts while Docker is being stopped.+sleep "$hold"diff --git a/ops/server/bin/linedesk-updates b/ops/server/bin/linedesk-updatesnew file mode 100755index 00000000..12b2effa--- /dev/null+++ b/ops/server/bin/linedesk-updates@@ -0,0 +1,40 @@+#!/bin/bash+# The update state of this server as one JSON line (the production guard's read command `updates` runs this; on a+# server without the guard: sudo linedesk-updates):+# {"host":"…","security_upgradable":N,"upgradable":N,"reboot_required":bool,"reboot_required_since":<unix>|null,+# "unattended_last_run":<unix>|null,"kernel_running":"…","kernel_newest_installed":"…","uptime_s":N}+# Read-only: the package counts come from apt's cache as the last `apt update` (the daily apt timer) left it; nothing+# is fetched or changed. security_upgradable counts packages a security pocket (Ubuntu's -security, ESM) offers, which+# unattended-upgrades installs by itself, except the ones it is told to leave (Docker's own packages: by hand).+set -u+export LC_ALL=C+# The paths can be changed for the tests (scripts/server-updates.test.sh), never as root.+[ "$(id -u)" != 0 ] || unset LINEDESK_REBOOT_FLAG LINEDESK_UNATTENDED_STAMP LINEDESK_UNATTENDED_LOG LINEDESK_BOOT_DIR+flag=${LINEDESK_REBOOT_FLAG:-/var/run/reboot-required}+stamp=${LINEDESK_UNATTENDED_STAMP:-/var/lib/apt/periodic/unattended-upgrades-stamp}+uu_log=${LINEDESK_UNATTENDED_LOG:-/var/log/unattended-upgrades/unattended-upgrades.log}+boot=${LINEDESK_BOOT_DIR:-/boot}++# A string for JSON: only characters that need no escaping, else "?".+str() { if [[ $1 =~ ^[A-Za-z0-9._+~:-]{1,100}$ ]]; then printf '"%s"' "$1"; else printf '"?"'; fi; }+mtime_or_null() { [ -e "$1" ] && stat -c %Y "$1" 2>/dev/null || echo null; }++# `apt list --upgradable` lines look like "name/noble-updates,noble-security 1.2 amd64 [upgradable from: 1.1]".+list=$(apt list --upgradable 2>/dev/null | grep '/' || true)+upgradable=$(grep -c . <<<"$list" || true)+security=$(awk '{ split($1, a, "/"); if (a[2] ~ /(^|,)[^,]*-security(,|$)/) n++ } END { print n + 0 }' <<<"$list")++reboot=false since=null+if [ -e "$flag" ]; then reboot=true since=$(mtime_or_null "$flag"); fi++# The last run of unattended-upgrades: apt's daily job stamps it; before the first stamp, its log.+last=$(mtime_or_null "$stamp")+[ "$last" != null ] || last=$(mtime_or_null "$uu_log")++running=$(uname -r)+newest=$(find "$boot" -maxdepth 1 -name 'vmlinuz-*' -printf '%f\n' 2>/dev/null | sed 's/^vmlinuz-//' | sort -V | tail -1)+uptime_s=$(cut -d. -f1 /proc/uptime)++printf '{"host":%s,"security_upgradable":%d,"upgradable":%d,"reboot_required":%s,"reboot_required_since":%s,"unattended_last_run":%s,"kernel_running":%s,"kernel_newest_installed":%s,"uptime_s":%d}\n' \+ "$(str "$(hostname)")" "$security" "$upgradable" "$reboot" "$since" "$last" "$(str "$running")" \+ "$(str "${newest:-?}")" "$uptime_s"diff --git a/ops/server/etc/needrestart.conf b/ops/server/etc/needrestart.confnew file mode 100644index 00000000..9f3c8a05--- /dev/null+++ b/ops/server/etc/needrestart.conf@@ -0,0 +1,12 @@+# Linedesk (ops/server/setup.sh installs this as /etc/needrestart/conf.d/linedesk.conf; edits there are overwritten by+# the next run). After an upgrade, services that still use an old library are restarted without asking+# (unattended-upgrades runs without a terminal). Never the ones whose restart ends calls: Docker (also in needrestart's+# defaults), containerd, WireGuard (the voice link) and systemd-networkd (a network blip during calls). A new kernel+# is only noted; linedesk-reboot-if-needed reboots.+$nrconf{restart} = 'a';+$nrconf{kernelhints} = -1;+$nrconf{ucodehints} = 0;+$nrconf{override_rc}{qr(^docker)} = 0;+$nrconf{override_rc}{qr(^containerd)} = 0;+$nrconf{override_rc}{qr(^wg-quick@)} = 0;+$nrconf{override_rc}{qr(^systemd-networkd)} = 0;diff --git a/ops/server/etc/unattended-upgrades.conf b/ops/server/etc/unattended-upgrades.confnew file mode 100644index 00000000..ef867bcd--- /dev/null+++ b/ops/server/etc/unattended-upgrades.conf@@ -0,0 +1,27 @@+// Linedesk (ops/server/setup.sh installs this as /etc/apt/apt.conf.d/52linedesk-unattended-upgrades; edits there are+// overwritten by the next run). Read after Ubuntu's 50unattended-upgrades, so these settings win.+// Security updates only: Ubuntu's security pocket and, where the server has Ubuntu Pro, ESM's security pockets.+#clear Unattended-Upgrade::Allowed-Origins;+#clear Unattended-Upgrade::Origins-Pattern;+Unattended-Upgrade::Allowed-Origins {+ "${distro_id}:${distro_codename}-security";+ "${distro_id}ESMApps:${distro_codename}-apps-security";+ "${distro_id}ESM:${distro_codename}-infra-security";+};+// Upgrading these restarts Docker, which ends every call: by hand, at a quiet moment (Docker's own packages from+// download.docker.com are not in the origins above anyway).+Unattended-Upgrade::Package-Blacklist {+ "docker\.io$";+ "containerd$";+ "runc$";+};+// apt never reboots; linedesk-reboot-if-needed does, in the night window and only without live calls.+Unattended-Upgrade::Automatic-Reboot "false";+// Only what an upgrade itself leaves unused; never other packages that look unused (something the stack needs may not+// be declared as a dependency).+Unattended-Upgrade::Remove-Unused-Dependencies "false";+Unattended-Upgrade::Remove-New-Unused-Dependencies "true";+Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";+// Every day: refresh the package lists, then install.+APT::Periodic::Update-Package-Lists "1";+APT::Periodic::Unattended-Upgrade "1";diff --git a/ops/server/setup.sh b/ops/server/setup.shindex e9b34969..c6dc1a14 100755--- a/ops/server/setup.sh+++ b/ops/server/setup.sh@@ -1,7 +1,7 @@#!/bin/sh# Sets up the server around a Linedesk install (as root, from the checkout in /opt/linedesk/app): email alerts, disk and-# memory checks, the nightly backup with its freshness check and weekly restore test, SIP only from carriers, and on-# request the web ports only from Cloudflare, SSH hardening, ufw and uptime checks of another install. Everything it+# memory checks, the nightly backup with its freshness check and weekly restore test, SIP only from carriers, security+# updates by themselves with a reboot at a quiet moment in the night when one is needed, and on request the web ports only from Cloudflare, SSH hardening, ufw and uptime checks of another install. Everything it# installs is in ops/server/ (README there). Run it again after an update: it is idempotent and keeps /etc/linedesk/ops.env.## sudo ops/server/setup.sh --alert-to [email protected] --label prod # several: --alert-to [email protected],[email protected]@@ -12,6 +12,8 @@# --monitor <host> [--monitor-sip <host>] check another install every 2 minutes from this server# --push-url <https URL> with --monitor (or on a voice server): also a phone push (ntfy topic URL) when a check goes down or up# --capacity-push <user@host> send the capacity samples (linedesk-capacity) there over SSH every 5 minutes+# --reboot-window <HH:MM-HH:MM|off> when a reboot after updates may happen (default 03:30-05:00), off: never+# --reboot-tz <Area/City> the window's time zone (default: the server's own, usually UTC)# A server with a voice link (the app server with docker-compose.voice-link.yml, voice server 1 with# docker-compose.voice-media.yml) also gets the voice-link firewall (only the addresses in /etc/linedesk/voice-nodes.txt);# a voice server (an agent and no API) the agent check.@@ -19,6 +21,7 @@ set -euhere=$(cd "$(dirname "$0")" && pwd)app_dir=${LINEDESK_APP_DIR:-$(cd "$here/../.." && pwd)}dry=0 cloudflare=0 harden_ssh=0 ufw=0 alert_to='' label='' monitor='' monitor_sip='' push_url='' capacity_push=''+reboot_window='' reboot_tz=''while [ $# -gt 0 ]; docase $1 in--dry-run) dry=1 ;;@@ -31,7 +34,9 @@ while [ $# -gt 0 ]; do--monitor-sip) monitor_sip=${2:?--monitor-sip needs a host}; shift ;;--push-url) push_url=${2:?--push-url needs a URL}; shift ;;--capacity-push) capacity_push=${2:?--capacity-push needs user@host}; shift ;;- *) sed -n '2,16p' "$0" >&2; exit 2 ;;+ --reboot-window) reboot_window=${2:?--reboot-window needs HH:MM-HH:MM or off}; shift ;;+ --reboot-tz) reboot_tz=${2:?--reboot-tz needs a time zone, e.g. America/New_York}; shift ;;+ *) sed -n '2,19p' "$0" >&2; exit 2 ;;esacshiftdone@@ -68,6 +73,9 @@ monitor=${monitor:-$(current LINEDESK_MONITOR_HOST)}monitor_sip=${monitor_sip:-$(current LINEDESK_MONITOR_SIP_HOST)}push_url=${push_url:-$(current LINEDESK_PUSH_URL)}capacity_push=${capacity_push:-$(current LINEDESK_CAPACITY_PUSH)}+reboot_window=${reboot_window:-$(current LINEDESK_REBOOT_WINDOW)}+reboot_window=${reboot_window:-03:30-05:00}+reboot_tz=${reboot_tz:-$(current LINEDESK_REBOOT_TZ)}label=${label:-$(hostname)}# ops.env is sourced by scripts that run as root: only plain values go in.valid() { printf '%s\n' "$2" | grep -Eq "$3" || { echo "not a valid $1: $2" >&2; exit 1; }; }@@ -78,6 +86,10 @@ valid "app folder" "$app_dir" '^/[A-Za-z0-9._/-]+$'[ -z "$monitor_sip" ] || valid "host name" "$monitor_sip" '^[A-Za-z0-9.-]+$'[ -z "$push_url" ] || valid "push URL" "$push_url" '^https://[A-Za-z0-9.-]+(:[0-9]+)?/[A-Za-z0-9._/-]+$'[ -z "$capacity_push" ] || valid "user@host" "$capacity_push" '^[a-z_][a-z0-9_-]*@[A-Za-z0-9.-]+$'+valid "reboot window (HH:MM-HH:MM or off)" "$reboot_window" '^(off|([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9])$'+[ "$reboot_window" = off ] || [ "${reboot_window%-*}" != "${reboot_window#*-}" ] || { echo "the reboot window starts and ends at the same time: $reboot_window" >&2; exit 1; }+[ -z "$reboot_tz" ] || { valid "time zone" "$reboot_tz" '^[A-Za-z0-9_+-]+(/[A-Za-z0-9_+-]+)*$' && [ -f "/usr/share/zoneinfo/$reboot_tz" ]; } ||+ { echo "not a time zone of this server: $reboot_tz (e.g. America/New_York, Europe/Berlin)" >&2; exit 1; }{echo "# Settings for the scripts from ops/server (setup.sh writes this file; edit it and run setup.sh again)."echo "LINEDESK_APP_DIR=$app_dir"@@ -87,6 +99,8 @@ valid "app folder" "$app_dir" '^/[A-Za-z0-9._/-]+$'[ -z "$monitor_sip" ] || echo "LINEDESK_MONITOR_SIP_HOST=$monitor_sip"[ -z "$push_url" ] || echo "LINEDESK_PUSH_URL=$push_url"[ -z "$capacity_push" ] || echo "LINEDESK_CAPACITY_PUSH=$capacity_push"+ echo "LINEDESK_REBOOT_WINDOW=$reboot_window"+ [ -z "$reboot_tz" ] || echo "LINEDESK_REBOOT_TZ=$reboot_tz"} > "$tmp/ops.env"put "$tmp/ops.env" "$ops_env" 644@@ -119,8 +133,20 @@ if [ -e /etc/systemd/system/linedesk-backup.service.d/alert.conf ]; thenrun rmdir --ignore-fail-on-non-empty /etc/systemd/system/linedesk-backup.service.dfi-# What runs: always the alerts, disk and memory and the SIP firewall; the backups once backup.env is set up.+# Security updates (Ubuntu's security pockets only) by unattended-upgrades every day; needrestart restarts the services+# that use an old library (never Docker, containerd or WireGuard); apt never reboots: linedesk-reboot-if-needed does,+# in the night window and only without live calls.+for pkg in unattended-upgrades needrestart; do+ dpkg-query -W -f '${Status}' "$pkg" 2>/dev/null | grep -q 'install ok installed' ||+ { changed=1; say "$pkg: installing"; run env DEBIAN_FRONTEND=noninteractive apt-get install -y -q "$pkg"; }+done+put "$here/etc/unattended-upgrades.conf" /etc/apt/apt.conf.d/52linedesk-unattended-upgrades 644+put "$here/etc/needrestart.conf" /etc/needrestart/conf.d/linedesk.conf 644++# What runs: always the alerts, disk and memory, the SIP firewall, apt's daily jobs and the reboot after updates; the+# backups once backup.env is set up.units='linedesk-resources.timer linedesk-capacity.timer linedesk-sip-firewall.service'+units="$units apt-daily.timer apt-daily-upgrade.timer linedesk-reboot-if-needed.timer"if [ -f "$app_dir/backup.env" ]; thenunits="$units linedesk-backup.timer linedesk-backup-check.timer linedesk-restore-test.timer"else@@ -269,5 +295,6 @@ if [ -n "$voice_link_unit" ]; thenfifisay "on: $units"+say "security updates: daily; a reboot they need happens in $reboot_window${reboot_tz:+ ($reboot_tz)} without live calls (journalctl -u linedesk-reboot-if-needed; state: linedesk-updates)"[ -z "$capacity_push" ] || say "capacity samples go to $capacity_push with this key (its line there: restrict,from=\"<this server's address>\",command=\"<receiver> <name>\"): $(cat "$capacity_key.pub")"say "test the alert email: /usr/local/sbin/linedesk-alert-text 'Test' 'Alerts from $(hostname) work.'"diff --git a/ops/server/systemd/linedesk-reboot-if-needed.service b/ops/server/systemd/linedesk-reboot-if-needed.servicenew file mode 100644index 00000000..5ebf0971--- /dev/null+++ b/ops/server/systemd/linedesk-reboot-if-needed.service@@ -0,0 +1,10 @@+[Unit]+Description=Linedesk: reboot after updates at a quiet moment in the night window (linedesk-reboot-if-needed)+OnFailure=linedesk-alert@%n.service+[Service]+Type=oneshot+StateDirectory=linedesk-reboot+ExecStart=/usr/local/sbin/linedesk-reboot-if-needed+# A hang (Docker not answering) fails the unit, which sends its alert, instead of stopping every later run. Above the+# script's wait after asking for the reboot (840 s).+TimeoutStartSec=15mindiff --git a/ops/server/systemd/linedesk-reboot-if-needed.timer b/ops/server/systemd/linedesk-reboot-if-needed.timernew file mode 100644index 00000000..dd9ae317--- /dev/null+++ b/ops/server/systemd/linedesk-reboot-if-needed.timer@@ -0,0 +1,6 @@+[Unit]+Description=Linedesk reboot-after-updates check every 10 minutes+[Timer]+OnCalendar=*:0/10+[Install]+WantedBy=timers.targetdiff --git a/scripts/server-updates.test.sh b/scripts/server-updates.test.shnew file mode 100644index 00000000..00aed370--- /dev/null+++ b/scripts/server-updates.test.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# Tests for the security-update helpers in ops/server/bin: linedesk-reboot-if-needed (when it reboots and when not, the+# window and its time zone, the alert after 7 days) and linedesk-updates (its JSON line). Nothing is rebooted: the+# commands it calls are stand-ins that write what they were asked.+# bash scripts/server-updates.test.sh (not as root: as root the scripts ignore the stand-ins)+set -uo pipefail+cd "$(dirname "$0")/.." || exit 1+bin=$PWD/ops/server/bin++failures=0+pass() { echo "ok $1"; }+fail() { echo "FAIL $1"; failures=$((failures + 1)); }++tmp=$(mktemp -d)+trap 'rm -rf "$tmp"' EXIT+mkdir -p "$tmp/opt/app" "$tmp/state"+flag=$tmp/reboot-required+# Stand-ins: the live calls come from $tmp/calls (empty: cannot tell), a reboot and an alert are written down.+printf '#!/bin/sh\n[ -s %s/calls ] && cat %s/calls\n' "$tmp" "$tmp" >"$tmp/live-calls"+printf '#!/bin/sh\necho reboot >>%s/rebooted\n' "$tmp" >"$tmp/reboot"+printf '#!/bin/sh\necho "$1" >>%s/alerts\n' "$tmp" >"$tmp/alert"+chmod +x "$tmp/live-calls" "$tmp/reboot" "$tmp/alert"++# check <name> <want: reboot|none|refused|fails> <UTC time of the run, YYYY-mm-dd HH:MM> [VAR=value ...]+# refused: no reboot and exit 2 (a broken setting); fails: no reboot and exit 1. Both fail the unit, which sends its+# OnFailure alert.+check() {+ local name=$1 want=$2 at=$3 got status+ shift 3+ rm -f "$tmp/rebooted"+ env -i PATH="$PATH" TZ=UTC LINEDESK_APP_DIR="$tmp/opt/app" STATE_DIRECTORY="$tmp/state" LINEDESK_REBOOT_FLAG="$flag" \+ LINEDESK_LIVE_CALLS_CMD="$tmp/live-calls" LINEDESK_REBOOT_CMD="$tmp/reboot" LINEDESK_ALERT_CMD="$tmp/alert" \+ LINEDESK_APT_BUSY_CMD=false LINEDESK_REBOOT_HOLD=0 LINEDESK_NOW="$(date -u -d "$at" +%s)" "$@" \+ bash "$bin/linedesk-reboot-if-needed" >"$tmp/out" 2>&1+ status=$?+ if [ -e "$tmp/rebooted" ]; then got=reboot; elif [ "$status" = 2 ]; then got=refused+ elif [ "$status" = 1 ]; then got=fails; else got=none; fi+ if [ "$got" = "$want" ] && { [ "$status" = 0 ] || [ "$got" = refused ] || [ "$got" = fails ]; }; then pass "$name"; else+ fail "$name (wanted $want, got $got, exit $status): $(cat "$tmp/out")"+ fi+}+needed() { touch -d "$1 UTC" "$flag"; echo linux-image-6.8.0-151-generic >"$flag.pkgs"; }++echo "linedesk-reboot-if-needed"+rm -f "$flag"+echo 0 >"$tmp/calls"+check "no reboot needed: nothing happens" none "2026-11-28 04:00"+needed "2026-11-27 06:00"+check "needed, no calls, inside the window: reboots" reboot "2026-11-28 04:00"+check "at the window's start" reboot "2026-11-28 03:30"+check "at the window's end: outside" none "2026-11-28 05:00"+check "needed, outside the window" none "2026-11-28 12:00"+echo 2 >"$tmp/calls"+check "live calls: waits" none "2026-11-28 04:00"+: >"$tmp/calls"+check "cannot tell whether calls are live: waits" none "2026-11-28 04:00"+echo 'error' >"$tmp/calls"+check "a non-number from the call count: waits" none "2026-11-28 04:00"+echo 0 >"$tmp/calls"+check "apt is running: waits" none "2026-11-28 04:00" LINEDESK_APT_BUSY_CMD=true+check "window across midnight, after midnight" reboot "2026-11-28 00:15" LINEDESK_REBOOT_WINDOW=23:30-01:00+check "window across midnight, before midnight" reboot "2026-11-27 23:45" LINEDESK_REBOOT_WINDOW=23:30-01:00+check "window across midnight, outside" none "2026-11-28 01:05" LINEDESK_REBOOT_WINDOW=23:30-01:00+# 08:40 UTC is 03:40 in New York (EST, UTC-5, in November).+check "window in another time zone, inside" reboot "2026-11-28 08:40" LINEDESK_REBOOT_TZ=America/New_York+check "window in another time zone, outside there" none "2026-11-28 03:40" LINEDESK_REBOOT_TZ=America/New_York+check "the window from the server's own time zone" reboot "2026-11-28 08:40" TZ=America/New_York+check "off: never" none "2026-11-28 04:00" LINEDESK_REBOOT_WINDOW=off+for bad in 3:30-05:00 03:30 03:30-03:30 25:00-01:00 '03:30-05:00;reboot'; do+ check "window '$bad' refused" refused "2026-11-28 04:00" LINEDESK_REBOOT_WINDOW="$bad"+done+check "an unknown time zone: refused" refused "2026-11-28 04:00" LINEDESK_REBOOT_TZ=Mars/Olympus+grep -q 'not a time zone' "$tmp/out" && pass "says why" || fail "says why: $(cat "$tmp/out")"+# A deploy holds the receiver's lock: no reboot until it is done.+: >"$tmp/opt/deploy.lock"+flock "$tmp/opt/deploy.lock" sleep 3 &+sleep 0.3+check "a deploy is running: waits" none "2026-11-28 04:00"+wait+check "the deploy is done" reboot "2026-11-28 04:00"++ln -sf /dev/null "$tmp/opt/deploy.lock"+check "the deploy lock is a link: refused" fails "2026-11-28 04:00"+rm -f "$tmp/opt/deploy.lock"+mkfifo "$tmp/opt/deploy.lock"+check "the deploy lock is a FIFO: refused" fails "2026-11-28 04:00"+rm -f "$tmp/opt/deploy.lock"++echo "alert after 7 days"+rm -f "$tmp/alerts" "$tmp/state/alerted"+needed "2026-11-20 06:00"+echo 1 >"$tmp/calls"+check "6 days: no alert yet" none "2026-11-26 12:00"+[ ! -e "$tmp/alerts" ] && pass "no alert before 7 days" || fail "no alert before 7 days"+check "7 days: an alert" none "2026-11-27 12:00"+[ "$(grep -c . "$tmp/alerts" 2>/dev/null)" = 1 ] && pass "one alert" || fail "one alert"+check "later the same day" none "2026-11-27 20:00"+[ "$(grep -c . "$tmp/alerts")" = 1 ] && pass "still one alert that day" || fail "still one alert that day"+check "the next day" none "2026-11-28 12:30"+[ "$(grep -c . "$tmp/alerts")" = 2 ] && pass "one more the next day" || fail "one more the next day"+rm -f "$flag"+check "rebooted: done" none "2026-11-28 13:00"+[ ! -e "$tmp/state/alerted" ] && pass "the alert state is reset" || fail "the alert state is reset"++echo "linedesk-updates"+mkdir -p "$tmp/boot"+touch "$tmp/boot/vmlinuz-6.8.0-99-generic" "$tmp/boot/vmlinuz-6.8.0-151-generic" "$tmp/boot/vmlinuz-6.8.0-149-generic"+needed "2026-11-26 06:11"+touch -d '2026-11-28 06:00 UTC' "$tmp/stamp"+line=$(LINEDESK_REBOOT_FLAG="$flag" LINEDESK_UNATTENDED_STAMP="$tmp/stamp" LINEDESK_BOOT_DIR="$tmp/boot" bash "$bin/linedesk-updates")+if python3 -I -c '+import json, sys+d = json.loads(sys.argv[1])+want = {"host", "security_upgradable", "upgradable", "reboot_required", "reboot_required_since", "unattended_last_run",+ "kernel_running", "kernel_newest_installed", "uptime_s"}+assert set(d) == want, set(d) ^ want+assert d["reboot_required"] is True and d["reboot_required_since"] == int(sys.argv[2]), d+assert d["unattended_last_run"] == int(sys.argv[3]), d+assert d["kernel_newest_installed"] == "6.8.0-151-generic", d+assert isinstance(d["security_upgradable"], int) and isinstance(d["upgradable"], int) and d["uptime_s"] > 0, d+assert d["security_upgradable"] <= d["upgradable"], d+' "$line" "$(stat -c %Y "$flag")" "$(stat -c %Y "$tmp/stamp")"; then pass "one JSON line with every field"; else+ fail "one JSON line with every field: $line"+fi+[ "$(grep -c . <<<"$line")" = 1 ] && pass "exactly one line" || fail "exactly one line"+rm -f "$flag" "$tmp/stamp"+line=$(LINEDESK_REBOOT_FLAG="$flag" LINEDESK_UNATTENDED_STAMP="$tmp/stamp" LINEDESK_UNATTENDED_LOG="$tmp/none" \+ LINEDESK_BOOT_DIR="$tmp/boot" bash "$bin/linedesk-updates")+grep -q '"reboot_required":false,"reboot_required_since":null,"unattended_last_run":null' <<<"$line" &&+ pass "no reboot needed, never ran: false and nulls" || fail "no reboot needed, never ran: $line"++[ "$failures" = 0 ] || { echo "$failures failed"; exit 1; }+echo "all passed"