You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

backups.py 7.2 KiB

14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
13 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. This module handles the On Demand Backup utility
  6. To setup in defs set:
  7. backup_path: path where backups will be taken (for eg /backups)
  8. backup_link_path: download link for backups (eg /var/www/wnframework/backups)
  9. backup_url: base url of the backup folder (eg http://mysite.com/backups)
  10. """
  11. #Imports
  12. import os, webnotes
  13. from datetime import datetime
  14. #Global constants
  15. verbose = 0
  16. import conf
  17. #-------------------------------------------------------------------------------
  18. class BackupGenerator:
  19. """
  20. This class contains methods to perform On Demand Backup
  21. To initialize, specify (db_name, user, password, db_file_name=None)
  22. If specifying db_file_name, also append ".sql.gz"
  23. """
  24. def __init__(self, db_name, user, password):
  25. self.db_name = db_name
  26. self.user = user
  27. self.password = password
  28. self.backup_path_files = None
  29. self.backup_path_db = None
  30. def get_backup(self, older_than=24, ignore_files=False):
  31. """
  32. Takes a new dump if existing file is old
  33. and sends the link to the file as email
  34. """
  35. #Check if file exists and is less than a day old
  36. #If not Take Dump
  37. self.get_recent_backup(older_than)
  38. if not (self.backup_path_files and self.backup_path_db):
  39. self.set_backup_file_name()
  40. self.take_dump()
  41. if not ignore_files:
  42. self.zip_files()
  43. def set_backup_file_name(self):
  44. import random
  45. todays_date = "".join(str(datetime.date(datetime.today())).split("-"))
  46. random_number = str(int(random.random()*99999999))
  47. #Generate a random name using today's date and a 8 digit random number
  48. for_db = todays_date + "_" + random_number + "_database.sql.gz"
  49. for_files = todays_date + "_" + random_number + "_files.tar"
  50. backup_path = get_backup_path()
  51. self.backup_path_db = os.path.join(backup_path, for_db)
  52. self.backup_path_files = os.path.join(backup_path, for_files)
  53. def get_recent_backup(self, older_than):
  54. file_list = os.listdir(get_backup_path())
  55. for this_file in file_list:
  56. this_file_path = os.path.join(get_backup_path(), this_file)
  57. if not is_file_old(this_file_path, older_than):
  58. if "_files" in this_file_path:
  59. self.backup_path_files = this_file_path
  60. if "_database" in this_file_path:
  61. self.backup_path_db = this_file_path
  62. def zip_files(self):
  63. files_path = os.path.join(os.path.dirname(os.path.abspath(conf.__file__)), 'public', 'files')
  64. cmd_string = """tar -cf %s %s""" % (self.backup_path_files, files_path)
  65. err, out = webnotes.utils.execute_in_shell(cmd_string)
  66. def take_dump(self):
  67. import webnotes.utils
  68. # escape reserved characters
  69. args = dict([item[0], webnotes.utils.esc(item[1], '$ ')]
  70. for item in self.__dict__.copy().items())
  71. cmd_string = """mysqldump -u %(user)s -p%(password)s %(db_name)s | gzip -c > %(backup_path_db)s""" % args
  72. err, out = webnotes.utils.execute_in_shell(cmd_string)
  73. def send_email(self):
  74. """
  75. Sends the link to backup file located at erpnext/backups
  76. """
  77. from webnotes.utils.email_lib import sendmail, get_system_managers
  78. backup_url = webnotes.conn.get_value('Website Settings',
  79. 'Website Settings', 'subdomain') or ''
  80. backup_url = os.path.join('http://' + backup_url, 'backups')
  81. recipient_list = get_system_managers()
  82. msg = """<p>Hello,</p>
  83. <p>Your backups are ready to be downloaded.</p>
  84. <p>1. <a href="%(db_backup_url)s">Click here to download\
  85. the database backup</a></p>
  86. <p>2. <a href="%(files_backup_url)s">Click here to download\
  87. the files backup</a></p>
  88. <p>This link will be valid for 24 hours. A new backup will be available
  89. for download only after 24 hours.</p>
  90. <p>Have a nice day!<br>ERPNext</p>""" % {
  91. "db_backup_url": os.path.join(backup_url, os.path.basename(self.backup_path_db)),
  92. "files_backup_url": os.path.join(backup_url, os.path.basename(self.backup_path_files))
  93. }
  94. datetime_str = datetime.fromtimestamp(os.stat(self.backup_path_db).st_ctime)
  95. subject = datetime_str.strftime("%d/%m/%Y %H:%M:%S") + """ - Backup ready to be downloaded"""
  96. sendmail(recipients=recipient_list, msg=msg, subject=subject)
  97. return recipient_list
  98. @webnotes.whitelist()
  99. def get_backup():
  100. """
  101. This function is executed when the user clicks on
  102. Toos > Download Backup
  103. """
  104. #if verbose: print webnotes.conn.cur_db_name + " " + conf.db_password
  105. delete_temp_backups()
  106. odb = BackupGenerator(webnotes.conn.cur_db_name, webnotes.conn.cur_db_name,\
  107. webnotes.get_db_password(webnotes.conn.cur_db_name))
  108. odb.get_backup()
  109. recipient_list = odb.send_email()
  110. webnotes.msgprint("""A download link to your backup will be emailed \
  111. to you shortly on the following email address:
  112. %s""" % (', '.join(recipient_list)))
  113. def scheduled_backup(older_than=6, ignore_files=False):
  114. """this function is called from scheduler
  115. deletes backups older than 7 days
  116. takes backup"""
  117. odb = new_backup(older_than, ignore_files)
  118. from webnotes.utils import now
  119. print "backup taken -", odb.backup_path_db, "- on", now()
  120. def new_backup(older_than=6, ignore_files=False):
  121. delete_temp_backups(older_than=168)
  122. odb = BackupGenerator(webnotes.conn.cur_db_name, webnotes.conn.cur_db_name,\
  123. webnotes.get_db_password(webnotes.conn.cur_db_name))
  124. odb.get_backup(older_than, ignore_files)
  125. return odb
  126. def delete_temp_backups(older_than=24):
  127. """
  128. Cleans up the backup_link_path directory by deleting files older than 24 hours
  129. """
  130. file_list = os.listdir(get_backup_path())
  131. for this_file in file_list:
  132. this_file_path = os.path.join(get_backup_path(), this_file)
  133. if is_file_old(this_file_path, older_than):
  134. os.remove(this_file_path)
  135. def is_file_old(db_file_name, older_than=24):
  136. """
  137. Checks if file exists and is older than specified hours
  138. Returns ->
  139. True: file does not exist or file is old
  140. False: file is new
  141. """
  142. if os.path.isfile(db_file_name):
  143. from datetime import timedelta
  144. import time
  145. #Get timestamp of the file
  146. file_datetime = datetime.fromtimestamp\
  147. (os.stat(db_file_name).st_ctime)
  148. if datetime.today() - file_datetime >= timedelta(hours = older_than):
  149. if verbose: print "File is old"
  150. return True
  151. else:
  152. if verbose: print "File is recent"
  153. return False
  154. else:
  155. if verbose: print "File does not exist"
  156. return True
  157. backup_path = None
  158. def get_backup_path():
  159. global backup_path
  160. if not backup_path:
  161. import os, conf
  162. backup_path = os.path.join(os.path.dirname(os.path.abspath(conf.__file__)),
  163. 'public', 'backups')
  164. return backup_path
  165. #-------------------------------------------------------------------------------
  166. if __name__ == "__main__":
  167. """
  168. is_file_old db_name user password
  169. get_backup db_name user password
  170. """
  171. import sys
  172. cmd = sys.argv[1]
  173. if cmd == "is_file_old":
  174. odb = BackupGenerator(sys.argv[2], sys.argv[3], sys.argv[4])
  175. is_file_old(odb.db_file_name)
  176. if cmd == "get_backup":
  177. odb = BackupGenerator(sys.argv[2], sys.argv[3], sys.argv[4])
  178. odb.get_backup()
  179. if cmd == "take_dump":
  180. odb = BackupGenerator(sys.argv[2], sys.argv[3], sys.argv[4])
  181. odb.take_dump()
  182. if cmd == "send_email":
  183. odb = BackupGenerator(sys.argv[2], sys.argv[3], sys.argv[4])
  184. odb.send_email("abc.sql.gz")
  185. if cmd == "delete_temp_backups":
  186. delete_temp_backups()