_dbus.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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 dbus
  20. _LOGGER = logging.getLogger(__name__)
  21. _SHUTDOWN_DELAY = datetime.timedelta(seconds=4)
  22. def get_login_manager() -> dbus.proxies.Interface:
  23. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html
  24. bus = dbus.SystemBus()
  25. proxy = bus.get_object(
  26. bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1"
  27. ) # type: dbus.proxies.ProxyObject
  28. # https://freedesktop.org/wiki/Software/systemd/logind/
  29. return dbus.Interface(object=proxy, dbus_interface="org.freedesktop.login1.Manager")
  30. def _log_shutdown_inhibitors(login_manager: dbus.proxies.Interface) -> None:
  31. if _LOGGER.getEffectiveLevel() > logging.DEBUG:
  32. return
  33. found_inhibitor = False
  34. try:
  35. # https://www.freedesktop.org/wiki/Software/systemd/inhibit/
  36. for what, who, why, mode, uid, pid in login_manager.ListInhibitors():
  37. if "shutdown" in what:
  38. found_inhibitor = True
  39. _LOGGER.debug(
  40. "detected shutdown inhibitor %s (pid=%u, uid=%u, mode=%s): %s",
  41. who,
  42. pid,
  43. uid,
  44. mode,
  45. why,
  46. )
  47. except dbus.DBusException as exc:
  48. _LOGGER.warning(
  49. "failed to fetch shutdown inhibitors: %s", exc.get_dbus_message()
  50. )
  51. return
  52. if not found_inhibitor:
  53. _LOGGER.debug("no shutdown inhibitor locks found")
  54. def schedule_shutdown(action: str) -> None:
  55. # https://github.com/systemd/systemd/blob/v237/src/systemctl/systemctl.c#L8553
  56. assert action in ["poweroff", "reboot"], action
  57. shutdown_datetime = datetime.datetime.now() + _SHUTDOWN_DELAY
  58. # datetime.datetime.isoformat(timespec=) not available in python3.5
  59. # https://github.com/python/cpython/blob/v3.5.9/Lib/datetime.py#L1552
  60. _LOGGER.info(
  61. "scheduling %s for %s", action, shutdown_datetime.strftime("%Y-%m-%d %H:%M:%S"),
  62. )
  63. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html?highlight=signature#basic-types
  64. shutdown_epoch_usec = dbus.UInt64(shutdown_datetime.timestamp() * 10 ** 6)
  65. login_manager = get_login_manager()
  66. try:
  67. # $ gdbus introspect --system --dest org.freedesktop.login1 \
  68. # --object-path /org/freedesktop/login1 | grep -A 1 ScheduleShutdown
  69. # ScheduleShutdown(in s arg_0,
  70. # in t arg_1);
  71. # $ gdbus call --system --dest org.freedesktop.login1 \
  72. # --object-path /org/freedesktop/login1 \
  73. # --method org.freedesktop.login1.Manager.ScheduleShutdown \
  74. # poweroff "$(date --date=10min +%s)000000"
  75. # $ dbus-send --type=method_call --print-reply --system --dest=org.freedesktop.login1 \
  76. # /org/freedesktop/login1 \
  77. # org.freedesktop.login1.Manager.ScheduleShutdown \
  78. # string:poweroff "uint64:$(date --date=10min +%s)000000"
  79. login_manager.ScheduleShutdown(action, shutdown_epoch_usec)
  80. except dbus.DBusException as exc:
  81. exc_msg = exc.get_dbus_message()
  82. if "authentication required" in exc_msg.lower():
  83. _LOGGER.error(
  84. "failed to schedule %s: unauthorized; missing polkit authorization rules?",
  85. action,
  86. )
  87. else:
  88. _LOGGER.error("failed to schedule %s: %s", action, exc_msg)
  89. _log_shutdown_inhibitors(login_manager)