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.

407 lines
17 KiB

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