贡献一个PostgreSQL的备份脚本(原创)

来源:互联网 发布:java bigdecimal 除法 编辑:程序博客网 时间:2024/05/20 02:21
http://bbs.pgsqldb.com/index.php?t=msg&th=10719&start=0&rid=5371&S=e00de55967f414965f973b2d64c67083

贡献一个PostgreSQL的备份脚本
<script type="text/javascript"><!--google_ad_client = "pub-5873492303276472";/* 728x90, 创建于 08-7-29 */google_ad_slot = "7502041044";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
使用方法:

1. 建立备份目录,设置所有者为postgres
2. 修改pgsql_backup.conf文件,设置需要备份的数据库的数据目录database,和备份目录backup
3. 修改数据库的配置文件postgresql.conf文件,修改archive_command = '/path/to/pgsql_backup.sh archive %p %f'
4. 以postgres用户身份建立定期任务,定期执行pgsql_backup.sh xlog
5. 执行pgsql_backup.sh base进行基础备份(之前,最好执行一次vacuumdb -afz)
6. 执行pgsql_backup.sh clean <timestamp>清除指定时间以前的备份数据


以下是备份脚本pgsql_backup.sh

#!/bin/bash

# 备份PostgreSQL数据库
# 支持以下命令:
# base: 进行一个基础备份
# archive: 归档数据库日志(用于设置postgresql.conf中的archive_command参数)
# xlog: 复制当前部分填充的日志段
# clean: 删除指定日期之前的备份数据
#

#database=/raid/postgresql/8.1/main
#backup=/data/backup/database

. /etc/admin/pgsql_backup.conf

base()
{
local v=$(date "+%Y%m%d")
local d="$backup/base/$v"
mkdir -p "$d"

# vacuumdb -afz
psql template1 -c "select pg_start_backup('$v');"
(cd "$database"; cp -a $(ls | sed 's/pg_xlog//') "$d")
psql template1 -c "select pg_stop_backup();"
}

# archive_command = '/raid/bin/pgsql_backup.sh archive %p %f'
archive()
{
local p="$1"
local f="$2"

if [ "$p" = "" ] || [ "$f" = "" ] || [ -f "$backup/archive/$f" ]; then
return 1
fi

mkdir -p "$backup/archive"

cp -a "$p" "$backup/archive/$f"
}

xlog()
{
mkdir -p "$database/pg_xlog"
rsync -a --delete "$database/pg_xlog" "$backup"
}

clean()
{
local t=$(echo "$1" | grep -E '^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$')

if [ "$t" = "" ]; then
echo "Timestamp '$1' error"
return 1
fi

touch -d "$t" "$backup/base/timestamp"
echo -n "Clean archived logs before $(date -r "$backup/base/timestamp" +"%Y-%m-%d")? [y/N] "
read a
if [ "$a" != "y" ]; then
return 1
fi

echo "cleaning..."

find $backup/archive -mindepth 1 -maxdepth 1 -not -newer $backup/base/timestamp -print -exec rm -rf {} /;
find $backup/base -mindepth 1 -maxdepth 1 -not -newer $backup/base/timestamp -print -exec rm -rf {} /;

echo "done."
}


case $1 in
base)
base
;;
archive)
archive "$2" "$3"
;;
clean)
clean "$2"
;;
xlog)
xlog
;;
*)
echo "usage: $0 {base|archive|xlog|clean}"
exit 1
;;
esac
 <script type="text/javascript"><!--google_ad_client = "pub-5873492303276472";/* 728x15, 创建于 08-7-29 */google_ad_slot = "7630759450";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击