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