淺談數據同步實現rsync+inotify

❎ 數據的實時同步介紹

在生產環境,有時會需要兩臺主機的特定目錄實現實時同步。比如,將NFS共享目錄的數據文件,自動實時同步到備份的服務器特定目錄中
在這裏插入圖片描述
實時同步技術介紹

  • 實現實時同步的方法
    • inotify + rsync 方式實現數據同步
    • sersync :金山公司周洋在 inotify 軟件基礎上進行開發的,功能更加強大
  • 工作原理:
    要利用監控服務(inotify),監控同步數據服務器目錄中信息的變化
    發現目錄中數據產生變化,就利用rsync服務推送到備份服務器上

❎ 數據的實時同步實現

inotify

🌐 inotify的介紹

  • 異步的文件系統事件監控機制,利用事件驅動機制,而無須通過諸如cron等的輪詢機制來獲取事件
  • linux內核從2.6.13起支持 inotify,通過inotify可以監控文件系統中添加、刪除,修改、移動等各種事件
[root@Centos7 ~]$grep -i inotify /boot/config-3.10.0-1062.el7.x86_64 
CONFIG_INOTIFY_USER=y

🌐 實現inotify軟件:

  • inotify-tools
  • sersync
  • lrsyncd

🌐 inotify+rsync使用方式

  • inotify 對同步數據目錄信息的監控
  • rsync 完成對數據的同步
  • 利用腳本進行結合

🌐 實現inotify

1️⃣ 查看內核情況

  • 內核是否支持inotify
    Linux支持inotify的內核最小版本爲 2.6.13,參看man 7 inotify
[root@Centos7 ~]$ls -l /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 Dec 20 14:59 max_queued_events
-rw-r--r-- 1 root root 0 Dec 20 14:59 max_user_instances
-rw-r--r-- 1 root root 0 Dec 20 14:59 max_user_watches
  • inotify內核參數說明:

    • max_queued_events:inotify事件隊列最大長度,如值太小會出現 Event Queue Overflow 錯誤,默認值:16384
    • max_user_instances:每個用戶創建inotify實例最大值,默認值:128
    • max_user_watches:可以監視的文件數量(單進程),默認值:8192
  • 示例:

/ 修改內存配置文件
[root@Centos7 ~]$vim /etc/sysctl.conf 
[root@Centos7 ~]$sysctl -p
fs.inotify.max_queued_events = 66666
fs.inotify.max_user_watches = 100000
[root@Centos7 ~]$cat /proc/sys/fs/inotify/*
66666
128
100000

2️⃣ inotify-tools工具

  • inotify-tools參考文檔:https://github.com/rvoicilas/inotify-tools/wiki
  • 安裝inotify-tools:基於epel源 yum -y install inotify-tools
  • inotify-tools包主要工具:
    inotifywait: 在被監控的文件或目錄上等待特定文件系統事件(open ,close,delete等)發
    生,常用於實時同步的目錄監控
    inotifywatch:收集被監控的文件系統使用的統計數據,指文件系統事件發生的次數統計

3️⃣ inotifywait 命令常見選項

-m, --monitor 始終保持事件監聽
-d, --daemon 以守護進程方式執行,和-m相似,配合-o使用
-r, --recursive 遞歸監控目錄數據信息變化
-q, --quiet 輸出少量事件信息
--exclude 指定排除文件或目錄,使用擴展的正則表達式匹配的模式實現
--excludei 和exclude相似,不區分大小寫
-o, --outfile 打印事件到文件中,相當於標準正確輸出,注意:使用絕對路徑
-s, --syslogOutput 發送錯誤到syslog相當於標準錯誤輸出
--timefmt 指定時間輸出格式
--format 指定的輸出格式;即實際監控輸出內容
-e 指定監聽指定的事件,如果省略,表示所有事件都進行監聽
  • inotifywait 的 --timefmt 時間格式
    參考 man 3 strftime
%Y 年份信息,包含世紀信息
%y 年份信息,不包括世紀信息
%m 顯示月份,範圍 01-12
%d 每月的第幾天,範圍是 01-31
%H 小時信息,使用 24小時制,範圍 00-23
%M 分鐘,範圍 00-59
  • inotifywait 的 --format 格式定義
%T 輸出時間格式中定義的時間格式信息,通過 --timefmt option 語法格式指定時間信息
%w 事件出現時,監控文件或目錄的名稱信息
%f 事件出現時,將顯示監控目錄下觸發事件的文件或目錄信息,否則爲空
%e 顯示發生的事件信息,不同的事件默認用逗號分隔
%Xe顯示發生的事件信息,不同的事件指定用X進行分隔
  • inotifywait -e 選項指定的事件類型
create 文件或目錄創建
delete 文件或目錄被刪除
modify 文件或目錄內容被寫入
attrib 文件或目錄屬性改變
close_write 文件或目錄關閉,在寫入模式打開之後關閉的
close_nowrite 文件或目錄關閉,在只讀模式打開之後關閉的
close 文件或目錄關閉,不管讀或是寫模式
open 文件或目錄被打開
moved_to 文件或目錄被移動到監控的目錄中
moved_from 文件或目錄從監控的目錄中被移動
move 文件或目錄不管移動到或是移出監控目錄都觸發事件
access 文件或目錄內容被讀取
delete_self 文件或目錄被刪除,目錄本身被刪除
unmount 取消掛載

4️⃣ 使用inotifywait示例

  • 安裝inotify-tools
yum -y install epel-release
yum -y install inotify-tools
  • 開啓持續監控
    inotifywait -mrq /data 持續監控 遞歸監控/data目錄變化,並輸出少量信息
    在這裏插入圖片描述

  • 開始後臺持續監控,並設定其輸出格式
    inotifywait -o /root/inotify.log -drq /data --timefmt "%Y-%m-%d %H:%M" --format "%T %w%f event: %e"
    在這裏插入圖片描述

  • 持續前臺監控特定事件
    inotifywait -mrq /data --timefmt "%F %H:%M" --format "%T %w%f event: %;e" -e create,delete,moved_to,close_write,attrib
    在這裏插入圖片描述

rsync

1️⃣ rsync基本概述

  • rsync 常用於做爲 linux系統下的數據鏡像備份工具,
    • 實現實現遠程同步,支持本地複製,或者與其他
    • SSH、rsync主機同步數據,支持增量備份,配合任務計劃,
    • rsync能實現定時或間隔同步,配合inotify或sersync,可以實現觸發式的實時數據同步
  • 官方網站: http://rsync.samba.org/
  • 軟件包:rsync,rsync-daemon(CentOS 8)
  • 服務文件:/usr/lib/systemd/system/rsyncd.service
  • 配置文件:/etc/rsyncd.conf
  • 端口:873/tcp

2️⃣ rsync工作模式

1️⃣ 本地模式

  • 語法格式:rsync [OPTION...] SRC... [DEST]
[root@Centos7 ~]$echo 123 > test.txt
[root@Centos7 ~]$cat test.txt 
123
[root@Centos7 ~]$rsync test.txt /tmp/
[root@Centos7 ~]$cat /tmp/test.txt 
123

2️⃣ 遠程shell模式

  • 本地主機使用遠程shell和遠程主機通信。
  • 命令行語法格式
Pull:
rsync [OPTION...] [USER@]HOST:SRC... [DEST]
Push:
rsync [OPTION...] SRC... [USER@]HOST:DEST
  • 示例1,推送到遠程主機
    rsync test.txt [email protected]:/tmp
    在這裏插入圖片描述
  • 示例2,拉取下載遠程主機文件
    rsync -avz [email protected]/root/test2.txt /tmp
    在這裏插入圖片描述
  • 示例3,拉取目錄
[root@Centos7 ~]$mkdir /data/backup
/ 拉取遠程文件
[root@Centos7 ~]$rsync -avz root@172.20.54.2:/etc/hostname /data/backup
root@172.20.54.2's password: 
receiving incremental file list
hostname

sent 43 bytes  received 107 bytes  42.86 bytes/sec
total size is 16  speedup is 0.11
/ 拉取遠程主機目錄下內容,不要目錄本身
[root@Centos7 ~]$rsync -avz root@172.20.54.2:/root/ /data/backup/
root@172.20.54.2's password: 
receiving incremental file list
./
.bash_history
.bash_logout
.bash_profile
.bashrc
.cshrc
.tcshrc
.viminfo
anaconda-ks.cfg
test2.txt

sent 198 bytes  received 3,412 bytes  1,031.43 bytes/sec
total size is 8,414  speedup is 2.33

/ 拉取遠程主機目錄以及目錄下內容
[root@Centos7 ~]$rsync -avz root@172.20.54.2:/root /data/backup/
root@172.20.54.2's password: 
receiving incremental file list
root/
root/.bash_history
root/.bash_logout
root/.bash_profile
root/.bashrc
root/.cshrc
root/.tcshrc
root/.viminfo
root/anaconda-ks.cfg
root/test2.txt

sent 199 bytes  received 3,428 bytes  1,036.29 bytes/sec
total size is 8,414  speedup is 2.32

3️⃣ 網絡套接字連接遠程主機

  • 本地主機通過網絡套接字連接遠程主機上的rsync daemon。
  • 命令行語法格式
Pull:            / 兩種寫法
rsync [OPTION...] [USER@]HOST::SRC... [DEST]
rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
Push:
rsync [OPTION...] SRC... [USER@]HOST::DEST
rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST

4️⃣ 後臺服務模式區別

  • Rsync 藉助 SSH 協議同步數據存在的缺陷
    1.使用系統用戶(不安全)
    2.使用普通用戶(會導致權限不足情況)
    3.守護進程傳輸方式: rsync 自身非常重要的功能(不使用系統用戶,更加安全)
  • 前兩種模式的本質是通過本地或遠程shell,而第3種方式則是讓遠程主機上運行rsyncd服務,使其監聽在一個端口上,等待客戶端的連接。

3️⃣ rsync 命令參數解釋

rsync #命令
[OPTION...] #選項
SRC... #遠程主機模塊(不是目錄)
[USER@] #遠程主機用戶(虛擬用戶)
HOST:: #遠程主機地址
[DEST] #將遠程主機模塊備份至本地什麼位置
-a #歸檔模式傳輸, 等於-tropgDl
-v #詳細模式輸出, 打印速率, 文件數量等
-z #傳輸時進行壓縮以提高效率
-r #遞歸傳輸目錄及子目錄,即目錄下得所有目錄都同樣傳輸。
-t #保持文件時間信息
-o #保持文件屬主信息
-p #保持文件權限
-g #保持文件屬組信息
-l #保留軟連接
-P #顯示同步的過程及傳輸時的進度等信息
-D #保持設備文件信息
-L #保留軟連接指向的目標文件
-e #使用的信道協議,指定替代 rsh 的 shell 程序
--exclude=PATTERN #指定排除不需要傳輸的文件模式
--exclude-from=file #文件名所在的目錄文件
--bwlimit=100 #限速傳輸
--delete #讓目標目錄和源目錄數據保持一致

4️⃣ rsync 後臺服務模式-服務端配置

1️⃣ 安裝rsync
yum - y install rsync
2️⃣ 修改配置文件

uid = root                         # 用戶UID
gid = root
use chroot = no                    # 禁錮推送的數據至某個目錄, 不允許跳出該目錄
max connetctions = 0               # 最大連接數,爲0不限制
ignore errors                      # 忽略錯誤信息
exlude = lost+found/               # 排除掉這兩個目錄的文件
read only = no                     # 設置rsync服務端文件爲讀寫權限
timeout = 600                      # 超時時長
list = false                       # 不顯示rsync服務端資源列表
auth users = rsyncuser             # 定義虛擬用戶,作爲連接認證用戶
secrets file = /etc/rsync.passwd   # 虛擬用戶密碼文件
log file = /var/log/rsyncd.log     # 日誌文件啓動rsync後自動產生這個文件,無需提前創建
pid file = /var/run/rsyncd.pid     # pid文件
lock file = /var/run/rsyncd.lock   # 支持max connections參數的鎖文件
host allow = 172.20.54.0/24        # 允許進行數據同步的客戶端IP地址,可以設置多個,用英文狀態下逗號隔開
[backup]                           # 名稱自定義
path = /backup                     # 服務端備份數據存放目錄
comment = welcome to test backup!  # 描述信息

3️⃣ 服務端準備其他文件

/ 創建備份數據存放目錄
mkdir /backup
/ 準備用戶驗證密碼文件
echo "rsyncuser:centos" > /etc/rsync.passwd
chmod 600 /etc/rsync.passwd

/ 啓動rsync 服務
systemctl start rsyncd
[root@Centos7 ~]$ss -ntlp
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      5             *:873                       *:*                   
users:(("rsync",pid=2216,fd=3))

5️⃣ rsync 後臺服務模式-客戶端配置

/ 安裝rsync服務
yum -y install rsync

/ 配置密碼文件
echo "centos" > /etc/rsync.passwd
chomd 600 /etc/rsync.passwd

6️⃣ rsync 客戶端測試

  • 啓動同步命令
    rsync -avz --delete --password-file=/etc/rsync.passwd /data/ [email protected]::backup
    在這裏插入圖片描述
  • 創建inotify_rsync.sh腳本,使用inotify+rsync組合
#!/bin/bash
SRC='/data/'             # 只同步目錄內容
DEST='[email protected]::backup'
/usr/bin/inotifywait -mrq --timefmt '%Y-%m-%d %H:%M' --format '%T %w%f%e' -e \
create,delete,moved_to,close_write,attrib ${SRC} | while read file;do \
/usr/bin/rsync -az --delete --password-file=/etc/rsync.passwd ${SRC} ${DEST} 
echo "${file} was backuped " >> /var/log/rsync.log
done

在這裏插入圖片描述

  • 把腳本加入開啓啓動,並後臺運行
vim /etc/rc.local
nohup sh /root/inotify_rsync.sh &
  • 查看日誌文件
    在這裏插入圖片描述

發佈了107 篇原創文章 · 獲贊 20 · 訪問量 6369
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章