Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

update.sh: read the record properly, never lose the good copy, ask before undoing an old update, never go older

milind-sonib80479aa111d
diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.yml
index 02e6e2a723..f00291e927 100644
--- a/.github/workflows/promote-stable.yml
+++ b/.github/workflows/promote-stable.yml
@@ -95,23 +95,41 @@ jobs:
echo "home=$IMAGE-cloud-home@$(digest_of "$IMAGE-cloud-home:v$VERSION")" >> "$GITHUB_OUTPUT"
- name: Write the record, refusing to move stable back
+ id: record
env:
VERSION: ${{ steps.release.outputs.version }}
SERVER: ${{ steps.images.outputs.server }}
HOME_IMAGE: ${{ steps.images.outputs.home }}
run: |
set -euo pipefail
+ # Only a branch that is not there means "no record yet". Anything else that goes wrong while reading it stops
+ # here: taken for a first promotion, it would skip the move-back guard and drop the history.
current=()
- if git fetch --depth 1 origin channels 2>/dev/null && git show FETCH_HEAD:stable.json > "$RUNNER_TEMP/current.json" 2>/dev/null; then
+ if git ls-remote --exit-code --heads origin channels >/dev/null; then
+ git fetch --depth 1 origin channels
+ git show FETCH_HEAD:stable.json > "$RUNNER_TEMP/current.json"
current=(--current "$RUNNER_TEMP/current.json")
+ # Where the tags go back to if the record cannot be published after they moved.
+ echo "previous_server=$(jq -er .image "$RUNNER_TEMP/current.json")" >> "$GITHUB_OUTPUT"
+ echo "previous_home=$(jq -er .cloudHomeImage "$RUNNER_TEMP/current.json")" >> "$GITHUB_OUTPUT"
+ else
+ status=$?
+ if [ "$status" != 2 ]; then
+ echo "::error::Could not ask GitHub whether the channels branch exists (git ls-remote exited $status). Nothing was changed; run this again."
+ exit 1
+ fi
+ echo "There is no channels branch yet: this is the first promotion."
fi
+ echo "first=$([ ${#current[@]} = 0 ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
node scripts/stable-channel.mjs record --version "$VERSION" --image "$SERVER" --cloud-home "$HOME_IMAGE" \
--release "$RUNNER_TEMP/release.json" "${current[@]}" $([ "$ALLOW_OLDER" = "true" ] && echo --allow-older) > "$RUNNER_TEMP/stable.json"
cat "$RUNNER_TEMP/stable.json"
# The tags move before the record does: a server follows the record, and the record never names a digest the
- # `stable` tag did not reach. Running this again with the same version repairs a run that stopped in between.
+ # `stable` tag did not reach. When the record then cannot be published, the last step puts the tags back where
+ # the record still says; running this again with the same version also repairs a run that stopped in between.
- name: Move the stable tags, without building
+ id: tags
env:
IMAGE: ${{ steps.release.outputs.image }}
SERVER: ${{ steps.images.outputs.server }}
@@ -125,12 +143,17 @@ jobs:
test "$IMAGE-cloud-home@$(digest_of "$IMAGE-cloud-home:stable")" = "$HOME_IMAGE"
- name: Publish the record on the channels branch
+ id: publish
env:
VERSION: ${{ steps.release.outputs.version }}
+ FIRST: ${{ steps.record.outputs.first }}
run: |
set -euo pipefail
work="$RUNNER_TEMP/channels"
- if git fetch --depth 1 origin channels 2>/dev/null; then
+ if [ "$FIRST" != true ]; then
+ git fetch --depth 1 origin channels
+ # The record was written from this stable.json; one that changed since is not overwritten.
+ git show FETCH_HEAD:stable.json | cmp -s - "$RUNNER_TEMP/current.json" || { echo "::error::stable.json changed while this ran. Run it again."; exit 1; }
git worktree add --detach "$work" FETCH_HEAD
else
git worktree add --detach "$work"
@@ -147,6 +170,22 @@ jobs:
git -C "$work" push origin HEAD:refs/heads/channels
fi
+ - name: Put the stable tags back where the record says
+ if: failure() && steps.tags.outcome != 'skipped' && steps.publish.outcome != 'success'
+ env:
+ IMAGE: ${{ steps.release.outputs.image }}
+ PREVIOUS_SERVER: ${{ steps.record.outputs.previous_server }}
+ PREVIOUS_HOME: ${{ steps.record.outputs.previous_home }}
+ run: |
+ set -euo pipefail
+ if [ -z "$PREVIOUS_SERVER" ] || [ -z "$PREVIOUS_HOME" ]; then
+ echo "::warning::There is no earlier record to put the stable tags back to. They may name the new version while no record does; run this again to publish the record."
+ exit 0
+ fi
+ docker buildx imagetools create --tag "$IMAGE:stable" "$PREVIOUS_SERVER"
+ docker buildx imagetools create --tag "$IMAGE-cloud-home:stable" "$PREVIOUS_HOME"
+ echo "::warning::The record was not published, so the stable tags were put back to $PREVIOUS_SERVER and $PREVIOUS_HOME."
+
- name: Summary
env:
VERSION: ${{ steps.release.outputs.version }}
diff --git a/.github/workflows/server-update-e2e.yml b/.github/workflows/server-update-e2e.yml
index 6a1c38fc63..3500cd2124 100644
--- a/.github/workflows/server-update-e2e.yml
+++ b/.github/workflows/server-update-e2e.yml
@@ -33,6 +33,8 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
+ - name: shellcheck
+ run: shellcheck -S warning deploy/update.sh deploy/e2e/update.sh
- name: Update, roll back and recover
env:
LAYOUT: ${{ matrix.layout }}
diff --git a/apps/docs/content/docs/self-hosting/deploy-vps.mdx b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
index db756d3421..f695fbb922 100644
--- a/apps/docs/content/docs/self-hosting/deploy-vps.mdx
+++ b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
@@ -306,50 +306,88 @@ curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy
sudo bash update.sh --dir /opt/openmausbot
```
+Until a first version has been made stable, `./update.sh` takes the newest
+release instead, as **Check for updates** does then.
+
The data may be a Docker volume or a folder on the server; the copy keeps
every file's owner and mode either way. The script then:
1. Downloads the stable image, by its digest. If that fails it stops, and
- nothing has changed.
-2. Checks there is room for a copy of your data, stops the server, and copies
- everything under `/data` into a Docker volume
- (`deploy_data-before-update`; `openmausbot_data-before-update` for
- `/opt/openmausbot`). The server is down from here until step 4;
- how long depends on how much data there is.
+ nothing has changed. It also stops, changing nothing, when that version is
+ older than the one your server says it runs (see "From `latest` to stable"
+ below).
+2. Checks there is room for a copy of your data where Docker keeps its
+ volumes, stops the server, checks that it has stopped, and copies
+ everything under `/data` into a new Docker volume named for the update
+ (`deploy_data-before-update-20261110T120000Z`;
+ `openmausbot_data-before-update-…` for `/opt/openmausbot`). It then
+ compares the copy with the data, every file by checksum; a copy that does
+ not match is thrown away, the server is started again, and nothing has
+ changed. The copy from the update before is removed only after this one
+ has matched. The server is down from here until step 4; how long depends
+ on how much data there is.
3. Writes the image into `.env` (`OMB_IMAGE=ghcr.io/milind-soni/openmausbot@sha256:…`)
and starts it.
4. Waits, up to five minutes, until the new server answers `/api/health`
steadily, says it is the new version, can still start a bot if it could
before (`openmausbot doctor`: an engine is ready), and Caddy runs again.
-5. If any of that fails: puts back `.env`, the data from the copy and the old
+5. If any of that fails: puts back the data from the copy, `.env` and the old
image, starts the old version, and tells you what went wrong. Your server
- is as it was before step 1.
-
-It is safe to interrupt and to run twice. Each step is written to
-`deploy/.update/journal` before it starts, so after Ctrl-C, a closed terminal or
-a reboot, the next `./update.sh` first finishes what was cut short: it keeps
-the new version if that is up and healthy, and otherwise puts the old one
-back. Run again after a finished update, it says there is nothing to do. Two
-runs at once are refused.
+ is as it was before step 1. The copy is put into a new folder inside the
+ data and checked there before it takes the data's place, so a restore that
+ fails (a full disk, say) leaves both the data and the copy as they were:
+ the server stays stopped, the update's journal is kept, and
+ `./update.sh --rollback` tries again once the cause is fixed.
+
+A closed terminal or a dropped SSH session does not stop an update: it carries
+on, and `deploy/.update/update.log` says how it ended. Each step is written to
+`deploy/.update/journal` before it starts. Ctrl-C undoes the update at once:
+before the new version starts, nothing has changed; after, the old version and
+its data are put back. When an update was cut short some other way (a reboot,
+a killed process), the next `./update.sh` keeps the new version if that is up
+and healthy. If it is not, it says which version and data going back would put
+back, and that everything made on the server since that update would be lost,
+and asks: `yes` goes back, `keep` leaves the server as it is (the copy stays
+for `--rollback`), and anything else, or no answer at all, changes nothing.
+Run again after a finished update, it says there is nothing to do. Two runs at
+once are refused.
```sh
./update.sh --check # what would change; changes nothing
./update.sh --version 0.1.151 # one released version instead of the stable one
./update.sh --rollback # the version and the data from before the last update
+./update.sh --allow-older # go ahead although that version is not newer than the one running
```
`--rollback` is for an update that passed its checks and still turned out
wrong. It asks first, because everything made since the update (chats, files,
-settings) is replaced by the copy. The copy is kept until the next update
-replaces it. The script's own log is `deploy/.update/update.log`.
+settings) is replaced by the copy; `--yes` answers for you. The copy is kept
+until the next update has made and checked its own. The script's own log is
+`deploy/.update/update.log`.
| The script ends with | Meaning |
| --- | --- |
| `0` | Updated, or already on that version |
| `1` | The update failed; the old version and its data are back |
-| `2` | The update failed and the old version did not come back healthy; read the last lines it printed |
+| `2` | The old version or its data could not be brought back; read the last lines it printed, then `./update.sh --rollback` |
| `3` | Another update is running |
-| `4` | Nothing was changed (could not download, not enough disk, refused) |
+| `4` | Nothing was changed (could not download, not enough disk, the folder cannot be written, a question not answered `yes`, refused) |
+| `5` | Nothing was changed: the version asked for is older than the one running, or one of the two versions cannot be told; `--allow-older` goes ahead |
+| `130` | Interrupted with Ctrl-C before the new version started: nothing was changed, and the server was started again |
+
+### From `latest` to stable
+
+A server started from the `latest` image runs a build of `main`. Its image is
+labelled with the branch, not a version, so `update.sh` goes by the version the
+server itself reports, which is that of the release it was built after, or of
+the next one. Such a build may already hold changes made after that release,
+and may have written data in ways the release does not read. So `update.sh`
+moves it to stable only once the stable version is newer than the version the
+server reports; until then it says so and changes nothing (exit `5`). Nothing
+else is needed: the first `./update.sh` after a newer version is made stable
+moves the server onto it and pins it by digest. To move now anyway, run
+`./update.sh --allow-older`; the data is copied first, and `--rollback` puts
+the `latest` build and its data back.
If you built the image yourself (`docker compose up -d --build`, with
`ENGINES` baked in), `update.sh` refuses to replace it without being told to:
diff --git a/deploy/e2e/update.sh b/deploy/e2e/update.sh
index 9e39fcfe5f..c595189d83 100755
--- a/deploy/e2e/update.sh
+++ b/deploy/e2e/update.sh
@@ -1,8 +1,10 @@
#!/usr/bin/env bash
# deploy/update.sh for real, on a host with Docker and nothing else running in it (CI, or a private docker:dind):
-# a server on one released version, then --check, an update to a stable record naming the next release by digest, the
-# same again (nothing to do), --rollback, an update to an image that never answers and damages the data (it must roll
-# back and leave every file as it was), and an update killed with SIGKILL while it waits, finished by the next run.
+# a server on one released version, then --check, an update to a stable record (with a history of earlier versions)
+# naming the next release by digest, the same again (nothing to do), --rollback, an update to an image that never
+# answers and damages the data (it must roll back and leave every file as it was), an update killed with SIGKILL while
+# it waits (the next run asks before it puts the data back), a rollback whose restore fails (data and copy untouched,
+# tried again on request), an update whose terminal hangs up half-way (it finishes), and a refused downgrade.
# LAYOUT=installer /opt/openmausbot with compose.yaml and a ./data folder, as deploy/install.sh lays it out
# LAYOUT=checkout a copy of deploy/ with docker-compose.yml and the named volume `data`
# OUT=<evidence folder> LAYOUT=installer bash deploy/e2e/update.sh
@@ -15,8 +17,8 @@ REPO=ghcr.io/milind-soni/openmausbot
FROM=${FROM_VERSION:-0.1.150}
TO=${TO_VERSION:-0.1.151}
mkdir -p "$OUT"
-if [ "$LAYOUT" = installer ]; then DIR=/opt/openmausbot DATA=/opt/openmausbot/data COPY=openmausbot_data-before-update
-else DIR=/srv/openmausbot-e2e/deploy DATA=deploy_data COPY=deploy_data-before-update; fi
+if [ "$LAYOUT" = installer ]; then DIR=/opt/openmausbot DATA=/opt/openmausbot/data
+else DIR=/srv/openmausbot-e2e/deploy DATA=deploy_data; fi
UPDATE=(bash "$ROOT/deploy/update.sh" --dir "$DIR")
step() { printf '\n== %s\n' "$*"; }
@@ -29,6 +31,14 @@ running_image() { docker inspect -f '{{.Image}}' "$(cd "$DIR" && docker compose
version() { (cd "$DIR" && docker compose exec -T omb curl -sf http://127.0.0.1:8799/.well-known/openmausbot/environment) | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'; }
wait_version() { for _ in $(seq 1 60); do [ "$(version)" = "$1" ] && return 0; sleep 3; done; return 1; }
in_data() { docker run --rm --network none --user 0:0 -v "$DATA:/d" --entrypoint sh "$REPO:v$FROM" -c "$1"; }
+# The copies of the data the updates made: one Docker volume each, and never more than one once an update is done.
+copies() { docker volume ls -q --filter label=com.mausbot.role=update-backup; }
+copy() {
+ local found
+ found=$(copies)
+ [ "$(printf '%s\n' "$found" | grep -c .)" = 1 ] || fail "expected one copy of the data, found: $(printf '%s ' $found)"
+ printf '%s' "$found"
+}
# Every file of the data with its owner, mode and checksum. Read while the server is stopped.
manifest() { docker run --rm --network none --user 0:0 -v "$1:/d:ro" --entrypoint sh "$REPO:v$FROM" -c 'cd /d && find . -type f -print0 | sort -z | xargs -0 -r stat -c "%u:%g %a %n"; find . -type f -print0 | sort -z | xargs -0 -r sha256sum'; }
@@ -36,7 +46,7 @@ step "a $LAYOUT install on $FROM"
for old in /opt/openmausbot /srv/openmausbot-e2e/deploy; do
if [ -d "$old" ]; then (cd "$old" && docker compose down -v) >/dev/null 2>&1; fi
done
-docker volume rm -f "$COPY" >/dev/null 2>&1
+for volume in $(copies); do docker volume rm -f "$volume" >/dev/null 2>&1; done
rm -rf "$DIR" && mkdir -p "$DIR"
docker pull -q "$REPO:v$FROM" >/dev/null && docker pull -q "$REPO:v$TO" >/dev/null || fail "could not pull the two releases"
if [ "$LAYOUT" = installer ]; then
@@ -90,7 +100,8 @@ wait_version "$FROM" || fail "$FROM did not come up"
OLD_ID=$(running_image)
cp "$DIR/.env" "$OUT/env.before"
STABLE=$(docker image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$REPO:v$TO" | grep "^$REPO@" | head -n 1)
-printf '{\n "channel": "stable",\n "version": "%s",\n "image": "%s",\n "history": [{ "version": "%s", "promotedAt": "2026-11-12T00:00:00.000Z" }]\n}\n' "$TO" "$STABLE" "$TO" >"$OUT/stable.json"
+# As promote-stable.yml writes it: the history names older versions after the current one.
+printf '{\n "channel": "stable",\n "version": "%s",\n "image": "%s",\n "history": [\n { "version": "%s", "promotedAt": "2026-11-12T00:00:00.000Z" },\n { "version": "%s", "promotedAt": "2026-11-05T00:00:00.000Z" },\n { "version": "0.1.140", "promotedAt": "2026-10-01T00:00:00.000Z" }\n ]\n}\n' "$TO" "$STABLE" "$TO" "$FROM" >"$OUT/stable.json"
export OMB_STABLE_URL="file://$OUT/stable.json"
echo "the stable record names $STABLE"
@@ -106,7 +117,7 @@ grep -qx "OMB_IMAGE=$STABLE" "$DIR/.env" || fail ".env is not pinned by digest"
[ "$(stat -c %a "$DIR/.env")" = 600 ] || fail ".env changed its mode"
in_data 'cat /d/.openmausbot/e2e-sentinel.txt' | grep -q "written under $FROM" || fail "the data did not carry over"
[ "$(cd "$DIR" && docker compose ps --status running --services | sort | tr '\n' ' ')" = "caddy omb " ] || fail "caddy or omb is not running"
-docker volume inspect "$COPY" >/dev/null || fail "no copy of the data"
+copy >/dev/null || fail "expected one copy of the data"
step "3. the same again: nothing to do"
"${UPDATE[@]}" | tee "$OUT/3-again.txt"
@@ -136,7 +147,8 @@ grep -q "did not work: it did not answer within 45 seconds" "$OUT/5-failed-updat
grep -q "Your server runs $FROM again, with its data as it was before the update." "$OUT/5-failed-update.txt" || fail "no plain outcome"
[ "$(running_image)" = "$OLD_ID" ] || fail "after the rollback another image runs"
cmp -s "$DIR/.env" "$OUT/env.before" || fail "after the rollback .env differs"
-manifest "$COPY" >"$OUT/5-copy.txt"
+snapshot=$(copy) || fail "expected one copy of the data"
+manifest "$snapshot" >"$OUT/5-copy.txt"
diff "$OUT/5-data-before.txt" "$OUT/5-copy.txt" >"$OUT/5-copy-vs-before.diff" || fail "the copy differs from the data before the update"
(cd "$DIR" && docker compose stop) >/dev/null 2>&1
manifest "$DATA" >"$OUT/5-data-after.txt"
@@ -146,7 +158,7 @@ in_data 'grep -q "written under" /d/.openmausbot/e2e-sentinel.txt && test ! -e /
(cd "$DIR" && docker compose start) >/dev/null 2>&1
wait_version "$FROM" || fail "$FROM does not answer after the rollback"
-step "6. an update killed while it waits is finished by the next run"
+step "6. an update killed while it waits: the next run asks, changes nothing unanswered, and puts the data back on yes"
OMB_UPDATE_WAIT_S=120 "${UPDATE[@]}" --image omb-e2e-broken:1 >"$OUT/6-killed.txt" 2>&1 &
pid=$!
for _ in $(seq 1 180); do grep -q "^phase=wait" "$DIR/.update/journal" 2>/dev/null && break; sleep 1; done
@@ -158,14 +170,64 @@ cat "$OUT/6-killed.txt"
[ -f "$DIR/.update/journal" ] || fail "no journal after the kill"
in_data 'grep -qx damaged /d/.openmausbot/e2e-sentinel.txt && test -e /d/.openmausbot/left-by-the-broken-version' || fail "the broken version did not damage the data, so this proves nothing"
echo "the killed update left the broken version running on damaged data"
-OMB_UPDATE_WAIT_S=45 "${UPDATE[@]}" | tee "$OUT/6-next-run.txt"
+OMB_UPDATE_WAIT_S=45 "${UPDATE[@]}" </dev/null | tee "$OUT/6-unanswered.txt"
+[ "${PIPESTATUS[0]}" = 4 ] || fail "a run nobody answered did not exit 4"
+grep -q "Everything made on this server since then (chats, files, settings) is lost." "$OUT/6-unanswered.txt" || fail "the question does not say what is lost"
+[ -f "$DIR/.update/journal" ] || fail "a run nobody answered dropped the journal"
+in_data 'grep -qx damaged /d/.openmausbot/e2e-sentinel.txt' || fail "a run nobody answered changed the data"
+printf 'yes\n' | OMB_UPDATE_WAIT_S=45 "${UPDATE[@]}" | tee "$OUT/6-next-run.txt"
grep -q "Your server runs $FROM again, with its data as it was before the update." "$OUT/6-next-run.txt" || fail "the next run did not put the old version back"
[ "$(running_image)" = "$OLD_ID" ] || fail "after the recovery another image runs"
in_data 'grep -q "written under" /d/.openmausbot/e2e-sentinel.txt' || fail "after the recovery the data is damaged"
cmp -s "$DIR/.env" "$OUT/env.before" || fail "after the recovery .env differs"
+
+step "7. a rollback whose restore fails leaves the data and the copy alone, keeps the journal, and is tried again on request"
+(cd "$DIR" && docker compose stop) >/dev/null 2>&1
+manifest "$DATA" >"$OUT/7-data-before.txt"
+OMB_UPDATE_WAIT_S=120 "${UPDATE[@]}" --image omb-e2e-broken:1 >"$OUT/7-failed-restore.txt" 2>&1 &
+pid=$!
+for _ in $(seq 1 180); do grep -q "^phase=wait" "$DIR/.update/journal" 2>/dev/null && break; sleep 1; done
+grep -q "^phase=wait" "$DIR/.update/journal" || fail "the update never reached its wait"
+# The restore runs in a helper from the old image: without it, putting the data back fails before it starts.
+docker image rm -f "$OLD_ID" >/dev/null || fail "could not remove the old image"
+wait "$pid"
+code=$?
+cat "$OUT/7-failed-restore.txt"
+[ "$code" = 2 ] || fail "a rollback whose restore failed exited $code, not 2"
+grep -q "Neither was changed" "$OUT/7-failed-restore.txt" || fail "no plain account of the failed restore"
+[ -f "$DIR/.update/journal" ] || fail "the failed restore dropped the journal"
+[ -z "$(cd "$DIR" && docker compose ps -q --status running omb)" ] || fail "a server was started on data that was not put back"
+docker pull -q "$REPO:v$FROM" >/dev/null || fail "could not pull $FROM again"
+in_data 'grep -qx damaged /d/.openmausbot/e2e-sentinel.txt && test ! -e /d/.omb-restore && test ! -e /d/.omb-replaced' || fail "the failed restore changed the data"
+snapshot=$(copy) || fail "expected one copy of the data"
+manifest "$snapshot" >"$OUT/7-copy.txt"
+diff "$OUT/7-data-before.txt" "$OUT/7-copy.txt" >/dev/null || fail "the failed restore changed the copy"
+OMB_UPDATE_WAIT_S=120 "${UPDATE[@]}" --rollback --yes | tee "$OUT/7-again.txt"
+[ "${PIPESTATUS[0]}" = 0 ] || fail "--rollback after the failed restore did not exit 0"
+[ "$(running_image)" = "$OLD_ID" ] || fail "after the second try another image runs"
+in_data 'grep -q "written under" /d/.openmausbot/e2e-sentinel.txt' || fail "after the second try the data is damaged"
+[ ! -f "$DIR/.update/journal" ] || fail "the journal outlived a finished rollback"
+
+step "8. an update whose terminal hangs up half-way finishes"
+"${UPDATE[@]}" >"$OUT/8-hangup.txt" 2>&1 &
+pid=$!
+for _ in $(seq 1 180); do grep -q "^phase=wait" "$DIR/.update/journal" 2>/dev/null && break; sleep 1; done
+grep -q "^phase=wait" "$DIR/.update/journal" || fail "the update never reached its wait"
+kill -HUP "$pid"
+wait "$pid"
+code=$?
+cat "$OUT/8-hangup.txt"
+[ "$code" = 0 ] || fail "the update exited $code after a hangup"
+[ "$(version)" = "$TO" ] || fail "after the hangup the server says $(version)"
+[ ! -f "$DIR/.update/journal" ] || fail "the hung-up update left its journal"
+
+step "9. no older version without --allow-older"
+"${UPDATE[@]}" --version "$FROM" | tee "$OUT/9-older.txt"
+[ "${PIPESTATUS[0]}" = 5 ] || fail "going back to $FROM did not exit 5"
+[ "$(version)" = "$TO" ] || fail "a refused downgrade changed the version"
cp "$DIR/.update/update.log" "$OUT/update.log"
(cd "$DIR" && docker compose down -v) >/dev/null 2>&1
-docker volume rm -f "$COPY" >/dev/null 2>&1
+for volume in $(copies); do docker volume rm -f "$volume" >/dev/null 2>&1; done
docker image rm -f omb-e2e-broken:1 openmausbot-before-update:local >/dev/null 2>&1
step "ALL PASSED ($LAYOUT)"
diff --git a/deploy/update.sh b/deploy/update.sh
index 2d765b786a..dfc4b3df1f 100755
--- a/deploy/update.sh
+++ b/deploy/update.sh
@@ -1,30 +1,46 @@
#!/usr/bin/env bash
# Updates this Docker Compose install to the stable version, with a way back:
#
-# ./update.sh the stable version
+# ./update.sh the stable version (the newest release until a first version is made stable)
# ./update.sh --version X.Y.Z one released version
# ./update.sh --check say what would change, and change nothing
-# ./update.sh --rollback put back the version and the data from before the last update
+# ./update.sh --rollback put back the version and the data from before the last update (asks first; --yes)
+# ./update.sh --allow-older go ahead when the version asked for is older than, or no newer than, the one running
# ./update.sh --dir PATH the install's folder, when it is not this one (the installer's: /opt/openmausbot)
#
# It runs on the server itself, beside docker-compose.yml, because a server cannot replace its own container. The steps
# are the ones the MausBot connector runs for a connected server (connector/src/home.ts `update`): download the new
-# image by digest, stop the server, copy its data aside, start the new image, and wait until it answers and can still
-# start bots. When it does not, the old image and the copy are put back. Each step is written to .update/journal
-# before it starts, so an update that was interrupted (Ctrl-C, a closed terminal, a reboot) is finished safely by
-# the next run, and a second run of a finished update changes nothing.
+# image by digest, stop the server and check that it stopped, copy its data into a new Docker volume and check the copy
+# file by file, start the new image, and wait until it answers and can still start bots. When it does not, the old image
+# and the copy are put back. The copy from the update before is removed only once the new copy has been checked.
#
-# Exit codes: 0 done or nothing to do, 1 the update failed and the old version is back, 2 the old version could not be
-# brought back either, 3 another update is running, 4 nothing was changed (refused, or could not download).
+# Each step is written to .update/journal before it starts. A closed terminal does not stop an update: it carries on,
+# and says how it ended in .update/update.log. An update this run interrupts (Ctrl-C) is undone at once. One an earlier
+# run left unfinished (a reboot, a kill) is kept when its new version is healthy; otherwise the next run asks before it
+# puts the old data back, and says what that loses.
+#
+# Exit codes, the same ones the connector's update runner reads (connector/host/mausbot-update-runner.sh):
+# 0 done, or nothing to do
+# 1 the update failed, and the old version and its data are back
+# 2 the old version or its data could not be brought back: see what it said; ./update.sh --rollback tries again
+# 3 another update is running here
+# 4 nothing was changed: refused, could not download, the folder cannot be written, or a question was not answered
+# 5 nothing was changed: the version asked for is older than the one running, or either version cannot be told
+# 130 interrupted (Ctrl-C) before the new version started: nothing was changed, and the server was started again
set -uo pipefail
+# An SSH session that drops sends SIGHUP, and a `| tee` that dies with it would send SIGPIPE: neither may stop an
+# update half-way. Output to a terminal that has gone is lost; .update/update.log keeps it.
+trap '' HUP PIPE
REPO="ghcr.io/milind-soni/openmausbot"
PINNED="^ghcr\.io/milind-soni/openmausbot@sha256:[0-9a-f]{64}$"
STABLE_URL=${OMB_STABLE_URL:-https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json}
+NEWEST_URL=${OMB_NEWEST_URL:-https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest}
SERVICE=${OMB_UPDATE_SERVICE:-omb}
WAIT_S=${OMB_UPDATE_WAIT_S:-300}
POLL_S=${OMB_UPDATE_POLL_S:-5}
KEEP_TAG="openmausbot-before-update:local"
+BACKUP_ROLE="com.mausbot.role=update-backup"
# The install: --dir, else the folder this script is in when that holds a Compose file, else where the installer
# (deploy/install.sh) puts one.
@@ -49,27 +65,112 @@ unset OMB_IMAGE
# A step interrupted while its output goes to the log still speaks to the terminal.
exec 3>&1
say() {
- printf '%s\n' "$*" >&3
- if [ -d "$STATE" ]; then printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$LOG"; fi
+ printf '%s\n' "$*" >&3 2>/dev/null
+ if [ -d "$STATE" ]; then printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$LOG" 2>/dev/null; fi
+ return 0
}
refuse() {
say "$*"
exit 4
}
+# What was typed after `question`, or nothing when there is no one to answer (no terminal, end of input).
+ask() {
+ local answer=""
+ printf '%s' "$1" >&3 2>/dev/null
+ read -r answer || answer=""
+ # A terminal echoes the Enter that ends the answer; anything else does not.
+ [ -t 0 ] || printf '\n' >&3 2>/dev/null
+ printf '%s' "$answer"
+}
compose() { docker compose "$@"; }
container() { compose ps -aq "$SERVICE" 2>/dev/null | head -n 1; }
inspect() { docker inspect -f "$1" "$2" 2>/dev/null; }
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'; }
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"; }
+is_version() { printf '%s' "$1" | grep -Eqx '[0-9]+\.[0-9]+\.[0-9]+'; }
+# True when version $1 is older than version $2 (both X.Y.Z).
+older_than() { [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -t. -k1,1n -k2,2n -k3,3n | head -n 1)" = "$1" ]; }
+
+# The string value of a top-level key of the JSON object on stdin, when the object has that key exactly once and it is
+# a string. Nested objects and arrays (a record's `history`) are stepped over, never matched.
+json_top() {
+ LC_ALL=C awk -v want="$1" '
+ { text = text $0 "\n" }
+ END {
+ n = length(text)
+ depth = 0
+ expect = ""
+ key = ""
+ found = 0
+ value = ""
+ for (i = 1; i <= n; i++) {
+ c = substr(text, i, 1)
+ if (c == "\"") {
+ start = i + 1
+ for (i++; i <= n; i++) {
+ c = substr(text, i, 1)
+ if (c == "\\") i++
+ else if (c == "\"") break
+ }
+ s = substr(text, start, i - start)
+ if (depth == 1 && expect == "value") {
+ if (key == want) { found++; value = s }
+ expect = ""
+ } else if (depth == 1) key = s
+ } else if (c == ":") {
+ if (depth == 1) expect = "value"
+ } else if (c == "{" || c == "[") {
+ if (depth == 1 && expect == "value") { if (key == want) found += 2; expect = "" }
+ depth++
+ } else if (c == "}" || c == "]") {
+ depth--
+ } else if (c == ",") {
+ if (depth == 1) expect = ""
+ } else if (c !~ /[ \t\r\n]/ && depth == 1 && expect == "value") {
+ if (key == want) found += 2
+ expect = ""
+ }
+ }
+ if (found != 1) exit 1
+ print value
+ }'
+}
+
+# GET $1 into BODY. Returns 0 with the body, 1 when there is no such file (HTTP 404, or a file:// path that is not
+# there), 2 when it could not be asked (no network, a timeout, any other answer).
+fetch() {
+ local url=$1 got code rc headers
+ BODY=""
+ if command -v curl >/dev/null 2>&1; then
+ got=$(curl -sSL --max-time 20 -w '\n%{http_code}' "$url" 2>/dev/null)
+ rc=$?
+ code=${got##*$'\n'}
+ BODY=${got%$'\n'*}
+ case "$rc:$code" in
+ 0:200 | 0:000) return 0 ;;
+ 0:404 | 37:*) BODY=""; return 1 ;;
+ *) BODY=""; return 2 ;;
+ esac
+ fi
+ headers=$(mktemp) || return 2
+ BODY=$(wget -S -T 20 -qO- "$url" 2>"$headers")
+ rc=$?
+ if [ "$rc" = 0 ]; then rm -f "$headers"; return 0; fi
+ BODY=""
+ if grep -q 'HTTP/[0-9.]* 404' "$headers"; then rm -f "$headers"; return 1; fi
+ rm -f "$headers"
+ return 2
+}
# The journal: one `key=value` per line, written whole and renamed into place.
J_phase="" J_target="" J_target_id="" J_version="" J_previous="" J_previous_id="" J_previous_version=""
-J_data="" J_backup="" J_engine="" J_caddy="" J_running=""
-JOURNAL_KEYS="phase target target_id version previous previous_id previous_version data backup engine caddy running"
+J_data="" J_backup="" J_engine="" J_caddy="" J_running="" J_started="" J_project=""
+JOURNAL_KEYS="phase target target_id version previous previous_id previous_version data backup engine caddy running started project"
write_record() {
local file=$1 key
for key in $JOURNAL_KEYS; do eval "printf '%s=%s\n' \"$key\" \"\$J_$key\""; done >"$file.tmp" && mv "$file.tmp" "$file"
@@ -87,7 +188,10 @@ phase() {
}
take_lock() {
- mkdir -p "$STATE" && chmod 700 "$STATE"
+ if ! mkdir -p "$STATE" 2>/dev/null || ! chmod 700 "$STATE" 2>/dev/null || [ ! -w "$STATE" ] || [ ! -w "$DIR" ]; then
+ printf '%s\n' "$DIR cannot be written by this user, so the update could not keep its journal or change .env. Nothing was changed. Run it as the user who owns $DIR, or with sudo."
+ exit 4
+ fi
if ! mkdir "$LOCK" 2>/dev/null; then
local other
other=$(cat "$LOCK/pid" 2>/dev/null || true)
@@ -96,26 +200,68 @@ take_lock() {
exit 3
fi
rm -rf "$LOCK"
- mkdir "$LOCK" || exit 3
+ mkdir "$LOCK" 2>/dev/null || { printf '%s\n' "Another update took the lock in $LOCK just now. Wait for it to finish."; exit 3; }
fi
echo $$ >"$LOCK/pid"
trap 'rm -rf "$LOCK"' EXIT
}
-# The copies run in a short-lived container from the server's own image, as root and without a network.
-copy_aside() { # data backup image
- docker volume rm -f "$2" >/dev/null 2>&1
- docker volume create --label com.mausbot.role=update-backup --label "com.mausbot.image=$3" "$2" >/dev/null || return 1
- docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" -v "$2:/to" --entrypoint cp "$3" -a /from/. /to/
+# Helpers run in a short-lived container from the server's own image, as root and without a network.
+helper() { # image, then `-v` mounts as source:target[:ro], then `--` and the shell script
+ local image=$1 mounts=()
+ shift
+ while [ "$1" != -- ]; do mounts+=(-v "$1"); shift; done
+ shift
+ docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper "${mounts[@]}" --entrypoint sh "$image" -c "$1"
+}
+# `same A B` succeeds when the two folders hold the same entries and every file has the same checksum.
+VERIFY='manifest() { (cd "$1" && find . -print | LC_ALL=C sort && find . -type f -exec sha256sum {} + | LC_ALL=C sort); }
+same() {
+ a=$(manifest "$1" | sha256sum) && b=$(manifest "$2" | sha256sum) || return 1
+ if [ "$a" != "$b" ]; then echo "the copy differs from the original"; return 1; fi
+ echo "checked: $(cd "$2" && find . -print | wc -l) entries, every file by checksum"
}
+'
+# A new volume for the copy, named for this update, so the copy from the update before stays until this one is checked.
+new_backup_name() {
+ local base name at=1
+ base="${J_project:-deploy}_data-before-update-$(date -u +%Y%m%dT%H%M%SZ)"
+ name=$base
+ while docker volume inspect "$name" >/dev/null 2>&1; do at=$((at + 1)); name="$base-$at"; done
+ printf '%s' "$name"
+}
+make_backup_volume() { # name image
+ docker volume create --label "$BACKUP_ROLE" --label "com.mausbot.project=$J_project" --label "com.mausbot.data=$J_data" --label "com.mausbot.image=$2" "$1" >/dev/null
+}
+copy_aside() { # data backup image: copy, then check the copy against the data, file by file
+ docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" -v "$2:/to" --entrypoint cp "$3" -a /from/. /to/ || return 1
+ helper "$3" "$1:/from:ro" "$2:/to:ro" -- "$VERIFY"'same /from /to'
+}
+# Every copy of this install's data but the one this update made: dropped once that one has been checked.
+drop_older_copies() {
+ local volume
+ for volume in $(docker volume ls -q --filter "label=$BACKUP_ROLE" --filter "label=com.mausbot.data=$J_data" 2>/dev/null); do
+ [ "$volume" = "$J_backup" ] || docker volume rm -f "$volume" >>"$LOG" 2>&1
+ done
+}
+# Puts the copy back. The copy goes into a new folder in the data first and is checked there; only then are the data's
+# entries swapped for it, by renames on one filesystem. A restore that fails before the swap leaves the data as it was.
put_back() { # backup data image
- docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" -v "$2:/to" --entrypoint sh "$3" \
- -c 'find /to -mindepth 1 -delete && cp -a /from/. /to/'
+ helper "$3" "$1:/from:ro" "$2:/to" -- "$VERIFY"'set -u
+stage=/to/.omb-restore
+old=/to/.omb-replaced
+rm -rf "$stage" "$old"
+mkdir "$stage" || exit 1
+if ! cp -a /from/. "$stage"/ || ! same /from "$stage"; then rm -rf "$stage"; exit 1; fi
+mkdir "$old" || exit 1
+find /to -mindepth 1 -maxdepth 1 ! -name .omb-restore ! -name .omb-replaced -exec mv {} "$old"/ \; || exit 1
+find "$stage" -mindepth 1 -maxdepth 1 -exec mv {} /to/ \; || exit 1
+rmdir "$stage" && rm -rf "$old"'
}
-room_for_copy() { # data image → 0 when there is room, or when it cannot be measured
+room_for_copy() { # data backup image → 0 when there is room where the copy goes, or when it cannot be measured
local sizes used free
- sizes=$(docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" --entrypoint sh "$2" \
- -c 'du -sk /from | cut -f1; df -Pk /from | tail -n 1 | tr -s " " | cut -d" " -f4' 2>/dev/null) || return 0
+ # The copy lands in a Docker volume, under Docker's own folder, which for a bind-mounted data folder is another disk.
+ sizes=$(helper "$3" "$1:/from:ro" "$2:/to" -- 'du -sk /from | cut -f1; df -Pk /to | tail -n 1 | tr -s " " | cut -d" " -f4' 2>/dev/null) || return 0
used=$(printf '%s\n' "$sizes" | sed -n 1p)
free=$(printf '%s\n' "$sizes" | sed -n 2p)
case "$used$free" in '' | *[!0-9]*) return 0 ;; esac
@@ -138,10 +284,17 @@ restore_env() {
elif [ -f "$STATE/env.absent" ]; then rm -f .env; fi
}
+# Stops the whole project and checks that the server's container is no longer running: no copy is taken of live data.
+stop_server() {
+ local cid
+ compose stop >>"$LOG" 2>&1 || return 1
+ cid=$(container)
+ [ -z "$cid" ] || [ "$(inspect '{{.State.Running}}' "$cid")" = false ]
+}
+
answers() { compose exec -T "$SERVICE" sh -c 'curl -sf --max-time 5 "http://127.0.0.1:${OMB_PORT:-8799}/api/health"' 2>/dev/null | grep -q openmausbot; }
reported_version() {
- compose exec -T "$SERVICE" sh -c 'curl -sf --max-time 5 "http://127.0.0.1:${OMB_PORT:-8799}/.well-known/openmausbot/environment"' 2>/dev/null \
- | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'
+ compose exec -T "$SERVICE" sh -c 'curl -sf --max-time 5 "http://127.0.0.1:${OMB_PORT:-8799}/.well-known/openmausbot/environment"' 2>/dev/null | json_top version
}
# `openmausbot doctor`: the server answers and at least one engine can start a bot.
engine_ready() { compose exec -T "$SERVICE" openmausbot doctor ${1:+--wait "$1"} >/dev/null 2>&1; }
@@ -195,20 +348,32 @@ finish() {
say "To go back to it: ./update.sh --rollback"
}
-# Puts back the settings, the data and the image from before the update, then says what happened and exits.
+# Puts back the settings, the data and the image from before the update, then says what happened and exits. The journal
+# stays until the data is back, so a rollback that could not finish is tried again, never forgotten.
roll_back() { # why, exit code when the old version is back
- local why=$1 code=$2 helper_image=$J_previous_id restored=yes back=no
+ local why=$1 code=$2 helper_image=$J_previous_id back=no
trap '' INT TERM
phase rollback
say "$why"
say "Putting back the version and the data from before the update…"
- compose stop >/dev/null 2>&1
- restore_env
- if docker volume inspect "$J_backup" >/dev/null 2>&1; then
- put_back "$J_backup" "$J_data" "$helper_image" >>"$LOG" 2>&1 || restored=no
- else
- restored=missing
+ if ! stop_server; then
+ say "The server could not be stopped (see $LOG), so its data was left as it is. The update's journal is kept: run ./update.sh --rollback again once docker compose stop works."
+ exit 2
fi
+ if ! docker volume inspect "$J_backup" >/dev/null 2>&1; then
+ restore_env
+ compose up -d --no-build >>"$LOG" 2>&1
+ rm -f "$JOURNAL" "$LAST"
+ say "The copy of the data from before the update ($J_backup) is missing, so the data was left as it is. The server runs $(old_name) again."
+ exit 2
+ fi
+ # 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 "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 2
+ fi
+ restore_env
compose up -d --no-build >>"$LOG" 2>&1
if [ "$(inspect '{{.Image}}' "$(container)")" != "$J_previous_id" ]; then
# .env named a tag that has moved since: the image kept aside at the swap is the one that ran.
@@ -217,14 +382,6 @@ roll_back() { # why, exit code when the old version is back
fi
if wait_healthy "$J_previous_id"; then back=yes; fi
rm -f "$JOURNAL" "$LAST"
- if [ "$restored" = missing ]; then
- say "The copy of the data from before the update ($J_backup) is missing, so the data was left as it is. The server runs $(old_name) again."
- exit 2
- fi
- if [ "$restored" = no ]; then
- say "The data could not be put back from the Docker volume $J_backup (see $LOG). That volume still holds it. Do not run another update before the data is back."
- exit 2
- fi
if [ "$back" = no ]; then
say "$(old_name) and its data are back, but it did not become healthy either ($WHY). See: docker compose logs $SERVICE"
exit 2
@@ -233,12 +390,51 @@ roll_back() { # why, exit code when the old version is back
exit "$code"
}
-# Finishes an update that was cut short. `signal`: this run was interrupted; otherwise an earlier one was.
+# An update an earlier run left in its swap, wait or rollback step. Kept when its new version is healthy; otherwise
+# nothing happens to the data until someone who can see what it costs says so.
+earlier_update() {
+ local answer wait=60
+ [ "$WAIT_S" -lt 60 ] 2>/dev/null && wait=$WAIT_S
+ if [ "$J_phase" != rollback ] && [ "$MODE" != rollback ] && WAIT_S=$wait wait_healthy "$J_target_id" "$J_version" && wait_whole; then
+ say "The last update was interrupted after the new version had started, and it is healthy."
+ finish
+ return 0
+ fi
+ if [ "$J_phase" = rollback ]; then
+ say "An earlier update to $(new_name) was being undone, and putting its data back did not finish."
+ elif [ "$MODE" = rollback ]; then
+ say "An earlier update to $(new_name), started ${J_started:-earlier}, did not finish."
+ else
+ say "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."
+ if [ "$MODE" = rollback ] && [ "$ASSUME_YES" = yes ]; then
+ answer=yes
+ elif [ "$MODE" = rollback ]; then
+ answer=$(ask "Type yes to go back: ")
+ else
+ answer=$(ask "Type yes to go back, or keep to leave the server as it is and forget that update: ")
+ fi
+ case "$MODE:$answer" in
+ rollback:yes) roll_back "Going back, as asked." 0 ;;
+ update:yes) roll_back "Going back, as asked." 1 ;;
+ 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."
+ ;;
+ *) refuse "Nothing was changed. The unfinished update stays recorded in $JOURNAL, and the next ./update.sh asks again." ;;
+ esac
+}
+
+# Finishes or undoes an update that was cut short. `signal`: this run was interrupted; otherwise an earlier one was.
recover() {
local how=${1:-}
read_record "$JOURNAL" || return 0
case "$J_phase" in
pull)
+ # Only this update's own, new copy is removed; the copy from the update before is never touched here.
+ [ -n "$J_backup" ] && docker volume rm -f "$J_backup" >/dev/null 2>&1
rm -f "$JOURNAL"
[ -n "$how" ] && say "Stopped before anything was changed."
;;
@@ -248,34 +444,29 @@ recover() {
rm -f "$JOURNAL"
say "The update stopped while it copied the data aside. Nothing was changed, and the server was started again."
;;
- wait)
- if [ -z "$how" ] && WAIT_S=60 wait_healthy "$J_target_id" "$J_version" && wait_whole; then
- say "The last update was interrupted after the new version had started, and it is healthy."
- finish
- return 0
- fi
- roll_back "The update to $(new_name) was interrupted before the new version proved healthy." 1
- ;;
- swap | rollback)
- roll_back "The update to $(new_name) was interrupted." 1
+ swap | wait | rollback)
+ if [ -n "$how" ]; then roll_back "The update to $(new_name) was interrupted." 1; fi
+ earlier_update
;;
*) rm -f "$JOURNAL" ;;
esac
}
+# Ctrl-C undoes only what this run started. While it looks at or asks about an earlier run's update, nothing changes.
+THIS_RUN=no
interrupted() {
trap '' INT TERM
say ""
say "Interrupted."
- recover signal
+ if [ "$THIS_RUN" = yes ]; then recover signal; else say "Nothing was changed."; fi
exit 130
}
usage() {
- sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'
+ sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'
exit "${1:-0}"
}
-MODE=update WANT_VERSION="" WANT_IMAGE="" ASSUME_YES=no REPLACE_BUILD=no
+MODE=update WANT_VERSION="" WANT_IMAGE="" ASSUME_YES=no REPLACE_BUILD=no ALLOW_OLDER=no
while [ $# -gt 0 ]; do
case "$1" in
--version) [ $# -ge 2 ] || usage 4; WANT_VERSION=${2#v}; shift ;;
@@ -285,12 +476,13 @@ while [ $# -gt 0 ]; do
--rollback) MODE=rollback ;;
--yes | -y) ASSUME_YES=yes ;;
--replace-local-build) REPLACE_BUILD=yes ;;
+ --allow-older) ALLOW_OLDER=yes ;;
-h | --help) usage 0 ;;
*) printf 'Unknown option: %s\n\n' "$1"; usage 4 ;;
esac
shift
done
-if [ -n "$WANT_VERSION" ] && ! printf '%s' "$WANT_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then refuse "--version takes a released version such as 0.1.151."; fi
+if [ -n "$WANT_VERSION" ] && ! is_version "$WANT_VERSION"; then refuse "--version takes a released version such as 0.1.151."; fi
docker 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"
@@ -304,44 +496,78 @@ fi
if [ "$MODE" = rollback ]; then
read_record "$LAST" || refuse "There is no earlier update to go back from."
if [ "$ASSUME_YES" != yes ]; then
- printf '%s\n' "This puts back $(old_name) and the data as it was before the last update."
- printf '%s' "Everything made since then (chats, files, settings) is lost. Type yes to go on: "
- read -r answer
- [ "$answer" = yes ] || refuse "Nothing was changed."
+ say "This puts back $(old_name) and the data as it was before the last update${J_started:+ (taken $J_started)}."
+ [ "$(ask "Everything made since then (chats, files, settings) is lost. Type yes to go on: ")" = yes ] || refuse "Nothing was changed."
fi
roll_back "Going back, as asked." 0
fi
+# A fresh record for this update: nothing of a journal read above carries over.
+J_phase="" J_target="" J_target_id="" J_version="" J_engine="" J_caddy="" J_started=""
CID=$(container)
[ -n "$CID" ] || refuse "This install has no server yet. Start it once first: docker compose up -d"
J_previous_id=$(inspect '{{.Image}}' "$CID")
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")
-PROJECT=$(inspect '{{index .Config.Labels "com.docker.compose.project"}}' "$CID")
-J_backup="${PROJECT:-deploy}_data-before-update"
+J_project=$(inspect '{{index .Config.Labels "com.docker.compose.project"}}' "$CID")
[ -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
+# branch, not a version, and says the version of the release it was built after.
+RUNNING_VERSION=""
+[ "$J_running" = yes ] && RUNNING_VERSION=$(reported_version)
+is_version "$RUNNING_VERSION" || RUNNING_VERSION=$J_previous_version
+CHANNEL=""
if [ -n "$WANT_IMAGE" ]; then
J_target=$WANT_IMAGE
- J_version=""
elif [ -n "$WANT_VERSION" ]; then
J_target="$REPO:v$WANT_VERSION"
J_version=$WANT_VERSION
else
- if command -v curl >/dev/null 2>&1; then RECORD=$(curl -fsSL --max-time 20 "$STABLE_URL" 2>/dev/null)
- else RECORD=$(wget -qO- -T 20 "$STABLE_URL" 2>/dev/null); fi
- [ -n "${RECORD:-}" ] || refuse "Could not read the stable channel ($STABLE_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z"
- RECORD=$(printf '%s' "$RECORD" | tr -d '\n\r')
- J_target=$(printf '%s' "$RECORD" | sed -n 's/.*"image"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
- J_version=$(printf '%s' "$RECORD" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([0-9][0-9.]*\)".*/\1/p')
- printf '%s' "$J_target" | grep -Eq "$PINNED" || refuse "The stable channel names no image this script accepts. Nothing was changed."
+ fetch "$STABLE_URL"
+ case $? in
+ 0)
+ CHANNEL=stable
+ J_target=$(printf '%s' "$BODY" | json_top image)
+ J_version=$(printf '%s' "$BODY" | json_top version)
+ printf '%s' "$J_target" | grep -Eq "$PINNED" && is_version "$J_version" || refuse "The stable channel names no image this script accepts. Nothing was changed."
+ ;;
+ 1)
+ # No version has been made stable yet: the newest release, as the server's own update check says then.
+ fetch "$NEWEST_URL" || refuse "Could not find the newest release ($NEWEST_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z"
+ J_version=$(printf '%s' "$BODY" | json_top tag_name)
+ J_version=${J_version#v}
+ is_version "$J_version" || refuse "The newest release names no version this script accepts. Nothing was changed."
+ CHANNEL=newest
+ J_target="$REPO:v$J_version"
+ ;;
+ *) refuse "Could not read the stable channel ($STABLE_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z" ;;
+ esac
fi
+# Why the version asked for may not replace the one running without --allow-older, or nothing.
+older_reason() {
+ if [ -z "$J_version" ]; then
+ printf '%s' "$J_target names no released version, so this cannot tell whether it is older than the version running."
+ elif [ -z "$RUNNING_VERSION" ]; then
+ printf '%s' "This cannot tell which version the server runs (it does not answer, and its image names no released version), so it cannot tell whether $J_version is older."
+ elif older_than "$J_version" "$RUNNING_VERSION"; then
+ printf '%s' "This server runs $RUNNING_VERSION, which is newer than $J_version. An older version may not read what a newer one wrote."
+ elif [ "$J_version" = "$RUNNING_VERSION" ] && [ -z "$J_previous_version" ]; then
+ printf '%s' "This server runs a build of main that says $RUNNING_VERSION, and may hold changes made after $J_version was released. It moves to stable by itself once a version newer than $RUNNING_VERSION is stable."
+ fi
+}
+
if [ "$MODE" = check ]; then
- printf '%s\n' "This server runs $(old_name)."
+ [ -n "$J_version" ] || J_version=$(image_version "$J_target")
+ if [ -n "$RUNNING_VERSION" ] && [ "$RUNNING_VERSION" != "$J_previous_version" ]; then printf '%s\n' "This server runs $(old_name), which says it is $RUNNING_VERSION."
+ else printf '%s\n' "This server runs $(old_name)."; fi
+ [ "$CHANNEL" = newest ] && printf '%s\n' "No version has been made stable yet, so ./update.sh takes the newest release, $J_version."
+ [ -f "$JOURNAL" ] && printf '%s\n' "An earlier update did not finish. ./update.sh first says what it would cost to go back, and asks."
if [ -n "$J_previous" ] && [ "$J_previous" = "$J_target" ]; then printf '%s\n' "That is the version asked for. Nothing to do."
+ elif [ "$ALLOW_OLDER" != yes ] && [ -n "$(older_reason)" ]; then printf '%s\n' "$(older_reason)" "./update.sh would change nothing without --allow-older."
else printf '%s\n' "./update.sh would update it to $(new_name)."; fi
exit 0
fi
@@ -350,10 +576,19 @@ if [ -z "$J_previous" ] && [ "$REPLACE_BUILD" != yes ]; then
refuse "This server runs an image built on this machine (docker compose up --build), with whatever ENGINES you baked into it. To stay on your own build: git pull && docker compose up -d --build. To move to the published image instead: ./update.sh --replace-local-build"
fi
+J_backup=$(new_backup_name)
+# Gives up before anything was changed: this update's journal and its own, new copy go; nothing else does.
+BACKUP_MADE=no
+abandon() {
+ [ "$BACKUP_MADE" = yes ] && docker volume rm -f "$J_backup" >/dev/null 2>&1
+ rm -f "$JOURNAL"
+}
+THIS_RUN=yes
phase pull
+[ "$CHANNEL" = newest ] && say "No version has been made stable yet, so this takes the newest release, $J_version."
say "Downloading $(new_name)…"
if ! docker pull -q "$J_target" >>"$LOG" 2>&1 && [ -z "$(image_id "$J_target")" ]; then
- rm -f "$JOURNAL"
+ abandon
refuse "Could not download $J_target (see $LOG). Nothing was changed."
fi
J_target_id=$(image_id "$J_target")
@@ -364,17 +599,24 @@ esac
[ -n "$J_version" ] || J_version=$(image_version "$J_target_id")
if [ "$J_target_id" = "$J_previous_id" ]; then
- rm -f "$JOURNAL"
+ abandon
say "This server already runs $(new_name). Nothing to do."
exit 0
fi
+if [ "$ALLOW_OLDER" != yes ] && [ -n "$(older_reason)" ]; then
+ abandon
+ say "$(older_reason)"
+ say "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 5
+fi
if ! OMB_IMAGE="$J_target" docker compose config 2>/dev/null | grep -qF "image: $J_target"; then
- rm -f "$JOURNAL"
+ abandon
refuse "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
-if ! room_for_copy "$J_data" "$J_previous_id"; then
- rm -f "$JOURNAL"
- refuse "There is not enough free disk for a copy of the data: it needs about $NEEDED_MB MB and $FREE_MB MB are free. Free some space, then run this again. Nothing was changed."
+BACKUP_MADE=yes
+if ! make_backup_volume "$J_backup" "$J_previous_id" || ! room_for_copy "$J_data" "$J_backup" "$J_previous_id"; then
+ abandon
+ refuse "There is not enough free disk for a copy of the data: it needs about ${NEEDED_MB:-?} MB and ${FREE_MB:-?} MB are free. Free some space, then run this again. Nothing was changed."
fi
J_engine=unknown
@@ -384,20 +626,30 @@ if [ "$J_running" = yes ]; then
caddy_runs && J_caddy=running
fi
+J_started=$(date -u +%Y-%m-%dT%H:%M:%SZ)
phase backup
say "Stopping the server and copying its data aside…"
-rm -f "$LAST"
-compose stop >>"$LOG" 2>&1
-if ! copy_aside "$J_data" "$J_backup" "$J_previous_id" >>"$LOG" 2>&1; then
+copied=no
+if stop_server; then
+ if copy_aside "$J_data" "$J_backup" "$J_previous_id" >>"$LOG" 2>&1; then copied=yes; fi
+ why="Copying the data aside failed, or the copy did not match the data (see $LOG)."
+else
+ why="The server could not be stopped (see $LOG), so its data was not copied."
+fi
+if [ "$copied" != yes ]; then
docker volume rm -f "$J_backup" >/dev/null 2>&1
[ "$J_running" = yes ] && compose up -d --no-build >>"$LOG" 2>&1
rm -f "$JOURNAL"
- refuse "Copying the data aside failed (see $LOG). Nothing was changed, and the server was started again."
+ refuse "$why Nothing was changed, and the server was started again."
fi
keep_env
docker tag "$J_previous_id" "$KEEP_TAG" >/dev/null 2>&1
phase swap
+# The new copy is checked, and from here on an interruption puts it back: the copy from the update before may go now,
+# and with it the way back to that one.
+rm -f "$LAST"
+drop_older_copies
say "Starting $(new_name)…"
pin_image "$J_target"
# Where Caddy waits for a healthy server, `up` itself fails when the new version never gets there; the wait below
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index 4f3b13079c..7ff733964e 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -286,50 +286,88 @@ curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy
sudo bash update.sh --dir /opt/openmausbot
```
+Until a first version has been made stable, `./update.sh` takes the newest
+release instead, as **Check for updates** does then.
+
The data may be a Docker volume or a folder on the server; the copy keeps
every file's owner and mode either way. The script then:
1. Downloads the stable image, by its digest. If that fails it stops, and
- nothing has changed.
-2. Checks there is room for a copy of your data, stops the server, and copies
- everything under `/data` into a Docker volume
- (`deploy_data-before-update`; `openmausbot_data-before-update` for
- `/opt/openmausbot`). The server is down from here until step 4;
- how long depends on how much data there is.
+ nothing has changed. It also stops, changing nothing, when that version is
+ older than the one your server says it runs (see "From `latest` to stable"
+ below).
+2. Checks there is room for a copy of your data where Docker keeps its
+ volumes, stops the server, checks that it has stopped, and copies
+ everything under `/data` into a new Docker volume named for the update
+ (`deploy_data-before-update-20261110T120000Z`;
+ `openmausbot_data-before-update-…` for `/opt/openmausbot`). It then
+ compares the copy with the data, every file by checksum; a copy that does
+ not match is thrown away, the server is started again, and nothing has
+ changed. The copy from the update before is removed only after this one
+ has matched. The server is down from here until step 4; how long depends
+ on how much data there is.
3. Writes the image into `.env` (`OMB_IMAGE=ghcr.io/milind-soni/openmausbot@sha256:…`)
and starts it.
4. Waits, up to five minutes, until the new server answers `/api/health`
steadily, says it is the new version, can still start a bot if it could
before (`openmausbot doctor`: an engine is ready), and Caddy runs again.
-5. If any of that fails: puts back `.env`, the data from the copy and the old
+5. If any of that fails: puts back the data from the copy, `.env` and the old
image, starts the old version, and tells you what went wrong. Your server
- is as it was before step 1.
-
-It is safe to interrupt and to run twice. Each step is written to
-`deploy/.update/journal` before it starts, so after Ctrl-C, a closed terminal or
-a reboot, the next `./update.sh` first finishes what was cut short: it keeps
-the new version if that is up and healthy, and otherwise puts the old one
-back. Run again after a finished update, it says there is nothing to do. Two
-runs at once are refused.
+ is as it was before step 1. The copy is put into a new folder inside the
+ data and checked there before it takes the data's place, so a restore that
+ fails (a full disk, say) leaves both the data and the copy as they were:
+ the server stays stopped, the update's journal is kept, and
+ `./update.sh --rollback` tries again once the cause is fixed.
+
+A closed terminal or a dropped SSH session does not stop an update: it carries
+on, and `deploy/.update/update.log` says how it ended. Each step is written to
+`deploy/.update/journal` before it starts. Ctrl-C undoes the update at once:
+before the new version starts, nothing has changed; after, the old version and
+its data are put back. When an update was cut short some other way (a reboot,
+a killed process), the next `./update.sh` keeps the new version if that is up
+and healthy. If it is not, it says which version and data going back would put
+back, and that everything made on the server since that update would be lost,
+and asks: `yes` goes back, `keep` leaves the server as it is (the copy stays
+for `--rollback`), and anything else, or no answer at all, changes nothing.
+Run again after a finished update, it says there is nothing to do. Two runs at
+once are refused.
```sh
./update.sh --check # what would change; changes nothing
./update.sh --version 0.1.151 # one released version instead of the stable one
./update.sh --rollback # the version and the data from before the last update
+./update.sh --allow-older # go ahead although that version is not newer than the one running
```
`--rollback` is for an update that passed its checks and still turned out
wrong. It asks first, because everything made since the update (chats, files,
-settings) is replaced by the copy. The copy is kept until the next update
-replaces it. The script's own log is `deploy/.update/update.log`.
+settings) is replaced by the copy; `--yes` answers for you. The copy is kept
+until the next update has made and checked its own. The script's own log is
+`deploy/.update/update.log`.
| The script ends with | Meaning |
| --- | --- |
| `0` | Updated, or already on that version |
| `1` | The update failed; the old version and its data are back |
-| `2` | The update failed and the old version did not come back healthy; read the last lines it printed |
+| `2` | The old version or its data could not be brought back; read the last lines it printed, then `./update.sh --rollback` |
| `3` | Another update is running |
-| `4` | Nothing was changed (could not download, not enough disk, refused) |
+| `4` | Nothing was changed (could not download, not enough disk, the folder cannot be written, a question not answered `yes`, refused) |
+| `5` | Nothing was changed: the version asked for is older than the one running, or one of the two versions cannot be told; `--allow-older` goes ahead |
+| `130` | Interrupted with Ctrl-C before the new version started: nothing was changed, and the server was started again |
+
+### From `latest` to stable
+
+A server started from the `latest` image runs a build of `main`. Its image is
+labelled with the branch, not a version, so `update.sh` goes by the version the
+server itself reports, which is that of the release it was built after, or of
+the next one. Such a build may already hold changes made after that release,
+and may have written data in ways the release does not read. So `update.sh`
+moves it to stable only once the stable version is newer than the version the
+server reports; until then it says so and changes nothing (exit `5`). Nothing
+else is needed: the first `./update.sh` after a newer version is made stable
+moves the server onto it and pins it by digest. To move now anyway, run
+`./update.sh --allow-older`; the data is copied first, and `--rollback` puts
+the `latest` build and its data back.
If you built the image yourself (`docker compose up -d --build`, with
`ENGINES` baked in), `update.sh` refuses to replace it without being told to:
diff --git a/docs/releasing.md b/docs/releasing.md
index 8439f4b999..1d4934ced2 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -66,14 +66,22 @@ The workflow builds nothing. It:
4. moves the `stable` tag of `ghcr.io/milind-soni/openmausbot` and of
`ghcr.io/milind-soni/openmausbot-cloud-home` to those digests;
5. commits `stable.json` (version, both images by digest, and every version
- that was stable in the last 90 days) to the `channels` branch.
+ that was stable in the last 90 days) to the `channels` branch. When that
+ fails after the tags moved, the tags are put back to the digests the
+ published record still names.
+
+It reads the current record before it writes the next one. Only a `channels`
+branch that does not exist counts as "no record yet"; any other failure to read
+it stops the run, so a network error never skips the move-back check or drops
+the history.
Servers read
`https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json`:
the update check (`server/update-check.ts`) for the version, and
`deploy/update.sh` for the image to pull. `latest` still follows `main` and is
never moved by this workflow. Running it again with the same version changes
-nothing, and repairs a run that stopped between the tag and the record. The
+nothing, and repairs a run that stopped between the tag and the record.
+Until a first version is promoted, both fall back to the newest release. The
`channels` branch is written only by this workflow; do not edit it by hand.
The checks live in `scripts/stable-channel.mjs`.
@@ -91,11 +99,12 @@ held to the same steps and the same promises:
| --- | --- | --- |
| Image by digest, before anything stops | `ensureImage`, `checkImage` | `docker pull` of the record's `…@sha256:…` |
| Room for the copy | `ensureRoomForCopy` | `room_for_copy` |
-| Stop, copy `/data` aside | `stopAndCopy` → volume `mausbot-snapshot` | `copy_aside` → volume `<project>_data-before-update` |
+| Stop, copy `/data` aside | `stopAndCopy` → volume `mausbot-snapshot` | `stop_server` (checked stopped), `copy_aside` → a new volume `<project>_data-before-update-<time>`, compared with the data file by file; the copy before it is removed only then |
+| Never older | the update runner refuses an older image (exit 5) | `older_reason`: by the version the server reports; exit 5 unless `--allow-older` |
| Start the new image | `createContainer`, `startHome` | `OMB_IMAGE` in `.env`, `docker compose up -d` |
| Healthy, and bots can start | signed health report names the image; the bot box still passes every check it passed before | `/api/health` three times running, the version it reports, `openmausbot doctor` if it passed before, Caddy |
-| On failure | `rollBack`: old image and the copy, reply `update_rolled_back` | `roll_back`: `.env`, the copy and the old image, exit 1 with the reason |
-| Interrupted | the operation in `home.json`; `recover` at the next start | `.update/journal`; the next run, or the signal handler |
+| On failure | `rollBack`: old image and the copy, reply `update_rolled_back` | `roll_back`: the copy (into a new folder, checked, then swapped in), `.env` and the old image, exit 1 with the reason; a restore that fails keeps the journal, exit 2 |
+| Interrupted | the operation in `home.json`; `recover` at the next start | `.update/journal`; a hangup is ignored, Ctrl-C undoes at once, and the next run keeps a healthy new version or asks before it puts data back |
| Run twice | a job id is answered again, never run again | "already runs …, nothing to do" |
`connector/test/home.test.ts` and `connector/e2e/run.sh` hold the connector to
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 0ba0e37b12..0c622ad4c4 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -1457,7 +1457,11 @@ git pull && pnpm install && sudo systemctl restart openmausbot # from s
`deploy/update.sh` is the whole routine for a Docker Compose install: the
stable image by digest, a copy of `/data` first, a health check that includes
"an engine can still start a bot", and the old image and the copy put back
-when the check fails. It is safe to interrupt and to run twice.
+when the check fails. It is safe to interrupt and to run twice, carries on
+when the terminal closes, never goes to an older version unless told to
+(`--allow-older`; a server on `latest` moves to stable once the stable version
+is newer than the one it reports), and asks before it puts back data from an
+update an earlier run left unfinished.
[Every step, the rollback and the exit codes](deploy-vps.md#update).
For the npm service there is no one-command updater yet:
diff --git a/scripts/testing/deploy-update.test.ts b/scripts/testing/deploy-update.test.ts
index 6c603e264f..392e1344bd 100644
--- a/scripts/testing/deploy-update.test.ts
+++ b/scripts/testing/deploy-update.test.ts
@@ -30,6 +30,12 @@ function tree(dir: string, prefix = ""): Record<string, string> {
return files;
}
+/** A stable.json as promote-stable.yml writes it: the newest entry first, then every version stable before it. */
+function stableRecord(version: string, image: string, earlier: string[] = []) {
+ const history = [version, ...earlier].map((entry, at) => ({ version: entry, promotedAt: `2026-11-${String(10 - at).padStart(2, "0")}T00:00:00.000Z` }));
+ return JSON.stringify({ channel: "stable", version, image, cloudHomeImage: `${REPO}-cloud-home@${id("9")}`, platforms: ["linux/amd64", "linux/arm64"], promotedAt: history[0]!.promotedAt, history }, null, 2);
+}
+
/** A Compose install on version 0.1.150 with some data, and a stable channel that names `target`. */
function install(target: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) {
const root = mkdtempSync(join(tmpdir(), "omb-update-"));
@@ -55,25 +61,34 @@ function install(target: Record<string, unknown> = {}, extra: Record<string, unk
containers: { omb: { id: "omb-1", image: OLD.id, status: "running", restarts: 0 }, caddy: { id: "caddy-1", status: "running" } },
...extra,
}));
- writeFileSync(join(root, "stable.json"), JSON.stringify({ channel: "stable", version: next.version, image: next.refs[0], history: [{ version: next.version, promotedAt: "2026-11-10T00:00:00Z" }] }, null, 2));
+ writeFileSync(join(root, "stable.json"), stableRecord(next.version, next.refs[0]!));
const state = () => JSON.parse(readFileSync(join(fake, "state.json"), "utf8"));
const run = (args: string[] = [], options: { input?: string; env?: Record<string, string> } = {}) => {
const result = spawnSync("bash", [join(deploy, "update.sh"), ...args], {
encoding: "utf8", input: options.input ?? "", timeout: 60_000,
env: {
- PATH: `${join(root, "bin")}:/usr/bin:/bin`, HOME: root, FAKE_DOCKER_DIR: fake, OMB_STABLE_URL: `file://${join(root, "stable.json")}`,
+ // sbin: sha256sum is /sbin/sha256sum on macOS.
+ PATH: `${join(root, "bin")}:/usr/bin:/bin:/usr/sbin:/sbin`, HOME: root, FAKE_DOCKER_DIR: fake,
+ 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", ...wait, ...options.env,
},
});
return { ...result, said: result.stdout.trim().split("\n") };
};
const calls = () => (existsSync(join(fake, "calls.log")) ? readFileSync(join(fake, "calls.log"), "utf8").trim().split("\n") : []);
+ /** The copies of the data an update made, oldest first: one Docker volume each. */
+ const copies = () => readdirSync(join(fake, "volumes")).filter((name) => name.startsWith("deploy_data-before-update-")).sort();
return {
- root, deploy, fake, data, state, run, calls,
+ root, deploy, fake, data, state, run, calls, copies,
setState: (patch: Record<string, unknown>) => writeFileSync(join(fake, "state.json"), JSON.stringify({ ...state(), ...patch })),
env: () => readFileSync(join(deploy, ".env"), "utf8"),
- backup: () => join(fake, "volumes", "deploy_data-before-update"),
+ backup: () => {
+ const [only, ...more] = copies();
+ if (!only || more.length) throw new Error(`expected one copy of the data, found: ${copies().join(", ")}`);
+ return join(fake, "volumes", only);
+ },
journal: () => existsSync(join(deploy, ".update", "journal")),
+ last: () => existsSync(join(deploy, ".update", "last")),
};
}
@@ -93,9 +108,10 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
"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 Docker volume deploy_data-before-update until the next update.",
+ `The data from before the update is kept in the Docker volume ${box.copies()[0]} until the next update.`,
"To go back to it: ./update.sh --rollback",
]);
+ expect(box.copies()).toEqual([expect.stringMatching(/^deploy_data-before-update-\d{8}T\d{6}Z$/)]);
expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);
expect(box.state().containers.omb).toMatchObject({ image: NEW.id, status: "running" });
expect(tree(box.backup())).toEqual(before);
@@ -104,13 +120,16 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
const calls = box.calls();
const order = [
calls.findIndex((call) => call.startsWith("pull")), calls.indexOf("compose stop"), calls.findIndex((call) => call.includes("--entrypoint cp")),
- calls.findIndex((call) => call.startsWith("compose up")), calls.findLastIndex((call) => call.includes("/api/health")),
+ calls.findIndex((call) => call.includes("same /from /to")), calls.findIndex((call) => call.startsWith("compose up")),
+ calls.findLastIndex((call) => call.includes("/api/health")),
];
expect(order.every((at) => at >= 0)).toBe(true);
expect(order).toEqual([...order].sort((a, b) => a - b));
expect(calls.find((call) => call.includes("--entrypoint cp"))).toBe(
- `run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v deploy_data:/from:ro -v deploy_data-before-update:/to --entrypoint cp ${OLD.id} -a /from/. /to/`,
+ `run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v deploy_data:/from:ro -v ${box.copies()[0]}:/to --entrypoint cp ${OLD.id} -a /from/. /to/`,
);
+ // The server was stopped, and seen to be stopped, before the copy.
+ expect(calls.slice(calls.indexOf("compose stop"), calls.findIndex((call) => call.includes("--entrypoint cp"))).some((call) => call.includes("{{.State.Running}}"))).toBe(true);
});
it("changes nothing when it is run again", () => {
@@ -120,7 +139,7 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
const again = box.run();
expect(again.status).toBe(0);
expect(again.said).toEqual(["Downloading 0.1.151…", "This server already runs 0.1.151. Nothing to do."]);
- expect(box.calls().slice(calls).some((call) => /^(compose (stop|up)|run|volume)/.test(call))).toBe(false);
+ expect(box.calls().slice(calls).some((call) => /^(compose (stop|up)|run|volume (create|rm))/.test(call))).toBe(false);
expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);
});
@@ -191,9 +210,9 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
const before = tree(box.data);
const refused = box.run();
expect(refused.status).toBe(4);
- expect(refused.said.at(-1)).toMatch(/^Copying the data aside failed .* Nothing was changed, and the server was started again\.$/);
+ expect(refused.said.at(-1)).toMatch(/^Copying the data aside failed, .* Nothing was changed, and the server was started again\.$/);
expect(box.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });
- expect(existsSync(box.backup())).toBe(false);
+ expect(box.copies()).toEqual([]);
expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });
});
@@ -226,7 +245,7 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
expect(done.status, done.stdout + done.stderr).toBe(0);
});
- it("finishes an update that was killed while the new version started: the next run puts the old one back", () => {
+ it("asks before it undoes an update an earlier run left unhealthy, says what that loses, and changes nothing without a yes", () => {
const box = install({ behaviour: "silent" }, { signalOn: { step: "compose up", signal: "SIGKILL" } });
const before = tree(box.data);
const killed = box.run();
@@ -235,10 +254,21 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
expect(box.env()).toContain("OMB_IMAGE=");
const next = box.run(["--check"]);
expect(next.status).toBe(0);
+ expect(next.stdout).toContain("An earlier update did not finish.");
expect(box.journal()).toBe(true);
- const repaired = box.run();
- expect(repaired.said.slice(0, 3)).toEqual([
- "The update to 0.1.151 was interrupted.",
+ // The new version has been running on the data since: nothing may take that away unasked.
+ const since = tree(box.data);
+ for (const unanswered of [box.run(), box.run([], { input: "no\n" }), box.run(["--rollback"])]) {
+ expect(unanswered.status).toBe(4);
+ expect(unanswered.stdout).toMatch(/An earlier update to 0\.1\.151, started \S+Z, did not finish/);
+ expect(unanswered.stdout).toContain("Everything made on this server since then (chats, files, settings) is lost.");
+ expect(unanswered.said.at(-1)).toContain("Nothing was changed.");
+ expect(tree(box.data)).toEqual(since);
+ expect(box.journal()).toBe(true);
+ }
+ const repaired = box.run([], { input: "yes\n" });
+ expect(repaired.said.slice(-3)).toEqual([
+ "Going back, as asked.",
"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.",
]);
@@ -249,7 +279,7 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
});
it("keeps a new version that turned out healthy when the update was killed while waiting for it", () => {
- const box = install({}, { signalOn: { step: "compose exec -T omb sh", signal: "SIGKILL" } });
+ const box = install({}, { signalOn: { match: "/api/health", signal: "SIGKILL" } });
expect(box.run().signal).toBe("SIGKILL");
const next = box.run();
expect(next.status).toBe(0);
@@ -259,7 +289,7 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
});
it("on Ctrl-C while copying, starts the server again with nothing changed; while waiting, puts the old version back", () => {
- const copying = install({}, { signalOn: { step: "run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v deploy_data:/from:ro -v deploy_data-before-update:/to", signal: "SIGINT" } });
+ const copying = install({}, { signalOn: { match: "--entrypoint cp ", signal: "SIGINT" } });
const stopped = copying.run();
expect(stopped.status).toBe(130);
expect(stopped.stdout).toContain("The update stopped while it copied the data aside. Nothing was changed, and the server was started again.");
@@ -267,7 +297,7 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
expect(copying.env()).toBe(ENV);
expect(copying.journal()).toBe(false);
- const waiting = install({}, { signalOn: { step: "compose exec -T omb sh", signal: "SIGTERM" } });
+ const waiting = install({}, { signalOn: { match: "/api/health", signal: "SIGTERM" } });
const before = tree(waiting.data);
const back = waiting.run();
expect(back.status).toBe(1);
@@ -302,13 +332,36 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
expect(box.env()).toBe(ENV);
});
- it("says so, and leaves the copy alone, when the data cannot be put back", () => {
+ it("when the data cannot be put back: leaves the data and the copy as they are, keeps the journal, and tries again only when asked", () => {
const box = install({ behaviour: "silent" }, { failRestore: true });
const before = tree(box.data);
const failed = box.run();
expect(failed.status).toBe(2);
- expect(failed.said.at(-1)).toContain("The data could not be put back from the Docker volume deploy_data-before-update");
+ expect(failed.stdout).toContain(`The data could not be put back from the Docker volume ${box.copies()[0]}`);
+ expect(failed.said.at(-1)).toContain("./update.sh --rollback tries again");
+ // Nothing half-restored, no old version started on the data the new one left, and nothing forgotten.
+ const left = tree(box.data);
+ expect(left).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.151\n" });
expect(tree(box.backup())).toEqual(before);
+ expect(box.state().containers.omb.status).toBe("exited");
+ expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);
+ expect(box.journal()).toBe(true);
+
+ // The next update neither replaces the copy nor touches the data until someone says yes.
+ box.setState({ failRestore: false });
+ const next = box.run();
+ expect(next.status).toBe(4);
+ expect(next.stdout).toContain("was being undone, and putting its data back did not finish.");
+ expect(tree(box.data)).toEqual(left);
+ expect(tree(box.backup())).toEqual(before);
+ expect(box.calls().filter((call) => call.includes("--entrypoint cp"))).toHaveLength(1);
+
+ const back = box.run(["--rollback", "--yes"]);
+ expect(back.status, back.stdout).toBe(0);
+ expect(back.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");
+ expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });
+ expect(box.env()).toBe(ENV);
+ expect(box.journal()).toBe(false);
});
it("updates to a named version, and --check changes nothing", () => {
@@ -322,4 +375,154 @@ describe.skipIf(!posix)("deploy/update.sh", () => {
expect(box.calls()).toContain(`pull -q ${REPO}:v0.1.151`);
expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);
});
+
+ it("reads the version from the record's top level, whatever its history holds", () => {
+ const box = install();
+ writeFileSync(join(box.root, "stable.json"), stableRecord("0.1.151", NEW.refs[0]!, ["0.1.150", "0.1.149", "0.1.148"]));
+ const done = box.run();
+ expect(done.status, done.stdout).toBe(0);
+ expect(done.said).toContain("Updated from 0.1.150 to 0.1.151.");
+ // Keys in any order, on one line, with the history before the version.
+ const again = install();
+ writeFileSync(join(again.root, "stable.json"), JSON.stringify({ history: [{ version: "0.1.151" }, { version: "0.1.140" }], image: NEW.refs[0], version: "0.1.151" }));
+ expect(again.run().said).toContain("Updated from 0.1.150 to 0.1.151.");
+ // A record whose top level names no version is refused, not read from its history.
+ const bare = install();
+ writeFileSync(join(bare.root, "stable.json"), JSON.stringify({ image: NEW.refs[0], history: [{ version: "0.1.151" }] }));
+ const refused = bare.run();
+ expect(refused.status).toBe(4);
+ expect(refused.stdout).toContain("The stable channel names no image this script accepts.");
+ });
+
+ it("carries on when the terminal closes in the middle of an update", () => {
+ const box = install({}, { signalOn: { match: "/api/health", signal: "SIGHUP" } });
+ const done = box.run();
+ expect(done.signal).toBe(null);
+ expect(done.status, done.stdout).toBe(0);
+ expect(done.said).toContain("Updated from 0.1.150 to 0.1.151.");
+ expect(box.state().containers.omb.image).toBe(NEW.id);
+ expect(box.journal()).toBe(false);
+ });
+
+ it("on Ctrl-C while it looks at an earlier run's unfinished update, changes nothing", () => {
+ const box = install({ behaviour: "silent" }, { signalOn: { step: "compose up", signal: "SIGKILL" } });
+ expect(box.run().signal).toBe("SIGKILL");
+ const since = tree(box.data);
+ box.setState({ signalOn: { match: "State.Status", signal: "SIGINT" } });
+ const stopped = box.run([], { input: "yes\n" });
+ expect(stopped.status).toBe(130);
+ expect(stopped.said.slice(-2)).toEqual(["Interrupted.", "Nothing was changed."]);
+ expect(box.journal()).toBe(true);
+ expect(tree(box.data)).toEqual(since);
+ expect(box.calls().some((call) => call.includes(".omb-restore"))).toBe(false);
+ });
+
+ it("keeps the server as it is when an earlier update is left unfinished and the owner says keep", () => {
+ const box = install({ behaviour: "silent" }, { signalOn: { match: "/api/health", signal: "SIGKILL" } });
+ expect(box.run().signal).toBe("SIGKILL");
+ const kept = box.run([], { input: "keep\n" });
+ expect(kept.status, kept.stdout).toBe(0);
+ expect(kept.stdout).toContain("Left as it is.");
+ expect(kept.said.at(-1)).toBe("This server already runs 0.1.151. Nothing to do.");
+ expect(box.state().containers.omb.image).toBe(NEW.id);
+ expect(box.journal()).toBe(false);
+ expect(box.last()).toBe(true);
+ });
+
+ it("never goes to an older version unless told to, judged by the version the server says it is", () => {
+ // 0.1.152 runs, and stable is still 0.1.151.
+ const newer = install();
+ newer.setState({ images: [{ ...OLD, version: "0.1.152" }, NEW] });
+ const refused = newer.run();
+ expect(refused.status).toBe(5);
+ expect(refused.stdout).toContain("This server runs 0.1.152, which is newer than 0.1.151.");
+ expect(refused.said.at(-1)).toContain("Nothing was changed. To go ahead anyway, with the data copied first: ./update.sh --allow-older");
+ expect(newer.calls().some((call) => /^(compose (stop|up)|run)/.test(call))).toBe(false);
+ expect(newer.env()).toBe(ENV);
+ expect(newer.journal()).toBe(false);
+ expect(newer.copies()).toEqual([]);
+ expect(newer.run(["--check"]).stdout).toContain("./update.sh would change nothing without --allow-older.");
+ const told = newer.run(["--allow-older"]);
+ expect(told.status, told.stdout).toBe(0);
+ expect(told.said).toContain("Updated from 0.1.152 to 0.1.151.");
+
+ // A build of main (`latest`) is labelled with the branch; it says the version of the release it was built after.
+ const main = install();
+ main.setState({ images: [{ ...OLD, version: undefined, label: "main", serves: "0.1.151" }, NEW] });
+ const same = main.run();
+ expect(same.status).toBe(5);
+ expect(same.stdout).toContain("This server runs a build of main that says 0.1.151, and may hold changes made after 0.1.151 was released.");
+ const behind = install();
+ behind.setState({ images: [{ ...OLD, version: undefined, label: "main", serves: "0.1.150" }, NEW] });
+ const moved = behind.run();
+ expect(moved.status, moved.stdout).toBe(0);
+ expect(behind.state().containers.omb.image).toBe(NEW.id);
+ });
+
+ it("does not copy the data until the server has stopped, and drops a copy that does not match", () => {
+ for (const [extra, words] of [
+ [{ failStop: true }, "The server could not be stopped"],
+ [{ corruptCopy: true }, "Copying the data aside failed, or the copy did not match the data"],
+ ] as const) {
+ const box = install({}, extra);
+ const before = tree(box.data);
+ const refused = box.run();
+ expect(refused.status, words).toBe(4);
+ expect(refused.said.at(-1)).toContain(words);
+ expect(refused.said.at(-1)).toContain("Nothing was changed, and the server was started again.");
+ expect(box.state().containers.omb.image).toBe(OLD.id);
+ expect(box.env()).toBe(ENV);
+ expect(box.copies()).toEqual([]);
+ expect(box.journal()).toBe(false);
+ if ("failStop" in extra) expect(box.calls().some((call) => call.includes("--entrypoint cp"))).toBe(false);
+ else expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });
+ }
+ });
+
+ it("keeps the copy from the update before until the next copy has been checked", () => {
+ const NEWER = { id: id("c"), refs: [`${REPO}@${id("3")}`, `${REPO}:v0.1.152`], version: "0.1.152", local: false, engine: true };
+ const box = install();
+ expect(box.run().status).toBe(0);
+ const [first] = box.copies();
+ box.setState({ images: [...box.state().images, NEWER] });
+ writeFileSync(join(box.root, "stable.json"), stableRecord("0.1.152", NEWER.refs[0]!, ["0.1.151"]));
+ box.setState({ corruptCopy: true });
+ expect(box.run().status).toBe(4);
+ expect(box.copies()).toEqual([first]);
+ expect(box.last()).toBe(true);
+ const done = box.run();
+ expect(done.status, done.stdout).toBe(0);
+ expect(done.said).toContain("Updated from 0.1.151 to 0.1.152.");
+ expect(box.copies()).toHaveLength(1);
+ expect(box.copies()[0]).not.toBe(first);
+ });
+
+ it("takes the newest release until a first version is made stable, and stops on a channel it cannot reach", () => {
+ const box = install();
+ rmSync(join(box.root, "stable.json"));
+ writeFileSync(join(box.root, "newest.json"), JSON.stringify({ tag_name: "v0.1.151", html_url: "https://example.test/release", assets: [{ name: "x", version: "9.9.9" }] }));
+ const done = box.run();
+ expect(done.status, done.stdout).toBe(0);
+ expect(done.said[0]).toBe("No version has been made stable yet, so this takes the newest release, 0.1.151.");
+ expect(box.calls()).toContain(`pull -q ${REPO}:v0.1.151`);
+ expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);
+
+ const unreachable = install();
+ const refused = unreachable.run([], { env: { OMB_STABLE_URL: "http://127.0.0.1:9/stable.json" } });
+ expect(refused.status).toBe(4);
+ expect(refused.stdout).toContain("Could not read the stable channel");
+ expect(unreachable.calls().some((call) => call.startsWith("pull"))).toBe(false);
+ });
+
+ it.skipIf(process.getuid?.() === 0)("says plainly that the install folder cannot be written, and changes nothing", () => {
+ const box = install();
+ chmodSync(box.deploy, 0o555);
+ try {
+ const refused = box.run();
+ expect(refused.status).toBe(4);
+ expect(refused.stdout).toContain("cannot be written by this user");
+ } finally {
+ chmodSync(box.deploy, 0o755);
+ }
+ });
});
diff --git a/scripts/testing/fake-compose-docker.mjs b/scripts/testing/fake-compose-docker.mjs
index 3fa1adf70a..a1cddbc583 100644
--- a/scripts/testing/fake-compose-docker.mjs
+++ b/scripts/testing/fake-compose-docker.mjs
@@ -26,9 +26,10 @@ const envFile = () => (existsSync(join(process.cwd(), ".env")) ? readFileSync(jo
const pinned = () => process.env.OMB_IMAGE ?? /^OMB_IMAGE=(.*)$/m.exec(envFile())?.[1] ?? null;
const composeImage = () => (state.composeReadsPin && pinned()) || state.defaultImage;
-/** `{step: "compose up", signal: "SIGKILL"}`: the update script is signalled as this call starts, once. */
+/** `{step: "compose up", signal: "SIGKILL"}`: the update script is signalled as this call starts, once. `match`, a
+ * regular expression, instead picks the call by any part of it. */
const trip = state.signalOn;
-if (trip && line.startsWith(trip.step)) {
+if (trip && (trip.match ? new RegExp(trip.match).test(line) : line.startsWith(trip.step))) {
delete state.signalOn;
save();
process.kill(Number(readFileSync(join(process.cwd(), ".update", "lock", "pid"), "utf8")), trip.signal);
@@ -54,6 +55,7 @@ function compose(rest) {
if (verb === "ps" && more.includes("-aq")) return omb ? out(omb.id) : undefined;
if (verb === "ps") return Object.entries(state.containers).filter(([, container]) => container?.status === "running").forEach(([name]) => out(name));
if (verb === "stop") {
+ if (state.failStop) fail("Error response from daemon: cannot stop container: permission denied");
for (const container of Object.values(state.containers)) if (container) Object.assign(container, { status: "exited" });
return;
}
@@ -86,7 +88,8 @@ function imageInspect(format, ref) {
if (!found) fail(`No such image: ${ref}`);
if (format === "{{.Id}}") return out(found.id);
if (format.includes(".RepoDigests")) return found.refs.filter((name) => name.includes("@sha256:")).forEach((name) => out(name));
- if (format.includes("image.version")) return out(found.version ? `v${found.version}` : "");
+ // `label`: what the image says it is, when that is not its version (a build of main says the branch).
+ if (format.includes("image.version")) return out(found.label ?? (found.version ? `v${found.version}` : ""));
fail(`fake docker: unknown image format: ${format}`, 64);
}
@@ -100,13 +103,22 @@ function run(rest) {
});
const entry = rest[rest.indexOf("--entrypoint") + 1];
const tail = rest.slice(rest.indexOf("--entrypoint") + 3);
+ const script = entry === "sh" ? tail[1] : "";
if (state.failCopy && entry === "cp") fail("cp: error writing '/to/messages.db': No space left on device");
- if (state.failRestore && entry === "sh" && tail[1].includes("find /to")) fail("cp: cannot create regular file");
+ // A restore that fails while it copies into its own folder, before the data is touched (a full disk, a killed helper).
+ if (state.failRestore && script.includes(".omb-restore")) fail("cp: cannot create regular file '/to/.omb-restore/messages.db': No space left on device");
if (Object.values(mounts).some((folder) => !folder.startsWith(join(dir, "volumes")))) fail("fake docker: a mount outside the fixture", 64);
const inFolders = (text) => text.replace(/\/(from|to)(?=[/\s.]|$)/g, (_, name) => mounts[`/${name}`] ?? join(dir, "volumes", "unmounted"));
- if (entry === "sh" && tail[1].startsWith("du -sk")) return out(`${state.dataKb ?? 1024}\n${state.freeKb ?? 50_000_000}`);
+ // Every /from and /to must become a fixture folder: a script that names one any other way would reach the real disk.
+ if (tail.map(inFolders).some((arg) => /(^|[^\w.-])\/(from|to)\b/.test(arg))) fail("fake docker: a container path the fixture cannot map", 64);
+ if (script.startsWith("du -sk")) return out(`${state.dataKb ?? 1024}\n${state.freeKb ?? 50_000_000}`);
const done = spawnSync(entry, tail.map(inFolders), { stdio: "inherit" });
if (done.status !== 0) fail(`helper exited ${done.status}`, done.status ?? 1);
+ // `corruptCopy`: the copy lands, and then a file in it is not what was copied (a bad disk, a copy cut short).
+ if (state.corruptCopy && entry === "cp") {
+ delete state.corruptCopy;
+ appendFileSync(join(mounts["/to"], "started-by.txt"), "garbled\n");
+ }
}
function main() {
@@ -125,9 +137,20 @@ function main() {
if (verb === "run") return run(rest);
if (verb === "volume") {
const name = rest.at(-1);
- if (rest[0] === "rm") return rmSync(volume(name), { recursive: true, force: true });
- if (rest[0] === "create") return mkdirSync(volume(name), { recursive: true });
+ state.volumeLabels ??= {};
+ if (rest[0] === "rm") {
+ delete state.volumeLabels[name];
+ return rmSync(volume(name), { recursive: true, force: true });
+ }
+ if (rest[0] === "create") {
+ state.volumeLabels[name] = rest.flatMap((arg, at) => (rest[at - 1] === "--label" ? [arg] : []));
+ return mkdirSync(volume(name), { recursive: true });
+ }
if (rest[0] === "inspect") return existsSync(volume(name)) ? out(name) : fail(`no such volume: ${name}`);
+ if (rest[0] === "ls") {
+ const wanted = rest.flatMap((arg, at) => (rest[at - 1] === "--filter" && arg.startsWith("label=") ? [arg.slice("label=".length)] : []));
+ return Object.entries(state.volumeLabels).filter(([, labels]) => wanted.every((label) => labels.includes(label))).forEach(([found]) => out(found));
+ }
}
fail(`fake docker: unknown command: ${line}`, 64);
}
diff --git a/scripts/testing/stable-channel.test.ts b/scripts/testing/stable-channel.test.ts
index 174532cdb5..cb2548eb8c 100644
--- a/scripts/testing/stable-channel.test.ts
+++ b/scripts/testing/stable-channel.test.ts
@@ -1,3 +1,4 @@
+import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -41,20 +42,29 @@ describe("the stable channel", () => {
expect(() => checkIndex({ mediaType: "application/vnd.oci.image.manifest.v1+json" }, ["linux/amd64"], "the server image")).toThrow("not a multi-platform image");
});
- it("records the version with both images by digest, in a shape update.sh reads without a JSON parser", () => {
+ it("records the version with both images by digest, and update.sh reads it from the top level, whatever the history holds", () => {
const record = stableRecord({ version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, release: release(), current: null, now: NOW });
expect(record).toEqual({
channel: "stable", version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, platforms: ["linux/amd64", "linux/arm64"],
releaseUrl: release().url, releasedAt: release().publishedAt, promotedAt: "2026-11-12T12:00:00.000Z",
history: [{ version: "0.1.151", promotedAt: "2026-11-12T12:00:00.000Z" }],
});
- const text = JSON.stringify(record, null, 2).replace(/\n/g, "");
- // deploy/update.sh's two sed expressions
- expect(/.*"image"\s*:\s*"([^"]*)".*/.exec(text)?.[1]).toBe(IMAGE);
- expect(/.*"version"\s*:\s*"([0-9][0-9.]*)".*/.exec(text)?.[1]).toBe("0.1.151");
- const script = readFileSync(join(import.meta.dirname, "..", "..", "deploy", "update.sh"), "utf8");
- expect(script).toContain(String.raw`sed -n 's/.*"image"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'`);
expect(() => stableRecord({ version: "0.1.151", image: "ghcr.io/milind-soni/openmausbot:v0.1.151", cloudHomeImage: HOME, release: release(), current: null, now: NOW })).toThrow("is not pinned by digest");
+ if (process.platform === "win32") return;
+ // Three promotions: the history then names older versions after the current one, as it does from the second on.
+ let next = record;
+ for (const [version, days] of [["0.1.152", 7], ["0.1.153", 14]] as const) {
+ next = stableRecord({ version, image: IMAGE, cloudHomeImage: HOME, release: release(), current: next, now: NOW + days * 86_400_000 });
+ }
+ expect(next.history.map((entry) => entry.version)).toEqual(["0.1.153", "0.1.152", "0.1.151"]);
+ // deploy/update.sh's own reader, run on the record as the workflow writes it.
+ const script = readFileSync(join(import.meta.dirname, "..", "..", "deploy", "update.sh"), "utf8");
+ const reader = /^json_top\(\) \{\n[\s\S]*?\n\}\n/m.exec(script)?.[0];
+ expect(reader).toBeDefined();
+ const read = (key: string) => spawnSync("bash", ["-c", `${reader}\njson_top "$1"`, "json_top", key], { input: JSON.stringify(next, null, 2), encoding: "utf8" });
+ expect(read("version").stdout.trim()).toBe("0.1.153");
+ expect(read("image").stdout.trim()).toBe(IMAGE);
+ expect(read("promotedAt").stdout.trim()).toBe(next.promotedAt);
});
it("will not move stable back unless told to, and promoting the same version again keeps its date", () => {
diff --git a/server/update-check.test.ts b/server/update-check.test.ts
index d37b22da48..537b924b42 100644
--- a/server/update-check.test.ts
+++ b/server/update-check.test.ts
@@ -89,6 +89,23 @@ describe("server update check", () => {
await expect(createUpdateChecker({ current: "0.1.92", install: "docker", fetch })()).rejects.toThrow("The stable channel answered 500");
});
+ it("gives the last answer while the channel cannot be read, for a day, and never the newest release instead", async () => {
+ let now = 0;
+ let down = false;
+ const fetch = vi.fn(async (url: string | URL | Request) => {
+ if (down) return { ok: false, status: 503, json: async () => ({}) } as Response;
+ return String(url) === STABLE_CHANNEL_URL ? promoted("0.1.93") : release("v0.1.99");
+ });
+ const check = createUpdateChecker({ current: "0.1.92", install: "docker", fetch, now: () => now });
+ expect(await check()).toMatchObject({ channel: "stable", latest: "0.1.93", available: true });
+ down = true;
+ now = 2 * 60 * 60_000;
+ expect(await check()).toMatchObject({ channel: "stable", latest: "0.1.93", available: true });
+ expect(fetch.mock.calls.map(([url]) => String(url))).not.toContain(LATEST_RELEASE_URL);
+ now = 25 * 60 * 60_000;
+ await expect(check()).rejects.toThrow("The stable channel answered 503");
+ });
+
it("says up to date, and asks at most once an hour", async () => {
let now = 0;
const fetch = github("v0.1.92", "0.1.92");
diff --git a/server/update-check.ts b/server/update-check.ts
index b52643bfb3..81a330efea 100644
--- a/server/update-check.ts
+++ b/server/update-check.ts
@@ -6,6 +6,8 @@ export const LATEST_RELEASE_URL = "https://api.github.com/repos/milind-soni/Open
/** Written by .github/workflows/promote-stable.yml: the released version our own Clouds have run for 48 hours. */
export const STABLE_CHANNEL_URL = "https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json";
const CACHE_MS = 60 * 60_000;
+/** How long the last answer stands in when the channel cannot be read: an outage of GitHub is no reason to say nothing. */
+const STALE_MS = 24 * 60 * 60_000;
/** "managed" is a hosted or Cloud server that is updated for its owner. */
export type InstallKind = "desktop" | "managed" | "docker" | "podman" | "npm" | "git" | "unknown";
@@ -101,6 +103,8 @@ export function createUpdateChecker(options: {
const now = options.now ?? Date.now;
const channel = options.channel ?? "stable";
let cached: { at: number; result: UpdateCheck } | undefined;
+ /** The last answer that was read, kept past the hour for a channel that cannot be read for a while. */
+ let lastGood: { at: number; result: UpdateCheck } | undefined;
let inflight: Promise<UpdateCheck> | undefined;
const base = (): UpdateCheck => ({
current: options.current,
@@ -146,8 +150,13 @@ export function createUpdateChecker(options: {
...(found.releaseUrl ? { releaseUrl: found.releaseUrl } : {}),
...updateCommand(options.install, { version: found.version, stable: promoted !== null }),
};
- cached = { at: now(), result };
+ cached = lastGood = { at: now(), result };
return result;
+ } catch (error) {
+ // Never a fall back to the newest release, which the stable channel has not taken yet: the last answer it gave,
+ // when there is one from the last day, else the error.
+ if (lastGood && now() - lastGood.at < STALE_MS) return lastGood.result;
+ throw error;
} finally {
inflight = undefined;
}