選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

225 行
7.2 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. from conf import backup_path, backup_link_path
  34. verbose = 0
  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, db_file_name=None):
  43. self.db_name = db_name.replace('$', '\$')
  44. self.user = user
  45. self.password = password
  46. self.db_file_name = db_file_name and db_file_name \
  47. or (os.path.join(backup_path, self.db_name + ".sql.gz"))
  48. def take_dump(self):
  49. """
  50. Dumps a db via mysqldump
  51. """
  52. os.system("""mysqldump -u %(user)s -p%(password)s %(db_name)s |
  53. gzip -c > %(db_file_name)s""" % self.__dict__)
  54. def copy_to_backup_link(self):
  55. """
  56. Copies the backup file from backup path to shared link path
  57. It also gives the file a random name, thus hiding the db_name
  58. """
  59. import random
  60. todays_date = "".join(str(datetime.date(datetime.today())).split("-"))
  61. random_number = str(int(random.random()*99999999))
  62. #Generate a random name using today's date and a 8 digit random number
  63. random_name = todays_date + "_" + random_number + ".sql.gz"
  64. os.system("""cp -f %(src_file)s %(dest_file)s""" % \
  65. {"src_file":self.db_file_name,
  66. "dest_file":os.path.join(backup_link_path, random_name)})
  67. if verbose: print "file copied"
  68. return random_name
  69. def get_recipients(self):
  70. """
  71. Get recepient's email address
  72. """
  73. #import webnotes.db
  74. #webnotes.conn = webnotes.db.Database(use_default=1)
  75. recipient_list = webnotes.conn.sql(\
  76. """SELECT parent FROM tabUserRole
  77. WHERE role='System Manager'
  78. AND parent!='Administrator'
  79. AND parent IN
  80. (SELECT email FROM tabProfile WHERE enabled=1)""")
  81. return [i[0] for i in recipient_list]
  82. def send_email(self, backup_file):
  83. """
  84. Sends the link to backup file located at erpnext/backups
  85. """
  86. if hasattr(conf, 'backup_url'):
  87. backup_url = conf.backup_url
  88. else:
  89. backup_url = webnotes.conn.get_value('Website Settings',
  90. 'Website Settings', 'subdomain') or ''
  91. if hasattr(conf, 'backup_folder_name'):
  92. backup_url = os.path.join(backup_url,
  93. conf.backup_folder_name)
  94. file_url = os.path.join(backup_url, backup_file)
  95. from webnotes.utils.email_lib import sendmail
  96. recipient_list = self.get_recipients()
  97. msg = """<a href=%(file_url)s>Click here to begin downloading\
  98. your backup</a>
  99. This link will be valid for 24 hours.
  100. Also, a new backup will be available for download (if requested)\
  101. only after 24 hours.""" % {"file_url":file_url}
  102. datetime_str = datetime.fromtimestamp(os.stat(self.db_file_name.replace('\$', '$')).st_ctime)
  103. subject = datetime_str.strftime("%d/%m/%Y %H:%M:%S") + """ - Backup ready to be downloaded"""
  104. sendmail(recipients=recipient_list, msg=msg, subject=subject, from_defs=1)
  105. return recipient_list
  106. def get_backup(self):
  107. """
  108. Takes a new dump if existing file is old
  109. and sends the link to the file as email
  110. """
  111. #Check if file exists and is less than a day old
  112. #If not Take Dump
  113. if is_file_old(self.db_file_name):
  114. self.take_dump()
  115. #Copy file to backup_link_path
  116. #This is a security hole. When the user calls get_backup repeatedly
  117. #a file will be generated each time.
  118. backup_file = self.copy_to_backup_link()
  119. #Email Link
  120. recipient_list = self.send_email(backup_file)
  121. return recipient_list
  122. @webnotes.whitelist()
  123. def get_backup():
  124. """
  125. This function is executed when the user clicks on
  126. Toos > Download Backup
  127. """
  128. #if verbose: print webnotes.conn.cur_db_name + " " + conf.db_password
  129. odb = BackupGenerator(webnotes.conn.cur_db_name, webnotes.conn.cur_db_name,\
  130. webnotes.get_db_password(webnotes.conn.cur_db_name))
  131. recipient_list = odb.get_backup()
  132. delete_temp_backups()
  133. webnotes.msgprint("""A download link to your backup will be emailed \
  134. to you shortly on the following email address:
  135. %s""" % (', '.join(recipient_list)))
  136. def delete_temp_backups():
  137. """
  138. Cleans up the backup_link_path directory by deleting files older than 24 hours
  139. """
  140. file_list = os.listdir(backup_link_path)
  141. for this_file in file_list:
  142. this_file_path = os.path.join(backup_link_path, this_file)
  143. if is_file_old(this_file_path):
  144. os.remove(this_file_path)
  145. def is_file_old(db_file_name, older_than=24):
  146. """
  147. Checks if file exists and is older than specified hours
  148. Returns ->
  149. True: file does not exist or file is old
  150. False: file is new
  151. """
  152. if os.path.isfile(db_file_name):
  153. from datetime import timedelta
  154. import time
  155. #Get timestamp of the file
  156. file_datetime = datetime.fromtimestamp\
  157. (os.stat(db_file_name).st_ctime)
  158. if datetime.today() - file_datetime >= timedelta(hours = older_than):
  159. if verbose: print "File is old"
  160. return True
  161. else:
  162. if verbose: print "File is recent"
  163. return False
  164. else:
  165. if verbose: print "File does not exist"
  166. return True
  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()