Advertisement
Guest User

Directory monitor

a guest
Sep 3rd, 2010
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.42 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # ----------------------------------------------------------------------------
  4. # Copyright (c) 2010, Asim Ihsan
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. # THE SOFTWARE.
  23. # ----------------------------------------------------------------------------
  24.  
  25. import os
  26. import sys
  27. import time
  28. import pprint
  29. import logging
  30. import datetime
  31. import glob
  32. import shutil
  33.  
  34. # ----------------------------------------------------------------------------
  35. #   Constants to change.
  36. # ----------------------------------------------------------------------------
  37.  
  38. DIRECTORIES = [r"/tmp/dir1",
  39.                r"/tmp/dir2",
  40.               ]
  41.  
  42. DESTINATION = r"/Volumes/MONGOOSE/temp"
  43.  
  44. CHECK_INTERVAL = 15 * 60 # 15 minutes
  45. RETRY_TIME = 30 * 60 # 30 minutes
  46.  
  47. START_TIME = datetime.time(hour=21, minute=0)
  48. END_TIME = datetime.time(hour=23, minute=0)
  49.  
  50. # ----------------------------------------------------------------------------
  51.  
  52. # ----------------------------------------------------------------------------
  53. #   Other constants, leave alone.
  54. # ----------------------------------------------------------------------------
  55.  
  56. # ----------------------------------------------------------------------------
  57.  
  58. # create logger
  59. logger = logging.getLogger("monitor_directory")
  60. logger.setLevel(logging.DEBUG)
  61.  
  62. # create console handler and set level to debug
  63. ch = logging.StreamHandler()
  64. ch.setLevel(logging.DEBUG)
  65.  
  66. # create formatter
  67. formatter = logging.Formatter("%(asctime)s - %(message)s")
  68.  
  69. # add formatter to ch
  70. ch.setFormatter(formatter)
  71.  
  72. # add ch to logger
  73. logger.addHandler(ch)
  74.  
  75. if __name__ == "__main__":
  76.     logger.debug("making sure directories exist...")
  77.     if any(not os.path.isdir(directory) for directory in DIRECTORIES):
  78.         for directory in DIRECTORIES:
  79.             if not os.path.isdir(directory):
  80.                 logger.error("directory '%s' does not exist" % (directory, ))
  81.         sys.exit(1)
  82.     if not os.path.isdir(DESTINATION):
  83.         logger.error("destination directory '%s' does not exist" % (directory, ))
  84.         sys.exit(1)
  85.     logger.debug("all directories exist")
  86.  
  87.     logger.info("starting to monitor the following directories:\n'%s'" % (pprint.pformat(DIRECTORIES), ))
  88.     while 1:
  89.         time_now = datetime.datetime.now().time()
  90.         if time_now < START_TIME or time_now > END_TIME:
  91.             logger.debug("not the right time.  will try again later.")
  92.             time.sleep(RETRY_TIME)
  93.             continue
  94.         logger.debug("correct time period. what's new?")
  95.         remote_files = [(path, os.stat(path).st_mtime) for subdir in DIRECTORIES for path in glob.glob(os.path.join(subdir, "*"))]
  96.         local_files = [(path, os.stat(path).st_mtime) for path in glob.glob(os.path.join(DESTINATION, "*"))]
  97.        
  98.         local_base_lookup = dict([(os.path.basename(path), m_time) for (path, m_time) in local_files])
  99.         today = datetime.date.today()
  100.         for (remote_path, remote_m_time) in remote_files:
  101.             logger.debug("considering %s..." % (remote_path, ))
  102.             # do not consider files that have not been modified today.
  103.             if datetime.datetime.fromtimestamp(remote_m_time).date() != today:
  104.                 logger.debug("remote file %s too old" % (remote_path, ))
  105.                 continue
  106.  
  107.             if os.path.basename(remote_path) not in local_base_lookup:
  108.                 logger.debug("remote path %s does not exist locally. will copy." % (remote_path, ))
  109.                 dest = os.path.join(DESTINATION, os.path.basename(remote_path))
  110.                 if os.path.isdir(remote_path):
  111.                     shutil.copytree(remote_path, dest)
  112.                 else:
  113.                     shutil.copy2(remote_path, dest)
  114.             #elif remote_m_time > local_base_lookup[os.path.basename(remote_path)]:
  115.             #    logger.debug("remote path %s exists locally but is newer.  will overwrite." % (remote_path, ))
  116.             #    if os.path.isdir(remote_path):
  117.             #        shutil.rmtree(os.path.join(local_base_lookup[os.path.basename(remote_path)]))
  118.             #    else:
  119.             #        os.delete(os.path.join(local_base_lookup[os.path.basename(remote_path)]))
  120.             #    if os.path.isdir(remote_path):
  121.             #        shutil.copytree(remote_path, dest)
  122.             #    else:
  123.             #        shutil.copy2(remote_path, dest)
  124.                
  125.         logger.debug("finished this interval, sleeping...")
  126.         time.sleep(CHECK_INTERVAL)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement