Inotify实现实时备份与调优

Inotify是一种强大的、细粒度的、异步的文件系统监控机制,linux内核2.6.13起,加入了Inotify支持,通过Inotify可以监控文件系统中添加、删除、修改、移动等各种事件,利用这个内核接口,Inotify就可以监控文件系统下的变化。

==============================================================

安装Inotify

1)查看内核是否支持
uname -r
yum install -y inotify-tools

2)检查安装
rpm -qa|grep inotify

3) Inotify-tools提供的两个工具

inotifywait:通过inotify API等待被监控文件上的相应事件并返回监控结果。

inotifywatch:用于收集关于被监视的文件系统的统计数据。

inotifywait:
-m :实时监控。
-d:后台运行。
-r:递归,对子目录监控。
-e:监控事件。以下
access:检测文件访问事件。
close_write:写入关闭事件。
modify:文件发生变化。
attrib:文件属性变化事件。
delete:文件被删除。
--timefmt :当在--format选项中使用%T时,--timefrt选项则可以用来指定自定义的符合strftime规范的时间格式,此时间格式可用的格式符可以通过strftime的手册页获取;--timefrt后常用的参数是'%d/%m/%y %H:%M';
--format :自定义inotifywait的输出格式,如--format '%T %w %f';常用的格式符如下:
%w:显示被监控文件的文件名;
%f:如果发生某事件的对象是目录,则显示被监控目录的名字;默认显示为空串;
%T:使用--timefmt选项中自定义的时间格式.
eg. inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e close_write /data #输出时间
eg. innotifywait -mrq --format '%w%f' -e create,close_write,delete /data #简化输出
-m :永远监控,实时监控。
-d:后台运行。
-q:仅打印监控事件的信息。
-r:递归,对子目录监控。
-e:监控事件。以下
access:检测文件访问事件。
close_write:写入关闭事件。
modify:文件发生变化。
attrib:文件属性变化事件。
delete:文件被删除。
--timefmt :当在--format选项中使用%T时,--timefrt选项则可以用来指定自定义的符合strftime规范的时间格式,此时间格式可用的格式符可以通过strftime的手册页获取;--timefrt后常用的参数是  '%d/%m/%y %H:%M';
--format :自定义inotifywait的输出格式,如--format '%T %w %f';常用的格式符如下:
%w:显示被监控文件的文件名.
%f:如果发生某事件的对象是目录,则显示被监控目录的名字;默认显示为空串;
%T:使用--timefmt选项中自定义的时间格式.
eg. inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e close_write /data #输出时间.
eg. innotifywait -mrq --format '%w%f' -e create,close_write,delete /data #简化输出.

关于inotify实现实时同步的脚本

inotifywait=/bin/inotifywait
dirbak=/data
$inotifywait -mrq --format '%w%f' -e modify,delete,create,attrib $dirbak\
|while read file   
do
          cd $dirbak
          /bin/rsync -az --delete ./ rsync://[email protected]/backup --password-file=/etc/rsync.password &
          echo "${file} is bak_file_`date +%F:%T`" >>/tmp/rsync.log 2>&1
done

&:让rsync在后台队列中运行,不需要等到执行完后再循环。

==========================================

关于inotify的调优

/proc/sys/fs/inotify/max_user_watches :设置inotifywait或inotifywatch命令可以监视的文件数量(单进程)。
/proc/sys/fs/inotify/max_queued_events :设置inotify实例时间(event)队列可容纳的时间数量。
/proc/sys/fs/inotify/max_user_instances :每个用户可以运行inotifywait或inotifywatch的进程数。 默认128不需要设了。

如果访问量大可以往上调,调整采用echo方式,写入rc.local即可。

==========================================

总结

优点:监控文件系统事件变化,通过inotify+rsync实现实时数据同步。

缺点:  如果大于200个文件(10-100k),同步会延迟。

============================

希望我的文档对你有所帮助,我会继续更新的

============================

猜你喜欢

转载自blog.csdn.net/csdn_changsha/article/details/79943766
今日推荐