rsync详解

##########################################################

#

#    rsync 3.0 解决了同步海量文件而占用内存比较高的原因

#

##########################################################

 

Linux发行版中大多都自带rsync,不过版本比较低,一般都是2.6.X

2.X的版本中,rsync备份时都是先列表再备份(添加或者删除),在处理大量文件时,会耗费比较多的内存。

备份的时候,rsync扫描到的每个文件(目录也一样),在它的列表中约占100字节的内存,如果加了--delete参数的话,占用的内存会更多。

例如我这里一台服务器,约800万的图片,而且更新比较频繁,文件数增长比较快,差不多每天增加约10万张。备份的时候,rsync大约占用了将近2G的内存,大量内存的占用,造成服务器物理内存不足,进而使用到swap,然后产生更高的iowait(交换内存),进而造成rsync列表更慢,并且影响到服务器上的业务。

对于这样的情况,在rsync 3.X出现之前,人们普遍给出的建议是把备份操作给拆分成若干个小的备份操作。比如原来有10个图片目录一起备份,现在拆成10个备份操作,每次只备份其中一个。另外,还有人建议减小目录的深度,这样可以减小目录的数量,可以减少rsync占用的内存。另外还有个叫做digisync的软件,是专门用来备份G级数量的文件的。

 

rsync 3.X采用的是incremental file list,与原来的 2.X相比,现在是一边列表一边备份(添加或删除)。这对于大量文件的备份操作来说,无疑节省了很多时间。

实测发现,rsync 3.0.4备份时占用的内存大约时4M,跟一个apache进程占用的内存差不多。

 

然后运行 rsync --version 来看看版本号

 

需要注意的是,源主机和目的主机必须都升级到 rsync 3.X 才能使用到rsync 3.X的新特性。

 

值得一提的是,自从 2006116号发布 version 2.6.9以后,一直到083月才发布3.0,使得很长一段时间内,大家不得不找各种各样的办法来处理大量的文件备份操作

 

 

################

#

#     注意

#

################

 

server段,要与clent段的“auth users”用户要一致。  通过过去的文件属主,是按照server段的USER ID号来认的。

可修改clent段的/etc/passwd,/etc/groupID号,来处理一致性问题。

 

 

 

################

#

#    server

#

################

 

# 官网有下载

http://rsync.samba.org/ftp/rsync/rsync-3.0.8.tar.gz

 

# 基本编译安装,只加了安装路径

./configure --prefix=/usr/local/rsync308

make

make-install

 

# 加个符号链接到$PATH

ln -s /usr/local/rsync308/bin/rsync /usr/local/bin/rsync

 

# server端,用守护进程开启

rsync --daemon

 

# 默认端口为873

netstat -tunlp

tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      5099/rsync 

 

# 默认配置文件 /etc/reyncd.conf

 

vim /etc/rsyncd.conf

-------------------------------------

uid = root

gid = root

use chroot = no

max connections = 4

pid file = /var/run/rsyncd.pid

lock file = /var/run/rsync.lock

log file = /var/log/rsyncd.log

 

[222]

path = /data/rsync

auth users = rsync222

hosts allow = 192.168.14.222

hosts deny = 0.0.0.0/32

secrets file = /etc/rsyncd.secrets

read only = no

 

# 密码文件,以明文显示,格式为 user:passwd

vim /etc/rsyncd.secrets

-------------------------------------

rsync222:passwd222

 

# 密码文件,root只读

chown root.root /etc/rsyncd.secrets

chmod 600 /etc/rsyncd.secrets

 

# 检测log日志

tail -f /var/log/rscyncd.log

 

 

################

#

#    cliect

#

################

 

# 密码文件,只需写入passwd即可

 

vim /etc/rsyncd.secrets

-----------------------------

passwd222

 

# 权限为root只读

chmod 600 /etc/rsyncd.secrets

 

# 客户端发起的同步命令 把本地的/data/www/的目录与文件,同步到服务端的222模块中

/usr/local/bin/rsync -Cavz --delete --progress --password-file=/etc/rsyncd.secrets /data/www/ rsync222@192.168.14.221::222/

 

##################

# 不用指定密码参数

 

#!/bin/bash

 

        RSYNC_PASSWORD=passwd222

        export RSYNC_PASSWORD

        rsync -Cavz /data/www/ rsync222@192.168.14.221::222/

 

#####################

#

#  同步要注意的小地方

#

#####################

 

rsync -avl –size-only /mnt/ /data/test/ –progress (常用)

 

rsync -avl –size-only /mnt /data/test/ –progress

 

以上二个,关键有一个地方不同,就是在/mnt后有没有"/" ,这二个会产生完全不同的结果,/的话,会给目录下的文件同步过去。相当于mnt下的目录和test下的目录一样。如果没有/的话,就会给文件夹和文件一起同步过去,也就是在/test/下会是/test/mnt.

 

 

 

另外,对经过n多的测试,发现在LAN中对nfs速度影响最大的是 rsize,wsize二个参数。如果你是内网环境,可以考虑如下的参数来优化

 

mount -t nfs IP:/data/test/ /mnt -o rsize=32768,wsize=32768,timeo=15,intr

 

要对比文件,有个很简单的方法

 

ls -Rl /data/test/ > out.txt

 

##########################################  debianapt部署  ##############################################

 

# aptitude -y install rsync

 

如没有配置文件的话,启动时报错:

# /etc/init.d/rsync status

could not access PID file for rsync ... failed!

 

要修改/etc/default/rsync文件,允许 --daemon 启动:

RSYNC_ENABLE=false

改为

RSYNC_ENABLE=true

 

否则在启动时报错:

# /etc/init.d/rsync start

rsync daemon not enabled in /etc/default/rsync, not starting... ... (warning).

 

# 参数文件,密码文件有了,并修改的/etc/default/rsync之后,启动正常。

# /etc/init.d/rsync start

Starting rsync daemon: rsync.

# /etc/init.d/rsync status

rsync is running.

 

# netstat -tunlp

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name

tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      25403/rsync 

 

 

 

##########################################  参数  ##############################################

 

################

#

#  客户端 参数

#

################

 

-v, –verbose               详细模式输出

-q, –quiet                 精简输出模式

-c, –checksum              打开校验开关,强制对文件传输进行校验

-a, –archive                 归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD,这样会复制目录中所有的文件和目录

-r, –recursive             对子目录以递归模式处理

-R, –relative              使用相对路径信息

-b, –backup                创建备份,也就是对于目的已经存在有同样的文件名时,将老的文件重新命名为~filename。可以使用--suffix                                  选项来指定不同的备份文件前缀。

-backup-dir                 将备份文件(~filename)存放在在目录下。

-suffix=SUFFIX              定义备份文件前缀

-u, –update                仅仅进行更新,也就是跳过所有已经存在于DST,并且文件时间晚于要备份的文件。(不覆盖更新的文件)

-l, –links                 保留软链结

-L, –copy-links            想对待常规文件一样处理软链结

-copy-unsafe-links          仅仅拷贝指向SRC路径目录树以外的链结

-safe-links                 忽略指向SRC路径目录树以外的链结

-H, –hard-links            保留硬链结

-p, –perms                 保持文件权限

-o, –owner                 保持文件属主信息

-g, –group                 保持文件属组信息

-D, –devices               保持设备文件信息

-t, –times                 保持文件时间信息

-S, –sparse                对稀疏文件进行特殊处理以节省DST的空间

-n, –dry-run               现实哪些文件将被传输

-W, –whole-file            拷贝文件,不进行增量检测

-x, –one-file-system       不要跨越文件系统边界

-B, –block-size=SIZE       检验算法使用的块尺寸,默认是700字节

-e, –rsh=COMMAND           指定替代rshshell程序

--rsync-path=PATH           指定远程服务器上的rsync命令所在路径信息

-C, --cvs-exclude           使用和CVS一样的方法自动忽略文件,用来排除那些不希望传输的文件

--existing                  仅仅更新那些已经存在于DST的文件,而不备份那些新创建的文件

--delete                    删除那些DSTSRC没有的文件,这个不会删除任何源数据

--delete-excluded           同样删除接收端那些被该选项指定排除的文件

--delete-after              传输结束以后再删除

--ignore-errors             及时出现IO错误也进行删除

--max-delete=NUM            最多删除NUM个文件

--partial                   保留那些因故没有完全传输的文件,以是加快随后的再次传输

--force                     强制删除目录,即使不为空

--numeric-ids               不将数字的用户和组ID匹配为用户名和组名

--timeout=TIME              IP超时时间,单位为秒

-I, --ignore-times          不跳过那些有同样的时间和长度的文件

--size-only                 当决定是否要备份文件时,仅仅察看文件大小而不考虑文件时间

--modify-window=NUM         决定文件是否时间相同时使用的时间戳窗口,默认为0

-T --temp-dir=DIR           DIR中创建临时文件

--compare-dest=DIR          同样比较DIR中的文件来决定是否需要备份

-P                          等同于 –partial –progress 显示备份过程

-z, --compress              对备份的文件在传输时进行压缩处理

--exclude=PATTERN           指定排除不需要传输的文件模式

--include=PATTERN           指定不排除而需要传输的文件模式

--exclude-from=FILE         排除一个指定文件名中指定模式的文件

--include-from=FILE         不排除排除一个指定文件名中指定模式匹配的文件

--version                   打印版本信息

--address                   绑定到特定的地址

--config=FILE               指定其他的配置文件,不使用默认的rsyncd.conf文件

--port=PORT                 指定其他的rsync服务端口

--blocking-io               对远程shell使用阻塞IO

--stats                     给出某些文件的传输状态

--progress                  在传输时现实传输过程

--log-format=FORMAT         指定日志文件格式

--password-file=FILE        FILE中得到密码

--bwlimit=KBPS              限制I/O带宽,KBytes per second

-h, --help                  显示帮助信息

 

 

 

################

#

#  服务端 参数

#

################

 

##########

# 全局参数

##########

 

motd file

"motd file"参数用来指定一个消息文件,当客户连接服务器时该文件的内容显示给客户,默认是没有motd文件的。

 

log file

"log file"指定rsync的日志文件,而不将日志发送给syslog

 

pid file

指定rsyncpid文件。

 

syslog facility

指定rsync发送日志消息给syslog时的消息级别,常见的消息级别是:uth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, sys-log, user, uucp, local0, local1, local2, local3,local4, local5, local6local7。默认值是daemon

 

 

##########

# 模块参数

##########

 

comment

给模块指定一个描述,该描述连同模块名在客户连接得到模块列表时显示给客户。默认没有描述定义。

 

path

指定该模块的供备份的目录树路径,该参数是必须指定的。

 

use chroot

如果"use chroot"指定为true,那么rsync在传输文件以前首先chrootpath参数所指定的目录下。这样做的原因是实现额外的安全防护,但是缺点是需要以roots权限,并且不能备份指向外部的符号连接所指向的目录文件。默认情况下chroot值为true

 

max connections

指定该模块的最大并发连接数量以保护服务器,超过限制的连接请求将被告知随后再试。默认值是0,也就是没有限制。

 

lock file

指定支持max connections参数的锁文件,默认值是/var/run/rsyncd.lock

 

read only

该选项设定是否允许客户上载文件。如果为true那么任何上载请求都会失败,如果为false并且服务器目录读写权限允许那么上载是允许的。默认值为true

 

list

该选项设定当客户请求可以使用的模块列表时,该模块是否应该被列出。如果设置该选项为false,可以创建隐藏的模块。默认值是true

 

uid

该选项指定当该模块传输文件时守护进程应该具有的uid,配合gid选项使用可以确定哪些可以访问怎么样的文件权限,默认值是"nobody"

 

gid

该选项指定当该模块传输文件时守护进程应该具有的gid。默认值为"nobody"

 

exlude

用来指定多个由空格隔开的多个模式列表,并将其添加到exclude列表中。这等同于在客户端命令中使用--exclude来指定模式,不过配置文件中指定的exlude模式不会传递给客户端,而仅仅应用于服务器。一个模块只能指定一个exlude选项,但是可以在模式前面使用"-""+"来指定是 exclude还是include

但是需要注意的一点是该选项有一定的安全性问题,客户很有可能绕过exlude列表,如果希望确保特定的文件不能被访问,那就最好结合uid/gid选项一起使用。

 

exlude from

指定一个包含exclude模式的定义的文件名,服务器从该文件中读取exlude列表定义。

 

include

用来指定多个由空格隔开的多个rsync并应该exlude的模式列表。这等同于在客户端命令中使用--include来指定模式,结合 includeexlude可以定义复杂的exlude/include规则。一个模块只能指定一个include选项,但是可以在模式前面使用"-""+"来指定是 exclude还是include

 

include from

指定一个包含include模式的定义的文件名,服务器从该文件中读取include列表定义。

 

auth users

该选项指定由空格或逗号分隔的用户名列表,只有这些用户才允许连接该模块。这里的用户和系统用户没有任何关系。如果"auth users"被设置,那么客户端发出对该模块的连接请求以后会被rsync请求challenged进行验证身份这里使用的 challenge/response认证协议。用户的名和密码以明文方式存放在"secrets file"选项指定的文件中。默认情况下无需密码就可以连接模块(也就是匿名方式)

 

secrets file

该选项指定一个包含定义用户名:密码对的文件。只有在"auth users"被定义时,该文件才有作用。文件每行包含一个username:passwd对。一般来说密码最好不要超过8个字符。没有默认的 secures file名,需要限式指定一个。(例如:/etc/rsyncd.secrets)

 

strict modes

该选项指定是否监测密码文件的权限,如果该选项值为true那么密码文件只能被rsync服务器运行身份的用户访问,其他任何用户不可以访问该文件。默认值为true

 

hosts allow

该选项指定哪些IP的客户允许连接该模块。客户模式定义可以是以下形式:

xxx.xxx.xxx.xxx                        # 客户主机只有完全匹配该IP才允许访问。        例如:192.167.0.1

a.b.c.d/n                                                # 属于该网络的客户都允许连接该模块。                例如:192.168.0.0/24

a.b.c.d/e.f.g.h                        # 属于该网络的客户都允许连接该模块。                例如:192.168.0.0/255.255.255.0

一个主机名                                                # 客户主机只有拥有该主机名才允许访问,        例如:backup.linuxaid.com.cn

*.linuxaid.com.cn                # 所有属于该域的主机都允许。

                                                                                # 默认是允许所有主机连接。

 

hosts deny

指定不允许连接rsync服务器的机器,可以使用hosts allow的定义方式来进行定义。默认是没有hosts deny定义。

 

ignore errors

指定rsyncd在判断是否运行传输时的删除操作时忽略server上的IP错误,一般来说rsync在出现IO错误时将将跳过--delete操作,以防止因为暂时的资源不足或其它IO错误导致的严重问题。

 

ignore nonreadable

指定rysnc服务器完全忽略那些用户没有访问权限的文件。这对于在需要备份的目录中有些文件是不应该被备份者得到的情况是有意义的。

 

transfer logging

使rsync服务器使用ftp格式的文件来记录下载和上载操作在自己单独的日志中。

 

log format

通过该选项用户在使用transfer logging可以自己定制日志文件的字段。其格式是一个包含格式定义符的字符串,可以使用的格式定义符如下所示:

 

%h 远程主机名

%a 远程IP地址

%l 文件长度字符数

%p 该次rsync会话的进程id

%o 操作类型:"send""recv"

%f 文件名

%P 模块路径

%m 模块名

%t 当前时间

%u 认证的用户名(匿名时是null)

%b 实际传输的字节数

%c 当发送文件时,该字段记录该文件的校验码

 

默认log格式为:"%o %h [%a] %m (%u) %f %l",一般来说,在每行的头上会添加"%t [%p] "。在源代码中同时发布有一个叫rsyncstatsperl脚本程序来统计这种格式的日志文件。

 

timeout

通过该选项可以覆盖客户指定的IP超时时间。通过该选项可以确保rsync服务器不会永远等待一个崩溃的客户。超时单位为秒钟,0表示没有超时定义,这也是默认值。对于匿名rsync服务器来说,一个理想的数字是600

 

refuse options

通过该选项可以定义一些不允许客户对该模块使用的命令参数列表。这里必须使用命令全名,而不能是简称。但发生拒绝某个命令的情况时服务器将报告错误信息然后退出。如果要防止使用压缩,应该是:"dont compress = *"

 

dont compress

用来指定那些不进行压缩处理再传输的文件,默认值是:

*.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz

 

 

##################

#

#  rsync examples

#

##################

 

If you have an interesting example of how you use rsync then please submit it to the rsync-bugs@samba.org for inclusion on this page.

backup to a central backup server with 7 day incremental

 

 

#!/bin/sh

 

# This script does personal backups to a rsync backup server. You will end up

# with a 7 day rotating incremental backup. The incrementals will go

# into subdirectories named after the day of the week, and the current

# full backup goes into a directory called "current"

# tridge@linuxcare.com

 

# directory to backup

BDIR=/home/$USER

 

# excludes file - this contains a wildcard pattern per line of files to exclude

EXCLUDES=$HOME/cron/excludes

 

# the name of the backup machine

BSERVER=owl

 

# your password on the backup server

export RSYNC_PASSWORD=XXXXXX

 

########################################################################

 

BACKUPDIR=`date +%A`

OPTS="--force --ignore-errors --delete-excluded --exclude-from=$EXCLUDES 

      --delete --backup --backup-dir=/$BACKUPDIR -a"

 

export PATH=$PATH:/bin:/usr/bin:/usr/local/bin

 

# the following line clears the last weeks incremental directory

[ -d $HOME/emptydir ] || mkdir $HOME/emptydir

rsync --delete -a $HOME/emptydir/ $BSERVER::$USER/$BACKUPDIR/

rmdir $HOME/emptydir

 

# now the actual transfer

rsync $OPTS $BDIR $BSERVER::$USER/current

 

backup to a spare disk

 

I do local backups on several of my machines using rsync. I have an

extra disk installed that can hold all the contents of the main

disk. I then have a nightly cron job that backs up the main disk to

the backup. This is the script I use on one of those machines.

 

    #!/bin/sh

 

    export PATH=/usr/local/bin:/usr/bin:/bin

 

    LIST="rootfs usr data data2"

 

    for d in $LIST; do

        mount /backup/$d

        rsync -ax --exclude fstab --delete /$d/ /backup/$d/

        umount /backup/$d

    done

 

    DAY=`date "+%A"`

    

    rsync -a --delete /usr/local/apache /data2/backups/$DAY

    rsync -a --delete /data/solid /data2/backups/$DAY

 

The first part does the backup on the spare disk. The second part

backs up the critical parts to daily directories.  I also backup the

critical parts using a rsync over ssh to a remote machine.

 

mirroring vger CVS tree

 

The vger.rutgers.edu cvs tree is mirrored onto cvs.samba.org via

anonymous rsync using the following script.

 

    #!/bin/bash

 

    cd /var/www/cvs/vger/

    PATH=/usr/local/bin:/usr/freeware/bin:/usr/bin:/bin

 

    RUN=`lps x | grep rsync | grep -v grep | wc -l`

    if [ "$RUN" -gt 0 ]; then

            echo already running

            exit 1

    fi

 

    rsync -az vger.rutgers.edu::cvs/CVSROOT/ChangeLog $HOME/ChangeLog

 

    sum1=`sum $HOME/ChangeLog`

    sum2=`sum /var/www/cvs/vger/CVSROOT/ChangeLog`

 

    if [ "$sum1" = "$sum2" ]; then

            echo nothing to do

            exit 0

    fi

 

    rsync -az --delete --force vger.rutgers.edu::cvs/ /var/www/cvs/vger/

    exit 0

 

Note in particular the initial rsync of the ChangeLog to determine if

anything has changed. This could be omitted but it would mean that the

rsyncd on vger would have to build a complete listing of the cvs area

at each run. As most of the time nothing will have changed I wanted to

save the time on vger by only doing a full rsync if the ChangeLog has

changed. This helped quite a lot because vger is low on memory and

generally quite heavily loaded, so doing a listing on such a large

tree every hour would have been excessive.

 

automated backup at home

 

I use rsync to backup my wifes home directory across a modem link each

night. The cron job looks like this

 

    #!/bin/sh

    cd ~susan

    {

    echo

    date

    dest=~/backup/`date +%A`

    mkdir $dest.new

    find . -xdev -type f ( -mtime 0 -or -mtime 1 ) -exec cp -aPv "{}"

    $dest.new ;

    cnt=`find $dest.new -type f | wc -l`

    if [ $cnt -gt 0 ]; then

      rm -rf $dest

      mv $dest.new $dest

    fi

    rm -rf $dest.new

    rsync -Cavze ssh . samba:backup

    } >> ~/backup/backup.log 2>&1

 

 

note that most of this script isn't anything to do with rsync, it just

creates a daily backup of Susans work in a ~susan/backup/ directory so

she can retrieve any version from the last week. The last line does

the rsync of her directory across the modem link to the host

samba. Note that I am using the -C option which allows me to add

entries to .cvsignore for stuff that doesn't need to be backed up.

 

 

Fancy footwork with remote file lists

 

One little known feature of rsync is the fact that when run over a

remote shell (such as rsh or ssh) you can give any shell command as

the remote file list. The shell command is expanded by your remote

shell before rsync is called. For example, see if you can work out

what this does:

 

        rsync -avR remote:'`find /home -name "*.[ch]"`' /tmp/

 

note that that is backquotes enclosed by quotes (some browsers don't

show that correctly).

--软件开发网 www.rjkfw.

posted @ 2015-07-23 22:55  调皮的猫  阅读(1947)  评论(0编辑  收藏  举报