2026-02-25 15:32:43 -07:00
|
|
|
"""
|
|
|
|
|
Scripts management for WROLPi Controller.
|
|
|
|
|
|
|
|
|
|
Manages maintenance scripts that run as systemd services (like repair.sh).
|
|
|
|
|
Uses systemd oneshot services for process survival across controller restarts.
|
|
|
|
|
"""
|
|
|
|
|
|
2026-11-08 11:25:26 -07:00
|
|
|
import json
|
2026-03-14 10:03:11 -06:00
|
|
|
import logging
|
2026-11-08 08:48:58 -07:00
|
|
|
import re
|
2026-02-25 15:32:43 -07:00
|
|
|
import subprocess
|
2026-10-11 18:29:42 -06:00
|
|
|
import time
|
|
|
|
|
from datetime import datetime, timezone
|
2026-02-25 15:32:43 -07:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
|
|
from controller.lib.config import is_docker_mode
|
|
|
|
|
|
2026-03-14 10:03:11 -06:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-11-08 08:48:58 -07:00
|
|
|
# A branch is written into the systemd env file and passed to `upgrade.sh -b`, so only plain git branch names are
|
|
|
|
|
# accepted: no whitespace (a newline would add an env variable), no leading dash (an option), no `..`.
|
|
|
|
|
# Matches `wrolpi.upgrade.validate_branch`.
|
|
|
|
|
BRANCH_PATTERN = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.\-]*(/[A-Za-z0-9_][A-Za-z0-9_.\-]*)*")
|
|
|
|
|
MAX_BRANCH_LENGTH = 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def is_valid_branch(branch: str) -> bool:
|
|
|
|
|
"""Return True if `branch` is a branch name `upgrade.sh` may be given."""
|
|
|
|
|
return isinstance(branch, str) \
|
|
|
|
|
and len(branch) <= MAX_BRANCH_LENGTH \
|
|
|
|
|
and BRANCH_PATTERN.fullmatch(branch) is not None \
|
|
|
|
|
and ".." not in branch \
|
|
|
|
|
and not branch.endswith((".", ".lock"))
|
|
|
|
|
|
|
|
|
|
|
2026-02-25 15:32:43 -07:00
|
|
|
# Available scripts with their configurations
|
|
|
|
|
# Parameters define inputs that scripts accept:
|
|
|
|
|
# - name: Parameter name (used as env var name, e.g., "branch" -> "BRANCH=value")
|
|
|
|
|
# - label: Display label for the input field
|
|
|
|
|
# - type: "branch" (auto-populates with current git branch) or "text"
|
|
|
|
|
# - required: Whether the parameter must have a value
|
|
|
|
|
AVAILABLE_SCRIPTS = {
|
2026-07-09 15:29:01 -06:00
|
|
|
"help": {
|
|
|
|
|
"name": "help",
|
|
|
|
|
"display_name": "System Diagnostics",
|
|
|
|
|
"description": "Runs help.sh which checks WROLPi services, certificates, database, and dependencies."
|
|
|
|
|
" Read-only; changes nothing.",
|
|
|
|
|
"service_name": "wrolpi-help-script.service",
|
|
|
|
|
"warnings": [],
|
|
|
|
|
},
|
2026-02-25 15:32:43 -07:00
|
|
|
"repair": {
|
|
|
|
|
"name": "repair",
|
|
|
|
|
"display_name": "Repair WROLPi",
|
|
|
|
|
"description": "Repairs WROLPi installation by resetting configs and restarting services.",
|
|
|
|
|
"service_name": "wrolpi-repair.service",
|
|
|
|
|
"warnings": [
|
|
|
|
|
"Resets git repository (discards any local code changes)",
|
|
|
|
|
"Stops ALL WROLPi services temporarily",
|
|
|
|
|
"May restore databases from backup blobs",
|
|
|
|
|
"Generates new SSL certificates",
|
|
|
|
|
"Takes several minutes to complete",
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
"upgrade": {
|
|
|
|
|
"name": "upgrade",
|
|
|
|
|
"display_name": "Upgrade WROLPi",
|
|
|
|
|
"description": "Upgrades WROLPi to the latest version from the specified branch.",
|
|
|
|
|
"service_name": "wrolpi-upgrade.service",
|
|
|
|
|
"env_file": "/tmp/wrolpi-upgrade.env",
|
|
|
|
|
"parameters": [
|
|
|
|
|
{"name": "branch", "label": "Branch", "type": "branch", "required": False},
|
|
|
|
|
],
|
|
|
|
|
"warnings": [
|
|
|
|
|
"Downloads updates from the internet",
|
|
|
|
|
"Restarts ALL WROLPi services",
|
|
|
|
|
"May take several minutes depending on connection speed",
|
|
|
|
|
"UI will be unavailable during upgrade",
|
|
|
|
|
],
|
|
|
|
|
},
|
2026-03-05 17:56:15 -07:00
|
|
|
"fix-permissions": {
|
|
|
|
|
"name": "fix-permissions",
|
|
|
|
|
"display_name": "Fix Media Permissions",
|
|
|
|
|
"description": "Fixes ownership and permissions on the media directory so WROLPi can read and write all files.",
|
|
|
|
|
"service_name": "wrolpi-fix-media-permissions.service",
|
|
|
|
|
"warnings": [
|
|
|
|
|
"Changes ownership of all media files to wrolpi:wrolpi",
|
|
|
|
|
"Ensures all files are readable and directories are traversable",
|
|
|
|
|
"May take a long time on large media libraries",
|
|
|
|
|
"Some filesystems (FAT/exFAT) do not support Unix permissions",
|
|
|
|
|
],
|
|
|
|
|
},
|
2026-02-25 15:32:43 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_current_branch() -> Optional[str]:
|
|
|
|
|
"""
|
|
|
|
|
Get the current git branch of /opt/wrolpi.
|
|
|
|
|
|
|
|
|
|
Returns:
|
2026-07-29 15:59:11 -06:00
|
|
|
Branch name ('release' on a detached HEAD), or None if unable to determine
|
2026-02-25 15:32:43 -07:00
|
|
|
"""
|
|
|
|
|
try:
|
2026-07-29 15:59:11 -06:00
|
|
|
# Not `rev-parse --abbrev-ref HEAD`: it reports "heads/release" when a stale
|
|
|
|
|
# `release` tag exists alongside the branch, breaking origin/{branch} lookups.
|
2026-02-25 15:32:43 -07:00
|
|
|
result = subprocess.run(
|
2026-07-29 15:59:11 -06:00
|
|
|
["git", "-C", "/opt/wrolpi", "branch", "--show-current"],
|
2026-02-25 15:32:43 -07:00
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=5,
|
|
|
|
|
)
|
|
|
|
|
if result.returncode == 0:
|
2026-07-29 15:59:11 -06:00
|
|
|
# A detached HEAD prints nothing; upgrades come from `release` by default.
|
|
|
|
|
return result.stdout.strip() or "release"
|
2026-02-25 15:32:43 -07:00
|
|
|
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
|
|
|
|
|
pass
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def list_available_scripts() -> list[dict]:
|
|
|
|
|
"""
|
|
|
|
|
List all available scripts with their info.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
List of script info dicts suitable for API response
|
|
|
|
|
"""
|
|
|
|
|
scripts = []
|
|
|
|
|
available = not is_docker_mode()
|
|
|
|
|
|
|
|
|
|
for name, info in AVAILABLE_SCRIPTS.items():
|
|
|
|
|
scripts.append({
|
|
|
|
|
"name": info["name"],
|
|
|
|
|
"display_name": info["display_name"],
|
|
|
|
|
"description": info["description"],
|
|
|
|
|
"warnings": info["warnings"],
|
|
|
|
|
"available": available,
|
|
|
|
|
"parameters": info.get("parameters", []),
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return scripts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_script_status() -> dict:
|
|
|
|
|
"""
|
|
|
|
|
Check if any script service is currently running.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
dict with:
|
|
|
|
|
running: bool - Whether a script is running
|
|
|
|
|
script_name: Optional[str] - Name of running script
|
|
|
|
|
service_name: Optional[str] - Systemd service name
|
|
|
|
|
started_at: Optional[str] - ISO timestamp when started
|
|
|
|
|
elapsed_seconds: Optional[int] - Seconds since start
|
|
|
|
|
"""
|
|
|
|
|
if is_docker_mode():
|
|
|
|
|
return {"running": False}
|
|
|
|
|
|
|
|
|
|
for name, info in AVAILABLE_SCRIPTS.items():
|
|
|
|
|
service = info["service_name"]
|
|
|
|
|
try:
|
|
|
|
|
# Check if service is active (running)
|
|
|
|
|
result = subprocess.run(
|
|
|
|
|
["systemctl", "is-active", service],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=5,
|
|
|
|
|
)
|
|
|
|
|
status = result.stdout.strip()
|
|
|
|
|
|
|
|
|
|
if status == "activating":
|
|
|
|
|
# Service is running - get start time
|
|
|
|
|
started_at, elapsed = _get_service_timing(service)
|
|
|
|
|
return {
|
|
|
|
|
"running": True,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
"service_name": service,
|
|
|
|
|
"started_at": started_at,
|
|
|
|
|
"elapsed_seconds": elapsed,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
return {"running": False}
|
|
|
|
|
|
|
|
|
|
|
A failed upgrade is shown on the upgrade page instead of redirecting home (#955)
* A failed upgrade is shown on the upgrade page instead of redirecting home
A failed upgrade restarts the services it stopped, so the upgrade page saw
them come back and redirected home as if the upgrade had worked. The
Controller now reports how the last run of a script ended
(GET /api/scripts/{name}/result, from systemd's Result and exit status),
and the upgrade page reads it before redirecting. A failure turns the
banner red, gives the exit code, opens the output, and offers a link back.
Only a run the page has seen start counts, because the result of an
earlier run is still reported until the new run begins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* An upgrade's result survives the daemon-reload it does
The upgrade reinstalls its unit and reloads systemd, which clears the run's
timestamps but keeps Result and the exit status. A failure is now known
from those alone, and the result reports whether the script is running, so
the upgrade page waits on that instead of on a timestamp that may never come.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:11:41 -07:00
|
|
|
def get_script_result(name: str) -> Optional[dict]:
|
|
|
|
|
"""
|
|
|
|
|
Report how the last run of a script ended, so a page waiting on it can tell success from failure.
|
|
|
|
|
|
|
|
|
|
A failed upgrade restarts the services it stopped, so the services coming back up does not mean it succeeded.
|
|
|
|
|
|
|
|
|
|
systemd keeps Result and the exit status across the daemon-reload an upgrade does, but not the run's
|
2026-11-08 11:25:26 -07:00
|
|
|
timestamps, so when the exit timestamp is missing the journal's record of the run's end is used instead.
|
A failed upgrade is shown on the upgrade page instead of redirecting home (#955)
* A failed upgrade is shown on the upgrade page instead of redirecting home
A failed upgrade restarts the services it stopped, so the upgrade page saw
them come back and redirected home as if the upgrade had worked. The
Controller now reports how the last run of a script ended
(GET /api/scripts/{name}/result, from systemd's Result and exit status),
and the upgrade page reads it before redirecting. A failure turns the
banner red, gives the exit code, opens the output, and offers a link back.
Only a run the page has seen start counts, because the result of an
earlier run is still reported until the new run begins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* An upgrade's result survives the daemon-reload it does
The upgrade reinstalls its unit and reloads systemd, which clears the run's
timestamps but keeps Result and the exit status. A failure is now known
from those alone, and the result reports whether the script is running, so
the upgrade page waits on that instead of on a timestamp that may never come.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:11:41 -07:00
|
|
|
|
|
|
|
|
Returns None for an unknown script, otherwise a dict with:
|
|
|
|
|
script_name: str
|
|
|
|
|
running: bool - Whether the script is running now
|
|
|
|
|
finished: bool - Whether a run is known to have ended (False while running, or if it never ran)
|
|
|
|
|
success: Optional[bool] - Whether the last run exited cleanly; None unless finished
|
|
|
|
|
result: Optional[str] - systemd's Result (e.g. "success", "exit-code")
|
|
|
|
|
exit_status: Optional[int] - The script's exit status
|
|
|
|
|
finished_at: Optional[str] - ISO timestamp when the last run ended
|
|
|
|
|
"""
|
|
|
|
|
if name not in AVAILABLE_SCRIPTS:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
result = {
|
|
|
|
|
"script_name": name,
|
|
|
|
|
"running": False,
|
|
|
|
|
"finished": False,
|
|
|
|
|
"success": None,
|
|
|
|
|
"result": None,
|
|
|
|
|
"exit_status": None,
|
|
|
|
|
"finished_at": None,
|
|
|
|
|
}
|
|
|
|
|
if is_docker_mode():
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
service = AVAILABLE_SCRIPTS[name]["service_name"]
|
|
|
|
|
try:
|
|
|
|
|
# A Unix timestamp, because systemd prints dates in the local timezone.
|
|
|
|
|
proc = subprocess.run(
|
|
|
|
|
["systemctl", "show", service, "--property=Result,ExecMainStatus,ActiveState,ExecMainExitTimestamp",
|
|
|
|
|
"--timestamp=unix"],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=5,
|
|
|
|
|
)
|
|
|
|
|
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
|
|
|
|
|
return result
|
|
|
|
|
if proc.returncode != 0:
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
properties = dict(line.partition("=")[::2] for line in proc.stdout.splitlines() if "=" in line)
|
|
|
|
|
if properties.get("ActiveState") in ("activating", "active", "reloading"):
|
|
|
|
|
result["running"] = True
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
result["exit_status"] = int(properties.get("ExecMainStatus", ""))
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
result["result"] = properties.get("Result") or None
|
|
|
|
|
failed = result["result"] not in (None, "success") or result["exit_status"] not in (0, None)
|
|
|
|
|
|
|
|
|
|
exit_timestamp = properties.get("ExecMainExitTimestamp", "").lstrip("@")
|
|
|
|
|
if exit_timestamp:
|
|
|
|
|
try:
|
|
|
|
|
result["finished_at"] = datetime.fromtimestamp(float(exit_timestamp), timezone.utc).isoformat()
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
|
2026-11-08 11:25:26 -07:00
|
|
|
if not result["finished_at"]:
|
|
|
|
|
# A clean Result with no exit timestamp is also what a service that never ran reports, so ask the journal.
|
|
|
|
|
journal_outcome, result["finished_at"] = _get_last_journal_outcome(service)
|
|
|
|
|
failed = failed or journal_outcome is False
|
|
|
|
|
if journal_outcome is None and not failed:
|
|
|
|
|
return result
|
|
|
|
|
|
A failed upgrade is shown on the upgrade page instead of redirecting home (#955)
* A failed upgrade is shown on the upgrade page instead of redirecting home
A failed upgrade restarts the services it stopped, so the upgrade page saw
them come back and redirected home as if the upgrade had worked. The
Controller now reports how the last run of a script ended
(GET /api/scripts/{name}/result, from systemd's Result and exit status),
and the upgrade page reads it before redirecting. A failure turns the
banner red, gives the exit code, opens the output, and offers a link back.
Only a run the page has seen start counts, because the result of an
earlier run is still reported until the new run begins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* An upgrade's result survives the daemon-reload it does
The upgrade reinstalls its unit and reloads systemd, which clears the run's
timestamps but keeps Result and the exit status. A failure is now known
from those alone, and the result reports whether the script is running, so
the upgrade page waits on that instead of on a timestamp that may never come.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 11:11:41 -07:00
|
|
|
if failed or result["finished_at"]:
|
|
|
|
|
result["finished"] = True
|
|
|
|
|
result["success"] = not failed
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
2026-11-08 11:25:26 -07:00
|
|
|
# systemd's journal message IDs for a unit that ended cleanly, or failed.
|
|
|
|
|
UNIT_SUCCESS_MESSAGE_ID = "7ad2d189f7e94e70a38c781354912448"
|
|
|
|
|
UNIT_FAILURE_MESSAGE_ID = "d9b373ed55a64feb8242e02dbe79a49c"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_last_journal_outcome(service: str) -> tuple[Optional[bool], Optional[str]]:
|
|
|
|
|
"""
|
|
|
|
|
Read how the service's last run ended from the journal, which keeps it across a daemon-reload.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
Tuple of (whether it succeeded, ISO timestamp when it ended); (None, None) if the journal has no record.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
proc = subprocess.run(
|
|
|
|
|
["journalctl", "--no-pager", "-n", "1", "-o", "json", "--output-fields=MESSAGE_ID",
|
|
|
|
|
f"UNIT={service}", f"MESSAGE_ID={UNIT_SUCCESS_MESSAGE_ID}", "+",
|
|
|
|
|
f"UNIT={service}", f"MESSAGE_ID={UNIT_FAILURE_MESSAGE_ID}"],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=5,
|
|
|
|
|
)
|
|
|
|
|
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
|
|
|
|
|
return None, None
|
|
|
|
|
if proc.returncode != 0 or not proc.stdout.strip():
|
|
|
|
|
return None, None
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
entry = json.loads(proc.stdout.strip().splitlines()[-1])
|
|
|
|
|
ended_at = datetime.fromtimestamp(int(entry["__REALTIME_TIMESTAMP"]) / 1_000_000, timezone.utc)
|
|
|
|
|
except (ValueError, KeyError, TypeError):
|
|
|
|
|
return None, None
|
|
|
|
|
return entry.get("MESSAGE_ID") == UNIT_SUCCESS_MESSAGE_ID, ended_at.isoformat()
|
|
|
|
|
|
|
|
|
|
|
2026-02-25 15:32:43 -07:00
|
|
|
def _get_service_timing(service: str) -> tuple[Optional[str], Optional[int]]:
|
|
|
|
|
"""
|
|
|
|
|
Get timing info for a running service.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
Tuple of (started_at ISO string, elapsed_seconds)
|
|
|
|
|
"""
|
|
|
|
|
try:
|
2026-10-11 18:29:42 -06:00
|
|
|
# A Unix timestamp, because systemd prints dates in the local timezone.
|
2026-02-25 15:32:43 -07:00
|
|
|
result = subprocess.run(
|
2026-10-11 18:29:42 -06:00
|
|
|
["systemctl", "show", service, "--property=ExecMainStartTimestamp", "--timestamp=unix"],
|
2026-02-25 15:32:43 -07:00
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=5,
|
|
|
|
|
)
|
|
|
|
|
if result.returncode == 0:
|
2026-10-11 18:29:42 -06:00
|
|
|
# Format: ExecMainStartTimestamp=@1760226500.123456
|
|
|
|
|
value = result.stdout.strip().partition("=")[2].lstrip("@")
|
|
|
|
|
if value:
|
|
|
|
|
try:
|
|
|
|
|
started = float(value)
|
|
|
|
|
except ValueError:
|
|
|
|
|
pass
|
|
|
|
|
else:
|
|
|
|
|
elapsed = int(time.time() - started)
|
|
|
|
|
return datetime.fromtimestamp(started, timezone.utc).isoformat(), max(0, elapsed)
|
2026-02-25 15:32:43 -07:00
|
|
|
except (subprocess.TimeoutExpired, subprocess.SubprocessError, FileNotFoundError):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
return None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def start_script(name: str, params: Optional[dict] = None) -> dict:
|
|
|
|
|
"""
|
|
|
|
|
Start a script by starting its systemd service.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
name: Script name (key in AVAILABLE_SCRIPTS)
|
|
|
|
|
params: Optional dict of parameter values (e.g., {"branch": "release"})
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
dict with:
|
|
|
|
|
success: bool
|
|
|
|
|
message: Optional[str]
|
|
|
|
|
error: Optional[str]
|
|
|
|
|
"""
|
|
|
|
|
if is_docker_mode():
|
|
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": "Scripts are not available in Docker mode",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if name not in AVAILABLE_SCRIPTS:
|
|
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": f"Unknown script: {name}",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Check if already running
|
|
|
|
|
status = get_script_status()
|
|
|
|
|
if status.get("running"):
|
|
|
|
|
if status.get("script_name") == name:
|
|
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": f"Script '{name}' is already running",
|
|
|
|
|
}
|
|
|
|
|
else:
|
|
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": f"Another script is already running: {status.get('script_name')}",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
script_config = AVAILABLE_SCRIPTS[name]
|
|
|
|
|
service = script_config["service_name"]
|
2026-10-27 15:35:12 -06:00
|
|
|
parameters = script_config.get("parameters", [])
|
2026-02-25 15:32:43 -07:00
|
|
|
|
2026-10-27 15:35:12 -06:00
|
|
|
# A misspelled parameter would otherwise be dropped, and the script run with its default.
|
|
|
|
|
unknown = sorted(set(params or {}) - {i["name"] for i in parameters})
|
|
|
|
|
if unknown:
|
|
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": f"Unknown parameters for script '{name}': {', '.join(unknown)}",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Always write the env file: the service cannot start without it, and a file left by an interrupted run must
|
|
|
|
|
# not choose the parameters.
|
2026-02-25 15:32:43 -07:00
|
|
|
env_file = script_config.get("env_file")
|
2026-10-27 15:35:12 -06:00
|
|
|
if env_file:
|
|
|
|
|
values = {key: value for key, value in (params or {}).items() if value}
|
2026-11-08 08:48:58 -07:00
|
|
|
for parameter in parameters:
|
|
|
|
|
value = values.get(parameter["name"])
|
|
|
|
|
if value is None:
|
|
|
|
|
continue
|
|
|
|
|
# Each value is one line of the env file.
|
|
|
|
|
if parameter["type"] == "branch" and not is_valid_branch(value):
|
|
|
|
|
return {"success": False, "error": f"Invalid branch name: {value!r}"}
|
|
|
|
|
if "\n" in str(value) or "\r" in str(value):
|
|
|
|
|
return {"success": False, "error": f"Invalid {parameter['label']}: must be a single line"}
|
2026-10-27 15:35:12 -06:00
|
|
|
for parameter in parameters:
|
|
|
|
|
if parameter["type"] == "branch" and not values.get(parameter["name"]):
|
|
|
|
|
# upgrade.sh upgrades the current branch when it is not given one.
|
|
|
|
|
values[parameter["name"]] = get_current_branch() or "release"
|
2026-02-25 15:32:43 -07:00
|
|
|
try:
|
|
|
|
|
with open(env_file, "w") as f:
|
2026-10-27 15:35:12 -06:00
|
|
|
for key, value in values.items():
|
|
|
|
|
# Convert param name to uppercase for env var
|
|
|
|
|
f.write(f"{key.upper()}={value}\n")
|
2026-02-25 15:32:43 -07:00
|
|
|
except OSError as e:
|
|
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": f"Failed to write script config: {e}",
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-14 10:03:11 -06:00
|
|
|
logger.info("Starting script '%s' (service: %s)", name, service)
|
2026-02-25 15:32:43 -07:00
|
|
|
try:
|
|
|
|
|
# Start the service (non-blocking via Popen)
|
|
|
|
|
# No sudo needed - Controller runs as root
|
|
|
|
|
subprocess.Popen(
|
|
|
|
|
["systemctl", "start", service],
|
|
|
|
|
stdout=subprocess.DEVNULL,
|
|
|
|
|
stderr=subprocess.DEVNULL,
|
|
|
|
|
stdin=subprocess.DEVNULL,
|
|
|
|
|
)
|
2026-03-14 10:03:11 -06:00
|
|
|
logger.info("Script '%s' started successfully", name)
|
2026-02-25 15:32:43 -07:00
|
|
|
return {
|
|
|
|
|
"success": True,
|
|
|
|
|
"message": f"Script '{name}' started",
|
|
|
|
|
}
|
|
|
|
|
except FileNotFoundError:
|
2026-03-14 10:03:11 -06:00
|
|
|
logger.warning("systemctl not found, cannot start script '%s'", name)
|
2026-02-25 15:32:43 -07:00
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": "systemctl not found",
|
|
|
|
|
}
|
|
|
|
|
except subprocess.SubprocessError as e:
|
2026-03-14 10:03:11 -06:00
|
|
|
logger.warning("Failed to start script '%s': %s", name, e)
|
2026-02-25 15:32:43 -07:00
|
|
|
return {
|
|
|
|
|
"success": False,
|
|
|
|
|
"error": str(e),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_script_output(name: str, lines: int = 100) -> dict:
|
|
|
|
|
"""
|
|
|
|
|
Get output from a script's systemd service via journalctl.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
name: Script name
|
|
|
|
|
lines: Number of lines to retrieve (default 100)
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
dict with:
|
|
|
|
|
output: str - Log output
|
|
|
|
|
lines: int - Lines requested
|
|
|
|
|
script_name: str - Script name
|
|
|
|
|
"""
|
|
|
|
|
if is_docker_mode():
|
|
|
|
|
return {
|
|
|
|
|
"output": "Scripts are not available in Docker mode",
|
|
|
|
|
"lines": 0,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if name not in AVAILABLE_SCRIPTS:
|
|
|
|
|
return {
|
|
|
|
|
"output": f"Unknown script: {name}",
|
|
|
|
|
"lines": 0,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
service = AVAILABLE_SCRIPTS[name]["service_name"]
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
result = subprocess.run(
|
|
|
|
|
["journalctl", "-u", service, "-n", str(lines), "--no-pager"],
|
|
|
|
|
capture_output=True,
|
|
|
|
|
text=True,
|
|
|
|
|
timeout=10,
|
|
|
|
|
)
|
|
|
|
|
return {
|
|
|
|
|
"output": result.stdout,
|
|
|
|
|
"lines": lines,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
}
|
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
|
return {
|
|
|
|
|
"output": "Timeout fetching logs",
|
|
|
|
|
"lines": 0,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
}
|
|
|
|
|
except FileNotFoundError:
|
|
|
|
|
return {
|
|
|
|
|
"output": "journalctl not found",
|
|
|
|
|
"lines": 0,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
}
|
|
|
|
|
except subprocess.SubprocessError as e:
|
|
|
|
|
return {
|
|
|
|
|
"output": str(e),
|
|
|
|
|
"lines": 0,
|
|
|
|
|
"script_name": name,
|
|
|
|
|
}
|