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.

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