author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 31 Jul 2009 23:37:42 +0200 | |
changeset 2600 | 6cd6c5d11b45 |
parent 2596 | d02eed70937f |
child 2631 | 90dd26e61361 |
permissions | -rw-r--r-- |
0 | 1 |
"""Defines the central class for the CubicWeb RQL server: the repository. |
2 |
||
3 |
The repository is an abstraction allowing execution of rql queries against |
|
4 |
data sources. Most of the work is actually done in helper classes. The |
|
5 |
repository mainly: |
|
6 |
||
7 |
* brings these classes all together to provide a single access |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
8 |
point to a cubicweb instance. |
0 | 9 |
* handles session management |
10 |
* provides method for pyro registration, to call if pyro is enabled |
|
11 |
||
12 |
||
13 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1954
diff
changeset
|
14 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 15 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1954
diff
changeset
|
16 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 17 |
""" |
18 |
__docformat__ = "restructuredtext en" |
|
19 |
||
20 |
import sys |
|
21 |
import Queue |
|
22 |
from os.path import join, exists |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
636
diff
changeset
|
23 |
from datetime import datetime |
0 | 24 |
from time import time, localtime, strftime |
25 |
||
26 |
from logilab.common.decorators import cached |
|
27 |
||
28 |
from yams import BadSchemaDefinition |
|
29 |
from rql import RQLSyntaxError |
|
30 |
||
31 |
from cubicweb import (CW_SOFTWARE_ROOT, UnknownEid, AuthenticationError, |
|
32 |
ETypeNotSupportedBySources, RTypeNotSupportedBySources, |
|
33 |
BadConnectionId, Unauthorized, ValidationError, |
|
34 |
ExecutionError, typed_eid, |
|
35 |
CW_MIGRATION_MAP) |
|
36 |
from cubicweb.cwvreg import CubicWebRegistry |
|
2596
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2493
diff
changeset
|
37 |
from cubicweb.schema import VIRTUAL_RTYPES, CubicWebSchema |
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2493
diff
changeset
|
38 |
from cubicweb import server |
0 | 39 |
from cubicweb.server.utils import RepoThread, LoopTask |
40 |
from cubicweb.server.pool import ConnectionsPool, LateOperation, SingleLastOperation |
|
41 |
from cubicweb.server.session import Session, InternalSession |
|
42 |
from cubicweb.server.querier import QuerierHelper |
|
43 |
from cubicweb.server.sources import get_source |
|
44 |
from cubicweb.server.hooksmanager import HooksManager |
|
45 |
from cubicweb.server.hookhelper import rproperty |
|
46 |
||
47 |
||
48 |
class CleanupEidTypeCacheOp(SingleLastOperation): |
|
49 |
"""on rollback of a insert query or commit of delete query, we have to |
|
50 |
clear repository's cache from no more valid entries |
|
51 |
||
52 |
NOTE: querier's rqlst/solutions cache may have been polluted too with |
|
53 |
queries such as Any X WHERE X eid 32 if 32 has been rollbacked however |
|
54 |
generated queries are unpredictable and analysing all the cache probably |
|
55 |
too expensive. Notice that there is no pb when using args to specify eids |
|
56 |
instead of giving them into the rql string. |
|
57 |
""" |
|
58 |
||
59 |
def commit_event(self): |
|
60 |
"""the observed connections pool has been rollbacked, |
|
61 |
remove inserted eid from repository type/source cache |
|
62 |
""" |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
63 |
try: |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
64 |
self.repo.clear_caches(self.session.transaction_data['pendingeids']) |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
65 |
except KeyError: |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
66 |
pass |
1482 | 67 |
|
0 | 68 |
def rollback_event(self): |
69 |
"""the observed connections pool has been rollbacked, |
|
70 |
remove inserted eid from repository type/source cache |
|
71 |
""" |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
72 |
try: |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
73 |
self.repo.clear_caches(self.session.transaction_data['neweids']) |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
74 |
except KeyError: |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
75 |
pass |
0 | 76 |
|
77 |
||
78 |
class FTIndexEntityOp(LateOperation): |
|
79 |
"""operation to delay entity full text indexation to commit |
|
80 |
||
81 |
since fti indexing may trigger discovery of other entities, it should be |
|
82 |
triggered on precommit, not commit, and this should be done after other |
|
83 |
precommit operation which may add relations to the entity |
|
84 |
""" |
|
85 |
||
86 |
def precommit_event(self): |
|
87 |
session = self.session |
|
88 |
entity = self.entity |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
89 |
if entity.eid in session.transaction_data.get('pendingeids', ()): |
0 | 90 |
return # entity added and deleted in the same transaction |
91 |
session.repo.system_source.fti_unindex_entity(session, entity.eid) |
|
92 |
for container in entity.fti_containers(): |
|
93 |
session.repo.index_entity(session, container) |
|
1482 | 94 |
|
0 | 95 |
def commit_event(self): |
96 |
pass |
|
97 |
||
98 |
def del_existing_rel_if_needed(session, eidfrom, rtype, eidto): |
|
99 |
"""delete existing relation when adding a new one if card is 1 or ? |
|
100 |
||
101 |
have to be done once the new relation has been inserted to avoid having |
|
102 |
an entity without a relation for some time |
|
103 |
||
104 |
this kind of behaviour has to be done in the repository so we don't have |
|
105 |
hooks order hazardness |
|
106 |
""" |
|
107 |
# skip delete queries (only?) if session is an internal session. This is |
|
108 |
# hooks responsability to ensure they do not violate relation's cardinality |
|
109 |
if session.is_super_session: |
|
110 |
return |
|
111 |
card = rproperty(session, rtype, eidfrom, eidto, 'cardinality') |
|
112 |
# one may be tented to check for neweids but this may cause more than one |
|
113 |
# relation even with '1?' cardinality if thoses relations are added in the |
|
114 |
# same transaction where the entity is being created. This never occurs from |
|
115 |
# the web interface but may occurs during test or dbapi connection (though |
|
116 |
# not expected for this). So: don't do it, we pretend to ensure repository |
|
117 |
# consistency. |
|
118 |
if card[0] in '1?': |
|
119 |
rschema = session.repo.schema.rschema(rtype) |
|
120 |
if not rschema.inlined: |
|
1320 | 121 |
session.unsafe_execute( |
122 |
'DELETE X %s Y WHERE X eid %%(x)s, NOT Y eid %%(y)s' % rtype, |
|
123 |
{'x': eidfrom, 'y': eidto}, 'x') |
|
0 | 124 |
if card[1] in '1?': |
1320 | 125 |
session.unsafe_execute( |
126 |
'DELETE X %s Y WHERE NOT X eid %%(x)s, Y eid %%(y)s' % rtype, |
|
127 |
{'x': eidfrom, 'y': eidto}, 'y') |
|
0 | 128 |
|
1482 | 129 |
|
0 | 130 |
class Repository(object): |
131 |
"""a repository provides access to a set of persistent storages for |
|
132 |
entities and relations |
|
133 |
||
134 |
XXX protect pyro access |
|
135 |
""" |
|
1482 | 136 |
|
0 | 137 |
def __init__(self, config, vreg=None, debug=False): |
138 |
self.config = config |
|
139 |
if vreg is None: |
|
140 |
vreg = CubicWebRegistry(config, debug) |
|
141 |
self.vreg = vreg |
|
142 |
self.pyro_registered = False |
|
143 |
self.info('starting repository from %s', self.config.apphome) |
|
144 |
# dictionary of opened sessions |
|
145 |
self._sessions = {} |
|
146 |
# list of functions to be called at regular interval |
|
147 |
self._looping_tasks = [] |
|
148 |
# list of running threads |
|
149 |
self._running_threads = [] |
|
150 |
# initial schema, should be build or replaced latter |
|
151 |
self.schema = CubicWebSchema(config.appid) |
|
152 |
# querier helper, need to be created after sources initialization |
|
153 |
self.querier = QuerierHelper(self, self.schema) |
|
1187 | 154 |
# should we reindex in changes? |
1217 | 155 |
self.do_fti = not config['delay-full-text-indexation'] |
0 | 156 |
# sources |
157 |
self.sources = [] |
|
158 |
self.sources_by_uri = {} |
|
159 |
# FIXME: store additional sources info in the system database ? |
|
160 |
# FIXME: sources should be ordered (add_entity priority) |
|
161 |
for uri, source_config in config.sources().items(): |
|
162 |
if uri == 'admin': |
|
163 |
# not an actual source |
|
1482 | 164 |
continue |
0 | 165 |
source = self.get_source(uri, source_config) |
166 |
self.sources_by_uri[uri] = source |
|
167 |
self.sources.append(source) |
|
168 |
self.system_source = self.sources_by_uri['system'] |
|
169 |
# ensure system source is the first one |
|
170 |
self.sources.remove(self.system_source) |
|
171 |
self.sources.insert(0, self.system_source) |
|
172 |
# cache eid -> type / source |
|
173 |
self._type_source_cache = {} |
|
174 |
# cache (extid, source uri) -> eid |
|
175 |
self._extid_cache = {} |
|
176 |
# create the hooks manager |
|
177 |
self.hm = HooksManager(self.schema) |
|
178 |
# open some connections pools |
|
179 |
self._available_pools = Queue.Queue() |
|
180 |
self._available_pools.put_nowait(ConnectionsPool(self.sources)) |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
181 |
if config.read_instance_schema: |
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
182 |
# normal start: load the instance schema from the database |
0 | 183 |
self.fill_schema() |
184 |
elif config.bootstrap_schema: |
|
185 |
# usually during repository creation |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
186 |
self.warning("set fs instance'schema as bootstrap schema") |
0 | 187 |
config.bootstrap_cubes() |
188 |
self.set_bootstrap_schema(self.config.load_schema()) |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
189 |
# need to load the Any and CWUser entity types |
0 | 190 |
self.vreg.schema = self.schema |
191 |
etdirectory = join(CW_SOFTWARE_ROOT, 'entities') |
|
1317 | 192 |
self.vreg.init_registration([etdirectory]) |
1316
6d71d38822ee
introduce init_registration method and call it in repo initialization
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
193 |
self.vreg.load_file(join(etdirectory, '__init__.py'), |
6d71d38822ee
introduce init_registration method and call it in repo initialization
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
194 |
'cubicweb.entities.__init__') |
6d71d38822ee
introduce init_registration method and call it in repo initialization
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
195 |
self.vreg.load_file(join(etdirectory, 'authobjs.py'), |
6d71d38822ee
introduce init_registration method and call it in repo initialization
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
196 |
'cubicweb.entities.authobjs') |
0 | 197 |
else: |
198 |
# test start: use the file system schema (quicker) |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
199 |
self.warning("set fs instance'schema") |
0 | 200 |
config.bootstrap_cubes() |
201 |
self.set_schema(self.config.load_schema()) |
|
202 |
if not config.creating: |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
203 |
if 'CWProperty' in self.schema: |
0 | 204 |
self.vreg.init_properties(self.properties()) |
205 |
# call source's init method to complete their initialisation if |
|
206 |
# needed (for instance looking for persistent configuration using an |
|
207 |
# internal session, which is not possible until pools have been |
|
208 |
# initialized) |
|
209 |
for source in self.sources: |
|
210 |
source.init() |
|
211 |
else: |
|
212 |
# call init_creating so for instance native source can configurate |
|
213 |
# tsearch according to postgres version |
|
214 |
for source in self.sources: |
|
215 |
source.init_creating() |
|
216 |
# close initialization pool and reopen fresh ones for proper |
|
217 |
# initialization now that we know cubes |
|
1482 | 218 |
self._get_pool().close(True) |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
219 |
# list of available pools (we can't iterated on Queue instance) |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
220 |
self.pools = [] |
0 | 221 |
for i in xrange(config['connections-pool-size']): |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
222 |
self.pools.append(ConnectionsPool(self.sources)) |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
223 |
self._available_pools.put_nowait(self.pools[-1]) |
1883
011e13d74cfc
shuting -> shutting
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1880
diff
changeset
|
224 |
self._shutting_down = False |
2473
490f88fb99b6
new distinguish repairing/creating from regular start.
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2268
diff
changeset
|
225 |
if not (config.creating or config.repairing): |
490f88fb99b6
new distinguish repairing/creating from regular start.
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2268
diff
changeset
|
226 |
# call instance level initialisation hooks |
2153
d42d1eaefcdd
call server_startup hook once pools have been initialized
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
227 |
self.hm.call_hooks('server_startup', repo=self) |
d42d1eaefcdd
call server_startup hook once pools have been initialized
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
228 |
# register a task to cleanup expired session |
d42d1eaefcdd
call server_startup hook once pools have been initialized
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
229 |
self.looping_task(self.config['session-time']/3., |
d42d1eaefcdd
call server_startup hook once pools have been initialized
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
230 |
self.clean_sessions) |
1482 | 231 |
|
0 | 232 |
# internals ############################################################### |
233 |
||
234 |
def get_source(self, uri, source_config): |
|
235 |
source_config['uri'] = uri |
|
236 |
return get_source(source_config, self.schema, self) |
|
1482 | 237 |
|
0 | 238 |
def set_schema(self, schema, resetvreg=True): |
239 |
schema.rebuild_infered_relations() |
|
240 |
self.info('set schema %s %#x', schema.name, id(schema)) |
|
241 |
self.debug(', '.join(sorted(str(e) for e in schema.entities()))) |
|
242 |
self.querier.set_schema(schema) |
|
243 |
for source in self.sources: |
|
244 |
source.set_schema(schema) |
|
245 |
self.schema = schema |
|
246 |
if resetvreg: |
|
247 |
# full reload of all appobjects |
|
248 |
self.vreg.reset() |
|
249 |
self.vreg.set_schema(schema) |
|
250 |
self.hm.set_schema(schema) |
|
251 |
self.hm.register_system_hooks(self.config) |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
252 |
# instance specific hooks |
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
253 |
if self.config.instance_hooks: |
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
254 |
self.info('loading instance hooks') |
0 | 255 |
self.hm.register_hooks(self.config.load_hooks(self.vreg)) |
256 |
||
257 |
def fill_schema(self): |
|
258 |
"""lod schema from the repository""" |
|
259 |
from cubicweb.server.schemaserial import deserialize_schema |
|
260 |
self.info('loading schema from the repository') |
|
261 |
appschema = CubicWebSchema(self.config.appid) |
|
262 |
self.set_bootstrap_schema(self.config.load_bootstrap_schema()) |
|
263 |
self.debug('deserializing db schema into %s %#x', appschema.name, id(appschema)) |
|
264 |
session = self.internal_session() |
|
265 |
try: |
|
266 |
try: |
|
267 |
deserialize_schema(appschema, session) |
|
268 |
except BadSchemaDefinition: |
|
269 |
raise |
|
270 |
except Exception, ex: |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
271 |
import traceback |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
272 |
traceback.print_exc() |
1482 | 273 |
raise Exception('Is the database initialised ? (cause: %s)' % |
0 | 274 |
(ex.args and ex.args[0].strip() or 'unknown')), \ |
275 |
None, sys.exc_info()[-1] |
|
276 |
self.info('set the actual schema') |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
277 |
# XXX have to do this since CWProperty isn't in the bootstrap schema |
0 | 278 |
# it'll be redone in set_schema |
279 |
self.set_bootstrap_schema(appschema) |
|
280 |
# 2.49 migration |
|
281 |
if exists(join(self.config.apphome, 'vc.conf')): |
|
282 |
session.set_pool() |
|
283 |
if not 'template' in file(join(self.config.apphome, 'vc.conf')).read(): |
|
284 |
# remaning from cubicweb < 2.38... |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
285 |
session.execute('DELETE CWProperty X WHERE X pkey "system.version.template"') |
0 | 286 |
session.commit() |
287 |
finally: |
|
288 |
session.close() |
|
289 |
self.config.init_cubes(self.get_cubes()) |
|
290 |
self.set_schema(appschema) |
|
1482 | 291 |
|
0 | 292 |
def set_bootstrap_schema(self, schema): |
293 |
"""disable hooks when setting a bootstrap schema, but restore |
|
294 |
the configuration for the next time |
|
295 |
""" |
|
296 |
config = self.config |
|
297 |
# XXX refactor |
|
298 |
config.core_hooks = False |
|
299 |
config.usergroup_hooks = False |
|
300 |
config.schema_hooks = False |
|
301 |
config.notification_hooks = False |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
302 |
config.instance_hooks = False |
0 | 303 |
self.set_schema(schema, resetvreg=False) |
304 |
config.core_hooks = True |
|
305 |
config.usergroup_hooks = True |
|
306 |
config.schema_hooks = True |
|
307 |
config.notification_hooks = True |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
308 |
config.instance_hooks = True |
1482 | 309 |
|
0 | 310 |
def start_looping_tasks(self): |
311 |
assert isinstance(self._looping_tasks, list), 'already started' |
|
312 |
for i, (interval, func) in enumerate(self._looping_tasks): |
|
313 |
self._looping_tasks[i] = task = LoopTask(interval, func) |
|
314 |
self.info('starting task %s with interval %.2fs', task.name, |
|
315 |
interval) |
|
316 |
task.start() |
|
317 |
# ensure no tasks will be further added |
|
318 |
self._looping_tasks = tuple(self._looping_tasks) |
|
319 |
||
320 |
def looping_task(self, interval, func): |
|
321 |
"""register a function to be called every `interval` seconds. |
|
1482 | 322 |
|
0 | 323 |
looping tasks can only be registered during repository initialization, |
324 |
once done this method will fail. |
|
325 |
""" |
|
326 |
try: |
|
327 |
self._looping_tasks.append( (interval, func) ) |
|
328 |
except AttributeError: |
|
329 |
raise RuntimeError("can't add looping task once the repository is started") |
|
330 |
||
331 |
def threaded_task(self, func): |
|
332 |
"""start function in a separated thread""" |
|
333 |
t = RepoThread(func, self._running_threads) |
|
334 |
t.start() |
|
1482 | 335 |
|
0 | 336 |
#@locked |
337 |
def _get_pool(self): |
|
338 |
try: |
|
339 |
return self._available_pools.get(True, timeout=5) |
|
340 |
except Queue.Empty: |
|
341 |
raise Exception('no pool available after 5 secs, probably either a ' |
|
342 |
'bug in code (to many uncommited/rollbacked ' |
|
343 |
'connections) or to much load on the server (in ' |
|
344 |
'which case you can try to set a bigger ' |
|
345 |
'connections pools size)') |
|
1482 | 346 |
|
0 | 347 |
def _free_pool(self, pool): |
348 |
self._available_pools.put_nowait(pool) |
|
349 |
||
350 |
def pinfo(self): |
|
351 |
# XXX: session.pool is accessed from a local storage, would be interesting |
|
352 |
# to see if there is a pool set in any thread specific data) |
|
353 |
import threading |
|
354 |
return '%s: %s (%s)' % (self._available_pools.qsize(), |
|
355 |
','.join(session.user.login for session in self._sessions.values() |
|
356 |
if session.pool), |
|
357 |
threading.currentThread()) |
|
358 |
def shutdown(self): |
|
359 |
"""called on server stop event to properly close opened sessions and |
|
360 |
connections |
|
361 |
""" |
|
1883
011e13d74cfc
shuting -> shutting
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1880
diff
changeset
|
362 |
self._shutting_down = True |
0 | 363 |
if isinstance(self._looping_tasks, tuple): # if tasks have been started |
364 |
for looptask in self._looping_tasks: |
|
365 |
self.info('canceling task %s...', looptask.name) |
|
366 |
looptask.cancel() |
|
367 |
looptask.join() |
|
368 |
self.info('task %s finished', looptask.name) |
|
369 |
for thread in self._running_threads: |
|
370 |
self.info('waiting thread %s...', thread.name) |
|
371 |
thread.join() |
|
372 |
self.info('thread %s finished', thread.name) |
|
373 |
self.hm.call_hooks('server_shutdown', repo=self) |
|
374 |
self.close_sessions() |
|
375 |
while not self._available_pools.empty(): |
|
376 |
pool = self._available_pools.get_nowait() |
|
377 |
try: |
|
378 |
pool.close(True) |
|
379 |
except: |
|
380 |
self.exception('error while closing %s' % pool) |
|
381 |
continue |
|
382 |
if self.pyro_registered: |
|
383 |
pyro_unregister(self.config) |
|
384 |
hits, misses = self.querier.cache_hit, self.querier.cache_miss |
|
385 |
try: |
|
386 |
self.info('rqlt st cache hit/miss: %s/%s (%s%% hits)', hits, misses, |
|
387 |
(hits * 100) / (hits + misses)) |
|
388 |
hits, misses = self.system_source.cache_hit, self.system_source.cache_miss |
|
389 |
self.info('sql cache hit/miss: %s/%s (%s%% hits)', hits, misses, |
|
390 |
(hits * 100) / (hits + misses)) |
|
391 |
nocache = self.system_source.no_cache |
|
392 |
self.info('sql cache usage: %s/%s (%s%%)', hits+ misses, nocache, |
|
393 |
((hits + misses) * 100) / (hits + misses + nocache)) |
|
394 |
except ZeroDivisionError: |
|
395 |
pass |
|
1482 | 396 |
|
2267
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
397 |
def _login_from_email(self, login): |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
398 |
session = self.internal_session() |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
399 |
try: |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
400 |
rset = session.execute('Any L WHERE U login L, U primary_email M, ' |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
401 |
'M address %(login)s', {'login': login}) |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
402 |
if rset.rowcount == 1: |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
403 |
login = rset[0][0] |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
404 |
finally: |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
405 |
session.close() |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
406 |
return login |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
407 |
|
0 | 408 |
def authenticate_user(self, session, login, password): |
409 |
"""validate login / password, raise AuthenticationError on failure |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
410 |
return associated CWUser instance on success |
0 | 411 |
""" |
2267
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
412 |
if self.vreg.config['allow-email-login'] and '@' in login: |
e1d2df3f1091
move login by email functionnality on the repository side to avoid buggy call to internal_session from the web interface side
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
413 |
login = self._login_from_email(login) |
0 | 414 |
for source in self.sources: |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
415 |
if source.support_entity('CWUser'): |
0 | 416 |
try: |
417 |
eid = source.authenticate(session, login, password) |
|
418 |
break |
|
419 |
except AuthenticationError: |
|
420 |
continue |
|
421 |
else: |
|
422 |
raise AuthenticationError('authentication failed with all sources') |
|
2268
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
423 |
cwuser = self._build_user(session, eid) |
0 | 424 |
if self.config.consider_user_state and \ |
2268
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
425 |
not cwuser.state in cwuser.AUTHENTICABLE_STATES: |
0 | 426 |
raise AuthenticationError('user is not in authenticable state') |
2268
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
427 |
return cwuser |
0 | 428 |
|
429 |
def _build_user(self, session, eid): |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
430 |
"""return a CWUser entity for user with the given eid""" |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
431 |
cls = self.vreg.etype_class('CWUser') |
0 | 432 |
rql = cls.fetch_rql(session.user, ['X eid %(x)s']) |
433 |
rset = session.execute(rql, {'x': eid}, 'x') |
|
434 |
assert len(rset) == 1, rset |
|
2268
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
435 |
cwuser = rset.get_entity(0, 0) |
1138
22f634977c95
make pylint happy, fix some bugs on the way
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
436 |
# pylint: disable-msg=W0104 |
2268
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
437 |
# prefetch / cache cwuser's groups and properties. This is especially |
0 | 438 |
# useful for internal sessions to avoid security insertions |
2268
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
439 |
cwuser.groups |
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
440 |
cwuser.properties |
2f336fd5e040
euser->cwuser
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2267
diff
changeset
|
441 |
return cwuser |
1482 | 442 |
|
0 | 443 |
# public (dbapi) interface ################################################ |
1482 | 444 |
|
0 | 445 |
def get_schema(self): |
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
446 |
"""return the instance schema. This is a public method, not |
0 | 447 |
requiring a session id |
448 |
""" |
|
449 |
try: |
|
450 |
# necessary to support pickling used by pyro |
|
451 |
self.schema.__hashmode__ = 'pickle' |
|
452 |
return self.schema |
|
453 |
finally: |
|
454 |
self.schema.__hashmode__ = None |
|
455 |
||
456 |
def get_cubes(self): |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
457 |
"""return the list of cubes used by this instance. This is a |
0 | 458 |
public method, not requiring a session id. |
459 |
""" |
|
2473
490f88fb99b6
new distinguish repairing/creating from regular start.
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2268
diff
changeset
|
460 |
versions = self.get_versions(not (self.config.creating |
490f88fb99b6
new distinguish repairing/creating from regular start.
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2268
diff
changeset
|
461 |
or self.config.repairing)) |
0 | 462 |
cubes = list(versions) |
463 |
cubes.remove('cubicweb') |
|
464 |
return cubes |
|
465 |
||
466 |
@cached |
|
467 |
def get_versions(self, checkversions=False): |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
468 |
"""return the a dictionary containing cubes used by this instance |
0 | 469 |
as key with their version as value, including cubicweb version. This is a |
470 |
public method, not requiring a session id. |
|
471 |
""" |
|
472 |
from logilab.common.changelog import Version |
|
473 |
vcconf = {} |
|
474 |
session = self.internal_session() |
|
475 |
try: |
|
476 |
for pk, version in session.execute( |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
477 |
'Any K,V WHERE P is CWProperty, P value V, P pkey K, ' |
0 | 478 |
'P pkey ~="system.version.%"', build_descr=False): |
479 |
cube = pk.split('.')[-1] |
|
480 |
# XXX cubicweb migration |
|
481 |
if cube in CW_MIGRATION_MAP: |
|
482 |
cube = CW_MIGRATION_MAP[cube] |
|
483 |
version = Version(version) |
|
484 |
vcconf[cube] = version |
|
485 |
if checkversions: |
|
486 |
if cube != 'cubicweb': |
|
487 |
fsversion = self.config.cube_version(cube) |
|
488 |
else: |
|
489 |
fsversion = self.config.cubicweb_version() |
|
490 |
if version < fsversion: |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2473
diff
changeset
|
491 |
msg = ('instance has %s version %s but %s ' |
0 | 492 |
'is installed. Run "cubicweb-ctl upgrade".') |
493 |
raise ExecutionError(msg % (cube, version, fsversion)) |
|
494 |
finally: |
|
495 |
session.close() |
|
496 |
return vcconf |
|
1482 | 497 |
|
0 | 498 |
@cached |
499 |
def source_defs(self): |
|
500 |
sources = self.config.sources().copy() |
|
501 |
# remove manager information |
|
502 |
sources.pop('admin', None) |
|
503 |
# remove sensitive information |
|
504 |
for uri, sourcedef in sources.iteritems(): |
|
505 |
sourcedef = sourcedef.copy() |
|
506 |
self.sources_by_uri[uri].remove_sensitive_information(sourcedef) |
|
507 |
sources[uri] = sourcedef |
|
508 |
return sources |
|
509 |
||
510 |
def properties(self): |
|
511 |
"""return a result set containing system wide properties""" |
|
512 |
session = self.internal_session() |
|
513 |
try: |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
514 |
return session.execute('Any K,V WHERE P is CWProperty,' |
0 | 515 |
'P pkey K, P value V, NOT P for_user U', |
516 |
build_descr=False) |
|
517 |
finally: |
|
518 |
session.close() |
|
519 |
||
1372
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
520 |
def register_user(self, login, password, email=None, **kwargs): |
0 | 521 |
"""check a user with the given login exists, if not create it with the |
522 |
given password. This method is designed to be used for anonymous |
|
523 |
registration on public web site. |
|
524 |
""" |
|
1664
03ebeccf9f1d
add XXX before 2 calls to self.repo.internal_session() on the web interface side
Florent <florent@secondweb.fr>
parents:
1482
diff
changeset
|
525 |
# XXX should not be called from web interface |
0 | 526 |
session = self.internal_session() |
1372
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
527 |
# for consistency, keep same error as unique check hook (although not required) |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
528 |
errmsg = session._('the value "%s" is already used, use another one') |
0 | 529 |
try: |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
530 |
if (session.execute('CWUser X WHERE X login %(login)s', {'login': login}) |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
531 |
or session.execute('CWUser X WHERE X use_email C, C address %(login)s', |
1372
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
532 |
{'login': login})): |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
533 |
raise ValidationError(None, {'login': errmsg % login}) |
0 | 534 |
# we have to create the user |
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1372
diff
changeset
|
535 |
user = self.vreg.etype_class('CWUser')(session, None) |
0 | 536 |
if isinstance(password, unicode): |
537 |
# password should *always* be utf8 encoded |
|
538 |
password = password.encode('UTF8') |
|
539 |
kwargs['login'] = login |
|
540 |
kwargs['upassword'] = password |
|
541 |
user.update(kwargs) |
|
542 |
self.glob_add_entity(session, user) |
|
543 |
session.execute('SET X in_group G WHERE X eid %(x)s, G name "users"', |
|
544 |
{'x': user.eid}) |
|
1372
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
545 |
if email or '@' in login: |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
546 |
d = {'login': login, 'email': email or login} |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
547 |
if session.execute('EmailAddress X WHERE X address %(email)s', d): |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
548 |
raise ValidationError(None, {'address': errmsg % d['email']}) |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
549 |
session.execute('INSERT EmailAddress X: X address %(email)s, ' |
d4264cd876e1
register_user can now also set an email
Florent <florent@secondweb.fr>
parents:
1320
diff
changeset
|
550 |
'U primary_email X, U use_email X WHERE U login %(login)s', d) |
0 | 551 |
session.commit() |
552 |
finally: |
|
553 |
session.close() |
|
594
76218d42d21f
return success or not on creation of user
Arthur Lutz <arthur.lutz@logilab.fr>
parents:
479
diff
changeset
|
554 |
return True |
1482 | 555 |
|
0 | 556 |
def connect(self, login, password, cnxprops=None): |
557 |
"""open a connection for a given user |
|
558 |
||
559 |
base_url may be needed to send mails |
|
560 |
cnxtype indicate if this is a pyro connection or a in-memory connection |
|
1482 | 561 |
|
0 | 562 |
raise `AuthenticationError` if the authentication failed |
563 |
raise `ConnectionError` if we can't open a connection |
|
564 |
""" |
|
565 |
# use an internal connection |
|
566 |
session = self.internal_session() |
|
567 |
# try to get a user object |
|
568 |
try: |
|
569 |
user = self.authenticate_user(session, login, password) |
|
570 |
finally: |
|
571 |
session.close() |
|
572 |
session = Session(user, self, cnxprops) |
|
573 |
user.req = user.rset.req = session |
|
574 |
user.clear_related_cache() |
|
575 |
self._sessions[session.id] = session |
|
576 |
self.info('opened %s', session) |
|
577 |
self.hm.call_hooks('session_open', session=session) |
|
578 |
# commit session at this point in case write operation has been done |
|
579 |
# during `session_open` hooks |
|
580 |
session.commit() |
|
581 |
return session.id |
|
582 |
||
583 |
def execute(self, sessionid, rqlstring, args=None, eid_key=None, build_descr=True): |
|
584 |
"""execute a RQL query |
|
585 |
||
586 |
* rqlstring should be an unicode string or a plain ascii string |
|
587 |
* args the optional parameters used in the query |
|
588 |
* build_descr is a flag indicating if the description should be |
|
589 |
built on select queries |
|
590 |
""" |
|
591 |
session = self._get_session(sessionid, setpool=True) |
|
592 |
try: |
|
593 |
try: |
|
594 |
return self.querier.execute(session, rqlstring, args, eid_key, |
|
595 |
build_descr) |
|
596 |
except (Unauthorized, RQLSyntaxError): |
|
597 |
raise |
|
598 |
except ValidationError, ex: |
|
599 |
# need ValidationError normalization here so error may pass |
|
600 |
# through pyro |
|
601 |
if hasattr(ex.entity, 'eid'): |
|
602 |
ex.entity = ex.entity.eid # error raised by yams |
|
603 |
args = list(ex.args) |
|
604 |
args[0] = ex.entity |
|
605 |
ex.args = tuple(args) |
|
606 |
raise |
|
607 |
except: |
|
608 |
# FIXME: check error to catch internal errors |
|
609 |
self.exception('unexpected error') |
|
610 |
raise |
|
611 |
finally: |
|
612 |
session.reset_pool() |
|
1482 | 613 |
|
0 | 614 |
def describe(self, sessionid, eid): |
615 |
"""return a tuple (type, source, extid) for the entity with id <eid>""" |
|
616 |
session = self._get_session(sessionid, setpool=True) |
|
617 |
try: |
|
618 |
return self.type_and_source_from_eid(eid, session) |
|
619 |
finally: |
|
620 |
session.reset_pool() |
|
621 |
||
622 |
def check_session(self, sessionid): |
|
623 |
"""raise `BadSessionId` if the connection is no more valid""" |
|
624 |
self._get_session(sessionid, setpool=False) |
|
625 |
||
626 |
def get_shared_data(self, sessionid, key, default=None, pop=False): |
|
627 |
"""return the session's data dictionary""" |
|
628 |
session = self._get_session(sessionid, setpool=False) |
|
629 |
return session.get_shared_data(key, default, pop) |
|
630 |
||
631 |
def set_shared_data(self, sessionid, key, value, querydata=False): |
|
632 |
"""set value associated to `key` in shared data |
|
633 |
||
634 |
if `querydata` is true, the value will be added to the repository |
|
635 |
session's query data which are cleared on commit/rollback of the current |
|
636 |
transaction, and won't be available through the connexion, only on the |
|
637 |
repository side. |
|
638 |
""" |
|
639 |
session = self._get_session(sessionid, setpool=False) |
|
640 |
session.set_shared_data(key, value, querydata) |
|
641 |
||
642 |
def commit(self, sessionid): |
|
643 |
"""commit transaction for the session with the given id""" |
|
644 |
self.debug('begin commit for session %s', sessionid) |
|
645 |
try: |
|
1880
293fe4b49e28
two in one: #343320: Logging out while deleting a CWUser blocks the cw server / #342692: ensure transaction state when Ctrl-C or other stop signal is received
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1664
diff
changeset
|
646 |
self._get_session(sessionid).commit() |
1482 | 647 |
except (ValidationError, Unauthorized): |
0 | 648 |
raise |
649 |
except: |
|
650 |
self.exception('unexpected error') |
|
651 |
raise |
|
1482 | 652 |
|
0 | 653 |
def rollback(self, sessionid): |
654 |
"""commit transaction for the session with the given id""" |
|
655 |
self.debug('begin rollback for session %s', sessionid) |
|
656 |
try: |
|
1880
293fe4b49e28
two in one: #343320: Logging out while deleting a CWUser blocks the cw server / #342692: ensure transaction state when Ctrl-C or other stop signal is received
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1664
diff
changeset
|
657 |
self._get_session(sessionid).rollback() |
0 | 658 |
except: |
659 |
self.exception('unexpected error') |
|
660 |
raise |
|
661 |
||
1939
67e7379edd96
#343379: disturbing message on upgrade
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1883
diff
changeset
|
662 |
def close(self, sessionid, checkshuttingdown=True): |
0 | 663 |
"""close the session with the given id""" |
1939
67e7379edd96
#343379: disturbing message on upgrade
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1883
diff
changeset
|
664 |
session = self._get_session(sessionid, setpool=True, |
67e7379edd96
#343379: disturbing message on upgrade
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1883
diff
changeset
|
665 |
checkshuttingdown=checkshuttingdown) |
0 | 666 |
# operation uncommited before close are rollbacked before hook is called |
667 |
session.rollback() |
|
668 |
self.hm.call_hooks('session_close', session=session) |
|
669 |
# commit session at this point in case write operation has been done |
|
670 |
# during `session_close` hooks |
|
671 |
session.commit() |
|
672 |
session.close() |
|
673 |
del self._sessions[sessionid] |
|
674 |
self.info('closed session %s for user %s', sessionid, session.user.login) |
|
1482 | 675 |
|
0 | 676 |
def user_info(self, sessionid, props=None): |
677 |
"""this method should be used by client to: |
|
678 |
* check session id validity |
|
679 |
* update user information on each user's request (i.e. groups and |
|
680 |
custom properties) |
|
681 |
""" |
|
682 |
session = self._get_session(sessionid, setpool=False) |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
683 |
if props is not None: |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
684 |
self.set_session_props(sessionid, props) |
0 | 685 |
user = session.user |
686 |
return user.eid, user.login, user.groups, user.properties |
|
1482 | 687 |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
688 |
def set_session_props(self, sessionid, props): |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
689 |
"""this method should be used by client to: |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
690 |
* check session id validity |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
691 |
* update user information on each user's request (i.e. groups and |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
692 |
custom properties) |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
693 |
""" |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
694 |
session = self._get_session(sessionid, setpool=False) |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
695 |
# update session properties |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
696 |
for prop, value in props.items(): |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
697 |
session.change_property(prop, value) |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2192
diff
changeset
|
698 |
|
0 | 699 |
# public (inter-repository) interface ##################################### |
1482 | 700 |
|
0 | 701 |
def entities_modified_since(self, etypes, mtime): |
702 |
"""function designed to be called from an external repository which |
|
703 |
is using this one as a rql source for synchronization, and return a |
|
704 |
3-uple containing : |
|
705 |
* the local date |
|
706 |
* list of (etype, eid) of entities of the given types which have been |
|
707 |
modified since the given timestamp (actually entities whose full text |
|
708 |
index content has changed) |
|
709 |
* list of (etype, eid) of entities of the given types which have been |
|
710 |
deleted since the given timestamp |
|
711 |
""" |
|
712 |
session = self.internal_session() |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
636
diff
changeset
|
713 |
updatetime = datetime.now() |
0 | 714 |
try: |
715 |
modentities, delentities = self.system_source.modified_entities( |
|
716 |
session, etypes, mtime) |
|
717 |
return updatetime, modentities, delentities |
|
718 |
finally: |
|
719 |
session.close() |
|
720 |
||
721 |
# session handling ######################################################## |
|
1482 | 722 |
|
0 | 723 |
def close_sessions(self): |
724 |
"""close every opened sessions""" |
|
725 |
for sessionid in self._sessions.keys(): |
|
726 |
try: |
|
1939
67e7379edd96
#343379: disturbing message on upgrade
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1883
diff
changeset
|
727 |
self.close(sessionid, checkshuttingdown=False) |
0 | 728 |
except: |
729 |
self.exception('error while closing session %s' % sessionid) |
|
730 |
||
731 |
def clean_sessions(self): |
|
732 |
"""close sessions not used since an amount of time specified in the |
|
733 |
configuration |
|
734 |
""" |
|
735 |
mintime = time() - self.config['session-time'] |
|
736 |
self.debug('cleaning session unused since %s', |
|
737 |
strftime('%T', localtime(mintime))) |
|
738 |
nbclosed = 0 |
|
739 |
for session in self._sessions.values(): |
|
740 |
if session.timestamp < mintime: |
|
741 |
self.close(session.id) |
|
742 |
nbclosed += 1 |
|
743 |
return nbclosed |
|
1482 | 744 |
|
0 | 745 |
def internal_session(self, cnxprops=None): |
746 |
"""return a dbapi like connection/cursor using internal user which |
|
747 |
have every rights on the repository. You'll *have to* commit/rollback |
|
748 |
or close (rollback implicitly) the session once the job's done, else |
|
749 |
you'll leak connections pool up to the time where no more pool is |
|
750 |
available, causing irremediable freeze... |
|
751 |
""" |
|
752 |
session = InternalSession(self, cnxprops) |
|
753 |
session.set_pool() |
|
754 |
return session |
|
1482 | 755 |
|
1939
67e7379edd96
#343379: disturbing message on upgrade
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1883
diff
changeset
|
756 |
def _get_session(self, sessionid, setpool=False, checkshuttingdown=True): |
0 | 757 |
"""return the user associated to the given session identifier""" |
1939
67e7379edd96
#343379: disturbing message on upgrade
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1883
diff
changeset
|
758 |
if checkshuttingdown and self._shutting_down: |
1883
011e13d74cfc
shuting -> shutting
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1880
diff
changeset
|
759 |
raise Exception('Repository is shutting down') |
0 | 760 |
try: |
761 |
session = self._sessions[sessionid] |
|
762 |
except KeyError: |
|
763 |
raise BadConnectionId('No such session %s' % sessionid) |
|
764 |
if setpool: |
|
765 |
session.set_pool() |
|
766 |
return session |
|
767 |
||
768 |
# data sources handling ################################################### |
|
769 |
# * correspondance between eid and (type, source) |
|
770 |
# * correspondance between eid and local id (i.e. specific to a given source) |
|
771 |
# * searchable text indexes |
|
1482 | 772 |
|
0 | 773 |
def type_and_source_from_eid(self, eid, session=None): |
774 |
"""return a tuple (type, source, extid) for the entity with id <eid>""" |
|
775 |
try: |
|
776 |
eid = typed_eid(eid) |
|
777 |
except ValueError: |
|
778 |
raise UnknownEid(eid) |
|
779 |
try: |
|
780 |
return self._type_source_cache[eid] |
|
781 |
except KeyError: |
|
782 |
if session is None: |
|
783 |
session = self.internal_session() |
|
784 |
reset_pool = True |
|
785 |
else: |
|
786 |
reset_pool = False |
|
787 |
try: |
|
788 |
etype, uri, extid = self.system_source.eid_type_source(session, |
|
789 |
eid) |
|
790 |
finally: |
|
791 |
if reset_pool: |
|
792 |
session.reset_pool() |
|
793 |
self._type_source_cache[eid] = (etype, uri, extid) |
|
794 |
if uri != 'system': |
|
795 |
self._extid_cache[(extid, uri)] = eid |
|
796 |
return etype, uri, extid |
|
797 |
||
798 |
def clear_caches(self, eids): |
|
799 |
etcache = self._type_source_cache |
|
800 |
extidcache = self._extid_cache |
|
801 |
rqlcache = self.querier._rql_cache |
|
802 |
for eid in eids: |
|
803 |
try: |
|
804 |
etype, uri, extid = etcache.pop(typed_eid(eid)) # may be a string in some cases |
|
805 |
rqlcache.pop('%s X WHERE X eid %s' % (etype, eid), None) |
|
806 |
extidcache.pop((extid, uri), None) |
|
807 |
except KeyError: |
|
808 |
etype = None |
|
809 |
rqlcache.pop('Any X WHERE X eid %s' % eid, None) |
|
810 |
for source in self.sources: |
|
811 |
source.clear_eid_cache(eid, etype) |
|
1482 | 812 |
|
0 | 813 |
def type_from_eid(self, eid, session=None): |
814 |
"""return the type of the entity with id <eid>""" |
|
815 |
return self.type_and_source_from_eid(eid, session)[0] |
|
1482 | 816 |
|
0 | 817 |
def source_from_eid(self, eid, session=None): |
818 |
"""return the source for the given entity's eid""" |
|
819 |
return self.sources_by_uri[self.type_and_source_from_eid(eid, session)[1]] |
|
1482 | 820 |
|
0 | 821 |
def eid2extid(self, source, eid, session=None): |
822 |
"""get local id from an eid""" |
|
823 |
etype, uri, extid = self.type_and_source_from_eid(eid, session) |
|
824 |
if source.uri != uri: |
|
825 |
# eid not from the given source |
|
826 |
raise UnknownEid(eid) |
|
827 |
return extid |
|
828 |
||
1954 | 829 |
def extid2eid(self, source, extid, etype, session=None, insert=True, |
1250
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
830 |
recreate=False): |
0 | 831 |
"""get eid from a local id. An eid is attributed if no record is found""" |
1954 | 832 |
cachekey = (extid, source.uri) |
0 | 833 |
try: |
834 |
return self._extid_cache[cachekey] |
|
835 |
except KeyError: |
|
836 |
pass |
|
837 |
reset_pool = False |
|
838 |
if session is None: |
|
839 |
session = self.internal_session() |
|
840 |
reset_pool = True |
|
1954 | 841 |
eid = self.system_source.extid2eid(session, source, extid) |
0 | 842 |
if eid is not None: |
843 |
self._extid_cache[cachekey] = eid |
|
1954 | 844 |
self._type_source_cache[eid] = (etype, source.uri, extid) |
1250
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
845 |
if recreate: |
1954 | 846 |
entity = source.before_entity_insertion(session, extid, etype, eid) |
1250
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
847 |
entity._cw_recreating = True |
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
848 |
if source.should_call_hooks: |
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
849 |
self.hm.call_hooks('before_add_entity', etype, session, entity) |
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
850 |
# XXX add fti op ? |
1954 | 851 |
source.after_entity_insertion(session, extid, entity) |
1250
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
852 |
if source.should_call_hooks: |
5c20a7f13c84
new recreate argument to extid2eid when an external source want to recreate entities previously imported with a predictable ext id
sylvain.thenault@logilab.fr
parents:
1228
diff
changeset
|
853 |
self.hm.call_hooks('after_add_entity', etype, session, entity) |
0 | 854 |
if reset_pool: |
855 |
session.reset_pool() |
|
856 |
return eid |
|
857 |
if not insert: |
|
858 |
return |
|
1954 | 859 |
# no link between extid and eid, create one using an internal session |
0 | 860 |
# since the current session user may not have required permissions to |
861 |
# do necessary stuff and we don't want to commit user session. |
|
862 |
# |
|
450
5e14ea0e81c8
a note for later
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
341
diff
changeset
|
863 |
# Moreover, even if session is already an internal session but is |
0 | 864 |
# processing a commit, we have to use another one |
865 |
if not session.is_internal_session: |
|
866 |
session = self.internal_session() |
|
867 |
reset_pool = True |
|
868 |
try: |
|
869 |
eid = self.system_source.create_eid(session) |
|
870 |
self._extid_cache[cachekey] = eid |
|
1954 | 871 |
self._type_source_cache[eid] = (etype, source.uri, extid) |
872 |
entity = source.before_entity_insertion(session, extid, etype, eid) |
|
0 | 873 |
if source.should_call_hooks: |
874 |
self.hm.call_hooks('before_add_entity', etype, session, entity) |
|
450
5e14ea0e81c8
a note for later
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
341
diff
changeset
|
875 |
# XXX call add_info with complete=False ? |
1954 | 876 |
self.add_info(session, entity, source, extid) |
877 |
source.after_entity_insertion(session, extid, entity) |
|
0 | 878 |
if source.should_call_hooks: |
879 |
self.hm.call_hooks('after_add_entity', etype, session, entity) |
|
880 |
else: |
|
881 |
# minimal meta-data |
|
882 |
session.execute('SET X is E WHERE X eid %(x)s, E name %(name)s', |
|
883 |
{'x': entity.eid, 'name': entity.id}, 'x') |
|
884 |
session.commit(reset_pool) |
|
885 |
return eid |
|
886 |
except: |
|
887 |
session.rollback(reset_pool) |
|
888 |
raise |
|
1482 | 889 |
|
0 | 890 |
def add_info(self, session, entity, source, extid=None, complete=True): |
891 |
"""add type and source info for an eid into the system table, |
|
892 |
and index the entity with the full text index |
|
893 |
""" |
|
894 |
# begin by inserting eid/type/source/extid into the entities table |
|
895 |
self.system_source.add_info(session, entity, source, extid) |
|
896 |
if complete: |
|
897 |
entity.complete(entity.e_schema.indexable_attributes()) |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
898 |
new = session.transaction_data.setdefault('neweids', set()) |
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
899 |
new.add(entity.eid) |
0 | 900 |
# now we can update the full text index |
1160
77bf88f01fcc
new delay-full-text-indexation configuration option
sylvain.thenault@logilab.fr
parents:
594
diff
changeset
|
901 |
if self.do_fti: |
77bf88f01fcc
new delay-full-text-indexation configuration option
sylvain.thenault@logilab.fr
parents:
594
diff
changeset
|
902 |
FTIndexEntityOp(session, entity=entity) |
0 | 903 |
CleanupEidTypeCacheOp(session) |
1482 | 904 |
|
0 | 905 |
def delete_info(self, session, eid): |
906 |
self._prepare_delete_info(session, eid) |
|
907 |
self._delete_info(session, eid) |
|
1482 | 908 |
|
0 | 909 |
def _prepare_delete_info(self, session, eid): |
910 |
"""prepare the repository for deletion of an entity: |
|
911 |
* update the fti |
|
912 |
* mark eid as being deleted in session info |
|
913 |
* setup cache update operation |
|
914 |
""" |
|
915 |
self.system_source.fti_unindex_entity(session, eid) |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
916 |
pending = session.transaction_data.setdefault('pendingeids', set()) |
0 | 917 |
pending.add(eid) |
918 |
CleanupEidTypeCacheOp(session) |
|
1482 | 919 |
|
0 | 920 |
def _delete_info(self, session, eid): |
921 |
"""delete system information on deletion of an entity: |
|
922 |
* delete all relations on this entity |
|
923 |
* transfer record from the entities table to the deleted_entities table |
|
924 |
""" |
|
925 |
etype, uri, extid = self.type_and_source_from_eid(eid, session) |
|
926 |
self._clear_eid_relations(session, etype, eid) |
|
927 |
self.system_source.delete_info(session, eid, etype, uri, extid) |
|
1482 | 928 |
|
0 | 929 |
def _clear_eid_relations(self, session, etype, eid): |
930 |
"""when a entity is deleted, build and execute rql query to delete all |
|
931 |
its relations |
|
932 |
""" |
|
933 |
rql = [] |
|
934 |
eschema = self.schema.eschema(etype) |
|
935 |
for rschema, targetschemas, x in eschema.relation_definitions(): |
|
936 |
rtype = rschema.type |
|
2596
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2493
diff
changeset
|
937 |
if rtype in VIRTUAL_RTYPES: |
0 | 938 |
continue |
939 |
var = '%s%s' % (rtype.upper(), x.upper()) |
|
940 |
if x == 'subject': |
|
941 |
# don't skip inlined relation so they are regularly |
|
942 |
# deleted and so hooks are correctly called |
|
943 |
rql.append('X %s %s' % (rtype, var)) |
|
944 |
else: |
|
945 |
rql.append('%s %s X' % (var, rtype)) |
|
946 |
rql = 'DELETE %s WHERE X eid %%(x)s' % ','.join(rql) |
|
947 |
# unsafe_execute since we suppose that if user can delete the entity, |
|
948 |
# he can delete all its relations without security checking |
|
949 |
session.unsafe_execute(rql, {'x': eid}, 'x', build_descr=False) |
|
950 |
||
951 |
def index_entity(self, session, entity): |
|
952 |
"""full text index a modified entity""" |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
953 |
alreadydone = session.transaction_data.setdefault('indexedeids', set()) |
0 | 954 |
if entity.eid in alreadydone: |
955 |
self.info('skipping reindexation of %s, already done', entity.eid) |
|
956 |
return |
|
957 |
alreadydone.add(entity.eid) |
|
958 |
self.system_source.fti_index_entity(session, entity) |
|
1482 | 959 |
|
0 | 960 |
def locate_relation_source(self, session, subject, rtype, object): |
961 |
subjsource = self.source_from_eid(subject, session) |
|
962 |
objsource = self.source_from_eid(object, session) |
|
963 |
if not (subjsource is objsource and subjsource.support_relation(rtype, 1)): |
|
964 |
source = self.system_source |
|
965 |
if not source.support_relation(rtype, 1): |
|
966 |
raise RTypeNotSupportedBySources(rtype) |
|
967 |
else: |
|
968 |
source = subjsource |
|
969 |
return source |
|
1482 | 970 |
|
0 | 971 |
def locate_etype_source(self, etype): |
972 |
for source in self.sources: |
|
973 |
if source.support_entity(etype, 1): |
|
974 |
return source |
|
975 |
else: |
|
976 |
raise ETypeNotSupportedBySources(etype) |
|
1482 | 977 |
|
0 | 978 |
def glob_add_entity(self, session, entity): |
979 |
"""add an entity to the repository |
|
1482 | 980 |
|
0 | 981 |
the entity eid should originaly be None and a unique eid is assigned to |
982 |
the entity instance |
|
983 |
""" |
|
984 |
entity = entity.pre_add_hook() |
|
985 |
eschema = entity.e_schema |
|
986 |
etype = str(eschema) |
|
987 |
source = self.locate_etype_source(etype) |
|
988 |
# attribute an eid to the entity before calling hooks |
|
989 |
entity.set_eid(self.system_source.create_eid(session)) |
|
2600
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
990 |
if server.DEBUG & server.DBG_REPO: |
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
991 |
print 'ADD entity', etype, entity.eid, dict(entity) |
0 | 992 |
entity._is_saved = False # entity has an eid but is not yet saved |
993 |
relations = [] |
|
994 |
# if inlined relations are specified, fill entity's related cache to |
|
995 |
# avoid unnecessary queries |
|
996 |
for attr in entity.keys(): |
|
997 |
rschema = eschema.subject_relation(attr) |
|
998 |
if not rschema.is_final(): # inlined relation |
|
999 |
entity.set_related_cache(attr, 'subject', |
|
1000 |
entity.req.eid_rset(entity[attr])) |
|
1001 |
relations.append((attr, entity[attr])) |
|
1002 |
if source.should_call_hooks: |
|
1003 |
self.hm.call_hooks('before_add_entity', etype, session, entity) |
|
1004 |
entity.set_defaults() |
|
1005 |
entity.check(creation=True) |
|
1006 |
source.add_entity(session, entity) |
|
1007 |
if source.uri != 'system': |
|
1008 |
extid = source.get_extid(entity) |
|
1009 |
self._extid_cache[(str(extid), source.uri)] = entity.eid |
|
1010 |
else: |
|
1011 |
extid = None |
|
1012 |
self.add_info(session, entity, source, extid, complete=False) |
|
1013 |
entity._is_saved = True # entity has an eid and is saved |
|
1014 |
#print 'added', entity#, entity.items() |
|
1015 |
# trigger after_add_entity after after_add_relation |
|
1016 |
if source.should_call_hooks: |
|
1017 |
self.hm.call_hooks('after_add_entity', etype, session, entity) |
|
1018 |
# call hooks for inlined relations |
|
1019 |
for attr, value in relations: |
|
1020 |
self.hm.call_hooks('before_add_relation', attr, session, |
|
1021 |
entity.eid, attr, value) |
|
1022 |
self.hm.call_hooks('after_add_relation', attr, session, |
|
1023 |
entity.eid, attr, value) |
|
1024 |
return entity.eid |
|
1482 | 1025 |
|
0 | 1026 |
def glob_update_entity(self, session, entity): |
1027 |
"""replace an entity in the repository |
|
1028 |
the type and the eid of an entity must not be changed |
|
1029 |
""" |
|
2600
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1030 |
etype = str(entity.e_schema) |
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1031 |
if server.DEBUG & server.DBG_REPO: |
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1032 |
print 'UPDATE entity', etype, entity.eid, dict(entity) |
0 | 1033 |
entity.check() |
1034 |
eschema = entity.e_schema |
|
1035 |
only_inline_rels, need_fti_update = True, False |
|
1036 |
relations = [] |
|
1037 |
for attr in entity.keys(): |
|
1038 |
if attr == 'eid': |
|
1039 |
continue |
|
1040 |
rschema = eschema.subject_relation(attr) |
|
1041 |
if rschema.is_final(): |
|
1042 |
if eschema.rproperty(attr, 'fulltextindexed'): |
|
1043 |
need_fti_update = True |
|
1044 |
only_inline_rels = False |
|
1045 |
else: |
|
1046 |
# inlined relation |
|
1047 |
previous_value = entity.related(attr) |
|
1048 |
if previous_value: |
|
1049 |
previous_value = previous_value[0][0] # got a result set |
|
1050 |
self.hm.call_hooks('before_delete_relation', attr, session, |
|
1051 |
entity.eid, attr, previous_value) |
|
1052 |
entity.set_related_cache(attr, 'subject', |
|
1053 |
entity.req.eid_rset(entity[attr])) |
|
1054 |
relations.append((attr, entity[attr], previous_value)) |
|
1055 |
source = self.source_from_eid(entity.eid, session) |
|
1056 |
if source.should_call_hooks: |
|
1057 |
# call hooks for inlined relations |
|
1058 |
for attr, value, _ in relations: |
|
1059 |
self.hm.call_hooks('before_add_relation', attr, session, |
|
1060 |
entity.eid, attr, value) |
|
1061 |
if not only_inline_rels: |
|
1062 |
self.hm.call_hooks('before_update_entity', etype, session, |
|
1063 |
entity) |
|
1064 |
source.update_entity(session, entity) |
|
1065 |
if not only_inline_rels: |
|
1160
77bf88f01fcc
new delay-full-text-indexation configuration option
sylvain.thenault@logilab.fr
parents:
594
diff
changeset
|
1066 |
if need_fti_update and self.do_fti: |
0 | 1067 |
# reindex the entity only if this query is updating at least |
1068 |
# one indexable attribute |
|
1069 |
FTIndexEntityOp(session, entity=entity) |
|
1070 |
if source.should_call_hooks: |
|
1071 |
self.hm.call_hooks('after_update_entity', etype, session, |
|
1072 |
entity) |
|
1073 |
if source.should_call_hooks: |
|
1074 |
for attr, value, prevvalue in relations: |
|
1075 |
if prevvalue: |
|
1076 |
self.hm.call_hooks('after_delete_relation', attr, session, |
|
1077 |
entity.eid, attr, prevvalue) |
|
1078 |
del_existing_rel_if_needed(session, entity.eid, attr, value) |
|
1079 |
self.hm.call_hooks('after_add_relation', attr, session, |
|
1080 |
entity.eid, attr, value) |
|
1081 |
||
1082 |
def glob_delete_entity(self, session, eid): |
|
1083 |
"""delete an entity and all related entities from the repository""" |
|
1084 |
# call delete_info before hooks |
|
1085 |
self._prepare_delete_info(session, eid) |
|
1086 |
etype, uri, extid = self.type_and_source_from_eid(eid, session) |
|
2600
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1087 |
if server.DEBUG & server.DBG_REPO: |
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1088 |
print 'DELETE entity', etype, eid |
0 | 1089 |
source = self.sources_by_uri[uri] |
1090 |
if source.should_call_hooks: |
|
1091 |
self.hm.call_hooks('before_delete_entity', etype, session, eid) |
|
1092 |
self._delete_info(session, eid) |
|
1093 |
source.delete_entity(session, etype, eid) |
|
1094 |
if source.should_call_hooks: |
|
1095 |
self.hm.call_hooks('after_delete_entity', etype, session, eid) |
|
1096 |
# don't clear cache here this is done in a hook on commit |
|
1482 | 1097 |
|
0 | 1098 |
def glob_add_relation(self, session, subject, rtype, object): |
1099 |
"""add a relation to the repository""" |
|
2600
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1100 |
if server.DEBUG & server.DBG_REPO: |
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1101 |
print 'ADD relation', subject, rtype, object |
0 | 1102 |
source = self.locate_relation_source(session, subject, rtype, object) |
1103 |
if source.should_call_hooks: |
|
1104 |
del_existing_rel_if_needed(session, subject, rtype, object) |
|
1105 |
self.hm.call_hooks('before_add_relation', rtype, session, |
|
1106 |
subject, rtype, object) |
|
1107 |
source.add_relation(session, subject, rtype, object) |
|
1108 |
if source.should_call_hooks: |
|
1109 |
self.hm.call_hooks('after_add_relation', rtype, session, |
|
1110 |
subject, rtype, object) |
|
1111 |
||
1112 |
def glob_delete_relation(self, session, subject, rtype, object): |
|
1113 |
"""delete a relation from the repository""" |
|
2600
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1114 |
if server.DEBUG & server.DBG_REPO: |
6cd6c5d11b45
[F repo debugging] log repo event on DBG_REPO debug level
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
1115 |
print 'DELETE relation', subject, rtype, object |
0 | 1116 |
source = self.locate_relation_source(session, subject, rtype, object) |
1117 |
if source.should_call_hooks: |
|
1118 |
self.hm.call_hooks('before_delete_relation', rtype, session, |
|
1119 |
subject, rtype, object) |
|
1120 |
source.delete_relation(session, subject, rtype, object) |
|
1121 |
if self.schema.rschema(rtype).symetric: |
|
1122 |
# on symetric relation, we can't now in which sense it's |
|
1123 |
# stored so try to delete both |
|
1124 |
source.delete_relation(session, object, rtype, subject) |
|
1125 |
if source.should_call_hooks: |
|
1126 |
self.hm.call_hooks('after_delete_relation', rtype, session, |
|
1127 |
subject, rtype, object) |
|
1128 |
||
1129 |
||
1130 |
# pyro handling ########################################################### |
|
1482 | 1131 |
|
0 | 1132 |
def pyro_register(self, host=''): |
1133 |
"""register the repository as a pyro object""" |
|
1134 |
from Pyro import core |
|
1135 |
port = self.config['pyro-port'] |
|
1136 |
nshost, nsgroup = self.config['pyro-ns-host'], self.config['pyro-ns-group'] |
|
1137 |
nsgroup = ':' + nsgroup |
|
1138 |
core.initServer(banner=0) |
|
1139 |
daemon = core.Daemon(host=host, port=port) |
|
1140 |
daemon.useNameServer(self.pyro_nameserver(nshost, nsgroup)) |
|
1141 |
# use Delegation approach |
|
1142 |
impl = core.ObjBase() |
|
1143 |
impl.delegateTo(self) |
|
1144 |
nsid = self.config['pyro-id'] or self.config.appid |
|
1145 |
daemon.connect(impl, '%s.%s' % (nsgroup, nsid)) |
|
1146 |
msg = 'repository registered as a pyro object using group %s and id %s' |
|
1147 |
self.info(msg, nsgroup, nsid) |
|
1148 |
self.pyro_registered = True |
|
1149 |
return daemon |
|
1482 | 1150 |
|
0 | 1151 |
def pyro_nameserver(self, host=None, group=None): |
1152 |
"""locate and bind the the name server to the daemon""" |
|
1153 |
from Pyro import naming, errors |
|
1154 |
# locate the name server |
|
1155 |
nameserver = naming.NameServerLocator().getNS(host) |
|
1156 |
if group is not None: |
|
1157 |
# make sure our namespace group exists |
|
1158 |
try: |
|
1159 |
nameserver.createGroup(group) |
|
1160 |
except errors.NamingError: |
|
1161 |
pass |
|
1162 |
return nameserver |
|
1163 |
||
1228
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1164 |
# multi-sources planner helpers ########################################### |
1482 | 1165 |
|
1228
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1166 |
@cached |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1167 |
def rel_type_sources(self, rtype): |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1168 |
return [source for source in self.sources |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1169 |
if source.support_relation(rtype) |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1170 |
or rtype in source.dont_cross_relations] |
1482 | 1171 |
|
1228
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1172 |
@cached |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1173 |
def can_cross_relation(self, rtype): |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1174 |
return [source for source in self.sources |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1175 |
if source.support_relation(rtype) |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1176 |
and rtype in source.cross_relations] |
1482 | 1177 |
|
1228
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1178 |
@cached |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1179 |
def is_multi_sources_relation(self, rtype): |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1180 |
return any(source for source in self.sources |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1181 |
if not source is self.system_source |
91ae10ffb611
* refactor ms planner (renaming, reorganization)
sylvain.thenault@logilab.fr
parents:
1217
diff
changeset
|
1182 |
and source.support_relation(rtype)) |
1482 | 1183 |
|
0 | 1184 |
|
1185 |
def pyro_unregister(config): |
|
1186 |
"""unregister the repository from the pyro name server""" |
|
1187 |
nshost, nsgroup = config['pyro-ns-host'], config['pyro-ns-group'] |
|
1188 |
appid = config['pyro-id'] or config.appid |
|
1189 |
from Pyro import core, naming, errors |
|
1190 |
core.initClient(banner=False) |
|
1191 |
try: |
|
1192 |
nameserver = naming.NameServerLocator().getNS(nshost) |
|
1193 |
except errors.PyroError, ex: |
|
1194 |
# name server not responding |
|
1195 |
config.error('can\'t locate pyro name server: %s', ex) |
|
1196 |
return |
|
1197 |
try: |
|
1198 |
nameserver.unregister(':%s.%s' % (nsgroup, appid)) |
|
1199 |
config.info('%s unregistered from pyro name server', appid) |
|
1200 |
except errors.NamingError: |
|
1201 |
config.warning('%s already unregistered from pyro name server', appid) |
|
1202 |
||
1203 |
||
1204 |
from logging import getLogger |
|
1205 |
from cubicweb import set_log_methods |
|
1206 |
set_log_methods(Repository, getLogger('cubicweb.repository')) |