autopostgresqlbackup 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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="$(printf '%.2i' "${DOMONTHLY}")"
  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. # Create required directories
  144. if [ ! -e "${BACKUPDIR}" ]; then # Check Backup Directory exists.
  145. mkdir -p "${BACKUPDIR}"
  146. fi
  147. if [ ! -e "${BACKUPDIR}/daily" ]; then # Check Daily Directory exists.
  148. mkdir -p "${BACKUPDIR}/daily"
  149. fi
  150. if [ ! -e "${BACKUPDIR}/weekly" ]; then # Check Weekly Directory exists.
  151. mkdir -p "${BACKUPDIR}/weekly"
  152. fi
  153. if [ ! -e "${BACKUPDIR}/monthly" ]; then # Check Monthly Directory exists.
  154. mkdir -p "${BACKUPDIR}/monthly"
  155. fi
  156. # Hostname
  157. HOSTNAME="$(uname -n)"
  158. if [[ "${HOSTNAME}" != *.* ]]; then
  159. HOSTNAME="$(hostname --fqdn)"
  160. fi
  161. HOST="${HOSTNAME}"
  162. if [ "${DBHOST}" != "localhost" ]; then
  163. HOST="${HOSTNAME}:${DBPORT}"
  164. fi
  165. CONN_ARGS=()
  166. # }}}
  167. # {{{ log{,ger,_info,_debug,_warn,_error}()
  168. logger() {
  169. local fd line severity reset color
  170. fd="${1}"
  171. severity="${2}"
  172. reset=
  173. color=
  174. if [ -n "${TERM}" ]; then
  175. reset="\e[0m"
  176. case "${severity}" in
  177. error)
  178. color="\e[0;91m"
  179. ;;
  180. warn)
  181. color="\e[0;93m"
  182. ;;
  183. debug)
  184. color="\e[0;96m"
  185. ;;
  186. *)
  187. color="\e[0;94m"
  188. ;;
  189. esac
  190. fi
  191. while IFS= read -r line ; do
  192. printf "%s|%s|%s\n" "${fd}" "${severity}" "${line}" >> "${LOG_FILE}"
  193. if [ "${DEBUG}" = "yes" ]; then
  194. if [ "${fd}" = "out" ]; then
  195. printf "${color}%6s${reset}|%s\n" "${severity}" "${line}" >&6
  196. elif [ "${fd}" = "err" ]; then
  197. printf "${color}%6s${reset}|%s\n" "${severity}" "${line}" >&7
  198. fi
  199. fi
  200. done
  201. }
  202. log() {
  203. echo "$@" | logger "out" ""
  204. }
  205. log_debug() {
  206. echo "$@" | logger "out" "debug"
  207. }
  208. log_info() {
  209. echo "$@" | logger "out" "info"
  210. }
  211. log_error() {
  212. echo "$@" | logger "err" "error"
  213. }
  214. log_warn() {
  215. echo "$@" | logger "err" "warn"
  216. }
  217. # }}}
  218. # {{{ gpg_setup()
  219. gpg_setup() {
  220. GPG_HOMEDIR="$(mktemp --quiet --directory -t "${NAME}.XXXXXX")"
  221. chmod 700 "${GPG_HOMEDIR}"
  222. log_debug "With encryption enabled creating a temporary GnuPG home in ${GPG_HOMEDIR}"
  223. gpg --quiet --homedir "${GPG_HOMEDIR}" --quick-gen-key --batch --passphrase-file /dev/null "root@${HOSTNAME}"
  224. }
  225. # }}}
  226. # {{{ encryption()
  227. encryption() {
  228. log_debug "Encrypting using public key ${ENCRYPTION_PUBLIC_KEY}"
  229. gpg --homedir "${GPG_HOMEDIR}" --encrypt --passphrase-file /dev/null --recipient-file "${ENCRYPTION_PUBLIC_KEY}" 2> >(logger "err" "error")
  230. }
  231. # }}}
  232. # {{{ compression()
  233. compression () {
  234. if [ -n "${COMP_OPTS}" ]; then
  235. IFS=" " read -r -a comp_args <<< "${COMP_OPTS}"
  236. log_debug "Compressing using '${COMP} ${comp_args[*]}'"
  237. "${COMP}" "${comp_args[@]}" 2> >(logger "err" "error")
  238. else
  239. log_debug "Compressing using '${COMP}'"
  240. "${COMP}" 2> >(logger "err" "error")
  241. fi
  242. }
  243. # }}}
  244. # {{{ pgdb_init()
  245. pgdb_init () {
  246. if [ "${DBHOST}" != "localhost" ]; then
  247. CONN_ARGS=(--host "${DBHOST}" --port "${DBPORT}")
  248. fi
  249. if [ -n "${USERNAME}" ]; then
  250. CONN_ARGS+=(--username "${USERNAME}")
  251. fi
  252. }
  253. # }}}
  254. # {{{ pgdb_list()
  255. pgdb_list () {
  256. local cmd_prog cmd_args raw_dblist dblist dbexcl databases
  257. cmd_prog="psql"
  258. cmd_args=(-t -l -A -F:)
  259. if [ "${#CONN_ARGS[@]}" -gt 0 ]; then
  260. cmd_args+=("${CONN_ARGS[@]}")
  261. fi
  262. log_debug "Running command: ${cmd_prog} ${cmd_args[*]}"
  263. raw_dblist=$(
  264. if [ -n "${SU_USERNAME}" ]; then
  265. if ! su - "${SU_USERNAME}" -c "${cmd_prog} ${cmd_args[*]}" 2> >(logger "err" "error"); then
  266. log_error "Running (as user '${SU_USERNAME}' command '${cmd_prog} ${cmd_args[*]}' has failed"
  267. fi
  268. elif ! "${cmd_prog}" "${cmd_args[@]}" 2> >(logger "err" "error"); then
  269. log_error "Running command '${cmd_prog} ${cmd_args[*]}' has failed"
  270. fi
  271. )
  272. read -r -a dblist <<< "$(
  273. printf "%s" "${raw_dblist}" | \
  274. sed -E -n 's/^([^:]+):.+$/\1/p' | \
  275. tr '\n' ' '
  276. )"
  277. log_debug "Automatically found databases: ${dblist[*]}"
  278. if [ -n "${DBEXCLUDE}" ]; then
  279. IFS=" " read -r -a dbexcl <<< "${DBEXCLUDE}"
  280. else
  281. dbexcl=()
  282. fi
  283. dbexcl+=(template0)
  284. log_debug "Excluded databases: ${dbexcl[*]}"
  285. mapfile -t databases < <(
  286. comm -23 \
  287. <(IFS=$'\n'; echo "${dblist[*]}" | sort) \
  288. <(IFS=$'\n'; echo "${dbexcl[*]}" | sort) \
  289. )
  290. databases+=("${GLOBALS_OBJECTS}")
  291. log_debug "Database(s) to be backuped: ${databases[*]}"
  292. printf "%s " "${databases[@]}"
  293. }
  294. # }}}
  295. # {{{ pgdb_dump()
  296. pgdb_dump () {
  297. local db_name cmd_prog cmd_args pg_args
  298. db_name="${1}"
  299. if [ -n "${PGDUMP_OPTS}" ]; then
  300. IFS=" " read -r -a PGDUMP_ARGS <<< "${PGDUMP_OPTS}"
  301. else
  302. PGDUMP_ARGS=()
  303. fi
  304. # pg_dumpall options
  305. if [ -n "${PGDUMPALL_OPTS}" ]; then
  306. IFS=" " read -r -a PGDUMPALL_ARGS <<< "${PGDUMPALL_OPTS}"
  307. else
  308. PGDUMPALL_ARGS=()
  309. fi
  310. if [ "${db_name}" = "${GLOBALS_OBJECTS}" ]; then
  311. cmd_prog="pg_dumpall"
  312. cmd_args=(--globals-only)
  313. pg_args=("${PGDUMPALL_ARGS[@]}")
  314. else
  315. cmd_prog="pg_dump"
  316. cmd_args=("${db_name}")
  317. pg_args=("${PGDUMP_ARGS[@]}")
  318. if [ "${CREATE_DATABASE}" = "yes" ]; then
  319. pg_args+=(--create)
  320. fi
  321. fi
  322. if [ "${#CONN_ARGS[@]}" -gt 0 ]; then
  323. cmd_args+=("${CONN_ARGS[@]}")
  324. fi
  325. if [ "${#pg_args[@]}" -gt 0 ]; then
  326. cmd_args+=("${pg_args[@]}")
  327. fi
  328. log_debug "Running command: ${cmd_prog} ${cmd_args[*]}"
  329. if [ -n "${SU_USERNAME}" ]; then
  330. if ! su - "${SU_USERNAME}" -c "${cmd_prog} ${cmd_args[*]}" 2> >(logger "err" "error"); then
  331. log_error "Running (as user '${SU_USERNAME}' command '${cmd_prog} ${cmd_args[*]}' has failed"
  332. fi
  333. elif ! "${cmd_prog}" "${cmd_args[@]}" 2> >(logger "err" "error"); then
  334. log_error "Running command '${cmd_prog} ${cmd_args[*]}' has failed"
  335. fi
  336. }
  337. # }}}
  338. # {{{ dump()
  339. dump() {
  340. local db_name dump_file comp_ext
  341. db_name="${1}"
  342. dump_file="${2}"
  343. if [ -n "${COMP}" ]; then
  344. comp_ext=".comp"
  345. case "${COMP}" in
  346. gzip|pigz)
  347. comp_ext=".gz"
  348. ;;
  349. bzip2)
  350. comp_ext=".bz2"
  351. ;;
  352. xz)
  353. comp_ext=".xz"
  354. ;;
  355. zstd)
  356. comp_ext=".zstd"
  357. ;;
  358. esac
  359. dump_file="${dump_file}${comp_ext}"
  360. fi
  361. if [ "${ENCRYPTION}" = "yes" ]; then
  362. dump_file="${dump_file}${ENCRYPTION_SUFFIX}"
  363. fi
  364. if [ -n "${COMP}" ] && [ "${ENCRYPTION}" = "yes" ]; then
  365. log_debug "Dumping (${db_name}) +compress +encrypt to '${dump_file}'"
  366. pgdb_dump "${db_name}" | compression | encryption > "${dump_file}"
  367. elif [ -n "${COMP}" ]; then
  368. log_debug "Dumping (${db_name}) +compress to '${dump_file}'"
  369. pgdb_dump "${db_name}" | compression > "${dump_file}"
  370. elif [ "${ENCRYPTION}" = "yes" ]; then
  371. log_debug "Dumping (${db_name}) +encrypt to '${dump_file}'"
  372. pgdb_dump "${db_name}" | encryption > "${dump_file}"
  373. else
  374. log_debug "Dumping (${db_name}) to '${dump_file}'"
  375. pgdb_dump "${db_name}" > "${dump_file}"
  376. fi
  377. if [ -f "${dump_file}" ]; then
  378. log_debug "Fixing permissions (${PERM}) on '${dump_file}'"
  379. chmod "${PERM}" "${dump_file}"
  380. fsize=$(stat -c '%s' "${dump_file}")
  381. if [ ! -s "${dump_file}" ]; then
  382. log_error "Something went wrong '${dump_file}' is empty"
  383. elif [ "${fsize}" -lt "${MIN_DUMP_SIZE}" ]; then
  384. log_warn "'${dump_file}' (${fsize} bytes) is below the minimum required size (${MIN_DUMP_SIZE} bytes)"
  385. fi
  386. else
  387. log_error "Something went wrong '${dump_file}' does not exists (error during dump?)"
  388. fi
  389. }
  390. # }}}
  391. # {{{ cleanup()
  392. cleanup() {
  393. local dumpdir db when count line
  394. dumpdir="${1}"
  395. db="${2}"
  396. when="${3}"
  397. count="${4}"
  398. # Since version >= 2.0 the dump filename no longer contains the week number
  399. # or the abbreviated month name so in order to be sure to remove the older
  400. # dumps we need to sort the filename on the datetime part (YYYY-MM-DD_HHhMMm)
  401. log_info "Rotating ${count} ${when} backups..."
  402. log_debug "Looking for '${db}_*' in '${dumpdir}/${when}/${db}'"
  403. find "${dumpdir}/${when}/${db}/" -name "${db}_*" | \
  404. sed -E 's/(^.+([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}h[0-9]{2}m).*$)/\2 \1/' | \
  405. sort -r | \
  406. sed -E -n 's/\S+ //p' | \
  407. tail -n "+${count}" | \
  408. xargs -L1 rm -fv | \
  409. while IFS= read -r line ; do
  410. log_info "${line}"
  411. done
  412. }
  413. # }}}
  414. # {{{ usage()
  415. usage() {
  416. cat <<EOH
  417. USAGE: $(basename "$0") [OPTIONS]
  418. ${NAME} ${VERSION}
  419. A fully automated tool to make periodic backups of PostgreSQL databases.
  420. Options:
  421. -h Shows this help
  422. -d Run in debug mode (no mail sent)
  423. EOH
  424. }
  425. # }}}
  426. # {{{ Process command line arguments
  427. while getopts "hd" OPTION ; do
  428. case "${OPTION}" in
  429. h)
  430. usage
  431. exit 0
  432. ;;
  433. d)
  434. DEBUG="yes"
  435. ;;
  436. *)
  437. printf "Try \`%s -h\` to check the command line arguments\n" "$(basename "$0")" >&2
  438. exit 1
  439. esac
  440. done
  441. # }}}
  442. # {{{ I/O redirection(s) for logging
  443. exec 6>&1 # Link file descriptor #6 with stdout.
  444. # Saves stdout.
  445. exec 7>&2 # Link file descriptor #7 with stderr.
  446. # Saves stderr.
  447. exec > >( logger "out")
  448. exec 2> >( logger "err")
  449. # }}}
  450. # {{{ PreBackup
  451. # Run command before we begin
  452. if [ -n "${PREBACKUP}" ]; then
  453. log_info "Prebackup command output:"
  454. ${PREBACKUP} | \
  455. while IFS= read -r line ; do
  456. log " ${line}"
  457. done
  458. fi
  459. # }}}
  460. # {{{ main()
  461. log_info "${NAME} version ${VERSION}"
  462. log_info "Homepage: ${HOMEPAGE}"
  463. log_info "Backup of Database Server - ${HOST}"
  464. if [ -n "${COMP}" ]; then
  465. if ! command -v "${COMP}" >/dev/null ; then
  466. log_warn "Disabling compression, '${COMP}' command not found"
  467. unset COMP
  468. fi
  469. fi
  470. if [ "${ENCRYPTION}" = "yes" ]; then
  471. if [ ! -s "${ENCRYPTION_PUBLIC_KEY}" ]; then
  472. log_warn "Disabling encryption, '${ENCRYPTION_PUBLIC_KEY}' is empty or does not exists"
  473. ENCRYPTION="no"
  474. elif ! command -v "gpg" >/dev/null ; then
  475. log_warn "Disabling encryption, 'gpg' command not found"
  476. ENCRYPTION="no"
  477. else
  478. gpg_setup
  479. if ! keyinfo="$(gpg --quiet --homedir "${GPG_HOMEDIR}" "${ENCRYPTION_PUBLIC_KEY}" 2>/dev/null)"; then
  480. log_warn "Disabling encryption, key in '${ENCRYPTION_PUBLIC_KEY}' does not seems to be a valid public key"
  481. ENCRYPTION="no"
  482. if command -v "openssl" >/dev/null && openssl x509 -noout -in "${ENCRYPTION_PUBLIC_KEY}" >/dev/null 2>&1; then
  483. log_warn "public key in '${ENCRYPTION_PUBLIC_KEY}' seems to be in PEM format"
  484. log_warn "Encryption using openssl is no longer supported: see ${HOMEPAGE}#openssl-encryption"
  485. fi
  486. else
  487. keyfp="$(echo "${keyinfo}" | sed -E -n 's/^\s*([a-z0-9]+)\s*$/\1/pi')"
  488. keyuid="$(echo "${keyinfo}" | sed -E -n 's/^\s*uid\s+(\S.*)$/\1/pi' | head -n1)"
  489. log_info "Encryption public key is: 0x${keyfp} (${keyuid})"
  490. fi
  491. fi
  492. fi
  493. log_info "Backup Start: $(date)"
  494. if [ "${DNOM}" = "${DOMONTHLY}" ]; then
  495. period="monthly"
  496. rotate="${BRMONTHLY}"
  497. elif [ "${DNOW}" = "${DOWEEKLY}" ]; then
  498. period="weekly"
  499. rotate="${BRWEEKLY}"
  500. else
  501. period="daily"
  502. rotate="${BRDAILY}"
  503. fi
  504. # If backing up all DBs on the server
  505. if [ "${DBNAMES}" = "all" ]; then
  506. DBNAMES="$(pgdb_list)"
  507. fi
  508. pgdb_init
  509. for db in ${DBNAMES} ; do
  510. db="${db//%/ / }"
  511. log_info "Backup of Database (${period}) '${db}'"
  512. backupdbdir="${BACKUPDIR}/${period}/${db}"
  513. if [ ! -e "${backupdbdir}" ]; then
  514. log_debug "Creating Backup DB directory '${backupdbdir}'"
  515. mkdir -p "${backupdbdir}"
  516. fi
  517. cleanup "${BACKUPDIR}" "${db}" "${period}" "${rotate}"
  518. backupfile="${backupdbdir}/${db}_${DATE}.${EXT}"
  519. dump "${db}" "${backupfile}"
  520. done
  521. log_info "Backup End: $(date)"
  522. log_info "Total disk space used for ${BACKUPDIR}: $(du -hs "${BACKUPDIR}" | cut -f1)"
  523. # }}}
  524. # {{{ PostBackup
  525. # Run command when we're done
  526. if [ -n "${POSTBACKUP}" ]; then
  527. log_info "Postbackup command output:"
  528. ${POSTBACKUP} | \
  529. while IFS= read -r line ; do
  530. log " ${line}"
  531. done
  532. fi
  533. # }}}
  534. # {{{ cleanup I/O redirections
  535. exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
  536. exec 2>&7 7>&- # Restore stdout and close file descriptor #7.
  537. # }}}
  538. # {{{ Reporting
  539. if [ "${DEBUG}" = "no" ] && grep -q '^err|' "${LOG_FILE}" ; then
  540. (
  541. printf "*Errors/Warnings* (below) reported during backup on *%s*:\n\n" "${HOST}"
  542. grep '^err|' "${LOG_FILE}" | cut -d '|' -f 3- | \
  543. while IFS= read -r line ; do
  544. printf " | %s\n" "${line}"
  545. done
  546. printf "\n\nFull backup log follows:\n\n"
  547. grep -v '^...|debug|' "${LOG_FILE}" | \
  548. while IFS="|" read -r fd level line ; do
  549. if [ -n "${level}" ]; then
  550. printf "%8s| %s\n" "*${level}*" "${line}"
  551. else
  552. printf "%8s| %s\n" "" "${line}"
  553. fi
  554. done
  555. printf "\nFor more information, try to run %s in debug mode, see \`%s -h\`\n" "${NAME}" "$(basename "$0")"
  556. ) | mail -s "${NAME} issues on ${HOSTNAME}" "${MAILADDR}"
  557. fi
  558. # }}}
  559. # {{{ Cleanup and exit()
  560. if [ -s "${LOGERR}" ]; then
  561. rc=1
  562. else
  563. rc=0
  564. fi
  565. # Cleanup GnuPG home dir
  566. if [ -d "${GPG_HOMEDIR}" ]; then
  567. rm -rf "${GPG_HOMEDIR}"
  568. fi
  569. # Clean up log files
  570. rm -f "${LOG_FILE}"
  571. exit ${rc}
  572. # }}}
  573. # vim: foldmethod=marker foldlevel=0 foldenable