def generate(self, cr, uid, ids, context=None):
        """
        context used to specify export_mode
        export_mode can be:
        - same_thread_raise_error (default)
        - same_thread_rollback_and_continue
        - new_thread
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        export_mode = context.get('export_mode', 'same_thread_rollback_and_continue')

        for export_id in ids:
            logger = SmileDBLogger(cr.dbname, 'ir.model.export', export_id, uid)
            if export_mode == 'new_thread':
                t = threading.Thread(target=self._generate_with_new_cursor, args=(cr.dbname, uid, export_id, logger, context))
                t.start()
            else:
                cr.execute('SAVEPOINT smile_export')
                try:
                    self._generate(cr, uid, export_id, logger, context)
                except Exception, e:
                    if export_mode == 'same_thread_rollback_and_continue':
                        cr.execute("ROLLBACK TO SAVEPOINT smile_export")
                        logger.error("Export rollbacking - Error: %s" % _get_exception_message(e))
                    else:  # same_thread_raise_error
                        raise e
    def generate(self, cr, uid, ids, context=None):
        """
        context used to specify export_mode
        export_mode can be:
        - same_thread_raise_error (default)
        - same_thread_rollback_and_continue
        - new_thread
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        export_mode = context.get('export_mode',
                                  'same_thread_rollback_and_continue')

        for export_id in ids:
            logger = SmileDBLogger(cr.dbname, 'ir.model.export', export_id,
                                   uid)
            if export_mode == 'new_thread':
                t = threading.Thread(target=self._generate_with_new_cursor,
                                     args=(cr.dbname, uid, export_id, logger,
                                           context))
                t.start()
            else:
                cr.execute('SAVEPOINT smile_export')
                try:
                    self._generate(cr, uid, export_id, logger, context)
                except Exception, e:
                    if export_mode == 'same_thread_rollback_and_continue':
                        cr.execute("ROLLBACK TO SAVEPOINT smile_export")
                        logger.error("Export rollbacking - Error: %s" %
                                     _get_exception_message(e))
                    else:  # same_thread_raise_error
                        raise e
 def unlink_res_ids(self, cr, uid, ids, model, res_ids, context):
     unlink_line_ids = []
     for template in self.browse(cr, uid, ids, context):
         if template.model != model:
             raise except_orm(
                 _('Error'),
                 _("unlink_res_ids: model(%s) does not match template model (%s, %s)"
                   ) % (model, template.id, template.model))
         export_line_ids = self.pool.get('ir.model.export.line').search(
             cr,
             uid, [
                 ('export_id.export_tmpl_id', '=', template.id),
                 ('res_id', 'in', res_ids),
             ],
             context=context)
         if export_line_ids:
             real_res_ids = [
                 line['res_id']
                 for line in self.pool.get('ir.model.export.line').read(
                     cr, uid, export_line_ids, ['res_id'], context)
             ]
             logger = SmileDBLogger(cr.dbname, 'ir.model.export.template',
                                    template.id, uid)
             logger.info(
                 'Unlinking model: %s, res_ids: %s - real_res_ids found: %s'
                 % (model, res_ids, real_res_ids))
             self.pool.get('ir.model.export.line').unlink(
                 cr, uid, export_line_ids, context)
             unlink_line_ids.extend(export_line_ids)
     return unlink_line_ids
 def unlink_res_ids(self, cr, uid, ids, model, res_ids, context):
     unlink_line_ids = []
     for template in self.browse(cr, uid, ids, context):
         if template.model != model:
             raise except_orm(_('Error'), _("unlink_res_ids: model(%s) does not match template model (%s, %s)")
                              % (model, template.id, template.model))
         export_line_ids = self.pool.get('ir.model.export.line').search(cr, uid, [('export_id.export_tmpl_id', '=', template.id),
                                                                                  ('res_id', 'in', res_ids),
                                                                                  ], context=context)
         if export_line_ids:
             real_res_ids = [line['res_id'] for line in self.pool.get('ir.model.export.line').read(cr, uid, export_line_ids, ['res_id'], context)]
             logger = SmileDBLogger(cr.dbname, 'ir.model.export.template', template.id, uid)
             logger.info('Unlinking model: %s, res_ids: %s - real_res_ids found: %s' % (model, res_ids, real_res_ids))
             self.pool.get('ir.model.export.line').unlink(cr, uid, export_line_ids, context)
             unlink_line_ids.extend(export_line_ids)
     return unlink_line_ids
    def create_export(self, cr, uid, ids, context=None):
        """
        context used to specify export_mode
        export_mode can be:
        - same_thread_raise_error
        - same_thread_rollback_and_continue (default)
        - new_thread
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        context.setdefault('export_mode', 'same_thread_rollback_and_continue')
        export_obj = self.pool.get('ir.model.export')
        export_ids = []
        for export_template in self.browse(cr, uid, ids, context):
            try:
                res_ids = self._get_res_ids(cr, uid, export_template, context)
                if export_template.unique:
                    old_res_ids = self.get_exported_res_ids(cr, uid, export_template.id, context)
                    res_ids = list(set(res_ids) - set(old_res_ids))

                res_ids_list = []
                if export_template.limit:
                    i = 0
                    while(res_ids[i: i + export_template.limit]):
                        if export_template.max_offset and i == export_template.max_offset * export_template.limit:
                            break
                        res_ids_list.append(res_ids[i: i + export_template.limit])
                        i += export_template.limit
                else:
                    res_ids_list = [res_ids]

                vals = {
                    'export_tmpl_id': export_template.id,
                    'state': 'running',
                }
                for index, export_res_ids in enumerate(res_ids_list):
                    if export_template.link_resources:
                        vals['line_ids'] = [(0, 0, {'res_id': res_id}) for res_id in export_res_ids]
                    else:
                        vals['resource_ids'] = export_res_ids
                    vals['offset'] = index + 1
                    export_ids.append(export_obj.create(cr, uid, vals, context))
            except Exception, e:
                tmpl_logger = SmileDBLogger(cr.dbname, 'ir.model.import.template', export_template.id, uid)
                tmpl_logger.error(_get_exception_message(e))
                raise e
    def create_import(self, cr, uid, ids, context=None):
        """
        context used to specify:
         - import_error_management: 'rollback_and_continue' or 'raise' (default='raise', see _process function)
         - rollback_and_continue: True/False (default=True)
         - commit_and_new_thread: True/False (default=False) = rollback_and_continue but in a new thread
         if commit_and_new_thread or rollback_and_continue= True, import_error_management is forced to rollback_and_continue
        returns a list: [import_id1, ...]
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        import_obj = self.pool.get('ir.model.import')

        import_name = context.get('import_name', '')
        test_mode = context.get('test_mode', False)

        import_ids = []
        for template in self.browse(cr, uid, ids, context):
            tmpl_logger = SmileDBLogger(cr.dbname, 'ir.model.import.template', template.id, uid)
            try:
                import_name = import_name or template.name
                import_id = import_obj.create(cr, uid, {
                    'name': import_name,
                    'import_tmpl_id': template.id,
                    'test_mode': test_mode,
                    'state': 'started',
                    'from_date': time.strftime('%Y-%m-%d %H:%M:%S'),
                }, context)
                import_ids.append(import_id)
                logger = SmileDBLogger(cr.dbname, 'ir.model.import', import_id, uid)
                import_obj.write(cr, uid, import_id, {'pid': logger.pid}, context)
                if context.get('commit_and_new_thread'):
                    cr.commit()
                    t = threading.Thread(target=import_obj._process_with_new_cursor, args=(cr.dbname, uid, import_id, logger, context))
                    t.start()
                elif context.get('rollback_and_continue', True):
                    cr.commit()
                    import_obj._process_with_new_cursor(cr.dbname, uid, import_id, logger, context)
                else:
                    import_obj._process_import(cr, uid, import_id, logger, context)
            except Exception, e:
                tmpl_logger.error(_get_exception_message(e))
                raise e
    def create_export(self, cr, uid, ids, context=None):
        """
        context used to specify export_mode
        export_mode can be:
        - same_thread_raise_error
        - same_thread_rollback_and_continue (default)
        - new_thread
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        context.setdefault('export_mode', 'same_thread_rollback_and_continue')
        export_pool = self.pool.get('ir.model.export')
        export_ids = []
        for export_template in self.browse(cr, uid, ids, context):
            context['logger'] = SmileDBLogger(cr.dbname,
                                              'ir.model.export.template',
                                              export_template.id, uid)
            res_ids = self._get_res_ids(cr, uid, export_template, context)
            if export_template.unique:
                old_res_ids = self.get_exported_res_ids(
                    cr, uid, export_template.id, context)
                res_ids = list(set(res_ids) - set(old_res_ids))

            res_ids_list = []
            if export_template.limit:
                i = 0
                while (res_ids[i:i + export_template.limit]):
                    if export_template.max_offset and i == export_template.max_offset * export_template.limit:
                        break
                    res_ids_list.append(res_ids[i:i + export_template.limit])
                    i += export_template.limit
            else:
                res_ids_list = [res_ids]

            vals = {
                'export_tmpl_id': export_template.id,
                'state': 'running',
            }
            for index, export_res_ids in enumerate(res_ids_list):
                if export_template.link_resources:
                    vals['line_ids'] = [(0, 0, {
                        'res_id': res_id
                    }) for res_id in export_res_ids]
                else:
                    vals['resource_ids'] = export_res_ids
                vals['offset'] = index + 1
                export_ids.append(
                    export_pool.create_new_cr(cr.dbname, uid, vals, context))

        export_pool.generate(cr, uid, export_ids, context)
        return export_ids
    def create_import(self, cr, uid, ids, context=None):
        """
        context used to specify:
         - import_error_management: 'rollback_and_continue' or 'raise' (default='raise', see _process function)
         - commit_and_new_thread: True/False (default=False)
         if commit_and_new_thread = True, import_error_management is forced to rollback_and_continue

        returns a dict: {'template_id1': import_id1, ...}
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        import_obj = self.pool.get('ir.model.import')

        import_name = context.get('import_name', '')
        test_mode = context.get('test_mode', False)
        commit_and_new_thread = context.get('commit_and_new_thread', False)

        result = {}

        for template in self.browse(cr, uid, ids, context):
            import_name = import_name or template.name

            logger = SmileDBLogger(cr.dbname, 'ir.model.import.template',
                                   template.id, uid)
            import_id = import_obj.create(
                cr, uid, {
                    'name': import_name,
                    'import_tmpl_id': template.id,
                    'test_mode': test_mode,
                    'pid': logger.pid,
                    'state': 'started',
                    'from_date': time.strftime('%Y-%m-%d %H:%M:%S'),
                }, context)

            result[template.id] = import_id

            if commit_and_new_thread:
                cr.commit()
                t = threading.Thread(
                    target=import_obj._process_with_new_cursor,
                    args=(cr.dbname, uid, import_id, logger, context))
                t.start()
            else:
                import_obj._process_import(cr, uid, import_id, logger, context)
        return result
    def generate(self, cr, uid, ids, context=None):
        """
        context used to specify:
         - export_error_management: 'rollback_and_continue' or 'raise' (default='raise', see _generate function)
         - commit_and_new_thread: True/False (default=False)
         if commit_and_new_thread = True, export_error_management is forced to rollback_and_continue
        """
        if isinstance(ids, (int, long)):
            ids = [ids]
        context = context or {}
        commit_and_new_thread = context.get('commit_and_new_thread', False)

        for export_id in ids:
            logger = SmileDBLogger(cr.dbname, 'ir.model.export', export_id, uid)
            if commit_and_new_thread:
                cr.commit()
                t = threading.Thread(target=self._generate_with_new_cursor, args=(cr.dbname, uid, export_id, logger, context))
                t.start()
            else:
                self._generate(cr, uid, export_id, logger, context)
        return True
Example #10
0
    def _run_now(self, cr, uid, trigger_id, context):
        logger = SmileDBLogger(cr.dbname, self._name, trigger_id, uid)

        # Get sequence in order to differentiate logs per run
        context.setdefault('pid_list',
                           []).append(str(logger.pid).rjust(8, '0'))
        pid = '-'.join((str(x) for x in context['pid_list']))
        if not pid:
            logger.critical(
                'Action Trigger failed: impossible to get a pid for dbname %s'
                % (cr.dbname))
            return

        # Get sequence in order to differentiate logs per run
        if context.get('test_mode', False):
            logger.info('[%s] Trigger in test mode' % (pid, ))
        logger.debug('[%s] Trigger on %s' %
                     (pid, context.get('trigger', 'manual')))
        logger.debug('[%s] Context: %s' % (pid, context))
        trigger = self.browse(cr, uid, trigger_id, context)

        # Filter objects
        filtered_object_ids = []
        try:
            filtered_object_ids = self._get_filtered_object_ids(
                cr, uid, trigger, context)
            logger.debug('[%s] Successful Objects Filtering: %s' %
                         (pid, filtered_object_ids))
        except Exception, e:
            logger.exception('[%s] Objects Filtering failed: %s' %
                             (pid, _get_exception_message(e)))
            if trigger.exception_handling == 'continue' or trigger.exception_warning == 'none':
                return True
            else:
                cr.rollback()
                logger.time_info("[%s] Transaction rolled back" % (pid, ))
                if trigger.exception_warning == 'custom':
                    raise orm.except_orm(
                        _('Error'),
                        _('%s\n[Pid: %s]') % (trigger.exception_message, pid))
                elif trigger.exception_warning == 'native':
                    raise orm.except_orm(
                        _('Error'),
                        _('%s\n[Pid: %s]') % (_get_exception_message(e), pid))
    def _run_now(self, cr, uid, trigger_id, context):
        logger = SmileDBLogger(cr.dbname, self._name, trigger_id, uid)

        # Get sequence in order to differentiate logs per run
        context.setdefault('pid_list', []).append(str(logger.pid).rjust(8, '0'))
        pid = '-'.join((str(x) for x in context['pid_list']))
        if not pid:
            logger.critical('Action Trigger failed: impossible to get a pid for dbname %s' % (cr.dbname))
            return

        # Get sequence in order to differentiate logs per run
        if context.get('test_mode', False):
            logger.info('[%s] Trigger in test mode' % (pid,))
        logger.debug('[%s] Trigger on %s' % (pid, context.get('trigger', 'manual')))
        logger.debug('[%s] Context: %s' % (pid, context))
        trigger = self.browse(cr, uid, trigger_id, context)

        # Filter objects
        filtered_object_ids = []
        try:
            filtered_object_ids = self._get_filtered_object_ids(cr, uid, trigger, context)
            logger.debug('[%s] Successful Objects Filtering: %s' % (pid, filtered_object_ids))
        except Exception, e:
            logger.exception('[%s] Objects Filtering failed: %s' % (pid, _get_exception_message(e)))
            if trigger.exception_handling == 'continue' or trigger.exception_warning == 'none':
                return True
            else:
                cr.rollback()
                logger.time_info("[%s] Transaction rolled back" % (pid,))
                if trigger.exception_warning == 'custom':
                    raise orm.except_orm(_('Error'), _('%s\n[Pid: %s]') % (trigger.exception_message, pid))
                elif trigger.exception_warning == 'native':
                    raise orm.except_orm(_('Error'), _('%s\n[Pid: %s]') % (_get_exception_message(e), pid))