autopostgresqlbackup 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. #!/bin/bash
  2. #
  3. # PostgreSQL Backup Script Ver 1.0
  4. # http://autopgsqlbackup.frozenpc.net
  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. # Change Log
  245. #=====================================================================
  246. #
  247. # VER 1.0 - (2005-03-25)
  248. # Initial Release - based on AutoMySQLBackup 2.2
  249. #
  250. #=====================================================================
  251. #=====================================================================
  252. #=====================================================================
  253. #
  254. # Should not need to be modified from here down!!
  255. #
  256. #=====================================================================
  257. #=====================================================================
  258. #=====================================================================
  259. PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/postgres/bin:/usr/local/pgsql/bin
  260. DATE=`date +%Y-%m-%d_%Hh%Mm` # Datestamp e.g 2002-09-21
  261. DOW=`date +%A` # Day of the week e.g. Monday
  262. DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday
  263. DOM=`date +%d` # Date of the Month e.g. 27
  264. M=`date +%B` # Month e.g January
  265. W=`date +%V` # Week Number e.g 37
  266. VER=1.0 # Version Number
  267. LOGFILE=${BACKUPDIR}/${DBHOST//\//_}-`date +%N`.log # Logfile Name
  268. LOGERR=${BACKUPDIR}/ERRORS_${DBHOST//\//_}-`date +%N`.log # Logfile Name
  269. BACKUPFILES=""
  270. # Add --compress pg_dump option to ${OPT}
  271. if [ "${COMMCOMP}" -gt 0 ]; then
  272. OPT="${OPT} --compress=${COMMCOMP}"
  273. fi
  274. # Create required directories
  275. if [ ! -e "${BACKUPDIR}" ]; then # Check Backup Directory exists.
  276. mkdir -p "${BACKUPDIR}"
  277. fi
  278. if [ ! -e "${BACKUPDIR}/daily" ]; then # Check Daily Directory exists.
  279. mkdir -p "${BACKUPDIR}/daily"
  280. fi
  281. if [ ! -e "${BACKUPDIR}/weekly" ]; then # Check Weekly Directory exists.
  282. mkdir -p "${BACKUPDIR}/weekly"
  283. fi
  284. if [ ! -e "${BACKUPDIR}/monthly" ]; then # Check Monthly Directory exists.
  285. mkdir -p "${BACKUPDIR}/monthly"
  286. fi
  287. if [ "${LATEST}" = "yes" ]; then
  288. if [ ! -e "${BACKUPDIR}/latest" ]; then # Check Latest Directory exists.
  289. mkdir -p "${BACKUPDIR}/latest"
  290. fi
  291. rm -f "${BACKUPDIR}"/latest/*
  292. fi
  293. # IO redirection for logging.
  294. touch ${LOGFILE}
  295. exec 6>&1 # Link file descriptor #6 with stdout.
  296. # Saves stdout.
  297. exec > ${LOGFILE} # stdout replaced with file ${LOGFILE}.
  298. touch ${LOGERR}
  299. exec 7>&2 # Link file descriptor #7 with stderr.
  300. # Saves stderr.
  301. exec 2> ${LOGERR} # stderr replaced with file ${LOGERR}.
  302. # Functions
  303. # Database dump function
  304. dbdump () {
  305. rm -f $2
  306. touch $2
  307. chmod ${PERM} $2
  308. for db in $1 ; do
  309. if [ -n "${SU}_USERNAME" ]; then
  310. if [ "${db}" = "${GLOBALS}_OBJECTS" ]; then
  311. su - ${SU}_USERNAME -l -c "pg_dumpall ${PGHOST} --globals-only" >> $2
  312. else
  313. su - ${SU}_USERNAME -l -c "pg_dump ${PGHOST} ${OPT} ${db}" >> $2
  314. fi
  315. else
  316. if [ "${db}" = "${GLOBALS}_OBJECTS" ]; then
  317. pg_dumpall --username=${USERNAME} ${PGHOST} --globals-only >> $2
  318. else
  319. pg_dump --username=${USERNAME} ${PGHOST} ${OPT} ${db} >> $2
  320. fi
  321. fi
  322. done
  323. return 0
  324. }
  325. # Encryption function
  326. encryption() {
  327. ENCRYPTED_FILE="$1${ENCRYPTION}_SUFFIX"
  328. # Encrypt as needed
  329. if [ "${ENCRYPTION}" = "yes" ]; then
  330. echo
  331. echo "Encrypting $1"
  332. echo " to ${ENCRYPTED}_FILE"
  333. echo " using cypher ${ENCRYPTION}_CIPHER and public key ${ENCRYPTION}_PUBLIC_KEY"
  334. if openssl smime -encrypt -${ENCRYPTION}_CIPHER -binary -outform DEM \
  335. -out "${ENCRYPTED}_FILE" \
  336. -in "$1" "${ENCRYPTION}_PUBLIC_KEY" ; then
  337. echo " and remove $1"
  338. chmod ${PERM} "${ENCRYPTED}_FILE"
  339. rm -f "$1"
  340. fi
  341. fi
  342. return 0
  343. }
  344. # Compression (and encrypt) function plus latest copy
  345. SUFFIX=""
  346. compression () {
  347. if [ "${COMP}" = "gzip" ]; then
  348. gzip -f "$1"
  349. echo
  350. echo Backup Information for "$1"
  351. gzip -l "$1.gz"
  352. SUFFIX=".gz"
  353. echo
  354. elif [ "${COMP}" = "bzip2" ]; then
  355. echo Compression information for "$1.bz2"
  356. bzip2 -f -v $1 2>&1
  357. SUFFIX=".bz2"
  358. elif [ "${COMP}" = "xz" ]; then
  359. xz -9 $1 2>&1
  360. echo Backup information for "$1.xz"
  361. xz -l "$1.xz"
  362. SUFFIX=".xz"
  363. else
  364. echo "No compression option set, check advanced settings"
  365. fi
  366. encryption $1${SUFFIX}
  367. if [ "${LATEST}" = "yes" ]; then
  368. cp $1${SUFFIX}* "${BACKUPDIR}/latest/"
  369. fi
  370. return 0
  371. }
  372. # Run command before we begin
  373. if [ "${PREBACKUP}" ]
  374. then
  375. echo ======================================================================
  376. echo "Prebackup command output."
  377. echo
  378. ${PREBACKUP}
  379. echo
  380. echo ======================================================================
  381. echo
  382. fi
  383. if [ "${SEPDIR}" = "yes" ]; then # Check if CREATE DATABSE should be included in Dump
  384. if [ "${CREATE}_DATABASE" = "no" ]; then
  385. OPT="${OPT}"
  386. else
  387. OPT="${OPT} --create"
  388. fi
  389. else
  390. OPT="${OPT}"
  391. fi
  392. # Hostname for LOG information
  393. if [ "${DBHOST}" = "localhost" ]; then
  394. HOST=`hostname`
  395. PGHOST=""
  396. else
  397. HOST=${DBHOST}
  398. PGHOST="-h ${DBHOST}"
  399. fi
  400. # If backing up all DBs on the server
  401. if [ "${DBNAMES}" = "all" ]; then
  402. if [ -n "${SU}_USERNAME" ]; then
  403. DBNAMES="$(su - ${SU}_USERNAME -l -c "LANG=C psql -U ${USERNAME} ${PGHOST} -l -A -F: | sed -ne '/:/ { /Name:Owner/d; /template0/d; s/:.*$//; p }'")"
  404. else
  405. DBNAMES="`LANG=C psql -U ${USERNAME} ${PGHOST} -l -A -F: | sed -ne "/:/ { /Name:Owner/d; /template0/d; s/:.*$//; p }"`"
  406. fi
  407. # If DBs are excluded
  408. for exclude in ${DBEXCLUDE} ; do
  409. DBNAMES=`echo ${DBNAMES} | sed "s/\b${exclude}\b//g"`
  410. done
  411. DBNAMES="$(echo ${DBNAMES}| tr '\n' ' ')"
  412. MDBNAMES=${DBNAMES}
  413. fi
  414. # Include global objects (users, tablespaces)
  415. DBNAMES="${GLOBALS}_OBJECTS ${DBNAMES}"
  416. MDBNAMES="${GLOBALS}_OBJECTS ${MDBNAMES}"
  417. echo ======================================================================
  418. echo AutoPostgreSQLBackup VER ${VER}
  419. echo http://autopgsqlbackup.frozenpc.net/
  420. echo
  421. echo Backup of Database Server - ${HOST}
  422. echo ======================================================================
  423. # Test is seperate DB backups are required
  424. if [ "${SEPDIR}" = "yes" ]; then
  425. echo Backup Start Time `date`
  426. echo ======================================================================
  427. # Monthly Full Backup of all Databases
  428. if [ "${DOM}" = "01" ]; then
  429. for MDB in ${MDBNAMES} ; do
  430. # Prepare ${DB} for using
  431. MDB="`echo ${MDB} | sed 's/%/ /g'`"
  432. if [ ! -e "${BACKUPDIR}/monthly/${MDB}" ]; then # Check Monthly DB Directory exists.
  433. mkdir -p "${BACKUPDIR}/monthly/${MDB}"
  434. fi
  435. echo Monthly Backup of ${MDB}...
  436. dbdump "${MDB}" "${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.${EXT}"
  437. compression "${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.${EXT}"
  438. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/monthly/${MDB}/${MDB}_${DATE}.${M}.${MDB}.${EXT}${SUFFIX}*"
  439. echo ----------------------------------------------------------------------
  440. done
  441. fi
  442. for DB in ${DBNAMES} ; do
  443. # Prepare ${DB} for using
  444. DB="`echo ${DB} | sed 's/%/ /g'`"
  445. # Create Seperate directory for each DB
  446. if [ ! -e "${BACKUPDIR}/daily/${DB}" ]; then # Check Daily DB Directory exists.
  447. mkdir -p "${BACKUPDIR}/daily/${DB}"
  448. fi
  449. if [ ! -e "${BACKUPDIR}/weekly/${DB}" ]; then # Check Weekly DB Directory exists.
  450. mkdir -p "${BACKUPDIR}/weekly/${DB}"
  451. fi
  452. # Weekly Backup
  453. if [ "${DNOW}" = "${DOWEEKLY}" ]; then
  454. echo Weekly Backup of Database \( ${DB} \)
  455. echo Rotating 5 weeks Backups...
  456. if [ "${W}" -le 05 ];then
  457. REMW=`expr 48 + ${W}`
  458. elif [ "${W}" -lt 15 ];then
  459. REMW=0`expr ${W} - 5`
  460. else
  461. REMW=`expr ${W} - 5`
  462. fi
  463. rm -fv "${BACKUPDIR}/weekly/${DB}/${DB}_week.${REMW}".*
  464. echo
  465. dbdump "${DB}" "${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.${EXT}"
  466. compression "${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.${EXT}"
  467. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/weekly/${DB}/${DB}_week.${W}.${DATE}.${EXT}${SUFFIX}*"
  468. echo ----------------------------------------------------------------------
  469. # Daily Backup
  470. else
  471. echo Daily Backup of Database \( ${DB} \)
  472. echo Rotating last weeks Backup...
  473. rm -fv "${BACKUPDIR}/daily/${DB}"/*."${DOW}".${EXT}*
  474. echo
  475. dbdump "${DB}" "${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.${EXT}"
  476. compression "${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.${EXT}"
  477. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/daily/${DB}/${DB}_${DATE}.${DOW}.${EXT}${SUFFIX}*"
  478. echo ----------------------------------------------------------------------
  479. fi
  480. done
  481. echo Backup End `date`
  482. echo ======================================================================
  483. else # One backup file for all DBs
  484. echo Backup Start `date`
  485. echo ======================================================================
  486. # Monthly Full Backup of all Databases
  487. if [ "${DOM}" = "01" ]; then
  488. echo Monthly full Backup of \( ${MDBNAMES} \)...
  489. dbdump "${MDBNAMES}" "${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.${EXT}"
  490. compression "${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.${EXT}"
  491. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/monthly/${DATE}.${M}.all-databases.${EXT}${SUFFIX}*"
  492. echo ----------------------------------------------------------------------
  493. fi
  494. # Weekly Backup
  495. if [ "${DNOW}" = "${DOWEEKLY}" ]; then
  496. echo Weekly Backup of Databases \( ${DBNAMES} \)
  497. echo
  498. echo Rotating 5 weeks Backups...
  499. if [ "${W}" -le 05 ];then
  500. REMW=`expr 48 + ${W}`
  501. elif [ "${W}" -lt 15 ];then
  502. REMW=0`expr ${W} - 5`
  503. else
  504. REMW=`expr ${W} - 5`
  505. fi
  506. rm -fv "${BACKUPDIR}/weekly/week.${REMW}".*
  507. echo
  508. dbdump "${DBNAMES}" "${BACKUPDIR}/weekly/week.${W}.${DATE}.${EXT}"
  509. compression "${BACKUPDIR}/weekly/week.${W}.${DATE}.${EXT}"
  510. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/weekly/week.${W}.${DATE}.${EXT}${SUFFIX}*"
  511. echo ----------------------------------------------------------------------
  512. # Daily Backup
  513. else
  514. echo Daily Backup of Databases \( ${DBNAMES} \)
  515. echo
  516. echo Rotating last weeks Backup...
  517. rm -fv "${BACKUPDIR}"/daily/*."${DOW}".${EXT}*
  518. echo
  519. dbdump "${DBNAMES}" "${BACKUPDIR}/daily/${DATE}.${DOW}.${EXT}"
  520. compression "${BACKUPDIR}/daily/${DATE}.${DOW}.${EXT}"
  521. BACKUPFILES="${BACKUPFILES} ${BACKUPDIR}/daily/${DATE}.${DOW}.${EXT}${SUFFIX}*"
  522. echo ----------------------------------------------------------------------
  523. fi
  524. echo Backup End Time `date`
  525. echo ======================================================================
  526. fi
  527. echo Total disk space used for backup storage..
  528. echo Size - Location
  529. echo `du -hs "${BACKUPDIR}"`
  530. echo
  531. # Run command when we're done
  532. if [ "${POSTBACKUP}" ]
  533. then
  534. echo ======================================================================
  535. echo "Postbackup command output."
  536. echo
  537. ${POSTBACKUP}
  538. echo
  539. echo ======================================================================
  540. fi
  541. #Clean up IO redirection
  542. exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
  543. exec 2>&7 7>&- # Restore stdout and close file descriptor #7.
  544. if [ "${MAILCONTENT}" = "files" ]; then
  545. if [ -s "${LOGERR}" ]; then
  546. # Include error log if is larger than zero.
  547. BACKUPFILES="${BACKUPFILES} ${LOGERR}"
  548. ERRORNOTE="WARNING: Error Reported - "
  549. fi
  550. #Get backup size
  551. ATTSIZE=`du -c ${BACKUPFILES} | grep "[[:digit:][:space:]]total$" |sed s/\s*total//`
  552. if [ ${MAXATTSIZE} -ge ${ATTSIZE} ]; then
  553. if which biabam >/dev/null 2>&1; then
  554. BACKUPFILES=$(echo ${BACKUPFILES} | sed -r -e 's#\s+#,#g')
  555. biabam -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" ${BACKUPFILES} ${MAILADDR} < ${LOGFILE}
  556. elif which heirloom-mailx >/dev/null 2>&1; then
  557. BACKUPFILES=$(echo ${BACKUPFILES} | sed -e 's# # -a #g')
  558. heirloom-mailx -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" ${BACKUPFILES} ${MAILADDR} < ${LOGFILE}
  559. elif which neomutt >/dev/null 2>&1; then
  560. BACKUPFILES=$(echo ${BACKUPFILES} | sed -e 's# # -a #g')
  561. neomutt -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" -a ${BACKUPFILES} -- ${MAILADDR} < ${LOGFILE}
  562. elif which mutt >/dev/null 2>&1; then
  563. BACKUPFILES=$(echo ${BACKUPFILES} | sed -e 's# # -a #g')
  564. mutt -s "PostgreSQL Backup Log and SQL Files for ${HOST} - ${DATE}" -a ${BACKUPFILES} -- ${MAILADDR} < ${LOGFILE}
  565. else
  566. cat "${LOGFILE}" | mail -s "WARNING! - Enable to send PostgreSQL Backup dumps, no suitable mail client found on ${HOST} - ${DATE}" ${MAILADDR}
  567. fi
  568. else
  569. cat "${LOGFILE}" | mail -s "WARNING! - PostgreSQL Backup exceeds set maximum attachment size on ${HOST} - ${DATE}" ${MAILADDR}
  570. fi
  571. elif [ "${MAILCONTENT}" = "log" ]; then
  572. cat "${LOGFILE}" | mail -s "PostgreSQL Backup Log for ${HOST} - ${DATE}" ${MAILADDR}
  573. if [ -s "${LOGERR}" ]; then
  574. cat "${LOGERR}" | mail -s "ERRORS REPORTED: PostgreSQL Backup error Log for ${HOST} - ${DATE}" ${MAILADDR}
  575. fi
  576. elif [ "${MAILCONTENT}" = "quiet" ]; then
  577. if [ -s "${LOGERR}" ]; then
  578. cat "${LOGERR}" | mail -s "ERRORS REPORTED: PostgreSQL Backup error Log for ${HOST} - ${DATE}" ${MAILADDR}
  579. cat "${LOGFILE}" | mail -s "PostgreSQL Backup Log for ${HOST} - ${DATE}" ${MAILADDR}
  580. fi
  581. else
  582. if [ -s "${LOGERR}" ]; then
  583. cat "${LOGFILE}"
  584. echo
  585. echo "###### WARNING ######"
  586. echo "Errors reported during AutoPostgreSQLBackup execution.. Backup failed"
  587. echo "Error log below.."
  588. cat "${LOGERR}"
  589. else
  590. cat "${LOGFILE}"
  591. fi
  592. fi
  593. if [ -s "${LOGERR}" ]; then
  594. STATUS=1
  595. else
  596. STATUS=0
  597. fi
  598. # Clean up Logfile
  599. rm -f "${LOGFILE}"
  600. rm -f "${LOGERR}"
  601. exit ${STATUS}