ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

inotify事件监控工具

2022-09-16 18:33:01  阅读:285  来源: 互联网

标签:rsync inotify -- backup 监控 file 工具 root


第1章 NFS存储服务器与backup备份服务器的搭建。

这里快速的搭建两台服务器,详细的部署与介绍请关注:

Rsync数据同步工具

企业级NFS网络文件共享服务

 

[root@backup ~]# rpm -qa rsync
[root@backup ~]# yum -y install rsync
[root@backup ~]# rpm -qa rsync
rsync-3.1.2-11.el7_9.x86_64
[root@backup ~]# cat /etc/rsyncd.conf 
# /etc/rsyncd: configuration file for rsync daemon mode

# See rsyncd.conf man page for more options.

# configuration example:

uid = rsync
gid = rsync
use chroot = no
max connections = 200
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log
# exclude = lost+found/
# transfer logging = yes
timeout = 300
# ignore nonreadable = yes
# dont compress   = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
[backup]
path = /backup/
ignore errors
read only = false
list = false
hosts allow = 172.16.1.0/24
hosts deny = 0.0.0.0/32
auth users = rsync_backup
secrets file = /etc/rsync.password
# [ftp]
#        path = /home/ftp
#        comment = ftp export area
[root@backup ~]# useradd -M -s /sbin/nologin rsync
[root@backup ~]# mkdir /backup
[root@backup ~]# chown -R rsync /backup
[root@backup ~]# systemctl enable --now rsyncd
Created symlink from /etc/systemd/system/multi-user.target.wants/rsyncd.service to /usr/lib/systemd/system/rsyncd.service.
[root@backup ~]# netstat -antup | grep rsync
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      1735/rsync          
tcp6       0      0 :::873                  :::*                    LISTEN      1735/rsync 
[root@backup ~]# echo "rsync_backup:123456" > /etc/rsync.password
[root@backup ~]# cat /etc/rsync.password
rsync_backup:123456
[root@backup ~]# chmod 600 /etc/rsync.password
[root@backup ~]# ll /etc/rsync.password
-rw------- 1 root root 20 Sep 17 00:10 /etc/rsync.password

 配置Rsync服务器端检查脚本

#!/bin/bash
# 全网服务器备份解决方案_rsync服务器端检查脚本


. /etc/init.d/functions
Path=/backup
fileName="md5sum.txt"
# 一共有几台客户端在推送数据
rsync_ClientNum=2

/etc/init.d/postfix status &>/dev/null || /etc/init.d/postfix start


if [ `find $Path/ -type f -name "md5sum*" | wc -l` -eq $rsync_ClientNum ];then
    for filepath in `find $Path/ -type f -name "md5sum*"`
    do
        /usr/bin/md5sum -c $filepath
        if [ $? -eq 0 ];then
            action "${filepath}备份正常!" /bin/true
            rm -rf $filepath
        else
            action "${filepath}备份异常!" /bin/false
            echo "${filepath}备份异常!" | mail -s "$(date +%F)备份检查告警" xxxxxxxx@qq.com
        fi
    done
else
    echo “Rsync客户端推送不完整!”
    echo "Rsync推送不完整" | mail -s "$(date +%F)备份推送告警" xxxxxxxxx@qq.com
fi

# 找出超过180天的不是周1的备份文件并删除
find $Path/ ! -name "*_2.tar.gz" -mtime +180 -type f | xargs rm -rf

将脚本挂定时任务

00 6 * * * /bin/sh /server/scripts/rsync_Server.sh >/dev/null 2>&1

backup服务器Rsync服务端至此配置完毕

开始部署nfs01服务器:Rsync客户端过程:

只需要创建密码文件(只包含密码即可),并赋予密码文件600权限

[root@nfs01 ~]# yum -y install rsync
[root@nfs01 ~]# echo "123456" > /etc/rsync.password
[root@nfs01 ~]# chmod 600 /etc/rsync.password
[root@nfs01 ~]# mkdir /backup
[root@nfs01 ~]# cd /backup
[root@nfs01 backup]# touch {1..5}
[root@nfs01 backup]# ls
1  2  3  4  5
[root@nfs01 backup]# rsync -avzP /backup/ rsync_backup@172.16.1.41::backup --password-file=/etc/rsync.password
sending incremental file list
./
1
              0 100%    0.00kB/s    0:00:00 (xfr#1, to-chk=4/6)
2
              0 100%    0.00kB/s    0:00:00 (xfr#2, to-chk=3/6)
3
              0 100%    0.00kB/s    0:00:00 (xfr#3, to-chk=2/6)
4
              0 100%    0.00kB/s    0:00:00 (xfr#4, to-chk=1/6)
5
              0 100%    0.00kB/s    0:00:00 (xfr#5, to-chk=0/6)

sent 289 bytes  received 122 bytes  274.00 bytes/sec
total size is 0  speedup is 0.00

nfs01服务器打包脚本实现

#!/bin/bash
# 全网服务器备份解决方案_rsync客户端打包脚本


Path=/backup
backup_Server=172.16.1.41
local_IP=`/sbin/ifconfig eth1|awk -F"[ :]+" 'NR==2{print $4}'`
Dir=${local_IP}_$(date +%F_%w)


mkdir -p $Path/$Dir
[ -f /var/spool/cron/root ] && cp -rp /var/spool/cron/root $Path/$Dir/
[ -f /etc/rc.d/rc.local ] && cp -rp /etc/rc.d/rc.local $Path/$Dir/
[ -d /server/scripts ] && cp -rp /server/scripts $Path/$Dir/
[ -d /var/html/www ] && cp -rp /var/html/www $Path/$Dir/
[ -d /app/logs ] && cp -rp /app/logs $Path/$Dir/
[ -f /etc/sysconfig/iptables ] && cp -rp /etc/sysconfig/iptables $Path/$Dir/
cd $Path

tar -zcf $Path/${Dir}.tar.gz $Dir

rm -rf $Path/$Dir
# 创建md5sum验证信息
/usr/bin/md5sum $Path/${Dir}.tar.gz > $Path/md5sum_$(local_IP).txt

# 推送打包的文件到备份服务器
rsync -az $Path/ rsync_backup@${backupServer}::backup --password-file=/etc/rsync.password
# 找出超过7天的备份并删除
find $Path/ -name "${local_IP}*" -type f -mtime +7 | xargs rm -rf

将脚本挂定时任务

00 0 * * * /bin/sh /server/scripts/backup.sh >/dev/null 2>&1

NFS服务器Rsync客户端至此配置完毕

第2章 rsync + inotify 组合的起源

Rsync(remote sync)远程同步工具,通过rsync可以实现对远程服务器数据的增量备份同步,但rsync自身也有瓶颈,同步数据时,rsync采用核心算法对远程服务器的目标文件进行比对,只进行差异同步。我们可以想象一下,如果服务器的文件数量达到了百万甚至千万量级,那么文件对比将是非常耗时的。而且发生变化的往往是其中很少的一部分,这是非常低效的方式。inotify的出现,可以缓解rsync不足之处,取长补短。

第3章 inotify简介

  • Inotify是一种强大的,细粒度的,异步的文件系统事件监控机制(软件),linux内核从2.6.13起,加入了Inotify支持,通过Inotify可以监控文件系统中添加,删除,修改,移动等各种事件,利用这个内核接口,第三方软件就可以监控文件系统下文件的各种变化情况,而inotify-tools正是实施这样监控的软件。还有国人周洋在金山公司开发的sersync。
  • Inotify实际是一种事件驱动机制,它为应用程序监控文件系统事件提供了实时响应事件的机制,而无须通过诸如cron等的轮询机制来获取事件。cron等机制不仅无法做到实时性,而且消耗大量系统资源。相比之下,inotify基于事件驱动,可以做到对事件处理的实时响应,也没有轮询造成的系统资源消耗,是非常自然的事件通知接口,也与自然世界的事件机制相符合。
  • inotify 的实现有几款软件
    1)inotify-tools,
    2)sersync(金山周洋)
    3)lsyncd

特别说明:

下面的inotify配置是建立在rsync服务基础上的配置过程。

第4章 inotify 实施准备

大前提rsync daemon 服务配置成功,可以再rsync客户端推送拉取数据,然后才能配置inotify服务。

第5章 开始安装

默认yum源:
base + extras + updates

扩展的yum源:
epel
1.网易163源
2.阿里云epel源

在安装inotify-tools前请先确认你的linux内核是否达到了2.6.13,并且在编译时开启CONFIG_INOTIFY选项,也可以通过以下命令检测。

5.1 查看当前系统是否支持inotify

[root@backup ~]# uname -r
3.10.0-1160.el7.x86_64
[root@backup ~]# ls -l /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 Sep 17 00:42 max_queued_events
-rw-r--r-- 1 root root 0 Sep 17 00:42 max_user_instances
-rw-r--r-- 1 root root 0 Sep 17 00:42 max_user_watches

#显示这三个文件证明支持

关键参数说明:

在/proc/sys/fs/inotify目录下有三个文件,对inotify机制有一定的限制
max_user_watches:设置inotifywait或inotifywatch命令可以监视的文件数量(单进程)
max_user_instances:设置每个用户可以运行的inotifywait或inotifywatch命令的进程数。
max_queued_events:设置inotify实例事件(event)队列可容纳的事件数量。

5.2 Yum安装inotify-tools:

[root@backup ~]# wget -O /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo
[root@backup ~]# yum clean all
[root@backup ~]# yum makecache
[root@backup ~]# yum -y install inotify-tools
[root@backup ~]# rpm -qa inotify-tools
inotify-tools-3.14-9.el7.x86_64

一共安装了2个工具,即inotifywait和inotifywatch
inotifywait:在被监控的文件或目录上等待特定文件系统事件(open,close,delete等)发生,执行后处于阻塞状态,适合shell脚本中使用。
inotifywatch:收集被监视的文件系统使用度统计数据,指文件系统事件发生的次数统计。

5.3 inotifywait命令常用参数详解

inotifywait --help

[root@backup ~]# inotifywait --help
inotifywait 3.14
Wait for a particular event on a file or set of files.
Usage: inotifywait [ options ] file1 [ file2 ] [ file3 ] [ ... ]
Options:
    -h|--help         Show this help text.
    @<file>           Exclude the specified file from being watched.
    --exclude <pattern>
                      Exclude all events on files matching the
                      extended regular expression <pattern>.
    --excludei <pattern>
                      Like --exclude but case insensitive.
    -m|--monitor      Keep listening for events forever.  Without
                      this option, inotifywait will exit after one
                      event is received.
    -d|--daemon       Same as --monitor, except run in the background
                      logging events to a file specified by --outfile.
                      Implies --syslog.
    -r|--recursive    Watch directories recursively.
    --fromfile <file>
                      Read files to watch from <file> or `-' for stdin.
    -o|--outfile <file>
                      Print events to <file> rather than stdout.
    -s|--syslog       Send errors to syslog rather than stderr.
    -q|--quiet        Print less (only print events).
    -qq               Print nothing (not even events).
    --format <fmt>    Print using a specified printf-like format
                      string; read the man page for more details.
    --timefmt <fmt>    strftime-compatible format string for use with
                      %T in --format string.
    -c|--csv          Print events in CSV format.
    -t|--timeout <seconds>
                      When listening for a single event, time out after
                      waiting for an event for <seconds> seconds.
                      If <seconds> is 0, inotifywait will never time out.
    -e|--event <event1> [ -e|--event <event2> ... ]
        Listen for specific event(s).  If omitted, all events are 
        listened for.

Exit status:
    0  -  An event you asked to watch for was received.
    1  -  An event you did not ask to watch for was received
          (usually delete_self or unmount), or some error occurred.
    2  -  The --timeout option was given and no events occurred
          in the specified interval of time.

Events:
    access        file or directory contents were read
    modify        file or directory contents were written
    attrib        file or directory attributes changed
    close_write    file or directory closed, after being opened in
                   writeable mode
    close_nowrite    file or directory closed, after being opened in
                   read-only mode
    close        file or directory closed, regardless of read/write mode
    open        file or directory opened
    moved_to    file or directory moved to watched directory
    moved_from    file or directory moved from watched directory
    move        file or directory moved to or from watched directory
    create        file or directory created within watched directory
    delete        file or directory deleted within watched directory
    delete_self    file or directory was deleted
    unmount        file system containing file or directory unmounted

下面用列表详细解释一下各个参数的含义:

inotifywait参数含义说明
-r --recursive 递归查询目录
-q --quiet 打印很少的信息,仅仅打印监控事件的信息
-m,--monitor 始终保持事件监听状态
--exclude 排除文件或目录时,不区分大小写。
--timefmt 指定时间输出的格式
--format 打印使用指定的输出类似格式字符串
-e,--event 通过此参数可以指定需要监控的事件,如下一个列表所示

 

 

 

 

 

 

 

 

-e :--event的各种事件含义:

Events含义
access 文件或目录被读取
modify 文件或目录内容被修改
attrib 文件或目录属性被改变
close 文件或目录封闭,无论读/写模式
open 文件或目录被打开
moved_to 文件或目录被移动至另外一个目录
move 文件或目录被移动到另一个目录或从另一个目录移动至当前目录
create 文件或目录被创建在当前目录
delete 文件或目录被删除
umount 文件系统被卸载

 

 

 

 

 

 

 

 

 

 

 

5.4 人工测试监控事件

开启两个窗口

5.4.1 测试create

在第一个窗口输入如下内容:
[root@backup ~]# ls /backup/
1  2  3  4  5
[root@backup ~]# inotifywait -mrq --timefmt '%y %m %d %H %M' --format '%T %w%f' -e create /backup

在第二个窗口:输入如下内容:
[root@backup ~]# cd /backup/
[root@backup backup]# touch test

此时回到第一个窗口出现如下内容:
22 09 17 01 13 /backup/test


#命令说明
inotifywait:ionotify的命令工具
-mrq:-q只输入简短信息 -r,递归监控整个目录包括子目录 -m进行不间断持续监听
--timefmt 指定输出的时间格式 
--format:指定输出信息的格式
-e create:制定监控的时间类型,监控创建create事件。

5.4.2 测试delte

第一个窗口输入如下信息:
[root@backup ~]# inotifywait -mrq --timefmt '%y %m %d %H %M' --format '%T %w%f' -e delete /backup

第二个窗口输入如下信息:
[root@backup backup]# rm -rf test

此时第一个窗口会出现如下信息:
22 09 17 01 18 /backup/test


#命令说明:
-e delete:指定监听的事件类型。监听删除delete事件

5.4.3 测试close_write

第一个窗口输入如下信息:
[root@backup ~]# inotifywait -mrq --timefmt '%y %m %d %H %M' --format '%T %w%f' -e close_write /backup

第二个窗口输入如下信息:
[root@backup backup]# touch close_write.log
[root@backup backup]# echo 1111 >> close_write.log 
[root@backup backup]# rm -f close_write.log

此时第一个窗口会出现如下信息:
22 09 17 01 20 /backup/close_write.log
22 09 17 01 20 /backup/close_write.log

#命令说明:
-e close_write:指定监听类型。监听文件写模式的关闭。

5.4.4 测试move_to

第一个窗口输入如下信息:
[root@backup ~]# inotifywait -mrq --timefmt '%y %m %d %H %M' --format '%T %w%f' -e moved_to /backup


第二个窗口输入如下信息:
[root@backup backup]# touch test
[root@backup backup]# mv test test1
[root@backup backup]# mkdir aaaa
[root@backup backup]# mv aaaa/ bbbb


此时第一个窗口会出现如下信息:
22 09 17 01 24 /backup/test1
22 09 17 01 24 /backup/bbbb

5.5 编写inotify实时监控脚本

#!/bin/bash

backup_Server=172.16.1.41


/usr/bin/inotifywait -mrq --format '%w%f' -e create,close_write,delete /backup | while read line
do
    cd /backup
    rsync -az ./ --delete rsync_backup@$backup_Server::nfsbackup --password-file=/etc/rsync.password
done

提示:

  • 上边那个脚本效率很低,效率低的原因在于只要目录出现变化就都会导致我整个目录下所有东西都被推送一遍。因此,我们可以做如下改动提高效率
#!/bin/bash

Path=/backup
backup_Server=172.16.1.41


/usr/bin/inotifywait -mrq --format '%w%f' -e create,close_write,delete /backup  | while read line  
do
    if [ -f $line ];then
        rsync -az $line --delete rsync_backup@$backup_Server::nfsbackup --password-file=/etc/rsync.password       
    else
        cd $Path &&\
        rsync -az ./ --delete rsync_backup@$backup_Server::nfsbackup --password-file=/etc/rsync.password
    fi

done

脚本可以加入开机启动:

echo "/bin/sh /server/scripts/inotify.sh &" >> /etc/rc.local

提示:
一个& 代表从后台开始运行该条命令。

5.6 关键参数调整

在/proc/sys/fs/inotify目录下有三个文件,对inotify机制有一定的限制
max_user_watches:设置inotifywait或inotifywatch命令可以监视的文件数量(单进程)
max_user_instances:设置每个用户可以运行的inotifywait或inotifywatch命令的进程数
max_queued_events:设置inotify实例事件(event)队列可容纳的事件数量。

实战调整:

[root@nfs01 backup]# cat /proc/sys/fs/inotify/max_user_watches 
8192
[root@nfs01 backup]# echo "50000000" > /proc/sys/fs/inotify/max_user_watches
[root@nfs01 backup]# cat /proc/sys/fs/inotify/max_user_watches 
50000000
[root@nfs01 backup]# cat /proc/sys/fs/inotify/max_queued_events
16384
[root@nfs01 backup]# echo "326790" > /proc/sys/fs/inotify/max_queued_events
[root@nfs01 backup]# cat /proc/sys/fs/inotify/max_queued_events
326790
[root@nfs01 backup]# sysctl -p

5.7 Rsync+inotify实时数据同步并发简单测试

10K-100K

每秒100个并发

[root@nfs01 backup]# paste inotify_100_server.log inotify_100_backup_server.log > inotify_100.txt
[root@nfs01 backup]# cat inotify_100.txt
23:05       34227   23:05   34227
23:05       34387   23:05   34387
23:05       35027   23:05   35027
23:05       35587   23:05   35587
23:05       36473   23:05   36473
23:05       36707   23:05   36707
23:05       37587   23:05   37587 
以下省略...

Inotify实时并发:

结论:经过测试,每秒200文件并发,数据同步几乎无延迟(小于1秒)

5.8 inotify 优点:

1)监控文件系统事件变化,通过同步工具实现实时数据同步。

5.9 inotify 缺点

1)并发如果大于200个文件(10-100k),同步就会有延迟
2)我们前面写的脚本,每次都是全部推送一次,但确实是增量的。也可以只同步变化的文件,不变化的不理。
3)监控到事件后,调用rsync同步是单进程的,而sersync为多进程同步。既然有了inotify-tools,为什么还要开发sersync?

5.10 serysync功能多:(inotify+rsync命令)

1)支持通过配置文件管理
2)真正的守护进程socket
3)可以对失败文件定时重传(定时任务功能)
4)第三方的HTTP接口(例如:更新cdn缓存)
5)默认多进程rsync同步

5.11 高并发数据实时同步方案小结:

1)inotify(sersync)+ rsync,是文件级别的。
2)drbd文件系统级别,文件系统级别,基于block块同步,缺点:备节点数据不可用
3)第三方软件的同步功能:mysql同步(主从复制),oracle,mongodb
4)程序双写,直接写两台服务器。
5)利用产品业务逻辑解决(读写分离,备份读不到,读主)

说明:
用户上传的图片或者附件单独存在NFS主服务器上;
用户读取数据从两台NFS备份服务器上读取;
NFS主和两台NFS备份通过inotify+rsync方式进行实时同步。

6)NFS集群(1,4,5方案整合)(双写主存储,备存储用inotify(sersync)+rsync

 

标签:rsync,inotify,--,backup,监控,file,工具,root
来源: https://www.cnblogs.com/xiaowenyiyi/p/16700089.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有