Files
tryton/trytond/modules/__init__.py
T

433 lines
15 KiB
Python
Raw Normal View History

2008-09-13 19:41:02 +02: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.
2012-04-01 23:08:15 +02:00
import os
import sys
2008-09-13 19:41:02 +02:00
import itertools
import logging
2010-08-19 22:01:12 +02:00
import contextlib
from functools import reduce
import imp
import operator
import ConfigParser
from glob import iglob
import datetime
2010-08-19 22:01:12 +02:00
import trytond.tools as tools
from trytond.config import CONFIG
from trytond.transaction import Transaction
from trytond.cache import Cache
import trytond.convert as convert
2008-09-13 19:41:02 +02:00
OPJ = os.path.join
MODULES_PATH = os.path.abspath(os.path.dirname(__file__))
2008-09-13 19:41:02 +02:00
MODULES = []
2008-11-18 17:40:30 +01:00
EGG_MODULES = {}
2009-08-07 10:42:23 +02:00
2012-04-01 23:08:15 +02:00
2009-08-07 10:42:23 +02:00
def update_egg_modules():
global EGG_MODULES
try:
import pkg_resources
for ep in pkg_resources.iter_entry_points('trytond.modules'):
mod_name = ep.module_name.split('.')[-1]
EGG_MODULES[mod_name] = ep
except ImportError:
pass
update_egg_modules()
2008-11-18 17:40:30 +01:00
2008-09-13 19:41:02 +02:00
class Graph(dict):
def add_node(self, name, deps):
for i in [Node(x, self) for x in deps]:
i.add_child(name)
if not deps:
Node(name, self)
def __iter__(self):
level = 0
2009-04-08 17:55:24 +02:00
done = set(self.keys())
2008-09-13 19:41:02 +02:00
while done:
2012-04-01 23:08:15 +02:00
level_modules = [(name, module) for name, module in self.items()
if module.depth == level]
2008-09-13 19:41:02 +02:00
for name, module in level_modules:
done.remove(name)
yield module
level += 1
def __str__(self):
res = ''
for i in self:
res += str(i)
res += '\n'
return res
class Singleton(object):
def __new__(cls, name, graph):
if name in graph:
inst = graph[name]
else:
inst = object.__new__(cls)
graph[name] = inst
return inst
class Node(Singleton):
def __init__(self, name, graph):
super(Node, self).__init__()
self.name = name
self.graph = graph
2012-01-22 00:07:15 +01:00
# __init__ is called even if Node already exists
if not hasattr(self, 'info'):
self.info = None
2008-09-13 19:41:02 +02:00
if not hasattr(self, 'childs'):
self.childs = []
if not hasattr(self, 'depth'):
self.depth = 0
def add_child(self, name):
node = Node(name, self.graph)
node.depth = max(self.depth + 1, node.depth)
if node not in self.all_childs():
self.childs.append(node)
self.childs.sort(key=operator.attrgetter('name'))
2008-09-13 19:41:02 +02:00
def all_childs(self):
res = []
for child in self.childs:
res.append(child)
res += child.all_childs()
return res
def has_child(self, name):
return Node(name, self.graph) in self.childs or \
bool([c for c in self.childs if c.has_child(name)])
def __setattr__(self, name, value):
super(Node, self).__setattr__(name, value)
if name == 'depth':
for child in self.childs:
setattr(child, name, value + 1)
def __iter__(self):
return itertools.chain(iter(self.childs),
*[iter(x) for x in self.childs])
def __str__(self):
return self.pprint()
def pprint(self, depth=0):
res = '%s\n' % self.name
for child in self.childs:
res += '%s`-> %s' % (' ' * depth, child.pprint(depth + 1))
return res
2012-04-01 23:08:15 +02:00
def get_module_info(name):
"Return the content of the tryton.cfg"
config = ConfigParser.ConfigParser()
with tools.file_open(os.path.join(name, 'tryton.cfg')) as fp:
config.readfp(fp)
directory = os.path.dirname(fp.name)
info = dict(config.items('tryton'))
info['directory'] = directory
for key in ('depends', 'extras_depend', 'xml'):
if key in info:
info[key] = info[key].strip().splitlines()
return info
def create_graph(module_list):
2008-09-13 19:41:02 +02:00
graph = Graph()
packages = []
for module in module_list:
try:
info = get_module_info(module)
except IOError:
if module != 'all':
raise Exception('Module %s not found' % module)
packages.append((module, info.get('depends', []),
info.get('extras_depend', []), info))
2008-09-13 19:41:02 +02:00
2009-04-08 17:55:24 +02:00
current, later = set([x[0] for x in packages]), set()
2012-01-22 00:07:15 +01:00
all_packages = set(current)
2008-09-13 19:41:02 +02:00
while packages and current > later:
2012-01-22 00:07:15 +01:00
package, deps, xdep, info = packages[0]
2008-09-13 19:41:02 +02:00
# if all dependencies of 'package' are already in the graph,
# add 'package' in the graph
2012-01-22 00:07:15 +01:00
all_deps = deps + [x for x in xdep if x in all_packages]
if reduce(lambda x, y: x and y in graph, all_deps, True):
2008-09-13 19:41:02 +02:00
if not package in current:
packages.pop(0)
continue
later.clear()
current.remove(package)
2012-01-22 00:07:15 +01:00
graph.add_node(package, all_deps)
2008-09-13 19:41:02 +02:00
node = Node(package, graph)
2012-01-22 00:07:15 +01:00
node.info = info
2008-09-13 19:41:02 +02:00
else:
later.add(package)
2012-01-22 00:07:15 +01:00
packages.append((package, deps, xdep, info))
2008-09-13 19:41:02 +02:00
packages.pop(0)
2012-01-22 00:07:15 +01:00
for package, deps, xdep, info in packages:
2008-09-13 19:41:02 +02:00
if package not in later:
continue
missings = [x for x in deps if x not in graph]
raise Exception('%s unmet dependencies: %s' % (package, missings))
2008-09-13 19:41:02 +02:00
return graph, packages, later
def is_module_to_install(module):
for kind in ('init', 'update'):
if 'all' in CONFIG[kind] and module != 'test':
return True
elif module in CONFIG[kind]:
return True
return False
2012-04-01 23:08:15 +02:00
2010-08-19 22:01:12 +02:00
def load_module_graph(graph, pool, lang=None):
2008-09-13 19:41:02 +02:00
if lang is None:
2012-01-27 21:11:06 +01:00
lang = [CONFIG['language']]
2008-09-13 19:41:02 +02:00
modules_todo = []
models_to_update_history = set()
2009-02-11 14:52:22 +01:00
logger = logging.getLogger('modules')
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
modules = [x.name for x in graph]
cursor.execute('SELECT name, state FROM ir_module_module '
'WHERE name in (' + ','.join(('%s',) * len(modules)) + ')',
modules)
module2state = dict(cursor.fetchall())
2008-09-13 19:41:02 +02:00
for package in graph:
module = package.name
if module not in MODULES:
continue
2009-02-11 14:52:22 +01:00
logger.info(module)
2008-09-13 19:41:02 +02:00
sys.stdout.flush()
2012-09-24 22:16:53 +02:00
classes = pool.setup(module)
package_state = module2state.get(module, 'uninstalled')
if (is_module_to_install(module)
or package_state in ('to install', 'to upgrade')):
if package_state not in ('to install', 'to upgrade'):
package_state = 'to install'
for child in package.childs:
module2state[child.name] = package_state
2012-09-24 22:16:53 +02:00
for type in classes.keys():
for cls in classes[type]:
logger.info('%s:register %s' % (module, cls.__name__))
cls.__register__(module)
for model in classes['model']:
if hasattr(model, '_history'):
2012-09-24 22:16:53 +02:00
models_to_update_history.add(model.__name__)
2008-09-13 19:41:02 +02:00
#Instanciate a new parser for the package:
tryton_parser = convert.TrytondXmlHandler(pool=pool, module=module)
2008-09-13 19:41:02 +02:00
2012-01-22 00:07:15 +01:00
for filename in package.info.get('xml', []):
filename = filename.replace('/', os.sep)
2009-02-11 14:52:22 +01:00
logger.info('%s:loading %s' % (module, filename))
# Feed the parser with xml content:
with tools.file_open(OPJ(module, filename)) as fp:
tryton_parser.parse_xmlstream(fp)
2008-09-13 19:41:02 +02:00
2009-01-26 16:18:48 +01:00
modules_todo.append((module, list(tryton_parser.to_delete)))
2008-09-13 19:41:02 +02:00
for filename in iglob('%s/%s/*.po'
% (package.info['directory'], 'locale')):
filename = filename.replace('/', os.sep)
2011-09-27 18:32:40 +02:00
lang2 = os.path.splitext(os.path.basename(filename))[0]
2008-09-13 19:41:02 +02:00
if lang2 not in lang:
continue
logger.info('%s:loading %s' % (module,
filename[len(package.info['directory']) + 1:]))
2012-09-24 22:16:53 +02:00
Translation = pool.get('ir.translation')
Translation.translation_import(lang2, module, filename)
2008-09-13 19:41:02 +02:00
cursor.execute('SELECT id FROM ir_module_module '
'WHERE name = %s', (package.name,))
try:
module_id, = cursor.fetchone()
cursor.execute('UPDATE ir_module_module SET state = %s '
'WHERE id = %s', ('installed', module_id))
except TypeError:
cursor.execute('INSERT INTO ir_module_module '
'(create_uid, create_date, name, state) '
'VALUES (%s, %s, %s, %s)', (0, datetime.datetime.now(),
package.name, 'installed'))
module2state[package.name] = 'installed'
2008-09-13 19:41:02 +02:00
2009-02-11 14:52:22 +01:00
cursor.commit()
2008-09-13 19:41:02 +02:00
# Create missing reports
from trytond.report import Report
2012-09-24 22:16:53 +02:00
ActionReport = pool.get('ir.action.report')
reports = ActionReport.search([
('module', '=', module),
])
report_names = pool.object_name_list(type='report')
2012-09-24 22:16:53 +02:00
for report in reports:
report_name = report.report_name
if report_name not in report_names:
report = object.__new__(Report)
2012-09-24 22:16:53 +02:00
report.__name__ = report_name
pool.add(report, type='report')
report.__init__()
for model_name in models_to_update_history:
model = pool.get(model_name)
if model._history:
2012-09-24 22:16:53 +02:00
logger.info('history:update %s' % model.__name__)
2010-08-19 22:01:12 +02:00
model._update_history_table()
2008-09-13 19:41:02 +02:00
# Vacuum :
while modules_todo:
(module, to_delete) = modules_todo.pop()
convert.post_import(pool, module, to_delete)
2008-09-13 19:41:02 +02:00
cursor.commit()
2012-04-01 23:08:15 +02:00
2008-09-13 19:41:02 +02:00
def get_module_list():
2008-12-01 20:25:09 +01:00
module_list = set()
2008-09-13 19:41:02 +02:00
if os.path.exists(MODULES_PATH) and os.path.isdir(MODULES_PATH):
for file in os.listdir(MODULES_PATH):
if file.startswith('.'):
continue
2008-09-13 19:41:02 +02:00
if os.path.isdir(OPJ(MODULES_PATH, file)):
2008-12-01 20:25:09 +01:00
module_list.add(file)
2009-08-07 10:42:23 +02:00
update_egg_modules()
module_list.update(EGG_MODULES.keys())
2008-12-01 20:25:09 +01:00
module_list.add('ir')
module_list.add('res')
module_list.add('webdav')
2010-03-04 14:02:27 +01:00
module_list.add('test')
2008-12-01 20:25:09 +01:00
return list(module_list)
2008-09-13 19:41:02 +02:00
2012-04-01 23:08:15 +02:00
def register_classes():
2009-08-07 10:42:23 +02:00
'''
Import modules to register the classes in the Pool
'''
import trytond.ir
2012-09-24 22:16:53 +02:00
trytond.ir.register()
import trytond.res
2012-09-24 22:16:53 +02:00
trytond.res.register()
import trytond.webdav
2012-09-24 22:16:53 +02:00
trytond.webdav.register()
import trytond.test
2012-09-24 22:16:53 +02:00
trytond.test.register()
2009-02-11 14:52:22 +01:00
logger = logging.getLogger('modules')
2008-09-13 19:41:02 +02:00
for package in create_graph(get_module_list())[0]:
module = package.name
2009-02-11 14:52:22 +01:00
logger.info('%s:registering classes' % module)
2008-09-13 19:41:02 +02:00
2012-03-25 00:15:17 +01:00
if module in ('ir', 'res', 'webdav', 'test'):
2008-09-13 19:41:02 +02:00
MODULES.append(module)
continue
2011-05-26 15:21:15 +02:00
if os.path.isdir(OPJ(MODULES_PATH, module)):
2012-10-24 23:38:12 +02:00
mod_path = MODULES_PATH
2008-11-18 17:40:30 +01:00
elif module in EGG_MODULES:
ep = EGG_MODULES[module]
mod_path = os.path.join(ep.dist.location,
*ep.module_name.split('.')[:-1])
if not os.path.isdir(mod_path):
# Find module in path
for path in sys.path:
mod_path = os.path.join(path,
*ep.module_name.split('.')[:-1])
if os.path.isdir(os.path.join(mod_path, module)):
break
if not os.path.isdir(os.path.join(mod_path, module)):
# When testing modules from setuptools location is the
# module directory
mod_path = os.path.dirname(ep.dist.location)
2008-11-18 17:40:30 +01:00
else:
raise Exception('Couldn\'t find module %s' % module)
2012-10-24 23:38:12 +02:00
mod_file, pathname, description = imp.find_module(module,
[mod_path])
the_module = imp.load_module('trytond.modules.' + module,
mod_file, pathname, description)
# Some modules register nothing in the Pool
if hasattr(the_module, 'register'):
the_module.register()
if mod_file is not None:
mod_file.close()
2008-09-13 19:41:02 +02:00
MODULES.append(module)
2012-04-01 23:08:15 +02:00
2009-02-11 14:52:22 +01:00
def load_modules(database_name, pool, update=False, lang=None):
2008-09-30 11:55:07 +02:00
res = True
2010-08-19 22:01:12 +02:00
if not Transaction().cursor:
contextmanager = Transaction().start(database_name, 0)
else:
contextmanager = contextlib.nested(Transaction().new_cursor(),
2010-10-11 20:05:47 +02:00
Transaction().set_user(0),
Transaction().reset_context())
2010-08-19 22:01:12 +02:00
with contextmanager:
cursor = Transaction().cursor
2009-02-11 14:52:22 +01:00
if update:
2012-03-25 00:15:17 +01:00
# Migration from 2.2: workflow module removed
cursor.execute('DELETE FROM ir_module_module '
'WHERE name = %s', ('workflow',))
2008-09-13 19:41:02 +02:00
if 'all' in CONFIG['init']:
cursor.execute("SELECT name FROM ir_module_module " \
2010-03-04 14:02:27 +01:00
"WHERE name != \'test\'")
2008-09-13 19:41:02 +02:00
else:
cursor.execute("SELECT name FROM ir_module_module " \
"WHERE state IN ('installed', 'to install', " \
"'to upgrade', 'to remove')")
else:
cursor.execute("SELECT name FROM ir_module_module " \
"WHERE state IN ('installed', 'to upgrade', 'to remove')")
module_list = [name for (name,) in cursor.fetchall()]
2009-02-11 14:52:22 +01:00
if update:
2008-09-13 19:41:02 +02:00
for module in CONFIG['init'].keys():
if CONFIG['init'][module]:
module_list.append(module)
for module in CONFIG['update'].keys():
if CONFIG['update'][module]:
module_list.append(module)
graph = create_graph(module_list)[0]
2008-09-13 19:41:02 +02:00
try:
2010-08-19 22:01:12 +02:00
load_module_graph(graph, pool, lang)
2010-07-08 19:53:39 +02:00
except Exception:
2008-09-13 19:41:02 +02:00
cursor.rollback()
raise
2009-02-11 14:52:22 +01:00
if update:
2008-09-13 19:41:02 +02:00
cursor.execute("SELECT name FROM ir_module_module " \
"WHERE state IN ('to remove')")
fetchall = cursor.fetchall()
if fetchall:
for (mod_name,) in fetchall:
2008-09-13 19:41:02 +02:00
#TODO check if ressource not updated by the user
cursor.execute('SELECT model, db_id FROM ir_model_data ' \
'WHERE module = %s ' \
'ORDER BY id DESC', (mod_name,))
for rmod, rid in cursor.fetchall():
2012-10-10 11:29:46 +02:00
pool.get(rmod).delete([rmod(rid)])
2008-09-13 19:41:02 +02:00
cursor.commit()
cursor.execute("UPDATE ir_module_module SET state = %s " \
"WHERE state IN ('to remove')", ('uninstalled',))
cursor.commit()
2008-09-30 11:55:07 +02:00
res = False
2008-09-13 19:41:02 +02:00
2012-09-24 22:16:53 +02:00
Module = pool.get('ir.module.module')
Module.update_list()
2008-09-13 19:41:02 +02:00
cursor.commit()
2010-08-19 22:01:12 +02:00
Cache.resets(database_name)
2008-09-30 11:55:07 +02:00
return res