d65cbd773332f5c06875950a6e1fc9a2e79cb361
[odoo/odoo.git] / openerp / service / model.py
1 # -*- coding: utf-8 -*-
2
3 from functools import wraps
4 import logging
5 from psycopg2 import IntegrityError, OperationalError, errorcodes
6 import random
7 import threading
8 import time
9
10 import openerp
11 from openerp.tools.translate import translate
12 from openerp.osv.orm import except_orm
13 from contextlib import contextmanager
14
15 import security
16
17 _logger = logging.getLogger(__name__)
18
19 PG_CONCURRENCY_ERRORS_TO_RETRY = (errorcodes.LOCK_NOT_AVAILABLE, errorcodes.SERIALIZATION_FAILURE, errorcodes.DEADLOCK_DETECTED)
20 MAX_TRIES_ON_CONCURRENCY_FAILURE = 5
21
22 def dispatch(method, params):
23     (db, uid, passwd ) = params[0:3]
24
25     # set uid tracker - cleaned up at the WSGI
26     # dispatching phase in openerp.service.wsgi_server.application
27     threading.current_thread().uid = uid
28
29     params = params[3:]
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)
39     return res
40
41 def check(f):
42     @wraps(f)
43     def wrapper(___dbname, *args, **kwargs):
44         """ Wraps around OSV functions and normalises a few exceptions
45         """
46         dbname = ___dbname      # NOTE: this forbid to use "___dbname" as arguments in http routes
47
48         def tr(src, ttype):
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 :(
52             ctx = {}
53             if not kwargs:
54                 if args and isinstance(args[-1], dict):
55                     ctx = args[-1]
56             elif isinstance(kwargs, dict):
57                 ctx = kwargs.get('context', {})
58
59             uid = 1
60             if args and isinstance(args[0], (long, int)):
61                 uid = args[0]
62
63             lang = ctx and ctx.get('lang')
64             if not (lang or hasattr(src, '__call__')):
65                 return src
66
67             # We open a *new* cursor here, one reason is that failed SQL
68             # queries (as in IntegrityError) will invalidate the current one.
69             cr = False
70
71             if hasattr(src, '__call__'):
72                 # callable. We need to find the right parameters to call
73                 # the  orm._sql_message(self, cr, uid, ids, context) function,
74                 # or we skip..
75                 # our signature is f(registry, dbname [,uid, obj, method, args])
76                 try:
77                     if args and len(args) > 1:
78                         # TODO self doesn't exist, but was already wrong before (it was not a registry but just the object_service.
79                         obj = self.get(args[1])
80                         if len(args) > 3 and isinstance(args[3], (long, int, list)):
81                             ids = args[3]
82                         else:
83                             ids = []
84                     cr = openerp.sql_db.db_connect(dbname).cursor()
85                     return src(obj, cr, uid, ids, context=(ctx or {}))
86                 except Exception:
87                     pass
88                 finally:
89                     if cr: cr.close()
90
91                 return False # so that the original SQL error will
92                              # be returned, it is the best we have.
93
94             try:
95                 cr = openerp.sql_db.db_connect(dbname).cursor()
96                 res = translate(cr, name=False, source_type=ttype,
97                                 lang=lang, source=src)
98                 if res:
99                     return res
100                 else:
101                     return src
102             finally:
103                 if cr: cr.close()
104
105         def _(src):
106             return tr(src, 'code')
107
108         tries = 0
109         while True:
110             try:
111                 if openerp.registry(dbname)._init:
112                     raise openerp.exceptions.Warning('Currently, this database is not fully loaded and can not be used.')
113                 return f(dbname, *args, **kwargs)
114             except OperationalError, e:
115                 # Automatically retry the typical transaction serialization errors
116                 if e.pgcode not in PG_CONCURRENCY_ERRORS_TO_RETRY:
117                     raise
118                 if tries >= MAX_TRIES_ON_CONCURRENCY_FAILURE:
119                     _logger.warning("%s, maximum number of tries reached" % errorcodes.lookup(e.pgcode))
120                     raise
121                 wait_time = random.uniform(0.0, 2 ** tries)
122                 tries += 1
123                 _logger.info("%s, retry %d/%d in %.04f sec..." % (errorcodes.lookup(e.pgcode), tries, MAX_TRIES_ON_CONCURRENCY_FAILURE, wait_time))
124                 time.sleep(wait_time)
125             except IntegrityError, inst:
126                 registry = openerp.registry(dbname)
127                 for key in registry._sql_error.keys():
128                     if key in inst[0]:
129                         raise openerp.osv.orm.except_orm(_('Constraint Error'), tr(registry._sql_error[key], 'sql_constraint') or inst[0])
130                 if inst.pgcode in (errorcodes.NOT_NULL_VIOLATION, errorcodes.FOREIGN_KEY_VIOLATION, errorcodes.RESTRICT_VIOLATION):
131                     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')
132                     _logger.debug("IntegrityError", exc_info=True)
133                     try:
134                         errortxt = inst.pgerror.replace('«','"').replace('»','"')
135                         if '"public".' in errortxt:
136                             context = errortxt.split('"public".')[1]
137                             model_name = table = context.split('"')[1]
138                         else:
139                             last_quote_end = errortxt.rfind('"')
140                             last_quote_begin = errortxt.rfind('"', 0, last_quote_end)
141                             model_name = table = errortxt[last_quote_begin+1:last_quote_end].strip()
142                         model = table.replace("_",".")
143                         if model in registry:
144                             model_obj = registry[model]
145                             model_name = model_obj._description or model_obj._name
146                         msg += _('\n\n[object with reference: %s - %s]') % (model_name, model)
147                     except Exception:
148                         pass
149                     raise openerp.osv.orm.except_orm(_('Integrity Error'), msg)
150                 else:
151                     raise openerp.osv.orm.except_orm(_('Integrity Error'), inst[0])
152
153     return wrapper
154
155 def execute_cr(cr, uid, obj, method, *args, **kw):
156     object = openerp.registry(cr.dbname).get(obj)
157     if not object:
158         raise except_orm('Object Error', "Object %s doesn't exist" % obj)
159     return getattr(object, method)(cr, uid, *args, **kw)
160
161 def execute_kw(db, uid, obj, method, args, kw=None):
162     return execute(db, uid, obj, method, *args, **kw or {})
163
164 @contextmanager
165 def closing_cr_and_commit(cr):
166     try:
167         yield cr
168         cr.commit()
169     except Exception:
170         cr.rollback()
171         raise
172     finally:
173         cr.close()
174
175 @check
176 def execute(db, uid, obj, method, *args, **kw):
177     threading.currentThread().dbname = db
178     with closing_cr_and_commit(openerp.registry(db).db.cursor()) as cr:
179         if method.startswith('_'):
180             raise except_orm('Access Denied', 'Private methods (such as %s) cannot be called remotely.' % (method,))
181         res = execute_cr(cr, uid, obj, method, *args, **kw)
182         if res is None:
183             _logger.warning('The method %s of the object %s can not return `None` !', method, obj)
184         return res
185
186 def exec_workflow_cr(cr, uid, obj, signal, *args):
187     res_id = args[0]
188     return execute_cr(cr, uid, obj, 'signal_workflow', [res_id], signal)[res_id]
189
190
191 @check
192 def exec_workflow(db, uid, obj, signal, *args):
193     with closing_cr_and_commit(openerp.registry(db).db.cursor()) as cr:
194         return exec_workflow_cr(cr, uid, obj, signal, *args)
195
196 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: