Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

221 rader
7.2 KiB

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