Exemplo n.º 1
0
 def client_db_restore(self,
                       db=None,
                       backup_file=None,
                       copy=False,
                       **params):
     if not db:
         raise werkzeug.exceptions.BadRequest("Database not specified")
     if service_db.exp_db_exist(db):
         raise werkzeug.exceptions.Conflict(
             description="Database %s already exists" % db)
     try:
         with tempfile.NamedTemporaryFile(delete=False) as data_file:
             backup_file.save(data_file)
         service_db.restore_db(db, data_file.name, str2bool(copy))
     except exceptions.AccessDenied as e:
         raise werkzeug.exceptions.Forbidden(description=str(e))
     except Exception as e:
         _logger.error("Cannot restore db %s", db, exc_info=True)
         raise werkzeug.exceptions.InternalServerError(
             "Cannot restore db (%s): %s" % (db, str(e)))
     else:
         self._postprocess_restored_db(db)
         return http.Response('OK', status=200)
     finally:
         os.unlink(data_file.name)
Exemplo n.º 2
0
def restore(ctx, db_name, copy, s3_file):
    config = (
        ctx.obj['config']
    )

    if update:
        config['update']['all'] = 1

    from odooku.backends import get_backend
    from odoo.api import Environment
    from odoo.service.db import restore_db

    s3_backend = get_backend('s3')

    with tempfile.NamedTemporaryFile(delete=False) as t:
        if s3_file:
            s3_backend.client.download_fileobj(s3_backend.bucket, s3_file, t)
        else:
            # Read from stdin
            while True:
                chunk = sys.stdin.read(CHUNK_SIZE)
                if not chunk:
                    break
                t.write(chunk)
        t.close()

        with Environment.manage():
            restore_db(
                db_name,
                t.name,
                copy=copy
            )

        os.unlink(t.name)
Exemplo n.º 3
0
    def restore_via_odoo_backup_sh(self,
                                   master_pwd,
                                   backup_file_name,
                                   name,
                                   encryption_password,
                                   copy=False):
        if config['admin_passwd'] != master_pwd:
            return env.get_template("backup_list.html").render(
                error="Incorrect master password")
        if os.path.exists(config.filestore(name)):
            return env.get_template("backup_list.html").render(
                error=
                'Filestore for database "{}" already exists. Please choose another database name'
                .format(name))
        cloud_params = self.get_cloud_params(request.httprequest.url,
                                             call_from='frontend')
        backup_object = BackupCloudStorage.get_object(
            cloud_params, filename=backup_file_name)
        backup_file = tempfile.NamedTemporaryFile()
        backup_file.write(backup_object['Body'].read())
        if backup_file_name.split('|')[0][-4:] == '.enc':
            if not encryption_password:
                raise UserError(
                    _('The backup are encrypted. But encryption password is not found. Please check your module settings.'
                      ))
            # GnuPG ignores the --output parameter with an existing file object as value
            decrypted_backup_file = tempfile.NamedTemporaryFile()
            decrypted_backup_file_name = decrypted_backup_file.name
            os.unlink(decrypted_backup_file_name)
            backup_file.seek(0)
            r = gnupg.GPG().decrypt_file(backup_file,
                                         passphrase=encryption_password,
                                         output=decrypted_backup_file_name)
            if not r.ok:
                error = 'gpg: {0}'.format(r.status)
                if not r.valid:
                    error += ". Maybe wrong password?"
                return env.get_template("backup_list.html").render(error=error)
            backup_file = open(decrypted_backup_file_name, 'rb')
        try:
            db.restore_db(name, backup_file.name, str2bool(copy))
            # Make all auto backup cron records inactive
            with closing(db_connect(name).cursor()) as cr:
                cr.autocommit(True)
                try:
                    cr.execute("""
                        UPDATE ir_cron SET active=false
                        WHERE active=true AND id IN (SELECT ir_cron_id FROM odoo_backup_sh_config_cron);

                        UPDATE odoo_backup_sh_config SET active=false WHERE active=true;
                    """)
                except Exception:
                    pass
            return http.local_redirect('/web/database/manager')
        except Exception as e:
            error = "Database restore error: %s" % (str(e) or repr(e))
            return env.get_template("backup_list.html").render(error=error)
        finally:
            os.unlink(backup_file.name)
Exemplo n.º 4
0
 def restore(self, master_pwd, backup_file, name, copy=False):
     try:
         data_file = None
         db.check_super(master_pwd)
         with tempfile.NamedTemporaryFile(delete=False) as data_file:
             backup_file.save(data_file)
         db.restore_db(name, data_file.name, str2bool(copy))
         return http.local_redirect('/web/v2/manager')
     except Exception as e:
         error = "Database restore error: %s" % (str(e) or repr(e))
         return self._render_template(error=error)
     finally:
         if data_file:
             os.unlink(data_file.name)
 def test_exp_database_backup_restore(self):
     dispatch_rpc('db', 'create_database', [
         MASTER_PASSWORD, "muk_dms_file_create_db_test", False, "en",
         "admin", "admin"
     ])
     self.assertTrue('muk_dms_file_create_db_test' in db_list())
     dump_stream = dump_db("muk_dms_file_create_db_test", None, 'zip')
     with tempfile.NamedTemporaryFile(delete=False) as data_file:
         data_file.write(dump_stream.read())
     restore_db('muk_dms_file_restore_db_test', data_file.name, True)
     self.assertTrue('muk_dms_file_restore_db_test' in db_list())
     dispatch_rpc('db', 'drop',
                  [MASTER_PASSWORD, 'muk_dms_file_restore_db_test'])
     dispatch_rpc('db', 'drop',
                  [MASTER_PASSWORD, 'muk_dms_file_create_db_test'])
     self.assertTrue('muk_dms_file_create_db_test' not in db_list())
     self.assertTrue('muk_dms_file_restore_db_test' not in db_list())
Exemplo n.º 6
0
 def restore(self, master_pwd, backup_file, name, copy=False):
     insecure = odoo.tools.config.verify_admin_password('admin')
     if insecure and master_pwd:
         dispatch_rpc('db', 'change_admin_password', ["admin", master_pwd])
     try:
         data_file = None
         db.check_super(master_pwd)
         with tempfile.NamedTemporaryFile(delete=False) as data_file:
             backup_file.save(data_file)
         db.restore_db(name, data_file.name, str2bool(copy))
         return request.redirect('/web/database/manager')
     except Exception as e:
         error = "Database restore error: %s" % (str(e) or repr(e))
         return self._render_template(error=error)
     finally:
         if data_file:
             os.unlink(data_file.name)
Exemplo n.º 7
0
    def restore(self):
        self.ensure_one()
        if not self.env.user._is_superuser() and not self.env.user.has_group('base.group_system'):
            raise AccessError(_("Only administrators can change the settings"))

        dbname = self._cr.dbname
        restore_name = self.restore_name
        request.session.logout()
        request.disable_db = True
        request._cr = None
        exp_drop(dbname)
        restore_db(dbname, restore_name)
        return {
            'type': 'ir.actions.act_url',
            'url': '/web/login',
            'target': 'self',
        }
Exemplo n.º 8
0
    def restore_database(self, **post):
        state = simplejson.loads(post.get('state'))

        origin_uri = state['origin_uri']
        access_token = post['access_token']
        saas_oauth_provider = request.env.ref(
            'saas_server.saas_oauth_provider').sudo()

        user_data = request.env['res.users'].sudo()._auth_oauth_rpc(
            saas_oauth_provider.validation_endpoint,
            access_token,
            local_host=saas_oauth_provider.local_host,
            local_port=saas_oauth_provider.local_port)
        if user_data.get("error"):
            raise Exception(user_data['error'])

        res = requests.get(origin_uri, stream=True)
        res.raise_for_status()

        db_name = "restored_" + datetime.datetime.now().strftime(
            "%Y%m%d_%H%M%S")

        with tempfile.TemporaryDirectory() as tmp_dir:
            filename = tmp_dir + "/" + db_name + ".zip"
            _logger.info("started downloaded database dump")
            with open(filename, "wb") as f:
                for chunk in res.iter_content(16 * 1024):
                    f.write(chunk)

            _logger.info("finished downloaded database dump")

            _logger.info("started restoring ...")
            restore_db(db_name, filename)
            _logger.info("finished restoring ...")

        return db_name