上一篇文章记录了怎么安装rsync以及怎么使用该服务备份数据,但是在集群中需要实时备份客户发过来的相关数据,这样在使用命令或者定时任务的方式执行备份,
就满足不了整个服务的需求了。
inotify是一种强大的、细粒度的、异步的文件系统事件监控机制,Linux内核从2.6.13开始引入,允许监控程序打开一个独立文件描述符,并针对事件集监控一个或者多个文件,
例如打开、关闭、移动/重命名、删除、创建或者改变属性。
安装过程说明:
1、下载软件
wget http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
说明:这个软件的下载地址目前还是可以使用的,但是通过浏览器的页面访问不了,所以建议备份一下该软件,另外github上有软件的源码(还没有测试)
2、编译安装
yum -y install gcc gcc-c++ 安装编译器 tar -xf inotify-tools-3.14.tar.gz -C /usr/local/src/ 解压软件 cd /usr/local/src/inotify-tools-3.14/ ./configure --prefix=/usr/local/inotify make && make install 配置编译安装
3、编写监控的脚本
由于inotify-tools安装之后只是一个简单的命令,所以需要借助脚本来实现文件的实时备份。
#!/bin/bash datapath=/data bip=192.168.8.5 /usr/bin/inotifywait -mrq --format '%w%f' -e create,close_write,delete $datapath \ 监控目录的状态 |while read file do if [ -f $file ];then rsync -az $file --delete rsync_back@$bip::backup --password-file=/etc/rsync.password 检测目录中文件的变化,有变化的同步提高性能,--delete实现无差异同步 else cd $datapath &&\ rsync -az ./ --delete rsync_back@$bip::backup --password-file=/etc/rsync.password 删除的时候进行全目录同步 fi done
可以使用如下命令调试脚本
bash -x ino-data.sh
可以使用如下命令查看目录的动态
watch ls 查看目录的动态,可以查看数据的实时同步的状态
4、编写inotify的启动脚本(参考)
#!/bin/bash #chkconfig: 2345 38 46 ################################ #this script is created by oldboy #zhou qq: #site: ################################ . /etc/init.d/function if [ $# -ne 1 ];then usage:$0 {start | stop} exit 1 fi case "$1" in start) /bin/bash /server/script/inotify.sh & if [ `ps -ef| grep inotify|wc -l` -gt 2 ];then action "inotify service is started" /bin/true else action "inotify service is started" /bin/false fi ;; stop) kill -9 `cat /usr/run/inotify.pid` > /dev/null 2>&1 pkill inotifywait sleep 1 if [ `ps -ef| grep inotify|grep -v grep` -eq 0 ];then action "inotify service is started" /bin/true else action "inotify service is started" /bin/false fi ;; *) usage: $0 {start|stop} exit 1 esac
5、inotify的优缺点:
inotify的优点
监控文件系统事件变化,通过同步工具实现实时数据同步
inotify的缺点
1、并发如果大于200个文件(10-100K),同步就会有延迟
2、我们写的脚本,每次都是全部推送一次,但确实是增量的
也可以只同步变化的文件,不变化的不理
3、监控到事件后,调用rsync同步时单线程的(加&并发)
注意事项:
--bwlimit=200
用于限制传输速率最大200kb,因为在实际应用中发现如果不做速率限制,会导致巨大的CPU消耗