Exemplo n.º 1
0
def new_dump_db(db_name, stream, backup_format='zip', anonymized=True):
    if anonymized:
        with RegistryManager.new(db_name).cursor() as cr:
            env = api.Environment(cr, SUPERUSER_ID, {})
            anon_query = env['ir.model.fields'].get_anonymization_query()
        if not anon_query:
            db._logger.info("No data to anonymize in database `%s`.", db_name)
        else:
            db._logger.info('Anonymize and dump database `%s`.', db_name)
            anon_db_name = '%s_anon_%s' % (db_name,
                                           time.strftime('%Y%m%d_%H%M%S'))
            db.exp_duplicate_database(db_name, anon_db_name)
            try:
                if backup_format == 'zip':
                    # To avoid to archive filestore
                    # with non-anonymized attachments
                    anon_fs = tools.config.filestore(anon_db_name)
                    shutil.rmtree(anon_fs, ignore_errors=True)
                with RegistryManager.new(anon_db_name).cursor() as cr:
                    db._logger.info('ANONYMIZE DB: %s', anon_db_name)
                    cr.execute(anon_query)
            except Exception:
                db.exp_drop(anon_db_name)
            return NewDbDump(anon_db_name, stream, backup_format)
    return native_dump_db(db_name, stream, backup_format)
Exemplo n.º 2
0
    def _create_db(self, template_db, db_name, demo, lang='en_US'):
        """Synchronous db creation"""
        if self.type == 'local':
            # to avoid installing extra modules we need this condition
            if tools.config['init']:
                tools.config['init'] = {}

            # we don't need tests in templates and builds
            test_enable = tools.config['test_enable']
            if test_enable:
                tools.config['test_enable'] = {}

        for r in self:
            if r.type != 'local':
                continue

            if template_db:
                db._drop_conn(self.env.cr, template_db)
                db.exp_duplicate_database(template_db, db_name)
            else:
                db.exp_create_database(
                    db_name, demo, lang)

        if test_enable:
            tools.config['test_enable'] = test_enable
Exemplo n.º 3
0
    def apply_duplicate(self):
        new_db = self.name + '.' + self.domain
        saas_portal_database = self.env['saas_portal.database']
        if saas_portal_database.search([('name', '=', new_db)]):
            raise ValidationError(
                _("This database already exists: "
                  "'%s'") % new_db
            )
        db._drop_conn(self.env.cr, self.cur_client_id.name)
        db.exp_duplicate_database(self.cur_client_id.name, new_db)

        vals = {
            'subdomain': self.name,
            'server_id': self.current_server_id.id,
            'plan_id': self.old_plan_id.id,
            'partner_id': self.partner_id and self.partner_id.id or None,
        }
        client = self.env['saas_portal.client'].create(vals)
        client.server_id.action_sync_server()
        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'saas_portal.client',
            'res_id': client.id,
            'target': 'current',
        }
    def duplicate_template(self):
        new_db = self.new_name + '.' + self.template_id.domain
        if self.template_id:
            saas_portal_database = self.env['saas_portal.database']
            if saas_portal_database.search([('name', '=', new_db)]):
                raise ValidationError(
                    _("This database already exists: "
                      "'%s'") % new_db)
            db._drop_conn(self.env.cr, self.template_id.name)
            db.exp_duplicate_database(self.template_id.name, new_db)
            new_template = saas_portal_database.create({
                'subdomain':
                self.new_name,
                'server_id':
                self.template_id.server_id.id,
                'db_primary_lang':
                self.lang,
                'state':
                'template',
                'db_type':
                'template'
            })
            if self.lang:
                with self.registry().cursor() as cr:
                    env = api.Environment(cr, SUPERUSER_ID, self._context)
                    # load a new language:
                    load_language(env.cr, self.lang)
                    # set this language for all partner records:
                    for partner in env['res.partner'].search([]):
                        partner.lang = self.lang
                    # if website is installed, also load the language
                    if env['ir.module.module'].search([
                        ('name', '=', 'website')
                    ]).state in ('installed', 'to upgrade'):
                        website = env["website"].get_current_website()
                        wiz = env["base.language.install"].create(
                            {"lang": self.lang})
                        wiz.website_ids = website
                        wiz.lang_install()
                        res_lang_id = env['res.lang'].search([('code', '=',
                                                               self.lang)])
                        if res_lang_id:
                            # make it a default website language
                            website.default_lang_id = res_lang_id

            action = self.env.ref('saas_portal.action_templates').read()[0]
            if action:
                action['views'] = [
                    (self.env.ref('saas_portal.view_databases_form').id,
                     'form')
                ]
                action['res_id'] = new_template.ids[0]
            else:
                action = {'type': 'ir.actions.act_window_close'}
            return action
Exemplo n.º 5
0
    def client_db_duplicate(self, db=None, new_dbname=None, **params):
        if not new_dbname:
            raise werkzeug.exceptions.BadRequest(
                "New database name not specified")
        if service_db.exp_db_exist(new_dbname):
            raise werkzeug.exceptions.Conflict(
                description="Database %s already exists" % new_dbname)

        _logger.info("Duplicate database: %s -> %s", db, new_dbname)
        service_db.exp_duplicate_database(db, new_dbname)
        return Response('OK', status=200)
Exemplo n.º 6
0
 def create_database(self, template_db=None, demo=False, lang='en_US'):
     self.ensure_one()
     new_db = self.name
     res = {}
     if template_db:
         db._drop_conn(self.env.cr, template_db)
         db.exp_duplicate_database(template_db, new_db)
     else:
         password = random_password()
         res.update({'superuser_password': password})
         db.exp_create_database(new_db, demo, lang, user_password=password)
     self.state = 'open'
     return res
Exemplo n.º 7
0
    def create_database(self, template_db=None, demo=False, lang='en_US'):
        self.ensure_one()
        new_db = self.db_name
        res = {}
        if new_db in database.list_dbs():
            raise UserError(_('Database Already Exist!'))
        if template_db:
            database._drop_conn(self.env.cr, template_db)
            database.exp_duplicate_database(template_db, new_db)
        else:
            # password = random_password()
            # res.update({'superuser_password': password})
            database.exp_create_database(new_db, demo, lang)
        if not self.is_template_db:
            self.upgrade_database({'params': True})
        _logger.info('Database created Successfully')

        return res
Exemplo n.º 8
0
    def create_db(self, template_db, db_name, demo, lang="en_US"):
        # to avoid installing extra modules we need this condition
        if tools.config["init"]:
            tools.config["init"] = {}

        # we don't need tests in templates and builds
        test_enable = tools.config["test_enable"]
        if test_enable:
            tools.config["test_enable"] = {}

        try:
            if template_db:
                # TODO: does drop connection works ok?
                with sql_db.db_connect(template_db).cursor() as cr:
                    db._drop_conn(cr, template_db)
                db.exp_duplicate_database(template_db, db_name)
            else:
                db.exp_create_database(db_name, demo, lang)

        finally:
            if test_enable:
                tools.config["test_enable"] = test_enable
Exemplo n.º 9
0
    def _create_db(self, template_db, db_name, demo, lang='en_US'):
        """Synchronous db creation"""
        if not self:
            return
        elif self.type != 'local':
            raise NotImplementedError()

        # to avoid installing extra modules we need this condition
        if tools.config['init']:
            tools.config['init'] = {}

        test_enable = tools.config['test_enable']
        if test_enable:
            tools.config['test_enable'] = {}

        # we don't need tests in templates and builds
        with turn_off_tests():
            if template_db:
                db._drop_conn(self.env.cr, template_db)
                db.exp_duplicate_database(template_db, db_name)
            else:
                db.exp_create_database(db_name, demo, lang)
Exemplo n.º 10
0
    def add_language_templates(self):
        if not self.language_ids:
            raise ValidationError(_("Please select language(s)!"))
        if self.template_id and self.language_ids:
            saas_portal_database = self.env['saas_portal.database']
            # first check if there are existing databases
            for language in self.language_ids:
                dbname = (self.prefix or '') + language.iso_code + (
                    self.suffix or '') + '.' + self.template_id.domain
                if saas_portal_database.search([('name', '=', dbname)]):
                    raise ValidationError(
                        _("This database already exists: "
                          "'%s'") % dbname)
            if self.plan_id and self.plan_id.product_tmpl_id:
                for attr in self.plan_id.product_tmpl_id.attribute_line_ids:
                    if attr.attribute_id and attr.attribute_id.saas_code == 'lang':
                        lang_attr = attr
                        break
            for language in self.language_ids:
                subdomain = (self.prefix
                             or '') + language.iso_code + (self.suffix or '')
                dbname = "%s.%s" % (subdomain, self.template_id.domain)
                db._drop_conn(self.env.cr, self.template_id.name)
                db.exp_duplicate_database(self.template_id.name, dbname)
                new_template = saas_portal_database.create({
                    'subdomain':
                    subdomain,
                    'server_id':
                    self.template_id.server_id.id,
                    'db_primary_lang':
                    language.code,
                    'plan_ids': [(4, self.plan_id.id)],
                    'state':
                    'template'
                })
                with self.registry(dbname).cursor() as cr:
                    env = api.Environment(cr, SUPERUSER_ID, self._context)
                    # load a new language:
                    load_language(env.cr, language.code)
                    # set this language for all partner records:
                    for partner in env['res.partner'].search([]):
                        partner.lang = language.code
                    # if website is installed, also load the language
                    if env['ir.module.module'].search([
                        ('name', '=', 'website')
                    ]).state in ('installed', 'to upgrade'):
                        website = env["website"].get_current_website()
                        wiz = env["base.language.install"].create(
                            {"lang": language.code})
                        wiz.website_ids = website
                        wiz.lang_install()
                        res_lang_id = env['res.lang'].search([('code', '=',
                                                               language.code)])
                        if res_lang_id:
                            # make it a default website language
                            website.default_lang_id = res_lang_id
                if lang_attr:
                    attr_value = self.env['product.attribute.value'].search([
                        ('name', '=', language.name),
                        ('attribute_id', '=', lang_attr.attribute_id.id)
                    ])
                    if attr_value:
                        attr_value.template_ids = [(4, new_template.id)]
                        self.plan_id.product_tmpl_id.write({
                            'attribute_line_ids': [(1, lang_attr.id, {
                                'value_ids': [(4, attr_value.id)]
                            })]
                        })
                    else:
                        lang_attr.value_ids = [(0, 0, {
                            'name':
                            language.name,
                            'attribute_id':
                            lang_attr.attribute_id.id,
                            'saas_lang':
                            language.code,
                            'template_ids': [(4, new_template.id)]
                        })]

            action = {'type': 'ir.actions.act_window_close'}
            return action