Power Button
In this section we'll add a power button to the Bitcoin Node Dashboard. Rather than allowing Apache to execute privileged commands directly, we'll create a small daemon that runs as root. The dashboard communicates with the daemon over a local Unix domain socket. The daemon performs the shutdown request on behalf of the dashboard, keeping the web server unprivileged.
The following files and directories will be used:
/usr/local/lib/shutdownd/shutdownd.py Shutdown daemon
/etc/systemd/system/shutdownd.service System service
/run/shutdownd.sock Unix domain socket
Connect to your Bitcoin node:
ssh nelson@bitcoin-node.local
Become superuser.
su -
Create the installation directory
mkdir -p /usr/local/lib/shutdownd
Create the daemon
nano /usr/local/lib/shutdownd/shutdownd.py
Paste the following:
#!/usr/bin/env python3
import os
import signal
import socket
import subprocess
import sys
SOCKET = "/run/shutdownd.sock"
POWEROFF = ["/usr/bin/systemctl", "poweroff"]
def cleanup(*args):
if os.path.exists(SOCKET):
os.remove(SOCKET)
sys.exit(0)
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGINT, cleanup)
if os.path.exists(SOCKET):
os.remove(SOCKET)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(SOCKET)
# root:www-data
os.chown(SOCKET, 0, 33)
os.chmod(SOCKET, 0o660)
server.listen()
while True:
conn, _ = server.accept()
with conn:
command = conn.recv(64).decode().strip()
if command == "shutdown":
conn.sendall(b"OK\n")
subprocess.Popen(POWEROFF)
else:
conn.sendall(b"DENIED\n")
Make the daemon executable.
chmod 755 /usr/local/lib/shutdownd/shutdownd.py
Create the system service
nano /etc/systemd/system/shutdownd.service
Paste the following:
[Unit]
Description=Shutdown request daemon
[Service]
Type=simple
ExecStart=/usr/local/lib/shutdownd/shutdownd.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
Enable the service
systemctl daemon-reload
systemctl enable shutdownd
systemctl start shutdownd
Check that the service is running.
systemctl status shutdownd
The service creates the socket:
/run/shutdownd.sock
The socket allows the dashboard to request a shutdown without giving Apache root privileges.
Configure the dashboard
The dashboard power button communicates with the daemon over the Unix domain socket.
When the button is pressed and confirmed, the dashboard sends:
shutdown
to:
/run/shutdownd.sock
If the daemon returns:
OK
the dashboard displays a Shutting down... page while the operating system performs an orderly shutdown.
Test the power button
Open the Bitcoin Node Dashboard in your browser.
Click the power button and confirm the shutdown.
The dashboard should display a message similar to:
Shutting down...
Bitcoin Core is being stopped safely.
Please wait until the computer has completely powered off
before disconnecting the power.
The node should then shut down cleanly. systemd will stop Bitcoin Core and the other running services before powering off the computer.