mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-25 01:16:18 -05:00
Creating Controller service which will control WROLPi services, admin, SMART, disks, and status. nginx will fallback to Controller UI when React UI is unavailable (such as during upgrades).
This commit is contained in:
parent
344fe9035f
commit
b9158b60fe
66 changed files with 9920 additions and 327 deletions
1
controller/lib/__init__.py
Normal file
1
controller/lib/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
"""Controller library modules."""
|
||||
480
controller/lib/admin.py
Normal file
480
controller/lib/admin.py
Normal file
|
|
@ -0,0 +1,480 @@
|
|||
"""
|
||||
Admin operations for WROLPi Controller.
|
||||
|
||||
Migrated from wrolpi/admin.py - provides system control functions.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import enum
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from controller.lib.config import get_config, is_docker_mode
|
||||
|
||||
|
||||
class HotspotStatus(enum.Enum):
|
||||
"""Hotspot status enum matching wrolpi/admin.py"""
|
||||
disconnected = enum.auto() # Radio is on, but Hotspot is not connected.
|
||||
unavailable = enum.auto() # Radio is off.
|
||||
connected = enum.auto() # Radio is on, Hotspot is on.
|
||||
unknown = enum.auto() # Unknown status. Hotspot may not be supported.
|
||||
in_use = enum.auto() # Wi-Fi device is in use for a network connection.
|
||||
|
||||
|
||||
class GovernorStatus(enum.Enum):
|
||||
"""CPU governor status enum matching wrolpi/admin.py"""
|
||||
ondemand = enum.auto()
|
||||
powersave = enum.auto()
|
||||
unknown = enum.auto()
|
||||
|
||||
|
||||
def get_current_ssid(interface: str = 'wlan0') -> str | None:
|
||||
"""
|
||||
Returns the name of the SSID that is currently connected.
|
||||
Returns None if Hotspot is active, or no Wi-Fi network is being used.
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['iwgetid', interface, '--raw'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
ssid = result.stdout.strip()
|
||||
return ssid if ssid else None
|
||||
elif result.returncode == 255:
|
||||
# Hotspot is in use
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
|
||||
return None
|
||||
|
||||
|
||||
def get_hotspot_status() -> HotspotStatus:
|
||||
"""
|
||||
Get current hotspot status matching wrolpi/admin.py logic.
|
||||
|
||||
Returns:
|
||||
HotspotStatus enum value
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return HotspotStatus.unknown
|
||||
|
||||
config = get_config()
|
||||
hotspot_config = config.get("hotspot", {})
|
||||
device = hotspot_config.get("device", "wlan0")
|
||||
|
||||
# Check if device is connected to a Wi-Fi network (not hotspot)
|
||||
if get_current_ssid(device):
|
||||
return HotspotStatus.in_use
|
||||
|
||||
# Check nmcli status
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["nmcli"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return HotspotStatus.unknown
|
||||
|
||||
output = result.stdout.strip()
|
||||
for line in output.splitlines():
|
||||
if line.startswith(f'{device}: connected'):
|
||||
return HotspotStatus.connected
|
||||
elif line.startswith(f'{device}: disconnected'):
|
||||
return HotspotStatus.disconnected
|
||||
elif line.startswith(f'{device}: unavailable'):
|
||||
return HotspotStatus.unavailable
|
||||
|
||||
return HotspotStatus.unknown
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return HotspotStatus.unknown
|
||||
except FileNotFoundError:
|
||||
return HotspotStatus.unknown
|
||||
except subprocess.SubprocessError:
|
||||
return HotspotStatus.unknown
|
||||
|
||||
|
||||
def get_hotspot_status_dict() -> dict:
|
||||
"""
|
||||
Get hotspot status as a dict for API responses.
|
||||
|
||||
Returns dict matching HotspotStatusResponse schema:
|
||||
enabled: bool - Whether hotspot is currently enabled
|
||||
available: bool - Whether hotspot functionality is available
|
||||
reason: Optional[str] - Reason if unavailable
|
||||
ssid: Optional[str] - Hotspot SSID when enabled
|
||||
device: Optional[str] - WiFi device name
|
||||
"""
|
||||
config = get_config()
|
||||
hotspot_config = config.get("hotspot", {})
|
||||
device = hotspot_config.get("device", "wlan0")
|
||||
status = get_hotspot_status()
|
||||
|
||||
# Map enum status to enabled/available flags
|
||||
enabled = status == HotspotStatus.connected
|
||||
available = status not in (HotspotStatus.unknown, HotspotStatus.unavailable)
|
||||
|
||||
reason = None
|
||||
if status == HotspotStatus.unknown:
|
||||
reason = "Hotspot not supported or nmcli unavailable"
|
||||
elif status == HotspotStatus.unavailable:
|
||||
reason = "WiFi radio is off"
|
||||
elif status == HotspotStatus.in_use:
|
||||
reason = "WiFi device is connected to a network"
|
||||
|
||||
return {
|
||||
"enabled": enabled,
|
||||
"available": available,
|
||||
"reason": reason,
|
||||
"ssid": hotspot_config.get("ssid", "WROLPi") if enabled else None,
|
||||
"device": device,
|
||||
}
|
||||
|
||||
|
||||
def enable_hotspot() -> dict:
|
||||
"""
|
||||
Enable the WiFi hotspot.
|
||||
|
||||
Returns:
|
||||
dict with success status and message
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
config = get_config()
|
||||
hotspot_config = config.get("hotspot", {})
|
||||
|
||||
device = hotspot_config.get("device", "wlan0")
|
||||
ssid = hotspot_config.get("ssid", "WROLPi")
|
||||
password = hotspot_config.get("password", "wrolpi hotspot")
|
||||
|
||||
try:
|
||||
# First ensure radio is on
|
||||
subprocess.run(
|
||||
["nmcli", "radio", "wifi", "on"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
# Create hotspot using NetworkManager
|
||||
result = subprocess.run(
|
||||
[
|
||||
"nmcli", "device", "wifi", "hotspot",
|
||||
"ifname", device,
|
||||
"ssid", ssid,
|
||||
"password", password,
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "ssid": ssid, "device": device}
|
||||
else:
|
||||
return {"success": False, "error": result.stderr.strip() or "Unknown error"}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Timeout enabling hotspot"}
|
||||
except FileNotFoundError:
|
||||
return {"success": False, "error": "nmcli not found"}
|
||||
except subprocess.SubprocessError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def disable_hotspot() -> dict:
|
||||
"""
|
||||
Disable the WiFi hotspot.
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
try:
|
||||
# Turn off the radio to disconnect hotspot
|
||||
result = subprocess.run(
|
||||
["nmcli", "radio", "wifi", "off"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
# Success even if already off
|
||||
return {"success": True}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Timeout disabling hotspot"}
|
||||
except FileNotFoundError:
|
||||
return {"success": False, "error": "nmcli not found"}
|
||||
except subprocess.SubprocessError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
GOVERNOR_MAP = {
|
||||
'ondemand': GovernorStatus.ondemand,
|
||||
'powersave': GovernorStatus.powersave,
|
||||
}
|
||||
|
||||
|
||||
def get_throttle_status() -> GovernorStatus:
|
||||
"""
|
||||
Get CPU throttle (governor) status matching wrolpi/admin.py logic.
|
||||
|
||||
Returns:
|
||||
GovernorStatus enum value
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return GovernorStatus.unknown
|
||||
|
||||
governor_path = Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")
|
||||
|
||||
if not governor_path.exists():
|
||||
return GovernorStatus.unknown
|
||||
|
||||
try:
|
||||
current = governor_path.read_text().strip()
|
||||
return GOVERNOR_MAP.get(current, GovernorStatus.unknown)
|
||||
except IOError:
|
||||
return GovernorStatus.unknown
|
||||
|
||||
|
||||
def get_throttle_status_dict() -> dict:
|
||||
"""
|
||||
Get throttle status as a dict for API responses.
|
||||
|
||||
Returns dict matching ThrottleStatusResponse schema:
|
||||
enabled: bool - Whether CPU throttle (powersave) is enabled
|
||||
available: bool - Whether throttle control is available
|
||||
reason: Optional[str] - Reason if unavailable
|
||||
governor: Optional[str] - Current CPU governor
|
||||
available_governors: Optional[list[str]] - Available governors
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {
|
||||
"enabled": False,
|
||||
"available": False,
|
||||
"reason": "Docker mode",
|
||||
"governor": None,
|
||||
"available_governors": None,
|
||||
}
|
||||
|
||||
governor_path = Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")
|
||||
available_path = Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors")
|
||||
|
||||
if not governor_path.exists():
|
||||
return {
|
||||
"enabled": False,
|
||||
"available": False,
|
||||
"reason": "cpufreq not available",
|
||||
"governor": None,
|
||||
"available_governors": None,
|
||||
}
|
||||
|
||||
try:
|
||||
current = governor_path.read_text().strip()
|
||||
available_governors = available_path.read_text().strip().split() if available_path.exists() else []
|
||||
|
||||
return {
|
||||
"enabled": current == "powersave",
|
||||
"available": True,
|
||||
"reason": None,
|
||||
"governor": current,
|
||||
"available_governors": available_governors,
|
||||
}
|
||||
except IOError as e:
|
||||
return {
|
||||
"enabled": False,
|
||||
"available": False,
|
||||
"reason": str(e),
|
||||
"governor": None,
|
||||
"available_governors": None,
|
||||
}
|
||||
|
||||
|
||||
def enable_throttle() -> dict:
|
||||
"""
|
||||
Enable CPU throttle (set powersave governor).
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
try:
|
||||
# Try cpufreq-set first
|
||||
result = subprocess.run(
|
||||
["cpufreq-set", "-g", "powersave"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "governor": "powersave"}
|
||||
else:
|
||||
return {"success": False, "error": result.stderr.strip() or "Unknown error"}
|
||||
|
||||
except FileNotFoundError:
|
||||
# Try direct write to sysfs
|
||||
try:
|
||||
for cpu_path in Path("/sys/devices/system/cpu/").glob("cpu[0-9]*/cpufreq/scaling_governor"):
|
||||
cpu_path.write_text("powersave")
|
||||
return {"success": True, "governor": "powersave"}
|
||||
except IOError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Timeout enabling throttle"}
|
||||
except subprocess.SubprocessError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def disable_throttle() -> dict:
|
||||
"""
|
||||
Disable CPU throttle (set ondemand or performance governor).
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
config = get_config()
|
||||
default_governor = config.get("throttle", {}).get("default_governor", "ondemand")
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["cpufreq-set", "-g", default_governor],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "governor": default_governor}
|
||||
else:
|
||||
return {"success": False, "error": result.stderr.strip() or "Unknown error"}
|
||||
|
||||
except FileNotFoundError:
|
||||
# Try direct write to sysfs
|
||||
try:
|
||||
for cpu_path in Path("/sys/devices/system/cpu/").glob("cpu[0-9]*/cpufreq/scaling_governor"):
|
||||
cpu_path.write_text(default_governor)
|
||||
return {"success": True, "governor": default_governor}
|
||||
except IOError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Timeout disabling throttle"}
|
||||
except subprocess.SubprocessError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def shutdown_system() -> dict:
|
||||
"""
|
||||
Shut down the system.
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Cannot shutdown from Docker container"}
|
||||
|
||||
try:
|
||||
subprocess.Popen(["shutdown", "-h", "now"])
|
||||
return {"success": True, "message": "System shutting down"}
|
||||
except FileNotFoundError:
|
||||
return {"success": False, "error": "shutdown command not found"}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def reboot_system() -> dict:
|
||||
"""
|
||||
Reboot the system.
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Cannot reboot from Docker container"}
|
||||
|
||||
try:
|
||||
subprocess.Popen(["reboot"])
|
||||
return {"success": True, "message": "System rebooting"}
|
||||
except FileNotFoundError:
|
||||
return {"success": False, "error": "reboot command not found"}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
async def restart_all_services() -> dict:
|
||||
"""
|
||||
Restart all WROLPi services including Controller itself.
|
||||
|
||||
Controller restarts itself LAST so it can report success for other services.
|
||||
|
||||
Returns:
|
||||
dict with results for each service
|
||||
"""
|
||||
if is_docker_mode():
|
||||
# In Docker mode, we can't use systemctl
|
||||
return {
|
||||
"success": False,
|
||||
"error": "Service restart via systemctl not available in Docker mode",
|
||||
}
|
||||
|
||||
services_to_restart = [
|
||||
"wrolpi-api",
|
||||
"wrolpi-app",
|
||||
"wrolpi-kiwix",
|
||||
"wrolpi-help",
|
||||
"renderd",
|
||||
"apache2",
|
||||
# Controller restarts itself last (scheduled after response)
|
||||
]
|
||||
|
||||
results = {}
|
||||
|
||||
for service in services_to_restart:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["systemctl", "restart", service],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
results[service] = {
|
||||
"success": result.returncode == 0,
|
||||
"error": result.stderr.strip() if result.returncode != 0 else None,
|
||||
}
|
||||
except subprocess.TimeoutExpired:
|
||||
results[service] = {"success": False, "error": "Timeout"}
|
||||
except FileNotFoundError:
|
||||
results[service] = {"success": False, "error": "systemctl not found"}
|
||||
except Exception as e:
|
||||
results[service] = {"success": False, "error": str(e)}
|
||||
|
||||
# Schedule Controller self-restart after response is sent
|
||||
loop = asyncio.get_event_loop()
|
||||
loop.call_later(1.0, _restart_self)
|
||||
|
||||
results["wrolpi-controller"] = {"success": True, "pending": True}
|
||||
return {"success": True, "services": results}
|
||||
|
||||
|
||||
def _restart_self():
|
||||
"""Restart the Controller service. Called after response is sent."""
|
||||
try:
|
||||
subprocess.Popen(["systemctl", "restart", "wrolpi-controller"])
|
||||
except Exception:
|
||||
# If we can't restart ourselves, not much we can do
|
||||
pass
|
||||
163
controller/lib/config.py
Normal file
163
controller/lib/config.py
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
"""
|
||||
Configuration management for the Controller.
|
||||
|
||||
Controller uses code-defined defaults and optionally loads overrides
|
||||
from controller.yaml on the WROLPi drive after it's mounted.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
from controller.defaults import DEFAULT_CONFIG
|
||||
|
||||
# Path to config file on the WROLPi drive
|
||||
CONFIG_PATH_ON_DRIVE = Path("/media/wrolpi/config/controller.yaml")
|
||||
|
||||
# Runtime config - starts as defaults, updated after drive mount
|
||||
_runtime_config: dict = copy.deepcopy(DEFAULT_CONFIG)
|
||||
|
||||
|
||||
def get_config() -> dict:
|
||||
"""Get the current runtime configuration."""
|
||||
return _runtime_config
|
||||
|
||||
|
||||
def get_config_value(key: str, default: Any = None) -> Any:
|
||||
"""Get a specific config value by dot-notation key (e.g., 'drives.auto_mount')."""
|
||||
keys = key.split(".")
|
||||
value = _runtime_config
|
||||
for k in keys:
|
||||
if isinstance(value, dict) and k in value:
|
||||
value = value[k]
|
||||
else:
|
||||
return default
|
||||
return value
|
||||
|
||||
|
||||
def is_docker_mode() -> bool:
|
||||
"""Check if running in Docker container."""
|
||||
return os.environ.get("DOCKERIZED", "").lower() == "true"
|
||||
|
||||
|
||||
# Raspberry Pi detection
|
||||
RPI_DEVICE_PATH = Path('/proc/device-tree/model')
|
||||
_RPI_DEVICE_MODEL_CONTENTS = RPI_DEVICE_PATH.read_text() if RPI_DEVICE_PATH.is_file() else None
|
||||
|
||||
|
||||
def is_rpi4() -> bool:
|
||||
"""Check if running on Raspberry Pi 4."""
|
||||
return 'Raspberry Pi 4' in _RPI_DEVICE_MODEL_CONTENTS if _RPI_DEVICE_MODEL_CONTENTS else False
|
||||
|
||||
|
||||
def is_rpi5() -> bool:
|
||||
"""Check if running on Raspberry Pi 5."""
|
||||
return 'Raspberry Pi 5' in _RPI_DEVICE_MODEL_CONTENTS if _RPI_DEVICE_MODEL_CONTENTS else False
|
||||
|
||||
|
||||
def is_rpi() -> bool:
|
||||
"""Check if running on any Raspberry Pi."""
|
||||
return is_rpi4() or is_rpi5()
|
||||
|
||||
|
||||
def get_media_directory() -> Path:
|
||||
"""Get the media directory path."""
|
||||
return Path(os.environ.get("MEDIA_DIRECTORY", "/media/wrolpi"))
|
||||
|
||||
|
||||
def is_primary_drive_mounted() -> bool:
|
||||
"""Check if the primary WROLPi drive is mounted."""
|
||||
return Path("/media/wrolpi/config").exists()
|
||||
|
||||
|
||||
def reload_config_from_drive() -> bool:
|
||||
"""
|
||||
Load config from the mounted WROLPi drive and merge with defaults.
|
||||
Called after the primary drive is mounted.
|
||||
|
||||
Returns True if config was loaded, False if no config file found.
|
||||
"""
|
||||
global _runtime_config
|
||||
|
||||
if not CONFIG_PATH_ON_DRIVE.exists():
|
||||
# No config file on drive - keep defaults
|
||||
return False
|
||||
|
||||
try:
|
||||
with open(CONFIG_PATH_ON_DRIVE) as f:
|
||||
drive_config = yaml.safe_load(f) or {}
|
||||
except (IOError, yaml.YAMLError) as e:
|
||||
# Failed to load - keep defaults
|
||||
print(f"Warning: Failed to load controller.yaml: {e}")
|
||||
return False
|
||||
|
||||
# Deep merge: drive_config overrides defaults
|
||||
_runtime_config = _deep_merge(copy.deepcopy(DEFAULT_CONFIG), drive_config)
|
||||
return True
|
||||
|
||||
|
||||
def save_config() -> None:
|
||||
"""
|
||||
Save current runtime config to the WROLPi drive.
|
||||
Only saves the diff from defaults to keep the file clean.
|
||||
"""
|
||||
if not is_primary_drive_mounted():
|
||||
raise RuntimeError("Cannot save config: primary drive not mounted")
|
||||
|
||||
# Calculate diff from defaults
|
||||
diff = _get_config_diff(_runtime_config, DEFAULT_CONFIG)
|
||||
|
||||
if not diff:
|
||||
# Nothing to save - config matches defaults
|
||||
return
|
||||
|
||||
CONFIG_PATH_ON_DRIVE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(CONFIG_PATH_ON_DRIVE, "w") as f:
|
||||
yaml.dump(diff, f, default_flow_style=False, sort_keys=False)
|
||||
|
||||
|
||||
def update_config(key: str, value: Any) -> None:
|
||||
"""
|
||||
Update a config value by dot-notation key.
|
||||
Does not automatically save - call save_config() after updates.
|
||||
"""
|
||||
keys = key.split(".")
|
||||
config = _runtime_config
|
||||
|
||||
# Navigate to parent of target key
|
||||
for k in keys[:-1]:
|
||||
if k not in config:
|
||||
config[k] = {}
|
||||
config = config[k]
|
||||
|
||||
# Set the value
|
||||
config[keys[-1]] = value
|
||||
|
||||
|
||||
def _deep_merge(base: dict, override: dict) -> dict:
|
||||
"""Deep merge two dicts. Override values take precedence."""
|
||||
result = base.copy()
|
||||
for key, value in override.items():
|
||||
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
||||
result[key] = _deep_merge(result[key], value)
|
||||
else:
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def _get_config_diff(current: dict, default: dict) -> dict:
|
||||
"""Get the difference between current config and defaults."""
|
||||
diff = {}
|
||||
for key, value in current.items():
|
||||
if key not in default:
|
||||
diff[key] = value
|
||||
elif isinstance(value, dict) and isinstance(default.get(key), dict):
|
||||
nested_diff = _get_config_diff(value, default[key])
|
||||
if nested_diff:
|
||||
diff[key] = nested_diff
|
||||
elif value != default.get(key):
|
||||
diff[key] = value
|
||||
return diff
|
||||
276
controller/lib/disks.py
Normal file
276
controller/lib/disks.py
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
"""
|
||||
Disk utilities for WROLPi Controller.
|
||||
|
||||
Provides disk detection, mounting, and WROLPi drive identification.
|
||||
"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from controller.lib.config import get_config, is_docker_mode
|
||||
|
||||
SUPPORTED_FILESYSTEMS = {"ext4", "btrfs", "vfat", "exfat"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class BlockDevice:
|
||||
"""Represents a block device/partition."""
|
||||
name: str
|
||||
path: str
|
||||
size: str
|
||||
fstype: Optional[str]
|
||||
mountpoint: Optional[str]
|
||||
label: Optional[str]
|
||||
uuid: Optional[str]
|
||||
model: Optional[str]
|
||||
is_wrolpi_drive: bool = False
|
||||
|
||||
|
||||
def get_block_devices() -> list[BlockDevice]:
|
||||
"""
|
||||
Get all block devices using lsblk.
|
||||
|
||||
Returns:
|
||||
list of BlockDevice objects
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return []
|
||||
|
||||
cmd = ["lsblk", "-J", "-o", "NAME,PATH,SIZE,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID,MODEL"]
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
|
||||
data = json.loads(result.stdout)
|
||||
devices = []
|
||||
|
||||
def process_device(dev: dict, parent_model: str = None):
|
||||
if dev.get("type") == "part" and dev.get("fstype") in SUPPORTED_FILESYSTEMS:
|
||||
devices.append(BlockDevice(
|
||||
name=dev["name"],
|
||||
path=dev.get("path", f"/dev/{dev['name']}"),
|
||||
size=dev.get("size", ""),
|
||||
fstype=dev.get("fstype"),
|
||||
mountpoint=dev.get("mountpoint"),
|
||||
label=dev.get("label"),
|
||||
uuid=dev.get("uuid"),
|
||||
model=parent_model,
|
||||
))
|
||||
# Process children (partitions)
|
||||
for child in dev.get("children", []):
|
||||
process_device(child, dev.get("model"))
|
||||
|
||||
for device in data.get("blockdevices", []):
|
||||
process_device(device)
|
||||
|
||||
return devices
|
||||
|
||||
except (subprocess.SubprocessError, json.JSONDecodeError):
|
||||
return []
|
||||
|
||||
|
||||
def get_uuid(device: str) -> Optional[str]:
|
||||
"""
|
||||
Get UUID for a device using blkid.
|
||||
|
||||
Args:
|
||||
device: Device path (e.g., /dev/sda1)
|
||||
|
||||
Returns:
|
||||
UUID string or None
|
||||
"""
|
||||
try:
|
||||
cmd = ["blkid", "-s", "UUID", "-o", "value", device]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=5)
|
||||
if result.returncode == 0:
|
||||
return result.stdout.strip()
|
||||
except subprocess.SubprocessError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def validate_mount_point(mount_point: str) -> None:
|
||||
"""
|
||||
Validate that mount point is safe.
|
||||
|
||||
Args:
|
||||
mount_point: Path to validate
|
||||
|
||||
Raises:
|
||||
ValueError: If mount point is not allowed
|
||||
"""
|
||||
import os
|
||||
|
||||
if not mount_point.startswith("/media"):
|
||||
raise ValueError(
|
||||
f"Mount point must be under /media, got: {mount_point}. "
|
||||
"Mounting to other locations is not allowed."
|
||||
)
|
||||
|
||||
# Prevent path traversal
|
||||
normalized = os.path.normpath(mount_point)
|
||||
if not normalized.startswith("/media"):
|
||||
raise ValueError(f"Invalid mount point after normalization: {normalized}")
|
||||
|
||||
|
||||
def mount_drive(
|
||||
device: str,
|
||||
mount_point: str,
|
||||
fstype: Optional[str] = None,
|
||||
options: str = "defaults",
|
||||
) -> dict:
|
||||
"""
|
||||
Mount a drive.
|
||||
|
||||
Args:
|
||||
device: Device path or UUID
|
||||
mount_point: Where to mount
|
||||
fstype: Filesystem type (auto-detected if not specified)
|
||||
options: Mount options
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
# Validate mount point
|
||||
try:
|
||||
validate_mount_point(mount_point)
|
||||
except ValueError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
# Create mount point if needed
|
||||
Path(mount_point).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Build mount command
|
||||
cmd = ["mount"]
|
||||
if fstype:
|
||||
cmd.extend(["-t", fstype])
|
||||
if options:
|
||||
cmd.extend(["-o", options])
|
||||
cmd.extend([device, mount_point])
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "mount_point": mount_point}
|
||||
else:
|
||||
return {"success": False, "error": result.stderr.strip()}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Mount timed out"}
|
||||
|
||||
|
||||
def unmount_drive(mount_point: str, lazy: bool = False) -> dict:
|
||||
"""
|
||||
Unmount a drive with safety checks.
|
||||
|
||||
Args:
|
||||
mount_point: Path to unmount
|
||||
lazy: Use lazy unmount if busy
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
if is_docker_mode():
|
||||
return {"success": False, "error": "Not available in Docker mode"}
|
||||
|
||||
# Safety rule: Don't unmount /media/wrolpi if no drives configured
|
||||
if mount_point == "/media/wrolpi":
|
||||
config = get_config()
|
||||
configured_mounts = config.get("drives", {}).get("mounts", [])
|
||||
|
||||
if not configured_mounts:
|
||||
return {
|
||||
"success": False,
|
||||
"error": "Cannot unmount /media/wrolpi: No drives are configured. "
|
||||
"This prevents accidental data loss.",
|
||||
}
|
||||
|
||||
# Check if this is the primary drive
|
||||
primary_mount = next(
|
||||
(m for m in configured_mounts if m.get("is_primary")),
|
||||
None
|
||||
)
|
||||
if primary_mount:
|
||||
return {
|
||||
"success": False,
|
||||
"error": "Cannot unmount /media/wrolpi: This is the primary WROLPi drive.",
|
||||
}
|
||||
|
||||
# Check if mount is busy
|
||||
if is_mount_busy(mount_point) and not lazy:
|
||||
return {
|
||||
"success": False,
|
||||
"error": f"Mount {mount_point} is busy. Use lazy unmount or stop services first.",
|
||||
}
|
||||
|
||||
# Unmount
|
||||
cmd = ["umount"]
|
||||
if lazy:
|
||||
cmd.append("-l")
|
||||
cmd.append(mount_point)
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "mount_point": mount_point}
|
||||
else:
|
||||
return {"success": False, "error": result.stderr.strip()}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": "Unmount timed out"}
|
||||
|
||||
|
||||
def is_mount_busy(mount_point: str) -> bool:
|
||||
"""Check if any processes are using the mount point."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["lsof", "+D", mount_point],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
return result.returncode == 0 and result.stdout.strip()
|
||||
except (subprocess.SubprocessError, FileNotFoundError):
|
||||
return False
|
||||
|
||||
|
||||
def get_mounts() -> list[dict]:
|
||||
"""
|
||||
Get current mounts under /media.
|
||||
|
||||
Returns:
|
||||
list of mount info dicts
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["findmnt", "-J", "-l", "-o", "TARGET,SOURCE,FSTYPE,OPTIONS"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
|
||||
data = json.loads(result.stdout)
|
||||
mounts = []
|
||||
|
||||
for fs in data.get("filesystems", []):
|
||||
target = fs.get("target", "")
|
||||
if target.startswith("/media"):
|
||||
mounts.append({
|
||||
"mount_point": target,
|
||||
"device": fs.get("source"),
|
||||
"fstype": fs.get("fstype"),
|
||||
"options": fs.get("options"),
|
||||
})
|
||||
|
||||
return mounts
|
||||
except (subprocess.SubprocessError, json.JSONDecodeError):
|
||||
return []
|
||||
240
controller/lib/docker_services.py
Normal file
240
controller/lib/docker_services.py
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
"""
|
||||
Docker container management for WROLPi Controller.
|
||||
|
||||
Used when running in Docker mode instead of systemd.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from controller.lib.config import is_docker_mode
|
||||
|
||||
# Import docker only if available (optional dependency)
|
||||
try:
|
||||
import docker
|
||||
from docker.errors import NotFound, APIError
|
||||
|
||||
DOCKER_AVAILABLE = True
|
||||
except ImportError:
|
||||
DOCKER_AVAILABLE = False
|
||||
docker = None
|
||||
NotFound = Exception
|
||||
APIError = Exception
|
||||
|
||||
# Container name prefix (from docker-compose project)
|
||||
CONTAINER_PREFIX = os.environ.get("COMPOSE_PROJECT_NAME", "wrolpi")
|
||||
|
||||
# Containers that should not have a "View" button (non-HTTP services)
|
||||
NON_VIEWABLE_CONTAINERS = {"db", "postgres", "postgresql", "redis", "memcached"}
|
||||
|
||||
# Containers that should use HTTPS (in addition to *_https suffix detection)
|
||||
HTTPS_CONTAINERS = {"web"}
|
||||
|
||||
|
||||
def can_manage_containers() -> bool:
|
||||
"""Check if we can manage Docker containers."""
|
||||
if not is_docker_mode():
|
||||
return False
|
||||
if not DOCKER_AVAILABLE:
|
||||
return False
|
||||
if not os.path.exists("/var/run/docker.sock"):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _get_client():
|
||||
"""Get Docker client."""
|
||||
if not DOCKER_AVAILABLE:
|
||||
raise RuntimeError("Docker library not installed")
|
||||
return docker.from_env()
|
||||
|
||||
|
||||
def _get_container_name(service_name: str) -> str:
|
||||
"""Convert service name to container name."""
|
||||
# docker-compose names: {project}-{service}-{number}
|
||||
return f"{CONTAINER_PREFIX}-{service_name}-1"
|
||||
|
||||
|
||||
def get_container_status(name: str) -> dict:
|
||||
"""
|
||||
Get status of a Docker container.
|
||||
|
||||
Args:
|
||||
name: Service name
|
||||
|
||||
Returns:
|
||||
dict with status info
|
||||
"""
|
||||
if not can_manage_containers():
|
||||
return {
|
||||
"name": name,
|
||||
"status": "unknown",
|
||||
"available": False,
|
||||
"reason": "Docker management not available",
|
||||
}
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
container_name = _get_container_name(name)
|
||||
container = client.containers.get(container_name)
|
||||
|
||||
# Map Docker status to our status
|
||||
docker_status = container.status
|
||||
if docker_status == "running":
|
||||
status = "running"
|
||||
elif docker_status == "exited":
|
||||
status = "stopped"
|
||||
elif docker_status == "restarting":
|
||||
status = "restarting"
|
||||
else:
|
||||
status = docker_status
|
||||
|
||||
# Get port info from container
|
||||
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {})
|
||||
port = None
|
||||
for container_port, host_bindings in ports.items():
|
||||
if host_bindings:
|
||||
port = int(host_bindings[0].get("HostPort", 0))
|
||||
break
|
||||
|
||||
return {
|
||||
"name": name,
|
||||
"container_name": container_name,
|
||||
"status": status,
|
||||
"docker_status": docker_status,
|
||||
"port": port,
|
||||
"available": True,
|
||||
"viewable": name not in NON_VIEWABLE_CONTAINERS,
|
||||
"use_https": name.endswith("_https") or name in HTTPS_CONTAINERS,
|
||||
}
|
||||
except NotFound:
|
||||
return {
|
||||
"name": name,
|
||||
"status": "not_found",
|
||||
"available": True,
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"name": name,
|
||||
"status": "error",
|
||||
"error": str(e),
|
||||
"available": False,
|
||||
}
|
||||
|
||||
|
||||
def get_all_containers_status() -> list[dict]:
|
||||
"""
|
||||
Get status of all WROLPi containers.
|
||||
|
||||
Returns:
|
||||
list of container status dicts
|
||||
"""
|
||||
if not can_manage_containers():
|
||||
return []
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
containers = client.containers.list(all=True)
|
||||
|
||||
results = []
|
||||
for container in containers:
|
||||
if container.name.startswith(CONTAINER_PREFIX):
|
||||
# Extract service name from container name
|
||||
parts = container.name.split("-")
|
||||
if len(parts) >= 2:
|
||||
service_name = parts[1]
|
||||
else:
|
||||
service_name = container.name
|
||||
|
||||
# Get port info from container
|
||||
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {})
|
||||
port = None
|
||||
for container_port, host_bindings in ports.items():
|
||||
if host_bindings:
|
||||
port = int(host_bindings[0].get("HostPort", 0))
|
||||
break
|
||||
|
||||
results.append({
|
||||
"name": service_name,
|
||||
"container_name": container.name,
|
||||
"status": "running" if container.status == "running" else "stopped",
|
||||
"docker_status": container.status,
|
||||
"port": port,
|
||||
"viewable": service_name not in NON_VIEWABLE_CONTAINERS,
|
||||
"use_https": service_name.endswith("_https") or service_name in HTTPS_CONTAINERS,
|
||||
})
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
return [{"error": str(e)}]
|
||||
|
||||
|
||||
def start_container(name: str) -> dict:
|
||||
"""Start a Docker container."""
|
||||
if not can_manage_containers():
|
||||
return {"success": False, "error": "Docker management not available"}
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
container_name = _get_container_name(name)
|
||||
container = client.containers.get(container_name)
|
||||
container.start()
|
||||
return {"success": True, "service": name, "action": "start"}
|
||||
except NotFound:
|
||||
return {"success": False, "error": f"Container not found: {name}"}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def stop_container(name: str) -> dict:
|
||||
"""Stop a Docker container."""
|
||||
if not can_manage_containers():
|
||||
return {"success": False, "error": "Docker management not available"}
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
container_name = _get_container_name(name)
|
||||
container = client.containers.get(container_name)
|
||||
container.stop(timeout=30)
|
||||
return {"success": True, "service": name, "action": "stop"}
|
||||
except NotFound:
|
||||
return {"success": False, "error": f"Container not found: {name}"}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def restart_container(name: str) -> dict:
|
||||
"""Restart a Docker container."""
|
||||
if not can_manage_containers():
|
||||
return {"success": False, "error": "Docker management not available"}
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
container_name = _get_container_name(name)
|
||||
container = client.containers.get(container_name)
|
||||
container.restart(timeout=30)
|
||||
return {"success": True, "service": name, "action": "restart"}
|
||||
except NotFound:
|
||||
return {"success": False, "error": f"Container not found: {name}"}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def get_container_logs(name: str, lines: int = 100) -> dict:
|
||||
"""Get logs from a Docker container."""
|
||||
if not can_manage_containers():
|
||||
return {"error": "Docker management not available"}
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
container_name = _get_container_name(name)
|
||||
container = client.containers.get(container_name)
|
||||
logs = container.logs(tail=lines).decode("utf-8")
|
||||
return {
|
||||
"service": name,
|
||||
"lines": lines,
|
||||
"logs": logs,
|
||||
}
|
||||
except NotFound:
|
||||
return {"error": f"Container not found: {name}"}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
198
controller/lib/fstab.py
Normal file
198
controller/lib/fstab.py
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
"""
|
||||
fstab management for WROLPi Controller.
|
||||
|
||||
Provides persistent mount configuration via /etc/fstab.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from controller.lib.disks import get_uuid, validate_mount_point
|
||||
from controller.lib.wrol_mode import require_normal_mode
|
||||
|
||||
FSTAB_PATH = Path("/etc/fstab")
|
||||
|
||||
|
||||
def backup_fstab() -> Path:
|
||||
"""Create a timestamped backup of fstab."""
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
backup_path = Path(f"/etc/fstab.backup.{timestamp}")
|
||||
shutil.copy(FSTAB_PATH, backup_path)
|
||||
|
||||
# Also keep a known backup location for easy recovery
|
||||
shutil.copy(FSTAB_PATH, Path("/etc/fstab.wrolpi.backup"))
|
||||
|
||||
return backup_path
|
||||
|
||||
|
||||
def parse_fstab() -> list[dict]:
|
||||
"""Parse fstab into a list of entries."""
|
||||
entries = []
|
||||
|
||||
with open(FSTAB_PATH, "r") as f:
|
||||
for line_num, line in enumerate(f, 1):
|
||||
stripped = line.strip()
|
||||
|
||||
# Preserve comments and blank lines
|
||||
if not stripped or stripped.startswith("#"):
|
||||
entries.append({
|
||||
"type": "comment",
|
||||
"line": line,
|
||||
"line_num": line_num,
|
||||
})
|
||||
continue
|
||||
|
||||
parts = stripped.split()
|
||||
if len(parts) >= 4:
|
||||
entries.append({
|
||||
"type": "mount",
|
||||
"device": parts[0],
|
||||
"mount_point": parts[1],
|
||||
"fstype": parts[2],
|
||||
"options": parts[3],
|
||||
"dump": parts[4] if len(parts) > 4 else "0",
|
||||
"pass": parts[5] if len(parts) > 5 else "0",
|
||||
"line_num": line_num,
|
||||
})
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def add_fstab_entry(
|
||||
device: str,
|
||||
mount_point: str,
|
||||
fstype: str,
|
||||
options: str = "defaults,nofail,x-systemd.device-timeout=10s",
|
||||
use_uuid: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
Add or update an fstab entry for persistent mounting.
|
||||
|
||||
Args:
|
||||
device: Device path (will be converted to UUID if use_uuid=True)
|
||||
mount_point: Where to mount
|
||||
fstype: Filesystem type
|
||||
options: Mount options
|
||||
use_uuid: Convert device to UUID (recommended)
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
# WROL Mode check
|
||||
try:
|
||||
require_normal_mode("add fstab entry")
|
||||
except PermissionError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
# Validate mount point
|
||||
try:
|
||||
validate_mount_point(mount_point)
|
||||
except ValueError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
# Convert to UUID if requested
|
||||
if use_uuid and device.startswith("/dev/"):
|
||||
uuid = get_uuid(device)
|
||||
if uuid:
|
||||
device_spec = f"UUID={uuid}"
|
||||
else:
|
||||
device_spec = device
|
||||
else:
|
||||
device_spec = device
|
||||
|
||||
# Backup fstab
|
||||
backup_fstab()
|
||||
|
||||
# Read current fstab
|
||||
entries = parse_fstab()
|
||||
|
||||
# Remove any existing entry for this mount point
|
||||
entries = [e for e in entries if e.get("mount_point") != mount_point]
|
||||
|
||||
# Build new entry line
|
||||
new_entry = f"{device_spec} {mount_point} {fstype} {options} 0 2\n"
|
||||
|
||||
# Write updated fstab
|
||||
with open(FSTAB_PATH, "w") as f:
|
||||
for entry in entries:
|
||||
if entry["type"] == "comment":
|
||||
f.write(entry["line"])
|
||||
else:
|
||||
f.write(
|
||||
f"{entry['device']} {entry['mount_point']} {entry['fstype']} "
|
||||
f"{entry['options']} {entry['dump']} {entry['pass']}\n"
|
||||
)
|
||||
# Add new entry with comment
|
||||
f.write(f"# WROLPi managed mount - added {datetime.now().isoformat()}\n")
|
||||
f.write(new_entry)
|
||||
|
||||
# Reload systemd
|
||||
subprocess.run(["systemctl", "daemon-reload"], capture_output=True)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"device": device_spec,
|
||||
"mount_point": mount_point,
|
||||
}
|
||||
|
||||
|
||||
def remove_fstab_entry(mount_point: str) -> dict:
|
||||
"""
|
||||
Remove an fstab entry by mount point.
|
||||
|
||||
Args:
|
||||
mount_point: Mount point to remove
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
# WROL Mode check
|
||||
try:
|
||||
require_normal_mode("remove fstab entry")
|
||||
except PermissionError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
# Validate mount point
|
||||
try:
|
||||
validate_mount_point(mount_point)
|
||||
except ValueError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
# Backup fstab
|
||||
backup_fstab()
|
||||
|
||||
entries = parse_fstab()
|
||||
original_count = len([e for e in entries if e["type"] == "mount"])
|
||||
|
||||
# Remove entry
|
||||
entries = [e for e in entries if e.get("mount_point") != mount_point]
|
||||
new_count = len([e for e in entries if e["type"] == "mount"])
|
||||
|
||||
if original_count == new_count:
|
||||
return {"success": False, "error": f"No entry found for {mount_point}"}
|
||||
|
||||
# Write updated fstab
|
||||
with open(FSTAB_PATH, "w") as f:
|
||||
for entry in entries:
|
||||
if entry["type"] == "comment":
|
||||
f.write(entry["line"])
|
||||
else:
|
||||
f.write(
|
||||
f"{entry['device']} {entry['mount_point']} {entry['fstype']} "
|
||||
f"{entry['options']} {entry['dump']} {entry['pass']}\n"
|
||||
)
|
||||
|
||||
subprocess.run(["systemctl", "daemon-reload"], capture_output=True)
|
||||
|
||||
return {"success": True, "mount_point": mount_point}
|
||||
|
||||
|
||||
def get_wrolpi_fstab_entries() -> list[dict]:
|
||||
"""Get all fstab entries for mounts under /media/wrolpi."""
|
||||
entries = parse_fstab()
|
||||
return [
|
||||
e for e in entries
|
||||
if e["type"] == "mount" and e["mount_point"].startswith("/media/wrolpi")
|
||||
]
|
||||
83
controller/lib/smart.py
Normal file
83
controller/lib/smart.py
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
"""
|
||||
SMART disk health monitoring for WROLPi Controller.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
# Import pySMART only if available
|
||||
try:
|
||||
from pySMART import DeviceList, Device
|
||||
|
||||
SMART_AVAILABLE = True
|
||||
except ImportError:
|
||||
SMART_AVAILABLE = False
|
||||
|
||||
from controller.lib.config import is_docker_mode
|
||||
|
||||
|
||||
def is_smart_available() -> bool:
|
||||
"""Check if SMART monitoring is available."""
|
||||
if is_docker_mode():
|
||||
return False
|
||||
return SMART_AVAILABLE
|
||||
|
||||
|
||||
def get_all_smart_status() -> list[dict]:
|
||||
"""
|
||||
Get SMART status for all drives.
|
||||
|
||||
Returns:
|
||||
list of SMART status dicts
|
||||
"""
|
||||
if not is_smart_available():
|
||||
return []
|
||||
|
||||
try:
|
||||
devices = DeviceList()
|
||||
results = []
|
||||
|
||||
for device in devices.devices:
|
||||
results.append(_get_device_smart(device))
|
||||
|
||||
return results
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def _get_device_smart(device) -> dict:
|
||||
"""Extract SMART data from a pySMART device."""
|
||||
return {
|
||||
"device": device.name,
|
||||
"path": f"/dev/{device.name}",
|
||||
"model": device.model,
|
||||
"serial": device.serial,
|
||||
"capacity": device.capacity,
|
||||
"assessment": device.assessment, # PASS, FAIL, WARN
|
||||
"temperature": _get_temperature(device),
|
||||
"power_on_hours": _get_attribute(device, "Power_On_Hours"),
|
||||
"reallocated_sectors": _get_attribute(device, "Reallocated_Sector_Ct"),
|
||||
"pending_sectors": _get_attribute(device, "Current_Pending_Sector"),
|
||||
"smart_enabled": device.smart_enabled,
|
||||
}
|
||||
|
||||
|
||||
def _get_temperature(device) -> Optional[int]:
|
||||
"""Get drive temperature from SMART attributes."""
|
||||
temp = _get_attribute(device, "Temperature_Celsius")
|
||||
if temp is None:
|
||||
temp = _get_attribute(device, "Airflow_Temperature_Cel")
|
||||
return temp
|
||||
|
||||
|
||||
def _get_attribute(device, name: str) -> Optional[int]:
|
||||
"""Get a specific SMART attribute value."""
|
||||
if not hasattr(device, 'attributes') or device.attributes is None:
|
||||
return None
|
||||
|
||||
for attr in device.attributes:
|
||||
if attr and attr.name == name:
|
||||
try:
|
||||
return int(attr.raw)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
return None
|
||||
362
controller/lib/status.py
Normal file
362
controller/lib/status.py
Normal file
|
|
@ -0,0 +1,362 @@
|
|||
"""
|
||||
System status collection for WROLPi Controller.
|
||||
|
||||
Provides functions to collect CPU, memory, load, disk, network, and power
|
||||
status information. This is the authoritative source for system hardware status.
|
||||
|
||||
The status format matches the main WROLPi API's format so the React app
|
||||
can seamlessly switch between data sources.
|
||||
"""
|
||||
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import psutil
|
||||
|
||||
# CPU frequency paths
|
||||
MIN_FREQUENCY_PATH = Path('/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq')
|
||||
MAX_FREQUENCY_PATH = Path('/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq')
|
||||
CUR_FREQUENCY_PATH = Path('/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq')
|
||||
|
||||
|
||||
def get_cpu_status() -> dict:
|
||||
"""
|
||||
Get CPU usage, frequency, temperature, and core count.
|
||||
|
||||
Returns format compatible with main API's cpu_stats:
|
||||
dict with keys: cores, cur_frequency, max_frequency, min_frequency,
|
||||
percent, temperature, high_temperature, critical_temperature
|
||||
"""
|
||||
cpu_percent = int(psutil.cpu_percent(interval=0.1))
|
||||
cpu_count = psutil.cpu_count()
|
||||
|
||||
# Get frequency from sys files (more reliable than psutil on RPi)
|
||||
min_frequency = max_frequency = cur_frequency = None
|
||||
try:
|
||||
if MIN_FREQUENCY_PATH.exists():
|
||||
min_frequency = int(MIN_FREQUENCY_PATH.read_text())
|
||||
if MAX_FREQUENCY_PATH.exists():
|
||||
max_frequency = int(MAX_FREQUENCY_PATH.read_text())
|
||||
if CUR_FREQUENCY_PATH.exists():
|
||||
cur_frequency = int(CUR_FREQUENCY_PATH.read_text())
|
||||
except (ValueError, IOError):
|
||||
pass
|
||||
|
||||
# Get temperature using psutil
|
||||
temperature = high_temperature = critical_temperature = None
|
||||
try:
|
||||
temp = psutil.sensors_temperatures()
|
||||
if temp:
|
||||
name = 'coretemp' if 'coretemp' in temp else list(temp.keys())[0]
|
||||
temperatures = temp.get(name)
|
||||
if temperatures:
|
||||
temperature = statistics.median([i.current or 0 for i in temperatures])
|
||||
high_temperature = statistics.median([i.high or 0 for i in temperatures])
|
||||
critical_temperature = statistics.median([i.critical or 0 for i in temperatures])
|
||||
|
||||
# Temperatures may not exist.
|
||||
high_temperature = high_temperature or 60
|
||||
critical_temperature = critical_temperature or 95
|
||||
|
||||
if high_temperature and high_temperature == critical_temperature:
|
||||
# Display yellow warning before red warning.
|
||||
high_temperature = critical_temperature - 25
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"cores": cpu_count,
|
||||
"cur_frequency": cur_frequency - min_frequency if cur_frequency and min_frequency else None,
|
||||
"max_frequency": max_frequency,
|
||||
"min_frequency": min_frequency,
|
||||
"percent": cpu_percent,
|
||||
"temperature": int(temperature) if temperature else None,
|
||||
"high_temperature": int(high_temperature) if high_temperature else None,
|
||||
"critical_temperature": int(critical_temperature) if critical_temperature else None,
|
||||
}
|
||||
|
||||
|
||||
def get_memory_status() -> dict:
|
||||
"""
|
||||
Get memory usage statistics.
|
||||
|
||||
Returns format compatible with main API's memory_stats:
|
||||
dict with keys: total, used, free, cached
|
||||
"""
|
||||
mem = psutil.virtual_memory()
|
||||
return {
|
||||
"total": mem.total,
|
||||
"used": mem.used,
|
||||
"free": mem.free,
|
||||
"cached": getattr(mem, 'cached', 0), # cached may not exist on all platforms (e.g., macOS)
|
||||
}
|
||||
|
||||
|
||||
def get_load_status() -> dict:
|
||||
"""
|
||||
Get system load averages.
|
||||
|
||||
Returns format compatible with main API's load_stats:
|
||||
dict with keys: minute_1, minute_5, minute_15
|
||||
"""
|
||||
load1, load5, load15 = psutil.getloadavg()
|
||||
return {
|
||||
"minute_1": str(round(load1, 2)),
|
||||
"minute_5": str(round(load5, 2)),
|
||||
"minute_15": str(round(load15, 2)),
|
||||
}
|
||||
|
||||
|
||||
IGNORED_DRIVES = ['/boot', '/etc']
|
||||
VALID_FORMATS = {'btrfs', 'ext4', 'ext3', 'ext2', 'vfat', 'exfat', 'apfs'}
|
||||
|
||||
|
||||
def get_drive_status() -> list[dict]:
|
||||
"""
|
||||
Get disk usage for mounted filesystems.
|
||||
|
||||
Returns format compatible with main API's drives_stats:
|
||||
list of dicts with keys: mount, percent, size, used
|
||||
"""
|
||||
drives = []
|
||||
seen_devices = set()
|
||||
|
||||
for partition in psutil.disk_partitions():
|
||||
# Skip ignored directories
|
||||
if any(partition.mountpoint.startswith(i) for i in IGNORED_DRIVES):
|
||||
continue
|
||||
# Skip non-standard filesystems
|
||||
if partition.fstype not in VALID_FORMATS:
|
||||
continue
|
||||
# Skip duplicate devices (only use first partition)
|
||||
if partition.device in seen_devices:
|
||||
continue
|
||||
seen_devices.add(partition.device)
|
||||
|
||||
try:
|
||||
usage = psutil.disk_usage(partition.mountpoint)
|
||||
drives.append({
|
||||
"mount": partition.mountpoint,
|
||||
"percent": int(usage.percent),
|
||||
"size": int(usage.total),
|
||||
"used": int(usage.used),
|
||||
})
|
||||
except (PermissionError, OSError):
|
||||
pass
|
||||
|
||||
return sorted(drives, key=lambda i: i["mount"])
|
||||
|
||||
|
||||
def get_primary_drive_status() -> Optional[dict]:
|
||||
"""
|
||||
Get status of the primary WROLPi drive (/media/wrolpi).
|
||||
|
||||
Returns:
|
||||
dict with drive status, or None if not mounted
|
||||
"""
|
||||
for drive in get_drive_status():
|
||||
if drive["mount"] == "/media/wrolpi":
|
||||
return drive
|
||||
return None
|
||||
|
||||
|
||||
IGNORED_NIC_NAMES = {'lo', 'veth', 'tun', 'docker', 'br-'}
|
||||
|
||||
|
||||
def get_network_status() -> dict:
|
||||
"""
|
||||
Get network interface statistics.
|
||||
|
||||
Returns format compatible with main API's nic_bandwidth_stats:
|
||||
dict of interface_name -> stats
|
||||
"""
|
||||
from datetime import datetime
|
||||
timestamp = datetime.now().timestamp()
|
||||
counters = dict()
|
||||
if_stats = psutil.net_if_stats()
|
||||
|
||||
for name, counter in sorted(psutil.net_io_counters(pernic=True, nowrap=True).items(), key=lambda i: i[0]):
|
||||
if name in IGNORED_NIC_NAMES:
|
||||
continue
|
||||
stats = if_stats.get(name)
|
||||
counters[name] = {
|
||||
'name': name,
|
||||
'now': timestamp,
|
||||
'bytes_recv': counter.bytes_recv,
|
||||
'bytes_sent': counter.bytes_sent,
|
||||
'speed': int(stats.speed) if stats else 0,
|
||||
# Initialize bandwidth per second to 0 (requires historical data to calculate)
|
||||
'bytes_recv_ps': 0,
|
||||
'bytes_sent_ps': 0,
|
||||
}
|
||||
|
||||
return counters
|
||||
|
||||
|
||||
def get_power_status() -> dict:
|
||||
"""
|
||||
Get power/voltage status (Raspberry Pi specific).
|
||||
|
||||
Returns format compatible with main API's power_stats:
|
||||
dict with keys: under_voltage, over_current
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
result = {
|
||||
"under_voltage": False,
|
||||
"over_current": False,
|
||||
}
|
||||
|
||||
try:
|
||||
# Check via dmesg (same method as main API)
|
||||
proc = subprocess.run(
|
||||
['dmesg'],
|
||||
capture_output=True,
|
||||
timeout=5,
|
||||
)
|
||||
if proc.returncode == 0 and proc.stdout:
|
||||
result["under_voltage"] = b' Undervoltage detected' in proc.stdout
|
||||
result["over_current"] = b' over-current change ' in proc.stdout
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_iostat_status() -> dict:
|
||||
"""
|
||||
Get IO statistics using iostat command.
|
||||
|
||||
Returns format compatible with main API's iostat_stats:
|
||||
dict with keys: percent_idle, percent_iowait, percent_nice,
|
||||
percent_steal, percent_system, percent_user
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
result = {
|
||||
"percent_idle": None,
|
||||
"percent_iowait": None,
|
||||
"percent_nice": None,
|
||||
"percent_steal": None,
|
||||
"percent_system": None,
|
||||
"percent_user": None,
|
||||
}
|
||||
|
||||
try:
|
||||
# Run iostat with 1 second interval, 2 counts (use second measurement)
|
||||
proc = subprocess.run(
|
||||
['iostat', '1', '2'],
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
if proc.returncode == 0 and proc.stdout:
|
||||
try:
|
||||
import jc
|
||||
iostat_stats = jc.parse('iostat', proc.stdout.decode(), quiet=True)
|
||||
if iostat_stats:
|
||||
# Filter CPU stats and get the second one (first is since boot)
|
||||
cpu_stats_list = [s for s in iostat_stats if s.get('type') == 'cpu']
|
||||
if len(cpu_stats_list) >= 2:
|
||||
cpu_stats = cpu_stats_list[1]
|
||||
result = {
|
||||
"percent_idle": cpu_stats.get('percent_idle'),
|
||||
"percent_iowait": cpu_stats.get('percent_iowait'),
|
||||
"percent_nice": cpu_stats.get('percent_nice'),
|
||||
"percent_steal": cpu_stats.get('percent_steal'),
|
||||
"percent_system": cpu_stats.get('percent_system'),
|
||||
"percent_user": cpu_stats.get('percent_user'),
|
||||
}
|
||||
except ImportError:
|
||||
# jc not available, parse manually
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return result
|
||||
|
||||
|
||||
IGNORED_PROCESS_COMMANDS = {'<defunct>'}
|
||||
|
||||
|
||||
def get_processes_status() -> list[dict]:
|
||||
"""
|
||||
Get top CPU-consuming processes.
|
||||
|
||||
Returns format compatible with main API's processes_stats:
|
||||
list of dicts with keys: pid, percent_cpu, percent_mem, command
|
||||
"""
|
||||
processes = []
|
||||
|
||||
try:
|
||||
# Get processes sorted by CPU usage
|
||||
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'cmdline']):
|
||||
try:
|
||||
info = proc.info
|
||||
cpu_percent = info.get('cpu_percent', 0)
|
||||
|
||||
# Only include processes using > 1% CPU
|
||||
if cpu_percent and cpu_percent > 1:
|
||||
cmdline = info.get('cmdline') or [info.get('name', '')]
|
||||
command = ' '.join(cmdline) if cmdline else info.get('name', '')
|
||||
|
||||
# Skip ignored commands
|
||||
if any(ignored in command for ignored in IGNORED_PROCESS_COMMANDS):
|
||||
continue
|
||||
|
||||
processes.append({
|
||||
"pid": info.get('pid'),
|
||||
"percent_cpu": int(cpu_percent),
|
||||
"percent_mem": int(info.get('memory_percent', 0)),
|
||||
"command": command[:512], # Limit command length
|
||||
})
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
pass
|
||||
|
||||
# Sort by CPU usage and return top 10
|
||||
processes = sorted(processes, key=lambda x: x['percent_cpu'], reverse=True)[:10]
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return processes
|
||||
|
||||
|
||||
IGNORED_DISK_NAMES = ('loop', 'ram')
|
||||
|
||||
|
||||
def get_disk_bandwidth_status() -> dict:
|
||||
"""
|
||||
Get disk IO bandwidth statistics.
|
||||
|
||||
Returns format compatible with main API's disk_bandwidth_stats:
|
||||
dict of disk_name -> stats with bytes_read, bytes_write, etc.
|
||||
"""
|
||||
from datetime import datetime
|
||||
timestamp = datetime.now().timestamp()
|
||||
counters = dict()
|
||||
|
||||
try:
|
||||
for name, counter in sorted(psutil.disk_io_counters(perdisk=True).items(), key=lambda i: i[0]):
|
||||
# Skip partitions (only report main disks)
|
||||
if any(name.startswith(i) for i in counters):
|
||||
continue
|
||||
# Skip ignored disk types
|
||||
if any(name.startswith(i) for i in IGNORED_DISK_NAMES):
|
||||
continue
|
||||
|
||||
counters[name] = {
|
||||
'name': name,
|
||||
'now': timestamp,
|
||||
'bytes_read': counter.read_bytes,
|
||||
'bytes_write': counter.write_bytes,
|
||||
# Initialize per-second rates to 0 (requires historical data)
|
||||
'bytes_read_ps': 0,
|
||||
'bytes_write_ps': 0,
|
||||
'max_read_ps': 500_000, # Default max for display scaling
|
||||
'max_write_ps': 500_000,
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return counters
|
||||
129
controller/lib/status_worker.py
Normal file
129
controller/lib/status_worker.py
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
"""
|
||||
Background status worker for WROLPi Controller.
|
||||
|
||||
Periodically collects all system status and caches it in app.state
|
||||
for O(1) response times on API endpoints.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import multiprocessing
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from controller.lib.status import (
|
||||
get_cpu_status,
|
||||
get_disk_bandwidth_status,
|
||||
get_drive_status,
|
||||
get_iostat_status,
|
||||
get_load_status,
|
||||
get_memory_status,
|
||||
get_network_status,
|
||||
get_power_status,
|
||||
get_processes_status,
|
||||
)
|
||||
|
||||
# Type alias for cached status dict
|
||||
CachedStatus = dict
|
||||
|
||||
|
||||
async def collect_all_status() -> CachedStatus:
|
||||
"""
|
||||
Collect all status information concurrently.
|
||||
|
||||
Returns a dict with all status types. Individual failures return None
|
||||
for that stat type rather than failing the entire collection.
|
||||
"""
|
||||
# Run all status collections concurrently using asyncio.to_thread
|
||||
# since the status functions are synchronous (use psutil)
|
||||
cpu, memory, load, drives, network, power, iostat, processes, disk_bandwidth = await asyncio.gather(
|
||||
asyncio.to_thread(get_cpu_status),
|
||||
asyncio.to_thread(get_memory_status),
|
||||
asyncio.to_thread(get_load_status),
|
||||
asyncio.to_thread(get_drive_status),
|
||||
asyncio.to_thread(get_network_status),
|
||||
asyncio.to_thread(get_power_status),
|
||||
asyncio.to_thread(get_iostat_status),
|
||||
asyncio.to_thread(get_processes_status),
|
||||
asyncio.to_thread(get_disk_bandwidth_status),
|
||||
return_exceptions=True,
|
||||
)
|
||||
|
||||
# Handle individual failures gracefully - return None for failed stats
|
||||
status = {
|
||||
"cpu_stats": cpu if not isinstance(cpu, Exception) else None,
|
||||
"memory_stats": memory if not isinstance(memory, Exception) else None,
|
||||
"load_stats": load if not isinstance(load, Exception) else None,
|
||||
"drives_stats": drives if not isinstance(drives, Exception) else [],
|
||||
"nic_bandwidth_stats": network if not isinstance(network, Exception) else {},
|
||||
"power_stats": power if not isinstance(power, Exception) else None,
|
||||
"iostat_stats": iostat if not isinstance(iostat, Exception) else None,
|
||||
"processes_stats": processes if not isinstance(processes, Exception) else [],
|
||||
"disk_bandwidth_stats": disk_bandwidth if not isinstance(disk_bandwidth, Exception) else {},
|
||||
"last_status": datetime.now().isoformat(),
|
||||
}
|
||||
|
||||
return status
|
||||
|
||||
|
||||
def get_adaptive_sleep(load_stats: Optional[dict], base_sleep: float = 5.0) -> float:
|
||||
"""
|
||||
Calculate adaptive sleep time based on system load.
|
||||
|
||||
If system is under heavy load (load_1 > cpu_count), increase sleep time
|
||||
to reduce overhead on the system.
|
||||
|
||||
Args:
|
||||
load_stats: Dict with minute_1 key (string), or None
|
||||
base_sleep: Base sleep interval in seconds
|
||||
|
||||
Returns:
|
||||
Sleep time in seconds (may be > base_sleep if system is stressed)
|
||||
"""
|
||||
if load_stats is None:
|
||||
return base_sleep
|
||||
|
||||
try:
|
||||
load_1 = float(load_stats.get("minute_1", 0))
|
||||
cpu_count = multiprocessing.cpu_count()
|
||||
|
||||
if load_1 > cpu_count:
|
||||
# System is stressed, slow down status updates
|
||||
return (base_sleep * load_1) / cpu_count
|
||||
except (ValueError, TypeError, ZeroDivisionError):
|
||||
pass
|
||||
|
||||
return base_sleep
|
||||
|
||||
|
||||
async def status_worker_loop(app, base_sleep: float = 5.0):
|
||||
"""
|
||||
Background loop that continuously collects status data.
|
||||
|
||||
Runs indefinitely until cancelled. Stores collected status in
|
||||
app.state.cached_status for fast endpoint access.
|
||||
|
||||
Args:
|
||||
app: FastAPI application instance
|
||||
base_sleep: Base sleep interval in seconds (default 5s)
|
||||
"""
|
||||
print("Status worker started")
|
||||
|
||||
while True:
|
||||
try:
|
||||
# Collect all status data
|
||||
status = await collect_all_status()
|
||||
|
||||
# Store in app.state (thread-safe for reading in single-worker uvicorn)
|
||||
app.state.cached_status = status
|
||||
|
||||
# Calculate adaptive sleep based on load
|
||||
sleep_time = get_adaptive_sleep(status.get("load_stats"), base_sleep)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
print("Status worker cancelled")
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"Status worker error: {e}")
|
||||
sleep_time = base_sleep
|
||||
|
||||
await asyncio.sleep(sleep_time)
|
||||
322
controller/lib/systemd.py
Normal file
322
controller/lib/systemd.py
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
"""
|
||||
Systemd service management for WROLPi Controller.
|
||||
|
||||
Provides start/stop/restart/status/logs for systemd services.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
|
||||
from controller.lib.config import get_config
|
||||
|
||||
|
||||
def get_managed_services() -> list[dict]:
|
||||
"""
|
||||
Get list of managed services from config.
|
||||
|
||||
Returns:
|
||||
list of service configs with name, systemd_name, port, etc.
|
||||
"""
|
||||
config = get_config()
|
||||
return config.get("managed_services", [])
|
||||
|
||||
|
||||
def get_service_config(name: str) -> Optional[dict]:
|
||||
"""
|
||||
Get config for a specific service by name.
|
||||
|
||||
Args:
|
||||
name: Service name (e.g., "wrolpi-api")
|
||||
|
||||
Returns:
|
||||
Service config dict or None if not found
|
||||
"""
|
||||
for service in get_managed_services():
|
||||
if service.get("name") == name:
|
||||
return service
|
||||
return None
|
||||
|
||||
|
||||
def _run_systemctl(command: str, service: str, timeout: int = 30) -> dict:
|
||||
"""
|
||||
Run a systemctl command.
|
||||
|
||||
Args:
|
||||
command: systemctl command (start, stop, restart, status, etc.)
|
||||
service: systemd service name
|
||||
timeout: Command timeout in seconds
|
||||
|
||||
Returns:
|
||||
dict with success, output, and error fields
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["systemctl", command, service],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
return {
|
||||
"success": result.returncode == 0,
|
||||
"output": result.stdout.strip(),
|
||||
"error": result.stderr.strip() if result.returncode != 0 else None,
|
||||
}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "output": "", "error": "Command timed out"}
|
||||
except FileNotFoundError:
|
||||
return {"success": False, "output": "", "error": "systemctl not found"}
|
||||
|
||||
|
||||
def get_service_status(name: str) -> dict:
|
||||
"""
|
||||
Get status of a managed service.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
|
||||
Returns:
|
||||
dict with status, active, enabled, etc.
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
|
||||
try:
|
||||
# Get active state
|
||||
active_result = subprocess.run(
|
||||
["systemctl", "is-active", systemd_name],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
is_active = active_result.stdout.strip()
|
||||
|
||||
# Get enabled state
|
||||
enabled_result = subprocess.run(
|
||||
["systemctl", "is-enabled", systemd_name],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
is_enabled = enabled_result.stdout.strip()
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
return {
|
||||
"name": name,
|
||||
"systemd_name": systemd_name,
|
||||
"status": "unknown",
|
||||
"active": "unknown",
|
||||
"enabled": False,
|
||||
"port": service_config.get("port"),
|
||||
"viewable": service_config.get("viewable", False),
|
||||
"view_path": service_config.get("view_path", ""),
|
||||
"use_https": service_config.get("use_https", False),
|
||||
"description": service_config.get("description", ""),
|
||||
"error": "systemctl not available",
|
||||
}
|
||||
|
||||
# Map to simple status
|
||||
if is_active == "active":
|
||||
status = "running"
|
||||
elif is_active == "activating":
|
||||
status = "running" # oneshot services show "activating" while running
|
||||
elif is_active == "inactive":
|
||||
status = "stopped"
|
||||
elif is_active == "failed":
|
||||
status = "failed"
|
||||
else:
|
||||
status = "unknown"
|
||||
|
||||
return {
|
||||
"name": name,
|
||||
"systemd_name": systemd_name,
|
||||
"status": status,
|
||||
"active": is_active,
|
||||
"enabled": is_enabled == "enabled",
|
||||
"port": service_config.get("port"),
|
||||
"viewable": service_config.get("viewable", False),
|
||||
"view_path": service_config.get("view_path", ""),
|
||||
"use_https": service_config.get("use_https", False),
|
||||
"description": service_config.get("description", ""),
|
||||
}
|
||||
|
||||
|
||||
def get_all_services_status() -> list[dict]:
|
||||
"""
|
||||
Get status of all managed services.
|
||||
|
||||
Services with show_only_when_running=True are excluded when not running.
|
||||
|
||||
Returns:
|
||||
list of service status dicts
|
||||
"""
|
||||
results = []
|
||||
for service in get_managed_services():
|
||||
status = get_service_status(service["name"])
|
||||
# Skip services with show_only_when_running if not running
|
||||
if service.get("show_only_when_running") and status.get("status") != "running":
|
||||
continue
|
||||
results.append(status)
|
||||
return results
|
||||
|
||||
|
||||
def start_service(name: str) -> dict:
|
||||
"""
|
||||
Start a managed service.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"success": False, "error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
result = _run_systemctl("start", systemd_name)
|
||||
|
||||
return {
|
||||
"success": result["success"],
|
||||
"service": name,
|
||||
"action": "start",
|
||||
"error": result.get("error"),
|
||||
}
|
||||
|
||||
|
||||
def stop_service(name: str) -> dict:
|
||||
"""
|
||||
Stop a managed service.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"success": False, "error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
result = _run_systemctl("stop", systemd_name)
|
||||
|
||||
return {
|
||||
"success": result["success"],
|
||||
"service": name,
|
||||
"action": "stop",
|
||||
"error": result.get("error"),
|
||||
}
|
||||
|
||||
|
||||
def restart_service(name: str) -> dict:
|
||||
"""
|
||||
Restart a managed service.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"success": False, "error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
result = _run_systemctl("restart", systemd_name)
|
||||
|
||||
return {
|
||||
"success": result["success"],
|
||||
"service": name,
|
||||
"action": "restart",
|
||||
"error": result.get("error"),
|
||||
}
|
||||
|
||||
|
||||
def enable_service(name: str) -> dict:
|
||||
"""
|
||||
Enable a service to start at boot.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"success": False, "error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
result = _run_systemctl("enable", systemd_name)
|
||||
|
||||
return {
|
||||
"success": result["success"],
|
||||
"service": name,
|
||||
"action": "enable",
|
||||
"error": result.get("error"),
|
||||
}
|
||||
|
||||
|
||||
def disable_service(name: str) -> dict:
|
||||
"""
|
||||
Disable a service from starting at boot.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
|
||||
Returns:
|
||||
dict with success status
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"success": False, "error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
result = _run_systemctl("disable", systemd_name)
|
||||
|
||||
return {
|
||||
"success": result["success"],
|
||||
"service": name,
|
||||
"action": "disable",
|
||||
"error": result.get("error"),
|
||||
}
|
||||
|
||||
|
||||
def get_service_logs(name: str, lines: int = 100, since: Optional[str] = None) -> dict:
|
||||
"""
|
||||
Get logs for a service.
|
||||
|
||||
Args:
|
||||
name: Service name from config
|
||||
lines: Number of lines to return
|
||||
since: Time specification (e.g., "1h", "30m", "2024-01-01")
|
||||
|
||||
Returns:
|
||||
dict with logs and metadata
|
||||
"""
|
||||
service_config = get_service_config(name)
|
||||
if not service_config:
|
||||
return {"error": f"Unknown service: {name}"}
|
||||
|
||||
systemd_name = service_config.get("systemd_name", name)
|
||||
|
||||
cmd = ["journalctl", "-u", systemd_name, "-n", str(lines), "--no-pager"]
|
||||
if since:
|
||||
cmd.extend(["--since", since])
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
|
||||
return {
|
||||
"service": name,
|
||||
"lines": lines,
|
||||
"since": since,
|
||||
"logs": result.stdout,
|
||||
}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"error": "Timeout getting logs"}
|
||||
except FileNotFoundError:
|
||||
return {"error": "journalctl not found"}
|
||||
45
controller/lib/wrol_mode.py
Normal file
45
controller/lib/wrol_mode.py
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
"""
|
||||
WROL Mode detection for WROLPi Controller.
|
||||
|
||||
WROL Mode (Without Rule of Law) is an emergency mode that restricts
|
||||
persistent configuration changes.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from controller.lib.config import get_media_directory
|
||||
|
||||
|
||||
def get_wrol_mode_flag_path() -> Path:
|
||||
"""Get the path to the WROL Mode flag file."""
|
||||
return get_media_directory() / "config" / ".wrol_mode"
|
||||
|
||||
|
||||
def is_wrol_mode() -> bool:
|
||||
"""
|
||||
Check if WROL Mode is active.
|
||||
|
||||
WROL Mode is indicated by the presence of a flag file.
|
||||
This file is created/deleted by the API when the user toggles WROL Mode.
|
||||
"""
|
||||
return get_wrol_mode_flag_path().exists()
|
||||
|
||||
|
||||
def require_normal_mode(operation: str) -> None:
|
||||
"""
|
||||
Raise an error if WROL Mode is active.
|
||||
|
||||
Use this to guard persistent operations that shouldn't be
|
||||
allowed during emergencies.
|
||||
|
||||
Args:
|
||||
operation: Description of the operation being attempted
|
||||
|
||||
Raises:
|
||||
PermissionError: If WROL Mode is active
|
||||
"""
|
||||
if is_wrol_mode():
|
||||
raise PermissionError(
|
||||
f"Cannot {operation} while WROL Mode is active. "
|
||||
"Disable WROL Mode to make persistent changes."
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue