#!/usr/bin/env python
#
 encoding:utf-8
#
 zhangtao 2016/07-28
#
 monit the change of file;
#
if file is modified,send httpGet request to service,then service reload config
#
############################################ 
import os
import urllib2
from urllib2 import URLError, HTTPError
from  pyinotify import  WatchManager, Notifier, ProcessEvent,IN_DELETE, IN_CREATE,IN_MODIFY
import threading
from  debuglogger import * 

config_urls=["http://127.0.0.1:6001/chelun?query=reload1","http://127.0.0.1:6001/chelun?query=reload2","http://127.0.0.1:6001/chelun?query=reload3"]
config_files=["service:dispatch.conf","service:proxy.conf","service:qc.conf"]
config_flags=[0,0,0]
config_timer=0
pid_file="run/daemon.pid"

def doGet(url):        
    request = urllib2.Request(url)
    try:
        response = urllib2.urlopen(request, timeout=10)
        page = response.read()
        return page        
    except URLError, e:
        if hasattr(e, 'code'):
            s='The server couldn\'t fulfill the request. errorcode:{0} url:{1}'.format(e.code,url)
            return s
        elif hasattr(e, 'reason'):
            s='We failed to reach a server. reason:{0} url:{1}'.format(e.reason,url)
        return s
    return "Error"
      

def func():
    global config_files
    global config_flags
    global config_urls
    global config_timer
    config_timer=0
    for i in xrange(3):
        if 1==config_flags[i]:
            result=doGet(config_urls[i])
            config_flags[i]=0
            s="fileChange:{0} triggerUrl:{1} rspResult:{2}".format( config_files[i],config_urls[i],result  )
            Logger.dumplog(s)

def startTimer():
    global config_timer
    if config_timer != 0:
        return
    config_timer=1
    timer = threading.Timer(5, func)
    timer.start()

class EventHandler(ProcessEvent):
  """事件处理"""
  def process_IN_CREATE(self, event):
    #print   "Create file: %s "  %   os.path.join(event.path,event.name)
    pass
 
  def process_IN_DELETE(self, event):
    #print   "Delete file: %s "  %   os.path.join(event.path,event.name)
    pass

  def process_IN_MODIFY(self, event):
    #print   "Modify file: %s "  %   os.path.join(event.path,event.name)
    pass
    if   "service:dispatch.conf" == event.name:
        config_flags[0] = 1
        startTimer()
    elif "service:proxy.conf" == event.name:
        config_flags[1] = 1
        startTimer()
    elif "service:qc.conf" == event.name:
        config_flags[2] = 1
        startTimer()
 
def FSMonitor(path='.'):
    wm = WatchManager() 
    #mask = IN_DELETE | IN_CREATE |IN_MODIFY
    mask = IN_MODIFY
    notifier = Notifier(wm, EventHandler())
    wm.add_watch(path, mask,auto_add=True,rec=True)
    s= 'now starting monitor %s'%(path)
    Logger.dumplog(s)
    pid=str( os.getpid() )
    with open(pid_file,"w") as f:
    f.write( pid  )    
    s="pid:{0}".format(pid)
    Logger.dumplog( s)

    while True:
      try:
          notifier.process_events()
          if notifier.check_events():
              notifier.read_events()
      except KeyboardInterrupt:
          notifier.stop()
          break


if __name__ == "__main__":
  FSMonitor('/data/config/')