progress-cli 0.10.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- progress_cli/__init__.py +11 -0
- progress_cli/__main__.py +4 -0
- progress_cli/backup.py +63 -0
- progress_cli/clone.py +538 -0
- progress_cli/copy.py +264 -0
- progress_cli/dev.py +254 -0
- progress_cli/init.py +444 -0
- progress_cli/main.py +44 -0
- progress_cli/package.py +175 -0
- progress_cli/restore.py +169 -0
- progress_cli/runner.py +135 -0
- progress_cli/update.py +300 -0
- progress_cli-0.10.0.dist-info/METADATA +52 -0
- progress_cli-0.10.0.dist-info/RECORD +16 -0
- progress_cli-0.10.0.dist-info/WHEEL +4 -0
- progress_cli-0.10.0.dist-info/entry_points.txt +2 -0
progress_cli/restore.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""`progress restore` — restore ArangoDB databases from an arangodump
|
|
2
|
+
snapshot, taken locally or fetched from a remote Progress host.
|
|
3
|
+
|
|
4
|
+
Remote restores copy the snapshot to this host first, then restore from
|
|
5
|
+
the local copy (never stream): the copy is resumable and inspectable, a
|
|
6
|
+
connection drop cannot leave a half-restored database, and the snapshot
|
|
7
|
+
stays available locally for repeat restores. See docs/cli/restore.md.
|
|
8
|
+
|
|
9
|
+
The `_system` database is never restored: it holds this deployment's
|
|
10
|
+
ArangoDB users and their passwords, which must keep matching the Docker
|
|
11
|
+
secrets generated by `progress init` on THIS host.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import subprocess
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
|
|
21
|
+
from progress_cli.runner import (
|
|
22
|
+
CONTAINER_BACKUP_DIR, PROD_ROOT, StepError, arango_exec,
|
|
23
|
+
arango_root_password, console, docker, find_arango_container, run, step,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def snapshot_databases(snapshot_dir: Path) -> list[str]:
|
|
28
|
+
"""Database subdirectories of a multi-database arangodump."""
|
|
29
|
+
return sorted(
|
|
30
|
+
entry.name for entry in snapshot_dir.iterdir()
|
|
31
|
+
if entry.is_dir() and any(entry.glob("*.structure.json"))
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def check_snapshot(snapshot_dir: Path) -> None:
|
|
36
|
+
if not snapshot_dir.is_dir():
|
|
37
|
+
raise StepError(f"Snapshot directory not found: {snapshot_dir}")
|
|
38
|
+
encryption = snapshot_dir / "ENCRYPTION"
|
|
39
|
+
if encryption.exists() and encryption.read_text().strip() != "none":
|
|
40
|
+
raise StepError(
|
|
41
|
+
f"Snapshot is encrypted ({encryption.read_text().strip()}) — "
|
|
42
|
+
"encrypted dumps are not supported.",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def restore_databases(db_container: str, container_dir: str,
|
|
47
|
+
databases: list[str]) -> None:
|
|
48
|
+
"""Run arangorestore inside the db container for each database."""
|
|
49
|
+
password = arango_root_password(db_container)
|
|
50
|
+
auth = ["--server.username", "root", "--server.password", password]
|
|
51
|
+
for db_name in databases:
|
|
52
|
+
with step(f"Restoring {db_name}") as s:
|
|
53
|
+
arango_exec(
|
|
54
|
+
db_container, "arangorestore", *auth,
|
|
55
|
+
"--server.database", db_name,
|
|
56
|
+
"--create-database", "true",
|
|
57
|
+
"--input-directory", f"{container_dir}/{db_name}",
|
|
58
|
+
)
|
|
59
|
+
s.done("arangorestore complete")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def stage_in_container(db_container: str, host_dir: Path) -> tuple[str, bool]:
|
|
63
|
+
"""Make `host_dir` visible inside the db container.
|
|
64
|
+
|
|
65
|
+
Returns (container_path, staged): when the directory already lives in
|
|
66
|
+
the host-mounted backup dir it is used in place; otherwise it is
|
|
67
|
+
docker-cp'd into the container's /db_backup volume and marked for
|
|
68
|
+
cleanup.
|
|
69
|
+
"""
|
|
70
|
+
host_backup_dir = PROD_ROOT / "db_backup"
|
|
71
|
+
try:
|
|
72
|
+
relative = host_dir.resolve().relative_to(host_backup_dir.resolve())
|
|
73
|
+
return f"{CONTAINER_BACKUP_DIR}/{relative}", False
|
|
74
|
+
except (ValueError, OSError):
|
|
75
|
+
pass
|
|
76
|
+
staged = f"{CONTAINER_BACKUP_DIR}/.restore-staging"
|
|
77
|
+
with step("Staging snapshot in container") as s:
|
|
78
|
+
subprocess.run(["docker", "exec", db_container, "rm", "-rf", staged],
|
|
79
|
+
capture_output=True)
|
|
80
|
+
arango_exec(db_container, "mkdir", "-p", CONTAINER_BACKUP_DIR)
|
|
81
|
+
docker("cp", str(host_dir), f"{db_container}:{staged}", timeout=3600)
|
|
82
|
+
s.done(staged)
|
|
83
|
+
return staged, True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def restore(
|
|
87
|
+
snapshot: str = typer.Argument("latest", help="Snapshot name under the backup directory, or an absolute path to a dump directory"),
|
|
88
|
+
from_: str = typer.Option(None, "--from", help="Remote source (user@host) — copies <snapshot> from its /opt/progress/db_backup over scp, then restores from the local copy"),
|
|
89
|
+
database: list[str] = typer.Option(None, "--db", "-d", help="Restore only these databases (default: every database in the snapshot)"),
|
|
90
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Skip the destructive-restore confirmation"),
|
|
91
|
+
container: str = typer.Option(None, "--container", help="Database container name/ID override"),
|
|
92
|
+
):
|
|
93
|
+
"""Restore databases from a snapshot into the running stack.
|
|
94
|
+
|
|
95
|
+
Overwrites existing collections in the target databases. The source
|
|
96
|
+
is a snapshot under /opt/progress/db_backup (default `latest`), an
|
|
97
|
+
absolute path, or a remote host's backup directory via --from.
|
|
98
|
+
"""
|
|
99
|
+
backup_dir = PROD_ROOT / "db_backup"
|
|
100
|
+
|
|
101
|
+
if from_ and snapshot.startswith("/"):
|
|
102
|
+
raise typer.BadParameter(
|
|
103
|
+
"--from takes a snapshot NAME under the remote's backup "
|
|
104
|
+
"directory, not an absolute path.")
|
|
105
|
+
if from_:
|
|
106
|
+
remote = f"{from_}:/opt/progress/db_backup/{snapshot}"
|
|
107
|
+
local_name = f"{from_.split('@')[-1]}-{snapshot}-{datetime.now():%Y%m%d-%H%M%S}"
|
|
108
|
+
dest_root = backup_dir if backup_dir.is_dir() else Path("/tmp/progress-restore")
|
|
109
|
+
dest_root.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
host_dir = dest_root / local_name
|
|
111
|
+
with step(f"Copying snapshot from {from_}") as s:
|
|
112
|
+
run("scp", "-r", "-q", remote, str(host_dir), timeout=7200)
|
|
113
|
+
size = run("du", "-sh", str(host_dir)).split()[0]
|
|
114
|
+
s.done(f"{host_dir} ({size})")
|
|
115
|
+
elif snapshot.startswith("/"):
|
|
116
|
+
host_dir = Path(snapshot)
|
|
117
|
+
else:
|
|
118
|
+
host_dir = backup_dir / snapshot
|
|
119
|
+
|
|
120
|
+
with step("Checking snapshot") as s:
|
|
121
|
+
check_snapshot(host_dir)
|
|
122
|
+
available = snapshot_databases(host_dir)
|
|
123
|
+
if not available:
|
|
124
|
+
raise StepError(
|
|
125
|
+
f"No database dumps found in {host_dir}.",
|
|
126
|
+
hint="Expected per-database subdirectories as produced by "
|
|
127
|
+
"`progress backup` / arangodump --all-databases.",
|
|
128
|
+
)
|
|
129
|
+
targets = [db for db in available if db != "_system"]
|
|
130
|
+
if database:
|
|
131
|
+
if "_system" in database:
|
|
132
|
+
raise StepError(
|
|
133
|
+
"_system is never restored — it holds this deployment's "
|
|
134
|
+
"ArangoDB users, which must keep matching the Docker "
|
|
135
|
+
"secrets generated on this host."
|
|
136
|
+
)
|
|
137
|
+
missing = set(database) - set(available)
|
|
138
|
+
if missing:
|
|
139
|
+
raise StepError(
|
|
140
|
+
f"Not in this snapshot: {', '.join(sorted(missing))}. "
|
|
141
|
+
f"Available: {', '.join(available)}")
|
|
142
|
+
targets = list(database)
|
|
143
|
+
if not targets:
|
|
144
|
+
raise StepError("Nothing to restore in this snapshot.")
|
|
145
|
+
s.done(", ".join(targets))
|
|
146
|
+
if "_system" in available and not database:
|
|
147
|
+
console.print(" [dim]_system is skipped — ArangoDB users stay local to this deployment.[/]")
|
|
148
|
+
|
|
149
|
+
with step("Locating database container") as s:
|
|
150
|
+
db_container = container or find_arango_container()
|
|
151
|
+
s.done(db_container)
|
|
152
|
+
|
|
153
|
+
if not yes:
|
|
154
|
+
console.print(
|
|
155
|
+
f"\n This overwrites existing collections in "
|
|
156
|
+
f"[bold]{', '.join(targets)}[/] on container {db_container}."
|
|
157
|
+
)
|
|
158
|
+
if not typer.confirm(" Proceed?", default=False):
|
|
159
|
+
raise typer.Exit(0)
|
|
160
|
+
|
|
161
|
+
container_dir, staged = stage_in_container(db_container, host_dir)
|
|
162
|
+
try:
|
|
163
|
+
restore_databases(db_container, container_dir, targets)
|
|
164
|
+
finally:
|
|
165
|
+
if staged:
|
|
166
|
+
subprocess.run(["docker", "exec", db_container, "rm", "-rf",
|
|
167
|
+
container_dir], capture_output=True)
|
|
168
|
+
|
|
169
|
+
console.print(f"\n Restored [bold]{', '.join(targets)}[/] from {host_dir}\n")
|
progress_cli/runner.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Shared plumbing for progress CLI commands.
|
|
2
|
+
|
|
3
|
+
Step-by-step console output, subprocess helpers and docker helpers.
|
|
4
|
+
Every command builds on the
|
|
5
|
+
same `step()` context manager so install transcripts read as one status
|
|
6
|
+
line per operation (ADR-0006 UX).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import typer
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
|
|
18
|
+
console = Console(highlight=False)
|
|
19
|
+
|
|
20
|
+
# Production install root. Overridable for tests only.
|
|
21
|
+
PROD_ROOT = Path(os.environ.get("PROGRESS_ROOT", "/opt/progress"))
|
|
22
|
+
REGISTRY = "registry.gitlab.com/progresslab/progress-platform"
|
|
23
|
+
CONTAINER_BACKUP_DIR = "/db_backup"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class StepError(Exception):
|
|
27
|
+
"""A step failed. `hint` is an actionable next step shown to the user."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, message: str, hint: str | None = None):
|
|
30
|
+
super().__init__(message)
|
|
31
|
+
self.hint = hint
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _StepSkipped(Exception):
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Step:
|
|
39
|
+
"""Handle yielded by `step()`; lets the body attach a detail or skip."""
|
|
40
|
+
|
|
41
|
+
def __init__(self) -> None:
|
|
42
|
+
self.detail: str | None = None
|
|
43
|
+
|
|
44
|
+
def done(self, detail: str) -> None:
|
|
45
|
+
self.detail = detail
|
|
46
|
+
|
|
47
|
+
def skip(self, reason: str) -> None:
|
|
48
|
+
raise _StepSkipped(reason)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@contextmanager
|
|
52
|
+
def step(label: str):
|
|
53
|
+
console.print(f" ▸ {label:<36}", end="")
|
|
54
|
+
handle = Step()
|
|
55
|
+
try:
|
|
56
|
+
yield handle
|
|
57
|
+
except _StepSkipped as sk:
|
|
58
|
+
console.print(f"[yellow]—[/] ({sk})")
|
|
59
|
+
except StepError as e:
|
|
60
|
+
console.print("[red]✗[/]")
|
|
61
|
+
console.print(f"\n[red]Error:[/] {e}")
|
|
62
|
+
if e.hint:
|
|
63
|
+
console.print(f"[yellow]Try:[/] {e.hint}")
|
|
64
|
+
raise typer.Exit(1)
|
|
65
|
+
except KeyboardInterrupt:
|
|
66
|
+
console.print("[yellow]interrupted[/]")
|
|
67
|
+
raise typer.Exit(130)
|
|
68
|
+
else:
|
|
69
|
+
suffix = f" ({handle.detail})" if handle.detail else ""
|
|
70
|
+
console.print(f"[green]✓[/]{suffix}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def run(*argv: str, input: str | None = None, env: dict | None = None,
|
|
74
|
+
timeout: int = 900) -> str:
|
|
75
|
+
"""Run a command, return stripped stdout; raise StepError with the
|
|
76
|
+
output tail on failure."""
|
|
77
|
+
try:
|
|
78
|
+
p = subprocess.run(
|
|
79
|
+
argv, capture_output=True, text=True, input=input,
|
|
80
|
+
env=env, timeout=timeout,
|
|
81
|
+
)
|
|
82
|
+
except FileNotFoundError:
|
|
83
|
+
raise StepError(f"Command not found: {argv[0]}")
|
|
84
|
+
except subprocess.TimeoutExpired:
|
|
85
|
+
raise StepError(f"`{' '.join(argv)}` timed out after {timeout}s")
|
|
86
|
+
if p.returncode != 0:
|
|
87
|
+
output = (p.stderr or p.stdout or "").strip()
|
|
88
|
+
shown = list(argv)
|
|
89
|
+
for i, arg in enumerate(shown):
|
|
90
|
+
if arg in ("--server.password", "--password", "--registry-token"):
|
|
91
|
+
if i + 1 < len(shown):
|
|
92
|
+
shown[i + 1] = "***"
|
|
93
|
+
raise StepError(f"`{' '.join(shown)}` failed:\n{output[-2000:]}")
|
|
94
|
+
return p.stdout.strip()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def docker(*args: str, **kw) -> str:
|
|
98
|
+
return run("docker", *args, **kw)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
PS_FORMAT = "{{.ID}}\t{{.Image}}\t{{.Names}}"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def find_arango_container() -> str:
|
|
105
|
+
"""Locate the running ArangoDB container (Swarm task or Compose service)."""
|
|
106
|
+
return pick_arango_container(docker("ps", "--format", PS_FORMAT))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def pick_arango_container(ps_output: str) -> str:
|
|
110
|
+
"""The ArangoDB container in `docker ps --format PS_FORMAT` output."""
|
|
111
|
+
rows = [line.split("\t") for line in ps_output.splitlines() if line.strip()]
|
|
112
|
+
arango = [r for r in rows if r[1].startswith("arangodb")]
|
|
113
|
+
if not arango:
|
|
114
|
+
raise StepError(
|
|
115
|
+
"No running ArangoDB container found.",
|
|
116
|
+
hint="Is the Progress stack up? Check `docker ps`.",
|
|
117
|
+
)
|
|
118
|
+
if len(arango) > 1:
|
|
119
|
+
preferred = [r for r in arango if "progress" in r[2]]
|
|
120
|
+
arango = preferred or arango
|
|
121
|
+
return arango[0][0]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def arango_root_password(container: str) -> str:
|
|
125
|
+
"""Root password from the container's Docker secret; empty when the
|
|
126
|
+
deployment runs without auth (dev stack)."""
|
|
127
|
+
p = subprocess.run(
|
|
128
|
+
["docker", "exec", container, "cat", "/run/secrets/progress_db_root_pwd"],
|
|
129
|
+
capture_output=True, text=True,
|
|
130
|
+
)
|
|
131
|
+
return p.stdout.strip() if p.returncode == 0 else ""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def arango_exec(container: str, *argv: str, timeout: int = 3600) -> str:
|
|
135
|
+
return docker("exec", container, *argv, timeout=timeout)
|
progress_cli/update.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""`progress update` — roll the running stack's Progress services to a new tag.
|
|
2
|
+
|
|
3
|
+
The services to update are discovered from the running stack, not from a
|
|
4
|
+
list in this code (ADR-0022): every service whose image comes from the
|
|
5
|
+
Progress registry gets the same image name at the new tag. Images only:
|
|
6
|
+
a release that adds services or stack files needs a new deploy.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import Dict, List, Tuple, Optional
|
|
13
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
14
|
+
|
|
15
|
+
import typer
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskID
|
|
18
|
+
|
|
19
|
+
from progress_cli.runner import REGISTRY
|
|
20
|
+
|
|
21
|
+
console = Console()
|
|
22
|
+
|
|
23
|
+
STACK_NAME = "progress"
|
|
24
|
+
CLONE_IMAGE_LABEL = "progress.clone.image" # set by `progress clone`
|
|
25
|
+
RELEASE_LOG_PATH = Path("/opt/progress/release")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def registry_services(services: List[dict]) -> Dict[str, str]:
|
|
29
|
+
"""Service name -> Progress image name (`api`, `wf-sys-worker`, …) for
|
|
30
|
+
every service running a Progress registry image. A cloned host pins
|
|
31
|
+
images by ID and keeps the original reference in a service label."""
|
|
32
|
+
found = {}
|
|
33
|
+
for svc in services:
|
|
34
|
+
spec = svc["Spec"]
|
|
35
|
+
ref = ((spec.get("Labels") or {}).get(CLONE_IMAGE_LABEL)
|
|
36
|
+
or spec["TaskTemplate"]["ContainerSpec"]["Image"]).split("@")[0]
|
|
37
|
+
if not ref.startswith(REGISTRY + "/"):
|
|
38
|
+
continue
|
|
39
|
+
path = ref[len(REGISTRY) + 1:]
|
|
40
|
+
found[spec["Name"]] = path.rsplit(":", 1)[0] if ":" in path else path
|
|
41
|
+
return found
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def stack_services() -> List[dict]:
|
|
45
|
+
ids = subprocess.run(
|
|
46
|
+
["docker", "service", "ls", "-q", "--filter",
|
|
47
|
+
f"label=com.docker.stack.namespace={STACK_NAME}"],
|
|
48
|
+
capture_output=True, text=True, check=True,
|
|
49
|
+
).stdout.split()
|
|
50
|
+
if not ids:
|
|
51
|
+
return []
|
|
52
|
+
return json.loads(subprocess.run(
|
|
53
|
+
["docker", "service", "inspect", *ids],
|
|
54
|
+
capture_output=True, text=True, check=True,
|
|
55
|
+
).stdout)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def run_docker_command(cmd: List[str], capture_output: bool = True) -> Tuple[bool, str]:
|
|
59
|
+
"""Run a docker command and return success status and output."""
|
|
60
|
+
try:
|
|
61
|
+
result = subprocess.run(
|
|
62
|
+
cmd,
|
|
63
|
+
capture_output=capture_output,
|
|
64
|
+
text=True,
|
|
65
|
+
check=False,
|
|
66
|
+
timeout=600 # 10 minute timeout
|
|
67
|
+
)
|
|
68
|
+
return result.returncode == 0, result.stderr if result.returncode != 0 else result.stdout
|
|
69
|
+
except subprocess.TimeoutExpired:
|
|
70
|
+
return False, "Command timed out after 10 minutes"
|
|
71
|
+
except Exception as e:
|
|
72
|
+
return False, str(e)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def pull_image(image_name: str, tag: str, progress: Progress, task_id: TaskID) -> Tuple[str, bool, str]:
|
|
76
|
+
"""Pull a Docker image with progress tracking."""
|
|
77
|
+
full_image_name = f"{REGISTRY}/{image_name}:{tag}"
|
|
78
|
+
cmd = ["docker", "pull", full_image_name]
|
|
79
|
+
|
|
80
|
+
# Start the pull process
|
|
81
|
+
process = subprocess.Popen(
|
|
82
|
+
cmd,
|
|
83
|
+
stdout=subprocess.PIPE,
|
|
84
|
+
stderr=subprocess.STDOUT,
|
|
85
|
+
text=True,
|
|
86
|
+
bufsize=1,
|
|
87
|
+
universal_newlines=True
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# Update progress while pulling
|
|
91
|
+
last_status = f"Pulling {image_name}..."
|
|
92
|
+
error_output = []
|
|
93
|
+
|
|
94
|
+
while True:
|
|
95
|
+
output = process.stdout.readline()
|
|
96
|
+
if output == '' and process.poll() is not None:
|
|
97
|
+
break
|
|
98
|
+
if output:
|
|
99
|
+
line = output.strip()
|
|
100
|
+
# Extract meaningful status from docker output
|
|
101
|
+
if "Pulling" in line or "Downloading" in line or "Extracting" in line or "Pull complete" in line:
|
|
102
|
+
# Clean up the line for display (remove ANSI codes if any)
|
|
103
|
+
clean_line = line.replace('\r', '').replace('\x1b[', '').split('\x1b')[0]
|
|
104
|
+
last_status = f"Pulling {image_name}... {clean_line[:60]}"
|
|
105
|
+
progress.update(task_id, description=last_status)
|
|
106
|
+
elif "error" in line.lower() or "failed" in line.lower():
|
|
107
|
+
error_output.append(line)
|
|
108
|
+
|
|
109
|
+
# Wait for process to complete
|
|
110
|
+
process.wait()
|
|
111
|
+
success = process.returncode == 0
|
|
112
|
+
error_text = "\n".join(error_output) if error_output else ""
|
|
113
|
+
|
|
114
|
+
return image_name, success, error_text
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def update_service(service_name: str, image_name: str, tag: str, progress: Progress, task_id: TaskID,
|
|
118
|
+
pinned_by_clone: bool = False) -> Tuple[str, bool, str]:
|
|
119
|
+
"""Update a Docker service with progress tracking."""
|
|
120
|
+
full_image_name = f"{REGISTRY}/{image_name}:{tag}"
|
|
121
|
+
cmd = ["docker", "service", "update", "--image", full_image_name, "--force", service_name]
|
|
122
|
+
if pinned_by_clone: # the label would keep pointing at the old reference
|
|
123
|
+
cmd[3:3] = ["--label-rm", CLONE_IMAGE_LABEL]
|
|
124
|
+
|
|
125
|
+
success, output = run_docker_command(cmd, capture_output=True)
|
|
126
|
+
|
|
127
|
+
return service_name, success, output if not success else ""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def write_release_log(tag: str) -> None:
|
|
131
|
+
"""Write release log entry."""
|
|
132
|
+
try:
|
|
133
|
+
RELEASE_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
134
|
+
timestamp = datetime.now().strftime("%Y%m%d-%H%M")
|
|
135
|
+
with open(RELEASE_LOG_PATH, "a") as f:
|
|
136
|
+
f.write(f"{timestamp} {tag}\n")
|
|
137
|
+
console.print(f"[green]✓[/green] Release log entry added: {timestamp} {tag}")
|
|
138
|
+
except Exception as e:
|
|
139
|
+
console.print(f"[yellow]⚠[/yellow] Warning: Could not write release log: {e}")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def show_service_status() -> None:
|
|
143
|
+
"""Show current Docker service status."""
|
|
144
|
+
try:
|
|
145
|
+
result = subprocess.run(
|
|
146
|
+
["docker", "service", "ls"],
|
|
147
|
+
capture_output=True,
|
|
148
|
+
text=True,
|
|
149
|
+
check=True
|
|
150
|
+
)
|
|
151
|
+
console.print("\n[bold]Current Services:[/bold]")
|
|
152
|
+
console.print(result.stdout)
|
|
153
|
+
except Exception as e:
|
|
154
|
+
console.print(f"[yellow]⚠[/yellow] Could not retrieve service status: {e}")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def update(
|
|
158
|
+
tag: Optional[str] = typer.Argument(None, help="Image tag to deploy"),
|
|
159
|
+
services: Optional[List[str]] = typer.Option(None, "--service", "-s", help="Only update services whose name contains this string (default: every service running a Progress image)"),
|
|
160
|
+
skip_pull: bool = typer.Option(False, "--skip-pull", help="Skip pulling images (use existing local images)"),
|
|
161
|
+
) -> None:
|
|
162
|
+
"""
|
|
163
|
+
Roll the stack's Progress services to a new image tag.
|
|
164
|
+
|
|
165
|
+
Every service running a Progress registry image is updated to the same
|
|
166
|
+
image at TAG; images are pulled and services updated in parallel.
|
|
167
|
+
Images only: a release that adds services needs a new deploy.
|
|
168
|
+
"""
|
|
169
|
+
# Get tag from argument or prompt
|
|
170
|
+
if not tag:
|
|
171
|
+
tag = typer.prompt("Please enter the image tag to deploy")
|
|
172
|
+
if not tag:
|
|
173
|
+
console.print("[red]❌ Error: No tag provided. Aborting.[/red]")
|
|
174
|
+
raise typer.Exit(1)
|
|
175
|
+
|
|
176
|
+
console.print(f"[green]✓[/green] Using tag: [bold]{tag}[/bold]\n")
|
|
177
|
+
|
|
178
|
+
# Determine which services/images to update, from the running stack
|
|
179
|
+
try:
|
|
180
|
+
running = stack_services()
|
|
181
|
+
except (subprocess.CalledProcessError, FileNotFoundError) as e:
|
|
182
|
+
console.print(f"[red]❌ Error: Could not list the stack's services: {e}[/red]")
|
|
183
|
+
raise typer.Exit(1)
|
|
184
|
+
discovered = registry_services(running)
|
|
185
|
+
if not discovered:
|
|
186
|
+
console.print(f"[red]❌ Error: No service in stack '{STACK_NAME}' runs a {REGISTRY} image.[/red]")
|
|
187
|
+
raise typer.Exit(1)
|
|
188
|
+
if services:
|
|
189
|
+
wanted = [s.lower() for s in services]
|
|
190
|
+
discovered = {name: image for name, image in discovered.items()
|
|
191
|
+
if any(w in name.lower() for w in wanted)}
|
|
192
|
+
if not discovered:
|
|
193
|
+
console.print("[red]❌ Error: No matching services found.[/red]")
|
|
194
|
+
raise typer.Exit(1)
|
|
195
|
+
cloned = {svc["Spec"]["Name"] for svc in running
|
|
196
|
+
if CLONE_IMAGE_LABEL in (svc["Spec"].get("Labels") or {})}
|
|
197
|
+
|
|
198
|
+
images_to_pull = sorted(set(discovered.values()))
|
|
199
|
+
services_to_update = sorted(discovered.items())
|
|
200
|
+
|
|
201
|
+
console.print(f"[bold]🚀 Starting image pull and service update process for tag '{tag}'...[/bold]\n")
|
|
202
|
+
|
|
203
|
+
# Pull images in parallel
|
|
204
|
+
if not skip_pull:
|
|
205
|
+
with Progress(
|
|
206
|
+
SpinnerColumn(),
|
|
207
|
+
TextColumn("[progress.description]{task.description}"),
|
|
208
|
+
BarColumn(),
|
|
209
|
+
console=console
|
|
210
|
+
) as progress:
|
|
211
|
+
tasks = {}
|
|
212
|
+
with ThreadPoolExecutor(max_workers=len(images_to_pull)) as executor:
|
|
213
|
+
# Start all pull tasks
|
|
214
|
+
futures = {}
|
|
215
|
+
for image in images_to_pull:
|
|
216
|
+
task_id = progress.add_task(f"Pulling {image}...", total=None)
|
|
217
|
+
tasks[image] = task_id
|
|
218
|
+
future = executor.submit(pull_image, image, tag, progress, task_id)
|
|
219
|
+
futures[future] = (image, task_id)
|
|
220
|
+
|
|
221
|
+
# Wait for all pulls to complete
|
|
222
|
+
pull_results = []
|
|
223
|
+
for future in as_completed(futures):
|
|
224
|
+
image, task_id = futures[future]
|
|
225
|
+
try:
|
|
226
|
+
image_name, success, error = future.result()
|
|
227
|
+
progress.update(task_id, completed=True)
|
|
228
|
+
if success:
|
|
229
|
+
progress.update(task_id, description=f"[green]✓[/green] Pulled {image_name}")
|
|
230
|
+
else:
|
|
231
|
+
progress.update(task_id, description=f"[red]✗[/red] Failed to pull {image_name}")
|
|
232
|
+
pull_results.append((image_name, success, error))
|
|
233
|
+
except Exception as e:
|
|
234
|
+
progress.update(task_id, description=f"[red]✗[/red] Error pulling {image}: {str(e)}")
|
|
235
|
+
pull_results.append((image, False, str(e)))
|
|
236
|
+
|
|
237
|
+
# Check for failures
|
|
238
|
+
failed_pulls = [r for r in pull_results if not r[1]]
|
|
239
|
+
if failed_pulls:
|
|
240
|
+
console.print("\n[red]❌ Error: One or more image pulls failed:[/red]")
|
|
241
|
+
for image, _, error in failed_pulls:
|
|
242
|
+
console.print(f" [red]✗[/red] {image}")
|
|
243
|
+
if error:
|
|
244
|
+
console.print(f" {error[:200]}")
|
|
245
|
+
raise typer.Exit(1)
|
|
246
|
+
|
|
247
|
+
console.print("\n[green]✅ All images pulled successfully.[/green]\n")
|
|
248
|
+
|
|
249
|
+
# Update services in parallel
|
|
250
|
+
with Progress(
|
|
251
|
+
SpinnerColumn(),
|
|
252
|
+
TextColumn("[progress.description]{task.description}"),
|
|
253
|
+
BarColumn(),
|
|
254
|
+
console=console
|
|
255
|
+
) as progress:
|
|
256
|
+
tasks = {}
|
|
257
|
+
with ThreadPoolExecutor(max_workers=len(services_to_update)) as executor:
|
|
258
|
+
# Start all update tasks
|
|
259
|
+
futures = {}
|
|
260
|
+
for service_name, image_name in services_to_update:
|
|
261
|
+
task_id = progress.add_task(f"Updating {service_name}...", total=None)
|
|
262
|
+
tasks[service_name] = task_id
|
|
263
|
+
future = executor.submit(update_service, service_name, image_name, tag, progress, task_id,
|
|
264
|
+
service_name in cloned)
|
|
265
|
+
futures[future] = (service_name, task_id)
|
|
266
|
+
|
|
267
|
+
# Wait for all updates to complete
|
|
268
|
+
update_results = []
|
|
269
|
+
for future in as_completed(futures):
|
|
270
|
+
service_name, task_id = futures[future]
|
|
271
|
+
try:
|
|
272
|
+
svc_name, success, error = future.result()
|
|
273
|
+
progress.update(task_id, completed=True)
|
|
274
|
+
if success:
|
|
275
|
+
progress.update(task_id, description=f"[green]✓[/green] Updated {svc_name}")
|
|
276
|
+
else:
|
|
277
|
+
progress.update(task_id, description=f"[red]✗[/red] Failed to update {svc_name}")
|
|
278
|
+
update_results.append((svc_name, success, error))
|
|
279
|
+
except Exception as e:
|
|
280
|
+
progress.update(task_id, description=f"[red]✗[/red] Error updating {service_name}: {str(e)}")
|
|
281
|
+
update_results.append((service_name, False, str(e)))
|
|
282
|
+
|
|
283
|
+
# Check for failures
|
|
284
|
+
failed_updates = [r for r in update_results if not r[1]]
|
|
285
|
+
if failed_updates:
|
|
286
|
+
console.print("\n[red]❌ Error: One or more service updates failed:[/red]")
|
|
287
|
+
for service, _, error in failed_updates:
|
|
288
|
+
console.print(f" [red]✗[/red] {service}")
|
|
289
|
+
if error:
|
|
290
|
+
console.print(f" {error[:200]}")
|
|
291
|
+
raise typer.Exit(1)
|
|
292
|
+
|
|
293
|
+
console.print(f"\n[green]🎉 All services updated successfully to tag '{tag}'![/green]\n")
|
|
294
|
+
|
|
295
|
+
# Write release log
|
|
296
|
+
console.print("[bold]📋 Adding release log entry[/bold]")
|
|
297
|
+
write_release_log(tag)
|
|
298
|
+
|
|
299
|
+
# Show service status
|
|
300
|
+
show_service_status()
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: progress-cli
|
|
3
|
+
Version: 0.10.0
|
|
4
|
+
Summary: Progress Platform operations CLI — install, back up, restore, and run a dev environment
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Requires-Dist: httpx>=0.27
|
|
8
|
+
Requires-Dist: pyyaml>=6
|
|
9
|
+
Requires-Dist: rich>=13
|
|
10
|
+
Requires-Dist: typer>=0.12
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# progress-cli
|
|
14
|
+
|
|
15
|
+
The Progress Platform operations CLI: `progress init` (provision a host),
|
|
16
|
+
`progress backup` / `progress restore` (database snapshots, local or
|
|
17
|
+
remote), `progress update` (roll services to a new release), and
|
|
18
|
+
`progress dev` (hot-reload development stack from a checkout).
|
|
19
|
+
|
|
20
|
+
Full reference: <https://progresslabit.github.io/progress-platform/cli/>
|
|
21
|
+
(sources in `docs/cli/`). Design decisions: `km/decisions/0019-progress-cli-implementation.md`,
|
|
22
|
+
`km/decisions/0022-cli-engine-deploy-package.md`.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
curl -fsSL https://progresslabit.github.io/progress-platform/install.sh | sudo sh # servers, all users
|
|
28
|
+
uv tool install progress-cli # or per user (pipx works too)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
or, from a checkout:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
uv tool install --from ./cli progress-cli
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Development
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
cd cli
|
|
41
|
+
uv venv && uv pip install -e . --python .venv/bin/python
|
|
42
|
+
.venv/bin/progress --help
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The wheel holds only the CLI code. Release-specific files ship per
|
|
46
|
+
platform release in the `deploy:<tag>` image (`deploy/package.Dockerfile`,
|
|
47
|
+
`deploy/manifest.yaml`); editable installs read the live repo files
|
|
48
|
+
instead. Outside `progress dev`, the CLI must not read repo files except
|
|
49
|
+
through the package (`tests/cli/test_package.py`). Versioning: bump
|
|
50
|
+
`version` in `pyproject.toml`, tag `cli-vX.Y.Z`, CI publishes to PyPI. The CI drift
|
|
51
|
+
gate (`tests/cli/test_cli_help.py`) snapshots every command's `--help`
|
|
52
|
+
against `docs/cli/`.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
progress_cli/__init__.py,sha256=8GIPljhPduYmh7wYSEs1KMPYi2m28y-HR5efc0ZrO8w,401
|
|
2
|
+
progress_cli/__main__.py,sha256=x_uEAqAZ3djYpOGZU7e4BPleVm2dfuCLoMsFG9y_Xe4,140
|
|
3
|
+
progress_cli/backup.py,sha256=k26k-29n0LPT9W6fJPxMgjjGZRyhmE6P_vZ2sOX1PKI,2520
|
|
4
|
+
progress_cli/clone.py,sha256=kQekd8IPjuquSqs2e7PYLabIxp0o7fTCN8_UHXs2CE4,27554
|
|
5
|
+
progress_cli/copy.py,sha256=vuOOPGeSYrDhm2TCXl9Y6-Wt7aSp9L9JmZSXe6mO9DQ,12759
|
|
6
|
+
progress_cli/dev.py,sha256=JtQI5WEN_nXBM4xJfF8cq6U8r9D-X1g3j-76lr5b7MQ,10516
|
|
7
|
+
progress_cli/init.py,sha256=h-oa8FScyiNABmjHb1O_445mk9IOUYbp6gc2fxveBxE,19051
|
|
8
|
+
progress_cli/main.py,sha256=ioHftnsTSD85_fsmQ4SbaY9-rd9AJraBOn1Np8cC2sg,1284
|
|
9
|
+
progress_cli/package.py,sha256=PMmwN5fwnwev7ycEBZNdbwbWQ_Nj8ekXC-ZuGW4eE1g,6644
|
|
10
|
+
progress_cli/restore.py,sha256=Oco_5DhUpUU04h5tDS1sjBhI4LzzCbvbvydtR3KcU5k,7403
|
|
11
|
+
progress_cli/runner.py,sha256=BUdgLruraXLVdh6uiPYSwHksgKfvYovqn4qqaNwP90w,4315
|
|
12
|
+
progress_cli/update.py,sha256=4jCj9oFvjY_dOKe_N2YGRGGYdXP2S0uAiMbBYreWBhU,12641
|
|
13
|
+
progress_cli-0.10.0.dist-info/METADATA,sha256=ro7vgs2wrsFFjWqQZ1W5jbuLhAnwPppQkLzR38Qhz-A,1819
|
|
14
|
+
progress_cli-0.10.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
15
|
+
progress_cli-0.10.0.dist-info/entry_points.txt,sha256=SRPjE8VzFiomN1937ZohwKiABxsPdUeHKEKScn2bae8,51
|
|
16
|
+
progress_cli-0.10.0.dist-info/RECORD,,
|