inotify+rsync实现文件同步

文章来源:http://hi.baidu.com/bailiangcn/blog/item/046f90012aec76067aec2c06.html
平时我们把rsync放在crontab里进行文件同步,同步的延时有可能会比我们想象的长。如果你的内核大于2.6.13,可以使用inotify来对文件进行监控,实现触发式同步。
在安装inotify-tools前请先确认你的linux内核是否打到了2.6.13,并且在编译时开启了CONFIG_INOTIFY选项。你 可以按下面的方式简单的确认这一点:ls /proc/sys/fs/inotify,如果支持的话会有 max_queued_events,max_user_instances,max_user_watches三项。
这儿有一篇文章“ 使用rsync+inotify配置触发式(实时)远程同步”,可以了解如何实现这个功能。
2008-11-01 TsengYia#126.com
################################################################
系统环境:RHEL5 [ 2.6.18-8.el5xen ]
软件环境:
rsync-2.6.8-3.1
nfs-utils-1.0.9-16.el5
portmap-4.0-65.2.2.1
目标功能:
源主机H1: 192.168.1.11/24
目标主机H2: 192.168.1.12/24
将H1主机中的开发数据(/var/devel/目录),上传同步至H2主机的/backup/devel/h1/目录。——当源数据有文件或目录更新时,即时启动rsync同步进程。[基于安全性考虑,建议只在内部网络中使用]
################################################################
除inotify-tools(需要2.6.13以上内核的inotify功能支持)以外,其他软件均使用RHEL5系统自带的rpm包安装。
一、配置目标主机H2(发布NFS可写共享)
shell> mkdir -p /backup/devel/h1/
shell> vi /etc/exports
/backup/devel/h1    192.168.1.11(rw,no_root_squash)
shell> service portmap start
shell> service nfs start
shell> chkconfig portmap on
shell> chkconfig nfs on
如有必要,可以结合防火墙规则控制访问权限
shell> iptables -I INPUT -p tcp –dport 111 -j DROP
shell> iptables -I INPUT -p tcp –dport 111 -s 192.168.1.11 -j ACCEPT
shell> iptables -I INPUT -p udp –dport 111 -j DROP
shell> iptables -I INPUT -p udp –dport 111 -s 192.168.1.11 -j ACCEPT
二、配置源主机H1(上传备份发起端)
1、安装inotify-tools工具包
shell> tar zxvf inotify-tools-3.13.tar.gz -C /usr/src/
shell> cd /usr/src/inotify-tools-3.13
shell> ./configure
shell> make
shell> make install
—— 可以使用man inotify、man inotifywait、man inotifywatch查看相关手册页。
2、挂载H2发布的备份目录
shell> service portmap start
shell> chkconfig portmap on
shell> mkdir -p /media/h2nfsdir/
shell> vi /etc/fstab
192.168.0.12:/backup/devel/h1    /media/h2nfsdir    nfs    defaults,noexec    0 0
shell> mount /media/h2nfsdir
3、编写触发同步脚本
shell> vi /opt/h1-h2_inosync.sh
#!/bin/sh
SRC=/var/devel/
DST=/media/h2nfsdir/
INWT=/usr/local/bin/inotifywait
RSYNC=/usr/bin/rsync
$INWT -mrq -e create,move,delete,modify $SRC | while read D E F ; do
$RSYNC -aHqz –delete $SRC $DST
done
shell> chkmod +x /opt/h1-h2_inosync.sh
4、每次开机自动运行监控脚本
shell> echo “/opt/h1-h2_inosync.sh &” >> /etc/rc.local
shell> /opt/h1-h2_inosync.sh &
三、测试实时同步
在源主机H1上,修改/var/devel/目录中的内容(如增、删、改文件,添加、移除目录等),
——同时在目标主机H2上,观察备份目录/backup/devel/h1/中内容的变化。