Files
tryton/trytond/pool.py
T

284 lines
9.0 KiB
Python
Raw Normal View History

2014-12-02 12:54:01 +01:00
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
2021-12-11 17:58:45 +01:00
import builtins
import logging
2021-12-11 17:58:45 +01:00
from collections import OrderedDict, defaultdict
from threading import RLock
2011-07-03 13:20:58 +02:00
from trytond.modules import load_modules, register_classes
from trytond.transaction import Transaction
2009-02-11 14:52:22 +01:00
2015-10-01 22:37:13 +02:00
__all__ = ['Pool', 'PoolMeta', 'PoolBase', 'isregisteredby']
2012-09-24 22:16:53 +02:00
2015-03-02 23:39:15 +01:00
logger = logging.getLogger(__name__)
2012-09-24 22:16:53 +02:00
class PoolMeta(type):
def __new__(cls, name, bases, dct):
2019-09-07 23:45:08 +02:00
if '__slots__' not in dct and not dct.get('__no_slots__'):
dct['__slots__'] = ()
2012-09-24 22:16:53 +02:00
new = type.__new__(cls, name, bases, dct)
if '__name__' in dct:
2014-11-10 23:30:49 +01:00
try:
new.__name__ = dct['__name__']
except TypeError:
new.__name__ = dct['__name__'].encode('utf-8')
2012-09-24 22:16:53 +02:00
return new
2009-02-11 14:52:22 +01:00
2018-06-26 19:11:19 +02:00
class PoolBase(object, metaclass=PoolMeta):
@classmethod
def __setup__(cls):
pass
@classmethod
def __post_setup__(cls):
pass
@classmethod
def __register__(cls, module_name):
pass
2009-02-11 14:52:22 +01:00
class Pool(object):
classes = {
2018-09-26 23:10:00 +02:00
'model': defaultdict(OrderedDict),
'wizard': defaultdict(OrderedDict),
'report': defaultdict(OrderedDict),
2009-02-11 14:52:22 +01:00
}
2018-01-12 15:46:52 +01:00
classes_mixin = defaultdict(list)
_started = False
2009-02-11 14:52:22 +01:00
_lock = RLock()
_locks = {}
_pool = {}
2010-03-04 14:02:27 +01:00
test = False
2011-07-03 13:20:58 +02:00
_instances = {}
2020-09-12 18:25:14 +02:00
_modules = None
2009-02-11 14:52:22 +01:00
2011-07-03 13:20:58 +02:00
def __new__(cls, database_name=None):
if database_name is None:
database_name = Transaction().database.name
2011-07-03 13:20:58 +02:00
result = cls._instances.get(database_name)
if result:
return result
lock = cls._locks.get(database_name)
if not lock:
with cls._lock:
lock = cls._locks.setdefault(database_name, RLock())
with lock:
return cls._instances.setdefault(database_name,
super(Pool, cls).__new__(cls))
2009-02-11 14:52:22 +01:00
2011-07-03 13:20:58 +02:00
def __init__(self, database_name=None):
if database_name is None:
database_name = Transaction().database.name
2009-02-11 14:52:22 +01:00
self.database_name = database_name
@staticmethod
2012-09-24 22:16:53 +02:00
def register(*classes, **kwargs):
2009-02-11 14:52:22 +01:00
'''
2012-09-24 22:16:53 +02:00
Register a list of classes
2009-02-11 14:52:22 +01:00
'''
2012-09-24 22:16:53 +02:00
module = kwargs['module']
type_ = kwargs['type_']
2018-03-20 17:27:12 +01:00
depends = set(kwargs.get('depends', []))
2012-09-24 22:16:53 +02:00
assert type_ in ('model', 'report', 'wizard')
for cls in classes:
2018-09-26 23:10:00 +02:00
mpool = Pool.classes[type_][module]
assert cls not in mpool, cls
assert issubclass(cls.__class__, PoolMeta), cls
2018-09-26 23:10:00 +02:00
mpool[cls] = depends
2009-02-11 14:52:22 +01:00
2018-01-12 15:46:52 +01:00
@staticmethod
def register_mixin(mixin, classinfo, module):
Pool.classes_mixin[module].append((classinfo, mixin))
2011-07-03 13:20:58 +02:00
@classmethod
def start(cls):
2009-08-07 10:42:23 +02:00
'''
Start/restart the Pool
'''
2011-07-03 13:20:58 +02:00
with cls._lock:
2018-06-26 19:11:19 +02:00
for classes in Pool.classes.values():
2012-09-24 22:16:53 +02:00
classes.clear()
register_classes()
cls._started = True
2009-08-07 10:42:23 +02:00
2011-07-03 13:20:58 +02:00
@classmethod
def stop(cls, database_name):
'''
Stop the Pool
'''
2011-07-03 13:20:58 +02:00
with cls._lock:
if database_name in cls._instances:
del cls._instances[database_name]
2021-01-20 00:52:07 +01:00
lock = cls._locks.get(database_name)
if not lock:
return
with lock:
if database_name in cls._pool:
del cls._pool[database_name]
2011-07-03 13:20:58 +02:00
@classmethod
def database_list(cls):
2009-02-11 14:52:22 +01:00
'''
:return: database list
'''
with cls._lock:
databases = []
for database in cls._pool.keys():
if cls._locks.get(database):
if cls._locks[database].acquire(False):
databases.append(database)
cls._locks[database].release()
return databases
2009-02-11 14:52:22 +01:00
@property
def lock(self):
'''
Return the database lock for the pool.
'''
return self._locks[self.database_name]
def init(self, update=None, lang=None, activatedeps=False):
2009-02-11 14:52:22 +01:00
'''
Init pool
Set update to proceed to update
lang is a list of language code to be updated
2009-02-11 14:52:22 +01:00
'''
with self._lock:
if not self._started:
self.start()
2011-07-03 13:20:58 +02:00
with self._locks[self.database_name]:
# Don't reset pool if already init and not to update
if not update and self._pool.get(self.database_name):
return
2015-03-05 11:32:18 +01:00
logger.info('init pool for "%s"', self.database_name)
2011-07-03 13:20:58 +02:00
self._pool.setdefault(self.database_name, {})
2020-09-12 18:25:14 +02:00
self._modules = []
2014-12-02 12:54:01 +01:00
# Clean the _pool before loading modules
2009-02-11 14:52:22 +01:00
for type in self.classes.keys():
self._pool[self.database_name][type] = {}
2020-05-28 18:22:45 +02:00
try:
restart = not load_modules(
self.database_name, self, update=update, lang=lang,
activatedeps=activatedeps)
except Exception:
del self._pool[self.database_name]
2020-09-12 18:25:14 +02:00
self._modules = None
2020-05-28 18:22:45 +02:00
raise
2009-02-11 14:52:22 +01:00
if restart:
self.init()
def get(self, name, type='model'):
'''
Get an object from the pool
:param name: the object name
:param type: the type
:return: the instance
'''
if type == '*':
for type in self.classes.keys():
if name in self._pool[self.database_name][type]:
break
try:
return self._pool[self.database_name][type][name]
except KeyError:
if type == 'report':
from trytond.report import Report
2021-12-11 17:58:45 +01:00
# Keyword argument 'type' conflicts with builtin function
2020-09-12 18:25:14 +02:00
cls = builtins.type(name, (Report,), {'__slots__': ()})
2012-09-24 22:16:53 +02:00
cls.__setup__()
2020-09-12 18:25:14 +02:00
cls.__post_setup__()
2012-09-24 22:16:53 +02:00
self.add(cls, type)
2020-09-12 18:25:14 +02:00
self.setup_mixin(self._modules, type='report', name=name)
return self.get(name, type=type)
raise
2009-02-11 14:52:22 +01:00
2012-09-24 22:16:53 +02:00
def add(self, cls, type='model'):
2009-02-11 14:52:22 +01:00
'''
2012-09-24 22:16:53 +02:00
Add a classe to the pool
2009-02-11 14:52:22 +01:00
'''
2011-07-03 13:20:58 +02:00
with self._locks[self.database_name]:
2012-09-24 22:16:53 +02:00
self._pool[self.database_name][type][cls.__name__] = cls
2009-02-11 14:52:22 +01:00
def iterobject(self, type='model'):
'''
Return an iterator over object name, object
:param type: the type
:return: an iterator
'''
2018-06-26 19:11:19 +02:00
return self._pool[self.database_name][type].items()
2018-03-20 17:27:12 +01:00
def fill(self, module, modules):
2009-02-11 14:52:22 +01:00
'''
2018-03-20 17:27:12 +01:00
Fill the pool with the registered class from the module for the
activated modules.
2016-03-17 22:56:58 +01:00
Return a list of classes for each type in a dictionary.
2009-02-11 14:52:22 +01:00
'''
2012-09-24 22:16:53 +02:00
classes = {}
for type_ in self.classes.keys():
classes[type_] = []
2018-09-26 23:10:00 +02:00
for cls, depends in self.classes[type_].get(module, {}).items():
2018-03-20 17:27:12 +01:00
if not depends.issubset(modules):
continue
2012-09-24 22:16:53 +02:00
try:
previous_cls = self.get(cls.__name__, type=type_)
2019-09-07 23:45:08 +02:00
cls = type(
cls.__name__, (cls, previous_cls), {'__slots__': ()})
2012-09-24 22:16:53 +02:00
except KeyError:
pass
2018-03-20 17:27:12 +01:00
assert issubclass(cls, PoolBase), cls
2012-09-24 22:16:53 +02:00
self.add(cls, type=type_)
classes[type_].append(cls)
2020-09-12 18:25:14 +02:00
self._modules.append(module)
2012-09-24 22:16:53 +02:00
return classes
2015-10-01 22:37:13 +02:00
2016-03-17 22:56:58 +01:00
def setup(self, classes=None):
logger.info('setup pool for "%s"', self.database_name)
if classes is None:
classes = {}
for type_ in self._pool[self.database_name]:
2020-03-01 12:33:54 +01:00
classes[type_] = list(
self._pool[self.database_name][type_].values())
2018-06-26 19:11:19 +02:00
for type_, lst in classes.items():
2016-03-17 22:56:58 +01:00
for cls in lst:
cls.__setup__()
for cls in lst:
cls.__post_setup__()
2020-09-12 18:25:14 +02:00
def setup_mixin(self, modules, type=None, name=None):
2018-01-12 15:46:52 +01:00
logger.info('setup mixin for "%s"', self.database_name)
2020-09-12 18:25:14 +02:00
if type is not None:
types = [type]
else:
types = self.classes.keys()
2018-01-12 15:46:52 +01:00
for module in modules:
if module not in self.classes_mixin:
continue
2020-09-12 18:25:14 +02:00
for type_ in types:
for kname, cls in self.iterobject(type=type_):
if name is not None and kname != name:
continue
2018-01-12 15:46:52 +01:00
for parent, mixin in self.classes_mixin[module]:
if (not issubclass(cls, parent)
or issubclass(cls, mixin)):
continue
2020-09-12 18:25:14 +02:00
cls = builtins.type(
cls.__name__, (mixin, cls), {'__slots__': ()})
2018-01-12 15:46:52 +01:00
self.add(cls, type=type_)
2021-01-20 00:52:07 +01:00
def refresh(self, modules):
2021-05-05 12:03:41 +02:00
if self._modules is not None and set(self._modules) != modules:
2021-01-20 00:52:07 +01:00
self.stop(self.database_name)
2015-10-01 22:37:13 +02:00
def isregisteredby(obj, module, type_='model'):
pool = Pool()
classes = pool.classes[type_]
2018-09-26 23:10:00 +02:00
return any(issubclass(obj, cls) for cls in classes[module])