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.

408 lines
15 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. # OpenERP, Open Source Management Solution
  4. # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
  5. # Copyright 2015 Agile Business Group <http://www.agilebg.com>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import xmlrpclib
  22. import socket
  23. import os
  24. import time
  25. import datetime
  26. import re
  27. from openerp import models, fields, api, _
  28. from openerp.exceptions import except_orm, Warning as UserError
  29. from openerp import tools
  30. from openerp.service import db
  31. import logging
  32. _logger = logging.getLogger(__name__)
  33. try:
  34. import pysftp
  35. except ImportError:
  36. _logger.debug('Can not import pysftp')
  37. def execute(connector, method, *args):
  38. res = False
  39. try:
  40. res = getattr(connector, method)(*args)
  41. except socket.error as e:
  42. raise e
  43. return res
  44. class DbBackup(models.Model):
  45. _name = 'db.backup'
  46. def get_connection_uri(self, host, port, secure=False):
  47. uri = 'http://%s:%s' % (host, port)
  48. if secure:
  49. uri = 'https://%s:%s' % (host, port)
  50. return uri
  51. def get_connection(self, host, port, secure=False):
  52. uri = self.get_connection_uri(host, port, secure)
  53. return xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
  54. def get_db_list(self, host, port, secure=False):
  55. conn = self.get_connection(host, port, secure)
  56. db_list = execute(conn, 'list')
  57. return db_list
  58. @api.model
  59. def _get_db_name(self):
  60. return self.env.cr.dbname
  61. # Columns local server
  62. host = fields.Char(
  63. string='Host', default='localhost', size=100, required=True)
  64. securehost = fields.Boolean(string='Secure Host')
  65. port = fields.Char(
  66. string='Port', default='8069', size=10, required=True)
  67. name = fields.Char(
  68. string='Database', size=100, required=True,
  69. default=_get_db_name,
  70. help='Database you want to schedule backups for'
  71. )
  72. adminpassword = fields.Char(
  73. string='Admin user Password',
  74. help=(
  75. "The password Admin password of Odoo Instance."
  76. ),
  77. required=True
  78. )
  79. bkp_dir = fields.Char(
  80. string='Backup Directory', size=100,
  81. default='/odoo/backups',
  82. help='Absolute path for storing the backups',
  83. required=True
  84. )
  85. autoremove = fields.Boolean(
  86. string='Auto. Remove Backups',
  87. help=(
  88. "If you check this option you can choose to "
  89. "automaticly remove the backup after xx days"
  90. )
  91. )
  92. daystokeep = fields.Integer(
  93. string='Remove after x days',
  94. default=30,
  95. help=(
  96. "Choose after how many days the backup should be "
  97. "deleted. For example:\nIf you fill in 5 the backups "
  98. "will be removed after 5 days."
  99. ), required=True
  100. )
  101. sftpwrite = fields.Boolean(
  102. string='Write to external server with sftp',
  103. help=(
  104. "If you check this option you can specify the details "
  105. "needed to write to a remote server with SFTP."
  106. )
  107. )
  108. sftppath = fields.Char(
  109. string='Path external server',
  110. help=(
  111. "The location to the folder where the dumps should be "
  112. "written to. For example /odoo/backups/.\nFiles will then"
  113. " be written to /odoo/backups/ on your remote server."
  114. )
  115. )
  116. sftpip = fields.Char(
  117. string='IP Address SFTP Server',
  118. help=(
  119. "The IP address from your remote"
  120. " server. For example 192.168.0.1"
  121. )
  122. )
  123. sftpport = fields.Integer(
  124. string="SFTP Port",
  125. default=22,
  126. help="The port on the FTP server that accepts SSH/SFTP calls."
  127. )
  128. sftpusername = fields.Char(
  129. string='Username SFTP Server',
  130. help=(
  131. "The username where the SFTP connection "
  132. "should be made with. This is the user on the external server."
  133. )
  134. )
  135. sftppassword = fields.Char(
  136. string='Password User SFTP Server',
  137. help=(
  138. "The password from the user where the SFTP connection "
  139. "should be made with. This is the password from the user"
  140. " on the external server."
  141. )
  142. )
  143. daystokeepsftp = fields.Integer(
  144. string='Remove SFTP after x days',
  145. default=30,
  146. help=(
  147. "Choose after how many days the backup should be deleted "
  148. "from the FTP server. For example:\nIf you fill in 5 the "
  149. "backups will be removed after 5 days from the FTP server."
  150. )
  151. )
  152. sendmailsftpfail = fields.Boolean(
  153. string='Auto. E-mail on backup fail',
  154. help=(
  155. "If you check this option you can choose to automaticly"
  156. " get e-mailed when the backup to the external server failed."
  157. )
  158. )
  159. emailtonotify = fields.Char(
  160. string='E-mail to notify',
  161. help=(
  162. "Fill in the e-mail where you want to be"
  163. " notified that the backup failed on the FTP."
  164. )
  165. )
  166. lasterrorlog = fields.Text(
  167. string='E-mail to notify',
  168. help=(
  169. "Fill in the e-mail where you want to be"
  170. " notified that the backup failed on the FTP."
  171. )
  172. )
  173. @api.multi
  174. def _check_db_exist(self):
  175. for rec in self:
  176. db_list = self.get_db_list(rec.host, rec.port, rec.securehost)
  177. if rec.name in db_list:
  178. return True
  179. return False
  180. _constraints = [
  181. (
  182. _check_db_exist,
  183. _('Error ,No such database exists'), ['name']
  184. )
  185. ]
  186. @api.multi
  187. def test_sftp_connection(self):
  188. confs = self.search([])
  189. # Check if there is a success or fail and write messages
  190. messageTitle = ""
  191. messageContent = ""
  192. for rec in confs:
  193. try:
  194. conn_success = True
  195. ipHost = rec.sftpip
  196. portHost = rec.sftpport
  197. usernameLogin = rec.sftpusername
  198. passwordLogin = rec.sftppassword
  199. # Connect with external server over SFTP, so we know sure that
  200. # everything works.
  201. srv = pysftp.Connection(host=ipHost, username=usernameLogin,
  202. password=passwordLogin, port=portHost)
  203. srv.close()
  204. # We have a success.
  205. messageTitle = _("Connection Test Succeeded!")
  206. messageContent = _(
  207. "Everything seems properly set up for FTP back-ups!")
  208. except Exception as e:
  209. conn_success = False
  210. messageTitle = _("Connection Test Failed!")
  211. if len(rec.sftpip) < 8:
  212. messageContent += _(
  213. "\nYour IP address seems to be too short.\n")
  214. messageContent += _("Here is what we got instead:\n")
  215. if not conn_success:
  216. raise except_orm(
  217. _(messageTitle), _(
  218. messageContent + "%s") %
  219. tools.ustr(e))
  220. else:
  221. raise UserError(_(messageTitle), _(messageContent))
  222. @api.model
  223. def schedule_backup(self):
  224. for rec in self.search([]):
  225. if not os.path.isdir(rec.bkp_dir):
  226. os.makedirs(rec.bkp_dir)
  227. # Create name for dumpfile.
  228. bkp_file = '%s_%s.dump.zip' % (
  229. time.strftime('%d_%m_%Y_%H_%M_%S'),
  230. rec.name)
  231. file_path = os.path.join(rec.bkp_dir, bkp_file)
  232. fbk = open(file_path, 'wb')
  233. db.dump_db(rec.name, fbk)
  234. fbk.close()
  235. # Check if user wants to write to SFTP or not.
  236. if rec.sftpwrite is True:
  237. try:
  238. # Store all values in variables
  239. dir = rec.bkp_dir
  240. pathToWriteTo = rec.sftppath
  241. ipHost = rec.sftpip
  242. portHost = rec.sftpport
  243. usernameLogin = rec.sftpusername
  244. passwordLogin = rec.sftppassword
  245. # Connect with external server over SFTP
  246. srv = pysftp.Connection(
  247. host=ipHost,
  248. username=usernameLogin,
  249. password=passwordLogin,
  250. port=portHost)
  251. # Move to the correct directory on external server. If the
  252. # user made a typo in his path with multiple slashes
  253. # (/odoo//backups/) it will be fixed by this regex.
  254. pathToWriteTo = re.sub('/+', '/', pathToWriteTo)
  255. try:
  256. srv.chdir(pathToWriteTo)
  257. except IOError:
  258. # Create directory and subdirs if they do not exist.
  259. currentDir = ''
  260. for dirElement in pathToWriteTo.split('/'):
  261. currentDir += dirElement + '/'
  262. try:
  263. srv.chdir(currentDir)
  264. except:
  265. _logger.info(
  266. _(
  267. '(Part of the) path didn\'t exist. '
  268. 'Creating it now at %s'
  269. ) % currentDir
  270. )
  271. # Make directory and then navigate into it
  272. srv.mkdir(currentDir, mode=777)
  273. srv.chdir(currentDir)
  274. pass
  275. srv.chdir(pathToWriteTo)
  276. # Loop over all files in the directory.
  277. _logger.debug(
  278. 'Start to copy files...'
  279. )
  280. for f in os.listdir(dir):
  281. fullpath = os.path.join(dir, f)
  282. if os.path.isfile(fullpath):
  283. srv.put(fullpath)
  284. # Navigate in to the correct folder.
  285. srv.chdir(pathToWriteTo)
  286. # Loop over all files in the directory from the back-ups.
  287. # We will check the creation date of every back-up.
  288. for file in srv.listdir(pathToWriteTo):
  289. # Get the full path
  290. fullpath = os.path.join(pathToWriteTo, file)
  291. if srv.isfile(fullpath) and ".dump.zip" in file:
  292. # Get the timestamp from the file on the external
  293. # server
  294. timestamp = srv.stat(fullpath).st_atime
  295. createtime = (
  296. datetime.datetime.fromtimestamp(timestamp)
  297. )
  298. now = datetime.datetime.now()
  299. delta = now - createtime
  300. # If the file is older than the daystokeepsftp (the
  301. # days to keep that the user filled in on the Odoo
  302. # form it will be removed.
  303. if (
  304. rec.daystokeepsftp > 0 and
  305. delta.days >= rec.daystokeepsftp
  306. ):
  307. # Only delete files, no directories!
  308. srv.unlink(file)
  309. # Close the SFTP session.
  310. srv.close()
  311. except Exception as e:
  312. _logger.debug(
  313. 'Exception We couldn\'t back '
  314. 'up to the FTP server..'
  315. )
  316. # At this point the SFTP backup failed.
  317. # We will now check if the user wants
  318. # an e-mail notification about this.
  319. if rec.sendmailsftpfail:
  320. self.send_notification(rec, e)
  321. # Remove all old files (on local server)
  322. # in case this is configured..
  323. if rec.autoremove is True:
  324. try:
  325. self.remove_folder(rec)
  326. except Exception as e:
  327. _logger.debug(
  328. 'Exception when try to remove file'
  329. )
  330. return True
  331. def send_notification(self, rec, e):
  332. try:
  333. ir_mail_server = self.env['ir.mail_server']
  334. message = (
  335. "Dear,\n\nThe backup for the server %s"
  336. " (IP: %s) failed.Please check"
  337. " the following details:\n\n"
  338. "IP address SFTP server: %s \nUsername: %s"
  339. "\nPassword: %s"
  340. "\n\nError details: %s \n\nWith kind regards"
  341. ) % (
  342. rec.host, rec.sftpip, rec.sftpip,
  343. rec.sftpusername, rec.sftppassword,
  344. tools.ustr(e)
  345. )
  346. msg = ir_mail_server.build_email(
  347. "auto_backup@%s.com" % rec.name,
  348. [rec.emailtonotify],
  349. "Backup from %s ( %s ) failed" % (
  350. rec.host, rec.sftpip),
  351. message)
  352. ir_mail_server.send_email(msg)
  353. except Exception as e:
  354. _logger.debug(
  355. 'Exception %s' % tools.ustr(e)
  356. )
  357. # This is done after the SFTP writing to prevent unusual behaviour:
  358. # If the user would set local back-ups to be kept 0 days and the SFTP
  359. # to keep backups xx days there wouldn't be any new back-ups added
  360. # to the SFTP.
  361. # If we'd remove the dump files before they're writen to the SFTP
  362. # there willbe nothing to write. Meaning that if an user doesn't want
  363. # to keep back-ups locally and only wants them on the SFTP
  364. # (NAS for example) there wouldn't be any writing to the
  365. # remote server if this if statement was before the SFTP write method
  366. # right above this comment.
  367. def remove_folder(self, rec):
  368. dir = rec.bkp_dir
  369. # Loop over all files in the directory.
  370. for f in os.listdir(dir):
  371. fullpath = os.path.join(dir, f)
  372. if os.path.isfile(fullpath) and ".dump.zip" in f:
  373. timestamp = os.stat(fullpath).st_ctime
  374. createtime = (
  375. datetime.datetime.fromtimestamp(timestamp)
  376. )
  377. now = datetime.datetime.now()
  378. delta = now - createtime
  379. if delta.days >= rec.daystokeep:
  380. _logger.debug(
  381. 'Remove local file...'
  382. )
  383. os.remove(fullpath)