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
4 changes: 2 additions & 2 deletions .github/workflows/installer_roundtrip.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ 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).
# keeps a Python of the app running during the uninstall, which must stop it and still remove the whole folder.
# 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:
Expand Down Expand Up @@ -76,7 +76,7 @@ jobs:
- 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)'
- name: 'Windows: uninstall while a Python of the app runs (it is stopped, the folder is removed)'
if: runner.os == 'Windows' && !cancelled()
run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App_busy" --busy --logs "$ARTIFACTS"

Expand Down
5 changes: 4 additions & 1 deletion .template_sync/manifest.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
template_version: 0.1.46
template_version: 0.1.47
migrations:
- from: 0.0.0
to: 0.0.1
Expand Down Expand Up @@ -144,3 +144,6 @@ migrations:
- from: 0.1.45
to: 0.1.46
script: migrations/v0_1_45_to_v0_1_46.py
- from: 0.1.46
to: 0.1.47
script: migrations/v0_1_46_to_v0_1_47.py
75 changes: 75 additions & 0 deletions .template_sync/migrations/v0_1_46_to_v0_1_47.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""Template 0.1.46 -> 0.1.47: on Windows the uninstall stops the app's running processes, so it can remove the whole app folder.

Design note: https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_47.md

Windows cannot delete a file that a running process uses. Testers who uninstalled while Jupyter was open found the app folder left behind
(python.exe, its DLLs, Lib, DLLs and Library: 0.4 to 4 GB). The uninstaller marks such files for deletion at the next restart, but Windows
does that only for an administrator, and the apps are installed for one user, so the files stayed for good.

What this changes in an app repository (idempotent, never deletes anything, never raises for a customised file):

1. app/bash_bat_scripts/pre_uninstall.bat gets six lines just before its line `echo Pre-uninstall completed!`: three REM lines, the app folder
(the folder of the script), one PowerShell command that stops every process whose program is inside the app folder (a Jupyter server and its kernels, a Napari or
Fiji tool worker), except the uninstaller and its helpers, and waits up to 15 s for each to end, and a line that shows its log
(%TEMP%\labconstrictor_pre_uninstall.log). A script without that line is left as it
is (SKIPPED, with what to do by hand). The file keeps its own line endings.

Linux and macOS are not changed: a running process does not stop the removal of its files there. The change reaches users with the app's next
release.
"""
from __future__ import annotations

from pathlib import Path
from typing import Any

DOCS_URL = "https://github.com/CellMigrationLab/LabConstrictor/blob/main/.tools/docs/migration_0_1_47.md"
TAG = "[migration 0.1.47]"
PRE_UNINSTALL_BAT = Path("app/bash_bat_scripts/pre_uninstall.bat")
ANCHOR = "echo Pre-uninstall completed!"
STOP_LINES = (
'REM Stop the processes of this app that still run (a Jupyter server and its kernels, a Napari or Fiji tool worker): Windows cannot delete',
'REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder (the folder',
'REM of this script) are stopped, never this uninstaller or its helpers; unsaved notebook edits since the last autosave are lost.',
'SET "LC_APP_ROOT=%~dp0"',
'"%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference=\'SilentlyContinue\'; $root=[IO.Path]::GetFullPath($env:LC_APP_ROOT).TrimEnd(\'\\\')+\'\\\'; Write-Output (\'Stopping the processes started from \' + $root); $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne \'_conda.exe\' -and $_.Name -notlike \'Uninstall-*\' }); foreach($p in $own){ Write-Output (\'Stopping \' + $p.Name + \' (process \' + $p.ProcessId + \')\'); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output \'No process of the app is running\' }" > "%TEMP%\\labconstrictor_pre_uninstall.log" 2>&1',
'type "%TEMP%\\labconstrictor_pre_uninstall.log"',
)
BY_HAND = f"add the lines of STOP_LINES in this migration before the end of the script (see {DOCS_URL})"


def log(message: str) -> None:
print(f"{TAG} {message}")


def add_stop_lines(path: Path) -> str:
text = path.read_bytes().decode("utf-8")
if STOP_LINES[0] in text:
return "unchanged: already stops the app's running processes"
lines = text.splitlines(keepends=True)
hits = [index for index, line in enumerate(lines) if line.rstrip("\r\n").strip() == ANCHOR]
if len(hits) != 1:
return f"SKIPPED: no single line {ANCHOR!r} (changed by hand), so it was left unchanged. By hand: {BY_HAND}"
newline = "\r\n" if "\r\n" in text else "\n"
index = hits[0]
lines[index:index] = [line + newline for line in STOP_LINES]
path.write_bytes("".join(lines).encode("utf-8"))
return "updated: the uninstall stops the app's running processes first, so it removes the whole app folder"


def migrate(repo_root: Path, context: dict[str, Any]) -> None:
"""Apply the 0.1.47 change (idempotent, never raises for a customised file, creates and deletes nothing)."""
_ = context
path = repo_root / PRE_UNINSTALL_BAT
if not path.is_file():
log(f"{PRE_UNINSTALL_BAT}: not present in this repository (nothing was created)")
log("done: no repository changes were required.")
return
try:
status = add_stop_lines(path)
except (OSError, UnicodeDecodeError) as exc:
status = f"SKIPPED: {exc}; left unchanged. See {DOCS_URL}"
log(f"{PRE_UNINSTALL_BAT}: {status}")
if status.startswith("updated"):
log(f"done: 1 change(s). It reaches users with the next release of the app. See {DOCS_URL}")
else:
log("done: no repository changes were required.")
41 changes: 41 additions & 0 deletions .tools/docs/migration_0_1_47.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Template 0.1.47: the Windows uninstall stops the app's running processes

Design note for the 0.1.47 migration (`.template_sync/migrations/v0_1_46_to_v0_1_47.py`).

## Why

Testers of LabConstrictor-CAREamics 0.0.5 uninstalled the app on two Windows 11 computers. Both times, part of the app folder
(`%LOCALAPPDATA%\<app>`) stayed behind: `python.exe`, `python3.dll`, `python312.dll`, the Visual C++ runtime DLLs and the folders `DLLs`,
`Lib`, `Library` and `<app>`. That was 433 MB on one computer and 4.1 GB on the other. Jupyter was still open.

Windows cannot delete a file that a running process uses. The uninstaller marks such files for deletion at the next restart, but Windows
does that only for an administrator, and the apps are installed for one user. The installer round trip of the template CI
(`.github/workflows/installer_roundtrip.yml`, `--busy`) showed the same thing with one Python process of the app running: those files stayed,
even after the process ended.

## What changes

`app/bash_bat_scripts/pre_uninstall.bat` now ends with one PowerShell command (after three REM lines and the app folder, which is the folder of
the script) that:

* stops every process whose program is inside the app folder: a Jupyter server and its kernels, a Napari or Fiji tool worker, any other
Python of the app;
* leaves the uninstaller alone: its own process chain, `_conda.exe` and `Uninstall-*.exe`;
* waits up to 15 s for each process to end;
* writes what it stopped to `%TEMP%\labconstrictor_pre_uninstall.log`, which the uninstaller also shows.

The uninstall then removes the whole folder. Notebook edits made since Jupyter's last autosave (every 2 minutes by default) are lost. The
installer round trip checks this on Windows: a running Python of the app is stopped, and the folder is gone.

Linux and macOS do not change: a running process does not stop the removal of its files there.

## What the migration does

It adds the six lines just before the line `echo Pre-uninstall completed!` of `pre_uninstall.bat`, keeping the file's line endings. A
script that already has them is left as it is. So is a script without that line (SKIPPED: add the lines by hand). The change reaches users
with the app's next release.

## Removing what an older uninstall left

Close Jupyter, Napari and Fiji (or restart the computer), then delete the folder `%LOCALAPPDATA%\<app>`. It holds only the app's program files;
notebooks, models and results are in the app's data folder, which the uninstall keeps.
6 changes: 6 additions & 0 deletions app/bash_bat_scripts/pre_uninstall.bat
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,11 @@ IF ERRORLEVEL 1 IF EXIST "%USERPROFILE%\.labconstrictor\apps\PROJECT_NAME.json"
"%PREFIX%\python.exe" -c "from menuinst.api import remove; import os; remove(os.path.join(r'%PREFIX%', 'PROJECT_NAME', 'notebook_launcher.json'))"
SET "ARP_KEY=HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\UNDERSCORED_PROJECT_NAME"
reg delete "%ARP_KEY%" /f >NUL 2>&1
REM Stop the processes of this app that still run (a Jupyter server and its kernels, a Napari or Fiji tool worker): Windows cannot delete
REM a file a process uses, so the uninstall left the app folder behind (template 0.1.47). Only programs inside this app folder (the folder
REM of this script) are stopped, never this uninstaller or its helpers; unsaved notebook edits since the last autosave are lost.
SET "LC_APP_ROOT=%~dp0"
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='SilentlyContinue'; $root=[IO.Path]::GetFullPath($env:LC_APP_ROOT).TrimEnd('\')+'\'; Write-Output ('Stopping the processes started from ' + $root); $all=@(Get-CimInstance Win32_Process); $keep=@{}; $id=[int]$PID; while($id -and -not $keep.ContainsKey($id)){ $keep[$id]=1; $id=[int](($all | Where-Object { [int]$_.ProcessId -eq $id } | Select-Object -First 1).ParentProcessId) }; $own=@($all | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -and -not $keep.ContainsKey([int]$_.ProcessId) -and $_.Name -ne '_conda.exe' -and $_.Name -notlike 'Uninstall-*' }); foreach($p in $own){ Write-Output ('Stopping ' + $p.Name + ' (process ' + $p.ProcessId + ')'); Stop-Process -Id ([int]$p.ProcessId) -Force }; foreach($p in $own){ Wait-Process -Id ([int]$p.ProcessId) -Timeout 15 }; if($own.Count -eq 0){ Write-Output 'No process of the app is running' }" > "%TEMP%\labconstrictor_pre_uninstall.log" 2>&1
type "%TEMP%\labconstrictor_pre_uninstall.log"
echo Pre-uninstall completed!
SetLocal EnableDelayedExpansion
3 changes: 3 additions & 0 deletions tests/_v0_1_46.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@

from pathlib import Path

from _v0_1_47 import before_0_1_47

PIN_0_1_45 = "v0.3.0-alpha.5"
PIN_0_1_46 = "v0.3.0-alpha.6"
PINNED_FILES = (Path("app/bash_bat_scripts/post_install.sh"), Path("app/bash_bat_scripts/post_install.bat"))


def before_0_1_46(relative: Path | str, data: bytes) -> bytes:
"""`data` (a live template file at `relative`) with the 0.1.46 pin moved back; any other file is returned as it is."""
data = before_0_1_47(relative, data)
if Path(relative) not in PINNED_FILES:
return data
return data.replace(PIN_0_1_46.encode(), PIN_0_1_45.encode())
31 changes: 31 additions & 0 deletions tests/_v0_1_47.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Helper of the tests: a live template file as it was before template 0.1.47.

Template 0.1.47 adds the lines that stop the app's running processes to pre_uninstall.bat. The tests of the older migrations compare with
the live files; `before_0_1_47` gives the bytes of a live file without those lines, so they keep checking what they checked. The change
itself is tested in test_template_sync_0_1_47.py.
"""
from __future__ import annotations

import importlib.util
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
PRE_UNINSTALL_BAT = Path("app/bash_bat_scripts/pre_uninstall.bat")


def _stop_lines() -> tuple[str, ...]:
spec = importlib.util.spec_from_file_location("migration_0_1_47_helper", ROOT / ".template_sync/migrations/v0_1_46_to_v0_1_47.py")
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return tuple(module.STOP_LINES)


def before_0_1_47(relative: Path | str, data: bytes) -> bytes:
"""`data` (a live template file at `relative`) without the 0.1.47 lines; any other file is returned as it is."""
if Path(relative) != PRE_UNINSTALL_BAT:
return data
text = data.decode("utf-8")
for newline in ("\r\n", "\n"):
text = text.replace("".join(line + newline for line in _stop_lines()), "")
return text.encode("utf-8")
31 changes: 18 additions & 13 deletions tests/smoke/installer_roundtrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
* 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.
may. pre_uninstall.bat stops it (template 0.1.47), so the same checks hold: the folder is gone (before, the files the process used stayed,
and Windows does not delete them at the next restart for a per-user install), and the process was stopped.

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)
Expand Down Expand Up @@ -179,14 +179,13 @@ def leftovers(prefix: Path) -> list[str]:
return lines


def check_uninstalled(prefix: Path, env: dict[str, str], other: Path, strict_folder: bool) -> None:
def check_uninstalled(prefix: Path, env: dict[str, str], other: Path) -> None:
left = leftovers(prefix)
for line in left:
print(line, flush=True)
if left and strict_folder:
if left:
raise AssertionError(f"the uninstall left the install folder: {left[0]}")
if not left:
ok("the install folder is gone")
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}")
Expand All @@ -206,7 +205,7 @@ def main() -> int:
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("--busy", action="store_true", help="Windows: a Python of the app runs during the uninstall, which must stop it")
parser.add_argument("--logs", type=Path, default=Path("artifacts"))
args = parser.parse_args()
prefix: Path = args.prefix.absolute()
Expand All @@ -224,15 +223,21 @@ def main() -> int:
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:
log = Path(os.environ.get("TEMP", ".")) / "labconstrictor_pre_uninstall.log"
print(f"--- {log}:\n{tail(log)}", flush=True)
if log.is_file():
shutil.copyfile(log, args.logs / "pre_uninstall_busy.log")
if busy.poll() is None:
for line in leftovers(prefix):
print(line, flush=True)
raise AssertionError(f"the uninstall did not stop the app's running process {busy.pid}")
ok(f"the uninstall stopped the app's running process {busy.pid}")
check_uninstalled(prefix, env, other)
finally:
if busy is not None and busy.poll() is 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

Expand Down
Loading
Loading