__init__.py 8.8 KB

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