Roll back the database and /data with a failed update
Before an update, coreapps dumps the app's database (pg_dump or mariadb-dump, in the database's container) and makes a reflink copy of /data (Cores' /federated is btrfs). A failed update restores both before starting the old version; a failed dump refuses the update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -44,6 +44,14 @@ What we learned provisioning (2026-12-02/03):
|
||||
|
||||
- [ ] The Core shows as Active in the dashboard
|
||||
- [ ] Tell Federated (2026-12-03):
|
||||
- `upgrade`'s snapshot before each app update mounts `/dev/sda4`
|
||||
(also `bin/btrfs-snapshot`). In coreapp-dev's VM the disk is virtio,
|
||||
`/dev/vda4`, so the mount fails and it sends a Matrix alert to
|
||||
Federated's room for every app it updates. Finding the device with
|
||||
`findmnt -no SOURCE /federated` would work on both. (Or the VM's
|
||||
disk could be SCSI, so it's `/dev/sda` as on their servers.)
|
||||
- `lib/functions.sh` has the Matrix alerts' access token in it, so
|
||||
every Core (and anyone who can read the Core repo) has it
|
||||
- Apps send mail as `fcore` (an `inetOrgPerson` in the `admins` group)
|
||||
with the Core's admin password (`MAIL_PASSWORD=$ADMINPASS` in e.g.
|
||||
`lib/bookstack.sh`), so every app holds the admin password. The
|
||||
@@ -344,15 +352,29 @@ Steps:
|
||||
Authelia, for admins only
|
||||
|
||||
Later:
|
||||
- Done 2026-12-03: a failed update rolls back. coreapps keeps copies of
|
||||
`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
|
||||
- Done 2026-12-03: a failed update rolls back. Before updating, coreapps
|
||||
keeps, in `/federated/apps/.coreapps-rollback-<name>-*/` (mode 700; not
|
||||
`/tmp`, which is in memory on a Core): `services/<name>/`, `.env`,
|
||||
`docker-compose.yml`, a dump of its database (`pg_dump -Fc`, or
|
||||
`mariadb-dump --single-transaction`, run in the database's container),
|
||||
and a reflink copy of `/data` (`cp --reflink=always`: instant on btrfs,
|
||||
as dev.fedcom.net's `/federated` is; where it can't, no copy, and the
|
||||
messages say `/data` isn't rolled back). A dump that fails refuses the
|
||||
update. If anything fails until the app answers (or on Ctrl-C), it stops
|
||||
the new container, runs the teardown of needs the update added, restores
|
||||
the database (drop, create, restore) and `/data`, puts the files back,
|
||||
starts the old version and removes the new image. The folder is deleted
|
||||
either way. Tested on dev.fedcom.net, with postgres and with mysql: data
|
||||
changed while the failed version ran is back as before
|
||||
- Cores' filesystem (checked 2026-12-03 on the VM, which runs
|
||||
Federated's own Core image): `/` and `/federated` are btrfs, `/federated`
|
||||
a subvolume of its own (`/dev/vda4`, `subvol=/federated`). Federated
|
||||
relies on it: `upgrade` takes a read-only snapshot
|
||||
`federated-before-<app>-<version>` of the whole subvolume before
|
||||
updating each of its apps (`lib/functions.sh`), and `bin/btrfs-snapshot`,
|
||||
`restore-btrfs-snapshot` and `free-up-space -s` manage snapshots. So
|
||||
`/data`'s reflink copy works on every Core
|
||||
- [ ] Large databases: the dump takes time and disk on every update
|
||||
- [ ] Uninstalling a need without removing the app (now refused)
|
||||
- [ ] `bin/start` / `bin/stop` don't know coreapps' apps (see "Tell
|
||||
Federated"); `restart: always` covers reboots
|
||||
|
||||
@@ -230,7 +230,18 @@ The Core's own scripts trace secrets, so their output goes to
|
||||
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".
|
||||
"Rolled back hello (its settings and /data as before the update). It's
|
||||
the same image tag as before".
|
||||
Data: an app with `needs = ["postgres"]` (then again with `["mysql"]`),
|
||||
a table with a row "before" and `/data/file` with "before". Start a
|
||||
failing update; once `/federated/apps/.coreapps-rollback-<name>-*/` has
|
||||
`db.dump` (`db.sql`) and `data`, and the container runs the new tag,
|
||||
change the row to "after", add a table and a file in `/data`. After
|
||||
"Rolled back: ... with its settings, its database and /data as before
|
||||
the update": the row says "before", the new table and file are gone,
|
||||
the table's owner is the app's user, the app's user can still read it,
|
||||
and no `.coreapps-rollback-*` folder is left. A successful update leaves
|
||||
none either.
|
||||
11. Superpanel: after deploy, `/federated/apps/superpanel/data/applist.json`
|
||||
(the dashboard) and `catalog.json` have the app; `service` has
|
||||
`URL="https://hello.$DOMAIN/"` and applist the same `url`. Change
|
||||
|
||||
+100
-11
@@ -36,6 +36,7 @@ tier would record the app as a billable add-on and --addon-ok isn't given.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -763,8 +764,12 @@ def install_app(m, p, folder, origin, addon_ok, recreate):
|
||||
else:
|
||||
say(f"Updating {name} to {m['version']}...")
|
||||
log = log_path(name, "update")
|
||||
with tempfile.TemporaryDirectory(prefix="coreapps-rollback-") as backup:
|
||||
keep_for_rollback(name, backup)
|
||||
# On the apps' filesystem: /tmp may be in memory, and /data's copy
|
||||
# is a reflink, which only works within a filesystem
|
||||
for stale in glob.glob(f"{APPS}/.coreapps-rollback-{name}-*"):
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
with tempfile.TemporaryDirectory(prefix=f".coreapps-rollback-{name}-", dir=APPS) as backup:
|
||||
keep_for_rollback(m, p, backup, log)
|
||||
try:
|
||||
make_service_folder(m, p, folder, origin)
|
||||
env = dict(os.environ, NAME_ID=name)
|
||||
@@ -793,13 +798,85 @@ def install_app(m, p, folder, origin, addon_ok, recreate):
|
||||
ROLLBACK_FILES = [".env", "docker-compose.yml"]
|
||||
|
||||
|
||||
def keep_for_rollback(name, backup):
|
||||
"""Copies of the app's service folder and settings, in backup."""
|
||||
# Its database, dumped before an update and put back if the update fails.
|
||||
# Each runs in the database's container (the same version as the server);
|
||||
# root's MariaDB password is read there, so it's not in a log.
|
||||
DUMP = {
|
||||
"postgres": ("db.dump", ["docker", "exec", "postgresql",
|
||||
"pg_dump", "-U", "postgres", "-Fc", "{db}"]),
|
||||
"mysql": ("db.sql", ["docker", "exec", "pdnsmysql", "sh", "-c",
|
||||
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb-dump -uroot '
|
||||
"--single-transaction --routines --triggers --events --databases {db}"]),
|
||||
}
|
||||
RESTORE = {
|
||||
"postgres": [
|
||||
["docker", "exec", "postgresql", "psql", "-U", "postgres", "-qc",
|
||||
"DROP DATABASE IF EXISTS {db} WITH (FORCE)"],
|
||||
["docker", "exec", "postgresql", "psql", "-U", "postgres", "-qc",
|
||||
"CREATE DATABASE {db} OWNER {db}"],
|
||||
["docker", "exec", "-i", "postgresql", "pg_restore", "-U", "postgres", "-d", "{db}"],
|
||||
],
|
||||
"mysql": [
|
||||
["docker", "exec", "pdnsmysql", "sh", "-c",
|
||||
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb -uroot -e "DROP DATABASE IF EXISTS {db}"'],
|
||||
["docker", "exec", "-i", "pdnsmysql", "sh", "-c",
|
||||
'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" exec mariadb -uroot'],
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def keep_for_rollback(m, p, backup, log):
|
||||
"""Copies of the app's service folder, settings, database and (where the
|
||||
filesystem makes it cheap) /data, in backup. Refuses the update if the
|
||||
database can't be dumped."""
|
||||
name = m["name"]
|
||||
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))
|
||||
for need in marker_needs(name):
|
||||
if need in DUMP:
|
||||
file, cmd = DUMP[need]
|
||||
with open(os.path.join(backup, file), "wb") as out, open(log, "a") as err:
|
||||
result = subprocess.run([c.replace("{db}", m["dbname"]) for c in cmd],
|
||||
stdout=out, stderr=err)
|
||||
if result.returncode != 0:
|
||||
raise Refused(f"Couldn't back up {name}'s database before updating, "
|
||||
f"so nothing was changed (log on the Core: {log}).")
|
||||
# A reflink copy shares the files' blocks until one side changes (btrfs,
|
||||
# XFS); a full copy of /data could be too big, so there's none
|
||||
data = os.path.join(APPS, name, "data")
|
||||
if os.path.isdir(data):
|
||||
result = run(["cp", "-a", "--reflink=always", data, os.path.join(backup, "data")])
|
||||
if result.returncode != 0:
|
||||
shutil.rmtree(os.path.join(backup, "data"), ignore_errors=True)
|
||||
say(f"Note: this Core's filesystem can't copy /data cheaply, so if the update "
|
||||
f"fails, {name}'s /data stays as the new version leaves it.")
|
||||
|
||||
|
||||
def restore_data(m, backup, log):
|
||||
"""The database and /data as they were before the update, where
|
||||
keep_for_rollback kept them. Returns what couldn't be put back."""
|
||||
name, problems = m["name"], []
|
||||
for need, (file, _) in DUMP.items():
|
||||
dump = os.path.join(backup, file)
|
||||
if not os.path.exists(dump):
|
||||
continue
|
||||
ok = True
|
||||
with open(log, "a") as err:
|
||||
for cmd in RESTORE[need]:
|
||||
with open(dump, "rb") if "-i" in cmd else open(os.devnull, "rb") as stdin:
|
||||
result = subprocess.run([c.replace("{db}", m["dbname"]) for c in cmd],
|
||||
stdin=stdin, stdout=err, stderr=err)
|
||||
ok = ok and result.returncode == 0
|
||||
if not ok:
|
||||
problems.append("putting back its database")
|
||||
data, kept = os.path.join(APPS, name, "data"), os.path.join(backup, "data")
|
||||
if os.path.isdir(kept):
|
||||
shutil.rmtree(data, ignore_errors=True)
|
||||
os.rename(kept, data)
|
||||
return problems
|
||||
|
||||
|
||||
# Undo the setup of needs the failed update added (their teardown, from the
|
||||
@@ -818,18 +895,29 @@ 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."""
|
||||
"""Put back the version that ran before a failed update, with its
|
||||
settings, database and (if it was copied) /data, and start it. Returns
|
||||
what to tell the person."""
|
||||
name = m["name"]
|
||||
say(f"Rolling back {name}...")
|
||||
problems = []
|
||||
# The new version mustn't write while its data is put back
|
||||
run(["docker", "stop", name])
|
||||
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'])}")
|
||||
# What's put back, for the message
|
||||
restored = ["its settings"]
|
||||
if any(os.path.exists(os.path.join(backup, f)) for f, _ in DUMP.values()):
|
||||
restored.append("its database")
|
||||
if os.path.isdir(os.path.join(backup, "data")):
|
||||
restored.append("/data")
|
||||
kept_data = (os.path.isdir(os.path.join(backup, "data"))
|
||||
or not os.path.isdir(os.path.join(APPS, name, "data")))
|
||||
problems += restore_data(m, backup, log)
|
||||
final = os.path.join(SERVICES, name)
|
||||
shutil.rmtree(final, ignore_errors=True)
|
||||
shutil.rmtree(final + ".new", ignore_errors=True)
|
||||
@@ -854,11 +942,12 @@ def roll_back(m, p, backup, log):
|
||||
if problems:
|
||||
return (f"Rolling back to {was} went wrong ({'; '.join(problems)}). "
|
||||
f"Look at the log on the Core: {log}.")
|
||||
what = ", ".join(restored[:-1]) + (" and " if len(restored) > 1 else "") + restored[-1]
|
||||
note = "" if kept_data else " /data is as the new version left it."
|
||||
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.")
|
||||
return (f"Rolled back {name} ({what} as before the update). It's the same image "
|
||||
f"tag as before ({m['version']}), so the image that failed is the one running." + note)
|
||||
return f"Rolled back: {name} {was} runs again, with {what} as before the update." + note
|
||||
|
||||
|
||||
def short_name(image):
|
||||
|
||||
@@ -297,10 +297,12 @@ Common causes:
|
||||
`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.
|
||||
- "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.
|
||||
ran before, with its settings, its database and `/data` as they were
|
||||
before the update (`/data` only where the Core's filesystem can copy it
|
||||
instantly; the message says), and undid needs the update added. Whatever
|
||||
the failed version wrote is gone. Its log is printed above that line
|
||||
(`coreapp logs` now shows the old version's). 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
|
||||
minute; it retries for two. It also tries the VM directly, which tells the
|
||||
app apart from the way in.
|
||||
|
||||
Reference in New Issue
Block a user