Compare commits
112 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f7f7cc694 | |||
| 71adac469e | |||
| b1a2b21fac | |||
| 7fe574c5dc | |||
| 0b4a1ccb87 | |||
| 5ce450a36a | |||
| 7f8232be5d | |||
| 6f0897afcb | |||
| 678aef8f1f | |||
| f28c75c600 | |||
| 9e946b9a97 | |||
| d4e3baa838 | |||
| a5c19a7d21 | |||
| 3c84918b85 | |||
| ec91a234b8 | |||
| d7c5635641 | |||
| e1f0d251e1 | |||
| 03c4a7f77b | |||
| d4d75a3245 | |||
| 3295d6d8b1 | |||
| 21062d6ad3 | |||
| b6eb3c836b | |||
| fd583a630b | |||
| 5f9d61cf96 | |||
| 3b76b07fb5 | |||
| e428b490e4 | |||
| cb399a8006 | |||
| 05872352f3 | |||
| af36309845 | |||
| cfde376aaa | |||
| b1e2693c99 | |||
| a10485e18e | |||
| df3371d66f | |||
| 03c87fe922 | |||
| 05cf3858b1 | |||
| 1433b6656e | |||
| 61d454110e | |||
| 359e5f5f26 | |||
| 84160125fb | |||
| fadf94e805 | |||
| 736a2bfb3c | |||
| 564a84b775 | |||
| 322dd5dbad | |||
| 3a5ebe5d36 | |||
| 175f3b8584 | |||
| 5fb6677d1d | |||
| 11206d9531 | |||
| d12fa75196 | |||
| ecd013b08d | |||
| ecc8005258 | |||
| 51d88c6d5f | |||
| 0693272611 | |||
| f8c31cfd6e | |||
| fea7970b2a | |||
| c18cb4945e | |||
| e248d53346 | |||
| 73d270a789 | |||
| 5b2984a47c | |||
| 43669271dd | |||
| fab9af2e11 | |||
| 5bef06e75f | |||
| a65f4759d5 | |||
| 19bea78585 | |||
| 774ec67117 | |||
| a7de3ad653 | |||
| 85f8f112c5 | |||
| d433931c54 | |||
| f3f0588d59 | |||
| 3696970331 | |||
| 675ebffc09 | |||
| 7fc0d8ff31 | |||
| d83940c966 | |||
| f11efe9bb0 | |||
| 3db4f1f8f8 | |||
| 79c7d36756 | |||
| 8615395304 | |||
| d6244ebb6e | |||
| 3bd2ebf505 | |||
| e0c7643dba | |||
| ae3f6c89fa | |||
| f296760c9b | |||
| a820c7c2bf | |||
| 415873c767 | |||
| a9b8623bc5 | |||
| 50034dd471 | |||
| 22331edfe6 | |||
| 7dfb4df498 | |||
| 541a8114c7 | |||
| 8a7ed7669d | |||
| 52f378a625 | |||
| 26dd5b8a01 | |||
| 35544fc98a | |||
| f9560aee8c | |||
| 74af823764 | |||
| 23708bfff9 | |||
| 7a08c0b335 | |||
| 35df57fcec | |||
| a495fc2852 | |||
| dadd7249fa | |||
| 4a47d5f965 | |||
| 2cfa573204 | |||
| bcff4d495d | |||
| 285575bfce | |||
| e7617dd8ea | |||
| cd89c1192a | |||
| ad9ab50ff2 | |||
| e8d19e88e1 | |||
| c3760309aa | |||
| 91f3b9942a | |||
| ddbca8e1e2 | |||
| 0da1bb6a8f | |||
| 8ec9c86d10 |
@@ -5,26 +5,38 @@ import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "indicadores_kit", "WebApi", "WebApp")
|
||||
CHECKS = ("Core", "Persistance", "Extraction", "Transformation", "models", "WebApi", "WebApp")
|
||||
IMPACT = {
|
||||
"Core": {"Core", "Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
|
||||
"Persistance": {"Persistance", "Transformation", "models", "indicadores_kit", "WebApi"},
|
||||
"Core": {"Core", "Persistance", "Transformation", "models", "WebApi"},
|
||||
"Persistance": {"Persistance", "Transformation", "models", "WebApi"},
|
||||
"Extraction": {"Extraction", "models", "WebApi"},
|
||||
"Transformation": {"Transformation", "Persistance", "models", "WebApi"},
|
||||
"models": {"models", "WebApi"},
|
||||
"indicadores_kit": {"indicadores_kit", "WebApi"},
|
||||
"WebApi": {"WebApi"},
|
||||
"WebApp": {"WebApp"},
|
||||
}
|
||||
DEPLOY_FILES = {".gitea/deploy/dev.py", ".gitea/deploy/host.py", ".gitea/deploy/test_dev.py",
|
||||
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/deploy-dev-diagnostic.yml"}
|
||||
# Gitlinks whose removal is a recognized structural change, with the checks covering the code that took over
|
||||
# their jobs. Adding, replacing or re-adding them still requires a manual mapping.
|
||||
RETIRED_GITLINKS = {
|
||||
"ISSSTELEON/indicadores_kit": {"Transformation", "models", "WebApi"},
|
||||
}
|
||||
# Gitlinks whose first appearance is a recognized structural change, with the checks covering the code that uses
|
||||
# them. Removing or replacing them still requires a manual mapping; later moves are compared like any gitlink.
|
||||
ADDED_GITLINKS = {
|
||||
"ISSSTELEON/models/libs/tea": {"models", "WebApi"},
|
||||
}
|
||||
DEPLOY_FILES = {".gitea/deploy/installer.py", ".gitea/deploy/registry.py", ".gitea/deploy/test_installer.py",
|
||||
".gitea/workflows/deploy-dev.yml", ".gitea/workflows/reinstall-dev.yml", ".gitea/workflows/load-dev-data.yml",
|
||||
".gitea/deploy/README.md", ".gitea/deploy/INTEGRATION.md",
|
||||
".gitea/workflows/deploy-dev-diagnostic.yml", ".gitea/workflows/deploy-terminal-release.yml"}
|
||||
PROBE_FILES = {".gitea/probe/README.md", ".gitea/probe/docker_probe.py", ".gitea/probe/test_docker_probe.py",
|
||||
".gitea/workflows/docker-persistence-probe.yml"}
|
||||
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
|
||||
CI_SELF_TESTED = {".gitea/ci/select.py", ".gitea/ci/select_checks.py", ".gitea/ci/test_select.py", ".gitea/workflows/ci.yml"}
|
||||
|
||||
|
||||
def deploy_file(path):
|
||||
return path in DEPLOY_FILES or (path.startswith('.gitea/deploy/') and path.endswith('.py'))
|
||||
return path in DEPLOY_FILES or (path.startswith(('.gitea/deploy/', '.gitea/deploy-terminal/'))
|
||||
and path.endswith('.py'))
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
@@ -46,6 +58,17 @@ def documentation(path):
|
||||
return path.lower().endswith((".md", ".rst"))
|
||||
|
||||
|
||||
def retired_removal(full, path, left, right, after):
|
||||
"""Whether a retired gitlink is removed and nothing takes its place in the candidate tree."""
|
||||
return (full in RETIRED_GITLINKS and left is not None and left[0] == "160000" and right is None
|
||||
and not any(other.startswith(path + "/") for other in after))
|
||||
|
||||
|
||||
def added(full, left, right):
|
||||
"""Whether a known gitlink appears where nothing was before."""
|
||||
return full in ADDED_GITLINKS and left is None and right is not None and right[0] == "160000"
|
||||
|
||||
|
||||
def compare(repo, old, new, prefix, changed):
|
||||
before, after = entries(repo, old), entries(repo, new)
|
||||
for path in sorted(before.keys() | after.keys()):
|
||||
@@ -55,6 +78,14 @@ def compare(repo, old, new, prefix, changed):
|
||||
full = f"{prefix}/{path}" if prefix else path
|
||||
if (left and left[0] == "160000") or (right and right[0] == "160000"):
|
||||
print(f"Changed submodule: {full}: {left} -> {right}")
|
||||
if retired_removal(full, path, left, right, after):
|
||||
print(f"Retired submodule removed: {full}")
|
||||
changed.add(full)
|
||||
continue
|
||||
if added(full, left, right):
|
||||
print(f"Known submodule added: {full}")
|
||||
changed.add(full)
|
||||
continue
|
||||
if not left or not right or left[0] != "160000" or right[0] != "160000":
|
||||
raise RuntimeError(f"Submodule added, removed or replaced: {full}; manual CI mapping required")
|
||||
child = repo / path
|
||||
@@ -75,7 +106,11 @@ def select(changed):
|
||||
selected = set()
|
||||
for path in changed:
|
||||
parts = path.split("/")
|
||||
if parts[0] != "ISSSTELEON":
|
||||
if path in RETIRED_GITLINKS:
|
||||
selected.update(RETIRED_GITLINKS[path])
|
||||
elif path in ADDED_GITLINKS:
|
||||
selected.update(ADDED_GITLINKS[path])
|
||||
elif parts[0] != "ISSSTELEON":
|
||||
if deploy_file(path) or path in PROBE_FILES:
|
||||
continue
|
||||
if path in CI_SELF_TESTED:
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -9,7 +10,7 @@ import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
spec = importlib.util.spec_from_file_location("ci_select", Path(__file__).with_name("select.py"))
|
||||
spec = importlib.util.spec_from_file_location("ci_select", Path(__file__).with_name("select_checks.py"))
|
||||
selector = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(selector)
|
||||
|
||||
@@ -27,13 +28,15 @@ class SelectionTests(unittest.TestCase):
|
||||
"""Deployment Python modules select installer checks without application suites."""
|
||||
self.assertEqual(selector.select(selector.DEPLOY_FILES), set())
|
||||
self.assertTrue(selector.deploy_file('.gitea/deploy/new.py'))
|
||||
self.assertTrue(selector.deploy_file('.gitea/deploy-terminal/install.py'))
|
||||
self.assertEqual(selector.select({".gitea/deploy/new.py"}), set())
|
||||
self.assertEqual(selector.select({".gitea/deploy-terminal/install.py"}), set())
|
||||
self.assertEqual(selector.select({".gitea/deploy/unknown.txt"}), set(selector.CHECKS))
|
||||
self.assertEqual(selector.select(selector.DEPLOY_FILES | {"ISSSTELEON/WebApp/a"}), {"WebApp"})
|
||||
|
||||
def test_host_script_selects_deploy_checks(self):
|
||||
"""A host-only change selects installer tests without selecting application suites."""
|
||||
changed = {'.gitea/deploy/host.py'}
|
||||
changed = {'.gitea/deploy/registry.py'}
|
||||
self.assertTrue(changed & selector.DEPLOY_FILES)
|
||||
self.assertEqual(selector.select(changed), set())
|
||||
|
||||
@@ -61,9 +64,10 @@ class SelectionTests(unittest.TestCase):
|
||||
|
||||
def test_report_rejects_failed_check(self):
|
||||
"""The workflow's actual reporting script returns failure for a failed selected check."""
|
||||
git = shutil.which("git")
|
||||
bash = shutil.which("bash")
|
||||
if not bash and os.name == "nt":
|
||||
bash = r"C:\Program Files\Git\bin\bash.exe"
|
||||
if os.name == "nt" and git:
|
||||
bash = Path(git).parents[1] / "bin" / "bash.exe"
|
||||
if not bash or not Path(bash).exists():
|
||||
self.fail("bash is required to test the workflow report")
|
||||
workflow = Path(__file__).parents[1] / "workflows" / "ci.yml"
|
||||
@@ -73,7 +77,7 @@ class SelectionTests(unittest.TestCase):
|
||||
script = "\n".join(line[10:] for line in block.splitlines())
|
||||
for outcome, expected in (("failure", 1), ("skipped", 1), ("success", 0)):
|
||||
env = {**os.environ, "CORE": outcome, "CORE_REQUIRED": "true"}
|
||||
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "INDICADORES", "WEBAPI", "WEBAPP"):
|
||||
for name in ("PERSISTANCE", "EXTRACTION", "TRANSFORMATION", "MODELS", "WEBAPI", "WEBAPP"):
|
||||
env[name] = "skipped"
|
||||
env[name + "_REQUIRED"] = "false"
|
||||
result = subprocess.run([bash, "-c", script], env=env, capture_output=True, text=True)
|
||||
@@ -190,6 +194,140 @@ class SelectionTests(unittest.TestCase):
|
||||
self.assertEqual({name for name in selector.CHECKS if values[name] == "true"},
|
||||
{"WebApp", "WebApi"})
|
||||
|
||||
def kit_history(self, root, final):
|
||||
"""Build an outer repo whose ISSSTELEON child holds the kit gitlink, then apply `final` to the child.
|
||||
|
||||
Returns the outer commits before and after; `final(run, child)` stages the candidate change."""
|
||||
child = root / "ISSSTELEON"
|
||||
child.mkdir()
|
||||
|
||||
def run(repo, *args):
|
||||
return subprocess.check_output(["git", "-C", str(repo), *args], stderr=subprocess.DEVNULL)
|
||||
|
||||
def commit(repo, name):
|
||||
run(repo, "commit", "-qm", name)
|
||||
return run(repo, "rev-parse", "HEAD").decode().strip()
|
||||
|
||||
for repo in (root, child):
|
||||
run(repo, "init", "-q")
|
||||
run(repo, "config", "user.email", "ci@example.invalid")
|
||||
run(repo, "config", "user.name", "CI")
|
||||
(child / "README.md").write_text("tree", encoding="utf-8")
|
||||
run(child, "add", "README.md")
|
||||
run(child, "update-index", "--add", "--cacheinfo", "160000," + "1" * 40 + ",indicadores_kit")
|
||||
run(child, "update-index", "--add", "--cacheinfo", "160000," + "2" * 40 + ",other_kit")
|
||||
commit(child, "base")
|
||||
run(root, "add", "ISSSTELEON")
|
||||
old = commit(root, "base")
|
||||
final(run, child)
|
||||
commit(child, "candidate")
|
||||
run(root, "add", "ISSSTELEON")
|
||||
return old, commit(root, "candidate")
|
||||
|
||||
def test_retired_kit_removal_is_recognized(self):
|
||||
"""Removing the retired kit gitlink selects its successors' checks.
|
||||
|
||||
Fails if the selector stops recognizing the known removal (CI rejects every PR that carries it)
|
||||
or maps it to the kit's own suite, which no longer exists in the candidate tree."""
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
old, new = self.kit_history(Path(temp), lambda run, child: run(
|
||||
child, "update-index", "--force-remove", "indicadores_kit"))
|
||||
changes = set()
|
||||
selector.compare(Path(temp), old, new, "", changes)
|
||||
self.assertEqual(changes, {"ISSSTELEON/indicadores_kit"})
|
||||
self.assertEqual(selector.select(changes), {"Transformation", "models", "WebApi"})
|
||||
self.assertNotIn("indicadores_kit", selector.CHECKS)
|
||||
|
||||
def test_other_structural_gitlink_changes_still_fail(self):
|
||||
"""Replacing the kit with files, re-pointing a different gitlink's removal or adding one stays fatal.
|
||||
|
||||
Fails if the retired-gitlink exception is widened to arbitrary structural changes."""
|
||||
def replace(run, child):
|
||||
run(child, "update-index", "--force-remove", "indicadores_kit")
|
||||
(child / "indicadores_kit").mkdir()
|
||||
(child / "indicadores_kit" / "code.py").write_text("pass", encoding="utf-8")
|
||||
run(child, "add", "indicadores_kit/code.py")
|
||||
|
||||
def remove_other(run, child):
|
||||
run(child, "update-index", "--force-remove", "other_kit")
|
||||
|
||||
def add(run, child):
|
||||
run(child, "update-index", "--add", "--cacheinfo", "160000," + "3" * 40 + ",new_kit")
|
||||
|
||||
for name, final in (("replace", replace), ("remove-other", remove_other), ("add", add)):
|
||||
with self.subTest(change=name), tempfile.TemporaryDirectory() as temp:
|
||||
old, new = self.kit_history(Path(temp), final)
|
||||
with self.assertRaisesRegex(RuntimeError, "manual CI mapping required"):
|
||||
selector.compare(Path(temp), old, new, "", set())
|
||||
|
||||
def test_adding_the_eeg_library_is_recognized(self):
|
||||
"""Adding the EEG library's gitlink below models selects the checks of the code that installs it.
|
||||
|
||||
Fails if the selector stops recognizing that addition (CI rejects the PR that brings the library in) or maps
|
||||
it to anything but models and the WebApi, the two environments that install it."""
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
old, new = self.kit_history(Path(temp), lambda run, child: run(
|
||||
child, "update-index", "--add", "--cacheinfo", "160000," + "4" * 40 + ",models/libs/tea"))
|
||||
changes = set()
|
||||
selector.compare(Path(temp), old, new, "", changes)
|
||||
self.assertEqual(changes, {"ISSSTELEON/models/libs/tea"})
|
||||
self.assertEqual(selector.select(changes), {"models", "WebApi"})
|
||||
|
||||
def test_removing_the_eeg_library_still_fails(self):
|
||||
"""Removing a known added gitlink is not covered by its entry.
|
||||
|
||||
Fails if the added-gitlink exception is widened to removals."""
|
||||
def add(run, child):
|
||||
run(child, "update-index", "--add", "--cacheinfo", "160000," + "4" * 40 + ",models/libs/tea")
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp)
|
||||
old, new = self.kit_history(root, add)
|
||||
subprocess.check_output(["git", "-C", str(root / "ISSSTELEON"), "update-index", "--force-remove",
|
||||
"models/libs/tea"])
|
||||
subprocess.check_output(["git", "-C", str(root / "ISSSTELEON"), "commit", "-qm", "drop"])
|
||||
subprocess.check_output(["git", "-C", str(root), "add", "ISSSTELEON"])
|
||||
subprocess.check_output(["git", "-C", str(root), "commit", "-qm", "drop"])
|
||||
dropped = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"]).decode().strip()
|
||||
with self.assertRaisesRegex(RuntimeError, "manual CI mapping required"):
|
||||
selector.compare(root, new, dropped, "", set())
|
||||
|
||||
def test_files_under_retired_path_select_everything(self):
|
||||
"""A regular path under the retired kit is unmapped, so it selects every check.
|
||||
|
||||
Fails if the retired entry starts acting as a component mapping for new files."""
|
||||
self.assertEqual(selector.select({"ISSSTELEON/indicadores_kit/code.py"}), set(selector.CHECKS))
|
||||
|
||||
def test_workflow_runs_exactly_the_selectable_checks(self):
|
||||
"""Every selectable check has a workflow step and the workflow reads no retired output.
|
||||
|
||||
Fails if a check is added to `CHECKS` without a step, or a step still waits on a check the selector no
|
||||
longer emits (a retired component would then be silently skipped or fail on a missing folder)."""
|
||||
workflow = (Path(__file__).parents[1] / "workflows" / "ci.yml").read_text(encoding="utf-8")
|
||||
outputs = set(re.findall(r"steps\.select\.outputs\.([A-Za-z_]+)", workflow))
|
||||
self.assertEqual(outputs - set(selector.CHECKS), {"probe", "deploy", "python"})
|
||||
for check in selector.CHECKS:
|
||||
self.assertGreaterEqual(workflow.count(f"if: steps.select.outputs.{check} == 'true'\n"), 1, check)
|
||||
for impacted in [*selector.IMPACT.values(), *selector.RETIRED_GITLINKS.values(),
|
||||
*selector.ADDED_GITLINKS.values()]:
|
||||
self.assertLessEqual(impacted, set(selector.CHECKS))
|
||||
|
||||
def test_webapi_step_serves_the_compiled_dbt_manifest(self):
|
||||
"""The WebApi step compiles dbt's manifest and exports it before pytest runs.
|
||||
|
||||
The measures and the indicator cycle are defined in the manifest's compiled SQL, which `dbt parse` does not
|
||||
produce. Fails if the step stops compiling it, compiles it without exporting `DBT_MANIFEST`, or exports it
|
||||
after pytest has started (the suite would then skip its manifest tests or raise on the missing variable)."""
|
||||
workflow = (Path(__file__).parents[1] / "workflows" / "ci.yml").read_text(encoding="utf-8")
|
||||
step = workflow.split(" - name: WebApi pytest\n", 1)[1].split(" - name:", 1)[0]
|
||||
compile_at = step.index("dbt compile")
|
||||
export_at = step.index('export DBT_MANIFEST="$RUNNER_TEMP/dbt-manifest/manifest.json"')
|
||||
self.assertIn("--no-introspect", step)
|
||||
self.assertIn('--target-path "$RUNNER_TEMP/dbt-manifest"', step)
|
||||
self.assertIn('test -s "$RUNNER_TEMP/dbt-manifest/manifest.json"', step)
|
||||
self.assertLess(compile_at, export_at)
|
||||
self.assertLess(export_at, step.index("pytest -q"))
|
||||
|
||||
def test_conflict_and_outdated_head(self):
|
||||
"""Divergent conflicting commits fail the merge and fail the ancestry requirement."""
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# Native release deployment
|
||||
|
||||
This manual-dispatch workflow prepares and deploys a published Release to
|
||||
`10.0.10.41` using native Ubuntu processes. A successful run means it has
|
||||
resolved the tag, transferred the pinned application source, prepared the
|
||||
instance, started three supervised user services, verified local health and
|
||||
confirmed that the runner can reach WebApp and the proxied API at
|
||||
`http://10.0.10.41:<puerto>/`. It then checks the service states once more.
|
||||
The intermediate bundle remains in the job workspace; no manual download,
|
||||
transfer, installation or activation is required per deployment.
|
||||
|
||||
The installer revision comes from the selected workflow branch, normally
|
||||
`dev`; the application revision comes exclusively from the tag. It is not
|
||||
restricted to `dev`, `staging` or `main`. The first intended test is a
|
||||
published Release for the operator-selected `staging` commit on port `18090`.
|
||||
No Release, tag, deployment or infrastructure change is created by this work.
|
||||
|
||||
## Architecture and prerequisites
|
||||
|
||||
An isolated non-root deployment account connects to the host over SSH with a
|
||||
dedicated key and a verified host key. It owns an isolated installation parent
|
||||
and runs its own `systemd --user` manager, with lingering enabled once by the
|
||||
operator. The account must not have Docker, sudo, wheel or root group
|
||||
membership; it must have no other administrative grants or capabilities. It
|
||||
can execute commands and write within its own permissions, so the private key
|
||||
is sensitive even though it does not confer root access. SSH key `restrict`
|
||||
options can disable forwarding and interactive PTY access; they do not prevent
|
||||
the account from executing arbitrary commands as itself.
|
||||
|
||||
The workflow uses no `sudo` and never changes the existing runner or Docker
|
||||
configuration. The operator confirmed that `ubuntu-latest`, `ubuntu-24.04` and
|
||||
`ubuntu-22.04` jobs use `docker://docker.gitea.com/runner-images` as configured
|
||||
in `/etc/act_runner/config.yaml`. The application itself runs as native user
|
||||
services on the host. The job must be able to reach Gitea, SSH on labserver, and the
|
||||
application's public port; these are required for the final checks. The host
|
||||
must provide Python >=3.12, uv, compatible Node/npm, nginx with
|
||||
`/etc/nginx/mime.types`, Tesseract and `spa`/`eng` language data. The inspected
|
||||
application container uses Node 22. The account must be able to reach any
|
||||
required package registries, and uv, npm, nginx and Tesseract must be on its
|
||||
noninteractive SSH PATH. `systemd --user`, its D-Bus runtime and the
|
||||
sandbox options in the units must work on the target Ubuntu configuration.
|
||||
User services explicitly use `PrivateUsers=true` with filesystem sandboxing;
|
||||
this requires unprivileged user namespaces to be available. Depending on the
|
||||
host, sandbox settings may fail or be ineffective; validate their effective
|
||||
behavior before relying on them. Availability and compatibility have not been
|
||||
demonstrated by local tests.
|
||||
|
||||
The operator reports that `admon` has interactive sudo and that the runner is
|
||||
an `act-runner` host process. `admon` is a member of Docker and sudo groups and
|
||||
must not be the deployment/service account. No assumption is made about runner
|
||||
sudo access. Use `admon` for the one-time authorized setup, not as the runtime
|
||||
identity or as an Action credential.
|
||||
|
||||
## One-time operator setup
|
||||
|
||||
Only after authorization for physical changes, an administrator should:
|
||||
|
||||
1. Provision a dedicated non-root account with a real home and a shell capable
|
||||
of the SSH commands and SFTP used here. Verify it has no Docker,
|
||||
administrative, custom sudoers or capability grants. The installer rejects
|
||||
the standard privileged groups but cannot detect every possible grant.
|
||||
2. Create an isolated parent directory outside `/srv/workingnarrative-dev`
|
||||
and all existing installation/data paths; give only that account the needed
|
||||
access. For a new directory an administrator may use, for example,
|
||||
`sudo mkdir /srv/workingnarrative-native`, followed by a reviewed `chown`
|
||||
and `chmod 0750` for the chosen account. Do not overwrite or reassign an
|
||||
existing directory without a separate review.
|
||||
3. Provision an SSH deployment key for that account through the authorized
|
||||
channel. Restrict its `authorized_keys` entry appropriately and verify the
|
||||
server host-key fingerprint independently. Do not store the `admon` password
|
||||
or enable passwordless sudo. Confirm SSH and SFTP work for this account.
|
||||
4. Enable lingering once with `sudo loginctl enable-linger <account>`. Confirm
|
||||
the account's user manager and `/run/user/<uid>/bus` are available. This is
|
||||
needed so services survive the SSH session and start after reboot. Confirm
|
||||
that the required systemd user-service sandbox options work; the deployment
|
||||
fails closed if its manager or services cannot start.
|
||||
5. Configure the following Gitea Actions variables and secrets through the
|
||||
authorized administrative process. No credentials are provisioned here.
|
||||
|
||||
| Kind | Name | Value |
|
||||
|---|---|---|
|
||||
| Variable | `NATIVE_ACCOUNT` | Dedicated deployment/service account |
|
||||
| Variable | `NATIVE_SSH_PORT` | SSH port for the host |
|
||||
| Variable | `NATIVE_HOSTNAME` | Exact hostname returned by the host |
|
||||
| Variable | `NATIVE_PARENT` | Existing dedicated absolute parent directory |
|
||||
| Secret | `NATIVE_SSH_KEY` | Dedicated account's private key, in full |
|
||||
| Secret | `NATIVE_KNOWN_HOSTS` | Independently verified SSH known-hosts entry |
|
||||
|
||||
The job writes the key and known-hosts data to temporary files with a private
|
||||
umask and removes them on normal shell exit. Use a trusted runner and its
|
||||
secret controls; abrupt termination may prevent cleanup. The Gitea job token must have read access to the published Release and all
|
||||
private application submodules. Configure only the required cross-repository
|
||||
read access through the authorized Gitea administration process. The resolver
|
||||
passes the job token to Git as an HTTP header scoped to the institutional
|
||||
repository namespace; it does not embed credentials in repository URLs.
|
||||
|
||||
## Running a deployment
|
||||
|
||||
After review, integration and one-time setup, the operator may publish the
|
||||
Release pointing to the selected application commit. In Gitea, dispatch
|
||||
`deploy-terminal-release` from the reviewed installer branch and supply the
|
||||
exactly three inputs: published `tag`, public `puerto` (default `18090`) and
|
||||
loopback `puerto_api` (default `28090`). Both ports must be integers in
|
||||
`1024..65535`, distinct and available on the host. This is a new-install-only
|
||||
workflow. It rejects an existing instance, unit path or occupied port rather
|
||||
than updating or overwriting it. Choose a different free API port when another
|
||||
native instance already uses the requested value.
|
||||
|
||||
The Action performs these steps:
|
||||
|
||||
1. Validate the institutional event, origin and published Release, fetch the
|
||||
exact tag, peel it to a commit and check that neither tag nor Release changed.
|
||||
2. Check out only recognized institutional application gitlinks at their
|
||||
committed SHAs, independently of branch heads. Archive committed application
|
||||
components and record tag, release ID, tag object, application and installer
|
||||
commits, gitlinks, installer file hashes and bundle digest.
|
||||
3. Connect to the configured host with strict SSH host-key checking. Check the
|
||||
hostname, account, groups, user manager and lingering, create a unique
|
||||
account-owned staging directory, and transfer the bundle and reviewed
|
||||
installer. The requested API port is included in the release record and
|
||||
checked against the value passed to the remote installer. The job does not copy any files into system-wide systemd paths.
|
||||
4. Exclusively create `NATIVE_PARENT/isssteleon-native-<puerto>`, check both
|
||||
ports, install Python and Node dependencies using the release's lockfiles,
|
||||
and compile Angular. Create four new SQLite files and validate the effective
|
||||
Persistance URLs and empty isolated files before running Alembic.
|
||||
5. Generate three units in the instance, link them exclusively into the
|
||||
account's user-unit directory, reload its user manager, and enable/start the
|
||||
API, indicator worker and nginx. There is no privileged operation per run.
|
||||
6. Verify the three units, direct and proxied `/health`, Angular root and SPA
|
||||
fallback on the host. From the runner check the public root and proxied API
|
||||
on `10.0.10.41:<puerto>`, then recheck the host services. Any failure makes
|
||||
the Action fail; a successful external check is recorded on the host.
|
||||
|
||||
Preparation uses the selected release's equivalents of these commands:
|
||||
|
||||
```sh
|
||||
# application/WebApi
|
||||
uv sync --locked --no-dev --extra sql-drivers
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/cacu/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/cama/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/tea/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c ../Persistance/persistance/governance/alembic.ini upgrade head
|
||||
# application/WebApp
|
||||
npm ci
|
||||
npm run build -- --configuration production
|
||||
```
|
||||
|
||||
The service commands use `.venv/bin/gunicorn` on `127.0.0.1:<API port>`,
|
||||
`.venv/bin/python -m <worker>` with the worker module the release contains
|
||||
(`webapi.recomputation`, or `webapi.indicadores_vivos` in older releases; a release
|
||||
with neither is refused), and a dedicated nginx process for the Angular production files and proxy.
|
||||
For `webapi.recomputation`, preparation builds the SQLite dbt manifest using the `sqlite` dependency group in the
|
||||
bundled `Transformation/` project and supplies it to the API and worker through `DBT_MANIFEST`.
|
||||
There is no isolated notebook runner:
|
||||
the services set `NOTEBOOK_EXECUTOR=contenedor` without a jobs folder, so an
|
||||
uploaded notebook fails instead of running inside the API process. The nginx process listens on the
|
||||
requested public port. The four domain databases, MLflow database and
|
||||
artifacts, reports, indicator queue and nginx temporary files are under the new
|
||||
instance's `data/`. No Docker volume, database, compose project or existing
|
||||
Docker installer is used or modified.
|
||||
|
||||
`installation.json` records identity, paths, service names, both requested ports, phases,
|
||||
status and health checks. User services use `default.target`, restart on
|
||||
failure and write to the user journal. For example, under the service account:
|
||||
|
||||
```sh
|
||||
systemctl --user status isssteleon-native-18090-{api,worker,web}.service
|
||||
journalctl --user -u isssteleon-native-18090-api.service -u isssteleon-native-18090-worker.service -u isssteleon-native-18090-web.service
|
||||
```
|
||||
|
||||
The helper explicitly sets `XDG_RUNTIME_DIR` and `DBUS_SESSION_BUS_ADDRESS`
|
||||
for noninteractive SSH. An operator's interactive session may also need these
|
||||
set for `systemctl --user` and `journalctl --user`. The host-local checks do
|
||||
not prove that the indicator worker completed a calculation or exercise
|
||||
clinical workflows; perform an authorized functional smoke test separately.
|
||||
|
||||
## Failure handling and validation
|
||||
|
||||
A failed build, migration, activation or health check makes the job fail.
|
||||
Instance files and databases are retained for inspection; no retry automatically
|
||||
reuses or migrates them. Failed activation attempts to disable/stop only the
|
||||
newly linked user units and records failure; any links left by systemd remain
|
||||
for inspection. If that stop
|
||||
itself fails, the operator must inspect the user manager; no global cleanup is
|
||||
performed. A public HTTP failure is reported back into the instance record when
|
||||
SSH remains available. If SSH fails while reporting, the job log is authoritative
|
||||
about that failure. Recovery, deletion or updates require a separate review.
|
||||
|
||||
Automated local tests use temporary Git repositories and bundles, mock SSH and
|
||||
systemd subprocesses, and exercise a real local port conflict. The observed
|
||||
staging application trees were exported and extracted from cached objects.
|
||||
These tests do not prove that user systemd, nginx, package downloads, real
|
||||
migrations, SSH, or the Gitea Actions context work on Ubuntu. Validate the full
|
||||
path in a disposable Ubuntu environment and complete the authorized one-time
|
||||
setup before requesting a physical test. The operator must check the actual
|
||||
public and loopback port availability and dedicated paths before that test.
|
||||
|
||||
The inspected local `dev` base was `e8d19e88e1022953f5714cf891129adfe992d3f7`;
|
||||
the older `91f3b9942a9df390da3435267c7131fe7464240c` was a historical local
|
||||
reference. The observed `staging` commit was
|
||||
`234c45c10ad901e75907d56b5443ecbc619af342` with application gitlink
|
||||
`f6d00f51f30cc5482c1711082f8656f2b3d9cd30`. A later selected commit must be
|
||||
reviewed against its own commands, migrations and gitlinks before publication.
|
||||
|
||||
A future `release: { types: [published] }` trigger is intentionally absent.
|
||||
After the manual workflow is validated, design and test event-specific tag
|
||||
handling and a trusted installer revision before enabling automatic publication
|
||||
triggers.
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Activate only this prepared instance through the account's user systemd manager."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import install
|
||||
|
||||
|
||||
def manager_environment(account):
|
||||
import pwd
|
||||
install.validate_service_account(account)
|
||||
entry = pwd.getpwuid(os.geteuid())
|
||||
home = Path(entry.pw_dir)
|
||||
if (not home.is_absolute() or home.resolve() != home or not home.is_dir()
|
||||
or home.stat().st_uid != os.geteuid() or home.stat().st_mode & 0o022):
|
||||
raise ValueError('service account home must be owned by the account and not group/world writable')
|
||||
runtime = Path('/run/user') / str(os.geteuid())
|
||||
bus = runtime / 'bus'
|
||||
if (runtime.is_symlink() or not runtime.is_dir() or runtime.stat().st_uid != os.geteuid()
|
||||
or bus.is_symlink() or not bus.exists() or not stat.S_ISSOCK(bus.stat().st_mode)):
|
||||
raise ValueError('user systemd runtime or D-Bus socket is unavailable')
|
||||
return {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'), 'HOME': str(home),
|
||||
'XDG_RUNTIME_DIR': str(runtime), 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=' + str(runtime / 'bus')}
|
||||
|
||||
|
||||
def command(args, env, *, check=True):
|
||||
return subprocess.run(args, env=env, capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def units_directory(home):
|
||||
"""Create account-owned systemd configuration without traversing symlinks."""
|
||||
current = Path(home)
|
||||
for part in ('.config', 'systemd', 'user'):
|
||||
current = current / part
|
||||
try:
|
||||
current.mkdir(mode=0o700)
|
||||
except FileExistsError:
|
||||
pass
|
||||
if current.is_symlink() or not current.is_dir() or current.stat().st_uid != os.geteuid() or current.stat().st_mode & 0o022:
|
||||
raise ValueError('unsafe user systemd unit directory: ' + str(current))
|
||||
return current
|
||||
|
||||
|
||||
def activate(instance, record, env):
|
||||
"""Link and start only fresh instance units; retain data and failure evidence."""
|
||||
base = Path(instance)
|
||||
install.validate_record(record)
|
||||
if (record.get('status') != 'prepared' or Path(record.get('base', '')) != base
|
||||
or base.is_symlink() or base.resolve() != base):
|
||||
raise ValueError('instance is not a freshly prepared installation')
|
||||
port = record['public_port']
|
||||
names = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
|
||||
if record.get('services') != names or base.name != f'isssteleon-native-{port}':
|
||||
raise ValueError('invalid service identity')
|
||||
linger = command(['loginctl', 'show-user', record['account'], '--property=Linger', '--value'], env)
|
||||
if linger.stdout.strip().lower() != 'yes':
|
||||
raise ValueError('user lingering is not enabled; one-time operator setup is required')
|
||||
command(['systemctl', '--user', 'show-environment'], env)
|
||||
unit_dir = units_directory(env['HOME'])
|
||||
for name in names:
|
||||
source = base / 'units' / name
|
||||
dest = unit_dir / name
|
||||
if source.is_symlink() or not source.is_file() or dest.exists() or dest.is_symlink():
|
||||
raise ValueError('missing source or existing unit path: ' + name)
|
||||
state = command(['systemctl', '--user', 'show', name, '--property=LoadState', '--value'], env)
|
||||
if state.stdout.strip() != 'not-found':
|
||||
raise ValueError('systemd unit already exists: ' + name)
|
||||
record.update(status='activating', phase='linking_user_units', unit_directory=str(unit_dir))
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
linked = []
|
||||
try:
|
||||
for name in names:
|
||||
os.symlink(base / 'units' / name, unit_dir / name)
|
||||
linked.append(name)
|
||||
command(['systemctl', '--user', 'daemon-reload'], env)
|
||||
record.update(phase='starting_user_units')
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
for name in names:
|
||||
command(['systemctl', '--user', 'enable', '--now', name], env)
|
||||
record.update(status='started', phase='awaiting_health', started_at=int(time.time()))
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
return record
|
||||
except BaseException as exc:
|
||||
if linked:
|
||||
try:
|
||||
command(['systemctl', '--user', 'disable', '--now', *linked], env, check=False)
|
||||
except OSError:
|
||||
pass
|
||||
record.update(status='activation_failed', phase='activation_failed', error=type(exc).__name__)
|
||||
try:
|
||||
install.atomic_record(base / 'installation.json', record)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('instance', type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
base = args.instance
|
||||
if not base.is_absolute() or base.is_symlink() or base.resolve() != base:
|
||||
raise ValueError('instance path must be absolute and not symlinked')
|
||||
path = base / 'installation.json'
|
||||
if path.is_symlink():
|
||||
raise ValueError('symlinked installation record')
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
install.validate_record(record)
|
||||
install.check_installer_files(Path(__file__).resolve().parent, record)
|
||||
result = activate(base, record, manager_environment(record['account']))
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
|
||||
print('Activation failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export exact committed application trees as a guarded release bundle."""
|
||||
import hashlib
|
||||
import gzip
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
import source
|
||||
|
||||
APPLICATION_COMPONENTS = {'Core', 'Persistance', 'Extraction', 'Transformation', 'WebApi', 'WebApp', 'models',
|
||||
'indicadores_kit'}
|
||||
|
||||
|
||||
def safe_member(member):
|
||||
path = PurePosixPath(member.name)
|
||||
return (not path.is_absolute() and member.name not in ('', '.')
|
||||
and all(part not in ('', '.', '..') for part in path.parts)
|
||||
and '\\' not in member.name and (member.isdir() or member.isfile()))
|
||||
|
||||
|
||||
def export(checkout, manifest, output):
|
||||
"""Export each verified commit, excluding Git metadata and untracked files."""
|
||||
checkout, output = Path(checkout), Path(output)
|
||||
seen = set()
|
||||
with output.open('xb') as raw, gzip.GzipFile(fileobj=raw, mode='wb', filename='', mtime=0) as zipped, tarfile.open(fileobj=zipped, mode='w:', format=tarfile.PAX_FORMAT) as bundle:
|
||||
for full, sha in sorted(manifest.items(), key=lambda item: (item[0].count('/'), item[0])):
|
||||
repo = checkout / full
|
||||
if source.git(repo, 'rev-parse', 'HEAD') != sha:
|
||||
raise ValueError('source checkout changed: ' + full)
|
||||
prefix = PurePosixPath('application') / PurePosixPath(full).relative_to('ISSSTELEON')
|
||||
with tempfile.TemporaryFile() as stream:
|
||||
subprocess.run(['git', '-C', str(repo), 'archive', '--format=tar', sha], stdout=stream, check=True)
|
||||
stream.seek(0)
|
||||
with tarfile.open(fileobj=stream, mode='r:') as archive:
|
||||
for member in archive:
|
||||
if full == 'ISSSTELEON' and PurePosixPath(member.name).parts[0] not in APPLICATION_COMPONENTS:
|
||||
continue
|
||||
if not safe_member(member):
|
||||
raise ValueError('unsafe Git archive member: ' + member.name)
|
||||
name = str(prefix / member.name)
|
||||
if name in seen:
|
||||
if member.isdir():
|
||||
continue
|
||||
raise ValueError('overlapping archive member: ' + name)
|
||||
seen.add(name)
|
||||
member.name = name
|
||||
member.uid = member.gid = 0
|
||||
member.uname = member.gname = ''
|
||||
member.mode = (0o755 if member.isdir() or member.mode & 0o111 else 0o644)
|
||||
bundle.addfile(member, archive.extractfile(member) if member.isfile() else None)
|
||||
digest = hashlib.sha256()
|
||||
with output.open('rb') as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def write_record(path, record):
|
||||
with Path(path).open('x', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, indent=2, sort_keys=True)
|
||||
stream.write('\n')
|
||||
@@ -0,0 +1,389 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare a new isolated native instance; never activate privileged services."""
|
||||
import argparse
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
import bundle
|
||||
|
||||
NAME = re.compile(r'^[a-z_][a-z0-9_-]{0,30}$')
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
DIGEST = re.compile(r'^[0-9a-f]{64}$')
|
||||
SAFE_PATH = re.compile(r'^/[A-Za-z0-9_./-]+$')
|
||||
DOCKER_ROOT = Path('/srv/workingnarrative-dev')
|
||||
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
|
||||
# Indicator worker modules a bundle may hold, newest first.
|
||||
WORKER_MODULES = ('webapi.recomputation', 'webapi.indicadores_vivos')
|
||||
INSTALLER_FILES = {'install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'}
|
||||
REQUIRED_LINKS = {'ISSSTELEON', 'ISSSTELEON/WebApi', 'ISSSTELEON/WebApp', 'ISSSTELEON/models'}
|
||||
LEGACY_LINKS = REQUIRED_LINKS | {'ISSSTELEON/indicadores_kit'}
|
||||
|
||||
|
||||
def validate_record(record):
|
||||
if not isinstance(record, dict):
|
||||
raise ValueError('invalid release record')
|
||||
if (not isinstance(record.get('tag'), str) or not record['tag'] or len(record['tag']) > 255
|
||||
or any(ord(c) < 32 for c in record['tag']) or type(record.get('release_id')) is not int
|
||||
or record['release_id'] <= 0 or type(record.get('public_port')) is not int
|
||||
or not 1024 <= record['public_port'] <= 65535
|
||||
or type(record.get('api_port')) is not int or not 1024 <= record['api_port'] <= 65535
|
||||
or record['api_port'] == record['public_port']):
|
||||
raise ValueError('invalid release identity or port')
|
||||
if any(not isinstance(record.get(k), str) or not SHA.fullmatch(record[k])
|
||||
for k in ('application_sha', 'installer_sha', 'tag_object')):
|
||||
raise ValueError('invalid commit identity')
|
||||
if not isinstance(record.get('bundle_sha256'), str) or not DIGEST.fullmatch(record['bundle_sha256']):
|
||||
raise ValueError('invalid bundle digest')
|
||||
files = record.get('installer_files')
|
||||
if (not isinstance(files, dict) or set(files) != INSTALLER_FILES
|
||||
or any(not isinstance(value, str) or not DIGEST.fullmatch(value) for value in files.values())):
|
||||
raise ValueError('invalid installer file manifest')
|
||||
links = record.get('gitlinks')
|
||||
if (not isinstance(links, dict) or set(links) not in (REQUIRED_LINKS, LEGACY_LINKS)
|
||||
or any(not isinstance(value, str) or not SHA.fullmatch(value) for value in links.values())):
|
||||
raise ValueError('unsupported or incomplete gitlinks')
|
||||
if not isinstance(record.get('installer_ref'), str) or not record['installer_ref'].startswith('refs/heads/'):
|
||||
raise ValueError('invalid installer reference')
|
||||
|
||||
|
||||
def digest(path):
|
||||
value = hashlib.sha256()
|
||||
with open(path, 'rb') as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
value.update(block)
|
||||
return value.hexdigest()
|
||||
|
||||
|
||||
|
||||
def check_installer_files(directory, record):
|
||||
for name, expected in record['installer_files'].items():
|
||||
file = Path(directory) / name
|
||||
if file.is_symlink() or not file.is_file() or digest(file) != expected:
|
||||
raise ValueError('installer file differs from release record: ' + name)
|
||||
|
||||
|
||||
|
||||
def validate_service_account(account):
|
||||
"""Reject root and accounts with common administrative or Docker groups."""
|
||||
import grp
|
||||
import pwd
|
||||
if not NAME.fullmatch(account) or os.geteuid() == 0:
|
||||
raise ValueError('a non-root service account is required')
|
||||
entry = pwd.getpwuid(os.geteuid())
|
||||
if entry.pw_name != account:
|
||||
raise ValueError('preparation must run as the selected service account')
|
||||
groups = set(os.getgroups()) | set(os.getgrouplist(account, entry.pw_gid))
|
||||
groups.update((entry.pw_gid, os.getegid()))
|
||||
privileged = {0}
|
||||
for name in ('docker', 'sudo', 'wheel'):
|
||||
try:
|
||||
privileged.add(grp.getgrnam(name).gr_gid)
|
||||
except KeyError:
|
||||
pass
|
||||
if groups & privileged:
|
||||
raise ValueError('service account belongs to a privileged administrative or Docker group')
|
||||
|
||||
|
||||
|
||||
def require_private_parent(parent):
|
||||
"""Reject installation parents that other accounts can replace or modify."""
|
||||
metadata = parent.stat()
|
||||
if metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022:
|
||||
raise ValueError('installation parent must be owned by the service account and not group/world writable')
|
||||
|
||||
|
||||
def validate_parent(parent):
|
||||
parent = Path(parent)
|
||||
if not parent.is_absolute() or not SAFE_PATH.fullmatch(str(parent)) or not parent.is_dir():
|
||||
raise ValueError('parent must be an existing absolute path without whitespace or shell metacharacters')
|
||||
if parent.resolve() != parent:
|
||||
raise ValueError('parent and its ancestors must not be symlinks or contain dot components')
|
||||
destination = parent / 'instance'
|
||||
if destination == DOCKER_ROOT or DOCKER_ROOT in destination.parents or destination in DOCKER_ROOT.parents:
|
||||
raise ValueError('native installation must be separate from the Docker deployment')
|
||||
require_private_parent(parent)
|
||||
return parent
|
||||
|
||||
|
||||
def check_port(port, public):
|
||||
if type(port) is not int or not 1024 <= port <= 65535:
|
||||
raise ValueError('ports must be between 1024 and 65535')
|
||||
families = [(socket.AF_INET, '0.0.0.0' if public else '127.0.0.1')]
|
||||
if socket.has_ipv6:
|
||||
families.append((socket.AF_INET6, '::' if public else '::1'))
|
||||
for family, address in families:
|
||||
try:
|
||||
with socket.socket(family, socket.SOCK_STREAM) as sock:
|
||||
if family == socket.AF_INET6:
|
||||
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
||||
sock.bind((address, port))
|
||||
except OSError as exc:
|
||||
if exc.errno in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL) and family == socket.AF_INET6:
|
||||
continue
|
||||
raise ValueError(f'port {port} is unavailable: {exc}') from exc
|
||||
|
||||
|
||||
def extract_bundle(archive_path, target):
|
||||
"""Extract regular files only into a new directory; reject links and duplicates."""
|
||||
target = Path(target)
|
||||
seen = set()
|
||||
total = 0
|
||||
with tarfile.open(archive_path, 'r:gz') as archive:
|
||||
for member in archive:
|
||||
if not bundle.safe_member(member):
|
||||
raise ValueError('unsafe archive member')
|
||||
path = PurePosixPath(member.name)
|
||||
if not path.parts or path.parts[0] != 'application' or member.name in seen:
|
||||
raise ValueError('invalid or duplicate archive member')
|
||||
seen.add(member.name)
|
||||
total += member.size
|
||||
if total > 4 * 1024 ** 3 or len(seen) > 250000:
|
||||
raise ValueError('archive exceeds extraction limits')
|
||||
dest = target.joinpath(*path.parts)
|
||||
if member.isdir():
|
||||
dest.mkdir(parents=True, exist_ok=True, mode=0o755)
|
||||
else:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
|
||||
with archive.extractfile(member) as source_stream, dest.open('xb') as out:
|
||||
shutil.copyfileobj(source_stream, out, 1024 * 1024)
|
||||
os.chmod(dest, 0o755 if member.mode & 0o111 else 0o644)
|
||||
app = target / 'application'
|
||||
required = ['WebApi/pyproject.toml', 'WebApi/uv.lock', 'WebApp/package.json', 'WebApp/package-lock.json']
|
||||
required += [f'Persistance/persistance/{domain}/alembic.ini' for domain in DOMAINS]
|
||||
if any(not (app / path).is_file() for path in required):
|
||||
raise ValueError('bundle lacks required locked application components')
|
||||
worker = worker_module(app)
|
||||
if worker == 'webapi.recomputation' and any(not (app / 'Transformation' / name).is_file() for name in
|
||||
('pyproject.toml', 'dbt_project.yml', 'profiles.yml')):
|
||||
raise ValueError('bundle lacks the Transformation project')
|
||||
return worker
|
||||
|
||||
|
||||
def worker_module(app):
|
||||
"""The indicator worker module the bundled WebApi provides."""
|
||||
for module in WORKER_MODULES:
|
||||
path = app / 'WebApi' / (module.replace('.', '/') + '.py')
|
||||
if path.is_file() and not path.is_symlink():
|
||||
return module
|
||||
raise ValueError('bundle lacks required locked application components')
|
||||
|
||||
|
||||
def atomic_record(path, record):
|
||||
temporary = path.with_suffix('.tmp')
|
||||
with temporary.open('x', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, indent=2, sort_keys=True)
|
||||
stream.write('\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def environment(base):
|
||||
data = base / 'data'
|
||||
result = {'PATH': os.environ.get('PATH', '/usr/local/bin:/usr/bin:/bin'),
|
||||
'HOME': str(data), 'LANG': 'C.UTF-8', 'UV_CACHE_DIR': str(data / 'uv-cache'),
|
||||
'npm_config_cache': str(data / 'npm-cache'),
|
||||
'MLFLOW_TRACKING_URI': 'sqlite:///' + str(data / 'mlflow.db'),
|
||||
'MLFLOW_ARTIFACT_ROOT': str(data / 'mlflow-artifacts'),
|
||||
'MLFLOW_DISABLE_TELEMETRY': 'true', 'DO_NOT_TRACK': 'true',
|
||||
'MLFLOW_DISABLE_AGENT_HINT': '1', 'WEBAPI_REPORT_DIR': str(data / 'reportes'),
|
||||
'INDICADORES_DIR': str(data / 'indicadores'),
|
||||
# No isolated notebook runner exists here: notebook runs fail instead of running in the API process.
|
||||
'NOTEBOOK_EXECUTOR': 'contenedor'}
|
||||
for domain in DOMAINS:
|
||||
result[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
|
||||
return result
|
||||
|
||||
|
||||
def run(args, cwd, env):
|
||||
subprocess.run([str(arg) for arg in args], cwd=cwd, env=env, check=True)
|
||||
|
||||
|
||||
|
||||
def verify_database_targets(uv, app, env, data):
|
||||
"""Check the selected application's effective settings before any migration."""
|
||||
code = """import os, sys
|
||||
from pathlib import Path
|
||||
from sqlalchemy.engine import make_url
|
||||
from persistance.settings import settings
|
||||
base = Path(sys.argv[1]).resolve()
|
||||
for domain in ('cacu', 'cama', 'tea', 'governance'):
|
||||
expected = base / (domain + '.db')
|
||||
url = getattr(settings, domain + '_database_url')
|
||||
parsed = make_url(url)
|
||||
if (url != os.environ[domain.upper() + '_DATABASE_URL'] or parsed.drivername != 'sqlite'
|
||||
or not parsed.database or Path(parsed.database) != expected or expected.is_symlink()
|
||||
or expected.resolve().parent != base or not expected.is_file() or expected.stat().st_size != 0):
|
||||
raise SystemExit('effective migration destination rejected: ' + domain)
|
||||
print('Verified four new isolated SQLite migration targets')
|
||||
"""
|
||||
run([uv, 'run', '--no-sync', 'python', '-c', code, data], app / 'WebApi', env)
|
||||
|
||||
|
||||
def compile_sqlite_manifest(uv, app, env, data):
|
||||
"""Build the bundle's dbt measure manifest against isolated SQLite targets."""
|
||||
transformation = app / 'Transformation'
|
||||
output = data / 'dbt'
|
||||
schemas = output / 'schemas'
|
||||
schemas.mkdir(parents=True)
|
||||
dbt_env = dict(env, DBT_SCHEMA_DIR=str(schemas))
|
||||
dbt_env.update({domain.upper() + '_DB_PATH': str(data / (domain + '.db')) for domain in DOMAINS})
|
||||
run([uv, 'sync', '--only-group', 'sqlite'], transformation, dbt_env)
|
||||
run([uv, 'run', '--no-sync', 'dbt', 'compile', '--profiles-dir', '.', '--profile', 'cacu', '--target', 'sqlite',
|
||||
'--no-introspect', '--target-path', output], transformation, dbt_env)
|
||||
manifest = output / 'manifest.json'
|
||||
if not manifest.is_file() or manifest.is_symlink():
|
||||
raise ValueError('compiled dbt manifest is missing')
|
||||
env.update(DBT_MANIFEST=str(manifest), TRANSFORMATION_DIR=str(transformation))
|
||||
|
||||
|
||||
def systemd_unit(base, account, service, api_port, nginx, worker):
|
||||
work = base / 'application' / 'WebApi'
|
||||
binary = work / '.venv' / 'bin'
|
||||
name = base.name
|
||||
common = f'''[Unit]\nDescription=ISSSTELEON native {service} {name}\nAfter=network.target\n'''
|
||||
if service == 'worker':
|
||||
common += f'After={name}-api.service\nRequires={name}-api.service\n'
|
||||
if service == 'web':
|
||||
common += f'After={name}-api.service\nRequires={name}-api.service\n'
|
||||
command = {
|
||||
'api': f'{binary}/gunicorn --bind 127.0.0.1:{api_port} --workers 2 --timeout 600 --access-logfile - webapi:create_app()',
|
||||
'worker': f'{binary}/python -m {worker}',
|
||||
'web': f'{nginx} -c {base}/nginx.conf -p {base}/',
|
||||
}[service]
|
||||
directory = base if service == 'web' else work
|
||||
return common + f'''\n[Service]\nType=simple\nWorkingDirectory={directory}\nEnvironmentFile={base}/service.env\nExecStart={command}\nRestart=on-failure\nRestartSec=5\nNoNewPrivileges=true\nPrivateUsers=true\nPrivateTmp=true\nProtectSystem=strict\nReadWritePaths={base}/data\n\n[Install]\nWantedBy=default.target\n'''
|
||||
|
||||
|
||||
def nginx_conf(base, port, api_port):
|
||||
data = base / 'data'
|
||||
return f'''worker_processes 1;\ndaemon off;\npid {data}/nginx.pid;\nerror_log stderr;\nevents {{ worker_connections 1024; }}\nhttp {{\n include /etc/nginx/mime.types;\n default_type application/octet-stream;\n access_log /dev/stdout;\n client_body_temp_path {data}/nginx-client;\n proxy_temp_path {data}/nginx-proxy;\n fastcgi_temp_path {data}/nginx-fastcgi;\n uwsgi_temp_path {data}/nginx-uwsgi;\n scgi_temp_path {data}/nginx-scgi;\n server {{\n listen {port};\n server_name _;\n root {base}/application/WebApp/dist/WebApp/browser;\n client_max_body_size 270m;\n location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) {{\n proxy_pass http://127.0.0.1:{api_port};\n proxy_set_header Host $host;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_read_timeout 600s;\n }}\n location ~* \\.(js|css)$ {{ add_header Cache-Control "public, max-age=31536000, immutable"; try_files $uri =404; }}\n location / {{ add_header Cache-Control "no-cache"; try_files $uri $uri/ /index.html; }}\n }}\n}}\n'''
|
||||
|
||||
|
||||
def prepare(parent, record, archive_path, expected_digest, api_port, account, expected_hostname, tools):
|
||||
"""Create a fresh instance; failure retains its data and prevents retries over it."""
|
||||
validate_record(record)
|
||||
if (not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,252}', expected_hostname)
|
||||
or socket.gethostname().lower() != expected_hostname.lower()):
|
||||
raise ValueError('host identity does not match the explicitly expected hostname')
|
||||
parent = validate_parent(parent)
|
||||
validate_service_account(account)
|
||||
if expected_digest != record['bundle_sha256'] or digest(archive_path) != expected_digest:
|
||||
raise ValueError('bundle digest does not match the independently supplied digest and record')
|
||||
port = record['public_port']
|
||||
if type(api_port) is not int or api_port != record['api_port']:
|
||||
raise ValueError('API port does not match the validated release request')
|
||||
check_port(port, True)
|
||||
check_port(api_port, False)
|
||||
base = parent / f'isssteleon-native-{port}'
|
||||
base.mkdir(mode=0o750) # exclusive; no update or reuse
|
||||
state = dict(record, status='preparing', phase='reserved', base=str(base), api_port=api_port,
|
||||
account=account, hostname=expected_hostname, services=[f'{base.name}-{part}.service' for part in ('api', 'worker', 'web')])
|
||||
metadata = base / 'installation.json'
|
||||
try:
|
||||
atomic_record(metadata, state)
|
||||
(base / 'data').mkdir(mode=0o700)
|
||||
worker = extract_bundle(archive_path, base)
|
||||
app = base / 'application'
|
||||
env = environment(base)
|
||||
for domain in DOMAINS:
|
||||
path = base / 'data' / (domain + '.db')
|
||||
with path.open('xb'):
|
||||
pass
|
||||
os.chmod(path, 0o600)
|
||||
state.update(phase='dependencies')
|
||||
atomic_record(metadata, state)
|
||||
run([tools['uv'], 'sync', '--locked', '--no-dev', '--extra', 'sql-drivers'], app / 'WebApi', env)
|
||||
run([tools['npm'], 'ci'], app / 'WebApp', env)
|
||||
run([tools['npm'], 'run', 'build', '--', '--configuration', 'production'], app / 'WebApp', env)
|
||||
if not (app / 'WebApp' / 'dist' / 'WebApp' / 'browser' / 'index.html').is_file():
|
||||
raise ValueError('Angular distribution index is missing')
|
||||
state.update(phase='verifying_migration_targets')
|
||||
atomic_record(metadata, state)
|
||||
verify_database_targets(tools['uv'], app, env, base / 'data')
|
||||
state.update(phase='migrations')
|
||||
atomic_record(metadata, state)
|
||||
for domain in DOMAINS:
|
||||
target = base / 'data' / (domain + '.db')
|
||||
if target.is_symlink() or target.resolve().parent != (base / 'data').resolve() or target.stat().st_size != 0:
|
||||
raise ValueError('migration target is not a new isolated database: ' + domain)
|
||||
run([tools['uv'], 'run', '--no-sync', 'alembic', '-c', app / 'Persistance' / 'persistance' / domain / 'alembic.ini', 'upgrade', 'head'], app / 'WebApi', env)
|
||||
if worker == 'webapi.recomputation':
|
||||
state.update(phase='compiling_measure_manifest')
|
||||
atomic_record(metadata, state)
|
||||
compile_sqlite_manifest(tools['uv'], app, env, base / 'data')
|
||||
service_env = {k: v for k, v in env.items() if k not in ('PATH', 'LANG', 'npm_config_cache', 'UV_CACHE_DIR')}
|
||||
(base / 'service.env').write_text(''.join(f'{key}={value}\n' for key, value in sorted(service_env.items())), encoding='utf-8')
|
||||
(base / 'nginx.conf').write_text(nginx_conf(base, port, api_port), encoding='utf-8')
|
||||
units = base / 'units'
|
||||
units.mkdir(mode=0o750)
|
||||
for service in ('api', 'worker', 'web'):
|
||||
(units / f'{base.name}-{service}.service').write_text(
|
||||
systemd_unit(base, account, service, api_port, tools['nginx'], worker), encoding='utf-8')
|
||||
run([tools['nginx'], '-t', '-c', base / 'nginx.conf', '-p', str(base) + '/'], base, env)
|
||||
state.update(status='prepared', phase='awaiting_systemd_activation', prepared_at=int(time.time()))
|
||||
atomic_record(metadata, state)
|
||||
return state
|
||||
except BaseException as exc:
|
||||
state.update(status='failed', error=type(exc).__name__)
|
||||
try:
|
||||
atomic_record(metadata, state)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def available_tools():
|
||||
result = {}
|
||||
for name in ('uv', 'npm', 'nginx', 'tesseract'):
|
||||
path = shutil.which(name)
|
||||
if not path or not SAFE_PATH.fullmatch(path):
|
||||
raise ValueError('missing or unsafe executable path: ' + name)
|
||||
result[name] = path
|
||||
languages = subprocess.run([result['tesseract'], '--list-langs'], capture_output=True, text=True, check=True).stdout.splitlines()
|
||||
if not {'spa', 'eng'} <= set(languages):
|
||||
raise ValueError('Tesseract requires spa and eng language data')
|
||||
if not Path('/etc/nginx/mime.types').is_file():
|
||||
raise ValueError('nginx mime.types is missing')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--record', required=True, type=Path)
|
||||
parser.add_argument('--bundle', required=True, type=Path)
|
||||
parser.add_argument('--bundle-sha256', required=True)
|
||||
parser.add_argument('--parent', required=True, type=Path)
|
||||
parser.add_argument('--api-port', required=True, type=int)
|
||||
parser.add_argument('--account', required=True)
|
||||
parser.add_argument('--expected-hostname', required=True)
|
||||
args = parser.parse_args()
|
||||
if sys.platform != 'linux':
|
||||
parser.error('native installation requires Linux')
|
||||
try:
|
||||
if Path('/.dockerenv').exists() or Path('/run/.containerenv').exists():
|
||||
raise ValueError('run preparation on the selected host, not inside a container')
|
||||
record = json.loads(args.record.read_text(encoding='utf-8'))
|
||||
validate_record(record)
|
||||
check_installer_files(Path(__file__).resolve().parent, record)
|
||||
result = prepare(args.parent, record, args.bundle, args.bundle_sha256, args.api_port, args.account, args.expected_hostname, available_tools())
|
||||
print(json.dumps(result, indent=2, sort_keys=True))
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, tarfile.TarError, json.JSONDecodeError) as exc:
|
||||
print('Native preparation failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deploy and verify a release through an explicitly configured non-root SSH account."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
import time
|
||||
import urllib.error
|
||||
|
||||
import verify
|
||||
|
||||
import install
|
||||
|
||||
FILES = ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py', 'release-record.json', 'release-source.tar.gz')
|
||||
HOST = re.compile(r'^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$')
|
||||
|
||||
|
||||
def ssh_options(identity, known_hosts):
|
||||
return ['-i', str(identity), '-o', 'BatchMode=yes', '-o', 'IdentitiesOnly=yes',
|
||||
'-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + str(known_hosts)]
|
||||
|
||||
|
||||
def remote_command(arguments):
|
||||
return shlex.join([str(part) for part in arguments])
|
||||
|
||||
|
||||
|
||||
def check_public(host, port, timeout=90):
|
||||
"""Require the runner to reach both the application and proxied API."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
status, body = verify.request(f'http://{host}:{port}/health')
|
||||
health = json.loads(body)
|
||||
index_status, index = verify.request(f'http://{host}:{port}/')
|
||||
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok' or index_status != 200 or not index:
|
||||
raise ValueError('public HTTP or proxied API health check failed')
|
||||
return
|
||||
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError('public endpoint is unavailable: ' + str(exc)) from exc
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def prepare(bundle_dir, digest, host, port, account, expected_hostname, parent, api_port, identity, known_hosts):
|
||||
"""Use pinned host keys and create a unique staging directory without elevated privileges."""
|
||||
bundle_dir = Path(bundle_dir).resolve()
|
||||
identity, known_hosts = Path(identity).resolve(), Path(known_hosts).resolve()
|
||||
if (not HOST.fullmatch(host) or not HOST.fullmatch(expected_hostname) or not install.NAME.fullmatch(account)
|
||||
or account == 'root' or not 1 <= port <= 65535 or not identity.is_file() or not known_hosts.is_file()
|
||||
or not install.SAFE_PATH.fullmatch(parent) or parent == '/' or '..' in Path(parent).parts):
|
||||
raise ValueError('invalid explicit SSH endpoint, host key, account or parent')
|
||||
files = [bundle_dir / name for name in FILES]
|
||||
if any(not item.is_file() or item.is_symlink() for item in files):
|
||||
raise ValueError('bundle or installer file is missing or symlinked')
|
||||
record = json.loads((bundle_dir / 'release-record.json').read_text(encoding='utf-8'))
|
||||
install.validate_record(record)
|
||||
install.check_installer_files(bundle_dir, record)
|
||||
if digest != record['bundle_sha256'] or install.digest(bundle_dir / 'release-source.tar.gz') != digest:
|
||||
raise ValueError('bundle checksum mismatch')
|
||||
if type(api_port) is not int or api_port != record['api_port']:
|
||||
raise ValueError('API port does not match the validated release request')
|
||||
ssh, scp = shutil.which('ssh'), shutil.which('scp')
|
||||
if not ssh or not scp:
|
||||
raise ValueError('ssh and scp are required')
|
||||
endpoint = account + '@' + host
|
||||
stage = parent.rstrip('/') + '/.release-' + uuid.uuid4().hex
|
||||
options = ssh_options(identity, known_hosts)
|
||||
# Check identity and containment remotely before making any files.
|
||||
guard = '''import grp,os,pathlib,pwd,socket,subprocess,sys
|
||||
parent,stage,account,host=sys.argv[1:]
|
||||
p=pathlib.Path(parent)
|
||||
resolved=p.resolve(strict=True)
|
||||
docker=pathlib.Path('/srv/workingnarrative-dev')
|
||||
entry=pwd.getpwuid(os.geteuid())
|
||||
if str(resolved)!=parent or not p.is_dir() or p.stat().st_uid!=os.geteuid() or p.stat().st_mode & 0o022 or docker==resolved or docker in resolved.parents or socket.gethostname().lower()!=host.lower() or os.geteuid()==0 or entry.pw_name!=account:
|
||||
raise SystemExit('remote identity or parent rejected')
|
||||
groups=set(os.getgroups()) | set(os.getgrouplist(account,entry.pw_gid)) | {entry.pw_gid,os.getegid()}
|
||||
privileged={0}
|
||||
for name in ('docker','sudo','wheel'):
|
||||
try:
|
||||
privileged.add(grp.getgrnam(name).gr_gid)
|
||||
except KeyError:
|
||||
pass
|
||||
if groups & privileged:
|
||||
raise SystemExit('remote service account has privileged group membership')
|
||||
runtime=pathlib.Path('/run/user') / str(os.geteuid())
|
||||
if not runtime.is_dir() or not (runtime / 'bus').exists():
|
||||
raise SystemExit('user manager runtime is unavailable')
|
||||
env=dict(os.environ, HOME=entry.pw_dir, XDG_RUNTIME_DIR=str(runtime), DBUS_SESSION_BUS_ADDRESS='unix:path=' + str(runtime / 'bus'))
|
||||
linger=subprocess.run(['loginctl','show-user',account,'--property=Linger','--value'],env=env,text=True,capture_output=True,check=True)
|
||||
if linger.stdout.strip().lower() != 'yes':
|
||||
raise SystemExit('user lingering is not enabled')
|
||||
subprocess.run(['systemctl','--user','show-environment'],env=env,capture_output=True,check=True)
|
||||
os.mkdir(stage,0o700)
|
||||
'''
|
||||
subprocess.run([ssh, *options, '-p', str(port), endpoint,
|
||||
remote_command(['python3', '-c', guard, parent, stage, account, expected_hostname])], check=True)
|
||||
print('Remote staging directory:', stage, flush=True)
|
||||
subprocess.run([scp, *options, '-P', str(port), *map(str, files), endpoint + ':' + stage + '/'], check=True)
|
||||
command = ['python3', stage + '/install.py', '--record', stage + '/release-record.json',
|
||||
'--bundle', stage + '/release-source.tar.gz', '--bundle-sha256', digest,
|
||||
'--parent', parent, '--account', account, '--expected-hostname', expected_hostname,
|
||||
'--api-port', str(api_port)]
|
||||
subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(command)], check=True)
|
||||
instance = parent.rstrip('/') + '/isssteleon-native-' + str(record['public_port'])
|
||||
def remote_run(args, check=True):
|
||||
return subprocess.run([ssh, *options, '-p', str(port), endpoint, remote_command(args)], check=check)
|
||||
remote_run(['python3', stage + '/activate.py', instance])
|
||||
remote_run(['python3', stage + '/verify.py', instance, '--wait-seconds', '180'])
|
||||
try:
|
||||
check_public(host, record['public_port'])
|
||||
except (OSError, ValueError) as exc:
|
||||
try:
|
||||
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'failed', '--wait-seconds', '0'], check=False)
|
||||
except OSError:
|
||||
pass
|
||||
raise exc
|
||||
remote_run(['python3', stage + '/verify.py', instance, '--public-result', 'ok', '--wait-seconds', '0'])
|
||||
return stage
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--bundle-dir', required=True, type=Path)
|
||||
parser.add_argument('--bundle-sha256', required=True)
|
||||
parser.add_argument('--host', required=True)
|
||||
parser.add_argument('--ssh-port', required=True, type=int)
|
||||
parser.add_argument('--account', required=True)
|
||||
parser.add_argument('--expected-hostname', required=True)
|
||||
parser.add_argument('--parent', required=True)
|
||||
parser.add_argument('--api-port', required=True, type=int)
|
||||
parser.add_argument('--identity', required=True, type=Path)
|
||||
parser.add_argument('--known-hosts', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
prepare(args.bundle_dir, args.bundle_sha256, args.host, args.ssh_port, args.account,
|
||||
args.expected_hostname, args.parent, args.api_port, args.identity, args.known_hosts)
|
||||
print('Native deployment is active and public HTTP checks passed.')
|
||||
return 0
|
||||
except (OSError, ValueError, subprocess.CalledProcessError, json.JSONDecodeError) as exc:
|
||||
print('Remote preparation failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve a published institutional release without deploying it."""
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import source
|
||||
import bundle
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SERVER = 'http://10.0.10.41:3000'
|
||||
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
|
||||
ORIGIN = SERVER + '/' + REPOSITORY + '.git'
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
|
||||
|
||||
def git(root, *args):
|
||||
return subprocess.run(['git', '-C', str(root), *args], check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
|
||||
def validate_tag(tag):
|
||||
if not tag or tag.startswith(('-', 'refs/')) or re.fullmatch(r'[0-9a-fA-F]{40}', tag):
|
||||
raise ValueError('tag must be an unambiguous tag name')
|
||||
subprocess.run(['git', 'check-ref-format', 'refs/tags/' + tag], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
return tag
|
||||
|
||||
|
||||
def validate_port(port):
|
||||
if not re.fullmatch(r'[0-9]{1,5}', port) or not 1024 <= int(port) <= 65535:
|
||||
raise ValueError('port must be an integer from 1024 to 65535')
|
||||
return int(port)
|
||||
|
||||
|
||||
def dispatch(root, env):
|
||||
ref, name, sha = (env.get('DISPATCH_REF', ''), env.get('DISPATCH_REF_NAME', ''), env.get('DISPATCH_SHA', ''))
|
||||
if (env.get('DISPATCH_REPOSITORY') != REPOSITORY or env.get('DISPATCH_SERVER', '').rstrip('/') != SERVER
|
||||
or env.get('DISPATCH_REF_TYPE') != 'branch' or not name or ref != 'refs/heads/' + name
|
||||
or not SHA.fullmatch(sha)):
|
||||
raise ValueError('invalid workflow dispatch identity')
|
||||
subprocess.run(['git', 'check-ref-format', ref], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
if git(root, 'rev-parse', 'HEAD') != sha or git(root, 'remote', 'get-url', 'origin') not in (ORIGIN, ORIGIN.removesuffix('.git')):
|
||||
raise ValueError('workflow checkout identity mismatch')
|
||||
return {'installer_ref': ref, 'installer_sha': sha}
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def release(tag, token):
|
||||
if not token:
|
||||
raise ValueError('Gitea token is required')
|
||||
url = SERVER + '/api/v1/repos/' + REPOSITORY + '/releases/tags/' + urllib.parse.quote(tag, safe='')
|
||||
req = urllib.request.Request(url, headers={'Authorization': 'token ' + token, 'Accept': 'application/json'})
|
||||
with urllib.request.build_opener(NoRedirect).open(req, timeout=15) as response:
|
||||
data = json.load(response)
|
||||
if (not isinstance(data, dict) or type(data.get('id')) is not int or data['id'] <= 0
|
||||
or data.get('tag_name') != tag or data.get('draft') is not False
|
||||
or not data.get('published_at')):
|
||||
raise ValueError('tag does not identify a published release')
|
||||
return {'release_id': data['id'], 'tag': tag}
|
||||
|
||||
|
||||
def resolve(root, tag, port, api_port, env):
|
||||
validate_tag(tag)
|
||||
port = validate_port(port)
|
||||
api_port = validate_port(api_port)
|
||||
if port == api_port:
|
||||
raise ValueError('public and API ports must differ')
|
||||
installer = dispatch(root, env)
|
||||
first = release(tag, env.get('RELEASE_TOKEN', ''))
|
||||
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
|
||||
try:
|
||||
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + tag + ':' + ref)
|
||||
object_sha = git(root, 'rev-parse', '--verify', ref)
|
||||
commit = git(root, 'rev-parse', '--verify', ref + '^{commit}')
|
||||
if not SHA.fullmatch(object_sha) or not SHA.fullmatch(commit):
|
||||
raise ValueError('invalid fetched tag object or commit')
|
||||
# A remote tag changed during resolution must not be silently accepted.
|
||||
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
|
||||
if lines != [object_sha + '\trefs/tags/' + tag]:
|
||||
raise ValueError('remote tag changed during resolution')
|
||||
if release(tag, env.get('RELEASE_TOKEN', '')) != first:
|
||||
raise ValueError('release changed during resolution')
|
||||
return dict(first, **installer, tag_object=object_sha, application_sha=commit, public_port=port, api_port=api_port)
|
||||
finally:
|
||||
git(root, 'update-ref', '-d', ref)
|
||||
|
||||
|
||||
|
||||
def prepare_source(root, record, output=None):
|
||||
"""Fetch the same tag again into a disposable checkout and verify gitlinks."""
|
||||
ref = 'refs/deploy-terminal/' + uuid.uuid4().hex
|
||||
try:
|
||||
git(root, 'fetch', '--no-tags', 'origin', '+refs/tags/' + record['tag'] + ':' + ref)
|
||||
if (git(root, 'rev-parse', '--verify', ref) != record['tag_object']
|
||||
or git(root, 'rev-parse', '--verify', ref + '^{commit}') != record['application_sha']):
|
||||
raise ValueError('tag changed before source preparation')
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-release-') as temporary:
|
||||
checkout = Path(temporary)
|
||||
subprocess.run(['git', 'init', '--quiet', str(checkout)], check=True)
|
||||
git(checkout, 'fetch', '--no-tags', str(root), ref)
|
||||
git(checkout, 'checkout', '--quiet', '--detach', record['application_sha'])
|
||||
if git(checkout, 'rev-parse', 'HEAD') != record['application_sha']:
|
||||
raise ValueError('application checkout mismatch')
|
||||
manifest = source.checkout_pinned(checkout)
|
||||
if output is not None:
|
||||
record['bundle_sha256'] = bundle.export(checkout, manifest, output)
|
||||
return manifest
|
||||
finally:
|
||||
git(root, 'update-ref', '-d', ref)
|
||||
|
||||
|
||||
|
||||
|
||||
def installer_manifest(root, sha):
|
||||
"""Bind exported installer scripts to the dispatched committed revision."""
|
||||
manifest = {}
|
||||
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
|
||||
relative = '.gitea/deploy-terminal/' + name
|
||||
committed = subprocess.run(['git', '-C', str(root), 'show', sha + ':' + relative],
|
||||
check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout
|
||||
if (Path(root) / relative).read_bytes() != committed:
|
||||
raise ValueError('installer file differs from dispatched revision: ' + name)
|
||||
manifest[name] = hashlib.sha256(committed).hexdigest()
|
||||
return manifest
|
||||
|
||||
|
||||
def revalidate(root, record, token):
|
||||
"""Fail if the tag or publication changed while the bundle was being built."""
|
||||
tag = validate_tag(record['tag'])
|
||||
lines = git(root, 'ls-remote', '--refs', 'origin', 'refs/tags/' + tag).splitlines()
|
||||
if lines != [record['tag_object'] + '\trefs/tags/' + tag]:
|
||||
raise ValueError('remote tag changed before bundle publication')
|
||||
if release(tag, token) != {'tag': tag, 'release_id': record['release_id']}:
|
||||
raise ValueError('release changed before bundle publication')
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
record = resolve(ROOT, os.environ.get('REQUESTED_TAG', ''), os.environ.get('REQUESTED_PORT', ''),
|
||||
os.environ.get('REQUESTED_API_PORT', ''), os.environ)
|
||||
output = Path(os.environ.get('RELEASE_OUTPUT', 'release-source.tar.gz'))
|
||||
record['installer_files'] = installer_manifest(ROOT, record['installer_sha'])
|
||||
record['gitlinks'] = prepare_source(ROOT, record, output)
|
||||
revalidate(ROOT, record, os.environ.get('RELEASE_TOKEN', ''))
|
||||
bundle.write_record(output.with_name('release-record.json'), record)
|
||||
print(json.dumps(record, sort_keys=True), flush=True)
|
||||
print('Release bundle prepared for automated native deployment.', flush=True)
|
||||
return 0
|
||||
except (ValueError, subprocess.CalledProcessError, OSError, urllib.error.URLError, json.JSONDecodeError) as exc:
|
||||
print('Release resolution failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check out only institutional application gitlinks at their committed SHAs."""
|
||||
import os
|
||||
import base64
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
INSTITUTIONAL = 'ssh://git@10.0.10.41:2222/ISSSTELEON/'
|
||||
# The exact origin each gitlink may come from; the EEG library is the one repository outside the organisation.
|
||||
ORIGINS = {
|
||||
'ISSSTELEON': INSTITUTIONAL + 'ISSSTELEON.git',
|
||||
'ISSSTELEON/WebApi': INSTITUTIONAL + 'WebApi.git',
|
||||
'ISSSTELEON/WebApp': INSTITUTIONAL + 'WebApp.git',
|
||||
'ISSSTELEON/models': INSTITUTIONAL + 'models.git',
|
||||
'ISSSTELEON/models/libs/tea': 'ssh://git@10.0.10.41:2222/alberto/tea.git',
|
||||
'ISSSTELEON/indicadores_kit': INSTITUTIONAL + 'indicadores_kit.git',
|
||||
}
|
||||
SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||
|
||||
|
||||
def git(repo, *args, binary=False):
|
||||
env = os.environ.copy()
|
||||
token = env.get('RELEASE_TOKEN')
|
||||
if token:
|
||||
try:
|
||||
count = int(env.get('GIT_CONFIG_COUNT', '0'))
|
||||
except ValueError as exc:
|
||||
raise ValueError('invalid inherited Git configuration count') from exc
|
||||
if not 0 <= count < 32:
|
||||
raise ValueError('invalid inherited Git configuration count')
|
||||
encoded = base64.b64encode(('x-access-token:' + token).encode()).decode('ascii')
|
||||
env['GIT_CONFIG_KEY_' + str(count)] = 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader'
|
||||
env['GIT_CONFIG_VALUE_' + str(count)] = 'AUTHORIZATION: basic ' + encoded
|
||||
env['GIT_CONFIG_COUNT'] = str(count + 1)
|
||||
env['GIT_TERMINAL_PROMPT'] = '0'
|
||||
result = subprocess.run(['git', '-C', str(repo), *args], check=True, env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=not binary)
|
||||
return result.stdout if binary else result.stdout.strip()
|
||||
|
||||
|
||||
def gitlinks(repo):
|
||||
entries = git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
|
||||
links = {}
|
||||
for entry in entries.split(b'\0'):
|
||||
if not entry:
|
||||
continue
|
||||
meta, name = entry.split(b'\t', 1)
|
||||
mode, kind, sha = meta.decode('ascii').split()
|
||||
if mode != '160000':
|
||||
continue
|
||||
path = os.fsdecode(name)
|
||||
if (kind != 'commit' or not SHA.fullmatch(sha) or path.startswith('/')
|
||||
or any(part in ('', '.', '..') for part in path.split('/')) or '\\' in path):
|
||||
raise ValueError('unsafe gitlink entry')
|
||||
links[path] = sha
|
||||
return links
|
||||
|
||||
|
||||
def checkout_pinned(root):
|
||||
"""Ignore unrelated top-level submodules; reject unknown application origins."""
|
||||
root = Path(root)
|
||||
outer = gitlinks(root)
|
||||
if 'ISSSTELEON' not in outer:
|
||||
raise ValueError('application gitlink is missing')
|
||||
manifest = {}
|
||||
|
||||
def visit(repo, path, prefix, sha):
|
||||
full = prefix + '/' + path if prefix else path
|
||||
if full not in ORIGINS:
|
||||
raise ValueError('unrecognized application gitlink: ' + full)
|
||||
config = git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
|
||||
matches = []
|
||||
for line in config.splitlines():
|
||||
parts = line.split(None, 1)
|
||||
if len(parts) == 2 and parts[1] == path:
|
||||
matches.append(parts[0][len('submodule.'):-len('.path')])
|
||||
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
|
||||
raise ValueError('ambiguous submodule mapping: ' + full)
|
||||
name = matches[0]
|
||||
origin = ORIGINS[full]
|
||||
if git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url') != origin:
|
||||
raise ValueError('untrusted submodule origin: ' + full)
|
||||
git(repo, '-c', 'protocol.file.allow=never', '-c', f'submodule.{name}.url={origin}',
|
||||
'submodule', 'update', '--init', '--checkout', '--', path)
|
||||
child = repo / path
|
||||
if git(child, 'rev-parse', 'HEAD') != sha:
|
||||
raise ValueError('gitlink checkout mismatch: ' + full)
|
||||
manifest[full] = sha
|
||||
for nested, child_sha in gitlinks(child).items():
|
||||
visit(child, nested, full, child_sha)
|
||||
|
||||
visit(root, 'ISSSTELEON', '', outer['ISSSTELEON'])
|
||||
return manifest
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Test user-service activation and failure handling with isolated unit directories."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import activate
|
||||
import install
|
||||
|
||||
|
||||
class ActivationTests(unittest.TestCase):
|
||||
"""Temporary files and a mocked user manager stand in for systemd and the host."""
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name).resolve()
|
||||
self.base = self.root / 'isssteleon-native-18090'
|
||||
self.base.mkdir()
|
||||
(self.base / 'data').mkdir()
|
||||
(self.base / 'data' / 'cacu.db').write_bytes(b'existing')
|
||||
(self.base / 'units').mkdir()
|
||||
self.names = [f'isssteleon-native-18090-{part}.service' for part in ('api', 'worker', 'web')]
|
||||
for name in self.names:
|
||||
(self.base / 'units' / name).write_text('[Service]\n', encoding='utf-8')
|
||||
self.unit_dir = self.root / 'user-units'
|
||||
self.unit_dir.mkdir()
|
||||
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090,
|
||||
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
|
||||
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
|
||||
'bundle_sha256': 'd' * 64, 'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
|
||||
'gitlinks': {name: 'f' * 40 for name in install.REQUIRED_LINKS},
|
||||
'status': 'prepared', 'base': str(self.base), 'api_port': 28090,
|
||||
'account': 'wnnative', 'services': self.names}
|
||||
(self.base / 'installation.json').write_text(json.dumps(self.record), encoding='utf-8')
|
||||
self.commands = []
|
||||
self.env = {'HOME': str(self.root)}
|
||||
|
||||
def fake_command(self, args, env, check=True):
|
||||
self.commands.append(args)
|
||||
if args[0] == 'loginctl': return types.SimpleNamespace(stdout='yes\n', returncode=0)
|
||||
if '--property=LoadState' in args: return types.SimpleNamespace(stdout='not-found\n', returncode=0)
|
||||
return types.SimpleNamespace(stdout='', returncode=0)
|
||||
|
||||
def fake_symlink(self, source, dest):
|
||||
Path(dest).write_text(str(source), encoding='utf-8')
|
||||
|
||||
def run_activate(self):
|
||||
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=self.fake_command), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
|
||||
return activate.activate(self.base, self.record, self.env)
|
||||
|
||||
def test_starts_only_new_user_units(self):
|
||||
"""Activation enables the three instance units in the user manager without root operations."""
|
||||
result = self.run_activate()
|
||||
self.assertEqual(result['status'], 'started')
|
||||
enabled = [cmd for cmd in self.commands if 'enable' in cmd]
|
||||
self.assertEqual(len(enabled), 3)
|
||||
self.assertTrue(all(cmd[:2] == ['systemctl', '--user'] for cmd in enabled))
|
||||
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
|
||||
|
||||
def test_existing_unit_is_never_replaced(self):
|
||||
"""An existing user unit must stop activation without modifying the existing unit or data."""
|
||||
existing = self.unit_dir / self.names[0]
|
||||
existing.write_text('keep', encoding='utf-8')
|
||||
with self.assertRaises(ValueError): self.run_activate()
|
||||
self.assertEqual(existing.read_text(), 'keep')
|
||||
self.assertFalse(any('enable' in cmd for cmd in self.commands))
|
||||
|
||||
def test_linger_is_required(self):
|
||||
"""A user manager without lingering must fail before creating or starting a unit."""
|
||||
def no_linger(args, env, check=True):
|
||||
return types.SimpleNamespace(stdout='no\n', returncode=0)
|
||||
with patch.object(activate, 'command', side_effect=no_linger), patch.object(activate, 'units_directory') as units:
|
||||
with self.assertRaises(ValueError): activate.activate(self.base, self.record, self.env)
|
||||
units.assert_not_called()
|
||||
|
||||
def test_start_failure_stops_only_new_units_and_keeps_data(self):
|
||||
"""A failed startup must mark failure and stop the newly linked units while retaining data."""
|
||||
def fail_start(args, env, check=True):
|
||||
if 'enable' in args and args[-1].endswith('-worker.service'):
|
||||
raise subprocess.CalledProcessError(1, args)
|
||||
return self.fake_command(args, env, check)
|
||||
with patch.object(activate, 'units_directory', return_value=self.unit_dir), patch.object(activate, 'command', side_effect=fail_start), patch.object(activate.os, 'symlink', side_effect=self.fake_symlink):
|
||||
with self.assertRaises(subprocess.CalledProcessError): activate.activate(self.base, self.record, self.env)
|
||||
state = json.loads((self.base / 'installation.json').read_text())
|
||||
self.assertEqual(state['status'], 'activation_failed')
|
||||
self.assertTrue(any(cmd[:4] == ['systemctl', '--user', 'disable', '--now'] for cmd in self.commands))
|
||||
self.assertEqual((self.base / 'data' / 'cacu.db').read_bytes(), b'existing')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Verify bundles export committed trees, excluding working files and Git metadata."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import bundle
|
||||
|
||||
|
||||
def git(repo, *args):
|
||||
return subprocess.run(['git', '-C', str(repo), *args], check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
|
||||
class BundleTests(unittest.TestCase):
|
||||
"""Two small temporary Git repositories model the application and a pinned child."""
|
||||
def test_export_uses_git_objects_and_pinned_nested_checkout(self):
|
||||
"""Uncommitted changes and untracked files cannot enter a release archive."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
app = root / 'ISSSTELEON'
|
||||
child = app / 'WebApi'
|
||||
for repo in (app, child):
|
||||
repo.mkdir(parents=True, exist_ok=True)
|
||||
git(repo, 'init', '--quiet')
|
||||
git(repo, 'config', 'user.name', 'Fixture')
|
||||
git(repo, 'config', 'user.email', 'fixture@example.invalid')
|
||||
tracked = repo / ('Core/tracked.txt' if repo == app else 'tracked.txt')
|
||||
tracked.parent.mkdir(parents=True, exist_ok=True)
|
||||
tracked.write_text('committed', encoding='utf-8')
|
||||
git(repo, 'add', str(tracked.relative_to(repo)))
|
||||
git(repo, 'commit', '-m', 'fixture')
|
||||
manifest = {'ISSSTELEON': git(app, 'rev-parse', 'HEAD'), 'ISSSTELEON/WebApi': git(child, 'rev-parse', 'HEAD')}
|
||||
(child / 'tracked.txt').write_text('modified', encoding='utf-8')
|
||||
(child / 'private.txt').write_text('untracked', encoding='utf-8')
|
||||
output = root / 'bundle.tar.gz'
|
||||
sha = bundle.export(root, manifest, output)
|
||||
self.assertEqual(sha, hashlib.sha256(output.read_bytes()).hexdigest())
|
||||
duplicate = root / 'duplicate.tar.gz'
|
||||
self.assertEqual(bundle.export(root, manifest, duplicate), sha)
|
||||
self.assertEqual(output.read_bytes(), duplicate.read_bytes())
|
||||
with tarfile.open(output) as archive:
|
||||
self.assertEqual(archive.extractfile('application/WebApi/tracked.txt').read(), b'committed')
|
||||
self.assertNotIn('application/WebApi/private.txt', archive.getnames())
|
||||
self.assertFalse(any('.git/' in name for name in archive.getnames()))
|
||||
|
||||
def test_unknown_checkout_is_rejected(self):
|
||||
"""A child checkout at a different SHA cannot be archived under a recorded gitlink."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
repo = Path(tmp) / 'ISSSTELEON'
|
||||
repo.mkdir()
|
||||
git(repo, 'init', '--quiet')
|
||||
git(repo, 'config', 'user.name', 'Fixture')
|
||||
git(repo, 'config', 'user.email', 'fixture@example.invalid')
|
||||
(repo / 'file').write_text('data', encoding='utf-8')
|
||||
git(repo, 'add', 'file')
|
||||
git(repo, 'commit', '-m', 'fixture')
|
||||
with self.assertRaises(ValueError):
|
||||
bundle.export(Path(tmp), {'ISSSTELEON': '0' * 40}, Path(tmp) / 'out.tar.gz')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Test isolated preparation and health verification with temporary release bundles and fake commands."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import install
|
||||
import verify
|
||||
|
||||
|
||||
class InstallerTests(unittest.TestCase):
|
||||
"""A temporary directory represents an empty dedicated installation parent."""
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.bundle = self.root / 'release.tar.gz'
|
||||
with tarfile.open(self.bundle, 'w:gz') as archive:
|
||||
files = [('application/WebApi/pyproject.toml', b'[project]'),
|
||||
('application/WebApi/uv.lock', b''),
|
||||
('application/WebApi/webapi/indicadores_vivos.py', b''),
|
||||
('application/WebApp/package.json', b'{}'),
|
||||
('application/WebApp/package-lock.json', b'{}')]
|
||||
files += [(f'application/Persistance/persistance/{domain}/alembic.ini', b'')
|
||||
for domain in install.DOMAINS]
|
||||
for name, content in files:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(content)
|
||||
archive.addfile(info, io.BytesIO(content))
|
||||
self.digest = hashlib.sha256(self.bundle.read_bytes()).hexdigest()
|
||||
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
|
||||
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
|
||||
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
|
||||
'bundle_sha256': self.digest,
|
||||
'installer_files': {name: 'e' * 64 for name in install.INSTALLER_FILES},
|
||||
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS}}
|
||||
self.account = 'wnnative'
|
||||
self.hostname = socket.gethostname()
|
||||
self.tools = {'uv': '/usr/bin/uv', 'npm': '/usr/bin/npm', 'nginx': '/usr/sbin/nginx'}
|
||||
self.calls = []
|
||||
self.real_check_port = install.check_port
|
||||
self.real_validate_parent = install.validate_parent
|
||||
self.real_validate_service_account = install.validate_service_account
|
||||
self.patches = [patch.object(install, 'validate_parent', return_value=self.root),
|
||||
patch.object(install, 'validate_service_account'),
|
||||
patch.object(install.os, 'geteuid', return_value=1234, create=True),
|
||||
patch.dict(sys.modules, {'pwd': types.SimpleNamespace(getpwuid=lambda uid: types.SimpleNamespace(pw_name=self.account))}),
|
||||
patch.object(install, 'check_port'), patch.object(install, 'run', side_effect=self.fake_run)]
|
||||
for item in self.patches:
|
||||
item.start()
|
||||
self.addCleanup(item.stop)
|
||||
|
||||
def fake_run(self, args, cwd, env):
|
||||
self.calls.append((list(map(str, args)), Path(cwd), dict(env)))
|
||||
if args[1:3] == ['run', 'build']:
|
||||
index = Path(cwd) / 'dist' / 'WebApp' / 'browser' / 'index.html'
|
||||
index.parent.mkdir(parents=True)
|
||||
index.write_text('app', encoding='utf-8')
|
||||
if 'alembic' in args:
|
||||
domain = next(part for part in install.DOMAINS if part in str(args[-3]))
|
||||
self.assertTrue(env[domain.upper() + '_DATABASE_URL'].replace('\\', '/').endswith('/data/' + domain + '.db'))
|
||||
(self.root / 'isssteleon-native-18090' / 'data' / (domain + '.db')).write_bytes(b'migrated')
|
||||
if 'dbt' in args:
|
||||
(Path(args[-1]) / 'manifest.json').write_text('{}', encoding='utf-8')
|
||||
|
||||
def prepare(self, api_port=28090):
|
||||
return install.prepare(self.root, self.record, self.bundle, self.digest, api_port, self.account, self.hostname, self.tools)
|
||||
|
||||
def rebundle(self, workers, *, transformation=True):
|
||||
"""Rewrite the fixture with the requested worker files and its current dbt project, if present."""
|
||||
with tarfile.open(self.bundle, 'r:gz') as archive:
|
||||
members = [(m, archive.extractfile(m).read()) for m in archive.getmembers()
|
||||
if not m.name.startswith('application/WebApi/webapi/')]
|
||||
with tarfile.open(self.bundle, 'w:gz') as archive:
|
||||
for member, content in members:
|
||||
archive.addfile(member, io.BytesIO(content))
|
||||
for worker in workers:
|
||||
info = tarfile.TarInfo(f'application/WebApi/webapi/{worker}.py')
|
||||
archive.addfile(info, io.BytesIO(b''))
|
||||
if transformation and 'recomputation' in workers:
|
||||
for name in ('pyproject.toml', 'dbt_project.yml', 'profiles.yml'):
|
||||
archive.addfile(tarfile.TarInfo(f'application/Transformation/{name}'), io.BytesIO(b''))
|
||||
self.digest = hashlib.sha256(self.bundle.read_bytes()).hexdigest()
|
||||
self.record['bundle_sha256'] = self.digest
|
||||
|
||||
def test_worker_unit_runs_the_bundled_queue_module(self):
|
||||
"""The worker unit runs `webapi.recomputation` when the release has it, the older module otherwise.
|
||||
|
||||
Fails if a current release is refused for lacking the removed module, or the unit names a module the
|
||||
bundle does not contain."""
|
||||
self.rebundle(['recomputation', 'indicadores_vivos'])
|
||||
self.prepare()
|
||||
worker = (self.root / 'isssteleon-native-18090' / 'units' / 'isssteleon-native-18090-worker.service').read_text()
|
||||
self.assertIn('-m webapi.recomputation\n', worker)
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
service_env = (base / 'service.env').read_text()
|
||||
self.assertIn(f'DBT_MANIFEST={base / "data" / "dbt" / "manifest.json"}\n', service_env)
|
||||
args, directory, env = next(call for call in self.calls if 'dbt' in call[0])
|
||||
self.assertIn('--no-introspect', args)
|
||||
self.assertEqual(directory, base / 'application' / 'Transformation')
|
||||
self.assertEqual(env['CAMA_DB_PATH'], str(base / 'data' / 'cama.db'))
|
||||
|
||||
def test_modern_worker_requires_transformation_project(self):
|
||||
"""Reject a current bundle missing dbt inputs before running builds or migrations."""
|
||||
self.rebundle(['recomputation'], transformation=False)
|
||||
with self.assertRaisesRegex(ValueError, 'lacks the Transformation project'):
|
||||
self.prepare()
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_release_gitlinks_support_both_known_shapes(self):
|
||||
"""Keep the kit optional for older releases and fail if any other link appears or is missing."""
|
||||
for paths in (install.REQUIRED_LINKS, install.LEGACY_LINKS):
|
||||
self.record['gitlinks'] = dict.fromkeys(paths, 'd' * 40)
|
||||
install.validate_record(self.record)
|
||||
for paths in (install.REQUIRED_LINKS - {'ISSSTELEON/models'}, install.REQUIRED_LINKS | {'ISSSTELEON/other'}):
|
||||
self.record['gitlinks'] = dict.fromkeys(paths, 'd' * 40)
|
||||
with self.assertRaisesRegex(ValueError, 'unsupported or incomplete gitlinks'):
|
||||
install.validate_record(self.record)
|
||||
|
||||
def test_release_without_a_worker_module_is_refused(self):
|
||||
"""A release with neither worker module stops before any service units are created.
|
||||
|
||||
Fails if the native installer prepares units for a worker that cannot start."""
|
||||
self.rebundle([])
|
||||
with self.assertRaisesRegex(ValueError, 'lacks required locked application components'):
|
||||
self.prepare()
|
||||
self.assertFalse((self.root / 'isssteleon-native-18090' / 'units').exists())
|
||||
|
||||
def test_notebooks_never_run_in_the_api_process(self):
|
||||
"""The native services select the isolated notebook executor, which has no jobs folder here.
|
||||
|
||||
Fails if an uploaded notebook could run unsandboxed in the API process of a native installation."""
|
||||
self.prepare()
|
||||
service_env = (self.root / 'isssteleon-native-18090' / 'service.env').read_text()
|
||||
self.assertIn('NOTEBOOK_EXECUTOR=contenedor\n', service_env)
|
||||
self.assertNotIn('NOTEBOOK_JOBS_DIR', service_env)
|
||||
|
||||
def test_new_installation_prepares_locked_build_migrations_and_units(self):
|
||||
"""A new instance must use locked builds, four isolated databases and three inactive unit files."""
|
||||
result = self.prepare()
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
self.assertEqual(result['status'], 'prepared')
|
||||
self.assertEqual([item[0][1:3] for item in self.calls[:3]], [['sync', '--locked'], ['ci'], ['run', 'build']])
|
||||
self.assertEqual(sum('alembic' in args for args, _, _ in self.calls), 4)
|
||||
guard_index = next(i for i, (args, _, _) in enumerate(self.calls) if args[1:4] == ['run', '--no-sync', 'python'])
|
||||
first_migration = next(i for i, (args, _, _) in enumerate(self.calls) if 'alembic' in args)
|
||||
self.assertLess(guard_index, first_migration)
|
||||
for domain in install.DOMAINS:
|
||||
self.assertEqual((base / 'data' / (domain + '.db')).read_bytes(), b'migrated')
|
||||
self.assertEqual(len(list((base / 'units').glob('*.service'))), 3)
|
||||
api = (base / 'units' / 'isssteleon-native-18090-api.service').read_text()
|
||||
worker = (base / 'units' / 'isssteleon-native-18090-worker.service').read_text()
|
||||
self.assertIn('127.0.0.1:28090', api)
|
||||
self.assertNotIn('User=', api)
|
||||
self.assertIn('WantedBy=default.target', api)
|
||||
self.assertIn('PrivateUsers=true', api)
|
||||
self.assertIn('webapi.indicadores_vivos', worker)
|
||||
self.assertIn('proxy_pass http://127.0.0.1:28090', (base / 'nginx.conf').read_text())
|
||||
self.assertFalse(any('systemctl' in args for args, _, _ in self.calls))
|
||||
|
||||
def test_custom_api_port_reaches_configuration_record_and_health_checks(self):
|
||||
"""The selected API port must drive loopback Gunicorn, nginx, metadata and verification."""
|
||||
self.record['api_port'] = 31001
|
||||
result = self.prepare(31001)
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
self.assertEqual(result['api_port'], 31001)
|
||||
self.assertEqual(json.loads((base / 'installation.json').read_text())['api_port'], 31001)
|
||||
self.assertIn('127.0.0.1:31001', (base / 'units' / 'isssteleon-native-18090-api.service').read_text())
|
||||
self.assertIn('proxy_pass http://127.0.0.1:31001', (base / 'nginx.conf').read_text())
|
||||
urls = []
|
||||
def request(url):
|
||||
urls.append(url)
|
||||
return 200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>'
|
||||
verify.check(dict(result, status='started'), command=lambda *a, **k: types.SimpleNamespace(returncode=0), get=request)
|
||||
self.assertIn('http://127.0.0.1:31001/health', urls)
|
||||
self.assertIn('http://127.0.0.1:18090/health', urls)
|
||||
|
||||
def test_api_port_mismatch_stops_before_creating_instance(self):
|
||||
"""A changed API port must not override the port recorded in the validated release request."""
|
||||
with self.assertRaises(ValueError): self.prepare(31001)
|
||||
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_existing_instance_is_never_overwritten_or_migrated(self):
|
||||
"""A repeated installation must reject the existing directory and preserve data."""
|
||||
self.prepare()
|
||||
marker = self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db'
|
||||
before = marker.read_bytes()
|
||||
call_count = len(self.calls)
|
||||
with self.assertRaises(FileExistsError):
|
||||
self.prepare()
|
||||
self.assertEqual(marker.read_bytes(), before)
|
||||
self.assertEqual(len(self.calls), call_count)
|
||||
|
||||
def test_digest_mismatch_and_port_conflict_stop_before_reservation(self):
|
||||
"""Wrong source integrity or occupied ports must not create an installation directory."""
|
||||
with self.assertRaises(ValueError):
|
||||
install.prepare(self.root, self.record, self.bundle, '0' * 64, 28090, self.account, self.hostname, self.tools)
|
||||
with patch.object(install, 'check_port', side_effect=ValueError('occupied')):
|
||||
with self.assertRaises(ValueError): self.prepare()
|
||||
self.assertFalse((self.root / 'isssteleon-native-18090').exists())
|
||||
|
||||
def test_partial_failure_preserves_data_and_rejects_retry(self):
|
||||
"""A build error must leave a failed record and data rather than erase or reuse it."""
|
||||
with patch.object(install, 'run', side_effect=RuntimeError('build failed')):
|
||||
with self.assertRaises(RuntimeError): self.prepare()
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
state = json.loads((base / 'installation.json').read_text())
|
||||
self.assertEqual(state['status'], 'failed')
|
||||
self.assertTrue((base / 'data' / 'cacu.db').exists())
|
||||
with self.assertRaises(FileExistsError): self.prepare()
|
||||
|
||||
def test_effective_target_guard_executes_and_rejects_mismatch(self):
|
||||
"""The guard must inspect effective settings in a separate Python process without migrating files."""
|
||||
data = self.root / 'guard-data'
|
||||
data.mkdir()
|
||||
for domain in install.DOMAINS:
|
||||
(data / (domain + '.db')).touch()
|
||||
env = dict(os.environ)
|
||||
env.update(install.environment(self.root))
|
||||
for domain in install.DOMAINS:
|
||||
env[domain.upper() + '_DATABASE_URL'] = 'sqlite:///' + str(data / (domain + '.db'))
|
||||
captured = []
|
||||
with patch.object(install, 'run', side_effect=lambda args, cwd, env: captured.append(args)):
|
||||
install.verify_database_targets('/usr/bin/uv', self.root, env, data)
|
||||
code = captured[0][-2]
|
||||
bootstrap = """import os, sys, types
|
||||
root = types.ModuleType('persistance')
|
||||
settings_module = types.ModuleType('persistance.settings')
|
||||
settings_module.settings = types.SimpleNamespace(**{d + '_database_url': os.environ[d.upper() + '_DATABASE_URL'] for d in ('cacu','cama','tea','governance')})
|
||||
if os.environ.get('FIXTURE_MISMATCH'):
|
||||
settings_module.settings.cacu_database_url = 'sqlite:////outside/data.db'
|
||||
sys.modules['persistance'] = root
|
||||
sys.modules['persistance.settings'] = settings_module
|
||||
sqlalchemy = types.ModuleType('sqlalchemy')
|
||||
engine = types.ModuleType('sqlalchemy.engine')
|
||||
engine.make_url = lambda url: types.SimpleNamespace(drivername='sqlite', database=url[len('sqlite:///'):])
|
||||
sys.modules['sqlalchemy'] = sqlalchemy
|
||||
sys.modules['sqlalchemy.engine'] = engine
|
||||
"""
|
||||
ok = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
|
||||
self.assertEqual(ok.returncode, 0, ok.stderr)
|
||||
mismatch = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=dict(env, FIXTURE_MISMATCH='1'), capture_output=True)
|
||||
self.assertNotEqual(mismatch.returncode, 0)
|
||||
(data / 'tea.db').write_bytes(b'existing')
|
||||
occupied = subprocess.run([sys.executable, '-c', bootstrap + code, str(data)], env=env, capture_output=True)
|
||||
self.assertNotEqual(occupied.returncode, 0)
|
||||
self.assertEqual((data / 'tea.db').read_bytes(), b'existing')
|
||||
|
||||
def test_effective_target_guard_failure_blocks_all_migrations(self):
|
||||
"""An application settings mismatch must stop the installer before any Alembic command."""
|
||||
def reject_guard(args, cwd, env):
|
||||
self.fake_run(args, cwd, env)
|
||||
if args[1:4] == ['run', '--no-sync', 'python']:
|
||||
raise RuntimeError('effective database URL mismatch')
|
||||
with patch.object(install, 'run', side_effect=reject_guard), self.assertRaises(RuntimeError):
|
||||
self.prepare()
|
||||
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
|
||||
record = json.loads((self.root / 'isssteleon-native-18090' / 'installation.json').read_text())
|
||||
self.assertEqual(record['phase'], 'verifying_migration_targets')
|
||||
self.assertEqual(record['status'], 'failed')
|
||||
|
||||
def test_migration_rejects_nonempty_target(self):
|
||||
"""Unexpected existing database contents must stop migrations rather than touch the data."""
|
||||
def inject(args, cwd, env):
|
||||
self.fake_run(args, cwd, env)
|
||||
if args[1:3] == ['run', 'build']:
|
||||
(self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').write_bytes(b'existing')
|
||||
with patch.object(install, 'run', side_effect=inject), self.assertRaises(ValueError): self.prepare()
|
||||
self.assertEqual((self.root / 'isssteleon-native-18090' / 'data' / 'cacu.db').read_bytes(), b'existing')
|
||||
self.assertFalse(any('alembic' in args for args, _, _ in self.calls))
|
||||
|
||||
def test_install_parent_must_be_private_and_account_owned(self):
|
||||
"""A parent writable by another account cannot hold a trusted fresh installation."""
|
||||
for owner, mode in [(9999, 0o750), (1234, 0o770), (1234, 0o757)]:
|
||||
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=owner, st_mode=mode))
|
||||
with self.subTest(owner=owner, mode=mode), self.assertRaises(ValueError):
|
||||
install.require_private_parent(parent)
|
||||
parent = types.SimpleNamespace(stat=lambda: types.SimpleNamespace(st_uid=1234, st_mode=0o750))
|
||||
install.require_private_parent(parent)
|
||||
|
||||
def test_privileged_service_group_memberships_are_rejected(self):
|
||||
"""Reject Docker, sudo and root group membership even for non-root accounts."""
|
||||
user = types.SimpleNamespace(pw_name=self.account, pw_gid=1001)
|
||||
fake_pwd = types.SimpleNamespace(getpwuid=lambda uid: user)
|
||||
fake_grp = types.SimpleNamespace(getgrnam=lambda name: types.SimpleNamespace(gr_gid={'docker': 998, 'sudo': 27, 'wheel': 10}[name]))
|
||||
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001, 998], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
|
||||
with self.assertRaises(ValueError): install.validate_service_account(self.account)
|
||||
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[27], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
|
||||
with self.assertRaises(ValueError): install.validate_service_account(self.account)
|
||||
with patch.dict(sys.modules, {'pwd': fake_pwd, 'grp': fake_grp}), patch.object(install.os, 'geteuid', return_value=1001, create=True), patch.object(install.os, 'getegid', return_value=1001, create=True), patch.object(install.os, 'getgroups', return_value=[1001], create=True), patch.object(install.os, 'getgrouplist', return_value=[1001], create=True), patch.object(install, 'validate_service_account', wraps=self.real_validate_service_account):
|
||||
install.validate_service_account(self.account)
|
||||
|
||||
def test_host_mismatch_and_docker_root_are_rejected(self):
|
||||
"""An unexpected host or Docker data parent cannot receive an installation."""
|
||||
with self.assertRaises(ValueError):
|
||||
install.prepare(self.root, self.record, self.bundle, self.digest, 28090, self.account, 'different-host', self.tools)
|
||||
parent = self.root / 'docker'
|
||||
parent.mkdir()
|
||||
import re
|
||||
real_validate_parent = self.real_validate_parent
|
||||
with patch.object(install, 'SAFE_PATH', re.compile(r'^.+$')), patch.object(install, 'DOCKER_ROOT', parent), patch.object(install, 'validate_parent', wraps=real_validate_parent):
|
||||
with self.assertRaises(ValueError): install.validate_parent(parent)
|
||||
self.assertFalse((parent / 'isssteleon-native-18090').exists())
|
||||
|
||||
def test_archive_rejects_traversal_and_links(self):
|
||||
"""Archive extraction must reject paths and links that escape the fresh instance."""
|
||||
for name, member_type in [('../escape', tarfile.REGTYPE), ('application/link', tarfile.SYMTYPE)]:
|
||||
path = self.root / ('bad-' + str(member_type[0]) + '.tar.gz')
|
||||
with tarfile.open(path, 'w:gz') as archive:
|
||||
info = tarfile.TarInfo(name)
|
||||
info.type = member_type
|
||||
if member_type == tarfile.SYMTYPE: info.linkname = '/tmp'
|
||||
archive.addfile(info)
|
||||
with self.subTest(name=name), self.assertRaises(ValueError):
|
||||
install.extract_bundle(path, self.root / 'extract')
|
||||
self.assertFalse((self.root / 'escape').exists())
|
||||
|
||||
def test_socket_conflict_detection(self):
|
||||
"""A real loopback listener must prevent the installer from using the same API port."""
|
||||
with socket.socket() as listener:
|
||||
listener.bind(('127.0.0.1', 0))
|
||||
listener.listen()
|
||||
with patch.object(install, 'check_port', wraps=self.real_check_port):
|
||||
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], False)
|
||||
with socket.socket() as listener:
|
||||
listener.bind(('0.0.0.0', 0))
|
||||
listener.listen()
|
||||
with patch.object(install, 'check_port', wraps=self.real_check_port):
|
||||
with self.assertRaises(ValueError): install.check_port(listener.getsockname()[1], True)
|
||||
|
||||
def test_failed_verification_is_recorded_and_can_be_retried(self):
|
||||
"""A startup failure remains visible in the record and permits another health check."""
|
||||
record = dict(self.prepare(), status='started')
|
||||
base = self.root / 'isssteleon-native-18090'
|
||||
(base / 'installation.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
with patch.object(sys, 'argv', ['verify.py', str(base), '--wait-seconds', '0']), patch.object(verify.activate, 'manager_environment', return_value={}), patch.object(verify, 'check', side_effect=ValueError('service failed')):
|
||||
self.assertEqual(verify.main(), 1)
|
||||
record = json.loads((base / 'installation.json').read_text())
|
||||
self.assertEqual(record['status'], 'verification_failed')
|
||||
self.assertIn('service failed', record['health']['error'])
|
||||
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
|
||||
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
|
||||
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
|
||||
|
||||
def test_health_requires_all_services_and_spa_fallback(self):
|
||||
"""Health fails if a unit is inactive or proxy and SPA checks do not match."""
|
||||
record = dict(self.prepare(), status='started')
|
||||
ok = lambda *args, **kwargs: types.SimpleNamespace(returncode=0)
|
||||
get = lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else b'<html>app</html>')
|
||||
self.assertEqual(verify.check(record, command=ok, get=get)['proxy_health'], 'ok')
|
||||
with self.assertRaises(ValueError):
|
||||
verify.check(record, command=lambda *a, **k: types.SimpleNamespace(returncode=3), get=get)
|
||||
with self.assertRaises(ValueError):
|
||||
verify.check(record, command=ok, get=lambda url: (200, b'{"status":"ok"}' if url.endswith('/health') else url.encode()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Test explicit, pinned-key SSH preparation with synthetic artifacts and no network."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import install
|
||||
import remote
|
||||
|
||||
|
||||
class RemoteTests(unittest.TestCase):
|
||||
"""Local fake files and mocked processes represent an authorized operator channel."""
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.dir = self.root / 'bundle'
|
||||
self.dir.mkdir()
|
||||
for name in install.INSTALLER_FILES:
|
||||
(self.dir / name).write_bytes(('content:' + name).encode())
|
||||
(self.dir / 'release-source.tar.gz').write_bytes(b'archive')
|
||||
self.sha = hashlib.sha256(b'archive').hexdigest()
|
||||
self.record = {'tag': 'v1', 'release_id': 1, 'public_port': 18090, 'api_port': 28090,
|
||||
'application_sha': 'a' * 40, 'installer_sha': 'b' * 40,
|
||||
'tag_object': 'c' * 40, 'installer_ref': 'refs/heads/dev',
|
||||
'bundle_sha256': self.sha,
|
||||
'gitlinks': {name: 'd' * 40 for name in install.REQUIRED_LINKS},
|
||||
'installer_files': {name: install.digest(self.dir / name) for name in install.INSTALLER_FILES}}
|
||||
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
|
||||
self.key = self.root / 'identity'
|
||||
self.known = self.root / 'known_hosts'
|
||||
self.key.write_text('fixture')
|
||||
self.known.write_text('fixture')
|
||||
|
||||
def call(self, host='10.0.10.41', account='wnnative', api_port=28090):
|
||||
return remote.prepare(self.dir, self.sha, host, 22, account, 'labserver',
|
||||
'/srv/workingnarrative-native', api_port, self.key, self.known)
|
||||
|
||||
def test_only_explicit_nonprivileged_ssh_and_pinned_host_keys(self):
|
||||
"""Preparation uses strict host-key checks and never invokes sudo or systemctl."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public') as public:
|
||||
stage = self.call()
|
||||
self.assertTrue(stage.startswith('/srv/workingnarrative-native/.release-'))
|
||||
self.assertEqual(run.call_count, 6)
|
||||
public.assert_called_once_with('10.0.10.41', 18090)
|
||||
for call in run.call_args_list:
|
||||
args = call.args[0]
|
||||
self.assertIn('StrictHostKeyChecking=yes', args)
|
||||
self.assertIn('BatchMode=yes', args)
|
||||
self.assertNotIn('sudo', args)
|
||||
self.assertNotIn('systemctl', args)
|
||||
self.assertIn('install.py', str(run.call_args_list[2]))
|
||||
self.assertIn('activate.py', str(run.call_args_list[3]))
|
||||
self.assertIn('--public-result ok', str(run.call_args_list[-1]))
|
||||
|
||||
def test_requested_api_port_is_transferred_and_mismatch_rejected(self):
|
||||
"""SSH must pass the exact recorded API port and reject any altered value before connection."""
|
||||
with patch.object(remote.subprocess, 'run') as run:
|
||||
with self.assertRaises(ValueError): self.call(api_port=31001)
|
||||
run.assert_not_called()
|
||||
self.record['api_port'] = 31001
|
||||
(self.dir / 'release-record.json').write_text(json.dumps(self.record), encoding='utf-8')
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public'):
|
||||
self.call(api_port=31001)
|
||||
self.assertIn('--api-port 31001', str(run.call_args_list[2]))
|
||||
|
||||
def test_bad_endpoint_or_tampered_installer_never_connects(self):
|
||||
"""Unsafe endpoint syntax or altered installer scripts must fail before SSH."""
|
||||
with patch.object(remote.subprocess, 'run') as run:
|
||||
with self.assertRaises(ValueError): self.call(host='host;evil')
|
||||
with self.assertRaises(ValueError): self.call(account='root')
|
||||
(self.dir / 'install.py').write_text('tampered', encoding='utf-8')
|
||||
with self.assertRaises(ValueError): self.call()
|
||||
run.assert_not_called()
|
||||
|
||||
def test_public_failure_fails_action_and_records_failure(self):
|
||||
"""An unreachable public endpoint must report failure instead of a successful deployment."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run') as run, patch.object(remote, 'check_public', side_effect=ValueError('unreachable')):
|
||||
with self.assertRaises(ValueError): self.call()
|
||||
self.assertIn('--public-result failed', str(run.call_args_list[-1]))
|
||||
self.assertFalse(run.call_args_list[-1].kwargs['check'])
|
||||
|
||||
def test_activation_failure_prevents_public_success(self):
|
||||
"""A failed service activation must stop before any public health check."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=[None, None, None, subprocess.CalledProcessError(1, 'ssh')]), patch.object(remote, 'check_public') as public:
|
||||
with self.assertRaises(subprocess.CalledProcessError): self.call()
|
||||
public.assert_not_called()
|
||||
|
||||
def test_public_probe_rejects_bad_health(self):
|
||||
"""The public endpoint must serve both the WebApp and a healthy proxied API."""
|
||||
responses = [(200, b'{"status":"ok"}'), (200, b'<html>app</html>')]
|
||||
with patch.object(remote.verify, 'request', side_effect=responses):
|
||||
remote.check_public('10.0.10.41', 18090, timeout=0)
|
||||
with patch.object(remote.verify, 'request', side_effect=[(200, b'{"status":"bad"}'), (200, b'app')]):
|
||||
with self.assertRaises(ValueError): remote.check_public('10.0.10.41', 18090, timeout=0)
|
||||
|
||||
def test_failed_remote_identity_check_never_uploads(self):
|
||||
"""A failed remote guard must prevent copying or executing the installer."""
|
||||
with patch.object(remote.shutil, 'which', side_effect=lambda name: '/usr/bin/' + name), patch.object(remote.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'ssh')) as run:
|
||||
with self.assertRaises(subprocess.CalledProcessError): self.call()
|
||||
self.assertEqual(run.call_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Exercise release identity and fail-closed behavior using temporary Git repositories and fake API responses."""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
spec = importlib.util.spec_from_file_location('resolve', Path(__file__).with_name('resolve.py'))
|
||||
resolver = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(resolver)
|
||||
|
||||
|
||||
def command(*args, cwd):
|
||||
return subprocess.run(args, cwd=cwd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
|
||||
class ResolutionTests(unittest.TestCase):
|
||||
"""A bare local origin stands in for the institutional repository."""
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
root = Path(self.temp.name)
|
||||
self.origin = root / 'origin.git'
|
||||
self.repo = root / 'repo'
|
||||
command('git', 'init', '--bare', str(self.origin), cwd=root)
|
||||
command('git', 'init', str(self.repo), cwd=root)
|
||||
command('git', 'config', 'user.name', 'Test', cwd=self.repo)
|
||||
command('git', 'config', 'user.email', 'test@example.invalid', cwd=self.repo)
|
||||
(self.repo / 'file').write_text('test', encoding='utf-8')
|
||||
command('git', 'add', 'file', cwd=self.repo)
|
||||
command('git', 'commit', '-m', 'initial', cwd=self.repo)
|
||||
self.sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
command('git', 'remote', 'add', 'origin', str(self.origin), cwd=self.repo)
|
||||
command('git', 'tag', '-a', 'v1', '-m', 'release', cwd=self.repo)
|
||||
command('git', 'push', 'origin', 'refs/tags/v1', cwd=self.repo)
|
||||
self.env = {'DISPATCH_REF': 'refs/heads/dev', 'DISPATCH_REF_NAME': 'dev',
|
||||
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_SHA': self.sha,
|
||||
'DISPATCH_REPOSITORY': resolver.REPOSITORY, 'DISPATCH_SERVER': resolver.SERVER,
|
||||
'RELEASE_TOKEN': 'test'}
|
||||
|
||||
def test_annotated_tag_resolves_to_commit_and_preserves_installer_identity(self):
|
||||
"""Peeling must return the commit while retaining the distinct tag object and installer revision."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
|
||||
record = resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
|
||||
self.assertEqual(record['application_sha'], self.sha)
|
||||
self.assertEqual(record['installer_sha'], self.sha)
|
||||
self.assertNotEqual(record['tag_object'], self.sha)
|
||||
self.assertEqual(record['release_id'], 7)
|
||||
self.assertEqual(record['public_port'], 18090)
|
||||
self.assertEqual(record['api_port'], 28090)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_invalid_or_missing_tags_and_ports_fail(self):
|
||||
"""Invalid inputs and absent remote refs must fail before they can identify a deployment."""
|
||||
for tag in ('', '-x', 'refs/tags/v1', 'bad..tag', 'a' * 40):
|
||||
with self.subTest(tag=tag), self.assertRaises((ValueError, subprocess.CalledProcessError)):
|
||||
resolver.validate_tag(tag)
|
||||
for port in ('0', '65536', 'abc'):
|
||||
with self.subTest(port=port), self.assertRaises(ValueError):
|
||||
resolver.validate_port(port)
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'missing'}):
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
resolver.resolve(self.repo, 'missing', '18090', '28090', self.env)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_custom_public_and_api_ports_are_recorded(self):
|
||||
"""The release record must retain both operator-selected ports without replacing either default."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
|
||||
record = resolver.resolve(self.repo, 'v1', '18123', '31001', self.env)
|
||||
self.assertEqual(record['public_port'], 18123)
|
||||
self.assertEqual(record['api_port'], 31001)
|
||||
|
||||
def test_both_requested_ports_are_validated_before_release_lookup(self):
|
||||
"""Invalid, privileged, oversized or equal ports must fail before any network access."""
|
||||
requests = [('0', '28090'), ('65536', '28090'), ('18090', '0'),
|
||||
('18090', '65536'), ('18090', 'abc'), ('18090', '18090')]
|
||||
with patch.object(resolver, 'dispatch') as dispatch, patch.object(resolver, 'release') as release:
|
||||
for public, api in requests:
|
||||
with self.subTest(public=public, api=api), self.assertRaises(ValueError):
|
||||
resolver.resolve(self.repo, 'v1', public, api, self.env)
|
||||
dispatch.assert_not_called()
|
||||
release.assert_not_called()
|
||||
|
||||
def test_wrong_identity_is_rejected(self):
|
||||
"""External repository, server and checkout identities cannot authorize resolution."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)):
|
||||
for key, value in [('DISPATCH_REPOSITORY', 'other/repo'), ('DISPATCH_SERVER', 'http://evil'), ('DISPATCH_SHA', '0' * 40)]:
|
||||
with self.subTest(key=key), self.assertRaises(ValueError):
|
||||
resolver.dispatch(self.repo, dict(self.env, **{key: value}))
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.dispatch(self.repo, self.env)
|
||||
|
||||
def test_release_change_fails_and_cleans_temporary_ref(self):
|
||||
"""A changed release cannot pass the second check and failure removes its temporary ref."""
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', side_effect=[{'release_id': 7, 'tag': 'v1'}, {'release_id': 8, 'tag': 'v1'}]):
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_source_preparation_uses_selected_commit_in_a_disposable_tree(self):
|
||||
"""Source preparation must retain the installer checkout and discard temporary application files."""
|
||||
tag_object = command('git', 'rev-parse', 'refs/tags/v1', cwd=self.repo)
|
||||
record = {'tag': 'v1', 'tag_object': tag_object, 'application_sha': self.sha}
|
||||
captured = []
|
||||
def inspect(checkout):
|
||||
captured.append(checkout)
|
||||
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=checkout), self.sha)
|
||||
return {'ISSSTELEON': 'a' * 40}
|
||||
with patch.object(resolver.source, 'checkout_pinned', side_effect=inspect):
|
||||
self.assertEqual(resolver.prepare_source(self.repo, record), {'ISSSTELEON': 'a' * 40})
|
||||
self.assertFalse(captured[0].exists())
|
||||
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), self.sha)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_source_preparation_rejects_changed_tag(self):
|
||||
"""A tag that changes between resolution and source checkout cannot reach submodule preparation."""
|
||||
record = {'tag': 'v1', 'tag_object': '0' * 40, 'application_sha': self.sha}
|
||||
with patch.object(resolver.source, 'checkout_pinned') as checkout:
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.prepare_source(self.repo, record)
|
||||
checkout.assert_not_called()
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_remote_tag_change_fails_closed(self):
|
||||
"""A tag moved after fetch must not be used even if the release remains published."""
|
||||
original_git = resolver.git
|
||||
def changed_git(root, *args):
|
||||
if args[0] == 'ls-remote':
|
||||
return '0' * 40 + '\trefs/tags/v1'
|
||||
return original_git(root, *args)
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver, 'git', side_effect=changed_git):
|
||||
with self.assertRaises(ValueError):
|
||||
resolver.resolve(self.repo, 'v1', '18090', '28090', self.env)
|
||||
self.assertEqual(command('git', 'for-each-ref', '--format=%(refname)', 'refs/deploy-terminal', cwd=self.repo), '')
|
||||
|
||||
def test_application_and_installer_commits_are_independent(self):
|
||||
"""A release can point to an older commit without changing the installer checkout."""
|
||||
(self.repo / 'file').write_text('installer', encoding='utf-8')
|
||||
command('git', 'commit', '-am', 'installer', cwd=self.repo)
|
||||
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
env = dict(self.env, DISPATCH_SHA=installer_sha)
|
||||
with patch.object(resolver, 'ORIGIN', str(self.origin)), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}):
|
||||
record = resolver.resolve(self.repo, 'v1', '18090', '28090', env)
|
||||
self.assertEqual(record['application_sha'], self.sha)
|
||||
self.assertEqual(record['installer_sha'], installer_sha)
|
||||
self.assertEqual(command('git', 'rev-parse', 'HEAD', cwd=self.repo), installer_sha)
|
||||
|
||||
def test_installer_files_match_dispatched_commit(self):
|
||||
"""Every transferred installer script must be the committed installer revision."""
|
||||
directory = self.repo / '.gitea' / 'deploy-terminal'
|
||||
directory.mkdir(parents=True)
|
||||
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
|
||||
(directory / name).write_bytes(('fixture ' + name).encode())
|
||||
command('git', 'add', '.gitea', cwd=self.repo)
|
||||
command('git', 'commit', '-m', 'installer', cwd=self.repo)
|
||||
sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
self.assertEqual(len(resolver.installer_manifest(self.repo, sha)), 6)
|
||||
(directory / 'install.py').write_text('modified', encoding='utf-8')
|
||||
with self.assertRaises(ValueError): resolver.installer_manifest(self.repo, sha)
|
||||
|
||||
def test_manual_workflow_prepares_bundle_and_release_record(self):
|
||||
"""A manual dispatch must publish the resolved identity and source digest together."""
|
||||
directory = self.repo / '.gitea' / 'deploy-terminal'
|
||||
directory.mkdir(parents=True)
|
||||
for name in ('install.py', 'activate.py', 'verify.py', 'remote.py', 'bundle.py', 'source.py'):
|
||||
(directory / name).write_bytes(('fixture ' + name).encode())
|
||||
command('git', 'add', '.gitea', cwd=self.repo)
|
||||
command('git', 'commit', '-m', 'installer', cwd=self.repo)
|
||||
installer_sha = command('git', 'rev-parse', 'HEAD', cwd=self.repo)
|
||||
output = self.repo.parent / 'artifact' / 'release-source.tar.gz'
|
||||
output.parent.mkdir()
|
||||
env = dict(self.env, DISPATCH_SHA=installer_sha, REQUESTED_TAG='v1', REQUESTED_PORT='18090', REQUESTED_API_PORT='28090', RELEASE_OUTPUT=str(output))
|
||||
links = {'ISSSTELEON': 'a' * 40}
|
||||
def export(checkout, manifest, path):
|
||||
Path(path).write_bytes(b'fixture bundle')
|
||||
return 'd' * 64
|
||||
with patch.object(resolver, 'ROOT', self.repo), patch.object(resolver, 'ORIGIN', str(self.origin)), patch.dict(os.environ, env), patch.object(resolver, 'release', return_value={'release_id': 7, 'tag': 'v1'}), patch.object(resolver.source, 'checkout_pinned', return_value=links), patch.object(resolver.bundle, 'export', side_effect=export):
|
||||
self.assertEqual(resolver.main(), 0)
|
||||
record = json.loads((output.parent / 'release-record.json').read_text())
|
||||
self.assertEqual(record['installer_sha'], installer_sha)
|
||||
self.assertEqual(record['application_sha'], self.sha)
|
||||
self.assertEqual(record['api_port'], 28090)
|
||||
self.assertEqual(record['gitlinks'], links)
|
||||
self.assertEqual(record['bundle_sha256'], 'd' * 64)
|
||||
self.assertEqual(len(record['installer_files']), 6)
|
||||
|
||||
def test_publication_is_rechecked_after_packaging(self):
|
||||
"""A release or tag changed during archive creation must not produce an artifact record."""
|
||||
record = {'tag': 'v1', 'tag_object': 'a' * 40, 'release_id': 7}
|
||||
with patch.object(resolver, 'git', return_value='b' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release') as release:
|
||||
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
|
||||
release.assert_not_called()
|
||||
with patch.object(resolver, 'git', return_value='a' * 40 + '\trefs/tags/v1'), patch.object(resolver, 'release', return_value={'tag': 'v1', 'release_id': 8}):
|
||||
with self.assertRaises(ValueError): resolver.revalidate(self.repo, record, 'token')
|
||||
|
||||
def test_release_metadata_must_be_published_and_match_tag(self):
|
||||
"""Drafts, missing publication times and mismatched tags must not qualify as published releases."""
|
||||
class Response:
|
||||
def __init__(self, data): self.data = json.dumps(data).encode()
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *args): pass
|
||||
def read(self, *args): return self.data
|
||||
class Opener:
|
||||
def __init__(self, data): self.data = data
|
||||
def open(self, req, timeout): return Response(self.data)
|
||||
good = {'id': 1, 'tag_name': 'v1', 'draft': False, 'published_at': '2026-01-01T00:00:00Z'}
|
||||
for change in ({'draft': True}, {'published_at': None}, {'tag_name': 'v2'}, {'id': True}):
|
||||
with self.subTest(change=change), patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(dict(good, **change))):
|
||||
with self.assertRaises(ValueError): resolver.release('v1', 'token')
|
||||
with patch.object(resolver.urllib.request, 'build_opener', return_value=Opener(good)):
|
||||
self.assertEqual(resolver.release('v1', 'token')['release_id'], 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Check pinned application traversal with synthetic Git-tree and configuration fixtures."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
import os
|
||||
import types
|
||||
from unittest.mock import patch
|
||||
import source
|
||||
|
||||
|
||||
class SourceTests(unittest.TestCase):
|
||||
"""A mocked Git interface models one outer and one nested application repository."""
|
||||
def setUp(self):
|
||||
self.a, self.b = 'a' * 40, 'b' * 40
|
||||
self.outer = Path('/fixture')
|
||||
self.application = self.outer / 'ISSSTELEON'
|
||||
self.api = self.application / 'WebApi'
|
||||
self.calls = []
|
||||
|
||||
def fake_git(self, repo, *args, binary=False):
|
||||
repo = Path(repo)
|
||||
self.calls.append((repo, args))
|
||||
if args[:1] == ('ls-tree',):
|
||||
if repo == self.outer:
|
||||
return (f'160000 commit {self.a}\tISSSTELEON\0' + f'160000 commit {self.b}\tdev-data\0').encode()
|
||||
if repo == self.application:
|
||||
return f'160000 commit {self.b}\tWebApi\0'.encode()
|
||||
return b''
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get-regexp'):
|
||||
return 'submodule.ISSSTELEON.path ISSSTELEON' if repo == self.outer else 'submodule.WebApi.path WebApi'
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
|
||||
name = 'ISSSTELEON' if repo == self.outer else 'WebApi'
|
||||
return 'ssh://git@10.0.10.41:2222/ISSSTELEON/' + name + '.git'
|
||||
if args[:2] == ('rev-parse', 'HEAD'):
|
||||
return self.a if repo == self.application else self.b
|
||||
return ''
|
||||
|
||||
def test_institutional_git_auth_is_scoped_and_not_in_command(self):
|
||||
"""Private nested Git fetches use a host-scoped job token without exposing it in arguments."""
|
||||
env = {'RELEASE_TOKEN': 'fixture-token', 'GIT_CONFIG_COUNT': '1',
|
||||
'GIT_CONFIG_KEY_0': 'url.http://10.0.10.41:3000/ISSSTELEON/.insteadOf',
|
||||
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/'}
|
||||
with patch.dict(os.environ, env, clear=True), patch.object(source.subprocess, 'run', return_value=types.SimpleNamespace(stdout='result')) as run:
|
||||
self.assertEqual(source.git(self.outer, 'status'), 'result')
|
||||
args, kwargs = run.call_args
|
||||
self.assertNotIn('fixture-token', str(args))
|
||||
self.assertEqual(kwargs['env']['GIT_CONFIG_COUNT'], '2')
|
||||
self.assertEqual(kwargs['env']['GIT_CONFIG_KEY_1'], 'http.http://10.0.10.41:3000/ISSSTELEON/.extraheader')
|
||||
self.assertEqual(kwargs['env']['GIT_TERMINAL_PROMPT'], '0')
|
||||
|
||||
def test_nested_links_are_pinned_and_unrelated_tree_is_ignored(self):
|
||||
"""Traverse the application link and its nested link without touching dev-data."""
|
||||
with patch.object(source, 'git', side_effect=self.fake_git):
|
||||
result = source.checkout_pinned(self.outer)
|
||||
self.assertEqual(result, {'ISSSTELEON': self.a, 'ISSSTELEON/WebApi': self.b})
|
||||
self.assertFalse(any('dev-data' in str(args) for _, args in self.calls if '--checkout' in args))
|
||||
self.assertTrue(all('--checkout' in args for _, args in self.calls if 'update' in args))
|
||||
|
||||
def test_external_origin_is_rejected(self):
|
||||
"""An external submodule URL must fail before Git can initialize it."""
|
||||
def fake(repo, *args, **kwargs):
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
|
||||
return 'https://outside.invalid/repo.git'
|
||||
return self.fake_git(repo, *args, **kwargs)
|
||||
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
|
||||
source.checkout_pinned(self.outer)
|
||||
self.assertFalse(any('--checkout' in args for _, args in self.calls))
|
||||
|
||||
def library_git(self, library_url):
|
||||
"""`fake_git` with models pinned below the application and the EEG library pinned below models."""
|
||||
models, library = self.application / 'models', self.application / 'models' / 'libs' / 'tea'
|
||||
c = 'c' * 40
|
||||
|
||||
def fake(repo, *args, **kwargs):
|
||||
repo = Path(repo)
|
||||
self.calls.append((repo, args))
|
||||
if args[:1] == ('ls-tree',):
|
||||
links = {self.outer: f'160000 commit {self.a}\tISSSTELEON\0',
|
||||
self.application: f'160000 commit {self.b}\tmodels\0', models: f'160000 commit {c}\tlibs/tea\0'}
|
||||
return links.get(repo, '').encode()
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get-regexp'):
|
||||
return {self.outer: 'submodule.ISSSTELEON.path ISSSTELEON',
|
||||
self.application: 'submodule.models.path models'}.get(repo, 'submodule.tea.path libs/tea')
|
||||
if args[:4] == ('config', '-f', '.gitmodules', '--get'):
|
||||
return {self.outer: 'ssh://git@10.0.10.41:2222/ISSSTELEON/ISSSTELEON.git',
|
||||
self.application: 'ssh://git@10.0.10.41:2222/ISSSTELEON/models.git'}.get(repo, library_url)
|
||||
if args[:2] == ('rev-parse', 'HEAD'):
|
||||
return {self.application: self.a, models: self.b, library: c}[repo]
|
||||
return ''
|
||||
return fake
|
||||
|
||||
def test_the_eeg_library_is_pinned_from_alberto_tea(self):
|
||||
"""Fails if the library below models stops being initialised from its own origin, alberto/tea."""
|
||||
with patch.object(source, 'git', side_effect=self.library_git('ssh://git@10.0.10.41:2222/alberto/tea.git')):
|
||||
result = source.checkout_pinned(self.outer)
|
||||
self.assertEqual(result['ISSSTELEON/models/libs/tea'], 'c' * 40)
|
||||
|
||||
def test_the_eeg_library_from_another_repository_is_rejected(self):
|
||||
"""Fails if trusting alberto/tea lets any other repository of that owner through."""
|
||||
with patch.object(source, 'git', side_effect=self.library_git('ssh://git@10.0.10.41:2222/alberto/other.git')):
|
||||
with self.assertRaisesRegex(ValueError, 'untrusted submodule origin'):
|
||||
source.checkout_pinned(self.outer)
|
||||
self.assertFalse(any('libs/tea' in args for _, args in self.calls if '--checkout' in args))
|
||||
|
||||
def test_wrong_nested_checkout_is_rejected(self):
|
||||
"""A nested checkout that differs from its gitlink must stop preparation."""
|
||||
def fake(repo, *args, **kwargs):
|
||||
if Path(repo) == self.api and args[:2] == ('rev-parse', 'HEAD'):
|
||||
return 'c' * 40
|
||||
return self.fake_git(repo, *args, **kwargs)
|
||||
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
|
||||
source.checkout_pinned(self.outer)
|
||||
|
||||
def test_unknown_nested_gitlink_is_rejected(self):
|
||||
"""Unrecognized nested repositories must never be initialized implicitly."""
|
||||
def fake(repo, *args, **kwargs):
|
||||
if Path(repo) == self.application and args[:1] == ('ls-tree',):
|
||||
return f'160000 commit {self.b}\tUnknown\0'.encode()
|
||||
return self.fake_git(repo, *args, **kwargs)
|
||||
with patch.object(source, 'git', side_effect=fake), self.assertRaises(ValueError):
|
||||
source.checkout_pinned(self.outer)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Protect the manual workflow's deployment chain and Docker independence."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
WORKFLOW = ROOT / '.gitea' / 'workflows' / 'deploy-terminal-release.yml'
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
"""Inspect the checked-in native workflow and its commands."""
|
||||
def test_workflow_dispatch_builds_and_executes_host_deployment(self):
|
||||
"""A manual dispatch must resolve first and invoke the automated host helper."""
|
||||
text = WORKFLOW.read_text(encoding='utf-8')
|
||||
self.assertIn('workflow_dispatch:', text)
|
||||
inputs = text.split(' inputs:', 1)[1].split('\njobs:', 1)[0]
|
||||
self.assertEqual(set(re.findall(r'^ ([a-z_]+):$', inputs, re.MULTILINE)), {'tag', 'puerto', 'puerto_api'})
|
||||
self.assertRegex(inputs, r"puerto_api:\s+description:[^\n]+\s+required: true\s+default: '28090'")
|
||||
self.assertNotIn('release:', text)
|
||||
self.assertIn('tag:', text)
|
||||
self.assertIn('puerto:', text)
|
||||
self.assertIn('puerto_api:', text)
|
||||
self.assertIn('inputs.puerto_api', text)
|
||||
self.assertIn('--api-port "$REQUESTED_API_PORT"', text)
|
||||
self.assertNotIn('NATIVE_API_PORT', text)
|
||||
self.assertLess(text.index('resolve.py'), text.index('remote.py \\'))
|
||||
self.assertIn('--host 10.0.10.41', text)
|
||||
self.assertIn('secrets.NATIVE_SSH_KEY', text)
|
||||
self.assertIn('secrets.NATIVE_KNOWN_HOSTS', text)
|
||||
self.assertNotIn('sudo ', text)
|
||||
|
||||
def test_native_workflow_does_not_call_docker_installer(self):
|
||||
"""Fail if the native workflow invokes Docker or delegates to the DEV installer."""
|
||||
text = WORKFLOW.read_text(encoding='utf-8')
|
||||
self.assertNotIn('.gitea/deploy/', text)
|
||||
self.assertNotIn('deploy-dev.yml', text)
|
||||
self.assertNotRegex(text, r'(?m)^\s*docker\s+')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify native unit state, API health and Angular routing after activation."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import install
|
||||
import activate
|
||||
|
||||
|
||||
def request(url):
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with opener.open(url, timeout=5) as response:
|
||||
return response.status, response.read(1024 * 1024)
|
||||
|
||||
|
||||
def check(record, command=subprocess.run, get=request, manager_env=None):
|
||||
install.validate_record(record)
|
||||
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
|
||||
raise ValueError('installation is not prepared')
|
||||
port = record['public_port']
|
||||
api = record.get('api_port')
|
||||
expected = [f'isssteleon-native-{port}-{part}.service' for part in ('api', 'worker', 'web')]
|
||||
if record.get('services') != expected or type(api) is not int or api == port or not 1024 <= api <= 65535:
|
||||
raise ValueError('invalid installed service metadata')
|
||||
for unit in expected:
|
||||
result = command(['systemctl', '--user', 'is-active', '--quiet', unit], check=False, capture_output=True, env=manager_env)
|
||||
if result.returncode:
|
||||
raise ValueError('service is not active: ' + unit)
|
||||
for url in (f'http://127.0.0.1:{api}/health', f'http://127.0.0.1:{port}/health'):
|
||||
status, body = get(url)
|
||||
health = json.loads(body)
|
||||
if status != 200 or not isinstance(health, dict) or health.get('status') != 'ok':
|
||||
raise ValueError('API health check failed: ' + url)
|
||||
status, index = get(f'http://127.0.0.1:{port}/')
|
||||
route_status, route = get(f'http://127.0.0.1:{port}/native-health-route')
|
||||
if status != 200 or route_status != 200 or not index or index != route:
|
||||
raise ValueError('Angular distribution or SPA fallback failed')
|
||||
return {'services': expected, 'api_health': 'ok', 'proxy_health': 'ok', 'spa_fallback': 'ok'}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('instance', type=Path)
|
||||
parser.add_argument('--wait-seconds', type=int, default=90)
|
||||
parser.add_argument('--public-result', choices=('ok', 'failed'))
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.wait_seconds <= 300:
|
||||
parser.error('wait-seconds must be between 0 and 300')
|
||||
record = None
|
||||
path = None
|
||||
tracked = False
|
||||
try:
|
||||
path = args.instance.resolve() / 'installation.json'
|
||||
if args.instance.is_symlink() or path.is_symlink():
|
||||
raise ValueError('symlinked installation or metadata')
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
if Path(record.get('base', '')) != args.instance.resolve():
|
||||
raise ValueError('installation path does not match record')
|
||||
install.validate_record(record)
|
||||
if record.get('status') not in ('started', 'local_healthy', 'healthy', 'verification_failed'):
|
||||
raise ValueError('installation is not prepared')
|
||||
tracked = True
|
||||
if args.public_result == 'failed':
|
||||
raise ValueError('external HTTP check failed from the Actions runner')
|
||||
manager_env = activate.manager_environment(record['account'])
|
||||
deadline = time.monotonic() + args.wait_seconds
|
||||
while True:
|
||||
try:
|
||||
checks = check(record, manager_env=manager_env)
|
||||
break
|
||||
except (OSError, ValueError, urllib.error.URLError, json.JSONDecodeError) as exc:
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError('health verification failed: ' + str(exc)) from exc
|
||||
time.sleep(2)
|
||||
if args.public_result == 'ok':
|
||||
checks['public_http'] = 'ok'
|
||||
record.update(status='healthy' if args.public_result == 'ok' else 'local_healthy',
|
||||
phase='running' if args.public_result == 'ok' else 'awaiting_external_health',
|
||||
health=checks, verified_at=int(time.time()))
|
||||
install.atomic_record(path, record)
|
||||
print(json.dumps(checks, indent=2, sort_keys=True))
|
||||
return 0
|
||||
except (OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
if tracked:
|
||||
record.update(status='verification_failed', phase='verification_failed',
|
||||
health={'result': 'failed', 'error': str(exc)}, verified_at=int(time.time()))
|
||||
try:
|
||||
install.atomic_record(path, record)
|
||||
except OSError:
|
||||
pass
|
||||
print('Verification failed: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,26 +1,83 @@
|
||||
# General DEV workflow integration
|
||||
# What was exercised, and what was not
|
||||
|
||||
`.gitea/workflows/deploy-dev.yml` accepts only `puerto` on `dev`. It checks out
|
||||
the dispatched SHA and recursive application gitlinks, then routes an unregistered
|
||||
free port to installation and a registered installation to conservative update.
|
||||
The same revision takes a verified no-op path. Existing storage is never reset as
|
||||
a fallback. Pending migrations are rejected for updates; post-activation failures
|
||||
require manual recovery as described in [README.md](README.md).
|
||||
Status of the disposable DEV installer (`installer.py`, `dataload.py`). See [README.md](README.md) for use.
|
||||
|
||||
Physical acceptance supplied by the operator: on 2026-11-10, port 18080 completed
|
||||
an update and port 18082 a new installation, both with `status=installed` and
|
||||
`recalculation=complete` at `ea198c43246e53b37b6d4fb655d8b06806560b17`. Port
|
||||
18081 retained revision `55e90fd49c6982793afb0633e974b33e44e58d94`. These results
|
||||
do not establish the behavior of every host, failure or recovery scenario.
|
||||
## Capabilities of the retired updater and where each went
|
||||
|
||||
Run the deployment and selector suites from the repository root:
|
||||
The conservative updater, its recovery tools and the data guards were removed after checking, one by one, that
|
||||
nothing else needs them:
|
||||
|
||||
```sh
|
||||
python3 -B -m unittest discover -s .gitea/deploy -p 'test_*.py' -v
|
||||
python3 -B -m unittest discover -s .gitea/ci -p 'test_*.py' -v
|
||||
git diff --check
|
||||
```
|
||||
| Capability of the retired tooling | Now | Why |
|
||||
| --- | --- | --- |
|
||||
| Install on a free port | `deploy-dev` | Covered, with a plan and a confirmation. |
|
||||
| Select the application revision | `referencia`: branch, tag or full SHA | Extended; the old input took a branch only. |
|
||||
| Resolve to exact commits and recursive gitlinks, record them | Same, recorded as `reference`, `revision`, `gitlinks` | Covered. |
|
||||
| Compose safety checks (services, mounts, ports, notebook runner isolation, no privileged options) | `installer.verify_config` | Kept unchanged in substance. |
|
||||
| Shared host lock and registry of instances | `registry.py` and the locked helper | Kept; a plan runs the helper read-only without the lock. |
|
||||
| Foreign container, volume, network and port detection | `resources.py` | Kept and made stricter (exact names, mounts, image IDs). |
|
||||
| Update in place with backup, schema and data guards, quiescing, recalculation checks | none | Retired by decision: DEV instances are disposable and data is not preserved on reinstall. |
|
||||
| Verified no-op on the same revision | none | Retired with the updater. |
|
||||
| Recovery tools for failed updates (`reconcile.py`, `reset_lab_18080.py`, `diagnose_storage.py`) | none | They only repair `updating` / `update_failed` records, which nothing creates any more. A record left in such a state is refused and needs manual inspection. The tools remain in Git history. |
|
||||
| Notebook jobs volume backup | none | A reinstall deletes the volume with the instance. |
|
||||
| Checked recalculation during a new install | none | Retired by decision: the worker starts with `INDICADORES_AL_INICIAR=0`. Health and routes are checked instead. |
|
||||
| Clean reinstall of an instance | `reinstall-dev` | New. |
|
||||
| Loading the simulated hospital | `load-dev-data` | New, replacing the manual steps of `docs/operations/dev-data-ingest.md`. |
|
||||
| Terminal (native) release deployment | unchanged | Independent: `deploy-terminal/` imports nothing from here and its workflow test asserts it. |
|
||||
| Host and Docker probe, checkout origin diagnostic | unchanged | `docker-persistence-probe.yml` and `origin_diagnostic.py` are independent of the installer. |
|
||||
|
||||
See the [operator README](README.md) for compatibility, recovery, optional pinned
|
||||
schema tests and remaining operational limits. The incident-specific reset tool
|
||||
and its [procedure](RESET-18080.md) are retained for existing recovery needs.
|
||||
Instances created by the old workflow keep their records. They can be reinstalled when they are named
|
||||
`isssteleon-dev-<puerto>`, have a commit in `revision` and a replaceable state. Instances with another name
|
||||
(for example `isssteleon-dev-prueba-02` on 18080) are not reinstallable by this tooling and are never touched by it.
|
||||
|
||||
## Exercised
|
||||
|
||||
Unit tests, `python3 -B -m unittest discover -s .gitea/deploy -p 'test_*.py'` (Windows with Python 3.12 and, for
|
||||
the registry, installer, data-load and workflow tests, Linux in a `python:3.12-slim` container where the symlink
|
||||
cases also run):
|
||||
|
||||
- reference resolution against local Git repositories: branch, lightweight and annotated tag, full SHA, ambiguity,
|
||||
abbreviations and ref paths refused, a reference that moves between resolution and checkout, an untrusted
|
||||
submodule origin;
|
||||
- registry ownership (marker, earlier DEV records, other installers, other names, non-replaceable states), linked
|
||||
directories, removal that never follows links, record removed last;
|
||||
- planning without side effects (no mutating Docker command, no registry entry, no write lock), the plan bound to the
|
||||
composition, port free, port held by a foreign container or by the host, registered port, protected ports, existing
|
||||
Docker resources;
|
||||
- install, reinstall of an own instance with foreign resources left untouched, no prune/down/forced removal, a
|
||||
reference that moves between plan and execution and after the build, resources that change after the build, a failed
|
||||
build before removal, a failed removal (kept, recorded, new confirmation needed), a failed start (recorded,
|
||||
retryable), the removal volume replaced mid-run;
|
||||
- data load: plan checks (running instance, no import attempts, no earlier load, reachable hospital, pins present),
|
||||
the loader built from the recorded pins, per-table counts, rejected rows, empty hospital, loader failure, indicator
|
||||
recalculation error and timeout, no installation resource touched;
|
||||
- the workflows' inputs, the environment-only passing of inputs and the dispatch validation.
|
||||
|
||||
Real Docker (Docker Desktop, Linux daemon), `ISSSTELEON-Deploy-Audit/scripts/dev_installer_trial.py`, 25 checks
|
||||
passed, nothing left behind, every pre-existing resource still present. Real: Git resolution and recursive checkout
|
||||
of `dev` over HTTP (outer `5bef06e`, ISSSTELEON `aa840b9`, WebApi `b1bbbc2`, WebApp `baf5edc`, models `7b2eae2`,
|
||||
dev-data `3dea0ad`), export of the pinned tree, `docker compose config` of the real `dist/docker-compose.yml`,
|
||||
the locked helper with the real registry, four real containers, the published port, `/health`, `/api` and `/`, the
|
||||
reinstall (old containers, data, volume and network gone; a foreign container and volume untouched), refusal of
|
||||
protected ports, of a port held by a foreign container and of an unknown reference.
|
||||
|
||||
Real Docker, `ISSSTELEON-Deploy-Audit/scripts/dev_data_load_trial.py`, 17 checks passed, nothing left behind. A
|
||||
throwaway MySQL 8.4 hospital (`wnrt-hospital`) was filled by `dev_data poblar` with 60 CaCu, 60 CaMa and 40 TEA
|
||||
patients; an instance was installed as above; the loader image was built by `dataload.build_loader` from the
|
||||
recorded commits (dev-data `3dea0ad` and the application's `Core`, fetched from Gitea by SHA); the load ran through
|
||||
the instance's published port and its own import API, which read the hospital at `host.docker.internal:39883`.
|
||||
Loaded without rejections: CaCu `Paciente` 60, `CitologiaCervical` 88, `BiopsiaCervical` 7, `NotaMedica` 43; CaMa
|
||||
`Paciente` 60, `Mastografia` 84, `BiopsiaMama` 17, `NotaMedica` 42; TEA 1,387 rows over eight tables. The three
|
||||
indicator recalculations ended `ok`, `/reportes/importaciones` listed the loads, and a second load was refused. The
|
||||
installed image was the earlier composition's (see below), so the import contract of the pinned WebApi was not
|
||||
the one exercised.
|
||||
|
||||
## Not exercised
|
||||
|
||||
- The institutional daemon host (`/srv/workingnarrative-dev`, the Gitea runner, the labserver Docker daemon).
|
||||
- A real image build in the trials: they tagged two local images of an earlier composition instead. The pinned
|
||||
composition's own build (dbt manifest, Angular build) was verified by the CI, not here.
|
||||
- Concurrent runs contending for the lock.
|
||||
- The data load against the shared hospital on the server (`10.0.10.41:9505`), or on the institutional host.
|
||||
- The data load against the pinned WebApi's import contract: the trial's instance ran an earlier composition's images.
|
||||
- CaMa stage, receptor, Ki-67 and T strata after a load: not inspected.
|
||||
- A reinstall of an instance created by the retired workflow.
|
||||
|
||||
@@ -1,438 +1,155 @@
|
||||
# DEV installation and conservative updates
|
||||
# Disposable DEV instances
|
||||
|
||||
The manual `deploy-dev` workflow accepts `puerto` on `dev`. An unregistered,
|
||||
available port installs a new instance. A registered port updates its existing
|
||||
managed instance, retaining the original `data/`, project, port and connections.
|
||||
Repeating the same outer revision verifies recursive gitlinks, recorded image
|
||||
identities, retained configuration, storage compatibility and service health.
|
||||
It records `result=unchanged` without builds, backups, restarts or recalculation.
|
||||
An inconsistent installation or failed update is rejected; it never falls back
|
||||
to resetting or recreating storage.
|
||||
Two manual workflows manage throwaway DEV instances of ISSSTELEON on the Docker host:
|
||||
|
||||
## Operator quick start
|
||||
|
||||
After the reviewed change reaches `dev`, open repository **Actions → deploy-dev →
|
||||
Run workflow**, select **dev**, enter only **puerto**, then inspect the run's SHA
|
||||
and final log. The same action installs a free port or updates its registered
|
||||
installation. Existing projects are discovered from their records; their names
|
||||
do not have to contain the port.
|
||||
|
||||
| Port / record | Outcome |
|
||||
| Workflow | Does |
|
||||
| --- | --- |
|
||||
| Unregistered and free on the daemon host | Existing fresh-install pipeline, initial migrations and checked recalculation. |
|
||||
| Valid `installed`, different outer revision | Conservative backup, code/image activation, preservation checks and recalculation. |
|
||||
| Valid `installed`, same outer revision | Verified no-op; preserve images, data and prior recalculation metadata. |
|
||||
| Foreign port owner, missing/duplicate record, wrong images/binds or missing data | Reject; inspect the diagnosed resource or record without deleting it. |
|
||||
| `updating`, `update_failed`, `failed` or another incomplete status | Reject; complete manual recovery/reconciliation before another deployment. |
|
||||
| Unknown revision, schema drift, pending migration or unsupported storage | Reject before stopping services; review compatibility separately. |
|
||||
| `deploy-dev` | Installs the selected version on a free port. |
|
||||
| `reinstall-dev` | Removes a registered DEV instance, data included, and installs the selected version in its place. |
|
||||
|
||||
The outer commit, not just the application gitlink, defines the release. A new
|
||||
outer commit with unchanged application pins still takes the checked update path.
|
||||
Updates do not execute pending migrations: they retain the existing migration
|
||||
compatibility gate. New installations continue to run their initial migrations.
|
||||
Both take `puerto`, `referencia` and `confirmacion`. Data is not preserved on a reinstall: these instances are
|
||||
meant to be replaced, not kept. Nothing here updates an instance in place.
|
||||
|
||||
Successful records contain `status=installed`, `revision`, `gitlinks`, `images`
|
||||
and `result=installed|updated|unchanged`. Updates also retain operation, target,
|
||||
backup and archive references. `unchanged` preserves previous recovery evidence
|
||||
and records `verification=complete`; it does not claim a new recalculation.
|
||||
The daemon-host record is `/srv/workingnarrative-dev/<registered-project>/installation.json`.
|
||||
To inspect it by port on that host without knowing the project:
|
||||
## Using them
|
||||
|
||||
```sh
|
||||
python3 -B - "$PORT" <<'PY'
|
||||
import json, pathlib, sys
|
||||
port = int(sys.argv[1])
|
||||
matches = []
|
||||
for path in pathlib.Path('/srv/workingnarrative-dev').glob('*/installation.json'):
|
||||
record = json.loads(path.read_text())
|
||||
if record.get('port') == port:
|
||||
matches.append(record)
|
||||
if len(matches) != 1:
|
||||
raise SystemExit('Expected exactly one registered installation; inspect the registry')
|
||||
record = matches[0]
|
||||
keys = ('project', 'port', 'status', 'phase', 'result', 'revision', 'gitlinks', 'images',
|
||||
'verification', 'recalculation', 'operation_id', 'target_revision', 'target_images',
|
||||
'backup', 'archive', 'recovery')
|
||||
print(json.dumps({key: record[key] for key in keys if key in record}, indent=2))
|
||||
PY
|
||||
Open **Actions**, choose the workflow, select `dev` under **Use workflow from** (the installer itself comes from
|
||||
that branch) and fill the inputs:
|
||||
|
||||
- `puerto`: the public port of the instance (1024 to 65535).
|
||||
- `referencia`: a branch, a tag or the full 40-character SHA of the `WorkingNarrative` commit to install. A short
|
||||
SHA, `refs/...` paths and names that are both a branch and a tag are refused.
|
||||
- `confirmacion`: leave it **empty** on the first run.
|
||||
|
||||
The first run is a plan: it changes nothing. It resolves the reference to an exact commit, initialises the
|
||||
recognised application gitlinks, checks the host, Docker and the composition, and prints the plan with a line like
|
||||
|
||||
```
|
||||
Nothing was changed. To approve exactly this plan, run again with confirmacion=instalar-18083-4ab9210e4d779764
|
||||
```
|
||||
|
||||
### Dispatch when the UI does not offer dev
|
||||
Run the workflow again with the same inputs and that text in `confirmacion`. The confirmation is a digest of the
|
||||
plan, so it only works for what was shown: the resolved commit and gitlinks, the port, and (for a reinstall) the
|
||||
containers, volume, network and directory to remove. If anything differs when the second run recomputes the plan,
|
||||
including the reference having moved to a new commit, it stops with nothing changed and prints the new
|
||||
confirmation.
|
||||
|
||||
Read-only API checks on 2026-11-10 confirmed Gitea **1.26.2**, repository default
|
||||
branch **main**, and Actions enabled. Anonymous workflow metadata returned 401;
|
||||
authenticated UI visibility and dispatch were not tested. Do not dispatch `main`
|
||||
or the old resetting workflow to work around the UI. Keep the general workflow's
|
||||
`refs/heads/dev` guard.
|
||||
### Install
|
||||
|
||||
An authorized operator can use the official
|
||||
[workflow dispatch endpoint](https://docs.gitea.com/api/operations/actions-dispatch-workflow/)
|
||||
with filename `deploy-dev.yml`, `ref=dev` and only the `puerto` input. Gitea's
|
||||
[v1.26.2 implementation](https://github.com/go-gitea/gitea/blob/v1.26.2/services/actions/workflow.go)
|
||||
resolves that branch's commit and reads the workflow from it. This supports using
|
||||
the API independently of default-branch UI discovery; it is source-based evidence,
|
||||
not a dispatch performed against this server.
|
||||
Refused unless the port is free: no registry record on it, nothing on the host listening, no container publishing
|
||||
it, no Docker resource named after the project, and the port not protected. On success the instance is
|
||||
`isssteleon-dev-<puerto>`, with its records under `/srv/workingnarrative-dev/isssteleon-dev-<puerto>/`.
|
||||
|
||||
**This submits a real deployment. Use only after review/merge and explicit
|
||||
authorization for the intended environment and port.** Set `PORT` and provide
|
||||
`GITEA_TOKEN` through the operator's private environment, then run:
|
||||
The install builds the two images, starts the four services (`webapi`, `indicadores`, `notebooks`, `webapp`) and
|
||||
checks the published port: `/health` answers `ok`, `/api` lists routes and `/` serves the web app. It does **not**
|
||||
recalculate indicators: the worker starts with `INDICADORES_AL_INICIAR=0` and recalculates after imports.
|
||||
|
||||
### Reinstall
|
||||
|
||||
The instance must be proven to be a DEV one of this installer before anything is planned:
|
||||
|
||||
- exactly one registry record on the port, named `isssteleon-dev-<puerto>`, with this installer's marker
|
||||
(`installer: dev-disposable`) or the shape earlier DEV installs wrote (a commit in `revision`), in a state that can
|
||||
be replaced (`preparing`, `building`, `starting`, `installed`, `failed`, `removing`);
|
||||
- every container labelled as the Compose project is named as one of its services, uses only the instance's data
|
||||
directory, its jobs volume and its default network, and runs an image of the record;
|
||||
- the only volume of the project is its notebook jobs volume, and its only network is its default one, held only
|
||||
by those containers;
|
||||
- no other container reaches the instance's directory, volume or network or publishes its port.
|
||||
|
||||
The plan lists each container (ID, name, image), volume, network and directory. After confirmation the installer
|
||||
builds the new images first, so a reference that cannot be built never costs an instance. Immediately before
|
||||
removing it re-resolves the reference and recomputes the plan; any difference stops it. Then it removes, in order,
|
||||
the containers by ID, the jobs volume by name, the network by ID and the directory (links are unlinked, never
|
||||
followed; the record goes last), and installs.
|
||||
|
||||
Never used: `docker system prune`, `docker volume prune`, `docker network prune`, `docker compose down`, forced
|
||||
removal, or any listing-based cleanup. Images are kept (see the limits).
|
||||
|
||||
Refused, with nothing changed: a port with no record (use `deploy-dev`), a record of another installer or project
|
||||
name, the states `updating`, `update_failed`, `replacing` and `replace_failed` left by earlier updaters (inspect them
|
||||
by hand), any foreign resource sharing the instance, and the protected ports **18087** and **4397**, which are
|
||||
refused by both workflows whatever their state.
|
||||
|
||||
A failure while removing keeps what remains, marks the record `removing` with the phase and error, and tells you a
|
||||
new plan is needed. A failure while installing marks the record `failed` with the error and the Compose
|
||||
diagnostics. Run `reinstall-dev` again to continue from either state.
|
||||
|
||||
### Inspecting an instance
|
||||
|
||||
```sh
|
||||
python3 -B - "$PORT" <<'PY'
|
||||
import json, os, sys, urllib.request
|
||||
port = sys.argv[1]
|
||||
if not port.isascii() or not port.isdigit() or not 1024 <= int(port) <= 65535:
|
||||
raise SystemExit('Invalid public port')
|
||||
request = urllib.request.Request(
|
||||
'http://10.0.10.41:3000/api/v1/repos/ISSSTELEON/WorkingNarrative/actions/workflows/deploy-dev.yml/dispatches',
|
||||
data=json.dumps({'ref': 'dev', 'inputs': {'puerto': port}}).encode(),
|
||||
headers={'Authorization': 'token ' + os.environ['GITEA_TOKEN'], 'Content-Type': 'application/json'},
|
||||
method='POST')
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
print('Dispatch HTTP status:', response.status)
|
||||
PY
|
||||
cat /srv/workingnarrative-dev/isssteleon-dev-<puerto>/installation.json
|
||||
```
|
||||
|
||||
Use an account/token with the repository's required Actions write access. An HTTP
|
||||
success only confirms dispatch acceptance: open the resulting run in Actions,
|
||||
verify `ref=dev`, the captured SHA and the intended port, then read its final
|
||||
result and installation record. A 401/403 requires access correction; a 404 may
|
||||
mean the workflow/ref is unavailable. Do not remove the branch guard or retry
|
||||
against another branch. The Action checks out its captured SHA, verifies HEAD,
|
||||
and initializes only recursive `ISSSTELEON` gitlinks; unrelated `dev-data` is not
|
||||
required to deploy.
|
||||
The record has `reference`, `reference_kind`, `revision` (the outer commit), `gitlinks` (the outer commit,
|
||||
`dev-data`, `ISSSTELEON` and each application), `images`, `installer`, `plan_digest`, `status`, `verification`
|
||||
and, after a reinstall, `replaced`.
|
||||
|
||||
Local validation, review scope and a proposed disposable-environment trial are in
|
||||
[INTEGRATION.md](INTEGRATION.md). Do not use existing installations for fault injection.
|
||||
## Prerequisites
|
||||
|
||||
The checkout follows the dispatched WorkingNarrative commit and every recursive
|
||||
gitlink. Source export rejects mismatching submodule checkouts. Builds include
|
||||
WebApp, WebApi, Core, Persistance, Extraction, indicadores_kit, models and other
|
||||
application trees at those pins. No `submodule update --remote` is used.
|
||||
The runner needs Python 3.12+, Git and Docker with Compose v2 (`config --format json`, `up --pull never`), and
|
||||
access to Gitea and the build registries. A Linux daemon is required. `/srv/workingnarrative-dev` must exist on the
|
||||
daemon host, private to the deployment account. The installer starts a short-lived helper container from
|
||||
`python:3.12-slim` (override with `DEV_INSTALLER_HELPER_IMAGE`) on the host network to take the host-wide lock,
|
||||
write the registry and probe ports; a plan runs it read-only and without the lock.
|
||||
|
||||
## Four distinct operations
|
||||
The managed layout is the SQLite one under `/data`; the effective Compose file is checked (services, mounts,
|
||||
ports, notebook runner isolation, no privileged options) and saved, so what runs is what was verified.
|
||||
|
||||
| Operation | Storage behavior |
|
||||
| --- | --- |
|
||||
| Install | Reserve a new project and create new storage; run initial migrations. |
|
||||
| Update | Replace application code/images while preserving existing storage; reject pending migrations. |
|
||||
| Regenerate data | Independent, explicitly authorized operation; never an automatic update or seed step. |
|
||||
| Recover | Validate a backup or historical archive and restore into a new isolated location before considering a live cutover. |
|
||||
|
||||
The previous replacement path archived `codigo/`, `deploy/` and `data/`, then
|
||||
created empty storage. The updater archives only `codigo/` and `deploy/`.
|
||||
Existing `.archive/` contents remain untouched. Missing existing storage is an
|
||||
error, including when only one required database is missing.
|
||||
|
||||
## Prerequisites and supported origins
|
||||
|
||||
The runner needs Python 3.12+, Git, Docker, Compose v2 (`config --format json`,
|
||||
`up --pull never`) and access to exact source pins and build registries.
|
||||
The daemon must be Linux and support host networking for the lock helper.
|
||||
An administrator must provision `/srv/workingnarrative-dev`, private to the
|
||||
deployment account, on the **daemon host**. Bind mounts must work with the
|
||||
images' default user and host security policy. The helper uses `python:3.12-slim`.
|
||||
Confirm which runner and daemon `ubuntu-latest` actually selects.
|
||||
|
||||
Only a valid `installed` record with all three matching, running containers is
|
||||
eligible. Checks cover project/service labels, actual image IDs, published port,
|
||||
exact writable `/data` binds and effective configuration against the running
|
||||
API/worker environment. Foreign overlapping mounts, port owners and peers on the
|
||||
instance's Docker networks are rejected. A daemon-host `flock` serializes
|
||||
cooperating installation/update jobs for the whole operation.
|
||||
|
||||
This first version supports the managed local SQLite layout only:
|
||||
|
||||
| Setting | Required existing value |
|
||||
| --- | --- |
|
||||
| `CACU_DATABASE_URL` | `sqlite:////data/cacu.db` |
|
||||
| `CAMA_DATABASE_URL` | `sqlite:////data/cama.db` |
|
||||
| `TEA_DATABASE_URL` | `sqlite:////data/tea.db` |
|
||||
| `GOVERNANCE_DATABASE_URL` | `sqlite:////data/governance.db` |
|
||||
| `MLFLOW_TRACKING_URI` | `sqlite:////data/mlflow.db` |
|
||||
| `MLFLOW_ARTIFACT_ROOT` | `/data/mlflow-artefactos` |
|
||||
| `WEBAPI_REPORT_DIR` | `/data/reportes` |
|
||||
| `INDICADORES_DIR` | `/data/indicadores` |
|
||||
|
||||
Operator `.env` values are retained; managed paths/version/port are fixed.
|
||||
The effective Compose specification is saved privately, escaping literal dollar
|
||||
signs. The one-shot worker receives resolved environment values through stdin,
|
||||
avoiding Docker env-file quoting differences and secret command arguments.
|
||||
External databases, custom persistent locations, linked/special storage entries,
|
||||
triggers and hidden/generated columns are unsupported and rejected. Connections
|
||||
are never redirected from custom storage to new local databases.
|
||||
|
||||
Each database must have exactly one Alembic revision, recognized by the candidate
|
||||
and already at its sole head. Tables, ordered columns, types, nullability,
|
||||
defaults, primary keys, indexes, foreign keys and CHECK constraints must match
|
||||
the candidate's in-memory model schema. SQLite integrity and foreign key checks
|
||||
must pass. Inspection overrides the application entrypoint, has no network, a
|
||||
read-only root and read-only data bind. It reads migration definitions, without
|
||||
invoking application migration environments.
|
||||
|
||||
For the currently pinned composition, admitted heads are:
|
||||
|
||||
| Database | Required head |
|
||||
| --- | --- |
|
||||
| CaCu | `b4f2d8c01e23` |
|
||||
| CaMa | `c5a3e9d12f34` |
|
||||
| TEA | `a3e1c7b90d12` |
|
||||
| Governance | `e7c5a1f34b56` |
|
||||
|
||||
The candidate computes these values dynamically. Governance at `d6b4f0e23a45`
|
||||
is rejected before stopping services: its next revision drops four historical
|
||||
cohort tables. The fifteen removed historical revisions, absent version tables,
|
||||
multiple revisions, a head stamp over mismatching structure and **every pending
|
||||
migration** are rejected. There is no stamp, downgrade, automatic conversion or
|
||||
historical bridge. Other engines/transitions need separate reviewed support.
|
||||
|
||||
## Update phases
|
||||
|
||||
1. Verify installation, running containers and retained configuration. Export the
|
||||
complete pinned composition, build both uniquely tagged application images
|
||||
and validate the controlled Compose specification. Existing services keep
|
||||
running throughout preparation.
|
||||
2. Inspect revisions/structure without writes. Check daemon-host space for backup,
|
||||
staged source and SQLite working pages. Recheck container identities. Preparation
|
||||
or compatibility failures leave the installed record/services untouched.
|
||||
Candidate images may remain for investigation.
|
||||
3. Record `updating` and operation/target references. Disable restart and stop the
|
||||
validated worker, API and frontend, then confirm they stopped. Recheck data
|
||||
directory/database identities and schema after quiescing.
|
||||
4. Verify a backup at `/srv/workingnarrative-dev/.backups/<project>/<operation>/`.
|
||||
Include all persistent files and empty directories. Every SQLite file, including
|
||||
optional MLflow storage, uses SQLite's backup API with a standalone destination
|
||||
journal mode; committed WAL pages are included. Other artifacts/logs are copied
|
||||
with checksums. Recognized SQLite sidecars are represented by the normalized
|
||||
backup. Source state must remain unchanged throughout.
|
||||
5. Stage all code/configuration under `.updates/<operation>/`, archive only old
|
||||
`codigo/` and `deploy/` under `.archive/<operation>/`, then rename staged code
|
||||
into place. Original `data/` and database files stay in place.
|
||||
6. Start only WebApi with a direct Gunicorn entrypoint. **Existing-instance updates
|
||||
never run the image's automatic Alembic entrypoint.** Verify API health, actual
|
||||
image, environment and original bind, then compare every table/file with the
|
||||
quiesced snapshot before allowing recalculation.
|
||||
7. Run `ColaDeRecalculo.correr` once for CaCu, CaMa and TEA, without `migrar`.
|
||||
Consume old markers, require `estado=ok` for all three and no pending markers.
|
||||
Check preservation with declared derived changes allowed. Start the regular
|
||||
worker with `INDICADORES_AL_INICIAR=0`, then the frontend.
|
||||
8. Verify services, frontend/proxied health, image/mount identities and storage
|
||||
again. Record `installed`, full Git provenance and completed recalculation.
|
||||
HTTP 200 alone never establishes success.
|
||||
|
||||
First installation reserves fresh `data/`, probes writable SQLite using the built
|
||||
image's default user, and starts only the API's normal initial migration entrypoint.
|
||||
It then uses the same controlled recalculation/persistence checks before starting
|
||||
worker and frontend. The worker cannot migrate concurrently.
|
||||
|
||||
The integrity policy protects original clinical/staging tables and all Governance
|
||||
rows exactly. Prior `carga`, report and cohort-history rows must survive; additions
|
||||
are allowed. Declared projections, catalogs, parameter definitions and calendar/
|
||||
period tables may change during recalculation. Indicator status/markers may change;
|
||||
the indicator JSONL log must preserve its old prefix. All other persistent files,
|
||||
including MLflow storage/artifacts and import logs, must remain unchanged. Worker
|
||||
views may be rebuilt. Metadata contains hashes/counts and per-row multiplicities
|
||||
for append-only history, without copying raw records into deployment metadata.
|
||||
|
||||
## Failures and recovery
|
||||
|
||||
No automatic image rollback or live data restore occurs. A failure after quiescing
|
||||
reserves project/port as `update_failed`, with phase, operation, origin/target
|
||||
references and expected backup/archive paths. Interruption may leave `updating`.
|
||||
Both statuses block another automatic deploy. Partial backups/archives/stages,
|
||||
old image tags and code/configuration are retained. No prune or archive cleanup runs.
|
||||
|
||||
Backup and optional isolated-restore parent directories are created and probed by
|
||||
the locked helper before quiescing. This catches some path and permission failures
|
||||
while services are still running; it does not guarantee later backup success or
|
||||
identify the cause of an earlier failure.
|
||||
|
||||
To diagnose candidate compatibility without an update, use a trusted checkout
|
||||
containing `diagnose_storage.py` and the exact retained candidate WebApi image on
|
||||
the daemon host. For example, with an independently verified instance path:
|
||||
|
||||
```sh
|
||||
INSTANCE=/srv/workingnarrative-dev/isssteleon-dev-prueba-02
|
||||
IMAGE=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["target_images"][0])' "$INSTANCE/installation.json")
|
||||
python3 -B .gitea/deploy/diagnose_storage.py --image "$IMAGE" --data "$INSTANCE/data"
|
||||
```
|
||||
|
||||
This starts temporary read-only, network-isolated containers using the existing
|
||||
candidate image without pulling it; it does not stop or start application services
|
||||
or write the data mount. It emits only allowlisted rejection categories, a domain,
|
||||
exception type, SQLite error name and numeric errno. A pass while services are
|
||||
running cannot rule out a failure after they stop; reproduce the same state only
|
||||
when the services are already stopped under an independently authorized plan.
|
||||
It does not compare the before/after directory or database identities.
|
||||
|
||||
### Reconcile a manually recovered pre-activation failure
|
||||
|
||||
Use this only after an operator has independently established that the original
|
||||
installation is running unchanged. It is not a general recovery procedure.
|
||||
Keep the original failed record and all artifacts; never restore over live data.
|
||||
|
||||
`reconcile.py` implements an explicit `check` and `apply` on the Docker daemon
|
||||
host. Both acquire the shared helper lock, check the failed record, original
|
||||
revision and source gitlink, supplied container IDs, image tags and IDs, mounts,
|
||||
Compose configuration, restart policies, service health, live SQLite state, the
|
||||
recovery archive SHA-256 and five SQLite files in an isolated restore. The archive
|
||||
must have one regular `data/<database>` member for each of those databases; the
|
||||
restored data directory must match the database files and SQLite sidecars in the
|
||||
archive. Integrity checks use temporary database copies including WAL and journal
|
||||
files; the shared-memory index is rebuilt. Neither the tar hash nor SQLite integrity establishes full backup or
|
||||
functional consistency. The external-copy flag is an operator attestation, not
|
||||
an automated check of remote storage. Confirm the application and recovery copy
|
||||
independently before applying. Temporary helper containers, the existing lock file and local
|
||||
temporary configuration are used; the check does not write the installation or
|
||||
backup. The source checkout must contain the original outer-repository revision.
|
||||
|
||||
Example, from a trusted checkout on the daemon host, after setting the independently
|
||||
verified original revision and the actual isolated restored `data` directory. Replace
|
||||
the placeholders with verified values (without angle brackets):
|
||||
|
||||
```sh
|
||||
REVISION_ORIGINAL=<verified-original-40-character-commit>
|
||||
RESTORED_DATA=<absolute-path-to-isolated-restored-data>
|
||||
python3 -B .gitea/deploy/reconcile.py check \
|
||||
--instance <instance> --port <port> --revision "$REVISION_ORIGINAL" \
|
||||
--operation <operation-id> \
|
||||
--webapi <webapi-container-id> \
|
||||
--webapp <webapp-container-id> \
|
||||
--indicadores <indicadores-container-id> \
|
||||
--backup <absolute-backup-path> \
|
||||
--backup-sha256 <backup-sha256> \
|
||||
--restored-data "$RESTORED_DATA" --external-copy-verified
|
||||
```
|
||||
|
||||
After reviewing a successful check and authorizing the write, repeat the exact
|
||||
command with `apply` in place of `check`. Apply repeats all checks under a new
|
||||
lock and changes only `status` atomically, provided the record is unchanged.
|
||||
An `eligible` check is not a reservation: validate again with `apply`.
|
||||
|
||||
1. Stop deployment jobs, acquire the same shared helper lock and retain it through
|
||||
the checks and record write. Privately copy `installation.json` outside the
|
||||
instance and record its hash. Confirm project, port and operation ID against
|
||||
the incident, and require `update_failed` in `quiescing`, `backup`, or
|
||||
`restore-verification`. If activation may have started, stop and investigate.
|
||||
2. Verify the original `codigo` and `deploy` are still active, no archive or
|
||||
staged activation for that operation was applied, and the recorded origin
|
||||
revision, gitlinks, image IDs, configuration, container IDs, project labels,
|
||||
port, network and writable data mounts match the original installation. Check
|
||||
no foreign writer can access its data. Use `verify_existing_containers` under
|
||||
the helper lock and independently check provenance and the retained Compose
|
||||
configuration; a running container alone does not prove data integrity.
|
||||
3. Confirm database integrity and expected existing data, application health and
|
||||
a verified independent recovery copy, including an isolated restore. Verify
|
||||
the original container restart policies against the retained Compose config;
|
||||
restore the declared policies on the identified containers if necessary and
|
||||
verify them. Do not recreate containers or run migrations for this step.
|
||||
4. Under the same lock, reread the record and require it still matches the saved
|
||||
hash. After all checks pass, use the trusted `host.write_record` atomic writer
|
||||
to change only `status` to `installed`, retaining the failure phase, operation,
|
||||
error and target fields as evidence. Reread and verify the result. If any check
|
||||
fails or the record changes, leave it blocked and investigate. A subsequent
|
||||
update must pass all normal preparation, compatibility and backup checks.
|
||||
|
||||
On API/recalculation/availability failure the updater tries to disable restart and
|
||||
stop only containers whose project, service and mounts it can verify. It retains
|
||||
storage. `quarantine` records an incomplete containment attempt. Failures during
|
||||
stopping or backup triggers a best-effort restart of the verified original containers
|
||||
with their original restart policies, after checking the original storage contract.
|
||||
Automatic restart requires known migration-free API and worker entrypoints; older
|
||||
entrypoints that may run migrations are left for explicit manual recovery.
|
||||
The record remains `update_failed` even when recovery succeeds. A failed or interrupted
|
||||
recovery can leave partially stopped services; inspect actual containers before recovery.
|
||||
|
||||
Inspect `installation.json`, `.archive/<operation>/`, `.updates/<operation>/`, the
|
||||
external backup manifest, specific project containers and private Docker logs.
|
||||
Archives from the old resetting installer are **not** consistency-certified backups.
|
||||
Do not assume copying a bare `.db` without its WAL history is sufficient.
|
||||
|
||||
With trusted deployment scripts on the host, verify and restore to a **new isolated
|
||||
directory** using Python's stdlib, without application imports:
|
||||
|
||||
```sh
|
||||
export PYTHONPATH=/path/to/WorkingNarrative/.gitea/deploy
|
||||
python3 -B -c 'import data_guard,sys; data_guard.verify_backup(sys.argv[1])' /path/to/backup
|
||||
python3 -B -c 'import data_guard,sys; data_guard.restore_backup(sys.argv[1],sys.argv[2])' /path/to/backup /new/isolated/data
|
||||
```
|
||||
|
||||
Restore refuses an existing destination, verifies checksums/integrity and compares
|
||||
the four databases' logical contents with the manifest. Before authorized live
|
||||
recovery, validate the old application's compatibility against that isolated copy,
|
||||
ownership/permissions, mounts, full configuration and successful recalculation.
|
||||
Preserve failed live storage as evidence and review a specific cutover procedure.
|
||||
Do not overwrite live files, change statuses to bypass checks or start old automatic
|
||||
migration entrypoints on an unvalidated schema. These restore commands do not
|
||||
cut over a service.
|
||||
|
||||
A killed job can leave its uniquely named `isssteleon-prepare-*` helper holding
|
||||
the lock. Verify no deployment is active before removing that specific helper.
|
||||
Never use global Docker cleanup to release it.
|
||||
|
||||
## Local validation and an isolated Docker trial
|
||||
|
||||
The general workflow has been physically exercised for a conservative update and
|
||||
a fresh installation. Use separate disposable resources for fault injection and
|
||||
recovery testing.
|
||||
|
||||
Run the synthetic suite from the WorkingNarrative root:
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
python3 -B -m unittest discover -s .gitea/deploy -p 'test_*.py' -v
|
||||
python3 -B -m unittest discover -s .gitea/ci -p 'test_*.py' -v
|
||||
git diff --check
|
||||
```
|
||||
|
||||
`test_conservative.py` uses temporary synthetic databases, witnesses, blobs,
|
||||
MLflow state, artifacts, logs and archives; an adapter replaces all Docker calls.
|
||||
It exercises code updates, repeated versions, rejected origins, WAL backup,
|
||||
corruption, derived changes, protected loss and failures. `test_target_contract.py`
|
||||
also compares real pinned migration definitions with metadata and tests schema
|
||||
backup/restore. Opt in with `ISSSTELEON_CONTRACT_SOURCE=/path/to/pinned/ISSSTELEON`
|
||||
and a disposable Python environment containing exact schema packages/hashes from
|
||||
WebApi's `uv.lock`. It applies revision functions only to newly created temporary
|
||||
SQLite files, without loading migration environments or institutional data.
|
||||
The stdlib suite skips these two opt-in tests without the selected source/runtime.
|
||||
`test_composition.py` resolves references against local Git repositories, `test_registry.py` covers ownership and
|
||||
removal on a temporary directory, and `test_installer.py` runs the flows against an in-memory Docker daemon. None of
|
||||
them contacts Docker or Gitea. [INTEGRATION.md](INTEGRATION.md) lists what was exercised on real Docker and what
|
||||
was not.
|
||||
|
||||
After review, a separately authorized physical trial needs an isolated Linux Docker
|
||||
daemon, synthetic storage and an empty private deployment base. Initialize recursive
|
||||
submodules at recorded pins; build without modifying locks. Run a first install on
|
||||
a disposable port, add clinical/Governance witnesses, registered-model state,
|
||||
artifacts and logs through supported interfaces, then repeat the same version and
|
||||
a compatible code revision. Compare original directory/file identities, data,
|
||||
history and mounts. Verify functional reads, completed indicator work, external
|
||||
client access and restart. Inject missing databases, unknown revisions, pending
|
||||
Governance drop, changed binds and build/startup/worker failures. Confirm early
|
||||
rejection or reserved failure state; restore backups to separate locations.
|
||||
Use separate disposable resources for fault injection and general recovery
|
||||
testing. A shared institutional daemon does not provide the same isolation.
|
||||
A later real dispatch requires separate authorization.
|
||||
## Limits
|
||||
|
||||
## Remaining limits before institutional use
|
||||
- Images are never removed. Each install leaves two images tagged with the project and an operation ID; remove an
|
||||
unused tag by name when disk space matters.
|
||||
- A process outside Docker that starts listening between the plan and the install is only detected when the
|
||||
helper tries the port.
|
||||
- Only the Compose project, its containers, volume, network and directory are identified. Anything else on the host
|
||||
that the instance's data directory was bind-mounted into by hand is not.
|
||||
- The installer trusts the registry directory: it is writable only by the deployment account.
|
||||
- Not tried on the institutional daemon host.
|
||||
|
||||
- The lock coordinates these scripts; it cannot stop host processes, privileged
|
||||
daemon users or direct network clients. Ensure exclusive maintenance access and
|
||||
no external writers until final verification. Docker ownership checks are not
|
||||
host-wide access control.
|
||||
- Databases are backed up sequentially after known writers stop. Snapshots and
|
||||
before/after checks detect changes, without a distributed transaction across
|
||||
uncontrolled writers. An incompatible read-only WAL probe must abort, not repair.
|
||||
- Verification scans all rows/files and stores append-only row hashes. Measure
|
||||
memory, disk, runtime and downtime on realistic synthetic volumes. The space
|
||||
estimate does not reserve Docker image/build space or exclude other disk users.
|
||||
Power-loss durability needs host testing.
|
||||
- Derived changes are scoped, but preservation checks do not prove clinical
|
||||
correctness, risk-estimate completeness or API behavior beyond checked paths.
|
||||
Future worker/model changes require integrity-policy review.
|
||||
- Container-user permissions, WAL, Compose interpolation, direct Gunicorn startup,
|
||||
actual worker completion, containment and restart/recovery need the isolated
|
||||
physical trial. Backup preserves file contents/modes/timestamps; ACLs, security
|
||||
labels and original uid/gid restoration need separate recovery validation.
|
||||
- Backups remain on the daemon host. Off-host replication, encryption, retention,
|
||||
confidential log handling and disaster recovery remain operator responsibilities.
|
||||
Simulated tests alone do not establish institutional deployment safety.
|
||||
## Loading simulated data (optional, after an install)
|
||||
|
||||
The incident-specific [18080 recovery procedure](RESET-18080.md) and its tested
|
||||
script remain available for the historical failed operation; they are not part of
|
||||
the general deployment workflow.
|
||||
`load-dev-data` fills an installed, still empty DEV instance with the simulated hospital that `dev-data` generates.
|
||||
It is a separate operation with the same plan and confirmation steps (`cargar-<puerto>-<digest>`) and takes
|
||||
`puerto`, `hospital` (`host:port`, default `10.0.10.41:9505`) and `confirmacion`.
|
||||
|
||||
How it works: the instance's API reads the hospital through its own import API, as a person would connect it in
|
||||
`/conectar`. The installer only builds the `dev-data` loader from the commit recorded in the instance
|
||||
(`gitlinks.dev-data`, plus `Core` of the recorded application commit), runs `dev_data cargar` for `cacu`, `cama` and
|
||||
`tea` against the published port, and then waits for the three indicator recalculations to end `ok`. It records
|
||||
`synthetic_data` (hospital, `dev-data` commit, per-table counts, indicator states) in the instance record.
|
||||
|
||||
It refuses an instance that is not a verified, running DEV installation, one with any import attempt
|
||||
(`/reportes/importaciones`) or an earlier load, an unreachable hospital address and anything that is not `host:port`.
|
||||
It fails, visibly and with the stage, on a loader error, any rejected row, a project with no rows, or a
|
||||
recalculation that errors or does not finish. After a failure the instance may be partly loaded, so it is marked
|
||||
and must be reinstalled before another attempt: the hospital's ids travel with the rows, so a load only works on
|
||||
an empty platform.
|
||||
|
||||
Limits, none of which this installer works around or decides:
|
||||
|
||||
- The hospital is an external MySQL (`dev-data-prueba` on the server, port 9505). The installer reads its TCP port
|
||||
from the daemon host and never writes to it; filling it is dev-data's own workflow (`montura/poblar.sh`). The
|
||||
WebApi blocks SQLite as an import source, so the hospital must be MySQL, MariaDB, PostgreSQL or SQL Server. The
|
||||
simulated hospital's credentials (`hospital`/`hospital`) are fixed in `dataload.py`.
|
||||
- The generated data is synthetic and deterministic (seed and reference date in `dev-data`); the volumes are
|
||||
dev-data's defaults for what is in the hospital.
|
||||
- A trial load of 60 CaCu, 60 CaMa and 40 TEA patients from a throwaway hospital completed without rejections (see
|
||||
[INTEGRATION.md](INTEGRATION.md)). What dev-data does not generate comes from reading its code, not from that load:
|
||||
CaMa stage, receptor, Ki-67 and T strata stay empty because dev-data generates BI-RADS, biopsy grade and notes
|
||||
with ICD-10 codes but no report text, which is where those values come from. Adding it is development in
|
||||
`dev-data` and a decision on which fields and rules to simulate; none is assumed here.
|
||||
- CaCu loads patients, cytologies, biopsies and notes only, without orders, episodes or blood counts. TEA loads all
|
||||
its tables.
|
||||
- Cohort definitions, metrics and clinical contracts are untouched: only the staging tables are loaded and the
|
||||
platform's own recalculation runs.
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# Authorized laboratory reset
|
||||
|
||||
Run only on `labserver`, with a trusted checkout containing the reset script,
|
||||
root access, Python 3, Docker Compose, GNU `cp` and `lsof`. The Docker daemon must
|
||||
be local. The target and original revision are fixed in the script. Read the
|
||||
operation ID from the failed installation record and use it for all three commands:
|
||||
|
||||
```sh
|
||||
OPERATION_ID=$(sudo python3 -c "import json; print(json.load(open('/srv/workingnarrative-dev/isssteleon-dev-prueba-02/installation.json'))['operation_id'])")
|
||||
sudo python3 -B .gitea/deploy/reset_lab_18080.py check --operation "$OPERATION_ID"
|
||||
sudo python3 -B .gitea/deploy/reset_lab_18080.py apply --operation "$OPERATION_ID"
|
||||
sudo python3 -B .gitea/deploy/reset_lab_18080.py check --operation "$OPERATION_ID"
|
||||
```
|
||||
|
||||
Check uses temporary isolated copies, never changes the installation, and takes
|
||||
the existing installer file lock. Apply preserves failed code, configuration,
|
||||
data, record and container descriptions at:
|
||||
|
||||
`/srv/workingnarrative-dev/.reset-18080-<operation_id>/`
|
||||
|
||||
The installer backup is a normalized SQLite snapshot: committed WAL pages are
|
||||
already in its database files. Unexpected WAL/journal files in that snapshot
|
||||
cause rejection, not deletion. All persisted files, owners, modes and extended
|
||||
attributes are copied and checked. API/worker commands are overridden with the
|
||||
existing migration-free configuration; initial recalculation is disabled.
|
||||
|
||||
Success requires original image IDs, correct mounts/environment, healthy services,
|
||||
HTTP `/` and `/health`, exact database rows and the existing persistent-file/audit
|
||||
policy. Only then is the archived record atomically reinstated as `installed`,
|
||||
with a link to preserved incident evidence. A final check reports `already recovered`.
|
||||
|
||||
After a normal failure, the script attempts to stop only this project's services
|
||||
and leaves `update_failed`. Repeat apply after correcting the failed prerequisite.
|
||||
Each later data attempt is preserved separately; original incident evidence is
|
||||
never replaced. If killed while services are running, explicitly stop this
|
||||
project before retrying:
|
||||
|
||||
```sh
|
||||
sudo docker compose --project-name isssteleon-dev-prueba-02 \
|
||||
--project-directory /srv/workingnarrative-dev/isssteleon-dev-prueba-02/deploy \
|
||||
--env-file /srv/workingnarrative-dev/isssteleon-dev-prueba-02/deploy/.env \
|
||||
-f /srv/workingnarrative-dev/isssteleon-dev-prueba-02/deploy/docker-compose.yml stop
|
||||
```
|
||||
|
||||
An interrupted preparation without `prepared` has made no active-directory swaps.
|
||||
Retain that incomplete work directory under another unique name before retrying.
|
||||
Ambiguous filesystem states are rejected. Do not delete evidence to bypass checks.
|
||||
No command targets 18081, other projects, remote Git or Actions.
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Resolve a Git reference to the exact composition an installation is built from.
|
||||
|
||||
A composition is the outer commit plus the commits of every recognised gitlink below `ISSSTELEON`. Everything
|
||||
here works in temporary directories and never touches Docker or the installation registry.
|
||||
"""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import tarfile
|
||||
|
||||
import proc
|
||||
|
||||
OFFICIAL = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
|
||||
ORIGIN_BASE = 'ssh://git@10.0.10.41:2222/ISSSTELEON/'
|
||||
# Public ports that belong to other installations and are never installed over or removed.
|
||||
PROTECTED_PORTS = {
|
||||
18087: 'CaMa installation',
|
||||
4397: 'installation kept for inspection',
|
||||
18090: 'DEV installation kept as a reference',
|
||||
18096: 'DEV installation kept as a reference',
|
||||
18097: 'DEV installation kept as a functional reference',
|
||||
}
|
||||
SHA = re.compile(r'[0-9a-f]{40}')
|
||||
TARGET_REF = 'refs/deploy/target'
|
||||
|
||||
TEA_ORIGIN = 'ssh://git@10.0.10.41:2222/alberto/tea.git'
|
||||
# The exact origin each gitlink may come from; the EEG library is the one repository outside the organisation.
|
||||
SUBMODULE_ORIGINS = {
|
||||
'ISSSTELEON': ORIGIN_BASE + 'ISSSTELEON.git',
|
||||
'ISSSTELEON/WebApp': ORIGIN_BASE + 'WebApp.git',
|
||||
'ISSSTELEON/WebApi': ORIGIN_BASE + 'WebApi.git',
|
||||
'ISSSTELEON/models': ORIGIN_BASE + 'models.git',
|
||||
'ISSSTELEON/models/libs/tea': TEA_ORIGIN,
|
||||
}
|
||||
# Application settings the installer fixes; an unset value falls back to the image's default, which is the same.
|
||||
PERSISTENT_ENV = {
|
||||
**{domain + '_DATABASE_URL': 'sqlite:////data/' + domain.lower() + '.db'
|
||||
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')},
|
||||
'MLFLOW_TRACKING_URI': 'sqlite:////data/mlflow.db',
|
||||
'MLFLOW_ARTIFACT_ROOT': '/data/mlflow-artefactos',
|
||||
'WEBAPI_REPORT_DIR': '/data/reportes',
|
||||
'INDICADORES_DIR': '/data/indicadores',
|
||||
}
|
||||
BASE_SERVICES = ('webapi', 'webapp', 'indicadores')
|
||||
NOTEBOOK_SERVICE = 'notebooks'
|
||||
NOTEBOOK_VOLUME = 'trabajos_notebooks'
|
||||
NOTEBOOK_JOBS = '/trabajos'
|
||||
NOTEBOOK_USER = '10001:10001'
|
||||
# Declared services that Compose leaves inactive unless their profile is enabled; never started here.
|
||||
PROFILE_SERVICES = ('entrenar',)
|
||||
|
||||
|
||||
def validate_port(text):
|
||||
"""The public port as an integer; protected ports are refused."""
|
||||
if not re.fullmatch(r'[0-9]{1,5}', str(text)) or not 1024 <= int(text) <= 65535:
|
||||
raise ValueError('puerto must be an integer from 1024 to 65535')
|
||||
port = int(text)
|
||||
if port in PROTECTED_PORTS:
|
||||
raise ValueError(f'port {port} is protected ({PROTECTED_PORTS[port]})')
|
||||
return port
|
||||
|
||||
|
||||
def project_for(port):
|
||||
return f'isssteleon-dev-{port}'
|
||||
|
||||
|
||||
def notebook_volume_name(project):
|
||||
return f'{project}_{NOTEBOOK_VOLUME}'
|
||||
|
||||
|
||||
def parse_reference(text):
|
||||
"""Classify a reference as a full commit SHA or a branch/tag name; abbreviations and ref paths are refused."""
|
||||
text = (text or '').strip()
|
||||
if not text:
|
||||
raise ValueError('referencia is required')
|
||||
if SHA.fullmatch(text):
|
||||
return 'commit', text
|
||||
if re.fullmatch(r'[0-9a-fA-F]{7,40}', text):
|
||||
raise ValueError('a commit must be given as its 40 lowercase hexadecimal characters')
|
||||
if text.startswith(('refs/', '-')) or text == '@' or any(c in text for c in ' \t\n\\'):
|
||||
raise ValueError('referencia must be a branch name, a tag name or a full commit SHA')
|
||||
try:
|
||||
proc.run(['git', 'check-ref-format', 'refs/heads/' + text])
|
||||
except Exception:
|
||||
raise ValueError('referencia is not a valid Git name') from None
|
||||
return 'name', text
|
||||
|
||||
|
||||
def resolve_reference(text, remote=None):
|
||||
"""Resolve a reference against the remote to `{'reference', 'kind', 'commit'}`.
|
||||
|
||||
A name that is both a branch and a tag, or neither, is refused. A commit is taken as given and checked
|
||||
when it is fetched."""
|
||||
remote = remote or OFFICIAL
|
||||
kind, value = parse_reference(text)
|
||||
if kind == 'commit':
|
||||
return {'reference': value, 'kind': 'commit', 'commit': value}
|
||||
listing = proc.run(['git', 'ls-remote', '--heads', '--tags', remote, 'refs/heads/' + value,
|
||||
'refs/tags/' + value, 'refs/tags/' + value + '^{}'])
|
||||
heads, tags, peeled = {}, {}, {}
|
||||
for line in listing.splitlines():
|
||||
sha, _, ref = line.partition('\t')
|
||||
if ref == 'refs/heads/' + value:
|
||||
heads[ref] = sha
|
||||
elif ref == 'refs/tags/' + value:
|
||||
tags[ref] = sha
|
||||
elif ref == 'refs/tags/' + value + '^{}':
|
||||
peeled[ref] = sha
|
||||
if heads and tags:
|
||||
raise ValueError(f'{value} is both a branch and a tag; use the full commit SHA')
|
||||
if not heads and not tags:
|
||||
raise ValueError(f'{value} is not a branch or a tag of the official repository')
|
||||
if heads:
|
||||
kind, commit = 'branch', next(iter(heads.values()))
|
||||
else:
|
||||
kind, commit = 'tag', next(iter(peeled.values()), None) or next(iter(tags.values()))
|
||||
if not SHA.fullmatch(commit):
|
||||
raise RuntimeError('the remote did not return a full commit SHA')
|
||||
return {'reference': value, 'kind': kind, 'commit': commit}
|
||||
|
||||
|
||||
def checkout(resolved, directory, remote=None):
|
||||
"""Fetch the resolved commit into `directory`, check it out and initialise the recognised gitlinks.
|
||||
|
||||
Returns the composition. Fails if the reference moved since it was resolved."""
|
||||
remote = remote or OFFICIAL
|
||||
directory = Path(directory)
|
||||
proc.run(['git', 'init', '--quiet', directory])
|
||||
if resolved['kind'] == 'commit':
|
||||
proc.git(directory, 'fetch', '--no-tags', remote, resolved['commit'])
|
||||
fetched = 'FETCH_HEAD'
|
||||
else:
|
||||
prefix = 'refs/heads/' if resolved['kind'] == 'branch' else 'refs/tags/'
|
||||
proc.git(directory, 'fetch', '--no-tags', remote, f'+{prefix}{resolved["reference"]}:{TARGET_REF}')
|
||||
fetched = TARGET_REF
|
||||
sha = proc.git(directory, 'rev-parse', '--verify', fetched + '^{commit}').strip()
|
||||
if sha != resolved['commit']:
|
||||
raise RuntimeError(f'{resolved["reference"]} moved from {resolved["commit"]} to {sha} while it was being resolved')
|
||||
proc.git(directory, 'checkout', '--quiet', '--detach', sha)
|
||||
checkout_pinned(directory)
|
||||
return composition_of(directory, resolved)
|
||||
|
||||
|
||||
def checkout_pinned(root):
|
||||
"""Initialise only recognised institutional gitlinks, each at the commit the parent records."""
|
||||
def visit(repo, prefix, selected=None):
|
||||
entries = proc.git(repo, 'ls-tree', '-rz', '--full-tree', 'HEAD', binary=True)
|
||||
for entry in entries.split(b'\0'):
|
||||
if not entry:
|
||||
continue
|
||||
meta, raw_path = entry.split(b'\t', 1)
|
||||
mode, _, sha = meta.decode().split()
|
||||
if mode != '160000':
|
||||
continue
|
||||
path = os.fsdecode(raw_path)
|
||||
if selected is not None and path != selected:
|
||||
continue
|
||||
full = f'{prefix}/{path}' if prefix else path
|
||||
if full not in SUBMODULE_ORIGINS or path in ('', '.', '..') or '..' in Path(path).parts:
|
||||
raise RuntimeError(f'unsupported application gitlink: {full}')
|
||||
config = proc.git(repo, 'config', '-f', '.gitmodules', '--get-regexp', r'^submodule\..*\.path$')
|
||||
matches = [line.split(None, 1)[0][len('submodule.'):-len('.path')]
|
||||
for line in config.splitlines() if len(line.split(None, 1)) == 2
|
||||
and line.split(None, 1)[1] == path]
|
||||
if len(matches) != 1 or not re.fullmatch(r'[A-Za-z0-9_-]+', matches[0]):
|
||||
raise RuntimeError(f'invalid submodule mapping: {full}')
|
||||
name = matches[0]
|
||||
origin = SUBMODULE_ORIGINS[full]
|
||||
if proc.git(repo, 'config', '-f', '.gitmodules', '--get', f'submodule.{name}.url').strip() != origin:
|
||||
raise RuntimeError(f'untrusted submodule origin: {full}')
|
||||
proc.git(repo, '-c', f'submodule.{name}.url={origin}', 'submodule', 'update', '--init', '--checkout',
|
||||
'--', path)
|
||||
child = repo / path
|
||||
if proc.git(child, 'rev-parse', 'HEAD').strip() != sha:
|
||||
raise RuntimeError(f'gitlink checkout mismatch: {full}')
|
||||
visit(child, full)
|
||||
|
||||
visit(Path(root), '', 'ISSSTELEON')
|
||||
|
||||
|
||||
def committed_trees(repo, revision, prefix=''):
|
||||
"""Walk the exact recursive gitlinks and reject any checkout that is not the recorded commit."""
|
||||
actual = proc.git(repo, 'rev-parse', 'HEAD').strip()
|
||||
if actual != revision:
|
||||
raise RuntimeError(f'{repo}: expected {revision}, found {actual}; initialize submodules recursively')
|
||||
yield repo, revision, prefix
|
||||
entries = proc.git(repo, 'ls-tree', '-rz', '--full-tree', revision, binary=True)
|
||||
for entry in entries.split(b'\0'):
|
||||
if not entry:
|
||||
continue
|
||||
meta, raw_path = entry.split(b'\t', 1)
|
||||
mode, _, sha = meta.decode().split()
|
||||
if mode != '160000':
|
||||
continue
|
||||
path = os.fsdecode(raw_path)
|
||||
if Path(path).is_absolute() or '..' in Path(path).parts:
|
||||
raise RuntimeError(f'unsafe gitlink path: {path}')
|
||||
yield from committed_trees(repo / path, sha, f'{prefix}/{path}' if prefix else path)
|
||||
|
||||
|
||||
def composition_of(root, resolved):
|
||||
"""The outer commit and the commit of every recognised gitlink, as an ordered mapping."""
|
||||
root = Path(root)
|
||||
outer = proc.git(root, 'rev-parse', 'HEAD').strip()
|
||||
pins = {}
|
||||
for line in proc.git(root, 'ls-tree', 'HEAD', 'ISSSTELEON', 'dev-data').splitlines():
|
||||
meta, _, path = line.partition('\t')
|
||||
mode, _, sha = meta.split()
|
||||
if mode == '160000':
|
||||
pins[path] = sha
|
||||
if 'ISSSTELEON' not in pins:
|
||||
raise RuntimeError('the outer repository does not pin ISSSTELEON')
|
||||
gitlinks = {'WorkingNarrative': outer, 'dev-data': pins.get('dev-data')}
|
||||
for prefix, sha in ((p or 'ISSSTELEON', s) for _, s, p in committed_trees(root / 'ISSSTELEON', pins['ISSSTELEON'])):
|
||||
gitlinks[prefix] = sha
|
||||
return {'reference': resolved['reference'], 'kind': resolved['kind'], 'commit': outer,
|
||||
'application': pins['ISSSTELEON'], 'gitlinks': gitlinks}
|
||||
|
||||
|
||||
def export_tree(repo, revision, dest, prefix=''):
|
||||
"""Export each committed tree below `repo`, following its exact gitlinks."""
|
||||
for child, sha, relative in committed_trees(repo, revision, prefix):
|
||||
target = Path(dest) / relative.removeprefix(prefix).lstrip('/')
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
archive = proc.git(child, 'archive', '--format=tar', sha, binary=True)
|
||||
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
|
||||
tar.extractall(target, filter='data')
|
||||
|
||||
|
||||
def digest_text(value):
|
||||
"""Canonical JSON used to compare plans."""
|
||||
return json.dumps(value, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
def copy_deploy(source, deploy):
|
||||
shutil.copytree(Path(source) / 'dist', deploy, symlinks=True)
|
||||
@@ -1,538 +0,0 @@
|
||||
"""Coordinate a schema-compatible application update without replacing storage."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
import shutil
|
||||
import sqlite3
|
||||
|
||||
INSPECTION_REASONS = frozenset({
|
||||
'persistent_directory_invalid', 'linked_persistent_entry', 'special_persistent_entry',
|
||||
'database_missing_or_linked', 'contract_domains_invalid', 'migration_version_unavailable',
|
||||
'migration_version_count', 'migration_revision_unknown', 'migration_pending', 'schema_mismatch',
|
||||
'sqlite_integrity_failed', 'sqlite_foreign_key_failed', 'schema_triggers_unsupported',
|
||||
'schema_options_unsupported', 'schema_columns_unsupported', 'schema_partial_indexes_unsupported',
|
||||
'schema_expression_indexes_unsupported', 'schema_constraint_invalid', 'unclassified',
|
||||
'directory_identity_changed', 'directory_disappeared', 'database_identity_changed',
|
||||
'audit_log_disappeared', 'audit_history_changed', 'auxiliary_integrity_failed',
|
||||
'protected_rows_changed', 'historical_rows_changed', 'persistent_file_changed',
|
||||
})
|
||||
INSPECTION_TYPES = frozenset({'RuntimeError', 'OperationalError', 'DatabaseError', 'IntegrityError',
|
||||
'PermissionError', 'FileNotFoundError', 'OSError', 'ValueError',
|
||||
'TypeError', 'KeyError', 'MemoryError', 'Other'})
|
||||
SQLITE_NAMES = {name for name in dir(sqlite3) if name.startswith('SQLITE_')
|
||||
and isinstance(getattr(sqlite3, name), int)}
|
||||
|
||||
PERSISTENT_ENV = {
|
||||
**{domain + '_DATABASE_URL': 'sqlite:////data/' + domain.lower() + '.db'
|
||||
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')},
|
||||
'MLFLOW_TRACKING_URI': 'sqlite:////data/mlflow.db',
|
||||
'MLFLOW_ARTIFACT_ROOT': '/data/mlflow-artefactos',
|
||||
'WEBAPI_REPORT_DIR': '/data/reportes',
|
||||
'INDICADORES_DIR': '/data/indicadores',
|
||||
}
|
||||
|
||||
|
||||
def failure_detail(exc):
|
||||
"""Describe subprocess failures without exposing their potentially sensitive output."""
|
||||
if not isinstance(exc, subprocess.CalledProcessError):
|
||||
return 'error type=' + type(exc).__name__
|
||||
detail = 'exit=' + str(exc.returncode)
|
||||
stderr = exc.stderr if isinstance(exc.stderr, str) else ''
|
||||
frames = re.findall(r'File "<string>", line (\d+), in ([A-Za-z_][A-Za-z_0-9]*)', stderr)
|
||||
allowed = {'main', 'backup_installation', 'verify_isolated_restore', 'create_backup',
|
||||
'verify_backup', 'restore_backup', 'storage_state', 'regular_tree',
|
||||
'inspect_databases', 'readonly', 'digest', 'sqlite_digest', 'require'}
|
||||
frames = [(line, name) for line, name in frames if name in allowed]
|
||||
if len(frames) > 1 and frames[-1][1] == 'require':
|
||||
frames.pop()
|
||||
if frames:
|
||||
line, name = frames[-1]
|
||||
detail += f', location={name}:{line}'
|
||||
match = re.search(r'(?m)^(PermissionError|FileNotFoundError|FileExistsError|OSError|'
|
||||
r'OperationalError|DatabaseError|IntegrityError|RuntimeError|ValueError|'
|
||||
r'JSONDecodeError|KeyError|TypeError|MemoryError)(?::|$)', stderr)
|
||||
if match:
|
||||
detail += ', error type=' + match.group(1)
|
||||
match = re.search(r'\[Errno (\d{1,4})\]', stderr)
|
||||
if match:
|
||||
detail += ', errno=' + match.group(1)
|
||||
for line in stderr.splitlines():
|
||||
prefix = line.partition('=')[0]
|
||||
if prefix not in ('WN_INSPECT_DIAGNOSTIC', 'WN_RECALC_DIAGNOSTIC', 'WN_VERIFY_DIAGNOSTIC'):
|
||||
continue
|
||||
try:
|
||||
diagnostic = json.loads(line.partition('=')[2])
|
||||
fields = {'reason', 'domain', 'type', 'sqlite', 'errno'}
|
||||
if prefix == 'WN_RECALC_DIAGNOSTIC':
|
||||
fields.add('stage')
|
||||
if (not isinstance(diagnostic, dict)
|
||||
or set(diagnostic) != fields
|
||||
or diagnostic['reason'] not in INSPECTION_REASONS
|
||||
or diagnostic['domain'] not in {'cacu', 'cama', 'tea', 'governance', 'none'}
|
||||
or diagnostic['type'] not in INSPECTION_TYPES
|
||||
or diagnostic['sqlite'] not in SQLITE_NAMES | {'none'}
|
||||
or (prefix == 'WN_RECALC_DIAGNOSTIC' and diagnostic['stage'] not in
|
||||
{'environment', 'import', 'initialize', 'enqueue', 'execute', 'domain_result', 'pending', 'unknown'})
|
||||
or (diagnostic['errno'] is not None and
|
||||
(type(diagnostic['errno']) is not int or not 0 <= diagnostic['errno'] <= 4095))):
|
||||
continue
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
detail += (f", reason={diagnostic['reason']}, domain={diagnostic['domain']}, "
|
||||
f"type={diagnostic['type']}, sqlite={diagnostic['sqlite']}")
|
||||
if prefix == 'WN_RECALC_DIAGNOSTIC':
|
||||
detail += ', stage=' + diagnostic['stage']
|
||||
if diagnostic['errno'] is not None:
|
||||
detail += ', errno=' + str(diagnostic['errno'])
|
||||
break
|
||||
return detail
|
||||
|
||||
|
||||
class GuardFailure(RuntimeError):
|
||||
"""A storage inspection failure with sanitized diagnostics."""
|
||||
|
||||
def __init__(self, action, detail):
|
||||
self.detail = detail
|
||||
super().__init__(action + ': candidate storage validation failed (' + detail + ')')
|
||||
|
||||
|
||||
class RecalculationFailure(RuntimeError):
|
||||
"""A sanitized failure in a specific recalculation operation."""
|
||||
|
||||
def __init__(self, step, category):
|
||||
self.step, self.category = step, category
|
||||
super().__init__('recalculation failed')
|
||||
|
||||
|
||||
def recalculation_step(step, operation):
|
||||
try:
|
||||
return operation()
|
||||
except GuardFailure as exc:
|
||||
raise RecalculationFailure(step, exc.detail) from None
|
||||
except Exception as exc:
|
||||
kind = type(exc).__name__
|
||||
kind = kind if kind in INSPECTION_TYPES | {'JSONDecodeError'} else 'Other'
|
||||
raise RecalculationFailure(step, 'error type=' + kind) from None
|
||||
|
||||
|
||||
def guard(api, image, action, payload, data=None, *, writable=False):
|
||||
"""Run inspection in the candidate image, overriding every application entrypoint."""
|
||||
script = Path(__file__).with_name('data_guard.py').read_text(encoding='utf-8')
|
||||
args = ['docker', 'run', '--rm', '-i', '--pull', 'never', '--network', 'none', '--read-only',
|
||||
'--tmpfs', '/tmp:rw,nosuid,nodev', '--workdir', '/app/WebApi']
|
||||
args += ['--env', 'PYTHONDONTWRITEBYTECODE=1', '--env', 'HOME=/tmp']
|
||||
if data is not None:
|
||||
args += ['--mount', f'type=bind,src={data},dst=/data' + ('' if writable else ',readonly')]
|
||||
args += ['--entrypoint', '/app/WebApi/.venv/bin/python', image, '-B', '-c', script, action]
|
||||
try:
|
||||
return json.loads(api.run(args, stdin=json.dumps(payload)))
|
||||
except Exception as exc:
|
||||
raise GuardFailure(action, failure_detail(exc)) from None
|
||||
|
||||
|
||||
def environment(container):
|
||||
return dict(value.split('=', 1) for value in container.get('Config', {}).get('Env', []) if '=' in value)
|
||||
|
||||
|
||||
def read_deployment(api, helper, project, directory):
|
||||
document = json.loads(api.host_action(helper, 'read-deploy', project, ''))
|
||||
directory.mkdir()
|
||||
for name in ('.env', 'docker-compose.yml'):
|
||||
(directory / name).write_text(document[name], encoding='utf-8')
|
||||
(directory / name).chmod(0o600)
|
||||
return document
|
||||
|
||||
|
||||
def current_environment(api, ids, config):
|
||||
items = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
services = {item['Config']['Labels']['com.docker.compose.service']: item for item in items}
|
||||
for name in ('webapi', 'indicadores'):
|
||||
actual = environment(services[name])
|
||||
if any(actual.get(key) != value for key, value in PERSISTENT_ENV.items()):
|
||||
raise RuntimeError('only the managed local SQLite storage layout is supported')
|
||||
declared = config['services'][name].get('environment', {})
|
||||
if any(value is None or actual.get(key) != str(value) for key, value in declared.items()):
|
||||
raise RuntimeError('running environment differs from retained deployment configuration')
|
||||
|
||||
|
||||
def write_configuration(api, deploy, data, record, revision, original_env):
|
||||
tag = api.configure(deploy, data, record['project'], revision, record['port'])
|
||||
# Retain operator configuration, including values absent from a newer image's defaults.
|
||||
replacements = {'ISSSTELEON_VERSION': tag, 'ISSSTELEON_DATOS': str(data),
|
||||
'ISSSTELEON_PUERTO': str(record['port']), **PERSISTENT_ENV}
|
||||
text = original_env.rstrip() + '\n'
|
||||
for key, value in replacements.items():
|
||||
if any(char in str(value) for char in ("'", '\n', '\r', '\x00')):
|
||||
raise RuntimeError('invalid managed configuration value')
|
||||
text += key + "='" + str(value) + "'\n"
|
||||
(deploy / '.env').write_text(text, encoding='utf-8')
|
||||
(deploy / '.env').chmod(0o600)
|
||||
return tag
|
||||
|
||||
|
||||
def controlled_config(config, *, migrate_on_start=False):
|
||||
"""Keep the worker idle until the checked one-shot recalculation has completed."""
|
||||
api = config['services']['webapi']
|
||||
worker = config['services']['indicadores']
|
||||
for service in (api, worker):
|
||||
service['environment'] = dict(service.get('environment', {}), **PERSISTENT_ENV)
|
||||
if any(not isinstance(value, str) for value in service['environment'].values()):
|
||||
raise RuntimeError('all candidate environment values must be resolved strings')
|
||||
if not migrate_on_start:
|
||||
env = api['environment']
|
||||
if str(env.get('PORT', '5000')) != '5000':
|
||||
raise RuntimeError('the managed API must listen on port 5000')
|
||||
workers, timeout = str(env.get('WEBAPI_WORKERS', '2')), str(env.get('WEBAPI_TIMEOUT', '600'))
|
||||
if not workers.isdigit() or not 1 <= int(workers) <= 32 or not timeout.isdigit() or int(timeout) < 1:
|
||||
raise RuntimeError('invalid API process configuration')
|
||||
api['working_dir'] = '/app/WebApi'
|
||||
api['entrypoint'] = ['/app/WebApi/.venv/bin/python', '-m', 'gunicorn',
|
||||
'--bind', '0.0.0.0:5000', '--workers', workers,
|
||||
'--timeout', timeout, '--access-logfile', '-', 'webapi:create_app()']
|
||||
api['command'] = []
|
||||
worker['working_dir'] = '/app/WebApi'
|
||||
worker['entrypoint'] = ['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos']
|
||||
worker['command'] = []
|
||||
worker['environment']['INDICADORES_AL_INICIAR'] = '0'
|
||||
return config
|
||||
|
||||
|
||||
def persist_config(deploy, config):
|
||||
def literal(value):
|
||||
if isinstance(value, str):
|
||||
return value.replace('$', '$$')
|
||||
if isinstance(value, list):
|
||||
return [literal(item) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {key: literal(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
path = deploy / 'docker-compose.yml'
|
||||
path.write_text(json.dumps(literal(config), indent=2), encoding='utf-8')
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def verify_api(api, cmd, data, image, *, timeout=300):
|
||||
deadline = time.monotonic() + timeout
|
||||
expected = api.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
|
||||
while time.monotonic() < deadline:
|
||||
ids = api.run([*cmd, 'ps', '-q', 'webapi']).splitlines()
|
||||
if len(ids) == 1:
|
||||
item = json.loads(api.run(['docker', 'inspect', ids[0]]))[0]
|
||||
if item.get('State', {}).get('Health', {}).get('Status') == 'healthy':
|
||||
mounts = item.get('Mounts', [])
|
||||
if (item.get('Image') != expected or len(mounts) != 1
|
||||
or mounts[0].get('Source') != str(data) or mounts[0].get('Destination') != '/data'
|
||||
or mounts[0].get('Type') != 'bind' or mounts[0].get('RW') is not True
|
||||
or any(environment(item).get(k) != v for k, v in PERSISTENT_ENV.items())):
|
||||
raise RuntimeError('updated API storage or image identity differs')
|
||||
return
|
||||
time.sleep(2)
|
||||
raise RuntimeError('updated API did not become healthy')
|
||||
|
||||
|
||||
def finish(api, cmd, image, deploy, data, contract, before, progress=None):
|
||||
progress = progress or (lambda phase: None)
|
||||
verify_api(api, cmd, data, image)
|
||||
guard(api, image, 'verify', {'data': '/data', 'contract': contract, 'before': before}, data, writable=True)
|
||||
progress('recalculation-and-persistence')
|
||||
def load_configuration():
|
||||
environment = json.loads((deploy / 'docker-compose.yml').read_text(encoding='utf-8'))[
|
||||
'services']['indicadores']['environment']
|
||||
return {key: value.replace('$$', '$') for key, value in environment.items()}
|
||||
worker_environment = recalculation_step('load-configuration', load_configuration)
|
||||
# Compose .env quoting differs from docker --env-file. Transport resolved values privately.
|
||||
result = recalculation_step('execute-recalculation', lambda: guard(
|
||||
api, image, 'recalculate', {'environment': worker_environment}, data, writable=True))
|
||||
def validate_result():
|
||||
if result != {'completed': ['cacu', 'cama', 'tea']}:
|
||||
raise RecalculationFailure('validate-result', 'incomplete or invalid result')
|
||||
validate_result()
|
||||
after = recalculation_step('verify-persistence', lambda: guard(
|
||||
api, image, 'verify', {'data': '/data', 'contract': contract, 'before': before, 'derived': True}, data,
|
||||
writable=True))
|
||||
progress('worker')
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'indicadores'])
|
||||
progress('frontend')
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapp'])
|
||||
return after
|
||||
|
||||
|
||||
def freeze_failed(api, cmd, project, data):
|
||||
"""Stop only verified instance containers; retain them and all storage for recovery."""
|
||||
ids = api.run([*cmd, 'ps', '-a', '-q']).splitlines()
|
||||
if not ids:
|
||||
return
|
||||
items = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
for item in items:
|
||||
labels = item.get('Config', {}).get('Labels') or {}
|
||||
if (labels.get('com.docker.compose.project') != project
|
||||
or labels.get('com.docker.compose.service') not in ('webapi', 'webapp', 'indicadores')):
|
||||
raise RuntimeError('failed container ownership is uncertain')
|
||||
if labels['com.docker.compose.service'] != 'webapp':
|
||||
mounts = item.get('Mounts', [])
|
||||
if (len(mounts) != 1 or mounts[0].get('Type') != 'bind'
|
||||
or mounts[0].get('Source') != str(data) or mounts[0].get('Destination') != '/data'):
|
||||
raise RuntimeError('failed container storage is uncertain')
|
||||
for container in ids:
|
||||
api.run(['docker', 'update', '--restart=no', container])
|
||||
api.run(['docker', 'stop', container])
|
||||
|
||||
|
||||
def container_snapshot(api, ids):
|
||||
items = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
if len(items) != len(ids) or [item.get('Id') for item in items] != ids:
|
||||
raise RuntimeError('original container identities changed')
|
||||
return items
|
||||
|
||||
|
||||
def recover_original(api, record, helper, base, ids, original, previous_cmd, initial):
|
||||
"""Restart only the original containers after confirming their retained state."""
|
||||
current = container_snapshot(api, ids)
|
||||
for old, item in zip(original, current):
|
||||
if (item.get('Image') != old.get('Image') or item.get('Mounts') != old.get('Mounts')
|
||||
or item.get('Config') != old.get('Config')):
|
||||
raise RuntimeError('original container identity or mounts changed')
|
||||
policy = old.get('HostConfig', {}).get('RestartPolicy', {})
|
||||
if policy.get('Name') not in ('no', 'always', 'unless-stopped', 'on-failure'):
|
||||
raise RuntimeError('original restart policy is unsupported')
|
||||
if type(policy.get('MaximumRetryCount', 0)) is not int or policy.get('MaximumRetryCount', 0) < 0:
|
||||
raise RuntimeError('original restart retry count is invalid')
|
||||
api_config = current[1]['Config']
|
||||
if not current[1].get('State', {}).get('Running'):
|
||||
entry = api_config.get('Entrypoint')
|
||||
if (not isinstance(entry, list) or len(entry) != 12
|
||||
or entry[:5] != ['/app/WebApi/.venv/bin/python', '-m', 'gunicorn', '--bind', '0.0.0.0:5000']
|
||||
or entry[5] != '--workers' or not str(entry[6]).isdigit()
|
||||
or entry[7] != '--timeout' or not str(entry[8]).isdigit()
|
||||
or entry[9:] != ['--access-logfile', '-', 'webapi:create_app()']
|
||||
or api_config.get('Cmd') not in (None, [])):
|
||||
raise RuntimeError('original API restart entrypoint is not verified migration-free')
|
||||
worker_config = current[0]['Config']
|
||||
if not current[0].get('State', {}).get('Running'):
|
||||
if (worker_config.get('Entrypoint') != ['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos']
|
||||
or worker_config.get('Cmd') not in (None, [])
|
||||
or environment(current[0]).get('INDICADORES_AL_INICIAR') != '0'):
|
||||
raise RuntimeError('original worker restart entrypoint is not verified safe')
|
||||
image = record['images'][0]
|
||||
contract = guard(api, image, 'contract', {})
|
||||
all_stopped = all(item.get('State', {}).get('Running') is False for item in current)
|
||||
state = guard(api, image, 'inspect', {'data': '/data', 'contract': contract, 'quiesced': all_stopped},
|
||||
base / record['project'] / 'data')
|
||||
if state != initial:
|
||||
raise RuntimeError('original storage identity or schema changed')
|
||||
for old, item in zip(original, current):
|
||||
policy = old['HostConfig']['RestartPolicy']
|
||||
value = policy['Name']
|
||||
if value == 'on-failure' and policy.get('MaximumRetryCount', 0):
|
||||
value += ':' + str(policy['MaximumRetryCount'])
|
||||
api.run(['docker', 'update', '--restart=' + value, item['Id']])
|
||||
for index in (1, 0, 2):
|
||||
if not current[index].get('State', {}).get('Running'):
|
||||
api.run(['docker', 'start', ids[index]])
|
||||
if api.verify_existing_containers(record, base, helper) != ids:
|
||||
raise RuntimeError('original container identities changed after restart')
|
||||
api.verify_services(previous_cmd, record['port'])
|
||||
for old, item in zip(original, container_snapshot(api, ids)):
|
||||
if (item.get('HostConfig', {}).get('RestartPolicy')
|
||||
!= old.get('HostConfig', {}).get('RestartPolicy')):
|
||||
raise RuntimeError('original restart policy was not restored')
|
||||
|
||||
|
||||
def update(api, record, helper, root, base, *, verify_restore=False):
|
||||
if (record.get('status') != 'installed'
|
||||
or not isinstance(record.get('revision'), str)
|
||||
or not re.fullmatch(r'[0-9a-f]{40}', record['revision'])
|
||||
or not isinstance(record.get('gitlinks'), dict)
|
||||
or 'ISSSTELEON' not in record['gitlinks']
|
||||
or any(not isinstance(sha, str) or not re.fullmatch(r'[0-9a-f]{40}', sha)
|
||||
for sha in record['gitlinks'].values())):
|
||||
raise RuntimeError('installation status or Git provenance is invalid; manual inspection required')
|
||||
project, port = record['project'], record['port']
|
||||
revision = api.git(root, 'rev-parse', 'HEAD').strip()
|
||||
expected = api.git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
|
||||
old_ids = api.verify_existing_containers(record, base, helper)
|
||||
phase = 'preparing'
|
||||
current = None
|
||||
operation_step = None
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-update-') as tmp:
|
||||
directory = Path(tmp)
|
||||
source, deploy, old_deploy = directory / 'codigo', directory / 'deploy', directory / 'old-deploy'
|
||||
data = base / project / 'data'
|
||||
try:
|
||||
retained = read_deployment(api, helper, project, old_deploy)
|
||||
previous_cmd = api.compose(project, old_deploy)
|
||||
old_config = json.loads(api.run([*previous_cmd, 'config', '--format', 'json']))
|
||||
old_tag = record['images'][0].removeprefix('isssteleon/webapi:')
|
||||
api.verify_config(old_config, project, data, old_tag, port)
|
||||
current_environment(api, old_ids, old_config)
|
||||
if revision == record['revision']:
|
||||
phase = 'same-revision-verification'
|
||||
operation_step = 'verify dispatched gitlinks against installation record'
|
||||
manifest = api.pinned_manifest(root / 'ISSSTELEON', expected)
|
||||
if record['gitlinks'] != manifest:
|
||||
raise RuntimeError('recorded gitlinks differ from the dispatched revision')
|
||||
operation_step = 'inspect installed storage contract'
|
||||
contract = guard(api, record['images'][0], 'contract', {})
|
||||
guard(api, record['images'][0], 'inspect', {'data': '/data', 'contract': contract}, data)
|
||||
operation_step = 'verify installed services and image identities'
|
||||
verify_api(api, previous_cmd, data, record['images'][0])
|
||||
api.verify_services(previous_cmd, port)
|
||||
if api.verify_existing_containers(record, base, helper) != old_ids:
|
||||
raise RuntimeError('installation containers changed during verification')
|
||||
operation_step = 'record verified no-op'
|
||||
api.host_action(helper, 'save', project, json.dumps(dict(
|
||||
record, result='unchanged', verification='complete')))
|
||||
print(f'Unchanged {project} on port {port} at {revision}; verification complete')
|
||||
return
|
||||
manifest = {}
|
||||
api.export_tree(root / 'ISSSTELEON', expected, source, manifest)
|
||||
shutil.copytree(source / 'dist', deploy, symlinks=True)
|
||||
tag = write_configuration(api, deploy, data, record, revision, retained['.env'])
|
||||
images = [f'isssteleon/webapi:{tag}', f'isssteleon/webapp:{tag}']
|
||||
api.run(['docker', 'build', '-t', images[0], '-f', source / 'WebApi/Dockerfile', source])
|
||||
api.run(['docker', 'build', '-t', images[1], source / 'WebApp'])
|
||||
cmd = api.compose(project, deploy)
|
||||
config = controlled_config(json.loads(api.run([*cmd, 'config', '--format', 'json'])))
|
||||
api.verify_config(config, project, data, tag, port)
|
||||
persist_config(deploy, config)
|
||||
phase = 'compatibility'
|
||||
contract = guard(api, images[0], 'contract', {})
|
||||
initial = guard(api, images[0], 'inspect', {'data': '/data', 'contract': contract}, data)
|
||||
prepared_bytes = sum(p.stat().st_size for tree in (source, deploy)
|
||||
for p in tree.rglob('*') if p.is_file())
|
||||
api.host_action(helper, 'update-space-restore' if verify_restore else 'update-space',
|
||||
project, str(prepared_bytes))
|
||||
operation_step = 'prepare backup destinations in helper'
|
||||
api.host_action(helper, 'prepare-backup', project,
|
||||
json.dumps({'verify_restore': verify_restore}))
|
||||
operation_step = None
|
||||
if api.verify_existing_containers(record, base, helper) != old_ids:
|
||||
raise RuntimeError('installation containers changed during preparation')
|
||||
original_containers = container_snapshot(api, old_ids)
|
||||
operation = uuid.uuid4().hex
|
||||
current = dict(record, status='updating', operation_id=operation, phase='quiescing',
|
||||
target_revision=revision, target_images=images, target_gitlinks=manifest,
|
||||
migrations='none-pending', recalculation='not-started')
|
||||
|
||||
def save():
|
||||
api.host_action(helper, 'save', project, json.dumps(current))
|
||||
|
||||
save()
|
||||
phase = 'quiescing'
|
||||
for container in old_ids:
|
||||
api.run(['docker', 'update', '--restart=no', container])
|
||||
api.run(['docker', 'stop', container])
|
||||
for container in old_ids:
|
||||
state = json.loads(api.run(['docker', 'inspect', '--format', '{{json .State}}', container]))
|
||||
if state.get('Running') is not False:
|
||||
raise RuntimeError('an existing writer did not stop')
|
||||
phase = 'backup'
|
||||
current['phase'] = phase
|
||||
current['backup'] = str(base / '.backups' / project / operation)
|
||||
operation_step = 'save backup phase record'
|
||||
save()
|
||||
operation_step = 'inspect quiesced storage'
|
||||
quiesced = guard(api, images[0], 'inspect', {'data': '/data', 'contract': contract,
|
||||
'quiesced': True}, data)
|
||||
operation_step = 'compare storage identity and schema'
|
||||
if quiesced != initial:
|
||||
raise RuntimeError('storage identity or schema changed during preparation')
|
||||
origin = {key: record[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images') if key in record}
|
||||
operation_step = 'create and verify backup in helper'
|
||||
backup = json.loads(api.host_action(helper, 'backup', project, json.dumps({
|
||||
'operation_id': operation, 'contract': contract, 'origin': origin})))
|
||||
if verify_restore:
|
||||
current['phase'] = phase = 'restore-verification'
|
||||
current['restore_check'] = str(base / '.restores' / project / operation)
|
||||
operation_step = 'save restore verification record'
|
||||
save()
|
||||
operation_step = 'restore and verify backup in helper'
|
||||
api.host_action(helper, 'verify-restore', project, operation)
|
||||
current['phase'] = phase = 'activating'
|
||||
current['archive'] = str(base / project / '.archive' / operation)
|
||||
save()
|
||||
api.host_action(helper, 'stage', project, operation)
|
||||
for name, path in (('codigo', source), ('deploy', deploy)):
|
||||
api.copy_to_host(helper, path, project, '.updates/' + operation + '/' + name)
|
||||
api.host_action(helper, 'activate', project, json.dumps({
|
||||
'operation_id': operation, 'previous': record}))
|
||||
current['phase'] = phase = 'api'
|
||||
save()
|
||||
# No pending migrations are supported; the direct entrypoint cannot run Alembic.
|
||||
api.run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapi'])
|
||||
|
||||
def progress(next_phase):
|
||||
nonlocal phase
|
||||
current['phase'] = phase = next_phase
|
||||
if next_phase == 'recalculation-and-persistence':
|
||||
current['recalculation'] = 'running'
|
||||
elif next_phase == 'worker':
|
||||
current['recalculation'] = 'complete'
|
||||
save()
|
||||
|
||||
finish(api, cmd, images[0], deploy, data, contract, backup['state'], progress)
|
||||
current['phase'] = phase = 'availability'
|
||||
save()
|
||||
api.verify_services(cmd, port)
|
||||
api.verify_existing_containers(dict(record, images=images), base, helper)
|
||||
guard(api, images[0], 'verify',
|
||||
{'data': '/data', 'contract': contract, 'before': backup['state'], 'derived': True}, data)
|
||||
current.update(status='installed', revision=revision, gitlinks=manifest, images=images,
|
||||
phase='complete', result='updated', recalculation='complete', verification='complete')
|
||||
current.pop('error', None)
|
||||
save()
|
||||
print(f'Updated {project} on port {port} at {revision}')
|
||||
except Exception as exc:
|
||||
failure_record_unavailable = False
|
||||
if current is not None:
|
||||
if phase in ('api', 'recalculation-and-persistence', 'worker', 'frontend', 'availability'):
|
||||
try:
|
||||
freeze_failed(api, cmd, project, data)
|
||||
except Exception:
|
||||
current['quarantine'] = 'incomplete; inspect owned containers before recovery'
|
||||
current.update(status='update_failed', phase=phase,
|
||||
error='Update failed; preserve storage and inspect recovery metadata.',
|
||||
recovery='manual; never restore over live data automatically')
|
||||
# Retain original provenance; target references remain separate for recovery.
|
||||
for key in ('revision', 'gitlinks', 'images'):
|
||||
if key in record:
|
||||
current[key] = record[key]
|
||||
if phase in ('quiescing', 'backup', 'restore-verification'):
|
||||
try:
|
||||
api.host_action(helper, 'save', project, json.dumps(current))
|
||||
except Exception:
|
||||
failure_record_unavailable = True
|
||||
try:
|
||||
recover_original(api, record, helper, base, old_ids, original_containers,
|
||||
previous_cmd, initial)
|
||||
current['recovery'] = 'original services verified; reconciliation required'
|
||||
except Exception:
|
||||
current['recovery'] = 'incomplete; inspect original services before reconciliation'
|
||||
try:
|
||||
api.host_action(helper, 'save', project, json.dumps(current))
|
||||
failure_record_unavailable = False
|
||||
except Exception:
|
||||
failure_record_unavailable = True
|
||||
else:
|
||||
api.host_action(helper, 'save', project, json.dumps(current))
|
||||
detail = ''
|
||||
if phase in ('compatibility', 'same-revision-verification') and isinstance(exc, GuardFailure):
|
||||
detail = '; ' + str(exc)
|
||||
elif phase == 'same-revision-verification':
|
||||
detail = '; operation=' + operation_step + '; ' + failure_detail(exc)
|
||||
if phase in ('compatibility', 'backup', 'restore-verification') and operation_step:
|
||||
detail = '; operation=' + operation_step + '; ' + failure_detail(exc)
|
||||
if operation_step == 'inspect quiesced storage' and isinstance(exc, GuardFailure):
|
||||
detail = '; operation=' + operation_step + '; ' + str(exc)
|
||||
if phase == 'recalculation-and-persistence' and isinstance(exc, RecalculationFailure):
|
||||
detail = '; operation=' + exc.step + '; ' + exc.category
|
||||
if failure_record_unavailable:
|
||||
detail += '; failure record could not be saved; inspect the installation manually'
|
||||
raise RuntimeError('Conservative update failed during ' + phase
|
||||
+ '; existing storage was not replaced' + detail) from None
|
||||
@@ -1,554 +0,0 @@
|
||||
"""Inspect SQLite metadata and verify quiesced synthetic or deployed storage.
|
||||
|
||||
Only contract generation imports application packages. Inspection never imports
|
||||
Persistance's engine factories or runs a migration.
|
||||
"""
|
||||
|
||||
from collections import Counter
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import stat
|
||||
import sys
|
||||
|
||||
DOMAINS = ('cacu', 'cama', 'tea', 'governance')
|
||||
APP_DATABASES = {domain + '.db' for domain in DOMAINS}
|
||||
INSPECTION_REASONS = {
|
||||
'persistent directory is missing or linked': 'persistent_directory_invalid',
|
||||
'linked persistent entry is unsupported': 'linked_persistent_entry',
|
||||
'special persistent entry is unsupported': 'special_persistent_entry',
|
||||
'required SQLite file is missing or linked': 'database_missing_or_linked',
|
||||
'four domain contracts are required': 'contract_domains_invalid',
|
||||
'Alembic version is unavailable': 'migration_version_unavailable',
|
||||
'exactly one installed revision is required': 'migration_version_count',
|
||||
'unknown Alembic revision': 'migration_revision_unknown',
|
||||
'pending migrations are not supported': 'migration_pending',
|
||||
'structure differs from the candidate': 'schema_mismatch',
|
||||
'SQLite integrity check failed': 'sqlite_integrity_failed',
|
||||
'SQLite foreign key check failed': 'sqlite_foreign_key_failed',
|
||||
'database triggers are unsupported': 'schema_triggers_unsupported',
|
||||
'custom table options are unsupported': 'schema_options_unsupported',
|
||||
'hidden or generated columns are unsupported': 'schema_columns_unsupported',
|
||||
'partial indexes are unsupported': 'schema_partial_indexes_unsupported',
|
||||
'expression indexes are unsupported': 'schema_expression_indexes_unsupported',
|
||||
'unclosed schema constraint': 'schema_constraint_invalid',
|
||||
'persistent directory identity changed': 'directory_identity_changed',
|
||||
'persistent directory disappeared': 'directory_disappeared',
|
||||
'database file identity changed': 'database_identity_changed',
|
||||
'indicator audit log disappeared': 'audit_log_disappeared',
|
||||
'indicator audit history changed': 'audit_history_changed',
|
||||
'auxiliary SQLite integrity check failed': 'auxiliary_integrity_failed',
|
||||
}
|
||||
INSPECTION_ERROR_TYPES = {'RuntimeError', 'OperationalError', 'DatabaseError', 'IntegrityError',
|
||||
'PermissionError', 'FileNotFoundError', 'OSError', 'ValueError',
|
||||
'TypeError', 'KeyError', 'MemoryError', 'Other'}
|
||||
SQLITE_ERROR_NAMES = {name for name in dir(sqlite3) if name.startswith('SQLITE_')
|
||||
and isinstance(getattr(sqlite3, name), int)}
|
||||
MUTABLE = {
|
||||
'persona', 'procedimiento', 'observacion_clinica', 'def_parametro',
|
||||
'dim_fecha', 'dim_grupo_edad', 'periodo_observacion', 'dim_periodo',
|
||||
'cat_estudio', 'cat_resultado', 'cat_valor', 'cat_estrato',
|
||||
'cat_estrato_valor', 'cat_measure', 'cat_measure_resultado',
|
||||
'cat_measure_valor', 'cat_measure_grupo', 'cat_measure_estrato',
|
||||
}
|
||||
APPEND_ONLY = {
|
||||
'carga', 'measure_report', 'measure_report_unidad',
|
||||
'measure_report_unidad_estrato', 'cohorte_armado', 'cohorte_miembro',
|
||||
'cohorte_exclusion', 'cohorte_variable',
|
||||
}
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def quote(name):
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def identity(path):
|
||||
info = Path(path).stat()
|
||||
return [info.st_dev, info.st_ino]
|
||||
|
||||
|
||||
def digest(path):
|
||||
result = hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
result.update(chunk)
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def regular_tree(root):
|
||||
root = Path(root)
|
||||
require(root.is_dir() and not root.is_symlink(), 'persistent directory is missing or linked')
|
||||
files = {}
|
||||
for path in sorted(root.rglob('*')):
|
||||
require(not path.is_symlink(), 'linked persistent entry is unsupported')
|
||||
mode = path.stat().st_mode
|
||||
require(stat.S_ISDIR(mode) or stat.S_ISREG(mode), 'special persistent entry is unsupported')
|
||||
if path.is_file():
|
||||
files[path.relative_to(root).as_posix()] = path
|
||||
return files
|
||||
|
||||
|
||||
def readonly(path, *, immutable=False):
|
||||
path = Path(path)
|
||||
require(path.is_file() and not path.is_symlink(), 'required SQLite file is missing or linked')
|
||||
connection = sqlite3.connect(path.resolve().as_uri() + '?mode=ro' + ('&immutable=1' if immutable else ''),
|
||||
uri=True, timeout=10)
|
||||
connection.execute('PRAGMA query_only=ON')
|
||||
return connection
|
||||
|
||||
|
||||
def checks(sql):
|
||||
"""Normalize CHECK bodies without depending on generated constraint names."""
|
||||
result = []
|
||||
for match in re.finditer(r'\bCHECK\s*\(', sql or '', re.I):
|
||||
start = match.end()
|
||||
depth, quoted, i = 1, None, start
|
||||
while depth and i < len(sql):
|
||||
char = sql[i]
|
||||
if quoted:
|
||||
if char == quoted:
|
||||
if i + 1 < len(sql) and sql[i + 1] == quoted:
|
||||
i += 1
|
||||
else:
|
||||
quoted = None
|
||||
elif char in ("'", '"'):
|
||||
quoted = char
|
||||
elif char == '(':
|
||||
depth += 1
|
||||
elif char == ')':
|
||||
depth -= 1
|
||||
i += 1
|
||||
require(depth == 0, 'unclosed schema constraint')
|
||||
result.append(re.sub(r'\s+', ' ', sql[start:i - 1]).strip())
|
||||
return sorted(result)
|
||||
|
||||
|
||||
def schema(connection):
|
||||
require(not connection.execute("SELECT 1 FROM sqlite_master WHERE type='trigger'").fetchone(),
|
||||
'database triggers are unsupported')
|
||||
result = {}
|
||||
tables = connection.execute(
|
||||
"SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
|
||||
).fetchall()
|
||||
for table, sql in tables:
|
||||
if table == 'alembic_version':
|
||||
continue
|
||||
require(not re.search(r'\b(WITHOUT\s+ROWID|STRICT|DEFERRABLE|COLLATE)\b', sql, re.I),
|
||||
'custom table options are unsupported')
|
||||
require(not any(row[6] for row in connection.execute('PRAGMA table_xinfo(' + quote(table) + ')')),
|
||||
'hidden or generated columns are unsupported')
|
||||
columns = [list(row[1:6]) for row in connection.execute('PRAGMA table_info(' + quote(table) + ')')]
|
||||
for column in columns:
|
||||
column[1] = re.sub(r'\s+', '', column[1]).upper()
|
||||
indexes = set()
|
||||
for index in connection.execute('PRAGMA index_list(' + quote(table) + ')'):
|
||||
require(not index[4], 'partial indexes are unsupported')
|
||||
if index[3] != 'pk':
|
||||
fields = tuple((row[2], row[3], row[4]) for row in connection.execute(
|
||||
'PRAGMA index_xinfo(' + quote(index[1]) + ')') if row[5])
|
||||
require(all(field[0] for field in fields), 'expression indexes are unsupported')
|
||||
indexes.add((bool(index[2]), fields))
|
||||
foreign = {}
|
||||
for row in connection.execute('PRAGMA foreign_key_list(' + quote(table) + ')'):
|
||||
foreign.setdefault(row[0], []).append(row)
|
||||
foreign = sorted(
|
||||
[[row[2], row[3], row[4], row[5], row[6], row[7]] for row in sorted(group, key=lambda r: r[1])]
|
||||
for group in foreign.values()
|
||||
)
|
||||
result[table] = {
|
||||
'columns': columns,
|
||||
'indexes': [[unique, [list(field) for field in fields]] for unique, fields in sorted(indexes)],
|
||||
'foreign_keys': foreign, 'checks': checks(sql),
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def target_contract():
|
||||
"""Create only in-memory reference schemas using the candidate's own metadata."""
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
from sqlalchemy import create_engine
|
||||
import persistance
|
||||
|
||||
result = {}
|
||||
for domain in DOMAINS:
|
||||
importlib.import_module('core.' + domain + '.models')
|
||||
if domain != 'governance':
|
||||
importlib.import_module('core.' + domain + '.indicadores.models')
|
||||
base = importlib.import_module('core.' + domain + '.base')
|
||||
model = getattr(base, {'cacu': 'CaCuModel', 'cama': 'CaMaModel',
|
||||
'tea': 'TeaModel', 'governance': 'GovernanceModel'}[domain])
|
||||
config = Config(str(Path(persistance.__file__).parent / domain / 'alembic.ini'))
|
||||
scripts = ScriptDirectory.from_config(config)
|
||||
heads = scripts.get_heads()
|
||||
require(len(heads) == 1, 'candidate must have one migration head per domain')
|
||||
engine = create_engine('sqlite://')
|
||||
try:
|
||||
model.metadata.create_all(engine)
|
||||
with closing(engine.raw_connection()) as connection:
|
||||
expected = schema(connection)
|
||||
finally:
|
||||
engine.dispose()
|
||||
result[domain] = {'head': heads[0], 'known': sorted(r.revision for r in scripts.walk_revisions()),
|
||||
'schema': expected}
|
||||
return result
|
||||
|
||||
|
||||
def inspect_databases(root, contract, *, rows=False, quiesced=False):
|
||||
root = Path(root)
|
||||
regular_tree(root)
|
||||
require(set(contract) == set(DOMAINS), 'four domain contracts are required')
|
||||
result = {}
|
||||
for domain in DOMAINS:
|
||||
try:
|
||||
path = root / (domain + '.db')
|
||||
def inspect_one(immutable=False):
|
||||
with closing(readonly(path, immutable=True) if immutable else readonly(path)) as connection:
|
||||
connection.execute('BEGIN')
|
||||
try:
|
||||
versions = connection.execute('SELECT version_num FROM alembic_version').fetchall()
|
||||
except sqlite3.Error as exc:
|
||||
error = RuntimeError(domain + ': Alembic version is unavailable')
|
||||
error.sqlite_errorname = getattr(exc, 'sqlite_errorname', None)
|
||||
raise error from None
|
||||
require(len(versions) == 1, domain + ': exactly one installed revision is required')
|
||||
current = versions[0][0]
|
||||
expected = contract[domain]
|
||||
require(current in expected['known'], domain + ': unknown Alembic revision')
|
||||
require(current == expected['head'], domain + ': pending migrations are not supported')
|
||||
actual = schema(connection)
|
||||
require(actual == expected['schema'], domain + ': structure differs from the candidate')
|
||||
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
|
||||
domain + ': SQLite integrity check failed')
|
||||
require(not connection.execute('PRAGMA foreign_key_check').fetchall(),
|
||||
domain + ': SQLite foreign key check failed')
|
||||
state = {'revision': current, 'schema': actual, 'identity': identity(path)}
|
||||
if rows:
|
||||
state['tables'] = table_state(connection, domain)
|
||||
return state
|
||||
try:
|
||||
result[domain] = inspect_one()
|
||||
except (RuntimeError, sqlite3.OperationalError) as exc:
|
||||
if not quiesced or getattr(exc, 'sqlite_errorname', None) != 'SQLITE_CANTOPEN':
|
||||
raise
|
||||
sidecars = [Path(str(path) + suffix) for suffix in ('-wal', '-shm', '-journal')]
|
||||
if any(p.exists() or p.is_symlink() for p in sidecars):
|
||||
raise
|
||||
before = path.stat()
|
||||
result[domain] = inspect_one(immutable=True)
|
||||
after = path.stat()
|
||||
if (any(p.exists() or p.is_symlink() for p in sidecars)
|
||||
or (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns)
|
||||
!= (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns)):
|
||||
raise RuntimeError('database changed during quiesced inspection')
|
||||
except Exception as exc:
|
||||
exc.inspection_domain = domain
|
||||
raise
|
||||
return {'directory': identity(root), 'databases': result}
|
||||
|
||||
|
||||
def inspection_diagnostic(exc):
|
||||
"""Return only allowlisted rejection categories, never exception text or data."""
|
||||
domain = getattr(exc, 'inspection_domain', None)
|
||||
domain = domain if domain in DOMAINS else 'none'
|
||||
message = str(exc)
|
||||
if domain == 'none':
|
||||
for candidate in DOMAINS:
|
||||
if message.startswith(candidate + ': '):
|
||||
domain = candidate
|
||||
break
|
||||
if domain != 'none' and message.startswith(domain + ': '):
|
||||
message = message[len(domain) + 2:]
|
||||
reason = INSPECTION_REASONS.get(message, 'unclassified')
|
||||
if message.startswith('persistent rows changed in '):
|
||||
reason = 'protected_rows_changed'
|
||||
elif message.startswith('historical rows changed in '):
|
||||
reason = 'historical_rows_changed'
|
||||
elif message.startswith('persistent file changed: '):
|
||||
reason = 'persistent_file_changed'
|
||||
kind = type(exc).__name__
|
||||
kind = kind if kind in INSPECTION_ERROR_TYPES else 'Other'
|
||||
sqlite_name = getattr(exc, 'sqlite_errorname', None)
|
||||
if sqlite_name not in SQLITE_ERROR_NAMES:
|
||||
sqlite_name = 'none'
|
||||
number = getattr(exc, 'errno', None)
|
||||
number = number if type(number) is int and 0 <= number <= 4095 else None
|
||||
return {'reason': reason, 'domain': domain, 'type': kind, 'sqlite': sqlite_name, 'errno': number}
|
||||
|
||||
|
||||
def table_state(connection, domain):
|
||||
result = {}
|
||||
for table, metadata in schema(connection).items():
|
||||
keys = [column[0] for column in sorted(metadata['columns'], key=lambda c: c[4]) if column[4]]
|
||||
require(keys, 'tables without primary keys are unsupported')
|
||||
query = 'SELECT * FROM ' + quote(table) + ' ORDER BY ' + ','.join(map(quote, keys))
|
||||
mode = ('mutable' if table in MUTABLE else 'append' if table in APPEND_ONLY else 'exact')
|
||||
if domain == 'governance':
|
||||
mode = 'exact'
|
||||
value_hash, row_hashes, count = hashlib.sha256(), Counter(), 0
|
||||
for row in connection.execute(query):
|
||||
encoded = json.dumps(row, default=lambda v: {'blob_sha256': hashlib.sha256(v).hexdigest()},
|
||||
ensure_ascii=True, separators=(',', ':')).encode()
|
||||
hashed = hashlib.sha256(encoded).hexdigest()
|
||||
value_hash.update(hashed.encode())
|
||||
if mode == 'append':
|
||||
row_hashes[hashed] += 1
|
||||
count += 1
|
||||
result[table] = {'mode': mode, 'count': count, 'sha256': value_hash.hexdigest()}
|
||||
if mode == 'append':
|
||||
result[table]['rows'] = dict(row_hashes)
|
||||
return result
|
||||
|
||||
|
||||
def is_sqlite(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return stream.read(16) == b'SQLite format 3\x00'
|
||||
|
||||
|
||||
def auxiliary(name, files):
|
||||
return any(name.endswith(suffix) and name[:-len(suffix)] in files
|
||||
and is_sqlite(files[name[:-len(suffix)]])
|
||||
for suffix in ('-wal', '-shm', '-journal'))
|
||||
|
||||
|
||||
def sqlite_digest(path):
|
||||
result = hashlib.sha256()
|
||||
with closing(readonly(path)) as connection:
|
||||
connection.execute('BEGIN')
|
||||
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
|
||||
'auxiliary SQLite integrity check failed')
|
||||
for statement in connection.iterdump():
|
||||
result.update(statement.encode('utf-8'))
|
||||
result.update(b'\n')
|
||||
return result.hexdigest()
|
||||
|
||||
|
||||
def storage_state(root, contract):
|
||||
result = inspect_databases(root, contract, rows=True)
|
||||
files = regular_tree(root)
|
||||
result['files'] = {
|
||||
name: {'size': path.stat().st_size, 'sha256': digest(path),
|
||||
**({'sqlite_sha256': sqlite_digest(path)} if is_sqlite(path) else {})}
|
||||
for name, path in files.items() if name not in APP_DATABASES and not auxiliary(name, files)
|
||||
}
|
||||
result['directories'] = sorted(path.relative_to(root).as_posix() for path in Path(root).rglob('*')
|
||||
if path.is_dir())
|
||||
return result
|
||||
|
||||
|
||||
def verify_state(root, contract, before, *, derived=False):
|
||||
after = storage_state(root, contract)
|
||||
require(after['directory'] == before['directory'], 'persistent directory identity changed')
|
||||
require(set(before['directories']) <= set(after['directories']), 'persistent directory disappeared')
|
||||
for domain in DOMAINS:
|
||||
old, new = before['databases'][domain], after['databases'][domain]
|
||||
require(new['identity'] == old['identity'], domain + ': database file identity changed')
|
||||
for table, prior in old['tables'].items():
|
||||
current = new['tables'][table]
|
||||
if derived and prior['mode'] == 'mutable':
|
||||
continue
|
||||
if derived and prior['mode'] == 'append':
|
||||
require(not (Counter(prior['rows']) - Counter(current['rows'])),
|
||||
domain + ': historical rows changed in ' + table)
|
||||
else:
|
||||
require(current == prior, domain + ': persistent rows changed in ' + table)
|
||||
permitted = {'indicadores/estado.json', 'indicadores/.estado.lock',
|
||||
*('indicadores/pendiente/' + domain for domain in DOMAINS if domain != 'governance')}
|
||||
for name in before['files'].keys() | after['files'].keys():
|
||||
if derived and name in permitted:
|
||||
continue
|
||||
if derived and name == 'reportes/indicadores.jsonl':
|
||||
if name in before['files']:
|
||||
path = Path(root) / name
|
||||
require(path.is_file(), 'indicator audit log disappeared')
|
||||
with path.open('rb') as stream:
|
||||
prefix = hashlib.sha256(stream.read(before['files'][name]['size'])).hexdigest()
|
||||
require(prefix == before['files'][name]['sha256'], 'indicator audit history changed')
|
||||
continue
|
||||
require(after['files'].get(name) == before['files'].get(name), 'persistent file changed: ' + name)
|
||||
return after
|
||||
|
||||
|
||||
def create_backup(root, destination, contract, origin):
|
||||
"""Snapshot only quiesced writers; normalize SQLite WAL through its backup API."""
|
||||
root, destination = Path(root), Path(destination)
|
||||
require(not destination.resolve().is_relative_to(root.resolve()), 'backup must be outside persistent storage')
|
||||
before = storage_state(root, contract)
|
||||
files = regular_tree(root)
|
||||
require({name for name in files if not auxiliary(name, files)} == APP_DATABASES | before['files'].keys(),
|
||||
'storage changed while creating the backup')
|
||||
require(not destination.exists() and not destination.is_symlink(), 'backup destination already exists')
|
||||
destination.mkdir(mode=0o700)
|
||||
data = destination / 'data'
|
||||
data.mkdir(mode=0o700)
|
||||
for path in root.rglob('*'):
|
||||
if path.is_dir():
|
||||
(data / path.relative_to(root)).mkdir(parents=True, exist_ok=True)
|
||||
shutil.copystat(path, data / path.relative_to(root))
|
||||
sqlite_files = []
|
||||
for name, path in files.items():
|
||||
if auxiliary(name, files):
|
||||
continue
|
||||
target = data / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if is_sqlite(path):
|
||||
with closing(readonly(path)) as source, closing(sqlite3.connect(target)) as copy:
|
||||
source.backup(copy)
|
||||
# A backup inherits WAL mode; use a standalone file for portable recovery.
|
||||
copy.execute('PRAGMA journal_mode=DELETE')
|
||||
require(copy.execute('PRAGMA integrity_check').fetchall() == [('ok',)], 'backup integrity failed')
|
||||
shutil.copystat(path, target)
|
||||
sqlite_files.append(name)
|
||||
if name not in APP_DATABASES:
|
||||
require(sqlite_digest(target) == before['files'][name]['sqlite_sha256'],
|
||||
'auxiliary SQLite backup content differs')
|
||||
else:
|
||||
shutil.copy2(path, target)
|
||||
require(digest(target) == before['files'][name]['sha256'], 'copied artifact differs from source')
|
||||
require(storage_state(root, contract) == before, 'storage changed while creating the backup')
|
||||
snapshot = inspect_databases(data, contract, rows=True)
|
||||
for domain in DOMAINS:
|
||||
require(snapshot['databases'][domain]['tables'] == before['databases'][domain]['tables'],
|
||||
domain + ': backup rows differ')
|
||||
manifest = {'format': 1, 'origin': origin, 'contract': contract, 'state': before,
|
||||
'sqlite_files': sqlite_files,
|
||||
'files': {name: digest(path) for name, path in regular_tree(data).items()}}
|
||||
with (destination / 'manifest.json').open('x', encoding='utf-8') as stream:
|
||||
json.dump(manifest, stream, sort_keys=True)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
verify_backup(destination)
|
||||
return manifest
|
||||
|
||||
|
||||
def verify_backup(destination):
|
||||
destination = Path(destination)
|
||||
require(destination.is_dir() and not destination.is_symlink(), 'invalid backup directory')
|
||||
manifest = json.loads((destination / 'manifest.json').read_text(encoding='utf-8'))
|
||||
files = regular_tree(destination / 'data')
|
||||
require(manifest['format'] == 1 and set(files) == set(manifest['files']), 'backup inventory differs')
|
||||
directories = sorted(path.relative_to(destination / 'data').as_posix()
|
||||
for path in (destination / 'data').rglob('*') if path.is_dir())
|
||||
require(directories == manifest['state']['directories'], 'backup directory inventory differs')
|
||||
for name, path in files.items():
|
||||
require(digest(path) == manifest['files'][name], 'backup checksum mismatch')
|
||||
for name in manifest['sqlite_files']:
|
||||
with closing(readonly(files[name])) as connection:
|
||||
require(connection.execute('PRAGMA integrity_check').fetchall() == [('ok',)], 'backup integrity failed')
|
||||
current = inspect_databases(destination / 'data', manifest['contract'], rows=True)
|
||||
for domain in DOMAINS:
|
||||
require(current['databases'][domain]['tables'] == manifest['state']['databases'][domain]['tables'],
|
||||
'backup logical content differs')
|
||||
return manifest
|
||||
|
||||
|
||||
def restore_backup(source, destination):
|
||||
"""Restore only to a new isolated directory; never overwrite an installation."""
|
||||
manifest = verify_backup(source)
|
||||
destination = Path(destination)
|
||||
require(not destination.resolve().is_relative_to(Path(source).resolve()),
|
||||
'restore destination must be outside the backup')
|
||||
require(not destination.exists() and not destination.is_symlink(), 'restore destination must be new')
|
||||
shutil.copytree(Path(source) / 'data', destination)
|
||||
files = regular_tree(destination)
|
||||
require({name: digest(path) for name, path in files.items()} == manifest['files'], 'restored files differ')
|
||||
actual = inspect_databases(destination, manifest['contract'], rows=True)
|
||||
for domain in DOMAINS:
|
||||
require(actual['databases'][domain]['tables'] == manifest['state']['databases'][domain]['tables'],
|
||||
'restored rows differ')
|
||||
return actual
|
||||
|
||||
|
||||
def recalculate(environment):
|
||||
"""Run each domain once and retain only safe failure context."""
|
||||
stage, domain = 'environment', 'none'
|
||||
try:
|
||||
require(isinstance(environment, dict) and all(isinstance(k, str) and isinstance(v, str)
|
||||
and '=' not in k and '\x00' not in k + v for k, v in environment.items()),
|
||||
'invalid resolved worker environment')
|
||||
os.environ.update(environment)
|
||||
stage = 'import'
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
stage = 'initialize'
|
||||
queue = ColaDeRecalculo()
|
||||
completed = []
|
||||
for domain in DOMAINS:
|
||||
if domain == 'governance':
|
||||
continue
|
||||
stage = 'enqueue'
|
||||
queue.tomar(domain)
|
||||
stage = 'execute'
|
||||
result = queue.correr(domain)
|
||||
stage = 'domain_result'
|
||||
require(isinstance(result, dict) and result.get('estado') == 'ok', 'indicator recalculation failed')
|
||||
completed.append(domain)
|
||||
domain, stage = 'none', 'pending'
|
||||
require(not queue.pendientes(), 'unexpected pending recalculations')
|
||||
return {'completed': completed}
|
||||
except Exception as exc:
|
||||
exc.recalculation_stage = stage
|
||||
exc.inspection_domain = domain
|
||||
raise
|
||||
|
||||
|
||||
def silent_recalculate(environment):
|
||||
"""Keep library stdout out of the machine-readable response."""
|
||||
sys.stdout.flush()
|
||||
saved = os.dup(1)
|
||||
try:
|
||||
with open(os.devnull, 'w') as sink:
|
||||
os.dup2(sink.fileno(), 1)
|
||||
try:
|
||||
return recalculate(environment)
|
||||
finally:
|
||||
sys.stdout.flush()
|
||||
finally:
|
||||
os.dup2(saved, 1)
|
||||
os.close(saved)
|
||||
|
||||
|
||||
def main():
|
||||
action, payload = sys.argv[1], json.load(sys.stdin)
|
||||
if action == 'contract':
|
||||
result = target_contract()
|
||||
elif action == 'inspect':
|
||||
result = inspect_databases(payload['data'], payload['contract'], quiesced=payload.get('quiesced', False))
|
||||
elif action == 'state':
|
||||
result = storage_state(payload['data'], payload['contract'])
|
||||
elif action == 'verify':
|
||||
result = verify_state(payload['data'], payload['contract'], payload['before'],
|
||||
derived=payload.get('derived', False))
|
||||
elif action == 'recalculate':
|
||||
result = silent_recalculate(payload['environment'])
|
||||
else:
|
||||
raise RuntimeError('unsupported guard action')
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as exc:
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'inspect':
|
||||
print('WN_INSPECT_DIAGNOSTIC=' + json.dumps(inspection_diagnostic(exc)), file=sys.stderr)
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'recalculate':
|
||||
diagnostic = inspection_diagnostic(exc)
|
||||
stage = getattr(exc, 'recalculation_stage', 'unknown')
|
||||
diagnostic['stage'] = stage if stage in ('environment', 'import', 'initialize', 'enqueue',
|
||||
'execute', 'domain_result', 'pending') else 'unknown'
|
||||
print('WN_RECALC_DIAGNOSTIC=' + json.dumps(diagnostic), file=sys.stderr)
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'verify':
|
||||
print('WN_VERIFY_DIAGNOSTIC=' + json.dumps(inspection_diagnostic(exc)), file=sys.stderr)
|
||||
print('Persistent storage validation failed; inspect the phase and metadata privately.', file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,283 @@
|
||||
"""Load the simulated hospital into an installed DEV instance.
|
||||
|
||||
The simulated hospital is a MySQL server filled by `dev-data`. The instance's API reads it through its own import
|
||||
API (`POST /imports/commit`), the same way a person connects a hospital; this installer only starts the `dev-data`
|
||||
loader at the commit the instance was installed with and checks the outcome. It never writes to the hospital.
|
||||
|
||||
Like the install, the operation has a plan step (no changes) and a confirmed step. It refuses an instance that is
|
||||
not a verified DEV installation of this installer, one that is not running, one that already has import attempts or
|
||||
an earlier load, and a hospital address that is not `host:port`.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
import tarfile
|
||||
import io
|
||||
|
||||
import composition
|
||||
import installer
|
||||
import proc
|
||||
import resources
|
||||
|
||||
HOSPITAL_DEFAULT = '10.0.10.41:9505'
|
||||
DEV_DATA_REMOTE = 'http://10.0.10.41:3000/edgar/dev-data.git'
|
||||
APPLICATION_REMOTE = 'http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON.git'
|
||||
# Credentials of the simulated hospital, which holds only generated data.
|
||||
HOSPITAL_USER = HOSPITAL_PASSWORD = 'hospital'
|
||||
PROJECTS = (('cacu', 'hospital_cacu'), ('cama', 'hospital_cama'), ('tea', 'hospital'))
|
||||
LINE = re.compile(r'^(?P<target>\S+): (?P<total>\d+) le\S+, (?P<created>\d+) nuevas, (?P<updated>\d+) actualizadas, '
|
||||
r'(?P<rejected>\d+) rechazadas', re.M)
|
||||
# Runs inside the loader image, which has the pinned generator's tables and a MySQL driver. It reads the hospital
|
||||
# (information_schema and row counts) and prints, per project, what the pinned generator expects and what is there.
|
||||
HOSPITAL_SCRIPT = """import json, sys
|
||||
import pymysql
|
||||
from dev_data.proyectos import PROYECTOS
|
||||
|
||||
config = json.loads(sys.argv[1])
|
||||
report = {}
|
||||
for name, database in config['projects']:
|
||||
try:
|
||||
connection = pymysql.connect(host=config['host'], port=config['port'], user=config['user'],
|
||||
password=config['password'], database=database, connect_timeout=10,
|
||||
read_timeout=120)
|
||||
except pymysql.MySQLError as error:
|
||||
report[name] = {'database': database, 'error': type(error).__name__ + ': ' + str(error.args[-1])[:200]}
|
||||
continue
|
||||
with connection, connection.cursor() as cursor:
|
||||
cursor.execute('select table_name, column_name from information_schema.columns where table_schema = %s',
|
||||
(database,))
|
||||
present = {}
|
||||
for table, column in cursor.fetchall():
|
||||
present.setdefault(table, set()).add(column)
|
||||
tables = {}
|
||||
for model in PROYECTOS[name].modelos.values():
|
||||
table = model.__tablename__
|
||||
entry = {'target': name + '.' + model.__name__, 'exists': table in present, 'rows': None,
|
||||
'missing_columns': []}
|
||||
if entry['exists']:
|
||||
entry['missing_columns'] = sorted(c.name for c in model.__table__.columns if c.name not in present[table])
|
||||
cursor.execute('select count(*) from `' + table + '`')
|
||||
entry['rows'] = cursor.fetchone()[0]
|
||||
tables[table] = entry
|
||||
report[name] = {'database': database, 'tables': tables}
|
||||
print(json.dumps(report))
|
||||
"""
|
||||
|
||||
|
||||
def validate_hospital(text):
|
||||
"""`host:port` of the simulated hospital as the instance's API reaches it; never a URL or credentials."""
|
||||
text = (text or '').strip()
|
||||
match = re.fullmatch(r'([A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?):([0-9]{1,5})', text)
|
||||
if not match or not 1 <= int(match.group(3)) <= 65535:
|
||||
raise ValueError('hospital must be host:port, for example 10.0.10.41:9505')
|
||||
return text
|
||||
|
||||
|
||||
def fetch_tree(remote, commit, directory, paths=()):
|
||||
"""Export `paths` (or everything) of one commit of `remote` into `directory`; the commit is fetched by SHA."""
|
||||
if not composition.SHA.fullmatch(commit or ''):
|
||||
raise RuntimeError('the installation record lacks a full commit for this repository')
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-fetch-') as tmp:
|
||||
proc.run(['git', 'init', '--quiet', tmp])
|
||||
proc.git(tmp, 'fetch', '--no-tags', remote, commit)
|
||||
if proc.git(tmp, 'rev-parse', 'FETCH_HEAD^{commit}').strip() != commit:
|
||||
raise RuntimeError(f'{remote} did not return {commit}')
|
||||
archive = proc.git(tmp, 'archive', '--format=tar', commit, *paths, binary=True)
|
||||
Path(directory).mkdir(parents=True, exist_ok=True)
|
||||
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
|
||||
tar.extractall(directory, filter='data')
|
||||
|
||||
|
||||
def plan_load(host, base, port, hospital):
|
||||
"""Check that the instance can take the load; nothing is created or started."""
|
||||
record = host.call('lookup', '-', port)
|
||||
if record is None:
|
||||
raise RuntimeError(f'no installation is registered on port {port}')
|
||||
project = record['project']
|
||||
identity = host.call('identity', project, {'port': port})
|
||||
if record['status'] != 'installed':
|
||||
raise RuntimeError(f'the instance is {record["status"]}, not installed')
|
||||
if record.get('synthetic_data'):
|
||||
raise RuntimeError('the instance already has a simulated-hospital load (or a failed attempt); '
|
||||
'reinstall it for a clean one')
|
||||
pins = record.get('gitlinks') or {}
|
||||
for name in ('dev-data', 'ISSSTELEON'):
|
||||
if not composition.SHA.fullmatch(pins.get(name) or ''):
|
||||
raise RuntimeError(f'the installation record does not pin {name}')
|
||||
resources.verify_running(project, port, base, record['images'], bool(record.get('notebook_volume')))
|
||||
attempts = json.loads(host.http_get(f'http://127.0.0.1:{port}/reportes/importaciones')['body']).get('intentos')
|
||||
if attempts:
|
||||
raise RuntimeError('the instance already has import attempts; the load needs an empty platform')
|
||||
host.tcp_check(hospital)
|
||||
return {'operation': 'load', 'port': port, 'project': project, 'hospital': hospital,
|
||||
'dev_data': pins['dev-data'], 'application': pins['ISSSTELEON'], 'record_sha256': identity['record_sha256'],
|
||||
'projects': [name for name, _ in PROJECTS]}
|
||||
|
||||
|
||||
def build_loader(plan, workdir):
|
||||
"""Build the loader image from the pinned `dev-data` and the pinned application's `Core`."""
|
||||
context = Path(workdir) / 'context'
|
||||
fetch_tree(DEV_DATA_REMOTE, plan['dev_data'], context / 'dev-data')
|
||||
fetch_tree(APPLICATION_REMOTE, plan['application'], context / 'ISSSTELEON', ('Core',))
|
||||
image = f'isssteleon-dev-data-load:{plan["project"]}-{plan["dev_data"][:12]}'
|
||||
proc.run(['docker', 'build', '-q', '-t', image, '-f', context / 'dev-data' / 'Dockerfile', context])
|
||||
return image
|
||||
|
||||
|
||||
def run_loader(plan, image):
|
||||
"""Load each project through the instance's published port and return the per-table counts."""
|
||||
counts = {}
|
||||
for name, database in PROJECTS:
|
||||
hospital = f'mysql+pymysql://{HOSPITAL_USER}:{HOSPITAL_PASSWORD}@{plan["hospital"]}/{database}'
|
||||
try:
|
||||
out = proc.run(['docker', 'run', '--rm', '--network', 'host', image, 'cargar', name,
|
||||
'--api', f'http://127.0.0.1:{plan["port"]}', '--hospital', hospital])
|
||||
except subprocess.CalledProcessError as exc:
|
||||
# The command line carries the hospital connection string, so only the loader's own words are kept.
|
||||
raise RuntimeError(f'the loader failed for {name}: {(exc.stderr or exc.stdout or "")[-1500:].strip()}') from None
|
||||
rows = [m.groupdict() for m in LINE.finditer(out)]
|
||||
if not rows:
|
||||
raise RuntimeError(f'the loader printed no table counts for {name}')
|
||||
counts[name] = {r['target']: {k: int(v) for k, v in r.items() if k != 'target'} for r in rows}
|
||||
return counts
|
||||
|
||||
|
||||
def check_hospital(plan, image):
|
||||
"""Read the hospital with the loader image and refuse it unless it has what the pinned generator expects.
|
||||
|
||||
Nothing is written anywhere. Returns the expected targets per project and the tables that hold no rows."""
|
||||
host, _, port = plan['hospital'].rpartition(':')
|
||||
config = json.dumps({'host': host, 'port': int(port), 'user': HOSPITAL_USER, 'password': HOSPITAL_PASSWORD,
|
||||
'projects': PROJECTS})
|
||||
try:
|
||||
out = proc.run(['docker', 'run', '--rm', '--network', 'host', '--entrypoint', 'uv', image, 'run', '--frozen',
|
||||
'--no-dev', 'python', '-c', HOSPITAL_SCRIPT, config])
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise RuntimeError(f'the hospital could not be read: {(exc.stderr or exc.stdout or "")[-1500:].strip()}') from None
|
||||
try:
|
||||
report = json.loads(out.strip().splitlines()[-1])
|
||||
except (ValueError, IndexError):
|
||||
raise RuntimeError('the hospital check printed no report') from None
|
||||
problems, expected, empty = [], {}, []
|
||||
for name, _ in PROJECTS:
|
||||
entry = report.get(name) or {}
|
||||
if 'error' in entry:
|
||||
problems.append(f'{name}: {entry["database"]} cannot be read ({entry["error"]})')
|
||||
continue
|
||||
tables = entry.get('tables') or {}
|
||||
expected[name] = [t['target'] for t in tables.values()]
|
||||
for table, found in tables.items():
|
||||
if not found['exists']:
|
||||
problems.append(f'{name}: table {table} is missing from {entry["database"]}')
|
||||
elif found['missing_columns']:
|
||||
problems.append(f'{name}: {table} lacks the columns {", ".join(found["missing_columns"])}')
|
||||
elif not found['rows']:
|
||||
empty.append(found['target'])
|
||||
if tables and all(t['exists'] and not t['rows'] for t in tables.values()):
|
||||
problems.append(f'{name}: {entry["database"]} has no rows')
|
||||
if problems:
|
||||
raise RuntimeError('the hospital does not have the schema and data the pinned dev-data expects, '
|
||||
'so nothing was loaded: ' + '; '.join(problems))
|
||||
return {'expected': expected, 'empty_tables': empty}
|
||||
|
||||
|
||||
def check_counts(counts, expected=None):
|
||||
"""A load is complete only if every expected table was loaded, stored every row it read and rejected none."""
|
||||
for name, tables in counts.items():
|
||||
if sum(t['total'] for t in tables.values()) == 0:
|
||||
raise RuntimeError(f'{name}: the hospital has no rows to load')
|
||||
missing = sorted(set((expected or {}).get(name, [])) - set(tables))
|
||||
if missing:
|
||||
raise RuntimeError(f'{name}: the loader reported no counts for {", ".join(missing)}')
|
||||
rejected = {target: t['rejected'] for target, t in tables.items() if t['rejected']}
|
||||
if rejected:
|
||||
raise RuntimeError(f'{name}: rows were rejected: {rejected}')
|
||||
short = {target: t['total'] - t['created'] - t['updated'] for target, t in tables.items()
|
||||
if t['created'] + t['updated'] != t['total']}
|
||||
if short:
|
||||
raise RuntimeError(f'{name}: rows were read but not stored: {short}')
|
||||
|
||||
|
||||
def wait_for_recalculation(host, port, timeout=1800):
|
||||
"""The worker recalculates after the imports; every domain must end `ok`, and an error stops the wait."""
|
||||
deadline = time.monotonic() + timeout
|
||||
status = {}
|
||||
while time.monotonic() < deadline:
|
||||
status = json.loads(host.http_get(f'http://127.0.0.1:{port}/reportes/indicadores')['body'])
|
||||
states = {domain: entry.get('estado') for domain, entry in status.items()}
|
||||
errors = {domain: entry.get('error') for domain, entry in status.items() if entry.get('estado') == 'error'}
|
||||
if errors:
|
||||
raise RuntimeError(f'indicator recalculation failed: {errors}')
|
||||
if states and all(state == 'ok' and not status[d].get('pendiente') for d, state in states.items()):
|
||||
return states
|
||||
time.sleep(15)
|
||||
raise RuntimeError(f'indicator recalculation did not finish: {status}')
|
||||
|
||||
|
||||
def execute_load(host, base, plan, workdir):
|
||||
"""Run the confirmed load. The hospital is checked before anything is written to the platform, so a hospital
|
||||
that cannot be loaded leaves the instance clean; a failure after that leaves it marked, because the platform
|
||||
may be half loaded."""
|
||||
project, port = plan['project'], plan['port']
|
||||
record = host.call('lookup', '-', port)
|
||||
|
||||
def mark(**data):
|
||||
record['synthetic_data'] = dict(record.get('synthetic_data') or {}, hospital=plan['hospital'],
|
||||
dev_data=plan['dev_data'], **data)
|
||||
host.call('save', project, record)
|
||||
|
||||
try:
|
||||
image = build_loader(plan, workdir)
|
||||
preflight = check_hospital(plan, image)
|
||||
except Exception as exc:
|
||||
detail = installer.failure_detail(exc)[:900]
|
||||
# Not a `synthetic_data` entry: nothing was written, so the load stays plannable. The changed record
|
||||
# invalidates the confirmation that led here.
|
||||
record['load_attempt'] = {'status': 'not_started', 'hospital': plan['hospital'], 'error': detail,
|
||||
'at': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}
|
||||
try:
|
||||
host.call('save', project, record)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise RuntimeError(f'the load did not start and the instance was not loaded, so it can be tried again ({detail})') from None
|
||||
mark(status='loading', empty_tables=preflight['empty_tables'])
|
||||
try:
|
||||
counts = run_loader(plan, image)
|
||||
mark(status='verifying', counts=counts)
|
||||
check_counts(counts, preflight['expected'])
|
||||
states = wait_for_recalculation(host, port)
|
||||
mark(status='loaded', counts=counts, indicators=states, empty_tables=preflight['empty_tables'])
|
||||
except Exception as exc:
|
||||
detail = installer.failure_detail(exc)
|
||||
mark(status='failed', error=detail)
|
||||
raise RuntimeError(f'the load failed ({detail[:600]}); the instance may be partly loaded, '
|
||||
'so reinstall it before trying again') from None
|
||||
return record['synthetic_data']
|
||||
|
||||
|
||||
def run_load(port_text, hospital_text, confirmation='', base=installer.BASE, host_factory=installer.Host):
|
||||
"""Plan, or with the matching confirmation execute, the load of the simulated hospital."""
|
||||
port = composition.validate_port(port_text)
|
||||
hospital = validate_hospital(hospital_text or HOSPITAL_DEFAULT)
|
||||
confirmation = (confirmation or '').strip()
|
||||
if confirmation and not re.fullmatch(rf'cargar-{port}-[0-9a-f]{{16}}', confirmation):
|
||||
raise ValueError(f'confirmacion must be cargar-{port}-<digest>, as printed by a run without it')
|
||||
with host_factory(base, bool(confirmation)) as host, tempfile.TemporaryDirectory(prefix='isssteleon-load-') as tmp:
|
||||
plan = plan_load(host, base, port, hospital)
|
||||
expected = f'cargar-{port}-{installer.digest(plan)}'
|
||||
print('Plan:', json.dumps(plan, indent=1, sort_keys=True))
|
||||
if not confirmation:
|
||||
print('Nothing was changed. To approve exactly this plan, run again with confirmacion=' + expected)
|
||||
return None
|
||||
if confirmation != expected:
|
||||
raise RuntimeError(f'confirmacion does not match the current plan ({expected}); nothing was changed')
|
||||
result = execute_load(host, base, plan, tmp)
|
||||
for tables in result['counts'].values():
|
||||
for target, t in tables.items():
|
||||
print(f'{target}: {t["total"]} read, {t["created"]} new, {t["updated"]} updated, {t["rejected"]} rejected')
|
||||
print(f'Loaded the simulated hospital into {plan["project"]}: {json.dumps(result["counts"], sort_keys=True)}')
|
||||
return result
|
||||
@@ -1,425 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install isolated DEV instances from committed Git trees."""
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import posixpath
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import tempfile
|
||||
import uuid
|
||||
|
||||
import conservative
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BASE = Path('/srv/workingnarrative-dev')
|
||||
|
||||
|
||||
def validate_port(port):
|
||||
if not re.fullmatch(r'[0-9]{1,5}', port) or not 1024 <= int(port) <= 65535:
|
||||
raise ValueError('port must be an integer from 1024 to 65535')
|
||||
return int(port)
|
||||
|
||||
|
||||
def automatic_instance(port):
|
||||
return f'dev-{validate_port(port)}'
|
||||
|
||||
|
||||
def validate(instance, port, operation):
|
||||
if not re.fullmatch(r'[a-z][a-z0-9]*(?:-[a-z0-9]+)*', instance) or len(instance) > 40:
|
||||
raise ValueError('instance must be 1-40 lowercase letters, digits or single hyphens, starting with a letter')
|
||||
port = validate_port(port)
|
||||
if operation != 'instalar':
|
||||
raise ValueError('only instalar is supported; no changes were made')
|
||||
return f'isssteleon-{instance}', port
|
||||
|
||||
|
||||
def run(args, cwd=None, binary=False, stdin=None):
|
||||
result = subprocess.run([str(a) for a in args], cwd=cwd, check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=not binary, env=clean_env(), input=stdin)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def clean_env():
|
||||
return {k: v for k, v in os.environ.items() if not k.startswith(('COMPOSE_', 'ISSSTELEON_'))}
|
||||
|
||||
|
||||
def git(repo, *args, binary=False):
|
||||
return run(['git', '-C', repo, *args], binary=binary)
|
||||
|
||||
|
||||
def committed_trees(repo, revision, prefix=''):
|
||||
"""Walk exact recursive gitlinks and reject mismatching checked-out commits."""
|
||||
actual = git(repo, 'rev-parse', 'HEAD').strip()
|
||||
if actual != revision:
|
||||
raise RuntimeError(f'{repo}: expected {revision}, found {actual}; initialize submodules recursively')
|
||||
yield repo, revision, prefix
|
||||
entries = git(repo, 'ls-tree', '-rz', '--full-tree', revision, binary=True)
|
||||
for entry in entries.split(b'\0'):
|
||||
if not entry:
|
||||
continue
|
||||
meta, raw_path = entry.split(b'\t', 1)
|
||||
mode, kind, sha = meta.decode().split()
|
||||
if mode != '160000':
|
||||
continue
|
||||
path = os.fsdecode(raw_path)
|
||||
if Path(path).is_absolute() or '..' in Path(path).parts:
|
||||
raise RuntimeError(f'unsafe gitlink path: {path}')
|
||||
yield from committed_trees(repo / path, sha, f'{prefix}/{path}' if prefix else path)
|
||||
|
||||
|
||||
def pinned_manifest(repo, revision):
|
||||
return {prefix or 'ISSSTELEON': sha for _, sha, prefix in committed_trees(repo, revision)}
|
||||
|
||||
|
||||
def export_tree(repo, revision, dest, manifest, prefix=''):
|
||||
"""Export each committed tree and recursively follow its exact gitlinks."""
|
||||
for child, sha, relative in committed_trees(repo, revision, prefix):
|
||||
manifest[relative or 'ISSSTELEON'] = sha
|
||||
target = dest / relative.removeprefix(prefix).lstrip('/')
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
archive = git(child, 'archive', '--format=tar', sha, binary=True)
|
||||
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
|
||||
tar.extractall(target, filter='data')
|
||||
|
||||
|
||||
def compose(project, deploy, *args):
|
||||
return ['docker', 'compose', '--project-name', project, '--project-directory', str(deploy),
|
||||
'--env-file', str(deploy / '.env'), '-f', str(deploy / 'docker-compose.yml'), *args]
|
||||
|
||||
|
||||
def helper_exec(helper, script, *args, stdin=None):
|
||||
return run(['docker', 'exec', *(['-i'] if stdin is not None else []),
|
||||
helper, 'python3', '-c', script, *args], stdin=stdin)
|
||||
|
||||
|
||||
def start_helper(base):
|
||||
name = 'isssteleon-prepare-' + uuid.uuid4().hex
|
||||
script = """import fcntl, time
|
||||
with open('/host/.install.lock', 'a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
open('/tmp/locked', 'w').close()
|
||||
while True: time.sleep(60)
|
||||
"""
|
||||
try:
|
||||
run(['docker', 'run', '-d', '--network', 'host', '--name', name, '--mount',
|
||||
f'type=bind,src={base},dst=/host', 'python:3.12-slim', 'python3', '-c', script])
|
||||
deadline = time.monotonic() + 300
|
||||
while time.monotonic() < deadline:
|
||||
if helper_exec(name, "import os; print(int(os.path.exists('/tmp/locked')))").strip() == '1':
|
||||
return name
|
||||
time.sleep(2)
|
||||
raise RuntimeError('timed out waiting for the shared installation lock')
|
||||
except Exception as exc:
|
||||
try:
|
||||
run(['docker', 'rm', '-f', name])
|
||||
except Exception:
|
||||
pass
|
||||
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) else str(exc)
|
||||
raise RuntimeError(f'preparation failed; daemon host directory {base} must already exist: {detail}') from exc
|
||||
|
||||
|
||||
def reserve(helper, project, port):
|
||||
for kind, args in [('containers', ['docker', 'ps', '-aq']),
|
||||
('networks', ['docker', 'network', 'ls', '-q']),
|
||||
('volumes', ['docker', 'volume', 'ls', '-q'])]:
|
||||
if run([*args, '--filter', f'label=com.docker.compose.project={project}']).strip():
|
||||
raise RuntimeError(f'Compose project already owns {kind}: {project}')
|
||||
host_action(helper, 'reserve', project, str(port))
|
||||
|
||||
|
||||
def host_action(helper, action, *args):
|
||||
script = Path(__file__).with_name('host.py').read_text(encoding='utf-8')
|
||||
guard = Path(__file__).with_name('data_guard.py').read_text(encoding='utf-8')
|
||||
prefix = ("import sys, types\n"
|
||||
"module = types.ModuleType('data_guard')\n"
|
||||
"sys.modules['data_guard'] = module\n"
|
||||
f"exec({guard!r}, module.__dict__)\n")
|
||||
return helper_exec(helper, prefix + script, '/host', action, *args[:-1], '-', stdin=str(args[-1]))
|
||||
|
||||
|
||||
def copy_to_host(helper, source, project, destination):
|
||||
run(['docker', 'cp', str(source), f'{helper}:/host/{project}/{destination}'])
|
||||
|
||||
|
||||
def configure(deploy, data, project, revision, port):
|
||||
tag = f'{project}-{revision[:12]}-{uuid.uuid4().hex}'
|
||||
env = (f'ISSSTELEON_VERSION={tag}\nISSSTELEON_DATOS={data}\nISSSTELEON_PUERTO={port}\n'
|
||||
+ ''.join(f'{name}_DATABASE_URL=sqlite:////data/{name.lower()}.db\n'
|
||||
for name in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')))
|
||||
(deploy / '.env').write_text(env, encoding='utf-8')
|
||||
return tag
|
||||
|
||||
|
||||
def verify_config(config, project, data, tag, port):
|
||||
if config.get('name') != project:
|
||||
raise RuntimeError('effective Compose project name does not match')
|
||||
services = config.get('services', {})
|
||||
if set(services) != {'webapi', 'webapp', 'indicadores'}:
|
||||
raise RuntimeError('unexpected Compose services')
|
||||
for name, service in services.items():
|
||||
if (service.get('privileged') or service.get('network_mode') == 'host'
|
||||
or service.get('pid') == 'host' or service.get('devices')):
|
||||
raise RuntimeError(f'unsafe Compose service: {name}')
|
||||
for name in ('webapi', 'indicadores'):
|
||||
service = services[name]
|
||||
if service.get('image') != f'isssteleon/webapi:{tag}':
|
||||
raise RuntimeError(f'unexpected {name} image')
|
||||
volumes = service.get('volumes', [])
|
||||
if len(volumes) != 1 or not any(v.get('type') == 'bind' and v.get('source') == str(data) and v.get('target') == '/data'
|
||||
and not v.get('read_only') for v in volumes):
|
||||
raise RuntimeError(f'unexpected {name} data mount')
|
||||
if service.get('ports'):
|
||||
raise RuntimeError(f'unexpected {name} published ports')
|
||||
env = service.get('environment', {})
|
||||
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
|
||||
if env.get(f'{domain}_DATABASE_URL') != f'sqlite:////data/{domain.lower()}.db':
|
||||
raise RuntimeError(f'unexpected {name} database configuration')
|
||||
if services['webapp'].get('image') != f'isssteleon/webapp:{tag}':
|
||||
raise RuntimeError('unexpected webapp image')
|
||||
if services['webapp'].get('volumes'):
|
||||
raise RuntimeError('unexpected webapp mounts')
|
||||
ports = services['webapp'].get('ports', [])
|
||||
if len(ports) != 1 or str(ports[0].get('published')) != str(port) or int(ports[0].get('target', 0)) != 80:
|
||||
raise RuntimeError('unexpected webapp port')
|
||||
|
||||
|
||||
def verify_services(cmd, port, timeout=300):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = 'services did not start'
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
for service in ('webapi', 'webapp', 'indicadores'):
|
||||
ids = run([*cmd, 'ps', '-q', service]).splitlines()
|
||||
if len(ids) != 1:
|
||||
raise RuntimeError(f'{service}: expected one running container')
|
||||
state = json.loads(run(['docker', 'inspect', '--format', '{{json .State}}', ids[0]]))
|
||||
if state.get('Status') != 'running':
|
||||
raise RuntimeError(f'{service}: {state.get("Status")}')
|
||||
if service == 'webapi' and state.get('Health', {}).get('Status') != 'healthy':
|
||||
raise RuntimeError(f'webapi health: {state.get("Health", {}).get("Status", "missing")}')
|
||||
if service == 'webapp':
|
||||
for path in ('/health', '/'):
|
||||
run(['docker', 'exec', ids[0], 'wget', '-q', '-O', '/dev/null',
|
||||
f'http://127.0.0.1{path}'])
|
||||
return
|
||||
except Exception as exc:
|
||||
last = str(exc)
|
||||
time.sleep(3)
|
||||
raise RuntimeError(f'availability check failed: {last}')
|
||||
|
||||
|
||||
def install(instance, port_text, operation, root=ROOT, base=BASE, helper=None):
|
||||
project, port = validate(instance, port_text, operation)
|
||||
revision = git(root, 'rev-parse', 'HEAD').strip()
|
||||
expected = git(root, 'ls-tree', 'HEAD', 'ISSSTELEON').split()[2]
|
||||
owns_helper = helper is None
|
||||
if owns_helper:
|
||||
helper = start_helper(base)
|
||||
try:
|
||||
reserve(helper, project, port)
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-deploy-') as tmp:
|
||||
directory = Path(tmp)
|
||||
source, deploy, data = directory / 'codigo', directory / 'deploy', base / project / 'data'
|
||||
record = {'project': project, 'port': port, 'revision': revision, 'status': 'preparing'}
|
||||
def save():
|
||||
host_action(helper, 'save', project, json.dumps(record))
|
||||
cmd = None
|
||||
try:
|
||||
save()
|
||||
manifest = {}
|
||||
export_tree(root / 'ISSSTELEON', expected, source, manifest)
|
||||
record['gitlinks'] = manifest
|
||||
shutil.copytree(source / 'dist', deploy, symlinks=True)
|
||||
tag = configure(deploy, data, project, revision, port)
|
||||
record['images'] = [f'isssteleon/webapi:{tag}', f'isssteleon/webapp:{tag}']
|
||||
copy_to_host(helper, source, project, 'codigo')
|
||||
copy_to_host(helper, deploy, project, 'deploy')
|
||||
record['status'] = 'building'
|
||||
save()
|
||||
run(['docker', 'build', '-t', record['images'][0], '-f', source / 'WebApi/Dockerfile', source])
|
||||
run(['docker', 'build', '-t', record['images'][1], source / 'WebApp'])
|
||||
probe = "import sqlite3, os; p='/data/.permission-probe.db'; c=sqlite3.connect(p); c.execute('create table probe (x int)'); c.execute('insert into probe values (1)'); c.commit(); c.close(); os.remove(p)"
|
||||
run(['docker', 'run', '--rm', '--mount', f'type=bind,src={data},dst=/data',
|
||||
'--entrypoint', 'python3', record['images'][0], '-c', probe])
|
||||
cmd = compose(project, deploy)
|
||||
config = conservative.controlled_config(
|
||||
json.loads(run([*cmd, 'config', '--format', 'json'])), migrate_on_start=True)
|
||||
verify_config(config, project, data, tag, port)
|
||||
conservative.persist_config(deploy, config)
|
||||
copy_to_host(helper, deploy / 'docker-compose.yml', project, 'deploy/docker-compose.yml')
|
||||
record['status'] = 'starting'
|
||||
record['phase'] = 'initial-migration-and-api'
|
||||
save()
|
||||
run([*cmd, 'up', '-d', '--no-build', '--pull', 'never', '--no-deps', 'webapi'])
|
||||
conservative.verify_api(sys.modules[__name__], cmd, data, record['images'][0])
|
||||
contract = conservative.guard(sys.modules[__name__], record['images'][0], 'contract', {})
|
||||
before = conservative.guard(sys.modules[__name__], record['images'][0], 'state',
|
||||
{'data': '/data', 'contract': contract}, data)
|
||||
record['phase'] = 'recalculation-and-persistence'
|
||||
save()
|
||||
conservative.finish(sys.modules[__name__], cmd, record['images'][0], deploy, data, contract, before)
|
||||
verify_services(cmd, port)
|
||||
verify_existing_containers(record, base, helper)
|
||||
record['status'] = 'installed'
|
||||
record['result'] = 'installed'
|
||||
record['phase'] = 'complete'
|
||||
record['recalculation'] = 'complete'
|
||||
save()
|
||||
print(f'Installed {project} on port {port} at {revision}')
|
||||
except Exception as exc:
|
||||
record['status'] = 'failed'
|
||||
record['error'] = str(exc)
|
||||
if isinstance(exc, subprocess.CalledProcessError):
|
||||
record['error'] += f'\ncommand: {exc.cmd}\nstdout: {exc.stdout}\nstderr: {exc.stderr}'
|
||||
save()
|
||||
if cmd:
|
||||
try:
|
||||
diagnostics = run([*cmd, 'ps', '-a']) + '\n' + run([*cmd, 'logs', '--no-color', '--tail', '100'])
|
||||
except Exception as diagnostic_error:
|
||||
diagnostics = str(diagnostic_error)
|
||||
path = directory / 'diagnostics.txt'
|
||||
path.write_text(diagnostics, encoding='utf-8')
|
||||
copy_to_host(helper, path, project, 'diagnostics.txt')
|
||||
raise
|
||||
finally:
|
||||
if owns_helper:
|
||||
run(['docker', 'rm', '-f', helper])
|
||||
|
||||
|
||||
def verify_existing_containers(record, base, helper):
|
||||
"""Reject unexpected containers, image identities, mounts and port owners."""
|
||||
project, port = record['project'], record['port']
|
||||
images = record.get('images')
|
||||
if not isinstance(images, list) or len(images) != 2 or not all(isinstance(x, str) for x in images):
|
||||
raise RuntimeError('installation image record is missing')
|
||||
image_ids = [run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip() for image in images]
|
||||
if not all(image_ids):
|
||||
raise RuntimeError('recorded image not found')
|
||||
ids = run(['docker', 'ps', '-aq', '--no-trunc']).splitlines()
|
||||
containers = json.loads(run(['docker', 'inspect', *ids])) if ids else []
|
||||
found = {}
|
||||
root = posixpath.normpath(str(base / project))
|
||||
data = posixpath.join(root, 'data')
|
||||
for item in containers:
|
||||
name = item.get('Name', '').lstrip('/')
|
||||
if name == helper:
|
||||
continue
|
||||
labels = item.get('Config', {}).get('Labels') or {}
|
||||
own = labels.get('com.docker.compose.project') == project
|
||||
mounts = item.get('Mounts') or []
|
||||
for mount in mounts:
|
||||
source = mount.get('Source', '')
|
||||
if not source.startswith('/'):
|
||||
raise RuntimeError(f'unknown container mount: {name}')
|
||||
source = posixpath.normpath(source)
|
||||
overlap = source == root or source.startswith(root + '/') or root.startswith(source.rstrip('/') + '/')
|
||||
if overlap and not own:
|
||||
raise RuntimeError(f'foreign container can access installation: {name}')
|
||||
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
|
||||
if not own and any(str(b.get('HostPort')) == str(port) for values in bindings.values() for b in (values or [])):
|
||||
raise RuntimeError(f'foreign container reserves port {port}: {name}')
|
||||
if not own:
|
||||
continue
|
||||
service = labels.get('com.docker.compose.service')
|
||||
if service not in ('webapi', 'webapp', 'indicadores') or service in found:
|
||||
raise RuntimeError('unexpected container in Compose project')
|
||||
if item.get('State', {}).get('Status') != 'running':
|
||||
raise RuntimeError(f'{service} is not running')
|
||||
expected = image_ids[1 if service == 'webapp' else 0]
|
||||
if item.get('Image') != expected:
|
||||
raise RuntimeError(f'{service} image does not match installation record')
|
||||
if service in ('webapi', 'indicadores'):
|
||||
if len(mounts) != 1 or not any(m.get('Type') == 'bind' and m.get('Source') == data and m.get('Destination') == '/data'
|
||||
and m.get('RW') is True for m in mounts):
|
||||
raise RuntimeError(f'{service} data mount does not match')
|
||||
if bindings:
|
||||
raise RuntimeError(f'{service} publishes an unexpected port')
|
||||
elif mounts or set(bindings) != {'80/tcp'} or not any(str(b.get('HostPort')) == str(port) for b in (bindings.get('80/tcp') or [])):
|
||||
raise RuntimeError('webapp port does not match')
|
||||
found[service] = item['Id']
|
||||
if set(found) != {'webapi', 'webapp', 'indicadores'}:
|
||||
raise RuntimeError('missing Compose project containers')
|
||||
own_networks = {network.get('NetworkID')
|
||||
for item in containers if item.get('Id') in found.values()
|
||||
for network in item.get('NetworkSettings', {}).get('Networks', {}).values()
|
||||
if network.get('NetworkID')}
|
||||
for item in containers:
|
||||
if item.get('Id') in found.values() or item.get('Name', '').lstrip('/') == helper:
|
||||
continue
|
||||
networks = item.get('NetworkSettings', {}).get('Networks', {})
|
||||
if any(network.get('NetworkID') in own_networks for network in networks.values()):
|
||||
raise RuntimeError('foreign container shares the installation network')
|
||||
return [found[name] for name in ('indicadores', 'webapi', 'webapp')]
|
||||
|
||||
|
||||
def update(record, helper, root=ROOT, base=BASE, *, verify_restore=False):
|
||||
return conservative.update(sys.modules[__name__], record, helper, root, base,
|
||||
verify_restore=verify_restore)
|
||||
|
||||
|
||||
def install_auto(port, root=ROOT, base=BASE, *, check_record=None):
|
||||
"""Route under the shared lock after checking any caller-specific record precondition."""
|
||||
normalized = validate_port(port)
|
||||
helper = start_helper(base)
|
||||
try:
|
||||
record = json.loads(host_action(helper, 'lookup', '-', str(normalized)))
|
||||
if check_record is not None:
|
||||
check_record(record)
|
||||
if record is None:
|
||||
ids = run(['docker', 'ps', '-aq', '--no-trunc']).splitlines()
|
||||
for item in json.loads(run(['docker', 'inspect', *ids])) if ids else []:
|
||||
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
|
||||
if any(str(b.get('HostPort')) == str(normalized) for values in bindings.values() for b in (values or [])):
|
||||
raise RuntimeError(f'port {normalized} is reserved by another container')
|
||||
host_action(helper, 'check-port', '-', str(normalized))
|
||||
install(automatic_instance(port), port, 'instalar', root, base, helper=helper)
|
||||
else:
|
||||
update(record, helper, root, base)
|
||||
finally:
|
||||
run(['docker', 'rm', '-f', helper])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('command', choices=['validate', 'install', 'validate-auto', 'install-auto'])
|
||||
parser.add_argument('arguments', nargs='*')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command in ('validate-auto', 'install-auto'):
|
||||
if len(args.arguments) != 1:
|
||||
raise ValueError('automatic commands require exactly one port')
|
||||
port_text = args.arguments[0]
|
||||
instance = automatic_instance(port_text)
|
||||
if args.command == 'validate-auto':
|
||||
project, port = validate(instance, port_text, 'instalar')
|
||||
print(f'Validated request: project={project}, port={port}')
|
||||
else:
|
||||
install_auto(port_text)
|
||||
else:
|
||||
if len(args.arguments) != 3:
|
||||
raise ValueError('commands require instance, port and operation')
|
||||
if args.command == 'validate':
|
||||
project, port = validate(*args.arguments)
|
||||
print(f'Validated request: project={project}, port={port}')
|
||||
else:
|
||||
install(*args.arguments)
|
||||
except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as exc:
|
||||
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc)
|
||||
print(f'Deployment failed: {detail}', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run candidate storage compatibility checks without changing the installation."""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import conservative
|
||||
import dev
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--image', required=True, help='exact candidate WebApi image tag or ID')
|
||||
parser.add_argument('--data', required=True, type=Path, help='absolute daemon-host data directory')
|
||||
args = parser.parse_args()
|
||||
if not args.data.is_absolute():
|
||||
parser.error('--data must be an absolute daemon-host path')
|
||||
try:
|
||||
contract = conservative.guard(dev, args.image, 'contract', {})
|
||||
conservative.guard(dev, args.image, 'inspect', {'data': '/data', 'contract': contract}, args.data)
|
||||
except conservative.GuardFailure as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
print('Candidate storage inspection passed.')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,277 @@
|
||||
"""A small in-memory Docker daemon and installation host for installer tests.
|
||||
|
||||
`FakeDocker.run` replaces `proc.run`: it answers the Docker and Compose commands the installer issues, keeps
|
||||
containers, volumes, networks and images in dictionaries and records every command in `calls`. `LocalHost`
|
||||
replaces the helper container: it runs the registry actions on a temporary directory.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import registry
|
||||
|
||||
def failure(args, message='simulated failure'):
|
||||
return subprocess.CalledProcessError(1, args, output='', stderr=message)
|
||||
|
||||
|
||||
def compose_config(project, env, notebooks=True):
|
||||
"""The effective configuration `docker compose config` prints for the pinned composition."""
|
||||
tag, data, port = env['ISSSTELEON_VERSION'], env['ISSSTELEON_DATOS'], env['ISSSTELEON_PUERTO']
|
||||
urls = {key: value for key, value in env.items() if key.endswith('_DATABASE_URL')}
|
||||
bind = {'type': 'bind', 'source': data, 'target': '/data'}
|
||||
jobs = {'type': 'volume', 'source': 'trabajos_notebooks', 'target': '/trabajos'}
|
||||
api = f'isssteleon/webapi:{tag}'
|
||||
services = {
|
||||
'webapi': {'image': api, 'environment': {**urls, 'NOTEBOOK_JOBS_DIR': '/trabajos',
|
||||
'NOTEBOOK_RUNNER_UID': '10001'},
|
||||
'volumes': [bind] + ([jobs] if notebooks else [])},
|
||||
'indicadores': {'image': api, 'command': ['indicadores'], 'environment': dict(urls), 'volumes': [bind]},
|
||||
'entrenar': {'image': api, 'command': ['entrenar'], 'profiles': ['entrenar'], 'environment': dict(urls),
|
||||
'volumes': [bind]},
|
||||
'webapp': {'image': f'isssteleon/webapp:{tag}', 'ports': [{'published': port, 'target': 80}]},
|
||||
}
|
||||
if notebooks:
|
||||
services['notebooks'] = {
|
||||
'image': api, 'command': ['notebooks'], 'user': '10001:10001', 'network_mode': 'none',
|
||||
'read_only': True, 'cap_drop': ['ALL'], 'security_opt': ['no-new-privileges:true'],
|
||||
'environment': {'NOTEBOOK_JOBS_DIR': '/trabajos'}, 'volumes': [jobs]}
|
||||
config = {'name': project, 'services': services, 'networks': {'default': {'name': project + '_default'}}}
|
||||
if notebooks:
|
||||
config['volumes'] = {'trabajos_notebooks': {'name': f'{project}_trabajos_notebooks'}}
|
||||
return config
|
||||
|
||||
|
||||
class FakeDocker:
|
||||
def __init__(self, base, notebooks=True):
|
||||
self.base, self.notebooks = base, notebooks
|
||||
self.containers, self.volumes, self.networks, self.images = {}, {}, {}, {}
|
||||
self.calls, self.hooks, self.counter = [], [], 0
|
||||
self.loader_output = lambda args: ''
|
||||
self.hospital_report = lambda args: ''
|
||||
|
||||
def new_id(self):
|
||||
self.counter += 1
|
||||
return f'{self.counter:064x}'
|
||||
|
||||
def mutating(self):
|
||||
"""Commands that change the daemon or the host, in order; listing and inspecting are not among them."""
|
||||
def changes(call):
|
||||
return (call[1] in ('build', 'run', 'update', 'stop', 'rm', 'cp', 'create', 'kill', 'system', 'prune')
|
||||
or call[1:3] in (['volume', 'rm'], ['volume', 'create'], ['volume', 'prune'],
|
||||
['network', 'rm'], ['network', 'create'], ['network', 'prune'])
|
||||
or (call[1] == 'compose' and ('up' in call or 'down' in call)))
|
||||
return [call for call in self.calls if changes(call)]
|
||||
|
||||
# -- seeding helpers -------------------------------------------------------------------------------
|
||||
def add_foreign(self, name, mounts=(), networks=('bridge',), ports=(), labels=None, image='foreign'):
|
||||
ident = self.new_id()
|
||||
self.containers[ident] = {
|
||||
'Id': ident, 'Name': '/' + name, 'Image': image, 'State': {'Status': 'running'},
|
||||
'Config': {'Labels': labels or {}}, 'Mounts': list(mounts),
|
||||
'HostConfig': {'PortBindings': {'80/tcp': [{'HostPort': str(p)}] for p in ports}},
|
||||
'NetworkSettings': {'Networks': {n: {'NetworkID': n} for n in networks}}}
|
||||
return ident
|
||||
|
||||
def add_volume(self, name, labels=None):
|
||||
self.volumes[name] = {'Name': name, 'Driver': 'local', 'Scope': 'local', 'Options': None,
|
||||
'Labels': labels or {}, 'CreatedAt': '2026-11-19T00:00:00Z',
|
||||
'Mountpoint': f'/var/lib/docker/volumes/{name}/_data'}
|
||||
|
||||
def add_network(self, name, labels=None):
|
||||
ident = self.new_id()
|
||||
self.networks[ident] = {'Id': ident, 'Name': name, 'Driver': 'bridge', 'Labels': labels or {}}
|
||||
return ident
|
||||
|
||||
# -- the command interpreter -----------------------------------------------------------------------
|
||||
def run(self, args, cwd=None, binary=False, stdin=None):
|
||||
args = [str(a) for a in args]
|
||||
self.calls.append(args)
|
||||
for hook in self.hooks:
|
||||
hook(self, args)
|
||||
if args[0] == 'git':
|
||||
raise AssertionError('tests must not run git through the fake daemon')
|
||||
verb = args[1]
|
||||
if verb == 'compose':
|
||||
return self.compose(args)
|
||||
method = getattr(self, 'do_' + verb.replace('-', '_'), None)
|
||||
if method is None:
|
||||
raise failure(args, f'unsupported docker command: {verb}')
|
||||
return method(args)
|
||||
|
||||
def do_ps(self, args):
|
||||
return '\n'.join(self.containers) + ('\n' if self.containers else '')
|
||||
|
||||
def do_inspect(self, args):
|
||||
if args[2] == '--format':
|
||||
return json.dumps(self.containers[args[4]]['State'])
|
||||
return json.dumps([self.containers[i] for i in args[2:]])
|
||||
|
||||
def do_image(self, args):
|
||||
tag = args[-1]
|
||||
if tag not in self.images:
|
||||
raise failure(args, 'no such image')
|
||||
return self.images[tag] + '\n'
|
||||
|
||||
def do_build(self, args):
|
||||
self.images[args[args.index('-t') + 1]] = 'sha256:' + self.new_id()
|
||||
return ''
|
||||
|
||||
def do_run(self, args):
|
||||
if 'cargar' in args:
|
||||
return self.loader_output(args)
|
||||
if '--entrypoint' in args and '-c' in args:
|
||||
return self.hospital_report(args)
|
||||
return ''
|
||||
|
||||
def do_update(self, args):
|
||||
return ''
|
||||
|
||||
def do_stop(self, args):
|
||||
self.containers[args[2]]['State'] = {'Status': 'exited'}
|
||||
return ''
|
||||
|
||||
def do_rm(self, args):
|
||||
self.containers.pop(args[2])
|
||||
return ''
|
||||
|
||||
def do_volume(self, args):
|
||||
if args[2] == 'ls':
|
||||
names = list(self.volumes)
|
||||
for i, a in enumerate(args):
|
||||
if a == '--filter':
|
||||
key, _, value = args[i + 1].partition('=')
|
||||
if key == 'name':
|
||||
names = [n for n in names if value in n]
|
||||
elif key == 'label':
|
||||
label, _, expected = value.partition('=')
|
||||
names = [n for n in names if self.volumes[n]['Labels'].get(label) == expected]
|
||||
return '\n'.join(names) + ('\n' if names else '')
|
||||
if args[2] == 'inspect':
|
||||
return json.dumps([self.volumes[args[3]]])
|
||||
if args[2] == 'rm':
|
||||
name = args[3]
|
||||
if any(m.get('Name') == name for c in self.containers.values() for m in c['Mounts']):
|
||||
raise failure(args, 'volume is in use')
|
||||
self.volumes.pop(name)
|
||||
return ''
|
||||
raise failure(args, 'unsupported volume command')
|
||||
|
||||
def do_network(self, args):
|
||||
if args[2] == 'ls':
|
||||
if '--format' in args:
|
||||
return '\n'.join(f'{i} {n["Name"]}' for i, n in self.networks.items()) + '\n'
|
||||
found = list(self.networks)
|
||||
if '--filter' in args:
|
||||
key, _, value = args[args.index('--filter') + 1].partition('=')
|
||||
label, _, expected = value.partition('=')
|
||||
found = [i for i in found if self.networks[i]['Labels'].get(label) == expected]
|
||||
return '\n'.join(found) + ('\n' if found else '')
|
||||
if args[2] == 'inspect':
|
||||
item = dict(self.networks[args[3]])
|
||||
item['Containers'] = {c['Id']: {} for c in self.containers.values()
|
||||
if args[3] in (c['NetworkSettings']['Networks'].get(item['Name'], {}).get('NetworkID'),)}
|
||||
return json.dumps([item])
|
||||
if args[2] == 'rm':
|
||||
self.networks.pop(args[3])
|
||||
return ''
|
||||
raise failure(args, 'unsupported network command')
|
||||
|
||||
def do_cp(self, args):
|
||||
return ''
|
||||
|
||||
# -- Compose ---------------------------------------------------------------------------------------
|
||||
def compose(self, args):
|
||||
deploy = Path(args[args.index('--project-directory') + 1])
|
||||
project = args[args.index('--project-name') + 1]
|
||||
action = next(a for a in args[args.index('-f') + 2:] if not a.startswith('-'))
|
||||
if action == 'config':
|
||||
env = dict(line.split('=', 1) for line in (deploy / '.env').read_text().splitlines() if line)
|
||||
return json.dumps(compose_config(project, env, self.notebooks))
|
||||
config = json.loads((deploy / 'docker-compose.yml').read_text().replace('$$', '$'))
|
||||
if action == 'up':
|
||||
self.up(project, config)
|
||||
return ''
|
||||
if action == 'ps':
|
||||
if '-q' in args:
|
||||
service = args[-1]
|
||||
return '\n'.join(i for i, c in self.containers.items()
|
||||
if c['Config']['Labels'].get('com.docker.compose.project') == project
|
||||
and c['Config']['Labels'].get('com.docker.compose.service') == service) + '\n'
|
||||
return 'ps output'
|
||||
if action == 'logs':
|
||||
return 'log output'
|
||||
raise failure(args, f'unsupported compose command: {action}')
|
||||
|
||||
def up(self, project, config):
|
||||
network = project + '_default'
|
||||
if network not in [n['Name'] for n in self.networks.values()]:
|
||||
self.add_network(network, {'com.docker.compose.project': project,
|
||||
'com.docker.compose.network': 'default'})
|
||||
volume = f'{project}_trabajos_notebooks'
|
||||
if 'volumes' in config and volume not in self.volumes:
|
||||
self.add_volume(volume, {'com.docker.compose.project': project,
|
||||
'com.docker.compose.volume': 'trabajos_notebooks'})
|
||||
net_id = next(i for i, n in self.networks.items() if n['Name'] == network)
|
||||
for service, spec in config['services'].items():
|
||||
if 'profiles' in spec:
|
||||
continue
|
||||
mounts = [{'Type': 'bind', 'Source': m['source'], 'Destination': m['target'], 'RW': True}
|
||||
if m['type'] == 'bind' else
|
||||
{'Type': 'volume', 'Name': volume, 'Destination': m['target'], 'RW': True}
|
||||
for m in spec.get('volumes', [])]
|
||||
ident = self.new_id()
|
||||
published = {f'{p["target"]}/tcp': [{'HostPort': str(p['published'])}] for p in spec.get('ports', [])}
|
||||
health = {'Health': {'Status': 'healthy'}} if service == 'webapi' else {}
|
||||
nets = {'none': {}} if spec.get('network_mode') == 'none' else {network: {'NetworkID': net_id}}
|
||||
self.containers[ident] = {
|
||||
'Id': ident, 'Name': f'/{project}-{service}-1', 'Image': self.images[spec['image']],
|
||||
'State': {'Status': 'running', **health},
|
||||
'Config': {'Labels': {'com.docker.compose.project': project,
|
||||
'com.docker.compose.service': service}, 'User': spec.get('user', '')},
|
||||
'Mounts': mounts, 'HostConfig': {'PortBindings': published},
|
||||
'NetworkSettings': {'Networks': nets}}
|
||||
|
||||
|
||||
class LocalHost:
|
||||
"""The daemon-host helper, running the registry actions on a temporary directory."""
|
||||
|
||||
def __init__(self, directory, responses=None):
|
||||
self.directory, self.entered = Path(directory), []
|
||||
self.name = 'local-helper'
|
||||
self.responses = responses or {}
|
||||
self.calls = []
|
||||
self.unreachable = set()
|
||||
|
||||
def __call__(self, base, lock):
|
||||
self.entered.append(lock)
|
||||
return self
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def call(self, action, project, payload):
|
||||
self.calls.append((action, project))
|
||||
return json.loads(json.dumps(registry.dispatch(self.directory, action, project, json.dumps(payload))))
|
||||
|
||||
def copy(self, source, project):
|
||||
shutil.copytree(source, self.directory / project / 'deploy')
|
||||
|
||||
def tcp_check(self, address):
|
||||
if address in self.unreachable:
|
||||
raise RuntimeError(f'{address} does not accept connections')
|
||||
|
||||
def http_get(self, url):
|
||||
path = '/' + url.split('/', 3)[3] if url.count('/') >= 3 else '/'
|
||||
if path in self.responses:
|
||||
return self.responses[path]
|
||||
return {'/reportes/importaciones': {'status': 200, 'body': '{"resumen": {}, "intentos": []}'},
|
||||
'/reportes/indicadores': {'status': 200, 'body': json.dumps(
|
||||
{d: {'estado': 'ok', 'pendiente': False} for d in ('cacu', 'cama', 'tea')})},
|
||||
'/health': {'status': 200, 'body': '{"status": "ok"}'},
|
||||
'/api': {'status': 200, 'body': '{"routes": [{"path": "/health"}]}'},
|
||||
'/': {'status': 200, 'body': '<html><body>app</body></html>'}}[path]
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Local Git repositories shaped like the official ones, for tests of reference resolution.
|
||||
|
||||
`build(root)` creates the remotes below `root/remotes`: the EEG library `alberto/tea`, WebApi, WebApp and models
|
||||
(pinning the library at `libs/tea`), ISSSTELEON pinning them, and an outer repository pinning ISSSTELEON plus a
|
||||
`dev-data` gitlink. Submodule URLs are the real ones; `environment(root)` redirects them to the local copies for every
|
||||
Git command run with it.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ORIGIN = 'ssh://git@10.0.10.41:2222/ISSSTELEON/'
|
||||
TEA_ORIGIN = 'ssh://git@10.0.10.41:2222/alberto/tea.git'
|
||||
IDENTITY = {'GIT_AUTHOR_NAME': 'test', 'GIT_AUTHOR_EMAIL': 'test@example.invalid',
|
||||
'GIT_COMMITTER_NAME': 'test', 'GIT_COMMITTER_EMAIL': 'test@example.invalid'}
|
||||
|
||||
|
||||
def environment(root):
|
||||
remotes = (Path(root) / 'remotes').as_posix()
|
||||
return {**IDENTITY, 'GIT_CONFIG_COUNT': '3',
|
||||
'GIT_CONFIG_KEY_0': f'url.file:///{remotes}/.insteadOf', 'GIT_CONFIG_VALUE_0': ORIGIN,
|
||||
'GIT_CONFIG_KEY_1': 'protocol.file.allow', 'GIT_CONFIG_VALUE_1': 'always',
|
||||
'GIT_CONFIG_KEY_2': f'url.file:///{remotes}/alberto/tea.git.insteadOf', 'GIT_CONFIG_VALUE_2': TEA_ORIGIN}
|
||||
|
||||
|
||||
def git(repo, *args, env=None):
|
||||
result = subprocess.run(['git', '-C', str(repo), *args], check=True, capture_output=True, text=True,
|
||||
env={**os.environ, **(env or {})})
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def commit(repo, name, text, env):
|
||||
path = Path(repo) / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding='utf-8')
|
||||
git(repo, 'add', '-A', env=env)
|
||||
git(repo, 'commit', '-q', '-m', f'change {name}', env=env)
|
||||
return git(repo, 'rev-parse', 'HEAD', env=env)
|
||||
|
||||
|
||||
def init(path, env):
|
||||
Path(path).mkdir(parents=True)
|
||||
git(path, 'init', '-q', '-b', 'dev', env=env)
|
||||
git(path, 'config', 'commit.gpgsign', 'false', env=env)
|
||||
|
||||
|
||||
def build(root):
|
||||
"""Create the remotes; returns their paths and the commit each one is at."""
|
||||
env = environment(root)
|
||||
remotes = Path(root) / 'remotes'
|
||||
result = {'env': env, 'remotes': remotes}
|
||||
init(remotes / 'alberto' / 'tea.git', env)
|
||||
result['tea'] = commit(remotes / 'alberto' / 'tea.git', 'pyproject.toml', '[project]\nname = "tea"\n', env)
|
||||
for name in ('WebApi', 'WebApp', 'models'):
|
||||
init(remotes / f'{name}.git', env)
|
||||
result[name] = commit(remotes / f'{name}.git', 'Dockerfile', f'FROM scratch # {name}\n', env)
|
||||
models = remotes / 'models.git'
|
||||
git(models, 'submodule', 'add', '-q', '--name', 'tea', TEA_ORIGIN, 'libs/tea', env=env)
|
||||
git(models, 'commit', '-q', '-m', 'pin the EEG library', env=env)
|
||||
result['models'] = git(models, 'rev-parse', 'HEAD', env=env)
|
||||
application = remotes / 'ISSSTELEON.git'
|
||||
init(application, env)
|
||||
commit(application, 'dist/docker-compose.yml', 'name: isssteleon\n', env)
|
||||
for name in ('WebApi', 'WebApp', 'models'):
|
||||
git(application, 'submodule', 'add', '-q', f'{ORIGIN}{name}.git', name, env=env)
|
||||
git(application, 'commit', '-q', '-m', 'pin applications', env=env)
|
||||
result['ISSSTELEON'] = git(application, 'rev-parse', 'HEAD', env=env)
|
||||
outer = remotes / 'WorkingNarrative.git'
|
||||
init(outer, env)
|
||||
git(outer, 'submodule', 'add', '-q', f'{ORIGIN}ISSSTELEON.git', 'ISSSTELEON', env=env)
|
||||
result['dev-data'] = 'd' * 40
|
||||
git(outer, 'update-index', '--add', '--cacheinfo', f'160000,{result["dev-data"]},dev-data', env=env)
|
||||
git(outer, 'commit', '-q', '-m', 'pin ISSSTELEON', env=env)
|
||||
result['outer'] = git(outer, 'rev-parse', 'HEAD', env=env)
|
||||
result['url'] = outer.as_posix()
|
||||
return result
|
||||
|
||||
|
||||
def advance(fixture, branch='dev'):
|
||||
"""Add a commit to the outer repository's branch and return its SHA."""
|
||||
outer = fixture['remotes'] / 'WorkingNarrative.git'
|
||||
git(outer, 'checkout', '-q', branch, env=fixture['env'])
|
||||
return commit(outer, 'notes.txt', os.urandom(8).hex(), fixture['env'])
|
||||
@@ -1,327 +0,0 @@
|
||||
"""Reserve projects and atomically persist records under the installer lock."""
|
||||
|
||||
import json
|
||||
import hashlib
|
||||
import errno
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import data_guard
|
||||
|
||||
|
||||
def write_record(directory, record):
|
||||
fd, name = tempfile.mkstemp(prefix='.installation-', dir=directory)
|
||||
try:
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, indent=2)
|
||||
stream.write('\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(name, directory / 'installation.json')
|
||||
if os.name != 'nt':
|
||||
directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory_fd)
|
||||
finally:
|
||||
os.close(directory_fd)
|
||||
finally:
|
||||
if os.path.exists(name):
|
||||
os.unlink(name)
|
||||
|
||||
|
||||
def read_record(directory):
|
||||
if (directory / 'installation.json').is_symlink():
|
||||
raise RuntimeError(f'symlinked installation record: {directory}')
|
||||
record = json.loads((directory / 'installation.json').read_text(encoding='utf-8'))
|
||||
if (not isinstance(record, dict) or record.get('project') != directory.name
|
||||
or type(record.get('port')) is not int or not 1024 <= record['port'] <= 65535
|
||||
or record.get('status') not in ('preparing', 'building', 'starting', 'installed', 'failed',
|
||||
'updating', 'update_failed', 'replacing', 'replace_failed')):
|
||||
raise RuntimeError(f'invalid installation record: {directory}')
|
||||
return record
|
||||
|
||||
|
||||
def reconcile_record(base, project, payload, *, apply=False):
|
||||
"""Check pre-activation state and optionally change only its status."""
|
||||
directory = base / project
|
||||
if directory.is_symlink() or not directory.is_dir():
|
||||
raise RuntimeError('invalid installation directory')
|
||||
record = read_record(directory)
|
||||
operation = payload['operation_id']
|
||||
if (not re.fullmatch(r'[0-9a-f]{32}', operation)
|
||||
or record.get('operation_id') != operation or record.get('status') != 'update_failed'
|
||||
or record.get('phase') not in ('quiescing', 'backup', 'restore-verification')):
|
||||
raise RuntimeError('record is not the expected pre-activation failure')
|
||||
if record['port'] != payload['port'] or record.get('revision') != payload['revision']:
|
||||
raise RuntimeError('recorded port or original revision differs')
|
||||
for entry in base.iterdir():
|
||||
if entry.name == project:
|
||||
continue
|
||||
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
|
||||
if entry.is_symlink() or not entry.is_dir():
|
||||
raise RuntimeError('invalid installation directory in registry')
|
||||
if read_record(entry)['port'] == record['port']:
|
||||
raise RuntimeError('port is reserved by another installation')
|
||||
if not re.fullmatch(r'[0-9a-f]{40}', record['revision']):
|
||||
raise RuntimeError('invalid original revision')
|
||||
if not isinstance(record.get('gitlinks'), dict) or not record['gitlinks']:
|
||||
raise RuntimeError('original gitlinks are missing')
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
path = directory / name
|
||||
if path.is_symlink() or not path.is_dir() or path.stat().st_dev != directory.stat().st_dev:
|
||||
raise RuntimeError('invalid original installation path: ' + name)
|
||||
for name in ('.archive', '.updates'):
|
||||
parent = directory / name
|
||||
if parent.is_symlink() or (parent.exists() and not parent.is_dir()):
|
||||
raise RuntimeError('invalid activation directory: ' + name)
|
||||
if (parent / operation).exists() or (parent / operation).is_symlink():
|
||||
raise RuntimeError('operation has activation or staging artifacts')
|
||||
path = directory / 'installation.json'
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
if apply:
|
||||
if payload.get('record_sha256') != digest:
|
||||
raise RuntimeError('record changed during reconciliation')
|
||||
write_record(directory, dict(record, status='installed'))
|
||||
return {'record': record, 'record_sha256': digest}
|
||||
|
||||
|
||||
def archive_installation(base, project, operation, previous):
|
||||
"""Archive application payloads while retaining the original data directory."""
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', operation):
|
||||
raise ValueError('invalid operation id')
|
||||
directory = base / project
|
||||
record = read_record(directory)
|
||||
if record['status'] != 'updating' or record.get('operation_id') != operation:
|
||||
raise RuntimeError('update is not reserved')
|
||||
archive_root = directory / '.archive'
|
||||
if archive_root.is_symlink() or (archive_root.exists() and not archive_root.is_dir()):
|
||||
raise RuntimeError('invalid archive directory')
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
path = directory / name
|
||||
if path.is_symlink() or not path.is_dir() or path.stat().st_dev != directory.stat().st_dev:
|
||||
raise RuntimeError(f'invalid installation path: {path}')
|
||||
archive_root.mkdir(mode=0o700, exist_ok=True)
|
||||
if archive_root.stat().st_dev != directory.stat().st_dev:
|
||||
raise RuntimeError('archive must be on the installation filesystem')
|
||||
target = archive_root / operation
|
||||
target.mkdir(mode=0o700)
|
||||
write_record(target, previous)
|
||||
for name in ('codigo', 'deploy'):
|
||||
os.rename(directory / name, target / name)
|
||||
return target
|
||||
|
||||
|
||||
def operation_directory(base, project, operation):
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', operation):
|
||||
raise ValueError('invalid operation id')
|
||||
directory = base / project
|
||||
record = read_record(directory)
|
||||
if record['status'] != 'updating' or record.get('operation_id') != operation:
|
||||
raise RuntimeError('update is not reserved')
|
||||
data_guard.regular_tree(directory / 'data')
|
||||
return directory
|
||||
|
||||
|
||||
def private_directory(path):
|
||||
if path.is_symlink() or (path.exists() and not path.is_dir()):
|
||||
raise RuntimeError('invalid private directory')
|
||||
path.mkdir(mode=0o700, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def prepare_backup(base, project, verify_restore):
|
||||
"""Check destination creation and helper write access before quiescing."""
|
||||
for name in (('.backups', '.restores') if verify_restore else ('.backups',)):
|
||||
directory = private_directory(private_directory(base / name) / project)
|
||||
fd, probe = tempfile.mkstemp(prefix='.write-check-', dir=directory)
|
||||
try:
|
||||
os.close(fd)
|
||||
finally:
|
||||
os.unlink(probe)
|
||||
|
||||
|
||||
def backup_installation(base, project, payload):
|
||||
"""Back up quiesced storage outside the application instance."""
|
||||
operation = payload['operation_id']
|
||||
directory = operation_directory(base, project, operation)
|
||||
backups = private_directory(base / '.backups')
|
||||
project_backups = private_directory(backups / project)
|
||||
destination = project_backups / operation
|
||||
manifest = data_guard.create_backup(directory / 'data', destination, payload['contract'], payload['origin'])
|
||||
return {'path': str(destination), 'state': manifest['state']}
|
||||
|
||||
|
||||
def verify_isolated_restore(base, project, operation):
|
||||
"""Restore the operation backup to a new private location and verify it."""
|
||||
operation_directory(base, project, operation)
|
||||
source = base / '.backups' / project / operation
|
||||
restores = private_directory(base / '.restores')
|
||||
project_restores = private_directory(restores / project)
|
||||
destination = project_restores / operation
|
||||
data_guard.restore_backup(source, destination)
|
||||
return destination
|
||||
|
||||
|
||||
def stage_installation(base, project, operation):
|
||||
directory = operation_directory(base, project, operation)
|
||||
updates = private_directory(directory / '.updates')
|
||||
target = updates / operation
|
||||
target.mkdir(mode=0o700)
|
||||
return target
|
||||
|
||||
|
||||
def activate_installation(base, project, operation, previous):
|
||||
directory = operation_directory(base, project, operation)
|
||||
candidate = directory / '.updates' / operation
|
||||
if candidate.is_symlink() or not candidate.is_dir():
|
||||
raise RuntimeError('staged application is missing')
|
||||
for name in ('codigo', 'deploy'):
|
||||
path = candidate / name
|
||||
if path.is_symlink() or not path.is_dir():
|
||||
raise RuntimeError('staged application is incomplete')
|
||||
archive = archive_installation(base, project, operation, previous)
|
||||
for name in ('codigo', 'deploy'):
|
||||
os.rename(candidate / name, directory / name)
|
||||
return archive
|
||||
|
||||
|
||||
def find_installation(base, port, *, missing_ok=False):
|
||||
"""Resolve a unique installed project by its recorded port under the shared lock."""
|
||||
if type(port) is not int or not 1024 <= port <= 65535:
|
||||
raise ValueError('invalid port')
|
||||
matches = []
|
||||
ports = {}
|
||||
for entry in base.iterdir():
|
||||
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
|
||||
if entry.is_symlink() or not entry.is_dir():
|
||||
raise RuntimeError(f'invalid instance directory: {entry}')
|
||||
record = read_record(entry)
|
||||
if not re.fullmatch(r'isssteleon-[a-z][a-z0-9]*(?:-[a-z0-9]+)*', entry.name) or len(entry.name) > 51:
|
||||
raise RuntimeError(f'invalid project name: {entry.name}')
|
||||
if record['port'] in ports:
|
||||
raise RuntimeError(f'duplicate recorded port {record["port"]}: {ports[record["port"]]} and {entry.name}')
|
||||
ports[record['port']] = entry.name
|
||||
if record['port'] == port:
|
||||
matches.append((entry, record))
|
||||
if not matches and missing_ok:
|
||||
return None
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError(f'no installation registered on port {port}')
|
||||
directory, record = matches[0]
|
||||
if record['status'] != 'installed':
|
||||
raise RuntimeError(f'installation is not installed: {directory} (status={record["status"]}); '
|
||||
'manual recovery or reconciliation required; no deployment was attempted')
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
path = directory / name
|
||||
if path.is_symlink() or not path.is_dir():
|
||||
raise RuntimeError(f'invalid installation path: {path}')
|
||||
archive_root = directory / '.archive'
|
||||
if archive_root.is_symlink() or (archive_root.exists() and not archive_root.is_dir()):
|
||||
raise RuntimeError(f'invalid archive directory: {archive_root}')
|
||||
if archive_root.exists() and archive_root.stat().st_dev != directory.stat().st_dev:
|
||||
raise RuntimeError('archive must be on the installation filesystem')
|
||||
if any((directory / name).stat().st_dev != directory.stat().st_dev for name in ('codigo', 'deploy', 'data')):
|
||||
raise RuntimeError('installation paths must be on the same filesystem')
|
||||
for name in ('.env', 'docker-compose.yml'):
|
||||
path = directory / 'deploy' / name
|
||||
if path.is_symlink():
|
||||
raise RuntimeError(f'symlinked deployment file: {path}')
|
||||
return record
|
||||
|
||||
|
||||
def reserve(base, project, port):
|
||||
directory = base / project
|
||||
if directory.exists() or directory.is_symlink():
|
||||
raise RuntimeError(f'instance directory already exists: {directory}')
|
||||
ports = {}
|
||||
for entry in base.iterdir():
|
||||
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
|
||||
if entry.is_symlink() or not entry.is_dir():
|
||||
raise RuntimeError(f'invalid instance directory: {entry}')
|
||||
record = read_record(entry)
|
||||
if record['port'] in ports:
|
||||
raise RuntimeError(f'duplicate recorded port {record["port"]}: {ports[record["port"]]} and {entry.name}')
|
||||
ports[record['port']] = entry.name
|
||||
if record['port'] == port:
|
||||
raise RuntimeError(f'port {port} is reserved by {entry.name}')
|
||||
directory.mkdir(mode=0o700)
|
||||
write_record(directory, {'project': project, 'port': port, 'status': 'preparing'})
|
||||
(directory / 'data').mkdir(mode=0o700)
|
||||
|
||||
|
||||
def main():
|
||||
base, action, project, value = sys.argv[1:]
|
||||
if value == '-':
|
||||
value = sys.stdin.read()
|
||||
base = Path(base)
|
||||
if action not in ('lookup', 'check-port') and not re.fullmatch(
|
||||
r'isssteleon-[a-z][a-z0-9]*(?:-[a-z0-9]+)*', project):
|
||||
raise ValueError('invalid project')
|
||||
if action == 'reserve':
|
||||
reserve(base, project, int(value))
|
||||
elif action == 'lookup':
|
||||
print(json.dumps(find_installation(base, int(value), missing_ok=True)))
|
||||
elif action == 'archive':
|
||||
payload = json.loads(value)
|
||||
print(archive_installation(base, project, payload['operation_id'], payload['previous']))
|
||||
elif action == 'read-deploy':
|
||||
directory = base / project / 'deploy'
|
||||
result = {}
|
||||
for name in ('.env', 'docker-compose.yml'):
|
||||
path = directory / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise RuntimeError('deployment configuration is missing or linked')
|
||||
result[name] = path.read_text(encoding='utf-8')
|
||||
print(json.dumps(result))
|
||||
elif action in ('reconcile-check', 'reconcile-apply'):
|
||||
print(json.dumps(reconcile_record(base, project, json.loads(value),
|
||||
apply=action == 'reconcile-apply')))
|
||||
elif action == 'backup':
|
||||
print(json.dumps(backup_installation(base, project, json.loads(value))))
|
||||
elif action == 'prepare-backup':
|
||||
prepare_backup(base, project, json.loads(value)['verify_restore'])
|
||||
elif action == 'verify-restore':
|
||||
print(verify_isolated_restore(base, project, value))
|
||||
elif action == 'stage':
|
||||
print(stage_installation(base, project, value))
|
||||
elif action == 'activate':
|
||||
payload = json.loads(value)
|
||||
print(activate_installation(base, project, payload['operation_id'], payload['previous']))
|
||||
elif action == 'space':
|
||||
if shutil.disk_usage(base).free < int(value):
|
||||
raise RuntimeError('insufficient space for prepared installation')
|
||||
elif action in ('update-space', 'update-space-restore'):
|
||||
files = data_guard.regular_tree(base / project / 'data')
|
||||
# Leave room for the normalized backup, staged source, and temporary SQLite pages.
|
||||
copies = 3 if action == 'update-space-restore' else 2
|
||||
required = copies * sum(path.stat().st_size for path in files.values()) + int(value) + 64 * 1024 * 1024
|
||||
if int(value) < 0 or shutil.disk_usage(base).free < required:
|
||||
raise RuntimeError('insufficient space for update backup and prepared application')
|
||||
elif action == 'check-port':
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(('0.0.0.0', int(value)))
|
||||
try:
|
||||
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
|
||||
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
||||
sock.bind(('::', int(value)))
|
||||
except OSError as exc:
|
||||
if exc.errno not in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
|
||||
raise
|
||||
elif action == 'save':
|
||||
directory = base / project
|
||||
previous = read_record(directory)
|
||||
record = json.loads(value)
|
||||
if record.get('project') != project or record.get('port') != previous['port']:
|
||||
raise RuntimeError('installation identity changed')
|
||||
write_record(directory, record)
|
||||
else:
|
||||
raise ValueError(f'unknown action: {action}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,529 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install and cleanly reinstall disposable DEV instances of ISSSTELEON.
|
||||
|
||||
Two operations, each in two steps. Run without a confirmation, an operation only reads: it resolves the Git
|
||||
reference to exact commits, checks the host, Docker and the composition, and prints the plan together with the
|
||||
confirmation that approves exactly that plan. Run with the confirmation, it recomputes the plan under the
|
||||
installer lock and acts only if it is unchanged.
|
||||
|
||||
installer.py install <puerto> <referencia> [confirmacion]
|
||||
installer.py reinstall <puerto> <referencia> [confirmacion]
|
||||
installer.py load-data <puerto> <hospital> [confirmacion]
|
||||
installer.py validate-dispatch
|
||||
|
||||
Reinstalling removes the registered instance's containers, notebook jobs volume, default network and directory,
|
||||
data included, after proving the instance is a DEV installation of this installer. No global cleanup is used.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import composition
|
||||
import proc
|
||||
import registry
|
||||
import resources
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BASE = PurePosixPath('/srv/workingnarrative-dev')
|
||||
HELPER_IMAGE = os.environ.get('DEV_INSTALLER_HELPER_IMAGE', 'python:3.12-slim')
|
||||
OFFICIAL_SERVER = 'http://10.0.10.41:3000'
|
||||
LOCK_SCRIPT = """import fcntl, time
|
||||
with open('/host/.install.lock', 'a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
open('/tmp/ready', 'w').close()
|
||||
while True: time.sleep(60)
|
||||
"""
|
||||
READ_ONLY_SCRIPT = """import time
|
||||
open('/tmp/ready', 'w').close()
|
||||
while True: time.sleep(60)
|
||||
"""
|
||||
TCP_SCRIPT = """import socket, sys
|
||||
host, _, port = sys.argv[1].rpartition(':')
|
||||
socket.create_connection((host, int(port)), timeout=10).close()
|
||||
"""
|
||||
HTTP_SCRIPT = """import json, sys, urllib.request
|
||||
with urllib.request.urlopen(sys.argv[1], timeout=15) as response:
|
||||
print(json.dumps({'status': response.status, 'body': response.read(200000).decode('utf-8', 'replace')}))
|
||||
"""
|
||||
|
||||
|
||||
def dispatch_metadata(root=ROOT):
|
||||
"""Validate the event identity and its immutable checked-out commit; return the workflow reference."""
|
||||
ref = os.environ.get('DISPATCH_REF', '')
|
||||
name = os.environ.get('DISPATCH_REF_NAME', '')
|
||||
sha = os.environ.get('DISPATCH_SHA', '')
|
||||
if (os.environ.get('DISPATCH_REPOSITORY') != 'ISSSTELEON/WorkingNarrative'
|
||||
or os.environ.get('DISPATCH_SERVER', '').rstrip('/') != OFFICIAL_SERVER
|
||||
or os.environ.get('DISPATCH_REF_TYPE') != 'branch'
|
||||
or not name or ref != 'refs/heads/' + name
|
||||
or not re.fullmatch(r'[0-9a-f]{40}', sha)):
|
||||
raise ValueError('invalid deployment event identity or branch reference')
|
||||
proc.run(['git', 'check-ref-format', ref])
|
||||
if proc.git(root, 'rev-parse', 'HEAD').strip() != sha:
|
||||
raise RuntimeError('checkout does not match the dispatched SHA')
|
||||
return {'workflow_ref': ref, 'workflow_sha': sha}
|
||||
|
||||
|
||||
class Host:
|
||||
"""Registry actions and local HTTP checks on the Docker daemon host, through a helper container.
|
||||
|
||||
With `lock` the helper holds the host-wide installer lock and can write the base directory; without it the
|
||||
helper only reads, which is what a plan needs."""
|
||||
|
||||
def __init__(self, base, lock):
|
||||
self.base, self.lock, self.name = base, lock, None
|
||||
|
||||
def __enter__(self):
|
||||
name = resources.HELPER_PREFIX + uuid.uuid4().hex
|
||||
mount = f'type=bind,src={self.base},dst=/host' + ('' if self.lock else ',readonly')
|
||||
try:
|
||||
proc.run(['docker', 'run', '-d', '--network', 'host', '--label', resources.HELPER_LABEL + '=helper',
|
||||
'--name', name, '--mount', mount, HELPER_IMAGE, 'python3', '-c',
|
||||
LOCK_SCRIPT if self.lock else READ_ONLY_SCRIPT])
|
||||
self.name = name
|
||||
deadline = time.monotonic() + 300
|
||||
while time.monotonic() < deadline:
|
||||
if self.exec("import os; print(int(os.path.exists('/tmp/ready')))").strip() == '1':
|
||||
return self
|
||||
time.sleep(2)
|
||||
raise RuntimeError('timed out waiting for the shared installation lock')
|
||||
except Exception as exc:
|
||||
self.close(name)
|
||||
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc)
|
||||
raise RuntimeError(f'helper failed; the daemon host directory {self.base} must already exist: {detail}') from exc
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close(self.name)
|
||||
|
||||
@staticmethod
|
||||
def close(name):
|
||||
if name:
|
||||
try:
|
||||
proc.run(['docker', 'rm', '-f', name])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def exec(self, script, *args, stdin=None):
|
||||
return proc.run(['docker', 'exec', *(['-i'] if stdin is not None else []), self.name, 'python3', '-c',
|
||||
script, *args], stdin=stdin)
|
||||
|
||||
def call(self, action, project, payload):
|
||||
source = Path(__file__).with_name('registry.py').read_text(encoding='utf-8')
|
||||
out = self.exec(source, '/host', action, project, '-', stdin=json.dumps(payload))
|
||||
return json.loads(out)
|
||||
|
||||
def copy(self, directory, project):
|
||||
"""Place the instance's deployment files next to its record."""
|
||||
proc.run(['docker', 'cp', str(directory), f'{self.name}:/host/{project}/deploy'])
|
||||
|
||||
def http_get(self, url):
|
||||
return json.loads(self.exec(HTTP_SCRIPT, url))
|
||||
|
||||
def tcp_check(self, address):
|
||||
"""Fail unless the daemon host can open a connection to `host:port`."""
|
||||
try:
|
||||
self.exec(TCP_SCRIPT, address)
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise RuntimeError(f'{address} does not accept connections from the daemon host: '
|
||||
f'{(exc.stderr or "").strip()[-200:]}') from None
|
||||
|
||||
|
||||
def compose(project, deploy, *args):
|
||||
return ['docker', 'compose', '--project-name', project, '--project-directory', str(deploy),
|
||||
'--env-file', str(deploy / '.env'), '-f', str(deploy / 'docker-compose.yml'), *args]
|
||||
|
||||
|
||||
def configure(deploy, data, project, revision, port, operation):
|
||||
tag = f'{project}-{revision[:12]}-{operation}'
|
||||
env = (f'ISSSTELEON_VERSION={tag}\nISSSTELEON_DATOS={data}\nISSSTELEON_PUERTO={port}\n'
|
||||
+ ''.join(f'{name}_DATABASE_URL=sqlite:////data/{name.lower()}.db\n'
|
||||
for name in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE')))
|
||||
(deploy / '.env').write_text(env, encoding='utf-8')
|
||||
return tag
|
||||
|
||||
|
||||
def unsafe_service(service):
|
||||
namespaces = [str(service.get(key, '')) for key in ('network_mode', 'pid', 'ipc', 'userns_mode', 'cgroup')]
|
||||
unmanaged = {'privileged', 'devices', 'device_cgroup_rules', 'cap_add', 'volumes_from', 'use_api_socket',
|
||||
'post_start', 'pre_stop', 'develop', 'secrets', 'configs', 'external_links'}
|
||||
return (any(service.get(key) for key in unmanaged)
|
||||
or any(value == 'host' or value.startswith(('container:', 'service:')) for value in namespaces))
|
||||
|
||||
|
||||
def data_mount(volume, data):
|
||||
return (volume.get('type') == 'bind' and volume.get('source') == str(data) and volume.get('target') == '/data'
|
||||
and not volume.get('read_only'))
|
||||
|
||||
|
||||
def jobs_mount(volume):
|
||||
return (volume.get('type') == 'volume' and volume.get('source') == composition.NOTEBOOK_VOLUME
|
||||
and volume.get('target') == composition.NOTEBOOK_JOBS and not volume.get('read_only')
|
||||
and volume.get('volume') in (None, {}))
|
||||
|
||||
|
||||
def verify_config(config, project, data, tag, port):
|
||||
"""Check the effective composition against what the installer manages; return whether it has notebooks."""
|
||||
if config.get('name') != project:
|
||||
raise RuntimeError('effective Compose project name does not match')
|
||||
services = config.get('services', {})
|
||||
notebooks = composition.NOTEBOOK_SERVICE in services
|
||||
required = set(composition.BASE_SERVICES) | ({composition.NOTEBOOK_SERVICE} if notebooks else set())
|
||||
declared = {name for name in services
|
||||
if name in composition.PROFILE_SERVICES and services[name].get('profiles') == [name]}
|
||||
if set(services) - declared != required:
|
||||
raise RuntimeError('unexpected Compose services')
|
||||
volume = composition.notebook_volume_name(project)
|
||||
if (config.get('volumes') or {}) != ({composition.NOTEBOOK_VOLUME: {'name': volume}} if notebooks else {}):
|
||||
raise RuntimeError('unexpected Compose volumes')
|
||||
networks = config.get('networks') or {}
|
||||
if networks:
|
||||
default = networks.get('default') or {}
|
||||
if (set(networks) != {'default'} or default.get('name') != project + '_default'
|
||||
or set(default) - {'name', 'ipam'} or default.get('ipam')):
|
||||
raise RuntimeError('unexpected Compose networks')
|
||||
for name, service in services.items():
|
||||
if unsafe_service(service):
|
||||
raise RuntimeError(f'unsafe Compose service: {name}')
|
||||
for name in ('webapi', 'indicadores', *sorted(declared)):
|
||||
service = services[name]
|
||||
if service.get('image') != f'isssteleon/webapi:{tag}':
|
||||
raise RuntimeError(f'unexpected {name} image')
|
||||
volumes = service.get('volumes', [])
|
||||
expected = 2 if notebooks and name == 'webapi' else 1
|
||||
if (len(volumes) != expected or sum(data_mount(v, data) for v in volumes) != 1
|
||||
or sum(jobs_mount(v) for v in volumes) != expected - 1):
|
||||
raise RuntimeError(f'unexpected {name} data mount')
|
||||
if service.get('ports'):
|
||||
raise RuntimeError(f'unexpected {name} published ports')
|
||||
env = service.get('environment', {})
|
||||
for domain in ('CACU', 'CAMA', 'TEA', 'GOVERNANCE'):
|
||||
if env.get(f'{domain}_DATABASE_URL') != f'sqlite:////data/{domain.lower()}.db':
|
||||
raise RuntimeError(f'unexpected {name} database configuration')
|
||||
if any(key in env and env[key] != value for key, value in composition.PERSISTENT_ENV.items()):
|
||||
raise RuntimeError(f'unexpected {name} storage configuration')
|
||||
if notebooks:
|
||||
env = services['webapi'].get('environment', {})
|
||||
if (env.get('NOTEBOOK_JOBS_DIR') != composition.NOTEBOOK_JOBS
|
||||
or env.get('NOTEBOOK_RUNNER_UID') != composition.NOTEBOOK_USER.split(':')[0]):
|
||||
raise RuntimeError('unexpected webapi notebook configuration')
|
||||
runner = services[composition.NOTEBOOK_SERVICE]
|
||||
env = runner.get('environment', {})
|
||||
if (runner.get('image') != f'isssteleon/webapi:{tag}' or runner.get('command') != ['notebooks']
|
||||
or runner.get('entrypoint') or runner.get('user') != composition.NOTEBOOK_USER
|
||||
or runner.get('network_mode') != 'none' or runner.get('read_only') is not True
|
||||
or 'ALL' not in (runner.get('cap_drop') or [])
|
||||
or 'no-new-privileges:true' not in (runner.get('security_opt') or [])
|
||||
or runner.get('ports') or len(runner.get('volumes', [])) != 1
|
||||
or not jobs_mount(runner['volumes'][0]) or env.get('NOTEBOOK_JOBS_DIR') != composition.NOTEBOOK_JOBS
|
||||
or any('/data' in str(value) for value in env.values())):
|
||||
raise RuntimeError('unexpected notebooks isolation')
|
||||
if services['webapp'].get('image') != f'isssteleon/webapp:{tag}':
|
||||
raise RuntimeError('unexpected webapp image')
|
||||
if services['webapp'].get('volumes'):
|
||||
raise RuntimeError('unexpected webapp mounts')
|
||||
ports = services['webapp'].get('ports', [])
|
||||
if len(ports) != 1 or str(ports[0].get('published')) != str(port) or int(ports[0].get('target', 0)) != 80:
|
||||
raise RuntimeError('unexpected webapp port')
|
||||
return notebooks
|
||||
|
||||
|
||||
def persist_config(deploy, config):
|
||||
"""Save the verified effective composition, so what runs is exactly what was checked."""
|
||||
def literal(value):
|
||||
if isinstance(value, str):
|
||||
return value.replace('$', '$$')
|
||||
if isinstance(value, list):
|
||||
return [literal(item) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {key: literal(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
path = deploy / 'docker-compose.yml'
|
||||
path.write_text(json.dumps(literal(config), indent=2), encoding='utf-8')
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def prepare(checkout_dir, comp, project, port, base, workdir):
|
||||
"""Export the composition and check that it can be built and run as this installer requires.
|
||||
|
||||
Writes only inside `workdir`; builds nothing."""
|
||||
operation = uuid.uuid4().hex[:16]
|
||||
source, deploy = Path(workdir) / 'codigo', Path(workdir) / 'deploy'
|
||||
composition.export_tree(Path(checkout_dir) / 'ISSSTELEON', comp['application'], source)
|
||||
for needed in ('WebApi/Dockerfile', 'WebApp/Dockerfile', 'dist/docker-compose.yml'):
|
||||
if not (source / needed).is_file():
|
||||
raise RuntimeError(f'the composition lacks {needed}')
|
||||
composition.copy_deploy(source, deploy)
|
||||
data = PurePosixPath(str(base)) / project / 'data'
|
||||
tag = configure(deploy, data, project, comp['commit'], port, operation)
|
||||
cmd = compose(project, deploy)
|
||||
config = json.loads(proc.run([*cmd, 'config', '--format', 'json']))
|
||||
notebooks = verify_config(config, project, data, tag, port)
|
||||
# The worker recalculates after imports; it does not recalculate on its own at start.
|
||||
worker = config['services']['indicadores']
|
||||
worker['environment'] = dict(worker.get('environment', {}), INDICADORES_AL_INICIAR='0')
|
||||
return {'source': source, 'deploy': deploy, 'data': data, 'tag': tag, 'operation': operation,
|
||||
'images': [f'isssteleon/webapi:{tag}', f'isssteleon/webapp:{tag}'], 'config': config,
|
||||
'notebooks': notebooks, 'cmd': cmd}
|
||||
|
||||
|
||||
def build_images(candidate):
|
||||
source = candidate['source']
|
||||
proc.run(['docker', 'build', '-t', candidate['images'][0], '-f', source / 'WebApi/Dockerfile', source])
|
||||
proc.run(['docker', 'build', '-t', candidate['images'][1], source / 'WebApp'])
|
||||
|
||||
|
||||
def digest(plan):
|
||||
return hashlib.sha256(composition.digest_text(plan).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def confirmation_for(plan):
|
||||
word = 'instalar' if plan['operation'] == 'install' else 'reinstalar'
|
||||
return f'{word}-{plan["port"]}-{digest(plan)}'
|
||||
|
||||
|
||||
def existing_image_ids(images):
|
||||
"""IDs of the recorded images that still exist; one that was removed cannot be in use."""
|
||||
ids = set()
|
||||
for image in images or []:
|
||||
try:
|
||||
ids.add(proc.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip())
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
return ids
|
||||
|
||||
|
||||
def plan_install(host, base, port, comp):
|
||||
"""Check that a new instance can take `port`; nothing is registered or created."""
|
||||
project = composition.project_for(port)
|
||||
if host.call('lookup', '-', port) is not None:
|
||||
raise RuntimeError(f'port {port} is already registered; use the reinstall workflow if it is a DEV instance')
|
||||
resources.assert_absent(project, port, base)
|
||||
host.call('check-port', '-', port)
|
||||
return {'operation': 'install', 'port': port, 'project': project, 'composition': comp}
|
||||
|
||||
|
||||
def plan_reinstall(host, base, port, comp):
|
||||
"""Describe everything a clean reinstallation would remove; the instance must prove to be a DEV one."""
|
||||
record = host.call('lookup', '-', port)
|
||||
if record is None:
|
||||
raise RuntimeError(f'no installation is registered on port {port}; use the install workflow')
|
||||
project = record['project']
|
||||
identity = host.call('identity', project, {'port': port})
|
||||
found = resources.discover(project, port, base, existing_image_ids(record.get('images')))
|
||||
if not found['containers']:
|
||||
host.call('check-port', '-', port)
|
||||
return {'operation': 'reinstall', 'port': port, 'project': project, 'composition': comp,
|
||||
'directory': identity, 'resources': resources.plan_view(found)}
|
||||
|
||||
|
||||
def verify_services(cmd, notebooks, timeout=600):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = 'services did not start'
|
||||
expected = composition.BASE_SERVICES + ((composition.NOTEBOOK_SERVICE,) if notebooks else ())
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
for service in expected:
|
||||
ids = proc.run([*cmd, 'ps', '-q', service]).splitlines()
|
||||
if len(ids) != 1:
|
||||
raise RuntimeError(f'{service}: expected one running container')
|
||||
state = json.loads(proc.run(['docker', 'inspect', '--format', '{{json .State}}', ids[0]]))
|
||||
if state.get('Status') != 'running':
|
||||
raise RuntimeError(f'{service}: {state.get("Status")}')
|
||||
if service == 'webapi' and state.get('Health', {}).get('Status') != 'healthy':
|
||||
raise RuntimeError(f'webapi health: {state.get("Health", {}).get("Status", "missing")}')
|
||||
return
|
||||
except Exception as exc:
|
||||
last = str(exc)
|
||||
time.sleep(3)
|
||||
raise RuntimeError(f'availability check failed: {last}')
|
||||
|
||||
|
||||
def verify_endpoints(host, port):
|
||||
"""The published port answers as the platform: web app, proxied API health and the API's route index."""
|
||||
url = f'http://127.0.0.1:{port}'
|
||||
health = host.http_get(url + '/health')
|
||||
if health['status'] != 200 or json.loads(health['body']).get('status') != 'ok':
|
||||
raise RuntimeError('API health through the published port is not ok')
|
||||
routes = host.http_get(url + '/api')
|
||||
if routes['status'] != 200 or not json.loads(routes['body']).get('routes'):
|
||||
raise RuntimeError('API route index through the published port is empty')
|
||||
home = host.http_get(url + '/')
|
||||
if home['status'] != 200 or '<html' not in home['body'].lower():
|
||||
raise RuntimeError('web app page through the published port is not served')
|
||||
return {'health': 'ok', 'api_routes': len(json.loads(routes['body'])['routes']), 'web': 'ok'}
|
||||
|
||||
|
||||
def failure_detail(exc):
|
||||
detail = str(exc)
|
||||
if isinstance(exc, subprocess.CalledProcessError):
|
||||
detail += f'\ncommand: {exc.cmd}\nstderr: {exc.stderr}'
|
||||
return detail[:4000]
|
||||
|
||||
|
||||
def activate(host, base, plan, candidate, metadata, replaced=None):
|
||||
"""Register the instance and start it; the images are already built. Any failure is recorded on the instance."""
|
||||
project, port, comp = plan['project'], plan['port'], plan['composition']
|
||||
record = {'project': project, 'port': port, 'status': 'preparing', 'installer': registry.INSTALLER,
|
||||
'reference': comp['reference'], 'reference_kind': comp['kind'], 'revision': comp['commit'],
|
||||
'gitlinks': comp['gitlinks'], 'images': candidate['images'], 'plan_digest': digest(plan),
|
||||
'operation_id': candidate['operation'], **metadata}
|
||||
if candidate['notebooks']:
|
||||
record['notebook_volume'] = composition.notebook_volume_name(project)
|
||||
if replaced:
|
||||
record['replaced'] = replaced
|
||||
host.call('reserve', project, {'port': port, 'record': record})
|
||||
|
||||
def save(**changes):
|
||||
record.update(changes)
|
||||
host.call('save', project, record)
|
||||
|
||||
try:
|
||||
probe = ("import sqlite3, os; p='/data/.permission-probe.db'; c=sqlite3.connect(p); "
|
||||
"c.execute('create table probe (x int)'); c.execute('insert into probe values (1)'); c.commit(); "
|
||||
"c.close(); os.remove(p)")
|
||||
proc.run(['docker', 'run', '--rm', '--pull', 'never', '--mount',
|
||||
f'type=bind,src={candidate["data"]},dst=/data', '--entrypoint', 'python3',
|
||||
candidate['images'][0], '-c', probe])
|
||||
persist_config(candidate['deploy'], candidate['config'])
|
||||
host.copy(candidate['deploy'], project)
|
||||
save(status='starting')
|
||||
proc.run([*candidate['cmd'], 'up', '-d', '--no-build', '--pull', 'never'])
|
||||
verify_services(candidate['cmd'], candidate['notebooks'])
|
||||
resources.verify_running(project, port, base, candidate['images'], candidate['notebooks'])
|
||||
verification = verify_endpoints(host, port)
|
||||
save(status='installed', result='reinstalled' if replaced else 'installed', verification=verification)
|
||||
except Exception as exc:
|
||||
try:
|
||||
diagnostics = proc.run([*candidate['cmd'], 'ps', '-a']) + '\n' + proc.run(
|
||||
[*candidate['cmd'], 'logs', '--no-color', '--tail', '60'])
|
||||
except Exception as diagnostic_error:
|
||||
diagnostics = str(diagnostic_error)
|
||||
save(status='failed', error=failure_detail(exc), diagnostics=diagnostics[-8000:])
|
||||
raise
|
||||
return record
|
||||
|
||||
|
||||
def remove_installation(host, base, plan, digest_value):
|
||||
"""Remove exactly the planned resources of the instance, then its directory. Docker resources go by ID or
|
||||
exact name, each after confirming it is still the one planned."""
|
||||
project, port = plan['project'], plan['port']
|
||||
record = host.call('lookup', '-', port)
|
||||
phase = 'marking'
|
||||
|
||||
def mark(new_phase, **extra):
|
||||
nonlocal phase
|
||||
phase = new_phase
|
||||
current = host.call('lookup', '-', port)
|
||||
reinstall = dict(current.get('reinstall') or {}, digest=digest_value, phase=new_phase, **extra)
|
||||
host.call('save', project, dict(current, status='removing', reinstall=reinstall))
|
||||
|
||||
try:
|
||||
mark('containers')
|
||||
for container in plan['resources']['containers']:
|
||||
proc.run(['docker', 'update', '--restart=no', container['id']])
|
||||
proc.run(['docker', 'stop', container['id']])
|
||||
proc.run(['docker', 'rm', container['id']])
|
||||
for volume in plan['resources']['volumes']:
|
||||
mark('volume')
|
||||
if resources.volume_identity(project) != volume:
|
||||
raise RuntimeError('notebook jobs volume changed since the plan')
|
||||
proc.run(['docker', 'volume', 'rm', volume['name']])
|
||||
for network in plan['resources']['networks']:
|
||||
mark('network')
|
||||
item = json.loads(proc.run(['docker', 'network', 'inspect', network['id']]))[0]
|
||||
if item.get('Name') != network['name'] or item.get('Containers'):
|
||||
raise RuntimeError('project network changed since the plan')
|
||||
proc.run(['docker', 'network', 'rm', network['id']])
|
||||
mark('directory')
|
||||
host.call('remove', project, {'identity': plan['directory'], 'digest': digest_value})
|
||||
except Exception as exc:
|
||||
try:
|
||||
current = host.call('lookup', '-', port)
|
||||
if current and current['project'] == project:
|
||||
reinstall = dict(current.get('reinstall') or {}, phase=phase, error=failure_detail(exc)[:2000])
|
||||
host.call('save', project, dict(current, status='removing', reinstall=reinstall))
|
||||
except Exception:
|
||||
pass
|
||||
raise RuntimeError(f'removal stopped during {phase} ({str(exc)[:500]}); what remains is kept and recorded; '
|
||||
'a new plan and confirmation are needed to continue') from None
|
||||
return {'operation_id': (record or {}).get('operation_id'), 'revision': (record or {}).get('revision'),
|
||||
'removed': {'containers': [c['name'] for c in plan['resources']['containers']],
|
||||
'volumes': [v['name'] for v in plan['resources']['volumes']],
|
||||
'networks': [n['name'] for n in plan['resources']['networks']]}}
|
||||
|
||||
|
||||
def validate_confirmation(operation, port, confirmation):
|
||||
word = 'instalar' if operation == 'install' else 'reinstalar'
|
||||
if confirmation and not re.fullmatch(rf'{word}-{port}-[0-9a-f]{{16}}', confirmation):
|
||||
raise ValueError(f'confirmacion must be {word}-{port}-<digest>, as printed by a run without it')
|
||||
|
||||
|
||||
def run_operation(operation, port_text, reference, confirmation='', base=BASE, metadata=None, host_factory=Host,
|
||||
remote=None):
|
||||
"""Plan, or with the matching confirmation execute, an installation or a clean reinstallation."""
|
||||
port = composition.validate_port(port_text)
|
||||
confirmation = (confirmation or '').strip()
|
||||
validate_confirmation(operation, port, confirmation)
|
||||
resolved = composition.resolve_reference(reference, remote)
|
||||
metadata = metadata or {}
|
||||
with host_factory(base, bool(confirmation)) as host, tempfile.TemporaryDirectory(prefix='isssteleon-dev-') as tmp:
|
||||
checkout_dir = Path(tmp) / 'checkout'
|
||||
comp = composition.checkout(resolved, checkout_dir, remote)
|
||||
planner = plan_install if operation == 'install' else plan_reinstall
|
||||
plan = planner(host, base, port, comp)
|
||||
candidate = prepare(checkout_dir, comp, plan['project'], port, base, Path(tmp) / 'candidate')
|
||||
expected = confirmation_for(plan)
|
||||
print('Plan:', json.dumps(plan, indent=1, sort_keys=True))
|
||||
if not confirmation:
|
||||
print('Nothing was changed. To approve exactly this plan, run again with confirmacion=' + expected)
|
||||
return None
|
||||
if confirmation != expected:
|
||||
raise RuntimeError(f'confirmacion does not match the current plan ({expected}); nothing was changed')
|
||||
build_images(candidate)
|
||||
replaced = None
|
||||
if operation == 'reinstall':
|
||||
recheck = composition.resolve_reference(reference, remote)
|
||||
if recheck['commit'] != comp['commit']:
|
||||
raise RuntimeError('the reference moved after the plan; nothing was removed')
|
||||
if confirmation_for(plan_reinstall(host, base, port, comp)) != expected:
|
||||
raise RuntimeError('the instance or its resources changed after the plan; nothing was removed')
|
||||
replaced = remove_installation(host, base, plan, digest(plan))
|
||||
host.call('check-port', '-', port)
|
||||
resources.assert_absent(plan['project'], port, base)
|
||||
record = activate(host, base, plan, candidate, metadata, replaced)
|
||||
print(f'{"Reinstalled" if replaced else "Installed"} {plan["project"]} on port {port} at {comp["commit"]}')
|
||||
return record
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
try:
|
||||
if argv[:1] == ['validate-dispatch'] and len(argv) == 1:
|
||||
print('Workflow event:', json.dumps(dispatch_metadata(), sort_keys=True))
|
||||
elif argv[:1] in (['install'], ['reinstall']) and 3 <= len(argv) <= 4:
|
||||
run_operation(argv[0], argv[1], argv[2], argv[3] if len(argv) == 4 else '',
|
||||
metadata=dispatch_metadata())
|
||||
elif argv[:1] == ['load-data'] and 3 <= len(argv) <= 4:
|
||||
import dataload
|
||||
dataload.run_load(argv[1], argv[2], argv[3] if len(argv) == 4 else '')
|
||||
else:
|
||||
raise ValueError('usage: installer.py install|reinstall <puerto> <referencia> [confirmacion] '
|
||||
'| load-data <puerto> <hospital> [confirmacion] | validate-dispatch')
|
||||
except (ValueError, RuntimeError, OSError, subprocess.SubprocessError) as exc:
|
||||
detail = exc.stderr if isinstance(exc, subprocess.CalledProcessError) and exc.stderr else str(exc)
|
||||
print(f'Deployment failed: {detail}', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Report sanitized checkout URL comparisons without contacting a remote."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
OFFICIAL = 'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git'
|
||||
SSH = 'ssh://git@10.0.10.41:2222/ISSSTELEON/WorkingNarrative.git'
|
||||
SERVER = 'http://10.0.10.41:3000'
|
||||
REPOSITORY = 'ISSSTELEON/WorkingNarrative'
|
||||
|
||||
|
||||
def describe(value):
|
||||
"""Return fixed labels and comparisons, never any part of the input."""
|
||||
try:
|
||||
parsed = urlsplit(value)
|
||||
scheme = parsed.scheme if parsed.scheme in ('http', 'https', 'ssh') else 'other'
|
||||
return {'exact_http': value == OFFICIAL,
|
||||
'exact_http_without_git': value == OFFICIAL.removesuffix('.git'), 'exact_ssh': value == SSH,
|
||||
'scheme': scheme, 'official_host': parsed.hostname == '10.0.10.41',
|
||||
'official_http_port': parsed.port == 3000,
|
||||
'official_ssh_port': parsed.port == 2222,
|
||||
'repository_path': parsed.path == '/ISSSTELEON/WorkingNarrative.git',
|
||||
'repository_path_without_git': parsed.path == '/ISSSTELEON/WorkingNarrative',
|
||||
'userinfo_present': parsed.username is not None or parsed.password is not None,
|
||||
'query_or_fragment': bool(parsed.query or parsed.fragment)}
|
||||
except ValueError:
|
||||
return {'invalid_url': True}
|
||||
|
||||
|
||||
def git_values(*args):
|
||||
result = subprocess.run(['git', *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
||||
text=True, encoding='utf-8', errors='replace', check=False)
|
||||
return result.stdout.splitlines() if result.returncode == 0 else []
|
||||
|
||||
|
||||
def main():
|
||||
literal = git_values('config', '--get-all', 'remote.origin.url')
|
||||
effective = git_values('remote', 'get-url', '--all', 'origin')
|
||||
github = os.environ.get('GITHUB_SERVER_URL', '')
|
||||
gitea = os.environ.get('GITEA_SERVER_URL', '')
|
||||
result = {'literal_origin': [describe(url) for url in literal],
|
||||
'effective_origin': [describe(url) for url in effective],
|
||||
'origin_rewritten': literal != effective,
|
||||
'github_server_is_official': github.rstrip('/') == SERVER,
|
||||
'gitea_server_is_official': gitea.rstrip('/') == SERVER,
|
||||
'server_variables_equal': bool(github and gitea) and github.rstrip('/') == gitea.rstrip('/'),
|
||||
'event_server_is_official': os.environ.get('DISPATCH_SERVER', '').rstrip('/') == SERVER,
|
||||
'event_repository_is_official': os.environ.get('DISPATCH_REPOSITORY') == REPOSITORY}
|
||||
print('Checkout origin diagnostic:', json.dumps(result, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
"""External commands used by the DEV installer; one place to replace in tests."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
|
||||
def clean_env():
|
||||
"""The process environment without Compose or installer variables that could redirect a command."""
|
||||
return {k: v for k, v in os.environ.items() if not k.startswith(('COMPOSE_', 'ISSSTELEON_'))}
|
||||
|
||||
|
||||
def run(args, cwd=None, binary=False, stdin=None):
|
||||
"""Run a command and return its stdout; a non-zero exit raises `CalledProcessError`."""
|
||||
result = subprocess.run([str(a) for a in args], cwd=cwd, check=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=not binary, env=clean_env(), input=stdin)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def git(repo, *args, binary=False):
|
||||
return run(['git', '-C', repo, *args], binary=binary)
|
||||
@@ -1,157 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check or explicitly reconcile a manually recovered installation on the daemon host."""
|
||||
|
||||
import argparse
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
import conservative
|
||||
import dev
|
||||
|
||||
DATABASES = ('cacu.db', 'cama.db', 'tea.db', 'governance.db', 'mlflow.db')
|
||||
|
||||
|
||||
def sha256_stream(stream):
|
||||
digest = hashlib.sha256()
|
||||
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def recovery_evidence(archive, restored, expected, installation):
|
||||
"""Check archive identity and five isolated SQLite copies without writing."""
|
||||
archive, restored, installation = Path(archive), Path(restored), Path(installation)
|
||||
if not re.fullmatch(r'[0-9a-fA-F]{64}', expected):
|
||||
raise ValueError('expected backup SHA-256 must contain 64 hexadecimal characters')
|
||||
if archive.is_symlink() or not archive.is_file() or restored.is_symlink() or not restored.is_dir():
|
||||
raise RuntimeError('backup archive or isolated restore is missing or linked')
|
||||
for path in (archive.resolve(), restored.resolve()):
|
||||
if path.is_relative_to(installation.resolve()) or installation.resolve().is_relative_to(path):
|
||||
raise RuntimeError('backup evidence must be outside the installation')
|
||||
with archive.open('rb') as stream:
|
||||
if sha256_stream(stream) != expected.lower():
|
||||
raise RuntimeError('backup archive SHA-256 differs')
|
||||
with tarfile.open(archive, 'r:gz') as tar:
|
||||
members = tar.getmembers()
|
||||
for name in DATABASES:
|
||||
matches = [m for m in members if m.name.rstrip('/').split('/')[-2:] == ['data', name]]
|
||||
if len(matches) != 1 or not matches[0].isfile():
|
||||
raise RuntimeError('backup archive lacks a unique regular data/' + name)
|
||||
path = restored / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise RuntimeError('isolated restore lacks ' + name)
|
||||
with tar.extractfile(matches[0]) as source, path.open('rb') as copy:
|
||||
if sha256_stream(source) != sha256_stream(copy):
|
||||
raise RuntimeError('isolated restore differs from archive: ' + name)
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-recovery-check-') as tmp:
|
||||
temporary = Path(tmp) / name
|
||||
shutil.copyfile(path, temporary)
|
||||
with tar.extractfile(matches[0]) as source, temporary.open('rb') as copy:
|
||||
if sha256_stream(source) != sha256_stream(copy):
|
||||
raise RuntimeError('SQLite copy differs from archive: ' + name)
|
||||
for suffix in ('-wal', '-shm', '-journal'):
|
||||
member = [m for m in members if m.name.rstrip('/').split('/')[-2:] == ['data', name + suffix]]
|
||||
sidecar = restored / (name + suffix)
|
||||
if len(member) > 1 or bool(member) != (sidecar.exists() or sidecar.is_symlink()):
|
||||
raise RuntimeError('isolated SQLite sidecar inventory differs: ' + name)
|
||||
if member:
|
||||
if not member[0].isfile() or sidecar.is_symlink() or not sidecar.is_file():
|
||||
raise RuntimeError('invalid SQLite sidecar: ' + name)
|
||||
with tar.extractfile(member[0]) as source, sidecar.open('rb') as copy:
|
||||
if sha256_stream(source) != sha256_stream(copy):
|
||||
raise RuntimeError('isolated SQLite sidecar differs: ' + name)
|
||||
if suffix != '-shm':
|
||||
shutil.copyfile(sidecar, Path(str(temporary) + suffix))
|
||||
with tar.extractfile(member[0]) as source, Path(str(temporary) + suffix).open('rb') as copy:
|
||||
if sha256_stream(source) != sha256_stream(copy):
|
||||
raise RuntimeError('SQLite sidecar copy differs: ' + name)
|
||||
with closing(sqlite3.connect(temporary)) as db:
|
||||
if db.execute('PRAGMA integrity_check').fetchall() != [('ok',)]:
|
||||
raise RuntimeError('isolated SQLite integrity failed: ' + name)
|
||||
|
||||
|
||||
def reconcile(args, api=dev):
|
||||
"""Hold the installer lock through every check and the optional atomic write."""
|
||||
project, port = api.validate(args.instance, str(args.port), 'instalar')
|
||||
ids = [args.indicadores, args.webapi, args.webapp]
|
||||
if len(set(ids)) != 3 or any(not re.fullmatch(r'[0-9a-f]{64}', value) for value in ids):
|
||||
raise ValueError('three distinct full original container IDs are required')
|
||||
if not args.external_copy_verified:
|
||||
raise RuntimeError('operator must attest the external backup copy was verified')
|
||||
lock = api.BASE / '.install.lock'
|
||||
if lock.is_symlink() or not lock.is_file():
|
||||
raise RuntimeError('existing shared installer lock file is missing or linked')
|
||||
helper = api.start_helper(api.BASE)
|
||||
try:
|
||||
request = {'port': port, 'revision': args.revision, 'operation_id': args.operation}
|
||||
result = json.loads(api.host_action(helper, 'reconcile-check', project, json.dumps(request)))
|
||||
record = result['record']
|
||||
expected_tag_prefix = project + '-' + args.revision[:12] + '-'
|
||||
images = record.get('images', [])
|
||||
if (len(images) != 2 or not images[0].startswith('isssteleon/webapi:' + expected_tag_prefix)
|
||||
or not images[1].startswith('isssteleon/webapp:' + expected_tag_prefix)
|
||||
or images[0].split(':', 1)[1] != images[1].split(':', 1)[1]):
|
||||
raise RuntimeError('recorded image tags do not match the original revision')
|
||||
link = api.git(api.ROOT, 'ls-tree', args.revision, 'ISSSTELEON').split()
|
||||
if len(link) < 3 or link[2] != record['gitlinks'].get('ISSSTELEON'):
|
||||
raise RuntimeError('original revision and recorded source gitlink differ')
|
||||
if api.verify_existing_containers(record, api.BASE, helper) != ids:
|
||||
raise RuntimeError('running container IDs differ from the original IDs')
|
||||
with tempfile.TemporaryDirectory(prefix='isssteleon-reconcile-') as tmp:
|
||||
deploy = Path(tmp) / 'deploy'
|
||||
conservative.read_deployment(api, helper, project, deploy)
|
||||
cmd = api.compose(project, deploy)
|
||||
config = json.loads(api.run([*cmd, 'config', '--format', 'json']))
|
||||
api.verify_config(config, project, api.BASE / project / 'data', images[0].split(':', 1)[1], port)
|
||||
conservative.current_environment(api, ids, config)
|
||||
containers = json.loads(api.run(['docker', 'inspect', *ids]))
|
||||
for item in containers:
|
||||
service = item['Config']['Labels']['com.docker.compose.service']
|
||||
expected_restart = config['services'][service].get('restart', 'no')
|
||||
actual_restart = item['HostConfig']['RestartPolicy']
|
||||
if expected_restart != actual_restart.get('Name') or actual_restart.get('MaximumRetryCount', 0):
|
||||
raise RuntimeError('restart policy differs for ' + service)
|
||||
api.verify_services(cmd, port, timeout=1)
|
||||
contract = conservative.guard(api, images[0], 'contract', {})
|
||||
conservative.guard(api, images[0], 'state', {'data': '/data', 'contract': contract},
|
||||
api.BASE / project / 'data')
|
||||
recovery_evidence(args.backup, args.restored_data, args.backup_sha256, api.BASE / project)
|
||||
if api.verify_existing_containers(record, api.BASE, helper) != ids:
|
||||
raise RuntimeError('container identities changed during validation')
|
||||
if args.mode == 'apply':
|
||||
request['record_sha256'] = result['record_sha256']
|
||||
api.host_action(helper, 'reconcile-apply', project, json.dumps(request))
|
||||
return {'result': 'reconciled' if args.mode == 'apply' else 'eligible', 'project': project,
|
||||
'note': 'External copy and functional recovery are operator attestations; '
|
||||
'SQLite integrity and archive hashes do not certify functional consistency.'}
|
||||
finally:
|
||||
api.run(['docker', 'rm', '-f', helper])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('mode', choices=('check', 'apply'))
|
||||
for name in ('instance', 'revision', 'operation', 'webapi', 'webapp', 'indicadores',
|
||||
'backup', 'backup-sha256', 'restored-data'):
|
||||
parser.add_argument('--' + name, required=True)
|
||||
parser.add_argument('--port', required=True, type=int)
|
||||
parser.add_argument('--external-copy-verified', action='store_true')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
print(json.dumps(reconcile(args)))
|
||||
except Exception as exc:
|
||||
print('Reconciliation rejected: ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Installation registry actions, run on the Docker daemon host inside the locked helper container.
|
||||
|
||||
The base directory holds one directory per installation, each with an `installation.json` record. Only the
|
||||
Python standard library is used because the helper image has nothing else. Usage:
|
||||
`registry.py <base> <action> <project> <value>` where `value` is `-` to read it from stdin.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
PROJECT = re.compile(r'isssteleon-[a-z][a-z0-9]*(?:-[a-z0-9]+)*')
|
||||
INSTALLER = 'dev-disposable'
|
||||
# `updating`, `update_failed`, `replacing` and `replace_failed` are written by the retired in-place updater; they
|
||||
# are read, never replaced.
|
||||
STATUSES = ('preparing', 'building', 'starting', 'installed', 'failed', 'removing',
|
||||
'updating', 'update_failed', 'replacing', 'replace_failed')
|
||||
REPLACEABLE = ('preparing', 'building', 'starting', 'installed', 'failed', 'removing')
|
||||
SHA = re.compile(r'[0-9a-f]{40}')
|
||||
|
||||
|
||||
def write_record(directory, record):
|
||||
"""Replace the record atomically."""
|
||||
fd, name = tempfile.mkstemp(prefix='.installation-', dir=directory)
|
||||
try:
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, indent=2, sort_keys=True)
|
||||
stream.write('\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(name, Path(directory) / 'installation.json')
|
||||
finally:
|
||||
if os.path.exists(name):
|
||||
os.unlink(name)
|
||||
|
||||
|
||||
def read_record(directory):
|
||||
directory = Path(directory)
|
||||
path = directory / 'installation.json'
|
||||
if path.is_symlink():
|
||||
raise RuntimeError(f'symlinked installation record: {directory.name}')
|
||||
record = json.loads(path.read_text(encoding='utf-8'))
|
||||
if (not isinstance(record, dict) or record.get('project') != directory.name
|
||||
or type(record.get('port')) is not int or not 1024 <= record['port'] <= 65535
|
||||
or record.get('status') not in STATUSES):
|
||||
raise RuntimeError(f'invalid installation record: {directory.name}')
|
||||
return record
|
||||
|
||||
|
||||
def scan(base):
|
||||
"""Every registered installation as `{port: (directory, record)}`; invalid or duplicate entries fail."""
|
||||
found = {}
|
||||
for entry in sorted(Path(base).iterdir()):
|
||||
if entry.name.startswith('.'):
|
||||
continue
|
||||
if entry.name.startswith('isssteleon-') or (entry.is_dir() and (entry / 'installation.json').exists()):
|
||||
if entry.is_symlink() or not entry.is_dir():
|
||||
raise RuntimeError(f'invalid instance directory: {entry.name}')
|
||||
if not PROJECT.fullmatch(entry.name) or len(entry.name) > 51:
|
||||
raise RuntimeError(f'invalid project name: {entry.name}')
|
||||
record = read_record(entry)
|
||||
if record['port'] in found:
|
||||
raise RuntimeError(f'duplicate recorded port {record["port"]}: {found[record["port"]][0].name} '
|
||||
f'and {entry.name}')
|
||||
found[record['port']] = (entry, record)
|
||||
return found
|
||||
|
||||
|
||||
def owned(record, port):
|
||||
"""How the record proves the installation is a DEV one: its own marker, or the shape earlier DEV runs wrote.
|
||||
|
||||
A record naming another project, another installer or no commit is not owned."""
|
||||
if record.get('project') != f'isssteleon-dev-{port}':
|
||||
return None
|
||||
marker = record.get('installer')
|
||||
if marker == INSTALLER:
|
||||
return 'marker'
|
||||
if marker is None and isinstance(record.get('revision'), str) and SHA.fullmatch(record['revision']):
|
||||
return 'legacy'
|
||||
return None
|
||||
|
||||
|
||||
def lookup(base, port):
|
||||
"""The record registered on `port`, or None."""
|
||||
found = scan(base).get(port)
|
||||
return found[1] if found else None
|
||||
|
||||
|
||||
def tree_entries(root):
|
||||
"""Every path below `root` without following links, so a link is a leaf."""
|
||||
for current, folders, files in os.walk(root, followlinks=False):
|
||||
for name in folders + files:
|
||||
yield Path(current) / name
|
||||
|
||||
|
||||
def identity(base, project, port):
|
||||
"""Check that the directory of `project` is a replaceable DEV installation and describe it for a plan."""
|
||||
base = Path(base)
|
||||
directory = base / project
|
||||
if not PROJECT.fullmatch(project):
|
||||
raise RuntimeError('invalid project name')
|
||||
if directory.is_symlink() or not directory.is_dir():
|
||||
raise RuntimeError('installation directory is missing or linked')
|
||||
found = scan(base).get(port)
|
||||
if found is None or found[0].name != project:
|
||||
raise RuntimeError(f'no installation of {project} is registered on port {port}')
|
||||
record = found[1]
|
||||
how = owned(record, port)
|
||||
if how is None:
|
||||
raise RuntimeError('the installation record does not prove a DEV installation of this installer')
|
||||
if record['status'] not in REPLACEABLE:
|
||||
raise RuntimeError(f'installation status {record["status"]} is not replaceable; inspect it manually')
|
||||
device = base.stat().st_dev
|
||||
if directory.stat().st_dev != device:
|
||||
raise RuntimeError('installation directory is on another filesystem')
|
||||
for path in tree_entries(directory):
|
||||
if os.lstat(path).st_dev != device:
|
||||
raise RuntimeError('installation directory crosses a filesystem boundary')
|
||||
info = directory.stat()
|
||||
return {'project': project, 'port': port, 'status': record['status'], 'ownership': how,
|
||||
'record_sha256': hashlib.sha256((directory / 'installation.json').read_bytes()).hexdigest(),
|
||||
'directory': [info.st_dev, info.st_ino], 'entries': sorted(p.name for p in directory.iterdir())}
|
||||
|
||||
|
||||
def reserve(base, project, port, record):
|
||||
"""Create the directory of a new installation and its first record; refuse any existing owner of either."""
|
||||
base = Path(base)
|
||||
if not PROJECT.fullmatch(project) or project != f'isssteleon-dev-{port}':
|
||||
raise RuntimeError('invalid project for this port')
|
||||
directory = base / project
|
||||
if directory.exists() or directory.is_symlink():
|
||||
raise RuntimeError(f'instance directory already exists: {project}')
|
||||
if port in scan(base):
|
||||
raise RuntimeError(f'port {port} is registered by another installation')
|
||||
if record.get('project') != project or record.get('port') != port or record.get('installer') != INSTALLER:
|
||||
raise RuntimeError('record does not describe this installation')
|
||||
directory.mkdir(mode=0o700)
|
||||
write_record(directory, record)
|
||||
(directory / 'data').mkdir(mode=0o700)
|
||||
|
||||
|
||||
def save(base, project, record):
|
||||
directory = Path(base) / project
|
||||
if directory.is_symlink() or not directory.is_dir():
|
||||
raise RuntimeError('installation directory is missing or linked')
|
||||
previous = read_record(directory)
|
||||
if record.get('project') != project or record.get('port') != previous['port']:
|
||||
raise RuntimeError('installation identity changed')
|
||||
write_record(directory, record)
|
||||
|
||||
|
||||
def remove(base, project, expected, digest):
|
||||
"""Delete the installation directory once it is still the one the plan named.
|
||||
|
||||
The directory must be marked `removing` by the operation whose plan has this digest. The record goes last,
|
||||
so a failure leaves a `removing` record that a new plan can resume."""
|
||||
base = Path(base)
|
||||
current = identity(base, project, expected['port'])
|
||||
if any(current[key] != expected[key] for key in ('project', 'port', 'ownership', 'directory')):
|
||||
raise RuntimeError('installation directory changed since the plan')
|
||||
directory = base / project
|
||||
record = read_record(directory)
|
||||
if record['status'] != 'removing' or (record.get('reinstall') or {}).get('digest') != digest:
|
||||
raise RuntimeError('installation is not marked as being removed by this plan')
|
||||
device = base.stat().st_dev
|
||||
paths = sorted(tree_entries(directory), key=lambda p: len(p.parts), reverse=True)
|
||||
keep = directory / 'installation.json'
|
||||
for path in paths:
|
||||
if path == keep:
|
||||
continue
|
||||
if os.lstat(path).st_dev != device:
|
||||
raise RuntimeError('installation directory crosses a filesystem boundary')
|
||||
if os.path.islink(path) or not path.is_dir():
|
||||
os.unlink(path)
|
||||
else:
|
||||
os.rmdir(path)
|
||||
os.unlink(keep)
|
||||
os.rmdir(directory)
|
||||
|
||||
|
||||
def check_port(port):
|
||||
"""Fail if something on the host already listens on `port`, on IPv4 or IPv6."""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(('0.0.0.0', port))
|
||||
try:
|
||||
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
|
||||
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
|
||||
sock.bind(('::', port))
|
||||
except OSError as exc:
|
||||
if exc.errno not in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
|
||||
raise
|
||||
|
||||
|
||||
def dispatch(base, action, project, value):
|
||||
"""Run one action; the result is JSON-serialisable."""
|
||||
if action not in ('lookup', 'check-port') and not PROJECT.fullmatch(project):
|
||||
raise ValueError('invalid project')
|
||||
if action == 'lookup':
|
||||
return lookup(base, int(value))
|
||||
if action == 'check-port':
|
||||
check_port(int(value))
|
||||
return None
|
||||
payload = json.loads(value)
|
||||
if action == 'identity':
|
||||
return identity(base, project, int(payload['port']))
|
||||
if action == 'reserve':
|
||||
reserve(base, project, int(payload['port']), payload['record'])
|
||||
return None
|
||||
if action == 'save':
|
||||
save(base, project, payload)
|
||||
return None
|
||||
if action == 'remove':
|
||||
remove(base, project, payload['identity'], payload['digest'])
|
||||
return None
|
||||
raise ValueError(f'unknown action: {action}')
|
||||
|
||||
|
||||
def main():
|
||||
base, action, project, value = sys.argv[1:]
|
||||
if value == '-':
|
||||
value = sys.stdin.read()
|
||||
print(json.dumps(dispatch(Path(base), action, project, value)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,409 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reset only the approved 18080 laboratory incident on the local daemon host."""
|
||||
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import uuid
|
||||
from urllib.request import ProxyHandler, build_opener
|
||||
|
||||
import conservative
|
||||
import data_guard
|
||||
import dev
|
||||
import host
|
||||
|
||||
PROJECT = 'isssteleon-dev-prueba-02'
|
||||
ORIGINAL = '55e90fd49c6982793afb0633e974b33e44e58d94'
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
if os.name == 'posix':
|
||||
descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(descriptor)
|
||||
finally:
|
||||
os.close(descriptor)
|
||||
|
||||
|
||||
def marker(path):
|
||||
with path.open('xb') as stream:
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
sync_directory(path.parent)
|
||||
|
||||
|
||||
def fingerprint(path, link_roots=()):
|
||||
"""Fingerprint entries without following links, restricted to authorized trees."""
|
||||
path = Path(path)
|
||||
if path.is_symlink() or not path.is_dir():
|
||||
raise RuntimeError('missing or linked tree root')
|
||||
result = {}
|
||||
for entry in [path, *sorted(path.rglob('*'))]:
|
||||
info = entry.lstat()
|
||||
destination = None
|
||||
if stat.S_ISLNK(info.st_mode):
|
||||
root = next((root for root in link_roots if entry.is_relative_to(root)), None)
|
||||
destination = os.readlink(entry)
|
||||
if root is None or os.path.isabs(destination):
|
||||
raise RuntimeError('unsupported tree link')
|
||||
lexical = Path(os.path.abspath(entry.parent / destination))
|
||||
try:
|
||||
resolved = entry.resolve(strict=True)
|
||||
except (OSError, RuntimeError) as exc:
|
||||
raise RuntimeError('invalid tree link') from exc
|
||||
if (not lexical.is_relative_to(root) or not resolved.is_relative_to(root)
|
||||
or not (resolved.is_file() or resolved.is_dir())):
|
||||
raise RuntimeError('tree link escapes or targets a special entry')
|
||||
elif not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)):
|
||||
raise RuntimeError('special tree entry is unsupported')
|
||||
attributes = ({name: os.getxattr(entry, name, follow_symlinks=False).hex()
|
||||
for name in os.listxattr(entry, follow_symlinks=False)}
|
||||
if hasattr(os, 'listxattr') else {})
|
||||
result[str(entry.relative_to(path))] = [info.st_mode & 0o7777, info.st_uid, info.st_gid,
|
||||
attributes, destination if stat.S_ISLNK(info.st_mode) else
|
||||
data_guard.digest(entry) if stat.S_ISREG(info.st_mode) else None]
|
||||
return result
|
||||
|
||||
|
||||
def tree(path):
|
||||
data_guard.regular_tree(path)
|
||||
return fingerprint(path)
|
||||
|
||||
|
||||
def code_tree(path):
|
||||
path = Path(path).absolute()
|
||||
return fingerprint(path, (path,))
|
||||
|
||||
|
||||
def recovery_tree(path):
|
||||
path = Path(path).absolute()
|
||||
roots = tuple(path / stage / name for stage in ('ready', 'failed') for name in ('codigo', 'deploy'))
|
||||
return fingerprint(path, roots)
|
||||
|
||||
|
||||
def copy_preserved(source, target):
|
||||
inspect = code_tree if Path(source).name in ('codigo', 'deploy') else tree
|
||||
inspect(source)
|
||||
dev.run(['cp', '-a', '--', source, target])
|
||||
if inspect(source) != inspect(target):
|
||||
raise RuntimeError('copy content or permissions differ')
|
||||
for path in target.rglob('*'):
|
||||
if stat.S_ISREG(path.lstat().st_mode):
|
||||
with path.open('rb') as stream:
|
||||
os.fsync(stream.fileno())
|
||||
for path in [*target.rglob('*'), target]:
|
||||
if stat.S_ISDIR(path.lstat().st_mode):
|
||||
sync_directory(path)
|
||||
|
||||
|
||||
def no_host_users(path):
|
||||
if not path.exists():
|
||||
return
|
||||
result = subprocess.run(['lsof', '-t', '+D', str(path)], capture_output=True, text=True)
|
||||
if result.stdout.strip() or result.stderr.strip() or result.returncode not in (0, 1):
|
||||
raise RuntimeError('host processes or incomplete lsof visibility prevent writer exclusion')
|
||||
|
||||
|
||||
def check_http():
|
||||
opener = build_opener(ProxyHandler({}))
|
||||
for path in ('/', '/health'):
|
||||
with opener.open('http://127.0.0.1:18080' + path, timeout=10) as response:
|
||||
if response.status != 200:
|
||||
raise RuntimeError('laboratory HTTP availability failed')
|
||||
|
||||
|
||||
def swap(root, work, name):
|
||||
"""Resume either rename without overwriting preserved or staged directories."""
|
||||
ready, active, failed = work / 'ready' / name, root / name, work / 'failed' / name
|
||||
if any(path.is_symlink() for path in (ready, active, failed)):
|
||||
raise RuntimeError('linked swap path')
|
||||
if ready.is_dir() and active.is_dir() and not failed.exists():
|
||||
os.rename(active, failed)
|
||||
sync_directory(root)
|
||||
sync_directory(failed.parent)
|
||||
if ready.is_dir() and not active.exists() and failed.is_dir():
|
||||
os.rename(ready, active)
|
||||
sync_directory(ready.parent)
|
||||
sync_directory(root)
|
||||
if ready.exists() or not active.is_dir() or not failed.is_dir():
|
||||
raise RuntimeError('ambiguous interrupted swap: ' + name)
|
||||
|
||||
|
||||
class LabReset:
|
||||
def __init__(self, base=dev.BASE, api=dev, copier=copy_preserved, *, operation):
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', operation):
|
||||
raise RuntimeError('invalid incident operation ID')
|
||||
self.operation = operation
|
||||
self.base, self.api, self.copy = base, api, copier
|
||||
self.root = base / PROJECT
|
||||
self.archive = self.root / '.archive' / operation
|
||||
self.backup = base / '.backups' / PROJECT / operation
|
||||
self.work = base / ('.reset-18080-' + operation)
|
||||
|
||||
def identity(self):
|
||||
for path in (self.base, self.root, self.archive, self.backup):
|
||||
if path.resolve() != path.absolute() or not path.is_dir():
|
||||
raise RuntimeError('missing or linked incident directory')
|
||||
failed = host.read_record(self.root)
|
||||
if self.work.exists():
|
||||
if self.work.is_symlink():
|
||||
raise RuntimeError('linked recovery directory')
|
||||
failed = json.loads((self.work / 'failed-record.json').read_text())
|
||||
recovery_tree(self.work)
|
||||
if (failed.get('project') != PROJECT or failed.get('port') != 18080
|
||||
or failed.get('operation_id') != self.operation or failed.get('revision') != ORIGINAL
|
||||
or failed.get('status') != 'update_failed'
|
||||
or failed.get('phase') != 'recalculation-and-persistence'):
|
||||
raise RuntimeError('incident identity differs')
|
||||
candidate = failed.get('target_revision')
|
||||
images = failed.get('target_images')
|
||||
gitlinks = failed.get('target_gitlinks')
|
||||
if not isinstance(candidate, str) or not re.fullmatch(r'[0-9a-f]{40}', candidate):
|
||||
raise RuntimeError('invalid incident candidate revision')
|
||||
pattern = re.escape(PROJECT + '-' + candidate[:12] + '-') + r'[0-9a-f]{32}'
|
||||
if (not isinstance(images, list) or len(images) != 2
|
||||
or not all(isinstance(image, str) for image in images)
|
||||
or not images[0].startswith('isssteleon/webapi:')
|
||||
or not re.fullmatch(pattern, images[0].removeprefix('isssteleon/webapi:'))
|
||||
or images[1] != images[0].replace('isssteleon/webapi:', 'isssteleon/webapp:', 1)
|
||||
or not isinstance(gitlinks, dict) or 'ISSSTELEON' not in gitlinks
|
||||
or not all(isinstance(k, str) and isinstance(v, str) and re.fullmatch(r'[0-9a-f]{40}', v)
|
||||
for k, v in gitlinks.items())
|
||||
or failed.get('backup') != str(self.backup)
|
||||
or failed.get('archive') != str(self.archive)):
|
||||
raise RuntimeError('incident candidate evidence differs')
|
||||
if (self.archive / 'installation.json').is_symlink():
|
||||
raise RuntimeError('linked archived record')
|
||||
original = json.loads((self.archive / 'installation.json').read_text())
|
||||
if (original.get('project') != PROJECT or original.get('port') != 18080
|
||||
or original.get('status') != 'installed' or original.get('revision') != ORIGINAL
|
||||
or original.get('gitlinks') != failed.get('gitlinks')
|
||||
or original.get('images') != failed.get('images')):
|
||||
raise RuntimeError('original provenance differs')
|
||||
self.failed, self.original = failed, original
|
||||
tree(self.backup)
|
||||
manifest = data_guard.verify_backup(self.backup)
|
||||
if manifest['origin'] != {key: original[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images')}:
|
||||
raise RuntimeError('backup provenance differs')
|
||||
# Installer backups normalize committed WAL into standalone SQLite files.
|
||||
for name in manifest['sqlite_files']:
|
||||
if any((self.backup / 'data' / (name + suffix)).exists() for suffix in ('-wal', '-shm', '-journal')):
|
||||
raise RuntimeError('backup is not the normalized pre-activation snapshot')
|
||||
code_tree(self.archive / 'codigo')
|
||||
code_tree(self.archive / 'deploy')
|
||||
self.image_ids = {}
|
||||
for image in original['images']:
|
||||
self.image_ids[image] = self.api.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
|
||||
if not self.image_ids[image]:
|
||||
raise RuntimeError('original image missing')
|
||||
return failed, original, manifest
|
||||
|
||||
def stopped(self):
|
||||
no_host_users(self.root / 'data')
|
||||
if self.work.exists():
|
||||
no_host_users(self.work)
|
||||
ids = self.api.run(['docker', 'ps', '-aq', '--no-trunc']).split()
|
||||
items = json.loads(self.api.run(['docker', 'inspect', *ids])) if ids else []
|
||||
own = []
|
||||
for item in items:
|
||||
labels = item.get('Config', {}).get('Labels') or {}
|
||||
ours = labels.get('com.docker.compose.project') == PROJECT
|
||||
for mount in item.get('Mounts', []):
|
||||
source = Path(mount.get('Source', '/'))
|
||||
if source == self.root or source.is_relative_to(self.root) or self.root.is_relative_to(source):
|
||||
if not ours:
|
||||
raise RuntimeError('foreign container can access laboratory')
|
||||
bindings = item.get('HostConfig', {}).get('PortBindings') or {}
|
||||
if not ours and any(str(binding.get('HostPort')) == '18080'
|
||||
for values in bindings.values() for binding in (values or [])):
|
||||
raise RuntimeError('foreign port owner')
|
||||
if ours:
|
||||
service = labels.get('com.docker.compose.service')
|
||||
if service not in ('webapi', 'webapp', 'indicadores') or service in own:
|
||||
raise RuntimeError('unexpected laboratory service')
|
||||
own.append(service)
|
||||
allowed = set(self.original['images'] + self.failed.get('target_images', []))
|
||||
if item.get('Config', {}).get('Image') not in allowed:
|
||||
raise RuntimeError('unexpected laboratory image identity')
|
||||
mounts = item.get('Mounts', [])
|
||||
if service == 'webapp':
|
||||
if mounts:
|
||||
raise RuntimeError('unexpected frontend mount')
|
||||
elif (len(mounts) != 1 or mounts[0].get('Type') != 'bind'
|
||||
or mounts[0].get('Source') != str(self.root / 'data')
|
||||
or mounts[0].get('Destination') != '/data' or mounts[0].get('RW') is not True):
|
||||
raise RuntimeError('unexpected writer storage mount')
|
||||
if item.get('State', {}).get('Running') is not False:
|
||||
raise RuntimeError('laboratory writers must be stopped before check/apply')
|
||||
if not self.work.exists() and set(own) != {'webapi', 'webapp', 'indicadores'}:
|
||||
raise RuntimeError('initial laboratory containers are incomplete')
|
||||
return items
|
||||
|
||||
def configuration(self, deploy, original):
|
||||
cmd = self.api.compose(PROJECT, deploy)
|
||||
config = json.loads(self.api.run([*cmd, 'config', '--format', 'json']))
|
||||
tag = original['images'][0].removeprefix('isssteleon/webapi:')
|
||||
self.api.verify_config(config, PROJECT, self.root / 'data', tag, 18080)
|
||||
if any(set(service) & {'post_start', 'pre_stop', 'develop', 'secrets', 'configs',
|
||||
'volumes_from', 'external_links', 'use_api_socket'}
|
||||
for service in config['services'].values()):
|
||||
raise RuntimeError('unsupported Compose lifecycle hooks')
|
||||
if any(network.get('external') for network in config.get('networks', {}).values()):
|
||||
raise RuntimeError('external recovery networks are not allowed')
|
||||
return conservative.controlled_config(config)
|
||||
|
||||
def validate_storage(self, original, manifest):
|
||||
contract = conservative.guard(self.api, original['images'][0], 'contract', {})
|
||||
if contract != manifest['contract']:
|
||||
raise RuntimeError('original image contract differs from backup')
|
||||
|
||||
def run(self, mode):
|
||||
failed, original, manifest = self.identity()
|
||||
if self.work.exists() and (self.work / 'complete').exists():
|
||||
active = host.read_record(self.root)
|
||||
if active.get('status') != 'installed' or active.get('revision') != ORIGINAL:
|
||||
raise RuntimeError('completed reset no longer matches active record')
|
||||
self.api.verify_existing_containers(original, self.base, '')
|
||||
self.api.verify_services(self.api.compose(PROJECT, self.root / 'deploy'), 18080)
|
||||
check_http()
|
||||
return 'already recovered'
|
||||
if self.work.exists() and not (self.work / 'prepared').exists():
|
||||
raise RuntimeError('preparation interrupted before swaps; retain this work directory under another name and retry')
|
||||
inspection = self.stopped()
|
||||
self.validate_storage(original, manifest)
|
||||
with tempfile.TemporaryDirectory(prefix='lab-18080-check-') as tmp:
|
||||
data_guard.restore_backup(self.backup, Path(tmp) / 'data')
|
||||
config = self.configuration(self.archive / 'deploy', original)
|
||||
if mode == 'check':
|
||||
return 'eligible; backup restored in isolation, images/configuration verified, no writers'
|
||||
if not self.work.exists():
|
||||
# Refuse cross-filesystem swaps before preserving any active directory.
|
||||
if any((self.root / name).stat().st_dev != self.base.stat().st_dev for name in ('codigo', 'deploy', 'data')):
|
||||
raise RuntimeError('active paths must share the recovery filesystem')
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(tree if name == 'data' else code_tree)(self.root / name)
|
||||
self.work.mkdir(mode=0o700)
|
||||
for name, value in (('failed-record.json', failed), ('containers.json', inspection)):
|
||||
with (self.work / name).open('x', encoding='utf-8') as stream:
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
sync_directory(self.work)
|
||||
(self.work / 'ready').mkdir()
|
||||
(self.work / 'failed').mkdir()
|
||||
try:
|
||||
if not (self.work / 'prepared').exists():
|
||||
if any((self.work / 'ready').iterdir()) or any((self.work / 'failed').iterdir()):
|
||||
raise RuntimeError('incomplete preparation retained; inspect recovery directory before retry')
|
||||
for name in ('codigo', 'deploy'):
|
||||
self.copy(self.archive / name, self.work / 'ready' / name)
|
||||
self.copy(self.backup / 'data', self.work / 'ready' / 'data')
|
||||
data_guard.verify_backup(self.backup)
|
||||
conservative.persist_config(self.work / 'ready' / 'deploy', config)
|
||||
shutil.copystat(self.archive / 'deploy' / 'docker-compose.yml',
|
||||
self.work / 'ready' / 'deploy' / 'docker-compose.yml')
|
||||
if os.name == 'posix':
|
||||
with (self.work / 'ready' / 'deploy' / 'docker-compose.yml').open('rb') as stream:
|
||||
os.fsync(stream.fileno())
|
||||
marker(self.work / 'prepared')
|
||||
self.stopped()
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
if (name == 'data' and (self.work / 'failed' / name).exists()
|
||||
and (self.work / 'ready' / name).exists() and (self.root / name).exists()):
|
||||
if tree(self.work / 'ready' / name) != tree(self.backup / 'data'):
|
||||
raise RuntimeError('interrupted data preparation differs from backup')
|
||||
os.rename(self.root / name, self.work / ('attempt-data-' + uuid.uuid4().hex))
|
||||
sync_directory(self.work)
|
||||
swap(self.root, self.work, name)
|
||||
if tree(self.root / 'data') != tree(self.backup / 'data'):
|
||||
self.copy(self.backup / 'data', self.work / 'ready' / 'data')
|
||||
os.rename(self.root / 'data', self.work / ('attempt-data-' + uuid.uuid4().hex))
|
||||
sync_directory(self.work)
|
||||
swap(self.root, self.work, 'data')
|
||||
# Verify the restored inventory before any application can write.
|
||||
if tree(self.root / 'data') != tree(self.backup / 'data'):
|
||||
raise RuntimeError('restored storage differs; preserve recovery directory for manual review')
|
||||
cmd = self.api.compose(PROJECT, self.root / 'deploy')
|
||||
effective = self.configuration(self.root / 'deploy', original)
|
||||
baseline = data_guard.storage_state(self.root / 'data', manifest['contract'])
|
||||
self.api.run([*cmd, 'up', '-d', '--force-recreate', '--no-build', '--pull', 'never'])
|
||||
self.api.verify_services(cmd, 18080)
|
||||
check_http()
|
||||
verified_ids = self.api.verify_existing_containers(original, self.base, '')
|
||||
conservative.current_environment(self.api, verified_ids, effective)
|
||||
before = data_guard.storage_state(self.root / 'data', manifest['contract'])
|
||||
for domain in data_guard.DOMAINS:
|
||||
if before['databases'][domain]['tables'] != manifest['state']['databases'][domain]['tables']:
|
||||
raise RuntimeError('restored database contents changed during startup')
|
||||
# Permit only the updater's existing marker/audit-file policy. All table
|
||||
# contents, including derived tables, were compared exactly above.
|
||||
data_guard.verify_state(self.root / 'data', manifest['contract'], baseline, derived=True)
|
||||
ids = self.api.run(['docker', 'ps', '-q', '--filter', 'label=com.docker.compose.project=' + PROJECT]).split()
|
||||
items = json.loads(self.api.run(['docker', 'inspect', *ids]))
|
||||
if len(items) != 3 or any(item['Image'] != self.image_ids[original['images'][
|
||||
1 if item['Config']['Labels']['com.docker.compose.service'] == 'webapp' else 0]] for item in items):
|
||||
raise RuntimeError('original image IDs changed')
|
||||
for item in items:
|
||||
name = item['Config']['Labels']['com.docker.compose.service']
|
||||
expected_policy = effective['services'][name].get('restart', 'no').split(':')
|
||||
policy = item.get('HostConfig', {}).get('RestartPolicy', {})
|
||||
retries = int(expected_policy[1]) if len(expected_policy) == 2 else 0
|
||||
if policy.get('Name') != expected_policy[0] or policy.get('MaximumRetryCount', 0) != retries:
|
||||
raise RuntimeError('service restart policy differs from verified configuration')
|
||||
if name in ('webapi', 'indicadores') and (
|
||||
item['Config'].get('Entrypoint') != effective['services'][name]['entrypoint']
|
||||
or item['Config'].get('Cmd') not in (None, [])):
|
||||
raise RuntimeError('service startup command differs from verified configuration')
|
||||
host.write_record(self.root, dict(original, recovery_incident=str(self.work)))
|
||||
marker(self.work / 'complete')
|
||||
return 'recovered and verified; status=installed'
|
||||
except BaseException:
|
||||
try:
|
||||
cmd = self.api.compose(PROJECT, self.root / 'deploy')
|
||||
conservative.freeze_failed(self.api, cmd, PROJECT, self.root / 'data')
|
||||
finally:
|
||||
host.write_record(self.root, dict(failed, recovery='lab reset incomplete; inspect ' + str(self.work)))
|
||||
raise
|
||||
|
||||
|
||||
@contextmanager
|
||||
def installer_lock(base):
|
||||
import fcntl
|
||||
path = base / '.install.lock'
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise RuntimeError('existing installer lock required')
|
||||
with path.open('r') as stream:
|
||||
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
yield
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('mode', choices=('check', 'apply'))
|
||||
parser.add_argument('--operation', required=True, help='operation ID from the failed installation record')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if os.name != 'posix' or os.geteuid() != 0 or socket.gethostname().split('.')[0] != 'labserver':
|
||||
raise RuntimeError('run as root on labserver with the local Docker daemon')
|
||||
info = json.loads(dev.run(['docker', 'info', '--format', '{{json .}}']))
|
||||
if info.get('Name', '').split('.')[0] != 'labserver' or info.get('OSType') != 'linux':
|
||||
raise RuntimeError('Docker daemon must be local labserver/Linux')
|
||||
with installer_lock(dev.BASE):
|
||||
print(LabReset(operation=args.operation).run(args.mode))
|
||||
except Exception as exc:
|
||||
print('Laboratory reset failed; category=' + type(exc).__name__ + '; ' + str(exc), file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Docker resources of one installation, and the checks that decide whether they are its own.
|
||||
|
||||
Nothing here changes Docker; every function only lists and inspects. An installation owns the containers,
|
||||
the notebook jobs volume and the default network of its Compose project, matched by label, exact name and use.
|
||||
Anything that touches its storage, volume, network or port without being one of those refuses the plan.
|
||||
"""
|
||||
|
||||
import json
|
||||
import posixpath
|
||||
import re
|
||||
|
||||
import composition
|
||||
import proc
|
||||
|
||||
PROJECT_LABEL = 'com.docker.compose.project'
|
||||
HELPER_LABEL = 'isssteleon.dev-installer'
|
||||
HELPER_PREFIX = 'isssteleon-prepare-'
|
||||
SERVICES = composition.BASE_SERVICES + (composition.NOTEBOOK_SERVICE,) + composition.PROFILE_SERVICES
|
||||
PLAN_KEYS = ('id', 'name', 'service', 'image', 'mounts')
|
||||
|
||||
|
||||
def daemon_path(path):
|
||||
"""A daemon-host path as text with `/` separators, so paths compare the same wherever this runs."""
|
||||
return posixpath.normpath(str(path).replace('\\', '/'))
|
||||
|
||||
|
||||
def overlaps(source, root):
|
||||
source = daemon_path(source)
|
||||
return source == root or source.startswith(root + '/') or root.startswith(source.rstrip('/') + '/')
|
||||
|
||||
|
||||
def inspect_all():
|
||||
ids = proc.run(['docker', 'ps', '-aq', '--no-trunc']).split()
|
||||
return json.loads(proc.run(['docker', 'inspect', *ids])) if ids else []
|
||||
|
||||
|
||||
def is_helper(item, base):
|
||||
"""A locked helper container of this installer: its name, label and single mount of the base directory."""
|
||||
labels = item.get('Config', {}).get('Labels') or {}
|
||||
mounts = item.get('Mounts') or []
|
||||
return (item.get('Name', '').startswith('/' + HELPER_PREFIX) and labels.get(HELPER_LABEL) == 'helper'
|
||||
and len(mounts) == 1 and mounts[0].get('Type') == 'bind'
|
||||
and daemon_path(mounts[0].get('Source', '')) == daemon_path(base)
|
||||
and mounts[0].get('Destination') == '/host')
|
||||
|
||||
|
||||
def mount_shape(mount):
|
||||
key = 'Name' if mount.get('Type') == 'volume' else 'Source'
|
||||
return {'type': mount.get('Type'), key.lower(): mount.get(key), 'target': mount.get('Destination')}
|
||||
|
||||
|
||||
def published_ports(item):
|
||||
bindings = (item.get('HostConfig') or {}).get('PortBindings') or {}
|
||||
return sorted({str(b.get('HostPort')) for values in bindings.values() for b in (values or [])})
|
||||
|
||||
|
||||
def volume_identity(project, *, missing_ok=False):
|
||||
"""The Compose-created local volume holding this installation's notebook jobs, or None if absent."""
|
||||
name = composition.notebook_volume_name(project)
|
||||
if name not in proc.run(['docker', 'volume', 'ls', '-q', '--filter', 'name=' + name]).split():
|
||||
if missing_ok:
|
||||
return None
|
||||
raise RuntimeError('notebook jobs volume is missing')
|
||||
items = json.loads(proc.run(['docker', 'volume', 'inspect', name]))
|
||||
if len(items) != 1:
|
||||
raise RuntimeError('notebook jobs volume identity is not verifiable')
|
||||
volume = items[0]
|
||||
labels = volume.get('Labels') or {}
|
||||
mountpoint = volume.get('Mountpoint')
|
||||
if (volume.get('Name') != name or volume.get('Driver') != 'local' or volume.get('Scope') != 'local'
|
||||
or volume.get('Options') or labels.get(PROJECT_LABEL) != project
|
||||
or labels.get('com.docker.compose.volume') != composition.NOTEBOOK_VOLUME
|
||||
or not isinstance(mountpoint, str) or not mountpoint.startswith('/')
|
||||
or not isinstance(volume.get('CreatedAt'), str) or not volume['CreatedAt']):
|
||||
raise RuntimeError('notebook jobs volume identity is not verifiable')
|
||||
return {'name': name, 'created': volume['CreatedAt'], 'mountpoint': posixpath.normpath(mountpoint)}
|
||||
|
||||
|
||||
def classify(items, project, base):
|
||||
"""Split containers into the project's and everyone else's; a lookalike without the label refuses."""
|
||||
own, foreign = [], []
|
||||
for item in items:
|
||||
if is_helper(item, base):
|
||||
continue
|
||||
labels = item.get('Config', {}).get('Labels') or {}
|
||||
name = item.get('Name', '')
|
||||
if labels.get(PROJECT_LABEL) == project:
|
||||
own.append(item)
|
||||
elif name.startswith('/' + project + '-'):
|
||||
raise RuntimeError(f'container {name.lstrip("/")} looks like the project without its label')
|
||||
else:
|
||||
foreign.append(item)
|
||||
return own, foreign
|
||||
|
||||
|
||||
def check_foreign(foreign, project, port, base):
|
||||
"""Refuse any other container that reaches the installation's storage, volume or network, or holds its port."""
|
||||
root = daemon_path(base) + '/' + project
|
||||
volume, network = composition.notebook_volume_name(project), project + '_default'
|
||||
for item in foreign:
|
||||
label = item.get('Name', '').lstrip('/')
|
||||
for mount in item.get('Mounts') or []:
|
||||
if mount.get('Name') == volume or overlaps(mount.get('Source') or '/', root):
|
||||
raise RuntimeError(f'container {label} shares the installation storage')
|
||||
if network in ((item.get('NetworkSettings') or {}).get('Networks') or {}):
|
||||
raise RuntimeError(f'container {label} shares the installation network')
|
||||
if str(port) in published_ports(item):
|
||||
raise RuntimeError(f'container {label} holds port {port}')
|
||||
|
||||
|
||||
def own_containers(own, project, base, image_ids):
|
||||
"""Summaries of the project's containers; each must be a known service, use only its own mounts and image."""
|
||||
root = daemon_path(base) + '/' + project
|
||||
data, volume, network = root + '/data', composition.notebook_volume_name(project), project + '_default'
|
||||
pattern = re.compile('/' + re.escape(project) + '-(' + '|'.join(SERVICES) + r')-(\d+|run-[0-9a-f]{12})')
|
||||
allowed = ({'type': 'bind', 'source': data, 'target': '/data'},
|
||||
{'type': 'volume', 'name': volume, 'target': composition.NOTEBOOK_JOBS})
|
||||
result = []
|
||||
for item in own:
|
||||
name = item.get('Name', '')
|
||||
match = pattern.fullmatch(name)
|
||||
if not match or item['Config']['Labels'].get('com.docker.compose.service') != match.group(1):
|
||||
raise RuntimeError(f'project container has an unexpected name or service: {name.lstrip("/")}')
|
||||
mounts = sorted((mount_shape(m) for m in item.get('Mounts') or []), key=json.dumps)
|
||||
for mount in mounts:
|
||||
if mount.get('source') is not None:
|
||||
mount['source'] = daemon_path(mount['source'])
|
||||
if any(mount not in allowed for mount in mounts):
|
||||
raise RuntimeError(f'project container mounts a path outside the installation: {name.lstrip("/")}')
|
||||
if set((item.get('NetworkSettings') or {}).get('Networks') or {}) - {network, 'none'}:
|
||||
raise RuntimeError(f'project container joins another network: {name.lstrip("/")}')
|
||||
if image_ids is not None and item.get('Image') not in image_ids:
|
||||
raise RuntimeError(f'project container does not use an image of the installation record: {name.lstrip("/")}')
|
||||
result.append({'id': item['Id'], 'name': name.lstrip('/'), 'service': match.group(1),
|
||||
'image': item.get('Image'), 'mounts': mounts,
|
||||
'state': (item.get('State') or {}).get('Status'), 'ports': published_ports(item)})
|
||||
return sorted(result, key=lambda c: c['name'])
|
||||
|
||||
|
||||
def volume_names(project):
|
||||
"""Names of the volumes labelled with the project or starting with its prefix."""
|
||||
labelled = set(proc.run(['docker', 'volume', 'ls', '-q', '--filter', f'label={PROJECT_LABEL}={project}']).split())
|
||||
named = {name for name in proc.run(['docker', 'volume', 'ls', '-q']).split() if name.startswith(project + '_')}
|
||||
return labelled | named
|
||||
|
||||
|
||||
def project_volumes(project):
|
||||
"""The notebook jobs volume if it exists; any other volume of the project or with its prefix refuses."""
|
||||
expected = composition.notebook_volume_name(project)
|
||||
names = volume_names(project)
|
||||
if names - {expected}:
|
||||
raise RuntimeError('unexpected volume of the project: ' + ', '.join(sorted(names - {expected})))
|
||||
return [volume_identity(project)] if expected in names else []
|
||||
|
||||
|
||||
def project_networks(project, own_ids):
|
||||
"""The project's default network if it exists, attached only by the project's own containers."""
|
||||
expected = project + '_default'
|
||||
listing = proc.run(['docker', 'network', 'ls', '--no-trunc', '--format', '{{.ID}} {{.Name}}']).splitlines()
|
||||
labelled = set(proc.run(['docker', 'network', 'ls', '-q', '--no-trunc', '--filter',
|
||||
f'label={PROJECT_LABEL}={project}']).split())
|
||||
found = [line.split(None, 1) for line in listing if len(line.split(None, 1)) == 2]
|
||||
candidates = {ident for ident, name in found if name == expected or name.startswith(project + '_')} | labelled
|
||||
result = []
|
||||
for ident in sorted(candidates):
|
||||
item = json.loads(proc.run(['docker', 'network', 'inspect', ident]))[0]
|
||||
labels = item.get('Labels') or {}
|
||||
if (item.get('Name') != expected or labels.get(PROJECT_LABEL) != project
|
||||
or labels.get('com.docker.compose.network') != 'default' or item.get('Driver') != 'bridge'):
|
||||
raise RuntimeError(f'network {item.get("Name")} is not the project default network')
|
||||
if set(item.get('Containers') or {}) - own_ids:
|
||||
raise RuntimeError(f'network {expected} has containers outside the project')
|
||||
result.append({'id': item['Id'], 'name': item['Name']})
|
||||
return result
|
||||
|
||||
|
||||
def discover(project, port, base, image_ids):
|
||||
"""Everything Docker holds for the project, checked. `image_ids` are the image IDs of the installation record;
|
||||
a container using another image is not part of it."""
|
||||
own, foreign = classify(inspect_all(), project, base)
|
||||
check_foreign(foreign, project, port, base)
|
||||
containers = own_containers(own, project, base, image_ids)
|
||||
return {'containers': containers, 'volumes': project_volumes(project),
|
||||
'networks': project_networks(project, {item['Id'] for item in own})}
|
||||
|
||||
|
||||
def plan_view(found):
|
||||
"""The part of `discover` that belongs in a plan: identities, not volatile state."""
|
||||
return {'containers': [{key: c[key] for key in PLAN_KEYS} for c in found['containers']],
|
||||
'volumes': found['volumes'], 'networks': found['networks']}
|
||||
|
||||
|
||||
def assert_absent(project, port, base):
|
||||
"""A project that is about to be installed owns nothing in Docker, and nobody else holds its port."""
|
||||
own, foreign = classify(inspect_all(), project, base)
|
||||
check_foreign(foreign, project, port, base)
|
||||
if own or volume_names(project) or project_networks(project, set()):
|
||||
raise RuntimeError(f'Docker already holds resources of {project}')
|
||||
|
||||
|
||||
def image_ids(images):
|
||||
"""Image IDs of the recorded tags; a missing image is an error, not an empty set."""
|
||||
ids = set()
|
||||
for image in images:
|
||||
ids.add(proc.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip())
|
||||
if not ids or not all(ids):
|
||||
raise RuntimeError('a recorded image was not found')
|
||||
return ids
|
||||
|
||||
|
||||
def verify_running(project, port, base, images, notebooks):
|
||||
"""After an installation: exactly the expected services run, on the recorded images and mounts, and only the
|
||||
web app publishes the port."""
|
||||
api_id, app_id = (proc.run(['docker', 'image', 'inspect', '--format', '{{.Id}}', image]).strip()
|
||||
for image in images)
|
||||
found = discover(project, port, base, {api_id, app_id})
|
||||
services = {}
|
||||
for item in found['containers']:
|
||||
if item['service'] in services or item['service'] in composition.PROFILE_SERVICES:
|
||||
raise RuntimeError('unexpected container in the Compose project')
|
||||
services[item['service']] = item
|
||||
expected = set(composition.BASE_SERVICES) | ({composition.NOTEBOOK_SERVICE} if notebooks else set())
|
||||
if set(services) != expected:
|
||||
raise RuntimeError('missing or unexpected Compose project containers')
|
||||
root = daemon_path(base) + '/' + project
|
||||
data = {'type': 'bind', 'source': root + '/data', 'target': '/data'}
|
||||
jobs = {'type': 'volume', 'name': composition.notebook_volume_name(project), 'target': composition.NOTEBOOK_JOBS}
|
||||
for name, item in services.items():
|
||||
if item['state'] != 'running':
|
||||
raise RuntimeError(f'{name} is not running')
|
||||
wanted = {'webapi': [data] + ([jobs] if notebooks else []), 'indicadores': [data],
|
||||
'notebooks': [jobs], 'webapp': []}[name]
|
||||
if sorted(item['mounts'], key=json.dumps) != sorted(wanted, key=json.dumps):
|
||||
raise RuntimeError(f'{name} mounts do not match')
|
||||
wanted_image = app_id if name == 'webapp' else api_id
|
||||
if item['image'] != wanted_image:
|
||||
raise RuntimeError(f'{name} image does not match the installation record')
|
||||
if item['ports'] != ([str(port)] if name == 'webapp' else []):
|
||||
raise RuntimeError(f'{name} publishes unexpected ports')
|
||||
return found
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Reference resolution and composition checkout, against local Git repositories (see gitfixture.py).
|
||||
|
||||
Fixtures: `Fixture` builds an outer repository on branch `dev` pinning ISSSTELEON, which pins WebApi, WebApp and
|
||||
models (which pins the EEG library at `libs/tea`), with the submodule URLs redirected to local copies for the duration
|
||||
of each test.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import composition
|
||||
import gitfixture
|
||||
|
||||
|
||||
class Fixture(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.fx = gitfixture.build(self.tmp.name)
|
||||
patcher = patch.dict(os.environ, self.fx['env'])
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.remote = self.fx['url']
|
||||
self.checkout_dir = Path(self.tmp.name) / 'checkout'
|
||||
|
||||
|
||||
class ResolveTests(Fixture):
|
||||
def test_branch_tag_and_commit_resolve_to_commits(self):
|
||||
"""Fails if a branch, a lightweight or annotated tag, or a full SHA stops resolving to its commit."""
|
||||
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
|
||||
gitfixture.git(outer, 'tag', 'light', env=self.fx['env'])
|
||||
gitfixture.git(outer, 'tag', '-a', 'annotated', '-m', 'release', env=self.fx['env'])
|
||||
for reference, kind in (('dev', 'branch'), ('light', 'tag'), ('annotated', 'tag')):
|
||||
with self.subTest(reference):
|
||||
resolved = composition.resolve_reference(reference, self.remote)
|
||||
self.assertEqual((resolved['kind'], resolved['commit']), (kind, self.fx['outer']))
|
||||
resolved = composition.resolve_reference(self.fx['outer'], self.remote)
|
||||
self.assertEqual((resolved['kind'], resolved['commit']), ('commit', self.fx['outer']))
|
||||
|
||||
def test_unknown_ambiguous_and_malformed_references_are_refused(self):
|
||||
"""Fails if a missing name, a name that is both branch and tag, an abbreviated SHA or a ref path is accepted."""
|
||||
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
|
||||
gitfixture.git(outer, 'tag', 'dev', env=self.fx['env'])
|
||||
with self.assertRaisesRegex(ValueError, 'both a branch and a tag'):
|
||||
composition.resolve_reference('dev', self.remote)
|
||||
with self.assertRaisesRegex(ValueError, 'not a branch or a tag'):
|
||||
composition.resolve_reference('missing', self.remote)
|
||||
for bad in ('', ' ', self.fx['outer'][:12], self.fx['outer'].upper(), 'refs/heads/dev', '-x', '@', 'a b',
|
||||
'a..b', 'x.lock'):
|
||||
with self.subTest(bad), self.assertRaises(ValueError):
|
||||
composition.resolve_reference(bad, self.remote)
|
||||
|
||||
|
||||
class CheckoutTests(Fixture):
|
||||
def test_composition_lists_the_exact_gitlinks(self):
|
||||
"""Fails if the composition omits the outer commit, the dev-data pin or any application gitlink."""
|
||||
resolved = composition.resolve_reference('dev', self.remote)
|
||||
comp = composition.checkout(resolved, self.checkout_dir, self.remote)
|
||||
self.assertEqual(comp['commit'], self.fx['outer'])
|
||||
self.assertEqual(comp['application'], self.fx['ISSSTELEON'])
|
||||
self.assertEqual(comp['gitlinks'], {
|
||||
'WorkingNarrative': self.fx['outer'], 'dev-data': self.fx['dev-data'],
|
||||
'ISSSTELEON': self.fx['ISSSTELEON'], 'WebApi': self.fx['WebApi'], 'WebApp': self.fx['WebApp'],
|
||||
'models': self.fx['models'], 'models/libs/tea': self.fx['tea']})
|
||||
|
||||
def test_a_reference_that_moved_since_resolution_is_refused(self):
|
||||
"""Fails if the checkout silently takes a newer commit than the one that was resolved and approved."""
|
||||
resolved = composition.resolve_reference('dev', self.remote)
|
||||
gitfixture.advance(self.fx)
|
||||
with self.assertRaisesRegex(RuntimeError, 'moved from'):
|
||||
composition.checkout(resolved, self.checkout_dir, self.remote)
|
||||
|
||||
def test_commit_reference_checks_out_that_commit_only(self):
|
||||
"""Fails if a full SHA checks out the branch tip instead of the requested commit."""
|
||||
gitfixture.advance(self.fx)
|
||||
resolved = composition.resolve_reference(self.fx['outer'], self.remote)
|
||||
comp = composition.checkout(resolved, self.checkout_dir, self.remote)
|
||||
self.assertEqual(comp['commit'], self.fx['outer'])
|
||||
|
||||
def test_untrusted_submodule_origin_is_refused(self):
|
||||
"""Fails if a gitlink whose URL is not the institutional one is initialised."""
|
||||
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
|
||||
gitfixture.git(outer, 'config', '-f', '.gitmodules', 'submodule.ISSSTELEON.url',
|
||||
'ssh://git@example.invalid/x/ISSSTELEON.git', env=self.fx['env'])
|
||||
gitfixture.git(outer, 'commit', '-q', '-am', 'redirect', env=self.fx['env'])
|
||||
resolved = composition.resolve_reference('dev', self.remote)
|
||||
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin'):
|
||||
composition.checkout(resolved, self.checkout_dir, self.remote)
|
||||
|
||||
def test_the_eeg_library_is_trusted_only_at_its_own_origin(self):
|
||||
"""Fails if the library's gitlink is initialised from any URL but alberto/tea, or refused at that one."""
|
||||
models = Path(self.tmp.name) / 'remotes' / 'models.git'
|
||||
gitfixture.git(models, 'config', '-f', '.gitmodules', 'submodule.tea.url',
|
||||
'ssh://git@10.0.10.41:2222/alberto/other.git', env=self.fx['env'])
|
||||
gitfixture.git(models, 'commit', '-q', '-am', 'redirect the library', env=self.fx['env'])
|
||||
application = Path(self.tmp.name) / 'remotes' / 'ISSSTELEON.git'
|
||||
gitfixture.git(application / 'models', 'pull', '-q', 'origin', 'dev', env=self.fx['env'])
|
||||
gitfixture.git(application, 'commit', '-q', '-am', 'move models', env=self.fx['env'])
|
||||
outer = Path(self.tmp.name) / 'remotes' / 'WorkingNarrative.git'
|
||||
gitfixture.git(outer / 'ISSSTELEON', 'pull', '-q', 'origin', 'dev', env=self.fx['env'])
|
||||
gitfixture.git(outer, 'commit', '-q', '-am', 'move ISSSTELEON', env=self.fx['env'])
|
||||
resolved = composition.resolve_reference('dev', self.remote)
|
||||
with self.assertRaisesRegex(RuntimeError, 'untrusted submodule origin: ISSSTELEON/models/libs/tea'):
|
||||
composition.checkout(resolved, self.checkout_dir, self.remote)
|
||||
|
||||
def test_export_contains_every_pinned_tree(self):
|
||||
"""Fails if the exported source lacks a pinned application's files, which the image builds need."""
|
||||
resolved = composition.resolve_reference('dev', self.remote)
|
||||
comp = composition.checkout(resolved, self.checkout_dir, self.remote)
|
||||
export = Path(self.tmp.name) / 'export'
|
||||
composition.export_tree(self.checkout_dir / 'ISSSTELEON', comp['application'], export)
|
||||
for path in ('dist/docker-compose.yml', 'WebApi/Dockerfile', 'WebApp/Dockerfile', 'models/Dockerfile',
|
||||
'models/libs/tea/pyproject.toml'):
|
||||
self.assertTrue((export / path).is_file(), path)
|
||||
|
||||
|
||||
class PortTests(unittest.TestCase):
|
||||
def test_protected_and_out_of_range_ports_are_refused(self):
|
||||
"""Fails if a protected port (including the reference installations 18090, 18096 and 18097), a privileged or
|
||||
an oversized port, or non-numeric text is accepted."""
|
||||
for bad in ('18087', '4397', '18090', '18096', '18097', '80', '70000', 'abc', '', '18083.5'):
|
||||
with self.subTest(bad), self.assertRaises(ValueError):
|
||||
composition.validate_port(bad)
|
||||
self.assertEqual(composition.validate_port('18083'), 18083)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,925 +0,0 @@
|
||||
"""Conservative updates against temporary SQLite files and a simulated Docker adapter.
|
||||
|
||||
The fixture has four versioned databases, protected patients, mutable projections,
|
||||
historical reports, an artifact and an existing archive. No daemon is contacted.
|
||||
"""
|
||||
|
||||
from contextlib import closing
|
||||
import copy
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import conservative
|
||||
import data_guard as guard
|
||||
import dev
|
||||
import host
|
||||
|
||||
HEADS = {'cacu': 'b4f2d8c01e23', 'cama': 'c5a3e9d12f34',
|
||||
'tea': 'a3e1c7b90d12', 'governance': 'e7c5a1f34b56'}
|
||||
|
||||
|
||||
def fixture(base, project='isssteleon-old', port=18080):
|
||||
"""Create synthetic witnesses and derive an independent expected schema before mutations."""
|
||||
root = base / project
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(root / name).mkdir(parents=True)
|
||||
(root / 'codigo' / 'version.txt').write_text('old')
|
||||
contract = {}
|
||||
for domain in guard.DOMAINS:
|
||||
with closing(sqlite3.connect(root / 'data' / (domain + '.db'))) as connection:
|
||||
connection.executescript("""
|
||||
CREATE TABLE alembic_version (version_num VARCHAR(32) PRIMARY KEY NOT NULL);
|
||||
CREATE TABLE patient (id INTEGER PRIMARY KEY, value TEXT NOT NULL, document BLOB);
|
||||
CREATE UNIQUE INDEX patient_value ON patient(value);
|
||||
CREATE TABLE persona (id INTEGER PRIMARY KEY, value TEXT);
|
||||
CREATE TABLE measure_report (id INTEGER PRIMARY KEY, value TEXT);
|
||||
INSERT INTO patient VALUES (1, 'SYNTHETIC-WITNESS', X'010203');
|
||||
INSERT INTO persona VALUES (1, 'original projection');
|
||||
INSERT INTO measure_report VALUES (1, 'historical report');
|
||||
""")
|
||||
connection.execute('INSERT INTO alembic_version VALUES (?)', (HEADS[domain],))
|
||||
connection.commit()
|
||||
contract[domain] = {'head': HEADS[domain], 'known': [HEADS[domain]],
|
||||
'schema': guard.schema(connection)}
|
||||
contract['governance']['known'].append('d6b4f0e23a45')
|
||||
(root / 'data' / 'mlflow-artefactos').mkdir()
|
||||
(root / 'data' / 'mlflow-artefactos' / 'model.bin').write_bytes(b'synthetic-model')
|
||||
with closing(sqlite3.connect(root / 'data' / 'mlflow.db')) as connection:
|
||||
connection.executescript("CREATE TABLE runs (id INTEGER PRIMARY KEY, value TEXT);"
|
||||
"INSERT INTO runs VALUES (1, 'synthetic registered model');")
|
||||
(root / 'data' / 'reportes').mkdir()
|
||||
(root / 'data' / 'reportes' / 'imports.jsonl').write_text('{"synthetic":true}\n')
|
||||
(root / 'data' / 'empty-directory').mkdir()
|
||||
(root / '.archive' / 'previous' / 'data').mkdir(parents=True)
|
||||
(root / '.archive' / 'previous' / 'data' / 'keep').write_text('historical archive')
|
||||
record = {'project': project, 'port': port, 'revision': 'a' * 40,
|
||||
'gitlinks': {'ISSSTELEON': 'b' * 40}, 'status': 'installed',
|
||||
'images': ['isssteleon/webapi:old', 'isssteleon/webapp:old']}
|
||||
host.write_record(root, record)
|
||||
return root, contract, record
|
||||
|
||||
|
||||
def change(root, domain, sql):
|
||||
"""Modify only a temporary fixture database for a rejection or worker scenario."""
|
||||
with closing(sqlite3.connect(root / 'data' / (domain + '.db'))) as connection:
|
||||
connection.execute(sql)
|
||||
connection.commit()
|
||||
|
||||
|
||||
class GuardTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
"""Reserve a private directory containing four synthetic databases."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.root, self.contract, self.record = fixture(self.base)
|
||||
self.data = self.root / 'data'
|
||||
|
||||
def test_known_heads_and_structures_are_read_only(self):
|
||||
"""Fail if compatible inspection changes any SQLite bytes or file identity."""
|
||||
before = {p.name: guard.digest(p) for p in self.data.glob('*.db')}
|
||||
state = guard.inspect_databases(self.data, self.contract)
|
||||
self.assertEqual(state['directory'], guard.identity(self.data))
|
||||
self.assertEqual(before, {p.name: guard.digest(p) for p in self.data.glob('*.db')})
|
||||
|
||||
@unittest.skipUnless(os.name == 'nt', 'requires Windows directory ACLs')
|
||||
def test_stopped_wal_reader_when_directory_forbids_sidecars(self):
|
||||
"""Fail if closing the WAL writer makes a read-only post-stop inspection fail."""
|
||||
sid = '*' + next(csv.reader(subprocess.check_output(
|
||||
['whoami', '/user', '/fo', 'csv', '/nh'], text=True).splitlines()))[1]
|
||||
db = sqlite3.connect(self.data / 'cama.db')
|
||||
db.execute('PRAGMA journal_mode=WAL')
|
||||
db.execute("INSERT INTO patient VALUES (2, 'wal witness', NULL)")
|
||||
db.commit()
|
||||
acl = subprocess.run(['icacls', str(self.data), '/deny', sid + ':(WD,AD)'], capture_output=True)
|
||||
if acl.returncode:
|
||||
db.close()
|
||||
self.skipTest('cannot set temporary directory ACL')
|
||||
try:
|
||||
guard.inspect_databases(self.data, self.contract)
|
||||
db.close()
|
||||
self.assertFalse((self.data / 'cama.db-wal').exists())
|
||||
with self.assertRaises(RuntimeError) as error:
|
||||
guard.inspect_databases(self.data, self.contract)
|
||||
self.assertEqual(getattr(error.exception, 'sqlite_errorname', None), 'SQLITE_CANTOPEN')
|
||||
guard.inspect_databases(self.data, self.contract, quiesced=True)
|
||||
finally:
|
||||
db.close()
|
||||
subprocess.run(['icacls', str(self.data), '/remove:d', sid], check=True, capture_output=True)
|
||||
|
||||
def test_quiesced_fallback_never_ignores_wal(self):
|
||||
"""Fail if the post-stop fallback reads an immutable main file while a WAL exists."""
|
||||
(self.data / 'cama.db-wal').write_bytes(b'committed pages')
|
||||
failure = sqlite3.OperationalError('cannot open')
|
||||
failure.sqlite_errorname = 'SQLITE_CANTOPEN'
|
||||
original = guard.readonly
|
||||
def open_db(path, **kwargs):
|
||||
if path.name == 'cama.db':
|
||||
raise failure
|
||||
return original(path, **kwargs)
|
||||
with patch.object(guard, 'readonly', side_effect=open_db), self.assertRaises(sqlite3.OperationalError):
|
||||
guard.inspect_databases(self.data, self.contract, quiesced=True)
|
||||
|
||||
def test_quiesced_inspection_reads_committed_wal_rows(self):
|
||||
"""Fail if post-stop inspection ignores committed rows still present in a WAL."""
|
||||
with closing(sqlite3.connect(self.data / 'cama.db')) as db:
|
||||
db.execute('PRAGMA journal_mode=WAL')
|
||||
db.execute('PRAGMA wal_autocheckpoint=0')
|
||||
db.execute("INSERT INTO patient VALUES (2, 'wal witness', NULL)")
|
||||
db.commit()
|
||||
state = guard.inspect_databases(self.data, self.contract, rows=True, quiesced=True)
|
||||
self.assertEqual(state['databases']['cama']['tables']['patient']['count'], 2)
|
||||
|
||||
def test_verify_reads_live_recalculation_wal(self):
|
||||
"""Verification sees committed projection changes in WAL with the writer still open."""
|
||||
before = guard.storage_state(self.data, self.contract)
|
||||
path = self.data / 'cacu.db'
|
||||
with closing(sqlite3.connect(path)) as writer:
|
||||
writer.execute('PRAGMA journal_mode=WAL')
|
||||
writer.execute('PRAGMA wal_autocheckpoint=0')
|
||||
writer.execute("UPDATE persona SET value='recalculated'")
|
||||
writer.commit()
|
||||
self.assertTrue(Path(str(path) + '-wal').is_file())
|
||||
original = guard.digest(path)
|
||||
after = guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
self.assertNotEqual(before['databases']['cacu']['tables']['persona']['sha256'],
|
||||
after['databases']['cacu']['tables']['persona']['sha256'])
|
||||
self.assertEqual(original, guard.digest(path))
|
||||
|
||||
@unittest.skipUnless(os.name == 'nt', 'requires Windows file ACLs')
|
||||
def test_quiesced_inspection_rejects_unreadable_database(self):
|
||||
"""Fail if the fallback bypasses denied database file permissions."""
|
||||
sid = '*' + next(csv.reader(subprocess.check_output(
|
||||
['whoami', '/user', '/fo', 'csv', '/nh'], text=True).splitlines()))[1]
|
||||
path = self.data / 'cama.db'
|
||||
if subprocess.run(['icacls', str(path), '/deny', sid + ':(RD)'], capture_output=True).returncode:
|
||||
self.skipTest('cannot set temporary database ACL')
|
||||
try:
|
||||
with self.assertRaises((RuntimeError, OSError, sqlite3.Error)):
|
||||
guard.inspect_databases(self.data, self.contract, quiesced=True)
|
||||
finally:
|
||||
subprocess.run(['icacls', str(path), '/remove:d', sid], check=True, capture_output=True)
|
||||
|
||||
def test_missing_database_is_not_created(self):
|
||||
"""Fail if a missing database is silently replaced by an empty SQLite file."""
|
||||
(self.data / 'tea.db').unlink()
|
||||
with self.assertRaisesRegex(RuntimeError, 'missing'):
|
||||
guard.inspect_databases(self.data, self.contract)
|
||||
self.assertFalse((self.data / 'tea.db').exists())
|
||||
|
||||
def test_unknown_revision_is_rejected_without_changes(self):
|
||||
"""Fail if an unknown historical revision is accepted or rewritten."""
|
||||
change(self.root, 'tea', "UPDATE alembic_version SET version_num='047529ced337'")
|
||||
before = guard.digest(self.data / 'tea.db')
|
||||
with self.assertRaisesRegex(RuntimeError, 'unknown'):
|
||||
guard.inspect_databases(self.data, self.contract)
|
||||
self.assertEqual(guard.digest(self.data / 'tea.db'), before)
|
||||
|
||||
def test_validator_emits_safe_specific_rejection(self):
|
||||
"""Fail if an unknown revision is hidden or its actual value leaks from the subprocess."""
|
||||
change(self.root, 'tea', "UPDATE alembic_version SET version_num='private-revision-value'")
|
||||
payload = json.dumps({'data': str(self.data), 'contract': self.contract})
|
||||
result = subprocess.run([sys.executable, '-B', str(Path(guard.__file__)), 'inspect'],
|
||||
input=payload, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertNotIn('private-revision-value', result.stderr)
|
||||
failure = subprocess.CalledProcessError(result.returncode, ['private'], stderr=result.stderr)
|
||||
detail = conservative.failure_detail(failure)
|
||||
self.assertIn('reason=migration_revision_unknown, domain=tea', detail)
|
||||
self.assertNotIn('private-revision-value', detail)
|
||||
|
||||
def test_sqlite_error_classification_discards_sensitive_text(self):
|
||||
"""Fail if SQLite diagnostic codes disappear or raw exception messages are emitted."""
|
||||
exc = sqlite3.OperationalError('secret SQL and private file')
|
||||
exc.sqlite_errorname = 'SQLITE_READONLY_CANTINIT'
|
||||
exc.inspection_domain = 'cacu'
|
||||
diagnostic = guard.inspection_diagnostic(exc)
|
||||
self.assertEqual(diagnostic['sqlite'], 'SQLITE_READONLY_CANTINIT')
|
||||
self.assertEqual(diagnostic['domain'], 'cacu')
|
||||
self.assertNotIn('secret', json.dumps(diagnostic))
|
||||
|
||||
def test_recalculation_stdout_cannot_corrupt_result(self):
|
||||
"""Fail if Python or native stdout makes a successful one-shot response invalid JSON."""
|
||||
package = self.base / 'webapi'
|
||||
package.mkdir()
|
||||
(package / '__init__.py').write_text('')
|
||||
(package / 'indicadores_vivos.py').write_text(
|
||||
'import os\n'
|
||||
'class ColaDeRecalculo:\n'
|
||||
' def tomar(self, domain): print("private witness")\n'
|
||||
' def correr(self, domain):\n'
|
||||
' os.write(1, b"native private witness\\n")\n'
|
||||
' return {"estado": "ok"}\n'
|
||||
' def pendientes(self): return []\n')
|
||||
env = dict(os.environ, PYTHONPATH=str(self.base))
|
||||
result = subprocess.run([sys.executable, '-B', str(Path(guard.__file__)), 'recalculate'],
|
||||
input=json.dumps({'environment': {}}), text=True, capture_output=True, env=env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout), {'completed': ['cacu', 'cama', 'tea']})
|
||||
self.assertNotIn('private witness', result.stdout)
|
||||
|
||||
def test_recalculation_rejection_identifies_domain_without_data(self):
|
||||
"""Fail if a failed domain is hidden or private worker errors reach diagnostics."""
|
||||
package = self.base / 'webapi'
|
||||
package.mkdir()
|
||||
(package / '__init__.py').write_text('')
|
||||
(package / 'indicadores_vivos.py').write_text(
|
||||
'class ColaDeRecalculo:\n'
|
||||
' def tomar(self, domain): pass\n'
|
||||
' def correr(self, domain):\n'
|
||||
' if domain == "cama": raise ValueError("private clinical data")\n'
|
||||
' return {"estado": "ok"}\n')
|
||||
env = dict(os.environ, PYTHONPATH=str(self.base))
|
||||
result = subprocess.run([sys.executable, '-B', str(Path(guard.__file__)), 'recalculate'],
|
||||
input=json.dumps({'environment': {}}), text=True, capture_output=True, env=env)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
detail = conservative.failure_detail(subprocess.CalledProcessError(1, ['private'], stderr=result.stderr))
|
||||
self.assertIn('domain=cama', detail)
|
||||
self.assertIn('stage=execute', detail)
|
||||
self.assertIn('type=ValueError', detail)
|
||||
self.assertNotIn('clinical', detail + result.stderr)
|
||||
|
||||
def test_diagnostic_parser_rejects_untrusted_error_text(self):
|
||||
"""Fail if crafted subprocess output can inject arbitrary text into workflow diagnostics."""
|
||||
fake = {'reason': 'secret patient', 'domain': 'tea', 'type': 'RuntimeError',
|
||||
'sqlite': 'none', 'errno': None}
|
||||
error = subprocess.CalledProcessError(1, ['private'],
|
||||
stderr='WN_INSPECT_DIAGNOSTIC=' + json.dumps(fake))
|
||||
self.assertEqual(conservative.failure_detail(error), 'exit=1')
|
||||
|
||||
def test_pending_governance_drop_is_rejected(self):
|
||||
"""Fail if the recognized predecessor of the destructive revision is admitted."""
|
||||
change(self.root, 'governance', "UPDATE alembic_version SET version_num='d6b4f0e23a45'")
|
||||
with self.assertRaisesRegex(RuntimeError, 'pending migrations'):
|
||||
guard.inspect_databases(self.data, self.contract)
|
||||
|
||||
def test_schema_drift_and_unversioned_databases_are_rejected(self):
|
||||
"""Fail if a head stamp hides a missing index, column or version table."""
|
||||
for sql in ('DROP INDEX patient_value', 'ALTER TABLE patient ADD COLUMN unexpected TEXT',
|
||||
'DROP TABLE alembic_version',
|
||||
'CREATE TRIGGER unexpected AFTER INSERT ON patient BEGIN DELETE FROM persona; END',
|
||||
'CREATE INDEX descending_value ON patient(value DESC)'):
|
||||
with self.subTest(sql=sql):
|
||||
other = self.base / ('case-' + str(len(list(self.base.iterdir()))))
|
||||
other.mkdir()
|
||||
root, contract, _ = fixture(other)
|
||||
change(root, 'cacu', sql)
|
||||
with self.assertRaises(RuntimeError):
|
||||
guard.inspect_databases(root / 'data', contract)
|
||||
|
||||
def test_backup_restore_preserves_rows_artifacts_and_empty_directories(self):
|
||||
"""Fail if a verified isolated restore loses witnesses, blobs, artifacts or directories."""
|
||||
backup = self.base / 'backup'
|
||||
guard.create_backup(self.data, backup, self.contract, self.record)
|
||||
restored = self.base / 'restored'
|
||||
guard.restore_backup(backup, restored)
|
||||
with closing(guard.readonly(restored / 'tea.db')) as connection:
|
||||
self.assertEqual(connection.execute('SELECT value, document FROM patient').fetchone(),
|
||||
('SYNTHETIC-WITNESS', b'\x01\x02\x03'))
|
||||
self.assertEqual((restored / 'mlflow-artefactos' / 'model.bin').read_bytes(), b'synthetic-model')
|
||||
self.assertTrue((restored / 'empty-directory').is_dir())
|
||||
with self.assertRaisesRegex(RuntimeError, 'must be new'):
|
||||
guard.restore_backup(backup, self.data)
|
||||
|
||||
def test_wal_backup_includes_committed_pages(self):
|
||||
"""Fail if the backup copies only the main SQLite file and misses committed WAL rows."""
|
||||
connection = sqlite3.connect(self.data / 'tea.db')
|
||||
self.addCleanup(connection.close)
|
||||
connection.execute('PRAGMA journal_mode=WAL')
|
||||
connection.execute('PRAGMA wal_autocheckpoint=0')
|
||||
connection.execute("INSERT INTO patient VALUES (2,'WAL-WITNESS',NULL)")
|
||||
connection.commit()
|
||||
self.assertTrue((self.data / 'tea.db-wal').exists())
|
||||
backup = self.base / 'wal-backup'
|
||||
guard.create_backup(self.data, backup, self.contract, self.record)
|
||||
with closing(guard.readonly(backup / 'data' / 'tea.db')) as copy_db:
|
||||
self.assertEqual(copy_db.execute('SELECT count(*) FROM patient').fetchone()[0], 2)
|
||||
self.assertFalse((backup / 'data' / 'tea.db-wal').exists())
|
||||
|
||||
def test_corrupted_backup_is_rejected(self):
|
||||
"""Fail if checksum verification accepts changed artifacts before restoration."""
|
||||
backup = self.base / 'backup'
|
||||
guard.create_backup(self.data, backup, self.contract, self.record)
|
||||
(backup / 'data' / 'mlflow-artefactos' / 'model.bin').write_bytes(b'changed')
|
||||
with self.assertRaisesRegex(RuntimeError, 'checksum'):
|
||||
guard.restore_backup(backup, self.base / 'restored')
|
||||
self.assertFalse((self.base / 'restored').exists())
|
||||
|
||||
def test_worker_changes_are_scoped_and_history_is_retained(self):
|
||||
"""Allow declared projections and appended reports while rejecting clinical loss."""
|
||||
before = guard.storage_state(self.data, self.contract)
|
||||
change(self.root, 'cacu', "UPDATE persona SET value='recomputed'")
|
||||
change(self.root, 'cacu', "INSERT INTO measure_report VALUES (2,'new report')")
|
||||
with self.assertRaisesRegex(RuntimeError, 'persistent rows changed'):
|
||||
guard.verify_state(self.data, self.contract, before)
|
||||
guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
change(self.root, 'cacu', "UPDATE patient SET value='unexpected change'")
|
||||
with self.assertRaisesRegex(RuntimeError, 'patient'):
|
||||
guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
|
||||
def test_derived_check_rejects_loss_of_historical_reports(self):
|
||||
"""Fail if an unchanged report count conceals replacement of a historical row."""
|
||||
before = guard.storage_state(self.data, self.contract)
|
||||
change(self.root, 'cacu', "UPDATE measure_report SET value='replacement'")
|
||||
with self.assertRaisesRegex(RuntimeError, 'historical rows'):
|
||||
guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
|
||||
def test_unknown_persistent_file_is_protected(self):
|
||||
"""Fail if the derived allowlist hides deletion of an unrelated persistent file."""
|
||||
path = self.data / 'custom.bin'
|
||||
path.write_bytes(b'custom witness')
|
||||
before = guard.storage_state(self.data, self.contract)
|
||||
path.unlink()
|
||||
with self.assertRaisesRegex(RuntimeError, 'persistent file'):
|
||||
guard.verify_state(self.data, self.contract, before, derived=True)
|
||||
|
||||
def test_only_sqlite_sidecars_are_excluded(self):
|
||||
"""Fail if a filename suffix silently excludes a regular persistent file from backup."""
|
||||
(self.data / 'notes').write_text('ordinary file')
|
||||
(self.data / 'notes-wal').write_text('ordinary auxiliary witness')
|
||||
backup = self.base / 'backup'
|
||||
guard.create_backup(self.data, backup, self.contract, self.record)
|
||||
restored = self.base / 'restore'
|
||||
guard.restore_backup(backup, restored)
|
||||
self.assertEqual((restored / 'notes-wal').read_text(), 'ordinary auxiliary witness')
|
||||
with closing(guard.readonly(restored / 'mlflow.db')) as db:
|
||||
self.assertEqual(db.execute('SELECT value FROM runs').fetchone()[0], 'synthetic registered model')
|
||||
|
||||
def test_backup_rejects_a_writer_that_changes_storage(self):
|
||||
"""Fail if a changing source can be certified as a quiesced backup."""
|
||||
original = guard.sqlite_digest
|
||||
changed = False
|
||||
|
||||
def concurrent_write(path):
|
||||
nonlocal changed
|
||||
if Path(path).parent.name == 'data' and not changed:
|
||||
changed = True
|
||||
(self.data / 'concurrent-writer').write_text('unexpected writer')
|
||||
return original(path)
|
||||
|
||||
with patch.object(guard, 'sqlite_digest', side_effect=concurrent_write), \
|
||||
self.assertRaisesRegex(RuntimeError, 'changed while'):
|
||||
guard.create_backup(self.data, self.base / 'backup', self.contract, self.record)
|
||||
|
||||
def test_backup_and_restore_reject_nested_destinations(self):
|
||||
"""Fail if recursive copying can include its own destination or mutate a verified backup."""
|
||||
with self.assertRaisesRegex(RuntimeError, 'outside persistent'):
|
||||
guard.create_backup(self.data, self.data / 'nested', self.contract, self.record)
|
||||
backup = self.base / 'backup'
|
||||
guard.create_backup(self.data, backup, self.contract, self.record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'outside the backup'):
|
||||
guard.restore_backup(backup, backup / 'data' / 'nested')
|
||||
|
||||
def test_missing_empty_backup_directory_is_detected(self):
|
||||
"""Fail if checksum-only validation overlooks loss of an empty persistent directory."""
|
||||
backup = self.base / 'backup'
|
||||
guard.create_backup(self.data, backup, self.contract, self.record)
|
||||
(backup / 'data' / 'empty-directory').rmdir()
|
||||
with self.assertRaisesRegex(RuntimeError, 'directory inventory'):
|
||||
guard.verify_backup(backup)
|
||||
|
||||
|
||||
class SimulatedDeployment:
|
||||
"""Use real host/data guards and synthetic files while substituting every Docker command."""
|
||||
|
||||
def __init__(self, root, contract, record):
|
||||
self.root, self.contract, self.record = root, contract, record
|
||||
self.calls = []
|
||||
self.revision = 'c' * 40
|
||||
self.fail = None
|
||||
self.mount_changed = False
|
||||
self.finished = False
|
||||
self.running = {name: True for name in ('worker', 'api', 'app')}
|
||||
self.configure = dev.configure
|
||||
self.compose = dev.compose
|
||||
self.verify_config = dev.verify_config
|
||||
self.env = {**conservative.PERSISTENT_ENV,
|
||||
'ISSSTELEON_VERSION': record['images'][0].removeprefix('isssteleon/webapi:'),
|
||||
'ISSSTELEON_DATOS': str(root / 'data'), 'ISSSTELEON_PUERTO': str(record['port']),
|
||||
'KEEP_THIS': 'unchanged', 'WEBAPI_TIMEOUT': '42'}
|
||||
(root / 'deploy' / '.env').write_text('\n'.join(k + '=' + v for k, v in self.env.items()))
|
||||
(root / 'deploy' / 'docker-compose.yml').write_text(json.dumps(self.config(self.env)))
|
||||
|
||||
def config(self, env):
|
||||
service = {'image': 'isssteleon/webapi:' + env['ISSSTELEON_VERSION'],
|
||||
'environment': dict(env),
|
||||
'volumes': [{'type': 'bind', 'source': str(self.root / 'data'), 'target': '/data'}]}
|
||||
return {'name': self.record['project'], 'services': {
|
||||
'webapi': copy.deepcopy(service), 'indicadores': copy.deepcopy(service),
|
||||
'webapp': {'image': 'isssteleon/webapp:' + env['ISSSTELEON_VERSION'],
|
||||
'ports': [{'published': str(self.record['port']), 'target': 80}]}}}
|
||||
|
||||
def git(self, root, *args):
|
||||
return self.revision if args[0] == 'rev-parse' else '160000 commit ' + 'd' * 40 + '\tISSSTELEON'
|
||||
|
||||
def export_tree(self, repo, revision, source, manifest):
|
||||
(source / 'dist').mkdir(parents=True)
|
||||
(source / 'dist' / 'docker-compose.yml').write_text('{}')
|
||||
(source / 'version.txt').write_text(self.revision)
|
||||
manifest.update(self.pinned_manifest(repo, revision))
|
||||
|
||||
def pinned_manifest(self, repo, revision):
|
||||
return {'ISSSTELEON': revision, 'WebApi': 'e' * 40, 'WebApp': 'f' * 40,
|
||||
'models': '1' * 40, 'indicadores_kit': '2' * 40}
|
||||
|
||||
def run(self, args, **kwargs):
|
||||
args = list(map(str, args))
|
||||
self.calls.append(args)
|
||||
if args[:2] == ['docker', 'build'] and self.fail == 'build':
|
||||
raise RuntimeError('synthetic build failure')
|
||||
if 'config' in args:
|
||||
directory = Path(args[args.index('--project-directory') + 1])
|
||||
env = dict(line.split('=', 1) for line in (directory / '.env').read_text().splitlines()
|
||||
if '=' in line and not line.startswith('#'))
|
||||
env = {k: v.strip("'") for k, v in env.items()}
|
||||
return json.dumps(self.config(env))
|
||||
if args[:2] == ['docker', 'inspect']:
|
||||
if '--format' in args:
|
||||
return json.dumps({'Running': self.running[args[-1]]})
|
||||
return json.dumps([{'Id': ident, 'Image': 'old-image', 'Mounts': [],
|
||||
'State': {'Running': self.running[ident]},
|
||||
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}},
|
||||
'Config': {'Labels': {'com.docker.compose.service': name},
|
||||
'Env': [k + '=' + v for k, v in self.env.items()] + ['INDICADORES_AL_INICIAR=0'],
|
||||
'Entrypoint': (['/app/WebApi/.venv/bin/python', '-m', 'gunicorn',
|
||||
'--bind', '0.0.0.0:5000', '--workers', '2',
|
||||
'--timeout', '600', '--access-logfile', '-',
|
||||
'webapi:create_app()'] if name == 'webapi' else
|
||||
['/app/WebApi/.venv/bin/python', '-m', 'webapi.indicadores_vivos']),
|
||||
'Cmd': []}}
|
||||
for ident, name in zip(('worker', 'api', 'app'), ('indicadores', 'webapi', 'webapp'))])
|
||||
if args[:2] == ['docker', 'stop']:
|
||||
self.running[args[-1]] = False
|
||||
if args[:2] == ['docker', 'start']:
|
||||
self.running[args[-1]] = True
|
||||
if 'up' in args and args[-1] == 'webapi' and self.fail == 'cutover':
|
||||
raise RuntimeError('synthetic cutover failure')
|
||||
if 'up' in args and args[-1] in ('indicadores', 'webapp') and not self.finished:
|
||||
raise AssertionError('regular services cannot start before checked recalculation')
|
||||
return ''
|
||||
|
||||
def host_action(self, helper, action, project, value):
|
||||
if action == 'lookup':
|
||||
return json.dumps(host.find_installation(self.root.parent, int(value), missing_ok=True))
|
||||
if action == 'update-space' and self.fail == 'space':
|
||||
raise RuntimeError('synthetic space failure')
|
||||
if action == 'read-deploy':
|
||||
return json.dumps({name: (self.root / 'deploy' / name).read_text()
|
||||
for name in ('.env', 'docker-compose.yml')})
|
||||
if action == 'prepare-backup':
|
||||
if self.fail == 'backup-preparation':
|
||||
raise PermissionError('synthetic preparation failure')
|
||||
host.prepare_backup(self.root.parent, project, json.loads(value)['verify_restore'])
|
||||
if action == 'save':
|
||||
host.write_record(self.root, json.loads(value))
|
||||
elif action == 'backup':
|
||||
if self.fail == 'backup':
|
||||
raise RuntimeError('synthetic backup failure')
|
||||
return json.dumps(host.backup_installation(self.root.parent, project, json.loads(value)))
|
||||
elif action == 'verify-restore':
|
||||
if self.fail == 'restore':
|
||||
raise RuntimeError('synthetic restore verification failure')
|
||||
return str(host.verify_isolated_restore(self.root.parent, project, value))
|
||||
elif action == 'stage':
|
||||
host.stage_installation(self.root.parent, project, value)
|
||||
elif action == 'activate':
|
||||
payload = json.loads(value)
|
||||
return str(host.activate_installation(self.root.parent, project,
|
||||
payload['operation_id'], payload['previous']))
|
||||
return ''
|
||||
|
||||
def copy_to_host(self, helper, source, project, destination):
|
||||
shutil.copytree(source, self.root / destination)
|
||||
|
||||
def verify_existing_containers(self, record, base, helper):
|
||||
if self.mount_changed:
|
||||
raise RuntimeError('data mount does not match')
|
||||
return ['worker', 'api', 'app']
|
||||
|
||||
def verify_services(self, cmd, port):
|
||||
record = host.read_record(self.root)
|
||||
if not self.finished and record['status'] != 'update_failed' and record['revision'] != self.revision:
|
||||
raise RuntimeError('worker completion was not verified')
|
||||
|
||||
def guard(self, api, image, action, payload, data=None, **kwargs):
|
||||
if action == 'contract':
|
||||
return self.contract
|
||||
if action == 'inspect':
|
||||
return guard.inspect_databases(self.root / 'data', self.contract)
|
||||
if action == 'verify':
|
||||
return guard.verify_state(self.root / 'data', self.contract, payload['before'],
|
||||
derived=payload.get('derived', False))
|
||||
if action == 'recalculate':
|
||||
if self.fail == 'worker':
|
||||
change(self.root, 'tea', "UPDATE patient SET value='lost value'")
|
||||
else:
|
||||
change(self.root, 'tea', "UPDATE persona SET value='expected derived change'")
|
||||
with closing(sqlite3.connect(self.root / 'data' / 'tea.db')) as connection:
|
||||
next_id = connection.execute('SELECT max(id)+1 FROM measure_report').fetchone()[0]
|
||||
connection.execute('INSERT INTO measure_report VALUES (?,?)', (next_id, 'new report'))
|
||||
connection.commit()
|
||||
self.finished = True
|
||||
return {'completed': ['cacu', 'cama', 'tea']}
|
||||
raise AssertionError(action)
|
||||
|
||||
|
||||
class UpdateTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
"""Prepare a managed synthetic installation and retain its original data identity."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.root, self.contract, self.record = fixture(self.base)
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
self.original_identity = guard.identity(self.root / 'data')
|
||||
|
||||
def execute(self):
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/synthetic-source'), self.base)
|
||||
|
||||
def test_update_keeps_original_data_and_all_components(self):
|
||||
"""Fail if complete code replacement moves data, drops witnesses or rewrites operator settings."""
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['result'], 'updated')
|
||||
self.assertEqual(record['phase'], 'complete')
|
||||
self.assertEqual(set(record['gitlinks']), {'ISSSTELEON', 'WebApi', 'WebApp', 'models', 'indicadores_kit'})
|
||||
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), self.runtime.revision)
|
||||
self.assertEqual((Path(record['archive']) / 'codigo' / 'version.txt').read_text(), 'old')
|
||||
self.assertFalse((Path(record['archive']) / 'data').exists())
|
||||
self.assertEqual((self.root / '.archive' / 'previous' / 'data' / 'keep').read_text(), 'historical archive')
|
||||
config = json.loads((self.root / 'deploy' / 'docker-compose.yml').read_text())
|
||||
self.assertEqual(config['services']['webapi']['environment']['KEEP_THIS'], 'unchanged')
|
||||
self.assertNotIn('alembic', str(config['services']['webapi']['entrypoint']))
|
||||
self.assertEqual(config['services']['indicadores']['environment']['INDICADORES_AL_INICIAR'], '0')
|
||||
self.assertEqual(host.find_installation(self.base, 18080)['project'], self.record['project'])
|
||||
guard.restore_backup(Path(record['backup']), self.base / 'isolated-restore')
|
||||
|
||||
def test_same_revision_and_next_revision_preserve_witnesses(self):
|
||||
"""Fail if repeating a release or changing only code resets databases."""
|
||||
for revision in ('c' * 40, 'c' * 40, 'f' * 40):
|
||||
self.runtime.revision = revision
|
||||
self.execute()
|
||||
self.record = host.read_record(self.root)
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
with closing(guard.readonly(self.root / 'data' / 'cacu.db')) as connection:
|
||||
self.assertEqual(connection.execute('SELECT value FROM patient').fetchone()[0], 'SYNTHETIC-WITNESS')
|
||||
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
|
||||
|
||||
def test_missing_unknown_and_pending_sources_abort_before_stop(self):
|
||||
"""Fail if missing data or incompatible versions reach the quiescing phase."""
|
||||
for kind in ('missing', 'unknown', 'governance'):
|
||||
with self.subTest(kind=kind), tempfile.TemporaryDirectory() as tmp:
|
||||
root, contract, record = fixture(Path(tmp))
|
||||
runtime = SimulatedDeployment(root, contract, record)
|
||||
if kind == 'missing':
|
||||
(root / 'data' / 'tea.db').unlink()
|
||||
else:
|
||||
domain = 'governance' if kind == 'governance' else 'tea'
|
||||
version = 'd6b4f0e23a45' if kind == 'governance' else 'unknown'
|
||||
change(root, domain, "UPDATE alembic_version SET version_num='" + version + "'")
|
||||
with patch.object(conservative, 'guard', side_effect=runtime.guard), self.assertRaises(RuntimeError):
|
||||
conservative.update(runtime, record, 'helper', Path('/source'), Path(tmp))
|
||||
self.assertFalse(any('stop' in args for args in runtime.calls))
|
||||
self.assertEqual(host.read_record(root), record)
|
||||
self.assertFalse((root.parent / '.backups').exists())
|
||||
|
||||
def test_build_failure_and_changed_mount_do_not_touch_running_installation(self):
|
||||
"""Fail if preparation errors stop services or alter the installed record."""
|
||||
for failure in ('build', 'mount', 'space', 'backup-preparation'):
|
||||
self.runtime.fail = failure
|
||||
self.runtime.mount_changed = failure == 'mount'
|
||||
with self.subTest(failure=failure), self.assertRaises(RuntimeError):
|
||||
self.execute()
|
||||
self.assertFalse(any('stop' in args for args in self.runtime.calls))
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_backup_destinations_are_prepared_and_probed(self):
|
||||
"""Fail if destination preparation omits restore or leaves its write probe behind."""
|
||||
host.prepare_backup(self.base, self.record['project'], True)
|
||||
for name in ('.backups', '.restores'):
|
||||
directory = self.base / name / self.record['project']
|
||||
self.assertTrue(directory.is_dir())
|
||||
self.assertEqual(list(directory.iterdir()), [])
|
||||
|
||||
def test_invalid_backup_parent_does_not_stop_services(self):
|
||||
"""Fail if an unusable backup parent is discovered only after stopping services."""
|
||||
(self.base / '.backups').write_text('not a directory')
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.execute()
|
||||
self.assertFalse(any('stop' in args for args in self.runtime.calls))
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_cutover_failure_retains_backup_original_data_and_recovery_record(self):
|
||||
"""Fail if a startup failure loses storage or is recorded as a successful update."""
|
||||
self.runtime.fail = 'cutover'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during api'):
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['status'], 'update_failed')
|
||||
self.assertEqual(record['revision'], self.record['revision'])
|
||||
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
|
||||
guard.verify_backup(Path(record['backup']))
|
||||
self.assertTrue((Path(record['archive']) / 'deploy' / '.env').is_file())
|
||||
|
||||
def test_backup_failure_never_activates_candidate_code(self):
|
||||
"""Fail if an unverified backup allows code activation or loses the original payload."""
|
||||
self.runtime.fail = 'backup'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during backup'):
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['status'], 'update_failed')
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
|
||||
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
|
||||
self.assertFalse((self.root / '.updates').exists())
|
||||
self.assertIn(str(self.base / '.backups'), record['backup'])
|
||||
self.assertEqual(record['recovery'], 'original services verified; reconciliation required')
|
||||
self.assertTrue(all(self.runtime.running.values()))
|
||||
starts = [args[-1] for args in self.runtime.calls if args[:2] == ['docker', 'start']]
|
||||
self.assertEqual(starts, ['api', 'worker', 'app'])
|
||||
|
||||
def test_recovery_rejects_changed_container(self):
|
||||
"""Fail if a changed container is started or the failed installation is marked installed."""
|
||||
self.runtime.fail = 'backup'
|
||||
original_run = self.runtime.run
|
||||
def changed(args, **kwargs):
|
||||
output = original_run(args, **kwargs)
|
||||
if list(map(str, args))[:2] == ['docker', 'inspect'] and '--format' not in args:
|
||||
items = json.loads(output)
|
||||
if not any(self.runtime.running.values()):
|
||||
items[0]['Mounts'] = [{'Source': '/unexpected'}]
|
||||
return json.dumps(items)
|
||||
return output
|
||||
self.runtime.run = changed
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['status'], 'update_failed')
|
||||
self.assertIn('incomplete', record['recovery'])
|
||||
self.assertFalse(any(args[:2] == ['docker', 'start'] for args in self.runtime.calls))
|
||||
|
||||
def test_recovery_rejects_unverified_api_entrypoint(self):
|
||||
"""Fail if recovery restarts an API whose entrypoint could run migrations."""
|
||||
self.runtime.fail = 'backup'
|
||||
original_run = self.runtime.run
|
||||
def legacy(args, **kwargs):
|
||||
output = original_run(args, **kwargs)
|
||||
if list(map(str, args))[:2] == ['docker', 'inspect'] and '--format' not in args:
|
||||
items = json.loads(output)
|
||||
items[1]['Config']['Entrypoint'] = ['/app/entrypoint.sh']
|
||||
return json.dumps(items)
|
||||
return output
|
||||
self.runtime.run = legacy
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.execute()
|
||||
self.assertIn('incomplete', host.read_record(self.root)['recovery'])
|
||||
self.assertFalse(any(args[:2] == ['docker', 'start'] for args in self.runtime.calls))
|
||||
|
||||
def test_recovery_attempted_when_failure_record_cannot_be_saved(self):
|
||||
"""Fail if a record write error prevents original services from being restarted."""
|
||||
self.runtime.fail = 'backup'
|
||||
original = self.runtime.host_action
|
||||
def action(helper, name, project, value):
|
||||
if name == 'save' and json.loads(value)['status'] == 'update_failed':
|
||||
raise OSError('record write failed')
|
||||
return original(helper, name, project, value)
|
||||
self.runtime.host_action = action
|
||||
with self.assertRaisesRegex(RuntimeError, 'failure record could not be saved'):
|
||||
self.execute()
|
||||
self.assertTrue(all(self.runtime.running.values()))
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'updating')
|
||||
|
||||
def test_backup_helper_reports_safe_failure_metadata(self):
|
||||
"""Fail if a helper error loses its location or exposes stderr and command contents."""
|
||||
stderr = ('Traceback (most recent call last):\n'
|
||||
' File "<string>", line 320, in create_backup\n'
|
||||
" secret patient data\nPermissionError: [Errno 13] private-path\n")
|
||||
failure = subprocess.CalledProcessError(7, ['secret-command'], stderr=stderr)
|
||||
original = self.runtime.host_action
|
||||
|
||||
def action(helper, name, project, value):
|
||||
if name == 'backup':
|
||||
raise failure
|
||||
return original(helper, name, project, value)
|
||||
|
||||
self.runtime.host_action = action
|
||||
with self.assertRaises(RuntimeError) as raised:
|
||||
self.execute()
|
||||
message = str(raised.exception)
|
||||
self.assertIn('operation=create and verify backup in helper', message)
|
||||
self.assertIn('exit=7, location=create_backup:320, error type=PermissionError, errno=13', message)
|
||||
self.assertNotIn('patient', message)
|
||||
self.assertNotIn('private-path', message)
|
||||
self.assertNotIn('secret-command', message)
|
||||
self.assertIs(raised.exception.__context__, failure)
|
||||
self.assertTrue(raised.exception.__suppress_context__)
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
|
||||
|
||||
def test_guard_reports_safe_subprocess_metadata(self):
|
||||
"""Fail if the quiesced inspection drops the exit code or prints sensitive stderr."""
|
||||
failure = subprocess.CalledProcessError(3, ['private'], stderr='RuntimeError: patient secret')
|
||||
with patch.object(self.runtime, 'run', side_effect=failure), self.assertRaises(conservative.GuardFailure) as raised:
|
||||
conservative.guard(self.runtime, 'image', 'inspect', {})
|
||||
self.assertIn('exit=3, error type=RuntimeError', str(raised.exception))
|
||||
self.assertNotIn('patient secret', str(raised.exception))
|
||||
|
||||
def test_quiesced_rejection_reaches_update_error_without_activation(self):
|
||||
"""Fail if post-stop validation loses its safe reason or permits code activation."""
|
||||
calls = 0
|
||||
diagnostic = {'reason': 'schema_mismatch', 'domain': 'tea', 'type': 'RuntimeError',
|
||||
'sqlite': 'none', 'errno': None}
|
||||
failure = subprocess.CalledProcessError(1, ['private'], stderr=(
|
||||
'WN_INSPECT_DIAGNOSTIC=' + json.dumps(diagnostic) + '\nprivate patient secret'))
|
||||
|
||||
original_guard = conservative.guard
|
||||
def validate_with_transport(api, image, action, payload, data=None, **kwargs):
|
||||
nonlocal calls
|
||||
if action == 'inspect':
|
||||
calls += 1
|
||||
if calls == 2:
|
||||
adapter = types.SimpleNamespace(run=lambda *a, **kw: (_ for _ in ()).throw(failure))
|
||||
return original_guard(adapter, image, action, payload, data)
|
||||
return self.runtime.guard(api, image, action, payload, data, **kwargs)
|
||||
|
||||
with patch.object(conservative, 'guard', side_effect=validate_with_transport), \
|
||||
self.assertRaises(RuntimeError) as raised:
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base)
|
||||
self.assertIn('operation=inspect quiesced storage', str(raised.exception))
|
||||
self.assertIn('reason=schema_mismatch, domain=tea', str(raised.exception))
|
||||
self.assertNotIn('patient secret', str(raised.exception))
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
|
||||
self.assertFalse((self.root / '.updates').exists())
|
||||
|
||||
def test_guard_inspection_uses_existing_image_and_readonly_mount(self):
|
||||
"""Fail if a diagnostic inspection pulls an image or permits writes to storage."""
|
||||
with patch.object(self.runtime, 'run', return_value='{}') as run:
|
||||
conservative.guard(self.runtime, 'candidate', 'inspect', {}, self.base / 'data')
|
||||
args = run.call_args.args[0]
|
||||
self.assertEqual(args[args.index('--pull') + 1], 'never')
|
||||
self.assertEqual(args[args.index('--network') + 1], 'none')
|
||||
self.assertIn('--read-only', args)
|
||||
self.assertTrue(args[args.index('--mount') + 1].endswith(',dst=/data,readonly'))
|
||||
|
||||
def test_restore_helper_reports_safe_failure_metadata(self):
|
||||
"""Fail if isolated restore errors hide their location or expose helper stderr."""
|
||||
failure = subprocess.CalledProcessError(
|
||||
1, ['private'], stderr=' File "<string>", line 376, in restore_backup\n'
|
||||
'RuntimeError: secret filename\n')
|
||||
original = self.runtime.host_action
|
||||
|
||||
def action(helper, name, project, value):
|
||||
if name == 'verify-restore':
|
||||
raise failure
|
||||
return original(helper, name, project, value)
|
||||
|
||||
self.runtime.host_action = action
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
self.assertRaises(RuntimeError) as raised:
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base,
|
||||
verify_restore=True)
|
||||
self.assertIn('operation=restore and verify backup in helper', str(raised.exception))
|
||||
self.assertIn('exit=1, location=restore_backup:376, error type=RuntimeError', str(raised.exception))
|
||||
self.assertNotIn('secret filename', str(raised.exception))
|
||||
self.assertEqual(host.read_record(self.root)['phase'], 'restore-verification')
|
||||
|
||||
def test_trial_restore_is_verified_before_activation(self):
|
||||
"""Fail if a trial activates code before restoring and verifying its backup."""
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'):
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base,
|
||||
verify_restore=True)
|
||||
record = host.read_record(self.root)
|
||||
self.assertTrue((Path(record['restore_check']) / 'cacu.db').is_file())
|
||||
self.assertEqual(record['result'], 'updated')
|
||||
|
||||
def test_trial_restore_failure_keeps_old_code_and_backup(self):
|
||||
"""Fail if a rejected isolated restore can activate the replacement application."""
|
||||
self.runtime.fail = 'restore'
|
||||
with patch.object(conservative, 'guard', side_effect=self.runtime.guard), \
|
||||
patch.object(conservative, 'verify_api'), patch.object(conservative, 'freeze_failed'), \
|
||||
self.assertRaisesRegex(RuntimeError, 'restore-verification'):
|
||||
conservative.update(self.runtime, self.record, 'helper', Path('/source'), self.base,
|
||||
verify_restore=True)
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['status'], 'update_failed')
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
|
||||
self.assertEqual(guard.identity(self.root / 'data'), self.original_identity)
|
||||
guard.verify_backup(Path(record['backup']))
|
||||
self.assertFalse((self.root / '.updates').exists())
|
||||
|
||||
def test_custom_connection_is_rejected_before_build_or_stop(self):
|
||||
"""Fail if a custom database connection is redirected to the managed SQLite layout."""
|
||||
self.runtime.env['TEA_DATABASE_URL'] = 'sqlite:////custom/tea.db'
|
||||
with self.assertRaisesRegex(RuntimeError, 'during preparing'):
|
||||
self.execute()
|
||||
self.assertFalse(any('stop' in args or 'build' in args for args in self.runtime.calls))
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_worker_cannot_turn_clinical_loss_into_success(self):
|
||||
"""Fail if successful health/recalculation responses hide changed protected patient values."""
|
||||
self.runtime.fail = 'worker'
|
||||
with self.assertRaisesRegex(RuntimeError, 'operation=verify-persistence'):
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record['status'], 'update_failed')
|
||||
restored = self.base / 'recoverable'
|
||||
guard.restore_backup(Path(record['backup']), restored)
|
||||
with closing(guard.readonly(restored / 'tea.db')) as connection:
|
||||
self.assertEqual(connection.execute('SELECT value FROM patient').fetchone()[0], 'SYNTHETIC-WITNESS')
|
||||
|
||||
def test_recalculation_step_categories_and_no_retry(self):
|
||||
"""Fail if any recalculation step loses its category, exposes details, or repeats a write."""
|
||||
deploy = self.base / 'steps'
|
||||
deploy.mkdir()
|
||||
config = deploy / 'docker-compose.yml'
|
||||
for step in ('load-configuration', 'execute-recalculation', 'validate-result', 'verify-persistence'):
|
||||
with self.subTest(step=step):
|
||||
config.write_text('invalid private secret' if step == 'load-configuration' else
|
||||
json.dumps({'services': {'indicadores': {'environment': {}}}}))
|
||||
calls = []
|
||||
def run_guard(api, image, action, payload, data=None, **kwargs):
|
||||
calls.append(action)
|
||||
if action == 'recalculate':
|
||||
if step == 'execute-recalculation':
|
||||
raise conservative.GuardFailure('recalculate', 'exit=1, type=OperationalError')
|
||||
if step == 'validate-result':
|
||||
return {'completed': ['cacu']}
|
||||
return {'completed': ['cacu', 'cama', 'tea']}
|
||||
if action == 'verify' and payload.get('derived') and step == 'verify-persistence':
|
||||
raise conservative.GuardFailure('verify', 'exit=1, type=DatabaseError')
|
||||
return {}
|
||||
with patch.object(conservative, 'verify_api'), patch.object(conservative, 'guard', side_effect=run_guard), \
|
||||
self.assertRaises(conservative.RecalculationFailure) as raised:
|
||||
conservative.finish(types.SimpleNamespace(run=lambda *a: ''), [], 'image',
|
||||
deploy, self.root / 'data', {}, {})
|
||||
self.assertEqual(raised.exception.step, step)
|
||||
self.assertNotIn('private secret', raised.exception.category)
|
||||
self.assertLessEqual(calls.count('recalculate'), 1)
|
||||
|
||||
def test_guard_transport_is_readonly_and_has_no_application_entrypoint(self):
|
||||
"""Fail if compatibility inspection starts the image entrypoint or permits storage writes."""
|
||||
calls = []
|
||||
adapter = types.SimpleNamespace(run=lambda args, **kwargs: calls.append((args, kwargs)) or '{}')
|
||||
conservative.guard(adapter, 'image', 'inspect', {'contract': {}}, Path('/srv/data'))
|
||||
args, kwargs = calls[0]
|
||||
self.assertIn('type=bind,src=' + str(Path('/srv/data')) + ',dst=/data,readonly', args)
|
||||
self.assertIn('--read-only', args)
|
||||
self.assertEqual(args[args.index('--entrypoint') + 1], '/app/WebApi/.venv/bin/python')
|
||||
self.assertIn('contract', kwargs['stdin'])
|
||||
|
||||
def test_resolved_worker_environment_keeps_literal_values(self):
|
||||
"""Fail if Compose or docker env-file quoting changes a retained worker value."""
|
||||
deploy = self.base / 'resolved'
|
||||
deploy.mkdir()
|
||||
environment = {**conservative.PERSISTENT_ENV, 'TOKEN': "literal $value and 'quotes'"}
|
||||
conservative.persist_config(deploy, {'services': {'indicadores': {'environment': environment}}})
|
||||
document = json.loads((deploy / 'docker-compose.yml').read_text())
|
||||
self.assertEqual(document['services']['indicadores']['environment']['TOKEN'], "literal $$value and 'quotes'")
|
||||
calls = []
|
||||
|
||||
def guard_call(api, image, action, payload, data=None, **kwargs):
|
||||
if action == 'verify':
|
||||
self.assertTrue(kwargs.get('writable'), 'live SQLite requires writable WAL coordination')
|
||||
calls.append((action, payload))
|
||||
return {'completed': ['cacu', 'cama', 'tea']} if action == 'recalculate' else {}
|
||||
|
||||
with patch.object(conservative, 'verify_api'), patch.object(conservative, 'guard', side_effect=guard_call):
|
||||
conservative.finish(types.SimpleNamespace(run=lambda args: ''), ['compose'], 'image',
|
||||
deploy, self.root / 'data', {}, {})
|
||||
recalc = next(payload for action, payload in calls if action == 'recalculate')
|
||||
self.assertEqual(recalc['environment'], environment)
|
||||
|
||||
def test_failure_containment_checks_ownership_before_stopping(self):
|
||||
"""Fail if uncertain ownership or mounts can stop a foreign container during recovery."""
|
||||
calls = []
|
||||
item = {'Config': {'Labels': {'com.docker.compose.project': self.record['project'],
|
||||
'com.docker.compose.service': 'webapi'}},
|
||||
'Mounts': [{'Type': 'bind', 'Source': '/foreign', 'Destination': '/data'}]}
|
||||
|
||||
def run(args):
|
||||
calls.append(args)
|
||||
return json.dumps([item]) if args[:2] == ['docker', 'inspect'] else 'candidate\n'
|
||||
|
||||
adapter = types.SimpleNamespace(run=run)
|
||||
with self.assertRaisesRegex(RuntimeError, 'storage is uncertain'):
|
||||
conservative.freeze_failed(adapter, ['compose'], self.record['project'], self.root / 'data')
|
||||
self.assertFalse(any('stop' in args for args in calls))
|
||||
item['Mounts'][0]['Source'] = str(self.root / 'data')
|
||||
conservative.freeze_failed(adapter, ['compose'], self.record['project'], self.root / 'data')
|
||||
self.assertIn(['docker', 'stop', 'candidate'], calls)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,342 @@
|
||||
"""Loading the simulated hospital into an installed instance, against the in-memory daemon of test_installer.py.
|
||||
|
||||
Fixtures: `LoadCase` extends `FlowCase` with a stand-in for the Git fetches of the loader sources, a loader that
|
||||
prints one count line per table and a hospital check that reports two tables per project (`good_hospital`); each
|
||||
test starts from an instance installed on port 18083.
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import dataload
|
||||
import fakedocker
|
||||
import registry
|
||||
from test_installer import BASE, FlowCase
|
||||
|
||||
LOADER_OUTPUT = ('Paciente: 300 leídas, 300 nuevas, 0 actualizadas, 0 rechazadas\n'
|
||||
'Citologia: 779 leídas, 779 nuevas, 0 actualizadas, 0 rechazadas\n')
|
||||
|
||||
|
||||
def good_hospital(**changes):
|
||||
"""What the hospital check prints for a hospital that has, per project, the tables of LOADER_OUTPUT with rows;
|
||||
`changes` maps a project to the entry that replaces its own."""
|
||||
tables = {'paciente': {'target': 'Paciente', 'exists': True, 'rows': 300, 'missing_columns': []},
|
||||
'citologia': {'target': 'Citologia', 'exists': True, 'rows': 779, 'missing_columns': []}}
|
||||
report = {name: {'database': database, 'tables': json.loads(json.dumps(tables))}
|
||||
for name, database in dataload.PROJECTS}
|
||||
report.update(changes)
|
||||
return report
|
||||
|
||||
|
||||
class LoadCase(FlowCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.fetched = []
|
||||
self.hospital = good_hospital()
|
||||
self.docker.loader_output = lambda args: LOADER_OUTPUT
|
||||
self.docker.hospital_report = lambda args: json.dumps(self.hospital)
|
||||
for module, name, value in ((dataload, 'fetch_tree', self.fetch_tree), (dataload.time, 'sleep', lambda s: None)):
|
||||
patcher = patch.object(module, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
self.install(18083)
|
||||
|
||||
def fetch_tree(self, remote, commit, directory, paths=()):
|
||||
self.fetched.append((remote, commit, tuple(paths)))
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / 'Dockerfile').write_text('FROM scratch')
|
||||
|
||||
def load(self, confirmation='', hospital='10.0.10.41:9505', port=18083):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
dataload.run_load(str(port), hospital, confirmation, base=BASE, host_factory=self.host)
|
||||
return out.getvalue()
|
||||
|
||||
def load_token(self, **kwargs):
|
||||
return re.search(r'confirmacion=(\S+)', self.load(**kwargs)).group(1)
|
||||
|
||||
def synthetic(self):
|
||||
return (self.record(18083) or {}).get('synthetic_data')
|
||||
|
||||
|
||||
class HospitalAddressTests(unittest.TestCase):
|
||||
def test_only_host_and_port_are_accepted(self):
|
||||
"""Fails if a URL, credentials, a path or an out-of-range port can be passed as the hospital address."""
|
||||
for good in ('10.0.10.41:9505', 'hospital.example:3306', 'h:1'):
|
||||
self.assertEqual(dataload.validate_hospital(good), good)
|
||||
for bad in ('', 'host', 'mysql://host:3306', 'user:pw@host:3306', 'host:0', 'host:70000', 'host:3306/db',
|
||||
'ho st:3306', '-host:3306'):
|
||||
with self.subTest(bad), self.assertRaises(ValueError):
|
||||
dataload.validate_hospital(bad)
|
||||
|
||||
|
||||
class PlanTests(LoadCase):
|
||||
def test_plan_changes_nothing_and_is_bound_to_the_pins_and_the_hospital(self):
|
||||
"""Fails if planning builds or runs anything, or one confirmation is valid for another hospital."""
|
||||
self.docker.calls.clear()
|
||||
token = self.load_token()
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
self.assertEqual(self.host.entered[-1], False)
|
||||
self.assertIsNone(self.synthetic())
|
||||
self.assertNotEqual(token, self.load_token(hospital='10.0.10.42:9505'))
|
||||
|
||||
def test_plan_refuses_what_is_not_a_clean_installed_dev_instance(self):
|
||||
"""Fails if the load can be planned for an unregistered, protected, failed, loaded or busy instance."""
|
||||
record = self.record(18083)
|
||||
with self.assertRaisesRegex(RuntimeError, 'no installation is registered'):
|
||||
self.load(port=18110)
|
||||
for port in (18090, 18096, 18097):
|
||||
with self.subTest(port), self.assertRaisesRegex(ValueError, 'protected'):
|
||||
self.load(port=port)
|
||||
with self.assertRaisesRegex(ValueError, 'protected'):
|
||||
self.load(port=18087)
|
||||
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', dict(record, status='failed'))
|
||||
with self.assertRaisesRegex(RuntimeError, 'not installed'):
|
||||
self.load()
|
||||
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', dict(record, synthetic_data={'status': 'loaded'}))
|
||||
with self.assertRaisesRegex(RuntimeError, 'already has a simulated-hospital load'):
|
||||
self.load()
|
||||
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', dict(record, installer='someone-else'))
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
|
||||
self.load()
|
||||
|
||||
def test_plan_refuses_an_instance_that_already_has_import_attempts(self):
|
||||
"""Fails if a platform that was already imported into is treated as empty."""
|
||||
self.host.responses['/reportes/importaciones'] = {'status': 200, 'body': '{"intentos": [{"operacion": "carga"}]}'}
|
||||
with self.assertRaisesRegex(RuntimeError, 'import attempts'):
|
||||
self.load()
|
||||
|
||||
def test_plan_refuses_an_instance_that_is_not_running(self):
|
||||
"""Fails if a stopped or altered instance is loaded."""
|
||||
for container in self.docker.containers.values():
|
||||
container['State'] = {'Status': 'exited'}
|
||||
with self.assertRaisesRegex(RuntimeError, 'is not running'):
|
||||
self.load()
|
||||
|
||||
def test_plan_refuses_an_unreachable_hospital(self):
|
||||
"""Fails if a hospital the host cannot reach is accepted, so the failure would come after building."""
|
||||
self.host.unreachable.add('10.0.10.41:9505')
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not accept connections'):
|
||||
self.load()
|
||||
|
||||
def test_plan_refuses_a_record_without_the_dev_data_pin(self):
|
||||
"""Fails if a load can proceed without the commit of the generator to build."""
|
||||
record = self.record(18083)
|
||||
record['gitlinks'] = {k: v for k, v in record['gitlinks'].items() if k != 'dev-data'}
|
||||
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not pin dev-data'):
|
||||
self.load()
|
||||
|
||||
|
||||
class ExecuteTests(LoadCase):
|
||||
def test_confirmed_load_builds_the_pinned_loader_and_records_the_result(self):
|
||||
"""Fails if the loader is built from anything but the pinned commits, or the outcome is not recorded."""
|
||||
token = self.load_token()
|
||||
self.docker.calls.clear()
|
||||
self.load(token)
|
||||
record = self.synthetic()
|
||||
self.assertEqual(record['status'], 'loaded')
|
||||
self.assertEqual(record['hospital'], '10.0.10.41:9505')
|
||||
self.assertEqual(record['counts']['cacu']['Paciente']['total'], 300)
|
||||
self.assertEqual(record['indicators'], {'cacu': 'ok', 'cama': 'ok', 'tea': 'ok'})
|
||||
gitlinks = self.record(18083)['gitlinks']
|
||||
self.assertEqual(self.fetched, [(dataload.DEV_DATA_REMOTE, gitlinks['dev-data'], ()),
|
||||
(dataload.APPLICATION_REMOTE, gitlinks['ISSSTELEON'], ('Core',))])
|
||||
verbs = [c[1] for c in self.docker.mutating()]
|
||||
self.assertEqual(verbs, ['build', 'run', 'run', 'run', 'run'])
|
||||
runs = [c for c in self.docker.calls if c[1] == 'run']
|
||||
self.assertTrue(all('--rm' in c and '--network' in c for c in runs))
|
||||
self.assertNotIn('cargar', runs[0])
|
||||
self.assertEqual([c[c.index('cargar') + 1] for c in runs[1:]], ['cacu', 'cama', 'tea'])
|
||||
|
||||
def test_wrong_confirmation_loads_nothing(self):
|
||||
"""Fails if a confirmation that is not the plan's starts a build or a load."""
|
||||
self.docker.calls.clear()
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
|
||||
self.load('cargar-18083-0000000000000000')
|
||||
with self.assertRaises(ValueError):
|
||||
self.load('instalar-18083-0000000000000000')
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
self.assertIsNone(self.synthetic())
|
||||
|
||||
def test_loader_failure_is_visible_and_blocks_a_second_load(self):
|
||||
"""Fails if a failed stage is swallowed, or a half-loaded instance can be loaded again."""
|
||||
token = self.load_token()
|
||||
|
||||
def fail(args):
|
||||
raise fakedocker.failure(args, 'POST /imports/commit: 500 boom')
|
||||
self.docker.loader_output = fail
|
||||
with self.assertRaisesRegex(RuntimeError, 'the load failed.*the loader failed for cacu.*boom.*reinstall'):
|
||||
self.load(token)
|
||||
self.assertEqual(self.synthetic()['status'], 'failed')
|
||||
self.assertIn('boom', self.synthetic()['error'])
|
||||
with self.assertRaisesRegex(RuntimeError, 'already has a simulated-hospital load'):
|
||||
self.load()
|
||||
|
||||
def test_rejected_rows_and_empty_hospitals_fail_the_load(self):
|
||||
"""Fails if a load with rejected rows, or from a hospital with no rows, is reported as complete."""
|
||||
for output, message in (('Paciente: 3 leídas, 2 nuevas, 0 actualizadas, 1 rechazadas\n'
|
||||
'Citologia: 1 leídas, 1 nuevas, 0 actualizadas, 0 rechazadas\n', 'rows were rejected'),
|
||||
('Paciente: 0 leídas, 0 nuevas, 0 actualizadas, 0 rechazadas\n'
|
||||
'Citologia: 0 leídas, 0 nuevas, 0 actualizadas, 0 rechazadas\n', 'no rows to load'),
|
||||
('nothing useful\n', 'printed no table counts')):
|
||||
with self.subTest(message):
|
||||
self.setUp()
|
||||
token = self.load_token()
|
||||
self.docker.loader_output = lambda args, o=output: o
|
||||
with self.assertRaisesRegex(RuntimeError, message):
|
||||
self.load(token)
|
||||
self.assertEqual(self.synthetic()['status'], 'failed')
|
||||
|
||||
def test_indicator_recalculation_error_fails_the_load(self):
|
||||
"""Fails if the load is reported complete while a domain's recalculation ended in error."""
|
||||
token = self.load_token()
|
||||
self.host.responses['/reportes/indicadores'] = {'status': 200, 'body': json.dumps({
|
||||
'cacu': {'estado': 'ok'}, 'cama': {'estado': 'error', 'error': {'tipo': 'ValueError'}},
|
||||
'tea': {'estado': 'ok'}})}
|
||||
with self.assertRaisesRegex(RuntimeError, 'recalculation failed'):
|
||||
self.load(token)
|
||||
self.assertEqual(self.synthetic()['status'], 'failed')
|
||||
|
||||
def test_recalculation_that_never_finishes_fails_the_load(self):
|
||||
"""Fails if the load waits forever, or succeeds, while a domain is still pending."""
|
||||
token = self.load_token()
|
||||
self.host.responses['/reportes/indicadores'] = {'status': 200, 'body': json.dumps({
|
||||
d: {'estado': 'en_curso', 'pendiente': True} for d in ('cacu', 'cama', 'tea')})}
|
||||
times = iter([0, 1, 5000])
|
||||
with patch.object(dataload.time, 'monotonic', lambda: next(times)), \
|
||||
self.assertRaisesRegex(RuntimeError, 'did not finish'):
|
||||
self.load(token)
|
||||
|
||||
def test_load_touches_no_installation_resource(self):
|
||||
"""Fails if the load stops, removes or recreates any container, volume or network of the instance."""
|
||||
before = (sorted(self.docker.containers), sorted(self.docker.volumes), sorted(self.docker.networks))
|
||||
self.docker.calls.clear()
|
||||
self.load(self.load_token())
|
||||
self.assertEqual((sorted(self.docker.containers), sorted(self.docker.volumes), sorted(self.docker.networks)), before)
|
||||
self.assertEqual([c[1] for c in self.docker.mutating()], ['build', 'run', 'run', 'run', 'run'])
|
||||
self.assertNotIn('hospital:hospital', json.dumps(self.synthetic()))
|
||||
|
||||
|
||||
class HospitalCheckTests(LoadCase):
|
||||
"""The hospital is read before anything is written to the platform, and every table is verified after."""
|
||||
|
||||
def writes(self):
|
||||
"""The loader runs (the commands that import into the platform)."""
|
||||
return [c for c in self.docker.calls if c[1] == 'run' and 'cargar' in c]
|
||||
|
||||
def attempt(self):
|
||||
"""The instance record the registry holds."""
|
||||
return self.record(18083)
|
||||
|
||||
def test_a_hospital_with_the_old_schema_is_refused_before_anything_is_written(self):
|
||||
"""Fails if a hospital that lacks a table of the pinned generator (the schema before the TEA redesign) is
|
||||
loaded, if refusing it leaves the instance marked so that it cannot be tried again, or if the refusal is
|
||||
not recorded on the instance."""
|
||||
token = self.load_token()
|
||||
del self.hospital['tea']['tables']['citologia']
|
||||
self.hospital['tea']['tables']['mchat'] = {'target': 'tea.Mchat', 'exists': False, 'rows': None,
|
||||
'missing_columns': []}
|
||||
with self.assertRaisesRegex(RuntimeError, 'did not start.*table mchat is missing from hospital'):
|
||||
self.load(token)
|
||||
self.assertEqual(self.writes(), [])
|
||||
self.assertIsNone(self.synthetic())
|
||||
record = self.attempt()
|
||||
self.assertEqual(record['status'], 'installed')
|
||||
self.assertEqual(record['load_attempt']['status'], 'not_started')
|
||||
self.assertIn('table mchat is missing', record['load_attempt']['error'])
|
||||
self.assertEqual(record['load_attempt']['hospital'], '10.0.10.41:9505')
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
|
||||
self.load(token)
|
||||
self.hospital = good_hospital()
|
||||
self.load(self.load_token())
|
||||
self.assertEqual(self.synthetic()['status'], 'loaded')
|
||||
self.assertEqual(self.attempt()['status'], 'installed')
|
||||
|
||||
def test_a_loader_that_cannot_be_built_leaves_the_instance_clean_and_recorded(self):
|
||||
"""Fails if a failed build of the loader marks the instance as loaded or failed, blocks a retry, or goes
|
||||
unrecorded."""
|
||||
token = self.load_token()
|
||||
good_fetch = self.fetch_tree
|
||||
|
||||
def broken(remote, commit, directory, paths=()):
|
||||
raise RuntimeError('git fetch failed: network unreachable')
|
||||
with patch.object(dataload, 'fetch_tree', broken), \
|
||||
self.assertRaisesRegex(RuntimeError, 'did not start.*network unreachable'):
|
||||
self.load(token)
|
||||
self.assertIsNone(self.synthetic())
|
||||
self.assertEqual(self.attempt()['status'], 'installed')
|
||||
self.assertIn('network unreachable', self.attempt()['load_attempt']['error'])
|
||||
self.assertEqual(self.writes(), [])
|
||||
with patch.object(dataload, 'fetch_tree', good_fetch):
|
||||
self.load(self.load_token())
|
||||
self.assertEqual(self.synthetic()['status'], 'loaded')
|
||||
|
||||
def test_missing_columns_unreadable_databases_and_empty_projects_are_refused(self):
|
||||
"""Fails if a table with a column the generator expects missing, a database the check cannot read or a
|
||||
project whose tables are all empty gets through to the loader."""
|
||||
cases = {
|
||||
'lacks the columns ord_pdf_blob': {'cacu': dict(self.hospital['cacu'], tables={
|
||||
'paciente': {'target': 'Paciente', 'exists': True, 'rows': 3, 'missing_columns': ['ord_pdf_blob']}})},
|
||||
'cannot be read': {'cama': {'database': 'hospital_cama', 'error': 'OperationalError: unknown database'}},
|
||||
'hospital has no rows': {'tea': dict(self.hospital['tea'], tables={
|
||||
'paciente': {'target': 'Paciente', 'exists': True, 'rows': 0, 'missing_columns': []}})},
|
||||
}
|
||||
for message, change in cases.items():
|
||||
with self.subTest(message):
|
||||
token = self.load_token()
|
||||
self.hospital = good_hospital(**change)
|
||||
with self.assertRaisesRegex(RuntimeError, message):
|
||||
self.load(token)
|
||||
self.assertEqual(self.writes(), [])
|
||||
self.assertIsNone(self.synthetic())
|
||||
|
||||
def test_an_empty_table_in_a_populated_project_is_recorded_and_does_not_stop_the_load(self):
|
||||
"""Fails if a table that legitimately has no rows (small hospitals) blocks the load, or goes unrecorded."""
|
||||
self.hospital['cacu']['tables']['citologia']['rows'] = 0
|
||||
self.load(self.load_token())
|
||||
self.assertEqual(self.synthetic()['status'], 'loaded')
|
||||
self.assertEqual(self.synthetic()['empty_tables'], ['Citologia'])
|
||||
|
||||
def test_a_table_the_loader_never_reported_fails_the_load(self):
|
||||
"""Fails if a project is accepted when the loader printed counts for only some of the tables the generator
|
||||
has, which is how a load that skipped a table would look."""
|
||||
token = self.load_token()
|
||||
self.docker.loader_output = lambda args: 'Paciente: 300 leídas, 300 nuevas, 0 actualizadas, 0 rechazadas\n'
|
||||
with self.assertRaisesRegex(RuntimeError, 'reported no counts for Citologia'):
|
||||
self.load(token)
|
||||
self.assertEqual(self.synthetic()['status'], 'failed')
|
||||
|
||||
def test_rows_read_but_not_stored_fail_the_load(self):
|
||||
"""Fails if a table that read more rows than it created or updated, with no rejection, counts as loaded."""
|
||||
token = self.load_token()
|
||||
self.docker.loader_output = lambda args: ('Paciente: 300 leídas, 290 nuevas, 0 actualizadas, 0 rechazadas\n'
|
||||
'Citologia: 779 leídas, 779 nuevas, 0 actualizadas, 0 rechazadas\n')
|
||||
with self.assertRaisesRegex(RuntimeError, r'read but not stored.*Paciente.*10'):
|
||||
self.load(token)
|
||||
self.assertEqual(self.synthetic()['status'], 'failed')
|
||||
|
||||
def test_a_hospital_check_that_prints_no_report_is_refused(self):
|
||||
"""Fails if a check that crashed or printed nothing is read as a clean hospital."""
|
||||
token = self.load_token()
|
||||
self.docker.hospital_report = lambda args: ''
|
||||
with self.assertRaisesRegex(RuntimeError, 'printed no report'):
|
||||
self.load(token)
|
||||
self.assertEqual(self.writes(), [])
|
||||
self.assertIsNone(self.synthetic())
|
||||
token = self.load_token()
|
||||
|
||||
def crash(args):
|
||||
raise fakedocker.failure(args, 'pymysql.err.OperationalError: connection refused')
|
||||
self.docker.hospital_report = crash
|
||||
with self.assertRaisesRegex(RuntimeError, 'could not be read.*connection refused'):
|
||||
self.load(token)
|
||||
self.assertIsNone(self.synthetic())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,257 +0,0 @@
|
||||
"""Exercise the workflow entrypoint with synthetic SQLite data and a fake daemon.
|
||||
|
||||
The update adapter uses real registry, backup, activation and preservation checks.
|
||||
All Docker, host port probes and application processes are substituted locally.
|
||||
"""
|
||||
|
||||
from contextlib import ExitStack
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import conservative
|
||||
import data_guard
|
||||
import dev
|
||||
import host
|
||||
from test_conservative import SimulatedDeployment, change, fixture
|
||||
|
||||
|
||||
class AutomaticDeploymentTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
"""Create a named installation whose identity is independent of its public port."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.root, self.contract, self.record = fixture(self.base, 'isssteleon-clinic-west', 23456)
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
|
||||
def execute(self):
|
||||
"""Invoke exactly the automatic command used by deploy-dev with no real daemon."""
|
||||
with ExitStack() as stack:
|
||||
for name in ('git', 'export_tree', 'pinned_manifest', 'run', 'host_action',
|
||||
'copy_to_host', 'verify_existing_containers', 'verify_services'):
|
||||
stack.enter_context(patch.object(dev, name, side_effect=getattr(self.runtime, name)))
|
||||
stack.enter_context(patch.object(dev, 'start_helper', return_value='owned-helper'))
|
||||
stack.enter_context(patch.object(conservative, 'guard', side_effect=self.runtime.guard))
|
||||
stack.enter_context(patch.object(conservative, 'verify_api'))
|
||||
stack.enter_context(patch.object(conservative, 'freeze_failed'))
|
||||
install = stack.enter_context(patch.object(dev, 'install', side_effect=AssertionError('unexpected install')))
|
||||
try:
|
||||
dev.install_auto(str(self.record['port']), Path('/synthetic-source'), self.base)
|
||||
finally:
|
||||
install.assert_not_called()
|
||||
self.assertEqual(self.runtime.calls[-1], ['docker', 'rm', '-f', 'owned-helper'])
|
||||
|
||||
def select_same_revision(self):
|
||||
"""Record a complete pinned manifest and completed work for an already installed release."""
|
||||
self.record.update(revision=self.runtime.revision, phase='complete', recalculation='complete',
|
||||
gitlinks=self.runtime.pinned_manifest(None, 'd' * 40))
|
||||
host.write_record(self.root, self.record)
|
||||
|
||||
def test_registered_port_updates_preserving_data_and_provenance(self):
|
||||
"""Fail if automatic dispatch resets storage or records images unrelated to its candidate."""
|
||||
before = data_guard.storage_state(self.root / 'data', self.contract)
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
data_guard.verify_state(self.root / 'data', self.contract, before, derived=True)
|
||||
self.assertEqual((record['project'], record['port']), ('isssteleon-clinic-west', 23456))
|
||||
self.assertEqual((record['revision'], record['target_revision']), (self.runtime.revision,) * 2)
|
||||
self.assertEqual(record['gitlinks'], self.runtime.pinned_manifest(None, 'd' * 40))
|
||||
self.assertEqual(record['gitlinks'], record['target_gitlinks'])
|
||||
builds = [args[args.index('-t') + 1] for args in self.runtime.calls if args[:2] == ['docker', 'build']]
|
||||
self.assertEqual(record['images'], builds)
|
||||
self.assertEqual(record['images'], record['target_images'])
|
||||
self.assertTrue(all(self.runtime.revision[:12] in image for image in builds))
|
||||
config = json.loads((self.root / 'deploy' / 'docker-compose.yml').read_text())
|
||||
self.assertEqual(config['services']['webapi']['image'], builds[0])
|
||||
self.assertEqual(config['services']['indicadores']['image'], builds[0])
|
||||
self.assertEqual(config['services']['webapp']['image'], builds[1])
|
||||
self.assertEqual((record['status'], record['result'], record['recalculation']),
|
||||
('installed', 'updated', 'complete'))
|
||||
|
||||
def test_same_revision_verifies_without_build_backup_restart_or_recalculation(self):
|
||||
"""Fail if a repeated release rebuilds, archives, recalculates or changes persistent bytes."""
|
||||
self.select_same_revision()
|
||||
before = {str(p.relative_to(self.root)): p.read_bytes() for p in self.root.rglob('*')
|
||||
if p.is_file() and p.name != 'installation.json'}
|
||||
self.execute()
|
||||
record = host.read_record(self.root)
|
||||
self.assertEqual(record, dict(self.record, result='unchanged', verification='complete'))
|
||||
self.assertFalse(self.runtime.finished)
|
||||
self.assertFalse((self.base / '.backups').exists())
|
||||
self.assertFalse(any('build' in args or 'stop' in args or 'up' in args or 'update' in args
|
||||
for args in self.runtime.calls))
|
||||
self.assertEqual(before, {str(p.relative_to(self.root)): p.read_bytes() for p in self.root.rglob('*')
|
||||
if p.is_file() and p.name != 'installation.json'})
|
||||
|
||||
def test_same_revision_rejects_mismatching_gitlinks(self):
|
||||
"""Fail if the outer SHA alone can hide inconsistent installed recursive gitlinks."""
|
||||
self.select_same_revision()
|
||||
self.record['gitlinks']['WebApi'] = '9' * 40
|
||||
host.write_record(self.root, self.record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'same-revision-verification'):
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
def test_same_revision_checks_storage_and_health_before_success(self):
|
||||
"""Fail if a repeated release skips schema, image, configuration or service verification."""
|
||||
self.select_same_revision()
|
||||
for problem in ('schema', 'health', 'image', 'configuration'):
|
||||
with self.subTest(problem=problem):
|
||||
original = self.runtime.verify_services
|
||||
if problem == 'schema':
|
||||
change(self.root, 'tea', "UPDATE alembic_version SET version_num='unknown'")
|
||||
elif problem == 'health':
|
||||
def unhealthy(*args):
|
||||
raise RuntimeError('unhealthy')
|
||||
self.runtime.verify_services = unhealthy
|
||||
elif problem == 'image':
|
||||
self.runtime.mount_changed = True
|
||||
else:
|
||||
self.runtime.env['CACU_DATABASE_URL'] = 'sqlite:////elsewhere/private.db'
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
self.assertFalse(any('stop' in args or 'build' in args for args in self.runtime.calls))
|
||||
change(self.root, 'tea', "UPDATE alembic_version SET version_num='" + self.contract['tea']['head'] + "'")
|
||||
self.runtime.verify_services = original
|
||||
self.runtime.mount_changed = False
|
||||
self.runtime.env['CACU_DATABASE_URL'] = conservative.PERSISTENT_ENV['CACU_DATABASE_URL']
|
||||
|
||||
def test_recovery_states_never_fall_back_to_installation(self):
|
||||
"""Fail if any interrupted or failed state is automatically retried or recreated."""
|
||||
for status in ('preparing', 'building', 'starting', 'failed', 'updating', 'update_failed',
|
||||
'replacing', 'replace_failed'):
|
||||
with self.subTest(status=status):
|
||||
record = dict(self.record, status=status)
|
||||
host.write_record(self.root, record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'not installed'):
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root), record)
|
||||
|
||||
def test_inconsistent_provenance_is_rejected_before_build_or_stop(self):
|
||||
"""Fail if a nominally installed record with missing or invalid provenance reaches Docker writes."""
|
||||
for fields in ({'revision': 'unknown'}, {'gitlinks': {}}, {'gitlinks': {'ISSSTELEON': 'bad'}}):
|
||||
with self.subTest(fields=fields):
|
||||
record = dict(self.record, **fields)
|
||||
host.write_record(self.root, record)
|
||||
with self.assertRaisesRegex(RuntimeError, 'Git provenance is invalid'):
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root), record)
|
||||
|
||||
def test_incompatible_candidate_never_recreates_or_stops_instance(self):
|
||||
"""Fail if a pending migration at the public entrypoint reaches backup, cutover or installation."""
|
||||
change(self.root, 'governance', "UPDATE alembic_version SET version_num='d6b4f0e23a45'")
|
||||
with self.assertRaisesRegex(RuntimeError, 'compatibility'):
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
self.assertFalse(any('stop' in args for args in self.runtime.calls))
|
||||
self.assertFalse((self.base / '.backups').exists())
|
||||
|
||||
def test_compatibility_rejection_exposes_only_safe_reason(self):
|
||||
"""Fail if the public update loses the candidate's allowlisted compatibility diagnostic."""
|
||||
original = self.runtime.guard
|
||||
def reject(api, image, action, payload, *args, **kwargs):
|
||||
if action == 'inspect':
|
||||
raise conservative.GuardFailure('inspect', 'reason=migration_pending, domain=governance')
|
||||
return original(api, image, action, payload, *args, **kwargs)
|
||||
self.runtime.guard = reject
|
||||
with self.assertRaisesRegex(RuntimeError, 'reason=migration_pending, domain=governance'):
|
||||
self.execute()
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
self.assertFalse(any('stop' in args for args in self.runtime.calls))
|
||||
|
||||
def test_candidate_failure_never_retries_as_a_fresh_install(self):
|
||||
"""Fail if build, backup, activation or recalculation failure triggers destructive fallback."""
|
||||
for failure in ('build', 'backup', 'cutover', 'worker'):
|
||||
with self.subTest(failure=failure), tempfile.TemporaryDirectory() as tmp:
|
||||
self.base = Path(tmp)
|
||||
self.root, self.contract, self.record = fixture(self.base, 'isssteleon-another', 31567)
|
||||
self.runtime = SimulatedDeployment(self.root, self.contract, self.record)
|
||||
self.runtime.fail = failure
|
||||
identity = data_guard.identity(self.root / 'data')
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.execute()
|
||||
self.assertEqual(data_guard.identity(self.root / 'data'), identity)
|
||||
self.assertFalse(any('down' in args or 'prune' in args for args in self.runtime.calls))
|
||||
|
||||
def test_unregistered_host_port_conflict_never_reserves_or_installs(self):
|
||||
"""Fail if a foreign non-Docker listener permits a new installation or skips lock cleanup."""
|
||||
actions = []
|
||||
def host_action(helper, action, project, value):
|
||||
actions.append(action)
|
||||
if action == 'lookup':
|
||||
return 'null'
|
||||
raise OSError('requested port is occupied')
|
||||
with patch.object(dev, 'start_helper', return_value='owned-helper'), \
|
||||
patch.object(dev, 'host_action', side_effect=host_action), \
|
||||
patch.object(dev, 'run', return_value='') as run, patch.object(dev, 'install') as install:
|
||||
with self.assertRaises(OSError):
|
||||
dev.install_auto('34567')
|
||||
install.assert_not_called()
|
||||
self.assertEqual(actions, ['lookup', 'check-port'])
|
||||
self.assertEqual(run.call_args.args[0], ['docker', 'rm', '-f', 'owned-helper'])
|
||||
|
||||
def test_free_port_runs_existing_fresh_install_and_records_built_images(self):
|
||||
"""Fail if the public entrypoint bypasses fresh-install phases or loses candidate/image provenance."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base, calls, checks = Path(tmp), [], []
|
||||
project, port = 'isssteleon-dev-34567', 34567
|
||||
revision, pin = 'a' * 40, 'b' * 40
|
||||
def host_action(helper, action, project, value):
|
||||
checks.append(action)
|
||||
if action == 'lookup':
|
||||
return json.dumps(host.find_installation(base, int(value), missing_ok=True))
|
||||
if action == 'save':
|
||||
host.write_record(base / project, json.loads(value))
|
||||
return ''
|
||||
def export(repo, sha, source, manifest):
|
||||
(source / 'dist').mkdir(parents=True)
|
||||
(source / 'dist' / 'docker-compose.yml').write_text('{}')
|
||||
manifest['ISSSTELEON'] = sha
|
||||
def copy_to_host(helper, source, project, destination):
|
||||
target = base / project / destination
|
||||
if source.is_dir():
|
||||
shutil.copytree(source, target)
|
||||
else:
|
||||
shutil.copy2(source, target)
|
||||
def run(args, **kwargs):
|
||||
calls.append(list(map(str, args)))
|
||||
if 'config' in args:
|
||||
directory = Path(args[args.index('--project-directory') + 1])
|
||||
env = dict(line.split('=', 1) for line in (directory / '.env').read_text().splitlines())
|
||||
api = {'image': 'isssteleon/webapi:' + env['ISSSTELEON_VERSION'],
|
||||
'environment': {**env, **conservative.PERSISTENT_ENV},
|
||||
'volumes': [{'type': 'bind', 'source': str(base / project / 'data'), 'target': '/data'}]}
|
||||
return json.dumps({'name': project, 'services': {'webapi': api, 'indicadores': copy.deepcopy(api),
|
||||
'webapp': {'image': 'isssteleon/webapp:' + env['ISSSTELEON_VERSION'],
|
||||
'ports': [{'published': str(port), 'target': 80}]}}})
|
||||
return ''
|
||||
with patch.object(dev, 'start_helper', return_value='owned-helper'), \
|
||||
patch.object(dev, 'host_action', side_effect=host_action), patch.object(dev, 'run', side_effect=run), \
|
||||
patch.object(dev, 'git', side_effect=lambda repo, *args: revision if args[0] == 'rev-parse' else
|
||||
'160000 commit ' + pin + '\tISSSTELEON'), \
|
||||
patch.object(dev, 'export_tree', side_effect=export), \
|
||||
patch.object(dev, 'copy_to_host', side_effect=copy_to_host), \
|
||||
patch.object(dev, 'reserve', side_effect=lambda helper, project, port: host.reserve(base, project, port)), \
|
||||
patch.object(conservative, 'guard'), patch.object(conservative, 'verify_api'), \
|
||||
patch.object(conservative, 'finish') as finish, patch.object(dev, 'verify_services'), \
|
||||
patch.object(dev, 'verify_existing_containers') as verify:
|
||||
dev.install_auto(str(port), Path('/synthetic-source'), base)
|
||||
record = host.find_installation(base, port)
|
||||
self.assertEqual(checks[:2], ['lookup', 'check-port'])
|
||||
self.assertEqual((record['status'], record['result'], record['phase'], record['revision']),
|
||||
('installed', 'installed', 'complete', revision))
|
||||
self.assertEqual(record['gitlinks'], {'ISSSTELEON': pin})
|
||||
self.assertEqual(record['images'], [c[c.index('-t') + 1] for c in calls if c[:2] == ['docker', 'build']])
|
||||
self.assertEqual(finish.call_count, 1)
|
||||
self.assertEqual(verify.call_count, 1)
|
||||
self.assertEqual(calls[-1], ['docker', 'rm', '-f', 'owned-helper'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,42 +0,0 @@
|
||||
"""Pin the general workflow's deployment safety boundaries using its checked-in YAML.
|
||||
|
||||
The fixture is the workflow text; no runner, network, Docker or dispatch is used.
|
||||
Behavioral routing and preservation are exercised in test_deploy_auto.py.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
|
||||
class GeneralWorkflowTests(unittest.TestCase):
|
||||
def test_dispatch_uses_only_port_and_exact_dev_checkout(self):
|
||||
"""Fail if deployment accepts unpinned source or bypasses the dev-only dispatch guard."""
|
||||
text = (Path(__file__).resolve().parents[1] / 'workflows' / 'deploy-dev.yml').read_text()
|
||||
inputs = text.split(' inputs:\n', 1)[1].split('\njobs:', 1)[0]
|
||||
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), ['puerto'])
|
||||
for boundary in ('test "$DISPATCH_REF" = refs/heads/dev', 'ref: ${{ github.sha }}',
|
||||
'test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"',
|
||||
'dev.py validate-auto "$PORT"',
|
||||
'git submodule update --init --recursive ISSSTELEON',
|
||||
'dev.py install-auto "$PORT"'):
|
||||
self.assertIn(boundary, text)
|
||||
self.assertLess(text.index('refs/heads/dev'), text.index('actions/checkout'))
|
||||
self.assertLess(text.index('git rev-parse HEAD'), text.index('validate-auto'))
|
||||
self.assertLess(text.index('validate-auto'), text.index('git submodule update'))
|
||||
self.assertNotIn('--remote', text)
|
||||
|
||||
def test_general_path_has_no_laboratory_identity_or_reset_fallback(self):
|
||||
"""Fail if production routing acquires a fixed trial identity or destructive reset command."""
|
||||
directory = Path(__file__).parent
|
||||
paths = [directory / name for name in ('dev.py', 'host.py', 'conservative.py')]
|
||||
paths.append(directory.parent / 'workflows' / 'deploy-dev.yml')
|
||||
for path in paths:
|
||||
with self.subTest(path=path.name):
|
||||
text = path.read_text()
|
||||
self.assertNotRegex(text, r'18080|18081|dev-prueba-02|reset_lab|trial_inspect')
|
||||
self.assertNotRegex(text, r"['\"](?:down|prune|reinstalar|recrear)['\"]")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,421 +0,0 @@
|
||||
"""Installer behavior with temporary directories, fake Docker commands and Git archives."""
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path, PurePosixPath
|
||||
from unittest.mock import patch
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
except ImportError:
|
||||
sys.modules['fcntl'] = types.SimpleNamespace(flock=lambda *args: None, LOCK_EX=1)
|
||||
import dev
|
||||
import host
|
||||
|
||||
|
||||
class InstallerTests(unittest.TestCase):
|
||||
def test_find_installation_uses_recorded_port(self):
|
||||
"""Resolve old and new project names; fail if identity is derived from the port."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
for project, port in [('isssteleon-dev-prueba-02', 18080), ('isssteleon-dev-18081', 18081)]:
|
||||
directory = base / project
|
||||
directory.mkdir()
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(directory / name).mkdir()
|
||||
host.write_record(directory, {'project': project, 'port': port, 'status': 'installed'})
|
||||
self.assertEqual(host.find_installation(base, port)['project'], project)
|
||||
with self.assertRaisesRegex(RuntimeError, 'no installation'):
|
||||
host.find_installation(base, 18082)
|
||||
self.assertIsNone(host.find_installation(base, 18082, missing_ok=True))
|
||||
|
||||
def test_find_installation_rejects_ambiguous_and_bad_records(self):
|
||||
"""Reject duplicates and unreadable records, even when the requested port has a match."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
for project in ('isssteleon-old', 'isssteleon-new'):
|
||||
directory = base / project
|
||||
directory.mkdir()
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(directory / name).mkdir()
|
||||
host.write_record(directory, {'project': project, 'port': 18080, 'status': 'installed'})
|
||||
with self.assertRaisesRegex(RuntimeError, 'duplicate recorded port'):
|
||||
host.find_installation(base, 18080)
|
||||
(base / 'isssteleon-new' / 'installation.json').write_text('{broken')
|
||||
with self.assertRaises(ValueError):
|
||||
host.find_installation(base, 18080)
|
||||
with self.assertRaises(ValueError):
|
||||
host.find_installation(base, 18082, missing_ok=True)
|
||||
|
||||
def test_host_lookup_reports_an_absent_port_without_reserving_it(self):
|
||||
"""A missing port returns null without creating a project or a reservation."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
with patch.object(sys, 'argv', ['host.py', str(base), 'lookup', '-', '18081']), \
|
||||
patch('builtins.print') as output:
|
||||
host.main()
|
||||
output.assert_called_once_with('null')
|
||||
self.assertEqual(list(base.iterdir()), [])
|
||||
|
||||
def test_find_installation_rejects_uncertain_status_and_paths(self):
|
||||
"""Reject interrupted operations and missing persistent paths before an update could run."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
directory = base / 'isssteleon-old'
|
||||
directory.mkdir()
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(directory / name).mkdir()
|
||||
for status in ('failed', 'updating', 'update_failed'):
|
||||
host.write_record(directory, {'project': directory.name, 'port': 18080, 'status': status})
|
||||
with self.subTest(status=status), self.assertRaisesRegex(RuntimeError, 'not installed'):
|
||||
host.find_installation(base, 18080)
|
||||
host.write_record(directory, {'project': directory.name, 'port': 18080, 'status': 'installed'})
|
||||
(directory / 'data').rmdir()
|
||||
with self.assertRaisesRegex(RuntimeError, 'invalid installation path'):
|
||||
host.find_installation(base, 18080)
|
||||
|
||||
def test_automatic_identity_and_invalid_inputs(self):
|
||||
"""Normalize valid ports and reject invalid requests before any installation side effect."""
|
||||
for port, expected in [('18081', 'dev-18081'), ('1024', 'dev-1024'),
|
||||
('65535', 'dev-65535'), ('01024', 'dev-1024')]:
|
||||
self.assertEqual(dev.automatic_instance(port), expected)
|
||||
for port in ('1023', '65536', 'abc', '', ' 1024', '+1024', '001024', '1.5'):
|
||||
with self.subTest(port=port), patch.object(dev, 'install') as install:
|
||||
with self.assertRaises(ValueError):
|
||||
dev.install_auto(port)
|
||||
install.assert_not_called()
|
||||
|
||||
def test_automatic_install_uses_existing_interface(self):
|
||||
"""Use the shared installation path with a normalized identity and install operation."""
|
||||
with patch.object(dev, 'install') as install, patch.object(dev, 'start_helper', return_value='helper'), \
|
||||
patch.object(dev, 'host_action', side_effect=['null', '']), patch.object(dev, 'run', return_value=''):
|
||||
dev.install_auto('01024')
|
||||
self.assertEqual(install.call_args.args[:3], ('dev-1024', '01024', 'instalar'))
|
||||
|
||||
def test_automatic_dispatch_uses_recorded_identity(self):
|
||||
"""An existing identity goes to conservative update, never a fresh installation."""
|
||||
record = {'project': 'isssteleon-dev-prueba-02', 'port': 18080, 'status': 'installed'}
|
||||
with patch.object(dev, 'start_helper', return_value='helper'), \
|
||||
patch.object(dev, 'host_action', return_value=json.dumps(record)), \
|
||||
patch.object(dev, 'update') as update, patch.object(dev, 'install') as install, \
|
||||
patch.object(dev, 'run'):
|
||||
dev.install_auto('18080')
|
||||
update.assert_called_once_with(record, 'helper', dev.ROOT, dev.BASE)
|
||||
install.assert_not_called()
|
||||
|
||||
def test_archive_keeps_reservation_and_original_data(self):
|
||||
"""Archive only application payloads; fail if data moves or the port becomes free."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
directory = base / 'isssteleon-dev-prueba-02'
|
||||
directory.mkdir()
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(directory / name).mkdir()
|
||||
(directory / name / 'old').write_text(name)
|
||||
previous = {'project': directory.name, 'port': 18080, 'status': 'installed'}
|
||||
operation = 'a' * 32
|
||||
host.write_record(directory, dict(previous, status='updating', operation_id=operation))
|
||||
archive = host.archive_installation(base, directory.name, operation, previous)
|
||||
self.assertTrue((directory / 'installation.json').exists())
|
||||
self.assertFalse((archive / 'data').exists())
|
||||
self.assertEqual((directory / 'data' / 'old').read_text(), 'data')
|
||||
self.assertEqual(json.loads((archive / 'installation.json').read_text()), previous)
|
||||
with self.assertRaisesRegex(RuntimeError, 'reserved'):
|
||||
host.reserve(base, 'isssteleon-dev-18080', 18080)
|
||||
with self.assertRaisesRegex(RuntimeError, 'not installed'):
|
||||
host.find_installation(base, 18080)
|
||||
|
||||
def test_archive_interruption_keeps_record_and_reservation(self):
|
||||
"""A failed code move retains an updating record and leaves persistent data in place."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
directory = base / 'isssteleon-old'
|
||||
directory.mkdir()
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(directory / name).mkdir()
|
||||
previous = {'project': directory.name, 'port': 18080, 'status': 'installed'}
|
||||
operation = 'b' * 32
|
||||
host.write_record(directory, dict(previous, status='updating', operation_id=operation))
|
||||
with patch.object(host.os, 'rename', side_effect=OSError('interrupted')):
|
||||
with self.assertRaises(OSError):
|
||||
host.archive_installation(base, directory.name, operation, previous)
|
||||
self.assertEqual(host.read_record(directory)['status'], 'updating')
|
||||
with self.assertRaises(RuntimeError):
|
||||
host.reserve(base, 'isssteleon-new', 18080)
|
||||
|
||||
def test_container_verification_rejects_foreign_mount_and_wrong_image(self):
|
||||
"""Only matching project containers may access the installation or be replaced."""
|
||||
project = 'isssteleon-dev-prueba-02'
|
||||
record = {'project': project, 'port': 18080, 'images': ['api-tag', 'app-tag']}
|
||||
data = '/srv/instances/' + project + '/data'
|
||||
def container(service):
|
||||
api = service != 'webapp'
|
||||
return {'Id': service, 'Name': '/' + service,
|
||||
'Config': {'Labels': {'com.docker.compose.project': project, 'com.docker.compose.service': service}},
|
||||
'State': {'Status': 'running'}, 'Image': 'api-id' if api else 'app-id',
|
||||
'HostConfig': {'PortBindings': {} if api else {'80/tcp': [{'HostPort': '18080'}]}},
|
||||
'Mounts': [{'Type': 'bind', 'Source': data, 'Destination': '/data', 'RW': True}] if api else []}
|
||||
containers = [container(s) for s in ('webapi', 'webapp', 'indicadores')]
|
||||
def run(args):
|
||||
if args[1:3] == ['image', 'inspect']:
|
||||
return 'api-id' if args[-1] == 'api-tag' else 'app-id'
|
||||
if args[1] == 'ps':
|
||||
return 'id1\nid2\nid3\n'
|
||||
return json.dumps(containers)
|
||||
with patch.object(dev, 'run', side_effect=run):
|
||||
self.assertEqual(dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper'),
|
||||
['indicadores', 'webapi', 'webapp'])
|
||||
containers.append({'Name': '/other', 'Config': {'Labels': {}}, 'HostConfig': {},
|
||||
'Mounts': [{'Source': '/srv/instances'}]})
|
||||
with self.assertRaisesRegex(RuntimeError, 'foreign container'):
|
||||
dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper')
|
||||
containers.pop()
|
||||
containers[0]['NetworkSettings'] = {'Networks': {'default': {'NetworkID': 'owned-network'}}}
|
||||
containers.append({'Name': '/peer', 'Config': {'Labels': {}}, 'HostConfig': {}, 'Mounts': [],
|
||||
'NetworkSettings': {'Networks': {'shared': {'NetworkID': 'owned-network'}}}})
|
||||
with self.assertRaisesRegex(RuntimeError, 'shares the installation network'):
|
||||
dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper')
|
||||
containers.pop()
|
||||
containers[0]['Image'] = 'wrong'
|
||||
with self.assertRaisesRegex(RuntimeError, 'image does not match'):
|
||||
dev.verify_existing_containers(record, PurePosixPath('/srv/instances'), 'helper')
|
||||
|
||||
def test_foreign_port_is_rejected_before_reservation(self):
|
||||
"""An unrelated container with the requested port is never stopped or overwritten."""
|
||||
foreign = [{'HostConfig': {'PortBindings': {'80/tcp': [{'HostPort': '18081'}]}}}]
|
||||
def run(args, **kwargs):
|
||||
if args[1] == 'ps':
|
||||
return 'foreign-id'
|
||||
if args[1] == 'inspect':
|
||||
return json.dumps(foreign)
|
||||
return ''
|
||||
with patch.object(dev, 'start_helper', return_value='helper'), \
|
||||
patch.object(dev, 'host_action', return_value='null'), patch.object(dev, 'run', side_effect=run) as calls, \
|
||||
patch.object(dev, 'install') as install, patch.object(dev, 'update') as update:
|
||||
with self.assertRaisesRegex(RuntimeError, 'reserved by another container'):
|
||||
dev.install_auto('18081')
|
||||
install.assert_not_called()
|
||||
update.assert_not_called()
|
||||
self.assertFalse(any('stop' in c.args[0] for c in calls.call_args_list))
|
||||
|
||||
def test_host_reservations_fail_closed(self):
|
||||
"""Preserve old and partial reservations and reject duplicate ports and identities."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
host.reserve(base, 'isssteleon-dev-prueba-02', 18080)
|
||||
with self.assertRaisesRegex(RuntimeError, 'reserved by isssteleon-dev-prueba-02'):
|
||||
host.reserve(base, 'isssteleon-dev-18080', 18080)
|
||||
with self.assertRaisesRegex(RuntimeError, 'already exists'):
|
||||
host.reserve(base, 'isssteleon-dev-prueba-02', 18081)
|
||||
partial = base / 'isssteleon-dev-18081'
|
||||
partial.mkdir()
|
||||
with self.assertRaises((OSError, ValueError, RuntimeError)):
|
||||
host.reserve(base, 'isssteleon-dev-18082', 18082)
|
||||
self.assertFalse((base / 'isssteleon-dev-18082').exists())
|
||||
(partial / 'installation.json').write_text('{broken')
|
||||
with self.assertRaises(ValueError):
|
||||
host.reserve(base, 'isssteleon-dev-18082', 18082)
|
||||
|
||||
def test_interrupted_reservation_blocks_subsequent_requests(self):
|
||||
"""Keep an interrupted directory and fail closed before reserving another port."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
base = Path(tmp)
|
||||
with patch.object(host, 'write_record', side_effect=OSError('interrupted')):
|
||||
with self.assertRaises(OSError):
|
||||
host.reserve(base, 'isssteleon-dev-18081', 18081)
|
||||
self.assertTrue((base / 'isssteleon-dev-18081').is_dir())
|
||||
with self.assertRaises(OSError):
|
||||
host.reserve(base, 'isssteleon-dev-18082', 18082)
|
||||
|
||||
def test_atomic_record_replacement_preserves_previous_record(self):
|
||||
"""Leave the previous complete record when atomic replacement fails."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
directory = Path(tmp)
|
||||
old = {'project': 'isssteleon-demo', 'port': 18080, 'status': 'preparing'}
|
||||
host.write_record(directory, old)
|
||||
with patch.object(host.os, 'replace', side_effect=OSError('interrupted')):
|
||||
with self.assertRaises(OSError):
|
||||
host.write_record(directory, dict(old, status='failed'))
|
||||
self.assertEqual(json.loads((directory / 'installation.json').read_text()), old)
|
||||
self.assertEqual(list(directory.iterdir()), [directory / 'installation.json'])
|
||||
|
||||
def test_existing_compose_resources_reject_reservation(self):
|
||||
"""Reject any existing Compose resource before creating a host reservation."""
|
||||
for kind in ('ps', 'network', 'volume'):
|
||||
with self.subTest(kind=kind), patch.object(dev, 'run', side_effect=lambda args: 'found' if kind in args else ''), \
|
||||
patch.object(dev, 'host_action') as action:
|
||||
with self.assertRaisesRegex(RuntimeError, 'Compose project already owns'):
|
||||
dev.reserve('helper', 'isssteleon-dev-18081', 18081)
|
||||
action.assert_not_called()
|
||||
|
||||
def test_validation(self):
|
||||
"""Accept valid input and reject unsafe input and unsupported operations."""
|
||||
self.assertEqual(dev.validate('demo-2', '8080', 'instalar'), ('isssteleon-demo-2', 8080))
|
||||
for instance, port, op in [('../x', '8080', 'instalar'), ('a--b', '8080', 'instalar'),
|
||||
('A', '8080', 'instalar'), ('a'*41, '8080', 'instalar'),
|
||||
('a', '80', 'instalar'), ('a', '65536', 'instalar'),
|
||||
('a', '8 080', 'instalar'), ('a', '8080', 'actualizar'),
|
||||
('a', '8080', 'reinstalar')]:
|
||||
with self.subTest(instance=instance, port=port, operation=op), self.assertRaises(ValueError):
|
||||
dev.validate(instance, port, op)
|
||||
|
||||
def test_configuration_is_instance_specific(self):
|
||||
"""Generate isolated paths, image tags and four local SQLite URLs."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
deploy = Path(tmp)
|
||||
tag = dev.configure(deploy, Path('/srv/demo/data'), 'isssteleon-demo', 'a'*40, 8081)
|
||||
env = (deploy / '.env').read_text()
|
||||
self.assertIn('ISSSTELEON_DATOS=' + str(Path('/srv/demo/data')) + '\n', env)
|
||||
self.assertIn('ISSSTELEON_PUERTO=8081\n', env)
|
||||
self.assertIn('GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db', env)
|
||||
self.assertTrue(tag.startswith('isssteleon-demo-aaaaaaaaaaaa-'))
|
||||
self.assertNotEqual(tag, dev.configure(deploy, Path('/srv/demo/data'), 'isssteleon-demo', 'a'*40, 8081))
|
||||
|
||||
def test_export_follows_committed_gitlinks_recursively(self):
|
||||
"""Export the recorded nested SHA and reject a checkout at another commit."""
|
||||
def archive(content):
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode='w') as tar:
|
||||
data = content.encode()
|
||||
info = tarfile.TarInfo('file.txt'); info.size = len(data)
|
||||
tar.addfile(info, io.BytesIO(data))
|
||||
return buf.getvalue()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / 'repo'; child = root / 'nested'; dest = Path(tmp) / 'out'
|
||||
def fake_git(repo, *args, **kwargs):
|
||||
if args[0] == 'rev-parse': return 'parent\n' if repo == root else 'child\n'
|
||||
if args[0] == 'archive': return archive('parent' if repo == root else 'child')
|
||||
return b'160000 commit child\tnested\0' if repo == root else b''
|
||||
manifest = {}
|
||||
with patch.object(dev, 'git', side_effect=fake_git):
|
||||
dev.export_tree(root, 'parent', dest, manifest)
|
||||
self.assertEqual((dest / 'nested/file.txt').read_text(), 'child')
|
||||
self.assertEqual(manifest, {'ISSSTELEON': 'parent', 'nested': 'child'})
|
||||
self.assertEqual(dev.pinned_manifest(root, 'parent'), manifest)
|
||||
with self.assertRaisesRegex(RuntimeError, 'expected wrong'):
|
||||
dev.export_tree(child, 'wrong', dest, {})
|
||||
with self.assertRaisesRegex(RuntimeError, 'expected wrong'):
|
||||
dev.pinned_manifest(child, 'wrong')
|
||||
|
||||
def test_compose_config_validation(self):
|
||||
"""Reject a changed project, database, mount, image or published port."""
|
||||
data = Path('/data/instance')
|
||||
api = {'image': 'isssteleon/webapi:tag', 'volumes': [{'type':'bind','source':str(data),'target':'/data'}],
|
||||
'environment': {f'{x}_DATABASE_URL':f'sqlite:////data/{x.lower()}.db' for x in ('CACU','CAMA','TEA','GOVERNANCE')}}
|
||||
config = {'name':'isssteleon-x', 'services': {'webapi':api, 'indicadores':api,
|
||||
'webapp':{'image':'isssteleon/webapp:tag','ports':[{'published':'8080','target':80}]}}}
|
||||
dev.verify_config(config, 'isssteleon-x', data, 'tag', 8080)
|
||||
for change in ('name', 'database', 'mount', 'image', 'port', 'extra_mount', 'privileged'):
|
||||
altered = json.loads(json.dumps(config))
|
||||
if change == 'name': altered['name'] = 'isssteleon'
|
||||
if change == 'database': altered['services']['webapi']['environment']['CACU_DATABASE_URL'] = 'postgres://shared'
|
||||
if change == 'mount': altered['services']['indicadores']['volumes'][0]['source'] = '/shared'
|
||||
if change == 'image': altered['services']['webapp']['image'] = 'other'
|
||||
if change == 'port': altered['services']['webapp']['ports'][0]['published'] = '8081'
|
||||
if change == 'extra_mount': altered['services']['webapp']['volumes'] = [{'type': 'bind', 'source': '/', 'target': '/host'}]
|
||||
if change == 'privileged': altered['services']['webapi']['privileged'] = True
|
||||
with self.subTest(change=change), self.assertRaises(RuntimeError):
|
||||
dev.verify_config(altered, 'isssteleon-x', data, 'tag', 8080)
|
||||
|
||||
def test_helper_uses_existing_host_mount_and_shared_lock(self):
|
||||
"""Fail if preparation uses an implicit mount or a job-local lock."""
|
||||
calls = []
|
||||
def fake_run(args, **kwargs):
|
||||
calls.append([str(x) for x in args])
|
||||
return '1' if 'exec' in args else ''
|
||||
with patch.object(dev, 'run', side_effect=fake_run):
|
||||
helper = dev.start_helper(PurePosixPath('/srv/workingnarrative-dev'))
|
||||
self.assertTrue(helper.startswith('isssteleon-prepare-'))
|
||||
self.assertIn('type=bind,src=/srv/workingnarrative-dev,dst=/host', calls[0])
|
||||
self.assertIn('fcntl.flock', calls[0][-1])
|
||||
self.assertIn('/host/.install.lock', calls[0][-1])
|
||||
|
||||
def test_install_transfers_and_probes_daemon_paths(self):
|
||||
"""Fail if persistent data or the SQLite check uses a job-local mount."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp) / 'repo'; base = PurePosixPath('/srv/workingnarrative-dev'); calls = []
|
||||
def fake_git(repo, *args, **kwargs):
|
||||
return 'a'*40 if args[0] == 'rev-parse' else '160000 commit ' + 'b'*40 + '\tISSSTELEON'
|
||||
def fake_export(repo, sha, dest, manifest):
|
||||
(dest / 'dist').mkdir(parents=True)
|
||||
(dest / 'dist/docker-compose.yml').write_text('fixture')
|
||||
manifest['ISSSTELEON'] = sha
|
||||
def fake_run(args, **kwargs):
|
||||
calls.append([str(x) for x in args])
|
||||
return '{}' if 'config' in args else ''
|
||||
with patch.object(dev, 'git', side_effect=fake_git), patch.object(dev, 'export_tree', side_effect=fake_export), \
|
||||
patch.object(dev, 'run', side_effect=fake_run), patch.object(dev, 'start_helper', return_value='helper'), \
|
||||
patch.object(dev, 'reserve') as reserve, patch.object(dev, 'verify_config'), patch.object(dev, 'verify_services'), \
|
||||
patch.object(dev, 'verify_existing_containers'), \
|
||||
patch.object(dev.conservative, 'controlled_config', return_value={}), \
|
||||
patch.object(dev.conservative, 'verify_api'), patch.object(dev.conservative, 'guard'), \
|
||||
patch.object(dev.conservative, 'finish'):
|
||||
dev.install('demo', '8080', 'instalar', root, base)
|
||||
reserve.assert_called_once_with('helper', 'isssteleon-demo', 8080)
|
||||
self.assertTrue(any(c[:2] == ['docker', 'cp'] and c[-1].endswith('/deploy') for c in calls))
|
||||
probe = next(c for c in calls if '--entrypoint' in c)
|
||||
self.assertIn('type=bind,src=/srv/workingnarrative-dev/isssteleon-demo/data,dst=/data', probe)
|
||||
self.assertIn('sqlite3.connect', probe[-1])
|
||||
self.assertEqual(calls[-1], ['docker', 'rm', '-f', 'helper'])
|
||||
|
||||
def test_reservation_failure_removes_helper(self):
|
||||
"""Fail if a rejected reservation leaves its helper holding the shared lock."""
|
||||
with patch.object(dev, 'git', side_effect=['a'*40, '160000 commit ' + 'b'*40 + '\tISSSTELEON']), \
|
||||
patch.object(dev, 'start_helper', return_value='helper'), \
|
||||
patch.object(dev, 'reserve', side_effect=RuntimeError('reserved')), \
|
||||
patch.object(dev, 'run') as run:
|
||||
with self.assertRaisesRegex(RuntimeError, 'reserved'):
|
||||
dev.install('demo', '8080', 'instalar')
|
||||
run.assert_called_once_with(['docker', 'rm', '-f', 'helper'])
|
||||
|
||||
def test_install_failure_retains_failed_reservation(self):
|
||||
"""Record a build preparation failure without deleting the reserved directory."""
|
||||
records = []
|
||||
def host_action(helper, action, project, payload):
|
||||
records.append(json.loads(payload))
|
||||
with patch.object(dev, 'git', side_effect=['a'*40, '160000 commit ' + 'b'*40 + '\tISSSTELEON']), \
|
||||
patch.object(dev, 'start_helper', return_value='helper'), patch.object(dev, 'reserve') as reserve, \
|
||||
patch.object(dev, 'host_action', side_effect=host_action), \
|
||||
patch.object(dev, 'export_tree', side_effect=RuntimeError('export failed')), \
|
||||
patch.object(dev, 'run') as run:
|
||||
with self.assertRaisesRegex(RuntimeError, 'export failed'):
|
||||
dev.install('demo', '8080', 'instalar')
|
||||
reserve.assert_called_once_with('helper', 'isssteleon-demo', 8080)
|
||||
self.assertEqual([record['status'] for record in records], ['preparing', 'failed'])
|
||||
self.assertEqual(records[-1]['port'], 8080)
|
||||
run.assert_called_once_with(['docker', 'rm', '-f', 'helper'])
|
||||
|
||||
def test_http_checks_use_webapp_container(self):
|
||||
"""Fail if frontend and proxied API checks use the job's loopback."""
|
||||
calls = []
|
||||
def fake_run(args):
|
||||
calls.append(args)
|
||||
if 'ps' in args: return 'container\n'
|
||||
if 'inspect' in args: return json.dumps({'Status':'running', 'Health':{'Status':'healthy'}})
|
||||
return ''
|
||||
with patch.object(dev, 'run', side_effect=fake_run):
|
||||
dev.verify_services(['compose'], 8080)
|
||||
urls = [c[-1] for c in calls if 'wget' in c]
|
||||
self.assertEqual(urls, ['http://127.0.0.1/health', 'http://127.0.0.1/'])
|
||||
self.assertTrue(all(c[:2] == ['docker', 'exec'] for c in calls if 'wget' in c))
|
||||
|
||||
def test_service_checks_are_independent(self):
|
||||
"""A missing worker or unhealthy API prevents a successful installation."""
|
||||
for service in ('webapi', 'webapp', 'indicadores'):
|
||||
def fake_run(args):
|
||||
if 'ps' in args:
|
||||
return '' if args[-1] == service else 'container\n'
|
||||
return json.dumps({'Status':'running', 'Health':{'Status':'healthy'}})
|
||||
with self.subTest(service=service), patch.object(dev, 'run', side_effect=fake_run), \
|
||||
patch.object(dev.time, 'sleep'), patch.object(dev.time, 'monotonic', side_effect=[0, 0, 301]):
|
||||
with self.assertRaisesRegex(RuntimeError, service): dev.verify_services(['compose'], 8080)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
"""Install and clean reinstall flows against an in-memory Docker daemon and a temporary installation host.
|
||||
|
||||
Fixtures (see fakedocker.py): `FakeDocker` answers the Docker and Compose commands and keeps containers, volumes,
|
||||
networks and images; `LocalHost` runs the registry actions on a temporary directory instead of in the locked helper;
|
||||
reference resolution and checkout are replaced by a controllable `self.commit`, because test_composition.py covers
|
||||
them against real Git repositories. Each test starts from an empty host.
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import composition
|
||||
import fakedocker
|
||||
import installer
|
||||
import proc
|
||||
import registry
|
||||
import resources
|
||||
|
||||
BASE = PurePosixPath('/srv/dev-test')
|
||||
SHA_A, SHA_B = 'a' * 40, 'b' * 40
|
||||
|
||||
|
||||
class FlowCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.registry_dir = Path(self.tmp.name) / 'base'
|
||||
self.registry_dir.mkdir()
|
||||
self.docker = fakedocker.FakeDocker(BASE)
|
||||
self.host = fakedocker.LocalHost(self.registry_dir)
|
||||
self.commit, self.busy, self.resolutions = SHA_A, set(), 0
|
||||
for module, name, value in (
|
||||
(proc, 'run', self.docker.run), (composition, 'resolve_reference', self.resolve),
|
||||
(composition, 'checkout', self.checkout), (composition, 'export_tree', self.export),
|
||||
(registry, 'check_port', self.check_port), (installer.time, 'sleep', lambda seconds: None)):
|
||||
patcher = patch.object(module, name, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
# -- stand-ins -------------------------------------------------------------------------------------
|
||||
def resolve(self, reference, remote=None):
|
||||
self.resolutions += 1
|
||||
return {'reference': reference, 'kind': 'branch', 'commit': self.commit}
|
||||
|
||||
def checkout(self, resolved, directory, remote=None):
|
||||
return {'reference': resolved['reference'], 'kind': resolved['kind'], 'commit': resolved['commit'],
|
||||
'application': 'c' * 40,
|
||||
'gitlinks': {'WorkingNarrative': resolved['commit'], 'dev-data': 'd' * 40, 'ISSSTELEON': 'c' * 40,
|
||||
'WebApi': 'e' * 40, 'WebApp': 'f' * 40, 'models': '1' * 40}}
|
||||
|
||||
def export(self, repo, revision, dest, prefix=''):
|
||||
for name in ('dist/docker-compose.yml', 'WebApi/Dockerfile', 'WebApp/Dockerfile'):
|
||||
(Path(dest) / name).parent.mkdir(parents=True, exist_ok=True)
|
||||
(Path(dest) / name).write_text('x')
|
||||
|
||||
def check_port(self, port):
|
||||
if port in self.busy:
|
||||
raise OSError('address already in use')
|
||||
|
||||
# -- operations ------------------------------------------------------------------------------------
|
||||
def operate(self, operation, port, confirmation='', reference='dev'):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
installer.run_operation(operation, str(port), reference, confirmation, base=BASE,
|
||||
metadata={'workflow_ref': 'refs/heads/dev', 'workflow_sha': SHA_A},
|
||||
host_factory=self.host)
|
||||
return out.getvalue()
|
||||
|
||||
def token(self, operation, port, reference='dev'):
|
||||
return re.search(r'confirmacion=(\S+)', self.operate(operation, port, '', reference)).group(1)
|
||||
|
||||
def install(self, port):
|
||||
self.operate('install', port, self.token('install', port))
|
||||
return registry.lookup(self.registry_dir, port)
|
||||
|
||||
def record(self, port):
|
||||
return registry.lookup(self.registry_dir, port)
|
||||
|
||||
def project_containers(self, port):
|
||||
project = f'isssteleon-dev-{port}'
|
||||
return {i: c for i, c in self.docker.containers.items()
|
||||
if c['Config']['Labels'].get('com.docker.compose.project') == project}
|
||||
|
||||
|
||||
class PlanTests(FlowCase):
|
||||
def test_install_plan_changes_nothing_and_takes_no_lock(self):
|
||||
"""Fails if planning builds, starts, registers or creates anything, or asks for the write lock."""
|
||||
output = self.operate('install', 18083)
|
||||
self.assertIn('confirmacion=instalar-18083-', output)
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
self.assertEqual(list(self.registry_dir.iterdir()), [])
|
||||
self.assertEqual(self.host.entered, [False])
|
||||
self.assertEqual(self.docker.images, {})
|
||||
|
||||
def test_reinstall_plan_lists_exact_resources_and_changes_nothing(self):
|
||||
"""Fails if the plan omits a container, the volume, the network or the directory, or changes anything."""
|
||||
self.install(18083)
|
||||
before = (len(self.docker.mutating()), sorted(self.docker.containers))
|
||||
output = self.operate('reinstall', 18083)
|
||||
plan = json.loads(output.split('Plan:', 1)[1].split('Nothing was changed')[0])
|
||||
self.assertEqual({c['service'] for c in plan['resources']['containers']},
|
||||
{'webapi', 'webapp', 'indicadores', 'notebooks'})
|
||||
self.assertEqual([v['name'] for v in plan['resources']['volumes']], ['isssteleon-dev-18083_trabajos_notebooks'])
|
||||
self.assertEqual([n['name'] for n in plan['resources']['networks']], ['isssteleon-dev-18083_default'])
|
||||
self.assertEqual(plan['directory']['project'], 'isssteleon-dev-18083')
|
||||
self.assertEqual((len(self.docker.mutating()), sorted(self.docker.containers)), before)
|
||||
self.assertEqual(self.host.entered[-1], False)
|
||||
|
||||
def test_plan_is_bound_to_the_composition(self):
|
||||
"""Fails if a different commit yields the same confirmation, so an approval would carry over."""
|
||||
first = self.token('install', 18083)
|
||||
self.commit = SHA_B
|
||||
self.assertNotEqual(self.token('install', 18083), first)
|
||||
|
||||
def test_plan_is_stable_for_the_same_inputs(self):
|
||||
"""Fails if the confirmation depends on anything random, so the second run could never match the first."""
|
||||
self.assertEqual(self.token('install', 18083), self.token('install', 18083))
|
||||
|
||||
|
||||
class InstallTests(FlowCase):
|
||||
def test_install_on_a_free_port_builds_starts_and_records_everything(self):
|
||||
"""Fails if the record lacks reference, commits, gitlinks, port, project, images or owner, or any check is skipped."""
|
||||
record = self.install(18083)
|
||||
self.assertEqual((record['status'], record['port'], record['project']),
|
||||
('installed', 18083, 'isssteleon-dev-18083'))
|
||||
self.assertEqual((record['installer'], record['reference'], record['revision']),
|
||||
(registry.INSTALLER, 'dev', SHA_A))
|
||||
self.assertEqual(record['gitlinks']['WebApi'], 'e' * 40)
|
||||
self.assertEqual(record['gitlinks']['dev-data'], 'd' * 40)
|
||||
self.assertEqual(len(record['images']), 2)
|
||||
self.assertEqual(record['verification'], {'health': 'ok', 'api_routes': 1, 'web': 'ok'})
|
||||
self.assertEqual(len(self.project_containers(18083)), 4)
|
||||
self.assertTrue((self.registry_dir / 'isssteleon-dev-18083' / 'deploy' / 'docker-compose.yml').exists())
|
||||
self.assertEqual(self.host.entered[-1], True)
|
||||
|
||||
def test_installed_worker_does_not_recalculate_at_start(self):
|
||||
"""Fails if the persisted composition lets the worker recalculate every domain when it starts."""
|
||||
self.install(18083)
|
||||
config = json.loads((self.registry_dir / 'isssteleon-dev-18083' / 'deploy' / 'docker-compose.yml').read_text())
|
||||
self.assertEqual(config['services']['indicadores']['environment']['INDICADORES_AL_INICIAR'], '0')
|
||||
|
||||
def test_wrong_or_stale_confirmation_changes_nothing(self):
|
||||
"""Fails if a confirmation that is not this plan's, or one for another port or operation, is accepted."""
|
||||
token = self.token('install', 18083)
|
||||
for bad in (token[:-1] + ('0' if token[-1] != '0' else '1'), token.replace('instalar', 'reinstalar'),
|
||||
token.replace('18083', '18084')):
|
||||
with self.subTest(bad), self.assertRaises((RuntimeError, ValueError)):
|
||||
self.operate('install', 18083, bad)
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
self.assertIsNone(self.record(18083))
|
||||
|
||||
def test_protected_ports_are_refused_before_anything_is_looked_at(self):
|
||||
"""Fails if a protected port, reference installations included, can be planned or installed."""
|
||||
for port in (18087, 4397, 18090, 18096, 18097):
|
||||
with self.subTest(port), self.assertRaisesRegex(ValueError, 'protected'):
|
||||
self.operate('install', port)
|
||||
self.assertEqual(self.docker.calls, [])
|
||||
|
||||
def test_port_held_by_a_foreign_container_is_refused(self):
|
||||
"""Fails if a port that another container publishes is treated as free."""
|
||||
self.docker.add_foreign('someone-else', ports=[18083])
|
||||
with self.assertRaisesRegex(RuntimeError, 'holds port 18083'):
|
||||
self.operate('install', 18083)
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
|
||||
def test_port_listened_on_by_the_host_is_refused(self):
|
||||
"""Fails if a port taken by a non-Docker process is treated as free."""
|
||||
self.busy.add(18083)
|
||||
with self.assertRaisesRegex(OSError, 'in use'):
|
||||
self.operate('install', 18083)
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
|
||||
def test_registered_port_is_refused_whoever_owns_it(self):
|
||||
"""Fails if install proceeds over a registered port, a DEV one or not."""
|
||||
self.install(18083)
|
||||
with self.assertRaisesRegex(RuntimeError, 'already registered'):
|
||||
self.operate('install', 18083)
|
||||
other = self.registry_dir / 'isssteleon-clinic-west'
|
||||
(other / 'data').mkdir(parents=True)
|
||||
registry.write_record(other, {'project': 'isssteleon-clinic-west', 'port': 18084, 'status': 'installed'})
|
||||
with self.assertRaisesRegex(RuntimeError, 'already registered'):
|
||||
self.operate('install', 18084)
|
||||
|
||||
def test_existing_docker_resources_of_the_project_refuse_the_install(self):
|
||||
"""Fails if a leftover network or volume with the project's name is adopted by a new install."""
|
||||
self.docker.add_volume('isssteleon-dev-18083_trabajos_notebooks')
|
||||
with self.assertRaisesRegex(RuntimeError, 'unexpected volume|already holds'):
|
||||
self.operate('install', 18083)
|
||||
|
||||
def test_build_failure_leaves_nothing_registered(self):
|
||||
"""Fails if a failed image build still reserves the port or creates a directory."""
|
||||
token = self.token('install', 18083)
|
||||
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'build failed'))
|
||||
if a[1] == 'build' else None)
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
self.operate('install', 18083, token)
|
||||
self.assertEqual(list(self.registry_dir.iterdir()), [])
|
||||
|
||||
def test_start_failure_is_recorded_on_the_instance(self):
|
||||
"""Fails if a failed start leaves the record as installed or without the error and diagnostics."""
|
||||
token = self.token('install', 18083)
|
||||
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'cannot start'))
|
||||
if a[1] == 'compose' and 'up' in a else None)
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
self.operate('install', 18083, token)
|
||||
record = self.record(18083)
|
||||
self.assertEqual(record['status'], 'failed')
|
||||
self.assertIn('cannot start', record['error'])
|
||||
self.assertIn('ps output', record['diagnostics'])
|
||||
|
||||
def test_unhealthy_endpoint_fails_the_install(self):
|
||||
"""Fails if an installation whose published port does not answer as the platform is marked installed."""
|
||||
self.host.responses['/health'] = {'status': 200, 'body': '{"status": "starting"}'}
|
||||
token = self.token('install', 18083)
|
||||
with self.assertRaisesRegex(RuntimeError, 'health'):
|
||||
self.operate('install', 18083, token)
|
||||
self.assertEqual(self.record(18083)['status'], 'failed')
|
||||
|
||||
def test_unsafe_composition_is_refused_while_planning(self):
|
||||
"""Fails if a composition with a privileged service reaches the plan."""
|
||||
original = fakedocker.compose_config
|
||||
|
||||
def unsafe(project, env, notebooks=True):
|
||||
config = original(project, env, notebooks)
|
||||
config['services']['webapi']['privileged'] = True
|
||||
return config
|
||||
|
||||
with patch.object(fakedocker, 'compose_config', unsafe), self.assertRaisesRegex(RuntimeError, 'unsafe'):
|
||||
self.operate('install', 18083)
|
||||
|
||||
|
||||
class ReinstallTests(FlowCase):
|
||||
def seed_foreign(self):
|
||||
"""Resources of another installation and unrelated ones that a reinstall of 18083 must not touch."""
|
||||
self.docker.add_volume('isssteleon-dev-18084_trabajos_notebooks',
|
||||
{'com.docker.compose.project': 'isssteleon-dev-18084'})
|
||||
self.docker.add_volume('isssteleon-dev-18083x_data')
|
||||
net = self.docker.add_network('isssteleon-dev-18084_default', {'com.docker.compose.project': 'isssteleon-dev-18084'})
|
||||
self.docker.add_foreign('isssteleon-dev-18084-webapp-1', networks=('isssteleon-dev-18084_default',), ports=[18084],
|
||||
labels={'com.docker.compose.project': 'isssteleon-dev-18084'})
|
||||
self.docker.add_foreign('unrelated', ports=[9999])
|
||||
return net
|
||||
|
||||
def test_reinstall_replaces_the_instance_and_removes_only_its_resources(self):
|
||||
"""Fails if a reinstall leaves old containers, data, volume or network, or touches any other resource."""
|
||||
record = self.install(18083)
|
||||
data = self.registry_dir / 'isssteleon-dev-18083' / 'data'
|
||||
(data / 'cacu.db').write_text('synthetic')
|
||||
self.seed_foreign()
|
||||
foreign_before = {i for i, c in self.docker.containers.items()
|
||||
if c['Config']['Labels'].get('com.docker.compose.project') != 'isssteleon-dev-18083'}
|
||||
old = set(self.project_containers(18083))
|
||||
old_volume = dict(self.docker.volumes['isssteleon-dev-18083_trabajos_notebooks'])
|
||||
self.commit = SHA_B
|
||||
token = self.token('reinstall', 18083)
|
||||
self.docker.calls.clear()
|
||||
self.operate('reinstall', 18083, token)
|
||||
new = self.record(18083)
|
||||
self.assertEqual((new['status'], new['result'], new['revision']), ('installed', 'reinstalled', SHA_B))
|
||||
self.assertEqual(new['replaced']['revision'], record['revision'])
|
||||
self.assertTrue(old.isdisjoint(self.project_containers(18083)))
|
||||
self.assertEqual(len(self.project_containers(18083)), 4)
|
||||
self.assertFalse((data / 'cacu.db').exists())
|
||||
self.assertTrue(foreign_before <= set(self.docker.containers))
|
||||
for name in ('isssteleon-dev-18084_trabajos_notebooks', 'isssteleon-dev-18083x_data'):
|
||||
self.assertIn(name, self.docker.volumes)
|
||||
self.assertEqual(len([n for n in self.docker.networks.values() if n['Name'].startswith('isssteleon-dev-1808')]), 2)
|
||||
self.assertNotEqual(old_volume, None)
|
||||
removed = [c for c in self.docker.calls if c[1] in ('stop', 'rm', 'update')]
|
||||
self.assertTrue(all(c[-1] in old for c in removed), removed)
|
||||
self.assertEqual([c[3] for c in self.docker.calls if c[1:3] == ['volume', 'rm']],
|
||||
['isssteleon-dev-18083_trabajos_notebooks'])
|
||||
|
||||
def test_no_global_cleanup_command_is_ever_issued(self):
|
||||
"""Fails if a reinstall issues prune, system, forced removal or compose down."""
|
||||
self.install(18083)
|
||||
self.docker.calls.clear()
|
||||
self.operate('reinstall', 18083, self.token('reinstall', 18083))
|
||||
for call in self.docker.calls:
|
||||
self.assertNotIn('prune', call)
|
||||
self.assertNotIn('system', call[1:2])
|
||||
self.assertNotIn('down', call)
|
||||
self.assertNotIn('-f', call[2:3] if call[1] == 'rm' else [])
|
||||
|
||||
def test_reinstall_without_a_registered_instance_is_refused(self):
|
||||
"""Fails if a free or foreign-held port is accepted by reinstall because nothing is registered."""
|
||||
with self.assertRaisesRegex(RuntimeError, 'no installation is registered'):
|
||||
self.operate('reinstall', 18083)
|
||||
self.docker.add_foreign('someone-else', ports=[18085])
|
||||
with self.assertRaisesRegex(RuntimeError, 'no installation is registered'):
|
||||
self.operate('reinstall', 18085)
|
||||
self.assertEqual(self.docker.mutating(), [])
|
||||
|
||||
def test_protected_ports_are_never_reinstalled_even_when_registered(self):
|
||||
"""Fails if a record on a protected port, reference installations included, lets a reinstall be planned."""
|
||||
for port in (18087, 4397, 18090, 18096, 18097):
|
||||
directory = self.registry_dir / f'isssteleon-dev-{port}'
|
||||
(directory / 'data').mkdir(parents=True)
|
||||
registry.write_record(directory, {'project': directory.name, 'port': port, 'status': 'installed',
|
||||
'installer': registry.INSTALLER, 'revision': SHA_A})
|
||||
with self.subTest(port), self.assertRaisesRegex(ValueError, 'protected'):
|
||||
self.operate('reinstall', port)
|
||||
|
||||
def test_instance_not_proven_to_be_dev_is_refused(self):
|
||||
"""Fails if a registered instance of another installer, name or state is planned for removal."""
|
||||
directory = self.registry_dir / 'isssteleon-clinic-west'
|
||||
(directory / 'data').mkdir(parents=True)
|
||||
registry.write_record(directory, {'project': directory.name, 'port': 18083, 'status': 'installed',
|
||||
'revision': SHA_A})
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
|
||||
self.operate('reinstall', 18083)
|
||||
self.install(18084)
|
||||
record = self.record(18084)
|
||||
for changes, message in (({'installer': 'someone-else'}, 'does not prove'),
|
||||
({'status': 'update_failed'}, 'not replaceable')):
|
||||
registry.write_record(self.registry_dir / 'isssteleon-dev-18084', dict(record, **changes))
|
||||
with self.subTest(changes), self.assertRaisesRegex(RuntimeError, message):
|
||||
self.operate('reinstall', 18084)
|
||||
self.assertEqual(self.docker.mutating()[-1][1:2], ['compose'])
|
||||
|
||||
def test_earlier_dev_records_are_accepted_when_their_resources_match(self):
|
||||
"""Fails if instances installed before the owner marker existed can never be reinstalled."""
|
||||
self.install(18083)
|
||||
record = self.record(18083)
|
||||
legacy = {k: v for k, v in record.items() if k not in ('installer', 'plan_digest')}
|
||||
registry.write_record(self.registry_dir / 'isssteleon-dev-18083', legacy)
|
||||
self.operate('reinstall', 18083, self.token('reinstall', 18083))
|
||||
self.assertEqual(self.record(18083)['installer'], registry.INSTALLER)
|
||||
|
||||
def test_container_on_an_unrecorded_image_is_not_the_installations_own(self):
|
||||
"""Fails if a container of the project label running some other image is removed as if it were the instance's."""
|
||||
self.install(18083)
|
||||
ident = self.docker.add_foreign('isssteleon-dev-18083-webapp-9', networks=('isssteleon-dev-18083_default',),
|
||||
labels={'com.docker.compose.project': 'isssteleon-dev-18083',
|
||||
'com.docker.compose.service': 'webapp'}, image='sha256:other')
|
||||
with self.assertRaisesRegex(RuntimeError, 'image of the installation record|unexpected name'):
|
||||
self.operate('reinstall', 18083)
|
||||
self.assertIn(ident, self.docker.containers)
|
||||
|
||||
def test_foreign_container_sharing_storage_volume_network_or_port_refuses_the_plan(self):
|
||||
"""Fails if a plan is produced while another container can reach the instance's data, jobs or network."""
|
||||
self.install(18083)
|
||||
cases = {
|
||||
'storage': dict(mounts=[{'Type': 'bind', 'Source': '/srv/dev-test', 'Destination': '/x', 'RW': True}]),
|
||||
'volume': dict(mounts=[{'Type': 'volume', 'Name': 'isssteleon-dev-18083_trabajos_notebooks',
|
||||
'Destination': '/j', 'RW': True}]),
|
||||
'network': dict(networks=('isssteleon-dev-18083_default',)),
|
||||
}
|
||||
for label, spec in cases.items():
|
||||
ident = self.docker.add_foreign('reader-' + label, **spec)
|
||||
with self.subTest(label), self.assertRaisesRegex(RuntimeError, 'shares|holds'):
|
||||
self.operate('reinstall', 18083)
|
||||
self.docker.containers.pop(ident)
|
||||
|
||||
def test_reference_that_moves_between_plan_and_execution_changes_the_confirmation(self):
|
||||
"""Fails if an approval given for one commit installs another that the reference moved to."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
self.commit = SHA_B
|
||||
before = sorted(self.docker.containers)
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.assertEqual(sorted(self.docker.containers), before)
|
||||
|
||||
def test_reference_that_moves_after_the_build_stops_before_removal(self):
|
||||
"""Fails if the final revalidation does not notice a reference that moved while images were being built."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
self.docker.hooks.append(lambda d, a: setattr(self, 'commit', SHA_B) if a[1] == 'build' else None)
|
||||
before = sorted(self.docker.containers)
|
||||
with self.assertRaisesRegex(RuntimeError, 'moved after the plan'):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.assertEqual(sorted(self.docker.containers), before)
|
||||
self.assertEqual(self.record(18083)['status'], 'installed')
|
||||
|
||||
def test_resources_that_change_after_the_build_stop_before_removal(self):
|
||||
"""Fails if a container that appears on the instance's volume after the plan does not stop the removal."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
count = {'builds': 0}
|
||||
|
||||
def intrude(daemon, args):
|
||||
if args[1] == 'build':
|
||||
count['builds'] += 1
|
||||
if count['builds'] == 2:
|
||||
daemon.add_foreign('late-reader', mounts=[{'Type': 'volume', 'Destination': '/j', 'RW': True,
|
||||
'Name': 'isssteleon-dev-18083_trabajos_notebooks'}])
|
||||
self.docker.hooks.append(intrude)
|
||||
before = {i for i, c in self.docker.containers.items() if c['Name'] != '/late-reader'}
|
||||
with self.assertRaisesRegex(RuntimeError, 'shares'):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.assertTrue(before <= set(self.docker.containers))
|
||||
self.assertEqual(self.record(18083)['status'], 'installed')
|
||||
|
||||
def test_build_failure_leaves_the_running_instance_untouched(self):
|
||||
"""Fails if the old instance is removed before the new images are known to build."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'build failed'))
|
||||
if a[1] == 'build' else None)
|
||||
before = sorted(self.docker.containers)
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.assertEqual(sorted(self.docker.containers), before)
|
||||
self.assertEqual(self.record(18083)['status'], 'installed')
|
||||
|
||||
def test_failure_while_removing_keeps_the_rest_and_needs_a_new_confirmation(self):
|
||||
"""Fails if a failed removal loses the record, continues anyway, or lets the old confirmation resume it."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
stops = []
|
||||
|
||||
def fail_second_stop(daemon, args):
|
||||
if args[1] == 'stop':
|
||||
stops.append(args[2])
|
||||
if len(stops) == 2:
|
||||
raise fakedocker.failure(args, 'cannot stop')
|
||||
self.docker.hooks.append(fail_second_stop)
|
||||
with self.assertRaisesRegex(RuntimeError, 'removal stopped during containers'):
|
||||
self.operate('reinstall', 18083, token)
|
||||
record = self.record(18083)
|
||||
self.assertEqual(record['status'], 'removing')
|
||||
self.assertEqual(record['reinstall']['phase'], 'containers')
|
||||
self.assertIn('cannot stop', record['reinstall']['error'])
|
||||
self.assertEqual(len(self.project_containers(18083)), 3)
|
||||
self.assertIn('isssteleon-dev-18083_trabajos_notebooks', self.docker.volumes)
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not match the current plan'):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.docker.hooks.clear()
|
||||
self.operate('reinstall', 18083, self.token('reinstall', 18083))
|
||||
self.assertEqual(self.record(18083)['status'], 'installed')
|
||||
self.assertEqual(len(self.project_containers(18083)), 4)
|
||||
|
||||
def test_volume_replaced_during_the_removal_is_not_deleted(self):
|
||||
"""Fails if the jobs volume is removed by name after something else recreated it since the plan."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
|
||||
def recreate(daemon, args):
|
||||
if args[1] == 'rm':
|
||||
daemon.volumes['isssteleon-dev-18083_trabajos_notebooks']['CreatedAt'] = '2030-01-01T00:00:00Z'
|
||||
self.docker.hooks.append(recreate)
|
||||
with self.assertRaisesRegex(RuntimeError, 'removal stopped during volume.*changed since the plan'):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.assertIn('isssteleon-dev-18083_trabajos_notebooks', self.docker.volumes)
|
||||
self.assertEqual(self.record(18083)['status'], 'removing')
|
||||
|
||||
def test_failure_while_installing_after_removal_is_recorded_and_can_be_retried(self):
|
||||
"""Fails if a start failure after the removal leaves no record, or blocks the next reinstall."""
|
||||
self.install(18083)
|
||||
token = self.token('reinstall', 18083)
|
||||
self.docker.hooks.append(lambda d, a: (_ for _ in ()).throw(fakedocker.failure(a, 'cannot start'))
|
||||
if a[1] == 'compose' and 'up' in a else None)
|
||||
with self.assertRaises(subprocess.CalledProcessError):
|
||||
self.operate('reinstall', 18083, token)
|
||||
self.assertEqual(self.record(18083)['status'], 'failed')
|
||||
self.assertIn('replaced', self.record(18083))
|
||||
self.docker.hooks.clear()
|
||||
self.operate('reinstall', 18083, self.token('reinstall', 18083))
|
||||
self.assertEqual(self.record(18083)['status'], 'installed')
|
||||
|
||||
|
||||
class EntryPointTests(unittest.TestCase):
|
||||
def test_arguments_are_checked(self):
|
||||
"""Fails if the command line accepts a missing reference, an unknown command or extra arguments."""
|
||||
for argv in ([], ['install'], ['install', '18083'], ['purge', '1', '2'], ['install', '1', '2', '3', '4'],
|
||||
['validate-dispatch', 'x']):
|
||||
with self.subTest(argv), contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(installer.main(argv), 1)
|
||||
|
||||
def test_dispatch_identity_is_validated(self):
|
||||
"""Fails if a dispatch from another repository, server, ref type or SHA is accepted."""
|
||||
good = {'DISPATCH_REPOSITORY': 'ISSSTELEON/WorkingNarrative', 'DISPATCH_SERVER': 'http://10.0.10.41:3000',
|
||||
'DISPATCH_REF_TYPE': 'branch', 'DISPATCH_REF': 'refs/heads/dev', 'DISPATCH_REF_NAME': 'dev',
|
||||
'DISPATCH_SHA': SHA_A}
|
||||
with patch.object(proc, 'run', lambda args, **kw: ''), patch.object(proc, 'git', lambda *a, **k: SHA_A + '\n'):
|
||||
with patch.dict('os.environ', good):
|
||||
self.assertEqual(installer.dispatch_metadata()['workflow_sha'], SHA_A)
|
||||
for key, value in (('DISPATCH_REPOSITORY', 'other/repo'), ('DISPATCH_SERVER', 'http://evil'),
|
||||
('DISPATCH_REF_TYPE', 'tag'), ('DISPATCH_REF', 'refs/heads/other'),
|
||||
('DISPATCH_SHA', 'xyz')):
|
||||
with self.subTest(key), patch.dict('os.environ', {**good, key: value}), self.assertRaises(ValueError):
|
||||
installer.dispatch_metadata()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Exercise sanitized origin diagnostics using temporary Git repositories."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import origin_diagnostic as diagnostic
|
||||
|
||||
|
||||
class OriginDiagnosticTests(unittest.TestCase):
|
||||
def test_url_classification_never_returns_input(self):
|
||||
"""Fail if credentials or deceptive URLs appear in the diagnostic output."""
|
||||
for url in ('http://secret:password@10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git',
|
||||
'http://10.0.10.41.evil:3000/ISSSTELEON/WorkingNarrative.git',
|
||||
'http://10.0.10.41:3000/ISSSTELEON/WorkingNarrative.git.evil'):
|
||||
with self.subTest(url=url):
|
||||
result = diagnostic.describe(url)
|
||||
self.assertFalse(result['exact_http'])
|
||||
self.assertNotIn(url, json.dumps(result))
|
||||
self.assertNotIn('password', json.dumps(result))
|
||||
self.assertTrue(diagnostic.describe(diagnostic.OFFICIAL)['exact_http'])
|
||||
self.assertTrue(diagnostic.describe(diagnostic.SSH)['exact_ssh'])
|
||||
|
||||
def test_real_git_rewrite_is_detected_without_disclosing_credentials(self):
|
||||
"""Fail if Git URL rewriting is missed or a configured credential is logged."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
subprocess.run(['git', 'init', '-q', tmp], check=True)
|
||||
subprocess.run(['git', '-C', tmp, 'remote', 'add', 'origin', diagnostic.SSH], check=True)
|
||||
env = os.environ.copy()
|
||||
env.update({'GIT_CONFIG_COUNT': '1',
|
||||
'GIT_CONFIG_KEY_0': 'url.http://secret:password@10.0.10.41:3000/ISSSTELEON/.insteadOf',
|
||||
'GIT_CONFIG_VALUE_0': 'ssh://git@10.0.10.41:2222/ISSSTELEON/',
|
||||
'DISPATCH_SERVER': diagnostic.SERVER, 'DISPATCH_REPOSITORY': diagnostic.REPOSITORY})
|
||||
result = subprocess.run([sys.executable, '-B', str(Path(diagnostic.__file__).resolve())],
|
||||
cwd=tmp, env=env, text=True, capture_output=True, check=True)
|
||||
self.assertNotIn('secret', result.stdout + result.stderr)
|
||||
self.assertNotIn('password', result.stdout + result.stderr)
|
||||
data = json.loads(result.stdout.split(': ', 1)[1])
|
||||
self.assertTrue(data['literal_origin'][0]['exact_ssh'])
|
||||
self.assertTrue(data['effective_origin'][0]['userinfo_present'])
|
||||
self.assertTrue(data['origin_rewritten'])
|
||||
self.assertTrue(data['event_repository_is_official'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,173 +0,0 @@
|
||||
"""Reconciliation checks using temporary installations, SQLite files and a fake Docker adapter."""
|
||||
|
||||
import argparse
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tarfile
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import host
|
||||
import reconcile
|
||||
|
||||
|
||||
class ReconciliationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
"""Build a failed managed instance and a five-database isolated recovery fixture."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
self.project = 'isssteleon-example'
|
||||
self.root = self.base / self.project
|
||||
for name in ('codigo', 'deploy', 'data'):
|
||||
(self.root / name).mkdir(parents=True)
|
||||
self.revision = 'a' * 40
|
||||
self.operation = 'b' * 32
|
||||
tag = self.project + '-' + self.revision[:12] + '-suffix'
|
||||
self.record = {'project': self.project, 'port': 23456, 'status': 'update_failed',
|
||||
'phase': 'backup', 'revision': self.revision, 'operation_id': self.operation,
|
||||
'error': 'retained', 'gitlinks': {'ISSSTELEON': 'c' * 40},
|
||||
'images': ['isssteleon/webapi:' + tag, 'isssteleon/webapp:' + tag]}
|
||||
host.write_record(self.root, self.record)
|
||||
self.restored = self.base / 'restored' / 'data'
|
||||
self.restored.mkdir(parents=True)
|
||||
for name in reconcile.DATABASES:
|
||||
with closing(sqlite3.connect(self.restored / name)) as db:
|
||||
db.execute('CREATE TABLE sample (id INTEGER PRIMARY KEY)')
|
||||
db.commit()
|
||||
self.archive = self.base / 'recovery.tar.gz'
|
||||
with tarfile.open(self.archive, 'w:gz') as tar:
|
||||
tar.add(self.restored, arcname='data')
|
||||
self.sha = hashlib.sha256(self.archive.read_bytes()).hexdigest()
|
||||
self.request = {'port': 23456, 'revision': self.revision, 'operation_id': self.operation}
|
||||
(self.base / '.install.lock').touch()
|
||||
|
||||
def test_check_and_atomic_apply_preserve_failure_metadata(self):
|
||||
"""Fail if check writes or apply changes any field other than the status."""
|
||||
before = (self.root / 'installation.json').read_bytes()
|
||||
result = host.reconcile_record(self.base, self.project, self.request)
|
||||
self.assertEqual((self.root / 'installation.json').read_bytes(), before)
|
||||
host.reconcile_record(self.base, self.project,
|
||||
dict(self.request, record_sha256=result['record_sha256']), apply=True)
|
||||
self.assertEqual(host.read_record(self.root), dict(self.record, status='installed'))
|
||||
|
||||
def test_reject_changed_record_and_activation(self):
|
||||
"""Fail if stale evidence or partial activation can change a failure record."""
|
||||
result = host.reconcile_record(self.base, self.project, self.request)
|
||||
host.write_record(self.root, dict(self.record, error='changed'))
|
||||
with self.assertRaisesRegex(RuntimeError, 'record changed'):
|
||||
host.reconcile_record(self.base, self.project,
|
||||
dict(self.request, record_sha256=result['record_sha256']), apply=True)
|
||||
(self.root / '.archive' / self.operation).mkdir(parents=True)
|
||||
with self.assertRaisesRegex(RuntimeError, 'activation'):
|
||||
host.reconcile_record(self.base, self.project, self.request)
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
|
||||
|
||||
def test_reject_wrong_phase_or_identity(self):
|
||||
"""Fail if post-activation failures or incorrect operator identities are accepted."""
|
||||
for change in ({'phase': 'api'}, {'status': 'updating'}, {'revision': 'd' * 40},
|
||||
{'operation_id': 'e' * 32}, {'port': 23457}):
|
||||
with self.subTest(change=change):
|
||||
host.write_record(self.root, dict(self.record, **change))
|
||||
with self.assertRaises(RuntimeError):
|
||||
host.reconcile_record(self.base, self.project, self.request)
|
||||
|
||||
def test_archive_and_isolated_sqlite_evidence(self):
|
||||
"""Fail if mismatched archive hashes or restored databases pass evidence validation."""
|
||||
reconcile.recovery_evidence(self.archive, self.restored, self.sha, self.root)
|
||||
with self.assertRaisesRegex(RuntimeError, 'SHA-256'):
|
||||
reconcile.recovery_evidence(self.archive, self.restored, '0' * 64, self.root)
|
||||
(self.restored / 'tea.db').write_bytes(b'bad')
|
||||
with self.assertRaisesRegex(RuntimeError, 'differs'):
|
||||
reconcile.recovery_evidence(self.archive, self.restored, self.sha, self.root)
|
||||
|
||||
def test_reject_sqlite_sidecars(self):
|
||||
"""Fail if immutable SQLite inspection silently ignores an isolated WAL."""
|
||||
(self.restored / 'tea.db-wal').write_bytes(b'')
|
||||
with self.assertRaisesRegex(RuntimeError, 'sidecar inventory'):
|
||||
reconcile.recovery_evidence(self.archive, self.restored, self.sha, self.root)
|
||||
|
||||
def test_archive_wal_is_used_for_isolated_integrity_check(self):
|
||||
"""Fail if restored committed WAL rows are omitted from the integrity check."""
|
||||
source = self.base / 'source' / 'cama.db'
|
||||
source.parent.mkdir()
|
||||
with closing(sqlite3.connect(source)) as db:
|
||||
db.execute('CREATE TABLE witness (value INTEGER)')
|
||||
db.commit()
|
||||
db.execute('PRAGMA journal_mode=WAL')
|
||||
db.execute('PRAGMA wal_autocheckpoint=0')
|
||||
db.execute('INSERT INTO witness VALUES (42)')
|
||||
db.commit()
|
||||
for suffix in ('', '-wal', '-shm'):
|
||||
shutil.copyfile(Path(str(source) + suffix), self.restored / ('cama.db' + suffix))
|
||||
with tarfile.open(self.archive, 'w:gz') as tar:
|
||||
tar.add(self.restored, arcname='data')
|
||||
digest = hashlib.sha256(self.archive.read_bytes()).hexdigest()
|
||||
real_connect = sqlite3.connect
|
||||
observed = []
|
||||
def connect(path, *args, **kwargs):
|
||||
connection = real_connect(path, *args, **kwargs)
|
||||
if Path(path).name == 'cama.db':
|
||||
observed.append(connection.execute('SELECT value FROM witness').fetchone())
|
||||
return connection
|
||||
with patch.object(reconcile.sqlite3, 'connect', side_effect=connect):
|
||||
reconcile.recovery_evidence(self.archive, self.restored, digest, self.root)
|
||||
self.assertEqual(observed, [(42,)])
|
||||
|
||||
def test_missing_external_attestation_is_rejected_before_helper(self):
|
||||
"""Fail if an unverified external backup can enter reconciliation."""
|
||||
args = argparse.Namespace(instance='example', port=23456, indicadores='1' * 64,
|
||||
webapi='2' * 64, webapp='3' * 64, external_copy_verified=False)
|
||||
with self.assertRaisesRegex(RuntimeError, 'external backup'):
|
||||
reconcile.reconcile(args)
|
||||
|
||||
def test_orchestration_check_apply_and_identity_rejection(self):
|
||||
"""Fail if check writes, apply skips validation, or mismatched container IDs are accepted."""
|
||||
ids = ['1' * 64, '2' * 64, '3' * 64]
|
||||
args = argparse.Namespace(instance='example', port=23456, indicadores=ids[0],
|
||||
webapi=ids[1], webapp=ids[2], external_copy_verified=True,
|
||||
revision=self.revision, operation=self.operation,
|
||||
backup=self.archive, restored_data=self.restored,
|
||||
backup_sha256=self.sha, mode='check')
|
||||
calls = []
|
||||
config = {'services': {name: {'restart': 'unless-stopped'}
|
||||
for name in ('indicadores', 'webapi', 'webapp')}}
|
||||
containers = [{'Config': {'Labels': {'com.docker.compose.service': name}},
|
||||
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}}}
|
||||
for name in ('indicadores', 'webapi', 'webapp')]
|
||||
|
||||
def action(helper, name, project, payload):
|
||||
calls.append(name)
|
||||
return json.dumps(host.reconcile_record(self.base, project, json.loads(payload),
|
||||
apply=name == 'reconcile-apply'))
|
||||
|
||||
api = types.SimpleNamespace(BASE=self.base, ROOT=self.base,
|
||||
validate=lambda *a: (self.project, 23456), start_helper=lambda base: 'helper',
|
||||
host_action=action, git=lambda *a: '160000 commit ' + 'c' * 40 + '\tISSSTELEON',
|
||||
verify_existing_containers=lambda *a: ids, compose=lambda *a: ['compose'],
|
||||
verify_config=lambda *a: None, verify_services=lambda *a, **kw: None,
|
||||
run=lambda args: json.dumps(config if 'config' in args else containers) if args != ['docker', 'rm', '-f', 'helper'] else '')
|
||||
with patch.object(reconcile.conservative, 'read_deployment'), \
|
||||
patch.object(reconcile.conservative, 'current_environment'), \
|
||||
patch.object(reconcile.conservative, 'guard', return_value={}):
|
||||
self.assertEqual(reconcile.reconcile(args, api)['result'], 'eligible')
|
||||
self.assertNotIn('reconcile-apply', calls)
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
args.mode = 'apply'
|
||||
self.assertEqual(reconcile.reconcile(args, api)['result'], 'reconciled')
|
||||
self.assertEqual(host.read_record(self.root), dict(self.record, status='installed'))
|
||||
host.write_record(self.root, self.record)
|
||||
args.webapi = '4' * 64
|
||||
with self.assertRaisesRegex(RuntimeError, 'container IDs'):
|
||||
reconcile.reconcile(args, api)
|
||||
self.assertEqual(host.read_record(self.root), self.record)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Registry actions on a temporary base directory: ownership, replaceable states and directory removal.
|
||||
|
||||
Fixtures: each test makes its own temporary base; `make` writes an installation directory with a record, a
|
||||
`data` folder and some files, the way the installer leaves one.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import registry
|
||||
|
||||
SHA = 'a' * 40
|
||||
|
||||
|
||||
def make(base, port=18083, status='installed', project=None, **extra):
|
||||
project = project or f'isssteleon-dev-{port}'
|
||||
directory = Path(base) / project
|
||||
(directory / 'data').mkdir(parents=True)
|
||||
(directory / 'data' / 'cacu.db').write_text('synthetic')
|
||||
record = {'project': project, 'port': port, 'status': status, 'installer': registry.INSTALLER,
|
||||
'revision': SHA, **extra}
|
||||
registry.write_record(directory, record)
|
||||
return directory, record
|
||||
|
||||
|
||||
class RegistryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.base = Path(self.tmp.name)
|
||||
|
||||
def test_reserve_creates_the_directory_and_record_and_refuses_a_second_claim(self):
|
||||
"""Fails if reserve overwrites an existing instance or lets a port be registered twice."""
|
||||
record = {'project': 'isssteleon-dev-18083', 'port': 18083, 'status': 'preparing',
|
||||
'installer': registry.INSTALLER}
|
||||
registry.reserve(self.base, 'isssteleon-dev-18083', 18083, record)
|
||||
self.assertEqual(registry.lookup(self.base, 18083)['status'], 'preparing')
|
||||
self.assertTrue((self.base / 'isssteleon-dev-18083' / 'data').is_dir())
|
||||
with self.assertRaisesRegex(RuntimeError, 'already exists'):
|
||||
registry.reserve(self.base, 'isssteleon-dev-18083', 18083, record)
|
||||
|
||||
def test_reserve_refuses_a_port_registered_under_another_name(self):
|
||||
"""Fails if a port already held by a differently named installation can be claimed again."""
|
||||
make(self.base, 18083, project='isssteleon-clinic-west')
|
||||
record = {'project': 'isssteleon-dev-18083', 'port': 18083, 'status': 'preparing',
|
||||
'installer': registry.INSTALLER}
|
||||
with self.assertRaisesRegex(RuntimeError, 'registered by another'):
|
||||
registry.reserve(self.base, 'isssteleon-dev-18083', 18083, record)
|
||||
|
||||
def test_reserve_refuses_a_project_that_does_not_match_the_port(self):
|
||||
"""Fails if an instance name other than isssteleon-dev-<port> can be created."""
|
||||
record = {'project': 'isssteleon-dev-1', 'port': 18083, 'status': 'preparing', 'installer': registry.INSTALLER}
|
||||
with self.assertRaisesRegex(RuntimeError, 'invalid project'):
|
||||
registry.reserve(self.base, 'isssteleon-dev-1', 18083, record)
|
||||
|
||||
def test_duplicate_ports_and_bad_records_fail_every_lookup(self):
|
||||
"""Fails if an ambiguous registry is read as if the requested port were unique."""
|
||||
make(self.base, 18083)
|
||||
make(self.base, 18083, project='isssteleon-other')
|
||||
with self.assertRaisesRegex(RuntimeError, 'duplicate recorded port'):
|
||||
registry.lookup(self.base, 18084)
|
||||
|
||||
def test_ownership_accepts_marker_and_earlier_dev_records_only(self):
|
||||
"""Fails if a record of another installer, another project name or without a commit proves ownership."""
|
||||
cases = [
|
||||
(dict(installer=registry.INSTALLER), 'isssteleon-dev-18083', 'marker'),
|
||||
(dict(installer=None), 'isssteleon-dev-18083', 'legacy'),
|
||||
(dict(installer='someone-else'), 'isssteleon-dev-18083', None),
|
||||
(dict(installer=None, revision='short'), 'isssteleon-dev-18083', None),
|
||||
(dict(installer=registry.INSTALLER), 'isssteleon-clinic-west', None),
|
||||
]
|
||||
for extra, project, expected in cases:
|
||||
record = {'project': project, 'port': 18083, 'status': 'installed', 'revision': SHA}
|
||||
record.update({k: v for k, v in extra.items() if v is not None})
|
||||
if extra.get('installer') is None:
|
||||
record.pop('installer', None)
|
||||
with self.subTest(extra=extra, project=project):
|
||||
self.assertEqual(registry.owned(record, 18083), expected)
|
||||
|
||||
def test_identity_refuses_unowned_and_unreplaceable_installations(self):
|
||||
"""Fails if an installation of another owner, or one mid-update, can be planned for removal."""
|
||||
make(self.base, 18083, project='isssteleon-clinic-west')
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
|
||||
registry.identity(self.base, 'isssteleon-clinic-west', 18083)
|
||||
with self.assertRaisesRegex(RuntimeError, 'missing or linked'):
|
||||
registry.identity(self.base, 'isssteleon-dev-18083', 18083)
|
||||
make(self.base, 18084, installer='other')
|
||||
with self.assertRaisesRegex(RuntimeError, 'does not prove'):
|
||||
registry.identity(self.base, 'isssteleon-dev-18084', 18084)
|
||||
for status in ('updating', 'update_failed', 'replacing', 'replace_failed'):
|
||||
make(self.base, 18090 + len(status), status=status)
|
||||
with self.subTest(status), self.assertRaisesRegex(RuntimeError, 'not replaceable'):
|
||||
registry.identity(self.base, f'isssteleon-dev-{18090 + len(status)}', 18090 + len(status))
|
||||
make(self.base, 18085)
|
||||
self.assertEqual(registry.identity(self.base, 'isssteleon-dev-18085', 18085)['ownership'], 'marker')
|
||||
|
||||
def test_identity_refuses_a_linked_installation_directory(self):
|
||||
"""Fails if a symlink standing in for the instance directory is followed."""
|
||||
outside = Path(self.tmp.name) / 'outside'
|
||||
outside.mkdir()
|
||||
registry.write_record(outside, {'project': 'isssteleon-dev-18083', 'port': 18083, 'status': 'installed',
|
||||
'installer': registry.INSTALLER})
|
||||
base = self.base / 'base'
|
||||
base.mkdir()
|
||||
try:
|
||||
os.symlink(outside, base / 'isssteleon-dev-18083', target_is_directory=True)
|
||||
except OSError:
|
||||
self.skipTest('symlinks are not available')
|
||||
with self.assertRaisesRegex(RuntimeError, 'missing or linked|invalid instance directory'):
|
||||
registry.identity(base, 'isssteleon-dev-18083', 18083)
|
||||
with self.assertRaisesRegex(RuntimeError, 'invalid instance directory'):
|
||||
registry.lookup(base, 18083)
|
||||
|
||||
def test_remove_deletes_the_directory_and_never_follows_links_out(self):
|
||||
"""Fails if removal deletes what a link inside the data directory points to, or leaves the directory."""
|
||||
directory, record = make(self.base)
|
||||
outside = Path(self.tmp.name) / 'keep'
|
||||
outside.mkdir()
|
||||
(outside / 'precious.txt').write_text('keep')
|
||||
try:
|
||||
os.symlink(outside, directory / 'data' / 'link', target_is_directory=True)
|
||||
except OSError:
|
||||
self.skipTest('symlinks are not available')
|
||||
(directory / 'data' / 'nested').mkdir()
|
||||
(directory / 'data' / 'nested' / 'file').write_text('x')
|
||||
plan = registry.identity(self.base, directory.name, 18083)
|
||||
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'abc'}))
|
||||
registry.remove(self.base, directory.name, plan, 'abc')
|
||||
self.assertFalse(directory.exists())
|
||||
self.assertEqual((outside / 'precious.txt').read_text(), 'keep')
|
||||
|
||||
def test_remove_requires_the_removing_mark_of_the_same_plan(self):
|
||||
"""Fails if a directory not marked by this plan's operation can be deleted."""
|
||||
directory, record = make(self.base)
|
||||
plan = registry.identity(self.base, directory.name, 18083)
|
||||
with self.assertRaisesRegex(RuntimeError, 'not marked as being removed'):
|
||||
registry.remove(self.base, directory.name, plan, 'abc')
|
||||
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'other'}))
|
||||
with self.assertRaisesRegex(RuntimeError, 'not marked as being removed'):
|
||||
registry.remove(self.base, directory.name, plan, 'abc')
|
||||
self.assertTrue((directory / 'data' / 'cacu.db').exists())
|
||||
|
||||
def test_remove_refuses_a_directory_whose_identity_differs_from_the_plan(self):
|
||||
"""Fails if a directory that is not the one the plan named (another device or inode) is deleted."""
|
||||
directory, record = make(self.base)
|
||||
plan = registry.identity(self.base, directory.name, 18083)
|
||||
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'abc'}))
|
||||
for changed in (dict(plan, directory=[0, 0]), dict(plan, ownership='legacy'), dict(plan, project='isssteleon-dev-1')):
|
||||
with self.subTest(changed), self.assertRaisesRegex(RuntimeError, 'changed since the plan'):
|
||||
registry.remove(self.base, directory.name, changed, 'abc')
|
||||
self.assertTrue((directory / 'data' / 'cacu.db').exists())
|
||||
|
||||
def test_failed_removal_keeps_the_record_last(self):
|
||||
"""Fails if the record is deleted before the data, which would hide a half-removed instance."""
|
||||
directory, record = make(self.base)
|
||||
plan = registry.identity(self.base, directory.name, 18083)
|
||||
registry.write_record(directory, dict(record, status='removing', reinstall={'digest': 'abc'}))
|
||||
original = os.unlink
|
||||
calls = []
|
||||
|
||||
def failing(path, *args, **kwargs):
|
||||
calls.append(Path(path).name)
|
||||
if Path(path).name == 'cacu.db':
|
||||
raise PermissionError('denied')
|
||||
return original(path, *args, **kwargs)
|
||||
|
||||
os.unlink = failing
|
||||
try:
|
||||
with self.assertRaises(PermissionError):
|
||||
registry.remove(self.base, directory.name, plan, 'abc')
|
||||
finally:
|
||||
os.unlink = original
|
||||
self.assertEqual(registry.read_record(directory)['status'], 'removing')
|
||||
|
||||
def test_check_port_fails_while_something_listens(self):
|
||||
"""Fails if a busy port is reported as free."""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.bind(('0.0.0.0', 0))
|
||||
sock.listen()
|
||||
with self.assertRaises(OSError):
|
||||
registry.check_port(sock.getsockname()[1])
|
||||
|
||||
def test_main_prints_json_for_lookup(self):
|
||||
"""Fails if the command-line entry stops printing the lookup result as JSON."""
|
||||
make(self.base)
|
||||
self.assertEqual(registry.dispatch(self.base, 'lookup', '-', '18083')['port'], 18083)
|
||||
self.assertIsNone(registry.dispatch(self.base, 'lookup', '-', '18099'))
|
||||
json.dumps(registry.dispatch(self.base, 'identity', 'isssteleon-dev-18083', json.dumps({'port': 18083})))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,322 +0,0 @@
|
||||
"""Exercise the fixed laboratory reset with synthetic SQLite storage and fake Docker."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import conservative
|
||||
import data_guard
|
||||
import dev
|
||||
import host
|
||||
import reset_lab_18080 as reset
|
||||
from test_conservative import fixture, change
|
||||
|
||||
OPERATION = 'a28cddb3dbda4ed48db577104c031b31'
|
||||
CANDIDATE = '9559cb2e36e7c07591808d5e17b004410008b72e'
|
||||
|
||||
|
||||
class Docker:
|
||||
"""Simulate only the target project's Docker operations and service verification."""
|
||||
compose = staticmethod(dev.compose)
|
||||
verify_config = staticmethod(dev.verify_config)
|
||||
|
||||
def __init__(self, root, original):
|
||||
self.root, self.original = root, original
|
||||
self.calls = []
|
||||
self.running = False
|
||||
self.fail_health = False
|
||||
self.fail_persistence = False
|
||||
|
||||
def config(self):
|
||||
service = {'image': self.original['images'][0], 'restart': 'unless-stopped',
|
||||
'environment': dict(conservative.PERSISTENT_ENV),
|
||||
'volumes': [{'type': 'bind', 'source': str(self.root / 'data'), 'target': '/data'}]}
|
||||
return {'name': reset.PROJECT, 'services': {'webapi': copy.deepcopy(service),
|
||||
'indicadores': copy.deepcopy(service), 'webapp': {'image': self.original['images'][1],
|
||||
'restart': 'unless-stopped', 'ports': [{'published': '18080', 'target': 80}]}}}
|
||||
|
||||
def run(self, args, **kwargs):
|
||||
args = list(map(str, args))
|
||||
self.calls.append(args)
|
||||
if args[:3] == ['docker', 'image', 'inspect']:
|
||||
return 'old-app' if 'webapi' in args[-1] else 'old-web'
|
||||
if 'config' in args:
|
||||
return json.dumps(self.config())
|
||||
if args[:2] == ['docker', 'ps']:
|
||||
return 'api worker web' if '-a' in ''.join(args[2:]) or self.running else ''
|
||||
if args[:2] == ['docker', 'inspect']:
|
||||
return json.dumps([{'Id': ident, 'Image': 'old-web' if name == 'webapp' else 'old-app',
|
||||
'Config': {'Image': self.original['images'][1 if name == 'webapp' else 0],
|
||||
'Env': [key + '=' + value for key, value in conservative.controlled_config(self.config())['services'][name].get('environment', {}).items()],
|
||||
'Entrypoint': conservative.controlled_config(self.config())['services'][name].get('entrypoint'),
|
||||
'Cmd': [],
|
||||
'Labels': {'com.docker.compose.project': reset.PROJECT,
|
||||
'com.docker.compose.service': name}},
|
||||
'State': {'Running': self.running}, 'Mounts': [] if name == 'webapp' else [
|
||||
{'Type': 'bind', 'Source': str(self.root / 'data'), 'Destination': '/data', 'RW': True}],
|
||||
'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped', 'MaximumRetryCount': 0}}}
|
||||
for ident, name in zip(('api', 'worker', 'web'), ('webapi', 'indicadores', 'webapp'))])
|
||||
if 'up' in args:
|
||||
self.running = True
|
||||
if self.fail_persistence:
|
||||
change(self.root, 'tea', "UPDATE patient SET value='changed'")
|
||||
return ''
|
||||
|
||||
def verify_services(self, cmd, port):
|
||||
if self.fail_health:
|
||||
raise RuntimeError('health failed')
|
||||
assert port == 18080 and self.running
|
||||
|
||||
def verify_existing_containers(self, original, base, helper):
|
||||
assert original == self.original and self.running
|
||||
return ['api', 'worker', 'web']
|
||||
|
||||
|
||||
class ResetTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
"""Create one failed lab, its immutable source archive and pre-activation backup."""
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name)
|
||||
root, self.contract, original = fixture(self.base)
|
||||
self.root = self.base / reset.PROJECT
|
||||
root.rename(self.root)
|
||||
self.original = dict(original, project=reset.PROJECT, revision=reset.ORIGINAL)
|
||||
self.archive = self.root / '.archive' / OPERATION
|
||||
self.archive.mkdir()
|
||||
for name in ('codigo', 'deploy'):
|
||||
shutil.copytree(self.root / name, self.archive / name)
|
||||
(self.archive / 'deploy' / '.env').write_text('')
|
||||
(self.archive / 'deploy' / 'docker-compose.yml').write_text('{}')
|
||||
(self.archive / 'installation.json').write_text(json.dumps(self.original))
|
||||
self.backup = self.base / '.backups' / reset.PROJECT / OPERATION
|
||||
self.backup.parent.mkdir(parents=True)
|
||||
origin = {key: self.original[key] for key in ('project', 'port', 'revision', 'gitlinks', 'images')}
|
||||
data_guard.create_backup(self.root / 'data', self.backup, self.contract, origin)
|
||||
self.failed = dict(self.original, status='update_failed', phase='recalculation-and-persistence',
|
||||
operation_id=OPERATION, target_revision=CANDIDATE,
|
||||
target_images=[f'isssteleon/{image}:{reset.PROJECT}-{CANDIDATE[:12]}-' + 'a' * 32
|
||||
for image in ('webapi', 'webapp')],
|
||||
target_gitlinks={'ISSSTELEON': 'b' * 40},
|
||||
backup=str(self.backup), archive=str(self.archive))
|
||||
host.write_record(self.root, self.failed)
|
||||
change(self.root, 'tea', "UPDATE patient SET value='failed recalculation'")
|
||||
(self.root / 'codigo' / 'version.txt').write_text('candidate')
|
||||
self.api = Docker(self.root, self.original)
|
||||
self.reset = reset.LabReset(self.base, self.api, shutil.copytree, operation=OPERATION)
|
||||
self.guard = patch.object(conservative, 'guard', return_value=self.contract)
|
||||
self.guard.start()
|
||||
self.addCleanup(self.guard.stop)
|
||||
self.freeze = patch.object(conservative, 'freeze_failed', side_effect=lambda *a: setattr(self.api, 'running', False))
|
||||
self.freeze.start()
|
||||
self.addCleanup(self.freeze.stop)
|
||||
self.host_users = patch.object(reset, 'no_host_users')
|
||||
self.host_users.start()
|
||||
self.addCleanup(self.host_users.stop)
|
||||
self.http = patch.object(reset, 'check_http')
|
||||
self.http.start()
|
||||
self.addCleanup(self.http.stop)
|
||||
|
||||
def test_check_does_not_change_installation(self):
|
||||
"""Fail if checking writes to the lab or creates its persistent recovery directory."""
|
||||
before = reset.tree(self.root)
|
||||
self.assertIn('eligible', self.reset.run('check'))
|
||||
self.assertEqual(reset.tree(self.root), before)
|
||||
self.assertFalse(self.reset.work.exists())
|
||||
self.assertFalse(any('up' in call for call in self.api.calls))
|
||||
|
||||
def add_script_links(self):
|
||||
"""Add the archived deployment script aliases to both code trees."""
|
||||
for directory in (self.archive / 'deploy', self.archive / 'codigo' / 'dist'):
|
||||
directory.mkdir(exist_ok=True)
|
||||
(directory / 'isssteleon.sh').write_text('#!/bin/sh\n')
|
||||
try:
|
||||
for name in ('estado.sh', 'actualizar.sh'):
|
||||
(directory / name).symlink_to('isssteleon.sh')
|
||||
except OSError as exc:
|
||||
self.skipTest('symbolic links unavailable: ' + str(exc))
|
||||
|
||||
def test_check_accepts_archived_script_links_without_changes(self):
|
||||
"""Check accepts relative aliases without changing the archived code or creating work."""
|
||||
self.add_script_links()
|
||||
before = [reset.code_tree(self.archive / name) for name in ('codigo', 'deploy')]
|
||||
self.assertIn('eligible', self.reset.run('check'))
|
||||
self.assertEqual(before, [reset.code_tree(self.archive / name) for name in ('codigo', 'deploy')])
|
||||
self.assertFalse(self.reset.work.exists())
|
||||
|
||||
@unittest.skipUnless(os.name == 'posix', 'archive copy uses POSIX cp and permissions')
|
||||
def test_apply_preserves_script_links_and_resume(self):
|
||||
"""Preparation copies aliases as links and retry validates the preserved trees."""
|
||||
self.add_script_links()
|
||||
self.reset.copy = reset.copy_preserved
|
||||
self.api.fail_health = True
|
||||
with self.assertRaisesRegex(RuntimeError, 'health failed'):
|
||||
self.reset.run('apply')
|
||||
for directory in (self.root / 'deploy', self.root / 'codigo' / 'dist'):
|
||||
for name in ('estado.sh', 'actualizar.sh'):
|
||||
self.assertTrue((directory / name).is_symlink())
|
||||
self.assertEqual(os.readlink(directory / name), 'isssteleon.sh')
|
||||
self.api.fail_health = False
|
||||
self.assertIn('recovered', self.reset.run('apply'))
|
||||
|
||||
def test_rejects_unsafe_code_links_and_persistent_links(self):
|
||||
"""Escaping, absolute, dangling and persistent links cannot pass validation."""
|
||||
self.add_script_links()
|
||||
directory = self.archive / 'deploy'
|
||||
link = directory / 'estado.sh'
|
||||
for destination in ('../../installation.json', str(directory / 'isssteleon.sh'), 'missing'):
|
||||
link.unlink()
|
||||
link.symlink_to(destination)
|
||||
with self.subTest(destination=destination), self.assertRaises(RuntimeError):
|
||||
self.reset.run('check')
|
||||
link.unlink()
|
||||
link.symlink_to('isssteleon.sh')
|
||||
(self.backup / 'data' / 'alias').symlink_to('tea.db')
|
||||
with self.assertRaisesRegex(RuntimeError, 'linked persistent'):
|
||||
self.reset.run('check')
|
||||
(self.backup / 'data' / 'alias').unlink()
|
||||
(self.root / 'data' / 'alias').symlink_to('tea.db')
|
||||
with self.assertRaisesRegex(RuntimeError, 'linked persistent'):
|
||||
self.reset.run('apply')
|
||||
self.assertFalse(self.reset.work.exists())
|
||||
|
||||
@unittest.skipUnless(hasattr(os, 'mkfifo'), 'FIFO requires POSIX')
|
||||
def test_rejects_special_code_entries(self):
|
||||
"""Code validation rejects special files even when no link points to them."""
|
||||
os.mkfifo(self.archive / 'deploy' / 'pipe')
|
||||
with self.assertRaisesRegex(RuntimeError, 'special tree entry'):
|
||||
self.reset.run('check')
|
||||
|
||||
def test_apply_restores_all_data_and_preserves_failure(self):
|
||||
"""Fail if recovery loses incident evidence or installs before checking services/storage."""
|
||||
self.assertIn('recovered', self.reset.run('apply'))
|
||||
active = host.read_record(self.root)
|
||||
self.assertEqual(active['status'], 'installed')
|
||||
self.assertEqual(active['revision'], reset.ORIGINAL)
|
||||
self.assertEqual(json.loads((self.reset.work / 'failed-record.json').read_text()), self.failed)
|
||||
self.assertEqual((self.reset.work / 'failed' / 'codigo' / 'version.txt').read_text(), 'candidate')
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'old')
|
||||
self.assertEqual(reset.tree(self.root / 'data'), reset.tree(self.backup / 'data'))
|
||||
config = json.loads((self.root / 'deploy' / 'docker-compose.yml').read_text())
|
||||
self.assertIn('gunicorn', config['services']['webapi']['entrypoint'])
|
||||
self.assertEqual(config['services']['indicadores']['environment']['INDICADORES_AL_INICIAR'], '0')
|
||||
self.assertEqual((self.root / 'deploy' / 'docker-compose.yml').stat().st_mode,
|
||||
(self.archive / 'deploy' / 'docker-compose.yml').stat().st_mode)
|
||||
self.assertEqual(self.reset.run('apply'), 'already recovered')
|
||||
|
||||
def test_refuses_corrupt_backup_and_active_writers(self):
|
||||
"""Fail if corrupt recovery data or active writers can reach the first swap."""
|
||||
self.api.running = True
|
||||
with self.assertRaisesRegex(RuntimeError, 'writers'):
|
||||
self.reset.run('apply')
|
||||
self.api.running = False
|
||||
(self.backup / 'data' / 'reportes' / 'imports.jsonl').write_text('corrupt')
|
||||
with self.assertRaisesRegex(RuntimeError, 'checksum'):
|
||||
self.reset.run('apply')
|
||||
self.assertFalse(self.reset.work.exists())
|
||||
|
||||
def test_startup_or_persistence_failure_stays_failed(self):
|
||||
"""Fail if health or protected-data changes are certified as a recovered lab."""
|
||||
self.api.fail_persistence = True
|
||||
with self.assertRaisesRegex(RuntimeError, 'contents changed'):
|
||||
self.reset.run('apply')
|
||||
self.assertEqual(host.read_record(self.root)['status'], 'update_failed')
|
||||
self.assertFalse((self.reset.work / 'complete').exists())
|
||||
self.assertFalse(self.api.running)
|
||||
self.assertTrue((self.reset.work / 'failed' / 'data').is_dir())
|
||||
preserved = reset.tree(self.reset.work / 'failed')
|
||||
self.api.fail_persistence = False
|
||||
self.reset.run('apply')
|
||||
self.assertEqual(reset.tree(self.reset.work / 'failed'), preserved)
|
||||
self.assertEqual(len(list(self.reset.work.glob('attempt-data-*'))), 1)
|
||||
|
||||
def test_missing_original_image_prevents_preparation(self):
|
||||
"""Fail if a missing original image reaches persistent preparation or container recreation."""
|
||||
run = self.api.run
|
||||
def missing(args, **kwargs):
|
||||
if list(args)[:3] == ['docker', 'image', 'inspect']:
|
||||
return ''
|
||||
return run(args, **kwargs)
|
||||
self.api.run = missing
|
||||
with self.assertRaisesRegex(RuntimeError, 'image missing'):
|
||||
self.reset.run('apply')
|
||||
self.assertFalse(self.reset.work.exists())
|
||||
|
||||
def test_swap_resumes_between_atomic_renames(self):
|
||||
"""Fail if an interrupted swap overwrites preserved evidence when resumed."""
|
||||
work = self.base / 'swap'
|
||||
(work / 'ready' / 'codigo').mkdir(parents=True)
|
||||
(work / 'failed').mkdir()
|
||||
(work / 'ready' / 'codigo' / 'version.txt').write_text('restored')
|
||||
(self.root / 'codigo').rename(work / 'failed' / 'codigo')
|
||||
reset.swap(self.root, work, 'codigo')
|
||||
reset.swap(self.root, work, 'codigo')
|
||||
self.assertEqual((self.root / 'codigo' / 'version.txt').read_text(), 'restored')
|
||||
self.assertEqual((work / 'failed' / 'codigo' / 'version.txt').read_text(), 'candidate')
|
||||
|
||||
def test_apply_resumes_after_swap_interruption(self):
|
||||
"""Fail if a crash between renames prevents resume or overwrites the failed tree."""
|
||||
rename = os.rename
|
||||
interrupted = False
|
||||
def crash(source, target):
|
||||
nonlocal interrupted
|
||||
if Path(source) == self.reset.work / 'ready' / 'codigo' and not interrupted:
|
||||
interrupted = True
|
||||
raise OSError('simulated interruption')
|
||||
return rename(source, target)
|
||||
with patch.object(reset.os, 'rename', side_effect=crash), self.assertRaises(OSError):
|
||||
self.reset.run('apply')
|
||||
preserved = reset.tree(self.reset.work / 'failed' / 'codigo')
|
||||
self.reset.run('apply')
|
||||
self.assertEqual(reset.tree(self.reset.work / 'failed' / 'codigo'), preserved)
|
||||
|
||||
def test_health_failure_can_be_retried_without_losing_evidence(self):
|
||||
"""Fail if retry after failed startup overwrites the original failed evidence."""
|
||||
self.api.fail_health = True
|
||||
with self.assertRaisesRegex(RuntimeError, 'health failed'):
|
||||
self.reset.run('apply')
|
||||
preserved = reset.tree(self.reset.work / 'failed')
|
||||
self.api.fail_health = False
|
||||
self.reset.run('apply')
|
||||
self.assertEqual(reset.tree(self.reset.work / 'failed'), preserved)
|
||||
|
||||
def test_wrong_incident_and_host_writer_rejected(self):
|
||||
"""Fail if another incident or an unexcluded host process can trigger recovery."""
|
||||
with patch.object(reset, 'no_host_users', side_effect=RuntimeError('active host writer')):
|
||||
with self.assertRaisesRegex(RuntimeError, 'host writer'):
|
||||
self.reset.run('apply')
|
||||
host.write_record(self.root, dict(self.failed, operation_id='0' * 32))
|
||||
with self.assertRaisesRegex(RuntimeError, 'incident identity'):
|
||||
self.reset.run('apply')
|
||||
self.assertFalse(self.reset.work.exists())
|
||||
|
||||
def test_candidate_revision_matches_incident_evidence(self):
|
||||
"""Distinct incident revisions pass only when both image tags and evidence agree."""
|
||||
for operation, revision in ((OPERATION, CANDIDATE),
|
||||
('8e68804b94f3447089e31467bab75934',
|
||||
'23ab1cb5f1e57251e8771af49010483d9a824ba3')):
|
||||
incident = reset.LabReset(self.base, self.api, shutil.copytree, operation=operation)
|
||||
if operation != OPERATION:
|
||||
shutil.copytree(self.archive, incident.archive)
|
||||
shutil.copytree(self.backup, incident.backup)
|
||||
tag = f'{reset.PROJECT}-{revision[:12]}-' + 'a' * 32
|
||||
record = dict(self.failed, target_revision=revision,
|
||||
operation_id=operation, backup=str(incident.backup), archive=str(incident.archive),
|
||||
target_images=['isssteleon/webapi:' + tag, 'isssteleon/webapp:' + tag])
|
||||
host.write_record(self.root, record)
|
||||
self.assertIn('eligible', incident.run('check'))
|
||||
host.write_record(self.root, dict(record, target_revision='f' * 40))
|
||||
with self.assertRaisesRegex(RuntimeError, 'candidate evidence'):
|
||||
incident.run('check')
|
||||
host.write_record(self.root, dict(self.failed, target_revision='../invalid'))
|
||||
with self.assertRaisesRegex(RuntimeError, 'candidate revision'):
|
||||
self.reset.run('check')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,72 +0,0 @@
|
||||
"""Check pinned metadata against real migrations using temporary empty databases.
|
||||
|
||||
Opt in with ISSSTELEON_CONTRACT_SOURCE and the candidate's locked schema packages.
|
||||
No application engine factory, migration environment or existing database is used.
|
||||
"""
|
||||
|
||||
from contextlib import closing
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import data_guard
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get('ISSSTELEON_CONTRACT_SOURCE'), 'candidate schema runtime not selected')
|
||||
class TargetContractTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
"""Import only Core and migration definitions from the selected source tree."""
|
||||
cls.source = Path(os.environ['ISSSTELEON_CONTRACT_SOURCE']).resolve()
|
||||
sys.path[:0] = [str(cls.source / name) for name in ('Core', 'Persistance')]
|
||||
cls.contract = data_guard.target_contract()
|
||||
|
||||
def setUp(self):
|
||||
"""Apply the real revision functions only to four disposable SQLite databases."""
|
||||
from alembic.config import Config
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from alembic.script import ScriptDirectory
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name) / 'data'
|
||||
self.root.mkdir()
|
||||
for domain in data_guard.DOMAINS:
|
||||
scripts = ScriptDirectory.from_config(Config(str(
|
||||
self.source / 'Persistance' / 'persistance' / domain / 'alembic.ini')))
|
||||
engine = create_engine('sqlite:///' + (self.root / (domain + '.db')).as_posix())
|
||||
try:
|
||||
with engine.begin() as connection:
|
||||
with Operations.context(MigrationContext.configure(connection)):
|
||||
for revision in reversed(list(scripts.walk_revisions())):
|
||||
revision.module.upgrade()
|
||||
connection.exec_driver_sql('CREATE TABLE alembic_version (version_num VARCHAR(32) PRIMARY KEY)')
|
||||
connection.exec_driver_sql('INSERT INTO alembic_version VALUES (?)',
|
||||
(self.contract[domain]['head'],))
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
def test_migrated_schema_matches_candidate_metadata(self):
|
||||
"""Fail if real baseline/head databases would be refused by the metadata contract."""
|
||||
for domain in data_guard.DOMAINS:
|
||||
with self.subTest(domain=domain), closing(data_guard.readonly(self.root / (domain + '.db'))) as db:
|
||||
self.assertEqual(data_guard.schema(db), self.contract[domain]['schema'])
|
||||
data_guard.inspect_databases(self.root, self.contract)
|
||||
|
||||
def test_actual_schema_backup_restores_to_an_isolated_directory(self):
|
||||
"""Fail if schema validation or SQLite backup cannot recover the real pinned structures."""
|
||||
(self.root / 'witness.bin').write_bytes(b'synthetic persistent artifact')
|
||||
backup = Path(self.temp.name) / 'backup'
|
||||
data_guard.create_backup(self.root, backup, self.contract, {'synthetic': True})
|
||||
restored = Path(self.temp.name) / 'restored'
|
||||
data_guard.restore_backup(backup, restored)
|
||||
self.assertEqual((restored / 'witness.bin').read_bytes(), b'synthetic persistent artifact')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Pin the safety boundaries of the three DEV workflows using their checked-in YAML.
|
||||
|
||||
The fixture is the workflow text; no runner, network, Docker or dispatch is involved. Behaviour of the operations is
|
||||
covered by test_installer.py and test_dataload.py.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
WORKFLOWS = Path(__file__).resolve().parents[1] / 'workflows'
|
||||
INPUTS = {
|
||||
'deploy-dev.yml': ['puerto', 'referencia', 'confirmacion'],
|
||||
'reinstall-dev.yml': ['puerto', 'referencia', 'confirmacion'],
|
||||
'load-dev-data.yml': ['puerto', 'hospital', 'confirmacion'],
|
||||
}
|
||||
COMMANDS = {
|
||||
'deploy-dev.yml': 'installer.py install "$PORT" "$REFERENCE" "$CONFIRMATION"',
|
||||
'reinstall-dev.yml': 'installer.py reinstall "$PORT" "$REFERENCE" "$CONFIRMATION"',
|
||||
'load-dev-data.yml': 'installer.py load-data "$PORT" "$HOSPITAL" "$CONFIRMATION"',
|
||||
}
|
||||
|
||||
|
||||
def text_of(name):
|
||||
return (WORKFLOWS / name).read_text(encoding='utf-8')
|
||||
|
||||
|
||||
class WorkflowTests(unittest.TestCase):
|
||||
def test_inputs_are_exactly_those_the_operation_needs(self):
|
||||
"""Fails if a workflow gains an input (a free-form path, a flag) or loses its confirmation step."""
|
||||
for name, expected in INPUTS.items():
|
||||
with self.subTest(name):
|
||||
text = text_of(name)
|
||||
inputs = text.split(' inputs:\n', 1)[1].split('\njobs:', 1)[0]
|
||||
self.assertEqual(re.findall(r'^ (\w+):', inputs, re.M), expected)
|
||||
self.assertRegex(inputs, r'confirmacion:\n(?: .*\n)*? required: false')
|
||||
|
||||
def test_inputs_reach_the_installer_only_through_the_environment(self):
|
||||
"""Fails if an input is interpolated into a shell command, where a crafted value could run code."""
|
||||
for name, command in COMMANDS.items():
|
||||
with self.subTest(name):
|
||||
text = text_of(name)
|
||||
self.assertIn(command, text)
|
||||
for line in text.splitlines():
|
||||
if line.strip().startswith('run:'):
|
||||
self.assertNotIn('${{', line)
|
||||
|
||||
def test_dispatch_identity_is_verified_before_any_operation(self):
|
||||
"""Fails if the workflow stops checking the dispatched repository, server and commit before acting."""
|
||||
for name, command in COMMANDS.items():
|
||||
with self.subTest(name):
|
||||
text = text_of(name)
|
||||
for boundary in ('${{ gitea.ref }}', '${{ gitea.ref_name }}', '${{ gitea.ref_type }}',
|
||||
'ref: ${{ gitea.sha }}', 'installer.py validate-dispatch'):
|
||||
self.assertIn(boundary, text)
|
||||
self.assertLess(text.index('validate-dispatch'), text.index(command))
|
||||
|
||||
def test_no_global_cleanup_or_old_routing_in_the_workflows(self):
|
||||
"""Fails if a workflow acquires a prune, a compose down, a fixed laboratory port or the retired updater."""
|
||||
for name in INPUTS:
|
||||
with self.subTest(name):
|
||||
text = text_of(name)
|
||||
self.assertNotRegex(text, r'prune|compose down|docker rm|dev\.py|deploy-branch|install-auto')
|
||||
self.assertNotRegex(text, r'18080|18081|18087|4397')
|
||||
|
||||
def test_a_missing_confirmation_is_the_default(self):
|
||||
"""Fails if a workflow defaults to acting: an empty confirmation must be what a plain run sends."""
|
||||
for name in INPUTS:
|
||||
with self.subTest(name):
|
||||
inputs = text_of(name).split('confirmacion:\n', 1)[1].split('type: string', 1)[0]
|
||||
self.assertIn("default: ''", inputs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -11,9 +11,12 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PR_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
GIT_CONFIG_COUNT: 1
|
||||
GIT_CONFIG_COUNT: 2
|
||||
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
|
||||
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
|
||||
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
CACU_DATABASE_URL: 'sqlite:///:memory:'
|
||||
CAMA_DATABASE_URL: 'sqlite:///:memory:'
|
||||
TEA_DATABASE_URL: 'sqlite:///:memory:'
|
||||
@@ -61,20 +64,23 @@ jobs:
|
||||
run: python3 -m unittest discover -s .gitea/ci -p 'test_*.py' -v
|
||||
- name: Select checks
|
||||
id: select
|
||||
run: python3 .gitea/ci/select.py '${{ steps.candidate.outputs.base }}' '${{ steps.candidate.outputs.tree }}'
|
||||
run: python3 .gitea/ci/select_checks.py '${{ steps.candidate.outputs.base }}' '${{ steps.candidate.outputs.tree }}'
|
||||
- name: Test Docker probe
|
||||
if: steps.select.outputs.probe == 'true'
|
||||
run: python3 -m unittest discover -s .gitea/probe -p 'test_*.py' -v
|
||||
- name: Test DEV installer
|
||||
- name: Test DEV and terminal installers
|
||||
if: steps.select.outputs.deploy == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
set -e
|
||||
test -f .gitea/deploy/dev.py
|
||||
test -f .gitea/deploy/test_dev.py
|
||||
test -f .gitea/deploy/installer.py
|
||||
test -f .gitea/deploy/test_installer.py
|
||||
test -f .gitea/workflows/deploy-dev.yml
|
||||
test -f .gitea/workflows/reinstall-dev.yml
|
||||
test -f .gitea/workflows/load-dev-data.yml
|
||||
test -f .gitea/workflows/deploy-dev-diagnostic.yml
|
||||
python3 -m unittest discover -s .gitea/deploy -p 'test_*.py' -v
|
||||
python3 -m unittest discover -s .gitea/deploy-terminal -p 'test_*.py' -v
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
if: steps.select.outputs.python == 'true'
|
||||
- uses: actions/setup-node@v4
|
||||
@@ -130,12 +136,6 @@ jobs:
|
||||
continue-on-error: true
|
||||
working-directory: ISSSTELEON/models
|
||||
run: uv run --python 3.12 pytest -q -rs
|
||||
- name: indicadores_kit pytest
|
||||
id: indicadores
|
||||
if: steps.select.outputs.indicadores_kit == 'true'
|
||||
continue-on-error: true
|
||||
working-directory: ISSSTELEON/indicadores_kit
|
||||
run: uv run --python 3.12 pytest -q -rs
|
||||
- name: WebApi pytest
|
||||
id: webapi
|
||||
if: steps.select.outputs.WebApi == 'true'
|
||||
@@ -143,6 +143,10 @@ jobs:
|
||||
working-directory: ISSSTELEON/WebApi
|
||||
run: |
|
||||
tesseract --list-langs | grep -qx spa
|
||||
# The measures and the cycle read dbt's compiled manifest (`DBT_MANIFEST`); `dbt parse` leaves no SQL in it.
|
||||
(cd ../Transformation && uv run --python 3.12 dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect --target-path "$RUNNER_TEMP/dbt-manifest")
|
||||
test -s "$RUNNER_TEMP/dbt-manifest/manifest.json"
|
||||
export DBT_MANIFEST="$RUNNER_TEMP/dbt-manifest/manifest.json"
|
||||
uv sync --python 3.12 --extra sql-drivers
|
||||
uv run --python 3.12 pytest -q -rs
|
||||
- name: WebApp install, build and tests
|
||||
@@ -163,7 +167,6 @@ jobs:
|
||||
EXTRACTION: ${{ steps.extraction.outcome }}
|
||||
TRANSFORMATION: ${{ steps.transformation.outcome }}
|
||||
MODELS: ${{ steps.models.outcome }}
|
||||
INDICADORES: ${{ steps.indicadores.outcome }}
|
||||
WEBAPI: ${{ steps.webapi.outcome }}
|
||||
WEBAPP: ${{ steps.webapp.outcome }}
|
||||
CORE_REQUIRED: ${{ steps.select.outputs.Core }}
|
||||
@@ -171,12 +174,11 @@ jobs:
|
||||
EXTRACTION_REQUIRED: ${{ steps.select.outputs.Extraction }}
|
||||
TRANSFORMATION_REQUIRED: ${{ steps.select.outputs.Transformation }}
|
||||
MODELS_REQUIRED: ${{ steps.select.outputs.models }}
|
||||
INDICADORES_REQUIRED: ${{ steps.select.outputs.indicadores_kit }}
|
||||
WEBAPI_REQUIRED: ${{ steps.select.outputs.WebApi }}
|
||||
WEBAPP_REQUIRED: ${{ steps.select.outputs.WebApp }}
|
||||
run: |
|
||||
failed=0
|
||||
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS INDICADORES WEBAPI WEBAPP; do
|
||||
for name in CORE PERSISTANCE EXTRACTION TRANSFORMATION MODELS WEBAPI WEBAPP; do
|
||||
result=${!name:-skipped}
|
||||
required_var=${name}_REQUIRED
|
||||
required=${!required_var:-}
|
||||
|
||||
@@ -5,9 +5,12 @@ jobs:
|
||||
diagnostic:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GIT_CONFIG_COUNT: 1
|
||||
GIT_CONFIG_COUNT: 2
|
||||
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
|
||||
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
|
||||
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Inspect runner and dependencies
|
||||
|
||||
@@ -1,35 +1,52 @@
|
||||
name: deploy-dev
|
||||
|
||||
# Installs a disposable DEV instance on a free port. Without `confirmacion` it only shows the plan and the
|
||||
# confirmation that approves it; a second run with that confirmation installs. Use `reinstall-dev` to replace an
|
||||
# existing instance.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
puerto:
|
||||
description: Public WebApp port; create a new instance or conservatively update its existing data
|
||||
description: Free public port for the new instance
|
||||
required: true
|
||||
type: string
|
||||
referencia:
|
||||
description: WorkingNarrative branch, tag or full 40-character commit to install
|
||||
required: true
|
||||
default: dev
|
||||
type: string
|
||||
confirmacion:
|
||||
description: Leave empty to see the plan; paste the confirmation it prints to install
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
install:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PORT: ${{ inputs.puerto }}
|
||||
DISPATCH_REF: ${{ github.ref }}
|
||||
DISPATCH_SHA: ${{ github.sha }}
|
||||
GIT_CONFIG_COUNT: 1
|
||||
REFERENCE: ${{ inputs.referencia }}
|
||||
CONFIRMATION: ${{ inputs.confirmacion }}
|
||||
DISPATCH_REF: ${{ gitea.ref }}
|
||||
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
|
||||
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
|
||||
DISPATCH_SHA: ${{ gitea.sha }}
|
||||
DISPATCH_REPOSITORY: ${{ gitea.repository }}
|
||||
DISPATCH_SERVER: ${{ gitea.server_url }}
|
||||
GIT_CONFIG_COUNT: 2
|
||||
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
|
||||
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
|
||||
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
steps:
|
||||
- name: Require dev branch
|
||||
run: test "$DISPATCH_REF" = refs/heads/dev
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.sha }}
|
||||
ref: ${{ gitea.sha }}
|
||||
- name: Verify dispatched revision
|
||||
run: test "$(git rev-parse HEAD)" = "$DISPATCH_SHA"
|
||||
- name: Validate request
|
||||
run: python3 -B .gitea/deploy/dev.py validate-auto "$PORT"
|
||||
- name: Checkout pinned submodules
|
||||
run: git submodule update --init --recursive ISSSTELEON
|
||||
- name: Install or conservatively update instance
|
||||
run: python3 -B .gitea/deploy/dev.py install-auto "$PORT"
|
||||
run: python3 -B .gitea/deploy/installer.py validate-dispatch
|
||||
- name: Diagnose checkout origin
|
||||
run: python3 -B .gitea/deploy/origin_diagnostic.py
|
||||
- name: Plan, or install with the confirmation
|
||||
run: python3 -B .gitea/deploy/installer.py install "$PORT" "$REFERENCE" "$CONFIRMATION"
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
name: deploy-terminal-release
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Published release tag
|
||||
required: true
|
||||
type: string
|
||||
puerto:
|
||||
description: Public WebApp port
|
||||
required: true
|
||||
default: '18090'
|
||||
type: string
|
||||
puerto_api:
|
||||
description: Internal loopback WebApi port
|
||||
required: true
|
||||
default: '28090'
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
RELEASE_OUTPUT: release-output/release-source.tar.gz
|
||||
REQUESTED_TAG: ${{ inputs.tag }}
|
||||
REQUESTED_PORT: ${{ inputs.puerto }}
|
||||
REQUESTED_API_PORT: ${{ inputs.puerto_api }}
|
||||
RELEASE_TOKEN: ${{ gitea.token }}
|
||||
GIT_CONFIG_COUNT: 2
|
||||
GIT_CONFIG_KEY_0: url.${{ gitea.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
|
||||
GIT_CONFIG_KEY_1: url.${{ gitea.server_url }}/alberto/tea.git.insteadOf
|
||||
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
DISPATCH_REF: ${{ gitea.ref }}
|
||||
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
|
||||
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
|
||||
DISPATCH_SHA: ${{ gitea.sha }}
|
||||
DISPATCH_REPOSITORY: ${{ gitea.repository }}
|
||||
DISPATCH_SERVER: ${{ gitea.server_url }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ gitea.sha }}
|
||||
- name: Prepare release bundle
|
||||
run: |
|
||||
mkdir release-output
|
||||
python3 -B .gitea/deploy-terminal/resolve.py
|
||||
cp .gitea/deploy-terminal/{install.py,activate.py,verify.py,remote.py,bundle.py,source.py,README.md} release-output/
|
||||
- name: Install, activate and verify native services
|
||||
env:
|
||||
NATIVE_ACCOUNT: ${{ vars.NATIVE_ACCOUNT }}
|
||||
NATIVE_SSH_PORT: ${{ vars.NATIVE_SSH_PORT }}
|
||||
NATIVE_HOSTNAME: ${{ vars.NATIVE_HOSTNAME }}
|
||||
NATIVE_PARENT: ${{ vars.NATIVE_PARENT }}
|
||||
NATIVE_SSH_KEY: ${{ secrets.NATIVE_SSH_KEY }}
|
||||
NATIVE_KNOWN_HOSTS: ${{ secrets.NATIVE_KNOWN_HOSTS }}
|
||||
run: |
|
||||
set -eu
|
||||
: "${NATIVE_ACCOUNT:?Missing NATIVE_ACCOUNT}"
|
||||
: "${NATIVE_SSH_PORT:?Missing NATIVE_SSH_PORT}"
|
||||
: "${NATIVE_HOSTNAME:?Missing NATIVE_HOSTNAME}"
|
||||
: "${NATIVE_PARENT:?Missing NATIVE_PARENT}"
|
||||
: "${REQUESTED_API_PORT:?Missing puerto_api}"
|
||||
: "${NATIVE_SSH_KEY:?Missing NATIVE_SSH_KEY}"
|
||||
: "${NATIVE_KNOWN_HOSTS:?Missing NATIVE_KNOWN_HOSTS}"
|
||||
umask 077
|
||||
scratch=$(mktemp -d)
|
||||
trap 'rm -f "$scratch/key" "$scratch/known_hosts"; rmdir "$scratch"' EXIT
|
||||
printf '%s\n' "$NATIVE_SSH_KEY" > "$scratch/key"
|
||||
printf '%s\n' "$NATIVE_KNOWN_HOSTS" > "$scratch/known_hosts"
|
||||
checksum=$(python3 -c 'import json; print(json.load(open("release-output/release-record.json"))["bundle_sha256"])')
|
||||
python3 -B release-output/remote.py \
|
||||
--bundle-dir release-output --bundle-sha256 "$checksum" \
|
||||
--host 10.0.10.41 --ssh-port "$NATIVE_SSH_PORT" \
|
||||
--account "$NATIVE_ACCOUNT" --expected-hostname "$NATIVE_HOSTNAME" \
|
||||
--parent "$NATIVE_PARENT" --api-port "$REQUESTED_API_PORT" \
|
||||
--identity "$scratch/key" --known-hosts "$scratch/known_hosts"
|
||||
@@ -0,0 +1,43 @@
|
||||
name: load-dev-data
|
||||
|
||||
# Loads the simulated hospital (dev-data) into an installed, still empty DEV instance through the instance's own
|
||||
# import API. Without `confirmacion` it only shows the plan and the confirmation that approves it.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
puerto:
|
||||
description: Public port of the DEV instance to load
|
||||
required: true
|
||||
type: string
|
||||
hospital:
|
||||
description: Simulated hospital as host:port, as the instance's API reaches it
|
||||
required: true
|
||||
default: 10.0.10.41:9505
|
||||
type: string
|
||||
confirmacion:
|
||||
description: Leave empty to see the plan; paste the confirmation it prints to load
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
load:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PORT: ${{ inputs.puerto }}
|
||||
HOSPITAL: ${{ inputs.hospital }}
|
||||
CONFIRMATION: ${{ inputs.confirmacion }}
|
||||
DISPATCH_REF: ${{ gitea.ref }}
|
||||
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
|
||||
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
|
||||
DISPATCH_SHA: ${{ gitea.sha }}
|
||||
DISPATCH_REPOSITORY: ${{ gitea.repository }}
|
||||
DISPATCH_SERVER: ${{ gitea.server_url }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ gitea.sha }}
|
||||
- name: Verify dispatched revision
|
||||
run: python3 -B .gitea/deploy/installer.py validate-dispatch
|
||||
- name: Plan, or load with the confirmation
|
||||
run: python3 -B .gitea/deploy/installer.py load-data "$PORT" "$HOSPITAL" "$CONFIRMATION"
|
||||
@@ -0,0 +1,52 @@
|
||||
name: reinstall-dev
|
||||
|
||||
# Cleanly replaces a registered DEV instance: removes its containers, notebook jobs volume, network and directory
|
||||
# (data included), then installs the selected reference. Without `confirmacion` it only shows what would be removed
|
||||
# and the confirmation that approves exactly that plan.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
puerto:
|
||||
description: Public port of the DEV instance to replace
|
||||
required: true
|
||||
type: string
|
||||
referencia:
|
||||
description: WorkingNarrative branch, tag or full 40-character commit to install
|
||||
required: true
|
||||
default: dev
|
||||
type: string
|
||||
confirmacion:
|
||||
description: Leave empty to see the plan; paste the confirmation it prints to remove and reinstall
|
||||
required: false
|
||||
default: ''
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
reinstall:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PORT: ${{ inputs.puerto }}
|
||||
REFERENCE: ${{ inputs.referencia }}
|
||||
CONFIRMATION: ${{ inputs.confirmacion }}
|
||||
DISPATCH_REF: ${{ gitea.ref }}
|
||||
DISPATCH_REF_NAME: ${{ gitea.ref_name }}
|
||||
DISPATCH_REF_TYPE: ${{ gitea.ref_type }}
|
||||
DISPATCH_SHA: ${{ gitea.sha }}
|
||||
DISPATCH_REPOSITORY: ${{ gitea.repository }}
|
||||
DISPATCH_SERVER: ${{ gitea.server_url }}
|
||||
GIT_CONFIG_COUNT: 2
|
||||
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
|
||||
# The EEG library (models/libs/tea) lives outside the organisation and is read anonymously.
|
||||
GIT_CONFIG_KEY_1: url.${{ github.server_url }}/alberto/tea.git.insteadOf
|
||||
GIT_CONFIG_VALUE_1: ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ gitea.sha }}
|
||||
- name: Verify dispatched revision
|
||||
run: python3 -B .gitea/deploy/installer.py validate-dispatch
|
||||
- name: Diagnose checkout origin
|
||||
run: python3 -B .gitea/deploy/origin_diagnostic.py
|
||||
- name: Plan, or reinstall with the confirmation
|
||||
run: python3 -B .gitea/deploy/installer.py reinstall "$PORT" "$REFERENCE" "$CONFIRMATION"
|
||||
@@ -0,0 +1,4 @@
|
||||
graphify-out
|
||||
.claude/
|
||||
samples/
|
||||
ISSSTELEON-entrega/
|
||||
@@ -49,25 +49,14 @@ read only when a task points there (§5).
|
||||
notes or sessions, and nothing from this repo (rule 12). No filler either: don't
|
||||
restate what the code says, don't open with "This function...", no
|
||||
hedging, no notes addressed to a reviewer, no emojis.
|
||||
10. **Tasks fit in one session; work happens on branches off `dev`.** A
|
||||
10. **Tasks fit in one session; work happens directly on `dev`.** A
|
||||
task is sized so one session can finish it. Work that doesn't fit is a
|
||||
composite issue listing its tasks. `dev` is the integration branch, in
|
||||
this repo and in every submodule, and work happens on one of two kinds of
|
||||
branch off it:
|
||||
- a task branch, for a standalone task or a whole composite, named
|
||||
`<type>/<issue>-<slug>` after that issue with `<type>` from its `type/`
|
||||
label (for example `feature/12-timeline-repository`), merged once;
|
||||
- a working branch, for a line of work that spans several issues (for
|
||||
example `feature/model-proto`), with the same name in every repo it
|
||||
touches; it's merged into `dev` after each completed task, and work
|
||||
continues on it.
|
||||
this repo and in every submodule, and work happens directly on it, in
|
||||
every repo it touches; no task or working branches.
|
||||
In this repo each commit cites its issue (`(#124)`); in the deliverable
|
||||
tree it doesn't (rule 12), and the issue cites the commit and the pull
|
||||
request instead. Nothing is committed directly on
|
||||
`dev`. Pushing a branch needs explicit permission every time. Pull
|
||||
requests into `dev` are opened by a person in the Gitea UI, or by an
|
||||
agent when the owner asks for that specific pull request; agents never
|
||||
approve or merge them.
|
||||
tree it doesn't (rule 12), and the issue cites the commit instead.
|
||||
Pushing to `dev` needs explicit permission every time.
|
||||
11. **Every test says why it exists.** Each test module says what it covers
|
||||
and which fixtures it uses; each fixture says what data it sets up; each
|
||||
test says, in its docstring, what behaviour it pins down and which change
|
||||
@@ -81,6 +70,12 @@ read only when a task points there (§5).
|
||||
describe the change in their own terms. The link goes the other way:
|
||||
each WorkingNarrative issue cites the commits and pull requests that
|
||||
resolve it.
|
||||
13. **The deployment on port 5310 is not touched.** Its containers
|
||||
(`sitio-b-*`), volumes (`sitio-b_*`) and images (`sitio-b/*`) hold the
|
||||
analysed real-data deployment: no `up`, `down`, `restart`, `recreate`,
|
||||
`load`, import, promote or analysis, and no `docker exec` that writes.
|
||||
Reading its API (GET requests) is fine. New deployments use another
|
||||
project name, ports and subnet.
|
||||
|
||||
---
|
||||
|
||||
@@ -104,14 +99,14 @@ ISSSTELEON/ (outer) this WorkingNarrative repo: AGENTS.md, reference PD
|
||||
├── models/ submodule: train/predict interface, cohorts, registry, OCR jobs
|
||||
├── WebApi/ submodule: Flask API (also holds `webapi.orquestacion`, the Hamilton-based ETL graph)
|
||||
├── WebApp/ submodule: Angular 22 + Material
|
||||
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080)
|
||||
└── docker-compose.yml webapi (gunicorn, :5050) + webapp (nginx, :8080) + indicadores + notebooks (isolated notebook runner)
|
||||
```
|
||||
|
||||
Commands below are given relative to the inner `ISSSTELEON/` checkout (where
|
||||
actual development happens) unless noted otherwise; `../` reaches this outer
|
||||
repo's own files (`../e2e/`, `../docs_desarrollo-2.pdf`, etc.).
|
||||
|
||||
Dependencies (uv path deps): WebApi → Persistance, models[export], Extraction ·
|
||||
Dependencies (uv path deps): WebApi → Persistance, models[notebooks], Extraction ·
|
||||
models → Persistance, Extraction · Persistance → Core · Extraction → (no
|
||||
internal deps). Each Python package has its own `uv` env: `cd <pkg> && uv run pytest -q`.
|
||||
|
||||
@@ -123,11 +118,21 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
|
||||
## 3. Git state of the local working tree
|
||||
|
||||
- **`dev` is where work happens**, in this repo and in every submodule
|
||||
(`WebApi`, `WebApp`, `models`, `indicadores_kit`), all on the `ISSSTELEON`
|
||||
org Gitea: each piece of work is a branch off `dev`, merged back by a pull
|
||||
request (rule 10). Other branches are not used for new work. In
|
||||
`indicadores_kit`, `origin` is our org copy; `upstream` is the external
|
||||
fork (read-only).
|
||||
(`WebApi`, `WebApp`, `models`), all on the `ISSSTELEON` org Gitea: each
|
||||
piece of work lands directly on `dev` (rule 10). Other branches are not
|
||||
used for new work. `indicadores_kit` is no longer a submodule: its jobs
|
||||
live in `Transformation/`, the WebApi and `models` (kit exit, 2026-11-15);
|
||||
the repo stays on Gitea for its notebooks.
|
||||
- **Changes flow `dev` → `staging` → `main`.** Changes are made directly on
|
||||
`dev`, then passed on to `staging`, and finally to `main`, which is what
|
||||
is handed off for installation. `staging` and `main` are never worked on
|
||||
directly, so `dev` must always contain both; the pending alignment is in
|
||||
`docs/ledgers/open-items.md`.
|
||||
- When SSH to Gitea is refused, the repos can still be read over HTTP
|
||||
without credentials (read-only):
|
||||
`git fetch http://10.0.10.41:3000/ISSSTELEON/<repo>.git '+refs/heads/*:refs/remotes/origin/*'`
|
||||
(`<repo>`: `WorkingNarrative`, `ISSSTELEON`, `WebApi`, `WebApp`, `models`).
|
||||
Pushing still needs SSH or a token.
|
||||
- This file lives outside the submodule, in the outer WorkingNarrative repo
|
||||
(`ISSSTELEON/../AGENTS.md`) — versioned there instead of the prior
|
||||
gitignored-local-notes setup, so it has real history and isn't lost on a
|
||||
@@ -143,7 +148,10 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
|
||||
one baseline generated from the models, verified upgrade/downgrade/upgrade
|
||||
on SQLite, MySQL 8, PostgreSQL 16 and SQL Server 2022; older revisions are
|
||||
gone, so a database stamped with them must start fresh):
|
||||
- tea `a3e1c7b90d12`, cacu `b4f2d8c01e23`, cama `c5a3e9d12f34`, governance `d6b4f0e23a45` -> `e7c5a1f34b56`
|
||||
- tea `a3e1c7b90d12` -> `f2b6d1e8c934` -> `6d772e9a342f` and `a7d3c9e5b160` -> `b9e4d2c71a05` (the join) -> `16bf0b0ee3e4` (EEG analysis outputs, `eeg_criterio`) -> `c4306f438b3a` (the four old criterion columns dropped) -> `41694156d3a1` (ADOS-2 association tables) and `c3f6a9e42d53` (risk index date) -> `e8c2a5d47f13` (their join) -> `98dadd777ffd` (`eeg_metrica_zona`);
|
||||
cacu `b4f2d8c01e23` -> `f89e1f081998`; cama `c5a3e9d12f34` -> `f82b64f43abd` (`cat_sistema_fuente`,
|
||||
`cat_mapeo`); governance `d6b4f0e23a45` -> `e7c5a1f34b56`. The TEA chain and the join verified
|
||||
upgrade/downgrade/upgrade on SQLite only.
|
||||
|
||||
---
|
||||
|
||||
@@ -153,7 +161,7 @@ Databases: four independent ones (`CACU_`, `CAMA_`, `TEA_`,
|
||||
never a `human-only` one. Read its **Done when** criteria and the
|
||||
documents its **Context** field names.
|
||||
- A task fits in one session; bigger work is a composite issue whose tasks
|
||||
share one branch off `dev` (rule 10). Whatever the task doesn't resolve
|
||||
all land on `dev` (rule 10). Whatever the task doesn't resolve
|
||||
goes to a ledger in `docs/ledgers/` and is cited in the issue; the task
|
||||
doesn't grow to absorb it.
|
||||
- Finish by moving the issue to `status/needs-review` with the evidence
|
||||
@@ -177,8 +185,9 @@ Read these only when a task points there (its `area/*` label or its **Context**
|
||||
|
||||
| What | Where |
|
||||
|---|---|
|
||||
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (indicator computation), `other.md` |
|
||||
| What each component contains | `docs/architecture/<area>.md`, named after the `area/*` label: `webapi.md` (import pipeline), `extraction.md` (documents, EEG), `models.md` (OCR jobs, governance, model versioning), `indicadores-kit.md` (the retired kit; measures now live in `Transformation/`, see `webapi.md`), `other.md` |
|
||||
| Live testing against real infrastructure | `docs/operations/`: `local-dashboard.md`, `fork-source.md`, `mysql-tunnel.md`, `docker-engines.md`, `seed-pipeline-verify.md`, `browser.md`, `dev-data-ingest.md` |
|
||||
| Plans and decisions | `plans/` |
|
||||
| What the contract promises against what exists | `docs/scope-status.md` |
|
||||
| How to test and run each package | `docs/testing.md` |
|
||||
| History of past sessions | `docs/history/sessions.md` (the original §6, §7, §8.1, §9 and §10 of this file) |
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# Written by build.sh on every build.
|
||||
requirements.lock
|
||||
constraints.txt
|
||||
.image
|
||||
@@ -0,0 +1,35 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Dask scheduler and workers for ISSSTELEON's TEA EEG batches (age baselines, EEG analysis). Build it with
|
||||
# ./build.sh, which writes requirements.lock and passes the ISSSTELEON checkout as the `isssteleon` build context.
|
||||
#
|
||||
# Only what the workers run: the tea library and the models package its tasks come from, with their dependencies
|
||||
# at the versions of the platform's lockfile (ISSSTELEON/WebApi/uv.lock). The same base as the platform's image,
|
||||
# so Python is the one distributed's version check expects.
|
||||
FROM python:3.12-slim
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.13.1 /uv /bin/uv
|
||||
|
||||
# One BLAS thread per worker process, as the platform's own local cluster does.
|
||||
ENV OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 \
|
||||
UV_SYSTEM_PYTHON=1 UV_NO_CACHE=1
|
||||
|
||||
COPY requirements.lock /opt/isssteleon/requirements.lock
|
||||
RUN uv pip install -r /opt/isssteleon/requirements.lock
|
||||
|
||||
# The workers unpickle models.tea.eeg tasks, which import models, tea, core and persistance.
|
||||
COPY --from=isssteleon Core /opt/isssteleon/Core
|
||||
COPY --from=isssteleon Persistance /opt/isssteleon/Persistance
|
||||
COPY --from=isssteleon Extraction /opt/isssteleon/Extraction
|
||||
COPY --from=isssteleon models /opt/isssteleon/models
|
||||
RUN uv pip install --no-deps \
|
||||
/opt/isssteleon/Core /opt/isssteleon/Persistance /opt/isssteleon/Extraction \
|
||||
/opt/isssteleon/models/libs/tea /opt/isssteleon/models \
|
||||
&& python -c "import models.tea.eeg.train, models.tea.eeg.analyze, models.eeg_analysis, tea, distributed; print('distributed', distributed.__version__)"
|
||||
|
||||
COPY versions.py /opt/isssteleon/versions.py
|
||||
RUN useradd --uid 10001 --create-home dask
|
||||
USER dask
|
||||
WORKDIR /home/dask
|
||||
|
||||
ARG ISSSTELEON_COMMIT=unknown
|
||||
LABEL org.opencontainers.image.title="isssteleon-dask" isssteleon.commit=$ISSSTELEON_COMMIT
|
||||
@@ -0,0 +1,97 @@
|
||||
# Dask cluster for the TEA EEG batches
|
||||
|
||||
A Kubernetes Dask cluster (dask-operator `DaskCluster`) that runs ISSSTELEON's TEA EEG work: training the age
|
||||
baselines on a local reference folder and, if the deployment points at it, the EEG analysis. The image holds only
|
||||
what those tasks run: the `tea` library and the `models` package, with their dependencies.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `Dockerfile` | the scheduler and worker image |
|
||||
| `build.sh` | resolves `requirements.lock` against the platform's lockfile, builds, checks versions, pushes |
|
||||
| `cluster.yaml` | the `isssteleon-eeg` DaskCluster: 10 worker pods (one per machine) x 4 processes, NodePorts 30786 and 30787 |
|
||||
| `loader.yaml`, `sync-reference.sh` | copy a local EDF folder into the `eeg-data` volume the workers read |
|
||||
| `deploy.sh` | applies the cluster with the built image and prints the scheduler address |
|
||||
| `versions.py` | the versions `build.sh` compares between this image and the platform's |
|
||||
|
||||
## Why the image is built this way
|
||||
|
||||
The platform submits the jobs from its `webapi` container and connects with distributed's version check, which
|
||||
refuses a scheduler or workers whose dask, distributed, cloudpickle, msgpack, tornado or Python differ. The
|
||||
workers also unpickle tasks such as `models.tea.eeg.analyze.reference`, which import `models`, `tea`, `core` and
|
||||
`persistance`. So:
|
||||
|
||||
- **The platform's base image**, `python:3.12-slim`, so Python is the one the platform runs.
|
||||
- **ISSSTELEON's packages** (`Core`, `Persistance`, `Extraction`, `models`, `models/libs/tea`) from the checkout
|
||||
you build from, which must be the commit the deployment runs. The image tag carries it
|
||||
(`dask:isssteleon-<commit>`).
|
||||
- **Their dependencies at the platform's exact versions**: `build.sh` exports `ISSSTELEON/WebApi/uv.lock` as
|
||||
constraints and resolves the five packages against it, plus bokeh for the scheduler's dashboard. Nothing else is
|
||||
installed: no S3 client (the workers read local folders), no notebooks, no OCR binaries.
|
||||
- It runs as an unprivileged user (uid 10001). The loader pod runs as root to write the volume.
|
||||
|
||||
## Before the first build
|
||||
|
||||
- `uv`, Docker with BuildKit, and `kubectl` pointing at the cluster, which runs the dask-operator.
|
||||
- The ISSSTELEON checkout next to this folder (`../ISSSTELEON`, submodules checked out), at the deployment's commit.
|
||||
- Docker on this machine allowed to push to `192.168.20.18:5000` (an `insecure-registries` entry if it is
|
||||
plain HTTP), and the cluster's nodes allowed to pull from it.
|
||||
- A `PersistentVolumeClaim` named `eeg-data` that every node can mount: `ReadWriteMany`, since the loader writes
|
||||
it while workers on several nodes read it.
|
||||
- The platform's deployment built once (`docker compose up --build -d` in `../manual-deploy`), so `build.sh` can
|
||||
compare versions with its image.
|
||||
|
||||
## Build, load the reference folder, deploy
|
||||
|
||||
```sh
|
||||
cd dask-cluster
|
||||
./build.sh # resolve, build, compare with the platform, push
|
||||
```
|
||||
|
||||
Put the ages table inside the folder first. Its columns are `archivo` (file name only) and `edad_meses` or
|
||||
`edad_anos`. Without one, ages come from each EDF's header. For Helsinki HK1K, whose headers have no birth date:
|
||||
|
||||
```sh
|
||||
cp ~/datos/edades-helsinki.csv ~/datos/helsinki/edades.csv
|
||||
./sync-reference.sh ~/datos/helsinki helsinki # -> /referencia/helsinki on every worker
|
||||
./deploy.sh # prints DASK_SCHEDULER_ADDRESS=tcp://<node>:30786
|
||||
```
|
||||
|
||||
## Train on the cluster
|
||||
|
||||
From `../manual-deploy`, with the address `deploy.sh` printed. The folder is mounted at the same path the
|
||||
workers see, so the same command also works without the cluster (drop the `-e`):
|
||||
|
||||
```sh
|
||||
docker compose run --rm \
|
||||
-e DASK_SCHEDULER_ADDRESS=tcp://<node>:30786 \
|
||||
--entrypoint /app/WebApi/.venv/bin/python \
|
||||
-v "$HOME/datos/helsinki:/referencia/helsinki:ro" \
|
||||
webapi -m models run tea eeg --train --environment prod \
|
||||
--reference-dir /referencia/helsinki --reference-ages /referencia/helsinki/edades.csv \
|
||||
--reference-name sitio-a --line-hz 50
|
||||
```
|
||||
|
||||
The listing and every study's measurement run on the workers, which read the files from the volume. Training each
|
||||
baseline on the measured features runs in the `webapi` container and registers in the deployment's MLflow.
|
||||
Follow it on the dashboard (`http://<node>:30787/status`).
|
||||
|
||||
To send the deployment's EEG analysis to the cluster too, set `DASK_SCHEDULER_ADDRESS` in `../manual-deploy/.env`
|
||||
and restart `webapi` and `indicadores`. Each EDF's bytes travel with its task, so the analysis needs no volume.
|
||||
|
||||
## Keep it in step
|
||||
|
||||
- **Rebuild after any change to ISSSTELEON** (models, tea, Core, Persistance, the WebApi lockfile), then
|
||||
`./deploy.sh` again. An image from another commit is refused by the version check or runs old code.
|
||||
- `./deploy.sh --delete` removes the cluster. The volume and its folders stay.
|
||||
- Scale with `kubectl scale daskcluster isssteleon-eeg --replicas N` or by editing `replicas`.
|
||||
|
||||
## If something fails
|
||||
|
||||
| What you see | What to do |
|
||||
|---|---|
|
||||
| `ValueError: Mismatched versions found` on the client | the image was built from another ISSSTELEON commit than the deployment: rebuild |
|
||||
| `no folder /referencia/<name>` from a worker | the folder wasn't synced, or `--reference-dir` names another one: `./sync-reference.sh` |
|
||||
| `KeyError: 'posterior_rhythm_hz'` while training | no study had an age in 16 to 36 months: check the ages table is in the folder and passed with `--reference-ages` |
|
||||
| Worker pods `Pending` | not enough memory or CPU per node for 22Gi and 5 CPUs, or the claim can't attach on several nodes |
|
||||
| `ErrImagePull` | the nodes can't pull from `192.168.20.18:5000` |
|
||||
| `build.sh` stops on `versions differ` | the platform's image is older or newer than the checkout: rebuild the deployment, or check out its commit |
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env bash
|
||||
# Builds the Dask image for ISSSTELEON's EEG batches and pushes it to the cluster's registry: the tea library and the
|
||||
# models package, with their dependencies at the platform's locked versions.
|
||||
#
|
||||
# ./build.sh resolve, build, compare with the platform's webapi image, push
|
||||
# ./build.sh --no-push the same without pushing
|
||||
# ./build.sh --resolve-only only write requirements.lock
|
||||
#
|
||||
# Environment:
|
||||
# ISSSTELEON_DIR the ISSSTELEON checkout the platform runs (default: ../ISSSTELEON)
|
||||
# REGISTRY where the image goes (default: 192.168.20.18:5000)
|
||||
# WEBAPI_IMAGE the platform's image to compare versions with (default: <COMPOSE_PROJECT_NAME>/webapi:local
|
||||
# from ../manual-deploy/.env); the comparison is skipped if that image isn't on this machine
|
||||
#
|
||||
# Writes requirements.lock, constraints.txt and .image (the tag deploy.sh applies).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
mode=${1:-push}
|
||||
ISSSTELEON_DIR=$(realpath "${ISSSTELEON_DIR:-../ISSSTELEON}")
|
||||
REGISTRY=${REGISTRY:-192.168.20.18:5000}
|
||||
LOCAL_PACKAGES=(Core Persistance Extraction models/libs/tea models)
|
||||
|
||||
for p in "${LOCAL_PACKAGES[@]}"; do
|
||||
[[ -f "$ISSSTELEON_DIR/$p/pyproject.toml" ]] || { echo "no $p in $ISSSTELEON_DIR (ISSSTELEON_DIR, submodules checked out?)" >&2; exit 1; }
|
||||
done
|
||||
commit=$(git -C "$ISSSTELEON_DIR" rev-parse --short HEAD)
|
||||
if [[ -n "$(git -C "$ISSSTELEON_DIR" status --porcelain --untracked-files=no)" ]]; then
|
||||
echo "warning: $ISSSTELEON_DIR has uncommitted changes; the image gets them, its tag says $commit-dirty" >&2
|
||||
commit="$commit-dirty"
|
||||
fi
|
||||
|
||||
echo "== constraints from $ISSSTELEON_DIR/WebApi/uv.lock"
|
||||
(cd "$ISSSTELEON_DIR/WebApi" && uv export --frozen --no-dev --no-hashes --no-emit-project) \
|
||||
| grep -v '^-e ' > constraints.txt
|
||||
|
||||
echo "== requirements.lock"
|
||||
input=$(mktemp --suffix=.in)
|
||||
trap 'rm -f "$input"' EXIT
|
||||
for p in "${LOCAL_PACKAGES[@]}"; do echo "$ISSSTELEON_DIR/$p"; done > "$input"
|
||||
# bokeh serves the scheduler's dashboard (port 8787); without it the status page is empty.
|
||||
echo "bokeh>=3.1" >> "$input"
|
||||
uv pip compile "$input" --python-version 3.12 --no-header --quiet \
|
||||
--constraint constraints.txt \
|
||||
--no-emit-package core --no-emit-package persistance --no-emit-package extraction \
|
||||
--no-emit-package tea --no-emit-package models \
|
||||
-o requirements.lock
|
||||
grep -E '^(dask|distributed|bokeh|numpy|pandas|mne|yasa)==' requirements.lock | tr '\n' ' '; echo
|
||||
[[ "$mode" == "--resolve-only" ]] && exit 0
|
||||
|
||||
image="$REGISTRY/dask:isssteleon-$commit"
|
||||
echo "== building $image"
|
||||
docker build --build-context isssteleon="$ISSSTELEON_DIR" --build-arg ISSSTELEON_COMMIT="$commit" -t "$image" .
|
||||
|
||||
if [[ -z "${WEBAPI_IMAGE:-}" && -f ../manual-deploy/.env ]]; then
|
||||
project=$(sed -n 's/^COMPOSE_PROJECT_NAME=//p' ../manual-deploy/.env | tail -1)
|
||||
[[ -n "$project" ]] && WEBAPI_IMAGE="$project/webapi:local"
|
||||
fi
|
||||
if [[ -n "${WEBAPI_IMAGE:-}" ]] && docker image inspect "$WEBAPI_IMAGE" >/dev/null 2>&1; then
|
||||
echo "== versions against $WEBAPI_IMAGE"
|
||||
ours=$(docker run --rm "$image" python /opt/isssteleon/versions.py | tail -1)
|
||||
theirs=$(docker run --rm -i --entrypoint /app/WebApi/.venv/bin/python "$WEBAPI_IMAGE" - < versions.py | tail -1)
|
||||
python3 - "$ours" "$theirs" <<'EOF'
|
||||
import json, sys
|
||||
ours, theirs = (json.loads(a) for a in sys.argv[1:])
|
||||
bad = []
|
||||
for k in sorted(set(ours) | set(theirs)):
|
||||
a, b = ours.get(k), theirs.get(k)
|
||||
if k == "python":
|
||||
if a != b:
|
||||
bad.append(f"python {a} here, {b} in the platform (distributed refuses even a patch difference: "
|
||||
"rebuild the platform with `docker compose build --pull`, then this image the same day)")
|
||||
elif a != b:
|
||||
bad.append(f"{k} {a} here, {b} in the platform")
|
||||
if bad:
|
||||
sys.exit("versions differ from the platform:\n " + "\n ".join(bad))
|
||||
print("same versions as the platform")
|
||||
EOF
|
||||
else
|
||||
echo "warning: no platform image to compare with (WEBAPI_IMAGE); build the deployment first to check" >&2
|
||||
fi
|
||||
|
||||
echo "$image" > .image
|
||||
if [[ "$mode" == "--no-push" ]]; then
|
||||
echo "built $image (not pushed)"
|
||||
exit 0
|
||||
fi
|
||||
echo "== pushing $image"
|
||||
docker push "$image"
|
||||
echo "pushed $image; next: ./sync-reference.sh <folder> <name>, then ./deploy.sh"
|
||||
@@ -0,0 +1,59 @@
|
||||
# The Dask cluster for ISSSTELEON's TEA EEG batches. Apply it with ./deploy.sh, which fills in __IMAGE__.
|
||||
#
|
||||
# Workers read reference EDFs from the eeg-data volume, mounted read-only at /referencia: a cohort uploaded with
|
||||
# `./sync-reference.sh <folder> <name>` is /referencia/<name>, the path given to --reference-dir. The volume is
|
||||
# shared by every worker on every node, so the claim must be ReadWriteMany (or ReadOnlyMany once loaded).
|
||||
#
|
||||
# Its own name and NodePorts, so it runs next to other Dask clusters.
|
||||
apiVersion: kubernetes.dask.org/v1
|
||||
kind: DaskCluster
|
||||
metadata:
|
||||
name: isssteleon-eeg
|
||||
spec:
|
||||
worker:
|
||||
replicas: 10
|
||||
spec:
|
||||
topologySpreadConstraints:
|
||||
- maxSkew: 1
|
||||
topologyKey: kubernetes.io/hostname
|
||||
whenUnsatisfiable: DoNotSchedule
|
||||
labelSelector:
|
||||
matchLabels:
|
||||
dask.org/cluster-name: isssteleon-eeg
|
||||
dask.org/component: worker
|
||||
containers:
|
||||
- name: worker
|
||||
image: __IMAGE__
|
||||
# One pod per machine (the spread constraint above), 4 worker processes per pod, one thread each, at the
|
||||
# 4.25 GiB a study needs; 4 x 4.25 GiB fits in 19Gi. To go to 5 per pod, use 22Gi and 5 CPUs.
|
||||
args: [dask, worker, --name, $(DASK_WORKER_NAME), --nworkers, "4", --nthreads, "1", --memory-limit, 4.25GiB]
|
||||
resources:
|
||||
requests: {memory: 19Gi, cpu: "4"}
|
||||
limits: {memory: 19Gi}
|
||||
env:
|
||||
- name: NODE_NAME
|
||||
valueFrom:
|
||||
fieldRef: {fieldPath: spec.nodeName}
|
||||
volumeMounts:
|
||||
- {name: referencia, mountPath: /referencia, readOnly: true}
|
||||
volumes:
|
||||
- name: referencia
|
||||
persistentVolumeClaim: {claimName: eeg-data, readOnly: true}
|
||||
scheduler:
|
||||
spec:
|
||||
containers:
|
||||
- name: scheduler
|
||||
# The same image as the workers: the platform checks the scheduler's versions too.
|
||||
image: __IMAGE__
|
||||
args: [dask, scheduler]
|
||||
ports:
|
||||
- {name: tcp-comm, containerPort: 8786}
|
||||
- {name: http-dashboard, containerPort: 8787}
|
||||
service:
|
||||
type: NodePort
|
||||
selector:
|
||||
dask.org/cluster-name: isssteleon-eeg
|
||||
dask.org/component: scheduler
|
||||
ports:
|
||||
- {name: tcp-comm, port: 8786, targetPort: tcp-comm, nodePort: 30786}
|
||||
- {name: http-dashboard, port: 8787, targetPort: http-dashboard, nodePort: 30787}
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env bash
|
||||
# Applies cluster.yaml with the image ./build.sh pushed, waits for the scheduler and prints the address the
|
||||
# platform uses.
|
||||
#
|
||||
# ./deploy.sh create or update the cluster
|
||||
# ./deploy.sh --delete remove it
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
name=isssteleon-eeg
|
||||
if [[ "${1:-}" == "--delete" ]]; then
|
||||
kubectl delete daskcluster "$name"
|
||||
exit 0
|
||||
fi
|
||||
IMAGE=${IMAGE:-$(cat .image 2>/dev/null || true)}
|
||||
[[ -n "$IMAGE" ]] || { echo "no image: run ./build.sh first, or set IMAGE" >&2; exit 1; }
|
||||
|
||||
sed "s#__IMAGE__#$IMAGE#g" cluster.yaml | kubectl apply -f -
|
||||
|
||||
selector="dask.org/cluster-name=$name,dask.org/component=scheduler"
|
||||
for _ in $(seq 60); do
|
||||
kubectl get pod -l "$selector" -o name 2>/dev/null | grep -q . && break
|
||||
sleep 5
|
||||
done
|
||||
kubectl wait --for=condition=Ready pod -l "$selector" --timeout=600s
|
||||
|
||||
node=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}')
|
||||
port=$(kubectl get service "$name-scheduler" -o jsonpath='{.spec.ports[?(@.name=="tcp-comm")].nodePort}' 2>/dev/null || echo 30786)
|
||||
dashboard=$(kubectl get service "$name-scheduler" -o jsonpath='{.spec.ports[?(@.name=="http-dashboard")].nodePort}' 2>/dev/null || echo 30787)
|
||||
echo
|
||||
echo "scheduler: DASK_SCHEDULER_ADDRESS=tcp://$node:${port:-30786}"
|
||||
echo "dashboard: http://$node:${dashboard:-30787}/status"
|
||||
echo "workers: kubectl get pods -l dask.org/cluster-name=$name,dask.org/component=worker"
|
||||
@@ -0,0 +1,22 @@
|
||||
# A short-lived pod with the eeg-data volume mounted read-write, so sync-reference.sh can copy a local folder
|
||||
# into it. sync-reference.sh fills in __IMAGE__ and deletes the pod when the copy is done.
|
||||
apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: isssteleon-eeg-loader
|
||||
labels: {app: isssteleon-eeg-loader}
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
containers:
|
||||
- name: loader
|
||||
image: __IMAGE__
|
||||
# The image runs as an unprivileged user; root here so it can write wherever the volume's owner allows.
|
||||
securityContext: {runAsUser: 0}
|
||||
command: [sleep, "86400"]
|
||||
resources:
|
||||
requests: {memory: 256Mi, cpu: "250m"}
|
||||
volumeMounts:
|
||||
- {name: referencia, mountPath: /referencia}
|
||||
volumes:
|
||||
- name: referencia
|
||||
persistentVolumeClaim: {claimName: eeg-data}
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env bash
|
||||
# Copies a local folder of reference EDFs into the eeg-data volume, where every worker reads it at
|
||||
# /referencia/<name>. Put the ages table (`archivo`, `edad_meses` or `edad_anos`) inside the folder first.
|
||||
#
|
||||
# ./sync-reference.sh ~/datos/helsinki helsinki
|
||||
#
|
||||
# Files already there with the same name are overwritten; nothing is deleted, and files left there by an earlier
|
||||
# sync don't affect the check, which compares each file of the local folder with its copy. Uses the image in
|
||||
# .image (or IMAGE) for the short-lived loader pod, so the cluster needs no other image.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
folder=${1:?usage: sync-reference.sh <local folder> <name>}
|
||||
name=${2:?usage: sync-reference.sh <local folder> <name>}
|
||||
[[ -d "$folder" ]] || { echo "no folder $folder" >&2; exit 1; }
|
||||
[[ "$name" =~ ^[A-Za-z0-9._-]+$ ]] || { echo "name: letters, digits, dot, dash or underscore only" >&2; exit 1; }
|
||||
IMAGE=${IMAGE:-$(cat .image 2>/dev/null || true)}
|
||||
[[ -n "$IMAGE" ]] || { echo "no image: run ./build.sh first, or set IMAGE" >&2; exit 1; }
|
||||
pod=isssteleon-eeg-loader
|
||||
|
||||
local_count=$(find "$folder" -type f -iname '*.edf' | wc -l)
|
||||
[[ "$local_count" -gt 0 ]] || { echo "no .edf files under $folder" >&2; exit 1; }
|
||||
find "$folder" -maxdepth 1 -iname '*.csv' | grep -q . || echo "warning: no .csv in $folder: ages will come from the EDF headers" >&2
|
||||
|
||||
sed "s#__IMAGE__#$IMAGE#g" loader.yaml | kubectl apply -f -
|
||||
trap 'rm -f "${server:-}" "${manifest:-}" "${expected:-}"; kill "${server_pid:-}" 2>/dev/null || true; kubectl delete pod "$pod" --wait=false >/dev/null 2>&1 || true' EXIT
|
||||
kubectl wait --for=condition=Ready "pod/$pod" --timeout=600s
|
||||
|
||||
echo "== copying $local_count EDF files from $folder to /referencia/$name"
|
||||
kubectl exec "$pod" -- mkdir -p "/referencia/$name"
|
||||
|
||||
# The bulk data flows over HTTP from this machine: the API server's exec stream is dropped
|
||||
# mid-transfer often enough that piping a large folder through kubectl exec never finishes.
|
||||
server=$(mktemp --suffix=.py)
|
||||
manifest=$(mktemp)
|
||||
cat > "$server" <<'EOF'
|
||||
import http.server, pathlib, sys
|
||||
|
||||
folder = pathlib.Path(sys.argv[1]).resolve()
|
||||
manifest = pathlib.Path(sys.argv[2]).read_bytes()
|
||||
|
||||
|
||||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, directory=str(folder), **kwargs)
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/__manifest":
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(manifest)))
|
||||
self.end_headers()
|
||||
self.wfile.write(manifest)
|
||||
return
|
||||
super().do_GET()
|
||||
|
||||
|
||||
http.server.ThreadingHTTPServer(("0.0.0.0", int(sys.argv[3])), Handler).serve_forever()
|
||||
EOF
|
||||
find "$folder" -type f -printf '%P\0' > "$manifest"
|
||||
port=${SYNC_PORT:-18777}
|
||||
python3 "$server" "$folder" "$manifest" "$port" >/dev/null 2>&1 &
|
||||
server_pid=$!
|
||||
cluster=$(kubectl config view -o jsonpath='{.contexts[?(@.name=="'"$(kubectl config current-context)"'")].context.cluster}')
|
||||
api=$(kubectl config view -o jsonpath='{.clusters[?(@.name=="'"$cluster"'")].cluster.server}')
|
||||
api_host=${api#http://}; api_host=${api_host#https://}; api_host=${api_host%%:*}
|
||||
host_ip=${SYNC_HOST_IP:-$(ip -4 route get "$api_host" | awk '{for (i = 1; i < NF; i++) if ($i == "src") {print $(i + 1); exit}}')}
|
||||
[[ -n "$host_ip" ]] || { echo "no host IP the pod can reach; set SYNC_HOST_IP" >&2; exit 1; }
|
||||
python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:$port/__manifest', timeout=5)" \
|
||||
|| { echo "the local HTTP server did not start (is port $port busy?)" >&2; exit 1; }
|
||||
|
||||
for attempt in $(seq 1 3); do
|
||||
if kubectl exec -i "$pod" -- python3 - "/referencia/$name" "http://$host_ip:$port" <<'EOF'; then
|
||||
import concurrent.futures, pathlib, sys, urllib.parse, urllib.request
|
||||
|
||||
dest, base = sys.argv[1], sys.argv[2]
|
||||
names = [n for n in urllib.request.urlopen(base + "/__manifest", timeout=30).read().decode().split("\0") if n]
|
||||
|
||||
|
||||
def fetch(name):
|
||||
target = pathlib.Path(dest, name)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
url = base + "/" + urllib.parse.quote(name)
|
||||
error = None
|
||||
for _ in range(5):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=300) as response, open(target, "wb") as out:
|
||||
while True:
|
||||
block = response.read(1 << 20)
|
||||
if not block:
|
||||
break
|
||||
out.write(block)
|
||||
return name, None
|
||||
except Exception as exc: # the next attempt rewrites the file
|
||||
error = exc
|
||||
return name, error
|
||||
|
||||
|
||||
failed = []
|
||||
with concurrent.futures.ThreadPoolExecutor(8) as pool:
|
||||
for i, (name, error) in enumerate(pool.map(fetch, names), 1):
|
||||
if error is not None:
|
||||
failed.append(name)
|
||||
if i % 100 == 0:
|
||||
print(f"{i}/{len(names)}", flush=True)
|
||||
if failed:
|
||||
print("failed: " + ", ".join(failed))
|
||||
sys.exit(1)
|
||||
print(f"downloaded {len(names)} files")
|
||||
EOF
|
||||
break
|
||||
fi
|
||||
if [[ $attempt == 3 ]]; then
|
||||
echo "the download keeps failing" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "download lost its exec stream, retrying" >&2
|
||||
done
|
||||
kill "$server_pid" 2>/dev/null || true
|
||||
server_pid=
|
||||
|
||||
# The workers run as an unprivileged user.
|
||||
kubectl exec "$pod" -- chmod -R a+rX "/referencia/$name"
|
||||
|
||||
# Each local file against its copy, by size: a missing or truncated file fails the sync by name.
|
||||
expected=$(mktemp)
|
||||
find "$folder" -type f -printf '%s\t%P\0' > "$expected"
|
||||
check='
|
||||
import os, sys
|
||||
dest, edfs, bad = sys.argv[1], 0, []
|
||||
for record in sys.stdin.buffer.read().decode().split("\0"):
|
||||
if not record:
|
||||
continue
|
||||
size, name = record.split("\t", 1)
|
||||
path = os.path.join(dest, name)
|
||||
got = os.path.getsize(path) if os.path.isfile(path) else None
|
||||
if got != int(size):
|
||||
bad.append(f"{name}: missing" if got is None else f"{name}: {got} of {size} bytes")
|
||||
elif name.lower().endswith(".edf"):
|
||||
edfs += 1
|
||||
print(edfs)
|
||||
print("\n".join(bad))
|
||||
sys.exit(1 if bad else 0)
|
||||
'
|
||||
if ! report=$(kubectl exec -i "$pod" -- python3 -c "$check" "/referencia/$name" < "$expected"); then
|
||||
echo "these files did not arrive whole:" >&2
|
||||
tail -n +2 <<< "$report" | head -20 >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "copied: $(head -1 <<< "$report") of $local_count EDF files to /referencia/$name, each at its local size"
|
||||
echo "train with: --reference-dir /referencia/$name$(find "$folder" -maxdepth 1 -iname '*.csv' -printf ' --reference-ages /referencia/'"$name"'/%f' -quit)"
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Prints, as JSON, the versions distributed's version check compares and the ones the EEG numbers depend on.
|
||||
|
||||
build.sh runs it in this image and in the platform's webapi image and refuses to push when they differ.
|
||||
"""
|
||||
import json
|
||||
import platform
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
|
||||
PACKAGES = ("dask", "distributed", "msgpack", "cloudpickle", "tornado", "toolz", "lz4",
|
||||
"numpy", "pandas", "scipy", "scikit-learn", "mne", "yasa", "antropy", "meegkit", "fooof", "tea")
|
||||
|
||||
|
||||
def _version(name: str) -> str | None:
|
||||
try:
|
||||
return version(name)
|
||||
except PackageNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
print(json.dumps({"python": platform.python_version(), **{p: _version(p) for p in PACKAGES}}, sort_keys=True))
|
||||
@@ -7,45 +7,122 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
Package `Extraction/extraction/`:
|
||||
- `readers/` — `DocumentReader` + `@register_reader`; `PdfReader` (text
|
||||
layer, Tesseract on pages without one, embedded image detection),
|
||||
`ImageReader` (PNG/JPG/multi-page TIFF). `combine_pages` builds one PDF
|
||||
from pages of several PDFs.
|
||||
`ImageReader` (PNG/JPG/multi-page TIFF), `TextReader` (fallback: plain
|
||||
text, one line per newline). `combine_pages` builds one PDF from pages of
|
||||
several PDFs.
|
||||
- Text layer: glyphs drawn several times a fraction of a point apart
|
||||
(fake bold) are deduplicated (`dedupe_chars`); every line keeps its
|
||||
words with their horizontal extent (`document.Line.words`).
|
||||
- OCR: a page that is mostly one scanned image is OCRed unless its text
|
||||
layer is substantial (a scanner may stamp a header over the scan); a
|
||||
page read with low confidence is retried at the orientation Tesseract's
|
||||
OSD detects. OCR lines carry word positions too.
|
||||
- `segmentation.py` — `Segmenter` subclasses: `auto`, `document`, `pages`
|
||||
(N per record), `key` (new record when the patient id changes; pages
|
||||
without id continue the previous record).
|
||||
- `nlp/` — `FieldSpec` (kind, labels, choices, pattern, scan_free_text,
|
||||
multiline); extractors `LabeledValueExtractor` (captions, multi-field
|
||||
lines, value under the label, fuzzy OCR-tolerant labels),
|
||||
`PatternExtractor`, `FreeTextMentionExtractor` (catalog terms in
|
||||
narrative, NegEx-style negation). Vocabulary of captions and clinical
|
||||
terms in `nlp/vocabulary.py` (extend there, no code changes).
|
||||
- `records.py` — `DocumentExtractor` and `RecordMerger` (same patient across
|
||||
multiline); extractors `LabeledValueExtractor`, `PatternExtractor`,
|
||||
`FreeTextMentionExtractor` (catalog terms in narrative, NegEx-style
|
||||
negation). Vocabulary of captions and clinical terms in
|
||||
`nlp/vocabulary.py` (extend there, no code changes); schema descriptions
|
||||
also become captions, without a leading item code or what follows a
|
||||
colon.
|
||||
- Layout handling, all general (no form-specific rules): several captions
|
||||
on one line; captions on one row with their values on the next, read
|
||||
per column from word positions; item numbers (`3.-`, `b)`) belong to the
|
||||
caption they precede and end the value before them; a value ends at a
|
||||
wide horizontal gap once it has started; abbreviated captions (`Fech.`)
|
||||
and dropped connectors (`de`, `del`) still match; a caption may run on a
|
||||
few words before its colon; a label right after a connector is the tail
|
||||
of a longer caption naming something else; an integer field never reads
|
||||
a date.
|
||||
- `nlp/discovery.py::discover_captions` — captions no `FieldSpec` claims,
|
||||
found anywhere a known label could be (several per line, numbered,
|
||||
heading a column) and read by the same extractor through temporary
|
||||
specs.
|
||||
- `template.py` — lines in the top or bottom margin that repeat (digits
|
||||
exact, letters OCR-tolerant) on documents of two or more different
|
||||
patients are the issuer's letterhead or footer; `DocumentExtractor`
|
||||
re-extracts the affected records without them. A header repeated only
|
||||
across one patient's documents is kept.
|
||||
- `records.py` — `DocumentExtractor` and `RecordMerger` (same key across
|
||||
pages/files, most confident value wins, confident disagreements become
|
||||
`FieldConflict`). `ExtractedRecord.discovered` also carries every caption
|
||||
no known `FieldSpec` claimed (`nlp/discovery.py::discover_captions`).
|
||||
- `readers/text.py` — `TextReader`, the fallback in `FALLBACK_READERS`:
|
||||
content that's neither a PDF nor an image, read as plain text (one page,
|
||||
one line per newline) as long as it decodes as one, instead of being
|
||||
rejected as an unsupported format.
|
||||
`FieldConflict`). `extract(..., source_fields=, record_keys=)`: values a
|
||||
structured source hands over per document (trusted over the page,
|
||||
including the key) and the record each document joins (documents sharing
|
||||
one merge; others stay apart even for the same patient).
|
||||
`ExtractedRecord.discovered` carries the captions no spec claimed.
|
||||
- WebApi side: `connectors/document.py` + `schemas/field_specs.py` (field
|
||||
specs derived from the target schema). Each row carries `documento` (the
|
||||
record's pages as one PDF), mappable to a file column. Corrections from
|
||||
the UI travel as `overrides`. Results cached per worker for repeated calls.
|
||||
A `document` source's `payload` may carry `sql` (a connection, `table` or
|
||||
`query`, `column`, `key_column`) instead of `files`: one document per
|
||||
row, the named column read as its bytes (a `varbinary(max)` PDF) or, via
|
||||
`TextReader`, as plain text — the same connector and extraction either way.
|
||||
record's pages as one PDF), mappable to a file column, and every
|
||||
discovered caption as a column of its own. Corrections from the UI travel
|
||||
as `overrides`; `include_pattern`/`exclude_pattern` keep or leave out
|
||||
documents by their text; unreadable documents are listed in `skipped`
|
||||
instead of failing the batch. Results cached per worker.
|
||||
- Documents stored in columns of any tabular source (SQL table or query,
|
||||
CSV, Excel, JSON): `connectors/document_columns.py::DocumentColumns`
|
||||
(document columns; `name_by`, `group_by` and `fields` as a column, a
|
||||
list of columns or a derived rule). Cells may hold the file as binary,
|
||||
hex or base64 text (`document_bytes`). Used by a `document` source's
|
||||
`sql` payload and by any import source's `documents` (see webapi.md).
|
||||
- `schemas/catalog_matching.py` + `services/catalog_commit_service.py`:
|
||||
a discovered caption is fuzzy-matched (`rapidfuzz`) against the project's
|
||||
catalog (`core/catalogos/<proyecto>.toml`); a close enough etiqueta reuses
|
||||
that `resultado_id`, otherwise one is minted
|
||||
(`indicadores_kit.registry.catalogos.add_resultado`) and synced. Written
|
||||
straight into `procedimiento`/`observacion` (no staging row for these),
|
||||
tagged with the sentinel `fuente_tabla` `catalogo_abierto` so it reads
|
||||
apart from every staging-derived row.
|
||||
opt-in per source (`catalog_fallback: true`). A discovered caption is
|
||||
fuzzy-matched (`rapidfuzz`) against the project's catalog
|
||||
(`core/catalogos/<proyecto>.toml`); only captions the catalog already
|
||||
knows are written, straight into `procedimiento`/`observacion`, tagged
|
||||
with the sentinel `fuente_tabla` `catalogo_abierto`. The import path never
|
||||
mints catalog entries (the catalog is versioned with the code);
|
||||
unmatched captions are counted, and the import report lists unused
|
||||
captions without their values (webapi.md).
|
||||
- WebApp: `DocumentReviewDialog` (records, value, confidence, method,
|
||||
source line and page, conflicts, image thumbnails, editable values).
|
||||
- Limits: NLP is rule-based (no trained model); images are located and
|
||||
shown, not classified, and only stored inside the record's PDF.
|
||||
source line and page, conflicts, image thumbnails, editable values,
|
||||
document filters; each value's assertion when it isn't affirmed, the
|
||||
other candidates as one-click picks, a warning on off-topic records).
|
||||
- Narrative layer (2026-11-13), all in `Extraction/` (`README.md` there has
|
||||
the method and references for VAR-04/VARM-05):
|
||||
- `nlp/context.py`: ConText/NegEx assertions (negated, hypothetical,
|
||||
historical, uncertain, presumed) with form-style answers after a mention
|
||||
(`Término: NO`) and a caption without its answer read as asserting
|
||||
nothing; sections from standalone headings (clinical, description,
|
||||
result, history, reference text), a caption with content qualifying only
|
||||
its line. Labels' values are only qualified by clinical and history
|
||||
sections, so a footer date under an interpretation guide still counts.
|
||||
- `FieldSpec` gained `anchors` (a generic answer like "POSITIVO" needs its
|
||||
concept before it), `severity` (most severe affirmed value wins),
|
||||
`negated_value` ("sin actividad epileptiforme" -> 0) and `unit`
|
||||
(`MeasurementExtractor`, ranges give their midpoint). Vocabulary for all
|
||||
of them, EEG terms (ACNS), narrative BI-RADS, Bethesda/LAST terms and
|
||||
section headings and triggers is in `nlp/vocabulary.py`.
|
||||
- `ocr_fold`: OCR look-alikes collapsed on both sides, as a fallback for
|
||||
labels and choices on OCR lines only.
|
||||
- Subject check: `DocumentExtractor(subject=, foreign=)` from
|
||||
`vocabulary.SUBJECTS` keyed by table name (`__table__.name`, e.g.
|
||||
`citologiacervical`). Only positive evidence gates: a record naming a
|
||||
foreign subject and not its own fills nothing; values held back from an
|
||||
off-topic segment come back if its merged record is on topic.
|
||||
- Every candidate is kept (`ExtractedRecord.candidates`) with features
|
||||
(no document text); `nlp/ranking.py` picks one: `HeuristicRanker`
|
||||
(confidence, with hypothetical and off-topic vetoed) or `LearnedRanker`
|
||||
(online logistic regression, AdaGrad + L2, blended with the heuristic
|
||||
until `TRUST_EXAMPLES`; the rules' vetoes hold until then).
|
||||
- `models/io/extraction_ranker.py` versions each domain's ranker as
|
||||
`<domain>-extraccion` (DEV version per batch, five routines, saved
|
||||
model). WebApi learns in line: `commit_sources` ->
|
||||
`review_learning.learn_from_reviews` (background, one worker) from
|
||||
records with `overrides` (corrected fields plus the rest as accepted).
|
||||
`python -m webapi.nlp evaluate|train` scores against / trains from an
|
||||
answer key (leave-one-document-out estimate first).
|
||||
- The connector fills the entity's `*_nlp_version` column with
|
||||
`extraction <version> + extraccion:<n>`; the review report carries
|
||||
`alternatives`, `on_topic` and `nlp_version`.
|
||||
- Development set: six real CaCu documents (cytology forms, HPV PCR
|
||||
reports, scanned biopsies) kept outside every repository; answer key in
|
||||
the session scratch only. Rules alone went from P 0.65 / R 0.85 to
|
||||
1.00 / 1.00 on them, and the leave-one-out ranker estimate is 1.00; both
|
||||
are fit on the same documents the rules were adjusted to.
|
||||
- Limits: images are located and shown, not classified, and only stored
|
||||
inside the record's PDF; the template rule needs at least two patients'
|
||||
documents in the batch.
|
||||
|
||||
### 5.4 EEG (TEA)
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
# indicadores-kit
|
||||
|
||||
Moved from `AGENTS.md` on 2026-11-03.
|
||||
Moved from `AGENTS.md` on 2026-11-03. **Retired on 2026-11-15:** the kit is no longer a submodule or a
|
||||
dependency. Its measures are dbt semantic models in `Transformation/`, answered on request by the WebApi as FHIR
|
||||
MeasureReports (`webapi/kpis.py`, `webapi/fhir/`); its silver load, reference tables and follow-up list are in
|
||||
`webapi/orchestration/` and `webapi/follow_up/`; its cohorts are in `models/cohorts/`. What follows describes the
|
||||
division of labor that still holds and the kit as it was.
|
||||
|
||||
### 5.6a Indicator computation — division of labor (clarified by the owner, 2026-10-19)
|
||||
|
||||
|
||||
@@ -14,19 +14,126 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
|
||||
### 5.5 Model versioning and cohorts (ML/MLD/EL)
|
||||
|
||||
- Governance DB tables (`Core/core/governance/`): ExtractionRun,
|
||||
CohortVersion, CohortMember, CohortExclusion, CohortExclusionCount,
|
||||
ModelVersion, ModelArtifact, ModelPrediction.
|
||||
- `models/models/registry.py` — `ModelRegistry`: register, attach reports,
|
||||
upload artifacts (checksummed, ONNX validated), status derived
|
||||
(desarrollo/candidata/produccion/retirada), `checks()` gates promotion
|
||||
(ML-02, ML-03, MLD-01, MLD-01b, MLD-03, ML-01b), retire, lineage, compare.
|
||||
- `models/models/cohort.py` — `CohortBuilder`, `ExclusionCriterion`,
|
||||
`@register_cohort_builder`. **No concrete builders exist**: clinical
|
||||
criteria are not defined in the requirements document, so production
|
||||
promotion is impossible until a scenario is registered.
|
||||
- `models/models/prediction.py` — `PredictionService` persists predictions
|
||||
tagged with the active version.
|
||||
- Routes `/governance/model-versions*`, `/governance/artifacts/<id>/download`,
|
||||
`/governance/cohort-scenarios`, `/governance/cohort-versions`. WebApp
|
||||
model-version detail dialog and cohort build menu.
|
||||
Versions, runs and their files live in MLflow; the cohorts a model trains on
|
||||
are the kit's builds (`cohorte_armado`) or dbt's, exported to Parquet files.
|
||||
|
||||
- `models/models/io/tracking.py`: `TrainingRun`, one MLflow run per training.
|
||||
It links the cohort build (ML-03), tags DEV/PROD (ML-02) and the git commit,
|
||||
saves the model (`log_model`, `modelo_sha`; PROD refuses a class defined in a
|
||||
notebook) and records each routine around training while it runs
|
||||
(`log_routine(kind, record)` → `rutinas/<KIND>.json`, counts and settings,
|
||||
never rows). `ROUTINE_KINDS` are the five of §5 of the requirements:
|
||||
MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES,
|
||||
CONFIANZA_SALIDA (`Core/core/governance/enums.py::ArtifactKind`, plus
|
||||
OTRO for any other file the run keeps). `run_files`/`run_file` list and
|
||||
download a run's files; a folder downloads as a zip.
|
||||
- `models/models/io/registry.py`: `registry`. Status is derived
|
||||
(desarrollo/candidata/produccion/retirada); `checks()` gates promotion:
|
||||
ML-02, ML-03, MLD-01 (metrics, technical report), MLD-01b, MLD-03, **ML-01a
|
||||
(all five routine records, written by the run) and ML-01b (the saved
|
||||
model)**. Only what the training run itself wrote counts: nothing can be
|
||||
uploaded to a version. `lineage()` returns every file of the run and the
|
||||
routine records; `artifact()` downloads one (ML-01b).
|
||||
- `models/models/cacu/cin2_logistic/model.py`: Hamilton nodes `sampling`,
|
||||
`missing_data`, `analytic_method`, `class_balance`, `output_confidence`
|
||||
(and `routines`, which gathers them) record what this training did:
|
||||
the temporal split, missing predictors as the `(none)` category,
|
||||
coefficients, class counts (no reweighting) and a calibration table.
|
||||
- Routes: `/governance/model-versions*` (list, register, reports, lineage,
|
||||
checks, promote, retire) and
|
||||
`GET /governance/model-versions/<d>/<s>/<v>/artifacts/<path>` (download).
|
||||
WebApp version dialog: checklist, cohort, the five routines (recorded or
|
||||
missing, each viewable), the run's files as downloads, reports, and
|
||||
"Probar en un notebook".
|
||||
- Removed 2026-11-13: uploading a file of any kind to a version (it let a
|
||||
hand-picked file satisfy ML-01b), and the ONNX checkpoint support with it
|
||||
(`ONNX_CHECKPOINT`, `inspect_onnx_metadata`, the `export` extra). Nothing
|
||||
produced an ONNX file and predictions never used one.
|
||||
|
||||
### 5.6 Notebooks run on the server (ML-01a, ML-04, ML-05)
|
||||
|
||||
A Jupyter notebook uploaded from the WebApp runs against one exported cohort
|
||||
build, isolated from the server, for development experiments.
|
||||
|
||||
- `models/models/pipelines/experiment.py`: `start` creates an MLflow run in
|
||||
`<domain>-<scenario>/experimentos`, tagged with the notebook's name and
|
||||
content hash, the build's file (`cohort_reference`), the chosen version and
|
||||
the code version, and stores the notebook without outputs. `execute` hands
|
||||
the job to an executor, then stores the page (`report/<name>.html`), what
|
||||
was imported (`importado.json`) and, if it failed, `error.txt`; the run is
|
||||
tagged `sandbox: contenedor|local`. Status: en_curso, terminado, fallido,
|
||||
interrumpido (running past `NOTEBOOK_JOB_TIMEOUT` + 30 min).
|
||||
- `models/models/io/notebook_jobs.py`: the job folder
|
||||
(`<NOTEBOOK_JOBS_DIR>/<run_id>/`: `notebook.ipynb`, a copy of the build's
|
||||
file `cohorte.parquet`, the chosen version's saved model `model/`,
|
||||
`job.json`), assembled aside and renamed into place, and handed to
|
||||
`NOTEBOOK_RUNNER_UID`. `run_job` runs it on the `python3` kernel with an
|
||||
environment built from the job alone: the build's file, `MODEL_PATH`, an
|
||||
MLflow store inside the job (`mlflow.db`, `artefactos/`), every
|
||||
`*_DATABASE_URL` set to `sqlite://`, HOME and temp folders inside the job;
|
||||
writes `page.html` and `result.json`. Executors (`EXECUTORS`,
|
||||
`register_executor`): `local` runs it in the API's process (development,
|
||||
unisolated); `contenedor` leaves it for the runner and waits
|
||||
(`NOTEBOOK_JOB_TIMEOUT`, 6 h). `NOTEBOOK_EXECUTOR` picks one; the default is
|
||||
`contenedor` when `NOTEBOOK_JOBS_DIR` is set. `serve` (`python -m models
|
||||
notebooks serve`) is the runner's loop; a job is claimed by creating
|
||||
`en_curso/` in it.
|
||||
- `models/models/io/notebook_import.py`: copies what the notebook trained
|
||||
into the platform's MLflow. Only `<domain>-<scenario>` experiments of the
|
||||
job's domain; each run becomes a new DEV run with the real cohort tags,
|
||||
`notebook.run_id`, the code version and a recomputed `modelo_sha`
|
||||
(`kit.armado_id` and the notebook's own `modelo_sha` are dropped); versions
|
||||
come across as DEV, never with an alias. The store is opened from a copy,
|
||||
files are walked without following links and must sit inside the job
|
||||
(`read_job_file`, `inside`), and `NOTEBOOK_MAX_IMPORT_MB` (500) caps them.
|
||||
All of it exists because the trusted side reads files an untrusted
|
||||
notebook wrote.
|
||||
- `models/models/notebook.py`: the API inside a notebook. `experiment()` →
|
||||
`.cohort()`, `.lineage()`, `.model()` (the job's copy, `MODEL_PATH`),
|
||||
`.training_run()` (a DEV `TrainingRun` linked to the build),
|
||||
`.register(run)`.
|
||||
- `models/models/io/rendering.py`: renderers as classes (`RENDERERS`,
|
||||
`register_renderer`): `quarto`, and `jupyter` (`nbclient` + `nbconvert`,
|
||||
the `notebooks` extra, which WebApi installs). `NOTEBOOK_RENDERER` picks
|
||||
one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT`
|
||||
(1800 s per cell).
|
||||
- `models/models/io/storage.py`: `exported_builds(root, domain)` and
|
||||
`build_file(root, url, source, build)`, read from the files alone.
|
||||
- Deployment: service `notebooks` in `docker-compose.yml` and
|
||||
`dist/docker-compose.yml`, the webapi image with command `notebooks`
|
||||
(`WebApi/docker-entrypoint.sh`): `network_mode: none`, `read_only`, tmpfs
|
||||
`/tmp`, user 10001, `cap_drop: ALL`, `no-new-privileges`, memory/CPU/PID
|
||||
limits, only the jobs volume at `/trabajos`. webapi mounts the same volume
|
||||
at the same path (the import checks paths as the runner wrote them) with
|
||||
`NOTEBOOK_JOBS_DIR=/trabajos` and `NOTEBOOK_RUNNER_UID=10001`.
|
||||
- WebApi (`webapi/blueprints/governance.py`): `GET /governance/cohort-files`,
|
||||
`GET|POST /governance/experiments` (multipart `file`, `domain`, `scenario`,
|
||||
`url`, `source`, `build`, `version?`; 202, executed in a thread pool,
|
||||
`WEBAPI_NOTEBOOK_WORKERS`, default 1),
|
||||
`GET /governance/experiments/<run_id>`, `.../page` (served with
|
||||
`Content-Security-Policy: sandbox`), `.../artifacts/<path>`.
|
||||
- WebApp: Gobernanza tab "Notebooks" (`experiments-panel`, polls while a run
|
||||
is in progress, flags "Sin aislar" runs) and `notebook-run-dialog` (also
|
||||
opened from a version).
|
||||
- Only `.ipynb` (nbformat 4) is accepted. Open items in
|
||||
`docs/ledgers/open-items.md`.
|
||||
|
||||
### TEA EEG training and analysis
|
||||
|
||||
- `models/models/tea/eeg/model.py` uses `EEG_ANALYSIS_CLUSTER` to select
|
||||
the runner that measures reference studies. It accepts `auto`, `local`,
|
||||
`remote`, and `sync`, and falls back to `auto` for `off` or an
|
||||
unrecognised value. Auto uses `DASK_SCHEDULER_ADDRESS` when configured.
|
||||
- `python -m models tea analyze --ids 12,34` reanalyses the specified EEGs
|
||||
regardless of pending status. `--ids` takes comma-separated database
|
||||
EEG IDs and is mutually exclusive with `--all` and `--limit`.
|
||||
- `tea.pipeline.cluster_status.ClusterStatus` reports the effective mode
|
||||
and remote health, including scheduler reachability, worker count,
|
||||
version compatibility, dashboard status, and reference volume visibility
|
||||
for the requested cohort.
|
||||
- `tea.pipeline.run_monitor.RunMonitor` publishes the current phase, counts,
|
||||
elapsed time, ETA, and recent samples during training and analysis. Dask
|
||||
runs include task counts and worker CPU and memory. When `RUN_PROGRESS_DIR`
|
||||
is set, the monitor atomically replaces `progress.json` in that directory.
|
||||
|
||||
See the [WebApi routes and detached job lifecycle](webapi.md#tea-eeg-governance).
|
||||
|
||||
@@ -23,4 +23,76 @@ Moved from `AGENTS.md` on 2026-11-03.
|
||||
`merge_duplicates` (opt-in, `merge_duplicates: true` on `/imports/commit`)
|
||||
combines rows of different sources sharing a natural key **before**
|
||||
validation (first source wins, disagreements reported as warnings).
|
||||
- **SQL sources** — `server.host` tolerates pasted forms (`host\instance`,
|
||||
`host,port`, `host:port`, JDBC/URI strings); a named instance without a
|
||||
port is left for the server to resolve. A user query is wrapped as a
|
||||
derived table, so a trailing `ORDER BY` that no TOP/LIMIT/OFFSET needs is
|
||||
dropped (SQL Server refuses it there). Every preview lists, in
|
||||
`document_columns`, the columns whose cells hold files.
|
||||
- **Mapping beyond one-to-one** — an import source may carry, besides
|
||||
`column_mapping` and `defaults`:
|
||||
- `derived`: `{field: rule}` computed from source columns
|
||||
(`imports/mapping/derived.py`; one `Derivation` class per operation plus
|
||||
`@register_derivation`): `column`, `concat`, `template`, `split`,
|
||||
`coalesce`, `extract`, `map`, with an optional `case`. Short forms: a
|
||||
column name or a list of columns. `GET /imports/derivations` describes
|
||||
them, and the WebApp builds its forms from it.
|
||||
- `documents`: columns holding documents (`DocumentColumns`, see
|
||||
extraction.md), with `group_by`, `name_by`, `fields`, `file_field` and
|
||||
the extraction settings. Values the mapping takes from the row's own
|
||||
columns are trusted over the page; then mapping and `derived` run again
|
||||
over each record's namespace (the rows' columns plus every field and
|
||||
caption its documents print), and extracted fields fill what's left.
|
||||
Rows without documents pass through mapped.
|
||||
- `catalog_fallback: true` to opt in to the catalog path (extraction.md).
|
||||
- Order: mapping and `derived` (one field can't be fed by both), document
|
||||
extraction, then `defaults` for anything still empty.
|
||||
- **Previews** — `POST /imports/mapped-preview` (`{source, limit}`: rows as
|
||||
they would be written); `POST /imports/sources/document/columns` (a source
|
||||
with `documents`: its columns plus the documents' fields and captions, as
|
||||
a preview with suggestions); `POST /imports/sources/document/extract`
|
||||
also takes `{source}` to review a mapping's documents.
|
||||
- **Import report (Bitácora de cargas)** — `imports/audit.py`, counts and
|
||||
shapes only, never record values. Per source it also lists the captions
|
||||
its documents print that nothing used (`etiquetas_sin_usar`, captions
|
||||
with how many records print them, from `WEBAPI_REPORT_MIN_COUNT` up;
|
||||
`etiquetas_sin_usar_poco_frecuentes` counts the rest).
|
||||
- Routes in `webapi/blueprints/imports.py`; `GET /api` lists every route.
|
||||
- WebApp: the flow editor's "Reglas" tab (`connect/components/mapping-rules`)
|
||||
sets document columns, derived fields and the catalog fallback, and shows
|
||||
the mapped preview.
|
||||
|
||||
### TEA EEG governance
|
||||
|
||||
The Gobernanza **TEA · EEG** panel uses these new and extended endpoints.
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|---|---|---|
|
||||
| GET | `/governance/tea/cluster` | Check the selected cluster mode, scheduler, versions, workers, dashboard, and optional reference cohort. |
|
||||
| GET | `/governance/tea/reference-cohorts` | List cohorts under `TEA_REFERENCE_ROOT`. |
|
||||
| POST | `/governance/tea/reference-cohorts/<name>/files` | Upload one EDF or `edades.csv` as multipart `file`. |
|
||||
| POST | `/governance/model-versions/tea/eeg/train-jobs` | Start training with optional cohort, line frequency, promotion, and cluster settings. |
|
||||
| GET | `/governance/tea/baselines/export` | Download the baseline ZIP with SHA-256 and version count headers. |
|
||||
| POST | `/governance/tea/baselines/import` | Import a multipart baseline ZIP and return its hash and imported versions. |
|
||||
| POST | `/governance/tea/eeg/analyze-jobs` | Start analysis for pending EEGs or select a limit, all EEGs, or explicit IDs. |
|
||||
| GET | `/governance/tea/eeg/analyze-jobs` | List analysis jobs, newest first. |
|
||||
| GET | `/governance/tea/eeg/analyze-jobs/<id>` | Read analysis job state and its summary when available. |
|
||||
| GET | `/governance/tea/jobs/<kind>/<job_id>/progress` | Read the latest training or analysis sample. Returns 404 before the first sample. |
|
||||
| GET | `/governance/tea/baselines/<scenario>/<version>/metrics` | List metrics with a baseline age curve. |
|
||||
| GET | `/governance/tea/baselines/<scenario>/<version>/curve` | Read the age percentiles for the requested `metric`. |
|
||||
| GET | `/governance/tea/eeg` | List EEGs with pagination and analysis status. |
|
||||
| GET | `/governance/tea/eeg/<eeg_id>/metrics` | Read study age, validity, metric values, z-scores, and outliers. |
|
||||
| POST | `/governance/tea/eeg/upload` | Validate and import one EDF via the import pipeline, with an optional patient ID. |
|
||||
| POST | `/governance/tea/eeg/preview` | Analyse one EDF (`edf`) and an optional ADOS-2 PDF (`ados2`) in memory and answer a patient-summary bundle with notices; nothing is stored. |
|
||||
| GET | `/governance/tea/eeg/summary` | Count EEGs, metrics, outliers, and FHIR view rows. |
|
||||
| POST | `/reportes/indicadores/tea/recalcular` | Queue a TEA indicator cycle. The contract specifies an optional cluster choice. The current handler queues the cycle using the service configuration. |
|
||||
|
||||
Reports, checks, promotion, and training job status use the existing governance
|
||||
routes. The cluster health endpoint uses the models-side `ClusterStatus`
|
||||
probe and accepts scheduler addresses from `DASK_SCHEDULER_ADDRESS` and
|
||||
`TEA_DASK_SCHEDULERS`.
|
||||
|
||||
`WebApi/webapi/detached_jobs.py` launches training and analysis as subprocesses
|
||||
in their own sessions. It records job metadata, stdout, stderr, and exit status
|
||||
in the job directory and passes that directory to the child as
|
||||
`RUN_PROGRESS_DIR`. The progress endpoint reads `progress.json` there.
|
||||
|
||||
@@ -2892,3 +2892,22 @@ code, given it adds a service to operate/secure? Lean toward only doing
|
||||
this if MLflow's web UI becomes independently useful for the team (e.g.
|
||||
browsing experiments/artifacts outside this app), not for the code
|
||||
reduction alone.
|
||||
|
||||
## 11. Indicator recompute moved from polling to a filesystem watch, 2026-11-13
|
||||
|
||||
`WebApi/webapi/indicadores_vivos.py`'s loop used to just sleep for
|
||||
`INDICADORES_INTERVALO_S` (default 20s) between checks of the
|
||||
`pendiente/<dominio>` marker directory. Replaced the sleep with a
|
||||
`watchdog` observer on that directory: any marker write now wakes the loop
|
||||
immediately (verified in a standalone smoke test: pickup in well under a
|
||||
second against a 100s fallback interval), and `INDICADORES_INTERVALO_S`
|
||||
stays only as a safety net for a missed or coalesced filesystem event, not
|
||||
the normal reaction time. `ColaDeRecalculo`'s marker/state semantics
|
||||
(`solicitar`/`tomar`/`atender`, the coalescing of requests that arrive
|
||||
mid-run) are unchanged; only how the loop wakes up moved. `watchdog` added
|
||||
as a WebApi dependency (`uv add watchdog`, pure Python, inotify on Linux).
|
||||
|
||||
This is the live mechanism G-DBT-3 (`docs/ledgers/grooming.md`) describes
|
||||
as "it drops a marker and the `indicadores` service runs the domain's
|
||||
cycle" — that description still holds; only the wake-up trigger inside it
|
||||
changed, not the cycle itself.
|
||||
|
||||
@@ -62,3 +62,31 @@ Something went wrong or was surprising while doing a task. Format and plan codes
|
||||
- **Decides:** owner.
|
||||
- **Decision:** 2026-11-05, owner: no past-date rebuilds for now, drop it from the export; a dbt snapshot may
|
||||
replace it in the future.
|
||||
|
||||
|
||||
### I-DBT-3. `cin2_logistic.predictors()` crashes the whole training run on a cohort member with a biopsy but no citología — high · open
|
||||
- **What happens:** `predictors()` builds each member's index sample from `citologia` rows only
|
||||
(`model.py`, lines ~61-68): `sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] ==
|
||||
cohort["fecha_indice"])]`, grouped by `pac_id`. For a cohort that includes a member with a `biopsia`
|
||||
row but no `citologia` row at all, `sample` comes back empty; the following
|
||||
`cohort.merge(sample, left_on="pac_id", right_index=True)` degenerates, and the resulting frame's
|
||||
implicit index ends up also named `pac_id` on top of the `pac_id` column already there. The later
|
||||
`pivot_table(index="pac_id", columns="tipo", values="valor_codigo", ...)` then raises
|
||||
`ValueError: 'pac_id' is both an index level and a column label, which is ambiguous`, which is
|
||||
unhandled and kills the whole run — not just that member's row.
|
||||
- **Evidence:** `docker compose ... run --rm entrenar` against a CaCu cohort containing one member with
|
||||
a `BiopsiaCervical` row (imported through the "documents in columns" connector) and no
|
||||
`CitologiaCervical` row for that patient. Full traceback bottoms out at
|
||||
`models/models/cacu/cin2_logistic/model.py:68`, in `predictors`, inside the `pivot_table` call.
|
||||
- **Consequence:** a cohort build with even one biopsy-only member (plausible: direct referral,
|
||||
partial/migrated history, a document-column import that only carries pathology results) blocks
|
||||
`entrenar` entirely for every member, not just that one. The model can't be trained at all until the
|
||||
offending member is removed from the cohort or the code tolerates the empty-sample case.
|
||||
- **Proposal:** make the empty-`sample` case produce `MISSING` predictors for that member instead of a
|
||||
malformed frame, e.g. reset the index after the merge (`results = cohort.merge(sample, left_on="pac_id",
|
||||
right_index=True).reset_index(drop=True)`) before the `pivot_table` call, or build `wide` from an
|
||||
explicit left-join against `members["pac_id"]` so a member with zero sample rows still gets a row of
|
||||
`MISSING` rather than disappearing and corrupting the frame's index naming. Add a unit test with a
|
||||
cohort containing one biopsy-only, no-citología member to pin this down.
|
||||
- **Decides:** owner (models package).
|
||||
- **Decision:**
|
||||
|
||||
@@ -293,3 +293,46 @@ Proposals that come up while doing a task and aren't resolved inside it. Each on
|
||||
from the indicator catalog and the gold YAML; one Hamilton node per indicator reads that declaration,
|
||||
as a MetricFlow `ratio` metric would.
|
||||
- **Issue:** #162
|
||||
|
||||
## G-GEN-1. Source terminology as catalog tables, editable from the UI
|
||||
- **Where:** `Core/core/catalogos/<dominio>.toml` (`codigos_hospital`, `etiquetas_fuente`, `alias`), the silver
|
||||
load's enum maps, `WebApi/webapi/orchestration/reference/source_mapping.py` (the mapping's rules) and
|
||||
`observacion_clinica.valor_fuente`.
|
||||
- **What happens:** how a lab provider or a medical-record header writes our codes lives in the catalog's TOML
|
||||
and in code. A provider change (new captions, spellings or test codes) needs a commit, a release and a deploy,
|
||||
and a deploy would overwrite any change made outside git.
|
||||
- **What it conflicts with:** rule 4 (two new tables); rule 2 (versioning has to work on every engine, so SQL
|
||||
Server's temporal tables can only be an add-on).
|
||||
- **Proposal:**
|
||||
1. Our codes (`cat_estudio`, `cat_resultado`, `cat_valor`) stay in the TOML, reviewed in git.
|
||||
2. How each source writes them moves to two tables, the database being their system of record:
|
||||
`cat_sistema_fuente` (who sends the data, by `fuente_tabla` and validity dates) and `cat_mapeo` (FHIR's
|
||||
ConceptMap: `clase` estudio, etiqueta or valor; the form and its normalized form; target; validity;
|
||||
`registrado_por`, `registrado_en`, `motivo`). Append-only; a deploy only inserts missing seed rows.
|
||||
3. The mapping is a partial, non-injective function `(system, resultado_id, normalized form, date) -> valor_id`
|
||||
into `cat_valor`. `source_mapping.check_function` already enforces it on the TOML; the UI and the API
|
||||
apply it on every save. `source_mapping.resolve` is the remap's rule: no mapping or two disagreeing
|
||||
mappings give no code, and the observation goes back to the out-of-catalog queue.
|
||||
4. A remap step on every cycle and on demand rewrites only `valor_id` where the code changes, under a
|
||||
`carga` of its own (`conocida_en` keeps reports cut before it reproducible). A new caption or study code
|
||||
needs a re-extraction or a reload instead.
|
||||
5. A queue screen (source text with no code), a mappings screen per system, a curator role, and a
|
||||
`ConceptMap` endpoint.
|
||||
6. Versioning: validity dates in the table (what the pipeline reads, every engine); in production SQL Server,
|
||||
system-versioned temporal tables on both tables for the edit audit, a SQL Server-only revision that's a
|
||||
no-op elsewhere.
|
||||
- **Open questions:** where a report records the mappings it used (`toml_sha`, `huella` or `parametros`);
|
||||
mappings per system only or also global; whether the temporal tables are in scope now.
|
||||
- **Evidence:** draft and SQLite demo in `mock/borradores/catalogo-mapeo/` (`PROPUESTA.md`, `01_tablas.sql`,
|
||||
`02_demo.py`): seeding from the TOML changes 0 stored observations; a new lab's 5 unmapped spellings land in
|
||||
the queue and, once mapped and remapped, reach dbt's timeline, the stratifiers and the invasive-cancer event
|
||||
unchanged.
|
||||
- **Found in:** #163 (CaMa values read from reports), 2026-11-13.
|
||||
- **Status:** approved by the owner on 2026-11-13 and implemented on `feature/163-source-terminology` (every
|
||||
repository rebased on `dev`): ISSSTELEON `66c4ba5` (Core tables), `74eb5a4` (a revision per domain),
|
||||
`14dff24` (`SourceMappingRepository`), `d6e2c68` (dbt's `vigencias_sin_traslape` on `cat_mapeo`),
|
||||
`72d092d` (pointers); WebApi `64d3d72` (`source_mapping`: `check_function`, `resolve`), `73cbf0c` (seeding in
|
||||
the `catalogs` step, `register` checking the function on write). Layers 1 (write check), 2 (`UNIQUE` and
|
||||
check constraints) and 3 (dbt test) are in; pandera is left for a bulk import of mappings. Still open: loads
|
||||
read the TOML's aliases, not `cat_mapeo`; the remap step; the UI screens; the `ConceptMap` endpoint;
|
||||
migrations verified on SQLite only.
|
||||
|
||||
@@ -11,7 +11,288 @@ Moved from `AGENTS.md` §5.7 on 2026-11-03. Each item can become an issue.
|
||||
- No authentication/authorization on WebApi; SQL credentials travel from the
|
||||
browser on each call (mitigated by `SqlSourcePolicy`).
|
||||
- Cross-field validation rules not implemented in the import schemas.
|
||||
- No trained NLP model (options discussed: pretrained Spanish clinical
|
||||
model as an extra `FieldExtractor`, plus learning from review corrections;
|
||||
needs real anonymized reports to evaluate).
|
||||
- Document NLP (narrative layer and learned ranker, see
|
||||
`docs/architecture/extraction.md`), still open:
|
||||
- Only measured on six real CaCu documents, the same ones the rules were
|
||||
adjusted on; a held-out set (ideally 30+ per report type, with an answer
|
||||
key written by someone else) is needed for an honest score. EEG,
|
||||
mammography and breast biopsy vocabulary has never seen a real report.
|
||||
- The ranker trained on those six lives only in a scratch MLflow store;
|
||||
on the server it starts empty until `python -m webapi.nlp train` is run
|
||||
with a key, or reviewers correct imports.
|
||||
- `<domain>-extraccion` versions can't pass ML-03 (no cohort: they learn
|
||||
from documents), so they can't be promoted; extraction uses the latest
|
||||
DEV version. Needs a decision on how governance treats this model.
|
||||
- Learning runs in one background thread per WebApi process; with several
|
||||
gunicorn workers two batches can continue the same version and both
|
||||
register, the second not including the first's examples.
|
||||
- A correction teaches only if made in the review dialog before
|
||||
committing (it travels as `overrides`); fixing a value later in the
|
||||
database teaches nothing.
|
||||
- No pretrained Spanish clinical model; it would be one more
|
||||
`FieldExtractor` whose candidates the ranker weighs, once a held-out
|
||||
set exists to show it helps.
|
||||
- Colposcopy (Reid, Swede) has no columns, so it stays as text.
|
||||
- Possible DICOM connector for mammograms (`pydicom`, fits `mast_dicom_blob`).
|
||||
- A source may hold a biopsy and the cytology that led to it as separate
|
||||
orders with nothing linking them (no shared id in the rows or in the
|
||||
documents). The CaCu confirmation indicator only counts the biopsy a
|
||||
cytology originated (`BiopsiaCervical.cit_id`), so such biopsies read as
|
||||
"sin biopsia aún". Option: a general import rule that fills a link with
|
||||
the same patient's latest record of the parent kind dated on or before
|
||||
the child's date; needs a decision on the rule and its time window.
|
||||
- Which printed date counts as a cytology's sampling date is a per-source
|
||||
mapping choice (request or reception date), not code.
|
||||
- `documents.group_by` takes the source's own columns (or rules over
|
||||
them), not values read from the documents.
|
||||
- A user query starting with `WITH` can't be wrapped as a derived table on
|
||||
SQL Server (`connectors/sql.py::_text_subquery`).
|
||||
- Compose ports and the `ng serve` proxy target are fixed in
|
||||
`docker-compose.yml` and `WebApp/proxy.conf.json`; neither reads an env
|
||||
var yet.
|
||||
- The template-line rule (`Extraction/extraction/template.py`) needs at
|
||||
least two patients' documents in one batch; a single document still
|
||||
reads its letterhead.
|
||||
- Branch alignment, as of 2026-11-13: `dev` was pushed in all six repos
|
||||
and contains `staging` and `main` everywhere, except that
|
||||
`WorkingNarrative`'s `main` keeps one merge commit with identical content.
|
||||
`staging` and `main` are behind `dev` until the next promotion. SSH to
|
||||
Gitea refuses the local key; pushes went over HTTP with the API token.
|
||||
- Notebooks run in the `notebooks` container (no network, read-only system,
|
||||
uid 10001, no capabilities, only the jobs volume), and what they train is
|
||||
imported by trusted code (`models.io.notebook_import`). Still open:
|
||||
- The app has no login, so anyone who reaches it can upload a notebook,
|
||||
and its page (which may print cohort rows) is readable by anyone.
|
||||
- The container was validated with `docker compose config` and tested as a
|
||||
separate process, not yet started as a real container.
|
||||
- Local development (`NOTEBOOK_EXECUTOR=local`, the default without
|
||||
`NOTEBOOK_JOBS_DIR`) runs notebooks unisolated in the API's process; runs
|
||||
say so (`sandbox: local`, "Sin aislar" in the WebApp).
|
||||
- A WebApi worker that restarts while waiting leaves its run "en curso"
|
||||
until it shows as "interrumpido" (job timeout + 30 min) and its job
|
||||
folder behind; nothing picks the result up again.
|
||||
- A version registered over `POST /governance/model-versions` has no routine
|
||||
records or saved model, so it fails ML-01a/ML-01b and can't be promoted;
|
||||
production versions come only from training code in `models`.
|
||||
- ML-01b is met by downloading a run's files; there is no portable model
|
||||
export (ONNX support was removed 2026-11-13 as unused).
|
||||
- The notebook tab needs exported cohort builds on the server
|
||||
(`python -m models cohorts export ...`), and the WebApi image must be
|
||||
rebuilt to get the Jupyter libraries (`models[notebooks]`).
|
||||
- `cin2_logistic`'s routine records (`model.py`) are the only real ones;
|
||||
any new model has to add its own five, or it can't be promoted.
|
||||
|
||||
### TEA redesign (#163, branch `feature/163-tea-redesign` off `refactor/kit-exit`), 2026-11-12
|
||||
|
||||
Left open by the implementation of `plans/kit-exit/tea-redesign.md` (all but the WebApp):
|
||||
|
||||
- §12.6 not done: CaCu's risk as `RiskAssessment`, imports as `transaction` Bundles with `AuditEvent` and
|
||||
`Provenance`, OCR jobs as `Task`, and CaCu's follow-up list as `EpisodeOfCare`. The old routes stay; removing
|
||||
them, and `/<domain>/indicadores`, needs the owner (§12.9).
|
||||
- §12.2: suppression (`data-absent-reason: masked`) and confidence intervals wait for #73.
|
||||
- The new Alembic revision (`f2b6d1e8c934`) was checked upgrade/downgrade/upgrade on SQLite only; MySQL,
|
||||
PostgreSQL and SQL Server untested (rule 7). `dbt build --select tea` passed on SQLite only; the SQL Server 2016
|
||||
VM and `e2e/sqlserver2016` (piece 11 of `tea-port.md`) not run. `tea_meses_cumplidos` has a separate `floor` path
|
||||
for the other engines, untested there.
|
||||
- Assumptions to confirm: the metric references live in dbt's var `tea` (an ephemeral model), not a seed, because
|
||||
the cycle doesn't run `dbt seed`; effect texts and electrode positions are in `WebApi/webapi/fhir/tea_eeg.toml`.
|
||||
An EEG without any criterion written is `SIN_ANALIZAR`, a third category of M29 (the §10 question). M25's units are
|
||||
all the period's children, its event the first F84.0 note. M29 counts the cohort's children only. ADOS-2 items are
|
||||
the 28 of the old staging (the plan says 29 but its own total of 76 columns has 28); labels of B13 to B18 and D5
|
||||
wait for the manuals. Codes are the project's: no LOINC or SNOMED until confirmed (§12.9).
|
||||
- `fhir.resources` (8.3, R4B models) added to WebApi's dev group to validate responses in tests: **approved by the
|
||||
owner 2026-11-15** as a new dependency (§12.9).
|
||||
- Patient routes (`EpisodeOfCare`, `$resumen-tea`) are registered only in DEV with the `simulado` tag; alterations
|
||||
stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`.
|
||||
|
||||
### Kit exit integrated on `dev` (branch `feature/kit-exit-integration`), 2026-11-15
|
||||
|
||||
Left open by bringing `feature/163-source-terminology`, `feature/163-tea-redesign` and the CaMa dashboard's
|
||||
presentation onto one branch:
|
||||
|
||||
- `cat_mapeo` is seeded by the `catalogs` step but no load reads it yet: the CaMa silver load still takes captions
|
||||
and aliases from the catalog's TOML (`webapi/orchestration/reference/catalogs.py`); the remap step, the mappings
|
||||
screens and the `ConceptMap` endpoint of G-GEN-1 are not built.
|
||||
- The follow-up list exists for CaCu only (`webapi/follow_up/`); the CaMa follow-up tab shows the unavailable state
|
||||
until a CaMa list is served. Angel's CaMa follow-up and Análisis endpoints (`dashboard-test`) read the kit and a
|
||||
synthetic reader, so they were not merged. **Ported 2026-11-15**: `webapi/cama_cohort.py`, `cama_runtime.py`,
|
||||
`cama_analysis.py` and `seguimiento_cama.py` brought in from `dashboard-test`, with `cama_cohort.py`'s three kit
|
||||
imports (`indicadores_kit.cama.{tablas,consultas.plata,familias.histopatologia_birads.consulta}`) replaced: the
|
||||
table namespace by `webapi.orchestration.tables.cama.TABLAS` (already the generic replacement), the kit's SQL
|
||||
select-builders (`mastografias`/`biopsias`) by Python equivalents of the already-committed
|
||||
`Transformation/models/cama/silver/cama_{mastografias,biopsias}.sql`, and the `BIRADS` code dict by one read off
|
||||
`core/catalogos/cama.toml`'s `mastografia.resultados.birads` values against the WebApp's `BIRADS_4..6` contract
|
||||
(`etiquetas-cohorte.ts`). Angel's own test suite (`test_cama_cohort.py`, `test_cama_runtime.py`,
|
||||
`test_seguimiento_cama.py`, 14 tests) ported with only the same import fix and passes unchanged, which is strong
|
||||
evidence the port is behaviorally faithful. The WebApp side needed no changes: it was already merged and only
|
||||
needed the backend to stop 503ing.
|
||||
- The three CaMa measures Angel added to the kit (`deteccion_histopatologica`, `dias_resultado_diagnostico`,
|
||||
`histopatologia_birads`, #161) were not ported; the dbt CaMa measures and the invasive-cancer stratifiers are what
|
||||
the page draws. Re-expressing them in dbt is a separate task.
|
||||
- `feature/cacu-pim-vigilancia` (models as a Hamilton dataflow, the CIN2+ prevalence-incidence scenario) is
|
||||
deferred: it predates the cohort move into `models/cohorts` and needs rebasing on the new `dev`.
|
||||
- The webapi image compiles dbt's manifest for SQLite at build time and, on another engine, at start-up against the
|
||||
configured databases (`webapi.dbt_manifest`). **Verified 2026-11-15** against real MySQL (`isssteleon-mysql-test`),
|
||||
SQL Server (`isssteleon-mssql-test`) and a throwaway PostgreSQL 16 container, each with scratch databases:
|
||||
`python -m webapi.dbt_manifest` compiled the full manifest (44 models, 39 metrics) on all three and printed the
|
||||
manifest path, matching the SQLite path's shape. Not yet run: `WebApi/webapi/__init__.py` actually serving `/kpis`
|
||||
from one of these compiled manifests (only the compile step was exercised, not a full request against it), and
|
||||
this was outside Docker Compose (the `webapi` service image itself wasn't rebuilt or started against them). Also
|
||||
found: `Transformation`'s `.venv` only has the `sqlite`+`sqlserver` groups synced, not `postgres`; MySQL needs its
|
||||
own `.venv-mysql` (`UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql`, undocumented until now) since
|
||||
dbt-mysql pins dbt-core 1.7 against the others' 1.12.
|
||||
- TEA's alterations stay hidden until `TEA_ALTERACIONES_VALIDADAS=1`; `fhir.resources` in the WebApi's dev group
|
||||
was approved by the owner 2026-11-15; suppression and intervals are #73's.
|
||||
- A risk batch stays `preliminary` until confirmed or voided (ADR-MD-008); the risk route serves only final batches.
|
||||
**Built 2026-11-15**: `GET/POST /cacu/riesgos/lotes...` (`webapi/risk_batches.py`, over a new
|
||||
`CohortRepository.pending_batches`) and a "Lotes de riesgo" tab in Gobernanza, so this is a WebApp action now,
|
||||
not only `python -m webapi.orchestration confirm-risks`. CaCu only; CaMa and TEA have no risk model to batch yet.
|
||||
- `models`' CLI `--promote` (the `entrenar` compose profile's last step) set the MLflow alias directly, bypassing
|
||||
`registry.promote`'s checklist entirely — contradicting its own docstring ("promotion is always a manual step").
|
||||
**Fixed 2026-11-15**: the CLI now calls `registry.promote` and reports the failing checks instead, same as the
|
||||
WebApi route. Found on the way: `registry.checks`'s ML-03 only recognized the kit's `armado_id` link, so a
|
||||
version trained on a dbt cohort (CaCu's path since this integration) could never pass the gate at all; fixed to
|
||||
also accept the `cohort.source`/`cohort.build` tags a dbt-sourced run carries.
|
||||
- Consequence of the fix above, found the same day: `docker-entrypoint.sh`'s `entrenar` branch ran
|
||||
`models run cacu cin2_logistic --export --train --promote` with no `--environment`, defaulting to DEV. Against
|
||||
the now-gated `--promote`, ML-02 (version tagged for production) would always fail, so `entrenar` as shipped
|
||||
could never actually put a version into production. **Fixed 2026-11-15**: the command now adds
|
||||
`--source dbt --manifest "$DBT_MANIFEST" --environment prod`, training and exporting from dbt's cohort instead of
|
||||
the kit's numbered builds — the only way to name a PROD run's cohort build (ML-03) without knowing its number
|
||||
ahead of time, and the same tag-based ML-03 path above, so the gate stays portable across environments (no live
|
||||
lookup of a local build row). Verified piece by piece against existing tests (dbt export through a live session:
|
||||
`models/tests/test_export_cohort.py::test_the_command_exports_from_dbt_through_the_session`; PROD train + gated
|
||||
promote from a dbt cohort: `models/tests/cacu/test_cin2_logistic.py::
|
||||
test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it`), not as one live combined run.
|
||||
- `entrenar` being a compose command assumed someone, somewhere, has a shell — raised 2026-11-15 as not actually
|
||||
true (no CLI access at ISSSTELEON, and hospital staff can't be expected to run one either). This put two
|
||||
questions to the owner: whether `cin2_logistic` is meant to stay a locally-fit model at all (a published,
|
||||
externally-validated set of coefficients, the way ASCCP's own risk tables work, would need no local training and
|
||||
make the CLI-access problem moot), and if so, whether to solve the access problem by pre-training offline and
|
||||
shipping a promoted version, or by moving the trigger from a shell to the browser.
|
||||
**Decided 2026-11-15: the model stays locally-fit** (`fit()` genuinely estimates its coefficients from the
|
||||
site's own cohort each time; it is not a candidate for published/external coefficients) **and the owner chose a
|
||||
UI training trigger over offline pre-training** — the latter ships with no clinical validation against the site
|
||||
that will use it, and would also need install-time seeding tooling that doesn't exist.
|
||||
**Built the same day**: `POST /governance/model-versions/<domain>/<scenario>/train`
|
||||
(`webapi/blueprints/governance.py`) runs the exact same `models.__main__.main` invocation `entrenar` does
|
||||
(`--export --source dbt --environment prod --train --promote`), over HTTP; 404 for no trainer, 409 for trained
|
||||
but not promoted (needs reports attached first), 503 with no manifest or an operational failure. A "Entrenar
|
||||
cin2_logistic" button in Gobernanza's model-versions panel calls it. `entrenar`'s compose command stays as an
|
||||
equivalent path for whoever does have server access; the manual documents both.
|
||||
|
||||
### The `tea` EEG library orchestrated into TEA (`plans/i-added-the-tea-lucky-mccarthy.md`), 2026-11-19
|
||||
|
||||
Left open by steps 0 and 1 (the library at `models/libs/tea` @ `9cef555`; the schema it writes):
|
||||
|
||||
- The library is installed from the `models/libs/tea` submodule, which stays at `alberto/tea.git`. Deploy and CI
|
||||
trust that exact origin and read it anonymously over HTTP: if the repository becomes private, CI and deploy
|
||||
can't fetch it. `models` now needs Python ≥ 3.12, and the WebApi runs on pandas 3.1 / numpy 2.5 (suite unchanged).
|
||||
- Revision `16bf0b0ee3e4` (`eeg_criterio` and the analysis columns on `eeg`, `eeg_metrica`,
|
||||
`eeg_metrica_electrodo`) was checked upgrade/downgrade/upgrade with data on SQLite only; MySQL, PostgreSQL and
|
||||
SQL Server untested (rule 7).
|
||||
- The four fixed criterion columns of `eeg` (`eeg_canales_amplitud`, `_alta_frecuencia`, `_correlacion`,
|
||||
`_sin_senal`) are still there: they go in their own revision with the step that moves silver and dbt to
|
||||
`eeg_valido` / `eeg_criterio`, so the chain stays green in between. Until then `mel_valor` is still read as a z by
|
||||
the FHIR map, while the dictionary already documents it as the raw value and `mel_z` as the z.
|
||||
- To confirm with the domain expert: which library feature each metric maps to (`spike_rate_nrem` for
|
||||
`PICOS_PAROXISTICOS`, `gradient_delta_sueno` for `GRADIENTE_ANTEROPOSTERIOR`, and the N3 spindles while
|
||||
`DIRECTOR_CLUSTER` has `use_n3=False`).
|
||||
- Step 2 (`models/models/tea/eeg/`, `models/models/eeg_analysis.py`, `python -m models tea analyze`): no baseline
|
||||
is registered yet, so every metric is stored with its raw value and null z / `met_fuera` until step 8 trains and
|
||||
promotes `tea-eeg-<biomarker>[-<stage>]`. Only `cluster="sync"` was run here; a LocalCluster and a remote
|
||||
scheduler (`DASK_SCHEDULER_ADDRESS`) are the library's own paths, untried from `models`. Only the modern
|
||||
implementation is supported (the legacy validator has no `checks_of`). On the synthetic studies and with
|
||||
`DIRECTOR_CLUSTER`, `HUSOS_SUENO_N3` comes out null.
|
||||
- Step 3 (`analyze_eeg` before `load` in the cycle, `POST /governance/eeg/run`, `EEG_ANALYSIS_CLUSTER`): with the
|
||||
default `auto` and no `DASK_SCHEDULER_ADDRESS`, the `indicadores` container starts a local Dask cluster sized by
|
||||
its free memory (4.25 GiB per worker); its memory limit in `docker-compose.yml` wasn't revisited, nor was a Dask
|
||||
scheduler service added. The analysis in a request is bounded by `limit` (5 by default) against gunicorn's 600 s
|
||||
timeout. Only `sync` was run here.
|
||||
- Step 4 (silver, catalog and the quality chain on the analysis's output; revision `c4306f438b3a` drops
|
||||
`eeg_canales_amplitud`, `_alta_frecuencia`, `_correlacion`, `_sin_senal`; the `tea.EegMetrica` and
|
||||
`tea.EegMetricaElectrodo` import targets retired): checked on SQLite only. FHIR shows only the numeric
|
||||
study-wide checks as quality observations, in the shape the WebApp's patient summary validates; the triage level
|
||||
(text) and the bad channels reach silver and `tea_paciente_eeg_criterios` but not FHIR until the FHIR rework
|
||||
(steps 6 and 7). `cri_decisivo` isn't carried into silver. dev-data no longer writes any analysis column or
|
||||
metric row (its `cargar` would have hit the retired targets): until step 7b makes its EDFs long enough for the
|
||||
library, the DEV EEGs come out not valid and the EEG panels and M29/M30 have nothing good to show. The z, -1/0/+1
|
||||
and p5/median/p95 are in silver but dbt still scores the metrics with the placeholder references (step 5).
|
||||
- Step 5 (dbt scores the metrics with the analysis's z, -1/0/+1 and the baseline's p5/median/p95;
|
||||
`tea_eeg_referencias` and the vars `referencias` and `alteracion_z` removed; the FHIR electrode map now plots each
|
||||
electrode's z, `valor_z`): this supersedes the TEA redesign's assumption that the metric references live in dbt's
|
||||
var `tea`. With no baseline in production every metric is `no_evaluable`, so M30 counts no alteration and the
|
||||
WebApp shows none until step 8 promotes the baselines (and the alterations stay hidden behind
|
||||
`TEA_ALTERACIONES_VALIDADAS` anyway).
|
||||
- Step 6 (FHIR): every answer is validated against `fhir.resources` R4B before it leaves (a non-conforming one is a
|
||||
500 `OperationOutcome`); `fhir-resources>=8.3` is now a main WebApi dependency, as the plan approved. The EEG's
|
||||
quality observations take the analysis's own shape (`urn:tea:validation` codes, A/N, `electrode` and `decisive`
|
||||
components), bad channels and the triage level included, and `CodeSystem/tea-eeg-criterio` labels them; the
|
||||
report adds the analysis's `valid`/`not-valid`. The WebApp's patient summary still filters `eeg.calidad_*` codes
|
||||
and BUENO/MALO, so its quality panel is empty until step 7. `CapabilityStatement.fhirVersion` stays `4.0.1`: no
|
||||
validated field differed between R4 and R4B in these resources.
|
||||
- Step 7 (WebApp aligned with the analysis's output: quality as the analysis's checks with the bad channels,
|
||||
`sin_analizar`, a missing duration or channel count, the ADOS-2 classifications of module T and an unclassified
|
||||
one, item codes 7-9, the age group from `$resumen-tea`'s episode, why a metric couldn't be evaluated, the curve's
|
||||
median, and the EEG filter and summary box by a valid EEG while the alterations are hidden; the status page reads
|
||||
the new checks; the TEA FHIR fixtures regenerated from the WebApi): `npx ng test` passes (1791 tests) on Node
|
||||
24.15.0, the CI's version, installed in a scratch folder. The follow-up list's EEG column still says «No disponible» while
|
||||
the alterations are hidden. The fixtures were regenerated by hand from the WebApi's TEA test database; there's no
|
||||
script for it in the tree.
|
||||
- Step 7b (dev-data gives only what the analysis reads: each EEG's story asks for good or bad, with or without
|
||||
sleep and which metrics are altered, and its EDF draws it, 3.5 min at 256 Hz with 24 channels, the shortest the
|
||||
library grades `completo` with margin; the hospital inserts its blobs in batches of at most 16 MB): on 30 children
|
||||
every analysed EEG came out as its story asked. Not run against the MySQL hospital or a deployed platform: about
|
||||
220 MB of EDFs for 200 children, and the `indicadores` cycle analyses them (minutes per batch). The gradient is
|
||||
never drawn altered. N3 spindles are found on these EDFs, unlike the earlier synthetic ones.
|
||||
- Step 8 (`python -m models run tea eeg --train [--promote]`: the age baselines trained on HK1K and registered as
|
||||
`tea-eeg-<biomarker>[-<stage>]`): tested on a synthetic reference table and synthetic EDFs, not on HK1K. The run
|
||||
is the owner's: it reads HK1K from the cluster's S3 (`raw/eeg-helsinki/`, the `eeg-reference` extra, keys from
|
||||
the environment) and must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI` of the deployment,
|
||||
SQLite inside the webapi container by default); with a remote Dask scheduler the workers need `models` and `tea`
|
||||
installed, otherwise `cluster=local` measures in the training process. Decision to confirm: a reference cohort
|
||||
outside the platform (`cohort.source = referencia`, the hash of its listing) satisfies ML-03 for these versions
|
||||
(`registry.checks`). Promotion still needs the three reports (MLD-01, MLD-01b, MLD-03), which is where the domain
|
||||
expert's validation goes; `TEA_ALTERACIONES_VALIDADAS` stays a separate switch in the WebApi.
|
||||
|
||||
### TEA: ADOS-2 association, zones and the library's spike and spindle changes (2026-11-21)
|
||||
|
||||
- The ADOS-2 association (`tea.associations.ados2`, `models tea relate-ados2`, the cycle's `relate_ados2`) writes
|
||||
every version unvalidated (`rel_validado` 0). Who validates a version, and how the panel shows an unvalidated one,
|
||||
is the domain expert's decision. On the 62 real EDFs only the ADOS-2 rows were invented, so the associations
|
||||
there say nothing.
|
||||
- Legacy `ados2_association` scores only the rows it was fitted on (the research code keeps only those
|
||||
probabilities); the platform runs modern, which scores any row.
|
||||
- Spike densities use a count reference (`CountRate`: the reference's aggregate rate and its negative-binomial
|
||||
dispersion, z from the child's mid-p tail in its own minutes). That method, and the 0.05 cut for `outside`, need
|
||||
the domain expert's review, like the other baselines.
|
||||
- Every biomarker module changed version (spikes 0.4.0, spindles 0.2.0, the rest 0.2.0 for the `outside` change),
|
||||
so every EEG is analysed again, and the baselines must be retrained and promoted with their reports before the
|
||||
next load. The cluster's image must come from the same ISSSTELEON commit as the deployment
|
||||
(`dask-cluster/build.sh`; it now adds bokeh for the dashboard).
|
||||
- `tea_ados2_reactivos.puntaje_algoritmo` now counts 7, 8 and 9 as 0 (the ADOS-2 algorithm's rule), which changes
|
||||
the domain totals everywhere it is read, not only in the association view. To confirm with the owner.
|
||||
- A child with two ADOS-2 on the same first date duplicates its rows in `tea_paciente_relacion_ados2`, as before.
|
||||
- Spindle per-electrode and per-zone densities exist only for the channels the detector searches (no T3-T6, O1,
|
||||
O2), so `spindle_zone_temporal_*` and `spindle_zone_occipital` are NaN by design.
|
||||
- Not ported (outside the brief): per-candidate `origen_estado` / `motivo_puerta` from `picos_eventos`, inherited
|
||||
per-electrode spike densities, and `ventana_de_candidatos`.
|
||||
- WebApi's suite has 13 failures on this machine that need tesseract, pymssql and the notebook runner; unrelated to
|
||||
this change.
|
||||
- The previous deployment's run reported that `models run tea eeg --promote` fails for the EEG baselines ("no such
|
||||
model"); not looked at here.
|
||||
- CaCu migration `a1d4e7c20b31` (risk index date, from `dev`) fails on an existing SQLite database that already has
|
||||
the dbt views: the batch rebuild of `evaluacion_riesgo` stops at `error in view cacu_riesgo_vigilancia: no such
|
||||
table: main.evaluacion_riesgo`. A fresh database is fine; any SQLite installation upgrading with the views built
|
||||
hits it. Seen on the manual deployment A (2026-11-22), which was restarted from an empty volume.
|
||||
- ADOS-2 CSS and classification are now computed by the platform (`tea.scoring`, `models tea score-ados2`, the
|
||||
cycle's `score_ados2`, `ADOS2_SCORING=off` to skip), and the hospital no longer sends module, algorithm, CSS or
|
||||
classification (dev-data takes module and algorithm from the PDF through the document source). Open:
|
||||
- the CSS cut points in `tea/scoring/ados2.py` are approximate, written from memory of the calibrated severity
|
||||
tables, not transcribed from the manual; they must be replaced with the licensed values (they are data);
|
||||
- the total is the sum of the items present, so an item read as `S/D` lowers it; the expected items per module and
|
||||
algorithm are not checked;
|
||||
- Toddler gets a range of concern and no CSS, and dev-data writes no PDF for a Toddler ADOS-2, so those children
|
||||
have no module, items or classification after the load;
|
||||
- the document import was not run end to end with `ado_modulo` and `ado_algoritmo` in the mapping (unit tests
|
||||
only); Module 2 prints no algorithm, so its `ado_algoritmo` stays empty.
|
||||
|
||||
@@ -42,9 +42,9 @@ own import API, the same way a person would connect the hospital in
|
||||
hospital is left alone unless `repoblar = si`. Check it:
|
||||
`dev-data/montura/comprobar_hospital.sh dev-data-prueba`.
|
||||
2. **The platform is newly installed and empty.** WN's `deploy-dev` workflow
|
||||
(`.gitea/deploy/dev.py install-auto <port>`) creates empty storage only for
|
||||
a new, unregistered port. A registered port conservatively updates its
|
||||
existing data. Confirm this is a new installation before loading anything.
|
||||
installs on a free port, and `reinstall-dev` replaces a DEV instance with a
|
||||
new, empty one. Neither updates data in place. Confirm the instance is new
|
||||
before loading anything.
|
||||
3. **Load it:**
|
||||
|
||||
```sh
|
||||
@@ -74,16 +74,14 @@ uv run --python 3.12 python -m dev_data cargar cacu --api http://10.0.10.41:<por
|
||||
|
||||
## As a Gitea action
|
||||
|
||||
Loading must be a separate, explicitly requested operation for a confirmed empty
|
||||
installation. Do not append this step unconditionally after `install-auto`:
|
||||
that command also updates populated instances. The runner checks out the WN tree with
|
||||
its submodules (`git submodule update --init --recursive`), which brings
|
||||
`dev-data` once the submodule is committed. A sketch, not applied:
|
||||
|
||||
```yaml
|
||||
- name: Load the simulated hospital
|
||||
run: dev-data/montura/cargar.sh "http://10.0.10.41:$PORT"
|
||||
```
|
||||
The `load-dev-data` workflow runs this load as a separate, explicitly requested
|
||||
operation for an installed, still empty DEV instance (`installer.py load-data`,
|
||||
documented in `.gitea/deploy/README.md`). It builds the loader from the `dev-data`
|
||||
commit recorded in the instance's installation record, reads the hospital at the
|
||||
`hospital` input (`host:port`, default `10.0.10.41:9505`), loads `cacu`, `cama` and
|
||||
`tea` through the instance's published port, and waits for the three indicator
|
||||
recalculations to end `ok`. It refuses an instance that already has import
|
||||
attempts or an earlier load.
|
||||
|
||||
What it needs:
|
||||
- the job can use Docker (it already does to build the platform images);
|
||||
@@ -99,6 +97,12 @@ What it needs:
|
||||
| CaMa | Paciente, Mastografia, BiopsiaMama, NotaMedica | 1,026 (300 patients) | 0 |
|
||||
| TEA | Pacientes and nine more | 2,738 (200 patients) | 0 |
|
||||
|
||||
Since the EEG analysis moved into the platform (2026-11-19), TEA's hospital
|
||||
has six tables (no `eeg_metrica` or `eeg_metrica_electrodo`) and each EEG
|
||||
carries a 3.5-minute EDF of about 2.6 MB (about 220 MB for 200 children), so
|
||||
the TEA row count above is lower now. The EEG panels and M29/M30 fill only
|
||||
after the `indicadores` cycle has analysed the EDFs.
|
||||
|
||||
Same counts on the empty sandbox `isssteleon-sandbox-his` (18093). The
|
||||
instance was reinstalled by the workflow afterwards, came back empty, and
|
||||
`montura/cargar.sh` loaded it again with the same counts.
|
||||
@@ -113,8 +117,7 @@ instance was reinstalled by the workflow afterwards, came back empty, and
|
||||
`ISSSTELEON/dev-data` layout; until it is updated, run `poblar.sh` from the
|
||||
WN checkout.
|
||||
- Regenerating the hospital (`repoblar = si`) does not replace data already
|
||||
imported into a deployment. Updating the application keeps those records.
|
||||
Regeneration requires a separately authorized data operation or a new isolated
|
||||
installation and load; reusing the port is not a reset mechanism.
|
||||
imported into a deployment. A clean load needs a reinstall of the DEV instance
|
||||
(`reinstall-dev`, which removes its data) followed by `load-dev-data`.
|
||||
- Superseded by #165 once the platform keeps its HIS connection: the
|
||||
deployment would declare the hospital as a configured source.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# What is promised, what we have, what is missing
|
||||
|
||||
Checked on 2026-11-13 against `Alcance_proyecto.pdf` (modules and the
|
||||
deliverables list) and `docs_desarrollo-2.pdf` (requirement IDs), reading
|
||||
the code rather than the notes. Hand-off is 2026-11-30. Status: **done**,
|
||||
**partial** or **missing**. Items that depend on the client's data or
|
||||
clinical decisions say so; they need negotiating, not just code.
|
||||
|
||||
## Contract deliverables
|
||||
|
||||
| Deliverable | Status | What exists / what is missing |
|
||||
|---|---|---|
|
||||
| Structured, integrated, cleaned database apart from the source systems | **done** | Four engine-agnostic databases (CaCu, CaMa, TEA, governance), versioned cohort builds. |
|
||||
| Data integration layer through web services (APIs) | **done** | "Conectar datos": SQL, Excel/CSV, PDF tables, clinical documents, EEG, documents stored in columns; validation, merge, import log. |
|
||||
| NLP modules | **partial** | Field extraction from forms and free text: captions and layout, ConText/NegEx assertions, sections, anchors, severity, measurements, OCR tolerance, subject check, review dialog; a learned candidate ranker that learns from review corrections (`<domain>-extraccion`); `python -m webapi.nlp evaluate/train`. Missing: a held-out evaluation set; EEG, mammography and breast biopsy vocabulary tested on real reports; colposcopy (Reid, Swede) has no columns. |
|
||||
| Breast cancer (CaMa) risk model | **missing** | `models/cama` holds only its package docstring. Needs data and outcome definition from the client. |
|
||||
| TEA diagnostic model from EEG alterations | **missing** | EDF files are read and validated (amendment done) and the report's EEG findings can be extracted; no signal features, no model. Needs data. |
|
||||
| CaCu progression risk model | **done (one scenario)** | `cin2_logistic`: routines recorded, estimate, risks stored with model provenance. Risk cut-offs (immediate / priority / scheduled) undefined, so the risk-band indicator is hidden. |
|
||||
| CaCu survival model (OS/DFS, Kaplan-Meier at 1/3/5 years) | **missing** | Only a draft survival chart contract in the indicators kit. Needs follow-up and death data. |
|
||||
| Interactive dashboards with each module's indicators | **partial** | Indicator pages per domain; no PDF/XLS export of indicators (only the import log downloads), no heatmap, no single combined view. |
|
||||
| User manual | **partial** | `dist/MANUAL.md` covers installation, operation and the import flow; not every screen. |
|
||||
| Technical manual | **partial** | Preliminary design specification PDF, package READMEs (`Extraction/README.md` documents the NLP method and references), architecture notes; no final consolidated document. |
|
||||
| Project closure letter | n/a | Administrative. |
|
||||
|
||||
## Modules
|
||||
|
||||
| Module | Status | Notes |
|
||||
|---|---|---|
|
||||
| M00 Configuración: login, 2FA, password change, lockout, access, profiles, users | **missing** | No authentication at all; the biggest security gap (anyone who reaches the app can import data and run notebooks). |
|
||||
| M00 Parametrización, catálogos generales | **partial** | Catalogs and parameters exist as versioned files (`core/catalogos/*.toml`, `parametros.toml`); no screens to edit them. |
|
||||
| M01 CaMa: BI-RADS indicators | **done** | BI-RADS 4/5, confirmation, biopsies, time to diagnosis. |
|
||||
| M01 CaMa: risk calculator, heatmap, PDF/XLS reports, individual profiles, model | **missing** | Risk band only as a proposal. |
|
||||
| M01 CaMa: mammogram images | **partial** | Images embedded in reports are located and stored; no DICOM connector. |
|
||||
| M02 TEA: % with/without EEG, evaluation, confirmation, screening-to-diagnosis | **done** | |
|
||||
| M02 TEA: % normal vs abnormal EEG, correlation with severity | **missing** | The extraction to fill `eeg_anormalidad_presente` and the conclusion category now exists; the indicators don't. |
|
||||
| M02 TEA: EEG model | **missing** | |
|
||||
| M03 CaCu: cytology distribution, histopathology confirmation, screening-to-diagnosis time, risk model | **done** | |
|
||||
| M03 CaCu: diagnosis-to-treatment time, survival, cut-offs, incidence/prevalence against state data, individual profiles | **missing** | |
|
||||
| M04 Integrated dashboard with PDF/XLS | **partial** | Per-domain pages only. |
|
||||
|
||||
## Requirements document
|
||||
|
||||
| IDs | Status | Notes |
|
||||
|---|---|---|
|
||||
| VAR-01..03, VARM-01..04a | **done** | OCR with confidence, status, main and alternative method, review flag. |
|
||||
| VAR-04, VARM-05 (document the extraction method) | **done** | `Extraction/README.md`: method and references; the evaluation command. A held-out score is still missing. |
|
||||
| VAR-07, VAR-08, VAR-09 | **done** | Transformation descriptions, source and dates at load, results persisted. |
|
||||
| IND-01..03 | **done** | |
|
||||
| EL-01..07 | **done** | Versioned builds with hash, per-criterion exclusion counts. |
|
||||
| ML-01a, ML-01b | **done** | Five routine records written by training; run files downloadable. |
|
||||
| ML-02, ML-03 | **done** | DEV/PROD tags; cohort link. The extraction ranker can't meet ML-03 (no cohort), so it can't be promoted: decision pending. |
|
||||
| ML-04, ML-05 | **done, unverified** | Read-only access; notebooks isolated in the `notebooks` container, never started as a real container. |
|
||||
| MLD-01, MLD-01b | **done** | Promotion checks for technical and clinical validation reports. |
|
||||
| MLD-03 (weights and OR/HR shown) | **partial** | Coefficients recorded in the METODO_ANALITICO routine; not shown on screen, the check only asks for a report link. |
|
||||
| MLD-4, MLD-5 | **done** | Estimates carry their version and are stored with it. |
|
||||
| TRIPOD 20b/20c | **partial** | EDA report covers part of it. |
|
||||
|
||||
## What code alone can still close before 2026-11-30
|
||||
|
||||
1. Minimal login, users and profiles (or a documented plan).
|
||||
2. PDF/XLS export of the indicator pages.
|
||||
3. Coefficients and OR on the model version screen (MLD-03).
|
||||
4. A user manual for every screen.
|
||||
5. Run the notebook container for real; rebuild the WebApi image.
|
||||
|
||||
Everything else on the missing list (CaMa and TEA models, survival, risk
|
||||
cut-offs, incidence against state data, a held-out NLP set) needs data or
|
||||
clinical decisions from the client and should be raised as a dependency.
|
||||
@@ -5,10 +5,10 @@ Moved from `AGENTS.md` §4 on 2026-11-03.
|
||||
```bash
|
||||
(cd Core && uv run pytest -q) # 18 (2 skip)
|
||||
(cd Persistance && uv run pytest -q) # 18 (1 skip)
|
||||
(cd Extraction && uv run pytest -q) # 31 (OCR tests need tesseract + spa data)
|
||||
(cd models && uv run pytest -q) # 41
|
||||
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 417 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
|
||||
(cd WebApp && npx ng test --watch=false && npx ng build) # 1235 (a few vendored indicadores specs time out under heavy load; pass alone)
|
||||
(cd Extraction && uv run pytest -q) # 83 (OCR tests need tesseract + spa and osd data)
|
||||
(cd models && uv run pytest -q) # 180 (real Jupyter kernels and a runner process in tests/pipelines/test_experiment.py)
|
||||
(cd WebApi && uv sync --extra sql-drivers && uv run pytest -q) # 497 passed, 7 skipped (MySQL live tests; includes webapi.orquestacion's own suite, test_orquestacion_*.py — folded in from the former standalone Orquestacion/ package, 2026-10-31)
|
||||
(cd WebApp && npx ng test --watch=false && npx ng build) # 1248 (a few specs, mostly indicadores, time out under heavy load; pass alone)
|
||||
```
|
||||
|
||||
If a package's `.venv` has stale absolute paths baked into its entry-point
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# TEA FHIR synthetic browser check
|
||||
|
||||
Run from a WorkingNarrative checkout whose ISSSTELEON and WebApp gitlinks include the local TEA changes. The script creates a temporary SQLite database from `WebApi/tests/staging/tea.py`; it never imports production data. `DEV_REVISION` enables the simulated patient routes. It serves the Angular build and the real Flask API on a temporary loopback port and closes them after the check.
|
||||
|
||||
Prerequisites: Python 3.12, uv, Node and npm, a Chromium-compatible browser, and Playwright available to Node. Install the WebApi dev dependencies and build WebApp. Generate the dbt manifest from this exact Transformation tree:
|
||||
|
||||
```sh
|
||||
cd ISSSTELEON/Transformation
|
||||
uv run dbt compile --profiles-dir . --profile tea
|
||||
cd ../WebApi
|
||||
uv sync --locked
|
||||
cd ../WebApp
|
||||
npm ci
|
||||
npm run build
|
||||
cd ../..
|
||||
```
|
||||
|
||||
Set `PLAYWRIGHT_PATH` to the installed Playwright module and `BROWSER_PATH` to the browser executable when the defaults in `verify.cjs` do not exist. Then run:
|
||||
|
||||
```sh
|
||||
ISSSTELEON/WebApi/.venv/bin/python e2e/tea-fhir/serve_and_verify.py
|
||||
```
|
||||
|
||||
On Windows use `ISSSTELEON\WebApi\.venv\Scripts\python.exe`. The harness supplies a Windows-only `fcntl` stub that raises if locking is used; it does not verify lock behaviour. `DBT_MANIFEST` is set to `Transformation/target/manifest.json` in the harness before Flask starts. For the API outside the harness, the file must be available inside the API environment at the path set in `DBT_MANIFEST`, and the cycle must create the definitions and event views in the domain database. Migrations alone do not do this. The WebApi image compiles the manifest from `Transformation` while it builds and sets `DBT_MANIFEST` to it (SQLite's SQL); the `indicadores` service runs the cycle after each import.
|
||||
|
||||
The browser check covers M28, history, filters, paging, the patient's identity, ADOS-2 and EEG, returning with focus, a partial record and a simulated FHIR 404. Patient selection races and absent/masked values are covered by the focused Angular tests. No EEG alteration validation switch is enabled.
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
api = root / 'ISSSTELEON' / 'WebApi'
|
||||
sys.path[:0] = [str(api), str(api / 'tests')]
|
||||
if os.name == 'nt':
|
||||
fcntl = types.ModuleType('fcntl')
|
||||
def unavailable(*args):
|
||||
raise RuntimeError('fcntl locking is unavailable in this Windows test')
|
||||
fcntl.flock, fcntl.LOCK_EX, fcntl.LOCK_UN = unavailable, 2, 8
|
||||
sys.modules['fcntl'] = fcntl
|
||||
os.environ['DEV_REVISION'] = 'pruebas'
|
||||
os.environ['DBT_MANIFEST'] = str(root / 'ISSSTELEON' / 'Transformation' / 'target' / 'manifest.json')
|
||||
os.environ['MLFLOW_DISABLE_AGENT_HINT'] = '1'
|
||||
|
||||
from conftest import base_de
|
||||
from flask import send_from_directory
|
||||
from werkzeug.serving import make_server
|
||||
from webapi import create_app
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='tea-e2e-') as directory:
|
||||
base = base_de('tea', Path(directory))
|
||||
base.run('catalogs', 'load', 'views', 'registry', 'definitions', 'event_models', allow_undecided=True)
|
||||
app = create_app()
|
||||
static = root / 'ISSSTELEON' / 'WebApp' / 'dist' / 'WebApp' / 'browser'
|
||||
@app.get('/indicadores/tea')
|
||||
def page():
|
||||
return send_from_directory(static, 'index.html')
|
||||
@app.get('/<path:filename>')
|
||||
def assets(filename):
|
||||
return send_from_directory(static, filename)
|
||||
server = make_server('127.0.0.1', 0, app)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
subprocess.run(['node', str(root / 'e2e' / 'tea-fhir' / 'verify.cjs'), str(server.server_port)], check=True, timeout=90)
|
||||
finally:
|
||||
server.shutdown()
|
||||
thread.join()
|
||||
base.motor.dispose()
|
||||
from persistance.db import get_tea_engine
|
||||
get_tea_engine().dispose()
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_PATH || 'C:/Users/angel/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
|
||||
(async () => {
|
||||
const browser = await chromium.launch({ executablePath: process.env.BROWSER_PATH || 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
const root = `http://127.0.0.1:${process.argv[2]}`;
|
||||
await page.goto(`${root}/indicadores/tea`);
|
||||
const m28 = page.locator('article').filter({ has: page.getByRole('heading', { name: 'Casos por estatus' }) });
|
||||
await m28.getByText('6', { exact: true }).waitFor();
|
||||
for (const [name, count] of [['Solo M-CHAT','2'], ['Hasta evaluación psicológica','1'], ['Hasta evaluación neuropediátrica','1'], ['Con EEG','2']]) {
|
||||
const row = m28.locator('dl div').filter({ hasText: name });
|
||||
if (await row.locator('dd').innerText() !== count) throw new Error(`M28 ${name}`);
|
||||
}
|
||||
console.log('M28: 6 casos y cuatro etapas');
|
||||
await page.getByRole('button', { name: 'Histórico' }).click();
|
||||
await page.getByRole('heading', { name: 'Casos por estatus' }).first().waitFor();
|
||||
if (await page.locator('article').count() !== 3) throw new Error('Histórico no devolvió tres periodos');
|
||||
await page.getByRole('button', { name: 'Seguimiento', exact: true }).click();
|
||||
await page.getByLabel('Fecha de corte').fill('2025-12-31');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('6 episodios', { exact: true }).waitFor();
|
||||
await page.getByRole('button', { name: 'Siguiente' }).click();
|
||||
await page.getByText('Página 2', { exact: true }).waitFor();
|
||||
if (await page.locator('tbody tr').count() !== 1) throw new Error('Paginación incorrecta');
|
||||
await page.getByRole('button', { name: 'Anterior' }).click();
|
||||
await page.getByText('Página 1', { exact: true }).waitFor();
|
||||
await page.getByLabel('Edad al M-CHAT').selectOption('16_23');
|
||||
await page.locator('select[name=status]').selectOption('finished');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('1 episodios', { exact: true }).waitFor();
|
||||
const button = page.getByRole('button', { name: 'Abrir ficha' });
|
||||
const patient = await button.getAttribute('data-patient');
|
||||
await button.click();
|
||||
await page.getByRole('heading', { name: 'Ficha del paciente' }).waitFor();
|
||||
await page.getByLabel('Ficha del paciente').getByText(patient, { exact: true }).waitFor();
|
||||
await page.getByText('Fecha: 2025-05-20').waitFor();
|
||||
await page.getByText('Calidad: Buena').waitFor();
|
||||
await page.getByText('Puntaje de severidad (CSS)', { exact: true }).waitFor();
|
||||
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
|
||||
if (await page.getByLabel('Edad al M-CHAT').inputValue() !== '16_23') throw new Error('Filtro perdido');
|
||||
await page.waitForFunction(() => document.activeElement?.getAttribute('data-patient') !== null);
|
||||
console.log('Histórico, filtros, paginación, ficha correcta y retorno con foco');
|
||||
await page.locator('select[name=status]').selectOption('active');
|
||||
await page.getByLabel('Edad al M-CHAT').selectOption('');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('4 episodios', { exact: true }).waitFor();
|
||||
const ids = await page.locator('button[data-patient]').evaluateAll(nodes => nodes.map(n => n.getAttribute('data-patient')));
|
||||
let partial = null;
|
||||
for (const id of ids) {
|
||||
const res = await page.request.get(`${root}/tea/fhir/Patient/${id}/$resumen-tea`);
|
||||
const body = await res.json();
|
||||
if (!body.entry.some(e => e.resource.resourceType === 'DiagnosticReport')) { partial = id; break; }
|
||||
}
|
||||
if (!partial) throw new Error('No se encontró ficha parcial');
|
||||
await page.locator(`button[data-patient="${partial}"]`).click();
|
||||
await page.getByText('Sin información de EEG.').waitFor();
|
||||
await page.getByRole('button', { name: 'Volver a Seguimiento' }).click();
|
||||
await page.locator('input[name=cssMin]').fill('100');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('No hay episodios para la selección.').waitFor();
|
||||
await page.locator('input[name=cssMin]').fill('');
|
||||
await page.getByRole('button', { name: 'Aplicar filtros' }).click();
|
||||
await page.getByText('4 episodios', { exact: true }).waitFor();
|
||||
await page.route('**/tea/fhir/Patient/*/$resumen-tea', route => route.fulfill({ status: 404, contentType: 'application/fhir+json', body: JSON.stringify({ resourceType: 'OperationOutcome', issue: [{ code: 'not-found', diagnostics: 'Paciente no encontrado' }] }) }));
|
||||
await page.locator(`button[data-patient="${partial}"]`).click();
|
||||
await page.getByRole('alert').getByText('Paciente no encontrado').waitFor();
|
||||
console.log('Ficha parcial y OperationOutcome 404');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => { console.error(error); process.exit(1); });
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# Settings for the manual deployment (docker-compose.yml in this folder). Docker
|
||||
# Compose reads it for the values below, and the webapi and indicadores
|
||||
# containers receive it as their environment.
|
||||
|
||||
# --- Project ---
|
||||
# Prefix of every container, network, volume and image. Change it (and the
|
||||
# ports) to run a second copy next to this one.
|
||||
COMPOSE_PROJECT_NAME=sitio-a
|
||||
|
||||
# --- Published ports ---
|
||||
# Address the ports bind to: 0.0.0.0 for every interface, 127.0.0.1 for this
|
||||
# machine only.
|
||||
BIND_ADDRESS=0.0.0.0
|
||||
# The application (nginx: pages and proxy to the API). Open this one.
|
||||
WEBAPP_PORT=5310
|
||||
# The API, direct.
|
||||
WEBAPI_PORT=5311
|
||||
# The simulated hospital's MySQL (user/password hospital/hospital).
|
||||
HOSPITAL_PORT=5312
|
||||
|
||||
# --- Simulated hospital contents ---
|
||||
# Patients generated per project, the generator's seed and reference date.
|
||||
N=200
|
||||
N_CACU=300
|
||||
N_CAMA=300
|
||||
SEMILLA=7
|
||||
REFERENCIA=2026-01-01
|
||||
TEA_ALTERACIONES_VALIDADAS=1
|
||||
# Folder of real EDF files, as an absolute path: each file becomes one more TEA
|
||||
# child (after the N synthetic ones), a confirmed autism case whose only EEG
|
||||
# carries that file. Empty: only the synthetic EDFs. Changing it needs
|
||||
# `docker compose down -v` (a populated hospital is left alone).
|
||||
EDF_CARPETA=/home/milk/datos/edf
|
||||
DASK_SCHEDULER_ADDRESS=tcp://10.0.10.41:30786
|
||||
# Gobernanza > TEA · EEG: the dashboard port and worker count the cluster card checks.
|
||||
TEA_DASK_DASHBOARD_PORT=30787
|
||||
TEA_DASK_EXPECTED_WORKERS=40
|
||||
# Folder (in the container) holding one subfolder per reference cohort, and the host folder mounted there.
|
||||
TEA_REFERENCE_ROOT=/referencia
|
||||
REFERENCIA_CARPETA=../manual-deploy/referencia
|
||||
# The indicator cycle leaves the EEGs unanalysed until the baselines are in production: upload them in
|
||||
# Gobernanza > TEA · EEG, promote, then analyse there. Set to auto to analyse in the cycle as before.
|
||||
EEG_ANALYSIS_CLUSTER=off
|
||||
|
||||
# --- Patient-level views ---
|
||||
# Any value turns on the routes that return one patient's data (the follow-up
|
||||
# lists, TEA's patient summary). They exist for simulated data only: leave it
|
||||
# unset on a platform that holds real patients.
|
||||
DEV_REVISION=manual-deploy
|
||||
|
||||
# --- Platform (same variables as ISSSTELEON/.env.example) ---
|
||||
# Target databases. Unset, each is a SQLite file in this project's
|
||||
# webapi_data volume.
|
||||
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
|
||||
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
|
||||
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
|
||||
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
|
||||
# WEBAPI_MAX_UPLOAD_MB=200
|
||||
# WEBAPI_WORKERS=2
|
||||
# WEBAPI_TIMEOUT=600
|
||||
# EXTRACTION_OCR_LANG=spa+eng
|
||||
@@ -0,0 +1 @@
|
||||
documentos/
|
||||
@@ -0,0 +1,443 @@
|
||||
# Manual deployment
|
||||
|
||||
The whole platform plus the simulated hospital in one Compose project, built
|
||||
from the two checkouts next to this folder (`../ISSSTELEON` and `../dev-data`).
|
||||
Everything here is simulated data.
|
||||
|
||||
Run every command from this folder.
|
||||
|
||||
## What it starts
|
||||
|
||||
| Service | What it is | Published on |
|
||||
|---|---|---|
|
||||
| `webapp` | the Angular app behind nginx, which also proxies the API | `WEBAPP_PORT` |
|
||||
| `webapi`, `indicadores` | the Flask API and the indicator recomputation | `WEBAPI_PORT` |
|
||||
| `hospital` | MySQL playing the hospital system (`hospital`, `hospital_cacu`, `hospital_cama`) | `HOSPITAL_PORT` |
|
||||
| `poblar`, `poblar-cacu`, `poblar-cama` | one-shot jobs that generate the hospital's data on `up` | |
|
||||
| `load` | one-shot job that imports the hospital into the platform | |
|
||||
| `documentos` | one-shot job that writes the test PDFs | |
|
||||
|
||||
Ports, bind address and project name come from `.env`. Change
|
||||
`COMPOSE_PROJECT_NAME` and the three ports to run a second copy on the same
|
||||
machine.
|
||||
|
||||
## Bring it up and load it
|
||||
|
||||
```sh
|
||||
docker compose up --build -d # platform and hospital; the hospital is populated
|
||||
docker compose run --rm --build load # import the hospital into the platform
|
||||
```
|
||||
|
||||
`load` prints one line per table (`leídas, nuevas, actualizadas, rechazadas`);
|
||||
every `rechazadas` should be 0. It needs an empty platform: the hospital's ids
|
||||
travel with the rows, so a second load is refused without writing anything.
|
||||
To load again, run `docker compose down -v` first.
|
||||
|
||||
```sh
|
||||
docker compose down # stop, keep the data
|
||||
docker compose down -v # stop and delete this project's data
|
||||
```
|
||||
|
||||
## TEA EEGs from real EDF files
|
||||
|
||||
Set `EDF_CARPETA` in `.env` to an absolute path holding `.edf` files. On the
|
||||
next populate, each file becomes one more TEA child after the `N` synthetic
|
||||
ones (`N-0201`, `N-0202`... with `N=200`), a case the platform counts as autism:
|
||||
an at-risk M-CHAT, an ADOS-2 classed autism (module 1 or 2, CSS 5 to 10), a
|
||||
note with F84.0, and one EEG that carries the file. The `N` synthetic children
|
||||
are the same as without the folder. Left empty, the hospital has only the
|
||||
synthetic EDFs.
|
||||
|
||||
```sh
|
||||
docker compose down -v # the populate jobs leave a populated hospital alone
|
||||
docker compose up --build -d
|
||||
docker compose logs poblar # one line per file: child key and where its age came from
|
||||
docker compose run --rm --build load
|
||||
```
|
||||
|
||||
Things to know:
|
||||
|
||||
- **The age is the file's**: recording start minus birth date in its header.
|
||||
The child's birth date and EEG date are set to keep it. A header without a
|
||||
birth date, or with the 01.01.85 "unknown" start, gets an age drawn inside
|
||||
the cohort, and the log says so.
|
||||
- **The stored header is rewritten** with the child's key, birth date, EEG
|
||||
date and `LAB-<key>-1`, so nothing of the original patient reaches the
|
||||
hospital. The signal is untouched.
|
||||
- **Size**: a file over 256 MB, or one that isn't an EDF, stops the TEA
|
||||
populate with its name and writes nothing. The hospital's MySQL takes 1 GB
|
||||
packets for these rows.
|
||||
- **The TEA figures move**: the extra confirmed cases raise prevalence, the
|
||||
M-CHAT positive predictive value and the confirmed counts. `documentos`
|
||||
writes PDFs only for the `N` synthetic children.
|
||||
- **A relative `EDF_CARPETA`** resolves from `../dev-data`, not from this
|
||||
folder; use an absolute path.
|
||||
|
||||
## Indicators
|
||||
|
||||
The measures are defined in dbt (`../ISSSTELEON/Transformation`). The `webapi`
|
||||
image compiles them into a manifest while it builds and sets `DBT_MANIFEST` to
|
||||
it; without that variable the API has no measure routes and the pages answer
|
||||
"No fue posible cargar los indicadores". Check it with:
|
||||
|
||||
```sh
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5210/tea/fhir/Measure # 200
|
||||
```
|
||||
|
||||
After `load`, the `indicadores` service recomputes each project on its own
|
||||
(it polls every 20 seconds, and a project takes from seconds to a few
|
||||
minutes). Until it finishes, the pages have no figures. Its state per project:
|
||||
|
||||
```sh
|
||||
curl -s http://localhost:5210/reportes/indicadores # "estado": "ok" when done
|
||||
docker compose logs -f indicadores
|
||||
```
|
||||
|
||||
A platform that was loaded before the image had the manifest keeps its data
|
||||
but has nothing computed. Rebuild and ask for the recomputation, once per
|
||||
project:
|
||||
|
||||
```sh
|
||||
docker compose up --build -d
|
||||
for p in cacu cama tea; do curl -s -X POST "http://localhost:5210/$p/fhir/Measure/\$recalcular"; done
|
||||
```
|
||||
|
||||
Things to know:
|
||||
|
||||
- **The manifest's SQL is SQLite's**, the default engine here. With
|
||||
`*_DATABASE_URL` on another engine, compile the manifest with that dbt
|
||||
target (`../ISSSTELEON/Transformation/profiles.yml`), mount it in `webapi`
|
||||
and `indicadores`, and set `DBT_MANIFEST` to its path.
|
||||
- **Patient-level pages need `DEV_REVISION`** (set in `.env`): the follow-up
|
||||
lists and TEA's patient summary are served only with it, because they are
|
||||
meant for simulated data.
|
||||
- **A change in `Transformation` needs a rebuild** (`up --build -d`) and a
|
||||
recomputation, as above.
|
||||
|
||||
## TEA from the app
|
||||
|
||||
The whole baseline flow runs from **Gobernanza → TEA · EEG** in the web app: check the cluster, train the
|
||||
seven EEG age baselines (or upload a `baselines.zip`), attach the reports, promote, analyse the EEGs and read the
|
||||
result. No shell is needed after the deployment is up and loaded. The command-line version of the same flow is in
|
||||
the next section; use it when the app can't do a step.
|
||||
|
||||
### The state `load` leaves
|
||||
|
||||
With the settings below, `up` and `load` leave the platform with the hospital's TEA children and their EEGs
|
||||
**unanalysed**: no baseline is in production and the indicator cycle skips the EEG analysis
|
||||
(`EEG_ANALYSIS_CLUSTER=off`). Resultado shows `EEGs 62, Analizados 0`. Nothing else is needed before the app steps.
|
||||
|
||||
```sh
|
||||
docker compose up --build -d # hospital populated with the real EDFs in EDF_CARPETA
|
||||
docker compose run --rm --build load # every `rechazadas` must be 0
|
||||
```
|
||||
|
||||
Settings in `.env` (the template is `ISSSTELEON/dist/.env.ejemplo`):
|
||||
|
||||
| Setting | Value here | Purpose |
|
||||
|---|---|---|
|
||||
| `EDF_CARPETA` | absolute path of the real EDFs | each file becomes one TEA child (see "TEA EEGs from real EDF files"); the `N` synthetic children are left out |
|
||||
| `DASK_SCHEDULER_ADDRESS` | `tcp://<host>:<port>` | where Remoto runs; empty means no cluster |
|
||||
| `TEA_DASK_EXPECTED_WORKERS` | `40` | the worker count the cluster card compares with |
|
||||
| `TEA_DASK_DASHBOARD_PORT` | `30787` | port of the Dask dashboard on the scheduler's host; `TEA_DASK_DASHBOARD_URL` replaces the whole address |
|
||||
| `TEA_DASK_SCHEDULERS` | optional | extra scheduler addresses the card may check, besides `DASK_SCHEDULER_ADDRESS` |
|
||||
| `TEA_REFERENCE_ROOT` | `/referencia` | folder in the `webapi` container with one subfolder per reference cohort, for local training and uploads |
|
||||
| `REFERENCIA_CARPETA` | `../manual-deploy/referencia` | host folder mounted at `/referencia` (relative paths resolve from `../ISSSTELEON`) |
|
||||
| `EEG_ANALYSIS_CLUSTER` | `off` | `off` leaves the EEG analysis out of the indicator cycle, so the EEGs wait for the baselines. `auto` analyses in the cycle on the cluster (or locally with no scheduler); `local`, `remote` and `sync` force a mode |
|
||||
| `TEA_REFERENCE_NAME` | optional | default cohort name for a training request that gives none |
|
||||
|
||||
Remote runs need the **platform and worker images built the same day** from the same checkout, with the same
|
||||
Python: Dask refuses a worker whose Python differs even by a patch. Build the platform with
|
||||
`docker compose build --pull`, then the worker image (`../dask-cluster/build.sh`) and `./deploy.sh`; `build.sh`
|
||||
stops with that advice when the two differ.
|
||||
|
||||
### The steps
|
||||
|
||||
| Step | What to do | What you see |
|
||||
|---|---|---|
|
||||
| **Clúster** | Pick Auto, Local, Remoto or Sync; the choice applies to Entrenar and Analizar. With Remoto press **Verificar**. | Scheduler, workers (`40 de 40`), versions (`Cliente y trabajadores coinciden`), dashboard, and a button that opens the Dask dashboard. |
|
||||
| **Datos de referencia** | Only for training on this machine (Local or Sync): upload a cohort's EDFs and its `edades.csv`, or see the cohorts already in `TEA_REFERENCE_ROOT`. | One row per cohort with its EDF count and whether it has ages. |
|
||||
| **Entrenar** | *Remoto*: type the cohort's path **on the cluster** (`/referencia/helsinki`) and its ages table (`/referencia/helsinki/edades.csv`); choose 50 or 60 Hz. *Local*: pick an uploaded cohort. Leave **Promover al terminar** unticked (promotion needs the reports). Press **Entrenar**. | The run monitor: phase, `done/total`, ETA, CPU and RAM per worker, task counts, and a history. Seven `eeg-*` versions appear when it ends (`223 estudios` on 40 workers took 3 min 16 s). |
|
||||
| **Líneas base** | **Exportar** downloads `baselines.zip`. **Importar** takes a zip from your computer instead of training, for example `baselines/baselines.zip`. Importing the same versions twice is refused. | The imported versions, or a clear message when they already exist. Wait for it to finish before the next step. |
|
||||
| **Reportes** | Enter the technical validation, clinical validation and interpretability addresses and apply them to the versions. At least one address is required. | `Reportes aplicados a 7 de 7 versiones.` |
|
||||
| **Promover** | **Promover todas**. A version missing its reports shows the checks that failed. | `Promovidas 7 de 7.` Promotion applies to the next analysis without restarting anything. |
|
||||
| **Verificar línea base** | Pick a scenario, version and metric to see its p5–p95 age curve and overlay analysed EEGs. A cohort too small to have curves says so. | The curve and, once EEGs are analysed, where each study falls. |
|
||||
| **Analizar** | Choose **Pendientes**, **Primeros N** or **EEGs elegidos**, then **Analizar**. **Subir EDF** adds a new study first. Then **Ejecutar ciclo de indicadores** to rebuild the indicator views from the new metrics. | The run monitor again, then `Válidos`, `No válidos`, `Fallidos`. |
|
||||
| **Resultado** | **Actualizar**. | EEGs, analysed, valid, metrics, metrics with z, high and low, and the FHIR view rows; the state of the TEA indicator cycle. |
|
||||
|
||||
Things to know:
|
||||
|
||||
- **Every step reads the versions again when you open it**, so a zip imported in Líneas base shows up in Reportes
|
||||
without reloading the page.
|
||||
- **Remote training reads the cluster's volume.** The files must already be at `/referencia/<name>` on the workers
|
||||
(`../dask-cluster/sync-reference.sh <folder> <name>`, step K2). Uploads in Datos de referencia reach only this
|
||||
machine, so they serve Local and Sync runs.
|
||||
- **Analysing on Remoto sends the EDFs to the workers**; the monitor may print a harmless Dask warning about the
|
||||
size of the task graph.
|
||||
- **A cohort with fewer than about 30 studies per age bin has no curves** and its metrics carry no z; use the
|
||||
full reference cohort for real results.
|
||||
- **To go back to analysing inside the cycle**, set `EEG_ANALYSIS_CLUSTER=auto`, recreate `webapi` and
|
||||
`indicadores`, and ask for a cycle in Analizar. EEGs already analysed without baselines are not re-analysed:
|
||||
choose **EEGs elegidos** for them.
|
||||
|
||||
What still needs the host: building and pushing the worker image (K1), copying reference data to the cluster (K2),
|
||||
deploying or deleting the cluster (K3), and the dev-data `poblar` and `load` jobs, which fill the simulated hospital
|
||||
and import it.
|
||||
|
||||
## TEA from the command line: EEG age baselines on a Dask cluster
|
||||
|
||||
Two copies of this deployment, built from the same folder: **A** (project
|
||||
`sitio-a`, the one in `.env`) trains the seven EEG age baselines on the Dask
|
||||
cluster and exports them; **B** (project `sitio-b`) runs the simulated
|
||||
hospital with the real EDFs, imports and promotes the baselines, then loads.
|
||||
B's indicator cycle analyses the EEGs on the cluster by itself. Both use the
|
||||
same ports, so only one runs at a time.
|
||||
|
||||
The commands below use these placeholders:
|
||||
|
||||
| Placeholder | What it is |
|
||||
|---|---|
|
||||
| `<referencia>` | folder of training EDFs plus `edades.csv`, the ages table |
|
||||
| `<edf>` | folder of EDFs for B's simulated hospital |
|
||||
| `<scheduler>` | the Dask scheduler, `tcp://<host>:<port>`; its dashboard is at `http://<host>:<port>/status` |
|
||||
| `$API` | `http://localhost:<WEBAPI_PORT>` |
|
||||
| `$PY` | `/app/WebApi/.venv/bin/python`, the Python inside the platform image (its entrypoint ignores other commands) |
|
||||
|
||||
Set the two variables in the shell first, for example
|
||||
`API=http://localhost:5210 PY=/app/WebApi/.venv/bin/python`.
|
||||
|
||||
Each deployment keeps its data in the volume `<project>_webapi_data`, mounted
|
||||
at `/data` (`/data/tea.db`, `/data/mlflow.db`). The cluster scripts are in
|
||||
`../dask-cluster`; its README explains how the worker image is built.
|
||||
|
||||
### Once: settings
|
||||
|
||||
The containers read their environment from `.env`, shared by A and B. It
|
||||
needs:
|
||||
|
||||
```sh
|
||||
EDF_CARPETA=<edf>
|
||||
TEA_ALTERACIONES_VALIDADAS=1
|
||||
DASK_SCHEDULER_ADDRESS=<scheduler>
|
||||
```
|
||||
|
||||
With the scheduler set, training, the indicator cycle and any manual analysis
|
||||
run on the cluster, and a TEA cycle needs the cluster up. To run without it,
|
||||
remove that line and recreate `webapi` and `indicadores`. A also puts the EDF
|
||||
children in its hospital; that doesn't matter, A is never loaded.
|
||||
|
||||
### K. The cluster
|
||||
|
||||
```sh
|
||||
kubectl get daskclusters # Running
|
||||
curl -s http://<host>:<dashboard-port>/json/counts.json # the expected number of workers
|
||||
```
|
||||
|
||||
Only after a change to ISSSTELEON or to the training data:
|
||||
|
||||
```sh
|
||||
cd ../dask-cluster
|
||||
WEBAPI_IMAGE=sitio-a/webapi:local ./build.sh # K1: rebuild and push the worker image
|
||||
./sync-reference.sh <referencia> <name> # K2: copy the training data to the cluster volume
|
||||
./deploy.sh # K3: start or update the cluster
|
||||
```
|
||||
|
||||
- **K1** must print the same versions as the platform, Python's patch included.
|
||||
Rebuild the deployments from the same ISSSTELEON commit with
|
||||
`docker compose build --pull`, and this image the same day, or the version
|
||||
check refuses the workers. `build.sh` writes the image tag to `.image`, which `deploy.sh`
|
||||
and `sync-reference.sh` read.
|
||||
- **K2** puts the files at `/referencia/<name>` in every worker and ends with
|
||||
`copied: n of n EDF files`, each at its local size; a missing or truncated
|
||||
file fails it by name. The pod downloads from this machine over HTTP while
|
||||
it runs, open to the LAN: fine for public reference data, not for patient
|
||||
EEGs.
|
||||
|
||||
### A. Train and export
|
||||
|
||||
```sh
|
||||
docker compose -p sitio-b down # A1: B down, A up
|
||||
docker compose up -d
|
||||
until curl -sf $API/health >/dev/null; do sleep 5; done
|
||||
docker compose exec webapi printenv DASK_SCHEDULER_ADDRESS # <scheduler>
|
||||
```
|
||||
|
||||
```sh
|
||||
# A2: train the seven baselines on the cluster
|
||||
docker compose run --rm --entrypoint $PY -v <referencia>:/referencia/<name>:ro \
|
||||
webapi -m models run tea eeg --train --environment prod \
|
||||
--reference-dir /referencia/<name> --reference-ages /referencia/<name>/edades.csv \
|
||||
--reference-name sitio-a --line-hz 50
|
||||
```
|
||||
|
||||
Seven lines, `eeg-…: trained, version N` (or `already trained`). The studies
|
||||
show on the cluster dashboard while it runs. For a run from scratch, use
|
||||
`docker compose down -v` in A1; it deletes A's MLflow and data.
|
||||
|
||||
```sh
|
||||
# A3: export, then stop A
|
||||
mkdir -p baselines
|
||||
docker compose run --rm --entrypoint $PY -v "$PWD/baselines:/salida" \
|
||||
webapi -m models tea export-baselines --out /salida/baselines.zip --environment prod
|
||||
sha256sum baselines/baselines.zip
|
||||
docker compose down
|
||||
```
|
||||
|
||||
It prints the seven versions and `written: /salida/baselines.zip (sha256 …)`,
|
||||
the same hash `sha256sum` shows. `down` without `-v` keeps A's MLflow.
|
||||
|
||||
### B. Import, promote, load
|
||||
|
||||
Every command is `docker compose -p sitio-b`. The baselines must be in
|
||||
production before `load`.
|
||||
|
||||
```sh
|
||||
docker compose down # B1: A down, B from empty
|
||||
docker compose -p sitio-b down -v # deletes B's data, never A's
|
||||
```
|
||||
|
||||
```sh
|
||||
# B2: build, then start, as two steps: in one go it can run the machine out of memory
|
||||
docker compose -p sitio-b build
|
||||
docker compose -p sitio-b up -d
|
||||
until curl -sf $API/health >/dev/null; do sleep 5; done
|
||||
docker compose -p sitio-b exec webapi printenv DASK_SCHEDULER_ADDRESS
|
||||
docker compose -p sitio-b logs poblar | head -3 # EDF de /edf: n archivos ...
|
||||
```
|
||||
|
||||
```sh
|
||||
# B3: import the baselines
|
||||
docker compose -p sitio-b run --rm -T --entrypoint $PY -v "$PWD/baselines:/salida:ro" \
|
||||
webapi -m models tea import-baselines /salida/baselines.zip | tee baselines/import-b.txt
|
||||
```
|
||||
|
||||
Seven lines, `eeg-…: imported as version 1`.
|
||||
|
||||
```sh
|
||||
# B4: attach the three reports to each version
|
||||
sed -nE 's/^([a-z0-9-]+): .* version ([0-9]+)$/\1 \2/p' baselines/import-b.txt |
|
||||
while read scenario version; do
|
||||
curl -s -o /dev/null -w "$scenario $version: %{http_code}\n" -X PATCH -H 'Content-Type: application/json' \
|
||||
-d '{"technical_validation_report_uri": "file:///pendiente/tecnico.pdf",
|
||||
"clinical_validation_report_uri": "file:///pendiente/clinico.pdf",
|
||||
"interpretability_report_uri": "file:///pendiente/interpretabilidad.pdf"}' \
|
||||
"$API/governance/model-versions/tea/$scenario/$version/reports"
|
||||
done
|
||||
```
|
||||
|
||||
Seven `200` lines. These URIs are placeholders for a test deployment; on a
|
||||
real installation they point at the domain expert's documents.
|
||||
|
||||
```sh
|
||||
# B5: promote the baselines
|
||||
docker compose -p sitio-b run --rm --entrypoint $PY webapi -m models run tea eeg --promote --environment prod
|
||||
```
|
||||
|
||||
Seven lines, `version 1 promoted`.
|
||||
|
||||
```sh
|
||||
# B6: load, and let the cycle analyse on the cluster
|
||||
docker compose -p sitio-b run --rm --build load
|
||||
docker compose -p sitio-b logs -f indicadores | grep --line-buffered -E 'analyze_eeg|tea: |ERROR'
|
||||
```
|
||||
|
||||
Every `rechazadas` is 0. Then `analyze_eeg: … elementos` while the dashboard
|
||||
shows the batches, and `tea: ok` when the views are built. This needs
|
||||
`EEG_ANALYSIS_CLUSTER=auto` in `.env`; with `off` (the default for the app
|
||||
flow) the cycle leaves the EEGs unanalysed and `analyze_eeg` never appears.
|
||||
|
||||
```sh
|
||||
# B7: check the result
|
||||
docker compose -p sitio-b exec -T webapi $PY -c "
|
||||
import sqlite3; c = sqlite3.connect('file:/data/tea.db?mode=ro', uri=True)
|
||||
print('analysed EEGs, metrics, with z, high, low:', c.execute('select count(distinct met_eeg_id), count(*), sum(met_z is not null), sum(met_fuera = 1), sum(met_fuera = -1) from eeg_metrica').fetchone())
|
||||
for t in ('tea_paciente_eegs', 'tea_paciente_eeg_metricas'): print(t, c.execute(f'select count(*) from {t}').fetchone()[0])"
|
||||
```
|
||||
|
||||
Most analysed EEGs should have metrics with a z; `H` and `L` in TEA's patient
|
||||
summary are metrics above or below the age curve (`N/A` are the validation
|
||||
criteria). In the app, TEA's patient summary shows each metric against its
|
||||
curve.
|
||||
|
||||
### Tear down
|
||||
|
||||
```sh
|
||||
docker compose -p sitio-b down # -v also deletes B's data
|
||||
(cd ../dask-cluster && ./deploy.sh --delete) # frees the nodes; the training data stays on the volume
|
||||
```
|
||||
|
||||
Before the next TEA load without the cluster, remove `DASK_SCHEDULER_ADDRESS`
|
||||
from `.env`.
|
||||
|
||||
### If something fails
|
||||
|
||||
| What you see | Why, and what to do |
|
||||
|---|---|
|
||||
| `port is already allocated` on `up` | The other deployment is still up: `docker compose down` (A) or `docker compose -p sitio-b down` (B). |
|
||||
| `printenv DASK_SCHEDULER_ADDRESS` prints nothing | The line isn't in `.env`, or the container started before it was added. Fix `.env` and recreate `webapi` and `indicadores`. |
|
||||
| `poblar` says `Sin archivos EDF` | `EDF_CARPETA` is empty. Fix `.env`, then B1 and B2. |
|
||||
| No alterations in the app after B6 | `curl -s $API/reportes/indicadores`: `en_curso` means the cycle is still running; `error` means read the `indicadores` logs. `TEA_ALTERACIONES_VALIDADAS` must be 1. |
|
||||
| Metrics without z after the load | The baselines weren't in production when the cycle analysed. Run B5, then `... run --rm --entrypoint $PY webapi -m models tea analyze --all` and request a fresh cycle with `POST /reportes/indicadores/tea/recalcular`. |
|
||||
| `ValueError: Mismatched versions found` | The worker image comes from another ISSSTELEON commit than the deployment's, or from a Python with another patch number (`python 3.12.15` against `3.12.16`). Rebuild the platform with `docker compose build --pull`, then K1 and K3 the same day. |
|
||||
| `all predefined address pools have been fully subnetted` | Docker has no free network left because of the other projects on the machine. Remove one you don't need, or give this project a subnet in an extra Compose file, `networks: {default: {ipam: {config: [{subnet: 10.240.77.0/24}]}}}`, any range that `docker network ls` and `ip route` don't use, and add it with `-f docker-compose.yml -f <file>`. |
|
||||
| `table _alembic_tmp_latest_metrics already exists` | The first start was interrupted while MLflow migrated its database. `down -v` and start again, and wait for `health` before the first request. |
|
||||
| The cycle or training hangs at the start | The container can't reach the scheduler, or the cluster is down. Check K. |
|
||||
| `no folder /referencia/<name>` from a worker | The training data isn't on the volume. K2. |
|
||||
| `KeyError: 'posterior_rhythm_hz'` | No study had an age: `edades.csv` missing from `<referencia>` or not passed with `--reference-ages`. |
|
||||
| `not promoted, missing: MLD-…` | A report is missing on that version. B4. |
|
||||
| The machine freezes during B2 | Out of memory. A down, other programs closed, `build` and `up -d` separately. |
|
||||
| `load` refuses a batch | B wasn't empty. B1 and B2 again. |
|
||||
|
||||
## Generate the test documents
|
||||
|
||||
```sh
|
||||
docker compose run --rm --build documentos
|
||||
```
|
||||
|
||||
It writes PDFs of the same patients the hospital holds into `./documentos`
|
||||
(ignored by git). It doesn't need the platform or the hospital to be up: the
|
||||
documents come from the same generator, seed (`SEMILLA`) and reference date
|
||||
(`REFERENCIA`) as the hospital's rows, so a patient key in a PDF is a patient
|
||||
key in the hospital.
|
||||
|
||||
| Folder | Documents | How many |
|
||||
|---|---|---|
|
||||
| `documentos/cacu/` | CaCu records, one per cytology (`CACU-0002-C1`), 3 to 7 pages: order, cover, cytology form and, when the history has them, HPV result, colposcopy note, pathology report and the note that resolves the cytology | the first `N_DOCUMENTOS_CACU` patients (20) |
|
||||
| `documentos/tea/` | the ADOS-2 score summary of the psychological evaluation, one page per child with module 1, 2 or 3 (`N-0001-ADOS2`) | all `N` children (200) |
|
||||
|
||||
Each record has its own folder:
|
||||
|
||||
- CaCu: `<key>_limpio.pdf` (text), `<key>_escaneado.pdf` (every page an
|
||||
image, no text layer, to exercise OCR), the page images and field masks,
|
||||
and `ground_truth.json` / `.csv` with each field's value and its box in
|
||||
both PDFs.
|
||||
- TEA: `<key>.pdf` with selectable text, not scanned, and its `ground_truth`.
|
||||
|
||||
`indice.json` in each folder lists the records.
|
||||
|
||||
Things to know:
|
||||
|
||||
- **CaCu is heavy by design.** Every page is rasterised and degraded: 12
|
||||
patients took 28 seconds and 35 MB for 76 pages on the development machine.
|
||||
Twenty patients give around 30 records; all 300 give 442 records and 1,800
|
||||
pages, so expect several minutes and close to 1 GB. Raise it for one run
|
||||
with `N_DOCUMENTOS_CACU=300 docker compose run --rm --build documentos`.
|
||||
- **Module 3 is rare.** With seed 7 the first child with ADOS-2 module 3 is
|
||||
number 247, so a hospital of 200 children has none. To see one, generate
|
||||
with `N=250` or more; those documents have no row in a 200-child hospital.
|
||||
- **What matches the hospital.** Patient key, dates, cytology and HPV results,
|
||||
biopsy grade, ICD-10 codes and each ADOS-2 item score are the hospital's.
|
||||
Names, doctors, vital signs and the wording of notes exist only in the
|
||||
documents. The ADOS-2 totals add only the items of the child's module; the
|
||||
platform adds every item the hospital row has, so its totals can be higher.
|
||||
- **The files belong to root**, because the container writes them. Delete the
|
||||
folder with `sudo rm -rf documentos`.
|
||||
- Nothing here loads these PDFs into the platform; `load` only imports the
|
||||
hospital's tables.
|
||||
|
||||
The same documents without Docker, from `../dev-data`:
|
||||
|
||||
```sh
|
||||
uv run python -m dev_data documentos cacu --referencia 2026-01-01 --salida datos/expedientes
|
||||
uv run python -m dev_data documentos tea --referencia 2026-01-01 --salida datos/ados2
|
||||
```
|
||||
@@ -0,0 +1,7 @@
|
||||
eeg-gradient: imported as version 1
|
||||
eeg-posterior-rhythm: imported as version 1
|
||||
eeg-spikes: imported as version 1
|
||||
eeg-spindle-topography-n2: imported as version 1
|
||||
eeg-spindle-topography-n3: imported as version 1
|
||||
eeg-spindles-n2: imported as version 1
|
||||
eeg-spindles-n3: imported as version 1
|
||||
@@ -0,0 +1,84 @@
|
||||
# Manual deployment of the whole platform plus the simulated hospital, built
|
||||
# from the two checkouts next to this folder (../ISSSTELEON and ../dev-data).
|
||||
# Ports, bind address and project name come from .env, so several copies can
|
||||
# run on one machine without touching each other or the other deployments.
|
||||
#
|
||||
# docker compose up --build -d # platform + hospital, hospital populated
|
||||
# docker compose run --rm --build load # import the hospital into the platform
|
||||
# docker compose run --rm --build documentos # write the test PDFs to ./documentos
|
||||
# docker compose down # stop, keep the data
|
||||
# docker compose down -v # stop and delete this project's data
|
||||
#
|
||||
# Run from this folder. `load` needs an empty platform: the hospital's ids
|
||||
# travel with the rows, so a second load is refused without writing anything.
|
||||
# To load again, `down -v` first. README.md has the whole walkthrough.
|
||||
include:
|
||||
- path:
|
||||
- ../ISSSTELEON/docker-compose.yml
|
||||
- platform.override.yml
|
||||
project_directory: ../ISSSTELEON
|
||||
env_file: .env
|
||||
- path:
|
||||
- ../dev-data/compose.prueba.yml
|
||||
- hospital.override.yml
|
||||
project_directory: ../dev-data
|
||||
env_file: .env
|
||||
|
||||
services:
|
||||
# One-shot: imports the three projects through the platform's import API.
|
||||
# Inside the project network the API is the webapp proxy and the hospital
|
||||
# is reached by service name, as the webapi container sees it.
|
||||
load:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: dev-data/Dockerfile
|
||||
profiles: [load]
|
||||
depends_on:
|
||||
webapi:
|
||||
condition: service_healthy
|
||||
webapp:
|
||||
condition: service_started
|
||||
poblar:
|
||||
condition: service_completed_successfully
|
||||
poblar-cacu:
|
||||
condition: service_completed_successfully
|
||||
poblar-cama:
|
||||
condition: service_completed_successfully
|
||||
entrypoint: ["sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
for pair in cacu:hospital_cacu cama:hospital_cama tea:hospital; do
|
||||
project="$${pair%%:*}"
|
||||
database="$${pair#*:}"
|
||||
echo "== $$project"
|
||||
uv run --frozen --no-dev python -m dev_data cargar "$$project" \
|
||||
--api http://webapp \
|
||||
--hospital "mysql+pymysql://hospital:hospital@hospital:3306/$$database"
|
||||
done
|
||||
echo
|
||||
echo "Loaded. TEA's EEGs are not analysed until their baselines are in production:"
|
||||
echo "open the app, Gobernanza > TEA · EEG, train or import baselines.zip, attach the reports,"
|
||||
echo "promote, then Analizar. README.md, \"TEA from the app\"."
|
||||
|
||||
# One-shot: writes the test PDFs of the same patients the hospital holds
|
||||
# (same seed and reference date) into ./documentos. It needs neither the
|
||||
# platform nor the hospital. CaCu pages are rasterised and degraded, which
|
||||
# is slow and large, so its count is separate from the hospital's.
|
||||
documentos:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: dev-data/Dockerfile
|
||||
profiles: [documentos]
|
||||
volumes:
|
||||
- ./documentos:/documentos
|
||||
entrypoint: ["sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
uv run --frozen --no-dev python -m dev_data documentos cacu \
|
||||
--n "${N_DOCUMENTOS_CACU:-20}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
|
||||
--salida /documentos/cacu
|
||||
uv run --frozen --no-dev python -m dev_data documentos tea \
|
||||
--n "${N:-200}" --semilla "${SEMILLA:-7}" --referencia "${REFERENCIA:-2026-01-01}" \
|
||||
--salida /documentos/tea
|
||||
@@ -0,0 +1,24 @@
|
||||
# Applied over ../dev-data/compose.prueba.yml. The platform reaches the
|
||||
# hospital by service name; the published port is only for inspecting it
|
||||
# from outside with a MySQL client.
|
||||
services:
|
||||
hospital:
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${HOSPITAL_PORT:-29505}:3306"
|
||||
|
||||
# Without their profile the populate jobs run on every `up`. They leave a
|
||||
# hospital that already has rows alone.
|
||||
#
|
||||
# TEA reads EDF_CARPETA, read-only, as /edf (`poblar tea --edf`). Paths here
|
||||
# resolve from ../dev-data, so the default is the empty sin-edf folder next to
|
||||
# this file: no real files, only the synthetic EDFs.
|
||||
poblar:
|
||||
profiles: !reset []
|
||||
environment:
|
||||
DEV_DATA_EDF: /edf
|
||||
volumes:
|
||||
- "${EDF_CARPETA:-../manual-deploy/sin-edf}:/edf:ro"
|
||||
poblar-cacu:
|
||||
profiles: !reset []
|
||||
poblar-cama:
|
||||
profiles: !reset []
|
||||
@@ -0,0 +1,33 @@
|
||||
# Applied over ../ISSSTELEON/docker-compose.yml. Paths here resolve from
|
||||
# ../ISSSTELEON.
|
||||
#
|
||||
# Images are tagged per project so a build here doesn't replace the
|
||||
# isssteleon/*:dev images other deployments run. The containers read
|
||||
# manual-deploy/.env instead of ISSSTELEON/.env, so a .env left in the source
|
||||
# tree never points this stack at another deployment's databases.
|
||||
x-api: &api
|
||||
image: ${COMPOSE_PROJECT_NAME}/webapi:local
|
||||
env_file: !override
|
||||
- ../manual-deploy/.env
|
||||
|
||||
services:
|
||||
webapi:
|
||||
<<: *api
|
||||
volumes:
|
||||
- "${REFERENCIA_CARPETA:-./referencia}:/referencia"
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPI_PORT:-25050}:5000"
|
||||
|
||||
indicadores:
|
||||
<<: *api
|
||||
|
||||
# Runs the webapi image this project builds; without this it asks for
|
||||
# isssteleon/webapi:dev, which nothing here builds.
|
||||
notebooks:
|
||||
image: ${COMPOSE_PROJECT_NAME}/webapi:local
|
||||
pull_policy: never
|
||||
|
||||
webapp:
|
||||
image: ${COMPOSE_PROJECT_NAME}/webapp:local
|
||||
ports: !override
|
||||
- "${BIND_ADDRESS:-0.0.0.0}:${WEBAPP_PORT:-28080}:80"
|
||||
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 82 KiB |