aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/sleep.py
blob: c607cdab0ac4695e7df2f71463b8b48fde7818ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# deck-it - telling the tablet the PC is going to sleep
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""Tells the tablet the PC is about to sleep, shut down or reboot.

elogind announces a suspend with PrepareForSleep and a poweroff or reboot
with PrepareForShutdown on the system bus, and waits for either only while
someone holds a delay inhibitor (at most InhibitDelayMaxSec, 5 s by
default). deck-it holds one; on the announcement the server marks every
answer for SHOW seconds, so the tablet's next poll sees it, then lets the
inhibitor go. On resume, or a shutdown called off, it takes it again.
A shutdown also runs `deck-it stop` first, so the tunnels, wayvnc and the
headless output go cleanly; the next boot's login brings it all back.
"""

import ctypes
import os
import signal
import subprocess
import time
from pathlib import Path

SHOW = 2.0   # the tablet polls every second (0.5 s on the assistant tab)
WHY = {"PrepareForSleep": "asleep", "PrepareForShutdown": "shutting down"}
why = ""     # the server sends it to the tablet while set: "The PC is <why>"
STOP = [str(Path(__file__).resolve().parent.parent / "deck-it"), "stop"]


def _die_with_parent():
    # PR_SET_PDEATHSIG: a server that dies takes dbus-monitor with it.
    ctypes.CDLL(None, use_errno=True).prctl(1, signal.SIGTERM)


def _inhibit():
    # elogind-inhibit holds the lock while its command runs. The command
    # ends with the server (tail --pid), so a crashed server never leaves a
    # lock delaying every suspend; its own session, so letting go on purpose
    # kills the tail too.
    return subprocess.Popen(
        ["elogind-inhibit", "--what=sleep:shutdown", "--mode=delay", "--who=deck-it",
         "--why=Tell the tablet the PC is going to sleep or off",
         "tail", f"--pid={os.getpid()}", "-f", "/dev/null"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)


def _release(p):
    try:
        os.killpg(p.pid, signal.SIGTERM)
    except ProcessLookupError:
        pass
    p.wait()


def _stop():
    # Its own session: the stop kills this server, and must outlive it. The
    # wait is bounded, the inhibitor only holds the shutdown for 5 s.
    try:
        subprocess.Popen(STOP, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True).wait(timeout=2.5)
    except (OSError, subprocess.TimeoutExpired):
        pass


def watch():
    """Runs for the server's life; without elogind or dbus-monitor it does nothing."""
    global why
    rule = "type='signal',interface='org.freedesktop.login1.Manager',member='{}'"
    try:
        mon = subprocess.Popen(
            ["dbus-monitor", "--system", *(rule.format(m) for m in WHY)],
            stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
            preexec_fn=_die_with_parent)
        lock = _inhibit()
    except OSError:
        return
    member = ""
    for line in mon.stdout:
        line = line.strip()
        if line.startswith("signal "):
            member = next((m for m in WHY if f"member={m}" in line), "")
        elif line == "boolean true" and member:
            why = WHY[member]
            time.sleep(SHOW)
            if member == "PrepareForShutdown":
                _stop()
            _release(lock)
        elif line == "boolean false" and member:
            why = ""
            lock = _inhibit()