__init__.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 = bus.get_object(
  32. bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1"
  33. ) # type: dbus.proxies.ProxyObject
  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. # datetime.datetime.isoformat(timespec=) not available in python3.5
  41. # https://github.com/python/cpython/blob/v3.5.9/Lib/datetime.py#L1552
  42. _LOGGER.info(
  43. "scheduling %s for %s", action, shutdown_datetime.strftime("%Y-%m-%d %H:%M:%S"),
  44. )
  45. shutdown_epoch_usec = int(shutdown_datetime.timestamp() * 10 ** 6)
  46. try:
  47. # $ gdbus introspect --system --dest org.freedesktop.login1 \
  48. # --object-path /org/freedesktop/login1 | grep -A 1 ScheduleShutdown
  49. # ScheduleShutdown(in s arg_0,
  50. # in t arg_1);
  51. # $ gdbus call --system --dest org.freedesktop.login1 \
  52. # --object-path /org/freedesktop/login1 \
  53. # --method org.freedesktop.login1.Manager.ScheduleShutdown \
  54. # poweroff "$(date --date=10min +%s)000000"
  55. # $ dbus-send --type=method_call --print-reply --system --dest=org.freedesktop.login1 \
  56. # /org/freedesktop/login1 \
  57. # org.freedesktop.login1.Manager.ScheduleShutdown \
  58. # string:poweroff "uint64:$(date --date=10min +%s)000000"
  59. _get_login_manager().ScheduleShutdown(action, shutdown_epoch_usec)
  60. except dbus.DBusException as exc:
  61. exc_msg = exc.get_dbus_message()
  62. if "authentication required" in exc_msg.lower():
  63. _LOGGER.error(
  64. "failed to schedule %s: unauthorized; missing polkit authorization rules?",
  65. action,
  66. )
  67. else:
  68. _LOGGER.error("failed to schedule %s: %s", action, exc_msg)
  69. class _Settings:
  70. # pylint: disable=too-few-public-methods
  71. def __init__(self, mqtt_topic_prefix: str) -> None:
  72. self._mqtt_topic_prefix = mqtt_topic_prefix
  73. @property
  74. def mqtt_topic_prefix(self) -> str:
  75. return self._mqtt_topic_prefix
  76. class _MQTTAction:
  77. # pylint: disable=too-few-public-methods
  78. def __init__(self, name: str, action: typing.Callable) -> None:
  79. self.name = name
  80. self.action = action
  81. def mqtt_message_callback(
  82. self,
  83. mqtt_client: paho.mqtt.client.Client,
  84. settings: _Settings,
  85. message: paho.mqtt.client.MQTTMessage,
  86. ) -> None:
  87. # pylint: disable=unused-argument; callback
  88. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L3416
  89. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L469
  90. _LOGGER.debug("received topic=%s payload=%r", message.topic, message.payload)
  91. if message.retain:
  92. _LOGGER.info("ignoring retained message")
  93. return
  94. _LOGGER.debug("executing action %s (%r)", self.name, self.action)
  95. self.action()
  96. _LOGGER.debug("completed action %s (%r)", self.name, self.action)
  97. _MQTT_TOPIC_SUFFIX_ACTION_MAPPING = {
  98. "poweroff": _MQTTAction(
  99. name="poweroff", action=functools.partial(_schedule_shutdown, action="poweroff")
  100. ),
  101. }
  102. def _mqtt_on_connect(
  103. mqtt_client: paho.mqtt.client.Client,
  104. settings: _Settings,
  105. flags: typing.Dict,
  106. return_code: int,
  107. ) -> None:
  108. # pylint: disable=unused-argument; callback
  109. # https://github.com/eclipse/paho.mqtt.python/blob/v1.5.0/src/paho/mqtt/client.py#L441
  110. assert return_code == 0, return_code # connection accepted
  111. mqtt_broker_host, mqtt_broker_port = mqtt_client.socket().getpeername()
  112. _LOGGER.debug("connected to MQTT broker %s:%d", mqtt_broker_host, mqtt_broker_port)
  113. for topic_suffix, action in _MQTT_TOPIC_SUFFIX_ACTION_MAPPING.items():
  114. topic = settings.mqtt_topic_prefix + "/" + topic_suffix
  115. _LOGGER.info("subscribing to %s", topic)
  116. mqtt_client.subscribe(topic)
  117. mqtt_client.message_callback_add(
  118. sub=topic, callback=action.mqtt_message_callback
  119. )
  120. _LOGGER.debug(
  121. "registered MQTT callback for topic %s triggering %r", topic, action.action
  122. )
  123. def _run(
  124. mqtt_host: str,
  125. mqtt_port: int,
  126. mqtt_username: typing.Optional[str],
  127. mqtt_password: typing.Optional[str],
  128. mqtt_topic_prefix: str,
  129. ) -> None:
  130. # https://pypi.org/project/paho-mqtt/
  131. mqtt_client = paho.mqtt.client.Client(
  132. userdata=_Settings(mqtt_topic_prefix=mqtt_topic_prefix)
  133. )
  134. mqtt_client.on_connect = _mqtt_on_connect
  135. mqtt_client.tls_set(ca_certs=None) # enable tls trusting default system certs
  136. _LOGGER.info(
  137. "connecting to MQTT broker %s:%d", mqtt_host, mqtt_port,
  138. )
  139. if mqtt_username:
  140. mqtt_client.username_pw_set(username=mqtt_username, password=mqtt_password)
  141. elif mqtt_password:
  142. raise ValueError("Missing MQTT username")
  143. mqtt_client.connect(host=mqtt_host, port=mqtt_port)
  144. mqtt_client.loop_forever()
  145. def _get_hostname() -> str:
  146. return socket.gethostname()
  147. def _main() -> None:
  148. logging.basicConfig(
  149. level=logging.DEBUG,
  150. format="%(asctime)s:%(levelname)s:%(message)s",
  151. datefmt="%Y-%m-%dT%H:%M:%S%z",
  152. )
  153. argparser = argparse.ArgumentParser(
  154. description="MQTT client triggering shutdown on systemd-based systems",
  155. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  156. )
  157. argparser.add_argument("--mqtt-host", type=str, required=True)
  158. argparser.add_argument("--mqtt-port", type=int, default=8883)
  159. argparser.add_argument("--mqtt-username", type=str)
  160. password_argument_group = argparser.add_mutually_exclusive_group()
  161. password_argument_group.add_argument("--mqtt-password", type=str)
  162. password_argument_group.add_argument(
  163. "--mqtt-password-file",
  164. type=pathlib.Path,
  165. metavar="PATH",
  166. dest="mqtt_password_path",
  167. help="stripping trailing newline",
  168. )
  169. # https://www.home-assistant.io/docs/mqtt/discovery/#discovery_prefix
  170. argparser.add_argument(
  171. "--mqtt-topic-prefix",
  172. type=str,
  173. default="systemctl/" + _get_hostname(),
  174. help=" ", # show default
  175. )
  176. args = argparser.parse_args()
  177. if args.mqtt_password_path:
  178. # .read_text() replaces \r\n with \n
  179. mqtt_password = args.mqtt_password_path.read_bytes().decode()
  180. if mqtt_password.endswith("\r\n"):
  181. mqtt_password = mqtt_password[:-2]
  182. elif mqtt_password.endswith("\n"):
  183. mqtt_password = mqtt_password[:-1]
  184. else:
  185. mqtt_password = args.mqtt_password
  186. _run(
  187. mqtt_host=args.mqtt_host,
  188. mqtt_port=args.mqtt_port,
  189. mqtt_username=args.mqtt_username,
  190. mqtt_password=mqtt_password,
  191. mqtt_topic_prefix=args.mqtt_topic_prefix,
  192. )