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