__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. # black keeps inserting a blank line above
  30. # https://pygobject.readthedocs.io/en/latest/getting_started.html#ubuntu-logo-ubuntu-debian-logo-debian
  31. import gi.repository.GLib # pylint-import-requirements: imports=PyGObject
  32. import paho.mqtt.client
  33. import systemctl_mqtt._dbus
  34. import systemctl_mqtt._homeassistant
  35. import systemctl_mqtt._mqtt
  36. _LOGGER = logging.getLogger(__name__)
  37. class _State:
  38. def __init__(
  39. self,
  40. mqtt_topic_prefix: str,
  41. homeassistant_discovery_prefix: str,
  42. homeassistant_node_id: str,
  43. ) -> None:
  44. self._mqtt_topic_prefix = mqtt_topic_prefix
  45. self._homeassistant_discovery_prefix = homeassistant_discovery_prefix
  46. self._homeassistant_node_id = homeassistant_node_id
  47. self._login_manager = (
  48. systemctl_mqtt._dbus.get_login_manager()
  49. ) # type: dbus.proxies.Interface
  50. self._shutdown_lock = None # type: typing.Optional[dbus.types.UnixFd]
  51. self._shutdown_lock_mutex = threading.Lock()
  52. @property
  53. def mqtt_topic_prefix(self) -> str:
  54. return self._mqtt_topic_prefix
  55. def acquire_shutdown_lock(self) -> None:
  56. with self._shutdown_lock_mutex:
  57. assert self._shutdown_lock is None
  58. # https://www.freedesktop.org/wiki/Software/systemd/inhibit/
  59. self._shutdown_lock = self._login_manager.Inhibit(
  60. "shutdown", "systemctl-mqtt", "Report shutdown via MQTT", "delay",
  61. )
  62. _LOGGER.debug("acquired shutdown inhibitor lock")
  63. def release_shutdown_lock(self) -> None:
  64. with self._shutdown_lock_mutex:
  65. if self._shutdown_lock:
  66. # https://dbus.freedesktop.org/doc/dbus-python/dbus.types.html#dbus.types.UnixFd.take
  67. os.close(self._shutdown_lock.take())
  68. _LOGGER.debug("released shutdown inhibitor lock")
  69. self._shutdown_lock = None
  70. @property
  71. def _preparing_for_shutdown_topic(self) -> str:
  72. return self.mqtt_topic_prefix + "/preparing-for-shutdown"
  73. def _publish_preparing_for_shutdown(
  74. self, mqtt_client: paho.mqtt.client.Client, active: bool, block: bool,
  75. ) -> None:
  76. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1199
  77. topic = self._preparing_for_shutdown_topic
  78. # pylint: disable=protected-access
  79. payload = systemctl_mqtt._mqtt.encode_bool(active)
  80. _LOGGER.info("publishing %r on %s", payload, topic)
  81. msg_info = mqtt_client.publish(
  82. topic=topic, payload=payload, retain=True,
  83. ) # type: paho.mqtt.client.MQTTMessageInfo
  84. if not block:
  85. return
  86. msg_info.wait_for_publish()
  87. if msg_info.rc != paho.mqtt.client.MQTT_ERR_SUCCESS:
  88. _LOGGER.error(
  89. "failed to publish on %s (return code %d)", topic, msg_info.rc
  90. )
  91. def _prepare_for_shutdown_handler(
  92. self, active: dbus.Boolean, mqtt_client: paho.mqtt.client.Client
  93. ) -> None:
  94. assert isinstance(active, dbus.Boolean)
  95. active = bool(active)
  96. self._publish_preparing_for_shutdown(
  97. mqtt_client=mqtt_client, active=active, block=True,
  98. )
  99. if active:
  100. self.release_shutdown_lock()
  101. else:
  102. self.acquire_shutdown_lock()
  103. def register_prepare_for_shutdown_handler(
  104. self, mqtt_client: paho.mqtt.client.Client
  105. ) -> None:
  106. self._login_manager.connect_to_signal(
  107. signal_name="PrepareForShutdown",
  108. handler_function=functools.partial(
  109. self._prepare_for_shutdown_handler, mqtt_client=mqtt_client
  110. ),
  111. )
  112. def publish_preparing_for_shutdown(
  113. self, mqtt_client: paho.mqtt.client.Client,
  114. ) -> None:
  115. try:
  116. active = self._login_manager.Get(
  117. "org.freedesktop.login1.Manager",
  118. "PreparingForShutdown",
  119. dbus_interface="org.freedesktop.DBus.Properties",
  120. )
  121. except dbus.DBusException as exc:
  122. _LOGGER.error(
  123. "failed to read logind's PreparingForShutdown property: %s",
  124. exc.get_dbus_message(),
  125. )
  126. return
  127. assert isinstance(active, dbus.Boolean), active
  128. self._publish_preparing_for_shutdown(
  129. mqtt_client=mqtt_client,
  130. active=bool(active),
  131. # https://github.com/eclipse/paho.mqtt.python/issues/439#issuecomment-565514393
  132. block=False,
  133. )
  134. def publish_preparing_for_shutdown_homeassistant_config(
  135. self, mqtt_client: paho.mqtt.client.Client
  136. ) -> None:
  137. # <discovery_prefix>/<component>/[<node_id>/]<object_id>/config
  138. # https://www.home-assistant.io/docs/mqtt/discovery/
  139. discovery_topic = "/".join(
  140. (
  141. self._homeassistant_discovery_prefix,
  142. "binary_sensor",
  143. self._homeassistant_node_id,
  144. "preparing-for-shutdown",
  145. "config",
  146. )
  147. )
  148. unique_id = "/".join(
  149. (
  150. "systemctl-mqtt",
  151. self._homeassistant_node_id,
  152. "logind",
  153. "preparing-for-shutdown",
  154. )
  155. )
  156. # https://www.home-assistant.io/integrations/binary_sensor.mqtt/#configuration-variables
  157. config = {
  158. "unique_id": unique_id,
  159. "state_topic": self._preparing_for_shutdown_topic,
  160. # pylint: disable=protected-access
  161. "payload_on": systemctl_mqtt._mqtt.encode_bool(True),
  162. "payload_off": systemctl_mqtt._mqtt.encode_bool(False),
  163. # friendly_name & template for default entity_id
  164. "name": "{} preparing for shutdown".format(self._homeassistant_node_id),
  165. }
  166. _LOGGER.debug("publishing home assistant config on %s", discovery_topic)
  167. mqtt_client.publish(
  168. topic=discovery_topic, payload=json.dumps(config), retain=True,
  169. )
  170. class _MQTTAction:
  171. # pylint: disable=too-few-public-methods
  172. def __init__(self, name: str, action: typing.Callable) -> None:
  173. self.name = name
  174. self.action = action
  175. def mqtt_message_callback(
  176. self,
  177. mqtt_client: paho.mqtt.client.Client,
  178. state: _State,
  179. message: paho.mqtt.client.MQTTMessage,
  180. ) -> None:
  181. # pylint: disable=unused-argument; callback
  182. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L3416
  183. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  184. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  185. if message.retain:
  186. _LOGGER.info("ignoring retained message")
  187. return
  188. _LOGGER.debug("executing action %s (%r)", self.name, self.action)
  189. self.action()
  190. _LOGGER.debug("completed action %s (%r)", self.name, self.action)
  191. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  192. "poweroff": _MQTTAction(
  193. name="poweroff",
  194. action=functools.partial(
  195. # pylint: disable=protected-access
  196. systemctl_mqtt._dbus.schedule_shutdown,
  197. action="poweroff",
  198. ),
  199. ),
  200. }
  201. def _mqtt_on_connect(
  202. mqtt_client: paho.mqtt.client.Client,
  203. state: _State,
  204. flags: typing.Dict,
  205. return_code: int,
  206. ) -> None:
  207. # pylint: disable=unused-argument; callback
  208. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  209. assert return_code == 0, return_code # connection accepted
  210. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  211. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  212. state.acquire_shutdown_lock()
  213. state.register_prepare_for_shutdown_handler(mqtt_client=mqtt_client)
  214. state.publish_preparing_for_shutdown(mqtt_client=mqtt_client)
  215. state.publish_preparing_for_shutdown_homeassistant_config(mqtt_client=mqtt_client)
  216. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  217. topic = state.mqtt_topic_prefix + "/" + topic_suffix
  218. _LOGGER.info("subscribing to %s", topic)
  219. mqtt_client.subscribe(topic)
  220. mqtt_client.message_callback_add(
  221. sub=topic, callback=action.mqtt_message_callback
  222. )
  223. _LOGGER.debug(
  224. "registered MQTT callback for topic %s triggering %r", topic, action.action
  225. )
  226. def _run(
  227. mqtt_host: str,
  228. mqtt_port: int,
  229. mqtt_username: typing.Optional[str],
  230. mqtt_password: typing.Optional[str],
  231. mqtt_topic_prefix: str,
  232. homeassistant_discovery_prefix: str,
  233. homeassistant_node_id: str,
  234. ) -> None:
  235. # pylint: disable=too-many-arguments
  236. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html#setting-up-an-event-loop
  237. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  238. # https://pypi.org/project/paho-mqtt/
  239. mqtt_client = paho.mqtt.client.Client(
  240. userdata=_State(
  241. mqtt_topic_prefix=mqtt_topic_prefix,
  242. homeassistant_discovery_prefix=homeassistant_discovery_prefix,
  243. homeassistant_node_id=homeassistant_node_id,
  244. )
  245. )
  246. mqtt_client.on_connect = _mqtt_on_connect
  247. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  248. _LOGGER.info(
  249. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  250. )
  251. if mqtt_username:
  252. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  253. elif mqtt_password:
  254. raise ValueError("Missing MQTT username")
  255. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  256. # loop_start runs loop_forever in a new thread (daemon)
  257. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1814
  258. # loop_forever attempts to reconnect if disconnected
  259. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L1744
  260. mqtt_client.loop_start()
  261. try:
  262. gi.repository.GLib.MainLoop().run()
  263. finally:
  264. # blocks until loop_forever stops
  265. _LOGGER.debug("waiting for MQTT loop to stop")
  266. mqtt_client.loop_stop()
  267. _LOGGER.debug("MQTT loop stopped")
  268. def _main() -> None:
  269. logging.basicConfig(
  270. level=logging.DEBUG,
  271. format="%(asctime)s:%(levelname)s:%(message)s",
  272. datefmt="%Y-%m-%dT%H:%M:%S%z",
  273. )
  274. argparser = argparse.ArgumentParser(
  275. description="MQTT client triggering & reporting shutdown on systemd-based systems",
  276. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  277. )
  278. argparser.add_argument("--mqtt-host", type=str, required=True)
  279. argparser.add_argument("--mqtt-port", type=int, default=8883)
  280. argparser.add_argument("--mqtt-username", type=str)
  281. password_argument_group = argparser.add_mutually_exclusive_group()
  282. password_argument_group.add_argument("--mqtt-password", type=str)
  283. password_argument_group.add_argument(
  284. "--mqtt-password-file",
  285. type=pathlib.Path,
  286. metavar="PATH",
  287. dest="mqtt_password_path",
  288. help="stripping trailing newline",
  289. )
  290. argparser.add_argument(
  291. "--mqtt-topic-prefix",
  292. type=str,
  293. # pylint: disable=protected-access
  294. default="systemctl/" + systemctl_mqtt._utils.get_hostname(),
  295. help=" ", # show default
  296. )
  297. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  298. argparser.add_argument(
  299. "--homeassistant-discovery-prefix", type=str, default="homeassistant", help=" ",
  300. )
  301. argparser.add_argument(
  302. "--homeassistant-node-id",
  303. type=str,
  304. # pylint: disable=protected-access
  305. default=systemctl_mqtt._homeassistant.get_default_node_id(),
  306. help=" ",
  307. )
  308. args = argparser.parse_args()
  309. if args.mqtt_password_path:
  310. # .read_text() replaces \r\n with \n
  311. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  312. if mqtt_password.endswith("\r\n"):
  313. mqtt_password = mqtt_password[:-2]
  314. elif mqtt_password.endswith("\n"):
  315. mqtt_password = mqtt_password[:-1]
  316. else:
  317. mqtt_password = args.mqtt_password
  318. # pylint: disable=protected-access
  319. if not systemctl_mqtt._homeassistant.validate_node_id(args.homeassistant_node_id):
  320. raise ValueError(
  321. "invalid home assistant node id {!r} (length >= 1, allowed characters: {})".format(
  322. args.homeassistant_node_id,
  323. # pylint: disable=protected-access
  324. systemctl_mqtt._homeassistant.NODE_ID_ALLOWED_CHARS,
  325. )
  326. + "\nchange --homeassistant-node-id"
  327. )
  328. _run(
  329. mqtt_host=args.mqtt_host,
  330. mqtt_port=args.mqtt_port,
  331. mqtt_username=args.mqtt_username,
  332. mqtt_password=mqtt_password,
  333. mqtt_topic_prefix=args.mqtt_topic_prefix,
  334. homeassistant_discovery_prefix=args.homeassistant_discovery_prefix,
  335. homeassistant_node_id=args.homeassistant_node_id,
  336. )