快速、灵活的文件同步复制工具—rsync(进阶篇)

一、自述

前一篇文档讲解了rsync的安装与配置以及应用实例(http://cfwlxf.blog.51cto.com/3966339/1406364),看过前一篇的文档朋友,尽管你还未曾在线上环境使用rsync提供服务,但你可能已经了解rsync实现文件同步的方式有两种,一种是默认使用SSH协议通信,实现文件同步,另一种通过虚拟通道,并以虚拟的用户名,密码进行验证通信,实现文件同步;那么此篇文档将要讲解rsync是如何通过SSH 免密钥认证与inotify-tools工具快速实现文件单向,双向的实时同步,何为双向同步,即两端同时互为服务端与客户端;

二、inotify-tools介绍

Inotify-tools是用C语言编写的工具,它提供了一组命令行程序,这些程序用来监控文件系统事件,比如文件的读写,创建,删除,更新等;inotify为Linux系统提供了一个简单的接口,利用这个接口,rsync便可利用inotifywait程序监测文件系统的读写,删除,修改事件等,实现文件的实时同步;其效率要比利用crond计划任务的轮询高效得多;而且inotifywait、inotifywatch程序的使用也非常简单。

官方WIKE文档请详见:https://github.com/rvoicilas/inotify-tools/wiki

三、inotify工作原理示意图

wKioL1Nx3Rmj44dIAALxu6XaH7c513.jpg

四、安装与配置

41 下载inotify-tools软件

[root@webserver1 ~]# mkdir /download/source -p
[root@webserver1 ~]# cd /download/source/
[root@webserver1 source]# wget http://jaist.dl.sourceforge.net/project/inotify-tools/inotify-tools/3.13/inotify-tools-3.13.tar.gz
--2014-05-11 23:09:48--  http://jaist.dl.sourceforge.net/project/inotify-tools/inotify-tools/3.13/inotify-tools-3.13.tar.gz
Resolving jaist.dl.sourceforge.net... 150.65.7.130, 2001:df0:2ed:feed::feed
Connecting to jaist.dl.sourceforge.net|150.65.7.130|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 389473 (380K) [application/x-gzip]
Saving to: °inotify-tools-3.13.tar.gz±
100%[======================================================================>] 389,473     30.6K/s   in 23s 
2014-05-11 23:10:11 (16.8 KB/s) - °inotify-tools-3.13.tar.gz± saved [389473/389473]


[root@webserver1 source]# ll inotify-tools-3.13.tar.gz

-rw-r--r-- 1 root root 389473 Jan12008inotify-tools-3.13.tar.gz

##提示:

当前使用VMware虚拟机,虚拟了两台已经安装CentOS系统的服务器,模拟线上的两台real server,实现两端图片文件实时同步;如果你的VMware无法连接互联网,你可以实现下载inotify-tools工具至本地,然后通过secureCRT软件或则其它软件上传至服务器,网卡桥接模式可以为network与bridged。


42 安装

[root@webserver1 source]# tar -xf inotify-tools-3.13.tar.gz

[root@webserver1 source]# cd inotify-tools-3.13

##建议在执行configure之前,先了解一些INSTALL文件,然后再进行安装;

[root@webserver1 inotify-tools-3.13]# ./configure

[root@webserver1 inotify-tools-3.13]# make

[root@webserver1 inotify-tools-3.13]# make install

[[email protected]]# ll /usr/local/bin/inotifywa*

-rwxr-xr-x 1 root root 38638 May 11 23:28/usr/local/bin/inotifywait

-rwxr-xr-x 1 root root 40409 May 11 23:28/usr/local/bin/inotifywatch

##提示

编译安装inotify-tools成功后,默认情况会在/usr/local/bin目录下生成两个二进制文件:inotifywait、inotifywatch;其中inotifywait命令监控inotify事件,你可以通过shell脚本更好的使用它,inotifywait可以查看任何文件和目录的设置,并且可以递归观看整个目录树;inotifywatch收集文件系统的使用统计和输出每个inotify事件;

inotifywait

This command simply blocks for inotify events, making itappropriate for use in shell scripts. It can watch any set of files anddirectories, and can recursively watch entire directory trees.

inotifywatch

inotifywatch collects filesystem usage statistics andoutputs counts of each inotify event.

43 实例演示

Inotifywait

[root@webserver1 scripts]# vim rsync_inotify.sh
#!/bin/sh
#describe:sync file
SRC=/source/test/
DST=/destination/test/          ## webserver2需要创建的目录,否则无法同步;
/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,create,move,delete,attrib $SRC \
| while read file
        do
        rsync --progress --delete  -avzPe 'ssh -p 22'  $SRC [email protected]:$DST && \
        echo -e "\033[32mSync $file is successfully.\033[0m"
done


431 文件同步过程,此时使用SSH协议,默认提供webserver2端密码;

wKiom1Nx3m-hs6VqAARGO42sXDM903.jpg

431 webserver2端验证同步结果

[root@webserver2 ~]# ls /destination/test/

workyesterday

Inotifywatch

[root@webserver1 ~]# inotifywatch -v -e access -emodify,delete,create,move,attrib -t 60 -r /test

Establishing watches...

Setting up watch(es) on /test

OK, /test is now being watched.

Total of 1 watches.

Finished establishing watches, now collecting statistics.

Will listen for events for 60 seconds.

totalattribmoved_fromcreatefilename

10514/test/


[root@webserver1 test]# touch work today disk memory

[root@webserver1 test]# mv disk /root

[root@webserver1 test]# chmod +x memory

[root@webserver1 test]# cat work


43 inotifywaitinotifywatch命令相关参数详解

-v, --verboseOutput some extra information on standarderror during execution.

##表示在命令执行过程中,输出一些额外的信息;


-m|--monitorKeep listening for events forever.Without this option, inotifywait will exitafter one event is received.

##表示永远保持事件监听状态,若不指定此选项,inotifywait将接收一个事件后退出;


-r|--recursiveWatchdirectories recursively.

##表示递归查询目录,即目录下包含的子目录;


-q|--quietPrint less (only print events).

##表示只打印较少的监控事件;


-t|--timeout <seconds> Whenlistening for a single event, time out after waiting for an event for<seconds> seconds.If <seconds> is 0, inotifywait will never timeout.

##表示当监听一个单一事件所等待的秒数,如果设置为0,inotifywait永远不会超时,处于监听状态;


-e|--event <event1> Listen forspecific event(s).If omitted, allevents are listened for.

#监听用户指定的事件,如果省略,将监听所有的事件;


--format <fmt> Print using a specified printf-like format string;read the man page for more details.

#打印使用指定的printf-like的格式字符串,如--format '%T %w %f'


--timefmt <fmt> strftime-compatibleformat string for use with %T in --format string.

#指定显示的时间格式,如--timefmt '%d/%m/%y%H:%M';

Events:

accessfile or directory contents were read        #文件或目录的内容被读取;
modifyfile or directory contents were written     #文件或目录的内容被写;
attribfile or directory attributes changed        #文件或目录的属性被改变;
createfile or directory created within watched directory    #监控目录中创建文件或目录
deletefile or directory deleted within watched directory    #监控目录中删除文件或目录



五、企业应用案例

51 案例解析

公司最近上线一个用于品牌手机维修的网站,前端的架构采用nginx+haproxy(当然不止代理这一个站点的访问请求)负责代理后端的两台realserver(真实服务器);为了不让用户访问到数据出现任何偏差,那么就必须保证两台服务器的数据完全是一致的,既然如此,那如何保证用户或则维修人员上传的图片保持一致;如何实现,可以通过文件实时同步工具sersync、rsync+inotify机制实现;

52 服务器资源列表

服务器名称

系统

CPU架构

内核

IP地址

角色

webserver1

CentOS 6.3

x86_64

2.6.32-279.el6.x86_64

10.16.10.29

Server,Client

webserver2

10.16.10.52

Server,Client

##提示

服务器web1web2互为服务端与客户端,两端分别安装rsyncinotify-tools软件,从而实现服务器的图片实时同步,保证两台服务器的数据完全是一致的,这样用户访问的数据才没有任何差异,非常服务器非正常状态,比如一端硬盘损坏,断电等;


53 配置

531 webserver1webserver2通过SSH免密钥认证,实现文件实时同步

#######Webserver1生成rsa算法密钥,操作如下:
[root@webserver1 ~]# /usr/bin/ssh-keygen -t rsa
[root@webserver1 ~]# scp ~/.ssh/id_rsa.pub [email protected]:/root
[email protected]'s password: 
id_rsa.pub100%3970.4KB/s00:00
#######webserver2端生成rsa算法密钥,操作如下:
[root@webserver2 ~]# ssh-keygen -t rsa
[root@webserver2 ~]# scp ~/.ssh/id_rsa.pub [email protected]:/root
[email protected]'s password: 
id_rsa.pub100%3970.4KB/s00:00
#######改名公钥id_rsa.pub为配置文件指定的验证文件authorized_keys,两端操作一致:
[root@webserver1 ~]# mv id_rsa.pub .ssh/authorized_keys 
[root@webserver1 ~]# chmod 600 .ssh/authorized_keys
[root@webserver2 ~]# mv id_rsa.pub .ssh/authorized_keys 
[root@webserver2 ~]# chmod 600 .ssh/authorized_keys

532 测试两端是否实时同步文件

######webserver1

wKioL1Nx3_KhKDD5AAKOQYGJVXc484.jpg

[root@webserver2~]# ll /destination/test/

total 0

-rw-r--r-- 1 rootroot 0 May 12 23:44 hello


#####webserver2

wKiom1Nx4DTwKsjHAALZ50DpT2M184.jpg

[root@webserver1~]# ll /destination/test/

total 0

-rw-r--r-- 1 rootroot 0 May 13 00:16 one


54 webserver1webserver2通过rsync虚拟通道,实现文件实时同步;

541 Webserver1rsync配置如下

[root@webserver1 scripts]# cat /etc/rsyncd.conf

uid = root

gid = root

use chroot = no

max connections = 3000

timeout = 300

pid file = /var/run/rsyncd.pid

lock file = /var/lock/rsyncd

log file = /var/log/rsyncd.log


[image]

comment = exiuxui Image data

path = /data/exiuxiu/program/image/

read only = no

list = yes

trict modes = yes

hosts allow = 10.16.10.0/24

hosts deny = *

ignore errors = no

ignore nonreadable = yes

transfer logging = no

log format = %t: host %h (%a) %o %f (%l bytes). Total %bbytes.

auth users = rsync_user

secrets file = /etc/rsyncd29.passwd


[root@webserver1 scripts]# vim /etc/rsyncd29.passwd

rsync_user:admin

[root@webserver1 scripts]# chmod 600 /etc/rsyncd29.passwd

[root@webserver2 ~]# vim /etc/rsyncd29.passwd

admin


542 Webserver2rsync配置如下

[root@webserver2 image]# cat /etc/rsyncd.conf

uid = root

gid = root

use chroot = no

max connections = 3000

timeout = 300

pid file = /var/run/rsyncd.pid

lock file = /var/lock/rsyncd

log file = /var/log/rsyncd.log

[image]

comment = exiuxui Image data

path = /data/exiuxiu/program/image

read only = no

list = yes

trict modes = yes

hosts allow = 10.16.10.0/24

hosts deny = *

ignore errors = no

ignore nonreadable = yes

transfer logging = no

log format = %t: host %h (%a) %o %f (%l bytes). Total %bbytes.

auth users = rsync_user

secrets file = /etc/rsyncd52.passwd


[root@webserver2 image]# vim /etc/rsyncd52.passwd

rsync_user:admin

[root@webserver2 image]# chmod 600 /etc/rsyncd52.passwd

[root@webserver1 ~]# vim /etc/rsyncd52.passwd

admin


543 Webserver1inotify同步脚本配置如下
[root@webserver1 scripts]# cat rsync_image52.sh
#!/bin/bash
# Descrtion : sync host 10.16.10.52 image file
PATH=/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/bin:/sbin
export PATH
# User custom variable
HOST=10.16.10.52
USER=rsync_user
SRC=/data/exiuxiu/program/image/
MODULE=image
/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w %f' -e modify,create,move,delete,attrib $SRC \
| while read file
        do
                rsync --progress --delete  -avzP $SRC $USER@$HOST::$MODULE --password-file=/etc/rsyncd52.passwd && \
                echo -e "\033[32mSync $file is successfully.\033[0m" >> /tmp/rsync_image.log 2>&1
        done

544 Webserver2inotify同步脚本配置如下
[root@webserver2 scripts]# cat rsync_image29.sh
#!/bin/bash
# Descrtion : sync host 10.16.10.52 image file
PATH=/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/bin:/bin:/sbin
export PATH
# User custom variable
HOST=10.16.10.29
USER=rsync_user
SRC=/data/exiuxiu/program/image/
MODULE=image
/usr/local/bin/inotifywait -mrq --timefmt '%d/%m/%y%H:%M' --format '%T %w %f' -e modify,create,move,delete,attrib $SRC \
| while read file
do
rsync --progress --delete -avzP --password-file=/etc/rsyncd29.passwd$SRC $USER@$HOST::$MODULE && \
echo -e "\033[32mSync $file is successfully.\033[0m" >>/tmp/rsync_image.log 2>&1
done


55 测试webserver1webserver2文件实时同步结果

551 webserver1端操作如下

[root@webserver1~]# sh /server/scripts/rsync_image52.sh &

[1] 38058

[root@webserver1image]# touch 4.jpeg 5.png

sendingincremental file list

./

4.jpeg

0 100%0.00kB/s0:00:00 (xfer#1, to-check=1/6)

5.png

0 100%0.00kB/s0:00:00 (xfer#2, to-check=0/6)

wKiom1Nx4PPTJFuNAAFhnxXiQtU637.jpg


552 webserver2端验证

wKioL1Nx4O7x5_BsAAB05SRmDtA718.jpg


553 webserver2端配置如下

[root@webserver2~]# sh /server/scripts/rsync_image29.sh &

[1] 34406

[root@webserver2~]# cd /data/exiuxiu/program/image/

[root@webserver2image]# touch 6.gif 7.jpeg 8.jpg

sendingincremental file list

./

6.gif

0 100%0.00kB/s0:00:00 (xfer#1, to-check=2/9)

7.jpeg

0 100%0.00kB/s0:00:00 (xfer#2, to-check=1/9)

8.jpg

0 100%0.00kB/s0:00:00 (xfer#3, to-check=0/9)

wKiom1Nx4SrhHoG4AAEF7kDlpcU076.jpg


554 webserver1端验证

wKioL1Nx4RWhp-cQAACQAnUIAiE453.jpg

##提示

关于rsync进阶篇写到便已经完成了,后期还会继续更新,参考这篇文档部署的朋友,建议先看完rsync基础篇;还有一点你需要弄清楚rsync的推送与拉取的概念,千万别混淆两者之间的区别,希望能够给需要的朋友带来一些帮助。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章