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