__init__.py 13 KB

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