__init__.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. # systemctl-mqtt - MQTT client triggering 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 argparse
  18. import datetime
  19. import functools
  20. import logging
  21. import pathlib
  22. import socket
  23. import typing
  24. import dbus
  25. import dbus.mainloop.glib
  26. # black keeps inserting a blank line above
  27. # https://pygobject.readthedocs.io/en/latest/getting_started.html#ubuntu-logo-ubuntu-debian-logo-debian
  28. import gi.repository.GLib # pylint-import-requirements: imports=PyGObject
  29. import paho.mqtt.client
  30. _LOGGER = logging.getLogger(__name__)
  31. _SHUTDOWN_DELAY = datetime.timedelta(seconds=4)
  32. def _get_login_manager() -> dbus.proxies.Interface:
  33. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html
  34. bus = dbus.SystemBus()
  35. proxy = bus.get_object(
  36. bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1"
  37. ) # type: dbus.proxies.ProxyObject
  38. # https://freedesktop.org/wiki/Software/systemd/logind/
  39. return dbus.Interface(object=proxy, dbus_interface="org.freedesktop.login1.Manager")
  40. def _log_shutdown_inhibitors(login_manager: dbus.proxies.Interface) -> None:
  41. if _LOGGER.getEffectiveLevel() > logging.DEBUG:
  42. return
  43. found_inhibitor = False
  44. try:
  45. # https://www.freedesktop.org/wiki/Software/systemd/inhibit/
  46. for what, who, why, mode, uid, pid in login_manager.ListInhibitors():
  47. if "shutdown" in what:
  48. found_inhibitor = True
  49. _LOGGER.debug(
  50. "detected shutdown inhibitor %s (pid=%u, uid=%u, mode=%s): %s",
  51. who,
  52. pid,
  53. uid,
  54. mode,
  55. why,
  56. )
  57. except dbus.DBusException as exc:
  58. _LOGGER.warning(
  59. "failed to fetch shutdown inhibitors: %s", exc.get_dbus_message()
  60. )
  61. return
  62. if not found_inhibitor:
  63. _LOGGER.debug("no shutdown inhibitor locks found")
  64. def _schedule_shutdown(action: str) -> None:
  65. # https://github.com/systemd/systemd/blob/v237/src/systemctl/systemctl.c#L8553
  66. assert action in ["poweroff", "reboot"], action
  67. shutdown_datetime = datetime.datetime.now() + _SHUTDOWN_DELAY
  68. # datetime.datetime.isoformat(timespec=) not available in python3.5
  69. # https://github.com/python/cpython/blob/v3.5.9/Lib/datetime.py#L1552
  70. _LOGGER.info(
  71. "scheduling %s for %s", action, shutdown_datetime.strftime("%Y-%m-%d %H:%M:%S"),
  72. )
  73. shutdown_epoch_usec = int(shutdown_datetime.timestamp() * 10 ** 6)
  74. login_manager = _get_login_manager()
  75. try:
  76. # $ gdbus introspect --system --dest org.freedesktop.login1 \
  77. # --object-path /org/freedesktop/login1 | grep -A 1 ScheduleShutdown
  78. # ScheduleShutdown(in s arg_0,
  79. # in t arg_1);
  80. # $ gdbus call --system --dest org.freedesktop.login1 \
  81. # --object-path /org/freedesktop/login1 \
  82. # --method org.freedesktop.login1.Manager.ScheduleShutdown \
  83. # poweroff "$(date --date=10min +%s)000000"
  84. # $ dbus-send --type=method_call --print-reply --system --dest=org.freedesktop.login1 \
  85. # /org/freedesktop/login1 \
  86. # org.freedesktop.login1.Manager.ScheduleShutdown \
  87. # string:poweroff "uint64:$(date --date=10min +%s)000000"
  88. login_manager.ScheduleShutdown(action, shutdown_epoch_usec)
  89. except dbus.DBusException as exc:
  90. exc_msg = exc.get_dbus_message()
  91. if "authentication required" in exc_msg.lower():
  92. _LOGGER.error(
  93. "failed to schedule %s: unauthorized; missing polkit authorization rules?",
  94. action,
  95. )
  96. else:
  97. _LOGGER.error("failed to schedule %s: %s", action, exc_msg)
  98. _log_shutdown_inhibitors(login_manager)
  99. class _Settings:
  100. # pylint: disable=too-few-public-methods
  101. def __init__(self, mqtt_topic_prefix: str) -> None:
  102. self._mqtt_topic_prefix = mqtt_topic_prefix
  103. @property
  104. def mqtt_topic_prefix(self) -> str:
  105. return self._mqtt_topic_prefix
  106. class _MQTTAction:
  107. # pylint: disable=too-few-public-methods
  108. def __init__(self, name: str, action: typing.Callable) -> None:
  109. self.name = name
  110. self.action = action
  111. def mqtt_message_callback(
  112. self,
  113. mqtt_client: paho.mqtt.client.Client,
  114. settings: _Settings,
  115. message: paho.mqtt.client.MQTTMessage,
  116. ) -> None:
  117. # pylint: disable=unused-argument; callback
  118. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L3416
  119. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  120. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  121. if message.retain:
  122. _LOGGER.info("ignoring retained message")
  123. return
  124. _LOGGER.debug("executing action %s (%r)", self.name, self.action)
  125. self.action()
  126. _LOGGER.debug("completed action %s (%r)", self.name, self.action)
  127. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  128. "poweroff": _MQTTAction(
  129. name="poweroff", action=functools.partial(_schedule_shutdown, action="poweroff")
  130. ),
  131. }
  132. def _mqtt_on_connect(
  133. mqtt_client: paho.mqtt.client.Client,
  134. settings: _Settings,
  135. flags: typing.Dict,
  136. return_code: int,
  137. ) -> None:
  138. # pylint: disable=unused-argument; callback
  139. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  140. assert return_code == 0, return_code # connection accepted
  141. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  142. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  143. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  144. topic = settings.mqtt_topic_prefix + "/" + topic_suffix
  145. _LOGGER.info("subscribing to %s", topic)
  146. mqtt_client.subscribe(topic)
  147. mqtt_client.message_callback_add(
  148. sub=topic, callback=action.mqtt_message_callback
  149. )
  150. _LOGGER.debug(
  151. "registered MQTT callback for topic %s triggering %r", topic, action.action
  152. )
  153. def _run(
  154. mqtt_host: str,
  155. mqtt_port: int,
  156. mqtt_username: typing.Optional[str],
  157. mqtt_password: typing.Optional[str],
  158. mqtt_topic_prefix: str,
  159. ) -> None:
  160. # https://pypi.org/project/paho-mqtt/
  161. mqtt_client = paho.mqtt.client.Client(
  162. userdata=_Settings(mqtt_topic_prefix=mqtt_topic_prefix)
  163. )
  164. mqtt_client.on_connect = _mqtt_on_connect
  165. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  166. _LOGGER.info(
  167. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  168. )
  169. if mqtt_username:
  170. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  171. elif mqtt_password:
  172. raise ValueError("Missing MQTT username")
  173. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  174. # loop_start runs loop_forever in a new thread (daemon)
  175. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1814
  176. # loop_forever attempts to reconnect if disconnected
  177. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1744
  178. mqtt_client.loop_start()
  179. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html#setting-up-an-event-loop
  180. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  181. try:
  182. gi.repository.GLib.MainLoop().run()
  183. finally:
  184. # blocks until loop_forever stops
  185. _LOGGER.debug("waiting for MQTT loop to stop")
  186. mqtt_client.loop_stop()
  187. _LOGGER.debug("MQTT loop stopped")
  188. def _get_hostname() -> str:
  189. return socket.gethostname()
  190. def _main() -> None:
  191. logging.basicConfig(
  192. level=logging.DEBUG,
  193. format="%(asctime)s:%(levelname)s:%(message)s",
  194. datefmt="%Y-%m-%dT%H:%M:%S%z",
  195. )
  196. argparser = argparse.ArgumentParser(
  197. description="MQTT client triggering shutdown on systemd-based systems",
  198. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  199. )
  200. argparser.add_argument("--mqtt-host", type=str, required=True)
  201. argparser.add_argument("--mqtt-port", type=int, default=8883)
  202. argparser.add_argument("--mqtt-username", type=str)
  203. password_argument_group = argparser.add_mutually_exclusive_group()
  204. password_argument_group.add_argument("--mqtt-password", type=str)
  205. password_argument_group.add_argument(
  206. "--mqtt-password-file",
  207. type=pathlib.Path,
  208. metavar="PATH",
  209. dest="mqtt_password_path",
  210. help="stripping trailing newline",
  211. )
  212. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  213. argparser.add_argument(
  214. "--mqtt-topic-prefix",
  215. type=str,
  216. default="systemctl/" + _get_hostname(),
  217. help=" ", # show default
  218. )
  219. args = argparser.parse_args()
  220. if args.mqtt_password_path:
  221. # .read_text() replaces \r\n with \n
  222. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  223. if mqtt_password.endswith("\r\n"):
  224. mqtt_password = mqtt_password[:-2]
  225. elif mqtt_password.endswith("\n"):
  226. mqtt_password = mqtt_password[:-1]
  227. else:
  228. mqtt_password = args.mqtt_password
  229. _run(
  230. mqtt_host=args.mqtt_host,
  231. mqtt_port=args.mqtt_port,
  232. mqtt_username=args.mqtt_username,
  233. mqtt_password=mqtt_password,
  234. mqtt_topic_prefix=args.mqtt_topic_prefix,
  235. )