예제 #1
0
 def dispatch(self, service_name, method, params):
     try:
         self.log('service', service_name)
         self.log('method', method)
         self.log('params', replace_request_password(params))
         auth = getattr(self, 'auth_proxy', None)
         result = ExportService.getService(service_name).dispatch(
             method, auth, params)
         self.log('result', result)
         # We shouldn't marshall None,
         if result == None:
             result = False
         return result
     except OpenERPDispatcherException:
         raise
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         tb = getattr(e, 'traceback', sys.exc_info())
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode']:
             import pdb
             pdb.post_mortem(tb[2])
         # TODO meaningful FaultCodes ..
         details = ''
         if len(e.args) > 1:
             details = e.args[1]
         raise OpenERPDispatcherException(e.args[0],
                                          details=details,
                                          traceback=tb_s)
        def print_thread(id, uid, ids, datas, context, printer):
            logger = netsvc.Logger()
            logger.notifyChannel("report", netsvc.LOG_DEBUG, "Printing thread started")

            cr = pooler.get_db(db).cursor()
            pool = pooler.get_pool(cr.dbname)

            exception_string = False
            exception_backtrace = False
            state = 'ready'
            result = False
            format = False

            service = netsvc.LocalService('report.'+object)
            try:
                (result, format) = service.create(cr, uid, ids, datas, context)
                result = base64.encodestring(result)
            except Exception, exception:
                import traceback
                import sys
                tb = sys.exc_info()
                tb_s = "".join(traceback.format_exception(*tb))
                logger = netsvc.Logger()
                logger.notifyChannel('web-services', netsvc.LOG_ERROR, 'Exception: %s\n%s' % (str(exception), tb_s))

                exception = ExceptionWithTraceback(tools.exception_to_unicode(exception), tb)
                self.exceptions_protect.acquire()
                self.exceptions[id] = exception
                self.exceptions_protect.release()

                state = 'error'
예제 #3
0
def dispatch_rpc(service_name, method, *params, **kwargs):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC or
    NET-RPC) is done in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + '.rpc.request')
        rpc_response = logging.getLogger(__name__ + '.rpc.response')
        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
        if rpc_request_flag or rpc_response_flag:
            start_time = time.time()
            if rpc_request and rpc_response_flag:
                log(rpc_request,logging.DEBUG,'%s.%s'%(service_name,method), replace_request_password(params))
        result = ExportService.getService(service_name).dispatch(method, *params, **kwargs)

        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            if rpc_response_flag:
                log(rpc_response,logging.DEBUG,'%s.%s time:%.3fs '%(service_name,method,end_time - start_time), result)
            else:
                log(rpc_request,logging.DEBUG,'%s.%s time:%.3fs '%(service_name,method,end_time - start_time), replace_request_password(params), depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.error(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #4
0
        def go(id, uid, ids, datas, context):
            cr = pooler.get_db(db).cursor()
            import traceback
            import sys
            try:
                obj = netsvc.LocalService('report.'+object)
                (result, format) = obj.create(cr, uid, ids, datas, context)
                if not result:
                    tb = sys.exc_info()
                    self._reports[id]['exception'] = ExceptionWithTraceback('RML is not available at specified location or not enough data to print!', tb)
                self._reports[id]['result'] = result
                self._reports[id]['format'] = format
                self._reports[id]['state'] = True
            except Exception, exception:

                tb = sys.exc_info()
                tb_s = "".join(traceback.format_exception(*tb))
                logger = netsvc.Logger()
                logger.notifyChannel('web-services', netsvc.LOG_ERROR,
                        'Exception: %s\n%s' % (str(exception), tb_s))
                if hasattr(exception, 'name') and hasattr(exception, 'value'):
                    self._reports[id]['exception'] = ExceptionWithTraceback(tools.ustr(exception.name), tools.ustr(exception.value))
                else:
                    self._reports[id]['exception'] = ExceptionWithTraceback(tools.exception_to_unicode(exception), tb)
                self._reports[id]['state'] = True
예제 #5
0
 def dispatch(self, service_name, method, params):
     try:
         auth = getattr(self, 'auth_provider', None)
         logger = logging.getLogger('result')
         start_time = end_time = 0
         if logger.isEnabledFor(logging.DEBUG_RPC_ANSWER):
             self.log('service', tuple(replace_request_password(params)), depth=None, fn='%s.%s'%(service_name,method))
         if logger.isEnabledFor(logging.DEBUG_RPC):
             start_time = time.time()
         result = ExportService.getService(service_name).dispatch(method, auth, params)
         if logger.isEnabledFor(logging.DEBUG_RPC):
             end_time = time.time()
         if not logger.isEnabledFor(logging.DEBUG_RPC_ANSWER):
             self.log('service (%.3fs)' % (end_time - start_time), tuple(replace_request_password(params)), depth=1, fn='%s.%s'%(service_name,method))
         self.log('execution time', '%.3fs' % (end_time - start_time), channel=logging.DEBUG_RPC_ANSWER)
         self.log('result', result, channel=logging.DEBUG_RPC_ANSWER)
         return result
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         tb = getattr(e, 'traceback', sys.exc_info())
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode'] and isinstance(tb[2], types.TracebackType):
             import pdb
             pdb.post_mortem(tb[2])
         raise OpenERPDispatcherException(e, tb_s)
예제 #6
0
        def go(id, uid, ids, datas, context):
            cr = pooler.get_db(db).cursor()
            import traceback
            import sys
            try:
                obj = netsvc.LocalService('report.'+object)
                bg_obj = pooler.get_pool(cr.dbname).get('memory.background.report')
                (result, format) = obj.create(cr, uid, ids, datas, context)
                if not result:
                    tb = sys.exc_info()
                    self._reports[id]['exception'] = ExceptionWithTraceback('RML is not available at specified location or not enough data to print!', tb)
                if context.get('background_id'):
                    bg_obj.update_percent(cr, uid, context['background_id'], {'percent': 1.00}, context=context)
                if isinstance(result, tools.misc.Path):
                    self._reports[id]['path'] = result.path
                    self._reports[id]['result'] = ''
                    self._reports[id]['delete'] = result.delete
                else:
                    self._reports[id]['result'] = result
                self._reports[id]['format'] = format
                self._reports[id]['state'] = True
            except Exception, exception:

                tb = sys.exc_info()
                tb_s = "".join(traceback.format_exception(*tb))
                logger = netsvc.Logger()
                logger.notifyChannel('web-services', netsvc.LOG_ERROR,
                        'Exception: %s\n%s' % (str(exception), tb_s))
                if hasattr(exception, 'name') and hasattr(exception, 'value'):
                    self._reports[id]['exception'] = ExceptionWithTraceback(tools.ustr(exception.name), tools.ustr(exception.value))
                else:
                    self._reports[id]['exception'] = ExceptionWithTraceback(tools.exception_to_unicode(exception), tb)
                self._reports[id]['state'] = True
예제 #7
0
 def _dispatch(self, method, params):
     try:
         service_name = self.path.split("/")[-1]
         return self.dispatch(service_name, method, params)
     except netsvc.OpenERPDispatcherException, e:
         raise xmlrpclib.Fault(tools.exception_to_unicode(e.exception),
                               e.traceback)
예제 #8
0
파일: netsvc.py 프로젝트: ascetic85/ziwei
    def run(self):
        import select
        self.running = True
        try:
            ts = tiny_socket.mysocket(self.sock) # 获取到socket
        except:
            self.sock.close()
            self.threads.remove(self)
            return False
        while self.running:
            try:
                msg = ts.myreceive() # 有请求
            except:
                self.sock.close()
                self.threads.remove(self)
                return False
            try:
                result = self.dispatch(msg[0], msg[1], msg[2:]) # 解析, 并获取相应结果 
                                                                # dispatch 在OpenERPDispatcher中实现
                ts.mysend(result) # 发送结果, 阻塞方式
            except OpenERPDispatcherException, e:
                new_e = Exception(tools.exception_to_unicode(e.exception)) # avoid problems of pickeling
                try:
                    ts.mysend(new_e, exception=True, traceback=e.traceback)
                except:
                    self.sock.close()
                    self.threads.remove(self)
                    return False

            self.sock.close()
            self.threads.remove(self)
            return True
예제 #9
0
def dispatch_rpc(service_name, method, params):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC or
    NET-RPC) is done in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + '.rpc.request')
        rpc_response = logging.getLogger(__name__ + '.rpc.response')
        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
        if rpc_request_flag or rpc_response_flag:
            start_time = time.time()
            start_rss, start_vms = 0, 0
            if psutil:
                start_rss, start_vms = psutil.Process(
                    os.getpid()).get_memory_info()
            if rpc_request and rpc_response_flag:
                log(rpc_request, logging.DEBUG,
                    '%s.%s' % (service_name, method),
                    replace_request_password(params))

        result = ExportService.getService(service_name).dispatch(
            method, params)

        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            end_rss, end_vms = 0, 0
            if psutil:
                end_rss, end_vms = psutil.Process(
                    os.getpid()).get_memory_info()
            logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (
                service_name, method, end_time - start_time, start_vms / 1024,
                end_vms / 1024, (end_vms - start_vms) / 1024)
            if rpc_response_flag:
                log(
                    rpc_response, logging.DEBUG, '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time), result)
            else:
                log(rpc_request,
                    logging.DEBUG,
                    '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time),
                    replace_request_password(params),
                    depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.exception(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #10
0
파일: ir_cron.py 프로젝트: Buyanbat/XacCRM
 def _callback(self, cr, uid, model, func, args):
     args = str2tuple(args)
     m = self.pool.get(model)
     if m and hasattr(m, func):
         f = getattr(m, func)
         try:
             f(cr, uid, *args)
         except Exception, e:
             self._logger.notifyChannel('timers', netsvc.LOG_ERROR, "Job call of self.pool.get('%s').%s(cr, uid, *%r) failed" % (model, func, args))
             self._logger.notifyChannel('timers', netsvc.LOG_ERROR, tools.exception_to_unicode(e))
예제 #11
0
파일: ir_cron.py 프로젝트: mrmoyeez/XacCRM
 def _callback(self, cr, uid, model, func, args):
     args = str2tuple(args)
     m = self.pool.get(model)
     if m and hasattr(m, func):
         f = getattr(m, func)
         try:
             f(cr, uid, *args)
         except Exception, e:
             self._logger.notifyChannel(
                 'timers', netsvc.LOG_ERROR,
                 "Job call of self.pool.get('%s').%s(cr, uid, *%r) failed" %
                 (model, func, args))
             self._logger.notifyChannel('timers', netsvc.LOG_ERROR,
                                        tools.exception_to_unicode(e))
예제 #12
0
def dispatch_rpc(service_name, method, *params, **kwargs):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC or
    NET-RPC) is done in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + '.rpc.request')
        rpc_response = logging.getLogger(__name__ + '.rpc.response')
        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
        if rpc_request_flag or rpc_response_flag:
            start_time = time.time()
            if rpc_request and rpc_response_flag:
                log(rpc_request, logging.DEBUG,
                    '%s.%s' % (service_name, method),
                    replace_request_password(params))
        result = ExportService.getService(service_name).dispatch(
            method, *params, **kwargs)

        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            if rpc_response_flag:
                log(
                    rpc_response, logging.DEBUG, '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time), result)
            else:
                log(rpc_request,
                    logging.DEBUG,
                    '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time),
                    replace_request_password(params),
                    depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.error(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #13
0
def dispatch_rpc(service_name, method, params):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC or
    NET-RPC) is done in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + '.rpc.request')
        rpc_response = logging.getLogger(__name__ + '.rpc.response')
        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
        if rpc_request_flag or rpc_response_flag:
            start_time = time.time()
            start_rss, start_vms = 0, 0
            if psutil:
                start_rss, start_vms = psutil.Process(os.getpid()).get_memory_info()
            if rpc_request and rpc_response_flag:
                log(rpc_request,logging.DEBUG,'%s.%s'%(service_name,method), replace_request_password(params))

        threading.current_thread().uid = None
        threading.current_thread().dbname = None
        result = ExportService.getService(service_name).dispatch(method, params)

        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            end_rss, end_vms = 0, 0
            if psutil:
                end_rss, end_vms = psutil.Process(os.getpid()).get_memory_info()
            logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (service_name, method, end_time - start_time, start_vms / 1024, end_vms / 1024, (end_vms - start_vms)/1024)
            if rpc_response_flag:
                log(rpc_response,logging.DEBUG, logline, result)
            else:
                log(rpc_request,logging.DEBUG, logline, replace_request_password(params), depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.exception(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #14
0
 def dispatch(self, service_name, method, params):
     try:
         logger = logging.getLogger('result')
         self.log('service', service_name)
         self.log('method', method)
         self.log('params', replace_request_password(params), depth=(None if logger.isEnabledFor(logging.DEBUG_RPC_ANSWER) else 1))
         auth = getattr(self, 'auth_provider', None)
         result = ExportService.getService(service_name).dispatch(method, auth, params)
         self.log('result', result, channel=logging.DEBUG_RPC_ANSWER)
         return result
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         tb = getattr(e, 'traceback', sys.exc_info())
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode']:
             import pdb
             pdb.post_mortem(tb[2])
         raise OpenERPDispatcherException(e, tb_s)
예제 #15
0
파일: netsvc.py 프로젝트: Unifield/ufcheck
 def dispatch(self, service_name, method, params):
     try:
         logger = logging.getLogger('result')
         self.log('service', service_name)
         self.log('method', method)
         self.log('params', replace_request_password(params), depth=(None if logger.isEnabledFor(logging.DEBUG_RPC_ANSWER) else 1))
         auth = getattr(self, 'auth_provider', None)
         result = ExportService.getService(service_name).dispatch(method, auth, params)
         self.log('result', result, channel=logging.DEBUG_RPC_ANSWER)
         return result
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         tb = getattr(e, 'traceback', sys.exc_info())
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode']:
             import pdb
             pdb.post_mortem(tb[2])
         raise OpenERPDispatcherException(e, tb_s)
예제 #16
0
    def dispatch(self, service_name, method, params):
        def _real_log(title, msg):
            self._logger.log(logging.DEBUG_RPC,
                             '%s: %s' % (title, pformat(msg)))

        try:
            if self._logger.isEnabledFor(logging.DEBUG_RPC):
                log = _real_log
            else:
                log = lambda *a: None
            log('service', service_name)
            log('method', method)
            log('params', params)
            auth = getattr(self, 'auth_proxy', None)
            if not auth:
                self._logger.warn("No Authentication!")
            result = ExportService.getService(service_name).new_dispatch(
                method, auth, params)
            log('result', result)
            # We shouldn't marshall None,
            if result == None:
                result = False
            return result
        except OpenERPDispatcherException:
            raise
        except Exception, e:
            log('exception', tools.exception_to_unicode(e))
            tb = getattr(e, 'traceback', sys.exc_info())
            tb_s = "".join(traceback.format_exception(*tb))
            if tools.config['debug_mode']:
                import pdb
                pdb.post_mortem(tb[2])
            details = ''
            if e.args:
                msg = e.args[0]
            else:
                msg = tools.ustr(e)
            if len(e.args) > 1:
                details = e.args[1]
            raise OpenERPDispatcherException(msg,
                                             details=details,
                                             traceback=tb_s)
예제 #17
0
파일: netsvc.py 프로젝트: Buyanbat/XacCRM
 def dispatch(self, service_name, method, params):
     try:
         self.log('service', service_name)
         self.log('method', method)
         self.log('params', params)
         auth = getattr(self, 'auth_provider', None)
         result = ExportService.getService(service_name).dispatch(method, auth, params)
         self.log('result', result)
         # We shouldn't marshall None,
         if result == None:
             result = False
         return result
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         tb = getattr(e, 'traceback', sys.exc_info())
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode']:
             import pdb
             pdb.post_mortem(tb[2])
         raise OpenERPDispatcherException(e, tb_s)
예제 #18
0
    def run(self):
        self.running = True
        try:
            ts = tiny_socket.mysocket(self.sock, self.is_gzip)
        except Exception:
            self.threads.remove(self)
            self.running = False
            return False

        while self.running:
            try:
                msg = ts.myreceive()
                result = self.dispatch(msg[0], msg[1], msg[2:])
                ts.mysend(result)
            except socket.timeout:
                #terminate this channel because other endpoint is gone
                break
            except netsvc.OpenERPDispatcherException, e:
                try:
                    new_e = Exception(tools.exception_to_unicode(
                        e.exception))  # avoid problems of pickeling
                    logging.getLogger('web-services').debug(
                        "netrpc: rpc-dispatching exception", exc_info=True)
                    ts.mysend(new_e, exception=True, traceback=e.traceback)
                except Exception:
                    #terminate this channel if we can't properly send back the error
                    logging.getLogger('web-services').exception(
                        "netrpc: cannot deliver exception message to client")
                    break
            except Exception, e:
                try:
                    tb = getattr(e, 'traceback', sys.exc_info())
                    tb_s = "".join(traceback.format_exception(*tb))
                    logging.getLogger('web-services').debug(
                        "netrpc: communication-level exception", exc_info=True)
                    ts.mysend(e, exception=True, traceback=tb_s)
                except Exception, ex:
                    #terminate this channel if we can't properly send back the error
                    logging.getLogger('web-services').exception(
                        "netrpc: cannot deliver exception message to client")
                    break
예제 #19
0
 def dispatch(self, service_name, method, params):
     try:
         self.log('service', service_name)
         self.log('method', method)
         self.log('params', params)
         auth = getattr(self, 'auth_provider', None)
         result = ExportService.getService(service_name).dispatch(
             method, auth, params)
         self.log('result', result)
         # We shouldn't marshall None,
         if result == None:
             result = False
         return result
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         tb = getattr(e, 'traceback', sys.exc_info())
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode']:
             import pdb
             pdb.post_mortem(tb[2])
         raise OpenERPDispatcherException(e, tb_s)
예제 #20
0
파일: netsvc.py 프로젝트: ascetic85/ziwei
 def dispatch(self, service_name, method, params):
     if service_name not in GROUPS['web-services']:
         raise Exception('AccessDenied')
     try:
         self.log('service', service_name)
         self.log('method', method)
         self.log('params', params)
         result = LocalService(service_name)(method, *params)
         self.log('result', result)
         return result
     except Exception, e:
         self.log('exception', tools.exception_to_unicode(e))
         if hasattr(e, 'traceback'):
             tb = e.traceback
         else:
             tb = sys.exc_info()
         tb_s = "".join(traceback.format_exception(*tb))
         if tools.config['debug_mode']:
             import pdb
             pdb.post_mortem(tb[2])
         raise OpenERPDispatcherException(e, tb_s)
예제 #21
0
 def go(id, uid, ids, datas, context):
     cr = pooler.get_db(db).cursor()
     import traceback
     import sys
     try:
         obj = netsvc.LocalService('report.'+object)
         (result, format) = obj.create(cr, uid, ids, datas, context)
         if not result:
             tb = sys.exc_info()
             self._reports[id]['exception'] = ExceptionWithTraceback('RML is not available at specified location or not enough data to print!', tb)
         self._reports[id]['result'] = result
         self._reports[id]['format'] = format
         self._reports[id]['state'] = True
     except Exception, exception:
         
         tb = sys.exc_info()
         tb_s = "".join(traceback.format_exception(*tb))
         logger = netsvc.Logger()
         logger.notifyChannel('web-services', netsvc.LOG_ERROR,
                 'Exception: %s\n%s' % (str(exception), tb_s))
         self._reports[id]['exception'] = ExceptionWithTraceback(tools.exception_to_unicode(exception), tb)
         self._reports[id]['state'] = True
예제 #22
0
    def run(self):
        self.running = True
        try:
            ts = tiny_socket.mysocket(self.sock, self.is_gzip)
        except Exception:
            self.threads.remove(self)
            self.running = False
            return False

        while self.running:
            try:
                msg = ts.myreceive()
                result = self.dispatch(msg[0], msg[1], msg[2:])
                ts.mysend(result)
            except socket.timeout:
                #terminate this channel because other endpoint is gone
                break
            except netsvc.OpenERPDispatcherException, e:
                try:
                    new_e = Exception(tools.exception_to_unicode(e.exception)) # avoid problems of pickeling
                    logging.getLogger('web-services').debug("netrpc: rpc-dispatching exception", exc_info=True)
                    ts.mysend(new_e, exception=True, traceback=e.traceback)
                except Exception:
                    #terminate this channel if we can't properly send back the error
                    logging.getLogger('web-services').exception("netrpc: cannot deliver exception message to client")
                    break
            except Exception, e:
                try:
                    tb = getattr(e, 'traceback', sys.exc_info())
                    tb_s = "".join(traceback.format_exception(*tb))
                    logging.getLogger('web-services').debug("netrpc: communication-level exception", exc_info=True)
                    ts.mysend(e, exception=True, traceback=tb_s)
                except Exception, ex:
                    #terminate this channel if we can't properly send back the error
                    logging.getLogger('web-services').exception("netrpc: cannot deliver exception message to client")
                    break
예제 #23
0
        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            if rpc_response_flag:
                log(rpc_response,logging.DEBUG,'%s.%s time:%.3fs '%(service_name,method,end_time - start_time), result)
            else:
                log(rpc_request,logging.DEBUG,'%s.%s time:%.3fs '%(service_name,method,end_time - start_time), replace_request_password(params), depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.error(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
    except Exception, e:
        _logger.error(hasattr(e, 'traceback') and traceback.print_tb(e.traceback) or tools.exception_to_unicode(e))
        post_mortem(sys.exc_info())
        raise

def post_mortem(info):
    if tools.config['debug_mode'] and isinstance(info[2], types.TracebackType):
        import pdb
        pdb.post_mortem(info[2])

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
예제 #24
0
def dispatch_rpc(service_name, method, params):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC) is done
    in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + '.rpc.request')
        rpc_response = logging.getLogger(__name__ + '.rpc.response')
        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
        if rpc_request_flag or rpc_response_flag:
            start_time = time.time()
            start_rss, start_vms = 0, 0
            start_rss, start_vms = psutil.Process(
                os.getpid()).get_memory_info()
            if rpc_request and rpc_response_flag:
                log(rpc_request, logging.DEBUG,
                    '%s.%s' % (service_name, method),
                    replace_request_password(params))

        threading.current_thread().uid = None
        threading.current_thread().dbname = None
        if service_name == 'common':
            dispatch = openerp.service.common.dispatch
        elif service_name == 'db':
            dispatch = openerp.service.db.dispatch
        elif service_name == 'object':
            dispatch = openerp.service.model.dispatch
        elif service_name == 'report':
            dispatch = openerp.service.report.dispatch
        else:
            dispatch = openerp.service.wsgi_server.rpc_handlers.get(
                service_name)
        result = dispatch(method, params)

        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            end_rss, end_vms = 0, 0
            end_rss, end_vms = psutil.Process(os.getpid()).get_memory_info()
            logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (
                service_name, method, end_time - start_time, start_vms / 1024,
                end_vms / 1024, (end_vms - start_vms) / 1024)
            if rpc_response_flag:
                log(rpc_response, logging.DEBUG, logline, result)
            else:
                log(rpc_request,
                    logging.DEBUG,
                    logline,
                    replace_request_password(params),
                    depth=1)

        return result
    except openerp.osv.orm.except_orm:
        raise
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.RedirectWarning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.exception(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #25
0
class dm_workitem(osv.osv):  # {{{
    _name = "dm.workitem"
    _description = "workitem"
    _SOURCES = [('address_id', 'Partner Address')]
    SELECTION_LIST = [('pending', 'Pending'), ('error', 'Error'),
                      ('cancel', 'Cancelled'), ('freeze', 'Frozen'),
                      ('done', 'Done')]

    def _get_id(self, cr, uid, ids, name, arg, context=None):
        if context is None:
            context = {}
        res = {}
        for wi in self.browse(cr, uid, ids, context):
            res[wi.id] = str(wi.id) or ''
        return res

    def _customer_id(self, cr, uid, ids, name, arg, context=None):
        if context is None:
            context = {}
        res = {}
        for wi in self.browse(cr, uid, ids, context):
            res[wi.id] = wi.address_id and wi.address_id.id or ''
        return res

    def _customer_email(self, cr, uid, ids, name, arg, context=None):
        if context is None:
            context = {}
        res = {}
        for wi in self.browse(cr, uid, ids, context):
            res[wi.id] = wi.address_id and wi.address_id.email or ''
        return res

    def id_search(self, cr, uid, obj, name, args, context={}):
        if not len(args):
            return []
        wi_id = args[0][2]
        if not wi_id:
            return []
        return [('id', 'in', [wi_id])]

    _columns = {
        'name':
        fields.function(_get_id,
                        method=True,
                        type='char',
                        string='ID',
                        fnct_search=id_search),
        'step_id':
        fields.many2one('dm.offer.step',
                        'Offer Step',
                        ondelete="cascade",
                        select="1"),
        'segment_id':
        fields.many2one('dm.campaign.proposition.segment',
                        'Segments',
                        select="1",
                        ondelete="cascade"),
        'address_id':
        fields.many2one('res.partner.address',
                        'Customer Address',
                        select="1",
                        ondelete="cascade"),
        'customer_id':
        fields.function(_customer_id,
                        method=True,
                        type='char',
                        string='Customer Id'),
        'customer_email':
        fields.function(_customer_email,
                        method=True,
                        type='char',
                        string='Customer Email'),
        'action_time':
        fields.datetime('Action Time', select="1"),
        'source':
        fields.selection(_SOURCES, 'Source', required=True),
        'error_msg':
        fields.text('System Message'),
        'is_preview':
        fields.boolean('Document Preview Workitem'),
        'tr_from_id':
        fields.many2one('dm.offer.step.transition',
                        'Source Transition',
                        ondelete="cascade"),
        'mail_service_id':
        fields.many2one('dm.mail_service', 'Mail Service'),
        'is_realtime':
        fields.boolean('Realtime Processing', select="1"),
        'state':
        fields.selection(SELECTION_LIST, 'Status', select="1"),
    }
    _defaults = {
        'source': lambda *a: 'address_id',
        'state': lambda *a: 'pending',
        'is_preview': lambda *a: False,
        'is_realtime': lambda *a: True,
        'action_time': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
    }

    def create(self, cr, uid, vals, context={}):
        id = super(dm_workitem, self).create(cr, uid, vals, context)
        obj = self.browse(cr, uid, id)
        if obj.is_realtime:
            wi_res = self.run(cr, uid, obj, context=context)
        return id


#    @tools.cache()

    @monitor
    def _check_sysmsg(self, cr, uid, code, context=None):
        """ Check action message code and set workitem log """
        sysmsg_id = self.pool.get('dm.sysmsg').search(cr,
                                                      uid,
                                                      [('code', '=', code)],
                                                      context=context)
        if sysmsg_id:
            sysmsg = self.pool.get('dm.sysmsg').browse(cr,
                                                       uid,
                                                       sysmsg_id,
                                                       context=context)[0]
            return {
                'state': sysmsg.state,
                'msg': sysmsg.message,
                'result': sysmsg.result
            }
        else:
            return {
                'state': 'error',
                'msg': "An unknown error has occured : %s" % code,
                'result': False
            }

    @monitor
    def run(self, cr, uid, wi, context={}):
        logger = netsvc.Logger()
        context['active_id'] = wi.id
        done = False
        ms_err = ''

        try:
            server_obj = self.pool.get('ir.actions.server')
            tr_res = True
            """ Check if action must be done or cancelled by checking the 
                            condition code of incoming transitions """
            for tr in wi.step_id.incoming_transition_ids:
                eval_context = {
                    'pool': self.pool,
                    'cr': cr,
                    'uid': uid,
                    'wi': wi,
                    'tr': tr,
                }
                val = {}
                """ Evaluate condition code (for non preview workitems only)"""
                if wi.is_preview:
                    val['action'] = True
                else:
                    exec tr.condition_id.in_act_cond.replace('\r','') in \
                                                 eval_context, val

                if not val.get('action', False):
                    """ If action returned by the trigger code is 
                                                            False stop here """
                    tr_res = False
                    act_step = tr.step_from_id.name or False
                    break

            if tr_res:
                "Execute server action"
                wi_res = server_obj.run(cr, uid, [wi.step_id.action_id.id],
                                        context)
                if not wi_res and wi.step_id.action_id.state == 'object_create':
                    # create object returns false ,asuming object is created
                    # state is set to done
                    self.write(cr, uid, [wi.id], {
                        'state': 'done',
                        'error_msg': 'Case is created'
                    })
                else:
                    """ Check returned code and set wi status """
                    wi_status = self._check_sysmsg(cr, uid, wi_res['code'],
                                                   context.copy())

                    "Set workitem state and message"
                    wr = self.write(cr, uid, [wi.id], {
                        'state': wi_status['state'],
                        'error_msg': wi_status['msg']
                    })
                    done = wi_status['result']
                    "If workitem done then execute mail service action"
                    if done:
                        doc_context = {}
                        doc_obj = self.pool.get(wi_res['model'])
                        for doc in doc_obj.browse(cr, uid, wi_res['ids']):
                            doc_context['active_id'] = doc.id
                            ms_res = server_obj.run(
                                cr, uid, [doc.mail_service_id.action_id.id],
                                doc_context)
                            ms_status = self._check_sysmsg(
                                cr, uid, ms_res['code'], context)
                            doc_obj.write(
                                cr, uid, [doc.id], {
                                    'state':
                                    ms_status['state'],
                                    'error_msg':
                                    'err_msg' in ms_res and ms_res['err_msg']
                                    or ms_status['msg'],
                                    'delivery_time':
                                    time.strftime('%Y-%m-%d  %H:%M:%S')
                                })
                            " If doc in error, change workitem status "
                            if not ms_status['result']:
                                # Attention : if 1 doc crashes => wi in error but other docs processed
                                # TODO : Add doc in error ref in wi error_msg
                                wr = self.write(
                                    cr, uid, [wi.id], {
                                        'state': ms_status['state'],
                                        'error_msg': ms_status['msg']
                                    })
                                done = False
            else:
                "Dont Execute Action if workitem is not to be processed"
                self.write(cr, uid, [wi.id], {
                    'state': 'cancel',
                    'error_msg': 'Cancelled by : %s' % act_step
                })

        except Exception, exception:
            tb = sys.exc_info()
            tb_s = "".join(traceback.format_exception(*tb))
            self.write(
                cr, uid, [wi.id], {
                    'state':
                    'error',
                    'error_msg':
                    'Exception: %s\n%s' %
                    (tools.exception_to_unicode(exception), tb_s)
                })
            netsvc.Logger().notifyChannel(
                'dm action', netsvc.LOG_ERROR, 'Exception: %s\n%s' %
                (tools.exception_to_unicode(exception), tb_s))
        """ Check if it has to create next auto workitems """
        if done and not wi.is_preview and wi.step_id.outgoing_transition_ids:
            try:
                for tr in wi.step_id.outgoing_transition_ids:
                    if tr.condition_id and tr.condition_id.gen_next_wi:
                        """ Compute action time """
                        wi_action_time = datetime.datetime.strptime(
                            wi.action_time, '%Y-%m-%d  %H:%M:%S')
                        kwargs = {(tr.delay_type + 's'): tr.delay}
                        next_action_time = wi_action_time + datetime.timedelta(
                            **kwargs)

                        if tr.action_hour:
                            """ If a static action hour is set, use it """
                            hour_str = str(tr.action_hour).split('.')[0] + ':' +\
                             str(int(int(str(tr.action_hour).split('.')[1]) * 0.6))
                            act_hour = datetime.datetime.strptime(
                                hour_str, '%H: % M')
                            next_action_time = next_action_time.replace(
                                hour=act_hour.hour)
                            next_action_time = next_action_time.replace(
                                minute=act_hour.minute)

                        if tr.action_day:
                            """ If a static action day of the month is set, use it """
                            next_action_time = next_action_time.replace(
                                day=int(tr.action_day))
                            if next_action_time.day > int(tr.action_day):
                                next_action_time = next_action_time.replace(
                                    month=next_action_time.month + 1)

                        if tr.action_date:
                            """ If a static date is set, use it """
                            next_action_time = tr.action_date

                        aw_id = self.copy(
                            cr, uid, wi.id, {
                                'step_id':
                                tr.step_to_id.id,
                                'tr_from_id':
                                tr.id,
                                'error_msg':
                                '',
                                'is_realtime':
                                False,
                                'action_time':
                                next_action_time.strftime('%Y-%m-%d  %H:%M:%S')
                            })

            except Exception, exception:
                tb = sys.exc_info()
                tb_s = "".join(traceback.format_exception(*tb))
                self.write(
                    cr, uid, [wi.id], {
                        'error_msg':
                        'Error while creating auto workitem:\nException: \
                %s\n%s' % (tools.exception_to_unicode(exception), tb_s)
                    })
                netsvc.Logger().notifyChannel(
                    'dm action - auto wi creation', netsvc.LOG_ERROR,
                    'Exception: %s\n%s' %
                    (tools.exception_to_unicode(exception), tb_s))
예제 #26
0
            if psutil:
                end_rss, end_vms = psutil.Process(os.getpid()).get_memory_info()
            logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (service_name, method, end_time - start_time, start_vms / 1024, end_vms / 1024, (end_vms - start_vms)/1024)
            if rpc_response_flag:
                log(rpc_response,logging.DEBUG, logline, result)
            else:
                log(rpc_request,logging.DEBUG, logline, replace_request_password(params), depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.exception(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
    except Exception, e:
        _logger.exception(tools.exception_to_unicode(e))
        post_mortem(sys.exc_info())
        raise

def post_mortem(info):
    if tools.config['debug_mode'] and isinstance(info[2], types.TracebackType):
        import pdb
        pdb.post_mortem(info[2])

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
예제 #27
0
def dispatch_rpc(service_name, method, params, kwargs=None):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC or
    NET-RPC) is done in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + '.rpc.request')
        rpc_response = logging.getLogger(__name__ + '.rpc.response')

        # Try checking up on the UID cache
        try:
            db_name = params[0]
        except:
            db_name = ''

        # Add a new RPC logger targetting a specific user
        try:
            uid = params[1]
        except:
            uid = 0

        rpc_user = logging.getLogger(__name__ + '.rpc.user.{}'.format(uid))

        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)

        # Add a new RPC logger targetting a specific user
        rpc_user_flag = rpc_user.isEnabledFor(logging.DEBUG)

        if rpc_request_flag or rpc_response_flag or rpc_user_flag:
            start_time = time.time()
            if rpc_request and rpc_response_flag:
                log(rpc_request, logging.DEBUG,
                    '%s.%s' % (service_name, method),
                    replace_request_password(params))
                log(rpc_request, logging.DEBUG,
                    '%s.%s KWARGS:' % (service_name, method), kwargs)

            if rpc_user_flag:
                log(rpc_user, logging.DEBUG, '%s.%s' % (service_name, method),
                    replace_request_password(params))
                log(rpc_user, logging.DEBUG,
                    '%s.%s KWARGS:' % (service_name, method), kwargs)

        # Throw error if sensitve keys are found in kwargs.
        # This really shouldn't matter as the system should
        # complain automatically due to arguments defined twice
        # but we'll make it explicit here.
        if kwargs == None:
            kwargs = {}
        for k in ['uid', 'cr']:
            if k in kwargs:
                raise openerp.exceptions.AccessDenied()

        # Pass the request on.
        result = ExportService.getService(service_name).dispatch(
            method, params, kwargs)

        if (rpc_request_flag or rpc_response_flag) or rpc_user_flag:
            end_time = time.time()
            if rpc_response_flag:
                log(
                    rpc_response, logging.DEBUG, '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time), result)
            else:
                log(rpc_request,
                    logging.DEBUG,
                    '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time),
                    replace_request_password(params),
                    depth=1)

            if rpc_user_flag:
                log(
                    rpc_user, logging.DEBUG, '%s.%s time:%.3fs ' %
                    (service_name, method, end_time - start_time), result)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        _logger.error(u"uid {} login {}: ".format(
            int(uid),
            UID_NAME_CACHE.get(db_name, {}).get(uid, 'unknown')) +
                      tools.exception_to_unicode(e))
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.error(u"uid {} login {}: ".format(
            int(uid),
            UID_NAME_CACHE.get(db_name, {}).get(uid, 'unknown')) +
                      tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #28
0
    def run(self, cr, uid, wi, context={}):
        logger = netsvc.Logger()
        context['active_id'] = wi.id
        done = False
        ms_err = ''

        try:
            server_obj = self.pool.get('ir.actions.server')
            tr_res = True
            """ Check if action must be done or cancelled by checking the 
                            condition code of incoming transitions """
            for tr in wi.step_id.incoming_transition_ids:
                eval_context = {
                    'pool': self.pool,
                    'cr': cr,
                    'uid': uid,
                    'wi': wi,
                    'tr': tr,
                }
                val = {}
                """ Evaluate condition code (for non preview workitems only)"""
                if wi.is_preview:
                    val['action'] = True
                else:
                    exec tr.condition_id.in_act_cond.replace('\r','') in \
                                                 eval_context, val

                if not val.get('action', False):
                    """ If action returned by the trigger code is 
                                                            False stop here """
                    tr_res = False
                    act_step = tr.step_from_id.name or False
                    break

            if tr_res:
                "Execute server action"
                wi_res = server_obj.run(cr, uid, [wi.step_id.action_id.id],
                                        context)
                if not wi_res and wi.step_id.action_id.state == 'object_create':
                    # create object returns false ,asuming object is created
                    # state is set to done
                    self.write(cr, uid, [wi.id], {
                        'state': 'done',
                        'error_msg': 'Case is created'
                    })
                else:
                    """ Check returned code and set wi status """
                    wi_status = self._check_sysmsg(cr, uid, wi_res['code'],
                                                   context.copy())

                    "Set workitem state and message"
                    wr = self.write(cr, uid, [wi.id], {
                        'state': wi_status['state'],
                        'error_msg': wi_status['msg']
                    })
                    done = wi_status['result']
                    "If workitem done then execute mail service action"
                    if done:
                        doc_context = {}
                        doc_obj = self.pool.get(wi_res['model'])
                        for doc in doc_obj.browse(cr, uid, wi_res['ids']):
                            doc_context['active_id'] = doc.id
                            ms_res = server_obj.run(
                                cr, uid, [doc.mail_service_id.action_id.id],
                                doc_context)
                            ms_status = self._check_sysmsg(
                                cr, uid, ms_res['code'], context)
                            doc_obj.write(
                                cr, uid, [doc.id], {
                                    'state':
                                    ms_status['state'],
                                    'error_msg':
                                    'err_msg' in ms_res and ms_res['err_msg']
                                    or ms_status['msg'],
                                    'delivery_time':
                                    time.strftime('%Y-%m-%d  %H:%M:%S')
                                })
                            " If doc in error, change workitem status "
                            if not ms_status['result']:
                                # Attention : if 1 doc crashes => wi in error but other docs processed
                                # TODO : Add doc in error ref in wi error_msg
                                wr = self.write(
                                    cr, uid, [wi.id], {
                                        'state': ms_status['state'],
                                        'error_msg': ms_status['msg']
                                    })
                                done = False
            else:
                "Dont Execute Action if workitem is not to be processed"
                self.write(cr, uid, [wi.id], {
                    'state': 'cancel',
                    'error_msg': 'Cancelled by : %s' % act_step
                })

        except Exception, exception:
            tb = sys.exc_info()
            tb_s = "".join(traceback.format_exception(*tb))
            self.write(
                cr, uid, [wi.id], {
                    'state':
                    'error',
                    'error_msg':
                    'Exception: %s\n%s' %
                    (tools.exception_to_unicode(exception), tb_s)
                })
            netsvc.Logger().notifyChannel(
                'dm action', netsvc.LOG_ERROR, 'Exception: %s\n%s' %
                (tools.exception_to_unicode(exception), tb_s))
예제 #29
0
파일: netsvc.py 프로젝트: guzzi235/saas3
def dispatch_rpc(service_name, method, params):
    """ Handle a RPC call.

    This is pure Python code, the actual marshalling (from/to XML-RPC) is done
    in a upper layer.
    """
    try:
        rpc_request = logging.getLogger(__name__ + ".rpc.request")
        rpc_response = logging.getLogger(__name__ + ".rpc.response")
        rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
        rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
        if rpc_request_flag or rpc_response_flag:
            start_time = time.time()
            start_rss, start_vms = 0, 0
            start_rss, start_vms = psutil.Process(os.getpid()).get_memory_info()
            if rpc_request and rpc_response_flag:
                log(rpc_request, logging.DEBUG, "%s.%s" % (service_name, method), replace_request_password(params))

        threading.current_thread().uid = None
        threading.current_thread().dbname = None
        if service_name == "common":
            dispatch = openerp.service.common.dispatch
        elif service_name == "db":
            dispatch = openerp.service.db.dispatch
        elif service_name == "object":
            dispatch = openerp.service.model.dispatch
        elif service_name == "report":
            dispatch = openerp.service.report.dispatch
        else:
            dispatch = openerp.service.wsgi_server.rpc_handlers.get(service_name)
        result = dispatch(method, params)

        if rpc_request_flag or rpc_response_flag:
            end_time = time.time()
            end_rss, end_vms = 0, 0
            end_rss, end_vms = psutil.Process(os.getpid()).get_memory_info()
            logline = "%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)" % (
                service_name,
                method,
                end_time - start_time,
                start_vms / 1024,
                end_vms / 1024,
                (end_vms - start_vms) / 1024,
            )
            if rpc_response_flag:
                log(rpc_response, logging.DEBUG, logline, result)
            else:
                log(rpc_request, logging.DEBUG, logline, replace_request_password(params), depth=1)

        return result
    except openerp.osv.orm.except_orm:
        raise
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.RedirectWarning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.exception(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
예제 #30
0
파일: netsvc.py 프로젝트: ascetic85/ziwei
 def _dispatch(self, method, params):
     try:
         service_name = self.path.split("/")[-1]
         return self.dispatch(service_name, method, params)
     except OpenERPDispatcherException, e:
         raise xmlrpclib.Fault(tools.exception_to_unicode(e.exception), e.traceback)
예제 #31
0
                    (service_name, method, end_time - start_time),
                    replace_request_password(params),
                    depth=1)

        return result
    except openerp.exceptions.AccessError:
        raise
    except openerp.exceptions.AccessDenied:
        raise
    except openerp.exceptions.Warning:
        raise
    except openerp.exceptions.DeferredException, e:
        _logger.error(tools.exception_to_unicode(e))
        post_mortem(e.traceback)
        raise
    except Exception, e:
        _logger.error(
            hasattr(e, 'traceback') and traceback.print_tb(e.traceback)
            or tools.exception_to_unicode(e))
        post_mortem(sys.exc_info())
        raise


def post_mortem(info):
    if tools.config['debug_mode'] and isinstance(info[2], types.TracebackType):
        import pdb
        pdb.post_mortem(info[2])


# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
예제 #32
0
    def run(self, cr, uid, wi, context={}):
        logger = netsvc.Logger()
        context['active_id'] = wi.id
        done = False
        ms_err = ''

        try:
            server_obj = self.pool.get('ir.actions.server')
            tr_res = True

            """ Check if action must be done or cancelled by checking the 
                            condition code of incoming transitions """
            for tr in wi.step_id.incoming_transition_ids:
                eval_context = {
                    'pool': self.pool,
                    'cr': cr,
                    'uid': uid,
                    'wi': wi,
                    'tr': tr,
                }
                val = {}

                """ Evaluate condition code (for non preview workitems only)"""
                if wi.is_preview:
                    val['action'] = True
                else:
                    exec tr.condition_id.in_act_cond.replace('\r','') in \
                                                 eval_context, val

                if not val.get('action', False):
                    """ If action returned by the trigger code is 
                                                            False stop here """
                    tr_res = False
                    act_step = tr.step_from_id.name or False
                    break

            if tr_res:
                "Execute server action"
                wi_res = server_obj.run(cr, uid, [wi.step_id.action_id.id], context)
                if not wi_res and wi.step_id.action_id.state == 'object_create': 
                    # create object returns false ,asuming object is created
                    # state is set to done 
                    self.write(cr, uid, [wi.id], {'state': 'done',
                                    'error_msg': 'Case is created'})
                else :
                    """ Check returned code and set wi status """
                    wi_status = self._check_sysmsg(cr, uid, wi_res['code'],
                                                    context.copy())

                    "Set workitem state and message"
                    wr = self.write(cr, uid, [wi.id], {'state': wi_status['state'],
                                                    'error_msg':wi_status['msg']})
                    done = wi_status['result']
                    "If workitem done then execute mail service action"
                    if done:
                        doc_context = {}
                        doc_obj = self.pool.get(wi_res['model'])
                        for doc in doc_obj.browse(cr, uid, wi_res['ids']):
                            doc_context['active_id'] = doc.id
                            ms_res = server_obj.run(cr, uid,
                                            [doc.mail_service_id.action_id.id],
                                            doc_context)
                            ms_status = self._check_sysmsg(cr, uid, ms_res['code'], context)
                            doc_obj.write(cr, uid, [doc.id],
                                {'state': ms_status['state'],
                                'error_msg': 'err_msg' in ms_res and ms_res['err_msg'] or ms_status['msg'], 
                                'delivery_time': time.strftime('%Y-%m-%d  %H:%M:%S')})
                            " If doc in error, change workitem status "
                            if not ms_status['result']:
                                # Attention : if 1 doc crashes => wi in error but other docs processed
                                # TODO : Add doc in error ref in wi error_msg
                                wr = self.write(cr, uid, [wi.id], {'state': ms_status['state'],
                                                    'error_msg':ms_status['msg']})
                                done = False
            else:
                "Dont Execute Action if workitem is not to be processed"
                self.write(cr, uid, [wi.id], {'state': 'cancel',
                                    'error_msg': 'Cancelled by : %s'% act_step})

        except Exception, exception:
            tb = sys.exc_info()
            tb_s = "".join(traceback.format_exception(*tb))
            self.write(cr, uid, [wi.id], {'state': 'error',
            'error_msg': 'Exception: %s\n%s' % (tools.exception_to_unicode(exception), 
                                                                        tb_s)})
            netsvc.Logger().notifyChannel('dm action', netsvc.LOG_ERROR, 
            'Exception: %s\n%s' % (tools.exception_to_unicode(exception), tb_s))