From 9ab00e9ef1abdca285389453cc2dd94a3ee1e962 Mon Sep 17 00:00:00 2001 From: archetipo Date: Tue, 21 Jul 2015 17:56:45 +0200 Subject: [PATCH] [RF] porting to new api [FIX] schedule_backup method [IMP] IT translation [IMP] tests --- auto_backup/__init__.py | 1 + auto_backup/__openerp__.py | 18 +- auto_backup/data/autobackup_mail_template.xml | 27 ++ auto_backup/i18n/it.po | 363 ++++++++++++++++++ auto_backup/model/backup_scheduler.py | 361 +++++++++-------- auto_backup/security/ir.model.access.csv | 2 + auto_backup/tests/__init__.py | 22 ++ auto_backup/tests/test_auto_backup.py | 64 +++ 8 files changed, 667 insertions(+), 191 deletions(-) create mode 100644 auto_backup/data/autobackup_mail_template.xml create mode 100644 auto_backup/i18n/it.po create mode 100644 auto_backup/security/ir.model.access.csv create mode 100644 auto_backup/tests/__init__.py create mode 100644 auto_backup/tests/test_auto_backup.py diff --git a/auto_backup/__init__.py b/auto_backup/__init__.py index b90f7bb08..084d03697 100644 --- a/auto_backup/__init__.py +++ b/auto_backup/__init__.py @@ -21,4 +21,5 @@ ############################################################################## from . import model +from . import tests # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/auto_backup/__openerp__.py b/auto_backup/__openerp__.py index 64f232256..e51b28e38 100644 --- a/auto_backup/__openerp__.py +++ b/auto_backup/__openerp__.py @@ -23,17 +23,23 @@ { "name" : "Database Auto-Backup", "version" : "1.0", - "author" : "VanRoey.be - Yenthe Van Ginneken, Agile Business Group", + "author" :( + "VanRoey.be - Yenthe Van Ginneken, Agile Business Group," + " Odoo Community Association (OCA)" + ), "website" : "http://www.vanroey.be/applications/bedrijfsbeheer/odoo", "category" : "Tools", "summary": "Backups data base", - "depends" : ['base'], - "init_xml" : [], - "demo_xml" : [], - "update_xml" : [ - "view/bkp_conf_view.xml", + "depends" : ['base','email_template'], + "demo_xml" : [ "data/backup_data.xml" ], + "data" : [ + "view/bkp_conf_view.xml", + "data/backup_data.xml", + "data/autobackup_mail_template.xml", + "security/ir.model.access.csv" + ], "active": False, "installable": True } diff --git a/auto_backup/data/autobackup_mail_template.xml b/auto_backup/data/autobackup_mail_template.xml new file mode 100644 index 000000000..f3a2d7858 --- /dev/null +++ b/auto_backup/data/autobackup_mail_template.xml @@ -0,0 +1,27 @@ + + + + + + Auto Backup Error notification + auto_backup@${object.name} + Backup from ${object.host} - (${object.sftpip}) failed + ${object.emailtonotify} + + + Dear,

+ +

The backup for the server ${object.host} (IP: ${object.sftpip}) failed.

+

Please check the following details:

+

IP address SFTP server: ${object.sftpip}

+

Username: ${object.sftpusername}

+

Password: ${object.sftppassword}

+

Error details: ${object.lasterrorlog}

+

With kind regards

+ + ]]>
+
+ +
+
\ No newline at end of file diff --git a/auto_backup/i18n/it.po b/auto_backup/i18n/it.po new file mode 100644 index 000000000..5137ea788 --- /dev/null +++ b/auto_backup/i18n/it.po @@ -0,0 +1,363 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * auto_backup +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 8.0\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2015-07-21 13:00+0000\n" +"PO-Revision-Date: 2015-07-21 13:00+0000\n" +"Last-Translator: <>\n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: \n" + +#. module: auto_backup +#: model:email.template,body_html:auto_backup.email_template_autobackup_error_noificaiton +msgid "\n" +" \n" +"

Dear,

\n" +"\n" +"

The backup for the server ${object.host} (IP: ${object.sftpip}) failed.

\n" +"

Please check the following details:

\n" +"

IP address SFTP server: ${object.sftpip}

\n" +"

Username: ${object.sftpusername}

\n" +"

Password: ${object.sftppassword}

\n" +"

Error details: ${object.lasterrorlog}

\n" +"

With kind regards

\n" +"\n" +" " +msgstr "\n" +" \n" +"

Buongiorno,

\n" +"\n" +"

Il backup del DB del server ${object.host} (IP: ${object.sftpip}) e' fallito.

\n" +"

Si prega di controllare le seguenti impostazioni:

\n" +"

Indirizzo IP server SFTP: ${object.sftpip}

\n" +"

Username: ${object.sftpusername}

\n" +"

Password: ${object.sftppassword}

\n" +"

Dettaglio errore: ${object.lasterrorlog}

\n" +"

Cordiali Saluti

\n" +"\n" +" " + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:204 +#, python-format +msgid "\n" +"Your IP address seems to be too short.\n" +"" +msgstr "\n" +"L' indirizzo IP sembra essere troppo corto.\n" +"" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:209 +#, python-format +msgid "%s" +msgstr "%s" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:288 +#, python-format +msgid "(Part of the) path didn't exist. Creating it now at %s" +msgstr "(Una parte del) path non esiste. Verra' creato in %s" + +#. module: auto_backup +#: help:db.backup,bkp_dir:0 +msgid "Absolute path for storing the backups" +msgstr "Percorso assoluto per il salvataggio del DB" + +#. module: auto_backup +#: field:db.backup,sendmailsftpfail:0 +msgid "Auto. E-mail on backup fail" +msgstr "Auto. E-mail nel caso di errori durante il backup " + +#. module: auto_backup +#: field:db.backup,autoremove:0 +msgid "Auto. Remove Backups" +msgstr "Rimuovi Backups" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Automatic backups of the database can be scheduled as follows:" +msgstr "Il backup automatico del DB e' pianificato come segue:" + +#. module: auto_backup +#: field:db.backup,bkp_dir:0 +msgid "Backup Directory" +msgstr "Backup Directory" + +#. module: auto_backup +#: model:email.template,subject:auto_backup.email_template_autobackup_error_noificaiton +msgid "Backup from ${object.host} - (${object.sftpip}) failed" +msgstr "Backup da ${object.host} - (${object.sftpip}) fallito" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_tree +msgid "Backups" +msgstr "Backups" + +#. module: auto_backup +#: help:db.backup,daystokeepsftp:0 +msgid "Choose after how many days the backup should be deleted from the FTP server. For example:\n" +"If you fill in 5 the backups will be removed after 5 days from the FTP server." +msgstr "Scegliere dopo quanti giorni si possa condsiderare da eliminare, un Backup nel server FTP. Per esempio:\n" +"se si imposta 5 i files di backups piu' vecchi di 5 giorni saranno eliminati dal server FTP" + +#. module: auto_backup +#: help:db.backup,daystokeep:0 +msgid "Scegliere dopo quanti giorni si possa condsiderare da eliminare un Backup. For example:\n" +"If you fill in 5 the backups will be removed after 5 days." +msgstr "Choose after how many days the backup should be deleted. For example:\n" +"se si imposta 5 i files di backups piu' vecchi di 5 giorni saranno eliminati." + +#. module: auto_backup +#: model:ir.actions.act_window,name:auto_backup.action_backup_conf_form +#: model:ir.ui.menu,name:auto_backup.backup_conf_menu +msgid "Configure Backup" +msgstr "Configura Backup" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:202 +#, python-format +msgid "Connection Test Failed!" +msgstr "Test connessione Fallito!" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:198 +#, python-format +msgid "Connection Test Succeeded!" +msgstr "Test connessione avvenuto con successo!" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:241 +#, python-format +msgid "Couldn't backup database %s. Bad database administratorpassword for server running at http://%s:%s" +msgstr "Impossibile eseguire il backup di %s. DB password erraata per il server http://%s:%s" + +#. module: auto_backup +#: field:db.backup,create_uid:0 +msgid "Created by" +msgstr "Created by" + +#. module: auto_backup +#: field:db.backup,create_date:0 +msgid "Created on" +msgstr "Created on" + +#. module: auto_backup +#: field:db.backup,name:0 +msgid "Database" +msgstr "Database" + +#. module: auto_backup +#: help:db.backup,name:0 +msgid "Database you want to schedule backups for" +msgstr "Database you want to schedule backups for" + +#. module: auto_backup +#: field:db.backup,emailtonotify:0 +#: field:db.backup,lasterrorlog:0 +msgid "E-mail to notify" +msgstr "E-mail di notifica" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:176 +#, python-format +msgid "Error" +msgstr "Errore" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:176 +#, python-format +msgid "Error ! No such database exists!" +msgstr "Errore ! Il DB non esiste!" + +#. module: auto_backup +#: code:addons/auto_backup/model/backup_scheduler.py:199 +#, python-format +msgid "Everything seems properly set up for FTP back-ups!" +msgstr "Tutto sembra impostato correttamente per il back-up FTP!" + +#. module: auto_backup +#: help:db.backup,emailtonotify:0 +#: help:db.backup,lasterrorlog:0 +msgid "Fill in the e-mail where you want to be notified that the backup failed on the FTP." +msgstr "Compilare l'e -mail in cui si desidera essere avvisati,se il backup FTP fallisce." + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "For example: /odoo/backups/" +msgstr "Es.: /odoo/backups/" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Go to Settings / Technical / Automation / Scheduled Actions." +msgstr "Anadare in Settings / Technical / Automation / Scheduled Actions." + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Help" +msgstr "Aiuto" + +#. module: auto_backup +#: field:db.backup,host:0 +msgid "Host" +msgstr "Host" + +#. module: auto_backup +#: field:db.backup,id:0 +msgid "ID" +msgstr "ID" + +#. module: auto_backup +#: field:db.backup,sftpip:0 +msgid "IP Address SFTP Server" +msgstr "IP Address SFTP Server" + +#. module: auto_backup +#: help:db.backup,sendmailsftpfail:0 +msgid "If you check this option you can choose to automaticly get e-mailed when the backup to the external server failed." +msgstr "Se si seleziona questa opzione è possibile scegliere di essere notificati automaticamente via e-mail quando il backup al server esterno fallisce ." + +#. module: auto_backup +#: help:db.backup,autoremove:0 +msgid "If you check this option you can choose to automaticly remove the backup after xx days" +msgstr "Se si seleziona questa opzione è possibile scegliere di rimuovere automaticamente il backup dopo xx giorni" + +#. module: auto_backup +#: help:db.backup,sftpwrite:0 +msgid "If you check this option you can specify the details needed to write to a remote server with SFTP." +msgstr "Se si seleziona questa opzione è possibile specificare i dettagli necessari per scrivere a un server remoto con SFTP ." + +#. module: auto_backup +#: field:db.backup,write_uid:0 +msgid "Last Updated by" +msgstr "Last Updated by" + +#. module: auto_backup +#: field:db.backup,write_date:0 +msgid "Last Updated on" +msgstr "Last Updated on" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Local backup configuration" +msgstr "Configurazione backup locale" + +#. module: auto_backup +#: field:db.backup,sftppassword:0 +msgid "Password User SFTP Server" +msgstr "Password utene SFTP Server" + +#. module: auto_backup +#: field:db.backup,sftppath:0 +msgid "Path external server" +msgstr "Path server esterno" + +#. module: auto_backup +#: field:db.backup,port:0 +msgid "Port" +msgstr "Porta" + +#. module: auto_backup +#: field:db.backup,daystokeepsftp:0 +msgid "Remove SFTP after x days" +msgstr "Rimuovi backup da SFTP dopo x giorni" + +#. module: auto_backup +#: field:db.backup,daystokeep:0 +msgid "Remove after x days" +msgstr "Rimuovi dopo x giorni" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "SFTP" +msgstr "SFTP" + +#. module: auto_backup +#: field:db.backup,sftpport:0 +msgid "SFTP Port" +msgstr "Porta SFTP" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_search +msgid "Search options" +msgstr "Search options" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Search the action named 'Backup scheduler'." +msgstr "Cerca l'azione denominata ' di pianificazione del backup ' ." + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Set the scheduler to active and fill in how often you want backups generated." +msgstr "Impostare lo scheduler per attivare e compilare la frequenza con cui si desidera generare il backup." + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Test" +msgstr "Test" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Test SFTP Connection" +msgstr "Test SFTP Connection" + +#. module: auto_backup +#: help:db.backup,sftpip:0 +msgid "The IP address from your remote server. For example 192.168.0.1" +msgstr "Indirizzo IP server remoto. Es. 192.168.0.1" + +#. module: auto_backup +#: help:db.backup,sftppath:0 +msgid "The location to the folder where the dumps should be written to. For example /odoo/backups/.\n" +"Files will then be written to /odoo/backups/ on your remote server." +msgstr "La posizione della cartella in cui i dumps devono essere scritti. Es. /odoo/backups/.\n" +"i files verranno scritti su /odoo/backups/ nel server remoto." + +#. module: auto_backup +#: help:db.backup,sftppassword:0 +msgid "The password from the user where the SFTP connection should be made with. This is the password from the user on the external server." +msgstr "La password dell'utente con cui la connessione SFTP deve essere fatta. Questa è la password dall'utente sul server esterno ." + +#. module: auto_backup +#: help:db.backup,sftpport:0 +msgid "The port on the FTP server that accepts SSH/SFTP calls." +msgstr "La porta sul server FTP che accetta chiamate SSH / SFTP." + +#. module: auto_backup +#: help:db.backup,sftpusername:0 +msgid "The username where the SFTP connection should be made with. This is the user on the external server." +msgstr "Il nome utente in cui la connessione SFTP dovrebbe essere fatto con . Questo è l'utente sul server esterno." + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "This configures the scheduler for automatic backup of the given database running on given host at given port on regular intervals." +msgstr "pianificazione per il backup automatico del database in esecuzione su dato host /porta ad intervalli regolari." + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Use SFTP with caution! This writes files to external servers under the path you specify." +msgstr "Usare SFTP con cautela ! Questo scrive file su server esterni nel percorso specificato " + +#. module: auto_backup +#: field:db.backup,sftpusername:0 +msgid "Username SFTP Server" +msgstr "Username SFTP Server" + +#. module: auto_backup +#: view:db.backup:auto_backup.view_backup_conf_form +msgid "Warning:" +msgstr "Warning:" + +#. module: auto_backup +#: field:db.backup,sftpwrite:0 +msgid "Write to external server with sftp" +msgstr "Salva il backup anche su server FTP esterno" + diff --git a/auto_backup/model/backup_scheduler.py b/auto_backup/model/backup_scheduler.py index 2c719ddcd..96ed67072 100644 --- a/auto_backup/model/backup_scheduler.py +++ b/auto_backup/model/backup_scheduler.py @@ -2,7 +2,7 @@ ############################################################################## # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved -# $Id$ +# Copyright 2015 Agile Business Group # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -33,9 +33,10 @@ except ImportError: 'through SFTP.Please install pysftp on your system.' '(sudo pip install pysftp)' ) -from openerp.osv import fields, osv +from openerp import models, fields, api, _ +from openerp.exceptions import except_orm, Warning from openerp import tools -from openerp import netsvc, _ +from openerp import netsvc import logging _logger = logging.getLogger(__name__) @@ -48,142 +49,146 @@ def execute(connector, method, *args): raise e return res -addons_path = tools.config['addons_path'] + '/auto_backup/DBbackups' - -class db_backup(osv.Model): +class db_backup(models.Model): _name = 'db.backup' - def get_db_list(self, cr, user, ids, host, port, context={}): - print("Host: " + host) - print("Port: " + port) - uri = 'http://' + host + ':' + port - conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db') + def get_connection(self, host, port): + uri = 'http://%s:%s' % (host, port) + return xmlrpclib.ServerProxy(uri + '/xmlrpc/db') + + def get_db_list(self, host, port): + conn = self.get_connection(host, port) db_list = execute(conn, 'list') return db_list - def _get_db_name(self, cr, uid, vals, context=None): - # attach_pool = self.pool.get("ir.logging") - dbName = cr.dbname - return dbName + @api.model + def _get_db_name(self): + return self.env.cr.dbname - _columns = { - # Columns local server - 'host': fields.char('Host', size=100, required='True'), - 'port': fields.char('Port', size=10, required='True'), - 'name': fields.char( - 'Database', size=100, required='True', - help='Database you want to schedule backups for' - ), - 'bkp_dir': fields.char( - 'Backup Directory', size=100, - help='Absolute path for storing the backups', - required='True' - ), - 'autoremove': fields.boolean( - 'Auto. Remove Backups', - help=( - "If you check this option you can choose to " - "automaticly remove the backup after xx days" - ) - ), - 'daystokeep': fields.integer( - 'Remove after x days', - 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 - ), - # Columns for external server (SFTP) - '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." - ) - ), - '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." - ) - ), - 'sftpip': fields.char( - 'IP Address SFTP Server', - help=( - "The IP address from your remote" - " server. For example 192.168.0.1" - ) - ), - 'sftpport': fields.integer( - "SFTP Port", - help="The port on the FTP server that accepts SSH/SFTP calls." - ), - '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." - ) - ), - '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." - ) - ), - '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." - ) - ), - '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." - ) - ), - '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." - ) - ), - } - - _defaults = { - # 'bkp_dir' : lambda *a : addons_path, - 'bkp_dir': '/odoo/backups', - 'host': 'localhost', - 'port': '8069', - 'name': _get_db_name, - 'daystokeepsftp': 30, - 'sftpport': 22, - } + # Columns local server + host = fields.Char( + string='Host', default='localhost', size=100, required=True) + port = fields.Char( + string='Port', default='8069', size=10, required=True) + name = fields.Char( + string='Database', size=100, required=True, + default=_get_db_name, + help='Database you want to schedule backups for' + ) + bkp_dir = fields.Char( + string='Backup Directory', size=100, + default='/odoo/backups', + help='Absolute path for storing the backups', + required=True + ) + autoremove = fields.Boolean( + string='Auto. Remove Backups', + help=( + "If you check this option you can choose to " + "automaticly remove the backup after xx days" + ) + ) + daystokeep = fields.Integer( + string='Remove after x days', + default=30, + 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 + ) + sftpwrite = fields.Boolean( + string='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." + ) + ) + sftppath = fields.Char( + string='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." + ) + ) + sftpip = fields.Char( + string='IP Address SFTP Server', + help=( + "The IP address from your remote" + " server. For example 192.168.0.1" + ) + ) + sftpport = fields.Integer( + string="SFTP Port", + default=22, + help="The port on the FTP server that accepts SSH/SFTP calls." + ) + sftpusername = fields.Char( + string='Username SFTP Server', + help=( + "The username where the SFTP connection " + "should be made with. This is the user on the external server." + ) + ) + sftppassword = fields.Char( + string='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." + ) + ) + daystokeepsftp = fields.Integer( + string='Remove SFTP after x days', + default=30, + 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." + ) + ) + sendmailsftpfail = fields.Boolean( + string='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." + ) + ) + emailtonotify = fields.Char( + string='E-mail to notify', + help=( + "Fill in the e-mail where you want to be" + " notified that the backup failed on the FTP." + ) + ) + lasterrorlog = fields.Text( + string='E-mail to notify', + help=( + "Fill in the e-mail where you want to be" + " notified that the backup failed on the FTP." + ) + ) - def _check_db_exist(self, cr, user, ids): - for rec in self.browse(cr, user, ids): - db_list = self.get_db_list(cr, user, ids, rec.host, rec.port) + @api.multi + def _check_db_exist(self): + for rec in self: + db_list = self.get_db_list(rec.host, rec.port) if rec.name in db_list: return True - return False + return False _constraints = [ - (_check_db_exist, _('Error ! No such database exists!'), []) + ( + _check_db_exist, + _('Error ! No such database exists!'), ['name'] + ) ] - def test_sftp_connection(self, cr, uid, ids, context=None): - conf_ids = self.search(cr, uid, []) - confs = self.browse(cr, uid, conf_ids) + @api.multi + def test_sftp_connection(self): + confs = self.search([]) # Check if there is a success or fail and write messages messageTitle = "" messageContent = "" @@ -211,38 +216,35 @@ class db_backup(osv.Model): "\nYour IP address seems to be too short.\n") messageContent += "Here is what we got instead:\n" if "Failed" in messageTitle: - raise osv.except_osv( + raise except_orm( _(messageTitle), _( messageContent + "%s") % tools.ustr(e)) else: - raise osv.except_osv(_(messageTitle), _(messageContent)) + raise Warning(_(messageTitle), _(messageContent)) - def schedule_backup(self, cr, user, context={}): - conf_ids = self.search(cr, user, []) - confs = self.browse(cr, user, conf_ids) - for rec in confs: - db_list = self.get_db_list(cr, user, [], rec.host, rec.port) + @api.model + def schedule_backup(self): + for rec in self.search([]): + db_list = self.get_db_list(rec.host, rec.port) if rec.name in db_list: + file_path = '' + bkp_file = '' try: if not os.path.isdir(rec.bkp_dir): os.makedirs(rec.bkp_dir) except: raise # Create name for dumpfile. - bkp_file = '%s_%s.dump' % ( + bkp_file = '%s_%s.dimp.zip' % ( time.strftime('%d_%m_%Y_%H_%M_%S'), rec.name) file_path = os.path.join(rec.bkp_dir, bkp_file) - uri = 'http://' + rec.host + ':' + rec.port - conn = xmlrpclib.ServerProxy(uri + '/xmlrpc/db') + conn = self.get_connection(rec.host, rec.port) bkp = '' try: bkp = execute( - conn, - 'dump', - tools.config['admin_passwd'], - rec.name) + conn, 'dump', tools.config['admin_passwd'], rec.name) except: _logger.notifyChannel( 'backup', netsvc.LOG_INFO, @@ -251,7 +253,7 @@ class db_backup(osv.Model): "Bad database administrator" "password for server running at http://%s:%s" ) % (rec.name, rec.host, rec.port)) - continue + return False bkp = base64.decodestring(bkp) fp = open(file_path, 'wb') fp.write(bkp) @@ -261,7 +263,7 @@ class db_backup(osv.Model): 'backup', netsvc.LOG_INFO, "database %s doesn't exist on http://%s:%s" % (rec.name, rec.host, rec.port)) - + return False # Check if user wants to write to SFTP or not. if rec.sftpwrite is True: try: @@ -282,7 +284,6 @@ class db_backup(osv.Model): # user made a typo in his path with multiple slashes # (/odoo//backups/) it will be fixed by this regex. pathToWriteTo = re.sub('([/]{2,5})+', '/', pathToWriteTo) - print(pathToWriteTo) try: srv.chdir(pathToWriteTo) except IOError: @@ -308,7 +309,6 @@ class db_backup(osv.Model): for f in os.listdir(dir): fullpath = os.path.join(dir, f) if os.path.isfile(fullpath): - print(fullpath) srv.put(fullpath) # Navigate in to the correct folder. @@ -319,19 +319,23 @@ class db_backup(osv.Model): for file in srv.listdir(pathToWriteTo): # Get the full path fullpath = os.path.join(pathToWriteTo, file) - # Get the timestamp from the file on the external - # server - timestamp = srv.stat(fullpath).st_atime - createtime = datetime.datetime.fromtimestamp(timestamp) - now = datetime.datetime.now() - delta = now - createtime - # 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. - if delta.days >= rec.daystokeepsftp: - # Only delete files, no directories! - if srv.isfile(fullpath) and ".dump" in file: - print("Delete: " + file) + if srv.isfile(fullpath) and ".dump.zip" in file: + # Get the timestamp from the file on the external + # server + timestamp = srv.stat(fullpath).st_atime + createtime = ( + datetime.datetime.fromtimestamp(timestamp) + ) + now = datetime.datetime.now() + delta = now - createtime + # 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. + if ( + rec.daystokeepsftp > 0 and + delta.days >= rec.daystokeepsftp + ): + # Only delete files, no directories! srv.unlink(file) # Close the SFTP session. srv.close() @@ -345,25 +349,13 @@ class db_backup(osv.Model): # an e-mail notification about this. if rec.sendmailsftpfail: try: - ir_mail_server = self.pool.get('ir.mail_server') - message = ( - "Dear,\n\nThe backup for the server %s" - " (IP: %s) failed.Please check" - " the following details:\n\n" - "IP address SFTP server: %s \nUsername: %s" - "\nPassword: %s" - "\n\nError details: %s \n\nWith kind regards" - ) % ( - rec.host, rec.sftpip, rec.sftpip, - rec.sftpusername, rec.sftppassword, - tools.ustr(e) + self.write({'lasterrorlog': tools.ustr(e)}) + abk_template = self.env.ref( + 'auto_backup.' + 'email_template_autobackup_error_noificaiton', + False ) - msg = ir_mail_server.build_email( - "auto_backup@" + rec.name + ".com", - [rec.emailtonotify], - "Backup from " + rec.host + "(" + rec.sftpip + - ") failed", message) - ir_mail_server.send_email(cr, user, msg) + abk_template.send_mail(self.id) except Exception: pass @@ -383,17 +375,16 @@ class db_backup(osv.Model): dir = rec.bkp_dir # Loop over all files in the directory. for f in os.listdir(dir): - fullpath = os.path.join(dir, f) - timestamp = os.stat(fullpath).st_ctime - createtime = datetime.datetime.fromtimestamp(timestamp) - now = datetime.datetime.now() - delta = now - createtime - if delta.days >= rec.daystokeep: - # Only delete files (which are .dump), no directories. - if os.path.isfile(fullpath) and ".dump" in f: - print("Delete: " + fullpath) + if os.path.isfile(fullpath) and ".dump.zip" in f: + fullpath = os.path.join(dir, f) + timestamp = os.stat(fullpath).st_ctime + createtime = ( + datetime.datetime.fromtimestamp(timestamp) + ) + now = datetime.datetime.now() + delta = now - createtime + if delta.days >= rec.daystokeep: os.remove(fullpath) - -db_backup() + return True # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/auto_backup/security/ir.model.access.csv b/auto_backup/security/ir.model.access.csv new file mode 100644 index 000000000..f5de02b31 --- /dev/null +++ b/auto_backup/security/ir.model.access.csv @@ -0,0 +1,2 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_db_backup,access_db_backup,model_db_backup,,1,0,0,0 \ No newline at end of file diff --git a/auto_backup/tests/__init__.py b/auto_backup/tests/__init__.py new file mode 100644 index 000000000..b35cb6653 --- /dev/null +++ b/auto_backup/tests/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# Copyright 2015 Agile Business Group +# Copyright (C) 2015 Alessio Gerace +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +from . import test_auto_backup \ No newline at end of file diff --git a/auto_backup/tests/test_auto_backup.py b/auto_backup/tests/test_auto_backup.py new file mode 100644 index 000000000..a94b40584 --- /dev/null +++ b/auto_backup/tests/test_auto_backup.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# Copyright 2015 Agile Business Group +# Copyright (C) 2015 Alessio Gerace +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import base64 +from openerp.tests import common +from openerp.exceptions import except_orm, Warning +from openerp.modules.module import get_module_resource +import os +import time +from datetime import datetime, date, timedelta + +class TestsAutoBackup(common.TransactionCase): + + def setUp(self): + super(TestsAutoBackup, self).setUp() + self.abk_model = self.env["db.backup"] + self.cron_model = self.env["ir.cron"] + + + def test_0(self): + with self.assertRaises(except_orm): + self.abk_model.create({'name': 'abcd'}) + + def test_1(self): + this = self.abk_model.create( + { + 'bkp_dir': '/tmp' + } + ) + self.assertEqual(this.host, 'localhost') + cronbk = self.cron_model.search([('name', '=', 'Backup scheduler')]) + import pdb;pdb.set_trace() + cronbk.write( + { + 'active': True, + 'doall': True + } + ) + filetime = ( + datetime.now() + timedelta(minutes=1) + ).strftime('%d_%m_%Y_%H_%M_%S') + + bkp_file = '%s_%s.dimp.zip' % ( + filetime, this.name) + file_path = os.path.join(this.bkp_dir, bkp_file) + self.assertEqual(os.path.isfile(file_path), True)