borgmatic/borgmatic/hooks/apprise.py

80 lines
2.3 KiB
Python
Raw Normal View History

2023-09-21 19:44:12 +00:00
import logging
2023-10-01 15:00:20 +00:00
import operator
2023-09-21 19:44:12 +00:00
logger = logging.getLogger(__name__)
def initialize_monitor(
ping_url, config, config_filename, monitoring_log_level, dry_run
): # pragma: no cover
'''
No initialization is necessary for this monitor.
'''
pass
def ping_monitor(hook_config, config, config_filename, state, monitoring_log_level, dry_run):
'''
2023-09-23 19:11:15 +00:00
Ping the configured Apprise service URLs. Use the given configuration filename in any log
entries. If this is a dry run, then don't actually ping anything.
2023-09-21 19:44:12 +00:00
'''
try:
import apprise
2023-10-01 15:00:20 +00:00
from apprise import NotifyFormat, NotifyType
except ImportError:
logger.warning('Unable to import Apprise in monitoring hook')
return
state_to_notify_type = {
'start': NotifyType.INFO,
'finish': NotifyType.SUCCESS,
'fail': NotifyType.FAILURE,
2023-10-01 15:00:20 +00:00
'log': NotifyType.INFO,
}
2023-09-21 19:44:12 +00:00
run_states = hook_config.get('states', ['fail'])
if state.name.lower() not in run_states:
return
state_config = hook_config.get(
state.name.lower(),
{
'title': f'A borgmatic {state.name} event happened',
2023-10-01 15:00:20 +00:00
'body': f'A borgmatic {state.name} event happened',
2023-09-21 19:44:12 +00:00
},
)
2023-09-23 19:11:15 +00:00
if not hook_config.get('services'):
logger.info(f'{config_filename}: No Apprise services to ping')
return
dry_run_string = ' (dry run; not actually pinging)' if dry_run else ''
2023-10-01 15:00:20 +00:00
labels_string = ', '.join(map(operator.itemgetter('label'), hook_config.get('services')))
2023-09-23 19:11:15 +00:00
logger.info(f'{config_filename}: Pinging Apprise services: {labels_string}{dry_run_string}')
2023-09-21 19:44:12 +00:00
2023-09-23 19:11:15 +00:00
apprise_object = apprise.Apprise()
2023-10-01 15:00:20 +00:00
apprise_object.add(list(map(operator.itemgetter('url'), hook_config.get('services'))))
2023-09-21 19:44:12 +00:00
if dry_run:
return
2023-09-23 19:11:15 +00:00
result = apprise_object.notify(
2023-10-01 15:00:20 +00:00
title=state_config.get('title', ''),
body=state_config.get('body'),
2023-09-21 19:44:12 +00:00
body_format=NotifyFormat.TEXT,
2023-10-01 15:00:20 +00:00
notify_type=state_to_notify_type[state.name.lower()],
)
2023-09-21 19:44:12 +00:00
if result is False:
2023-10-01 15:00:20 +00:00
logger.warning(f'{config_filename}: Error sending some Apprise notifications')
2023-09-21 19:44:12 +00:00
def destroy_monitor(
ping_url_or_uuid, config, config_filename, monitoring_log_level, dry_run
): # pragma: no cover
'''
No destruction is necessary for this monitor.
'''
pass