Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

224 wiersze
7.0 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. """
  23. This module handles the On Demand Backup utility
  24. To setup in defs set:
  25. backup_path: path where backups will be taken (for eg /backups)
  26. backup_link_path: download link for backups (eg /var/www/wnframework/backups)
  27. backup_url: base url of the backup folder (eg http://mysite.com/backups)
  28. """
  29. #Imports
  30. import os, webnotes
  31. from datetime import datetime
  32. #Global constants
  33. verbose = 0
  34. import conf
  35. #-------------------------------------------------------------------------------
  36. class BackupGenerator:
  37. """
  38. This class contains methods to perform On Demand Backup
  39. To initialize, specify (db_name, user, password, db_file_name=None)
  40. If specifying db_file_name, also append ".sql.gz"
  41. """
  42. def __init__(self, db_name, user, password):
  43. self.db_name = db_name
  44. self.user = user
  45. self.password = password
  46. self.backup_file_name = self.get_backup_file_name()
  47. self.backup_file_path = os.path.join(conf.backup_path, self.backup_file_name)
  48. def get_backup_file_name(self):
  49. import random
  50. todays_date = "".join(str(datetime.date(datetime.today())).split("-"))
  51. random_number = str(int(random.random()*99999999))
  52. #Generate a random name using today's date and a 8 digit random number
  53. random_name = todays_date + "_" + random_number + ".sql.gz"
  54. return random_name
  55. def take_dump(self):
  56. """
  57. Dumps a db via mysqldump
  58. """
  59. import webnotes.utils
  60. # escape reserved characters
  61. args = dict([item[0], webnotes.utils.esc(item[1], '$ ')] for item in self.__dict__.copy().items())
  62. webnotes.errprint(args)
  63. cmd_string = "mysqldump -u %(user)s -p%(password)s %(db_name)s | gzip -c > %(backup_file_path)s" \
  64. % args
  65. ret = os.system(cmd_string)
  66. def get_recipients(self):
  67. """
  68. Get recepient's email address
  69. """
  70. #import webnotes.db
  71. #webnotes.conn = webnotes.db.Database(use_default=1)
  72. recipient_list = webnotes.conn.sql(\
  73. """SELECT parent FROM tabUserRole
  74. WHERE role='System Manager'
  75. AND parent!='Administrator'
  76. AND parent IN
  77. (SELECT email FROM tabProfile WHERE enabled=1)""")
  78. return [i[0] for i in recipient_list]
  79. def send_email(self, backup_file):
  80. """
  81. Sends the link to backup file located at erpnext/backups
  82. """
  83. backup_url = webnotes.conn.get_value('Website Settings',
  84. 'Website Settings', 'subdomain') or ''
  85. backup_url = os.path.join('http://' + backup_url, 'backups')
  86. file_url = os.path.join(backup_url, backup_file)
  87. from webnotes.utils.email_lib import sendmail
  88. recipient_list = self.get_recipients()
  89. msg = """<a href="%(file_url)s">Click here to begin downloading\
  90. your backup</a>
  91. This link will be valid for 24 hours.
  92. Also, a new backup will be available for download (if requested)\
  93. only after 24 hours.""" % {"file_url":file_url}
  94. backup_file_path = os.path.join(conf.backup_path, backup_file)
  95. datetime_str = datetime.fromtimestamp(os.stat(backup_file_path).st_ctime)
  96. subject = datetime_str.strftime("%d/%m/%Y %H:%M:%S") + """ - Backup ready to be downloaded"""
  97. sendmail(recipients=recipient_list, msg=msg, subject=subject)
  98. return recipient_list
  99. def get_backup(self):
  100. """
  101. Takes a new dump if existing file is old
  102. and sends the link to the file as email
  103. """
  104. #Check if file exists and is less than a day old
  105. #If not Take Dump
  106. backup_file = recent_backup_exists()
  107. if not backup_file:
  108. self.take_dump()
  109. backup_file = self.backup_file_name
  110. #Email Link
  111. recipient_list = self.send_email(backup_file)
  112. return recipient_list
  113. @webnotes.whitelist()
  114. def get_backup():
  115. """
  116. This function is executed when the user clicks on
  117. Toos > Download Backup
  118. """
  119. #if verbose: print webnotes.conn.cur_db_name + " " + conf.db_password
  120. delete_temp_backups()
  121. odb = BackupGenerator(webnotes.conn.cur_db_name, webnotes.conn.cur_db_name,\
  122. webnotes.get_db_password(webnotes.conn.cur_db_name))
  123. recipient_list = odb.get_backup()
  124. webnotes.msgprint("""A download link to your backup will be emailed \
  125. to you shortly on the following email address:
  126. %s""" % (', '.join(recipient_list)))
  127. def recent_backup_exists():
  128. file_list = os.listdir(conf.backup_path)
  129. for this_file in file_list:
  130. this_file_path = os.path.join(conf.backup_path, this_file)
  131. if not is_file_old(this_file_path):
  132. return this_file
  133. return None
  134. def delete_temp_backups():
  135. """
  136. Cleans up the backup_link_path directory by deleting files older than 24 hours
  137. """
  138. file_list = os.listdir(conf.backup_path)
  139. for this_file in file_list:
  140. this_file_path = os.path.join(conf.backup_path, this_file)
  141. if is_file_old(this_file_path):
  142. os.remove(this_file_path)
  143. def is_file_old(db_file_name, older_than=24):
  144. """
  145. Checks if file exists and is older than specified hours
  146. Returns ->
  147. True: file does not exist or file is old
  148. False: file is new
  149. """
  150. if os.path.isfile(db_file_name):
  151. from datetime import timedelta
  152. import time
  153. #Get timestamp of the file
  154. file_datetime = datetime.fromtimestamp\
  155. (os.stat(db_file_name).st_ctime)
  156. if datetime.today() - file_datetime >= timedelta(hours = older_than):
  157. if verbose: print "File is old"
  158. return True
  159. else:
  160. if verbose: print "File is recent"
  161. return False
  162. else:
  163. if verbose: print "File does not exist"
  164. return True
  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()