__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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 asyncio
  20. import datetime
  21. import functools
  22. import importlib.metadata
  23. import json
  24. import logging
  25. import os
  26. import pathlib
  27. import socket
  28. import ssl
  29. import threading
  30. import typing
  31. import aiomqtt
  32. import jeepney
  33. import jeepney.bus_messages
  34. import jeepney.io.asyncio
  35. import systemctl_mqtt._dbus.login_manager
  36. import systemctl_mqtt._dbus.service_manager
  37. import systemctl_mqtt._homeassistant
  38. import systemctl_mqtt._mqtt
  39. _MQTT_DEFAULT_PORT = 1883
  40. _MQTT_DEFAULT_TLS_PORT = 8883
  41. # > payload_not_available string (Optional, default: offline)
  42. # https://web.archive.org/web/20250101075341/https://www.home-assistant.io/integrations/sensor.mqtt/#payload_not_available
  43. _MQTT_PAYLOAD_NOT_AVAILABLE = "offline"
  44. _MQTT_PAYLOAD_AVAILABLE = "online"
  45. # https://www.home-assistant.io/integrations/mqtt/#birth-and-last-will-messages
  46. _HOMEASSISTANT_BIRTH_TOPIC = "homeassistant/status"
  47. _HOMEASSISTANT_BIRTH_PAYLOAD = b"online"
  48. _ARGUMENT_LOG_LEVEL_MAPPING = {
  49. a: getattr(logging, a.upper())
  50. for a in ("debug", "info", "warning", "error", "critical")
  51. }
  52. _LOGGER = logging.getLogger(__name__)
  53. class _State:
  54. # pylint: disable=too-many-instance-attributes
  55. def __init__( # pylint: disable=too-many-arguments
  56. self,
  57. *,
  58. mqtt_topic_prefix: str,
  59. homeassistant_discovery_prefix: str,
  60. homeassistant_discovery_object_id: str,
  61. poweroff_delay: datetime.timedelta,
  62. monitored_system_unit_names: list[str],
  63. controlled_system_unit_names: list[str],
  64. ) -> None:
  65. self._mqtt_topic_prefix = mqtt_topic_prefix
  66. self._homeassistant_discovery_prefix = homeassistant_discovery_prefix
  67. self._homeassistant_discovery_object_id = homeassistant_discovery_object_id
  68. self._login_manager = (
  69. systemctl_mqtt._dbus.login_manager.get_login_manager_proxy()
  70. )
  71. self._shutdown_lock: jeepney.fds.FileDescriptor | None = None
  72. self._shutdown_lock_mutex = threading.Lock()
  73. self.poweroff_delay = poweroff_delay
  74. self._monitored_system_unit_names = monitored_system_unit_names
  75. self._controlled_system_unit_names = controlled_system_unit_names
  76. @property
  77. def mqtt_topic_prefix(self) -> str:
  78. return self._mqtt_topic_prefix
  79. @property
  80. def mqtt_availability_topic(self) -> str:
  81. # > mqtt.ATTR_TOPIC: "homeassistant/status",
  82. # https://github.com/home-assistant/core/blob/2024.12.5/tests/components/mqtt/conftest.py#L23
  83. # > _MQTT_AVAILABILITY_TOPIC = "switchbot-mqtt/status"
  84. # https://github.com/fphammerle/switchbot-mqtt/blob/v3.3.1/switchbot_mqtt/__init__.py#L30
  85. return self._mqtt_topic_prefix + "/status"
  86. def get_system_unit_active_state_mqtt_topic(self, *, unit_name: str) -> str:
  87. return self._mqtt_topic_prefix + "/unit/system/" + unit_name + "/active-state"
  88. def get_system_unit_action_mqtt_topic(
  89. self, *, unit_name: str, action_name: str
  90. ) -> str:
  91. return self._mqtt_topic_prefix + "/unit/system/" + unit_name + "/" + action_name
  92. @property
  93. def monitored_system_unit_names(self) -> list[str]:
  94. return self._monitored_system_unit_names
  95. @property
  96. def controlled_system_unit_names(self) -> list[str]:
  97. return self._controlled_system_unit_names
  98. @property
  99. def shutdown_lock_acquired(self) -> bool:
  100. return self._shutdown_lock is not None
  101. def acquire_shutdown_lock(self) -> None:
  102. with self._shutdown_lock_mutex:
  103. assert self._shutdown_lock is None
  104. # https://www.freedesktop.org/wiki/Software/systemd/inhibit/
  105. (self._shutdown_lock,) = self._login_manager.Inhibit(
  106. what="shutdown",
  107. who="systemctl-mqtt",
  108. why="Report shutdown via MQTT",
  109. mode="delay",
  110. )
  111. assert isinstance(
  112. self._shutdown_lock, jeepney.fds.FileDescriptor
  113. ), self._shutdown_lock
  114. _LOGGER.debug("acquired shutdown inhibitor lock")
  115. def release_shutdown_lock(self) -> None:
  116. with self._shutdown_lock_mutex:
  117. if self._shutdown_lock:
  118. self._shutdown_lock.close()
  119. _LOGGER.debug("released shutdown inhibitor lock")
  120. self._shutdown_lock = None
  121. @property
  122. def _preparing_for_shutdown_topic(self) -> str:
  123. return self.mqtt_topic_prefix + "/preparing-for-shutdown"
  124. async def _publish_preparing_for_shutdown(
  125. self, *, mqtt_client: aiomqtt.Client, active: bool
  126. ) -> None:
  127. topic = self._preparing_for_shutdown_topic
  128. # pylint: disable=protected-access
  129. payload = systemctl_mqtt._mqtt.encode_bool(active)
  130. _LOGGER.info("publishing %r on %s", payload, topic)
  131. await mqtt_client.publish(topic=topic, payload=payload, retain=False)
  132. async def preparing_for_shutdown_handler(
  133. self, active: bool, mqtt_client: aiomqtt.Client
  134. ) -> None:
  135. active = bool(active)
  136. await self._publish_preparing_for_shutdown(
  137. mqtt_client=mqtt_client, active=active
  138. )
  139. if active:
  140. self.release_shutdown_lock()
  141. else:
  142. self.acquire_shutdown_lock()
  143. async def publish_preparing_for_shutdown(self, mqtt_client: aiomqtt.Client) -> None:
  144. try:
  145. ((return_type, active),) = self._login_manager.Get("PreparingForShutdown")
  146. except jeepney.wrappers.DBusErrorResponse as exc:
  147. _LOGGER.error(
  148. "failed to read logind's PreparingForShutdown property: %s", exc
  149. )
  150. return
  151. assert return_type == "b", return_type
  152. assert isinstance(active, bool), active
  153. await self._publish_preparing_for_shutdown(
  154. mqtt_client=mqtt_client, active=active
  155. )
  156. async def publish_homeassistant_device_config(
  157. self, mqtt_client: aiomqtt.Client
  158. ) -> None:
  159. # <discovery_prefix>/<component>/[<node_id>/]<object_id>/config
  160. # https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
  161. discovery_topic = "/".join(
  162. (
  163. self._homeassistant_discovery_prefix,
  164. "device",
  165. self._homeassistant_discovery_object_id,
  166. "config",
  167. )
  168. )
  169. hostname = (
  170. # pylint: disable=protected-access; function in internal module
  171. systemctl_mqtt._utils.get_hostname()
  172. )
  173. package_metadata = importlib.metadata.metadata(__name__)
  174. unique_id_prefix = "systemctl-mqtt-" + hostname
  175. config = {
  176. "device": {"identifiers": [hostname], "name": hostname},
  177. "origin": {
  178. "name": package_metadata["Name"],
  179. "sw_version": package_metadata["Version"],
  180. "support_url": package_metadata["Home-page"],
  181. },
  182. "availability": {"topic": self.mqtt_availability_topic},
  183. "components": {
  184. "logind/preparing-for-shutdown": {
  185. "unique_id": unique_id_prefix + "-logind-preparing-for-shutdown",
  186. "object_id": f"{hostname}_logind_preparing_for_shutdown", # entity id
  187. "name": "preparing for shutdown", # home assistant prepends device name
  188. "platform": "binary_sensor",
  189. "state_topic": self._preparing_for_shutdown_topic,
  190. # pylint: disable=protected-access
  191. "payload_on": systemctl_mqtt._mqtt.encode_bool(True),
  192. "payload_off": systemctl_mqtt._mqtt.encode_bool(False),
  193. },
  194. },
  195. }
  196. for mqtt_topic_suffix in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.keys():
  197. # false positive warning by mypy:
  198. # > Unsupported target for indexed assignment
  199. config["components"]["logind/" + mqtt_topic_suffix] = { # type: ignore
  200. "unique_id": unique_id_prefix + "-logind-" + mqtt_topic_suffix,
  201. "object_id": hostname
  202. + "_logind_"
  203. + mqtt_topic_suffix.replace("-", "_"), # entity id
  204. "name": mqtt_topic_suffix.replace("-", " "),
  205. "platform": "button",
  206. "command_topic": self.mqtt_topic_prefix + "/" + mqtt_topic_suffix,
  207. }
  208. for unit_name in self._monitored_system_unit_names:
  209. config["components"]["unit/system/" + unit_name + "/active-state"] = { # type: ignore
  210. "unique_id": f"{unique_id_prefix}-unit-system-{unit_name}-active-state",
  211. "object_id": f"{hostname}_unit_system_{unit_name}_active_state",
  212. "name": f"{unit_name} active state",
  213. "platform": "sensor",
  214. "state_topic": self.get_system_unit_active_state_mqtt_topic(
  215. unit_name=unit_name
  216. ),
  217. }
  218. for unit_name in self._controlled_system_unit_names:
  219. component_prefix = "unit/system/" + unit_name
  220. for action_name, action_class in [
  221. ("start", _MQTTActionStartUnit),
  222. ("stop", _MQTTActionStopUnit),
  223. ("restart", _MQTTActionRestartUnit),
  224. ("isolate", _MQTTActionIsolateUnit),
  225. ]:
  226. if action_class(unit_name).is_allowed():
  227. config["components"][component_prefix + "/" + action_name] = { # type: ignore
  228. "unique_id": f"{unique_id_prefix}-unit-system-{unit_name}-{action_name}",
  229. "object_id": f"{hostname}_unit_system_{unit_name}_{action_name}",
  230. "name": f"{unit_name} {action_name}",
  231. "platform": "button",
  232. "command_topic": self.get_system_unit_action_mqtt_topic(
  233. unit_name=unit_name, action_name=action_name
  234. ),
  235. }
  236. _LOGGER.debug("publishing home assistant config on %s", discovery_topic)
  237. await mqtt_client.publish(
  238. topic=discovery_topic, payload=json.dumps(config), retain=False
  239. )
  240. class _MQTTAction(metaclass=abc.ABCMeta):
  241. def is_allowed(self) -> bool:
  242. return True
  243. @abc.abstractmethod
  244. def trigger(self, state: _State) -> None:
  245. pass # pragma: no cover
  246. def __str__(self) -> str:
  247. return type(self).__name__
  248. class _MQTTActionSchedulePoweroff(_MQTTAction):
  249. # pylint: disable=too-few-public-methods
  250. def trigger(self, state: _State) -> None:
  251. # pylint: disable=protected-access
  252. systemctl_mqtt._dbus.login_manager.schedule_shutdown(
  253. action="poweroff", delay=state.poweroff_delay
  254. )
  255. class _MQTTActionStartUnit(_MQTTAction):
  256. # pylint: disable=protected-access,too-few-public-methods
  257. def __init__(self, unit_name: str):
  258. self._unit_name = unit_name
  259. def trigger(self, state: _State) -> None:
  260. systemctl_mqtt._dbus.service_manager.start_unit(unit_name=self._unit_name)
  261. class _MQTTActionStopUnit(_MQTTAction):
  262. # pylint: disable=protected-access,too-few-public-methods
  263. def __init__(self, unit_name: str):
  264. self._unit_name = unit_name
  265. def trigger(self, state: _State) -> None:
  266. systemctl_mqtt._dbus.service_manager.stop_unit(unit_name=self._unit_name)
  267. class _MQTTActionRestartUnit(_MQTTAction):
  268. # pylint: disable=protected-access,too-few-public-methods
  269. def __init__(self, unit_name: str):
  270. self._unit_name = unit_name
  271. def trigger(self, state: _State) -> None:
  272. systemctl_mqtt._dbus.service_manager.restart_unit(unit_name=self._unit_name)
  273. class _MQTTActionIsolateUnit(_MQTTAction):
  274. # pylint: disable=protected-access,too-few-public-methods
  275. def __init__(self, unit_name: str):
  276. self._unit_name = unit_name
  277. def is_allowed(self) -> bool:
  278. return systemctl_mqtt._dbus.service_manager.is_isolate_unit_allowed(
  279. unit_name=self._unit_name
  280. )
  281. def trigger(self, state: _State) -> None:
  282. systemctl_mqtt._dbus.service_manager.isolate_unit(unit_name=self._unit_name)
  283. class _MQTTActionLockAllSessions(_MQTTAction):
  284. # pylint: disable=too-few-public-methods
  285. def trigger(self, state: _State) -> None:
  286. # pylint: disable=protected-access
  287. systemctl_mqtt._dbus.login_manager.lock_all_sessions()
  288. class _MQTTActionSuspend(_MQTTAction):
  289. # pylint: disable=too-few-public-methods
  290. def trigger(self, state: _State) -> None:
  291. # pylint: disable=protected-access
  292. systemctl_mqtt._dbus.login_manager.suspend()
  293. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  294. "poweroff": _MQTTActionSchedulePoweroff(),
  295. "lock-all-sessions": _MQTTActionLockAllSessions(),
  296. "suspend": _MQTTActionSuspend(),
  297. }
  298. async def _mqtt_message_loop(*, state: _State, mqtt_client: aiomqtt.Client) -> None:
  299. _LOGGER.info("subscribing to %s", _HOMEASSISTANT_BIRTH_TOPIC)
  300. await mqtt_client.subscribe(_HOMEASSISTANT_BIRTH_TOPIC)
  301. action_by_topic: dict[str, _MQTTAction] = {}
  302. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  303. topic = state.mqtt_topic_prefix + "/" + topic_suffix
  304. _LOGGER.info("subscribing to %s", topic)
  305. await mqtt_client.subscribe(topic)
  306. action_by_topic[topic] = action
  307. for unit_name in state.controlled_system_unit_names:
  308. for topic_suffix, action_class in [
  309. ("start", _MQTTActionStartUnit),
  310. ("stop", _MQTTActionStopUnit),
  311. ("restart", _MQTTActionRestartUnit),
  312. ("isolate", _MQTTActionIsolateUnit),
  313. ]:
  314. topic = (
  315. state.mqtt_topic_prefix
  316. + "/unit/system/"
  317. + unit_name
  318. + "/"
  319. + topic_suffix
  320. )
  321. _LOGGER.info("subscribing to %s", topic)
  322. await mqtt_client.subscribe(topic)
  323. action_by_topic[topic] = action_class(unit_name=unit_name)
  324. async for message in mqtt_client.messages:
  325. if message.retain:
  326. _LOGGER.info("ignoring retained message on topic %r", message.topic.value)
  327. elif message.topic.value == _HOMEASSISTANT_BIRTH_TOPIC:
  328. _LOGGER.debug("received homeassistant status: %r", message.payload)
  329. if message.payload == _HOMEASSISTANT_BIRTH_PAYLOAD:
  330. await state.publish_homeassistant_device_config(mqtt_client=mqtt_client)
  331. else:
  332. _LOGGER.debug(
  333. "received message on topic %r: %r", message.topic.value, message.payload
  334. )
  335. action_by_topic[message.topic.value].trigger(state=state)
  336. async def _dbus_signal_loop_preparing_for_shutdown(
  337. *,
  338. state: _State,
  339. mqtt_client: aiomqtt.Client,
  340. dbus_router: jeepney.io.asyncio.DBusRouter,
  341. bus_proxy: jeepney.io.asyncio.Proxy,
  342. ) -> None:
  343. preparing_for_shutdown_match_rule = (
  344. # pylint: disable=protected-access
  345. systemctl_mqtt._dbus.login_manager.get_login_manager_signal_match_rule(
  346. "PrepareForShutdown"
  347. )
  348. )
  349. assert await bus_proxy.AddMatch(preparing_for_shutdown_match_rule) == ()
  350. with dbus_router.filter(preparing_for_shutdown_match_rule) as queue:
  351. while True:
  352. message: jeepney.low_level.Message = await queue.get()
  353. (preparing_for_shutdown,) = message.body
  354. await state.preparing_for_shutdown_handler(
  355. active=preparing_for_shutdown, mqtt_client=mqtt_client
  356. )
  357. queue.task_done()
  358. async def _get_unit_path(
  359. *, service_manager: jeepney.io.asyncio.Proxy, unit_name: str
  360. ) -> str:
  361. (path,) = await service_manager.GetUnit(name=unit_name)
  362. return path
  363. async def _dbus_signal_loop_unit( # pylint: disable=too-many-arguments
  364. *,
  365. state: _State,
  366. mqtt_client: aiomqtt.Client,
  367. dbus_router: jeepney.io.asyncio.DBusRouter,
  368. bus_proxy: jeepney.io.asyncio.Proxy,
  369. unit_name: str,
  370. unit_path: str,
  371. ) -> None:
  372. unit_proxy = jeepney.io.asyncio.Proxy(
  373. # pylint: disable=protected-access
  374. msggen=systemctl_mqtt._dbus.service_manager.Unit(object_path=unit_path),
  375. router=dbus_router,
  376. )
  377. unit_properties_changed_match_rule = jeepney.MatchRule(
  378. type="signal",
  379. interface="org.freedesktop.DBus.Properties",
  380. member="PropertiesChanged",
  381. path=unit_path,
  382. )
  383. assert (await bus_proxy.AddMatch(unit_properties_changed_match_rule)) == ()
  384. # > Table 1. Unit ACTIVE states …
  385. # > active Started, bound, plugged in, …
  386. # > inactive Stopped, unbound, unplugged, …
  387. # > failed … process returned error code on exit, crashed, an operation
  388. # . timed out, or after too many restarts).
  389. # > activating Changing from inactive to active.
  390. # > deactivating Changing from active to inactive.
  391. # > maintenance Unit is inactive and … maintenance … in progress.
  392. # > reloading Unit is active and it is reloading its configuration.
  393. # > refreshing Unit is active and a new mount is being activated in its
  394. # . namespace.
  395. # https://web.archive.org/web/20250101121304/https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.systemd1.html
  396. active_state_topic = state.get_system_unit_active_state_mqtt_topic(
  397. unit_name=unit_name
  398. )
  399. ((_, last_active_state),) = await unit_proxy.Get(property_name="ActiveState")
  400. await mqtt_client.publish(topic=active_state_topic, payload=last_active_state)
  401. with dbus_router.filter(unit_properties_changed_match_rule) as queue:
  402. while True:
  403. await queue.get()
  404. ((_, current_active_state),) = await unit_proxy.Get(
  405. property_name="ActiveState"
  406. )
  407. if current_active_state != last_active_state:
  408. await mqtt_client.publish(
  409. topic=active_state_topic, payload=current_active_state
  410. )
  411. last_active_state = current_active_state
  412. queue.task_done()
  413. async def _dbus_signal_loop(*, state: _State, mqtt_client: aiomqtt.Client) -> None:
  414. async with jeepney.io.asyncio.open_dbus_router(bus="SYSTEM") as router:
  415. # router: jeepney.io.asyncio.DBusRouter
  416. bus_proxy = jeepney.io.asyncio.Proxy(
  417. msggen=jeepney.bus_messages.message_bus, router=router
  418. )
  419. system_service_manager = jeepney.io.asyncio.Proxy(
  420. # pylint: disable=protected-access
  421. msggen=systemctl_mqtt._dbus.service_manager.ServiceManager(),
  422. router=router,
  423. )
  424. await asyncio.gather(
  425. *[
  426. _dbus_signal_loop_preparing_for_shutdown(
  427. state=state,
  428. mqtt_client=mqtt_client,
  429. dbus_router=router,
  430. bus_proxy=bus_proxy,
  431. )
  432. ]
  433. + [
  434. _dbus_signal_loop_unit(
  435. state=state,
  436. mqtt_client=mqtt_client,
  437. dbus_router=router,
  438. bus_proxy=bus_proxy,
  439. unit_name=unit_name,
  440. unit_path=await _get_unit_path(
  441. service_manager=system_service_manager, unit_name=unit_name
  442. ),
  443. )
  444. for unit_name in state.monitored_system_unit_names
  445. ],
  446. return_exceptions=False,
  447. )
  448. async def _run( # pylint: disable=too-many-arguments
  449. *,
  450. mqtt_host: str,
  451. mqtt_port: int,
  452. mqtt_username: str | None,
  453. mqtt_password: str | None,
  454. mqtt_topic_prefix: str,
  455. homeassistant_discovery_prefix: str,
  456. homeassistant_discovery_object_id: str,
  457. poweroff_delay: datetime.timedelta,
  458. monitored_system_unit_names: list[str],
  459. controlled_system_unit_names: list[str],
  460. mqtt_disable_tls: bool = False,
  461. ) -> None:
  462. state = _State(
  463. mqtt_topic_prefix=mqtt_topic_prefix,
  464. homeassistant_discovery_prefix=homeassistant_discovery_prefix,
  465. homeassistant_discovery_object_id=homeassistant_discovery_object_id,
  466. poweroff_delay=poweroff_delay,
  467. monitored_system_unit_names=monitored_system_unit_names,
  468. controlled_system_unit_names=controlled_system_unit_names,
  469. )
  470. _LOGGER.info(
  471. "connecting to MQTT broker %s:%d (TLS %s)",
  472. mqtt_host,
  473. mqtt_port,
  474. "disabled" if mqtt_disable_tls else "enabled",
  475. )
  476. if mqtt_password and not mqtt_username:
  477. raise ValueError("Missing MQTT username")
  478. async with aiomqtt.Client( # raises aiomqtt.MqttError
  479. hostname=mqtt_host,
  480. port=mqtt_port,
  481. # > The settings [...] usually represent a higher security level than
  482. # > when calling the SSLContext constructor directly.
  483. # https://web.archive.org/web/20230714183106/https://docs.python.org/3/library/ssl.html
  484. tls_context=None if mqtt_disable_tls else ssl.create_default_context(),
  485. username=None if mqtt_username is None else mqtt_username,
  486. password=None if mqtt_password is None else mqtt_password,
  487. will=aiomqtt.Will( # e.g. on SIGTERM & SIGKILL
  488. topic=state.mqtt_availability_topic,
  489. payload=_MQTT_PAYLOAD_NOT_AVAILABLE,
  490. retain=True,
  491. ),
  492. ) as mqtt_client:
  493. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_host, mqtt_port)
  494. if not state.shutdown_lock_acquired:
  495. state.acquire_shutdown_lock()
  496. await state.publish_homeassistant_device_config(mqtt_client=mqtt_client)
  497. await state.publish_preparing_for_shutdown(mqtt_client=mqtt_client)
  498. try:
  499. await mqtt_client.publish(
  500. topic=state.mqtt_availability_topic,
  501. payload=_MQTT_PAYLOAD_AVAILABLE,
  502. retain=True,
  503. )
  504. # asynpio.TaskGroup added in python3.11
  505. await asyncio.gather(
  506. _mqtt_message_loop(state=state, mqtt_client=mqtt_client),
  507. _dbus_signal_loop(state=state, mqtt_client=mqtt_client),
  508. return_exceptions=False,
  509. )
  510. finally: # e.g. on SIGINT
  511. # https://web.archive.org/web/20250101080719/https://github.com/empicano/aiomqtt/issues/28
  512. await mqtt_client.publish(
  513. topic=state.mqtt_availability_topic,
  514. payload=_MQTT_PAYLOAD_NOT_AVAILABLE,
  515. retain=True,
  516. )
  517. def _main() -> None:
  518. logging.basicConfig(
  519. level=logging.INFO,
  520. format="%(asctime)s:%(levelname)s:%(message)s",
  521. datefmt="%Y-%m-%dT%H:%M:%S%z",
  522. )
  523. argparser = argparse.ArgumentParser(
  524. description="MQTT client triggering & reporting shutdown on systemd-based systems",
  525. )
  526. argparser.add_argument(
  527. "--log-level",
  528. choices=_ARGUMENT_LOG_LEVEL_MAPPING.keys(),
  529. default="info",
  530. help="log level (default: %(default)s)",
  531. )
  532. argparser.add_argument("--mqtt-host", type=str, required=True)
  533. argparser.add_argument(
  534. "--mqtt-port",
  535. type=int,
  536. help=f"default {_MQTT_DEFAULT_TLS_PORT} ({_MQTT_DEFAULT_PORT} with --mqtt-disable-tls)",
  537. )
  538. argparser.add_argument("--mqtt-username", type=str)
  539. argparser.add_argument("--mqtt-disable-tls", action="store_true")
  540. password_argument_group = argparser.add_mutually_exclusive_group()
  541. password_argument_group.add_argument("--mqtt-password", type=str)
  542. password_argument_group.add_argument(
  543. "--mqtt-password-file",
  544. type=pathlib.Path,
  545. metavar="PATH",
  546. dest="mqtt_password_path",
  547. help="stripping trailing newline",
  548. )
  549. argparser.add_argument(
  550. "--mqtt-topic-prefix",
  551. type=str,
  552. # pylint: disable=protected-access
  553. default="systemctl/" + systemctl_mqtt._utils.get_hostname(),
  554. help="default: %(default)s",
  555. )
  556. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  557. argparser.add_argument(
  558. "--homeassistant-discovery-prefix",
  559. type=str,
  560. default="homeassistant",
  561. help="home assistant's prefix for discovery topics" + " (default: %(default)s)",
  562. )
  563. argparser.add_argument(
  564. "--homeassistant-discovery-object-id",
  565. type=str,
  566. # pylint: disable=protected-access
  567. default=systemctl_mqtt._homeassistant.get_default_discovery_object_id(),
  568. help="part of discovery topic (default: %(default)s)",
  569. )
  570. argparser.add_argument(
  571. "--poweroff-delay-seconds", type=float, default=4.0, help="default: %(default)s"
  572. )
  573. argparser.add_argument(
  574. "--monitor-system-unit",
  575. type=str,
  576. metavar="UNIT_NAME",
  577. dest="monitored_system_unit_names",
  578. action="append",
  579. help="e.g. --monitor-system-unit ssh.service --monitor-system-unit custom.service",
  580. )
  581. argparser.add_argument(
  582. "--control-system-unit",
  583. type=str,
  584. metavar="UNIT_NAME",
  585. dest="controlled_system_unit_names",
  586. action="append",
  587. help="e.g. --control-system-unit ansible-pull.service --control-system-unit custom.service",
  588. )
  589. args = argparser.parse_args()
  590. logging.root.setLevel(_ARGUMENT_LOG_LEVEL_MAPPING[args.log_level])
  591. if args.mqtt_port:
  592. mqtt_port = args.mqtt_port
  593. elif args.mqtt_disable_tls:
  594. mqtt_port = _MQTT_DEFAULT_PORT
  595. else:
  596. mqtt_port = _MQTT_DEFAULT_TLS_PORT
  597. if args.mqtt_password_path:
  598. # .read_text() replaces \r\n with \n
  599. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  600. if mqtt_password.endswith("\r\n"):
  601. mqtt_password = mqtt_password[:-2]
  602. elif mqtt_password.endswith("\n"):
  603. mqtt_password = mqtt_password[:-1]
  604. else:
  605. mqtt_password = args.mqtt_password
  606. # pylint: disable=protected-access
  607. if not systemctl_mqtt._homeassistant.validate_discovery_object_id(
  608. args.homeassistant_discovery_object_id
  609. ):
  610. raise ValueError(
  611. # pylint: disable=protected-access
  612. "invalid home assistant discovery object id"
  613. f" {args.homeassistant_discovery_object_id!r} (length >= 1"
  614. ", allowed characters:"
  615. f" {systemctl_mqtt._homeassistant.NODE_ID_ALLOWED_CHARS})"
  616. "\nchange --homeassistant-discovery-object-id"
  617. )
  618. asyncio.run(
  619. _run(
  620. mqtt_host=args.mqtt_host,
  621. mqtt_port=mqtt_port,
  622. mqtt_disable_tls=args.mqtt_disable_tls,
  623. mqtt_username=args.mqtt_username,
  624. mqtt_password=mqtt_password,
  625. mqtt_topic_prefix=args.mqtt_topic_prefix,
  626. homeassistant_discovery_prefix=args.homeassistant_discovery_prefix,
  627. homeassistant_discovery_object_id=args.homeassistant_discovery_object_id,
  628. poweroff_delay=datetime.timedelta(seconds=args.poweroff_delay_seconds),
  629. monitored_system_unit_names=args.monitored_system_unit_names or [],
  630. controlled_system_unit_names=args.controlled_system_unit_names or [],
  631. )
  632. )