Install apps from their repository, including private ones
coreapps plan|install <https://host/owner/repo>[@tag] reads only coreapp.toml and icon.png at the tag's commit (depth 1, blobs on demand, regular files only), with git limited to https and no prompts or system settings. The default tag is the newest numeric release; version must match the tag; the image is always pulled. The marker records source, tag and commit; the same name from another repository is refused. coreapps update <name> moves to the newest release. On the workstation: coreapp install <url> (shows the app and its needs, asks) and update. Private apps: coreapps login <host> <user> keeps a read-only token (from stdin) in /etc/coreapps/credentials (root only), checked with the host's registry first. git gets it as an extraHeader for that host only, docker in a config made for each pull. coreapp login/logout/logins on the workstation. Tested with a private repository and package on Federated's Gitea. Fixed: old images of docker.io/library/... weren't deleted (docker lists them by short name); remove force-deleted images another app could use; coreapp help cut off multi-line descriptions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+394
-25
@@ -9,18 +9,33 @@ 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 <dir> what install would do on this Core
|
||||
coreapps install [--addon-ok] [--recreate] <dir>
|
||||
coreapps plan <source> what install would do on this Core
|
||||
coreapps install [--addon-ok] [--recreate] <source>
|
||||
install the app, or update it
|
||||
(--recreate: a new container even if
|
||||
nothing changed)
|
||||
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
|
||||
coreapps list the apps installed by coreapps
|
||||
coreapps login <host> <user> keep a token (read from stdin) for
|
||||
installing private apps from host
|
||||
coreapps logout <host> forget host's token
|
||||
coreapps logins the hosts this Core has tokens for
|
||||
|
||||
<source> is a folder with coreapp.toml (and icon.png), or a git
|
||||
repository: https://host/owner/repo[@tag]. A private repository, and a
|
||||
private image, need a token for their host (coreapps login): a Gitea token
|
||||
with read access to repositories and packages. From a repository, only
|
||||
coreapp.toml and icon.png are read, at the tag (default: the newest
|
||||
release tag, v1.2.3), whose version must match; the image is pulled from
|
||||
its registry.
|
||||
|
||||
`manifest` also works off the Core. install exits with 3 if this Core's
|
||||
tier would record the app as a billable add-on and --addon-ok isn't given.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -31,6 +46,7 @@ import tempfile
|
||||
import time
|
||||
import tomllib
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
HERE = os.path.dirname(os.path.realpath(__file__))
|
||||
@@ -71,6 +87,24 @@ FIELDS = {
|
||||
}
|
||||
REQUIRED = ["name", "title", "version", "image", "port"]
|
||||
|
||||
# Repositories apps are installed from: https only, no user or password in
|
||||
# the URL. Tags: v + a version; releases (picked by default) are numeric.
|
||||
REPO_URL = r"https://[A-Za-z0-9.-]+(?::[0-9]{1,5})?(?:/[A-Za-z0-9._-]+){2,}?(?:\.git)?/?"
|
||||
TAG = r"v[A-Za-z0-9][A-Za-z0-9._-]{0,63}"
|
||||
RELEASE_TAG = r"v[0-9]+(?:\.[0-9]+)*"
|
||||
# git for untrusted repositories: https only, never asks for a password,
|
||||
# ignores the system's and root's git settings
|
||||
GIT_ENV = {"PATH": "/usr/bin:/bin", "GIT_TERMINAL_PROMPT": "0",
|
||||
"GIT_ALLOW_PROTOCOL": "https", "GIT_CONFIG_NOSYSTEM": "1",
|
||||
"GIT_CONFIG_GLOBAL": "/dev/null", "HOME": "/nonexistent",
|
||||
"LC_ALL": "C"}
|
||||
GIT_TIMEOUT = 120
|
||||
# Tokens for private repositories and registries, by host (root only)
|
||||
CREDENTIALS = "/etc/coreapps/credentials"
|
||||
HOST = r"[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[0-9]{1,5})?"
|
||||
LOGIN_USER = r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}"
|
||||
TOKEN = r"[A-Za-z0-9._~+/=-]{8,512}"
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
"""The app can't be installed as it is; the message says why."""
|
||||
@@ -85,6 +119,8 @@ def say(*args):
|
||||
def read_manifest(folder):
|
||||
"""coreapp.toml in folder, checked, with defaults filled in."""
|
||||
path = os.path.join(folder, "coreapp.toml")
|
||||
if os.path.islink(path):
|
||||
raise Refused("coreapp.toml is a symbolic link; it has to be a file.")
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
data = tomllib.load(f)
|
||||
@@ -215,7 +251,245 @@ def pick_address(name):
|
||||
raise Refused(f"No free address left in {PREFIX}{FIRST}-{LAST}.")
|
||||
|
||||
|
||||
def plan(m):
|
||||
# --- Tokens for private apps ----------------------------------------------------
|
||||
|
||||
def read_credentials():
|
||||
try:
|
||||
with open(CREDENTIALS, "rb") as f:
|
||||
data = tomllib.load(f)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except tomllib.TOMLDecodeError as e:
|
||||
raise Refused(f"{CREDENTIALS} isn't valid: {e}")
|
||||
return {host: c for host, c in data.items()
|
||||
if isinstance(c, dict) and re.fullmatch(LOGIN_USER, str(c.get("user", "")))
|
||||
and re.fullmatch(TOKEN, str(c.get("token", "")))}
|
||||
|
||||
|
||||
def write_credentials(creds):
|
||||
os.makedirs(os.path.dirname(CREDENTIALS), mode=0o700, exist_ok=True)
|
||||
os.chmod(os.path.dirname(CREDENTIALS), 0o700)
|
||||
text = ("# Tokens coreapps uses to install private apps, by host. Manage with\n"
|
||||
"# coreapps login / logout.\n")
|
||||
for host in sorted(creds):
|
||||
text += f'\n["{host}"]\nuser = "{creds[host]["user"]}"\ntoken = "{creds[host]["token"]}"\n'
|
||||
new = CREDENTIALS + ".new"
|
||||
fd = os.open(new, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(text)
|
||||
os.rename(new, CREDENTIALS)
|
||||
|
||||
|
||||
def basic_auth(host):
|
||||
"""'user:token' in base64 for host, or None."""
|
||||
c = read_credentials().get(host)
|
||||
if not c:
|
||||
return None
|
||||
return base64.b64encode(f"{c['user']}:{c['token']}".encode()).decode()
|
||||
|
||||
|
||||
def url_host(url):
|
||||
return url.split("://", 1)[1].split("/", 1)[0].lower()
|
||||
|
||||
|
||||
def check_token(host, user, token):
|
||||
"""Whether host's registry accepts the token: True, False, or None
|
||||
(couldn't tell)."""
|
||||
auth = "Basic " + base64.b64encode(f"{user}:{token}".encode()).decode()
|
||||
|
||||
def get(url):
|
||||
req = urllib.request.Request(url, headers={"Authorization": auth})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as r:
|
||||
return r.status, r.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers
|
||||
except (urllib.error.URLError, OSError):
|
||||
return None, {}
|
||||
|
||||
status, headers = get(f"https://{host}/v2/")
|
||||
if status == 200:
|
||||
return True
|
||||
challenge = (headers or {}).get("WWW-Authenticate", "")
|
||||
m = re.search(r'realm="([^"]+)"', challenge)
|
||||
if status == 401 and challenge.lower().startswith("bearer") and m:
|
||||
service = re.search(r'service="([^"]+)"', challenge)
|
||||
realm = m.group(1) + (f"?service={urllib.parse.quote(service.group(1))}" if service else "")
|
||||
status, _ = get(realm)
|
||||
if status == 200:
|
||||
return True
|
||||
if status in (401, 403):
|
||||
return False
|
||||
return False if status in (401, 403) else None
|
||||
|
||||
|
||||
def login(host, user):
|
||||
host = host.lower()
|
||||
if not re.fullmatch(HOST, host):
|
||||
raise Refused(f"'{host}' isn't a host name (like gitea.example.com).")
|
||||
if not re.fullmatch(LOGIN_USER, user):
|
||||
raise Refused(f"'{user}' isn't a user name.")
|
||||
token = sys.stdin.readline().strip()
|
||||
if not re.fullmatch(TOKEN, token):
|
||||
raise Refused("That isn't a token (8-512 letters, digits and . _ ~ + / = -).")
|
||||
ok = check_token(host, user, token)
|
||||
if ok is False:
|
||||
raise Refused(f"{host} rejected the token for {user}. Nothing was saved.")
|
||||
creds = read_credentials()
|
||||
creds[host] = {"user": user, "token": token}
|
||||
write_credentials(creds)
|
||||
say(f"Saved a token for {user}@{host}"
|
||||
+ (" (its registry accepts it)." if ok else " (couldn't check it with its registry)."))
|
||||
return 0
|
||||
|
||||
|
||||
def logout(host):
|
||||
creds = read_credentials()
|
||||
if creds.pop(host.lower(), None) is None:
|
||||
say(f"No token for {host}.")
|
||||
return 0
|
||||
write_credentials(creds)
|
||||
say(f"Forgot the token for {host}.")
|
||||
return 0
|
||||
|
||||
|
||||
def list_logins():
|
||||
creds = read_credentials()
|
||||
if not creds:
|
||||
say("No tokens: this Core installs public apps only.")
|
||||
for host in sorted(creds):
|
||||
say(f"{host} (user {creds[host]['user']})")
|
||||
return 0
|
||||
|
||||
|
||||
# --- Where an app comes from: a folder or a repository ------------------------
|
||||
|
||||
def normalize_url(url):
|
||||
"""https://Host/owner/repo.git/ -> https://host/owner/repo"""
|
||||
url = url.rstrip("/")
|
||||
if url.endswith(".git"):
|
||||
url = url[:-4]
|
||||
scheme, _, rest = url.partition("://")
|
||||
host, _, path = rest.partition("/")
|
||||
return f"{scheme}://{host.lower()}/{path}"
|
||||
|
||||
|
||||
def version_key(tag):
|
||||
return [int(part) for part in tag[1:].split(".")]
|
||||
|
||||
|
||||
def git(args, cwd=None, auth=None):
|
||||
"""git with GIT_ENV; auth: (url prefix, base64 user:token) to send as a
|
||||
header (in the environment, so it's never in a URL or an error)."""
|
||||
env = dict(GIT_ENV)
|
||||
if auth:
|
||||
env.update({"GIT_CONFIG_COUNT": "1",
|
||||
"GIT_CONFIG_KEY_0": f"http.{auth[0]}/.extraHeader",
|
||||
"GIT_CONFIG_VALUE_0": f"Authorization: Basic {auth[1]}"})
|
||||
try:
|
||||
out = subprocess.run(["git", *args], cwd=cwd, env=env, capture_output=True,
|
||||
timeout=GIT_TIMEOUT)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Refused(f"git {args[0]} took longer than {GIT_TIMEOUT} s.")
|
||||
return out
|
||||
|
||||
|
||||
def git_blob(folder, commit, path, limit, auth=None):
|
||||
"""A regular file's bytes at commit, or None if it isn't one (missing,
|
||||
a link, a folder) or is bigger than limit. (Fetched on demand, so it may
|
||||
need the repository's token.)"""
|
||||
out = git(["ls-tree", commit, "--", path], cwd=folder, auth=auth)
|
||||
fields = out.stdout.decode().split()
|
||||
if out.returncode != 0 or len(fields) < 3 or fields[0] != "100644" or fields[1] != "blob":
|
||||
return None
|
||||
size = git(["cat-file", "-s", fields[2]], cwd=folder, auth=auth)
|
||||
if size.returncode != 0 or int(size.stdout or 0) > limit:
|
||||
return None
|
||||
blob = git(["cat-file", "blob", fields[2]], cwd=folder, auth=auth)
|
||||
return blob.stdout if blob.returncode == 0 else None
|
||||
|
||||
|
||||
def fetch_repo(arg, staging):
|
||||
"""coreapp.toml and icon.png from a repository at a tag, into staging.
|
||||
Returns the source's details."""
|
||||
url, _, tag = arg.partition("@")
|
||||
if not re.fullmatch(REPO_URL, url):
|
||||
raise Refused(f"'{url}' isn't a repository address coreapps installs from: "
|
||||
"https://host/owner/repo (no user or password in it).")
|
||||
url = normalize_url(url)
|
||||
host = url_host(url)
|
||||
token = basic_auth(host)
|
||||
auth = (f"https://{host}", token) if token else None
|
||||
no_access = ("" if token else
|
||||
f" If it's private, give this Core a token for {host}: coreapp login {host}.")
|
||||
if tag and not re.fullmatch(TAG, tag):
|
||||
raise Refused(f"'{tag}' isn't a release tag (v and a version, like v1.2.0).")
|
||||
if not tag:
|
||||
out = git(["ls-remote", "--tags", "--refs", url], auth=auth)
|
||||
if out.returncode != 0:
|
||||
raise Refused(f"Couldn't read {url}: {out.stderr.decode().strip() or 'no answer'}."
|
||||
+ no_access)
|
||||
tags = [line.split("refs/tags/", 1)[1] for line in out.stdout.decode().splitlines()
|
||||
if "refs/tags/" in line]
|
||||
releases = [t for t in tags if re.fullmatch(RELEASE_TAG, t)]
|
||||
if not releases:
|
||||
raise Refused(f"{url} has no release tags (like v1.2.0). Publish a release "
|
||||
"(coreapp publish tags it), or name a tag: <url>@<tag>.")
|
||||
tag = max(releases, key=version_key)
|
||||
git(["init", "-q", "--bare", staging + "/git"])
|
||||
out = git(["fetch", "-q", "--depth", "1", "--filter=blob:none", "--no-tags", url,
|
||||
f"refs/tags/{tag}"], cwd=staging + "/git", auth=auth)
|
||||
if out.returncode != 0:
|
||||
raise Refused(f"Couldn't fetch {tag} from {url}: {out.stderr.decode().strip()}"
|
||||
+ no_access)
|
||||
commit = git(["rev-parse", "FETCH_HEAD^{commit}"], cwd=staging + "/git").stdout.decode().strip()
|
||||
manifest = git_blob(staging + "/git", commit, "coreapp.toml", 64 * 1024, auth)
|
||||
if manifest is None:
|
||||
raise Refused(f"{url} has no coreapp.toml (a file, up to 64 KB) at {tag}.")
|
||||
with open(os.path.join(staging, "coreapp.toml"), "wb") as f:
|
||||
f.write(manifest)
|
||||
icon = git_blob(staging + "/git", commit, "icon.png", 1024 * 1024, auth)
|
||||
if icon is not None:
|
||||
with open(os.path.join(staging, "icon.png"), "wb") as f:
|
||||
f.write(icon)
|
||||
shutil.rmtree(staging + "/git")
|
||||
return {"source": url, "tag": tag, "commit": commit}
|
||||
|
||||
|
||||
def resolve(arg, staging):
|
||||
"""The folder to read the app from, and where it came from."""
|
||||
if arg.startswith("https://"):
|
||||
return staging, fetch_repo(arg, staging)
|
||||
if not os.path.isdir(arg):
|
||||
raise Refused(f"'{arg}' is neither a folder nor an https:// repository.")
|
||||
return arg, {}
|
||||
|
||||
|
||||
def check_release(m, origin):
|
||||
"""A repository's app: its version is the tag's, its image can be pulled."""
|
||||
if not origin:
|
||||
return
|
||||
if "v" + m["version"] != origin["tag"]:
|
||||
raise Refused(f"At {origin['tag']}, coreapp.toml says version = \"{m['version']}\"; "
|
||||
"a release's tag and version have to match.")
|
||||
if m["image"].startswith("localhost/"):
|
||||
raise Refused(f"image = \"{m['image']}\" is a local image, which can't be "
|
||||
"installed from a repository. Publish it to a registry first "
|
||||
"(coreapp publish).")
|
||||
|
||||
|
||||
def marker_value(name, key):
|
||||
try:
|
||||
with open(os.path.join(SERVICES, name, MARKER)) as f:
|
||||
for line in f:
|
||||
if line.startswith(key + "="):
|
||||
return line.split("=", 1)[1].strip()
|
||||
except OSError:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def plan(m, origin=None):
|
||||
"""What installing m would do here, or Refused."""
|
||||
name = m["name"]
|
||||
domain, tier = federated_settings()
|
||||
@@ -246,8 +520,17 @@ def plan(m):
|
||||
"removing them would delete what the app keeps there. "
|
||||
"Remove the app and install it again to do that.")
|
||||
p["new_needs"] = [n for n in m["needs"] if n not in before]
|
||||
# Another repository's app of the same name would take over this
|
||||
# one's data, database and sign-in client
|
||||
installed_from = marker_value(name, "source")
|
||||
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.")
|
||||
else:
|
||||
p["new_needs"] = list(m["needs"])
|
||||
for key in ("source", "tag", "commit"):
|
||||
if origin:
|
||||
p[key] = origin[key]
|
||||
return p
|
||||
|
||||
|
||||
@@ -277,7 +560,7 @@ def icon_from(folder):
|
||||
"""The app's icon.png if it's a reasonable PNG, else the default."""
|
||||
path = os.path.join(folder, "icon.png")
|
||||
try:
|
||||
if os.path.getsize(path) <= 1024 * 1024:
|
||||
if not os.path.islink(path) and os.path.getsize(path) <= 1024 * 1024:
|
||||
with open(path, "rb") as f:
|
||||
if f.read(8) == b"\x89PNG\r\n\x1a\n":
|
||||
return path
|
||||
@@ -286,7 +569,7 @@ def icon_from(folder):
|
||||
return os.path.join(TEMPLATES, "icon.png")
|
||||
|
||||
|
||||
def make_service_folder(m, p, source):
|
||||
def make_service_folder(m, p, source, origin):
|
||||
"""/federated/services/<name>/ in the Core's generic format, from m."""
|
||||
values = {
|
||||
"NAME": m["name"], "TITLE": m["title"], "DESCRIPTION": m["description"],
|
||||
@@ -319,7 +602,9 @@ def make_service_folder(m, p, source):
|
||||
shutil.copyfile(os.path.join(source, "coreapp.toml"), os.path.join(new, "coreapp.toml"))
|
||||
write(os.path.join(new, MARKER),
|
||||
"# Installed by coreapps; delete with coreapps remove\n"
|
||||
f"needs={' '.join(m['needs'])}\n")
|
||||
f"needs={' '.join(m['needs'])}\n"
|
||||
+ "".join(f"{key}={origin[key]}\n" for key in ("source", "tag", "commit")
|
||||
if origin))
|
||||
shutil.rmtree(final, ignore_errors=True)
|
||||
os.rename(new, final)
|
||||
|
||||
@@ -345,17 +630,34 @@ def run_logged(cmd, log, failure):
|
||||
raise Refused(f"{failure} (whole log on the Core: {log}).")
|
||||
|
||||
|
||||
def ensure_image(m):
|
||||
def ensure_image(m, pull=False):
|
||||
"""The image on this Core. pull: always from its registry (a release is
|
||||
what's published, not a same-named image built here)."""
|
||||
ref = f"{m['image']}:{m['version']}"
|
||||
if run(["docker", "image", "inspect", ref]).returncode == 0:
|
||||
if not pull and run(["docker", "image", "inspect", ref]).returncode == 0:
|
||||
return
|
||||
if m["image"].startswith("localhost/"):
|
||||
raise Refused(f"The image {ref} isn't on this Core, and localhost/ images "
|
||||
"can't be pulled. coreapp deploy copies it here.")
|
||||
say(f"Pulling {ref}...")
|
||||
out = run(["docker", "pull", "-q", ref])
|
||||
registry = m["image"].split("/", 1)[0]
|
||||
token = basic_auth(registry)
|
||||
# The token goes in a docker config just for this pull, so the Core
|
||||
# keeps no docker login
|
||||
with tempfile.TemporaryDirectory(prefix="coreapps-docker-") as config:
|
||||
env = dict(os.environ)
|
||||
if token:
|
||||
key = "https://index.docker.io/v1/" if registry == "docker.io" else registry
|
||||
fd = os.open(os.path.join(config, "config.json"), os.O_WRONLY | os.O_CREAT, 0o600)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
json.dump({"auths": {key: {"auth": token}}}, f)
|
||||
env["DOCKER_CONFIG"] = config
|
||||
out = run(["docker", "pull", "-q", ref], env=env)
|
||||
if out.returncode != 0:
|
||||
raise Refused(f"Couldn't pull {ref}: {out.stderr.strip()}")
|
||||
hint = ("" if token else
|
||||
f" If it's private, give this Core a token for {registry}: coreapp login {registry}.")
|
||||
raise Refused(f"Couldn't pull {ref}: {out.stderr.strip().rstrip('.')}."
|
||||
+ (hint or " Is it published?"))
|
||||
|
||||
|
||||
def image_user(ref):
|
||||
@@ -425,17 +727,27 @@ done
|
||||
'''
|
||||
|
||||
|
||||
def install(folder, addon_ok, recreate=False):
|
||||
m = read_manifest(folder)
|
||||
p = plan(m)
|
||||
def install(arg, addon_ok, recreate=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)
|
||||
return install_app(m, p, folder, origin, addon_ok, recreate)
|
||||
|
||||
|
||||
def install_app(m, p, folder, origin, addon_ok, recreate):
|
||||
name = m["name"]
|
||||
if p["addon"] == "yes" and not addon_ok:
|
||||
say(f"This Core's tier is '{p['tier']}': installing records '{name}' as an "
|
||||
"add-on app (ADDON_APPS in /etc/federated), which Federated may bill for. "
|
||||
"Run again with --addon-ok to install anyway.")
|
||||
return 3
|
||||
ensure_image(m)
|
||||
make_service_folder(m, p, folder)
|
||||
if origin:
|
||||
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":
|
||||
say(f"Installing {name} at {p['address']} (the Core's installapp)...")
|
||||
@@ -462,12 +774,32 @@ def install(folder, addon_ok, recreate=False):
|
||||
return 0
|
||||
|
||||
|
||||
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/"):
|
||||
if image.startswith(prefix):
|
||||
return image[len(prefix):]
|
||||
return image
|
||||
|
||||
|
||||
def image_tags(image):
|
||||
"""The tags of image on this Core."""
|
||||
out = run(["docker", "image", "ls", "--format", "{{.Repository}} {{.Tag}}"])
|
||||
return [tag for repo, _, tag in (line.partition(" ") for line in out.stdout.splitlines())
|
||||
if repo == short_name(image) and tag != "<none>"]
|
||||
|
||||
|
||||
def remove_images(image, keep=None):
|
||||
"""image's tags on this Core except keep. Without force: docker refuses
|
||||
to delete one a container uses (another app may use the same image)."""
|
||||
for tag in image_tags(image):
|
||||
if tag != keep:
|
||||
run(["docker", "image", "rm", f"{short_name(image)}:{tag}"])
|
||||
|
||||
|
||||
def remove_old_images(m):
|
||||
"""The app's images with other versions, now that this one runs."""
|
||||
out = run(["docker", "image", "ls", "--format", "{{.Repository}}:{{.Tag}}", m["image"]])
|
||||
for ref in out.stdout.split():
|
||||
if ref != f"{m['image']}:{m['version']}":
|
||||
run(["docker", "image", "rm", ref])
|
||||
remove_images(m["image"], keep=m["version"])
|
||||
|
||||
|
||||
def wait_until_answering(m, p):
|
||||
@@ -494,6 +826,26 @@ def wait_until_answering(m, p):
|
||||
"its log is above).")
|
||||
|
||||
|
||||
def update(name, addon_ok):
|
||||
"""An app installed from a repository, to its newest release."""
|
||||
if not re.fullmatch(FIELDS["name"], name) or not is_ours(name):
|
||||
raise Refused(f"No app called '{name}' installed by coreapps on this Core.")
|
||||
source = marker_value(name, "source")
|
||||
if not source:
|
||||
raise Refused(f"'{name}' was installed from a folder, not a repository; "
|
||||
"update it the same way (coreapp deploy).")
|
||||
with tempfile.TemporaryDirectory(prefix="coreapps-") as staging:
|
||||
folder, origin = resolve(source, staging)
|
||||
if origin["tag"] == marker_value(name, "tag"):
|
||||
say(f"{name} is at the newest release, {origin['tag']}.")
|
||||
return 0
|
||||
m = read_manifest(folder)
|
||||
check_release(m, origin)
|
||||
if m["name"] != name:
|
||||
raise Refused(f"At {origin['tag']}, {source} is the app '{m['name']}', not '{name}'.")
|
||||
return install_app(m, plan(m, origin), folder, origin, addon_ok, False)
|
||||
|
||||
|
||||
def remove(name):
|
||||
if not re.fullmatch(FIELDS["name"], name):
|
||||
raise Refused(f"'{name}' isn't an app name.")
|
||||
@@ -509,9 +861,7 @@ def remove(name):
|
||||
run_logged([FEDERATED + "/bin/uninstallapp", name], log, "uninstallapp failed")
|
||||
shutil.rmtree(folder)
|
||||
if image:
|
||||
ids = run(["docker", "image", "ls", "-q", image]).stdout.split()
|
||||
for image_id in sorted(set(ids)):
|
||||
run(["docker", "image", "rm", "-f", image_id])
|
||||
remove_images(image)
|
||||
# uninstallapp made superpanel's catalog while the folder was still
|
||||
# there, so it would still offer the app: make it again, as installapp
|
||||
# does
|
||||
@@ -530,12 +880,14 @@ def list_apps():
|
||||
continue
|
||||
service = os.path.join(SERVICES, name, "service")
|
||||
state = run(["docker", "inspect", "-f", "{{.State.Status}}", name]).stdout.strip()
|
||||
source = marker_value(name, "source")
|
||||
rows.append((name, service_value(service, "VERSION"),
|
||||
service_value(service, "INTERNAL_IP"), state or "not running"))
|
||||
service_value(service, "INTERNAL_IP"), state or "not running",
|
||||
f"{source}@{marker_value(name, 'tag')}" if source else "(from a folder)"))
|
||||
if not rows:
|
||||
say("No apps installed by coreapps.")
|
||||
for row in rows:
|
||||
say("%-24s %-12s %-16s %s" % row)
|
||||
say("%-24s %-12s %-14s %-12s %s" % row)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -556,7 +908,14 @@ def main(args):
|
||||
if os.geteuid() != 0:
|
||||
raise Refused("Run coreapps as root on the Core.")
|
||||
if cmd == "plan" and len(rest) == 1:
|
||||
p = plan(read_manifest(rest[0]))
|
||||
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)
|
||||
for key in ("name", "title", "description", "version", "image"):
|
||||
print(f"{key}={m[key]}")
|
||||
print(f"needs={' '.join(m['needs'])}")
|
||||
for key, value in p.items():
|
||||
print(f"{key}={' '.join(value) if isinstance(value, list) else value}")
|
||||
return 0
|
||||
@@ -566,8 +925,18 @@ def main(args):
|
||||
folders = [a for a in rest if a not in ("--addon-ok", "--recreate")]
|
||||
if len(folders) == 1:
|
||||
return install(folders[0], addon_ok, recreate)
|
||||
if cmd == "update" and rest:
|
||||
names = [a for a in rest if a != "--addon-ok"]
|
||||
if len(names) == 1:
|
||||
return update(names[0], "--addon-ok" in rest)
|
||||
if cmd == "remove" and len(rest) == 1:
|
||||
return remove(rest[0])
|
||||
if cmd == "login" and len(rest) == 2:
|
||||
return login(rest[0], rest[1])
|
||||
if cmd == "logout" and len(rest) == 1:
|
||||
return logout(rest[0])
|
||||
if cmd == "logins" and not rest:
|
||||
return list_logins()
|
||||
if cmd == "list" and not rest:
|
||||
return list_apps()
|
||||
sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n")
|
||||
|
||||
Reference in New Issue
Block a user