autopostgresqlbackup 19 KB

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