python pyinotify模塊詳解


轉載於http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=23504396&id=2929446
1年多前就看過相關內容了,當時python還不太會用看不懂別人寫的代碼,最近閑着又翻出來看看順便解讀下pyinotify的代碼

使用源自於
http://blog.daviesliu.net/2008/04/24/sync/

這里的代碼有2個錯誤,一個是base多定義了一次,另外就是有幾行縮進好像有點問題,需要自己控制下縮進

一行一行解讀
  1. flags = IN_CLOSE_WRITE|IN_CREATE|IN_Q_OVERFLOW
這里flags的值是int行的,這里原來我半天沒看懂。
如果寫成
flags = pyinotify.IN_DELETE | pyinotify.IN_CREATE就好懂多了,這里用幾個監控的類型的int值進行邏輯運算成監控需要監控的改變類型的數值具體數值怎么定義可以看 看pyinotify.py文件中的class EventsCodes:中定義FLAG_COLLECTIONS的數值

dirs = {}
定義一個空的字典
base = '/log/lighttpd/cache/images/icon/u241'
這里定義了需要監控的文件夾,注意上面連接代碼里有個base,自然是原作者忘記注釋了其中一個,我們改成/tmp來測試

class UpdateParentDir(ProcessEvent):這里之前看不懂,特別是下面的process_IN_CLOSE_WRITE(self, event):,都不知道event哪里來的因為以前學c么什么函數重載,類的重載。這里其實就是什么派生重載子類而已

我們先看在pyinotify.py里看ProcessEvent這個類,這個類繼承自_ProcessEvent這個類...,於是先去瞅瞅_ProcessEvent這個類
_ProcessEvent這個類沒有init方法,只有__call__方法,call方法相當於重載了(),具體我們可以測試,我們先call方法里加入print "++++++++++++"
到最后我們再看結果,先跳過

繼續看ProcessEvent類的init方法
  1. def __init__(self, pevent=None, **kargs):
  2.     self.pevent = pevent
  3.     self.my_init(**kargs)
這個init方法也很簡單,不賦值也沒有問題self.my_init(**kargs)是留給我們自己寫方法擴展的,可以不理會。所以這個init方法也沒什么好看鳥。

我們可以直接看別人重載的方法在源代碼pyinotify.py中的樣子
  1. def process_IN_Q_OVERFLOW(self, event):
  2.     log.warning('Event queue overflowed.')
  3.     
  4. def process_default(self, event):
  5.     pass
非常明了,不重載之前,原函數只是把對應變化寫入log中,重載之后我們可以根據變化做自己想要的操作,比如備份改變的文件,或做同步操作之類。

現在重點是那個event,init里有說明type event: Event instance,不過UpdateParentDir還沒開始調用,所以我們先放下Event模塊不看。

先看下面的wm = WatchManager()
  1. class WatchManager:
  2.     def __init__(self, exclude_filter=lambda path: False):
  3.     self._fd = self._inotify_wrapper.inotify_init()
init里主要看self._fd
這個fd是返回inotify監控的節點滴,這里調用了c封裝的_inotify_wrapper,應該是初始化監控對象
WatchManager在監控代碼中也沒傳參數,看到后面代碼這個類還是通過類的add_watch方法傳入內容的,看add_watch方法
  1. def add_watch(self, path, mask, proc_fun=None, rec=False,
  2.                   auto_add=False, do_glob=False, quiet=True,
  3.                   exclude_filter=None):
這個方法主要是把path(也是就代碼中的base指定的目錄)格式化后傳入,然后返回個path中內容的字典,監控工作還是沒開始。
  1. wd = ret_[rpath] = self.__add_watch(rpath, mask,
  2.                                                             proc_fun,
  3.                                                             auto_add,
  4.                                                             exclude_filter)
add_watch里還調用了__add_watch,__add_watch里面又調用了watch方法,這里主要是從_inotify_wrapper這個c封裝中獲得inotify的對象

現在可以看把WatchManager和ProcessEvent聯系起來的Notifier類了
  1. class Notifier:
  2.     def __init__(self, watch_manager, default_proc_fun=None, read_freq=0,
  3.                  threshold=0, timeout=None):
  4.         """        
  5.         @type watch_manager: WatchManager instance        
  6.         @param default_proc_fun: Default processing method. If None, a new
  7.                                  instance of PrintAllEvents will be assigned.        
  8.         @type default_proc_fun: instance of ProcessEvent
  9.          """
  10.         # Watch Manager instance
  11.         self._watch_manager = watch_manager
  12.         # File descriptor
  13.         self._fd = self._watch_manager.get_fd()
  14.         # Poll object and registration
  15.         self._pollobj = select.poll()
  16.         self._pollobj.register(self._fd, select.POLLIN)
  17.         # This pipe is correctely initialized and used by ThreadedNotifier
  18.         self._pipe = (-1, -1)
  19.         # Event queue
  20.         self._eventq = deque()
  21.         # System processing functor, common to all events
  22.         self._sys_proc_fun = _SysProcessEvent(self._watch_manager, self)
  23.         # Default processing method
  24.         self._default_proc_fun = default_proc_fun
  25.         if default_proc_fun is None:
  26.             self._default_proc_fun = PrintAllEvents()
  27.         # Loop parameters
  28.         self._read_freq = read_freq
  29.         self._threshold = threshold
  30.         self._timeout = timeout
  31.         # Coalesce events option
  32.         self._coalesce = False
  33.         # set of str(raw_event), only used when coalesce option is True
  34.         self._eventset = set()
Notifier類傳入一個wm類和ProcessEvent類,我們來自己看看init方法代碼

  1. self._fd = self._watch_manager.get_fd()
這里看上面WatchManager類的self._fd

  1. self._pollobj = select.poll()
這里就是重點了,poll模型,寫過socket的應該知道,異步非阻塞,這里可以看出處理消息方式了
shell中使用while read,這里使用poll模型,效率差距立判了。
python2.7以上才有epoll模型,高版本pyinotify應該會使用epoll模型,如果python版本高,應該自己可以修改這里的代碼來使用epoll

  1. self._sys_proc_fun = _SysProcessEvent(self._watch_manager, self)
再調用_SysProcessEvent類,這個類是ProcessEvent的父類,到下面才好理解這個是干嘛的 

  1. self._default_proc_fun = default_proc_fun
這里就是我們傳入的ProcessEvent類,self._default_proc_fun和self._sys_proc_fun分別在什么情況下用要下面代碼才看得出來

init里其他的就不說了,定義隊列超時時間之類
ok,到Notifier類初始化完畢,我們的監控都還么正式開始,只是打開了入口(即self._fd = self._inotify_wrapper.inotify_init())
至於dirs.update(wm.add_watch(base, flags, rec=True, auto_add=True))這里當dirs不存在好了,因為wm.add_watch方法會返回一個監控目錄根目錄內容的字典
所以用了個dirs來裝返回值,其實沒有也無所謂。

正式開始是在notifier.loop() 
我們來看Notifier類的loop方法
  1. def loop(self, callback=None, daemonize=False, **args):
  2.         """
  3.         Events are read only one time every min(read_freq, timeout)
  4.         seconds at best and only if the size to read is >= threshold.
  5.         After this method returns it must not be called again for the same
  6.         instance.

  7.         @param callback: Functor called after each event processing iteration.
  8.                          Expects to receive the notifier object (self) as first
  9.                          parameter. If this function returns True the loop is
  10.                          immediately terminated otherwise the loop method keeps
  11.                          looping.
  12.         @type callback: callable object or function
  13.         @param daemonize: This thread is daemonized if set to True.
  14.         @type daemonize: boolean
  15.         @param args: Optional and relevant only if daemonize is True. Remaining
  16.                      keyworded arguments are directly passed to daemonize see
  17.                      __daemonize() method. If pid_file=None or is set to a
  18.                      pathname the caller must ensure the file does not exist
  19.                      before this method is called otherwise an exception
  20.                      pyinotify.NotifierError will be raised. If pid_file=False
  21.                      it is still daemonized but the pid is not written in any
  22.                      file.
  23.         @type args: various
  24.         """
  25.         if daemonize:
  26.             self.__daemonize(**args)

  27.         # Read and process events forever
  28.         while 1:
  29.             try:
  30.                 self.process_events()
  31.                 if (callback is not None) and (callback(self) is True):
  32.                     break
  33.                 ref_time = time.time()
  34.                 # check_events is blocking
  35.                 if self.check_events():
  36.                     self._sleep(ref_time)
  37.                     self.read_events()
  38.             except KeyboardInterrupt:
  39.                 # Stop monitoring if sigint is caught (Control-C).
  40.                 log.debug('Pyinotify stops monitoring.')
  41.                 break
  42.         # Close internals
  43.         self.stop()
我們一行一行的看loop的代碼
loop傳入的參數daemonize可以看daemonize方法,這個其實就是把進程變守護進程的方法,這個和普通守護進程方法差不多
無非就是fork兩次setsid父進程退出一類
callback也沒什么大用貌似用來自定義的,跳過
下面終於看見while 1了我們的監控開始
 
loop的循環里首先try process_events方法,於是去看process_events方法
  1. def process_events(self):
  2.         """
  3.         Routine for processing events from queue by calling their
  4.         associated proccessing method (an instance of ProcessEvent).
  5.         It also does internal processings, to keep the system updated.
  6.         """
  7.         while self._eventq:
  8.             raw_event = self._eventq.popleft() # pop next event
  9.             watch_ = self._watch_manager.get_watch(raw_event.wd)
  10.             if watch_ is None:
  11.                 # Not really sure how we ended up here, nor how we should
  12.                 # handle these types of events and if it is appropriate to
  13.                 # completly skip them (like we are doing here).
  14.                 log.warning("Unable to retrieve Watch object associated to %s",
  15.                             repr(raw_event))
  16.                 continue
  17.             revent = self._sys_proc_fun(raw_event) # system processings
  18.             if watch_ and watch_.proc_fun:
  19.                 watch_.proc_fun(revent) # user processings
  20.             else:
  21.                 self._default_proc_fun(revent)
  22.         self._sys_proc_fun.cleanup() # remove olds MOVED_* events records
  23.         if self._coalesce:
  24.             self._eventset.clear()
由於第一次執行的時候self._eventq隊列里肯定沒東西是空的我們先跳過process_events看loop方法后面的代碼
  1. if (callback is not None) and (callback(self) is True):
  2.     break
  3. ref_time = time.time()
這兩行簡單,跳過
if self.check_events():
這里可以看check_events():方法,可以看見
  1. def check_events(self, timeout=None):
  2.         """
  3.         Check for new events available to read, blocks up to timeout
  4.         milliseconds.

  5.         @param timeout: If specified it overrides the corresponding instance
  6.                         attribute _timeout.
  7.         @type timeout: int

  8.         @return: New events to read.
  9.         @rtype: bool
  10.         """
  11.         while True:
  12.             try:
  13.                 # blocks up to 'timeout' milliseconds
  14.                 if timeout is None:
  15.                     timeout = self._timeout
  16.                 ret = self._pollobj.poll(timeout)
  17.             except select.error, err:
  18.                 if err[0] == errno.EINTR:
  19.                     continue # interrupted, retry
  20.                 else:
  21.                     raise
  22.             else:
  23.                 break

  24.         if not ret or (self._pipe[0] == ret[0][0]):
  25.             return False
  26.         # only one fd is polled
  27.         return ret[0][1] & select.POLLIN
check_events就是處理poll的,poll具體怎么用可以google的poll用法,我只用過select所以不太熟悉poll,但是原理是一樣的
其實loop里的while 1這里就相當於我以前寫select的
  1. while True:
  2.             GetList,SendList,ErrList = select.select([self.socket,],[],[],0)
  3.             if len(GetList) > 0:
  4.                 try:
  5.                     curSock,userAddr = self.socket.accept()
  6. # curSock.settimeout(15)
  7.                     self.socket_pool.append(curSock)
  8.                     print "get new socket"
  9.                 except:
  10.                     print "error or time out"

  11.             get_sock_pool,send_sock_pool,err_sock_pool = select.select(self.socket_pool,[],[],0)
這樣的代碼了,不停的掃描socket緩沖區,當返回值大於0就接受數據。
loop也是一樣,不過用的是poll模型加deque隊列(deque隊列其實和list差不多,不過比list靈活,可以從兩端彈出、插入數值,list只能從后面插)

check完了就read
  1. def read_events(self):
  2.         """
  3.         Read events from device, build _RawEvents, and enqueue them.
  4.         """
  5.         buf_ = array.array('i', [0])
  6.         # get event queue size
  7.         if fcntl.ioctl(self._fd, termios.FIONREAD, buf_, 1) == -1:
  8.             return
  9.         queue_size = buf_[0]
  10.         if queue_size < self._threshold:
  11.             log.debug('(fd: %d) %d bytes available to read but threshold is '
  12.                       'fixed to %d bytes', self._fd, queue_size,
  13.                       self._threshold)
  14.             return

  15.         try:
  16.             # Read content from file
  17.             r = os.read(self._fd, queue_size)
  18.         except Exception, msg:
  19.             raise NotifierError(msg)
  20.         log.debug('Event queue size: %d', queue_size)
  21.         rsum = 0 # counter
  22.         while rsum < queue_size:
  23.             s_size = 16
  24.             # Retrieve wd, mask, cookie and fname_len
  25.             wd, mask, cookie, fname_len = struct.unpack('iIII',
  26.                                                         r[rsum:rsum+s_size])
  27.             # Retrieve name
  28.             fname, = struct.unpack('%ds' % fname_len,
  29.                                    r[rsum + s_size:rsum + s_size + fname_len])
  30.             rawevent = _RawEvent(wd, mask, cookie, fname)
  31.             if self._coalesce:
  32.                 # Only enqueue new (unique) events.
  33.                 raweventstr = str(rawevent)
  34.                 if raweventstr not in self._eventset:
  35.                     self._eventset.add(raweventstr)
  36.                     self._eventq.append(rawevent)
  37.             else:
  38.                 self._eventq.append(rawevent)
  39.             rsum += s_size + fname_len
這兩個函數都和poll有關,看不懂無所謂,但是大概可以知道這里就是poll使得self._eventq()中有數據(就是把變化的內容傳入隊列)
read_events后process_events函數就能執行了。
看process_events中有數據以后的執行方式

當self._eventq有內容內容以后


  1. raw_event = self._eventq.popleft()
彈出隊列中的內容,這個raw_event就是Event類


  1. watch_ = self._watch_manager.get_watch(raw_event.wd)
通過剛才彈出的對象返回inotify對象


  1. if watch_ is None:
通過上面返回值判斷是否被監控,這個判斷保險用的,當作不存在


  1. revent = self._sys_proc_fun(raw_event)
創建個叫revent的_SysProcessEvent類,這個類傳入的參數raw_event是個event對象,這個event就是變動的文件的相關信息


  1. if watch_ and watch_.proc_fun:
  2.     watch_.proc_fun(revent)
  3. else:
  4.     self._default_proc_fun(revent)
判斷是否把這個類丟給_default_proc_fun。
這里執行了self._default_proc_fun(revent)的話,我們在UpdateParentDir(ProcessEvent):里的方法就會執行   

_SysProcessEvent有啥用?其實沒啥用,這個類就是定義了默認的各種mark的處理方式讓傳入的類去繼承而已。
在_SysProcessEvent的process_IN_CREATE方法里加入
print "=============="


我們拿改好的代碼執行下,當創建一個文件時,出現下面打印(請無視掉caonima....謝謝)
  1. #!/usr/bin/python

  2. from pyinotify import *
  3. import os, os.path

  4. flags = IN_CLOSE_WRITE|IN_CREATE|IN_Q_OVERFLOW
  5. dirs = {}
  6. base = '/log/lighttpd/cache/images/icon/u241'
  7. base = 'tmp'

  8. class UpdateParentDir(ProcessEvent):
  9.     def process_IN_CLOSE_WRITE(self, event):
  10.         print 'modify', event.pathname
  11.         mtime = os.path.getmtime(event.pathname)
  12.         p = event.path
  13.         while p.startswith(base):
  14.             m = os.path.getmtime(p)
  15.             if m < mtime:
  16.              print 'update', p
  17.                 os.utime(p, (mtime,mtime))
  18.             elif m > mtime:
  19.                 mtime = m
  20.             p = os.path.dirname(p)
  21.     
  22.     process_IN_MODIFY = process_IN_CLOSE_WRITE

  23.     def process_IN_Q_OVERFLOW(self, event):
  24.         print 'over flow'
  25.         max_queued_events.value *= 2

  26.     def process_default(self, event):
  27.         pass

  28. wm = WatchManager()
  29. notifier = Notifier(wm, UpdateParentDir())
  30. dirs.update(wm.add_watch(base, flags, rec=True, auto_add=True))

  31. notifier.loop()
{'/tmp': 1, '/tmp/.font-unix': 4, '/tmp/.wapi': 5, '/tmp/hsperfdata_root': 2, '/tmp/.ICE-unix': 3}
+++++++++++call+++caonima++++++++++++++
============sys========caonimai============
+++++++++++call+++caonima++++++++++++++
+++++++++++call+++caonima++++++++++++++
+++++++++++call+++caonima++++++++++++++
modify /tmp/14


分析下可以知道,繼承_ProcessEvent類的時候先call了一次
在process_events方法中有revent = self._sys_proc_fun(raw_event),所以創建創的時候打印了"========"
所以后面self._default_proc_fun(revent)重載的之前,_ProcessEvent中的process_IN_CREATE 其實已經執行過了,即使后面重載process_IN_CREATE方法,原來的process_IN_CREATE
方法還是會被調用過

至於程序怎么識別process_IN_xxx之類的方法可以看_ProcessEvent里的__call__方法
  1. meth = getattr(self, 'process_' + maskname, None)
  2.     if meth is not None:
  3.         return meth(event)

  4. meth = getattr(self, 'process_IN_' + maskname.split('_')[1], None)
getattr函數很簡單,返回名為process_+ maskname的函數
后面多定義了個process_IN +maskname的函數,所以process和process_IN都是可以的函數名

這個pyinotify最重要的就是這幾個函數
  1. self._inotify_wrapper = INotifyWrapper.create()
  2.         if self._inotify_wrapper is None:
  3.             raise InotifyBindingNotFoundError()

  4.         self._fd = self._inotify_wrapper.inotify_init() # file descriptor
  5.         
  6.         
  7.          wd = self._inotify_wrapper.inotify_add_watch(self._fd, path, mask)
我們自己寫個類似pyinotify的函數來試試直接調用INotifyWrapper看看

找了下發現INotifyWrapper也是pyinotify里面定義的類,最終找到
  1. try:
  2.             libc_name = ctypes.util.find_library('c')
  3.         except (OSError, IOError):
  4.             pass # Will attemp to load it with None anyway.

  5.         if sys.version_info >= (2, 6):
  6.             self._libc = ctypes.CDLL(libc_name, use_errno=True)
  7.             self._get_errno_func = ctypes.get_errno
  8.         else:
  9.             self._libc = ctypes.CDLL(libc_name)
  10.             try:
  11.                 location = self._libc.__errno_location
  12.                 location.restype = ctypes.POINTER(ctypes.c_int)
  13.                 self._get_errno_func = lambda: location().contents.value
  14.             except AttributeError:
  15.                 pass

  16.         # Eventually check that libc has needed inotify bindings.
  17.         if (not hasattr(self._libc, 'inotify_init') or
  18.             not hasattr(self._libc, 'inotify_add_watch') or
  19.             not hasattr(self._libc, 'inotify_rm_watch')):
  20.             return False
  21.         return True
最終發現是通過ctypes.CDLL('libc.so.6')掉出inotify相關的c封裝的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM