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/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Progress Platform operations CLI."""
|
|
2
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
__version__ = version("progress-cli")
|
|
6
|
+
except PackageNotFoundError: # unpackaged checkout (tests): same single source
|
|
7
|
+
import tomllib
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
__version__ = tomllib.loads(
|
|
11
|
+
(Path(__file__).parents[1] / "pyproject.toml").read_text())["project"]["version"]
|
progress_cli/__main__.py
ADDED
progress_cli/backup.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""`progress backup` — dump ArangoDB into the db container's /db_backup
|
|
2
|
+
volume (on a production host that's the /opt/progress/db_backup bind
|
|
3
|
+
mount) and repoint the `latest` link."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
|
|
10
|
+
from progress_cli.runner import (
|
|
11
|
+
CONTAINER_BACKUP_DIR, PROD_ROOT, arango_exec, arango_root_password,
|
|
12
|
+
console, find_arango_container, step,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def backup(
|
|
17
|
+
database: list[str] = typer.Option(None, "--db", "-d", help="Dump only these databases (default: all databases)"),
|
|
18
|
+
label: str = typer.Option(None, "--label", help="Snapshot directory name (default: local timestamp, e.g. 20260709-153000)"),
|
|
19
|
+
container: str = typer.Option(None, "--container", help="Database container name/ID override"),
|
|
20
|
+
):
|
|
21
|
+
"""Create a database snapshot with arangodump.
|
|
22
|
+
|
|
23
|
+
Writes to <snapshot> inside the db container's /db_backup volume and
|
|
24
|
+
updates the `latest` link to point at it. On a host installed by
|
|
25
|
+
`progress init` the snapshot lands in /opt/progress/db_backup/.
|
|
26
|
+
"""
|
|
27
|
+
name = label or datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
28
|
+
|
|
29
|
+
with step("Locating database container") as s:
|
|
30
|
+
db_container = container or find_arango_container()
|
|
31
|
+
s.done(db_container)
|
|
32
|
+
|
|
33
|
+
password = arango_root_password(db_container)
|
|
34
|
+
auth = ["--server.username", "root", "--server.password", password]
|
|
35
|
+
|
|
36
|
+
with step(f"Dumping to {name}") as s:
|
|
37
|
+
target = f"{CONTAINER_BACKUP_DIR}/{name}"
|
|
38
|
+
# arangodump only creates the leaf directory
|
|
39
|
+
arango_exec(db_container, "mkdir", "-p", target)
|
|
40
|
+
if database:
|
|
41
|
+
for db_name in database:
|
|
42
|
+
arango_exec(
|
|
43
|
+
db_container, "arangodump", *auth,
|
|
44
|
+
"--server.database", db_name,
|
|
45
|
+
"--output-directory", f"{target}/{db_name}",
|
|
46
|
+
)
|
|
47
|
+
s.done(", ".join(database))
|
|
48
|
+
else:
|
|
49
|
+
arango_exec(
|
|
50
|
+
db_container, "arangodump", *auth,
|
|
51
|
+
"--all-databases", "true",
|
|
52
|
+
"--output-directory", target,
|
|
53
|
+
)
|
|
54
|
+
s.done("all databases")
|
|
55
|
+
|
|
56
|
+
with step("Updating `latest` link") as s:
|
|
57
|
+
arango_exec(db_container, "ln", "-sfn", name,
|
|
58
|
+
f"{CONTAINER_BACKUP_DIR}/latest")
|
|
59
|
+
s.done(f"latest → {name}")
|
|
60
|
+
|
|
61
|
+
host_path = PROD_ROOT / "db_backup" / name
|
|
62
|
+
location = host_path if host_path.exists() else f"{db_container}:{CONTAINER_BACKUP_DIR}/{name}"
|
|
63
|
+
console.print(f"\n Snapshot: [bold]{location}[/]\n")
|
progress_cli/clone.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
"""`progress clone` — copy a running Progress host onto a fresh Linux VM.
|
|
2
|
+
|
|
3
|
+
Runs on the TARGET and pulls from the source over SSH, like
|
|
4
|
+
`restore --from`. Nothing is generated or re-rendered, so it works for
|
|
5
|
+
any release that keeps the /opt/progress layout (0.9 Ansible installs
|
|
6
|
+
included):
|
|
7
|
+
|
|
8
|
+
- services are recreated from the source's live Swarm specs, which
|
|
9
|
+
carry the deploy-time environment (the 0.9 playbook passed VERSION,
|
|
10
|
+
DB_ROOT_PWD and HOST at deploy time and never wrote them down);
|
|
11
|
+
- images are copied by ID with docker save/load: no registry
|
|
12
|
+
credentials, and floating tags (`3-latest`) cannot drift;
|
|
13
|
+
- secrets keep the source's values, read from the containers that
|
|
14
|
+
mount them (Swarm never returns a secret's value);
|
|
15
|
+
- /opt/progress and every volume the services mount are rsynced: once
|
|
16
|
+
hot, then again with the source stack scaled to 0, so the database
|
|
17
|
+
files are consistent and _system users keep matching the secrets.
|
|
18
|
+
|
|
19
|
+
A failure after the source was stopped scales it back up. See
|
|
20
|
+
docs/cli/clone.md.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import copy
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import platform
|
|
28
|
+
import re
|
|
29
|
+
import shlex
|
|
30
|
+
import shutil
|
|
31
|
+
import subprocess
|
|
32
|
+
import time
|
|
33
|
+
from datetime import datetime, timezone
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
import httpx
|
|
37
|
+
import typer
|
|
38
|
+
|
|
39
|
+
from progress_cli.init import (
|
|
40
|
+
DB_INIT_MARKER, MARKER, _load_env_file, install_docker,
|
|
41
|
+
)
|
|
42
|
+
from progress_cli.runner import (
|
|
43
|
+
PROD_ROOT, REGISTRY, StepError, console, docker, run, step,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
SSH_OPTS = [
|
|
47
|
+
"-o", "BatchMode=yes",
|
|
48
|
+
"-o", "ControlMaster=auto",
|
|
49
|
+
"-o", "ControlPath=/tmp/progress-clone-%C",
|
|
50
|
+
"-o", "ControlPersist=15m",
|
|
51
|
+
]
|
|
52
|
+
SERVICE_LABEL = "com.docker.swarm.service.name"
|
|
53
|
+
CLONE_TAG = "progress-clone" # progress-clone:<source image id> on the target
|
|
54
|
+
# Overlay networks get a fresh VXLAN ID on the target.
|
|
55
|
+
SKIP_NETWORK_OPTIONS = {"com.docker.network.driver.overlay.vxlanid_list"}
|
|
56
|
+
WORKER_SUFFIX = "_wf-integration-worker" # runs client flows against the customer's systems
|
|
57
|
+
PROD_NAMES = {"prod", "production"}
|
|
58
|
+
API_SUFFIX = "_api"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---- pure helpers (tests/cli/test_clone.py) -----------------------------
|
|
62
|
+
|
|
63
|
+
def release_tag(services: list[dict]) -> str:
|
|
64
|
+
"""The single Progress image tag the source runs.
|
|
65
|
+
|
|
66
|
+
Raises when services disagree (a partial `update`): cloning a mixed
|
|
67
|
+
deployment would hide the problem behind one VERSION line.
|
|
68
|
+
"""
|
|
69
|
+
tags: dict[str, str] = {}
|
|
70
|
+
for svc in services:
|
|
71
|
+
task = svc["Spec"]["TaskTemplate"]
|
|
72
|
+
if (task.get("RestartPolicy") or {}).get("Condition") == "none":
|
|
73
|
+
continue # one-shot leftovers (init-db) keep their install-time tag
|
|
74
|
+
# A cloned host runs images pinned by ID; the original ref is in the label.
|
|
75
|
+
ref = ((svc["Spec"].get("Labels") or {}).get("progress.clone.image")
|
|
76
|
+
or task["ContainerSpec"]["Image"]).split("@")[0]
|
|
77
|
+
if not ref.startswith(REGISTRY + "/"):
|
|
78
|
+
continue
|
|
79
|
+
_, _, tag = ref.rpartition(":")
|
|
80
|
+
tags[svc["Spec"]["Name"]] = "latest" if "/" in tag else tag
|
|
81
|
+
if not tags:
|
|
82
|
+
raise StepError(f"No service on the source runs a {REGISTRY} image.")
|
|
83
|
+
if len(set(tags.values())) > 1:
|
|
84
|
+
listing = ", ".join(f"{name}={tag}" for name, tag in sorted(tags.items()))
|
|
85
|
+
raise StepError(
|
|
86
|
+
f"Source services run different release tags: {listing}",
|
|
87
|
+
hint="Align them on the source (docker service update --image …), then rerun.",
|
|
88
|
+
)
|
|
89
|
+
return next(iter(tags.values()))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def target_spec(svc: dict, image_id: str | None,
|
|
93
|
+
network_names: dict[str, str], secret_ids: dict[str, str]) -> dict:
|
|
94
|
+
"""Source service spec rewritten for the target: image pinned by ID,
|
|
95
|
+
network and secret references remapped from source IDs."""
|
|
96
|
+
spec = copy.deepcopy(svc["Spec"])
|
|
97
|
+
container = spec["TaskTemplate"]["ContainerSpec"]
|
|
98
|
+
if image_id:
|
|
99
|
+
spec.setdefault("Labels", {})["progress.clone.image"] = container["Image"]
|
|
100
|
+
container["Image"] = image_id
|
|
101
|
+
for attachment in spec["TaskTemplate"].get("Networks") or []:
|
|
102
|
+
attachment["Target"] = network_names[attachment["Target"]]
|
|
103
|
+
for attachment in spec.get("Networks") or []:
|
|
104
|
+
attachment["Target"] = network_names[attachment["Target"]]
|
|
105
|
+
for ref in container.get("Secrets") or []:
|
|
106
|
+
ref["SecretID"] = secret_ids[ref["SecretName"]]
|
|
107
|
+
return spec
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def loaded_image_id(output: str) -> str:
|
|
111
|
+
"""The ID `docker load` gave one image saved by ID. It is not the
|
|
112
|
+
source's ID when the image stores differ: Docker 29's containerd store
|
|
113
|
+
derives IDs from the manifest, older engines from the config."""
|
|
114
|
+
ids = re.findall(r"^Loaded image ID: (sha256:[0-9a-f]{64})$", output, re.M)
|
|
115
|
+
if len(ids) != 1:
|
|
116
|
+
raise StepError(f"Unexpected docker load output: {output[-300:]}")
|
|
117
|
+
return ids[0]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def env_label(name: str, color: str | None) -> tuple[str, str]:
|
|
121
|
+
"""Validated (NAME, color) for a non-production environment."""
|
|
122
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]{1,16}", name):
|
|
123
|
+
raise typer.BadParameter(f"{name!r}: 1-16 letters, digits, - or _.", param_hint="--env")
|
|
124
|
+
if name.lower() in PROD_NAMES:
|
|
125
|
+
raise typer.BadParameter("--env marks a non-production copy. For a cutover, omit it.",
|
|
126
|
+
param_hint="--env")
|
|
127
|
+
if color and not re.fullmatch(r"#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?", color):
|
|
128
|
+
raise typer.BadParameter(f"{color!r}: expected #rgb or #rrggbb.", param_hint="--env-color")
|
|
129
|
+
return name.upper(), color or ""
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def with_env(env: list[str] | None, values: dict[str, str]) -> list[str]:
|
|
133
|
+
"""A container spec's Env list with KEY=value entries set or replaced.
|
|
134
|
+
Service env, not api.env: older APIs reject unknown keys in their .env
|
|
135
|
+
file, but ignore unknown environment variables."""
|
|
136
|
+
return [e for e in env or [] if e.partition("=")[0] not in values] + [
|
|
137
|
+
f"{k}={v}" for k, v in values.items()]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def set_env_var(text: str, key: str, value: str) -> str:
|
|
141
|
+
"""Set KEY=value in a dotenv text, replacing the line or appending it."""
|
|
142
|
+
lines = [line for line in text.splitlines() if not line.startswith(f"{key}=")]
|
|
143
|
+
return "\n".join([f"{key}={value}", *lines]) + "\n"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def volume_data_path(volume: dict) -> str:
|
|
147
|
+
"""Where a local volume's data lives: the bind device, or the mountpoint."""
|
|
148
|
+
options = volume.get("Options") or {}
|
|
149
|
+
if "bind" in options.get("o", "").split(","):
|
|
150
|
+
return options["device"]
|
|
151
|
+
return volume["Mountpoint"]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ---- remote / docker plumbing -------------------------------------------
|
|
155
|
+
|
|
156
|
+
def remote(src: str, *argv: str, timeout: int = 900) -> str:
|
|
157
|
+
return run("ssh", *SSH_OPTS, src, shlex.join(argv), timeout=timeout)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def rsync(src: str, source_path: str, target_path: str, *, hot: bool) -> None:
|
|
161
|
+
"""Mirror a source directory; progress goes straight to the terminal.
|
|
162
|
+
Exit 24 (files vanished mid-copy) is expected on the hot pass."""
|
|
163
|
+
console.print()
|
|
164
|
+
# --one-file-system: never descend into mounts such as the autofs
|
|
165
|
+
# network shares under cmounts/; the mountpoint itself is copied.
|
|
166
|
+
argv = [
|
|
167
|
+
"rsync", "-aHAX", "--one-file-system", "--numeric-ids", "--delete", "--info=progress2",
|
|
168
|
+
"--exclude", f"/config/{MARKER}",
|
|
169
|
+
"-e", shlex.join(["ssh", *SSH_OPTS]),
|
|
170
|
+
f"{src}:{source_path.rstrip('/')}/", f"{target_path.rstrip('/')}/",
|
|
171
|
+
]
|
|
172
|
+
Path(target_path).mkdir(parents=True, exist_ok=True)
|
|
173
|
+
code = subprocess.run(argv).returncode
|
|
174
|
+
if code != 0 and not (hot and code == 24):
|
|
175
|
+
raise StepError(f"rsync of {source_path} exited with {code}.",
|
|
176
|
+
hint="Rerun progress clone: copies resume where they stopped.")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def docker_api() -> httpx.Client:
|
|
180
|
+
return httpx.Client(transport=httpx.HTTPTransport(uds="/var/run/docker.sock"),
|
|
181
|
+
base_url="http://docker", timeout=60)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def scale_command(replicas: dict[str, int]) -> list[str]:
|
|
185
|
+
return ["docker", "service", "scale", "--detach",
|
|
186
|
+
*(f"{name}={n}" for name, n in sorted(replicas.items()))]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def clone(
|
|
190
|
+
from_: str = typer.Option(..., "--from", help="Source host (root@host). The target must reach it over SSH with a key"),
|
|
191
|
+
restart_source: bool = typer.Option(False, "--restart-source", help="Scale the source back up after the copy (rehearsals). Default: leave it stopped (cutover)"),
|
|
192
|
+
env: str = typer.Option(None, "--env", help="Make this host a non-production environment (TEST, DEV…): the source restarts afterwards, client flows stay stopped, and the UI shows the name"),
|
|
193
|
+
env_color: str = typer.Option(None, "--env-color", help="With --env: the UI's environment color, #rgb or #rrggbb"),
|
|
194
|
+
yes: bool = typer.Option(False, "--yes", "-y", help="Skip the confirmation before the source is stopped"),
|
|
195
|
+
):
|
|
196
|
+
"""Clone a running Progress host onto this fresh machine.
|
|
197
|
+
|
|
198
|
+
Copies services, images, secrets, /opt/progress and every mounted
|
|
199
|
+
volume from the source, stopping the source stack for the final
|
|
200
|
+
copy. Run as root on the target.
|
|
201
|
+
"""
|
|
202
|
+
src = from_
|
|
203
|
+
if env_color and not env:
|
|
204
|
+
raise typer.BadParameter("--env-color needs --env.")
|
|
205
|
+
if env:
|
|
206
|
+
env, env_color = env_label(env, env_color)
|
|
207
|
+
restart_source = True # the source is production: it must come back
|
|
208
|
+
|
|
209
|
+
# ---- checks ---------------------------------------------------------
|
|
210
|
+
with step("Checking this host") as s:
|
|
211
|
+
if platform.system() != "Linux":
|
|
212
|
+
raise StepError("progress clone provisions a Linux host.")
|
|
213
|
+
if os.geteuid() != 0:
|
|
214
|
+
raise StepError("Must run as root.", hint="sudo progress clone …")
|
|
215
|
+
if (PROD_ROOT / "config" / MARKER).exists():
|
|
216
|
+
raise StepError(f"{PROD_ROOT / 'config' / MARKER} exists: this host is already installed.")
|
|
217
|
+
if not shutil.which("rsync"):
|
|
218
|
+
raise StepError("rsync is not installed.", hint="apt install rsync")
|
|
219
|
+
s.done("Linux, root, rsync")
|
|
220
|
+
|
|
221
|
+
with step(f"Connecting to {src}") as s:
|
|
222
|
+
if remote(src, "id", "-u") != "0":
|
|
223
|
+
raise StepError(f"{src} is not root.", hint="Use --from root@host.")
|
|
224
|
+
for tool in ("docker", "rsync"):
|
|
225
|
+
remote(src, "sh", "-c", f"command -v {tool}")
|
|
226
|
+
source_docker = remote(src, "docker", "version", "--format", "{{.Server.Version}}")
|
|
227
|
+
s.done(f"root, Docker {source_docker}, rsync")
|
|
228
|
+
|
|
229
|
+
# ---- inventory (source still running) -------------------------------
|
|
230
|
+
with step("Reading source services") as s:
|
|
231
|
+
ids = remote(src, "docker", "service", "ls", "-q").split()
|
|
232
|
+
if not ids:
|
|
233
|
+
raise StepError(f"No Swarm services on {src}.", hint="Is the source stack running?")
|
|
234
|
+
services, one_shot = [], []
|
|
235
|
+
for svc in json.loads(remote(src, "docker", "service", "inspect", *ids)):
|
|
236
|
+
# One-shot jobs (db init) already ran: recreating them reruns them.
|
|
237
|
+
if (svc["Spec"]["TaskTemplate"].get("RestartPolicy") or {}).get("Condition") == "none":
|
|
238
|
+
one_shot.append(svc["Spec"]["Name"])
|
|
239
|
+
else:
|
|
240
|
+
services.append(svc)
|
|
241
|
+
for svc in services:
|
|
242
|
+
name, task = svc["Spec"]["Name"], svc["Spec"]["TaskTemplate"]
|
|
243
|
+
if task["ContainerSpec"].get("Configs"):
|
|
244
|
+
raise StepError(f"{name} uses Docker configs: unsupported.")
|
|
245
|
+
pinned = [c for c in (task.get("Placement") or {}).get("Constraints") or []
|
|
246
|
+
if "node.id" in c or "node.hostname" in c]
|
|
247
|
+
if pinned:
|
|
248
|
+
raise StepError(f"{name} is pinned to a source node ({pinned[0]}).")
|
|
249
|
+
# Global services (e.g. portainer_agent) cannot scale to 0: they keep
|
|
250
|
+
# running on the source and must not write to the copied volumes.
|
|
251
|
+
replicas = {svc["Spec"]["Name"]: svc["Spec"]["Mode"]["Replicated"]["Replicas"]
|
|
252
|
+
for svc in services if "Replicated" in svc["Spec"]["Mode"]}
|
|
253
|
+
names = {svc["Spec"]["Name"] for svc in services}
|
|
254
|
+
release = release_tag(services)
|
|
255
|
+
skipped = f", skipping one-shot {', '.join(one_shot)}" if one_shot else ""
|
|
256
|
+
s.done(f"{len(services)} services, release {release}{skipped}")
|
|
257
|
+
|
|
258
|
+
with step("Reading containers and secrets") as s:
|
|
259
|
+
container_ids = remote(src, "docker", "ps", "-q").split()
|
|
260
|
+
containers: dict[str, dict] = {} # service -> one running container
|
|
261
|
+
for c in json.loads(remote(src, "docker", "inspect", *container_ids)) if container_ids else []:
|
|
262
|
+
svc_name = c["Config"]["Labels"].get(SERVICE_LABEL)
|
|
263
|
+
if svc_name and c["State"]["Running"]:
|
|
264
|
+
containers.setdefault(svc_name, c)
|
|
265
|
+
image_ids = {name: c["Image"] for name, c in containers.items()}
|
|
266
|
+
|
|
267
|
+
all_secret_ids = remote(src, "docker", "secret", "ls", "-q").split()
|
|
268
|
+
secret_labels = {
|
|
269
|
+
entry["Spec"]["Name"]: entry["Spec"].get("Labels") or {}
|
|
270
|
+
for entry in (json.loads(remote(src, "docker", "secret", "inspect", *all_secret_ids))
|
|
271
|
+
if all_secret_ids else [])
|
|
272
|
+
}
|
|
273
|
+
secret_values: dict[str, bytes] = {}
|
|
274
|
+
for svc in services:
|
|
275
|
+
container = containers.get(svc["Spec"]["Name"])
|
|
276
|
+
for ref in svc["Spec"]["TaskTemplate"]["ContainerSpec"].get("Secrets") or []:
|
|
277
|
+
if container is None or ref["SecretName"] in secret_values:
|
|
278
|
+
continue
|
|
279
|
+
# Raw bytes, not run(): a trailing newline is part of the value.
|
|
280
|
+
p = subprocess.run(
|
|
281
|
+
["ssh", *SSH_OPTS, src, shlex.join(
|
|
282
|
+
["docker", "exec", container["Id"], "cat", f"/run/secrets/{ref['File']['Name']}"])],
|
|
283
|
+
capture_output=True,
|
|
284
|
+
)
|
|
285
|
+
if p.returncode == 0:
|
|
286
|
+
secret_values[ref["SecretName"]] = p.stdout
|
|
287
|
+
wanted = {ref["SecretName"] for svc in services
|
|
288
|
+
for ref in svc["Spec"]["TaskTemplate"]["ContainerSpec"].get("Secrets") or []}
|
|
289
|
+
unread = sorted(wanted - set(secret_values))
|
|
290
|
+
if unread:
|
|
291
|
+
raise StepError(
|
|
292
|
+
f"Cannot read secrets {', '.join(unread)}: no running container mounts them.",
|
|
293
|
+
hint="Start a service that mounts them on the source, then rerun.",
|
|
294
|
+
)
|
|
295
|
+
s.done(f"{len(image_ids)} running, {len(secret_values)} secrets")
|
|
296
|
+
|
|
297
|
+
with step("Reading networks and volumes") as s:
|
|
298
|
+
network_ids = sorted({a["Target"] for svc in services
|
|
299
|
+
for a in (svc["Spec"]["TaskTemplate"].get("Networks") or [])
|
|
300
|
+
+ (svc["Spec"].get("Networks") or [])})
|
|
301
|
+
networks = json.loads(remote(src, "docker", "network", "inspect", *network_ids)) if network_ids else []
|
|
302
|
+
network_names = {n["Id"]: n["Name"] for n in networks}
|
|
303
|
+
volume_names = sorted({m["Source"] for svc in services
|
|
304
|
+
for m in svc["Spec"]["TaskTemplate"]["ContainerSpec"].get("Mounts") or []
|
|
305
|
+
if m.get("Type") == "volume" and m.get("Source")})
|
|
306
|
+
volumes = json.loads(remote(src, "docker", "volume", "inspect", *volume_names)) if volume_names else []
|
|
307
|
+
for v in volumes:
|
|
308
|
+
if v["Driver"] != "local":
|
|
309
|
+
raise StepError(f"Volume {v['Name']} uses driver {v['Driver']}: unsupported.")
|
|
310
|
+
prod = str(PROD_ROOT).rstrip("/") + "/"
|
|
311
|
+
# Volumes outside /opt/progress get their own rsync.
|
|
312
|
+
extra_paths = sorted({volume_data_path(v) for v in volumes
|
|
313
|
+
if not volume_data_path(v).startswith(prod)})
|
|
314
|
+
s.done(f"{len(networks)} networks, {len(volumes)} volumes ({len(extra_paths)} outside {PROD_ROOT})")
|
|
315
|
+
|
|
316
|
+
with step("Checking disk space") as s:
|
|
317
|
+
data_bytes = sum(int(line.split()[0]) for line in remote(
|
|
318
|
+
src, "du", "-sxb", str(PROD_ROOT), *extra_paths, timeout=3600).splitlines())
|
|
319
|
+
unique_images = sorted(set(image_ids.values()))
|
|
320
|
+
image_bytes = sum(int(x) for x in remote(
|
|
321
|
+
src, "docker", "image", "inspect", "--format", "{{.Size}}", *unique_images).split()) if unique_images else 0
|
|
322
|
+
need = (data_bytes + image_bytes) * 1.1 + 5e9
|
|
323
|
+
free = shutil.disk_usage("/").free
|
|
324
|
+
if free < need:
|
|
325
|
+
raise StepError(f"Need {need / 1e9:.0f} GB free on /, found {free / 1e9:.0f} GB.")
|
|
326
|
+
s.done(f"{data_bytes / 1e9:.1f} GB data + {image_bytes / 1e9:.1f} GB images, {free / 1e9:.0f} GB free")
|
|
327
|
+
|
|
328
|
+
if not yes:
|
|
329
|
+
console.print(
|
|
330
|
+
f"\n The final copy stops all {len(replicas)} replicated services on [bold]{src}[/]."
|
|
331
|
+
+ (f"\n They restart there afterwards. This host becomes [bold]{env}[/], with client"
|
|
332
|
+
f"\n flows ({WORKER_SUFFIX.lstrip('_')}) stopped." if env else
|
|
333
|
+
f"\n The clone then starts them here, scheduled flows and integrations included:"
|
|
334
|
+
f"\n if this host can reach the customer's systems, it acts on them.")
|
|
335
|
+
)
|
|
336
|
+
if not typer.confirm(" Proceed?", default=False):
|
|
337
|
+
raise typer.Exit(0)
|
|
338
|
+
console.print()
|
|
339
|
+
|
|
340
|
+
# ---- target setup + hot copy (source still running) -----------------
|
|
341
|
+
with step("Installing Docker") as s:
|
|
342
|
+
install_docker(s, source_docker)
|
|
343
|
+
|
|
344
|
+
with step("Initializing Docker Swarm") as s:
|
|
345
|
+
if docker("info", "--format", "{{.Swarm.LocalNodeState}}") == "active":
|
|
346
|
+
s.skip("already active")
|
|
347
|
+
docker("swarm", "init")
|
|
348
|
+
|
|
349
|
+
with step("Creating networks") as s:
|
|
350
|
+
existing = set(docker("network", "ls", "--format", "{{.Name}}").splitlines())
|
|
351
|
+
for n in networks:
|
|
352
|
+
if n["Name"] in existing or n["Name"] == "ingress":
|
|
353
|
+
continue
|
|
354
|
+
args = ["network", "create", "--driver", n["Driver"]]
|
|
355
|
+
args += ["--attachable"] if n.get("Attachable") else []
|
|
356
|
+
args += ["--internal"] if n.get("Internal") else []
|
|
357
|
+
for k, v in (n.get("Labels") or {}).items():
|
|
358
|
+
args += ["--label", f"{k}={v}"]
|
|
359
|
+
for k, v in (n.get("Options") or {}).items():
|
|
360
|
+
if k not in SKIP_NETWORK_OPTIONS:
|
|
361
|
+
args += ["-o", f"{k}={v}"]
|
|
362
|
+
docker(*args, n["Name"])
|
|
363
|
+
s.done(", ".join(n["Name"] for n in networks))
|
|
364
|
+
|
|
365
|
+
with step("Creating secrets") as s:
|
|
366
|
+
existing = set(docker("secret", "ls", "--format", "{{.Name}}").splitlines())
|
|
367
|
+
for name, value in sorted(secret_values.items()):
|
|
368
|
+
if name in existing:
|
|
369
|
+
continue
|
|
370
|
+
labels = [a for k, v in secret_labels.get(name, {}).items() for a in ("--label", f"{k}={v}")]
|
|
371
|
+
p = subprocess.run(["docker", "secret", "create", *labels, name, "-"],
|
|
372
|
+
input=value, capture_output=True)
|
|
373
|
+
if p.returncode != 0:
|
|
374
|
+
raise StepError(f"Creating secret {name} failed: {p.stderr.decode()[-500:]}")
|
|
375
|
+
s.done(f"{len(secret_values)} with the source's values")
|
|
376
|
+
|
|
377
|
+
with step("Creating volumes") as s:
|
|
378
|
+
existing = set(docker("volume", "ls", "-q").splitlines())
|
|
379
|
+
for v in volumes:
|
|
380
|
+
if v["Name"] in existing:
|
|
381
|
+
continue
|
|
382
|
+
args = ["volume", "create", "--driver", "local"]
|
|
383
|
+
for k, val in (v.get("Options") or {}).items():
|
|
384
|
+
args += ["-o", f"{k}={val}"]
|
|
385
|
+
for k, val in (v.get("Labels") or {}).items():
|
|
386
|
+
args += ["--label", f"{k}={val}"]
|
|
387
|
+
docker(*args, v["Name"])
|
|
388
|
+
s.done(f"{len(volumes)} volumes")
|
|
389
|
+
target_volumes = {v["Name"]: v for v in json.loads(docker("volume", "inspect", *volume_names))} if volume_names else {}
|
|
390
|
+
copies = [(str(PROD_ROOT), str(PROD_ROOT))] + [
|
|
391
|
+
(volume_data_path(v), volume_data_path(target_volumes[v["Name"]]))
|
|
392
|
+
for v in volumes if volume_data_path(v) in extra_paths
|
|
393
|
+
]
|
|
394
|
+
|
|
395
|
+
with step("Copying images") as s:
|
|
396
|
+
# Services are pinned to the ID each image gets HERE, found through a
|
|
397
|
+
# progress-clone:<source id> tag, which also lets a rerun skip it.
|
|
398
|
+
target_ids: dict[str, str] = {}
|
|
399
|
+
copied, started = 0, time.monotonic()
|
|
400
|
+
for image in unique_images:
|
|
401
|
+
tag = f"{CLONE_TAG}:{image.removeprefix('sha256:')}"
|
|
402
|
+
if subprocess.run(["docker", "image", "inspect", tag],
|
|
403
|
+
capture_output=True).returncode != 0:
|
|
404
|
+
out = run("bash", "-c", "set -o pipefail; " + shlex.join(
|
|
405
|
+
["ssh", *SSH_OPTS, "-o", "Compression=yes", src, "docker", "save", image])
|
|
406
|
+
+ " | docker load", timeout=7200)
|
|
407
|
+
docker("tag", loaded_image_id(out), tag)
|
|
408
|
+
copied += 1
|
|
409
|
+
target_ids[image] = docker("image", "inspect", "--format", "{{.Id}}", tag)
|
|
410
|
+
s.done(f"{copied} copied, {len(unique_images) - copied} present, "
|
|
411
|
+
f"{time.monotonic() - started:.0f}s")
|
|
412
|
+
|
|
413
|
+
for source_path, target_path in copies:
|
|
414
|
+
with step(f"Copying {source_path} (hot)") as s:
|
|
415
|
+
rsync(src, source_path, target_path, hot=True)
|
|
416
|
+
s.done("source still running")
|
|
417
|
+
|
|
418
|
+
# ---- cutover: source stopped from here on ---------------------------
|
|
419
|
+
restart = scale_command(replicas)
|
|
420
|
+
with step("Stopping source services") as s:
|
|
421
|
+
remote(src, *scale_command({name: 0 for name in replicas}))
|
|
422
|
+
console.print(f"\n [dim]Restart the source by hand with: ssh {src} {shlex.join(restart)}[/]")
|
|
423
|
+
deadline = time.monotonic() + 300
|
|
424
|
+
while set(remote(src, "docker", "ps", "--format",
|
|
425
|
+
f'{{{{.Label "{SERVICE_LABEL}"}}}}').split()) & set(replicas):
|
|
426
|
+
if time.monotonic() > deadline:
|
|
427
|
+
raise StepError("Source containers still running after 5 minutes.")
|
|
428
|
+
time.sleep(3)
|
|
429
|
+
s.done("all at 0 replicas")
|
|
430
|
+
|
|
431
|
+
try:
|
|
432
|
+
for source_path, target_path in copies:
|
|
433
|
+
with step(f"Copying {source_path} (final)") as s:
|
|
434
|
+
rsync(src, source_path, target_path, hot=False)
|
|
435
|
+
s.done("consistent copy")
|
|
436
|
+
|
|
437
|
+
with step("Recording release in progress.env") as s:
|
|
438
|
+
env_file = PROD_ROOT / "config" / "progress.env"
|
|
439
|
+
env_file.write_text(set_env_var(env_file.read_text() if env_file.exists() else "",
|
|
440
|
+
"VERSION", release))
|
|
441
|
+
s.done(f"VERSION={release}")
|
|
442
|
+
|
|
443
|
+
label = {"PROGRESS_ENV_NAME": env, "PROGRESS_ENV_COLOR": env_color} if env else {}
|
|
444
|
+
if env:
|
|
445
|
+
with step("Labelling the environment") as s:
|
|
446
|
+
# progress.env: read by `init` deploys and by `copy`; never copied over.
|
|
447
|
+
text = env_file.read_text()
|
|
448
|
+
for key, value in label.items():
|
|
449
|
+
text = set_env_var(text, key, value)
|
|
450
|
+
env_file.write_text(text)
|
|
451
|
+
s.done(env + (f" {env_color}" if env_color else ""))
|
|
452
|
+
|
|
453
|
+
with step("Creating services") as s:
|
|
454
|
+
existing = set(docker("service", "ls", "--format", "{{.Name}}").splitlines())
|
|
455
|
+
secret_ids = dict(line.split() for line in docker(
|
|
456
|
+
"secret", "ls", "--format", "{{.Name}} {{.ID}}").splitlines())
|
|
457
|
+
with docker_api() as api:
|
|
458
|
+
for svc in services:
|
|
459
|
+
name = svc["Spec"]["Name"]
|
|
460
|
+
image = target_ids.get(image_ids.get(name, ""))
|
|
461
|
+
if name in existing:
|
|
462
|
+
# An earlier failed run may have pinned another ID.
|
|
463
|
+
if image and image != docker(
|
|
464
|
+
"service", "inspect", "--format",
|
|
465
|
+
"{{.Spec.TaskTemplate.ContainerSpec.Image}}", name):
|
|
466
|
+
docker("service", "update", "--detach", "--image", image, name)
|
|
467
|
+
continue
|
|
468
|
+
spec = target_spec(svc, image, network_names, secret_ids)
|
|
469
|
+
if env and name.endswith(WORKER_SUFFIX) and "Replicated" in spec["Mode"]:
|
|
470
|
+
spec["Mode"]["Replicated"]["Replicas"] = 0
|
|
471
|
+
if env and name.endswith(API_SUFFIX):
|
|
472
|
+
container = spec["TaskTemplate"]["ContainerSpec"]
|
|
473
|
+
container["Env"] = with_env(container.get("Env"), label)
|
|
474
|
+
r = api.post("/services/create", json=spec)
|
|
475
|
+
if r.status_code != 201:
|
|
476
|
+
raise StepError(f"Creating {spec['Name']} failed: HTTP {r.status_code} {r.text[-500:]}")
|
|
477
|
+
s.done(f"{len(services)} services, images pinned by ID")
|
|
478
|
+
|
|
479
|
+
with step("Waiting for services") as s:
|
|
480
|
+
# Converged twice, 30s apart, so a crash-looping service shows up.
|
|
481
|
+
deadline, stable_since = time.monotonic() + 600, None
|
|
482
|
+
while True:
|
|
483
|
+
rows = [line.split() for line in docker(
|
|
484
|
+
"service", "ls", "--format", "{{.Name}} {{.Replicas}}").splitlines()]
|
|
485
|
+
behind = [f"{name} {r}" for name, r, *_ in rows
|
|
486
|
+
if name in names and r.split("/")[0] != r.split("/")[1]]
|
|
487
|
+
if behind:
|
|
488
|
+
stable_since = None
|
|
489
|
+
elif stable_since is None:
|
|
490
|
+
stable_since = time.monotonic()
|
|
491
|
+
elif time.monotonic() - stable_since > 30:
|
|
492
|
+
break
|
|
493
|
+
if time.monotonic() > deadline:
|
|
494
|
+
raise StepError(f"Services not running after 10 minutes: {', '.join(behind)}",
|
|
495
|
+
hint="docker service ps --no-trunc <service>")
|
|
496
|
+
time.sleep(3)
|
|
497
|
+
host = _load_env_file(env_file).get("HOST")
|
|
498
|
+
if host:
|
|
499
|
+
try:
|
|
500
|
+
r = httpx.get("http://127.0.0.1/api/hello", headers={"Host": host},
|
|
501
|
+
timeout=10, follow_redirects=True, verify=False)
|
|
502
|
+
except httpx.HTTPError as e:
|
|
503
|
+
raise StepError(f"API not reachable: {e}",
|
|
504
|
+
hint="docker service logs progress_api")
|
|
505
|
+
if r.status_code >= 500:
|
|
506
|
+
raise StepError(f"API answers HTTP {r.status_code}.",
|
|
507
|
+
hint="docker service logs progress_api")
|
|
508
|
+
s.done(f"{len(names)} services converged" + (", API up" if host else ""))
|
|
509
|
+
|
|
510
|
+
with step("Writing install markers") as s:
|
|
511
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
512
|
+
(PROD_ROOT / "config" / DB_INIT_MARKER).write_text(now + "\n")
|
|
513
|
+
(PROD_ROOT / "config" / MARKER).write_text(f"{release} {now} cloned-from {src}\n")
|
|
514
|
+
s.done(f"{release}, cloned from {src}")
|
|
515
|
+
except BaseException:
|
|
516
|
+
console.print(f"\n [yellow]Clone failed after the source was stopped: restarting {src}.[/]")
|
|
517
|
+
subprocess.run(["ssh", *SSH_OPTS, src, shlex.join(restart)])
|
|
518
|
+
raise
|
|
519
|
+
|
|
520
|
+
if restart_source:
|
|
521
|
+
with step("Restarting source services") as s:
|
|
522
|
+
remote(src, *restart)
|
|
523
|
+
s.done(f"{len(replicas)} services")
|
|
524
|
+
|
|
525
|
+
console.print(f"\n Cloned [bold]{src}[/] ({release}) onto this host.\n")
|
|
526
|
+
if not restart_source:
|
|
527
|
+
console.print(f" The source is stopped. Restart it with: ssh {src} {shlex.join(restart)}")
|
|
528
|
+
if env:
|
|
529
|
+
workers = sorted(n for n in names if n.endswith(WORKER_SUFFIX))
|
|
530
|
+
console.print(
|
|
531
|
+
f" Client flows are stopped: the copied connections still point at the customer's\n"
|
|
532
|
+
" systems. Change them, then start the worker:\n"
|
|
533
|
+
+ "".join(f" docker service update --force --replicas 1 {w}\n" for w in workers)
|
|
534
|
+
)
|
|
535
|
+
console.print(
|
|
536
|
+
" Next: point DNS at this host; if the source was reached by IP, its address is\n"
|
|
537
|
+
" still in the service config. Run `docker login` before `progress update`.\n"
|
|
538
|
+
)
|