服務器雙向同步( 可實時 ) unison + inotify

一. Unison簡介

Unison是Windows、Linux以及其餘Unix平臺下均可以使用的文件同步工具,它能使兩個文件夾(本地或網絡上的)保持內容的一致。
1. 跨平臺使用;對內核和用戶權限沒有特別要求; html

2. Unison是雙向的,它能自動處理兩分拷貝中更新沒有衝突的部分,有衝突的部分將會顯示出來讓用戶選擇更新策略;linux

3. 只要是能連通的兩臺主機,就能夠運行unison,能夠直接使用socket鏈接或安全的ssh鏈接方式,對帶寬的要求不高,使用相似rsync的壓縮傳輸協議。centos

二. 如何使用unison

本次操做環境:  兩臺centos服務器    服務器A        服務器B  安全

1. 安裝 ocaml 

Linux下經過源碼包編譯安裝Unison時,須要用到Objective Caml compiler 這個東西.  bash

[root@centos-A data]# rpm -qa |grep ocaml   ##能夠先檢查下是否安裝過. 圖方便本次我直接yum了
ocaml-runtime-3.11.2-5.el6.x86_64
ocaml-3.11.2-5.el6.x86_64

下載地址  http://caml.inria.fr/pub/distrib/    或者 http://ocaml.org/docs/install.html   服務器

能夠這樣編譯安裝, 其實yum安裝也能夠. 版本至少爲3.07或更高  yum install ocaml網絡

wget http://caml.inria.fr/pub/distrib/ocaml-4.02/ocaml-4.02.0.tar.gz併發

tar xf ocaml-4.02.0.tar.gzapp

cd ocaml-4.02.0dom

./configure

make world opt

make install

ocaml -version   #看版本是否安裝成功

2. 安裝unison

下載地址:  https://www.seas.upenn.edu/~bcpierce/unison/download/releases/   

找stable穩定版本, 這個東西配置epel源能夠yum安裝, 但版本不高,當前時間多爲 unison240  或者  unison227 

以前安裝2.48.3時以下操做

wget http://www.seas.upenn.edu/~bcpierce/unison//download/releases/unison-2.48.3/unison-2.48.3.tar.gz

tar xf unison-2.48.3.tar.gz

cd unison-2.4

make UISTYLE=text

mkdir /root/bin/

cp unison /root/bin/

make install

cp ./unison /usr/bin/

如今最新穩定版爲 2.48.4

[root@admin opt]# wget https://www.seas.upenn.edu/~bcpierce/unison/download/releases/unison-2.48.4/unison-2.48.4.tar.gz
[root@admin opt]# tar xf unison-2.48.4.tar.gz 
[root@admin opt]# ll
total 1184
drwxr-xr-x. 2 root root 4096 Mar 26 2015 rh
drwxrwxr-x. 9 root root 4096 May 24 2016 src
-rw-r--r--. 1 root root 1200861 May 24 2016 unison-2.48.4.tar.gz
[root@admin opt]# cd src/
[root@admin src]# make UISTYLE=text
File "/opt/src/fsmonitor/linux/watcher.ml", line 55, characters 5-10:
Error: Syntax error
make: *** [fsmonitor/linux/watcher.cmx] Error 2

[root@admin src]# make install
mv /root/bin//unison /tmp/unison-2903
mv: cannot stat `/root/bin//unison': No such file or directory
make: [doinstall] Error 1 (ignored)
cp unison /root/bin/
cp: cannot create regular file `/root/bin/': Is a directory
[root@admin src]# cp ./unison  /usr/local/bin/
[root@admin ~]# which unison
/usr/local/bin/unison

3. ssh免密認證

最好是用普通用戶作認證. root有風險

[root@admin ~]# useradd admin
[root@admin ~]# echo bszh****|passwd --stdin admin
Changing password for user admin.
passwd: all authentication tokens updated successfully.
[root@admin ~]# su - admin
[admin@admin ~]$ pwd
/home/admin
[admin@admin ~]$ ssh-keygen -t rsa #### 不用 -t 指定加密方式默認就是rsa 關於加密方式可參考 ssh-keygen -t ecdsa 非交互生成密鑰 :  ssh-keygen -t dsa -f /root/.ssh/id_dsa -P ""
Generating public/private rsa key pair.
Enter file in which to save the key (/home/admin/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/admin/.ssh/id_rsa.
Your public key has been saved in /home/admin/.ssh/id_rsa.pub.
The key fingerprint is:
14:e9:57:7c:7f:5b:42:2f:64:30:6d:85:8a:9e:60:6e admin@admin
The key's randomart image is:
+--[ RSA 2048]----+
|        .. .oo o.|
|        ..  o.O  |
|       ..  o B o |
|       .+ o . o =|
|       oS+ .   o+|
|        E o    . |
|       .         |
|                 |
|                 |
+-----------------+

 [admin@admin ~]$ ssh-copy-id -i .ssh/id_rsa.pub '-p 22 admin@192.168.0.11'
admin@192.168.0.11's password:
Now try logging into the machine, with "ssh '-p 22 admin@192.168.0.11'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

 雙方作好ssh認證後就能夠測試unison可用不可用了.

  unison -batch /home/admin/test/ ssh://admin@192.168.0.11//home/admin/test

unison同步時, 若是ssh不是默認的22端口,須要指定特定端口時 

  unison -batch /data/unisontest ssh://admin@111.198.29.223:2211//data/unisontest

4. 修改配置作同步

只附上一個的配置文件吧, 另外一個和這個除了地址路徑外都同樣

[admin@VM_0_15_centos test]$ cat /home/admin/.unison/default.prf

# Unison preferences file
root = /data/test
root = ssh://admin@111.198.29.223:2211//data/test/
batch = true
owner = true
group = true
perms = -1
fastcheck = false
rsync = false
sshargs = -C
xferbycopying = true
log = true
logfile = /home/admin/.unison/unison.log

好了. 基本能用了. 能夠結合定時任務用,可是效果很差, 尤爲是須要同步的目錄裏文件頻繁更新和過大時. 

三. unison常見問題處理

1. Fatal error: Warning: inconsistent state   ==>   Archive ***** on host   should be DELETED

[admin@VM_0_15_centos ~]$ unison -batch /data/test ssh://admin@111.198.29.223:2211//data/test
Contacting server...
Connected [//VM_0_15_centos//data/test -> //centos-A//data/test]
Looking for changes
Fatal error: Warning: inconsistent state.
The archive file is missing on some hosts.
For safety, the remaining copies should be deleted.
Archive arfab143f600338a088d5a48b8eb04b701 on host VM_0_15_centos is MISSING
Archive ar2a565bcf1cefb35d97b1813caeda9557 on host centos-A should be DELETED
Please delete archive files as appropriate and try again
or invoke Unison with -ignorearchives flag.

[root@centos-A data]# su - admin
[admin@centos-A ~]$ cd .unison/
[admin@centos-A .unison]$ ll
total 184
-rw------- 1 admin admin   1144 Mar 14 13:15 ar2a565bcf1cefb35d97b1813caeda9557
-rw------- 1 admin admin    581 Mar 12 14:15 ar8714267eb7e6ade26891aefe9bcfb48a
-rw------- 1 admin admin    677 Mar 13 16:00 ar9b59ffdaa0a611b441fd0fa73b15649e
-rw------- 1 admin admin    260 Mar 12 15:32 default.prf
-rw------- 1 admin admin     34 Mar 12 15:21 fp2a565bcf1cefb35d97b1813caeda9557
-rw------- 1 admin admin     34 Mar 12 14:23 fp8714267eb7e6ade26891aefe9bcfb48a
-rw------- 1 admin admin     34 Mar 13 16:00 fp9b59ffdaa0a611b441fd0fa73b15649e
-rw------- 1 admin admin 156303 Mar 14 13:15 unison.log
[admin@centos-A .unison]$ ll ar2a565bcf1cefb35d97b1813caeda9557
-rw------- 1 admin admin 1144 Mar 14 13:15 ar2a565bcf1cefb35d97b1813caeda9557
[admin@centos-A .unison]$ rm ar2a565bcf1cefb35d97b1813caeda9557

 2. Permission denied

[admin@centos-A test]$ unison
Contacting server...
Connected [//VM_0_15_centos//data/test -> //centos-A//data/test]
Looking for changes
Waiting for changes from server
Reconciling changes
props <-?-> props /
local : dir props changed modified on 2019-03-15 at 10:33:43 size 0 --rwxr-xr-x user=admin group=admin
VM_0_15_c... : dir props changed modified on 2019-03-14 at 19:18:58 size 0 --rwxr-xr-x user=0 group=0
new file ----> oo.txt
local : new file modified on 2019-03-15 at 10:33:43 size 0 --rw-rw-r-- user=admin group=admin
VM_0_15_c... : absent
Propagating updates
UNISON 2.48.4 started propagating changes at 10:36:25.31 on 15 Mar 2019
[CONFLICT] Skipping
properties changed on both sides
[BGN] Copying oo.txt from /data/test to //VM_0_15_centos//data/test
Failed: Error in processing a transfer instruction:
Permission denied [open(/data/test/.unison.oo.txt.fab143f600338a088d5a48b8eb04b701.unison.tmp)]
100% 00:00 ETAFailed [oo.txt]: Error in processing a transfer instruction:
Permission denied [open(/data/test/.unison.oo.txt.fab143f600338a088d5a48b8eb04b701.unison.tmp)]
UNISON 2.48.4 finished propagating changes at 10:36:25.34 on 15 Mar 2019
Saving synchronizer state
Synchronization incomplete at 10:36:25 (0 items transferred, 1 skipped, 1 failed)
skipped: (properties changed on both sides)
failed: oo.txt

解決方法 : 檢查服務器須要同步的文件目錄的屬主權限是否正確. root用戶的目錄普通用戶默認是沒有權限的

四. 配合inotify可實時

Inotify 是一個 Linux 內核特性,它監控文件系統,而且及時向專門的應用程序發出相關的事件警告,好比刪除、讀、寫和卸載操做等。您還能夠跟蹤活動的源頭和目標等細節。

Inotify 是一個 Linux特性,它監控文件系統操做,好比讀取、寫入和建立。Inotify 反應靈敏,用法很是簡單,而且比 cron 任務的繁忙輪詢高效得多。

inotify是強大的, 細粒度的, 可異步的文件系統/目錄 事件監控機制(軟件)    內核2.6.13以後版本支持inotity

對文件或目錄的 添加、刪除,修改、移動 操做均可以經過 inotify監控

軟件名稱:  inotify-tools

1. 檢查系統是否支持

[admin@admin test]$ uname -r
2.6.32-696.el6.x86_64
[admin@admin test]$ ll /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 Mar 13 17:22 max_queued_events
-rw-r--r-- 1 root root 0 Mar 13 17:22 max_user_instances
-rw-r--r-- 1 root root 0 Mar 13 17:22 max_user_watches
[admin@admin test]$ ###顯示上面這三個文件表明支持

在/proc/sys/fs/inotify日錄下有三個文件,對inotify機制有必定的限制

max_user_watches   設置inotifywait或inotifywatch命令能夠監視的文件數量(單進程)

max_user_instances  設置每一個用戶能夠運行的inotifywait或inotifywatch命令的進程數。

max_queued_events:設置inotify實例事件(event)隊列可容納的事件數量。

2. 安裝 inotify-tools

[root@admin ~]# # yum install inotify-tools 
[root@admin ~]# rpm -qa |grep inotify
inotify-tools-3.14-1.el6.x86_64

 其實一共安裝了2個命令. 即 inotifywait inotifywatch

  inotifywait :  在被監控的文件或目錄上等待特定的文件系統事件( open , close, delete 等)發生, 執行後處於阻塞狀態, 適合在腳本中使用

  inotifywatch : 收集被監視的文件系統使用度統計數據, 指文件系統事件發生的次數統計

 inotifywait參數

-r     --recursive      #遞歸查詢目錄

-q    --quiet            #打印不多的信息,僅僅打印監控事件的信息

-m   --monitor        #始終保持事件監聽狀態

--timefmt  <fmt>    #打印使用指定的輸出相似格式字符串

-e                        #經過此參數能夠指定須要監控的事件,以下所示:

 

moved_to            #有文件或目錄被移動至這個目錄。

create                #文件或目錄被建立在當前目錄

delete                #文件或目錄被刪除

close_write         #修改文件或目錄的內容

-h,–help
輸出幫助信息
@
排除不須要監視的文件,能夠是相對路徑,也能夠是絕對路徑。
–fromfile 
從文件讀取須要監視的文件或排除的文件,一個文件一行,排除的文件以@開頭。
-m, –monitor
接收到一個事情而不退出,無限期地執行。默認的行爲是接收到一個事情後當即退出。
-d, –daemon
跟–monitor同樣,除了是在後臺運行,須要指定–outfile把事情輸出到一個文件。也意味着使用了–syslog。
-o, –outfile 
輸出事情到一個文件而不是標準輸出。
-s, –syslog
輸出錯誤信息到系統日誌
-r, –recursive
監視一個目錄下的全部子目錄。
-q, –quiet
指定一次,不會輸出詳細信息,指定二次,除了致命錯誤,不會輸出任何信息。
–exclude 
正則匹配須要排除的文件,大小寫敏感。
–excludei 
正則匹配須要排除的文件,忽略大小寫。
-t , –timeout 
設置超時時間,若是爲0,則無限期地執行下去。
-e , –event 
指定監視的事件。
-c, –csv
輸出csv格式。
–timefmt 
指定時間格式,用於–format選項中的%T格式。
–format 
指定輸出格式。
%w 表示發生事件的目錄
%f 表示發生事件的文件
%e 表示發生的事件
%Xe 事件以「X」分隔
%T 使用由–timefmt定義的時間格式
inotifywait參數

inotifywatch參數

參數:
-h, –help
輸出幫助信息
-v, –verbose
輸出詳細信息
@
排除不須要監視的文件,能夠是相對路徑,也能夠是絕對路徑。
–fromfile 
從文件讀取須要監視的文件或排除的文件,一個文件一行,排除的文件以@開頭。
-z, –zero
輸出表格的行和列,即便元素爲空
–exclude 
正則匹配須要排除的文件,大小寫敏感。
–excludei 
正則匹配須要排除的文件,忽略大小寫。
-r, –recursive
監視一個目錄下的全部子目錄。
-t , –timeout 
設置超時時間
-e , –event 
只監聽指定的事件。
-a , –ascending 
以指定事件升序排列。
-d , –descending 
以指定事件降序排列。
inotifywatch參數

 

3. 可監聽的事件

access

文件讀取

modify

文件更改。

attrib

文件屬性更改,如權限,時間戳等。

close_write

以可寫模式打開的文件被關閉,不表明此文件必定已經寫入數據。

close_nowrite

以只讀模式打開的文件被關閉。

close

文件被關閉,無論它是如何打開的。

open

文件打開。

moved_to

一個文件或目錄移動到監聽的目錄,即便是在同一目錄內移動,此事件也觸發。

moved_from

一個文件或目錄移出監聽的目錄,即便是在同一目錄內移動,此事件也觸發。

move

包括moved_to和 moved_from

move_self

文件或目錄被移除,以後再也不監聽此文件或目錄。

create

文件或目錄建立

delete

文件或目錄刪除

delete_self

文件或目錄移除,以後再也不監聽此文件或目錄

unmount

文件系統取消掛載,以後再也不監聽此文件系統。

4. 數據實時複製

 監視目錄變更後執行同步的腳本

[admin@VM_0_15_centos .unison]$ cat /script/inotify-unison.sh#!/bin/bash
##########################################
inotifywait -mrq  /data/test/ --format "%w%f"  -e create,delete,close_write,moved_to|while read line
  do
    echo `date +%F' '%T'  '%A`
    unison
    echo -e ' \n \n '
done

 爲監視腳本寫個簡單服務

[root@VM_0_15_centos ~]# cat /etc/init.d/unison_inotify
#!/bin/bash
# intofitywait watch /data/test/
# unison ---  sync from /data/test to //remote//data/test

. /etc/rc.d/init.d/functions
use_username=admin
log_path=/home/$use_username/.unison/unison-diy.log
procID=`ps aux |grep inotify-unison.sh |grep -v grep|awk '{print $2}'`

start() {
        echo -n $"Starting unison_inotify... "
        su - $use_username -c "nohup  /script/inotify-unison.sh  >>$log_path 2>&1 &"
    RETVAL=$?
        [ $RETVAL = 0 ] && action
}

stop() {
    #echo  $"Stopping unison_inotify ... "
    kill $procID  >/dev/null 2>&1
    RETVAL=$?
    [ $RETVAL = 0 ] && echo  "Stopping unison_inotify...  `action`" || echo 'unison_inotify(PID) is not run'
}
status() {
    check_proc=`ps aux |grep inotify-unison.sh |grep -v grep|awk '{print $2}'|wc -l`    
    if [ $check_proc -ne 0 ]
      then
       echo 'unison_inotify is running'
    else
       echo 'unison_inotify is not run'
    fi
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  status)
    status
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo $"Usage: $prog {start|stop|status}"
    RETVAL=2
esac

exit $RETVAL

[root@VM_0_15_centos ~]# 

服務腳本使用效果

5. inotify優缺點

優勢:   監控文件系統事件變化, 經過同步工具實現實時數據同步.

缺點:

1.  併發若是大於200個文件 ( 10-100K ), 同步就會有延遲.

2. 待續...

相關文章
相關標籤/搜索