__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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, block: 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, retain=True,
  137. ) # type: paho.mqtt.client.MQTTMessageInfo
  138. if not block:
  139. return
  140. msg_info.wait_for_publish()
  141. if msg_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  142. _LOGGER.error(
  143. "failed to publish on %s (return code %d)", topic, msg_info.rc
  144. )
  145. def _prepare_for_shutdown_handler(
  146. self, active: dbus.Boolean, mqtt_client: paho.mqtt.client.Client
  147. ) -> None:
  148. assert isinstance(active, dbus.Boolean)
  149. active = bool(active)
  150. self._publish_preparing_for_shutdown(
  151. mqtt_client=mqtt_client, active=active, block=True,
  152. )
  153. if active:
  154. self.release_shutdown_lock()
  155. else:
  156. self.acquire_shutdown_lock()
  157. def register_prepare_for_shutdown_handler(
  158. self, mqtt_client: paho.mqtt.client.Client
  159. ) -> None:
  160. self._login_manager.connect_to_signal(
  161. signal_name="PrepareForShutdown",
  162. handler_function=functools.partial(
  163. self._prepare_for_shutdown_handler, mqtt_client=mqtt_client
  164. ),
  165. )
  166. def publish_preparing_for_shutdown(
  167. self, mqtt_client: paho.mqtt.client.Client,
  168. ) -> None:
  169. try:
  170. active = self._login_manager.Get(
  171. "org.freedesktop.login1.Manager",
  172. "PreparingForShutdown",
  173. dbus_interface="org.freedesktop.DBus.Properties",
  174. )
  175. except dbus.DBusException as exc:
  176. _LOGGER.error(
  177. "failed to read logind's PreparingForShutdown property: %s",
  178. exc.get_dbus_message(),
  179. )
  180. return
  181. assert isinstance(active, dbus.Boolean), active
  182. self._publish_preparing_for_shutdown(
  183. mqtt_client=mqtt_client,
  184. active=bool(active),
  185. # https://github.com/eclipse/paho.mqtt.python/issues/439#issuecomment-565514393
  186. block=False,
  187. )
  188. class _MQTTAction:
  189. # pylint: disable=too-few-public-methods
  190. def __init__(self, name: str, action: typing.Callable) -> None:
  191. self.name = name
  192. self.action = action
  193. def mqtt_message_callback(
  194. self,
  195. mqtt_client: paho.mqtt.client.Client,
  196. state: _State,
  197. message: paho.mqtt.client.MQTTMessage,
  198. ) -> None:
  199. # pylint: disable=unused-argument; callback
  200. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L3416
  201. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  202. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  203. if message.retain:
  204. _LOGGER.info("ignoring retained message")
  205. return
  206. _LOGGER.debug("executing action %s (%r)", self.name, self.action)
  207. self.action()
  208. _LOGGER.debug("completed action %s (%r)", self.name, self.action)
  209. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  210. "poweroff": _MQTTAction(
  211. name="poweroff", action=functools.partial(_schedule_shutdown, action="poweroff")
  212. ),
  213. }
  214. def _mqtt_on_connect(
  215. mqtt_client: paho.mqtt.client.Client,
  216. state: _State,
  217. flags: typing.Dict,
  218. return_code: int,
  219. ) -> None:
  220. # pylint: disable=unused-argument; callback
  221. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  222. assert return_code == 0, return_code # connection accepted
  223. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  224. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  225. state.acquire_shutdown_lock()
  226. state.register_prepare_for_shutdown_handler(mqtt_client=mqtt_client)
  227. state.publish_preparing_for_shutdown(mqtt_client=mqtt_client)
  228. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  229. topic = state.mqtt_topic_prefix + "/" + topic_suffix
  230. _LOGGER.info("subscribing to %s", topic)
  231. mqtt_client.subscribe(topic)
  232. mqtt_client.message_callback_add(
  233. sub=topic, callback=action.mqtt_message_callback
  234. )
  235. _LOGGER.debug(
  236. "registered MQTT callback for topic %s triggering %r", topic, action.action
  237. )
  238. def _run(
  239. mqtt_host: str,
  240. mqtt_port: int,
  241. mqtt_username: typing.Optional[str],
  242. mqtt_password: typing.Optional[str],
  243. mqtt_topic_prefix: str,
  244. ) -> None:
  245. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html#setting-up-an-event-loop
  246. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  247. # https://pypi.org/project/paho-mqtt/
  248. mqtt_client = paho.mqtt.client.Client(
  249. userdata=_State(mqtt_topic_prefix=mqtt_topic_prefix)
  250. )
  251. mqtt_client.on_connect = _mqtt_on_connect
  252. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  253. _LOGGER.info(
  254. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  255. )
  256. if mqtt_username:
  257. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  258. elif mqtt_password:
  259. raise ValueError("Missing MQTT username")
  260. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  261. # loop_start runs loop_forever in a new thread (daemon)
  262. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1814
  263. # loop_forever attempts to reconnect if disconnected
  264. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1744
  265. mqtt_client.loop_start()
  266. try:
  267. gi.repository.GLib.MainLoop().run()
  268. finally:
  269. # blocks until loop_forever stops
  270. _LOGGER.debug("waiting for MQTT loop to stop")
  271. mqtt_client.loop_stop()
  272. _LOGGER.debug("MQTT loop stopped")
  273. def _get_hostname() -> str:
  274. return socket.gethostname()
  275. def _main() -> None:
  276. logging.basicConfig(
  277. level=logging.DEBUG,
  278. format="%(asctime)s:%(levelname)s:%(message)s",
  279. datefmt="%Y-%m-%dT%H:%M:%S%z",
  280. )
  281. argparser = argparse.ArgumentParser(
  282. description="MQTT client triggering & reporting shutdown on systemd-based systems",
  283. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  284. )
  285. argparser.add_argument("--mqtt-host", type=str, required=True)
  286. argparser.add_argument("--mqtt-port", type=int, default=8883)
  287. argparser.add_argument("--mqtt-username", type=str)
  288. password_argument_group = argparser.add_mutually_exclusive_group()
  289. password_argument_group.add_argument("--mqtt-password", type=str)
  290. password_argument_group.add_argument(
  291. "--mqtt-password-file",
  292. type=pathlib.Path,
  293. metavar="PATH",
  294. dest="mqtt_password_path",
  295. help="stripping trailing newline",
  296. )
  297. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  298. argparser.add_argument(
  299. "--mqtt-topic-prefix",
  300. type=str,
  301. default="systemctl/" + _get_hostname(),
  302. help=" ", # show default
  303. )
  304. args = argparser.parse_args()
  305. if args.mqtt_password_path:
  306. # .read_text() replaces \r\n with \n
  307. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  308. if mqtt_password.endswith("\r\n"):
  309. mqtt_password = mqtt_password[:-2]
  310. elif mqtt_password.endswith("\n"):
  311. mqtt_password = mqtt_password[:-1]
  312. else:
  313. mqtt_password = args.mqtt_password
  314. _run(
  315. mqtt_host=args.mqtt_host,
  316. mqtt_port=args.mqtt_port,
  317. mqtt_username=args.mqtt_username,
  318. mqtt_password=mqtt_password,
  319. mqtt_topic_prefix=args.mqtt_topic_prefix,
  320. )