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