Roll back failed updates to the version that ran before

coreapps keeps copies of the app's service folder, .env and compose
file during an update. If it fails before the app answers, it tears
down needs the update added, restores the copies, starts the old
version and removes the new image. Data isn't rolled back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 15:22:04 -07:00
co-authored by Claude Opus 5.5
parent 8ef2112e3c
commit 4e0292fd91
5 changed files with 115 additions and 14 deletions
+9 -2
View File
@@ -344,8 +344,15 @@ Steps:
Authelia, for admins only Authelia, for admins only
Later: Later:
- [ ] A failed update leaves the new `services/<name>/` in place with the - Done 2026-12-03: a failed update rolls back. coreapps keeps copies of
old container running; keep the old folder until the update works `services/<name>/`, `.env` and `docker-compose.yml`; if anything fails
until the app answers (or on Ctrl-C), it runs the teardown of needs the
update added, puts the copies back, starts the old version and removes
the new image. Data (`/data`, database contents) isn't rolled back: a new
version that migrated its database can leave the old one unable to run.
Tested on dev.fedcom.net
- [ ] Back up the app's database (and `/data`?) before an update, to roll
back data too; or a `coreapps rollback` that restores it on request
- [ ] Uninstalling a need without removing the app (now refused) - [ ] Uninstalling a need without removing the app (now refused)
- [ ] `bin/start` / `bin/stop` don't know coreapps' apps (see "Tell - [ ] `bin/start` / `bin/stop` don't know coreapps' apps (see "Tell
Federated"); `restart: always` covers reboots Federated"); `restart: always` covers reboots
+1 -1
View File
@@ -81,7 +81,7 @@ each new app explains the files and the settings it gets.
| `coreapp new --postgres --sso <name>` | Both: a database and sign-in (the example counts each person's visits) | | `coreapp new --postgres --sso <name>` | Both: a database and sign-in (the example counts each person's visits) |
| `coreapp new --mysql <name>` | (Instead of `--postgres`, with no example app.) Its own database on the Core's MariaDB | | `coreapp new --mysql <name>` | (Instead of `--postgres`, with no example app.) Its own database on the Core's MariaDB |
| `coreapp new --email <name>` | (With any of the above.) Sending mail through the Core's mail server, with the app's own account | | `coreapp new --email <name>` | (With any of the above.) Sending mail through the Core's mail server, with the app's own account |
| `coreapp deploy [--recreate]` | Build its image, copy it to the Core over SSH, install it, or update it keeping its settings and data (`--recreate`: a fresh container even if nothing changed) | | `coreapp deploy [--recreate]` | Build its image, copy it to the Core over SSH, install it, or update it keeping its settings and data; a failed update rolls back to the version before (`--recreate`: a fresh container even if nothing changed) |
| `coreapp check` | It answers at `https://<name>.<domain><health>` with a valid certificate | | `coreapp check` | It answers at `https://<name>.<domain><health>` with a valid certificate |
| `coreapp status` / `logs [-f]` / `shell [command]` | Its container, its log, a shell in it (or one command, without a terminal) | | `coreapp status` / `logs [-f]` / `shell [command]` | Its container, its log, a shell in it (or one command, without a terminal) |
| `coreapp list` | The apps on the Core installed this way | | `coreapp list` | The apps on the Core installed this way |
+10 -1
View File
@@ -222,7 +222,16 @@ The Core's own scripts trace secrets, so their output goes to
(the `--postgres`/`--sso` examples), `coreapp shell` then (the `--postgres`/`--sso` examples), `coreapp shell` then
`touch /data/x` works; on the Core, `/federated/apps/<name>/data` belongs `touch /data/x` works; on the Core, `/federated/apps/<name>/data` belongs
to uid 65534. to uid 65534.
10. On a Core whose tier isn't enterprise, deploying a new app asks before 10. A failed update rolls back. Note `md5sum` of the app's `.env`,
`docker-compose.yml`, `service` and `.coreapp` on the Core. Raise
`version`, set `port = 9999` (nothing answers there) and add `"postgres"`
to `needs`, then deploy: after "doesn't answer", "Rolling back" and
"Rolled back: hello 0.2.0 runs again"; deploy exits 1. The four files
are unchanged, the container runs the old tag and answers on its old
port, the new tag is gone from `docker image ls`, and `coreapp_hello`
isn't in PostgreSQL. With the same `version` (and `port = 9999`):
"Rolled back hello's settings. It's the same image tag as before".
11. On a Core whose tier isn't enterprise, deploying a new app asks before
it's recorded as an add-on; answering no deploys nothing. it's recorded as an add-on; answering no deploys nothing.
### With a database ### With a database
+90 -10
View File
@@ -750,27 +750,35 @@ def install_app(m, p, folder, origin, addon_ok, recreate):
say(f"{m['title']} {m['version']} from {origin['source']} ({origin['tag']}, " say(f"{m['title']} {m['version']} from {origin['source']} ({origin['tag']}, "
f"commit {origin['commit'][:12]})") f"commit {origin['commit'][:12]})")
ensure_image(m, pull=bool(origin)) ensure_image(m, pull=bool(origin))
make_service_folder(m, p, folder, origin)
if p["state"] == "new": if p["state"] == "new":
make_service_folder(m, p, folder, origin)
say(f"Installing {name} at {p['address']} (the Core's installapp)...") say(f"Installing {name} at {p['address']} (the Core's installapp)...")
log = log_path(name, "install") log = log_path(name, "install")
run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed") run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed")
# installapp's start step only knows Federated's own apps # installapp's start step only knows Federated's own apps
compose_up(m, log) compose_up(m, log)
wait_until_answering(m, p)
else: else:
say(f"Updating {name} to {m['version']}...") say(f"Updating {name} to {m['version']}...")
log = log_path(name, "update") log = log_path(name, "update")
env = dict(os.environ, NAME_ID=name) with tempfile.TemporaryDirectory(prefix="coreapps-rollback-") as backup:
with open(log, "a") as f: keep_for_rollback(name, backup)
result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name, try:
m["version"], *p["new_needs"]], make_service_folder(m, p, folder, origin)
stdout=f, stderr=subprocess.STDOUT, env=env) env = dict(os.environ, NAME_ID=name)
if result.returncode != 0: with open(log, "a") as f:
raise Refused(f"Updating failed (whole log on the Core: {log}).") result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name,
compose_up(m, log, recreate) m["version"], *p["new_needs"]],
stdout=f, stderr=subprocess.STDOUT, env=env)
if result.returncode != 0:
raise Refused(f"Updating failed (whole log on the Core: {log}).")
compose_up(m, log, recreate)
wait_until_answering(m, p)
except (Exception, KeyboardInterrupt) as e:
say(f"{e}" if isinstance(e, Refused) else f"Updating failed: {e!r}")
raise Refused(roll_back(m, p, backup, log)) from e
wait_until_answering(m, p)
check_needs(m) check_needs(m)
if p["state"] == "update": if p["state"] == "update":
remove_old_images(m) remove_old_images(m)
@@ -778,6 +786,78 @@ def install_app(m, p, folder, origin, addon_ok, recreate):
return 0 return 0
# Kept during an update, to put back if it fails
ROLLBACK_FILES = [".env", "docker-compose.yml"]
def keep_for_rollback(name, backup):
"""Copies of the app's service folder and settings, in backup."""
shutil.copytree(os.path.join(SERVICES, name), os.path.join(backup, "service"),
symlinks=True)
for f in ROLLBACK_FILES:
if os.path.exists(os.path.join(APPS, name, f)):
shutil.copy2(os.path.join(APPS, name, f), os.path.join(backup, f))
# Undo the setup of needs the failed update added (their teardown, from the
# new service folder). Arguments: name, needs.
ROLLBACK_SCRIPT = r'''
cd /federated
. /etc/federated
. lib/functions.sh
. lib/helpers.sh
name=$1
shift
for need in "$@"; do
if [ -e services/$name/needs/$need/teardown ]; then . services/$name/needs/$need/teardown; fi
done
'''
def roll_back(m, p, backup, log):
"""Put back the version that ran before a failed update, and start it.
The app's data (/data, its database) stays as the new version left it.
Returns what to tell the person."""
name = m["name"]
say(f"Rolling back {name}...")
problems = []
if p["new_needs"] and os.path.isdir(os.path.join(SERVICES, name, "needs")):
with open(log, "a") as f:
result = subprocess.run(["bash", "-c", ROLLBACK_SCRIPT, "rollback", name,
*p["new_needs"]], stdout=f, stderr=subprocess.STDOUT)
if result.returncode != 0:
problems.append(f"undoing needs {', '.join(p['new_needs'])}")
final = os.path.join(SERVICES, name)
shutil.rmtree(final, ignore_errors=True)
shutil.rmtree(final + ".new", ignore_errors=True)
shutil.copytree(os.path.join(backup, "service"), final, symlinks=True)
for f in ROLLBACK_FILES:
if os.path.exists(os.path.join(backup, f)):
shutil.copy2(os.path.join(backup, f), os.path.join(APPS, name, f))
try:
old = read_manifest(final)
except Refused:
old = None
with open(log, "a") as f:
result = subprocess.run(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml",
"-p", name, "up", "-d", "--remove-orphans", "--force-recreate"],
stdout=f, stderr=subprocess.STDOUT)
if result.returncode != 0:
problems.append("starting the old version")
# The new version's image, unless it's the same tag as the old one
if old and (old["image"], old["version"]) != (m["image"], m["version"]):
run(["docker", "image", "rm", f"{m['image']}:{m['version']}"])
was = f"{old['version']}" if old else "the version before"
if problems:
return (f"Rolling back to {was} went wrong ({'; '.join(problems)}). "
f"Look at the log on the Core: {log}.")
if old and (old["image"], old["version"]) == (m["image"], m["version"]):
return (f"Rolled back {name}'s settings. It's the same image tag as before "
f"({m['version']}), so the image that failed is the one running.")
return (f"Rolled back: {name} {was} runs again, with its settings. Its data "
"(/data, its database) is as the new version left it.")
def short_name(image): def short_name(image):
"""The image's name as docker lists it (docker.io/library/x is x).""" """The image's name as docker lists it (docker.io/library/x is x)."""
for prefix in ("docker.io/library/", "docker.io/"): for prefix in ("docker.io/library/", "docker.io/"):
+5
View File
@@ -296,6 +296,11 @@ Common causes:
- "doesn't answer at http://192.168.5.x:PORT/...": the app crashed (see - "doesn't answer at http://192.168.5.x:PORT/...": the app crashed (see
`coreapp logs`), listens on another port or on 127.0.0.1, or `health` `coreapp logs`), listens on another port or on 127.0.0.1, or `health`
points at a path that fails or redirects to an error. points at a path that fails or redirects to an error.
- "Rolled back": an update failed, so the Core put back the version that
ran before, with its settings, and undid needs the update added. The
failed version's log is printed above that line (`coreapp logs` now shows
the old version's). Its data and database aren't rolled back. When the
version wasn't raised, the image that failed is the one running again.
- `coreapp check` fails but deploy worked: a new certificate can take a - `coreapp check` fails but deploy worked: a new certificate can take a
minute; it retries for two. It also tries the VM directly, which tells the minute; it retries for two. It also tries the VM directly, which tells the
app apart from the way in. app apart from the way in.