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:
+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):
|
||||
|
||||
Reference in New Issue
Block a user