__init__.py 15 KB

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