#!/bin/bash # {{ ansible_managed }} # OnFailure= handler for the Nextcloud backup units. Invoked as: # nextcloud-backup-alert.sh # # Deliberately NOT `set -e`: an alert handler that dies partway through # reports nothing, which is worse than a partial report. Same reasoning as # roles/ups/templates/ups-restore.sh.j2. set -uo pipefail TAG=nextcloud-backup UNIT="${1:-unknown}" TO="{{ backup_alert_email | default('root') }}" HOST="$(hostname -f 2>/dev/null || hostname)" result="$(systemctl show -p Result --value "$UNIT" 2>/dev/null)" code="$(systemctl show -p ExecMainStatus --value "$UNIT" 2>/dev/null)" # One machine-parseable line for Graylog, then the context. logger -t "$TAG" -p daemon.err -- \ "status=failed unit=$UNIT result=${result:-unknown} exit=${code:-unknown}" body="$(printf 'Nextcloud backup FAILED on %s\n\nunit: %s\nresult: %s\nexit: %s\n\n--- last 40 journal lines ---\n' \ "$HOST" "$UNIT" "${result:-unknown}" "${code:-unknown}") $(journalctl -u "$UNIT" -n 40 --no-pager -o cat 2>/dev/null)" echo "$body" | logger -t "$TAG" -p daemon.err # Mail is best-effort: if the MTA is not configured the journald record above # is still the authoritative signal, so never fail the handler on this. if command -v sendmail >/dev/null 2>&1; then printf 'To: %s\nSubject: [%s] Nextcloud backup FAILED: %s\nContent-Type: text/plain; charset=UTF-8\n\n%s\n' \ "$TO" "$HOST" "$UNIT" "$body" | sendmail -t \ && logger -t "$TAG" -p daemon.info -- "alert_mail=sent to=$TO" \ || logger -t "$TAG" -p daemon.err -- "alert_mail=failed to=$TO" else logger -t "$TAG" -p daemon.err -- "alert_mail=skipped reason=no-sendmail" fi exit 0