1 # -*- coding: utf-8 -*-
3 from functools import wraps
5 from psycopg2 import IntegrityError, OperationalError, errorcodes
11 from openerp.tools.translate import translate
12 from openerp.osv.orm import except_orm
13 from contextlib import contextmanager
17 _logger = logging.getLogger(__name__)
19 PG_CONCURRENCY_ERRORS_TO_RETRY = (errorcodes.LOCK_NOT_AVAILABLE, errorcodes.SERIALIZATION_FAILURE, errorcodes.DEADLOCK_DETECTED)
20 MAX_TRIES_ON_CONCURRENCY_FAILURE = 5
22 def dispatch(method, params):
23 (db, uid, passwd ) = params[0:3]
25 # set uid tracker - cleaned up at the WSGI
26 # dispatching phase in openerp.service.wsgi_server.application
27 threading.current_thread().uid = uid
30 if method == 'obj_list':
31 raise NameError("obj_list has been discontinued via RPC as of 6.0, please query ir.model directly!")
32 if method not in ['execute', 'execute_kw', 'exec_workflow']:
33 raise NameError("Method not available %s" % method)
34 security.check(db,uid,passwd)
35 openerp.modules.registry.RegistryManager.check_registry_signaling(db)
36 fn = globals()[method]
37 res = fn(db, uid, *params)
38 openerp.modules.registry.RegistryManager.signal_caches_change(db)
43 def wrapper(___dbname, *args, **kwargs):
44 """ Wraps around OSV functions and normalises a few exceptions
46 dbname = ___dbname # NOTE: this forbid to use "___dbname" as arguments in http routes
49 # We try to do the same as the _(), but without the frame
50 # inspection, since we aready are wrapping an osv function
51 # trans_obj = self.get('ir.translation') cannot work yet :(
54 if args and isinstance(args[-1], dict):
56 elif isinstance(kwargs, dict):
57 # kwargception because call_kw set its context in kwargs['kwargs']
58 ctx = kwargs.get('context', kwargs.get('kwargs', {}).get('context', {}))
61 if args and isinstance(args[0], (long, int)):
64 lang = ctx and ctx.get('lang')
65 if not (lang or hasattr(src, '__call__')):
68 # We open a *new* cursor here, one reason is that failed SQL
69 # queries (as in IntegrityError) will invalidate the current one.
72 if hasattr(src, '__call__'):
73 # callable. We need to find the right parameters to call
74 # the orm._sql_message(self, cr, uid, ids, context) function,
76 # our signature is f(registry, dbname [,uid, obj, method, args])
78 if args and len(args) > 1:
79 # TODO self doesn't exist, but was already wrong before (it was not a registry but just the object_service.
80 obj = self.get(args[1])
81 if len(args) > 3 and isinstance(args[3], (long, int, list)):
85 cr = openerp.sql_db.db_connect(dbname).cursor()
86 return src(obj, cr, uid, ids, context=(ctx or {}))
92 return False # so that the original SQL error will
93 # be returned, it is the best we have.
96 cr = openerp.sql_db.db_connect(dbname).cursor()
97 res = translate(cr, name=False, source_type=ttype,
98 lang=lang, source=src)
107 return tr(src, 'code')
112 if openerp.registry(dbname)._init:
113 raise openerp.exceptions.Warning('Currently, this database is not fully loaded and can not be used.')
114 return f(dbname, *args, **kwargs)
115 except OperationalError, e:
116 # Automatically retry the typical transaction serialization errors
117 if e.pgcode not in PG_CONCURRENCY_ERRORS_TO_RETRY:
119 if tries >= MAX_TRIES_ON_CONCURRENCY_FAILURE:
120 _logger.warning("%s, maximum number of tries reached" % errorcodes.lookup(e.pgcode))
122 wait_time = random.uniform(0.0, 2 ** tries)
124 _logger.info("%s, retry %d/%d in %.04f sec..." % (errorcodes.lookup(e.pgcode), tries, MAX_TRIES_ON_CONCURRENCY_FAILURE, wait_time))
125 time.sleep(wait_time)
126 except IntegrityError, inst:
127 registry = openerp.registry(dbname)
128 for key in registry._sql_error.keys():
130 raise openerp.osv.orm.except_orm(_('Constraint Error'), tr(registry._sql_error[key], 'sql_constraint') or inst[0])
131 if inst.pgcode in (errorcodes.NOT_NULL_VIOLATION, errorcodes.FOREIGN_KEY_VIOLATION, errorcodes.RESTRICT_VIOLATION):
132 msg = _('The operation cannot be completed, probably due to the following:\n- deletion: you may be trying to delete a record while other records still reference it\n- creation/update: a mandatory field is not correctly set')
133 _logger.debug("IntegrityError", exc_info=True)
135 errortxt = inst.pgerror.replace('«','"').replace('»','"')
136 if '"public".' in errortxt:
137 context = errortxt.split('"public".')[1]
138 model_name = table = context.split('"')[1]
140 last_quote_end = errortxt.rfind('"')
141 last_quote_begin = errortxt.rfind('"', 0, last_quote_end)
142 model_name = table = errortxt[last_quote_begin+1:last_quote_end].strip()
143 model = table.replace("_",".")
144 if model in registry:
145 model_obj = registry[model]
146 model_name = model_obj._description or model_obj._name
147 msg += _('\n\n[object with reference: %s - %s]') % (model_name, model)
150 raise openerp.osv.orm.except_orm(_('Integrity Error'), msg)
152 raise openerp.osv.orm.except_orm(_('Integrity Error'), inst[0])
156 def execute_cr(cr, uid, obj, method, *args, **kw):
157 object = openerp.registry(cr.dbname).get(obj)
159 raise except_orm('Object Error', "Object %s doesn't exist" % obj)
160 return getattr(object, method)(cr, uid, *args, **kw)
162 def execute_kw(db, uid, obj, method, args, kw=None):
163 return execute(db, uid, obj, method, *args, **kw or {})
166 def closing_cr_and_commit(cr):
177 def execute(db, uid, obj, method, *args, **kw):
178 threading.currentThread().dbname = db
179 with closing_cr_and_commit(openerp.registry(db).db.cursor()) as cr:
180 if method.startswith('_'):
181 raise except_orm('Access Denied', 'Private methods (such as %s) cannot be called remotely.' % (method,))
182 res = execute_cr(cr, uid, obj, method, *args, **kw)
184 _logger.warning('The method %s of the object %s can not return `None` !', method, obj)
187 def exec_workflow_cr(cr, uid, obj, signal, *args):
189 return execute_cr(cr, uid, obj, 'signal_workflow', [res_id], signal)[res_id]
193 def exec_workflow(db, uid, obj, signal, *args):
194 with closing_cr_and_commit(openerp.registry(db).db.cursor()) as cr:
195 return exec_workflow_cr(cr, uid, obj, signal, *args)
197 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: