__init__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # systemctl-mqtt - MQTT client triggering 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 logging
  21. import pathlib
  22. import socket
  23. import typing
  24. import dbus
  25. import paho.mqtt.client
  26. _LOGGER = logging.getLogger(__name__)
  27. _SHUTDOWN_DELAY = datetime.timedelta(seconds=4)
  28. def _get_login_manager() -> dbus.proxies.Interface:
  29. # https://dbus.freedesktop.org/doc/dbus-python/tutorial.html
  30. bus = dbus.SystemBus()
  31. proxy: dbus.proxies.ProxyObject = bus.get_object(
  32. bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1"
  33. )
  34. # https://freedesktop.org/wiki/Software/systemd/logind/
  35. return dbus.Interface(object=proxy, dbus_interface="org.freedesktop.login1.Manager")
  36. def _schedule_shutdown(action: str) -> None:
  37. # https://github.com/systemd/systemd/blob/v237/src/systemctl/systemctl.c#L8553
  38. assert action in ["poweroff", "reboot"], action
  39. shutdown_datetime = datetime.datetime.now() + _SHUTDOWN_DELAY
  40. _LOGGER.info(
  41. "scheduling %s for %s",
  42. action,
  43. shutdown_datetime.isoformat(sep=" ", timespec="seconds"),
  44. )
  45. shutdown_epoch_usec = int(shutdown_datetime.timestamp() * 10 ** 6)
  46. try:
  47. _get_login_manager().ScheduleShutdown(action, shutdown_epoch_usec)
  48. except dbus.DBusException as exc:
  49. _LOGGER.error("failed to schedule shutdown: %s", exc.get_dbus_message())
  50. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  51. "poweroff": functools.partial(_schedule_shutdown, action="poweroff"),
  52. }
  53. class _Settings:
  54. # pylint: disable=too-few-public-methods
  55. def __init__(self, mqtt_topic_prefix: str) -> None:
  56. self.mqtt_topic_action_mapping: typing.Dict[str, typing.Callable] = {}
  57. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  58. topic = mqtt_topic_prefix + "/" + topic_suffix
  59. self.mqtt_topic_action_mapping[topic] = action
  60. def _mqtt_on_connect(
  61. mqtt_client: paho.mqtt.client.Client,
  62. settings: _Settings,
  63. flags: typing.Dict,
  64. return_code: int,
  65. ) -> None:
  66. # pylint: disable=unused-argument; callback
  67. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  68. assert return_code == 0, return_code # connection accepted
  69. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  70. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  71. for topic in settings.mqtt_topic_action_mapping.keys():
  72. _LOGGER.debug("subscribing to %s", topic)
  73. mqtt_client.subscribe(topic)
  74. def _mqtt_on_message(
  75. mqtt_client: paho.mqtt.client.Client,
  76. settings: _Settings,
  77. message: paho.mqtt.client.MQTTMessage,
  78. ) -> None:
  79. # pylint: disable=unused-argument; callback
  80. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  81. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  82. if message.retain:
  83. _LOGGER.info("ignoring retained message")
  84. return
  85. try:
  86. action = settings.mqtt_topic_action_mapping[message.topic]
  87. except KeyError:
  88. _LOGGER.warning("unexpected topic %s", message.topic)
  89. return
  90. _LOGGER.debug("executing action %r", action)
  91. action()
  92. _LOGGER.debug("completed action %r", action)
  93. def _run(
  94. mqtt_host: str,
  95. mqtt_port: int,
  96. mqtt_username: typing.Optional[str],
  97. mqtt_password: typing.Optional[str],
  98. mqtt_topic_prefix: str,
  99. ) -> None:
  100. # https://pypi.org/project/paho-mqtt/
  101. mqtt_client = paho.mqtt.client.Client(
  102. userdata=_Settings(mqtt_topic_prefix=mqtt_topic_prefix)
  103. )
  104. mqtt_client.on_connect = _mqtt_on_connect
  105. mqtt_client.on_message = _mqtt_on_message
  106. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  107. _LOGGER.info(
  108. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  109. )
  110. if mqtt_username:
  111. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  112. elif mqtt_password:
  113. raise ValueError("Missing MQTT username")
  114. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  115. mqtt_client.loop_forever()
  116. def _get_hostname() -> str:
  117. return socket.gethostname()
  118. def _main() -> None:
  119. logging.basicConfig(
  120. level=logging.DEBUG,
  121. format="%(asctime)s:%(levelname)s:%(message)s",
  122. datefmt="%Y-%m-%dT%H:%M:%S%z",
  123. )
  124. argparser = argparse.ArgumentParser(
  125. description="MQTT client triggering shutdown on systemd-based systems",
  126. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  127. )
  128. argparser.add_argument("--mqtt-host", type=str, required=True)
  129. argparser.add_argument("--mqtt-port", type=int, default=8883)
  130. argparser.add_argument("--mqtt-username", type=str)
  131. password_argument_group = argparser.add_mutually_exclusive_group()
  132. password_argument_group.add_argument("--mqtt-password", type=str)
  133. password_argument_group.add_argument(
  134. "--mqtt-password-file",
  135. type=pathlib.Path,
  136. metavar="PATH",
  137. dest="mqtt_password_path",
  138. help="stripping trailing newline",
  139. )
  140. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  141. argparser.add_argument(
  142. "--mqtt-topic-prefix",
  143. type=str,
  144. default="systemctl/" + _get_hostname(),
  145. help=" ", # show default
  146. )
  147. args = argparser.parse_args()
  148. if args.mqtt_password_path:
  149. # .read_text() replaces \r\n with \n
  150. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  151. if mqtt_password.endswith("\r\n"):
  152. mqtt_password = mqtt_password[:-2]
  153. elif mqtt_password.endswith("\n"):
  154. mqtt_password = mqtt_password[:-1]
  155. else:
  156. mqtt_password = args.mqtt_password
  157. _run(
  158. mqtt_host=args.mqtt_host,
  159. mqtt_port=args.mqtt_port,
  160. mqtt_username=args.mqtt_username,
  161. mqtt_password=mqtt_password,
  162. mqtt_topic_prefix=args.mqtt_topic_prefix,
  163. )