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.

302 lines
11 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 AGPL-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.debug('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. tempdir = fields.Char(
  54. string="Temporary directory",
  55. help="Backups first go to a temporary directory. In case you need to "
  56. "put them somewhere else, fill in the directory here",
  57. )
  58. sftp_host = fields.Char(
  59. string='SFTP Server',
  60. oldname="sftpip",
  61. help=(
  62. "The host name or IP address from your remote"
  63. " server. For example 192.168.0.1"
  64. )
  65. )
  66. sftp_port = fields.Integer(
  67. string="SFTP Port",
  68. default=22,
  69. oldname="sftpport",
  70. help="The port on the FTP server that accepts SSH/SFTP calls."
  71. )
  72. sftp_user = fields.Char(
  73. string='Username in the SFTP Server',
  74. oldname="sftpusername",
  75. help=(
  76. "The username where the SFTP connection "
  77. "should be made with. This is the user on the external server."
  78. )
  79. )
  80. sftp_password = fields.Char(
  81. string="SFTP Password",
  82. oldname="sftppassword",
  83. help="The password for the SFTP connection. If you specify a private "
  84. "key file, then this is the password to decrypt it.",
  85. )
  86. sftp_private_key = fields.Char(
  87. string="Private key location",
  88. help="Path to the private key file. Only the Odoo user should have "
  89. "read permissions for that file.",
  90. )
  91. @api.model
  92. def _default_folder(self):
  93. """Default to ``backups`` folder inside current server datadir."""
  94. return os.path.join(
  95. tools.config["data_dir"],
  96. "backups",
  97. self.env.cr.dbname)
  98. @api.multi
  99. @api.depends("folder", "method", "sftp_host", "sftp_port", "sftp_user")
  100. def _compute_name(self):
  101. """Get the right summary for this job."""
  102. for rec in self:
  103. if rec.method == "local":
  104. rec.name = "%s @ localhost" % rec.folder
  105. elif rec.method == "sftp":
  106. rec.name = "sftp://%s@%s:%d%s" % (
  107. rec.sftp_user, rec.sftp_host, rec.sftp_port, rec.folder)
  108. @api.constrains("folder", "method")
  109. @api.multi
  110. def _check_folder(self):
  111. """Do not use the filestore or you will backup your backups."""
  112. for s in self:
  113. if (s.method == "local" and
  114. s.folder.startswith(
  115. tools.config.filestore(self.env.cr.dbname))):
  116. raise exceptions.ValidationError(
  117. _("Do not save backups on your filestore, or you will "
  118. "backup your backups too!"))
  119. @api.multi
  120. def action_sftp_test_connection(self):
  121. """Check if the SFTP settings are correct."""
  122. try:
  123. # Just open and close the connection
  124. with self.sftp_connection():
  125. raise exceptions.Warning(_("Connection Test Succeeded!"))
  126. except (pysftp.CredentialException, pysftp.ConnectionException):
  127. _logger.info("Connection Test Failed!", exc_info=True)
  128. raise exceptions.Warning(_("Connection Test Failed!"))
  129. @api.multi
  130. def action_backup(self):
  131. """Run selected backups."""
  132. backup = None
  133. filename = self.filename(datetime.now())
  134. successful = self.browse()
  135. # Start with local storage
  136. for rec in self.filtered(lambda r: r.method == "local"):
  137. with rec.backup_log():
  138. # Directory must exist
  139. try:
  140. os.makedirs(rec.folder)
  141. except OSError:
  142. pass
  143. with open(os.path.join(rec.folder, filename),
  144. 'wb') as destiny:
  145. # Copy the cached backup
  146. if backup:
  147. with open(backup) as cached:
  148. shutil.copyfileobj(cached, destiny)
  149. # Generate new backup
  150. else:
  151. with rec.custom_tempdir():
  152. db.dump_db(self.env.cr.dbname, destiny)
  153. backup = backup or destiny.name
  154. successful |= rec
  155. # Ensure a local backup exists if we are going to write it remotely
  156. sftp = self.filtered(lambda r: r.method == "sftp")
  157. if sftp:
  158. if backup:
  159. cached = open(backup)
  160. else:
  161. cached = db.dump_db(self.env.cr.dbname, None)
  162. with cached:
  163. for rec in sftp:
  164. with rec.backup_log():
  165. with rec.sftp_connection() as remote:
  166. # Directory must exist
  167. try:
  168. remote.makedirs(rec.folder)
  169. except pysftp.ConnectionException:
  170. pass
  171. # Copy cached backup to remote server
  172. with remote.open(
  173. os.path.join(rec.folder, filename),
  174. "wb") as destiny:
  175. shutil.copyfileobj(cached, destiny)
  176. successful |= rec
  177. # Remove old files for successful backups
  178. successful.cleanup()
  179. @api.model
  180. def action_backup_all(self):
  181. """Run all scheduled backups."""
  182. return self.search([]).action_backup()
  183. @api.multi
  184. @contextmanager
  185. def custom_tempdir(self):
  186. old_tempdir = tempfile.tempdir
  187. if self.tempdir:
  188. tempfile.tempdir = self.tempdir
  189. try:
  190. yield
  191. finally:
  192. tempfile.tempdir = old_tempdir
  193. @api.multi
  194. @contextmanager
  195. def backup_log(self):
  196. """Log a backup result."""
  197. try:
  198. _logger.info("Starting database backup: %s", self.name)
  199. yield
  200. except:
  201. _logger.exception("Database backup failed: %s", self.name)
  202. escaped_tb = tools.html_escape(traceback.format_exc())
  203. self.message_post(
  204. "<p>%s</p><pre>%s</pre>" % (
  205. _("Database backup failed."),
  206. escaped_tb),
  207. subtype=self.env.ref(
  208. "auto_backup.mail_message_subtype_failure"
  209. ),
  210. )
  211. else:
  212. _logger.info("Database backup succeeded: %s", self.name)
  213. self.message_post(_("Database backup succeeded."))
  214. @api.multi
  215. def cleanup(self):
  216. """Clean up old backups."""
  217. now = datetime.now()
  218. for rec in self.filtered("days_to_keep"):
  219. with rec.cleanup_log():
  220. oldest = self.filename(now - timedelta(days=rec.days_to_keep))
  221. if rec.method == "local":
  222. for name in iglob(os.path.join(rec.folder,
  223. "*.dump.zip")):
  224. if os.path.basename(name) < oldest:
  225. os.unlink(name)
  226. elif rec.method == "sftp":
  227. with rec.sftp_connection() as remote:
  228. for name in remote.listdir(rec.folder):
  229. if (name.endswith(".dump.zip") and
  230. os.path.basename(name) < oldest):
  231. remote.unlink('%s/%s' % (rec.folder, name))
  232. @api.multi
  233. @contextmanager
  234. def cleanup_log(self):
  235. """Log a possible cleanup failure."""
  236. try:
  237. _logger.info("Starting cleanup process after database backup: %s",
  238. self.name)
  239. yield
  240. except:
  241. _logger.exception("Cleanup of old database backups failed: %s")
  242. escaped_tb = tools.html_escape(traceback.format_exc())
  243. self.message_post(
  244. "<p>%s</p><pre>%s</pre>" % (
  245. _("Cleanup of old database backups failed."),
  246. escaped_tb),
  247. subtype=self.env.ref("auto_backup.failure"))
  248. else:
  249. _logger.info("Cleanup of old database backups succeeded: %s",
  250. self.name)
  251. @api.model
  252. def filename(self, when):
  253. """Generate a file name for a backup.
  254. :param datetime.datetime when:
  255. Use this datetime instead of :meth:`datetime.datetime.now`.
  256. """
  257. return "{:%Y_%m_%d_%H_%M_%S}.dump.zip".format(when)
  258. @api.multi
  259. def sftp_connection(self):
  260. """Return a new SFTP connection with found parameters."""
  261. params = {
  262. "host": self.sftp_host,
  263. "username": self.sftp_user,
  264. "port": self.sftp_port,
  265. }
  266. _logger.debug(
  267. "Trying to connect to sftp://%(username)s@%(host)s:%(port)d",
  268. extra=params)
  269. if self.sftp_private_key:
  270. params["private_key"] = self.sftp_private_key
  271. if self.sftp_password:
  272. params["private_key_pass"] = self.sftp_password
  273. else:
  274. params["password"] = self.sftp_password
  275. return pysftp.Connection(**params)