Guest User

Untitled

a guest
Jul 21st, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. # -*- coding: utf8 -*-
  2.  
  3. import datetime, os
  4.  
  5. class MongoDbExporter(object):
  6.  
  7. """
  8. a tiny wrapper for the bash utility named mongoexporter.
  9. """
  10.  
  11. LOCK_FILE = 'log.txt'
  12.  
  13. def __init__(self, config):
  14. self.host = config.get("host"),
  15. self.database = config.get("database")
  16. self.collection = config.get("collection")
  17. self.backup_dir = config.get("backup_dir")
  18.  
  19. if self.backup_dir:
  20. if not self.backup_dir.endswith('/'):
  21. self.backup_dir += "/"
  22. self.backup_file = self.backup_dir + self.__generateBackupDate() + ".json"
  23. if not os.access(os.getcwd(), os.W_OK):
  24. raise Exception("i cannot create lock file. make this directory writable.")
  25.  
  26. self.__controlConfig(config)
  27.  
  28. def backUp(self):
  29. print "started"
  30.  
  31. self.__createLock()
  32. command = "mongoexport -c %s -d %s >> %s" % (self.collection,
  33. self.database,
  34. self.backup_file)
  35. os.system(command)
  36. self.__acquireLock()
  37.  
  38. def __controlConfig(self, config):
  39. for config_variable in config.iterkeys():
  40. if config.get(config_variable) == None:
  41. raise Exception("%s cannot be empty" % config_variable)
  42.  
  43. if not config.get("backup_dir").startswith("/"):
  44. raise Exception("backup_dir variable must be absolute.")
  45.  
  46. if not os.path.exists(config.get("backup_dir")):
  47. print "backup directory doesnt exist, trying to create."
  48. os.makedirs(config.get("backup_dir"))
  49.  
  50. def __generateBackupDate(self):
  51. dt = datetime.datetime.now()
  52. return datetime.datetime.strftime(dt, "%Y-%m-%d-%H-%M")
  53.  
  54. def __createLock(self):
  55. self.__controlLock()
  56. print "creating lock file"
  57. fp = open(MongoDbExporter.LOCK_FILE, 'w')
  58. fp.close()
  59.  
  60. def __acquireLock(self):
  61. print "lock acquired"
  62. os.remove(MongoDbExporter.LOCK_FILE)
  63.  
  64. def __controlLock(self):
  65. if os.path.exists(MongoDbExporter.LOCK_FILE):
  66. raise Exception("an alive dumper instance exists. try later.")
  67.  
  68. if __name__ == '__main__':
  69. backup = MongoDbExporter({
  70. "host" : "localhost",
  71. "database" : "test",
  72. "collection" : "logs",
  73. "backup_dir" : "/home/emre/tmp/"
  74. })
  75.  
  76. backup.backUp()
Add Comment
Please, Sign In to add comment