(转)04sersync/lsync实时同步

04sersync/lsync实时同步

第1章 Inotify简介

Inotify是一种强大的,细粒度的,异步的文件系统事件监视机制,Linux2.6.13起加入了inotify支持,通过inotify可以监控文件系统中添加,删除,修改,移动等各种事件,利用这个内核接口,第三方软件就可以监控文件系统下文件的各种变化情况,而inotify-tools正是实施这样监控的软件,另外一个这样效果的软件是中国人周洋在金山公司开发的sersync,还有一个配置更简单的软件叫lsyncd

第2章 Inotify安装

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

[root@nfs01 ~]# uname -r
3.10.0-327.el7.x86_64
[root@nfs01 ~]#  ls -l /proc/sys/fs/inotify/
总用量 0
-rw-r--r-- 1 root root 0 7月  18 18:06 max_queued_events
-rw-r--r-- 1 root root 0 7月  18 18:06 max_user_instances
-rw-r--r-- 1 root root 0 7月  18 18:06 max_user_watches
[root@nfs01 ~]# rpm -qa inotify-tools

2.2 安装inotify-tools

[root@nfs01 ~]# yum install inotify-tools -y

2.3 关键参数说明:

1)在/proc/sys/fs/inotify目录下有三个文件,对inotify机制有一定限制

[root@nfs01 ~]# ls -l /proc/sys/fs/inotify/
总用量 0
-rw-r--r-- 1 root root 0 7月  18 18:06 max_queued_events
-rw-r--r-- 1 root root 0 7月  18 18:06 max_user_instances
-rw-r--r-- 1 root root 0 7月  18 18:06 max_user_watches
########################################################
max_queued_events   =====>设置inotify设置inotify实例事件(event)队列可容纳的事件数量
max_user_instances  =====>设置每个用户可以运行的inotify或者inotifywatch命令的进程数
max_user_watches    =====>设置inotifywait或者inotifywatch命令可以监视的文件数量(单进程)

2.6 inotifywait详细参数

[root@nfs01 ~]# 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 ###文件系统被卸载

2.7 参数说明

inotifywait参数说明
参数名称            参数说明
-m ,-monitor       始终保持事件监听状态
-r,-recursive      递归查询目录
-q,-quiet          只打印监控事件的信息
-exclude           排除文件或目录时,不区分大小写
-t,-timeout        超时时间
-timefmt           指定时间输出格式
-format            指定时间输出格式
-e,event           后面指定增,删,改等事件
inotifywait events 事件说明
access             读取文件或目录内容
modify             修改文件或目录内容
attrib             文件或目录的属性改变
close_write        修改真实文件内容
close_nowrite   
close   
open               文件或目录被打开
moved_to           文件或目录移动到
moved_from         文件或目录从...移动到
move               移动文件或目录移动到监视目录
create             在监视目录下创建文件或目录
delete             删除监视目录下的文件或目录
delete_self 
umount             卸载文件系统

2.8 查看inotify默认参数

[root@nfs01 ~]# sysctl -a |egrep max_queued_events
fs.inotify.max_queued_events = 16384
[root@nfs01 ~]#  sysctl -a |egrep max_user_watches
fs.epoll.max_user_watches = 201256
fs.inotify.max_user_watches = 8192
[root@nfs01 ~]# sysctl -a |egrep max_user_instances
fs.inotify.max_user_instances = 128

2.9 针对上述命令进行测试

1)测试create和delete开启两个窗口:

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e delete,create /backup

2)测试close_write

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e close_write /backup

3)打印出事件类型

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f %e' -e close_write /backup

2.10 把客户端监控到情况出发rsync推送变化的文件

方法一:新建脚本

[root@nfs01 ~]# cat inotify_push.sh 
#!/bin/bash

Path=/data
backup_Server=172.16.1.41
export RSYNC_PASSWORD=oldboy

/usr/bin/inotifywait -mrq --format '%w%f' -e create,close_write,delete /data | while read line
do
echo "${line}"
if [ -f $line ];then
    rsync -azvP $line --delete rsync_backup@$backup_Server::data
    else
    cd $Path &&\
    rsync -azvP ./ --delete rsync_backup@$backup_Server::data
fi
done

2.11 inotify优缺点

inotify优点
1)监控文件系统事件变化,通过同步工具实现实时数据同步
inotify缺点
1)并发如果大于200个文(10-100k),同步就会由延迟
2)我们前面的脚本,每次都是全部推送一次,但是确实是增量的,也可以只同步变化的文件
3)监控到事件后,调用rsync同步是单进程(加&并发)sersync多进程同步
既然有了inotify-tools,为什么还需要sersync呢?

2.12 sersync功能多:(inotify+rsync命令)

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

第3章 高并发数据实时同步方案小结:

1.inotify(sersync)+rsync,是文件级别的
2.drbd文件系统级别,文件系统级别,基于block块同步,缺点:备节点数据不可用
3.第三方软件的同步功能:mysql同步(主从复制),orcal,mongodb
4.程序双写,直接写两台服务器
5.利用产品业务逻辑解决,读写分离
6.NFS集群(1,4,5方案整合)(双写主存储,备存储用inotify(sersync)+rsync,备没有找主来解决延迟问题)

第4章 sersync使用说明

以下内容摘抄sersync作者官网的说明

4.1 sersync介绍

sersync主要用于服务器同步,web镜像等功能.基于boost1.41.0,inotify api,rsync command开发.目前使用的比较多的同步解决方案是inotify-tools+rsync,另外一个是google开源项目Openduckbill(依赖于inotify-tolls),这两个都是基于脚本语言编写的.

4.2 sersync优点

1.sersync是使用c++编写,而且对linux系统文件系统产生的临时文件和重复的文件操作进行过滤(详细见附录,这个过滤脚本程序没有实现),所以结合rsync同步的时候,节省了运行时耗和网络资源,因此更快
2.相比较上面两个项目,sersync配置起来很简单,其中bin目录下已经有基本上静态编译的2进制文件,配合bin目录下的xml配置文件直接使用即可.
3.另外本项目相比较其他脚本开源项目,使用多线程进行同步,尤其在同步较大文件时,能够保证多个服务器保持同步状态
4.本项目有出错处理机制,通过失败队列对出错的文件重新同步,如果仍旧失败,则每10个小时对同步失败的文件重新同步
5.本项目自带crontab功能,只需在xml配置文件中开启,即可按照您的要求,隔一段时间整体同步一次,无须在额外配置crontab功能
6.本项目socket与http插件拓展,满足您二次开发的需要.

4.3 sersync配置过程

主机规划:

nfs-server 172.16.1.31 rsync+inotify+sersync  nfs-client
backup     172.16.1.41 rsync-server           nfs-server

4.3.1 使用sersync前提条件

1.部署好rsync服务
2.修改sersync配置文件
3.启动sersync即可。

4.3.2 安装sersync服务

下载压缩包,但是googlecode经常访问不了,所以这个方法不一定可以

[root@nfs01 ~]# cd /opt/
[root@nfs01 /opt]# wget 'http://sersync.googlecode.com/files/sersync2.5.4_64bit_binary_stable_final.tar.gz'
[root@nfs01 /opt]# tar zxvf sersync2.5.4_64bit_binary_stable_final.tar.gz 
[root@nfs01 /opt]# tree
.
├── GNU-Linux-x86
│   ├── confxml.xml  ###配置文件
│   └── sersync2      ###执行程序
└── sersync2.5.4_64bit_binary_stable_final.tar.gz
[root@nfs01 /opt]# mv GNU-Linux-x86 sersync
[root@nfs01 /opt]# cd sersync/
[root@nfs01 /opt/sersync]# cp confxml.xml confxml.xml.bak

4.3.3 配置解释

image

4.4.4 配置文件修改

=====================================================
    23      <sersync>
    24          <localpath watch="/data">
    25              <remote ip="172.16.1.41" name="data"/>
    26              <!--<remote ip="192.168.8.39" name="tongbu"/>-->
    27              <!--<remote ip="192.168.8.40" name="tongbu"/>-->
    28          </localpath>
    29          <rsync>
    30              <commonParams params="-az"/>
    31              <auth start="true" users="rsync_backup" passwordfile="/etc/rsync.pwd"/>
    32              <userDefinedPort start="false" port="874"/><!-- port=874 -->
    33              <timeout start="false" time="100"/><!-- timeout=100 -->
    34              <ssh start="false"/>
    35          </rsync>
    36          <failLog path="/tmp/rsync_fail_log.sh" timeToExecute="60"/><!--default every 60mins execute once-->
    37          <crontab start="false" schedule="600"><!--600mins-->
=====================================================

4.4.5查看帮助说明

[root@nfs01 /opt/sersync]# ./sersync2 -h
set the system param
execute:echo 50000000 > /proc/sys/fs/inotify/max_user_watches
execute:echo 327679 > /proc/sys/fs/inotify/max_queued_events
parse the command param
_______________________________________________________
参数-d:启用守护进程模式
参数-r:在监控前,将监控目录与远程主机用rsync命令推送一遍
c参数-n: 指定开启守护线程的数量,默认为10个
参数-o:指定配置文件,默认使用confxml.xml文件
参数-m:单独启用其他模块,使用 -m refreshCDN 开启刷新CDN模块
参数-m:单独启用其他模块,使用 -m socket 开启socket模块
参数-m:单独启用其他模块,使用 -m http 开启http模块
不加-m参数,则默认执行同步程序
________________________________________________________
[root@nfs01 /opt/sersync]# 

4.4.6 启动服务

[root@nfs01 /opt/sersync]# /opt/sersync/sersync2 -dro /opt/sersync/confxml.xml

4.4.7 测试数据是否同步

第5章 lsyncd同步

5.1 官方地址

[https://github.com/axkibe/lsyncd](https://github.com/axkibe/lsyncd)

5.2 lsyncd介绍

参考博客

[https://www.cnblogs.com/zxci/p/6243574.html](https://www.cnblogs.com/zxci/p/6243574.html)

lsyncd简介

Lysncd 实际上是lua语言封装了 inotify 和 rsync 工具,采用了 Linux 内核(2.6.13 及以后)里的 inotify 触发机制,然后通过rsync去差异同步,达到实时的效果。我认为它最令人称道的特性是,完美解决了 `inotify + rsync`海量文件同步带来的文件频繁发送文件列表的问题 —— 通过时间延迟或累计触发事件次数实现。另外,它的配置方式很简单,lua本身就是一种配置语言,可读性非常强。lsyncd也有多种工作模式可以选择,本地目录cp,本地目录rsync,远程目录rsyncssh。
实现简单高效的本地目录同步备份(网络存储挂载也当作本地目录),一个命令搞定。

5.3 安装

[root@nfs01 ~]# yum install lsyncd -y

5.4 创建配置文件

[root@nfs01 ~]# cat /etc/lsyncd.conf
settings {
  logfile = "/var/log/lsyncd/lsyncd.log",
  statusFile = "/var/log/lsyncd/lsyncd.status",
  inotifyMode = "CloseWrite",
  maxProcesses = 8,
}
sync {
  default.rsync,
  source = "/data",
  target = "rsync_backup@172.16.1.41::data",
  delete = true,
  exclude = { ".*" },
  delay = 1,
  rsync = {
    binary = "/usr/bin/rsync",
    archive = true,
    compress = true,
    verbose = true,
    password_file = "/etc/rsync.passwd",
    _extra = {"--bwlimit=200"}
  }
}

sync {
  default.rsync,
  source = "/backup",
  target = "rsync_backup@172.16.1.41::backup",
  delete = true,
  exclude = { ".*" },
  delay = 1,
  rsync = {
    binary = "/usr/bin/rsync",
    archive = true,
    compress = true,
    verbose = true,
    password_file = "/etc/rsync.passwd",
    _extra = {"--bwlimit=200"}
  }
}

5.5 配置文件解释

参考网友博客

https://www.cnblogs.com/zxci/p/6243574.html

5.6 启动命令

[root@nfs01 ~]# systemctl start lsyncd

5.7 测试检查

NFS测试

[root@nfs ~]# cd /data
[root@nfs /data]# for i in {1..1000};do echo "${i}"; echo "${i}" > ${i}.txt;sleep 0.1;done

backup测试

[root@backup ~]# cd /data
[root@backup /data]# while true ;do ls |wc -l;sleep 0.1;done

小礼物走一走,来简书关注我

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,651评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,468评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,931评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,218评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,234评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,198评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,084评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,926评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,341评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,563评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,731评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,430评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,036评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,676评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,829评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,743评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,629评论 2 354

推荐阅读更多精彩内容