autopostgresqlbackup 19 KB

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