-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg_backup_cron.sh
More file actions
executable file
·71 lines (60 loc) · 2.15 KB
/
pg_backup_cron.sh
File metadata and controls
executable file
·71 lines (60 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/bash
# Cron wrapper script for PostgreSQL backup
# This script ensures proper environment and error handling for cron execution.
#
# NOTE: The Python backup script already writes detailed logs to
# /var/log/pgbackup/pgbackup_YYYYMMDD.log
# This cron log only captures the wrapper's own status messages and any
# stderr from the Python process to avoid giant duplicate log files.
# Set script directory
SCRIPT_DIR="/opt/pgSQL-bck-script"
SCRIPT="$SCRIPT_DIR/pg_backup_main.py"
# Set up logging (lightweight cron-only log)
LOG_DIR="/var/log/pgbackup"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
CRON_LOG="$LOG_DIR/cron_${TIMESTAMP}.log"
# Ensure log directory exists and is writable
mkdir -p "$LOG_DIR" 2>/dev/null || {
CRON_LOG="/tmp/pgbackup_cron_${TIMESTAMP}.log"
}
# Function to log messages
log_message() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$CRON_LOG"
}
# Check if script exists
if [ ! -f "$SCRIPT" ]; then
log_message "ERROR: Backup script not found at $SCRIPT"
exit 1
fi
# Check if Python 3 is available
if ! command -v python3 &> /dev/null; then
log_message "ERROR: python3 not found in PATH"
exit 1
fi
# Set PATH to include common locations (cron has minimal PATH)
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# Set Python path if needed
export PYTHONPATH="$SCRIPT_DIR:$PYTHONPATH"
log_message "Starting PostgreSQL backup (cron job)"
log_message "User: $(whoami)"
# Execute the backup script.
# stdout goes to /dev/null (already captured by the Python logger to its own log file).
# Only stderr is captured in the cron log for debugging unexpected crashes.
python3 "$SCRIPT" > /dev/null 2>> "$CRON_LOG"
EXIT_CODE=$?
case $EXIT_CODE in
0)
log_message "Backup completed successfully"
exit 0
;;
75)
# EX_TEMPFAIL: another backup instance already holds the lock
log_message "Another backup instance is already running -- skipping this run"
exit 0
;;
*)
log_message "ERROR: Backup failed (exit code: $EXIT_CODE)"
log_message "Check the main log file for details: $LOG_DIR/pgbackup_$(date +%Y%m%d).log"
exit $EXIT_CODE
;;
esac