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.

268 lines
9.4 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2004-2009 Tiny SPRL (<http://tiny.be>).
  3. # © 2015 Agile Business Group <http://www.agilebg.com>
  4. # © 2016 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
  5. # License GPL-3.0 or later (http://www.gnu.org/licenses/gpl.html).
  6. import os
  7. import shutil
  8. import tempfile
  9. import traceback
  10. from contextlib import contextmanager
  11. from datetime import datetime, timedelta
  12. from glob import iglob
  13. from openerp import exceptions, models, fields, api, _, tools
  14. from openerp.service import db
  15. import logging
  16. _logger = logging.getLogger(__name__)
  17. try:
  18. import pysftp
  19. except ImportError:
  20. _logger.warning('Cannot import pysftp')
  21. class DbBackup(models.Model):
  22. _name = 'db.backup'
  23. _inherit = "mail.thread"
  24. _sql_constraints = [
  25. ("days_to_keep_positive", "CHECK(days_to_keep >= 0)",
  26. "I cannot remove backups from the future. Ask Doc for that."),
  27. ]
  28. name = fields.Char(
  29. string="Name",
  30. compute="_compute_name",
  31. store=True,
  32. help="Summary of this backup process",
  33. )
  34. folder = fields.Char(
  35. default=lambda self: self._default_folder(),
  36. oldname="bkp_dir",
  37. help='Absolute path for storing the backups',
  38. required=True
  39. )
  40. days_to_keep = fields.Integer(
  41. oldname="daystokeep",
  42. required=True,
  43. default=0,
  44. help="Backups older than this will be deleted automatically. "
  45. "Set 0 to disable autodeletion.",
  46. )
  47. method = fields.Selection(
  48. selection=[("local", "Local disk"), ("sftp", "Remote SFTP server")],
  49. default="local",
  50. help="Choose the storage method for this backup.",
  51. )
  52. sftp_host = fields.Char(
  53. string='SFTP Server',
  54. oldname="sftpip",
  55. help=(
  56. "The host name or IP address from your remote"
  57. " server. For example 192.168.0.1"
  58. )
  59. )
  60. sftp_port = fields.Integer(
  61. string="SFTP Port",
  62. default=22,
  63. oldname="sftpport",
  64. help="The port on the FTP server that accepts SSH/SFTP calls."
  65. )
  66. sftp_user = fields.Char(
  67. string='Username in the SFTP Server',
  68. oldname="sftpusername",
  69. help=(
  70. "The username where the SFTP connection "
  71. "should be made with. This is the user on the external server."
  72. )
  73. )
  74. sftp_password = fields.Char(
  75. string="SFTP Password",
  76. oldname="sftppassword",
  77. help="The password for the SFTP connection. If you specify a private "
  78. "key file, then this is the password to decrypt it.",
  79. )
  80. sftp_private_key = fields.Char(
  81. string="Private key location",
  82. help="Path to the private key file. Only the Odoo user should have "
  83. "read permissions for that file.",
  84. )
  85. @api.model
  86. def _default_folder(self):
  87. """Default to ``backups`` folder inside current database datadir."""
  88. return os.path.join(
  89. tools.config.filestore(self.env.cr.dbname),
  90. "backups")
  91. @api.multi
  92. @api.depends("folder", "method", "sftp_host", "sftp_port", "sftp_user")
  93. def _compute_name(self):
  94. """Get the right summary for this job."""
  95. for rec in self:
  96. if rec.method == "local":
  97. rec.name = "%s @ localhost" % rec.folder
  98. elif rec.method == "sftp":
  99. rec.name = "sftp://%s@%s:%d%s" % (
  100. rec.sftp_user, rec.sftp_host, rec.sftp_port, rec.folder)
  101. @api.multi
  102. def action_sftp_test_connection(self):
  103. """Check if the SFTP settings are correct."""
  104. try:
  105. # Just open and close the connection
  106. with self.sftp_connection():
  107. raise exceptions.Warning(_("Connection Test Succeeded!"))
  108. except (pysftp.CredentialException, pysftp.ConnectionException):
  109. _logger.info("Connection Test Failed!", exc_info=True)
  110. raise exceptions.Warning(_("Connection Test Failed!"))
  111. @api.multi
  112. def action_backup(self):
  113. """Run selected backups."""
  114. backup = None
  115. filename = self.filename(datetime.now())
  116. successful = self.browse()
  117. # Start with local storage
  118. for rec in self.filtered(lambda r: r.method == "local"):
  119. with rec.backup_log():
  120. # Directory must exist
  121. try:
  122. os.makedirs(rec.folder)
  123. except OSError:
  124. pass
  125. with open(os.path.join(rec.folder, filename),
  126. 'wb') as destiny:
  127. # Copy the cached backup
  128. if backup:
  129. with open(backup) as cached:
  130. shutil.copyfileobj(cached, destiny)
  131. # Generate new backup
  132. else:
  133. db.dump_db(self.env.cr.dbname, destiny)
  134. backup = backup or destiny.name
  135. successful |= rec
  136. # Ensure a local backup exists if we are going to write it remotely
  137. sftp = self.filtered(lambda r: r.method == "sftp")
  138. if sftp:
  139. if backup:
  140. cached = open(backup)
  141. else:
  142. cached = tempfile.TemporaryFile()
  143. db.dump_db(self.env.cr.dbname, cached)
  144. with cached:
  145. for rec in sftp:
  146. with rec.backup_log():
  147. with rec.sftp_connection() as remote:
  148. # Directory must exist
  149. try:
  150. remote.makedirs(rec.folder)
  151. except pysftp.ConnectionException:
  152. pass
  153. # Copy cached backup to remote server
  154. with remote.open(
  155. os.path.join(rec.folder, filename),
  156. "wb") as destiny:
  157. shutil.copyfileobj(cached, destiny)
  158. successful |= rec
  159. # Remove old files for successful backups
  160. successful.cleanup()
  161. @api.model
  162. def action_backup_all(self):
  163. """Run all scheduled backups."""
  164. return self.search([]).action_backup()
  165. @api.multi
  166. @contextmanager
  167. def backup_log(self):
  168. """Log a backup result."""
  169. try:
  170. _logger.info("Starting database backup: %s", self.name)
  171. yield
  172. except:
  173. _logger.exception("Database backup failed: %s", self.name)
  174. escaped_tb = tools.html_escape(traceback.format_exc())
  175. self.message_post(
  176. "<p>%s</p><pre>%s</pre>" % (
  177. _("Database backup failed."),
  178. escaped_tb),
  179. subtype=self.env.ref("auto_backup.failure"))
  180. else:
  181. _logger.info("Database backup succeeded: %s", self.name)
  182. self.message_post(_("Database backup succeeded."))
  183. @api.multi
  184. def cleanup(self):
  185. """Clean up old backups."""
  186. now = datetime.now()
  187. for rec in self.filtered("days_to_keep"):
  188. with rec.cleanup_log():
  189. oldest = self.filename(now - timedelta(days=rec.days_to_keep))
  190. if rec.method == "local":
  191. for name in iglob(os.path.join(rec.folder,
  192. "*.dump.zip")):
  193. if name < oldest:
  194. os.unlink(name)
  195. elif rec.method == "sftp":
  196. with rec.sftp_connection() as remote:
  197. for name in remote.listdir(rec.folder):
  198. if name.endswith(".dump.zip") and name < oldest:
  199. remote.unlink(name)
  200. @api.multi
  201. @contextmanager
  202. def cleanup_log(self):
  203. """Log a possible cleanup failure."""
  204. try:
  205. _logger.info("Starting cleanup process after database backup: %s",
  206. self.name)
  207. yield
  208. except:
  209. _logger.exception("Cleanup of old database backups failed: %s")
  210. escaped_tb = tools.html_escape(traceback.format_exc())
  211. self.message_post(
  212. "<p>%s</p><pre>%s</pre>" % (
  213. _("Cleanup of old database backups failed."),
  214. escaped_tb),
  215. subtype=self.env.ref("auto_backup.failure"))
  216. else:
  217. _logger.info("Cleanup of old database backups succeeded: %s",
  218. self.name)
  219. @api.model
  220. def filename(self, when):
  221. """Generate a file name for a backup.
  222. :param datetime.datetime when:
  223. Use this datetime instead of :meth:`datetime.datetime.now`.
  224. """
  225. return "{:%Y_%m_%d_%H_%M_%S}.dump.zip".format(when)
  226. @api.multi
  227. def sftp_connection(self):
  228. """Return a new SFTP connection with found parameters."""
  229. params = {
  230. "host": self.sftp_host,
  231. "username": self.sftp_user,
  232. "port": self.sftp_port,
  233. }
  234. _logger.debug(
  235. "Trying to connect to sftp://%(username)s@%(host)s:%(port)d",
  236. extra=params)
  237. if self.sftp_private_key:
  238. params["private_key"] = self.stfpprivatekey
  239. if self.sftp_password:
  240. params["private_key_pass"] = self.sftp_password
  241. else:
  242. params["password"] = self.sftp_password
  243. return pysftp.Connection(**params)