-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup-db.sh
executable file
·102 lines (79 loc) · 2.21 KB
/
backup-db.sh
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/bin/bash
ROTATION_SIZE=3
NAME="$(basename $0)"
test -z "${BACKUP_ROOT}" && BACKUP_ROOT="/var/local/backups"
#
# Helper functions
#
rotate_and_backup()
{
# The command that actually carries out the backup. It is expected to write its
# output directly to stdout
local backup_command=${1}
# The directory to store backups under.
local backup_dir=${2}
# The filename prefix
local fname=${3}
# Rotate
for ((i=${ROTATION_SIZE}; i>0; i--))
do
let j=i-1
test -f "${backup_dir}/${fname}.${j}" && mv "${backup_dir}/${fname}.${j}" "${backup_dir}/${fname}.${i}"
done
# Backup
eval ${backup_command} > "${backup_dir}/${fname}.0"
}
backup_mysql_databases()
{
logger -t ${NAME} -s -p 'local0.info' "Backing-up MySQL databases"
sudo mysqldump -A -l
}
backup_postgres_databases()
{
logger -t ${NAME} -s -p 'local0.info' "Backing-up PostgreSQL databases"
sudo -u postgres pg_dumpall
}
#
# Main
#
# Determine source and destination
if test -d "${BACKUP_ROOT}"
then
logger -t ${NAME} -s -p 'local0.info' "Using BACKUP_ROOT: ${BACKUP_ROOT}";
else
logger -t ${NAME} -s -p 'local0.error' "Cannot use BACKUP_ROOT: Not a directory!";
exit 1;
fi;
backup_dir=
while getopts "b:" option
do
case ${option} in
b)
backup_dir=${BACKUP_ROOT}"/"${OPTARG}
;;
?)
echo "Unknown option: ${option}"
exit 1
;;
esac
done
if test -z "${backup_dir}"
then
backup_dir=${BACKUP_ROOT}"/"${HOSTNAME}"/db"
fi;
mkdir -p ${backup_dir}
backup_dir=$(cd ${backup_dir} && pwd)
logger -t ${NAME} -s -p 'local0.info' "Using backup_dir: ${backup_dir}";
# Dump
# TODO:
# Find a better way to determine if database servers are actually running (assume a debian-based system)
mysql_running=$(ps aux| grep -e '/usr/\(bin\|sbin\)/mysqld'| grep -v -e grep)
if test -n "${mysql_running}"
then
rotate_and_backup backup_mysql_databases ${backup_dir} 'mysqldump.sql'
fi
postgres_running=$(ps aux| grep -e '/usr/lib/postgresql/[89].[1-9]/bin/postgres'| grep -v -e grep)
if test -n "${postgres_running}"
then
rotate_and_backup backup_postgres_databases ${backup_dir} 'pgdump.sql'
fi