Laboratorio domestico
demo-kit/ è quello che simula il dispositivo per la demo nella pagina di inizio. Il dispositivo stesso non ne ha bisogno.
demo-kit/ è quello che simula il dispositivo per la demo nella pagina di inizio. Il dispositivo stesso non ne ha bisogno.
#!/usr/bin/env python3
"""Home lab panel: the load of a Linux machine and its containers, as a small HTTP API with a screen of its own.
python homelab_panel.py [--port 8765] [--allow-actions] [--simulate] [--engine docker|podman] [--verbose]
It listens on 127.0.0.1 only. `cz agent run` with `cz service add api 127.0.0.1:8765 --protocol http` makes it
reachable through Connectivitizer (../README.md); the Connectivitizer app then shows ../ui/homelab.html.
GET /load the machine: uptime, load, CPU, memory, disks, temperature, network
GET /services the containers
POST /services/<id>/restart only with --allow-actions (or HOMELAB_ALLOW_ACTIONS=1); otherwise 403
POST /services/<id>/stop
POST /services/<id>/start
GET /.cz/ui.json, /.cz/ui.html the screen (../ui/manifest.json, ../ui/homelab.html)
The machine is read from /proc, os.statvfs and /sys/class/thermal, the containers from the container engine's
command line (docker or podman, whichever is installed). On a machine that is not Linux everything is simulated;
on Linux without a container engine the services are. /load says so with "simulated": true.
Python 3.9 or newer, standard library only.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import shutil
import socket
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlsplit
UI_FOLDER = Path(__file__).resolve().parent.parent / "ui"
ACTIONS = ("restart", "stop", "start")
ACTION_PATH = re.compile(r"^/services/([^/]+)/(restart|stop|start)$")
CONTAINER_ID = re.compile(r"^[0-9a-f]{12,64}$")
GB = 1024 ** 3
MB = 1024 ** 2
KB = 1024
def clamp(value: float, low: float, high: float) -> float:
return max(low, min(high, value))
# --------------------------------------------------------------------------------------------------------
# The machine, from /proc
# --------------------------------------------------------------------------------------------------------
class LinuxHost:
"""Samples /proc once a second, so that CPU and network are rates over the last second."""
REAL_FILESYSTEMS = {"ext2", "ext3", "ext4", "xfs", "btrfs", "zfs", "f2fs", "vfat", "exfat", "ntfs", "ntfs3", "fuseblk", "bcachefs"}
SKIPPED_INTERFACES = ("lo", "veth", "docker", "br-", "virbr", "cni", "flannel", "podman", "tun", "tap")
def __init__(self) -> None:
self._lock = threading.Lock()
self._cpu_percent = 0.0
self._rx_rate = 0.0
self._tx_rate = 0.0
self._last_cpu = self._read_cpu()
self._last_net = self._read_net()
self._last_time = time.monotonic()
threading.Thread(target=self._sample_forever, name="host", daemon=True).start()
def _read_cpu() -> tuple[int, int]:
"""(busy, total) jiffies of all cores since boot."""
with open("/proc/stat", encoding="ascii") as file:
fields = [int(value) for value in file.readline().split()[1:]]
idle = fields[3] + (fields[4] if len(fields) > 4 else 0) # idle + iowait
total = sum(fields[:8]) # without guest time, which is already in user
return total - idle, total
def _read_net(self) -> tuple[int, int]:
"""(received, sent) bytes of the real interfaces since boot."""
received = sent = 0
with open("/proc/net/dev", encoding="ascii") as file:
for line in file.readlines()[2:]:
name, _, rest = line.partition(":")
if name.strip().startswith(self.SKIPPED_INTERFACES):
continue
fields = rest.split()
if len(fields) >= 9:
received += int(fields[0])
sent += int(fields[8])
return received, sent
def _sample_forever(self) -> None:
while True:
time.sleep(1)
try:
cpu, net, now = self._read_cpu(), self._read_net(), time.monotonic()
elapsed = max(now - self._last_time, 0.001)
total = cpu[1] - self._last_cpu[1]
with self._lock:
if total > 0:
self._cpu_percent = clamp(100 * (cpu[0] - self._last_cpu[0]) / total, 0, 100)
self._rx_rate = max(0.0, (net[0] - self._last_net[0]) / elapsed)
self._tx_rate = max(0.0, (net[1] - self._last_net[1]) / elapsed)
self._last_cpu, self._last_net, self._last_time = cpu, net, now
except (OSError, ValueError, IndexError):
pass # a reading that fails is skipped; the last one stays
def _memory() -> dict:
values = {}
with open("/proc/meminfo", encoding="ascii") as file:
for line in file:
key, _, rest = line.partition(":")
values[key] = int(rest.split()[0]) * 1024
total = values.get("MemTotal", 0)
available = values.get("MemAvailable", values.get("MemFree", 0))
return {"used": max(0, total - available), "total": total}
def _disks(self) -> list[dict]:
disks, seen = [], set()
with open("/proc/mounts", encoding="utf-8", errors="replace") as file:
for line in file:
fields = line.split()
if len(fields) < 3:
continue
device, mount, filesystem = fields[0], fields[1].replace("\\040", " "), fields[2]
if filesystem not in self.REAL_FILESYSTEMS or device in seen or device.startswith("/dev/loop"):
continue
if mount.startswith(("/boot", "/snap", "/var/lib/docker", "/var/lib/containers")):
continue
try:
stat = os.statvfs(mount)
filesystem_id = os.stat(mount).st_dev # the same file system mounted twice is listed once
except OSError:
continue
total = stat.f_blocks * stat.f_frsize
if total <= 0 or filesystem_id in seen:
continue
seen.update((device, filesystem_id))
disks.append({"mount": mount, "used": total - stat.f_bfree * stat.f_frsize, "total": total})
disks.sort(key=lambda disk: (disk["mount"] != "/", disk["mount"]))
return disks[:6]
def _temperature() -> float | None:
hottest = None
for zone in Path("/sys/class/thermal").glob("thermal_zone*/temp"):
try:
value = int(zone.read_text(encoding="ascii").strip()) / 1000
except (OSError, ValueError):
continue
if 0 < value < 150 and (hottest is None or value > hottest):
hottest = value
return None if hottest is None else round(hottest, 1)
def load(self) -> dict:
with open("/proc/uptime", encoding="ascii") as file:
uptime = float(file.read().split()[0])
with self._lock:
cpu, rx, tx = self._cpu_percent, self._rx_rate, self._tx_rate
return {
"hostname": socket.gethostname(),
"uptimeSeconds": int(uptime),
"load": [round(value, 2) for value in os.getloadavg()],
"cpuPercent": round(cpu, 1),
"memory": self._memory(),
"disks": self._disks(),
"temperatureC": self._temperature(),
"network": {"rxBytesPerSec": int(rx), "txBytesPerSec": int(tx)},
}
# --------------------------------------------------------------------------------------------------------
# The containers, from the engine's command line
# --------------------------------------------------------------------------------------------------------
class UnknownService(Exception):
pass
class ActionFailed(Exception):
pass
class EngineServices:
"""Asks docker or podman. Every command is a fixed list of arguments; the only variable ones are container
ids that the engine itself reported and that look like ids. Nothing from a request ever reaches a command."""
def __init__(self, binary: str) -> None:
self.binary = binary
self._lock = threading.Lock() # the list
self._refreshing = threading.Lock() # one round of commands at a time
self._services: list[dict] = []
self._full_ids: dict[str, str] = {} # the short id the API shows -> the engine's id
self._restarting: set[str] = set()
self.refresh()
threading.Thread(target=self._refresh_forever, name="services", daemon=True).start()
def _run(self, arguments: list[str], timeout: float = 20) -> str:
done = subprocess.run([self.binary, *arguments], capture_output=True, text=True, timeout=timeout, check=False,
stdin=subprocess.DEVNULL)
if done.returncode != 0:
raise ActionFailed((done.stderr or "").strip()[:200] or f"{self.binary} {arguments[0]} failed")
return done.stdout
def _refresh_forever(self) -> None:
while True:
time.sleep(2)
try:
self.refresh()
except (ActionFailed, OSError, ValueError, subprocess.TimeoutExpired) as error:
print(f"services: {error}", file=sys.stderr)
def refresh(self) -> None:
with self._refreshing:
ids = [line.strip() for line in self._run(["ps", "-aq", "--no-trunc"]).splitlines()]
ids = [value for value in ids if CONTAINER_ID.match(value)]
inspected = json.loads(self._run(["inspect", *ids])) if ids else []
usage = self._usage()
now = datetime.now(timezone.utc)
services, full_ids = [], {}
for container in inspected:
full = str(container.get("Id", ""))
if not CONTAINER_ID.match(full):
continue
short = full[:12]
state = container.get("State") or {}
health = ((state.get("Health") or state.get("Healthcheck") or {}).get("Status") or "").lower()
if short in self._restarting or state.get("Restarting") or state.get("Status") == "restarting":
name_of_state = "restarting"
elif state.get("Running"):
name_of_state = "unhealthy" if health == "unhealthy" else "running"
else:
name_of_state = "stopped"
alive = name_of_state in ("running", "unhealthy")
cpu, memory = usage.get(short, (0.0, 0))
ports = set()
for bindings in ((container.get("NetworkSettings") or {}).get("Ports") or {}).values():
for binding in bindings or []:
if binding.get("HostPort"):
ports.add(str(binding["HostPort"]))
config = container.get("Config") or {}
services.append({
"id": short,
"name": str(container.get("Name", short)).lstrip("/"),
"image": str(config.get("Image") or container.get("ImageName") or ""),
"state": name_of_state,
"uptimeSeconds": self._seconds_since(state.get("StartedAt"), now) if alive else 0,
"cpuPercent": cpu if alive else 0.0,
"memoryBytes": memory if alive else 0,
"ports": sorted(ports, key=lambda port: (len(port), port)),
"restarts": int(container.get("RestartCount") or 0),
})
full_ids[short] = full
services.sort(key=lambda service: service["name"])
with self._lock:
self._services, self._full_ids = services, full_ids
def _usage(self) -> dict[str, tuple[float, int]]:
"""CPU percent and memory bytes by short id. Without it the list still works, with zeros."""
usage: dict[str, tuple[float, int]] = {}
try:
output = self._run(["stats", "--no-stream", "--no-trunc", "--format", "{{json .}}"], timeout=30)
except (ActionFailed, OSError, subprocess.TimeoutExpired):
return usage
for line in output.splitlines():
try:
row = json.loads(line)
except ValueError:
continue
identifier = str(row.get("ID") or row.get("ContainerID") or row.get("Container") or row.get("id") or "")
if not CONTAINER_ID.match(identifier):
continue
usage[identifier[:12]] = (
self._percent(row.get("CPUPerc") or row.get("CPU") or row.get("cpu_percent")),
self._bytes(str(row.get("MemUsage") or row.get("mem_usage") or "").split("/")[0]),
)
return usage
def _percent(text: object) -> float:
try:
return round(max(0.0, float(str(text).strip().rstrip("%"))), 1)
except ValueError:
return 0.0
def _bytes(text: str) -> int:
match = re.match(r"^\s*([0-9.]+)\s*([A-Za-z]*)", text)
if not match:
return 0
units = {"": 1, "b": 1, "kb": 1000, "kib": KB, "mb": 1000 ** 2, "mib": MB, "gb": 1000 ** 3, "gib": GB, "tb": 1000 ** 4, "tib": 1024 ** 4}
try:
return int(float(match.group(1)) * units.get(match.group(2).lower(), 1))
except ValueError:
return 0
def _seconds_since(started: object, now: datetime) -> int:
"""StartedAt is RFC 3339 with up to nine decimals, which datetime does not read."""
match = re.match(r"^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.\d+)?\s*(Z|[+-]\d\d:\d\d)?", str(started or ""))
if not match:
return 0
try:
moment = datetime.fromisoformat(match.group(1) + (match.group(2) or "Z").replace("Z", "+00:00"))
except ValueError:
return 0
return max(0, int((now - moment).total_seconds()))
def list(self) -> list[dict]:
with self._lock:
return [dict(service, state="restarting", uptimeSeconds=0, cpuPercent=0.0, memoryBytes=0)
if service["id"] in self._restarting else dict(service) for service in self._services]
def _get(self, short: str) -> dict:
for service in self.list():
if service["id"] == short:
return service
raise UnknownService(short)
def act(self, requested: str, action: str) -> dict:
with self._lock:
full = self._full_ids.get(requested) # the id the engine reported; never the text of the request
if full is None or action not in ACTIONS:
raise UnknownService(requested)
short = full[:12]
if action == "restart":
# A restart takes as long as the service needs to stop. The answer does not wait for it.
with self._lock:
if short in self._restarting:
return self._get_locked(short)
self._restarting.add(short)
threading.Thread(target=self._restart, args=(short, full), name="restart", daemon=True).start()
else:
self._run([action, full], timeout=60)
self.refresh()
return self._get(short)
def _get_locked(self, short: str) -> dict:
for service in self._services:
if service["id"] == short:
return dict(service, state="restarting", uptimeSeconds=0, cpuPercent=0.0, memoryBytes=0)
raise UnknownService(short)
def _restart(self, short: str, full: str) -> None:
try:
self._run(["restart", full], timeout=120)
except (ActionFailed, OSError, subprocess.TimeoutExpired) as error:
print(f"restart of {short}: {error}", file=sys.stderr)
finally:
with self._lock:
self._restarting.discard(short)
try:
self.refresh()
except (ActionFailed, OSError, ValueError, subprocess.TimeoutExpired):
pass
# --------------------------------------------------------------------------------------------------------
# Simulated: for a machine without /proc or without a container engine, so the example runs anywhere
# --------------------------------------------------------------------------------------------------------
class SimulatedServices:
RESTART_SECONDS = 3.0
SICK_EVERY, SICK_FROM, SICK_FOR = 56, 24, 15 # photo-library fails its health check for a while, and recovers
DEFINITIONS = [
# id, name, image, ports, cpu (percent of a core), swing, period, memory, up for (days), restarts, stopped
("7c1e09ab52d4", "reverse-proxy", "homelab/reverse-proxy:2.8", ["80", "443"], 1.6, 0.5, 9, 46 * MB, 23, 0, False),
("3f9a1c0b7d21", "media-server", "homelab/media-server:1.32", ["8096"], 21, 0.7, 17, 840 * MB, 6.2, 1, False),
("b48d2e6f1a90", "photo-library", "homelab/photo-library:0.9", ["2342"], 7, 0.6, 13, 620 * MB, 2.4, 4, False),
("90aa3c5e77f1", "home-automation", "homelab/home-automation:2026.11", ["8123"], 3.4, 0.4, 11, 410 * MB, 11.3, 0, False),
("e2d7f0146c3b", "git-forge", "homelab/git-forge:1.22", ["3000", "2222"], 1.1, 0.8, 21, 212 * MB, 23, 0, False),
("5b6c8d9e0f12", "dns-filter", "homelab/dns-filter:5.18", ["53", "8053"], 0.7, 0.5, 7, 58 * MB, 23, 0, False),
("a1f4e8c2d603", "metrics", "homelab/metrics:3.1", ["9090"], 4.2, 0.3, 15, 336 * MB, 4.1, 2, False),
("0d3b5a7c9e11", "backup-runner", "homelab/backup-runner:0.17", [], 2.5, 0.5, 10, 128 * MB, 0, 0, True),
]
def __init__(self) -> None:
self._lock = threading.Lock()
self._began = time.time()
self._settled = 0.0
self._random = random.Random(20261116)
self._services = []
for index, (identifier, name, image, ports, cpu, swing, period, memory, days, restarts, stopped) in enumerate(self.DEFINITIONS):
self._services.append({
"id": identifier, "name": name, "image": image, "ports": ports, "base_cpu": cpu, "swing": swing, "period": period,
"base_memory": memory, "phase": index * 1.7, "state": "stopped" if stopped else "running",
"started": time.time() - days * 86400, "restarts": restarts, "restart_until": 0.0, "skip_cycle": -1, "cpu": 0.0, "memory": 0.0,
})
def _settle(self) -> None:
"""Moves the pretend services on to now. Called with the lock held."""
now = time.time()
t = now - self._began
cycle, in_cycle = int(t // self.SICK_EVERY), t % self.SICK_EVERY
sick_now = self.SICK_FROM <= in_cycle < self.SICK_FROM + self.SICK_FOR
fresh = now - self._settled >= 0.9
if fresh:
self._settled = now
for service in self._services:
if service["state"] == "restarting" and now >= service["restart_until"]:
service["state"], service["started"] = "running", now
if service["name"] == "photo-library":
if service["state"] == "running" and sick_now and service["skip_cycle"] != cycle:
service["state"] = "unhealthy"
elif service["state"] == "unhealthy" and not sick_now:
service["state"] = "running"
if not fresh:
continue
if service["state"] not in ("running", "unhealthy"):
service["cpu"] = service["memory"] = 0.0
continue
age = now - service["started"]
base, swing, phase = service["base_cpu"], service["swing"], service["phase"]
wave = 1 + swing * math.sin(t / service["period"] * 2 * math.pi + phase) + swing * 0.4 * math.sin(t / 3.1 + phase * 2)
cpu = base * wave * (0.85 + self._random.random() * 0.3)
if age < 8:
cpu += (base * 2.5 + 6) * (1 - age / 8) # starting up is work
if service["state"] == "unhealthy":
cpu = base * 4.5 + self._random.uniform(0, 14)
service["cpu"] = clamp(cpu, 0.1, 400)
service["memory"] = (service["base_memory"] * clamp(age / 20, 0.25, 1) * (1 + 0.05 * math.sin(t / 37 + phase))
* (1.3 if service["state"] == "unhealthy" else 1))
def _view(service: dict) -> dict:
alive = service["state"] in ("running", "unhealthy")
return {
"id": service["id"],
"name": service["name"],
"image": service["image"],
"state": service["state"],
"uptimeSeconds": int(time.time() - service["started"]) if alive else 0,
"cpuPercent": round(service["cpu"], 1),
"memoryBytes": int(service["memory"]),
"ports": list(service["ports"]),
"restarts": service["restarts"],
}
def list(self) -> list[dict]:
with self._lock:
self._settle()
return [self._view(service) for service in self._services]
def totals(self) -> tuple[float, float, float]:
"""(sum of CPU percent, sum of memory, CPU of the media server), for the simulated machine."""
with self._lock:
self._settle()
media = next(service["cpu"] for service in self._services if service["name"] == "media-server")
return sum(service["cpu"] for service in self._services), sum(service["memory"] for service in self._services), media
def act(self, requested: str, action: str) -> dict:
with self._lock:
self._settle()
service = next((candidate for candidate in self._services if candidate["id"] == requested), None)
if service is None or action not in ACTIONS:
raise UnknownService(requested)
now = time.time()
cycle = int((now - self._began) // self.SICK_EVERY)
if action == "restart" and service["state"] != "restarting":
service.update(state="restarting", restart_until=now + self.RESTART_SECONDS, restarts=service["restarts"] + 1,
skip_cycle=cycle, cpu=0.0, memory=0.0)
elif action == "stop":
service.update(state="stopped", cpu=0.0, memory=0.0)
elif action == "start" and service["state"] == "stopped":
service.update(state="running", started=now, skip_cycle=cycle)
return self._view(service)
class SimulatedHost:
CORES = 4
def __init__(self, services: SimulatedServices) -> None:
self._services = services
self._began = time.time()
self._booted = time.time() - (23 * 86400 + 6 * 3600 + 41 * 60)
def load(self) -> dict:
t = time.time() - self._began
cpu_sum, memory_sum, media = self._services.totals()
cpu = clamp(2.5 + cpu_sum / self.CORES + random.uniform(-0.6, 0.6), 0.5, 100)
base = cpu / 100 * self.CORES
return {
"hostname": "homelab",
"uptimeSeconds": int(time.time() - self._booted),
"load": [round(base * 1.08 + 0.12 + 0.05 * math.sin(t / 5), 2), round(0.52 + 0.06 * math.sin(t / 60), 2), round(0.47 + 0.03 * math.sin(t / 170), 2)],
"cpuPercent": round(cpu, 1),
"memory": {"used": int(1.25 * GB + memory_sum), "total": 8 * GB},
"disks": [
{"mount": "/", "used": int(21.4 * GB), "total": 59 * GB},
{"mount": "/mnt/tank", "used": int(2.61 * 1024 * GB + t * 2.2 * MB), "total": int(3.58 * 1024 * GB)},
{"mount": "/mnt/backup", "used": int(1.52 * 1024 * GB), "total": int(1.79 * 1024 * GB)},
],
"temperatureC": round(43 + cpu * 0.42 + 1.2 * math.sin(t / 23), 1),
"network": {
"rxBytesPerSec": int(clamp(520 * KB + cpu_sum * 12 * KB + 260 * KB * math.sin(t / 6) + 140 * KB * math.sin(t / 2.3) + random.uniform(0, 90 * KB), 4 * KB, 900 * MB)),
"txBytesPerSec": int(clamp(60 * KB + min(media, 40) * 70 * KB * (1 + 0.25 * math.sin(t / 4)) + random.uniform(0, 80 * KB), 4 * KB, 900 * MB)),
},
}
# --------------------------------------------------------------------------------------------------------
# HTTP
# --------------------------------------------------------------------------------------------------------
class Panel:
def __init__(self, host, services, simulated: bool, allow_actions: bool, verbose: bool) -> None:
self.host, self.services, self.simulated, self.allow_actions, self.verbose = host, services, simulated, allow_actions, verbose
class Handler(BaseHTTPRequestHandler):
server_version = "homelab-panel/1"
panel: Panel # set on the class by main()
def log_message(self, format: str, *args) -> None: # noqa: A002 (the name is http.server's)
if self.panel.verbose:
super().log_message(format, *args)
def _send(self, status: int, body: bytes, content_type: str) -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def _json(self, status: int, value: object) -> None:
self._send(status, json.dumps(value).encode("utf-8"), "application/json")
def _error(self, status: int, code: str, message: str) -> None:
self._json(status, {"error": code, "message": message})
def _file(self, name: str, content_type: str) -> None:
try:
self._send(200, (UI_FOLDER / name).read_bytes(), content_type)
except OSError:
self._error(404, "not-found", f"{name} is not in {UI_FOLDER}.")
def do_GET(self) -> None: # noqa: N802 (the name is http.server's)
path = urlsplit(self.path).path
try:
if path == "/load":
self._json(200, {**self.panel.host.load(), "simulated": self.panel.simulated})
elif path == "/services":
self._json(200, self.panel.services.list())
elif path == "/.cz/ui.json":
self._file("manifest.json", "application/json")
elif path in ("/.cz/ui.html", "/"):
self._file("homelab.html", "text/html; charset=utf-8")
else:
self._error(404, "not-found", "There is nothing at this path.")
except (BrokenPipeError, ConnectionError):
pass
except Exception as error: # a failed reading must not end the connection without an answer
self._error(500, "failed", str(error)[:200])
do_HEAD = do_GET # noqa: N815
def do_POST(self) -> None: # noqa: N802
length = int(self.headers.get("Content-Length") or 0)
if length > 0:
self.rfile.read(min(length, 65536)) # no action has a body; what was sent is dropped
match = ACTION_PATH.match(urlsplit(self.path).path)
if not match:
self._error(404, "not-found", "There is nothing at this path.")
return
# A web page open in a browser on this machine could post here. Browsers say where a request comes
# from; one from another site is refused. The Connectivitizer app and curl send no Origin.
origin = self.headers.get("Origin")
if origin and urlsplit(origin).netloc != (self.headers.get("Host") or ""):
self._error(403, "foreign-origin", "Requests from other sites are not accepted.")
return
if not self.panel.allow_actions:
self._error(403, "read-only", "The panel is in read-only mode. Start it with --allow-actions to restart, stop and start services.")
return
try:
self._json(200, self.panel.services.act(unquote(match.group(1)), match.group(2)))
except UnknownService:
self._error(404, "unknown-service", "There is no service with this id.")
except (ActionFailed, OSError, subprocess.TimeoutExpired) as error:
self._error(502, "action-failed", str(error)[:200])
def find_engine(wanted: str | None) -> str | None:
for name in ([wanted] if wanted else ["docker", "podman"]):
path = shutil.which(name)
if path:
return path
return None
def main() -> None:
parser = argparse.ArgumentParser(description="Home lab panel: the load of this machine and its containers, for the Connectivitizer app.")
parser.add_argument("--port", type=int, default=int(os.environ.get("HOMELAB_PORT", "8765")), help="the port on 127.0.0.1 (default 8765)")
parser.add_argument("--allow-actions", action="store_true", default=os.environ.get("HOMELAB_ALLOW_ACTIONS", "").lower() in ("1", "true", "yes"),
help="allow restart, stop and start (also HOMELAB_ALLOW_ACTIONS=1)")
parser.add_argument("--read-only", action="store_true", help="refuse restart, stop and start: the default, and stronger than --allow-actions")
parser.add_argument("--simulate", action="store_true", help="pretend machine and services, also on Linux")
parser.add_argument("--engine", choices=["docker", "podman"], default=os.environ.get("HOMELAB_ENGINE") or None, help="the container engine (default: the one that is installed)")
parser.add_argument("--verbose", action="store_true", help="log every request")
options = parser.parse_args()
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(line_buffering=True) # so the lines below show up at once in a log or journal
allow_actions = options.allow_actions and not options.read_only
on_linux = sys.platform.startswith("linux")
services = None
if on_linux and not options.simulate:
engine = find_engine(options.engine)
if engine:
try:
services = EngineServices(engine)
print(f"Services: from {engine}.")
except (ActionFailed, OSError, ValueError, subprocess.TimeoutExpired) as error:
print(f"Services: {engine} did not answer ({error}).")
simulated_services = services is None
if simulated_services:
services = SimulatedServices()
print("Services: SIMULATED (not Linux, --simulate, or no container engine). Nothing real is listed, restarted or stopped.")
if on_linux and not options.simulate:
host = LinuxHost()
print("Machine: from /proc.")
else:
# The pretend machine carries the load of pretend services, also when the real services are listed.
host = SimulatedHost(services if isinstance(services, SimulatedServices) else SimulatedServices())
print("Machine: SIMULATED (this is not Linux, or --simulate). The numbers are invented.")
simulated = simulated_services or isinstance(host, SimulatedHost)
Handler.panel = Panel(host, services, simulated, allow_actions, options.verbose)
server = ThreadingHTTPServer(("127.0.0.1", options.port), Handler)
server.daemon_threads = True
print(f"Actions: {'ALLOWED (restart, stop, start)' if allow_actions else 'read-only (start with --allow-actions to allow restart, stop, start)'}.")
print(f"Listening on http://127.0.0.1:{options.port} (the screen: http://127.0.0.1:{options.port}/.cz/ui.html)")
try:
server.serve_forever()
except KeyboardInterrupt:
print()
finally:
server.server_close()
if __name__ == "__main__":
main()