Skip to content

Commit 7e8f381

Browse files
core: services: commander: Use shutdown for proper shutdown/reboot
Signed-off-by: Patrick José Pereira <[email protected]>
1 parent df0ef2c commit 7e8f381

File tree

1 file changed

+26
-20
lines changed

1 file changed

+26
-20
lines changed

core/services/commander/main.py

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
#! /usr/bin/env python3
22
import logging
33
import shutil
4+
import subprocess
45
from enum import Enum
56
from pathlib import Path
6-
from typing import Any, Callable
7+
from typing import Any
78

89
import appdirs
910
import uvicorn
@@ -34,6 +35,25 @@ class ShutdownType(str, Enum):
3435
POWEROFF = "poweroff"
3536

3637

38+
def run_command(command: str) -> "subprocess.CompletedProcess['bytes']":
39+
user = "pi"
40+
password = "raspberry"
41+
42+
return subprocess.run(
43+
[
44+
"sshpass",
45+
"-p",
46+
password,
47+
"ssh",
48+
"-o",
49+
"StrictHostKeyChecking=no",
50+
f"{user}@localhost",
51+
command,
52+
],
53+
check=True,
54+
)
55+
56+
3757
# TODO: Update commander to work with openapi modules and improve modularity and code organization
3858
@app.post("/shutdown", status_code=status.HTTP_200_OK)
3959
@version(1, 0)
@@ -44,27 +64,13 @@ async def shutdown(response: Response, shutdown_type: ShutdownType, i_know_what_
4464
detail="Developer, you don't know what you are doing, command aborted.",
4565
)
4666
try:
47-
# For more information about sysrq: https://www.kernel.org/doc/html/latest/admin-guide/sysrq.html
48-
## We enable all functions of sysrq to allow a safe reboot/shutdown
49-
# pylint: disable=consider-using-with
50-
open("/proc/sys/kernel/sysrq", "wb").write(b"1")
51-
52-
# We are doing it!
53-
# pylint: disable=consider-using-with
54-
run_sysrq_command: Callable[[str], int] = lambda command: open("/proc/sysrq-trigger", "wb").write(
55-
command.encode()
56-
)
57-
pre_commands = [
58-
"s", # Will attempt to sync all mounted filesystems.
59-
"u", # Will attempt to remount all mounted filesystems read-only. (To make sure that sync was done!)
60-
]
61-
for command in pre_commands:
62-
run_sysrq_command(command)
63-
67+
hold_time_seconds = 5
6468
if shutdown_type == ShutdownType.REBOOT:
65-
run_sysrq_command("b")
69+
output = run_command(f"(sleep {hold_time_seconds}; sudo shutdown --reboot -h now)&")
70+
logger.debug(f"reboot: {output}")
6671
elif shutdown_type == ShutdownType.POWEROFF:
67-
run_sysrq_command("o")
72+
output = run_command(f"(sleep {hold_time_seconds}; sudo shutdown --poweroff -h now)&")
73+
logger.debug(f"shutdown: {output}")
6874

6975
return HTMLResponse(status_code=200)
7076
except Exception as error:

0 commit comments

Comments
 (0)