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.

285 lines
10 KiB

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