|
| 1 | +"""mekhenet - simple HTTP API to pass command from services to host via socket |
| 2 | +
|
| 3 | +curl --unix-socket /run/offspot/mekhenet.sock http://host/service-is-enabled/ssh |
| 4 | +""" |
| 5 | + |
| 6 | +import subprocess |
| 7 | +from pathlib import Path |
| 8 | +from typing import Annotated |
| 9 | + |
| 10 | +from fastapi import FastAPI |
| 11 | +from fastapi import Path as FastAPIPath |
| 12 | + |
| 13 | +allowed_toggle_actions = ("enable", "disable") |
| 14 | +allowed_services = ("ssh",) |
| 15 | +systemctl_path = Path("/usr/bin/systemctl") |
| 16 | + |
| 17 | +app = FastAPI() |
| 18 | + |
| 19 | + |
| 20 | +@app.get("/reboot/{after_seconds}") |
| 21 | +async def request_host_reboot( |
| 22 | + after_seconds: Annotated[ |
| 23 | + int, FastAPIPath(title="Nb. of seconds after which to reboot") |
| 24 | + ], |
| 25 | +): |
| 26 | + reboot = subprocess.run( |
| 27 | + [ |
| 28 | + str(systemctl_path), |
| 29 | + "reboot", |
| 30 | + "--when", |
| 31 | + f"+{after_seconds!s}s", |
| 32 | + ], |
| 33 | + check=False, |
| 34 | + ) |
| 35 | + return {"success": reboot.returncode == 0} |
| 36 | + |
| 37 | + |
| 38 | +@app.get("/toggle-service/{action}/{name}") |
| 39 | +async def request_service_toggle( |
| 40 | + action: Annotated[str, FastAPIPath(title="Action to use (enable/disable)")], |
| 41 | + name: Annotated[str, FastAPIPath(title="Name of service to toggle")], |
| 42 | +): |
| 43 | + if action not in allowed_toggle_actions: |
| 44 | + return { |
| 45 | + "success": False, |
| 46 | + "details": f"Forbidden action. Only {', '.join(allowed_toggle_actions)}", |
| 47 | + } |
| 48 | + if name not in allowed_services: |
| 49 | + return { |
| 50 | + "success": False, |
| 51 | + "details": "Forbidden service.", |
| 52 | + } |
| 53 | + toggle = subprocess.run( |
| 54 | + [str(systemctl_path), action, name], |
| 55 | + check=False, |
| 56 | + ) |
| 57 | + return {"success": toggle.returncode == 0} |
| 58 | + |
| 59 | + |
| 60 | +@app.get("/service-is-enabled/{name}") |
| 61 | +async def request_service_enabled( |
| 62 | + name: Annotated[str, FastAPIPath(title="Name of service to query")], |
| 63 | +): |
| 64 | + if name not in allowed_services: |
| 65 | + return { |
| 66 | + "success": False, |
| 67 | + "details": "Forbidden service.", |
| 68 | + } |
| 69 | + toggle = subprocess.run( |
| 70 | + [str(systemctl_path), "is-enabled", name], |
| 71 | + text=True, |
| 72 | + capture_output=True, |
| 73 | + check=False, |
| 74 | + ) |
| 75 | + if toggle.stdout.strip() in ("enabled", "disabled"): |
| 76 | + return {"success": True, "enabled": toggle.stdout.strip() == "enabled"} |
| 77 | + |
| 78 | + return {"success": False, "details": toggle.stdout.splitlines()[0].strip()} |
0 commit comments