autopostgresqlbackup 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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-2021 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. #=====================================================================
  24. # Set the following variables to your system needs
  25. # (Detailed instructions below variables)
  26. #=====================================================================
  27. # }}}
  28. # {{{ Variables
  29. # Username to access the PostgreSQL server e.g. dbuser
  30. USERNAME=postgres
  31. # Password
  32. # create a file ${HOME}/.pgpass containing a line like this
  33. # hostname:*:*:dbuser:dbpass
  34. # replace hostname with the value of DBHOST and postgres with
  35. # the value of USERNAME
  36. # Host name (or IP address) of PostgreSQL server e.g localhost
  37. DBHOST=localhost
  38. # List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3"
  39. DBNAMES="all"
  40. # pseudo database name used to dump global objects (users, roles, tablespaces)
  41. GLOBALS_OBJECTS="postgres_globals"
  42. # Backup directory location e.g /backups
  43. BACKUPDIR="/backups"
  44. # Mail setup
  45. # What would you like to be mailed to you?
  46. # - log : send only log file
  47. # - files : send log file and sql files as attachments (see docs)
  48. # - stdout : will simply output the log to the screen if run manually.
  49. # - quiet : Only send logs if an error occurs to the MAILADDR.
  50. MAILCONTENT="stdout"
  51. # Set the maximum allowed email size in k. (4000 = approx 5MB email [see docs])
  52. MAXATTSIZE="4000"
  53. # Email Address to send mail to? (user@domain.com)
  54. MAILADDR="user@domain.com"
  55. # ============================================================
  56. # === ADVANCED OPTIONS ( Read the doc's below for details )===
  57. #=============================================================
  58. # List of DBBNAMES for Monthly Backups.
  59. MDBNAMES="template1 ${DBNAMES}"
  60. # List of DBNAMES to EXLUCDE if DBNAMES are set to all (must be in " quotes)
  61. DBEXCLUDE=""
  62. # Include CREATE DATABASE in backup?
  63. CREATE_DATABASE=yes
  64. # Separate backup directory and file for each DB? (yes or no)
  65. SEPDIR=yes
  66. # Which day do you want weekly backups? (1 to 7 where 1 is Monday)
  67. DOWEEKLY=6
  68. # Choose Compression type. (gzip, bzip2 or xz)
  69. COMP=gzip
  70. # Compress communications between backup server and PostgreSQL server?
  71. # set compression level from 0 to 9 (0 means no compression)
  72. COMMCOMP=0
  73. # Additionally keep a copy of the most recent backup in a seperate directory.
  74. LATEST=no
  75. # OPT string for use with pg_dump ( see man pg_dump )
  76. OPT=""
  77. # Backup files extension
  78. EXT="sql"
  79. # Backup files permissions
  80. PERM=600
  81. # Encyrption settings
  82. # (inspired by http://blog.altudov.com/2010/09/27/using-openssl-for-asymmetric-encryption-of-backups/)
  83. #
  84. # Once the backup done, each SQL dump will be encrypted and the original file
  85. # will be deleted (if encryption was successful).
  86. # It is recommended to backup into a staging directory, and then use the
  87. # POSTBACKUP script to sync the encrypted files to the desired location.
  88. #
  89. # Encryption uses private/public keys. You can generate the key pairs like the following:
  90. # openssl req -x509 -nodes -days 100000 -newkey rsa:2048 -keyout backup.key -out backup.crt -subj '/'
  91. #
  92. # Decryption:
  93. # openssl smime -decrypt -in backup.sql.gz.enc -binary -inform DEM -inkey backup.key -out backup.sql.gz
  94. # Enable encryption
  95. ENCRYPTION=no
  96. # Encryption public key
  97. ENCRYPTION_PUBLIC_KEY=""
  98. # Encryption Cipher (see enc manpage)
  99. ENCRYPTION_CIPHER="aes256"
  100. # Suffix for encyrpted files
  101. ENCRYPTION_SUFFIX=".enc"
  102. # Command to run before backups (uncomment to use)
  103. #PREBACKUP="/etc/postgresql-backup-pre"
  104. # Command run after backups (uncomment to use)
  105. #POSTBACKUP="/etc/postgresql-backup-post"
  106. # }}}
  107. # {{{ OS Specific
  108. #=====================================================================
  109. # Debian specific options ===
  110. #=====================================================================
  111. if [ -f /etc/default/autopostgresqlbackup ]; then
  112. . /etc/default/autopostgresqlbackup
  113. fi
  114. # }}}
  115. # {{{ Documentation
  116. #=====================================================================
  117. # Options documentation
  118. #=====================================================================
  119. # Set USERNAME and PASSWORD of a user that has at least SELECT permission
  120. # to ALL databases.
  121. #
  122. # Set the DBHOST option to the server you wish to backup, leave the
  123. # default to backup "this server".(to backup multiple servers make
  124. # copies of this file and set the options for that server)
  125. #
  126. # Put in the list of DBNAMES(Databases)to be backed up. If you would like
  127. # to backup ALL DBs on the server set DBNAMES="all".(if set to "all" then
  128. # any new DBs will automatically be backed up without needing to modify
  129. # this backup script when a new DB is created).
  130. #
  131. # If the DB you want to backup has a space in the name replace the space
  132. # with a % e.g. "data base" will become "data%base"
  133. # NOTE: Spaces in DB names may not work correctly when SEPDIR=no.
  134. #
  135. # You can change the backup storage location from /backups to anything
  136. # you like by using the BACKUPDIR setting..
  137. #
  138. # The MAILCONTENT and MAILADDR options and pretty self explanitory, use
  139. # these to have the backup log mailed to you at any email address or multiple
  140. # email addresses in a space seperated list.
  141. # (If you set mail content to "log" you will require access to the "mail" program
  142. # on your server. If you set this to "files" you will have to have mutt installed
  143. # on your server. If you set it to "stdout" it will log to the screen if run from
  144. # the console or to the cron job owner if run through cron. If you set it to "quiet"
  145. # logs will only be mailed if there are errors reported. )
  146. #
  147. # MAXATTSIZE sets the largest allowed email attachments total (all backup files) you
  148. # want the script to send. This is the size before it is encoded to be sent as an email
  149. # so if your mail server will allow a maximum mail size of 5MB I would suggest setting
  150. # MAXATTSIZE to be 25% smaller than that so a setting of 4000 would probably be fine.
  151. #
  152. # Finally copy autopostgresqlbackup.sh to anywhere on your server and make sure
  153. # to set executable permission. You can also copy the script to
  154. # /etc/cron.daily to have it execute automatically every night or simply
  155. # place a symlink in /etc/cron.daily to the file if you wish to keep it
  156. # somwhere else.
  157. # NOTE:On Debian copy the file with no extention for it to be run
  158. # by cron e.g just name the file "autopostgresqlbackup"
  159. #
  160. # Thats it..
  161. #
  162. #
  163. # === Advanced options doc's ===
  164. #
  165. # The list of MDBNAMES is the DB's to be backed up only monthly. You should
  166. # always include "template1" in this list to backup the default database
  167. # template used to create new databases.
  168. # NOTE: If DBNAMES="all" then MDBNAMES has no effect as all DBs will be backed
  169. # up anyway.
  170. #
  171. # If you set DBNAMES="all" you can configure the option DBEXCLUDE. Other
  172. # wise this option will not be used.
  173. # This option can be used if you want to backup all dbs, but you want
  174. # exclude some of them. (eg. a db is to big).
  175. #
  176. # Set CREATE_DATABASE to "yes" (the default) if you want your SQL-Dump to create
  177. # a database with the same name as the original database when restoring.
  178. # Saying "no" here will allow your to specify the database name you want to
  179. # restore your dump into, making a copy of the database by using the dump
  180. # created with autopostgresqlbackup.
  181. # NOTE: Not used if SEPDIR=no
  182. #
  183. # The SEPDIR option allows you to choose to have all DBs backed up to
  184. # a single file (fast restore of entire server in case of crash) or to
  185. # seperate directories for each DB (each DB can be restored seperately
  186. # in case of single DB corruption or loss).
  187. #
  188. # To set the day of the week that you would like the weekly backup to happen
  189. # set the DOWEEKLY setting, this can be a value from 1 to 7 where 1 is Monday,
  190. # The default is 6 which means that weekly backups are done on a Saturday.
  191. #
  192. # COMP is used to choose the copmression used, options are gzip or bzip2.
  193. # bzip2 will produce slightly smaller files but is more processor intensive so
  194. # may take longer to complete.
  195. #
  196. # COMMCOMP is used to set the compression level (from 0 to 9, 0 means no compression)
  197. # between the client and the server, so it is useful to save bandwidth when backing up
  198. # a remote PostgresSQL server over the network.
  199. #
  200. # LATEST is to store an additional copy of the latest backup to a standard
  201. # location so it can be downloaded bt thrid party scripts.
  202. #
  203. # Use PREBACKUP and POSTBACKUP to specify Per and Post backup commands
  204. # or scripts to perform tasks either before or after the backup process.
  205. #
  206. #
  207. #=====================================================================
  208. # Backup Rotation..
  209. #=====================================================================
  210. #
  211. # Daily Backups are rotated weekly..
  212. # Weekly Backups are run by default on Saturday Morning when
  213. # cron.daily scripts are run...Can be changed with DOWEEKLY setting..
  214. # Weekly Backups are rotated on a 5 week cycle..
  215. # Monthly Backups are run on the 1st of the month..
  216. # Monthly Backups are NOT rotated automatically...
  217. # It may be a good idea to copy Monthly backups offline or to another
  218. # server..
  219. #
  220. #=====================================================================
  221. # Please Note!!
  222. #=====================================================================
  223. #
  224. # I take no resposibility for any data loss or corruption when using
  225. # this script..
  226. # This script will not help in the event of a hard drive crash. If a
  227. # copy of the backup has not be stored offline or on another PC..
  228. # You should copy your backups offline regularly for best protection.
  229. #
  230. # Happy backing up...
  231. #
  232. #=====================================================================
  233. # Restoring
  234. #=====================================================================
  235. # Firstly you will need to uncompress the backup file.
  236. # eg.
  237. # gunzip file.gz (or bunzip2 file.bz2)
  238. #
  239. # Next you will need to use the postgresql client to restore the DB from the
  240. # sql file.
  241. # eg.
  242. # psql --host dbserver --dbname database < /path/file.sql
  243. #
  244. # NOTE: Make sure you use "<" and not ">" in the above command because
  245. # you are piping the file.sql to psql and not the other way around.
  246. #
  247. # Lets hope you never have to use this.. :)
  248. # }}}
  249. # {{{ Defaults
  250. PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/postgres/bin:/usr/local/pgsql/bin
  251. DATE=`date +%Y-%m-%d_%Hh%Mm` # Datestamp e.g 2002-09-21
  252. DOW=`date +%A` # Day of the week e.g. Monday
  253. DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday
  254. DOM=`date +%d` # Date of the Month e.g. 27
  255. M=`date +%B` # Month e.g January
  256. W=`date +%V` # Week Number e.g 37
  257. VER=1.1 # Version Number
  258. LOGFILE=${BACKUPDIR}/${DBHOST//\//_}-`date +%N`.log # Logfile Name
  259. LOGERR=${BACKUPDIR}/ERRORS_${DBHOST//\//_}-`date +%N`.log # Logfile Name
  260. BACKUPFILES=""
  261. # Add --compress pg_dump option to ${OPT}
  262. if [ "${COMMCOMP}" -gt 0 ]; then
  263. OPT="${OPT} --compress=${COMMCOMP}"
  264. fi
  265. # Create required directories
  266. if [ ! -e "${BACKUPDIR}" ]; then # Check Backup Directory exists.
  267. mkdir -p "${BACKUPDIR}"
  268. fi
  269. if [ ! -e "${BACKUPDIR}/daily" ]; then # Check Daily Directory exists.
  270. mkdir -p "${BACKUPDIR}/daily"
  271. fi
  272. if [ ! -e "${BACKUPDIR}/weekly" ]; then # Check Weekly Directory exists.
  273. mkdir -p "${BACKUPDIR}/weekly"
  274. fi
  275. if [ ! -e "${BACKUPDIR}/monthly" ]; then # Check Monthly Directory exists.
  276. mkdir -p "${BACKUPDIR}/monthly"
  277. fi
  278. if [ "${LATEST}" = "yes" ]; then
  279. if [ ! -e "${BACKUPDIR}/latest" ]; then # Check Latest Directory exists.
  280. mkdir -p "${BACKUPDIR}/latest"
  281. fi
  282. rm -f "${BACKUPDIR}"/latest/*
  283. fi
  284. # IO redirection for logging.
  285. touch ${LOGFILE}
  286. exec 6>&1 # Link file descriptor #6 with stdout.
  287. # Saves stdout.
  288. exec > ${LOGFILE} # stdout replaced with file ${LOGFILE}.
  289. touch ${LOGERR}
  290. exec 7>&2 # Link file descriptor #7 with stderr.
  291. # Saves stderr.
  292. exec 2> ${LOGERR} # stderr replaced with file ${LOGERR}.
  293. if [ "${SEPDIR}" = "yes" ]; then # Check if CREATE DATABSE should be included in Dump
  294. if [ "${CREATE}_DATABASE" = "no" ]; then
  295. OPT="${OPT}"
  296. else
  297. OPT="${OPT} --create"
  298. fi
  299. else
  300. OPT="${OPT}"
  301. fi
  302. # Hostname for LOG information
  303. if [ "${DBHOST}" = "localhost" ]; then
  304. HOST=`hostname`
  305. PGHOST=""
  306. else
  307. HOST=${DBHOST}
  308. PGHOST="-h ${DBHOST}"
  309. fi
  310. # If backing up all DBs on the server
  311. if [ "${DBNAMES}" = "all" ]; then
  312. if [ -n "${SU}_USERNAME" ]; then
  313. DBNAMES="$(su - ${SU}_USERNAME -l -c "LANG=C psql -U ${USERNAME} ${PGHOST} -l -A -F: | sed -ne '/:/ { /Name:Owner/d; /template0/d; s/:.*$//; p }'")"
  314. else
  315. DBNAMES="`LANG=C psql -U ${USERNAME} ${PGHOST} -l -A -F: | sed -ne "/:/ { /Name:Owner/d; /template0/d; s/:.*$//; p }"`"
  316. fi
  317. # If DBs are excluded
  318. for exclude in ${DBEXCLUDE} ; do
  319. DBNAMES=`echo ${DBNAMES} | sed "s/\b${exclude}\b//g"`
  320. done
  321. DBNAMES="$(echo ${DBNAMES}| tr '\n' ' ')"
  322. MDBNAMES=${DBNAMES}
  323. fi
  324. # Include global objects (users, tablespaces)
  325. DBNAMES="${GLOBALS}_OBJECTS ${DBNAMES}"
  326. MDBNAMES="${GLOBALS}_OBJECTS ${MDBNAMES}"
  327. # }}}
  328. # {{{ dbdump()
  329. dbdump () {
  330. rm -f "${2}"
  331. touch "${2}"
  332. chmod ${PERM} "${2}"
  333. for db in ${1} ; do
  334. if [ -n "${SU}_USERNAME" ]; then
  335. if [ "${db}" = "${GLOBALS}_OBJECTS" ]; then
  336. su - ${SU}_USERNAME -l -c "pg_dumpall ${PGHOST} --globals-only" >> "${2}"
  337. else
  338. su - ${SU}_USERNAME -l -c "pg_dump ${PGHOST} ${OPT} ${db}" >> "${2}"
  339. fi
  340. else
  341. if [ "${db}" = "${GLOBALS}_OBJECTS" ]; then
  342. pg_dumpall --username=${USERNAME} ${PGHOST} --globals-only >> "${2}"
  343. else
  344. pg_dump --username=${USERNAME} ${PGHOST} ${OPT} ${db} >> "${2}"
  345. fi
  346. fi
  347. done
  348. return 0
  349. }
  350. # }}}
  351. # {{{ encryption()
  352. encryption() {
  353. ENCRYPTED_FILE="${1}${ENCRYPTION}_SUFFIX"
  354. # Encrypt as needed
  355. if [ "${ENCRYPTION}" = "yes" ]; then
  356. echo
  357. echo "Encrypting ${1}"
  358. echo " to ${ENCRYPTED}_FILE"
  359. echo " using cypher ${ENCRYPTION}_CIPHER and public key ${ENCRYPTION}_PUBLIC_KEY"
  360. if openssl smime -encrypt -${ENCRYPTION}_CIPHER -binary -outform DEM \
  361. -out "${ENCRYPTED}_FILE" \
  362. -in "${1}" "${ENCRYPTION}_PUBLIC_KEY" ; then
  363. echo " and remove ${1}"
  364. chmod ${PERM} "${ENCRYPTED}_FILE"
  365. rm -f "${1}"
  366. fi
  367. fi
  368. return 0
  369. }
  370. # }}}
  371. # {{{ compression()
  372. # Compression (and encrypt) function plus latest copy
  373. SUFFIX=""
  374. compression () {
  375. if [ "${COMP}" = "gzip" ]; then
  376. gzip -f "${1}"
  377. echo
  378. echo Backup Information for "${1}"
  379. gzip -l "${1}.gz"
  380. SUFFIX=".gz"
  381. echo
  382. elif [ "${COMP}" = "bzip2" ]; then
  383. echo Compression information for "${1}.bz2"
  384. bzip2 -f -v "${1}" 2>&1
  385. SUFFIX=".bz2"
  386. elif [ "${COMP}" = "xz" ]; then
  387. xz -9 "${1}" 2>&1
  388. echo Backup information for "${1}.xz"
  389. xz -l "${1}.xz"
  390. SUFFIX=".xz"
  391. else
  392. echo "No compression option set, check advanced settings"
  393. fi
  394. encryption "${1}${SUFFIX}"
  395. if [ "${LATEST}" = "yes" ]; then
  396. cp ${1}${SUFFIX}* "${BACKUPDIR}/latest/"
  397. fi
  398. return 0
  399. }
  400. # }}}
  401. # {{{ PreBackup
  402. # Run command before we begin
  403. if [ "${PREBACKUP}" ]
  404. then
  405. echo ======================================================================
  406. echo "Prebackup command output."
  407. echo
  408. ${PREBACKUP}
  409. echo
  410. echo ======================================================================
  411. echo
  412. fi
  413. # }}}
  414. # {{{ main()
  415. echo ======================================================================
  416. echo AutoPostgreSQLBackup VER ${VER}
  417. echo
  418. echo Backup of Database Server - ${HOST}
  419. echo ======================================================================
  420. # Test is seperate DB backups are required
  421. if [ "${SEPDIR}" = "yes" ]; then
  422. echo Backup Start Time `date`
  423. echo ======================================================================
  424. # Monthly Full Backup of all Databases
  425. if [ "${DOM}" = "01" ]; then
  426. for MDB in ${MDBNAMES} ; do
  427. # Prepare ${DB} for using
  428. MDB="`echo ${MDB} | sed 's/%/ /g'`"
  429. if [ ! -e "${BACKUPDIR}/monthly/${MDB}" ]; then # Check Monthly DB Directory exists.
  430. mkdir -p "${BACKUPDIR}/monthly/${MDB}"
  431. fi
  432. echo Monthly Backup of ${MDB}...
  433. dbdump "${MDB}" "${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.${EXT}"
  434. compression "${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.${EXT}"
  435. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.${EXT}${SUFFIX}*"
  436. echo ----------------------------------------------------------------------
  437. done
  438. fi
  439. for DB in ${DBNAMES} ; do
  440. # Prepare ${DB} for using
  441. DB="`echo ${DB} | sed 's/%/ /g'`"
  442. # Create Seperate directory for each DB
  443. if [ ! -e "${BACKUPDIR}/daily/${DB}" ]; then # Check Daily DB Directory exists.
  444. mkdir -p "${BACKUPDIR}/daily/${DB}"
  445. fi
  446. if [ ! -e "${BACKUPDIR}/weekly/${DB}" ]; then # Check Weekly DB Directory exists.
  447. mkdir -p "${BACKUPDIR}/weekly/${DB}"
  448. fi
  449. # Weekly Backup
  450. if [ "${DNOW}" = "${DOWEEKLY}" ]; then
  451. echo Weekly Backup of Database \( ${DB} \)
  452. echo Rotating 5 weeks Backups...
  453. if [ "${W}" -le 05 ];then
  454. REMW=`expr 48 + ${W}`
  455. elif [ "${W}" -lt 15 ];then
  456. REMW=0`expr ${W} - 5`
  457. else
  458. REMW=`expr ${W} - 5`
  459. fi
  460. rm -fv "${BACKUPDIR}/weekly/${DB}/${DB}_week.${REMW}".*
  461. echo
  462. dbdump "${DB}" "${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.${EXT}"
  463. compression "${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.${EXT}"
  464. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.${EXT}${SUFFIX}*"
  465. echo ----------------------------------------------------------------------
  466. # Daily Backup
  467. else
  468. echo Daily Backup of Database \( ${DB} \)
  469. echo Rotating last weeks Backup...
  470. rm -fv "${BACKUPDIR}/daily/${DB}"/*."${DOW}".${EXT}*
  471. echo
  472. dbdump "${DB}" "${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.${EXT}"
  473. compression "${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.${EXT}"
  474. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.${EXT}${SUFFIX}*"
  475. echo ----------------------------------------------------------------------
  476. fi
  477. done
  478. echo Backup End `date`
  479. echo ======================================================================
  480. else # One backup file for all DBs
  481. echo Backup Start `date`
  482. echo ======================================================================
  483. # Monthly Full Backup of all Databases
  484. if [ "${DOM}" = "01" ]; then
  485. echo Monthly full Backup of \( ${MDBNAMES} \)...
  486. dbdump "${MDBNAMES}" "${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.${EXT}"
  487. compression "${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.${EXT}"
  488. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.${EXT}${SUFFIX}*"
  489. echo ----------------------------------------------------------------------
  490. fi
  491. # Weekly Backup
  492. if [ "${DNOW}" = "${DOWEEKLY}" ]; then
  493. echo Weekly Backup of Databases \( ${DBNAMES} \)
  494. echo
  495. echo Rotating 5 weeks Backups...
  496. if [ "${W}" -le 05 ];then
  497. REMW=`expr 48 + ${W}`
  498. elif [ "${W}" -lt 15 ];then
  499. REMW=0`expr ${W} - 5`
  500. else
  501. REMW=`expr ${W} - 5`
  502. fi
  503. rm -fv "${BACKUPDIR}/weekly/week.${REMW}".*
  504. echo
  505. dbdump "${DBNAMES}" "${BACKUPDIR}/weekly/week.${W}.${DATE}.${EXT}"
  506. compression "${BACKUPDIR}/weekly/week.${W}.${DATE}.${EXT}"
  507. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/weekly/week.${W}.${DATE}.${EXT}${SUFFIX}*"
  508. echo ----------------------------------------------------------------------
  509. # Daily Backup
  510. else
  511. echo Daily Backup of Databases \( ${DBNAMES} \)
  512. echo
  513. echo Rotating last weeks Backup...
  514. rm -fv "${BACKUPDIR}"/daily/*."${DOW}".${EXT}*
  515. echo
  516. dbdump "${DBNAMES}" "${BACKUPDIR}/daily/${DATE}.${DOW}.${EXT}"
  517. compression "${BACKUPDIR}/daily/${DATE}.${DOW}.${EXT}"
  518. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/daily/${DATE}.${DOW}.${EXT}${SUFFIX}*"
  519. echo ----------------------------------------------------------------------
  520. fi
  521. echo Backup End Time `date`
  522. echo ======================================================================
  523. fi
  524. echo Total disk space used for backup storage..
  525. echo Size - Location
  526. echo `du -hs "${BACKUPDIR}"`
  527. echo
  528. # }}}
  529. # {{{ PostBackup
  530. # Run command when we're done
  531. if [ "${POSTBACKUP}" ]
  532. then
  533. echo ======================================================================
  534. echo "Postbackup command output."
  535. echo
  536. ${POSTBACKUP}
  537. echo
  538. echo ======================================================================
  539. fi
  540. # }}}
  541. # {{{ cleanup I/O
  542. #Clean up IO redirection
  543. exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
  544. exec 2>&7 7>&- # Restore stdout and close file descriptor #7.
  545. # }}}
  546. # {{{ Reporting
  547. if [ "${MAILCONTENT}" = "files" ]; then
  548. if [ -s "${LOGERR}" ]; then
  549. # Include error log if is larger than zero.
  550. BACKUPFILES="${BACKUPFILES} ${LOGERR}"
  551. ERRORNOTE="WARNING: Error Reported - "
  552. fi
  553. #Get backup size
  554. ATTSIZE=`du -c ${BACKUPFILES} | grep "[[:digit:][:space:]]total$" |sed s/\s*total//`
  555. if [ ${MAXATTSIZE} -ge ${ATTSIZE} ]; then
  556. if which biabam >/dev/null 2>&1; then
  557. BACKUPFILES=$(echo ${BACKUPFILES} | sed -r -e 's#\s+#,#g')
  558. biabam -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" ${BACKUPFILES} ${MAILADDR} < ${LOGFILE}
  559. elif which heirloom-mailx >/dev/null 2>&1; then
  560. BACKUPFILES=$(echo ${BACKUPFILES} | sed -e 's# # -a #g')
  561. heirloom-mailx -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" ${BACKUPFILES} ${MAILADDR} < ${LOGFILE}
  562. elif which neomutt >/dev/null 2>&1; then
  563. BACKUPFILES=$(echo ${BACKUPFILES} | sed -e 's# # -a #g')
  564. neomutt -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" -a ${BACKUPFILES} -- ${MAILADDR} < ${LOGFILE}
  565. elif which mutt >/dev/null 2>&1; then
  566. BACKUPFILES=$(echo ${BACKUPFILES} | sed -e 's# # -a #g')
  567. mutt -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" -a ${BACKUPFILES} -- ${MAILADDR} < ${LOGFILE}
  568. else
  569. cat "${LOGFILE}" | mail -s "WARNING! - Enable to send PostgreSQL Backup dumps, no suitable mail client found on ${HOST} - ${DATE}" ${MAILADDR}
  570. fi
  571. else
  572. cat "${LOGFILE}" | mail -s "WARNING! - PostgreSQL Backup exceeds set maximum attachment size on ${HOST} - ${DATE}" ${MAILADDR}
  573. fi
  574. elif [ "${MAILCONTENT}" = "log" ]; then
  575. cat "${LOGFILE}" | mail -s "PostgreSQL Backup Log for ${HOST} - ${DATE}" ${MAILADDR}
  576. if [ -s "${LOGERR}" ]; then
  577. cat "${LOGERR}" | mail -s "ERRORS REPORTED: PostgreSQL Backup error Log for ${HOST} - ${DATE}" ${MAILADDR}
  578. fi
  579. elif [ "${MAILCONTENT}" = "quiet" ]; then
  580. if [ -s "${LOGERR}" ]; then
  581. cat "${LOGERR}" | mail -s "ERRORS REPORTED: PostgreSQL Backup error Log for ${HOST} - ${DATE}" ${MAILADDR}
  582. cat "${LOGFILE}" | mail -s "PostgreSQL Backup Log for ${HOST} - ${DATE}" ${MAILADDR}
  583. fi
  584. else
  585. if [ -s "${LOGERR}" ]; then
  586. cat "${LOGFILE}"
  587. echo
  588. echo "###### WARNING ######"
  589. echo "Errors reported during AutoPostgreSQLBackup execution.. Backup failed"
  590. echo "Error log below.."
  591. cat "${LOGERR}"
  592. else
  593. cat "${LOGFILE}"
  594. fi
  595. fi
  596. # }}}
  597. # {{{ Cleanup logs and exit()
  598. if [ -s "${LOGERR}" ]; then
  599. STATUS=1
  600. else
  601. STATUS=0
  602. fi
  603. # Clean up Logfile
  604. rm -f "${LOGFILE}"
  605. rm -f "${LOGERR}"
  606. exit ${STATUS}
  607. # }}}
  608. # vim: foldmethod=marker foldlevel=0 foldenable