Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions .github/workflows/installer_roundtrip.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
name: Installer round trip

# Builds a real installer of a small demo app made from this template (tests/smoke/make_demo_app.py: the placeholders filled in, the
# release scripts run as release_constructor.yml runs them, the same constructor environment and build script), installs it silently,
# checks the install, uninstalls it silently and checks what is left (tests/smoke/installer_roundtrip.py). On Windows a second round trip
# keeps a Python of the app running during the uninstall and prints what stays of the folder (diagnosis only).
# It runs on the pull requests that change what an installer is made of, and by hand. It does not run in the apps created from the template.
on:
pull_request:
paths:
- 'app/**'
- 'construct.yaml'
- 'environment.yaml'
- 'setup.py'
- 'requirements*.txt'
- '.tools/bash/**'
- '.tools/python/**'
- '.tools/templates/**'
- 'tests/smoke/**'
- '.github/workflows/installer_roundtrip.yml'
- '.github/workflows/release_constructor.yml'
workflow_dispatch:

permissions:
contents: read

concurrency:
group: installer-roundtrip-${{ github.ref }}
cancel-in-progress: true

jobs:
roundtrip:
if: github.repository == 'CellMigrationLab/LabConstrictor'
name: Install and uninstall (${{ matrix.os }})
runs-on: ${{ matrix.os }}
timeout-minutes: 75
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
defaults:
run:
shell: bash -l {0}
env:
CONSTRUCTOR_ENV: constructor-env
DEMO: ${{ github.workspace }}/../demo-app
ARTIFACTS: ${{ github.workspace }}/artifacts
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4

- uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4
with:
python-version: '3.11'

- name: Make the demo app from the template (placeholders filled in, release scripts run)
run: |
pip install -r .tools/requirements.txt pillow==11.3.0
python tests/smoke/make_demo_app.py "$DEMO" --version 1.2.3

- name: Set up Miniconda
uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3
with:
auto-activate: true
miniforge-version: latest
use-mamba: true

- name: Create the constructor environment (the release's script)
run: bash .tools/bash/create_constructor_environment.sh

- name: Build the installer (the release's script)
working-directory: ${{ env.DEMO }}
env:
OUTPUT_DIR: dist
run: bash .tools/bash/build_installer_with_constructor.sh && ls -la dist

- name: Install, check, uninstall, check
run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App" --logs "$ARTIFACTS"

- name: 'Windows: uninstall while a Python of the app runs (prints what stays)'
if: runner.os == 'Windows' && !cancelled()
run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App_busy" --busy --logs "$ARTIFACTS"

- name: Upload the logs
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: installer-roundtrip-${{ matrix.os }}-logs
path: artifacts/
if-no-files-found: ignore
241 changes: 241 additions & 0 deletions tests/smoke/installer_roundtrip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
"""Install and uninstall a real installer of the demo app (tests/smoke/make_demo_app.py), silently, and check what each leaves behind.

Install (Windows: the .exe with /S /InstallationType=JustMe; Linux and macOS: the .sh with -b -p), then:
* the post-install log ends with "Post-install completed successfully.";
* the tools registry has the app's entry (<LC_HOME>/apps/Demo App.json): the tools were registered;
* Windows: "Installed apps" lists the app exactly once, under its own name, with the publisher and the version of the release, and
that entry's uninstaller exists.
Uninstall (Windows: Uninstall-Demo_App.exe /S, which hands over to a copy of itself and returns at once, so the folder is watched;
Linux and macOS: the bundled uninstall.sh), then:
* the install folder is gone, the registry entry of the app is gone and the entry of another app is still there (user data is kept);
* Windows: no "Installed apps" entry points to the folder any more.

--busy (Windows): a Python process started from the install folder runs during the uninstall, as Jupyter, Napari or Fiji's tool worker
may. What stays of the folder is printed (files in use cannot be deleted; the uninstaller marks them for removal at the next restart), and
only the "Installed apps" and registry checks fail the run: this mode diagnoses, it does not decide what the uninstaller should do.

Usage: python tests/smoke/installer_roundtrip.py INSTALLER_DIR PREFIX [--busy] [--logs DIR]
(PREFIX: a folder that does not exist yet, without spaces; LC_HOME is set to a fresh folder next to it)
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

APP = "Demo App"
FOLDER = "Demo_App"
OWNER = "CellMigrationLab"
WINDOWS = sys.platform == "win32"
SUCCESS = "Post-install completed successfully."
INSTALL_TIMEOUT = 45 * 60
UNINSTALL_TIMEOUT = 20 * 60
UNINSTALL_ROOT = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"


def step(message: str) -> None:
print(f"\n=== {message}", flush=True)


def ok(message: str) -> None:
print(f"OK {message}", flush=True)


def find_installer(folder: Path) -> Path:
pattern = "*.exe" if WINDOWS else "*.sh"
found = sorted(folder.rglob(pattern))
if len(found) != 1:
raise AssertionError(f"expected one {pattern} installer in {folder}, found {[str(p) for p in found]}")
return found[0]


def apps_entries(prefix: Path) -> list[dict[str, str]]:
"""Windows: the "Installed apps" entries (HKCU and HKLM) named after the app or whose uninstaller is in the install folder."""
if sys.platform != "win32": # also tells mypy that winreg is used on Windows only
return []
import winreg

found = []
for hive, hive_name in ((winreg.HKEY_CURRENT_USER, "HKCU"), (winreg.HKEY_LOCAL_MACHINE, "HKLM")):
try:
uninstall = winreg.OpenKey(hive, UNINSTALL_ROOT)
except OSError:
continue
with uninstall:
for index in range(winreg.QueryInfoKey(uninstall)[0]):
name = winreg.EnumKey(uninstall, index)
values: dict[str, str] = {"key": f"{hive_name}\\{name}"}
with winreg.OpenKey(uninstall, name) as key:
for value in ("DisplayName", "DisplayVersion", "Publisher", "UninstallString"):
try:
values[value] = str(winreg.QueryValueEx(key, value)[0])
except OSError:
values[value] = ""
if name.startswith(FOLDER) or str(prefix).lower() in values["UninstallString"].lower():
found.append(values)
return found


def tail(path: Path, lines: int = 80) -> str:
try:
return "\n".join(path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:])
except OSError as exc:
return f"(cannot read {path}: {exc})"


def install(installer: Path, prefix: Path, version: str, env: dict[str, str], logs: Path) -> None:
step(f"Install {installer.name} into {prefix}")
if WINDOWS:
# /D must be last and unquoted (NSIS).
command = [str(installer), "/S", "/InstallationType=JustMe", "/RegisterPython=0", "/AddToPath=0", f"/D={prefix}"]
else:
command = ["bash", str(installer), "-b", "-p", str(prefix)]
started = time.monotonic()
result = subprocess.run(command, env=env, timeout=INSTALL_TIMEOUT, check=False)
print(f"installer exit code {result.returncode} after {time.monotonic() - started:.0f} s", flush=True)
log = prefix / "menuinst_debug.log"
if log.is_file():
shutil.copyfile(log, logs / f"post_install_{'busy' if 'busy' in prefix.name else 'plain'}.log")
if result.returncode != 0:
raise AssertionError(f"the installer failed (exit code {result.returncode}); end of the post-install log:\n{tail(log)}")
text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
if SUCCESS not in text:
raise AssertionError(f"the post-install log does not say {SUCCESS!r}; its end:\n{tail(log)}")
ok("the post-install script completed")
entry = Path(env["LC_HOME"]) / "apps" / f"{APP}.json"
if not entry.is_file():
raise AssertionError(f"no registry entry {entry} (the tools were not registered); end of the post-install log:\n{tail(log)}")
data = json.loads(entry.read_text(encoding="utf-8"))
ok(f"registry entry {entry.name}: version {data.get('version')!r}, module {data.get('module')!r}")
if WINDOWS:
check_one_apps_entry(prefix, version)


def check_one_apps_entry(prefix: Path, version: str) -> None:
entries = apps_entries(prefix)
for entry in entries:
print(f" Installed apps: {entry}", flush=True)
if len(entries) != 1:
raise AssertionError(f"Installed apps must list the app once, it lists {len(entries)} entries: {entries}")
entry = entries[0]
expected = {"DisplayName": APP, "Publisher": OWNER, "DisplayVersion": version}
wrong = {name: entry[name] for name, value in expected.items() if entry[name] != value}
if wrong:
raise AssertionError(f"the Installed apps entry has {wrong}, expected {expected}")
uninstaller = Path(entry["UninstallString"].strip('"'))
if not uninstaller.is_file():
raise AssertionError(f"the uninstaller of the Installed apps entry does not exist: {uninstaller}")
ok(f"Installed apps lists {APP!r} once (publisher {OWNER}, version {version}), and its uninstaller exists")


def start_busy_process(prefix: Path) -> subprocess.Popen[bytes]:
"""A Python of the app that keeps running, as a Jupyter server or a tool worker does."""
python = prefix / ("python.exe" if WINDOWS else "bin/python")
process = subprocess.Popen([str(python), "-c", "import time; time.sleep(3600)"], cwd=prefix)
time.sleep(5)
if process.poll() is not None:
raise AssertionError(f"the busy process of {python} ended at once (exit code {process.returncode})")
print(f"busy process {process.pid} runs {python}", flush=True)
return process


def uninstall(prefix: Path, env: dict[str, str]) -> None:
step(f"Uninstall {prefix}")
started = time.monotonic()
if WINDOWS:
uninstaller = prefix / f"Uninstall-{FOLDER}.exe"
if not uninstaller.is_file():
raise AssertionError(f"no uninstaller {uninstaller}")
subprocess.run([str(uninstaller), "/S"], env=env, timeout=UNINSTALL_TIMEOUT, check=False)
# The uninstaller copies itself to %TEMP% and returns at once; the copy removes the folder. Wait until it is done.
while time.monotonic() - started < UNINSTALL_TIMEOUT:
if not uninstaller.exists() and not apps_entries(prefix):
break
time.sleep(10)
time.sleep(20) # the last files and the folder itself go after the uninstaller
else:
result = subprocess.run(["bash", str(prefix / "uninstall.sh")], env=env, stdin=subprocess.DEVNULL, timeout=UNINSTALL_TIMEOUT, check=False)
if result.returncode != 0:
raise AssertionError(f"uninstall.sh failed (exit code {result.returncode})")
print(f"uninstall took {time.monotonic() - started:.0f} s", flush=True)


def leftovers(prefix: Path) -> list[str]:
if not prefix.exists():
return []
files = [p for p in prefix.rglob("*") if p.is_file()]
size = sum(p.stat().st_size for p in files if p.exists())
top: dict[str, int] = {}
for path in files:
part = path.relative_to(prefix).parts[0]
top[part] = top.get(part, 0) + 1
lines = [f"{prefix} still holds {len(files)} file(s), {size / 1e6:.1f} MB"]
lines += [f" {name}: {count} file(s)" for name, count in sorted(top.items(), key=lambda item: -item[1])[:25]]
return lines


def check_uninstalled(prefix: Path, env: dict[str, str], other: Path, strict_folder: bool) -> None:
left = leftovers(prefix)
for line in left:
print(line, flush=True)
if left and strict_folder:
raise AssertionError(f"the uninstall left the install folder: {left[0]}")
if not left:
ok("the install folder is gone")
entry = Path(env["LC_HOME"]) / "apps" / f"{APP}.json"
if entry.exists():
raise AssertionError(f"the registry entry of the app is still there: {entry}")
ok("the registry entry of the app is gone")
if not other.is_file():
raise AssertionError(f"the uninstall removed another app's registry entry: {other}")
ok("another app's registry entry is kept")
if WINDOWS:
entries = apps_entries(prefix)
if entries:
raise AssertionError(f"Installed apps still lists the app after the uninstall: {entries}")
ok("Installed apps no longer lists the app")


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("installer_dir", type=Path)
parser.add_argument("prefix", type=Path)
parser.add_argument("--version", default="1.2.3")
parser.add_argument("--busy", action="store_true", help="Windows: a Python of the app runs during the uninstall (diagnosis)")
parser.add_argument("--logs", type=Path, default=Path("artifacts"))
args = parser.parse_args()
prefix: Path = args.prefix.absolute()
if prefix.exists() or " " in str(prefix):
raise SystemExit(f"{prefix}: give a new folder without spaces")
args.logs.mkdir(parents=True, exist_ok=True)
lc_home = prefix.parent / f"{prefix.name}_lc_home"
shutil.rmtree(lc_home, ignore_errors=True)
other = lc_home / "apps" / "Other App.json"
other.parent.mkdir(parents=True)
other.write_text('{"name": "Other App"}\n', encoding="utf-8")
env = {**os.environ, "LC_HOME": str(lc_home)}

install(find_installer(args.installer_dir), prefix, args.version, env, args.logs)
busy = start_busy_process(prefix) if args.busy else None
try:
uninstall(prefix, env)
check_uninstalled(prefix, env, other, strict_folder=busy is None)
finally:
if busy is not None:
busy.kill()
busy.wait()
time.sleep(5)
step("After the busy process ended")
for line in leftovers(prefix) or [f"{prefix} is gone"]:
print(line, flush=True)
print("\ninstaller round trip: all checks passed")
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading