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.

266 lines
14 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
  6. # $Id$
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. #
  21. ##############################################################################
  22. import xmlrpclib
  23. import socket
  24. import os
  25. import time
  26. import datetime
  27. import base64
  28. import re
  29. try:
  30. import pysftp
  31. except ImportError:
  32. raise ImportError('This module needs pysftp to automaticly write backups to the FTP through SFTP.Please install pysftp on your system.(sudo pip install pysftp)')
  33. from openerp.osv import fields,osv,orm
  34. from openerp import tools
  35. from openerp import netsvc
  36. from openerp import tools, _
  37. import logging
  38. _logger = logging.getLogger(__name__)
  39. def execute(connector, method, *args):
  40. res = False
  41. try:
  42. res = getattr(connector,method)(*args)
  43. except socket.error,e:
  44. raise e
  45. return res
  46. addons_path = tools.config['addons_path'] + '/auto_backup/DBbackups'
  47. class db_backup(osv.Model):
  48. _name = 'db.backup'
  49. def get_db_list(self, cr, user, ids, host, port, context={}):
  50. print("Host: " + host)
  51. print("Port: " + port)
  52. uri = 'http://' + host + ':' + port
  53. conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
  54. db_list = execute(conn, 'list')
  55. return db_list
  56. def _get_db_name(self,cr,uid, vals,context=None):
  57. attach_pool = self.pool.get("ir.logging")
  58. dbName = cr.dbname
  59. return dbName
  60. _columns = {
  61. #Columns local server
  62. 'host' : fields.char('Host', size=100, required='True'),
  63. 'port' : fields.char('Port', size=10, required='True'),
  64. 'name' : fields.char('Database', size=100, required='True',help='Database you want to schedule backups for'),
  65. 'bkp_dir' : fields.char('Backup Directory', size=100, help='Absolute path for storing the backups', required='True'),
  66. 'autoremove': fields.boolean('Auto. Remove Backups', help="If you check this option you can choose to automaticly remove the backup after xx days"),
  67. 'daystokeep': fields.integer('Remove after x days',
  68. help="Choose after how many days the backup should be deleted. For example:\nIf you fill in 5 the backups will be removed after 5 days.",required=True),
  69. #Columns for external server (SFTP)
  70. 'sftpwrite': fields.boolean('Write to external server with sftp', help="If you check this option you can specify the details needed to write to a remote server with SFTP."),
  71. 'sftppath': fields.char('Path external server', help="The location to the folder where the dumps should be written to. For example /odoo/backups/.\nFiles will then be written to /odoo/backups/ on your remote server."),
  72. 'sftpip': fields.char('IP Address SFTP Server', help="The IP address from your remote server. For example 192.168.0.1"),
  73. 'sftpport': fields.integer("SFTP Port", help="The port on the FTP server that accepts SSH/SFTP calls."),
  74. 'sftpusername': fields.char('Username SFTP Server', help="The username where the SFTP connection should be made with. This is the user on the external server."),
  75. 'sftppassword': fields.char('Password User SFTP Server', help="The password from the user where the SFTP connection should be made with. This is the password from the user on the external server."),
  76. 'daystokeepsftp': fields.integer('Remove SFTP after x days', help="Choose after how many days the backup should be deleted from the FTP server. For example:\nIf you fill in 5 the backups will be removed after 5 days from the FTP server."),
  77. 'sendmailsftpfail': fields.boolean('Auto. E-mail on backup fail', help="If you check this option you can choose to automaticly get e-mailed when the backup to the external server failed."),
  78. 'emailtonotify': fields.char('E-mail to notify', help="Fill in the e-mail where you want to be notified that the backup failed on the FTP."),
  79. }
  80. _defaults = {
  81. #'bkp_dir' : lambda *a : addons_path,
  82. 'bkp_dir' : '/odoo/backups',
  83. 'host' : lambda *a : 'localhost',
  84. 'port' : lambda *a : '8069',
  85. 'name': _get_db_name,
  86. 'daystokeepsftp': 30,
  87. 'sftpport': 22,
  88. }
  89. def _check_db_exist(self, cr, user, ids):
  90. for rec in self.browse(cr,user,ids):
  91. db_list = self.get_db_list(cr, user, ids, rec.host, rec.port)
  92. if rec.name in db_list:
  93. return True
  94. return False
  95. _constraints = [
  96. (_check_db_exist, _('Error ! No such database exists!'), [])
  97. ]
  98. def test_sftp_connection(self, cr, uid, ids, context=None):
  99. conf_ids= self.search(cr, uid, [])
  100. confs = self.browse(cr,uid,conf_ids)
  101. #Check if there is a success or fail and write messages
  102. messageTitle = ""
  103. messageContent = ""
  104. for rec in confs:
  105. db_list = self.get_db_list(cr, uid, [], rec.host, rec.port)
  106. try:
  107. pathToWriteTo = rec.sftppath
  108. ipHost = rec.sftpip
  109. portHost = rec.sftpport
  110. usernameLogin = rec.sftpusername
  111. passwordLogin = rec.sftppassword
  112. #Connect with external server over SFTP, so we know sure that everything works.
  113. srv = pysftp.Connection(host=ipHost, username=usernameLogin,
  114. password=passwordLogin,port=portHost)
  115. srv.close()
  116. #We have a success.
  117. messageTitle = "Connection Test Succeeded!"
  118. messageContent = "Everything seems properly set up for FTP back-ups!"
  119. except Exception, e:
  120. messageTitle = "Connection Test Failed!"
  121. if len(rec.sftpip) < 8:
  122. messageContent += "\nYour IP address seems to be too short.\n"
  123. messageContent += "Here is what we got instead:\n"
  124. if "Failed" in messageTitle:
  125. raise osv.except_osv(_(messageTitle), _(messageContent + "%s") % tools.ustr(e))
  126. else:
  127. raise osv.except_osv(_(messageTitle), _(messageContent))
  128. def schedule_backup(self, cr, user, context={}):
  129. conf_ids= self.search(cr, user, [])
  130. confs = self.browse(cr,user,conf_ids)
  131. for rec in confs:
  132. db_list = self.get_db_list(cr, user, [], rec.host, rec.port)
  133. if rec.name in db_list:
  134. try:
  135. if not os.path.isdir(rec.bkp_dir):
  136. os.makedirs(rec.bkp_dir)
  137. except:
  138. raise
  139. #Create name for dumpfile.
  140. bkp_file='%s_%s.dump' % (time.strftime('%d_%m_%Y_%H_%M_%S'),rec.name)
  141. file_path = os.path.join(rec.bkp_dir,bkp_file)
  142. fp = open(file_path,'wb')
  143. uri = 'http://' + rec.host + ':' + rec.port
  144. conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db')
  145. bkp=''
  146. try:
  147. bkp = execute(conn, 'dump', tools.config['admin_passwd'], rec.name)
  148. except:
  149. 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))
  150. continue
  151. bkp = base64.decodestring(bkp)
  152. fp.write(bkp)
  153. fp.close()
  154. else:
  155. logger.notifyChannel('backup', netsvc.LOG_INFO, "database %s doesn't exist on http://%s:%s" %(rec.name, rec.host, rec.port))
  156. #Check if user wants to write to SFTP or not.
  157. if rec.sftpwrite is True:
  158. try:
  159. #Store all values in variables
  160. dir = rec.bkp_dir
  161. pathToWriteTo = rec.sftppath
  162. ipHost = rec.sftpip
  163. portHost = rec.sftpport
  164. usernameLogin = rec.sftpusername
  165. passwordLogin = rec.sftppassword
  166. #Connect with external server over SFTP
  167. srv = pysftp.Connection(host=ipHost, username=usernameLogin,
  168. password=passwordLogin, port=portHost)
  169. #Move to the correct directory on external server. If the user made a typo in his path with multiple slashes (/odoo//backups/) it will be fixed by this regex.
  170. pathToWriteTo = re.sub('([/]{2,5})+','/',pathToWriteTo)
  171. print(pathToWriteTo)
  172. try:
  173. srv.chdir(pathToWriteTo)
  174. except IOError:
  175. #Create directory and subdirs if they do not exist.
  176. currentDir = ''
  177. for dirElement in pathToWriteTo.split('/'):
  178. currentDir += dirElement + '/'
  179. try:
  180. srv.chdir(currentDir)
  181. except:
  182. print('(Part of the) path didn\'t exist. Creating it now at ' + currentDir)
  183. #Make directory and then navigate into it
  184. srv.mkdir(currentDir, mode=777)
  185. srv.chdir(currentDir)
  186. pass
  187. srv.chdir(pathToWriteTo)
  188. #Loop over all files in the directory.
  189. for f in os.listdir(dir):
  190. fullpath = os.path.join(dir, f)
  191. if os.path.isfile(fullpath):
  192. print(fullpath)
  193. srv.put(fullpath)
  194. #Navigate in to the correct folder.
  195. srv.chdir(pathToWriteTo)
  196. #Loop over all files in the directory from the back-ups.
  197. #We will check the creation date of every back-up.
  198. for file in srv.listdir(pathToWriteTo):
  199. #Get the full path
  200. fullpath = os.path.join(pathToWriteTo,file)
  201. #Get the timestamp from the file on the external server
  202. timestamp = srv.stat(fullpath).st_atime
  203. createtime = datetime.datetime.fromtimestamp(timestamp)
  204. now = datetime.datetime.now()
  205. delta = now - createtime
  206. #If the file is older than the daystokeepsftp (the days to keep that the user filled in on the Odoo form it will be removed.
  207. if delta.days >= rec.daystokeepsftp:
  208. #Only delete files, no directories!
  209. if srv.isfile(fullpath) and ".dump" in file:
  210. print("Delete: " + file)
  211. srv.unlink(file)
  212. #Close the SFTP session.
  213. srv.close()
  214. except Exception, e:
  215. _logger.debug('Exception! We couldn\'t back up to the FTP server..')
  216. #At this point the SFTP backup failed. We will now check if the user wants
  217. #an e-mail notification about this.
  218. if rec.sendmailsftpfail:
  219. try:
  220. ir_mail_server = self.pool.get('ir.mail_server')
  221. message = "Dear,\n\nThe backup for the server " + rec.host + " (IP: " + rec.sftpip + ") failed.Please check the following details:\n\nIP address SFTP server: " + rec.sftpip + "\nUsername: " + rec.sftpusername + "\nPassword: " + rec.sftppassword + "\n\nError details: " + tools.ustr(e) + "\n\nWith kind regards"
  222. msg = ir_mail_server.build_email("auto_backup@" + rec.name + ".com", [rec.emailtonotify], "Backup from " + rec.host + "(" + rec.sftpip + ") failed", message)
  223. ir_mail_server.send_email(cr, user, msg)
  224. except Exception:
  225. pass
  226. """Remove all old files (on local server) in case this is configured..
  227. This is done after the SFTP writing to prevent unusual behaviour:
  228. If the user would set local back-ups to be kept 0 days and the SFTP
  229. to keep backups xx days there wouldn't be any new back-ups added to the
  230. SFTP.
  231. If we'd remove the dump files before they're writen to the SFTP there willbe nothing to write. Meaning that if an user doesn't want to keep back-ups locally and only wants them on the SFTP (NAS for example) there wouldn't be any writing to the remote server if this if statement was before the SFTP write method right above this comment.
  232. """
  233. if rec.autoremove is True:
  234. dir = rec.bkp_dir
  235. #Loop over all files in the directory.
  236. for f in os.listdir(dir):
  237. fullpath = os.path.join(dir, f)
  238. timestamp = os.stat(fullpath).st_ctime
  239. createtime = datetime.datetime.fromtimestamp(timestamp)
  240. now = datetime.datetime.now()
  241. delta = now - createtime
  242. if delta.days >= rec.daystokeep:
  243. #Only delete files (which are .dump), no directories.
  244. if os.path.isfile(fullpath) and ".dump" in f:
  245. print("Delete: " + fullpath)
  246. os.remove(fullpath)
  247. db_backup()
  248. # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: