Pin a release's image by digest, and refuse downgrades without --downgrade
After pulling a release, coreapps records its registry digest and runs image:version@sha256:..., so a re-pushed tag can't change an installed app; installing that release again with another digest is refused. An older release than the installed one needs --downgrade (coreapps install/plan, coreapp install), since it may not understand the newer one's data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+80
-10
@@ -9,11 +9,12 @@ own templates, so what an app can do on the Core is decided here, not by
|
||||
whoever wrote the app.
|
||||
|
||||
coreapps manifest <dir> check <dir>/coreapp.toml, print its values
|
||||
coreapps plan <source> what install would do on this Core
|
||||
coreapps install [--addon-ok] [--recreate] <source>
|
||||
coreapps plan [--downgrade] <source> what install would do on this Core
|
||||
coreapps install [--addon-ok] [--recreate] [--downgrade] <source>
|
||||
install the app, or update it
|
||||
(--recreate: a new container even if
|
||||
nothing changed)
|
||||
nothing changed; --downgrade: allow an
|
||||
older release than the installed one)
|
||||
coreapps update [--addon-ok] <name> update an app installed from a
|
||||
repository to its newest release
|
||||
coreapps remove <name> uninstall an app installed by coreapps
|
||||
@@ -413,6 +414,10 @@ def normalize_url(url):
|
||||
return f"{scheme}://{host.lower()}/{path}"
|
||||
|
||||
|
||||
def is_release(tag):
|
||||
return bool(re.fullmatch(r"v[0-9]+(?:\.[0-9]+)*", tag or ""))
|
||||
|
||||
|
||||
def version_key(tag):
|
||||
return [int(part) for part in tag[1:].split(".")]
|
||||
|
||||
@@ -528,7 +533,7 @@ def marker_value(name, key):
|
||||
return ""
|
||||
|
||||
|
||||
def plan(m, origin=None):
|
||||
def plan(m, origin=None, downgrade=False):
|
||||
"""What installing m would do here, or Refused."""
|
||||
name = m["name"]
|
||||
domain, tier = federated_settings()
|
||||
@@ -565,6 +570,18 @@ def plan(m, origin=None):
|
||||
if origin and installed_from and installed_from != origin["source"]:
|
||||
raise Refused(f"'{name}' on this Core was installed from {installed_from}, "
|
||||
f"not {origin['source']}. Remove it first to install this one.")
|
||||
# An older release may not understand what the newer one left in
|
||||
# its database and /data
|
||||
installed_tag = marker_value(name, "tag")
|
||||
if origin and is_release(installed_tag) and is_release(origin["tag"]) \
|
||||
and version_key(origin["tag"]) < version_key(installed_tag):
|
||||
if not downgrade:
|
||||
raise Refused(
|
||||
f"'{name}' has {installed_tag} installed; {origin['tag']} is older, and may "
|
||||
"not understand the data the newer version left (its database and /data). "
|
||||
"To install it anyway, add --downgrade (if it fails to start, the update "
|
||||
"rolls back).")
|
||||
p["downgrade_from"] = installed_tag
|
||||
else:
|
||||
p["new_needs"] = list(m["needs"])
|
||||
for key in ("source", "tag", "commit"):
|
||||
@@ -669,8 +686,8 @@ def make_service_folder(m, p, source, origin):
|
||||
write(os.path.join(new, MARKER),
|
||||
"# Installed by coreapps; delete with coreapps remove\n"
|
||||
f"needs={' '.join(m['needs'])}\n"
|
||||
+ "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit")
|
||||
if origin))
|
||||
+ "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit", "digest")
|
||||
if origin and origin.get(key)))
|
||||
shutil.rmtree(final, ignore_errors=True)
|
||||
os.rename(new, final)
|
||||
|
||||
@@ -726,6 +743,32 @@ def ensure_image(m, pull=False):
|
||||
+ (hint or " Is it published?"))
|
||||
|
||||
|
||||
def image_digest(m):
|
||||
"""The registry's digest of the pulled image:version (sha256:...), or ""."""
|
||||
out = run(["docker", "image", "inspect", "--format", "{{json .RepoDigests}}",
|
||||
f"{m['image']}:{m['version']}"])
|
||||
|
||||
def short(repo):
|
||||
return repo.removeprefix("docker.io/").removeprefix("library/")
|
||||
try:
|
||||
digests = json.loads(out.stdout) if out.returncode == 0 else []
|
||||
except ValueError:
|
||||
digests = []
|
||||
for d in digests or []:
|
||||
repo, _, digest = d.partition("@")
|
||||
if short(repo) == short(m["image"]) and re.fullmatch(r"sha256:[0-9a-f]{64}", digest):
|
||||
return digest
|
||||
return ""
|
||||
|
||||
|
||||
def set_env(name, key, value):
|
||||
"""key=value in the app's .env, replacing it or added at the end."""
|
||||
path = f"{APPS}/{name}/.env"
|
||||
with open(path) as f:
|
||||
lines = [line for line in f.read().splitlines() if not line.startswith(key + "=")]
|
||||
write(path, "\n".join(lines + [f"{key}={value}"]) + "\n", 0o600)
|
||||
|
||||
|
||||
def image_user(ref):
|
||||
"""The uid:gid the image runs as, or None for root (or unknown)."""
|
||||
user = run(["docker", "image", "inspect", "-f", "{{.Config.User}}", ref]).stdout.strip()
|
||||
@@ -756,6 +799,9 @@ def prepare_data(m):
|
||||
def compose_up(m, log, recreate=False):
|
||||
name = m["name"]
|
||||
prepare_data(m)
|
||||
# A release runs the image it was installed with (image:version@digest),
|
||||
# even if the tag is pushed again; a folder's image by its tag
|
||||
set_env(name, "IMAGE_DIGEST", "@" + m["digest"] if m.get("digest") else "")
|
||||
run_logged(["docker", "compose", "-f", f"{APPS}/{name}/docker-compose.yml",
|
||||
"-p", name, "up", "-d", "--remove-orphans",
|
||||
*(["--force-recreate"] if recreate else [])], log,
|
||||
@@ -793,12 +839,12 @@ done
|
||||
'''
|
||||
|
||||
|
||||
def install(arg, addon_ok, recreate=False):
|
||||
def install(arg, addon_ok, recreate=False, downgrade=False):
|
||||
with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
|
||||
folder, origin = resolve(arg, staging)
|
||||
m = read_manifest(folder)
|
||||
check_release(m, origin)
|
||||
p = plan(m, origin)
|
||||
p = plan(m, origin, downgrade)
|
||||
return install_app(m, p, folder, origin, addon_ok, recreate)
|
||||
|
||||
|
||||
@@ -813,6 +859,8 @@ 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))
|
||||
if origin:
|
||||
pin_release(m, p, origin)
|
||||
state, note = icon_check(folder)
|
||||
if state != "ok":
|
||||
say(f"Note: {note}")
|
||||
@@ -858,6 +906,26 @@ def install_app(m, p, folder, origin, addon_ok, recreate):
|
||||
return 0
|
||||
|
||||
|
||||
def pin_release(m, p, origin):
|
||||
"""Record the pulled release's digest (m and the marker), or refuse if
|
||||
the release installed here has changed in its registry since."""
|
||||
name, ref = m["name"], f"{m['image']}:{m['version']}"
|
||||
digest = image_digest(m)
|
||||
if not digest:
|
||||
raise Refused(f"Can't read the registry's digest of {ref}.")
|
||||
before = marker_value(name, "digest") if p["state"] == "update" else ""
|
||||
if before and before != digest and marker_value(name, "tag") == origin["tag"]:
|
||||
# Put the tag back on the installed image, and drop the changed one
|
||||
run(["docker", "tag", f"{m['image']}@{before}", ref])
|
||||
run(["docker", "image", "rm", f"{m['image']}@{digest}"])
|
||||
raise Refused(f"{ref} in its registry isn't the image installed here (installed "
|
||||
f"{before[:19]}..., now {digest[:19]}...): the release was changed after "
|
||||
f"it was published. {name} keeps running the installed one. A new "
|
||||
"version should have a new tag.")
|
||||
m["digest"] = origin["digest"] = digest
|
||||
say(f"Image: {ref}@{digest}")
|
||||
|
||||
|
||||
# Kept during an update, to put back if it fails
|
||||
ROLLBACK_FILES = [".env", "docker-compose.yml"]
|
||||
|
||||
@@ -1261,12 +1329,14 @@ def main(args):
|
||||
return 0
|
||||
if os.geteuid() != 0:
|
||||
raise Refused("Run coreapps as root on the Core.")
|
||||
downgrade = "--downgrade" in rest
|
||||
rest = [a for a in rest if a != "--downgrade"]
|
||||
if cmd == "plan" and len(rest) == 1:
|
||||
with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
|
||||
folder, origin = resolve(rest[0], staging)
|
||||
m = read_manifest(folder)
|
||||
check_release(m, origin)
|
||||
p = plan(m, origin)
|
||||
p = plan(m, origin, downgrade)
|
||||
for key in ("name", "title", "description", "version", "image"):
|
||||
print(f"{key}={m[key]}")
|
||||
print(f"needs={' '.join(m['needs'])}")
|
||||
@@ -1278,7 +1348,7 @@ def main(args):
|
||||
recreate = "--recreate" in rest
|
||||
folders = [a for a in rest if a not in ("--addon-ok", "--recreate")]
|
||||
if len(folders) == 1:
|
||||
return install(folders[0], addon_ok, recreate)
|
||||
return install(folders[0], addon_ok, recreate, downgrade)
|
||||
if cmd == "update" and rest:
|
||||
names = [a for a in rest if a != "--addon-ok"]
|
||||
if len(names) == 1:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
services:
|
||||
{{NAME}}:
|
||||
image: @CONTAINER@:${IMAGE_VERSION}
|
||||
image: @CONTAINER@:${IMAGE_VERSION}${IMAGE_DIGEST:-}
|
||||
container_name: {{NAME}}
|
||||
hostname: {{NAME}}.@DOMAIN@
|
||||
restart: always
|
||||
|
||||
Reference in New Issue
Block a user