__init__.py 13 KB

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