autopostgresqlbackup 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. #!/usr/bin/env bash
  2. # {{{ License and Copyright
  3. # PostgreSQL Backup Script
  4. # https://github.com/k0lter/autopostgresqlbackup
  5. # Copyright (c) 2005 Aaron Axelsen <axelseaa@amadmax.com>
  6. # 2005 Friedrich Lobenstock <fl@fl.priv.at>
  7. # 2013-2023 Emmanuel Bouthenot <kolter@openics.org>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  22. # }}}
  23. # {{{ Variables
  24. # Email Address to send errors to
  25. MAILADDR="root"
  26. # By default, on Debian systems (and maybe others), only postgres user is
  27. # allowed to access PostgreSQL databases without password.
  28. #
  29. # In order to dump databases we need to run pg_dump/psql commands as postgres
  30. # with su. This setting makes possible to run backups with a substitute user
  31. # using su. If
  32. #
  33. # empty, su usage will be disabled)
  34. SU_USERNAME=
  35. # Username to access the PostgreSQL server
  36. USERNAME="postgres"
  37. # Password settings
  38. # In order to use a password to connect to database create a file
  39. # ${HOME}/.pgpass containing a line like this
  40. #
  41. # hostname:*:*:dbuser:dbpass
  42. #
  43. # replace hostname with the value of ${DBHOST}, dbuser with the value of
  44. # ${USERNAME} and dbpass with the password.
  45. # Host name (or IP address) of PostgreSQL server
  46. DBHOST="localhost"
  47. # Port of PostgreSQL server (only used if ${DBHOST} != localhost).
  48. DBPORT="5432"
  49. # List of database(s) names(s) to backup If you would like to backup all
  50. # databases on the server set DBNAMES="all".
  51. #
  52. # If set to "all" then any new databases will automatically be backed up
  53. # without needing to modify this settings when a new database is created.
  54. #
  55. # If the database you want to backup has a space in the name replace the space
  56. # with a % ("data base" will become "data%base").
  57. DBNAMES="all"
  58. # List of databases to exclude if DBNAMES is not set to all.
  59. DBEXCLUDE=""
  60. # Pseudo database name used to dump global objects (users, roles, tablespaces)
  61. GLOBALS_OBJECTS="postgres_globals"
  62. # Backup directory
  63. BACKUPDIR="/var/backups"
  64. # Include CREATE DATABASE in backups?
  65. CREATE_DATABASE="yes"
  66. # Which day do you want weekly backups? (1 to 7 where 1 is Monday)
  67. # When set to 0, weekly backups are disabled
  68. DOWEEKLY=7
  69. # Which day do you want monthly backups?
  70. # When set to 0, monthly backups are disabled
  71. DOMONTHLY=1
  72. # Backup retention count for daily backups, older backups are removed.
  73. BRDAILY=14
  74. # Backup retention count for weekly backups, older backups are removed.
  75. BRWEEKLY=5
  76. # Backup retention count for monthly backups, older backups are removed.
  77. BRMONTHLY=12
  78. # Compression tool. It could be gzip, pigz, bzip2, xz, zstd or any compression
  79. # tool that supports to read data to be compressed from stdin and outputs them
  80. # to stdout).
  81. # If the tool is not in ${PATH}, the absolute path can be used.
  82. COMP="gzip"
  83. # Compression tools options to be used with COMP
  84. COMP_OPTS=
  85. # Options string for use with pg_dump (see pg_dump manual page).
  86. PGDUMP_OPTS=
  87. # Options string for use with pg_dumpall (see pg_dumpall manual page).
  88. PGDUMPALL_OPTS=
  89. # Backup files extension
  90. EXT="sql"
  91. # Backup files permission
  92. PERM=600
  93. # Minimum size (in bytes) for a dump/file (compressed or not).
  94. # File size below this limit will raise an warning.
  95. MIN_DUMP_SIZE=256
  96. # Enable encryption (asymmetric) with GnuPG.
  97. ENCRYPTION="no"
  98. # Encryption public key (path to the key)
  99. # Export your public key=""
  100. # gpg --export 0xY0URK3Y1D --output mypubkey.gpg or \
  101. # gpg --export --armor 0xY0URK3Y1D --output mypubkey.asc
  102. # then copy mypubkey.asc or mypubkey.gpg to the path pointed by the
  103. # ${ENCRYPTION_PUBLIC_KEY}.
  104. #
  105. # Decryption
  106. # gpg --decrypt --output backup.sql.gz backup.sql.gz.enc
  107. #
  108. ENCRYPTION_PUBLIC_KEY=
  109. # Suffix for encyrpted files
  110. ENCRYPTION_SUFFIX=".enc"
  111. # Command or script to execute before backups
  112. PREBACKUP=
  113. # Command or script to execute after backups
  114. POSTBACKUP=
  115. # }}}
  116. # {{{ OS Specific
  117. if [ -f /etc/default/autopostgresqlbackup ]; then
  118. # shellcheck source=/dev/null
  119. . /etc/default/autopostgresqlbackup
  120. fi
  121. # }}}
  122. # {{{ Defaults
  123. PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/postgres/bin:/usr/local/pgsql/bin
  124. HOMEPAGE="https://github.com/k0lter/autopostgresqlbackup"
  125. NAME="AutoPostgreSQLBackup" # Script name
  126. VERSION="2.0" # Version Number
  127. DATE="$(date '+%Y-%m-%d_%Hh%Mm')" # Datestamp e.g 2002-09-21
  128. DNOW="$(date '+%u')" # Day number of the week 1 to 7 where 1 represents Monday
  129. DNOM="$(date '+%d')" # Date of the Month e.g. 27
  130. LOG_DIR="${BACKUPDIR}" # Directory where the main log is saved
  131. # Fix day of month (left padding with 0)
  132. DOMONTHLY="$(echo "${DOMONTHLY}" | sed -r 's/^[0-9]$/0\0/')"
  133. # Using a shared memory filesystem (if available) to avoid
  134. # issues when there is no left space on backup storage
  135. if [ -w "/dev/shm" ]; then
  136. LOG_DIR="/dev/shm"
  137. fi
  138. LOG_FILE="${LOG_DIR}/${NAME}_${DBHOST//\//_}-$(date '+%Y-%m-%d_%Hh%Mm').log"
  139. # Debug mode
  140. DEBUG="no"
  141. # Encryption prerequisites
  142. GPG_HOMEDIR=
  143. # pg_dump options
  144. if [ -n "${PGDUMP_OPTS}" ]; then
  145. IFS=" " read -r -a PGDUMP_ARGS <<< "${PGDUMP_OPTS}"
  146. else
  147. PGDUMP_ARGS=()
  148. fi
  149. # pg_dumpall options
  150. if [ -n "${PGDUMPALL_OPTS}" ]; then
  151. IFS=" " read -r -a PGDUMPALL_ARGS <<< "${PGDUMPALL_OPTS}"
  152. else
  153. PGDUMPALL_ARGS=()
  154. fi
  155. # Create required directories
  156. if [ ! -e "${BACKUPDIR}" ]; then # Check Backup Directory exists.
  157. mkdir -p "${BACKUPDIR}"
  158. fi
  159. if [ ! -e "${BACKUPDIR}/daily" ]; then # Check Daily Directory exists.
  160. mkdir -p "${BACKUPDIR}/daily"
  161. fi
  162. if [ ! -e "${BACKUPDIR}/weekly" ]; then # Check Weekly Directory exists.
  163. mkdir -p "${BACKUPDIR}/weekly"
  164. fi
  165. if [ ! -e "${BACKUPDIR}/monthly" ]; then # Check Monthly Directory exists.
  166. mkdir -p "${BACKUPDIR}/monthly"
  167. fi
  168. # Hostname for LOG information and
  169. # pg_dump{,all} connection settings
  170. if [ "${DBHOST}" = "localhost" ]; then
  171. HOST="$(hostname --fqdn)"
  172. PG_CONN=()
  173. else
  174. HOST="${DBHOST}:${DBPORT}"
  175. PG_CONN=(--host "${DBHOST}" --port "${DBPORT}")
  176. fi
  177. if [ -n "${USERNAME}" ]; then
  178. PG_CONN+=(--username "${USERNAME}")
  179. fi
  180. # }}}
  181. # {{{ log{,ger,_info,_debug,_warn,_error}()
  182. logger() {
  183. local fd line severity reset color
  184. fd="${1}"
  185. severity="${2}"
  186. reset=
  187. color=
  188. if [ -n "${TERM}" ]; then
  189. reset="\e[0m"
  190. case "${severity}" in
  191. error)
  192. color="\e[0;91m"
  193. ;;
  194. warn)
  195. color="\e[0;93m"
  196. ;;
  197. debug)
  198. color="\e[0;96m"
  199. ;;
  200. *)
  201. color="\e[0;94m"
  202. ;;
  203. esac
  204. fi
  205. while IFS= read -r line ; do
  206. printf "%s|%s|%s\n" "${fd}" "${severity}" "${line}" >> "${LOG_FILE}"
  207. if [ "${DEBUG}" = "yes" ]; then
  208. if [ "${fd}" = "out" ]; then
  209. printf "${color}%6s${reset}|%s\n" "${severity}" "${line}" >&6
  210. elif [ "${fd}" = "err" ]; then
  211. printf "${color}%6s${reset}|%s\n" "${severity}" "${line}" >&7
  212. fi
  213. fi
  214. done
  215. }
  216. log() {
  217. echo "$@" | logger "out" ""
  218. }
  219. log_debug() {
  220. echo "$@" | logger "out" "debug"
  221. }
  222. log_info() {
  223. echo "$@" | logger "out" "info"
  224. }
  225. log_error() {
  226. echo "$@" | logger "err" "error"
  227. }
  228. log_warn() {
  229. echo "$@" | logger "err" "warn"
  230. }
  231. # }}}
  232. # {{{ gpg_setup()
  233. gpg_setup() {
  234. GPG_HOMEDIR="$(mktemp --quiet --directory -t "${NAME}.XXXXXX")"
  235. chmod 700 "${GPG_HOMEDIR}"
  236. log_debug "With encryption enabled creating a temporary GnuPG home in ${GPG_HOMEDIR}"
  237. gpg --quiet --homedir "${GPG_HOMEDIR}" --quick-gen-key --batch --passphrase-file /dev/null "root@$(hostname --fqdn)"
  238. }
  239. # }}}
  240. # {{{ dblist()
  241. dblist () {
  242. local cmd_prog cmd_args raw_dblist dblist dbexcl databases
  243. cmd_prog="psql"
  244. cmd_args=(-t -l -A -F:)
  245. if [ "${#PG_CONN[@]}" -gt 0 ]; then
  246. cmd_args+=("${PG_CONN[@]}")
  247. fi
  248. log_debug "Running command: ${cmd_prog} ${cmd_args[*]}"
  249. raw_dblist=$(
  250. if [ -n "${SU_USERNAME}" ]; then
  251. if ! su - "${SU_USERNAME}" -c "${cmd_prog} ${cmd_args[*]}" 2> >(logger "err" "error"); then
  252. log_error "Running (as user '${SU_USERNAME}' command '${cmd_prog} ${cmd_args[*]}' has failed"
  253. fi
  254. elif ! "${cmd_prog}" "${cmd_args[@]}" 2> >(logger "err" "error"); then
  255. log_error "Running command '${cmd_prog} ${cmd_args[*]}' has failed"
  256. fi
  257. )
  258. read -r -a dblist <<< "$(
  259. printf "%s" "${raw_dblist}" | \
  260. sed -r -n 's/^([^:]+):.+$/\1/p' | \
  261. tr '\n' ' '
  262. )"
  263. log_debug "Automatically found databases: ${dblist[*]}"
  264. if [ -n "${DBEXCLUDE}" ]; then
  265. IFS=" " read -r -a dbexcl <<< "${DBEXCLUDE}"
  266. else
  267. dbexcl=()
  268. fi
  269. dbexcl+=(template0)
  270. log_debug "Excluded databases: ${dbexcl[*]}"
  271. mapfile -t databases < <(
  272. comm -23 \
  273. <(IFS=$'\n'; echo "${dblist[*]}" | sort) \
  274. <(IFS=$'\n'; echo "${dbexcl[*]}" | sort) \
  275. )
  276. databases+=("${GLOBALS_OBJECTS}")
  277. log_debug "Database(s) to be backuped: ${databases[*]}"
  278. printf "%s " "${databases[@]}"
  279. }
  280. # }}}
  281. # {{{ dbdump()
  282. dbdump () {
  283. local db_name cmd_prog cmd_args pg_args
  284. db_name="${1}"
  285. if [ "${db_name}" = "${GLOBALS_OBJECTS}" ]; then
  286. cmd_prog="pg_dumpall"
  287. cmd_args=(--globals-only)
  288. pg_args=("${PGDUMPALL_ARGS[@]}")
  289. else
  290. cmd_prog="pg_dump"
  291. cmd_args=("${db_name}")
  292. pg_args=("${PGDUMP_ARGS[@]}")
  293. if [ "${CREATE_DATABASE}" = "yes" ]; then
  294. pg_args+=(--create)
  295. fi
  296. fi
  297. if [ "${#PG_CONN[@]}" -gt 0 ]; then
  298. cmd_args+=("${PG_CONN[@]}")
  299. fi
  300. if [ "${#pg_args[@]}" -gt 0 ]; then
  301. cmd_args+=("${pg_args[@]}")
  302. fi
  303. log_debug "Running command: ${cmd_prog} ${cmd_args[*]}"
  304. if [ -n "${SU_USERNAME}" ]; then
  305. if ! su - "${SU_USERNAME}" -c "${cmd_prog} ${cmd_args[*]}" 2> >(logger "err" "error"); then
  306. log_error "Running (as user '${SU_USERNAME}' command '${cmd_prog} ${cmd_args[*]}' has failed"
  307. fi
  308. elif ! "${cmd_prog}" "${cmd_args[@]}" 2> >(logger "err" "error"); then
  309. log_error "Running command '${cmd_prog} ${cmd_args[*]}' has failed"
  310. fi
  311. }
  312. # }}}
  313. # {{{ encryption()
  314. encryption() {
  315. log_debug "Encrypting using public key ${ENCRYPTION_PUBLIC_KEY}"
  316. gpg --homedir "${GPG_HOMEDIR}" --encrypt --passphrase-file /dev/null --recipient-file "${ENCRYPTION_PUBLIC_KEY}" 2> >(logger "err" "error")
  317. }
  318. # }}}
  319. # {{{ compression()
  320. compression () {
  321. if [ -n "${COMP_OPTS}" ]; then
  322. IFS=" " read -r -a comp_args <<< "${COMP_OPTS}"
  323. log_debug "Compressing using '${COMP} ${comp_args[*]}'"
  324. "${COMP}" "${comp_args[@]}" 2> >(logger "err" "error")
  325. else
  326. log_debug "Compressing using '${COMP}'"
  327. "${COMP}" 2> >(logger "err" "error")
  328. fi
  329. }
  330. # }}}
  331. # {{{ dump()
  332. dump() {
  333. local db_name dump_file comp_ext
  334. db_name="${1}"
  335. dump_file="${2}"
  336. if [ -n "${COMP}" ]; then
  337. comp_ext=".comp"
  338. case "${COMP}" in
  339. gzip|pigz)
  340. comp_ext=".gz"
  341. ;;
  342. bzip2)
  343. comp_ext=".bz2"
  344. ;;
  345. xz)
  346. comp_ext=".xz"
  347. ;;
  348. zstd)
  349. comp_ext=".zstd"
  350. ;;
  351. esac
  352. dump_file="${dump_file}${comp_ext}"
  353. fi
  354. if [ "${ENCRYPTION}" = "yes" ]; then
  355. dump_file="${dump_file}${ENCRYPTION_SUFFIX}"
  356. fi
  357. if [ -n "${COMP}" ] && [ "${ENCRYPTION}" = "yes" ]; then
  358. log_debug "Dumping (${db_name}) +compress +encrypt to '${dump_file}'"
  359. dbdump "${db_name}" | compression | encryption > "${dump_file}"
  360. elif [ -n "${COMP}" ]; then
  361. log_debug "Dumping (${db_name}) +compress to '${dump_file}'"
  362. dbdump "${db_name}" | compression > "${dump_file}"
  363. elif [ "${ENCRYPTION}" = "yes" ]; then
  364. log_debug "Dumping (${db_name}) +encrypt to '${dump_file}'"
  365. dbdump "${db_name}" | encryption > "${dump_file}"
  366. else
  367. log_debug "Dumping (${db_name}) to '${dump_file}'"
  368. dbdump "${db_name}" > "${dump_file}"
  369. fi
  370. if [ -f "${dump_file}" ]; then
  371. log_debug "Fixing permissions (${PERM}) on '${dump_file}'"
  372. chmod "${PERM}" "${dump_file}"
  373. fsize=$(stat -c '%s' "${dump_file}")
  374. if [ ! -s "${dump_file}" ]; then
  375. log_error "Something went wrong '${dump_file}' is empty"
  376. elif [ "${fsize}" -lt "${MIN_DUMP_SIZE}" ]; then
  377. log_warn "'${dump_file}' (${fsize} bytes) is below the minimum required size (${MIN_DUMP_SIZE} bytes)"
  378. fi
  379. else
  380. log_error "Something went wrong '${dump_file}' does not exists (error during dump?)"
  381. fi
  382. }
  383. # }}}
  384. # {{{ cleanup()
  385. cleanup() {
  386. local dumpdir db when count line
  387. dumpdir="${1}"
  388. db="${2}"
  389. when="${3}"
  390. count="${4}"
  391. # Since version >= 2.0 the dump filename no longer contains the week number
  392. # or the abbreviated month name so in order to be sure to remove the older
  393. # dumps we need to sort the filename on the datetime part (YYYY-MM-DD_HHhMMm)
  394. log_info "Rotating ${count} ${when} backups..."
  395. log_debug "Looking for '${db}_*' in '${dumpdir}/${when}/${db}'"
  396. find "${dumpdir}/${when}/${db}/" -name "${db}_*" | \
  397. sed -r 's/^.+([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}h[0-9]{2}m).*$/\1 \0/' | \
  398. sort -r | \
  399. sed -r -n 's/\S+ //p' | \
  400. tail -n "+${count}" | \
  401. xargs -L1 rm -fv | \
  402. while IFS= read -r line ; do
  403. log_info "${line}"
  404. done
  405. }
  406. # }}}
  407. # {{{ usage()
  408. usage() {
  409. cat <<EOH
  410. USAGE: $(basename "$0") [OPTIONS]
  411. ${NAME} ${VERSION}
  412. A fully automated tool to make periodic backups of PostgreSQL databases.
  413. Options:
  414. -h Shows this help
  415. -d Run in debug mode (no mail sent)
  416. EOH
  417. }
  418. # }}}
  419. # {{{ Process command line arguments
  420. while getopts "hd" OPTION ; do
  421. case "${OPTION}" in
  422. h)
  423. usage
  424. exit 0
  425. ;;
  426. d)
  427. DEBUG="yes"
  428. ;;
  429. *)
  430. printf "Try \`%s -h\` to check the command line arguments\n" "$(basename "$0")" >&2
  431. exit 1
  432. esac
  433. done
  434. # }}}
  435. # {{{ I/O redirection(s) for logging
  436. exec 6>&1 # Link file descriptor #6 with stdout.
  437. # Saves stdout.
  438. exec 7>&2 # Link file descriptor #7 with stderr.
  439. # Saves stderr.
  440. exec > >( logger "out")
  441. exec 2> >( logger "err")
  442. # }}}
  443. # {{{ PreBackup
  444. # Run command before we begin
  445. if [ -n "${PREBACKUP}" ]; then
  446. log_info "Prebackup command output:"
  447. ${PREBACKUP} | \
  448. while IFS= read -r line ; do
  449. log " ${line}"
  450. done
  451. fi
  452. # }}}
  453. # {{{ main()
  454. log_info "${NAME} version ${VERSION}"
  455. log_info "Homepage: ${HOMEPAGE}"
  456. log_info "Backup of Database Server - ${HOST}"
  457. if [ -n "${COMP}" ]; then
  458. if ! command -v "${COMP}" >/dev/null ; then
  459. log_warn "Disabling compression, '${COMP}' command not found"
  460. unset COMP
  461. fi
  462. fi
  463. if [ "${ENCRYPTION}" = "yes" ]; then
  464. if [ ! -s "${ENCRYPTION_PUBLIC_KEY}" ]; then
  465. log_warn "Disabling encryption, '${ENCRYPTION_PUBLIC_KEY}' is empty or does not exists"
  466. ENCRYPTION="no"
  467. elif ! command -v "gpg" >/dev/null ; then
  468. log_warn "Disabling encryption, 'gpg' command not found"
  469. ENCRYPTION="no"
  470. else
  471. gpg_setup
  472. if ! keyinfo="$(gpg --quiet --homedir "${GPG_HOMEDIR}" "${ENCRYPTION_PUBLIC_KEY}" 2>/dev/null)"; then
  473. log_warn "Disabling encryption, key in '${ENCRYPTION_PUBLIC_KEY}' does not seems to be a valid public key"
  474. ENCRYPTION="no"
  475. if command -v "openssl" >/dev/null && openssl x509 -noout -in "${ENCRYPTION_PUBLIC_KEY}" >/dev/null 2>&1; then
  476. log_warn "public key in '${ENCRYPTION_PUBLIC_KEY}' seems to be in PEM format"
  477. log_warn "Encryption using openssl is no longer supported: see ${HOMEPAGE}#openssl-encryption"
  478. fi
  479. else
  480. keyfp="$(echo "${keyinfo}" | sed -r -n 's/^\s*([a-z0-9]+)\s*$/\1/pi')"
  481. keyuid="$(echo "${keyinfo}" | sed -r -n 's/^\s*uid\s+(\S.*)$/\1/pi' | head -n1)"
  482. log_info "Encryption public key is: 0x${keyfp} (${keyuid})"
  483. fi
  484. fi
  485. fi
  486. log_info "Backup Start: $(date)"
  487. if [ "${DNOM}" = "${DOMONTHLY}" ]; then
  488. period="monthly"
  489. rotate="${BRMONTHLY}"
  490. elif [ "${DNOW}" = "${DOWEEKLY}" ]; then
  491. period="weekly"
  492. rotate="${BRWEEKLY}"
  493. else
  494. period="daily"
  495. rotate="${BRDAILY}"
  496. fi
  497. # If backing up all DBs on the server
  498. if [ "${DBNAMES}" = "all" ]; then
  499. DBNAMES="$(dblist)"
  500. fi
  501. for db in ${DBNAMES} ; do
  502. db="${db//%/ / }"
  503. log_info "Backup of Database (${period}) '${db}'"
  504. backupdbdir="${BACKUPDIR}/${period}/${db}"
  505. if [ ! -e "${backupdbdir}" ]; then
  506. log_debug "Creating Backup DB directory '${backupdbdir}'"
  507. mkdir -p "${backupdbdir}"
  508. fi
  509. cleanup "${BACKUPDIR}" "${db}" "${period}" "${rotate}"
  510. backupfile="${backupdbdir}/${db}_${DATE}.${EXT}"
  511. dump "${db}" "${backupfile}"
  512. done
  513. log_info "Backup End: $(date)"
  514. log_info "Total disk space used for ${BACKUPDIR}: $(du -hs "${BACKUPDIR}" | cut -f1)"
  515. # }}}
  516. # {{{ PostBackup
  517. # Run command when we're done
  518. if [ -n "${POSTBACKUP}" ]; then
  519. log_info "Postbackup command output:"
  520. ${POSTBACKUP} | \
  521. while IFS= read -r line ; do
  522. log " ${line}"
  523. done
  524. fi
  525. # }}}
  526. # {{{ cleanup I/O redirections
  527. exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
  528. exec 2>&7 7>&- # Restore stdout and close file descriptor #7.
  529. # }}}
  530. # {{{ Reporting
  531. if [ "${DEBUG}" = "no" ] && grep -q '^err|' "${LOG_FILE}" ; then
  532. (
  533. printf "*Errors/Warnings* (below) reported during backup on *%s*:\n\n" "${HOST}"
  534. grep '^err|' "${LOG_FILE}" | cut -d '|' -f 3- | \
  535. while IFS= read -r line ; do
  536. printf " | %s\n" "${line}"
  537. done
  538. printf "\n\nFull backup log follows:\n\n"
  539. grep -v '^...|debug|' "${LOG_FILE}" | \
  540. while IFS="|" read -r fd level line ; do
  541. if [ -n "${level}" ]; then
  542. printf "%8s| %s\n" "*${level}*" "${line}"
  543. else
  544. printf "%8s| %s\n" "" "${line}"
  545. fi
  546. done
  547. printf "\nFor more information, try to run %s in debug mode, see \`%s -h\`\n" "${NAME}" "$(basename "$0")"
  548. ) | mail -s "${NAME} issues on $(hostname --fqdn)" "${MAILADDR}"
  549. fi
  550. # }}}
  551. # {{{ Cleanup and exit()
  552. if [ -s "${LOGERR}" ]; then
  553. rc=1
  554. else
  555. rc=0
  556. fi
  557. # Cleanup GnuPG home dir
  558. if [ -d "${GPG_HOMEDIR}" ]; then
  559. rm -rf "${GPG_HOMEDIR}"
  560. fi
  561. # Clean up log files
  562. rm -f "${LOG_FILE}"
  563. exit ${rc}
  564. # }}}
  565. # vim: foldmethod=marker foldlevel=0 foldenable