This repository has been archived by the owner on Dec 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
db_smart_backup.sh
executable file
·1576 lines (1411 loc) · 44.2 KB
/
db_smart_backup.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# LICENSE: BSD 3 clause
# Author: Mathieu Le Marec - Pasquet / kiorky@cryptelium.net
__NAME__="db_smart_backup"
# even if it is not really tested, we are trying to get full posix compatibility
# and to run on another shell than bash
#if [ x"$SHELL" = "x/bin/bash" ];then
# set -o posix &> /dev/null
#fi
generate_configuration_file() {
cat > ${DSB_CONF_FILE} << EOF
# A script can run only for one database type and a specific host
# at a time (mysql, postgresql)
# But you can run it with multiple configuration files
# You can obiously share the same base backup directory.
# set to 1 to deactivate colors (cron)
#NO_COLOR=""
# Choose Compression type. (gzip or bzip2 or xz or zstd)
#COMP=bzip2
#User to run dumps dump binaries as, defaults to logged in user
#RUNAS=postgres
#DB user to connect to the database with, defaults to \$RUNAS
#DBUSER=postgres
######## Backup settings
# one of: postgresql mysql
#BACKUP_TYPE=postgresql
#BACKUP_TYPE=mysql
#BACKUP_TYPE=mongodb
#BACKUP_TYPE=slapd
#BACKUP_TYPE=redis
#BACKUP_TYPE=es
# Backup directory location e.g /backups
#TOP_BACKUPDIR="/var/db_smart_backup"
# do also global backup (use by postgresql to save roles/groups and only that
#DO_GLOBAL_BACKUP="1"
# HOW MANY BACKUPS TO KEEP & LEVEL
# How many snapshots to keep (lastlog for dump)
# How many per day
#KEEP_LASTS=24
#KEEP_DAYS=14
#KEEP_WEEKS=8
#KEEP_MONTHES=12
#EEP_LOGS=60
# directories permission
#DPERM="750"
# directory permission
#FPERM="640"
# OWNER/GROUP
#OWNER=root
#GROUP=root
######## Database connection settings
# host defaults to localhost
# and without port we use a connection via socket
#HOST=""
#PORT=""
# defaults to postgres on postgresql backup
# as ident is used by default on many installs, we certainly
# do not need either a password
#PASSWORD=""
# List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3"
#DBNAMES="all"
# List of DBNAMES to EXLUCDE if DBNAMES are set to all (must be in " quotes)
#DBEXCLUDE=""
######### Elasticsearch
# ES_URI="http://localhost:9200"
# ES_USER="user"
# ES_PASSWORD="secret"
# path to snapshots (have to be added to path.repo in elasticsearch.yml)
# ES_SNAPSHOTS_DIR="\${ES_SNAPSHOTS_DIR:-\${ES_TMP}/snapshots}"
# elasticsearch daemon user
######### Postgresql
# binaries path
#PSQL=""
#PG_DUMP=""
#PG_DUMPALL=""
######## slapd
# SLAPCAT_ARGS="\${SLAPCAT_ARGS:-""}"
# SLAPD_DIR="\${SLAPD_DIR:-/var/lib/ldap}"
# OPT string for use with pg_dump ( see man pg_dump )
#OPT="--create -Fc"
# OPT string for use with pg_dumpall ( see man pg_dumpall )
#OPTALL="--globals-only"
######## MYSQL
#MYSQL_SOCK_PATHS=""
#MYSQL=""
#MYSQLDUMP=""
# do we disable mysqldump --single-transaction0
#MYSQLDUMP_NO_SINGLE_TRANSACTION=""
# disable to enable autocommit
#MYSQLDUMP_AUTOCOMMIT="1"
# set to enable complete inserts (true by default, disabling enable extended inserts)
#MYSQLDUMP_COMPLETEINSERTS="1"
# do we disable mysqldump --lock-tables=false
#MYSQLDUMP_LOCKTABLES=""
# set to add extra dumps info
#MYSQLDUMP_DEBUG=""
# set to disable dump routines
#MYSQLDUMP_NOROUTINES=""
# do we use ssl to connect
#MYSQL_USE_SSL=""
######## mongodb
# MONGODB_PATH="\${MONGODB_PATH:-"/var/lib/mongodb"}"
# MONGODB_USER="\${MONGODB_USER:-""}"
# MONGODB_PASSWORD="\${MONGODB_PASSWORD:-"\${PASSWORD}"}"
# MONGODB_ARGS="\${MONGODB_ARGS:-""}"
######## Redis
# REDIS_PATH="\${REDIS_PATH:-"/var/lib/redis"}"
######## Hooks (optionnal)
# functions names which point to functions defined in your
# configuration file
# Pay attention not to make function names colliding with functions in the script
#
# All those hooks can call externals programs (eg: python scripts)
# Look inside the shell script to know which variables you ll have
# set in the context, but you ll have useful information available at
# each stage like the dbname, etc.
#
# Function to run before backups (uncomment to use)
#pre_backup_hook() {
#}
# Function to run after global backup (uncomment to use)
#post_global_backup_hook() {
#}
# Function to run after global backup (uncomment to use)
#post_global_backup_failure_hook() {
#}
# Fuction run after each database backup if the backup failed
#post_db_backup_failure_hook() {
#}
# Function to run after each database backup (uncomment to use)
#post_db_backup_hook() {
#}
# Function to run after backup rotation
#post_rotate_hook() {
#}
# Function to run after backup orphan cleanup
#post_cleanup_hook() {
#}
# Function run after backups (uncomment to use)
#post_backup_hook="mycompany_postbackup"
# Function to run after the recap mail emission
#failure_hook() {
#}
# vim:set ft=sh:
EOF
chmod 640 "${DSB_CONF_FILE}"
}
fn_exists() {
echo $(LC_ALL=C;LANG=C;type ${1} 2>&1 | head -n1 | grep -q "is a function";echo $?)
}
print_name() {
echo -e "[${__NAME__}]"
}
log() {
echo -e "${RED}$(print_name) ${@}${NORMAL}" 1>&2
}
cyan_log() {
echo -e "${CYAN}${@}${NORMAL}" 1>&2
}
die_() {
ret="${1}"
shift
cyan_log "ABRUPT PROGRAM TERMINATION: ${@}"
do_hook "FAILURE command output" "failure_hook"
exit ${ret}
}
die() {
die_ 1 "${@}"
}
die_in_error_() {
ret="${1}"
shift
msg="${@:-"${ERROR_MSG}"}"
if [ x"${ret}" != "x0" ];then
die_ "${ret}" "${msg}"
fi
}
die_in_error() {
die_in_error_ "$?" "${@}"
}
yellow_log(){
echo -e "${YELLOW}$(print_name) ${@}${NORMAL}" 1>&2
}
readable_date() {
date +"%Y-%m-%d %H:%M:%S.%N"
}
debug() {
if [ x"${DSB_DEBUG}" != "x" ];then
yellow_log "DEBUG $(readable_date): $@"
fi
}
remove_files() {
for i in $@;do if [ -e $i ];then rm -f "$i";fi;done
}
usage() {
cyan_log "- Backup your databases with ease"
yellow_log " $0"
yellow_log " /path/toconfig"
yellow_log " alias to --backup"
yellow_log " -b|--backup /path/toconfig:"
yellow_log " backup databases"
yellow_log " --gen-config [/path/toconfig (default: ${DSB_CONF_FILE}_DEFAULT)]"
yellow_log " generate a new config file]"
}
runas() {
echo "${RUNAS:-"$(whoami)"}"
}
quote_all() {
cmd=""
for i in "${@}";do
cmd="${cmd} \"$(echo "${i}"|sed "s/\"/\"\'\"/g")\""
done
echo "${cmd}"
}
runcmd_as() {
cd "${RUNAS_DIR:-/}"
bin="${1}"
shift
args=$(quote_all "${@}")
if [ x"$(runas)" = "x" ] || [ x"$(runas)" = "x$(whoami)" ];then
${bin} "${@}"
else
su ${RUNAS} -c "${bin} ${args}"
fi
}
get_compressed_name() {
if [ x"${COMP}" = "xxz" ];then
echo "${1}.xz";
elif [ x"${COMP}" = "xgz" ] || [ x"${COMP}" = "xgzip" ];then
echo "${1}.gz";
elif [ x"${COMP}" = "xbzip2" ] || [ x"${COMP}" = "xbz2" ];then
echo "${1}.bz2";
elif [ x"${COMP}" = "xzstd" ] || [ x"${COMP}" = "xzst" ];then
echo "${1}.zst";
else
echo "${1}";
fi
}
set_compressor() {
for comp in ${COMP} ${COMPS};do
c=""
if [ x"${comp}" = "xxz" ];then
XZ="${XZ:-xz}"
c="${XZ}"
elif [ x"${comp}" = "xgz" ] || [ x"${comp}" = "xgzip" ];then
GZIP="${GZIP:-gzip}"
c="${GZIP}"
elif [ x"${comp}" = "xbzip2" ] || [ x"${comp}" = "xbz2" ];then
BZIP2="${BZIP2:-bzip2}"
c="${BZIP2}"
elif [ x"${comp}" = "xzstd" ] || [ x"${comp}" = "xzst" ];then
ZSTD="${ZSTD:-zstd}"
c="${ZSTD}"
else
c="nocomp"
fi
# test that the binary is present
if [ x"$c" != "xnocomp" ] && [ -e "$(which "$c")" ];then
COMP=$c
break
else
COMP="nocomp"
fi
done
export COMP=$COMP
}
comp_msg() {
sz="";s1="";s2="";ratio=""
if [ -e "$zname" ];then
sz="$(du -sh "$zname"|awk '{print $1}') "
s1="$(du -sb "$zname"|awk '{print $1}')"
fi
if [ -e "$name" ];then
s2="$(du -sb "$name"|awk '{print $1}')"
fi
if [ -e "$zname" ] && [ -e "$name" ];then
ratio=$(echo "$s1" "${s2}" | awk '{printf "%.2f \n", $1/$2}')
fi
log "${RED}${NORMAL}${YELLOW} ${COMP}${NORMAL}${RED} -> ${YELLOW}${zname}${NORMAL} ${RED}(${NORMAL}${YELLOW} ${sz} ${NORMAL}${RED}/${NORMAL} ${YELLOW}${ratio}${NORMAL}${RED})${NORMAL}"
}
cleanup_uncompressed_dump_if_ok() {
comp_msg
dumpfiles=""
if [ x"$?" != x"0" ];then
dumpfiles="${zname}"
fi
if [ x"$?" = x"0" ];then
if [ "${PIPED_BACKUP_COMPRESSION}" != "x1" ];then
dumpfiles="${name}"
fi
fi
remove_files "$dumpfiles"
}
do_compression() {
COMPRESSED_NAME=""
name="${1}"
zname="${2:-$(get_compressed_name ${1})}"
if [ x"${COMP}" = "xxz" ];then
if [ "x${PIPED_BACKUP_COMPRESSION}" != "x1" ];then
"${XZ}" --stdout -f -k "${name}" > "${zname}"
else
"${XZ}" --stdout -f -k > "${zname}"
fi
cleanup_uncompressed_dump_if_ok
elif [ x"${COMP}" = "xgz" ] || [ x"${COMP}" = "xgzip" ];then
if [ "x${PIPED_BACKUP_COMPRESSION}" != "x1" ];then
"${GZIP}" -f -c "${name}" > "${zname}"
else
"${GZIP}" -f -c > "${zname}"
fi
cleanup_uncompressed_dump_if_ok
elif [ x"${COMP}" = "xbzip2" ] || [ x"${COMP}" = "xbz2" ];then
if [ "x${PIPED_BACKUP_COMPRESSION}" != "x1" ];then
"${BZIP2}" -f -k -c "${name}" > "${zname}"
else
"${BZIP2}" -f -k -c > "${zname}"
fi
cleanup_uncompressed_dump_if_ok
elif [ x"${COMP}" = "xzstd" ] || [ x"${COMP}" = "xzst" ];then
if [ "x${PIPED_BACKUP_COMPRESSION}" != "x1" ];then
"${ZSTD}" -f -c -q "${name}" > "${zname}"
else
"${ZSTD}" -f -c -q > "${zname}"
fi
cleanup_uncompressed_dump_if_ok
else
/bin/true # noop
fi
if ( [ -e "${zname}" ] && [ x"${zname}" != "x${name}" ] ) || [ "${PIPED_BACKUP_COMPRESSION}" = "x1" ];then
COMPRESSED_NAME="${zname}"
else
if [ -e "${name}" ];then
log "No compressor found, no compression done"
COMPRESSED_NAME="${name}"
else
log "Compression error"
fi
fi
if [ x"${COMPRESSED_NAME}" != "x" ];then
fix_perm "${fic}"
fi
}
get_logsdir() {
dir="${TOP_BACKUPDIR}/logs"
echo "$dir"
}
get_logfile() {
filen="$(get_logsdir)/${__NAME__}_${FULL_FDATE}.log"
echo ${filen}
}
get_backupdir() {
dir="${TOP_BACKUPDIR}/${BACKUP_TYPE:-}"
if [ x"${BACKUP_TYPE}" = "xpostgresql" ];then
host="${HOST}"
if [ x"${HOST}" = "x" ] || [ x"${PGHOST}" = "x" ];then
host="localhost"
fi
if [ -e $host ];then
host="localhost"
fi
dir="$dir/$host"
fi
echo "$dir"
}
create_db_directories() {
db="${1}"
dbdir="$(get_backupdir)/${db}"
created="0"
for d in\
"$dbdir"\
"$dbdir/weekly"\
"$dbdir/monthly"\
"$dbdir/dumps"\
"$dbdir/daily"\
"$dbdir/lastsnapshots"\
;do
if [ ! -e "$d" ];then
mkdir -p "$d"
created="1"
fi
done
if [ x"${created}" = "x1" ];then
fix_perms
fi
}
link_into_dirs() {
db="${1}"
real_filename="${2}"
real_zfilename="$(get_compressed_name "${real_filename}")"
daily_filename="$(get_backupdir)/${db}/daily/${db}_${YEAR}_${DOY}_${DATE}.${BACKUP_EXT}"
lastsnapshots_filename="$(get_backupdir)/${db}/lastsnapshots/${db}_${YEAR}_${DOY}_${FDATE}.${BACKUP_EXT}"
weekly_filename="$(get_backupdir)/${db}/weekly/${db}_${YEAR}_${W}.${BACKUP_EXT}"
monthly_filename="$(get_backupdir)/${db}/monthly/${db}_${YEAR}_${MNUM}.${BACKUP_EXT}"
lastsnapshots_zfilename="$(get_compressed_name "${lastsnapshots_filename}")"
daily_zfilename="$(get_compressed_name "${daily_filename}")"
weekly_zfilename="$(get_compressed_name "$weekly_filename")"
monthly_zfilename="$(get_compressed_name "${monthly_filename}")"
if [ ! -e "${daily_zfilename}" ];then
ln "${real_zfilename}" "${daily_zfilename}"
fi
if [ ! -e "${weekly_zfilename}" ];then
ln "${real_zfilename}" "${weekly_zfilename}"
fi
if [ ! -e "${monthly_zfilename}" ];then
ln "${real_zfilename}" "${monthly_zfilename}"
fi
if [ ! -e "${lastsnapshots_zfilename}" ];then
ln "${real_zfilename}" "${lastsnapshots_zfilename}"
fi
}
dummy_callee_for_tests() {
echo "here"
}
dummy_for_tests() {
dummy_callee_for_tests
}
remove_backup_status_files() {
remove_files "$statusfile" "$statusfile.c"
}
do_db_backup_() {
LAST_BACKUP_STATUS=""
db="${1}"
fun_="${2}"
create_db_directories "${db}"
real_filename="$(get_backupdir)/${db}/dumps/${db}_${FDATE}.${BACKUP_EXT}"
zreal_filename="$(get_compressed_name "${real_filename}")"
statusfile=$(mktemp)
remove_backup_status_files
adb="${YELLOW}${db}${NORMAL} "
if [ x"${db}" = x"${GLOBAL_SUBDIR}" ];then
adb=""
fi
log "Dumping database ${adb}${RED}to maybe uncompressed dump: ${YELLOW}${real_filename}${NORMAL}"
if [ "x${PIPED_BACKUP_COMPRESSION}" = "x1" ];then
# ensure backup + compression is atomic with the absence of +o pipefail in old posix shells
( $fun_ "${db}" "${real_filename}" && touch "$statusfile" ) \
| ( do_compression "${real_filename}" "${zreal_filename}" && touch "$statusfile.c" )
if [ "x$?" != "x0" ] || ! ( [ -e "$statusfile" ] && [ -e "$statusfile.c" ] );then
remove_backup_status_files
LAST_BACKUP_STATUS="failure"
log "${CYAN} Backup of ${db} failed !!!${NORMAL}"
fi
else
$fun_ "${db}" "${real_filename}"
fi
if [ x"$?" != "x0" ];then
LAST_BACKUP_STATUS="failure"
log "${CYAN} Backup of ${db} failed !!!${NORMAL}"
else
if [ "x${PIPED_BACKUP_COMPRESSION}" != "x1" ];then
do_compression "${real_filename}" "${zreal_filename}"
fi
link_into_dirs "${db}" "${real_filename}"
fi
}
do_db_backup() {
db="`echo ${1} | sed 's/%/ /g'`"
fun_="${BACKUP_TYPE}_dump"
do_db_backup_ "${db}" "$fun_"
}
do_global_backup() {
db="$GLOBAL_SUBDIR"
fun_="${BACKUP_TYPE}_dumpall"
log_rule
log "GLOBAL BACKUP"
log_rule
do_db_backup_ "${db}" "$fun_"
}
activate_IO_redirection() {
if [ x"${DSB_ACTITED_RIO}" = x"" ];then
DSB_ACTITED_RIO="1"
logdir="$(dirname $(get_logfile))"
if [ ! -e "${logdir}" ];then
mkdir -p "${logdir}"
fi
touch "$(get_logfile)"
exec 1> >(tee -a "$(get_logfile)") 2>&1
fi
}
deactivate_IO_redirection() {
if [ x"${DSB_ACTITED_RIO}" != x"" ];then
DSB_ACTITED_RIO=""
exec 1>&1 # Restore stdout and close file descriptor #6.
exec 2>&2 # Restore stdout and close file descriptor #7.
fi
}
do_pre_backup() {
debug "do_pre_backup"
# IO redirection for logging.
if [ x"$COMP" = "xnocomp" ];then
comp_msg="No compression"
else
comp_msg="${COMP}"
fi
# If backing up all DBs on the server
log_rule
log "DB_SMART_BACKUP by kiorky@cryptelium.net / http://www.makina-corpus.com"
log "Conf: ${YELLOW}'${DSB_CONF_FILE}'"
log "Log: ${YELLOW}'$(get_logfile)'"
log "Backup Start Time: ${YELLOW}$(readable_date)${NORMAL}"
log "Backup of database compression://type@server: ${YELLOW}${comp_msg}://${BACKUP_TYPE}@${HOST}${NORMAL}"
log_rule
}
fix_perm() {
fic="${1}"
if [ -e "${fic}" ];then
if [ -d "${fic}" ];then
perm="${DPERM:-750}"
elif [ -f "${fic}" ];then
perm="${FPERM:-640}"
fi
chown ${OWNER:-"root"}:${GROUP:-"root"} "${fic}"
chmod -f $perm "${fic}"
fi
}
fix_perms() {
debug "fix_perms"
find "${TOP_BACKUPDIR}" -type d -print|\
while read fic
do
fix_perm "${fic}"
done
find "${TOP_BACKUPDIR}" -type f -print|\
while read fic
do
fix_perm "${fic}"
done
}
wrap_log() {
echo -e "$("$@"|sed "s/^/$(echo -e "${NORMAL}${RED}")$(print_name) $(echo -e "${NORMAL}${YELLOW}")/g"|sed "s/\t/ /g"|sed "s/ +/ /g")${NORMAL}"
}
do_post_backup() {
# Run command when we're done
log_rule
debug "do_post_backup"
log "Total disk space used for backup storage.."
log " Size - Location:"
wrap_log du -shc "$(get_backupdir)"/*
log_rule
log "Backup end time: ${YELLOW}$(readable_date)${NORMAL}"
log_rule
deactivate_IO_redirection
sanitize_log
}
sanitize_log() {
sed -i -e "s/\x1B\[[0-9;]*[JKmsu]//g" "$(get_logfile)"
}
get_sorted_files() {
files="$(ls -1 "${1}" 2>/dev/null)"
sep="____----____----____"
echo -e "${files}"|while read fic;do
key=""
oldkey="${fic}"
while true;do
key="$(echo "${oldkey}"|sed -e "s/_\([0-9][^0-9]\)/_0\1/g")"
if [ x"${key}" != x"${oldkey}" ];then
oldkey="${key}"
else
break
fi
done
echo "${key}${sep}${fic}"
done | sort -n -r | awk -F"$sep" '{print $2}'
}
do_rotate() {
log_rule
debug "rotate"
log "Execute backup rotation policy, keep"
log " - logs : ${YELLOW}${KEEP_LOGS}${NORMAL}"
log " - last snapshots : ${YELLOW}${KEEP_LASTS}${NORMAL}"
log " - daily dumps : ${YELLOW}${KEEP_DAYS}${NORMAL}"
log " - weekly dumpss : ${YELLOW}${KEEP_WEEKS}${NORMAL}"
log " - monthly dumps : ${YELLOW}${KEEP_MONTHES}${NORMAL}"
# ./TOPDIR/POSTGRESQL/HOSTNAME
# or ./TOPDIR/logs for logs
ls -1d "${TOP_BACKUPDIR}" "$(get_backupdir)"/*|while read nsubdir;do
# ./TOPDIR/HOSTNAME/DBNAME/${monthly,weekly,daily,dumps}
suf=""
if [ x"$nsubdir" = "x${TOP_BACKUPDIR}" ];then
subdirs="logs"
suf="/logs"
else
subdirs="monthly weekly daily lastsnapshots"
fi
log " - Operating in: ${YELLOW}'${nsubdir}${suf}'${NORMAL}"
for chronodir in ${subdirs};do
subdir="${nsubdir}/${chronodir}"
if [ -d "${subdir}" ];then
if [ x"${chronodir}" = "xlogs" ];then
to_keep=${KEEP_LOGS:-60}
elif [ x"${chronodir}" = "xweekly" ];then
to_keep=${KEEP_WEEKS:-2}
elif [ x"${chronodir}" = "xmonthly" ];then
to_keep=${KEEP_MONTHES:-2}
elif [ x"${chronodir}" = "xdaily" ];then
to_keep=${KEEP_DAYS:-2}
elif [ x"${chronodir}" = "xlastsnapshots" ];then
to_keep=${KEEP_LASTS:-2}
else
to_keep="65535" # int limit
fi
i=0
get_sorted_files "${subdir}" | while read nfic;do
dfic="${subdir}/${nfic}"
i="$((${i}+1))"
if [ "${i}" -gt "${to_keep}" ] &&\
[ -e "${dfic}" ] &&\
[ ! -d ${dfic} ];then
log " * Unlinking ${YELLOW}${dfic}${NORMAL}"
remove_files "${dfic}"
fi
done
fi
done
done
}
log_rule() {
log "======================================================================"
}
handle_hook_error() {
debug "handle_hook_error"
log "Unexpected exit of ${HOOK_CMD} hook, you should never issue an exit in a hook"
log_rule
DSB_RETURN_CODE="1"
handle_exit
}
do_prune() {
do_rotate
do_hook "Postrotate command output" "post_rotate_hook"
do_cleanup_orphans
do_hook "Postcleanup command output" "post_cleanup_hook"
fix_perms
do_post_backup
do_hook "Postbackup command output" "post_backup_hook"
}
handle_exit() {
DSB_RETURN_CODE="${DSB_RETURN_CODE:-$?}"
if [ x"${DSB_BACKUP_STARTED}" != "x" ];then
debug "handle_exit"
DSB_HOOK_NO_TRAP="1"
do_prune
if [ x"$DSB_RETURN_CODE" != "x0" ];then
log "WARNING, this script did not behaved correctly, check the log: $(get_logfile)"
fi
if [ x"${DSB_GLOBAL_BACKUP_IN_FAILURE}" != x"" ];then
cyan_log "Global backup failed, check the log: $(get_logfile)"
DSB_RETURN_CODE="${DSB_BACKUP_FAILED}"
fi
if [ x"${DSB_BACKUP_IN_FAILURE}" != x"" ];then
cyan_log "One of the databases backup failed, check the log: $(get_logfile)"
DSB_RETURN_CODE="${DSB_BACKUP_FAILED}"
fi
fi
exit "${DSB_RETURN_CODE}"
}
do_trap() {
debug "do_trap"
trap handle_exit EXIT SIGHUP SIGINT SIGQUIT SIGTERM
}
do_cleanup_orphans() {
log_rule
debug "do_cleanup_orphans"
log "Cleaning orphaned dumps:"
# prune all files in dumps dirs which have no more any
# hardlinks in chronoted directories (weekly, monthly, daily)
find "$(get_backupdir)" -type f -links 1 -print 2>/dev/null|\
while read fic
do
log " * Pruning ${YELLOW}${fic}${NORMAL}"
remove_files "${fic}"
done
}
do_hook() {
HOOK_HEADER="${1}"
HOOK_CMD="${2}"
if [ x"${DSB_HOOK_NO_TRAP}" = "x" ];then
trap handle_hook_error EXIT SIGHUP SIGINT SIGQUIT SIGTERM
fi
if [ x"$(fn_exists ${HOOK_CMD})" = "x0" ];then
debug "do_hook ${HOOK_CMD}"
log_rule
log "HOOK: ${YELLOW} ${HOOK_HEADER}"
"${HOOK_CMD}"
log_rule
log ""
fi
if [ x"${DSB_HOOK_NO_TRAP}" = "x" ];then
trap handle_exit EXIT SIGHUP SIGINT SIGQUIT SIGTERM
fi
}
do_backup() {
debug "do_backup"
if [ x"${BACKUP_TYPE}" = "x" ];then
die "No backup type, choose between mysql,postgresql,redis,mongodb,slapd,es"
fi
# if either the source failed or we do not have a configuration file, bail out
die_in_error "Invalid configuration file: ${DSB_CONF_FILE}"
DSB_BACKUP_STARTED="y"
do_pre_backup
do_hook "Prebackup command output" "pre_backup_hook"
if [ x"${DO_GLOBAL_BACKUP}" != "x" ];then
do_global_backup
if [ x"${LAST_BACKUP_STATUS}" = "xfailure" ];then
do_hook "Postglobalbackup command output" "post_global_backup_hook"
DSB_GLOBAL_BACKUP_IN_FAILURE="y"
else
do_hook "Postglobalbackup(failure) command output" "post_global_backup_failure_hook"
fi
fi
if [ "x${BACKUP_DB_NAMES}" != "x" ];then
log_rule
log "DATABASES BACKUP"
log_rule
for db in ${BACKUP_DB_NAMES};do
do_db_backup $db
if [ x"${LAST_BACKUP_STATUS}" = "xfailure" ];then
do_hook "Postdbbackup: ${db} command output" "post_db_backup_hook"
DSB_BACKUP_IN_FAILURE="y"
else
do_hook "Postdbbackup: ${db}(failure) command output" "post_db_backup_failure_hook"
fi
done
fi
}
mark_run_rotate() {
DSB_CONF_FILE="${1}"
DO_PRUNE="1"
}
mark_run_backup() {
DSB_CONF_FILE="${1}"
DO_BACKUP="1"
}
verify_backup_type() {
for typ_ in _dump _dumpall;do
if [ x"$(fn_exists ${BACKUP_TYPE}${typ_})" != "x0" ];then
die "Please provide a ${BACKUP_TYPE}${typ_} export function"
fi
done
}
db_user() {
echo "${DBUSER:-${RUNAS:-$(whoami)}}"
}
set_colors() {
YELLOW="\e[1;33m"
RED="\\033[31m"
CYAN="\\033[36m"
NORMAL="\\033[0m"
if [ x"$NO_COLOR" != "x" ] || [ x"$NOCOLOR" != "x" ] || [ x"$NO_COLORS" != "x" ] || [ x"$NOCOLORS" != "x" ];then
YELLOW=""
RED=""
CYAN=""
NORMAL=""
fi
}
set_vars() {
debug "set_vars"
args=${@}
set_colors
PARAM=""
DSB_CONF_FILE_DEFAULT="/etc/db_smartbackup.conf.sh"
parsable_args="$(echo "${@}"|sed "s/^--//g")"
if [ x"${parsable_args}" = "x" ];then
USAGE="1"
fi
if [ -e "${parsable_args}" ];then
mark_run_backup ${1}
else
while true
do
sh="1"
if [ x"${1}" = "x$PARAM" ];then
break
fi
if [ x"${1}" = "x--gen-config" ];then
DSB_GENERATE_CONFIG="1"
DSB_CONF_FILE="${2:-${DSB_CONF_FILE_DEFAULT}}"
sh="2"
elif [ x"${1}" = "x-p" ] || [ x"${1}" = "x--prune" ];then
mark_run_rotate ${2};sh="2"
elif [ x"${1}" = "x-b" ] || [ x"${1}" = "x--backup" ];then
mark_run_backup ${2};sh="2"
else
if [ x"${DB_SMART_BACKUP_AS_FUNCS}" = "x" ];then
usage
die "Invalid invocation"
fi
fi
PARAM="${1}"
OLD_ARG="${1}"
for i in $(seq $sh);do
shift
if [ x"${1}" = "x${OLD_ARG}" ];then
break
fi
done
if [ x"${1}" = "x" ];then
break
fi
done
fi
######## Backup settings
NO_COLOR="${NO_COLOR:-}"
COMP=${COMP:-xz}
BACKUP_TYPE=${BACKUP_TYPE:-}
TOP_BACKUPDIR="${TOP_BACKUPDIR:-/var/db_smart_backup}"
DEFAULT_DO_GLOBAL_BACKUP="1"
if [ "x${BACKUP_TYPE}" = "xes" ];then
DEFAULT_DO_GLOBAL_BACKUP=""
fi
DO_GLOBAL_BACKUP="${DO_GLOBAL_BACKUP-${DEFAULT_DO_GLOBAL_BACKUP}}"
KEEP_LASTS="${KEEP_LASTS:-24}"
KEEP_DAYS="${KEEP_DAYS:-14}"
KEEP_WEEKS="${KEEP_WEEKS:-8}"
KEEP_MONTHES="${KEEP_MONTHES:-12}"
KEEP_LOGS="${KEEP_LOGS:-60}"
DPERM="${DPERM:-"750"}"
FPERM="${FPERM:-"640"}"
OWNER="${OWNER:-"root"}"
GROUP="${GROUP:-"root"}"
######## Database connection settings
HOST="${HOST:-localhost}"
PORT="${PORT:-}"
RUNAS="" # see runas function
DBUSER="" # see db_user function
PASSWORD="${PASSWORD:-}"
DBNAMES="${DBNAMES:-all}"
DBEXCLUDE="${DBEXCLUDE:-}"
######## hostname
GET_HOSTNAME=`hostname -f`
if [ x"${GET_HOSTNAME}" = x"" ]; then
GET_HOSTNAME=`hostname -s`
fi
######## Mail setup
MAILCONTENT="${MAILCONTENT:-stdout}"
MAXATTSIZE="${MAXATTSIZE:-4000}"
MAILADDR="${MAILADDR:-root@localhost}"
MAIL_SERVERNAME="${MAIL_SERVERNAME:-${GET_HOSTNAME}}"
######### Postgresql
PSQL="${PSQL:-"$(which psql 2>/dev/null)"}"
PG_DUMP="${PG_DUMP:-"$(which pg_dump 2>/dev/null)"}"
PG_DUMPALL="${PG_DUMPALL:-"$(which pg_dumpall 2>/dev/null)"}"
OPT="${OPT:-"--create -Fc -Z0"}"
OPTALL="${OPTALL:-"--globals-only"}"
######### MYSQL
MYSQL_USE_SSL="${MYSQL_USE_SSL:-}"
MYSQL_SOCK_PATHS="${MYSQL_SOCK_PATHS:-"/var/run/mysqld/mysqld.sock"}"
MYSQL="${MYSQL:-$(which mysql 2>/dev/null)}"
MYSQLDUMP="${MYSQLDUMP:-$(which mysqldump 2>/dev/null)}"
MYSQLDUMP_NO_SINGLE_TRANSACTION="${MYSQLDUMP_NO_SINGLE_TRANSACTION:-}"
MYSQLDUMP_AUTOCOMMIT="${MYSQLDUMP_AUTOCOMMIT:-1}"
MYSQLDUMP_COMPLETEINSERTS="${MYSQLDUMP_COMPLETEINSERTS:-1}"
MYSQLDUMP_LOCKTABLES="${MYSQLDUMP_LOCKTABLES:-}"
MYSQLDUMP_DEBUG="${MYSQLDUMP_DEBUG:-}"
MYSQLDUMP_NOROUTINES="${MYSQLDUMP_NOROUTINES:-}"
# mongodb
MONGODB_PATH="${MONGODB_PATH:-"/var/lib/mongodb"}"
MONGODB_USER="${MONGODB_USER:-"${DBUSER}"}"
MONGODB_PASSWORD="${MONGODB_PASSWORD:-"${PASSWORD}"}"
MONGODB_ARGS="${MONGODB_ARGS:-""}"
# slapd
SLAPCAT_ARGS="${SLAPCAT_ARGS:-""}"
SLAPD_DIR="${SLAPD_DIR:-/var/lib/ldap}"
######## Hooks
pre_backup_hook="${pre_backup_hook:-}"
post_global_backup_hook="${post_global_backup_hook-}"
post_db_backup_hook="${post_db_backup_hook-}"
post_backup_hook="${post_backup_hook-}"
######## Advanced options
COMPS="${COMPS-"xz zstd bz2 gzip nocomp"}"
COMP="${COMP-"${COMPS}"}"
GLOBAL_SUBDIR="__GLOBAL__"
PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
DATE=`date +%Y-%m-%d` # Datestamp e.g 2002-09-21
FDATE=`date +%Y-%m-%d_%H-%M-%S` # Datestamp e.g 2002-09-21
FULL_FDATE=`date +%Y-%m-%d_%H-%M-%S.%N` # Datestamp e.g 2002-09-21
DOY=`date +%j` # Day of the YEAR 0..366
DOW=`date +%A` # Day of the week e.g. Monday
DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday
DOM=`date +%d` # Date of the Month e.g. 27
M=`date +%B` # Month e.g January
YEAR=`date +%Y` # Datestamp e.g 2002-09-21
MNUM=`date +%m` # Month e.g 1
W=`date +%V` # Week Number e.g 37
DSB_BACKUPFILES="" # thh: added for later mailing
DSB_RETURN_CODE=""
DSB_GLOBAL_BACKUP_FAILED="3"
DSB_BACKUP_FAILED="4"
# source conf file if any
if [ -e "${DSB_CONF_FILE}" ];then
. "${DSB_CONF_FILE}"
fi