123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- import datetime
- import logging
- import dbus
- _LOGGER = logging.getLogger(__name__)
- def get_login_manager() -> dbus.proxies.Interface:
-
- bus = dbus.SystemBus()
- proxy = bus.get_object(
- bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1"
- )
-
- return dbus.Interface(object=proxy, dbus_interface="org.freedesktop.login1.Manager")
- def _log_shutdown_inhibitors(login_manager: dbus.proxies.Interface) -> None:
- if _LOGGER.getEffectiveLevel() > logging.DEBUG:
- return
- found_inhibitor = False
- try:
-
- for what, who, why, mode, uid, pid in login_manager.ListInhibitors():
- if "shutdown" in what:
- found_inhibitor = True
- _LOGGER.debug(
- "detected shutdown inhibitor %s (pid=%u, uid=%u, mode=%s): %s",
- who,
- pid,
- uid,
- mode,
- why,
- )
- except dbus.DBusException as exc:
- _LOGGER.warning(
- "failed to fetch shutdown inhibitors: %s", exc.get_dbus_message()
- )
- return
- if not found_inhibitor:
- _LOGGER.debug("no shutdown inhibitor locks found")
- def schedule_shutdown(*, action: str, delay: datetime.timedelta) -> None:
-
- assert action in ["poweroff", "reboot"], action
- shutdown_datetime = datetime.datetime.now() + delay
-
-
- _LOGGER.info(
- "scheduling %s for %s", action, shutdown_datetime.strftime("%Y-%m-%d %H:%M:%S")
- )
-
- shutdown_epoch_usec = dbus.UInt64(shutdown_datetime.timestamp() * 10**6)
- login_manager = get_login_manager()
- try:
-
-
-
-
-
-
-
-
-
-
-
-
- login_manager.ScheduleShutdown(action, shutdown_epoch_usec)
- except dbus.DBusException as exc:
- exc_msg = exc.get_dbus_message()
- if "authentication required" in exc_msg.lower():
- _LOGGER.error(
- "failed to schedule %s: unauthorized; missing polkit authorization rules?",
- action,
- )
- else:
- _LOGGER.error("failed to schedule %s: %s", action, exc_msg)
- _log_shutdown_inhibitors(login_manager)
- def lock_all_sessions() -> None:
- """
- $ loginctl lock-sessions
- """
- _LOGGER.info("instruct all sessions to activate screen locks")
- get_login_manager().LockSessions()
|