2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

lsyncdでWindowsとNASのデータを同期する

Last updated at Posted at 2019-11-19

バックアップ用ストレージにユーザープロファイルを同期することは、データ消失を防止する上で非常に重要ですが、WindowsにおいてはWindows10標準搭載の「ファイル履歴」を含め、SMB経由での同期しか行うことができないため非常に低速となります。
そこで、Unix用のファイル同期ソリューションであるrsyncを用いて同期を高速化することを考えます。

rsyncをwindowsで使う

ファイル同期においてrsyncの右に出るものはいません。
ひとたびNASにrsyncサーバーを立ててしまえば、

$ rsync -avh ~/ rsync://192.168.0.123/home/

のように書けばすぐにNASのhomeモジュール内にホームディレクトリのファイルが全て同期されます。
しかも、転送する必要のあるファイルしかやり取りしないため、robocopy+SMBなどによる転送とは比べ物にならないくらい高速です。

しかし、当然ながらrsyncはunix向けのソフトウェアでありwindowsでは利用することができません。

rsync on WSL

しかし、Windows10をお使いならば心配は無用です。
Windows Subsystem for Linuxは実際rsyncを実行するのに十分なシステムコールを備えており、
以下のコマンドによるホームディレクトリの同期はうまく動作します。

$ sudo apt -y install rsync
$ rsync -avh --exclude '/AppData/' /mnt/c/Users/hoge/ rsync://192.168.0.123/home/

lsyncdでリアルタイム同期

rsyncでは明示的にコマンドを実行しない限り同期が行われませんでしたが、
これをinotifyやfseventsなどを活用してリアルタイムに行うデーモン「lsyncd」が存在します。

例えば、以下のようなコンフィグを記述します。

/etc/lsyncd.conf
settings {
    logfile = "/var/log/lsyncd.log",
    statusFile = "/tmp/lsyncd.stat",
    insist = true,
    nodaemon = true,
}
sync {
    default.rsync,
    delay = 0,
    source = "/mnt/c/Users/hoge/",
    target = "rsync://192.168.0.123/home/",
    exclude = { "/AppData/" },
    rsync = {
        archive = true,
        links = true,
        update = true,
        verbose = true,
    },
}

WSLにlsyncdをインストールします。

$ sudo apt -y install lsyncd

デーモンを開始するためのコマンドラインは以下のとおりです。

$ sudo lsyncd -pidfile /run/lsyncd.pid /etc/lsyncd.conf
16:58:59 Normal: --- Startup ---
16:58:59 Normal: recursive startup rsync: /mnt/c/Users/hoge/ -> rsync://192.168.0.123/homes/ excluding
/AppData/
sending incremental file list
sent 1,152 bytes  received 21,533 bytes  817.28 bytes/sec
total size is 15,899,217,862  speedup is 5470.29
16:59:34 Normal: Startup of /mnt/c/Users/hoge/ -> rsync://192.168.0.123/homes/ finished.

これはinotifyを用いてファイルの変更を検知します。例えば、

$ echo 'hello' > /mnt/c/Users/hoge/test.txt

と実行すると、以下のようなログが出力されます。

lsyncd
17:07:43 Normal: Calling rsync with filter-list of new/modified files/dirs
/test.txt
/
sending incremental file list
./
test.txt
sent 155 bytes  received 37 bytes 122.67 bytes/sec
total size is 0  speedup is 0.00
17:07:44 Normal: Finished a list after exitcode: 0

このようにリアルタイムにユーザープロファイルを同期することが可能です。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?