Don't print tracebacks when desktop notifications fail

Without dbus-python, or without a session bus (e.g. when running
from a timer), each notification printed a traceback. Skip
notifications if dbus is not installed, and log a single warning
if sending one fails. Remove the now unneeded NameError handling
around _notify calls.
This commit is contained in:
Fuxino
2026-10-08 17:55:57 +02:00
parent 578d992a19
commit ac7e6ec21b
+14 -26
View File
@@ -15,7 +15,6 @@ Classes:
from __future__ import annotations
# Import libraries
import traceback
import sys
import os
import pwd
@@ -51,7 +50,7 @@ except ImportError:
try:
import dbus
except ImportError:
pass
dbus = None
load_dotenv()
@@ -316,10 +315,7 @@ class Backup:
logger.critical(
'Cannot access the backup directory. Permission denied')
try:
_notify('Backup failed (check log for details)')
except NameError:
pass
sys.exit(3)
@@ -500,10 +496,7 @@ class Backup:
logger.info('Starting backup...')
try:
_notify('Starting backup...')
except NameError:
pass
self.define_backup_dir()
self.find_last_backup()
@@ -525,10 +518,7 @@ class Backup:
logger.info(
'No existing files or directories specified for backup. Nothing to do')
try:
_notify('Backup finished. No files copied')
except NameError:
pass
return 1
@@ -615,17 +605,11 @@ class Backup:
if output == 'ok':
logger.info('Backup completed')
try:
_notify('Backup completed')
except NameError:
pass
else:
logger.error('Backup failed')
try:
_notify('Backup failed (check log for details)')
except NameError:
pass
if self._ssh:
self._ssh.close()
@@ -634,20 +618,14 @@ class Backup:
logger.error(
'Some errors occurred while performing the backup')
try:
_notify(
'Some errors occurred while performing the backup. Check log for details')
except NameError:
pass
return 4
logger.info('Backup completed')
try:
_notify('Backup completed')
except NameError:
pass
return 0
@@ -844,12 +822,20 @@ def _target_uid() -> int | None:
return None
_notify_failed = False
def _notify(text: str) -> None:
global _notify_failed
if dbus is None or _notify_failed:
return
euid = os.geteuid()
uid = _target_uid()
if uid is None:
print('notify: no target uid (neither SUDO_UID nor DOAS_USER set)', file=sys.stderr)
logger.debug('Cannot send desktop notification: user not found')
return
@@ -862,8 +848,10 @@ def _notify(text: str) -> None:
'/org/freedesktop/Notifications')
obj = dbus.Interface(obj, 'org.freedesktop.Notifications')
obj.Notify('simple_backup', 0, '', 'simple_backup', text, [], {'urgency': dbus.Byte(1)}, 10000)
except Exception:
traceback.print_exc()
except Exception as e:
# Report the failure only once (e.g. no session bus available), then stop trying
_notify_failed = True
logger.warning('Cannot send desktop notification: %s', e)
finally:
os.seteuid(euid)