數據一致性方案之 Rsync-Inotify 實現文件同步

背景

在分佈式系統中,如何保證數據的一致性,一直是一個難題!業界也出現了很多不同的方案來實現數據的一致性。如使用數據庫,使用一致性算法如 raft 等等,這些方案對數據比較小的內容有較好的效果,對應比較多內容的,則可能會遭遇問題。今天也介紹一種保證數據一致性的方法,即使用文件同步的方式:Rsync+Inotify。

Rsync+Inotify 文件同步架構

rsync 是 Unix 下的一款應用軟件,它能同步更新兩處計算機的文件與目錄,並適當利用差分編碼以減少數據傳輸量。rsync 中的一項同類軟件不常見的重要特性是每個目標的鏡像只需發送一次。rsync 可以拷貝/顯示目錄內容,以及拷貝文件,並可選壓縮以及遞歸拷貝。

inotify 是 Linux 核心子系統之一,作爲文件系統的附加功能,它可監控文件系統並將異動通知應用程序。本系統的出現取代了舊有 Linux 核心裏,擁有類似功能之 dnotify 模塊。

從上圖可以看出,rsync 有客戶端和服務器端,inotify 負責監控客戶端的文件變化,然後通過 rsync 客戶端將變化發送到目標服務器端。

Rsync+Inotify 文件同步示例

以 linux 中 centos7 爲例,其它系統可以做參考:

客戶端安裝 rsync

yum -y install rsync

客戶端安裝 inotify

//從內核和目錄裏面查看是否支持inotify
ls -l /proc/sys/fs/inotify/ 
  //檢查是否有安裝inotify 如果沒有就安裝
rpm -qa inotify-tools 
yum install inotify-tools -y
//檢查是否安裝完成
inotifywait --help
inotifywatch --help

客戶端準備配置和監控腳本

在 / etc 目錄下創建 rsync.password 文件,並賦予 600 權限

chmod 600 rsync.password

準備監控腳本 inotify.sh,監控文件變化

#!/bin/bash
inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,attrib /opt/source/ | while read file
do

rsync -vzrtopg --progress /opt/source/ backuser@168.192.1.1::dest --password-file=/etc/rsync.password
rsync -vzrtopg --progress /opt/source/ backuser@168.192.1.2::dest --password-file=/etc/rsync.password


echo "${files} was rsynced" >> /var/log/rsync.log 2>&1
done

安裝完成後會生成兩個命令
/usr/bin/inotifywait
/usr/bin/inotifywatch

注意 dest 不是目錄,而是 rsync 服務端定義的別名,在服務端的 rsync.conf 文件中配置的。

啓動腳本編寫 start.sh:

#!/bin/bash
ps -elf | grep inotify &> /dev/null
if [ -z $? ]
   then
        echo "inotify service is running"
   else
        sh /home/inotify.sh &
        echo "inotify service is activing"
fi

文件授權,並執行

chmod u+x *.sh
sh start.sh

服務器端安裝 rsync

yum -y install rsync

服務器配置文件

rsync.password

和上面客戶端相同。

rsyncd.conf

log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
secrets file = /etc/rsync.password
motd file = /etc/rsyncd.motd

[web_log]
path = /usr/local/dest/
comment = dest
uid = root
gid = root
port=873
use chroot = false
read only = false
list = false
max connections = 200
timeout = 600
auth users = backuser
hosts allow = 168.192.1.1,168.192.1.2

啓動 rsync

rsync  --daemon

測試

在目標文件,新建文件,在目標文件即可以看到。

總結

常見錯誤

password file must not be other-accessible
continuing without password file
Password:
rsync 客戶端路徑是否寫錯,權限設置不對,需要再次輸入密碼,客戶端和服務端的密碼文件都應該是 600 的權限纔可以。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/OKbdMCi_X9VJruDis5eoXA