autopostgresqlbackup 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. #
  7. # This script is based of the AutoMySQLBackup Script Ver 2.2
  8. # It can be found at http://sourceforge.net/projects/automysqlbackup/
  9. #
  10. # The PostgreSQL changes are based on a patch agaisnt AutoMySQLBackup 1.9
  11. # created by Friedrich Lobenstock <fl@fl.priv.at>
  12. #
  13. # This program is free software; you can redistribute it and/or modify
  14. # it under the terms of the GNU General Public License as published by
  15. # the Free Software Foundation; either version 2 of the License, or
  16. # (at your option) any later version.
  17. #
  18. # This program is distributed in the hope that it will be useful,
  19. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. # GNU General Public License for more details.
  22. #
  23. # You should have received a copy of the GNU General Public License
  24. # along with this program; if not, write to the Free Software
  25. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  26. #
  27. #=====================================================================
  28. # Set the following variables to your system needs
  29. # (Detailed instructions below variables)
  30. #=====================================================================
  31. # Username to access the PostgreSQL server e.g. dbuser
  32. USERNAME=postgres
  33. # Password
  34. # create a file $HOME/.pgpass containing a line like this
  35. # hostname:*:*:dbuser:dbpass
  36. # replace hostname with the value of DBHOST and postgres with
  37. # the value of USERNAME
  38. # Host name (or IP address) of PostgreSQL server e.g localhost
  39. DBHOST=localhost
  40. # List of DBNAMES for Daily/Weekly Backup e.g. "DB1 DB2 DB3"
  41. DBNAMES="all"
  42. # Backup directory location e.g /backups
  43. BACKUPDIR="/home/backups/pgsql_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. MAILCONTENT="log"
  50. # Set the maximum allowed email size in k. (4000 = approx 5MB email [see docs])
  51. MAXATTSIZE="4000"
  52. # Email Address to send mail to? (user@domain.com)
  53. MAILADDR="root@localhost"
  54. # ============================================================
  55. # === ADVANCED OPTIONS ( Read the doc's below for details )===
  56. #=============================================================
  57. # List of DBBNAMES for Monthly Backups.
  58. MDBNAMES="template1 $DBNAMES"
  59. # List of DBNAMES to EXLUCDE if DBNAMES are set to all (must be in " quotes)
  60. DBEXCLUDE=""
  61. # Include CREATE DATABASE in backup?
  62. CREATE_DATABASE=yes
  63. # Separate backup directory and file for each DB? (yes or no)
  64. SEPDIR=yes
  65. # Which day do you want weekly backups? (1 to 7 where 1 is Monday)
  66. DOWEEKLY=6
  67. # Choose Compression type. (gzip or bzip2)
  68. COMP=gzip
  69. # Command to run before backups (uncomment to use)
  70. #PREBACKUP="/etc/pgsql-backup-pre"
  71. # Command run after backups (uncomment to use)
  72. POSTBACKUP="bash /home/backups/scripts/ftp_pgsql"
  73. #=====================================================================
  74. # Options documentation
  75. #=====================================================================
  76. # Set USERNAME and PASSWORD of a user that has at least SELECT permission
  77. # to ALL databases.
  78. #
  79. # Set the DBHOST option to the server you wish to backup, leave the
  80. # default to backup "this server".(to backup multiple servers make
  81. # copies of this file and set the options for that server)
  82. #
  83. # Put in the list of DBNAMES(Databases)to be backed up. If you would like
  84. # to backup ALL DBs on the server set DBNAMES="all".(if set to "all" then
  85. # any new DBs will automatically be backed up without needing to modify
  86. # this backup script when a new DB is created).
  87. #
  88. # If the DB you want to backup has a space in the name replace the space
  89. # with a % e.g. "data base" will become "data%base"
  90. # NOTE: Spaces in DB names may not work correctly when SEPDIR=no.
  91. #
  92. # You can change the backup storage location from /backups to anything
  93. # you like by using the BACKUPDIR setting..
  94. #
  95. # The MAILCONTENT and MAILADDR options and pretty self explanitory, use
  96. # these to have the backup log mailed to you at any email address or multiple
  97. # email addresses in a space seperated list.
  98. # (If you set mail content to "log" you will require access to the "mail" program
  99. # on your server. If you set this to "files" you will have to have mutt installed
  100. # on your server. If you set it sto stdout it will log to the screen if run from
  101. # the console or to the cron job owner if run through cron)
  102. #
  103. # MAXATTSIZE sets the largest allowed email attachments total (all backup files) you
  104. # want the script to send. This is the size before it is encoded to be sent as an email
  105. # so if your mail server will allow a maximum mail size of 5MB I would suggest setting
  106. # MAXATTSIZE to be 25% smaller than that so a setting of 4000 would probably be fine.
  107. #
  108. # Finally copy automysqlbackup.sh to anywhere on your server and make sure
  109. # to set executable permission. You can also copy the script to
  110. # /etc/cron.daily to have it execute automatically every night or simply
  111. # place a symlink in /etc/cron.daily to the file if you wish to keep it
  112. # somwhere else.
  113. # NOTE:On Debian copy the file with no extention for it to be run
  114. # by cron e.g just name the file "automysqlbackup"
  115. #
  116. # Thats it..
  117. #
  118. #
  119. # === Advanced options doc's ===
  120. #
  121. # The list of MDBNAMES is the DB's to be backed up only monthly. You should
  122. # always include "mysql" in this list to backup your user/password
  123. # information along with any other DBs that you only feel need to
  124. # be backed up monthly. (if using a hosted server then you should
  125. # probably remove "mysql" as your provider will be backing this up)
  126. # NOTE: If DBNAMES="all" then MDBNAMES has no effect as all DBs will be backed
  127. # up anyway.
  128. #
  129. # If you set DBNAMES="all" you can configure the option DBEXCLUDE. Other
  130. # wise this option will not be used.
  131. # This option can be used if you want to backup all dbs, but you want
  132. # exclude some of them. (eg. a db is to big).
  133. #
  134. # Set CREATE_DATABASE to "yes" (the default) if you want your SQL-Dump to create
  135. # a database with the same name as the original database when restoring.
  136. # Saying "no" here will allow your to specify the database name you want to
  137. # restore your dump into, making a copy of the database by using the dump
  138. # created with automysqlbackup.
  139. # NOTE: Not used if SEPDIR=no
  140. #
  141. # The SEPDIR option allows you to choose to have all DBs backed up to
  142. # a single file (fast restore of entire server in case of crash) or to
  143. # seperate directories for each DB (each DB can be restored seperately
  144. # in case of single DB corruption or loss).
  145. #
  146. # To set the day of the week that you would like the weekly backup to happen
  147. # set the DOWEEKLY setting, this can be a value from 1 to 7 where 1 is Monday,
  148. # The default is 6 which means that weekly backups are done on a Saturday.
  149. #
  150. # COMP is used to choose the copmression used, options are gzip or bzip2.
  151. # bzip2 will produce slightly smaller files but is more processor intensive so
  152. # may take longer to complete.
  153. #
  154. # Use PREBACKUP and POSTBACKUP to specify Per and Post backup commands
  155. # or scripts to perform tasks either before or after the backup process.
  156. #
  157. #
  158. #=====================================================================
  159. # Backup Rotation..
  160. #=====================================================================
  161. #
  162. # Daily Backups are rotated weekly..
  163. # Weekly Backups are run by default on Saturday Morning when
  164. # cron.daily scripts are run...Can be changed with DOWEEKLY setting..
  165. # Weekly Backups are rotated on a 5 week cycle..
  166. # Monthly Backups are run on the 1st of the month..
  167. # Monthly Backups are NOT rotated automatically...
  168. # It may be a good idea to copy Monthly backups offline or to another
  169. # server..
  170. #
  171. #=====================================================================
  172. # Please Note!!
  173. #=====================================================================
  174. #
  175. # I take no resposibility for any data loss or corruption when using
  176. # this script..
  177. # This script will not help in the event of a hard drive crash. If a
  178. # copy of the backup has not be stored offline or on another PC..
  179. # You should copy your backups offline regularly for best protection.
  180. #
  181. # Happy backing up...
  182. #
  183. #=====================================================================
  184. # Change Log
  185. #=====================================================================
  186. #
  187. # VER 1.0 - (2005-03-25)
  188. # Initial Release - based on AutoMySQLBackup 2.2
  189. #
  190. #=====================================================================
  191. #=====================================================================
  192. #
  193. # Should not need to be modified from here down!!
  194. #
  195. #=====================================================================
  196. #=====================================================================
  197. PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/postgres/bin:/usr/local/pgsql/bin
  198. DATE=`date +%Y-%m-%d` # Datestamp e.g 2002-09-21
  199. DOW=`date +%A` # Day of the week e.g. Monday
  200. DNOW=`date +%u` # Day number of the week 1 to 7 where 1 represents Monday
  201. DOM=`date +%d` # Date of the Month e.g. 27
  202. M=`date +%B` # Month e.g January
  203. W=`date +%V` # Week Number e.g 37
  204. VER=1.0 # Version Number
  205. LOGFILE=$BACKUPDIR/$DBHOST-`date +%N`.log # Logfile Name
  206. OPT="" # OPT string for use with mysqldump ( see man mysqldump )
  207. BACKUPFILES="" # thh: added for later mailing
  208. # Create required directories
  209. if [ ! -e "$BACKUPDIR" ] # Check Backup Directory exists.
  210. then
  211. mkdir -p "$BACKUPDIR"
  212. fi
  213. if [ ! -e "$BACKUPDIR/daily" ] # Check Daily Directory exists.
  214. then
  215. mkdir -p "$BACKUPDIR/daily"
  216. fi
  217. if [ ! -e "$BACKUPDIR/weekly" ] # Check Weekly Directory exists.
  218. then
  219. mkdir -p "$BACKUPDIR/weekly"
  220. fi
  221. if [ ! -e "$BACKUPDIR/monthly" ] # Check Monthly Directory exists.
  222. then
  223. mkdir -p "$BACKUPDIR/monthly"
  224. fi
  225. # IO redirection for logging.
  226. touch $LOGFILE
  227. exec 6>&1 # Link file descriptor #6 with stdout.
  228. # Saves stdout.
  229. exec > $LOGFILE # stdout replaced with file $LOGFILE.
  230. # Functions
  231. # Database dump function
  232. dbdump () {
  233. pg_dump --username=$USERNAME $HOST $OPT $1 > $2
  234. return 0
  235. }
  236. # Compression function
  237. SUFFIX=""
  238. compression () {
  239. if [ "$COMP" = "gzip" ]; then
  240. gzip -f "$1"
  241. echo
  242. echo Backup Information for "$1"
  243. gzip -l "$1.gz"
  244. SUFFIX=".gz"
  245. elif [ "$COMP" = "bzip2" ]; then
  246. echo Compression information for "$1.bz2"
  247. bzip2 -f -v $1 2>&1
  248. SUFFIX=".bz2"
  249. else
  250. echo "No compression option set, check advanced settings"
  251. fi
  252. return 0
  253. }
  254. # Run command before we begin
  255. if [ "$PREBACKUP" ]
  256. then
  257. echo ======================================================================
  258. echo "Prebackup command output."
  259. echo
  260. eval $PREBACKUP
  261. echo
  262. echo ======================================================================
  263. echo
  264. fi
  265. if [ "$SEPDIR" = "yes" ]; then # Check if CREATE DATABSE should be included in Dump
  266. if [ "$CREATE_DATABASE" = "no" ]; then
  267. OPT="$OPT"
  268. else
  269. OPT="$OPT --create"
  270. fi
  271. else
  272. OPT="$OPT"
  273. fi
  274. # Hostname for LOG information
  275. if [ "$DBHOST" = "localhost" ]; then
  276. DBHOST="`hostname -f`"
  277. HOST=""
  278. else
  279. HOST="-h $DBHOST"
  280. fi
  281. # If backing up all DBs on the server
  282. if [ "$DBNAMES" = "all" ]; then
  283. DBNAMES="`psql -U $USERNAME $HOST -l -A -F: | sed -ne "/:/ { /Name:Owner/d; /template0/d; s/:.*$//; p }"`"
  284. # If DBs are excluded
  285. for exclude in $DBEXCLUDE
  286. do
  287. DBNAMES=`echo $DBNAMES | sed "s/\b$exclude\b//g"`
  288. done
  289. MDBNAMES=$DBNAMES
  290. fi
  291. echo ======================================================================
  292. echo AutoPostgreSQLBackup VER $VER
  293. echo http://autopgsqlbackup.frozenpc.net/
  294. echo
  295. echo Backup of Database Server - $DBHOST
  296. echo ======================================================================
  297. # Test is seperate DB backups are required
  298. if [ "$SEPDIR" = "yes" ]; then
  299. echo Backup Start Time `date`
  300. echo ======================================================================
  301. # Monthly Full Backup of all Databases
  302. if [ $DOM = "01" ]; then
  303. for MDB in $MDBNAMES
  304. do
  305. # Prepare $DB for using
  306. MDB="`echo $MDB | sed 's/%/ /g'`"
  307. if [ ! -e "$BACKUPDIR/monthly/$MDB" ] # Check Monthly DB Directory exists.
  308. then
  309. mkdir -p "$BACKUPDIR/monthly/$MDB"
  310. fi
  311. echo Monthly Backup of $MDB...
  312. dbdump "$MDB" "$BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql"
  313. compression "$BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql"
  314. BACKUPFILES="$BACKUPFILES $BACKUPDIR/monthly/$MDB/${MDB}_$DATE.$M.$MDB.sql$SUFFIX"
  315. echo ----------------------------------------------------------------------
  316. done
  317. fi
  318. for DB in $DBNAMES
  319. do
  320. # Prepare $DB for using
  321. DB="`echo $DB | sed 's/%/ /g'`"
  322. # Create Seperate directory for each DB
  323. if [ ! -e "$BACKUPDIR/daily/$DB" ] # Check Daily DB Directory exists.
  324. then
  325. mkdir -p "$BACKUPDIR/daily/$DB"
  326. fi
  327. if [ ! -e "$BACKUPDIR/weekly/$DB" ] # Check Weekly DB Directory exists.
  328. then
  329. mkdir -p "$BACKUPDIR/weekly/$DB"
  330. fi
  331. # Weekly Backup
  332. if [ $DNOW = $DOWEEKLY ]; then
  333. echo Weekly Backup of Database \( $DB \)
  334. echo Rotating 5 weeks Backups...
  335. if [ "$W" -le 05 ];then
  336. REMW=`expr 48 + $W`
  337. elif [ "$W" -lt 15 ];then
  338. REMW=0`expr $W - 5`
  339. else
  340. REMW=`expr $W - 5`
  341. fi
  342. eval rm -fv "$BACKUPDIR/weekly/$DB/week.$REMW.*"
  343. echo
  344. dbdump "$DB" "$BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql"
  345. compression "$BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql"
  346. BACKUPFILES="$BACKUPFILES $BACKUPDIR/weekly/$DB/${DB}_week.$W.$DATE.sql$SUFFIX"
  347. echo ----------------------------------------------------------------------
  348. # Daily Backup
  349. else
  350. echo Daily Backup of Database \( $DB \)
  351. echo Rotating last weeks Backup...
  352. eval rm -fv "$BACKUPDIR/daily/$DB/*.$DOW.sql.*"
  353. echo
  354. dbdump "$DB" "$BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql"
  355. compression "$BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql"
  356. BACKUPFILES="$BACKUPFILES $BACKUPDIR/daily/$DB/${DB}_$DATE.$DOW.sql$SUFFIX"
  357. echo ----------------------------------------------------------------------
  358. fi
  359. done
  360. echo Backup End `date`
  361. echo ======================================================================
  362. else # One backup file for all DBs
  363. echo Backup Start `date`
  364. echo ======================================================================
  365. # Monthly Full Backup of all Databases
  366. if [ $DOM = "01" ]; then
  367. echo Monthly full Backup of \( $MDBNAMES \)...
  368. dbdump "$MDBNAMES" "$BACKUPDIR/monthly/$DATE.$M.all-databases.sql"
  369. compression "$BACKUPDIR/monthly/$DATE.$M.all-databases.sql"
  370. BACKUPFILES="$BACKUPFILES $BACKUPDIR/monthly/$DATE.$M.all-databases.sql$SUFFIX"
  371. echo ----------------------------------------------------------------------
  372. fi
  373. # Weekly Backup
  374. if [ $DNOW = $DOWEEKLY ]; then
  375. echo Weekly Backup of Databases \( $DBNAMES \)
  376. echo
  377. echo Rotating 5 weeks Backups...
  378. if [ "$W" -le 05 ];then
  379. REMW=`expr 48 + $W`
  380. elif [ "$W" -lt 15 ];then
  381. REMW=0`expr $W - 5`
  382. else
  383. REMW=`expr $W - 5`
  384. fi
  385. eval rm -fv "$BACKUPDIR/weekly/week.$REMW.*"
  386. echo
  387. dbdump "$DBNAMES" "$BACKUPDIR/weekly/week.$W.$DATE.sql"
  388. compression "$BACKUPDIR/weekly/week.$W.$DATE.sql"
  389. BACKUPFILES="$BACKUPFILES $BACKUPDIR/weekly/week.$W.$DATE.sql$SUFFIX"
  390. echo ----------------------------------------------------------------------
  391. # Daily Backup
  392. else
  393. echo Daily Backup of Databases \( $DBNAMES \)
  394. echo
  395. echo Rotating last weeks Backup...
  396. eval rm -fv "$BACKUPDIR/daily/*.$DOW.sql.*"
  397. echo
  398. dbdump "$DBNAMES" "$BACKUPDIR/daily/$DATE.$DOW.sql"
  399. compression "$BACKUPDIR/daily/$DATE.$DOW.sql"
  400. BACKUPFILES="$BACKUPFILES $BACKUPDIR/daily/$DATE.$DOW.sql$SUFFIX"
  401. echo ----------------------------------------------------------------------
  402. fi
  403. echo Backup End Time `date`
  404. echo ======================================================================
  405. fi
  406. echo Total disk space used for backup storage..
  407. echo Size - Location
  408. echo `du -hs "$BACKUPDIR"`
  409. echo
  410. # Run command when we're done
  411. if [ "$POSTBACKUP" ]
  412. then
  413. echo ======================================================================
  414. echo "Postbackup command output."
  415. echo
  416. eval $POSTBACKUP
  417. echo
  418. echo ======================================================================
  419. fi
  420. #Clean up IO redirection
  421. exec 1>&6 6>&- # Restore stdout and close file descriptor #6.
  422. if [ "$MAILCONTENT" = "files" ]
  423. then
  424. #Get backup size
  425. ATTSIZE=`du -c $BACKUPFILES | grep "[[:digit:][:space:]]total$" |sed s/\s*total//`
  426. if [ $MAXATTSIZE -ge $ATTSIZE ]
  427. then
  428. BACKUPFILES=`echo "$BACKUPFILES" | sed -e "s# # -a #g"` #enable multiple attachments
  429. mutt -s "PostgreSQL Backup Log and SQL Files for $DBHOST - $DATE" $BACKUPFILES $MAILADDR < $LOGFILE #send via mutt
  430. else
  431. cat "$LOGFILE" | mail -s "WARNING! - PostgreSQL Backup exceeds set maximum attachment size on $HOST - $DATE" $MAILADDR
  432. fi
  433. elif [ "$MAILCONTENT" = "log" ]
  434. then
  435. cat "$LOGFILE" | mail -s "PostgreSQL Backup Log for $DBHOST - $DATE" $MAILADDR
  436. else
  437. cat "$LOGFILE"
  438. fi
  439. # Clean up Logfile
  440. eval rm -f "$LOGFILE"
  441. exit 0