autopostgresqlbackup 25 KB

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