__init__.py 14 KB

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