_dbus.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # systemctl-mqtt - MQTT client triggering & reporting shutdown on systemd-based systems
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import datetime
  18. import logging
  19. import jeepney
  20. import jeepney.io.blocking
  21. _LOGGER = logging.getLogger(__name__)
  22. _LOGIN_MANAGER_OBJECT_PATH = "/org/freedesktop/login1"
  23. _LOGIN_MANAGER_INTERFACE = "org.freedesktop.login1.Manager"
  24. def get_login_manager_signal_match_rule(member: str) -> jeepney.MatchRule:
  25. return jeepney.MatchRule(
  26. type="signal",
  27. interface=_LOGIN_MANAGER_INTERFACE,
  28. member=member,
  29. path=_LOGIN_MANAGER_OBJECT_PATH,
  30. )
  31. class LoginManager(jeepney.MessageGenerator):
  32. """
  33. https://freedesktop.org/wiki/Software/systemd/logind/
  34. $ python3 -m jeepney.bindgen \
  35. --bus unix:path=/var/run/dbus/system_bus_socket \
  36. --name org.freedesktop.login1 --path /org/freedesktop/login1
  37. """
  38. interface = _LOGIN_MANAGER_INTERFACE
  39. def __init__(self):
  40. super().__init__(
  41. object_path=_LOGIN_MANAGER_OBJECT_PATH, bus_name="org.freedesktop.login1"
  42. )
  43. # pylint: disable=invalid-name; inherited method names from Manager object
  44. def ListInhibitors(self) -> jeepney.low_level.Message:
  45. return jeepney.new_method_call(remote_obj=self, method="ListInhibitors")
  46. def LockSessions(self) -> jeepney.low_level.Message:
  47. return jeepney.new_method_call(remote_obj=self, method="LockSessions")
  48. def CanPowerOff(self) -> jeepney.low_level.Message:
  49. return jeepney.new_method_call(remote_obj=self, method="CanPowerOff")
  50. def ScheduleShutdown(
  51. self, *, action: str, time: datetime.datetime
  52. ) -> jeepney.low_level.Message:
  53. return jeepney.new_method_call(
  54. remote_obj=self,
  55. method="ScheduleShutdown",
  56. signature="st",
  57. body=(action, int(time.timestamp() * 1e6)), # (type, usec)
  58. )
  59. def Inhibit(
  60. self, *, what: str, who: str, why: str, mode: str
  61. ) -> jeepney.low_level.Message:
  62. return jeepney.new_method_call(
  63. remote_obj=self,
  64. method="Inhibit",
  65. signature="ssss",
  66. body=(what, who, why, mode),
  67. )
  68. def Get(self, property_name: str) -> jeepney.low_level.Message:
  69. return jeepney.new_method_call(
  70. remote_obj=jeepney.DBusAddress(
  71. object_path=self.object_path,
  72. bus_name=self.bus_name,
  73. interface="org.freedesktop.DBus.Properties",
  74. ),
  75. method="Get",
  76. signature="ss",
  77. body=(self.interface, property_name),
  78. )
  79. def get_login_manager_proxy() -> jeepney.io.blocking.Proxy:
  80. # https://jeepney.readthedocs.io/en/latest/integrate.html
  81. # https://gitlab.com/takluyver/jeepney/-/blob/master/examples/aio_notify.py
  82. return jeepney.io.blocking.Proxy(
  83. msggen=LoginManager(),
  84. connection=jeepney.io.blocking.open_dbus_connection(
  85. bus="SYSTEM",
  86. # > dbus-broker[…]: Peer :1.… is being disconnected as it does not
  87. # . support receiving file descriptors it requested.
  88. enable_fds=True,
  89. ),
  90. )
  91. def _log_shutdown_inhibitors(login_manager_proxy: jeepney.io.blocking.Proxy) -> None:
  92. if _LOGGER.getEffectiveLevel() > logging.DEBUG:
  93. return
  94. found_inhibitor = False
  95. try:
  96. # https://www.freedesktop.org/wiki/Software/systemd/inhibit/
  97. (inhibitors,) = login_manager_proxy.ListInhibitors()
  98. for what, who, why, mode, uid, pid in inhibitors:
  99. if "shutdown" in what:
  100. found_inhibitor = True
  101. _LOGGER.debug(
  102. "detected shutdown inhibitor %s (pid=%u, uid=%u, mode=%s): %s",
  103. who,
  104. pid,
  105. uid,
  106. mode,
  107. why,
  108. )
  109. except jeepney.wrappers.DBusErrorResponse as exc:
  110. _LOGGER.warning("failed to fetch shutdown inhibitors: %s", exc)
  111. return
  112. if not found_inhibitor:
  113. _LOGGER.debug("no shutdown inhibitor locks found")
  114. def schedule_shutdown(*, action: str, delay: datetime.timedelta) -> None:
  115. # https://github.com/systemd/systemd/blob/v237/src/systemctl/systemctl.c#L8553
  116. assert action in ["poweroff", "reboot"], action
  117. time = datetime.datetime.now() + delay
  118. # datetime.datetime.isoformat(timespec=) not available in python3.5
  119. # https://github.com/python/cpython/blob/v3.5.9/Lib/datetime.py#L1552
  120. _LOGGER.info("scheduling %s for %s", action, time.strftime("%Y-%m-%d %H:%M:%S"))
  121. login_manager = get_login_manager_proxy()
  122. try:
  123. # $ gdbus introspect --system --dest org.freedesktop.login1 \
  124. # --object-path /org/freedesktop/login1 | grep -A 1 ScheduleShutdown
  125. # ScheduleShutdown(in s arg_0,
  126. # in t arg_1);
  127. # $ gdbus call --system --dest org.freedesktop.login1 \
  128. # --object-path /org/freedesktop/login1 \
  129. # --method org.freedesktop.login1.Manager.ScheduleShutdown \
  130. # poweroff "$(date --date=10min +%s)000000"
  131. # $ dbus-send --type=method_call --print-reply --system --dest=org.freedesktop.login1 \
  132. # /org/freedesktop/login1 \
  133. # org.freedesktop.login1.Manager.ScheduleShutdown \
  134. # string:poweroff "uint64:$(date --date=10min +%s)000000"
  135. login_manager.ScheduleShutdown(action=action, time=time)
  136. except jeepney.wrappers.DBusErrorResponse as exc:
  137. if (
  138. exc.name == "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired"
  139. and exc.data == ("Interactive authentication required.",)
  140. ):
  141. _LOGGER.error(
  142. "failed to schedule %s: unauthorized; missing polkit authorization rules?",
  143. action,
  144. )
  145. else:
  146. _LOGGER.error("failed to schedule %s: %s", action, exc)
  147. _log_shutdown_inhibitors(login_manager)
  148. def lock_all_sessions() -> None:
  149. """
  150. $ loginctl lock-sessions
  151. """
  152. _LOGGER.info("instruct all sessions to activate screen locks")
  153. get_login_manager_proxy().LockSessions()