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
+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']}, "
f"commit {origin['commit'][:12]})")
ensure_image(m, pull=bool(origin))
make_service_folder(m, p, folder, origin)
if p["state"] == "new":
make_service_folder(m, p, folder, origin)
say(f"Installing {name} at {p['address']} (the Core's installapp)...")
log = log_path(name, "install")
run_logged([FEDERATED + "/bin/installapp", "-n", name], log, "installapp failed")
# installapp's start step only knows Federated's own apps
compose_up(m, log)
wait_until_answering(m, p)
else:
say(f"Updating {name} to {m['version']}...")
log = log_path(name, "update")
env = dict(os.environ, NAME_ID=name)
with open(log, "a") as f:
result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name,
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)
with tempfile.TemporaryDirectory(prefix="coreapps-rollback-") as backup:
keep_for_rollback(name, backup)
try:
make_service_folder(m, p, folder, origin)
env = dict(os.environ, NAME_ID=name)
with open(log, "a") as f:
result = subprocess.run(["bash", "-c", UPDATE_SCRIPT, "update", name,
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)
if p["state"] == "update":
remove_old_images(m)
@@ -778,6 +786,78 @@ def install_app(m, p, folder, origin, addon_ok, recreate):
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):
"""The image's name as docker lists it (docker.io/library/x is x)."""
for prefix in ("docker.io/library/", "docker.io/"):