利用inotify+rsync实现文件同步

2015年2月11日10:41:43 评论 7,331

一、需求:公司项目需要同步线上web日志到测试环境,以便开发可以随时查看。因为上线web服务有10几个,同步到测试环境上的文件夹也要有10几个,故此例子为多对多的同步。

rsync是一款非常强大的同步工具,采用差异同步方法,只上传文件或文件夹不同的部分。但是也有缺点,问题就是每次执行rsync命令都会遍历目标目录,当文件不多时,这没什么问题,一旦文件数到了一定规模,那么每次遍历都会消耗很多资源。这就导致了极速管家项目出现机器IO被占满,无法使用状况。于是后面就用到了inotify+rsync方法,inotify是一个强大的文件系统监控机制,通过Inotify可以监控文件系统中的添加、删除、修改、移动等各种事件。

二、环境:

源服务器:两台内网web机器通过128.113.24.188做转发

目的服务器:128.113.24.203

三、操作

1. 在目的服务器配置rsync配置文件/etc/rsyncd.conf。其中[xms-8.6],[zms-8.6]为认证的模块名,会和源服务器上的配置文件进行对应;

auth users:认证的用户名,此用户与系统无关,只有这里指定的用户才允许连接改模块

secrets file:/etc/webuser.pass存放用户名密码文件,只有当auth users被定义时,该文件才起作用,文件每行包含一个username:passwd。该文件权限一定要是600,否则无效。

uid = nobody
gid = nobody
use chroot = no
max connections = 20
strict modes = yes
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log

[xms-8.6]
path = /cache1/logs/xms-8.6/
comment = web file
ignore errors
read only = no
write only = no
hosts allow =128.113.24.188
hosts deny = *
list = false
uid = root
gid = root
auth users = webuser
secrets file = /etc/webuser.pass

[zms-8.6]
path = /cache1/logs/zms-8.6/
comment = web file
ignore errors
read only = no
write only = no
hosts allow = 128.113.24.188
hosts deny = *
list = false
uid = root
gid = root
auth users = webuser
secrets file = /etc/webuser.pass

2. 源服务器配置先安装inotify-tools

下载路径:wget http://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz

编写rsync监控脚本

xmssrc:为本地需要同步的路径,多个路径就定义多个

xms:为目的服务器起上定义的认证模块名

-e后面跟着的为监控的事件

nohup sh /usr/local/bin/inotifyrsync.sh &  命令为让shell文件在后台自动运行

host=128.113.24.203
xmssrc=/cache1/tomcat-xxt-xms/logs/
zmssrc=/cache1/tomcat-xxt-zms/logs/

xms='xms-8.6'
zms='zms-8.6'

user=webuser
/usr/local/inotify/bin/inotifywait -mrq --timefmt '%y/%m/%d %H:%M' --format '%T %w%f%e' -e close_write,delete,create,attrib,move $xmssrc $zmssrc  \
| while read files
        do
        /usr/bin/rsync -vzrtopg --delete --progress --password-file=/etc/webuser.pass $xmssrc $user@$host::$xms &&
        /usr/bin/rsync -vzrtopg --delete --progress --password-file=/etc/webuser.pass $zmssrc $user@$host::$zms 

        echo "${files} was rsynced." >> /var/log/rsync.log 2>&1
        done
weinxin
聂扬帆博客
一个分享IT运维相关工作经验和实战技巧的个人博客

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: