Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Podman: rootless install as a service, with updates
milind-soni3f2fa77d66af
diff --git a/.github/workflows/podman-service.yml b/.github/workflows/podman-service.ymlnew file mode 100644index 0000000000..4c0d82b29c--- /dev/null+++ b/.github/workflows/podman-service.yml@@ -0,0 +1,44 @@+name: Podman service++# The rootless Podman install (deploy/podman/install.sh) on a stock ubuntu-24.04 runner, as its own user runs it: the+# published server image as the user's systemd service, a turn with the repository's fake engine, Chrome, restarts,+# the LAN switch, an update and a rolled-back one through deploy/update.sh, and an uninstall (deploy/e2e/podman.sh).+# It talks to no production service and needs no secret.+on:+ pull_request:+ paths:+ - deploy/podman/install.sh+ - deploy/update.sh+ - deploy/e2e/podman.sh+ - .github/workflows/podman-service.yml+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: podman-service-${{ github.ref }}+ cancel-in-progress: true++jobs:+ e2e:+ name: install, restart, update and roll back as a rootless user service on Ubuntu 24.04+ runs-on: ubuntu-24.04+ timeout-minutes: 45+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: shellcheck+ run: shellcheck deploy/podman/install.sh deploy/e2e/podman.sh+ - name: Install, restart, update, roll back and uninstall+ env:+ OUT: ${{ runner.temp }}/podman-service+ run: bash deploy/e2e/podman.sh+ - name: Keep the evidence+ if: always()+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: podman-service+ path: ${{ runner.temp }}/podman-service+ retention-days: 14diff --git a/deploy/e2e/podman.sh b/deploy/e2e/podman.shnew file mode 100755index 0000000000..0ce895367c--- /dev/null+++ b/deploy/e2e/podman.sh@@ -0,0 +1,221 @@+#!/usr/bin/env bash+# The rootless Podman install (deploy/podman/install.sh) on a stock Ubuntu 24.04 host, as its own user runs it: install a+# published release as the user's systemd service, run it again, a bot turn with the repository's fake engine, Chrome in+# the server's container, a kill of the server and a restart of the user's systemd (what a boot does), the LAN switch and+# back, an update to the next release, an update that cannot start and is rolled back, and an uninstall that keeps the+# data. It also records whether the bots' sandbox (bubblewrap) can run in a rootless container, and with what.+# The files the installer places (update.sh) come from this checkout.+# OUT=<evidence folder> bash deploy/e2e/podman.sh+set -euo pipefail+ROOT=$(cd "$(dirname "$0")/../.." && pwd)+OUT=${OUT:-$(mktemp -d)}+mkdir -p "$OUT"+REPO=ghcr.io/milind-soni/openmausbot+OLD_VERSION=${OMB_E2E_OLD_VERSION:-0.1.165}+NEW_VERSION=${OMB_E2E_NEW_VERSION:-0.1.166}+DIR="$HOME/.local/share/openmausbot"+UNIT="$HOME/.config/containers/systemd/openmausbot.container"+INSTALL=(env "OMB_INSTALL_SOURCE=file://$ROOT" sh "$ROOT/deploy/podman/install.sh")+FINDINGS="$OUT/findings.txt"+: >"$FINDINGS"++step() { printf '\n== %s\n' "$*"; }+finding() { printf '%s\n' "$*" | tee -a "$FINDINGS"; }+fail() {+ printf 'FAILED: %s\n' "$*" >&2+ journalctl --user -u openmausbot -n 120 --no-pager >"$OUT/journal.txt" 2>&1 || true+ tail -n 60 "$OUT/journal.txt" >&2 || true+ exit 1+}+contains() { # file words what+ grep -qF -- "$2" "$1" || fail "$3: $(tail -n 20 "$1")"+}+healthy() { curl -sf --max-time 5 "http://127.0.0.1:${1:-8799}/api/health" 2>/dev/null | grep -q openmausbot; }+healthy_again() {+ local _+ for _ in $(seq 1 80); do+ healthy "${1:-8799}" && return 0+ sleep 3+ done+ fail "the server did not answer again"+}+container_id() { podman inspect -f '{{.Id}}' openmausbot 2>/dev/null || true; }+in_server() { podman exec openmausbot "$@"; }++step "this host: rootless Podman, and systemd for this user without a login (linger, as a server has it)"+podman version | tee "$OUT/podman-version.txt"+if ! grep -q "^$(id -un):" /etc/subuid; then+ sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 "$(id -un)"+ podman system migrate+fi+sudo loginctl enable-linger "$(id -un)"+XDG_RUNTIME_DIR="/run/user/$(id -u)"+export XDG_RUNTIME_DIR+for _ in $(seq 1 30); do [ -S "$XDG_RUNTIME_DIR/bus" ] && break; sleep 1; done+export DBUS_SESSION_BUS_ADDRESS="unix:path=$XDG_RUNTIME_DIR/bus"+systemctl --user show-environment >/dev/null || fail "no systemd for this user"+finding "host: $(sed -n 's/^PRETTY_NAME=//p' /etc/os-release | tr -d '"'), kernel $(uname -r), $(uname -m), Podman $(podman version --format '{{.Client.Version}}'), $(podman info --format '{{.Host.NetworkBackend}} network, {{.Host.CgroupsVersion}}, rootless={{.Host.Security.Rootless}}')"+finding "host: kernel.apparmor_restrict_unprivileged_userns=$(cat /proc/sys/kernel/apparmor_restrict_unprivileged_userns 2>/dev/null || echo absent)"++step "the repository's fake engine, wired into the data folder before the first start"+fake="$DIR/data/.openmausbot/fake-engine"+mkdir -p "$fake"+for file in fake-claude-cli launch-note room-handoff-agent stream-script cleanup; do cp "$ROOT/server/testing/$file.ts" "$fake/"; done+chmod 755 "$fake/fake-claude-cli.ts"+cat >"$DIR/data/.openmausbot/config.json" <<'JSON'+{+ "features": { "smartSetupChoices": false },+ "instances": {+ "claude": { "driver": "claudeAgent", "displayName": "E2E fake engine", "config": { "cli": "/data/.openmausbot/fake-engine/fake-claude-cli.ts" } }+ }+}+JSON+chmod 700 "$DIR/data"++step "install $OLD_VERSION as this user's service"+OMB_INSTALL_IMAGE="$REPO:v$OLD_VERSION" "${INSTALL[@]}" >"$OUT/install.txt" 2>&1 || { cat "$OUT/install.txt"; fail "the install failed"; }+cat "$OUT/install.txt"+contains "$OUT/install.txt" "MausBot is running as your user's service (openmausbot), on http://127.0.0.1:8799." "the install did not finish"+contains "$OUT/install.txt" "It starts at boot, without anyone logged in." "the install did not see linger"+grep -q "^Image=$REPO@sha256:[0-9a-f]\{64\}$" "$UNIT" || fail "the unit does not pin the image by digest: $(grep '^Image=' "$UNIT")"+grep -q "^UserNS=keep-id:uid=[0-9]*,gid=[0-9]*$" "$UNIT" || fail "the unit does not map the image's user to this one"+cp "$UNIT" "$OUT/openmausbot.container"+/usr/libexec/podman/quadlet -dryrun -user >"$OUT/quadlet-dryrun.txt" 2>&1 || true+contains "$OUT/quadlet-dryrun.txt" "---openmausbot.service---" "quadlet did not make the service"+systemctl --user is-active --quiet openmausbot || fail "the service is not active"+healthy || fail "the server does not answer on 127.0.0.1:8799"+ss -ltnH >"$OUT/listening.txt"+grep -q "127.0.0.1:8799 " "$OUT/listening.txt" || fail "nothing listens on 127.0.0.1:8799: $(cat "$OUT/listening.txt")"+if grep -qE "(0\.0\.0\.0|\*|\[::\]):8799 " "$OUT/listening.txt"; then fail "the server answers beyond this machine without --lan"; fi+[ "$(stat -c %u "$DIR/data")" = "$(id -u)" ] || fail "the data folder is not this user's"+[ -z "$(find "$DIR/data" ! -user "$(id -u)" -print -quit)" ] || fail "the server wrote files that are not this user's on the host: $(find "$DIR/data" ! -user "$(id -u)" | head -n 5)"+[ "$(stat -c %a "$DIR/.env")" = 600 ] && [ "$(stat -c %a "$DIR/server.env")" = 600 ] || fail "the settings are readable by others"+{ [ -x "$DIR/update.sh" ] && cmp -s "$ROOT/deploy/update.sh" "$DIR/update.sh"; } || fail "update.sh was not placed"+finding "install: service active, 127.0.0.1:8799 only, image pinned by digest, data owned by the user on the host"++step "running it again changes nothing"+first=$(container_id)+"${INSTALL[@]}" >"$OUT/install-again.txt" 2>&1 || { cat "$OUT/install-again.txt"; fail "the second run failed"; }+contains "$OUT/install-again.txt" "the one already installed" "the second run did not keep the installed version"+[ "$(container_id)" = "$first" ] || fail "the second run restarted the server"+finding "idempotent: a second run kept the version and did not restart the server"++step "a bot turn with the fake engine"+in_server openmausbot new-bot Probe --json >"$OUT/new-bot.json" 2>"$OUT/new-bot.err" || { cat "$OUT/new-bot.json" "$OUT/new-bot.err"; fail "new-bot failed"; }+in_server openmausbot run Probe "hello from the podman e2e" --json --timeout 2m >"$OUT/run.json" 2>"$OUT/run.err" || { cat "$OUT/run.json" "$OUT/run.err"; fail "the turn failed"; }+contains "$OUT/run.json" "hello from fake claude" "the turn did not answer with the fake engine's reply"+finding "turn: new-bot + run answered \"hello from fake claude\" through the server in the rootless container"++step "Chrome in the server's container"+if in_server sh -c 'agent-browser open "data:text/html,<title>podman-e2e</title>" >/dev/null && agent-browser get title; agent-browser close >/dev/null 2>&1 || true' >"$OUT/chrome.txt" 2>&1 &&+ grep -q podman-e2e "$OUT/chrome.txt"; then+ finding "chrome: agent-browser started the image's browser and read a page title, with no extra flags"+else+ cat "$OUT/chrome.txt"+ fail "the image's browser did not start in the rootless container"+fi++step "the bots' sandbox (bubblewrap) in a rootless container: the first setting that lets it run"+image=$(sed -n 's/^Image=//p' "$UNIT")+userns=$(sed -n 's/^UserNS=//p' "$UNIT")+printf 'FROM %s\nUSER root\nRUN apt-get update && apt-get install -y --no-install-recommends bubblewrap socat && rm -rf /var/lib/apt/lists/*\nUSER maus\n' "$image" >"$OUT/Containerfile.box"+podman build -q -t localhost/omb-box-probe:e2e -f "$OUT/Containerfile.box" "$OUT" >/dev/null+probe=(--unshare-user --unshare-pid --unshare-net --unshare-ipc --unshare-uts --die-with-parent --ro-bind /usr /usr+ --symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64 --proc /proc --dev /dev --tmpfs /tmp /bin/true)+box_rung=""+for rung in "default" "seccomp=repository profile" "unmask=/proc" "apparmor=unconfined"; do+ extra=()+ case "$rung" in+ seccomp*) extra=(--security-opt "seccomp=$ROOT/connector/profiles/seccomp-omb-home.json") ;;+ unmask*) extra=(--security-opt "seccomp=$ROOT/connector/profiles/seccomp-omb-home.json" --security-opt unmask=/proc/*) ;;+ apparmor*) extra=(--security-opt "seccomp=$ROOT/connector/profiles/seccomp-omb-home.json" --security-opt unmask=/proc/* --security-opt apparmor=unconfined) ;;+ esac+ if podman run --rm --userns "$userns" ${extra[@]+"${extra[@]}"} --entrypoint bwrap localhost/omb-box-probe:e2e "${probe[@]}" >"$OUT/bwrap-$rung.txt" 2>&1; then+ box_rung=$rung+ break+ fi+ finding "bot box: bubblewrap refused with $rung: $(head -c 300 "$OUT/bwrap-$rung.txt" | tr '\n' ' ')"+done+if [ -n "$box_rung" ]; then+ finding "bot box: bubblewrap ran its probe with: $box_rung"+ podman run --rm --userns "$userns" --network host -e OMB_BOT_BOX=1 -e OMB_DATA_DIR=/tmp/box-data ${extra[@]+"${extra[@]}"} \+ --entrypoint node localhost/omb-box-probe:e2e dist-server/bot-box/box-check.js --public=none >"$OUT/box-check.json" 2>&1 || true+ finding "bot box self-check (published image + bubblewrap): $(head -c 600 "$OUT/box-check.json" | tr '\n' ' ')"+else+ finding "bot box: bubblewrap did not run in a rootless container with any of the settings tried"+fi+podman rmi -f localhost/omb-box-probe:e2e >/dev/null 2>&1 || true++step "a server that is killed is started again by systemd"+before=$(container_id)+launcher=$(podman top openmausbot hpid args | awk '/server-launcher/ { print $1; exit }')+[ -n "$launcher" ] || fail "no server process to kill"+kill -9 "$launcher"+for _ in $(seq 1 40); do [ "$(container_id)" != "$before" ] && [ -n "$(container_id)" ] && break; sleep 2; done+healthy_again+[ "$(container_id)" != "$before" ] || fail "the killed server was not started again"+finding "restart: kill -9 of server-launcher; systemd started a new container ($(systemctl --user show -p NRestarts --value openmausbot) restart(s)) and it answered"++step "a restart of this user's systemd (what a boot does, with linger) starts it again"+sudo systemctl restart "user@$(id -u).service"+for _ in $(seq 1 30); do systemctl --user show-environment >/dev/null 2>&1 && break; sleep 1; done+healthy_again+systemctl --user is-active --quiet openmausbot || fail "the service did not start with the user's systemd"+finding "boot: after systemctl restart user@$(id -u).service the service came back by itself (WantedBy=default.target)"++step "--lan: other devices on this network reach it, and must pair; --local takes it back"+"${INSTALL[@]}" --lan >"$OUT/install-lan.txt" 2>&1 || { cat "$OUT/install-lan.txt"; fail "the --lan run failed"; }+healthy_again+address=$(ip -4 -o route get 1.1.1.1 | sed -n 's/.* src \([0-9.]*\).*/\1/p')+ss -ltnH | grep -qE "(0\.0\.0\.0|\*):8799 " || fail "the server does not listen beyond loopback with --lan"+from_lan=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://$address:8799/api/bots" || true)+from_here=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://127.0.0.1:8799/api/bots" || true)+[ "$from_lan" = 403 ] || [ "$from_lan" = 401 ] || fail "a request from $address got $from_lan from /api/bots, not a refusal"+[ "$from_here" = 200 ] || fail "this machine's own request got $from_here from /api/bots"+"${INSTALL[@]}" --local >"$OUT/install-local.txt" 2>&1 || { cat "$OUT/install-local.txt"; fail "the --local run failed"; }+healthy_again+if ss -ltnH | grep -qE "(0\.0\.0\.0|\*):8799 "; then fail "--local left the server listening beyond loopback"; fi+finding "lan: with --lan, $address got $from_lan and 127.0.0.1 got $from_here on /api/bots; --local went back to loopback"++step "update to $NEW_VERSION, through update.sh"+"$DIR/update.sh" --version "$NEW_VERSION" >"$OUT/update.txt" 2>&1 || { cat "$OUT/update.txt"; fail "the update failed"; }+cat "$OUT/update.txt"+contains "$OUT/update.txt" "Updated from $OLD_VERSION to $NEW_VERSION." "the update did not finish"+new_image=$(sed -n 's/^Image=//p' "$UNIT")+{ [ "$new_image" != "$image" ] && grep -qx "OMB_IMAGE=$new_image" "$DIR/.env"; } || fail "the unit and .env do not name the new image"+[ "$(podman inspect -f '{{.Image}}' openmausbot)" = "$(podman image inspect -f '{{.Id}}' "$new_image")" ] || fail "the server does not run the new image"+in_server sh -c 'curl -sf http://127.0.0.1:8799/.well-known/openmausbot/environment' | grep -q "\"version\":\"$NEW_VERSION\"" || fail "the server does not say it is $NEW_VERSION"+in_server openmausbot bots --json | grep -q Probe || fail "the bot made before the update is gone"+podman volume ls -q | grep -q "^openmausbot_data-before-update-" || fail "no copy of the data was kept"+finding "update: $OLD_VERSION -> $NEW_VERSION by digest, data copied to a Podman volume first, the bot made before it still there"++step "an update to a version that cannot start is rolled back"+printf 'FROM %s\nCMD ["sh", "-c", "echo broken on purpose; exit 3"]\n' "$new_image" >"$OUT/Containerfile.broken"+podman build -q -t localhost/omb-broken:e2e -f "$OUT/Containerfile.broken" "$OUT" >/dev/null+status=0+OMB_UPDATE_WAIT_S=90 "$DIR/update.sh" --image localhost/omb-broken:e2e --allow-older >"$OUT/update-broken.txt" 2>&1 || status=$?+cat "$OUT/update-broken.txt"+[ "$status" = 1 ] || fail "the broken update exited $status, not 1"+contains "$OUT/update-broken.txt" "Your server runs $NEW_VERSION again, with its data as it was before the update." "the broken update was not rolled back"+[ "$(sed -n 's/^Image=//p' "$UNIT")" = "$new_image" ] || fail "the unit does not name $NEW_VERSION again"+healthy_again+in_server openmausbot bots --json | grep -q Probe || fail "the bot is gone after the rollback"+finding "rollback: an image that exits at start was rolled back to $NEW_VERSION with its data; the service answers"+podman rmi -f localhost/omb-broken:e2e >/dev/null 2>&1 || true++step "uninstall keeps the data"+"${INSTALL[@]}" --uninstall >"$OUT/uninstall.txt" 2>&1 || { cat "$OUT/uninstall.txt"; fail "the uninstall failed"; }+cat "$OUT/uninstall.txt"+[ ! -e "$UNIT" ] || fail "the unit is still there"+if systemctl --user is-active --quiet openmausbot; then fail "the service still runs"; fi+if healthy; then fail "the server still answers"; fi+[ -f "$DIR/data/.openmausbot/config.json" ] || fail "the uninstall removed the data"+finding "uninstall: the service and its unit are gone, the data stays"++step "clean up"+podman volume ls -q | grep "^openmausbot_data-before-update-" | xargs -r podman volume rm -f >/dev/null+podman unshare rm -rf "$DIR"+podman image ls --format '{{.Repository}}:{{.Tag}} {{.Size}}' | tee "$OUT/images.txt"+echo+echo "findings:"+cat "$FINDINGS"diff --git a/deploy/podman/README.md b/deploy/podman/README.mdindex 20e076f80f..4a83eb8f0c 100644--- a/deploy/podman/README.md+++ b/deploy/podman/README.md@@ -1,5 +1,10 @@# Self-host the full stack with rootless Podman+For the server alone as your user's systemd service, with updates and a way+back, one command is enough: `install.sh` here+([Podman (rootless, as a service)](../../docs/self-hosting.md#podman-rootless-as-a-service)).+The recipe below builds from a checkout and adds Caddy and per-bot desktops.+Run the OpenMausBot server, Caddy, and per-bot Linux desktops with one Podmanengine. Docker Engine, Docker Desktop, and Docker Compose are not required;`podman-compose` provides the Compose commands. The existingdiff --git a/deploy/podman/install.sh b/deploy/podman/install.shnew file mode 100755index 0000000000..638a891fe4--- /dev/null+++ b/deploy/podman/install.sh@@ -0,0 +1,406 @@+#!/bin/sh+# MausBot's server as your own user's service, with rootless Podman: no root, no Docker. One line, run as yourself:+#+# curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy/podman/install.sh | sh+# ... | sh -s -- --lan also answer other devices on this network (private addresses only)+# ... | sh -s -- --uninstall stops and removes the service; keeps your data+#+# It writes a Quadlet unit (~/.config/containers/systemd/openmausbot.container) that runs the published server image,+# pinned by its digest, as your user: systemd restarts it when it fails, and starts it at boot once your user may run+# services without being logged in (it prints the one `loginctl enable-linger` line for that; it never runs sudo).+# Your data stays in ~/.local/share/openmausbot/data. Running it again repairs the install and never touches your data.+# Updates, with a copy of the data first and a way back: ~/.local/share/openmausbot/update.sh+#+# Nothing runs until the last line calls main, so a download that is cut off part-way runs nothing. It sends no+# telemetry. It contacts the image registry (ghcr.io), GitHub's release list and this repository's files.+set -eu++settings() {+ IMAGE_REPO=ghcr.io/milind-soni/openmausbot+ STABLE_URL=https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json+ RELEASES_URL=https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest+ REPOSITORY_FILES=https://raw.githubusercontent.com/milind-soni/OpenMausBot+ # One copy of this repository's files to use instead (https://… or file:///…), as deploy/install.sh takes it.+ SOURCE_ASKED="${OMB_INSTALL_SOURCE:-}"+ INSTALL_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/openmausbot"+ UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/containers/systemd"+ NAME=openmausbot+ HEALTH_WAIT_S="${OMB_INSTALL_HEALTH_WAIT_S:-240}"+ MODE=install+ LAN=""+ PORT=""+ PUBLIC_URL=""+ IMAGE=""+}++say() { printf '%s\n' "$*"; }+ok() { printf ' ok %s\n' "$*"; }+note() { printf ' note %s\n' "$*"; }+fail() {+ printf '\n%s\n' "$*" >&2+ exit 1+}++usage() {+ say "Usage: curl -fsSL $REPOSITORY_FILES/main/deploy/podman/install.sh | sh -s -- [options]"+ say ""+ say " --lan also answer other devices on this network (private addresses only, plain http)"+ say " --local answer this machine only again (the default)"+ say " --port N the server's port on this machine (default 8799; webhooks use the next one)"+ say " --public-url URL the HTTPS address a proxy or tunnel in front of it serves, for pairing links"+ say " --dir PATH where the data and settings live (default ~/.local/share/openmausbot)"+ say " --uninstall stop and remove the service; keeps the data"+}++parse() {+ while [ $# -gt 0 ]; do+ case "$1" in+ --lan) LAN=1 ;;+ --local) LAN=0 ;;+ --uninstall) MODE=uninstall ;;+ --port | --public-url | --dir)+ [ $# -ge 2 ] || fail "$1 needs a value."+ case "$1" in+ --port) PORT=$2 ;;+ --public-url) PUBLIC_URL=$2 ;;+ --dir) INSTALL_DIR=$2 ;;+ esac+ shift+ ;;+ -h | --help)+ usage+ exit 0+ ;;+ *) fail "Unknown option $1. Run with --help for the options." ;;+ esac+ shift+ done+ case "$PORT" in+ "") ;;+ *[!0-9]*) fail "--port takes a number, like 8799." ;;+ *) if [ "$PORT" -lt 1024 ] || [ "$PORT" -gt 65534 ]; then fail "--port takes a number from 1024 to 65534."; fi ;;+ esac+ case "$PUBLIC_URL" in+ "" | https://*) ;;+ *) fail "--public-url takes the https:// address people open, like https://maus.example.com." ;;+ esac+ case "$PUBLIC_URL" in *[!A-Za-z0-9:/._-]*) fail "--public-url takes a plain address, like https://maus.example.com." ;; esac+ case "$INSTALL_DIR" in+ /*) ;;+ *) fail "--dir takes an absolute path." ;;+ esac+ case "$INSTALL_DIR" in *[!A-Za-z0-9/._-]*) fail "--dir takes a path of letters, digits, dots, dashes and slashes." ;; esac+ DATA_DIR="$INSTALL_DIR/data"+ UNIT="$UNIT_DIR/$NAME.container"+}++# The user's own systemd: `systemctl --user` must reach it, which a login session or linger gives.+user_systemd() {+ if [ -z "${XDG_RUNTIME_DIR:-}" ] && [ -d "/run/user/$(id -u)" ]; then+ XDG_RUNTIME_DIR="/run/user/$(id -u)"+ export XDG_RUNTIME_DIR+ fi+ systemctl --user show-environment >/dev/null 2>&1+}++quadlet_binary() {+ for candidate in /usr/libexec/podman/quadlet /usr/lib/podman/quadlet /usr/local/libexec/podman/quadlet; do+ if [ -x "$candidate" ]; then+ printf '%s' "$candidate"+ return 0+ fi+ done+ return 1+}++podman_version() { podman version --format '{{.Client.Version}}' 2>/dev/null || podman --version 2>/dev/null | sed 's/.* //'; }++# Podman 4.4 brought Quadlet; keep-id with a uid of its own, and a health check that restarts, came by 4.6.+check_host() {+ say "Checking this machine..."+ [ "$(uname -s)" = Linux ] || fail "This installs a systemd service, which needs Linux. On a Mac or Windows, use the desktop app or Docker."+ [ "$(id -u)" != 0 ] || fail "Run this as the user the server should run as, not as root (no sudo): it installs a service of your own."+ command -v podman >/dev/null 2>&1 || fail "Podman is not installed. Install it with your system's packages (sudo apt-get install -y podman, sudo dnf install -y podman), then run this again."+ version=$(podman_version)+ major=$(printf '%s' "$version" | cut -d. -f1)+ minor=$(printf '%s' "$version" | cut -d. -f2)+ case "$major.$minor" in+ *[!0-9.]* | .*) fail "Could not tell which Podman this is (podman version said: ${version:-nothing})." ;;+ esac+ if [ "$major" -lt 4 ] || { [ "$major" -eq 4 ] && [ "$minor" -lt 6 ]; }; then+ fail "This needs Podman 4.6 or newer, for its systemd units; this machine has $version. Ubuntu 24.04, Debian 13 and Fedora 39 or newer have it."+ fi+ ok "Podman $version"+ [ "$(podman info --format '{{.Host.Security.Rootless}}' 2>/dev/null || true)" = true ] ||+ fail "Podman does not run rootless for this user. Give the user subordinate ids (sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 $(id -un)), then run this again."+ ok "rootless"+ QUADLET=$(quadlet_binary) || fail "Podman's systemd generator (quadlet) is missing. Install your distribution's full podman package, then run this again."+ user_systemd || fail "systemd for your user is not reachable (systemctl --user). Log in to this machine directly or over SSH, not with su or sudo, or run: sudo loginctl enable-linger $(id -un) then run this again."+ ok "systemd for your user"+}++linger_on() { [ "$(loginctl show-user "$(id -un)" -p Linger --value 2>/dev/null || true)" = yes ]; }++fetch() { # url destination: 1 when it cannot be had+ tmp_fetch=$(mktemp "$2.XXXXXX")+ if curl -fsSL --max-time 60 "$1" -o "$tmp_fetch" 2>/dev/null && [ -s "$tmp_fetch" ]; then+ mv "$tmp_fetch" "$2"+ return 0+ fi+ rm -f "$tmp_fetch"+ return 1+}++write_file() { # path [mode], the content on standard input: replaced in one step+ tmp_file=$(mktemp "$1.XXXXXX")+ cat >"$tmp_file"+ chmod "${2:-644}" "$tmp_file"+ mv "$tmp_file" "$1"+}++env_value() { # file name+ sed -n "s/^$2=//p" "$1" 2>/dev/null | tail -n 1+}++set_env() { # file name value: that one line, every other line as the person wrote it+ { if [ -f "$1" ]; then grep -v "^$2=" "$1" || true; fi; printf '%s=%s\n' "$2" "$3"; } | write_file "$1" 600+}++unset_env() { # file name+ if grep -q "^$2=" "$1" 2>/dev/null; then { grep -v "^$2=" "$1" || true; } | write_file "$1" 600; fi+}++# The image by digest: the one update.sh pinned, else the stable channel's, else the newest release's.+choose_image() {+ asked="${OMB_INSTALL_IMAGE:-}"+ pinned=$(env_value "$INSTALL_DIR/.env" OMB_IMAGE)+ if [ -n "$asked" ]; then+ case "$asked" in *[!A-Za-z0-9/:._@-]*) fail "OMB_INSTALL_IMAGE is not an image name." ;; esac+ IMAGE=$asked+ ok "version: $IMAGE, as asked"+ elif [ -n "$pinned" ]; then+ IMAGE=$pinned+ ok "version: the one already installed ($IMAGE); update.sh changes it"+ else+ stable=$(curl -fsS --max-time 20 "$STABLE_URL" 2>/dev/null || true)+ IMAGE=$(printf '%s' "$stable" | sed -n 's/.*"image": *"\([^"]*\)".*/\1/p' | head -n 1)+ case "$IMAGE" in+ "$IMAGE_REPO"@sha256:*) ok "version: the stable channel" ;;+ *)+ release=$(curl -fsS --max-time 20 "$RELEASES_URL" 2>/dev/null | sed -n 's/.*"tag_name": *"\(v[0-9][0-9.]*\)".*/\1/p' | head -n 1)+ [ -n "$release" ] || fail "The newest MausBot release could not be read from api.github.com. Check this machine's outbound HTTPS, then run this again."+ IMAGE="$IMAGE_REPO:$release"+ ok "version: $release, the newest release"+ ;;+ esac+ fi+ say "Downloading MausBot (the first time is about a gigabyte)..."+ podman pull -q "$IMAGE" >/dev/null || fail "MausBot could not be downloaded ($IMAGE; Podman's message is above). Check this machine's outbound HTTPS, then run this again."+ # A tag moves; the digest does not, so a restart never brings a different version than update.sh chose.+ case "$IMAGE" in+ *@sha256:*) ;;+ "$IMAGE_REPO":*)+ digest=$(podman image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE" 2>/dev/null | grep "^$IMAGE_REPO@sha256:" | head -n 1 || true)+ [ -z "$digest" ] || IMAGE=$digest+ ;;+ esac+}++# The image's own user and group (its `maus`): the container runs as them, mapped to this user by keep-id, so the data+# folder stays this user's own on the host. Never a recursive chown (`:U`).+image_user() {+ RUN_UID=$(podman run --rm --network none --entrypoint id "$IMAGE" -u 2>/dev/null || true)+ RUN_GID=$(podman run --rm --network none --entrypoint id "$IMAGE" -g 2>/dev/null || true)+ case "$RUN_UID:$RUN_GID" in+ *[!0-9:]* | : | :* | *:) fail "The MausBot image did not say which user it runs as. Run this again; if it still fails, send us this line." ;;+ esac+}++selinux_on() { command -v selinuxenabled >/dev/null 2>&1 && selinuxenabled; }++write_settings() {+ SETTINGS_BEFORE=$(cat "$INSTALL_DIR/server.env" 2>/dev/null || true)+ mkdir -p "$INSTALL_DIR" "$UNIT_DIR"+ chmod 700 "$INSTALL_DIR"+ [ -d "$DATA_DIR" ] || mkdir -m 700 "$DATA_DIR"+ if [ ! -f "$INSTALL_DIR/server.env" ]; then+ write_file "$INSTALL_DIR/server.env" 600 <<'ENV'+# The server's settings (docs/self-hosting.md). The Podman installer sets OMB_PORT, OMB_WEBHOOK_PORT, OMB_LAN and+# OMB_PUBLIC_URL when asked, and keeps every other line. Apply a change with: systemctl --user restart openmausbot+OMB_PORT=8799+OMB_WEBHOOK_PORT=8800+OMB_SERVER_NAME=mausbot-podman+OMB_CLI_PREFIX=podman exec -it openmausbot openmausbot+ENV+ fi+ if [ -n "$PORT" ]; then+ set_env "$INSTALL_DIR/server.env" OMB_PORT "$PORT"+ set_env "$INSTALL_DIR/server.env" OMB_WEBHOOK_PORT "$((PORT + 1))"+ fi+ case "$LAN" in+ 1) set_env "$INSTALL_DIR/server.env" OMB_LAN 1 ;;+ 0) unset_env "$INSTALL_DIR/server.env" OMB_LAN ;;+ esac+ if [ -n "$PUBLIC_URL" ]; then+ set_env "$INSTALL_DIR/server.env" OMB_PUBLIC_URL "$PUBLIC_URL"+ set_env "$INSTALL_DIR/server.env" OMB_WEBHOOK_PUBLIC_URL "$PUBLIC_URL"+ fi+ SERVER_PORT=$(env_value "$INSTALL_DIR/server.env" OMB_PORT)+ SERVER_PORT=${SERVER_PORT:-8799}+ # The install's own settings, which update.sh reads and pins: the image, nothing else.+ set_env "$INSTALL_DIR/.env" OMB_IMAGE "$IMAGE"+ # update.sh knows this install by this file: the unit it updates.+ printf '%s\n' "$UNIT" | write_file "$INSTALL_DIR/podman.unit" 600+}++unit_text() {+ label=""+ if selinux_on; then label=":Z"; fi+ cat <<UNIT+# Written by MausBot's Podman installer (deploy/podman/install.sh), and written again each time it runs. The server's+# settings are in $INSTALL_DIR/server.env; update.sh changes Image= below.+[Unit]+Description=MausBot server (rootless Podman)+Documentation=https://github.com/milind-soni/OpenMausBot/blob/main/docs/self-hosting.md#podman-rootless-as-a-service++[Container]+ContainerName=$NAME+Image=$IMAGE+# The host's network, as a server started with npx has it: it listens on 127.0.0.1 (OMB_LAN=1: private addresses too),+# a program on this machine counts as its owner, and every other device pairs. No port is forwarded into a container.+Network=host+# The image's user is this user on the host, so the data folder stays yours.+UserNS=keep-id:uid=$RUN_UID,gid=$RUN_GID+Volume=$DATA_DIR:/data$label+EnvironmentFile=$INSTALL_DIR/server.env+# Chrome's shared memory, as the Docker install gives it. The image brings its own init (tini).+ShmSize=512m+HealthCmd=curl -sf http://127.0.0.1:$SERVER_PORT/api/health | grep -q openmausbot+HealthInterval=30s+HealthTimeout=5s+HealthRetries=3+HealthStartPeriod=120s+# A server that stops answering is stopped, and systemd starts it again.+HealthOnFailure=kill++[Service]+Restart=on-failure+RestartSec=5+# Room to download the image again if it was removed, and for a slow first start.+TimeoutStartSec=900+TimeoutStopSec=70++[Install]+WantedBy=default.target+UNIT+}++write_unit() {+ CHANGED=no+ # A changed unit, or changed settings (--lan, --port), take a restart; a run that changes nothing restarts nothing.+ if [ ! -f "$UNIT" ] || [ "$(unit_text)" != "$(cat "$UNIT")" ] || [ "$SETTINGS_BEFORE" != "$(cat "$INSTALL_DIR/server.env")" ]; then CHANGED=yes; fi+ unit_text | write_file "$UNIT"+ # A key this Podman does not know would otherwise leave only "unit not found".+ check=$(QUADLET_UNIT_DIRS="$UNIT_DIR" "$QUADLET" -dryrun -user 2>&1 || true)+ case "$check" in+ *"---$NAME.service---"*) ;;+ *) fail "Podman could not read the unit it was given ($UNIT): $(printf '%s' "$check" | grep -i "$NAME\|error" | head -n 3)" ;;+ esac+ systemctl --user daemon-reload+}++# update.sh (deploy/update.sh) updates with a copy of the data and a way back. Its copy from the installed version's tag+# when that one knows a Podman install, else the newest.+place_update() {+ version=$(podman image inspect -f '{{index .Config.Labels "org.opencontainers.image.version"}}' "$IMAGE" 2>/dev/null |+ sed -n 's/^v\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$/v\1/p' | head -n 1 || true)+ for source in ${SOURCE_ASKED:-${version:+$REPOSITORY_FILES/$version} $REPOSITORY_FILES/main}; do+ if fetch "$source/deploy/update.sh" "$INSTALL_DIR/update.sh.new" && grep -q 'podman.unit' "$INSTALL_DIR/update.sh.new"; then+ chmod 755 "$INSTALL_DIR/update.sh.new"+ mv "$INSTALL_DIR/update.sh.new" "$INSTALL_DIR/update.sh"+ return 0+ fi+ rm -f "$INSTALL_DIR/update.sh.new"+ done+ note "update.sh could not be downloaded; run this again later to place it."+}++answers() { curl -sf --max-time 5 "http://127.0.0.1:$SERVER_PORT/api/health" 2>/dev/null | grep -q openmausbot; }++wait_healthy() {+ waited=0+ while [ "$waited" -lt "$HEALTH_WAIT_S" ]; do+ if answers; then return 0; fi+ sleep 3+ waited=$((waited + 3))+ done+ return 1+}++port_taken() { ss -ltnH "( sport = :$1 )" 2>/dev/null | grep -q .; }++start_service() {+ if ! systemctl --user is-active --quiet "$NAME" && port_taken "$SERVER_PORT"; then+ fail "Something else on this machine already listens on port $SERVER_PORT (another MausBot server?). Stop it, or run this again with --port and a free port, like --port 8811."+ fi+ if [ "$CHANGED" = yes ] || ! systemctl --user is-active --quiet "$NAME"; then+ say "Starting MausBot..."+ systemctl --user restart "$NAME" ||+ fail "MausBot could not be started. Its log: journalctl --user -u $NAME -n 50"+ fi+ wait_healthy || fail "MausBot started but did not answer within $HEALTH_WAIT_S seconds. Its log: journalctl --user -u $NAME -n 50"+}++finish() {+ say ""+ say "MausBot is running as your user's service ($NAME), on http://127.0.0.1:$SERVER_PORT."+ if [ "$(env_value "$INSTALL_DIR/server.env" OMB_LAN)" = 1 ]; then say "Other devices on this network can pair over plain http; nothing on the open internet can reach it."; fi+ say ""+ say " Pair a device podman exec -it $NAME openmausbot pair"+ say " Log journalctl --user -u $NAME -f"+ say " Update $INSTALL_DIR/update.sh"+ say " Data $DATA_DIR"+ say ""+ if linger_on; then+ say "It starts at boot, without anyone logged in."+ else+ say "It stops when you log out, and does not start at boot, until your user may run services on its own. Once, as an"+ say "administrator:"+ say ""+ say " sudo loginctl enable-linger $(id -un)"+ fi+}++run_install() {+ check_host+ choose_image+ image_user+ write_settings+ write_unit+ place_update+ start_service+ finish+}++run_uninstall() {+ user_systemd || fail "systemd for your user is not reachable (systemctl --user). Log in to this machine directly or over SSH, then run this again."+ systemctl --user stop "$NAME" 2>/dev/null || true+ rm -f "$UNIT"+ systemctl --user daemon-reload 2>/dev/null || true+ rm -f "$INSTALL_DIR/podman.unit"+ say "MausBot's service is stopped and removed. Your data stays in $DATA_DIR."+ say "To remove the data too (some files belong to the container's other ids, so through Podman):"+ say " podman unshare rm -rf $INSTALL_DIR"+ say "The downloaded images: podman image ls ghcr.io/milind-soni/openmausbot"+}++main() {+ settings+ parse "$@"+ case "$MODE" in+ install) run_install ;;+ uninstall) run_uninstall ;;+ esac+}++main "$@"diff --git a/deploy/update.sh b/deploy/update.shindex 142df1ea25..cd48a57a14 100755--- a/deploy/update.sh+++ b/deploy/update.sh@@ -66,7 +66,7 @@ for arg in "$@"; dodoneif [ -z "$DIR" ]; thenDIR=$(cd "$(dirname "$0")" && pwd)- if [ ! -f "$DIR/docker-compose.yml" ] && [ ! -f "$DIR/compose.yaml" ] && [ -f /opt/openmausbot/compose.yaml ]; then DIR=/opt/openmausbot; fi+ if [ ! -f "$DIR/docker-compose.yml" ] && [ ! -f "$DIR/compose.yaml" ] && [ ! -f "$DIR/podman.unit" ] && [ -f /opt/openmausbot/compose.yaml ]; then DIR=/opt/openmausbot; fifiSTATE="$DIR/.update"JOURNAL="$STATE/journal"@@ -76,6 +76,14 @@ LOG="$STATE/update.log"cd "$DIR" 2>/dev/null || { printf '%s\n' "There is no folder $DIR."; exit 4; }# The pin is read from .env, never from the shell that happens to run this.unset OMB_IMAGE+# A rootless Podman install (deploy/podman/install.sh) runs the server as its user's own systemd service, from the Quadlet+# unit that podman.unit names. The steps are the same, through Podman and `systemctl --user` (podman_compose below).+UNIT=""+STORE=Docker+if [ -f podman.unit ]; then+ UNIT=$(head -n 1 podman.unit)+ STORE=Podman+fi# A step interrupted while its output goes to the log still speaks to the terminal.exec 3>&1@@ -107,6 +115,39 @@ image_id() { docker image inspect -f '{{.Id}}' "$1" 2>/dev/null; }published_ref() { docker image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$1" 2>/dev/null | grep "^$REPO@" | head -n 1; }# The released version an image is labelled with; nothing for a build of main, whose label is the branch.image_version() { docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.version"}}' "$1" 2>/dev/null | sed -n 's/^v\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$/\1/p'; }+if [ -n "$UNIT" ]; then+ # The unit's name is its container's: openmausbot.container runs openmausbot.service, container openmausbot.+ SERVER_UNIT=$(basename "$UNIT" .container)+ # Podman takes the same commands as Docker here. The helpers mount the data folder, which SELinux labels for the+ # server's container alone, so they run without a label of their own.+ docker() { if [ "$1" = run ]; then shift; podman run --security-opt label=disable "$@"; else podman "$@"; fi; }+ compose() { podman_compose "$@"; }+fi+# Image= in the unit follows OMB_IMAGE in .env, the one place an update pins it.+unit_image() {+ local image+ image=$(sed -n 's/^OMB_IMAGE=//p' .env 2>/dev/null | tail -n 1)+ printf '%s' "$image" | grep -Eqx '[A-Za-z0-9/:._@-]+' || return 1+ [ -f "$UNIT" ] && grep -q '^Image=' "$UNIT" || return 1+ sed "s|^Image=.*|Image=$image|" "$UNIT" >"$UNIT.update.tmp" && mv "$UNIT.update.tmp" "$UNIT"+}+# The Compose commands this script uses, for the one service of a Podman install. It has no Caddy.+podman_compose() {+ local verb=$1+ shift+ case "$verb" in+ stop) systemctl --user stop "$SERVER_UNIT.service" ;;+ up) unit_image && systemctl --user daemon-reload && systemctl --user restart "$SERVER_UNIT.service" ;;+ ps) if [ "${1:-}" = -aq ]; then podman ps -aq --filter "name=^$SERVER_UNIT\$"; fi ;;+ exec)+ # `exec -T omb …`: the container is the unit's, and nothing is forwarded to its standard input.+ shift 2+ podman exec "$SERVER_UNIT" "$@" </dev/null+ ;;+ logs) journalctl --user -u "$SERVER_UNIT.service" -n 40 -o cat --no-pager ;;+ *) return 1 ;;+ esac+}name_of() { if [ -n "${2:-}" ]; then printf '%s' "$2"; else printf '%s' "$1" | sed 's/^.*sha256:\(.\{12\}\).*$/image \1/'; fi; }old_name() { name_of "${J_previous:-$J_previous_id}" "$J_previous_version"; }new_name() { name_of "$J_target" "$J_version"; }@@ -552,7 +593,7 @@ finish() {if old_repository_layout; thensay "Note: this docker-compose.yml runs Caddy in the server's network, so HTTPS goes down whenever the server restarts without Caddy (a crash, docker compose restart). git pull brings the current one, then: docker compose up -d"fi- say "The data from before the update is kept in the Docker volume $J_backup until the next update."+ say "The data from before the update is kept in the $STORE volume $J_backup until the next update."say "To go back to it: ./update.sh --rollback"}@@ -578,7 +619,7 @@ roll_back() { # why, exit code when the old version is backfi# The settings go back with the data, never before it: an old version is not started on data a newer one left.if ! put_back "$J_backup" "$J_data" "$helper_image" >>"$LOG" 2>&1; then- say "The data could not be put back from the Docker volume $J_backup (see $LOG). Neither was changed: the data is as $(new_name) left it, and the volume still holds the copy. The server is stopped."+ say "The data could not be put back from the $STORE volume $J_backup (see $LOG). Neither was changed: the data is as $(new_name) left it, and the volume still holds the copy. The server is stopped."say "Once the cause is fixed (often disk space), ./update.sh --rollback tries again. To run the server on the data as it is instead: docker compose up -d (that starts $(new_name) again)."exit 2fi@@ -617,7 +658,7 @@ earlier_update() {elsesay "An earlier update to $(new_name), started ${J_started:-earlier}, did not finish, and $(new_name) is not healthy now ($WHY)."fi- say "Going back puts $(old_name) and the data as it was at ${J_started:-that update} back, from the Docker volume $J_backup. Everything made on this server since then (chats, files, settings) is lost."+ say "Going back puts $(old_name) and the data as it was at ${J_started:-that update} back, from the $STORE volume $J_backup. Everything made on this server since then (chats, files, settings) is lost."if [ "$MODE" = rollback ] && [ "$ASSUME_YES" = yes ]; thenanswer=yeselif [ "$MODE" = rollback ]; then@@ -631,7 +672,7 @@ earlier_update() {update:keep)cp "$JOURNAL" "$LAST.tmp" && mv "$LAST.tmp" "$LAST"rm -f "$JOURNAL"- say "Left as it is. The copy from before that update stays in the Docker volume $J_backup; ./update.sh --rollback puts it back."+ say "Left as it is. The copy from before that update stays in the $STORE volume $J_backup; ./update.sh --rollback puts it back.";;*) refuse "Nothing was changed. The unfinished update stays recorded in $JOURNAL, and the next ./update.sh asks again." ;;esac@@ -734,8 +775,20 @@ if [ "$MODE" = target ]; thenexit 0fi+if [ -n "$UNIT" ]; then+ # Root has Podman images and services of its own, not this user's.+ [ "$(id -u)" != 0 ] || refuse "This is a Podman install of your own user: run it as that user, without sudo."+ if [ -z "${XDG_RUNTIME_DIR:-}" ] && [ -d "/run/user/$(id -u)" ]; then+ XDG_RUNTIME_DIR="/run/user/$(id -u)"+ export XDG_RUNTIME_DIR+ fi+ command -v podman >/dev/null 2>&1 || refuse "This needs Podman (podman version)."+ systemctl --user show-environment >/dev/null 2>&1 || refuse "systemd for your user is not reachable (systemctl --user). Log in to this machine directly or over SSH, then run this again."+ [ -f "$UNIT" ] || refuse "The service's unit $UNIT is gone. Run the Podman installer again, then this."+elsedocker compose version >/dev/null 2>&1 || refuse "This needs Docker with the Compose plugin (docker compose version)."[ -f docker-compose.yml ] || [ -f compose.yaml ] || [ -n "${COMPOSE_FILE:-}" ] || refuse "There is no docker-compose.yml or compose.yaml in $DIR. Name the install's folder: ./update.sh --dir PATH"+fiif [ "$MODE" != check ]; thentake_lock@@ -762,6 +815,7 @@ J_previous=$(published_ref "$J_previous_id")J_previous_version=$(image_version "$J_previous_id")J_data=$(inspect '{{range .Mounts}}{{if eq .Destination "/data"}}{{if eq .Type "volume"}}{{.Name}}{{else}}{{.Source}}{{end}}{{end}}{{end}}' "$CID")J_project=$(inspect '{{index .Config.Labels "com.docker.compose.project"}}' "$CID")+[ -z "$UNIT" ] || J_project=$SERVER_UNIT[ -n "$J_data" ] || refuse "The server's container has no /data volume, so its data cannot be copied aside. Nothing was changed."if [ "$(inspect '{{.State.Running}}' "$CID")" = true ]; then J_running=yes; else J_running=no; fi# The version the server says it is decides what counts as older: a build of main (`latest`) is labelled with the@@ -842,7 +896,7 @@ if [ "$ALLOW_OLDER" != yes ] && [ -n "$(older_reason)" ]; thensay "Nothing was changed. To go ahead anyway, with the data copied first: ./update.sh --allow-older${WANT_VERSION:+ --version $WANT_VERSION}${WANT_IMAGE:+ --image $WANT_IMAGE}"exit 5fi-if ! OMB_IMAGE="$J_target" docker compose config 2>/dev/null | grep -qF "image: $J_target"; then+if [ -z "$UNIT" ] && ! OMB_IMAGE="$J_target" docker compose config 2>/dev/null | grep -qF "image: $J_target"; thenabandonrefuse "The Compose file in $DIR does not take its image from OMB_IMAGE. Get the current one (git pull, or run the installer again), then run this again. Nothing was changed."fi@@ -895,7 +949,7 @@ pin_image "$J_target"# and fails when the new version never gets there; the wait below then says why. The current files start Caddy with# the server, so `up` returns at once and the wait below is the only one.if ! compose up -d --no-build >>"$LOG" 2>&1 && [ "$(inspect '{{.Image}}' "$(container)")" != "$J_target_id" ]; then- roll_back "Docker could not start $(new_name) (see $LOG)." 1+ roll_back "$STORE could not start $(new_name) (see $LOG)." 1fiphase waitdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 56f7815adf..436f86c4c9 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -161,6 +161,77 @@ its npx cache. The service log never shows a code. Get one with:npx openmausbot pair```+### Podman (rootless, as a service)++On Linux with Podman 4.6 or newer (Ubuntu 24.04, Debian 13, Fedora 39 and+later), one command run as your own user, without `sudo`, installs the+published server image as your user's systemd service:++```sh+curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy/podman/install.sh | sh+podman exec -it openmausbot openmausbot pair # a code, and a sign-in link for this machine's browser+```++It writes a Quadlet unit, `~/.config/containers/systemd/openmausbot.container`,+that runs the image pinned by its digest. systemd starts it again when it+fails or stops answering its health check. It starts at boot once your user+may run services without being logged in. The installer checks this and+prints the one line to run as an administrator; it never runs `sudo` itself:++```sh+sudo loginctl enable-linger "$USER"+```++The server uses the host's network, as `npx openmausbot serve` does. It+listens on `127.0.0.1:8799` only, and a program on this machine counts as its+owner ([Loopback trust](#loopback-trust-owner-or-service)). Nothing is+forwarded into a container. Options, given after `sh -s --`:++| Option | Does |+|---|---|+| `--lan` | Also answers other devices on this network, over plain http, and only from private addresses. Each device pairs. |+| `--local` | Back to this machine only (the default). |+| `--port N` | Another port, when 8799 is taken (webhooks use the next one). |+| `--public-url URL` | The HTTPS address a tunnel or proxy in front of it serves, for pairing links. |+| `--uninstall` | Stops and removes the service. Keeps the data. |++Running the command again repairs the install and keeps the version, the+data and your settings. It restarts the server only when something changed.++| | Where |+|---|---|+| Data (chats, settings, engine logins) | `~/.local/share/openmausbot/data`, owned by your user on the host |+| The server's settings | `~/.local/share/openmausbot/server.env`. Apply a change with `systemctl --user restart openmausbot` |+| Log | `journalctl --user -u openmausbot -f` |+| Status | `systemctl --user status openmausbot` |++**Update.** `~/.local/share/openmausbot/update.sh` updates to the stable+version (`--version X.Y.Z` for another, `--check` to only look). It is+`deploy/update.sh`, as for Docker installs: it downloads the image by digest,+stops the service, copies the data into a Podman volume and checks the copy,+points the unit at the new image and restarts the service. Then it waits until+the server answers and can still start bots. If it cannot, the old image and+the copy of the data go back. `update.sh --rollback` goes back after an update+that worked. Run it as your user, without `sudo`. The app's **Update server**+button does not run it on this install yet: run `update.sh` yourself.++**Uninstall.** Run the same command with `--uninstall`. The data stays.+Some of its files can belong to the container's other user ids, so remove+it through Podman: `podman unshare rm -rf ~/.local/share/openmausbot`.++**What rootless does not do.**++- The bots' sandbox (bubblewrap) is not part of the published server image,+ so bots run in the server's container, beside its data. Use this install+ on a machine only you sign in to, as with the Docker image.+- Chrome runs without its own sandbox inside the container, as in every+ container install. The container is the boundary.+- Ports below 1024 need root or a sysctl change; put Caddy, a tunnel or+ Tailscale in front for HTTPS (`--public-url`).+- Per-bot Linux desktops (**Local VM**) need the Podman socket, which this+ install does not mount. [deploy/podman](../deploy/podman/README.md) runs+ the full stack with them.+## Troubleshooting| You see | It means | Do this |diff --git a/scripts/testing/deploy-update-podman.test.ts b/scripts/testing/deploy-update-podman.test.tsnew file mode 100644index 0000000000..e1414104b5--- /dev/null+++ b/scripts/testing/deploy-update-podman.test.ts@@ -0,0 +1,164 @@+// deploy/update.sh on a rootless Podman install (deploy/podman/install.sh): the server is the user's own systemd service+// from a Quadlet unit, so the update goes through Podman and `systemctl --user`, and the unit's Image= follows the pin.+// Podman, systemctl and journalctl are stand-ins over the Compose fake deploy-update.test.ts uses, with real folders for+// the data and its copy. The real thing runs in deploy/e2e/podman.sh.+import { spawnSync } from "node:child_process";+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++const SCRIPT = join(import.meta.dirname, "..", "..", "deploy", "update.sh");+const FAKE = join(import.meta.dirname, "fake-compose-docker.mjs");+const REPO = "ghcr.io/milind-soni/openmausbot";+const posix = process.platform !== "win32";++const id = (letter: string) => `sha256:${letter.repeat(64)}`;+const OLD = { id: id("a"), refs: [`${REPO}:v0.1.150`, `${REPO}@${id("1")}`], version: "0.1.150", local: true, engine: true, counts: true };+const NEW = { id: id("b"), refs: [`${REPO}@${id("2")}`, `${REPO}:v0.1.151`], version: "0.1.151", local: false, engine: true, counts: true };++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function tree(dir: string, prefix = ""): Record<string, string> {+ const files: Record<string, string> = {};+ for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) Object.assign(files, tree(path, `${prefix}${name}/`));+ else files[`${prefix}${name}`] = readFileSync(path, "utf8");+ }+ return files;+}++const unitText = (image: string) => `[Container]\nContainerName=openmausbot\nImage=${image}\nNetwork=host\n\n[Service]\nRestart=on-failure\n`;++/** A Podman install on 0.1.150, its unit and settings as the installer writes them, and a stable channel naming `target`. */+function install(target: Record<string, unknown> = {}) {+ const root = mkdtempSync(join(tmpdir(), "omb-update-podman-"));+ dirs.push(root);+ const home = join(root, "share", "openmausbot");+ const unit = join(root, "config", "containers", "systemd", "openmausbot.container");+ const fake = join(root, "fake");+ const data = join(fake, "volumes", "deploy_data");+ mkdirSync(join(root, "bin"));+ mkdirSync(home, { recursive: true });+ mkdirSync(join(root, "config", "containers", "systemd"), { recursive: true });+ mkdirSync(join(data, ".openmausbot"), { recursive: true });+ writeFileSync(join(data, ".openmausbot", "bots.json"), '[{"name":"Mira"}]');+ writeFileSync(join(data, "started-by.txt"), "0.1.150\n");+ copyFileSync(SCRIPT, join(home, "update.sh"));+ writeFileSync(join(home, ".env"), `OMB_IMAGE=${OLD.refs[1]}\n`, { mode: 0o600 });+ writeFileSync(join(home, "podman.unit"), `${unit}\n`);+ writeFileSync(unit, unitText(OLD.refs[1]!));+ const node = JSON.stringify(process.execPath);+ const shim = (name: string, body: string) => {+ writeFileSync(join(root, "bin", name), `#!/bin/sh\necho "$*" >>"$FAKE_DOCKER_DIR/${name}.log"\n${body}\n`);+ chmodSync(join(root, "bin", name), 0o755);+ };+ // Podman's own spelling of what the Compose fake answers: the unit's container by name, and exec without -T.+ shim("podman", [+ 'case "$1" in',+ ` ps) exec ${node} "${FAKE}" compose ps -aq omb ;;`,+ ` exec) shift 2; exec ${node} "${FAKE}" compose exec -T omb "$@" ;;`,+ ` run) shift; [ "$1" = --security-opt ] && shift 2; exec ${node} "${FAKE}" run "$@" ;;`,+ ` compose) echo "a Podman install never runs compose" >&2; exit 64 ;;`,+ ` *) exec ${node} "${FAKE}" "$@" ;;`,+ "esac",+ ].join("\n"));+ // The user's systemd: restart starts the container from the unit's Image=, which is the only place it is read.+ shim("systemctl", [+ '[ "$1" = --user ] || { echo "only the user\'s own systemd" >&2; exit 64; }',+ "shift",+ 'case "$1" in',+ " show-environment | daemon-reload) exit 0 ;;",+ ` stop) exec ${node} "${FAKE}" compose stop ;;`,+ ` restart) OMB_IMAGE=$(sed -n 's/^Image=//p' "${unit}") exec ${node} "${FAKE}" compose up -d ;;`,+ "esac",+ "exit 64",+ ].join("\n"));+ shim("journalctl", `exec ${node} "${FAKE}" compose logs`);+ writeFileSync(join(fake, "state.json"), JSON.stringify({+ serial: 1, composeReadsPin: true, defaultImage: OLD.refs[1], dataVolume: "deploy_data", images: [OLD, { ...NEW, ...target }],+ containers: { omb: { id: "omb-1", image: OLD.id, status: "running", restarts: 0 } },+ }));+ writeFileSync(join(root, "stable.json"), JSON.stringify({ channel: "stable", version: "0.1.151", image: NEW.refs[0], history: [] }));+ const run = (args: string[] = [], env: Record<string, string> = {}) => {+ const result = spawnSync("bash", [join(home, "update.sh"), ...args], {+ encoding: "utf8", input: "", timeout: 60_000,+ env: {+ PATH: `${join(root, "bin")}:/usr/bin:/bin:/usr/sbin:/sbin`, HOME: root, FAKE_DOCKER_DIR: fake, XDG_RUNTIME_DIR: root,+ OMB_STABLE_URL: `file://${join(root, "stable.json")}`, OMB_NEWEST_URL: `file://${join(root, "newest.json")}`,+ OMB_UPDATE_POLL_S: "0", OMB_UPDATE_WAIT_S: "120", OMB_UPDATE_ENGINE_WAIT_S: "1", ...env,+ },+ });+ return { ...result, said: result.stdout.trim().split("\n") };+ };+ const log = (name: string) => (existsSync(join(fake, `${name}.log`)) ? readFileSync(join(fake, `${name}.log`), "utf8").trim().split("\n") : []);+ const copies = () => readdirSync(join(fake, "volumes")).filter((name) => name.includes("-before-update-")).sort();+ return {+ data, run, log, copies,+ state: () => JSON.parse(readFileSync(join(fake, "state.json"), "utf8")),+ env: () => readFileSync(join(home, ".env"), "utf8"),+ unit: () => readFileSync(unit, "utf8"),+ };+}++describe.skipIf(!posix)("deploy/update.sh on a Podman install", () => {+ it("copies the data aside, pins the new image in .env and in the unit, and restarts the user's service", () => {+ const box = install();+ const before = tree(box.data);+ const done = box.run();+ expect(done.status, done.stdout + done.stderr).toBe(0);+ expect(box.copies()).toEqual([expect.stringMatching(/^openmausbot_data-before-update-\d{8}T\d{6}Z$/)]);+ expect(done.said).toEqual([+ "Downloading 0.1.151…",+ "Stopping the server and copying its data aside…",+ "Starting 0.1.151…",+ "Waiting for it to answer and to be able to start bots…",+ "Updated from 0.1.150 to 0.1.151.",+ `The data from before the update is kept in the Podman volume ${box.copies()[0]} until the next update.`,+ "To go back to it: ./update.sh --rollback",+ ]);+ expect(box.env()).toBe(`OMB_IMAGE=${NEW.refs[0]}\n`);+ expect(box.unit()).toBe(unitText(NEW.refs[0]!));+ expect(box.state().containers.omb).toMatchObject({ image: NEW.id, status: "running" });+ expect(tree(join(box.data, "..", box.copies()[0]!))).toEqual(before);+ const systemctl = box.log("systemctl");+ expect(systemctl.indexOf("--user stop openmausbot.service")).toBeGreaterThanOrEqual(0);+ expect(systemctl.indexOf("--user daemon-reload")).toBeLessThan(systemctl.indexOf("--user restart openmausbot.service"));+ // The helpers copy the data with SELinux's label for the server's container out of their way, and with no network.+ expect(box.log("podman").find((call) => call.includes("--entrypoint cp"))).toMatch(/^run --security-opt label=disable --rm --network none --user 0:0 /);+ expect(box.log("podman").some((call) => call.startsWith("compose"))).toBe(false);+ });++ it("puts back the old image in the unit, its settings and the data when the new version never answers", () => {+ const box = install({ behaviour: "silent" });+ const before = tree(box.data);+ const failed = box.run([], { OMB_UPDATE_WAIT_S: "2" });+ expect(failed.status).toBe(1);+ expect(failed.said.slice(-3)).toEqual([+ "The update to 0.1.151 did not work: it did not answer within 2 seconds.",+ "Putting back the version and the data from before the update…",+ "Your server runs 0.1.150 again, with its data as it was before the update.",+ ]);+ expect(box.env()).toBe(`OMB_IMAGE=${OLD.refs[1]}\n`);+ expect(box.unit()).toBe(unitText(OLD.refs[1]!));+ expect(box.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });+ expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });+ });++ it("refuses to run as root, whose Podman is not this install's", () => {+ if (process.getuid?.() !== 0) {+ const box = install();+ const id = join(dirs.at(-1)!, "bin", "id");+ writeFileSync(id, '#!/bin/sh\n[ "$1" = -u ] && echo 0 || exec /usr/bin/id "$@"\n');+ chmodSync(id, 0o755);+ const refused = box.run();+ expect(refused.status).toBe(4);+ expect(refused.stdout).toContain("run it as that user, without sudo");+ expect(box.log("systemctl")).toEqual([]);+ }+ });+});