快速、靈活的文件同步複製工具—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的推送與拉取的概念,千萬別混淆兩者之間的區別,希望能夠給需要的朋友帶來一些幫助。


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