天天看点

Linux文件实时同步--inotify + rsync + pyinotify

   本文介绍下用法、注意事项、pyinotify多进程实现数据同步

   Inotify的出身:

   Linux 桌面系统与 MAC 或 Windows 相比有许多不如人意的地方,为了改善这种状况,开源社区提出用户态需要内核提供一些机制,以便用户态能够及时地得知内核或底层硬件设备发生了什么从而能够更好地管理设备,给用户提供更好的服务。inotify 是一种文件系统的变化通知机制,如文件增加、删除等事件可以立刻让用户态得知,该机制是著名的桌面搜索引擎项目 beagle 引入的,并在 Gamin 等项目中被应用。

   Inotify优点:

   之前的一种机制:dnotify有很多缺陷,被监视的目录都会导致过多的文件描述符,对于移动存储设备无法umount;监控对象基于目录,对于文件的变化需要缓存更多的stat结构数据。实现接口使用signal不是很友好;

   1、Inotify 不需要对被监视的目标打开文件描述符,而且如果被监视目标在可移动介质上,那么在 umount 该介质上的文件系统后,被监视目标对应的 watch 将被自动删除,并且会产生一个 umount 事件。

   2、Inotify 既可以监视文件,也可以监视目录

   3、Inotify 使用系统调用而非 SIGIO 来通知文件系统事件。

   4、Inotify 使用文件描述符作为接口,因而可以使用通常的文件 I/O 操作select 和 poll 来监视文件系统的变化。

   Inotify 可以监视的文件系统事件包括:

   IN_ACCESS,即文件被访问

   IN_MODIFY,文件被 write

   IN_ATTRIB,文件属性被修改,如 chmod、chown、touch 等

   IN_CLOSE_WRITE,可写文件被 close

   IN_CLOSE_NOWRITE,不可写文件被 close

   IN_OPEN,文件被 open

   IN_MOVED_FROM,文件被移走,如 mv

   IN_MOVED_TO,文件被移来,如 mv、cp

   IN_CREATE,创建新文件

   IN_DELETE,文件被删除,如 rm

   IN_DELETE_SELF,自删除,即一个可执行文件在执行时删除自己

   IN_MOVE_SELF,自移动,即一个可执行文件在执行时移动自己

   IN_UNMOUNT,宿主文件系统被 umount

   IN_CLOSE,文件被关闭,等同于(IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)

   IN_MOVE,文件被移动,等同于(IN_MOVED_FROM | IN_MOVED_TO)

   查看内核是否支持inotify机制

   grep INOTIFY_USER /boot/config-$(uname -r)

   输出:CONFIG_INOTIFY_USER=y 表示支持inotify机制

   安装部分:<code>yum install inotify-tools (版本为3.13)</code>

   inotify-tools包含两个工具inotifywait(监测事件的发生);inotifywatch(事件变化统计)

   使用方法:

   可以通过man 解决:man inotifywait;man inotifywatch;man inotify

   相关参数设置:

/proc/sys/fs/inotify/max_queued_events 被监测对象的队列最大数(对于较多文件的情况,适当增大)  

  /proc/sys/fs/inotify/max_user_instances 被监测对象最大数,默认为8192

   官方简单脚本举例:

   该脚本简单的精妙,但也存在不少不足;

   1、脚本执行为单进程,对于含有多个文件的情况需要考虑并发执行

   2、wait会产生很多冗余事件;比如对于在文件中写数据,打开文件都会产生临时文件a`或者a.swp  a.swpx 文件,让rsync产生更多的冗余计算;

   3、错误处理机制,脚本出现错误的处理的问题,比如rsync 连接失败,是否隔一段时间重连等?

   但为了方便,个人使用了pyinotify 模块实现以上功能:

   代码示例为:

   稍后填充!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

<code>#!/usr/bin/env python</code>

<code>#encoding=utf8</code>

<code>import</code> <code>os</code>

<code>import</code> <code>subprocess</code>

<code>import</code> <code>time</code>

<code>import</code> <code>sys</code>

<code>from</code>  <code>pyinotify </code><code>import</code>  <code>WatchManager, Notifier,ProcessEvent,IN_DELETE, IN_CREATE,IN_MODIFY</code>

<code>class</code> <code>rsync_file_cmd():</code>

<code>    </code><code>def</code> <code>__init__(</code><code>self</code><code>,src_file,dst,dst_file):</code>

<code>        </code><code>self</code><code>.src_file</code><code>=</code><code>src_file</code>

<code>        </code><code>self</code><code>.dst</code><code>=</code><code>dst</code>

<code>        </code><code>self</code><code>.dst_file</code><code>=</code><code>dst_file</code>

<code>        </code><code>self</code><code>.cmd</code><code>=</code><code>'rsync -arz --timeout=60 -e "ssh -p 22" %s %s:%s'</code> <code>%</code><code>(</code><code>self</code><code>.src_file,</code><code>self</code><code>.dst,</code><code>self</code><code>.dst_file)</code>

<code>        </code><code>self</code><code>.del_cmd</code><code>=</code><code>'ssh -p 22  %s "rm -rf %s"'</code> <code>%</code> <code>(</code><code>self</code><code>.dst,</code><code>self</code><code>.dst_file)</code>

<code>class</code> <code>EventHandler(ProcessEvent):</code>

<code>    </code><code>"""Handle"""</code>

<code>    </code><code>def</code> <code>process_IN_CREATE(</code><code>self</code><code>, event):</code>

<code>        </code><code>if</code> <code>event.name.startswith(</code><code>'.'</code><code>) </code><code>or</code> <code>event.name.endswith(</code><code>'~'</code><code>) </code><code>or</code> <code>event.name</code><code>=</code><code>=</code><code>'4913'</code><code>:</code>

<code>            </code><code>pass</code>

<code>        </code><code>else</code><code>:</code>

<code>            </code><code>create_sync</code><code>=</code><code>rsync_file_cmd(</code><code>str</code><code>(event.pathname),</code><code>'[email protected]'</code><code>,</code><code>str</code><code>(event.pathname))</code>

<code>            </code><code>subprocess.call(create_sync.cmd,shell</code><code>=</code><code>True</code><code>)</code>

<code>    </code><code>def</code> <code>process_IN_DELETE(</code><code>self</code><code>, event):</code>

<code>            </code><code>delete_sync</code><code>=</code><code>rsync_file_cmd(</code><code>str</code><code>(event.pathname),</code><code>'[email protected]'</code><code>,</code><code>str</code><code>(event.pathname))</code>

<code>            </code><code>subprocess.call(delete_sync.del_cmd,shell</code><code>=</code><code>True</code><code>)</code>

<code>    </code><code>def</code> <code>process_IN_MODIFY(</code><code>self</code><code>, event):</code>

<code>            </code><code>modify_sync</code><code>=</code><code>rsync_file_cmd(</code><code>str</code><code>(event.pathname),</code><code>'[email protected]'</code><code>,</code><code>str</code><code>(event.pathname))</code>

<code>            </code><code>subprocess.call(modify_sync.cmd,shell</code><code>=</code><code>True</code><code>)</code>

<code>def</code> <code>FSMonitor(path</code><code>=</code><code>'/root/wpf'</code><code>):</code>

<code>        </code><code>wm </code><code>=</code> <code>WatchManager()</code>

<code>        </code><code>mask </code><code>=</code> <code>IN_DELETE | IN_MODIFY | IN_CREATE</code>

<code>        </code><code>notifier </code><code>=</code> <code>Notifier(wm, EventHandler(),read_freq</code><code>=</code><code>10</code><code>)</code>

<code>        </code><code>notifier.coalesce_events()</code>

<code>        </code><code># 设置受监视的事件,这里只监视文件创建事件,(rec=True, auto_add=True)为递归处理</code>

<code>        </code><code>wm.add_watch(path,mask,rec</code><code>=</code><code>True</code><code>, auto_add</code><code>=</code><code>True</code><code>)</code>

<code>        </code><code>notifier.loop()</code>

<code>if</code> <code>__name__</code><code>=</code><code>=</code><code>'__main__'</code><code>:</code>

<code>    </code><code>try</code><code>:</code>

<code>        </code><code>pid </code><code>=</code> <code>os.fork()</code>

<code>        </code><code>if</code> <code>pid &gt; </code><code>0</code><code>:</code>

<code>            </code><code>sys.exit(</code><code>0</code><code>)</code>

<code>    </code><code>except</code> <code>OSError, e:</code>

<code>        </code><code>print</code> <code>&gt;&gt;sys.stderr, </code><code>'fork failed: %d (%s)'</code> <code>%</code> <code>(e.errno, e.strerror)</code>

<code>        </code><code>sys.exit(</code><code>1</code><code>)</code>

<code>    </code><code>os.setsid()</code>

<code>    </code><code>os.umask(</code><code>0</code><code>)</code>

<code>    </code><code>FSMonitor()</code>

<code>    </code><code>print</code> <code>'start!'</code>

本文转自 位鹏飞 51CTO博客,原文链接:http://blog.51cto.com/weipengfei/1195019,如需转载请自行联系原作者

继续阅读