Merge pull request #648 from odoo-dev/7.0-fix-searchbar-navigation-ged
[odoo/odoo.git] / openerp / modules / registry.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 """ Models registries.
23
24 """
25 from contextlib import contextmanager
26 import logging
27 import threading
28
29 import openerp.sql_db
30 import openerp.osv.orm
31 import openerp.tools
32 import openerp.modules.db
33 import openerp.tools.config
34 from openerp.tools import assertion_report
35
36 _logger = logging.getLogger(__name__)
37
38 class Registry(object):
39     """ Model registry for a particular database.
40
41     The registry is essentially a mapping between model names and model
42     instances. There is one registry instance per database.
43
44     """
45
46     def __init__(self, db_name):
47         self.models = {}    # model name/model instance mapping
48         self._sql_error = {}
49         self._store_function = {}
50         self._init = True
51         self._init_parent = {}
52         self._assertion_report = assertion_report.assertion_report()
53         self.fields_by_model = None
54
55         # modules fully loaded (maintained during init phase by `loading` module)
56         self._init_modules = set()
57
58         self.db_name = db_name
59         self.db = openerp.sql_db.db_connect(db_name)
60
61         # Indicates that the registry is 
62         self.ready = False
63
64         # Inter-process signaling (used only when openerp.multi_process is True):
65         # The `base_registry_signaling` sequence indicates the whole registry
66         # must be reloaded.
67         # The `base_cache_signaling sequence` indicates all caches must be
68         # invalidated (i.e. cleared).
69         self.base_registry_signaling_sequence = None
70         self.base_cache_signaling_sequence = None
71
72         # Flag indicating if at least one model cache has been cleared.
73         # Useful only in a multi-process context.
74         self._any_cache_cleared = False
75
76         cr = self.db.cursor()
77         has_unaccent = openerp.modules.db.has_unaccent(cr)
78         if openerp.tools.config['unaccent'] and not has_unaccent:
79             _logger.warning("The option --unaccent was given but no unaccent() function was found in database.")
80         self.has_unaccent = openerp.tools.config['unaccent'] and has_unaccent
81         cr.close()
82
83     def do_parent_store(self, cr):
84         for o in self._init_parent:
85             self.get(o)._parent_store_compute(cr)
86         self._init = False
87
88     def obj_list(self):
89         """ Return the list of model names in this registry."""
90         return self.models.keys()
91
92     def add(self, model_name, model):
93         """ Add or replace a model in the registry."""
94         self.models[model_name] = model
95
96     def get(self, model_name):
97         """ Return a model for a given name or None if it doesn't exist."""
98         return self.models.get(model_name)
99
100     def __getitem__(self, model_name):
101         """ Return a model for a given name or raise KeyError if it doesn't exist."""
102         return self.models[model_name]
103
104     def load(self, cr, module):
105         """ Load a given module in the registry.
106
107         At the Python level, the modules are already loaded, but not yet on a
108         per-registry level. This method populates a registry with the given
109         modules, i.e. it instanciates all the classes of a the given module
110         and registers them in the registry.
111
112         """
113         models_to_load = [] # need to preserve loading order
114         # Instantiate registered classes (via the MetaModel automatic discovery
115         # or via explicit constructor call), and add them to the pool.
116         for cls in openerp.osv.orm.MetaModel.module_to_models.get(module.name, []):
117             # models register themselves in self.models
118             model = cls.create_instance(self, cr)
119             if model._name not in models_to_load:
120                 # avoid double-loading models whose declaration is split
121                 models_to_load.append(model._name)
122         return [self.models[m] for m in models_to_load]
123
124     def clear_caches(self):
125         """ Clear the caches
126         This clears the caches associated to methods decorated with
127         ``tools.ormcache`` or ``tools.ormcache_multi`` for all the models.
128         """
129         for model in self.models.itervalues():
130             model.clear_caches()
131         # Special case for ir_ui_menu which does not use openerp.tools.ormcache.
132         ir_ui_menu = self.models.get('ir.ui.menu')
133         if ir_ui_menu:
134             ir_ui_menu.clear_cache()
135
136
137     # Useful only in a multi-process context.
138     def reset_any_cache_cleared(self):
139         self._any_cache_cleared = False
140
141     # Useful only in a multi-process context.
142     def any_cache_cleared(self):
143         return self._any_cache_cleared
144
145     @classmethod
146     def setup_multi_process_signaling(cls, cr):
147         if not openerp.multi_process:
148             return None, None
149
150         # Inter-process signaling:
151         # The `base_registry_signaling` sequence indicates the whole registry
152         # must be reloaded.
153         # The `base_cache_signaling sequence` indicates all caches must be
154         # invalidated (i.e. cleared).
155         cr.execute("""SELECT sequence_name FROM information_schema.sequences WHERE sequence_name='base_registry_signaling'""")
156         if not cr.fetchall():
157             cr.execute("""CREATE SEQUENCE base_registry_signaling INCREMENT BY 1 START WITH 1""")
158             cr.execute("""SELECT nextval('base_registry_signaling')""")
159             cr.execute("""CREATE SEQUENCE base_cache_signaling INCREMENT BY 1 START WITH 1""")
160             cr.execute("""SELECT nextval('base_cache_signaling')""")
161         
162         cr.execute("""
163                     SELECT base_registry_signaling.last_value,
164                            base_cache_signaling.last_value
165                     FROM base_registry_signaling, base_cache_signaling""")
166         r, c = cr.fetchone()
167         _logger.debug("Multiprocess load registry signaling: [Registry: # %s] "\
168                     "[Cache: # %s]",
169                     r, c)
170         return r, c
171
172     @contextmanager
173     def cursor(self, auto_commit=True):
174         cr = self.db.cursor()
175         try:
176             yield cr
177             if auto_commit:
178                 cr.commit()
179         finally:
180             cr.close()
181
182
183 class RegistryManager(object):
184     """ Model registries manager.
185
186         The manager is responsible for creation and deletion of model
187         registries (essentially database connection/model registry pairs).
188
189     """
190     # Mapping between db name and model registry.
191     # Accessed through the methods below.
192     registries = {}
193     registries_lock = threading.RLock()
194
195     @classmethod
196     def get(cls, db_name, force_demo=False, status=None, update_module=False):
197         """ Return a registry for a given database name."""
198         with cls.registries_lock:
199             try:
200                 return cls.registries[db_name]
201             except KeyError:
202                 return cls.new(db_name, force_demo, status,
203                                update_module)
204             finally:
205                 # set db tracker - cleaned up at the WSGI
206                 # dispatching phase in openerp.service.wsgi_server.application
207                 threading.current_thread().dbname = db_name
208
209     @classmethod
210     def new(cls, db_name, force_demo=False, status=None,
211             update_module=False):
212         """ Create and return a new registry for a given database name.
213
214         The (possibly) previous registry for that database name is discarded.
215
216         """
217         import openerp.modules
218         with cls.registries_lock:
219             registry = Registry(db_name)
220
221             # Initializing a registry will call general code which will in turn
222             # call registries.get (this object) to obtain the registry being
223             # initialized. Make it available in the registries dictionary then
224             # remove it if an exception is raised.
225             cls.delete(db_name)
226             cls.registries[db_name] = registry
227             try:
228                 with registry.cursor() as cr:
229                     seq_registry, seq_cache = Registry.setup_multi_process_signaling(cr)
230                     registry.base_registry_signaling_sequence = seq_registry
231                     registry.base_cache_signaling_sequence = seq_cache
232                 # This should be a method on Registry
233                 openerp.modules.load_modules(registry.db, force_demo, status, update_module)
234             except Exception:
235                 del cls.registries[db_name]
236                 raise
237
238             # load_modules() above can replace the registry by calling
239             # indirectly new() again (when modules have to be uninstalled).
240             # Yeah, crazy.
241             registry = cls.registries[db_name]
242
243             cr = registry.db.cursor()
244             try:
245                 registry.do_parent_store(cr)
246                 registry.get('ir.actions.report.xml').register_all(cr)
247                 cr.commit()
248             finally:
249                 cr.close()
250
251         registry.ready = True
252
253         if update_module:
254             # only in case of update, otherwise we'll have an infinite reload loop!
255             cls.signal_registry_change(db_name)
256         return registry
257
258     @classmethod
259     def delete(cls, db_name):
260         """Delete the registry linked to a given database.  """
261         with cls.registries_lock:
262             if db_name in cls.registries:
263                 cls.registries[db_name].clear_caches()
264                 del cls.registries[db_name]
265
266     @classmethod
267     def delete_all(cls):
268         """Delete all the registries. """
269         with cls.registries_lock:
270             for db_name in cls.registries.keys():
271                 cls.delete(db_name)
272
273     @classmethod
274     def clear_caches(cls, db_name):
275         """Clear caches
276
277         This clears the caches associated to methods decorated with
278         ``tools.ormcache`` or ``tools.ormcache_multi`` for all the models
279         of the given database name.
280
281         This method is given to spare you a ``RegistryManager.get(db_name)``
282         that would loads the given database if it was not already loaded.
283         """
284         with cls.registries_lock:
285             if db_name in cls.registries:
286                 cls.registries[db_name].clear_caches()
287
288     @classmethod
289     def check_registry_signaling(cls, db_name):
290         if openerp.multi_process and db_name in cls.registries:
291             registry = cls.get(db_name)
292             cr = registry.db.cursor()
293             try:
294                 cr.execute("""
295                     SELECT base_registry_signaling.last_value,
296                            base_cache_signaling.last_value
297                     FROM base_registry_signaling, base_cache_signaling""")
298                 r, c = cr.fetchone()
299                 _logger.debug("Multiprocess signaling check: [Registry - old# %s new# %s] "\
300                     "[Cache - old# %s new# %s]",
301                     registry.base_registry_signaling_sequence, r,
302                     registry.base_cache_signaling_sequence, c)
303                 # Check if the model registry must be reloaded (e.g. after the
304                 # database has been updated by another process).
305                 if registry.base_registry_signaling_sequence is not None and registry.base_registry_signaling_sequence != r:
306                     _logger.info("Reloading the model registry after database signaling.")
307                     registry = cls.new(db_name)
308                 # Check if the model caches must be invalidated (e.g. after a write
309                 # occured on another process). Don't clear right after a registry
310                 # has been reload.
311                 elif registry.base_cache_signaling_sequence is not None and registry.base_cache_signaling_sequence != c:
312                     _logger.info("Invalidating all model caches after database signaling.")
313                     registry.clear_caches()
314                     registry.reset_any_cache_cleared()
315                     # One possible reason caches have been invalidated is the
316                     # use of decimal_precision.write(), in which case we need
317                     # to refresh fields.float columns.
318                     for model in registry.models.values():
319                         for column in model._columns.values():
320                             if hasattr(column, 'digits_change'):
321                                 column.digits_change(cr)
322                 registry.base_registry_signaling_sequence = r
323                 registry.base_cache_signaling_sequence = c
324             finally:
325                 cr.close()
326
327     @classmethod
328     def signal_caches_change(cls, db_name):
329         if openerp.multi_process and db_name in cls.registries:
330             # Check the registries if any cache has been cleared and signal it
331             # through the database to other processes.
332             registry = cls.get(db_name)
333             if registry.any_cache_cleared():
334                 _logger.info("At least one model cache has been cleared, signaling through the database.")
335                 cr = registry.db.cursor()
336                 r = 1
337                 try:
338                     cr.execute("select nextval('base_cache_signaling')")
339                     r = cr.fetchone()[0]
340                 finally:
341                     cr.close()
342                 registry.base_cache_signaling_sequence = r
343                 registry.reset_any_cache_cleared()
344
345     @classmethod
346     def signal_registry_change(cls, db_name):
347         if openerp.multi_process and db_name in cls.registries:
348             _logger.info("Registry changed, signaling through the database")
349             registry = cls.get(db_name)
350             cr = registry.db.cursor()
351             r = 1
352             try:
353                 cr.execute("select nextval('base_registry_signaling')")
354                 r = cr.fetchone()[0]
355             finally:
356                 cr.close()
357             registry.base_registry_signaling_sequence = r
358
359 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: