X-Original-To: pgsql-admin-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [64.117.224.130]) by svr1.postgresql.org (Postfix) with ESMTP id 52A1ED1C4BA for ; Tue, 12 Aug 2003 17:37:49 +0000 (GMT) Received: from svr1.postgresql.org ([64.117.224.193]) by localhost (neptune.hub.org [64.117.224.130]) (amavisd-new, port 10024) with ESMTP id 92896-03 for ; Tue, 12 Aug 2003 14:36:15 -0300 (ADT) Received: from THOR.goeci.com (thor.goeci.com [66.28.220.99]) by svr1.postgresql.org (Postfix) with ESMTP id 549DDD1B539 for ; Tue, 12 Aug 2003 14:37:37 -0300 (ADT) Received: by THOR.goeci.com with Internet Mail Service (5.5.2653.19) id ; Tue, 12 Aug 2003 13:37:37 -0400 Message-ID: <2D92FEBFD3BE1346A6C397223A8DD3FC09239E@THOR.goeci.com> From: Murthy Kambhampaty To: 'Bruce Momjian' , Christopher Browne Cc: pgsql-admin@postgresql.org Subject: Re: Backup routine Date: Tue, 12 Aug 2003 13:37:37 -0400 MIME-Version: 1.0 X-Mailer: Internet Mail Service (5.5.2653.19) Content-Type: multipart/mixed; boundary="----_=_NextPart_000_01C360F6.8CE4CE94" X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200308/151 X-Sequence-Number: 9873 This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_000_01C360F6.8CE4CE94 Content-Type: text/plain; charset="iso-8859-1" There's an extensive discussion of doing file system level backups off an LVM snapshot taken on a frozen XFS filesystem (XFS provides xfs_freeze command which allows the sysadmin to freeze and unfreeze a given file system at will). See http://marc.theaimsgroup.com/?l=postgresql-admin&w=2&r=1&s=LVM+snapshots&q=b (as Mike Castle points out in this thread, this gives you a "consistent state" but not a know one). If your hardware gives you the ability to freeze I/O, you might get similar capabilities with other filesystems/OSes than XFS on Linux. In that thread, I also discussed a strategy for getting consistent backups when the $PGDATA/pg_xlog/ folder is on a different filesystem: freeze $PGDATA/pg_xlog/ freeze $PGDATA create snapshot $PGDATA/pg_xlog/ and mount that to $PGDATA.snap/pg_xlog\ create snapshot $PGDATA and mount that to $PGDATA.snap unfreeze $PGDATA unfreeze $PGDATA/pg_xlog/ (notice that since you only need to freeze the filesystem during snapshot creation, which is fast, you don't hold the postmaster up very long) rsync $PGDATA.snap/ to a backup volume umount and lvremove the snapshot of $PGDATA/pg_xlog/ umount and lvremove the snapshot of $PGDATA/ Filesystem performance is adversely affected as long as the snapshots exist; so I do a "preliminary rsync" (giving an inconsistent backup) at the beginning of the sequence to minimize the amount of data to be backed up from the snapshot(s). An example bash script which handles $PGDATA/pg_xlog/ being on a different filesystem (and mounted, not symlinked, to $PGDATA/pg_xlog) is attached. It has been tested under a fairly heavy load and seems to handle the job. I'd be interested in comments on the strategy/implementation from the postgresql gurus on this list (the script is rather messy, sorry). Thanks, Murthy >-----Original Message----- >From: Bruce Momjian [mailto:pgman@candle.pha.pa.us] >Sent: Sunday, August 10, 2003 23:13 >To: Christopher Browne >Cc: pgsql-admin@postgresql.org >Subject: Re: [ADMIN] Backup routine > > >Christopher Browne wrote: >> The world rejoiced as peterandsarah@blueyonder.co.uk (Peter >and Sarah Childs) wrote: >> > However there is a third way. That should be safe but some >> > people may disagree with me! If you can "freeze" the disk while you >> > take the backup. The backup can be used as if the computer had >> > crashed with no hard disk failure at all. Ie WAL will be consistant >> > and database may take longer but once it is up it will be >safe (like >> > paragaph 1). Now freezeing a disk for backup is not that >> > difficult. You should be doing it anyway for user file >> > consistancy. (You don't want the first 30 pages of you document to >> > disagree with the end because somone was saving it during the >> > backup! >> >> I heard D'Arcy Cain indicate that some SAN systems (I think he >> mentioned NetApp) support this sort of thing, too. Digital's AdvFS >> also supports it. >> >> Of course, if you take this approach, you have to make _certain_ that >> when you "freeze" a replica of a filesystem, that _ALL_ of the >> database is contained in that one filesystem. If you move WAL to a >> different filesystem, bets would be off again... > >Also, I assume you have to stop the server just for a moment while you >do the freeze, right? > >-- > Bruce Momjian | http://candle.pha.pa.us > pgman@candle.pha.pa.us | (610) 359-1001 > + If your life is a hard drive, | 13 Roberts Road > + Christ can be your backup. | Newtown Square, >Pennsylvania 19073 > >---------------------------(end of >broadcast)--------------------------- >TIP 2: you can get off all lists at once with the unregister command > (send "unregister YourEmailAddressHere" to >majordomo@postgresql.org) > ------_=_NextPart_000_01C360F6.8CE4CE94 Content-Type: application/octet-stream; name="pgSnapBack2.sh.discuss" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="pgSnapBack2.sh.discuss" #!/bin/bash # FN: pgsnapshot.sh # AB: creates and mounts snapshot of $PGDATA; rsyncs from bkHost; # unmounts and removes snapshot; reinitializes database on backup server # DT: 2003-03-05 # AU: S. Murthy Kambhampaty # DISCLAIMER=3D" This document is provided without restriction to aid discussion about files= ystem online backup and recovery (BAR) of the postgresql database cluster. Any other use is very likely to cause all sorts of damage, and is hazardous." # PREREQUISITES: # postgresql (version 7.2.4 and 7.3.2 have been found to work) # rsync (2.5.6) with suitable server configuration on the backup server # LVM (1.0.3, included in latest SGI XFS enhanced kernels, and 1.0.7 have b= een found to work) # ssh with certificate based authentication of postgres user logging in fro= m production server # to backup server echo $DISCLAIMER exit 9999 PATH=3D/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # What is this script called and where is it running: ThisCMD=3D$(echo -e "$(basename $0)" | awk 'BEGIN{FS=3D"."}{print $1}') pgSRV=3D$(echo -e "$(hostname)" | awk 'BEGIN{FS=3D"."}{print $1}') # The postgresql superuser # (if you want to mail error logs somewhere else, either # set your mail server to forward pgSuper's mail, or add a pgMonitor # and change the two sendmail command lines below: pgSuper=3Dpostgres BackupSRV=3DbkHost DataFS=3D/home/db pgData=3D/home/db/pgsql/pgdata RsyncDM=3D"mirrors_$pgSRV" # What is the rsync module on the backup server = called SnapNM=3Dpgsnapshot XLSnapNM=3Dpgxlsnapshot # # As long as you have installed postgresql in # "/usr/bin/pgsql-M.m/, where M.m=3D$(echo -n $(cat $PGDATA/PG_VERSION)), # on both the production server and the backup server, # you shouldn;t have to edit beyond this point # # If $pgData is a symlink, redefine pgData [[ -L "$pgData" ]] && pgData=3D$(ls -l "$pgData" | awk '{FS=3D" "}{print $N= F}') # Which version of postgresql? pgMinor=3D$(echo -n "$(cat "$pgData/PG_VERSION")") # A function to execute commands on the backup server: RMTExec () { ssh -i "/home/$pgSuper/.ssh/id_rsa" $pgSuper@$BackupSRV "$1" } # A function to do the rsync # /etc/rsync.d on the backup server must be configured # A module named mirrors_$pgSRV must point to a directory # on the backup server. Within that folder a subdirectory # named pgdata must exist, and will contain the backup # copy of the database RsyncLockFile=3D"/home/$pgSuper/$ThisCMD.lock" # rsync options: # The -B option to increase block size on large files: # 1. Reduces the chance of changes being missed # 2. Uses more bandwidth # If you are really paranoid about missing changes, or if most # tables have very little common data from backup to backup, add the # -W option to rsync whole files, rather than changes only. # NOTE: give the -n option to rsync until sure that it # is configured properly. rsync is not forgiviging. RsyncCMD () { rsync -avW -B $((1024 *1024)) --stats \ --delete --force --exclude=3D'postmaster.pid' \ $1/ \ $BackupSRV::$RsyncDM/pgdata/$2/ # If you don't give a second arguement, $2= is null } # When the postmaster is started on the backup server, # the data directory is: pgDataBK=3D$(RMTExec "cat /etc/rsyncd.conf" | sed -n /$RsyncDM/,/^$/p | gre= p path | awk 'BEGIN{FS=3D" =3D "}{print $2}')"/pgdata" # A function to print a formatted timestamp in the log DateCMD () { # Two trailing spaces are intentional echo -n "$(date +%Y-%m-%d) $(date +%X) " return 0 } # A function to mail the error log and bailout; called on program error ExitOnError () { # This function takes two arguments an "exit code" and and "error message" # in order rm -f "$DoSnapLockFile" &>/dev/null echo $'\n\n'"$(DateCMD) $2"$'\n\t'\ "Notified superuser"\ | tee -a "$STASFile" >&2 exec >&6 6>&- exec 2>&7 7>&- cat <(echo "Subject: ATTN: $2"\ $'\n'"X-Priority: 2 (high)"\ $'\n'"!"\ $'\n\t'"Review $(echo -n "$LogFile"), the command log"\ $'\n\t\t'"Error report listed below:" $'\n')\ "$LogFile.err"\ | sendmail "$pgSuper" exit $1 return $1 # Superfluous: this function does not return } # A function for LVM snapshot creation and mounting # There must exist a directory named /mnt/$SnapNM # to which the snapshot is mounted DataLV=3D"$(mount | grep "$DataFS\>[^/]" | awk 'BEGIN{FS=3D" "}{print $1}')" DataVG=3D"$(dirname "$DataLV")" # Please keep the XLogLV and DataLV in the = same VG SnapDir=3D"/mnt/$SnapNM" XlogLV=3D"$(mount | grep "$pgData/pg_xlog\>[^/]" | awk 'BEGIN{FS=3D" "}{pri= nt $1}')" [[ -n "$XlogLV" ]] && XLSnapMB=3D512 DoSnap () { AvailMB=3D"$(echo -n $(vgdisplay --colon "$DataVG") | awk 'BEGIN{FS=3D":"}= {print $16 *$13/2048}')" # 2048 512-byte blocks per MB if [[ -n "$(lvscan | grep "$SnapNM")" || -n "$(lvscan | grep "$XLSnapNM")"= ]]; then echo $'\n\t'"WARNING: Snapshot named $SnapNM or $XLSnapNM already exists.= Terminating ..." >&2 SnapTest=3D32 # lvcreate error: "32 snapshot already exists" elif ((-XLSnapMB +AvailMB <=3D0)); then # Variables need not be preceeded = by '$' in arithmetic expansion; # the above syntax does not work if you test ((-$XLSnapMB +$AvailMB)), s= o you'll # have to put up with the confusion over referencing variables without t= he preceding # $-sign sometimes echo $'\n\t'"WARNING: No space left in $DataVG for snapshot creation. Ter= minating ..." >&2 SnapTest=3D19 # lvcreate error: "19 not enoungh space available to create= logical volume" else # Use all the free space available in $DataVG for the snapshot! [[ -n "$XlogLV" ]] && xfs_freeze -f "$pgData/pg_xlog" xfs_freeze -f "$DataFS" [[ -n "$XlogLV" ]] && { lvcreate -s -L "$XLSnapMB"M -n "$XLSnapNM" "$Xlog= LV"; XLSnapTest=3D$?; } lvcreate -s -L "$((-XLSnapMB +AvailMB))"M -n "$SnapNM" "$DataLV" SnapTest=3D$? xfs_freeze -u "$DataFS" [[ -n "$XlogLV" ]] && xfs_freeze -u "$pgData/pg_xlog" fi # If snapshot creation failed bail; else mount the snapshot volume if ((+XLSnapTest +SnapTest >0)); then ExitOnError 991$SnapTextXL$SnapTest "pgBackup; Snapshot creation failed" else echo $'\n\t'"$(DateCMD) Successfully created snapshot" lvscan | grep snap # Report the snapshot volumes [[ -n "$XlogLV" ]] && { mount -t xfs "$DataVG/$XLSnapNM" "/mnt/$XLSnapNM"= -o nouuid,ro; XLMountTest=3D$?; } LogDev=3D"$(cat "/etc/mtab" | grep "$DataFS\>[^/]" | awk 'BEGIN{FS=3D"log= dev=3D"}{print $2}' | awk 'BEGIN{FS=3D","}{print $1}')" if [[ -n "$LogDev" ]]; then mount -t xfs "$DataVG/$SnapNM" "$SnapDir" -o nouuid,ro,logdev=3D"$LogDe= v" MountTest=3D$? else mount -t xfs "$DataVG/$SnapNM" "$SnapDir" -o nouuid,ro MountTest=3D$? fi mount | grep snap # Report the mounts fi # If snapshot mount failed, then bail; else return if ((+$MountTestXL +$MountTest >0)); then lvremove -f "$DataVG/$SnapNM" [[ -n "$XlogLV" ]] && lvremove -f "$DataVG/$XLSnapNM" ExitOnError 992$MountTest "pgBackup; Snapshot mount failed" fi return 0 # Only returns on success } # Setup logging, and get going: STASFile=3D"$pgData/pgSnapBack.status" LogFile=3D"/home/$pgSuper/$ThisCMD-$(date +%Y%m%d-%H%M)" exec 6>&1; exec > "$LogFile" exec 7>&2; exec 2> "$LogFile.err" echo "$(DateCMD) Backup initiated"\ | tee "$STASFile" # First vacuum all databases # echo $'\n\n'"$(DateCMD) Vacuuming databases on $(hostname)" # # Mark vacuum start and end in the log to ease log navigation # /usr/local/pgsql/bin/psql -U gouser -d template1 -c \ # "select '+++++ Nightly Vacuum About To Commence +++++'" >/dev/null # /usr/local/pgsql/bin/vacuumdb -U postgres -q -a -z && \ # /usr/local/pgsql/bin/psql -U gouser -d template1 -c \ # "select '+++++ Nightly Vacuum Completed +++++'" >/dev/null && \ # echo $'\n\t' "$(DateCMD) Successfully vacuumed databases on $(hostname)" # Phase 1 rsync echo $'\n\n'"$(DateCMD) Phase 1 - rsync from pgdata to mirror on $BackupSRV= "\ | tee -a "$STASFile" while [[ -f "$RsyncLockFile" ]]; do echo "$(DateCMD) previous Rsync still running"$'\n'\ "Waiting for completion" >&2 sleep 300 done # Before you start the backup, make sure that no postmaster is running on t= he backup folder: # (test cribbed from the pg_ctl script) while [[ -n $(RMTExec "sed -n 1p $pgDataBK/postmaster.pid 2>/dev/null") ]];= do echo "$(DateCMD) A postmaster is running at the remote location; waiting = 5 minutes ..." sleep 300 done # You don't want to start simultaneous rsyncs, and you don't want to # start the postmaster while an rsync is running; so put down some # lock files (there was something on linux-xfs about xfs not recovering # inodes allocated to empty files, so don't just "touch" a lockfile, put # something in it). echo "$(DateCMD) Phase 1 - rsync" > "$RsyncLockFile" cat "$RsyncLockFile" | RMTExec "cat - > ~/RsyncLockFile" RsyncCMD "$pgData/" && echo $'\n'"$(DateCMD) Rsync complete"$'\n\n' rm -f "$RsyncLockFile" # Now create and mount the snapshot volume # I'm still seing XFS lockups that go away with xfs_freeze -u $DataFS # So, put up a monitor for all processes wanting to write to to the $DataFS= , and if # you see a D-state on those processes, issue xfs_freeze -u $DataFS DoSnapLockFile=3D"/usr/var/lock/$(basename "$LogFile").PID" ParentPID=3D$$ echo $ParentPID > "$DoSnapLockFile" # Initailize "$DoSnapLockFile" ( while [[ -f "$DoSnapLockFile" ]]; do sleep 60.$ParentPID # snaphsots should not take a full minute, but keep an= eye on this one [[ -f "$DoSnapLockFile" ]] && # In a successful run, it could be gone by t= he time we wake this loop { if [[ "$(ps -eo pid,ppid,session,stat,wchan | grep "D xfs_check_frozen"= | grep $ParentPID )" !=3D "" ]]; then echo $'\n'"Snapshot creation seems to have led to system lockup." \ $'\n\t'"Process list from backup session:" >&2 ps -eo pid,ppid,session,flags,pagein,stackp,stat,args,wchan | grep $Paren= tPID | sed -e "/grep/d" >&2 echo $'\n'"Issuing xfs_freeze -u $DataFS" \ $'\n\t'"Consider this backup unsuccessful." >&2 xfs_freeze -u "$DataFS" [[ -n "$XlogLV" ]] && xfs_freeze -u "$pgData/pg_xlog" rm -f "$DoSnapLockFile" break fi } done ) & echo $'\n\n'"$(DateCMD) Snapshot creation and mounting"\ | tee -a "$STASFile" DoSnap # Phase 2 rsync echo $'\n\n'"$(DateCMD) Phase 2 - rsync from snapshot to mirror on ""$Backu= pSRV" while [[ -f "$RsyncLockFile" ]]; do echo "$(DateCMD) previous Rsync still running"$'\n'\ "Waiting for completion" >&2 sleep 300 done echo "$(DateCMD) Phase 2 rsync" > "$RsyncLockFile" cat "$RsyncLockFile" | RMTExec "cat - > ~/RsyncLockFile" RsyncCMD "--exclude=3D'pg_xlog/' $SnapDir${pgData#$DataFS}" / && { [[ -n "$XlogLV" ]] && RsyncCMD "/mnt/$XLSnapNM/" "pg_xlog"; } && echo $'\n\t'"$(DateCMD) Phase 2 rsync complete"$'\n'\ | tee -a "$STASFile" rm -f "$RsyncLockFile" RMTExec "rm -f ~/RsyncLockFile" # Now remove the snapshot and monitoring stuff umount "$DataVG/$SnapNM" umount "/mnt/$XLSnapNM" lvremove -f "$DataVG/$SnapNM" [[ -n "$XlogLV" ]] && lvremove -f "$DataVG/$XLSnapNM" # should no longer be an issue rm -f "$DoSnapLockFile" kill -INT $(ps ax | grep sleep | grep $ParentPID | awk 'BEGIN{FS=3D" "}{pri= nt $1}') &>/dev/null && \ echo "$(DateCMD) Removed snapshot of \$PGDATA"$'\n\n' # "Reinitialize" the snapshot of the database on the backup server echo $'\n\n'"$(DateCMD) Start postmaster on $BackupSRV, capture output, and= shutdown" RMTExec "/usr/local/pgsql-$pgMinor/bin/postmaster -B4096 -p55432\ -D $pgDataBK 2>&1" & sleep 300 # give the postmaster time for recovery RMTExec "/usr/local/pgsql-$pgMinor/bin/pg_ctl stop -D $pgDataBK -m immediat= e" && echo $'\n\n'"$(DateCMD) Attempted to reinitialize backup; check for errors= above" # Mop up if [[ ! -s "$LogFile.err" ]]; then echo "Completed, no errors" > "$LogFile.err" rm -f "$LogFile.err" echo $'\n\n'"$(DateCMD) Backup completed."\ | tee -a "$STASFile" echo "$(DateCMD) Verify postmaster-messages, listed above, for success." exec >&6 6>&- exec 2>&7 7>&- exit 0 else ExitOnError 999 "pgBackup; Backup encountered errors" fi true # Superflous ------_=_NextPart_000_01C360F6.8CE4CE94--