__init__.py 25 KB

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