_dbus.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 Suspend(self, *, interactive: bool) -> jeepney.low_level.Message:
  60. return jeepney.new_method_call(
  61. remote_obj=self, method="Suspend", signature="b", body=(interactive,)
  62. )
  63. def Inhibit(
  64. self, *, what: str, who: str, why: str, mode: str
  65. ) -> jeepney.low_level.Message:
  66. return jeepney.new_method_call(
  67. remote_obj=self,
  68. method="Inhibit",
  69. signature="ssss",
  70. body=(what, who, why, mode),
  71. )
  72. def Get(self, property_name: str) -> jeepney.low_level.Message:
  73. return jeepney.new_method_call(
  74. remote_obj=jeepney.DBusAddress(
  75. object_path=self.object_path,
  76. bus_name=self.bus_name,
  77. interface="org.freedesktop.DBus.Properties",
  78. ),
  79. method="Get",
  80. signature="ss",
  81. body=(self.interface, property_name),
  82. )
  83. def get_login_manager_proxy() -> jeepney.io.blocking.Proxy:
  84. # https://jeepney.readthedocs.io/en/latest/integrate.html
  85. # https://gitlab.com/takluyver/jeepney/-/blob/master/examples/aio_notify.py
  86. return jeepney.io.blocking.Proxy(
  87. msggen=LoginManager(),
  88. connection=jeepney.io.blocking.open_dbus_connection(
  89. bus="SYSTEM",
  90. # > dbus-broker[…]: Peer :1.… is being disconnected as it does not
  91. # . support receiving file descriptors it requested.
  92. enable_fds=True,
  93. ),
  94. )
  95. def _log_shutdown_inhibitors(login_manager_proxy: jeepney.io.blocking.Proxy) -> None:
  96. if _LOGGER.getEffectiveLevel() > logging.DEBUG:
  97. return
  98. found_inhibitor = False
  99. try:
  100. # https://www.freedesktop.org/wiki/Software/systemd/inhibit/
  101. (inhibitors,) = login_manager_proxy.ListInhibitors()
  102. for what, who, why, mode, uid, pid in inhibitors:
  103. if "shutdown" in what:
  104. found_inhibitor = True
  105. _LOGGER.debug(
  106. "detected shutdown inhibitor %s (pid=%u, uid=%u, mode=%s): %s",
  107. who,
  108. pid,
  109. uid,
  110. mode,
  111. why,
  112. )
  113. except jeepney.wrappers.DBusErrorResponse as exc:
  114. _LOGGER.warning("failed to fetch shutdown inhibitors: %s", exc)
  115. return
  116. if not found_inhibitor:
  117. _LOGGER.debug("no shutdown inhibitor locks found")
  118. def schedule_shutdown(*, action: str, delay: datetime.timedelta) -> None:
  119. # https://github.com/systemd/systemd/blob/v237/src/systemctl/systemctl.c#L8553
  120. assert action in ["poweroff", "reboot"], action
  121. time = datetime.datetime.now() + delay
  122. # datetime.datetime.isoformat(timespec=) not available in python3.5
  123. # https://github.com/python/cpython/blob/v3.5.9/Lib/datetime.py#L1552
  124. _LOGGER.info("scheduling %s for %s", action, time.strftime("%Y-%m-%d %H:%M:%S"))
  125. login_manager = get_login_manager_proxy()
  126. try:
  127. # $ gdbus introspect --system --dest org.freedesktop.login1 \
  128. # --object-path /org/freedesktop/login1 | grep -A 1 ScheduleShutdown
  129. # ScheduleShutdown(in s arg_0,
  130. # in t arg_1);
  131. # $ gdbus call --system --dest org.freedesktop.login1 \
  132. # --object-path /org/freedesktop/login1 \
  133. # --method org.freedesktop.login1.Manager.ScheduleShutdown \
  134. # poweroff "$(date --date=10min +%s)000000"
  135. # $ dbus-send --type=method_call --print-reply --system --dest=org.freedesktop.login1 \
  136. # /org/freedesktop/login1 \
  137. # org.freedesktop.login1.Manager.ScheduleShutdown \
  138. # string:poweroff "uint64:$(date --date=10min +%s)000000"
  139. login_manager.ScheduleShutdown(action=action, time=time)
  140. except jeepney.wrappers.DBusErrorResponse as exc:
  141. if (
  142. exc.name == "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired"
  143. and exc.data == ("Interactive authentication required.",)
  144. ):
  145. _LOGGER.error(
  146. "failed to schedule %s: unauthorized; missing polkit authorization rules?",
  147. action,
  148. )
  149. else:
  150. _LOGGER.error("failed to schedule %s: %s", action, exc)
  151. _log_shutdown_inhibitors(login_manager)
  152. def suspend() -> None:
  153. _LOGGER.info("suspending system")
  154. get_login_manager_proxy().Suspend(interactive=False)
  155. def lock_all_sessions() -> None:
  156. """
  157. $ loginctl lock-sessions
  158. """
  159. _LOGGER.info("instruct all sessions to activate screen locks")
  160. get_login_manager_proxy().LockSessions()