root / snf-pithos-backend / pithos / backends / lib / sqlalchemy / node.py @ 6a82f89f
History | View | Annotate | Download (40.2 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from time import time |
35 |
from sqlalchemy import Table, Integer, BigInteger, DECIMAL, Column, String, MetaData, ForeignKey |
36 |
from sqlalchemy.types import Text |
37 |
from sqlalchemy.schema import Index, Sequence |
38 |
from sqlalchemy.sql import func, and_, or_, not_, null, select, bindparam, text, exists |
39 |
from sqlalchemy.ext.compiler import compiles |
40 |
from sqlalchemy.engine.reflection import Inspector |
41 |
from sqlalchemy.exc import NoSuchTableError |
42 |
|
43 |
from dbworker import DBWorker |
44 |
|
45 |
from pithos.backends.filter import parse_filters |
46 |
|
47 |
|
48 |
ROOTNODE = 0
|
49 |
|
50 |
( SERIAL, NODE, HASH, SIZE, TYPE, SOURCE, MTIME, MUSER, UUID, CHECKSUM, CLUSTER ) = range(11) |
51 |
|
52 |
( MATCH_PREFIX, MATCH_EXACT ) = range(2) |
53 |
|
54 |
inf = float('inf') |
55 |
|
56 |
|
57 |
def strnextling(prefix): |
58 |
"""Return the first unicode string
|
59 |
greater than but not starting with given prefix.
|
60 |
strnextling('hello') -> 'hellp'
|
61 |
"""
|
62 |
if not prefix: |
63 |
## all strings start with the null string,
|
64 |
## therefore we have to approximate strnextling('')
|
65 |
## with the last unicode character supported by python
|
66 |
## 0x10ffff for wide (32-bit unicode) python builds
|
67 |
## 0x00ffff for narrow (16-bit unicode) python builds
|
68 |
## We will not autodetect. 0xffff is safe enough.
|
69 |
return unichr(0xffff) |
70 |
s = prefix[:-1]
|
71 |
c = ord(prefix[-1]) |
72 |
if c >= 0xffff: |
73 |
raise RuntimeError |
74 |
s += unichr(c+1) |
75 |
return s
|
76 |
|
77 |
def strprevling(prefix): |
78 |
"""Return an approximation of the last unicode string
|
79 |
less than but not starting with given prefix.
|
80 |
strprevling(u'hello') -> u'helln\\xffff'
|
81 |
"""
|
82 |
if not prefix: |
83 |
## There is no prevling for the null string
|
84 |
return prefix
|
85 |
s = prefix[:-1]
|
86 |
c = ord(prefix[-1]) |
87 |
if c > 0: |
88 |
s += unichr(c-1) + unichr(0xffff) |
89 |
return s
|
90 |
|
91 |
_propnames = { |
92 |
'serial' : 0, |
93 |
'node' : 1, |
94 |
'hash' : 2, |
95 |
'size' : 3, |
96 |
'type' : 4, |
97 |
'source' : 5, |
98 |
'mtime' : 6, |
99 |
'muser' : 7, |
100 |
'uuid' : 8, |
101 |
'checksum' : 9, |
102 |
'cluster' : 10 |
103 |
} |
104 |
|
105 |
def create_tables(engine): |
106 |
metadata = MetaData() |
107 |
|
108 |
#create nodes table
|
109 |
columns=[] |
110 |
columns.append(Column('node', Integer, primary_key=True)) |
111 |
columns.append(Column('parent', Integer,
|
112 |
ForeignKey('nodes.node',
|
113 |
ondelete='CASCADE',
|
114 |
onupdate='CASCADE'),
|
115 |
autoincrement=False))
|
116 |
columns.append(Column('latest_version', Integer))
|
117 |
columns.append(Column('path', String(2048), default='', nullable=False)) |
118 |
nodes = Table('nodes', metadata, *columns, mysql_engine='InnoDB') |
119 |
Index('idx_nodes_path', nodes.c.path, unique=True) |
120 |
Index('idx_nodes_parent', nodes.c.parent)
|
121 |
|
122 |
#create policy table
|
123 |
columns=[] |
124 |
columns.append(Column('node', Integer,
|
125 |
ForeignKey('nodes.node',
|
126 |
ondelete='CASCADE',
|
127 |
onupdate='CASCADE'),
|
128 |
primary_key=True))
|
129 |
columns.append(Column('key', String(128), primary_key=True)) |
130 |
columns.append(Column('value', String(256))) |
131 |
policy = Table('policy', metadata, *columns, mysql_engine='InnoDB') |
132 |
|
133 |
#create statistics table
|
134 |
columns=[] |
135 |
columns.append(Column('node', Integer,
|
136 |
ForeignKey('nodes.node',
|
137 |
ondelete='CASCADE',
|
138 |
onupdate='CASCADE'),
|
139 |
primary_key=True))
|
140 |
columns.append(Column('population', Integer, nullable=False, default=0)) |
141 |
columns.append(Column('size', BigInteger, nullable=False, default=0)) |
142 |
columns.append(Column('mtime', DECIMAL(precision=16, scale=6))) |
143 |
columns.append(Column('cluster', Integer, nullable=False, default=0, |
144 |
primary_key=True, autoincrement=False)) |
145 |
statistics = Table('statistics', metadata, *columns, mysql_engine='InnoDB') |
146 |
|
147 |
#create versions table
|
148 |
columns=[] |
149 |
columns.append(Column('serial', Integer, primary_key=True)) |
150 |
columns.append(Column('node', Integer,
|
151 |
ForeignKey('nodes.node',
|
152 |
ondelete='CASCADE',
|
153 |
onupdate='CASCADE')))
|
154 |
columns.append(Column('hash', String(256))) |
155 |
columns.append(Column('size', BigInteger, nullable=False, default=0)) |
156 |
columns.append(Column('type', String(256), nullable=False, default='')) |
157 |
columns.append(Column('source', Integer))
|
158 |
columns.append(Column('mtime', DECIMAL(precision=16, scale=6))) |
159 |
columns.append(Column('muser', String(256), nullable=False, default='')) |
160 |
columns.append(Column('uuid', String(64), nullable=False, default='')) |
161 |
columns.append(Column('checksum', String(256), nullable=False, default='')) |
162 |
columns.append(Column('cluster', Integer, nullable=False, default=0)) |
163 |
versions = Table('versions', metadata, *columns, mysql_engine='InnoDB') |
164 |
Index('idx_versions_node_mtime', versions.c.node, versions.c.mtime)
|
165 |
Index('idx_versions_node_uuid', versions.c.uuid)
|
166 |
|
167 |
#create attributes table
|
168 |
columns = [] |
169 |
columns.append(Column('serial', Integer,
|
170 |
ForeignKey('versions.serial',
|
171 |
ondelete='CASCADE',
|
172 |
onupdate='CASCADE'),
|
173 |
primary_key=True))
|
174 |
columns.append(Column('domain', String(256), primary_key=True)) |
175 |
columns.append(Column('key', String(128), primary_key=True)) |
176 |
columns.append(Column('value', String(256))) |
177 |
attributes = Table('attributes', metadata, *columns, mysql_engine='InnoDB') |
178 |
|
179 |
metadata.create_all(engine) |
180 |
return metadata.sorted_tables
|
181 |
|
182 |
class Node(DBWorker): |
183 |
"""Nodes store path organization and have multiple versions.
|
184 |
Versions store object history and have multiple attributes.
|
185 |
Attributes store metadata.
|
186 |
"""
|
187 |
|
188 |
# TODO: Provide an interface for included and excluded clusters.
|
189 |
|
190 |
def __init__(self, **params): |
191 |
DBWorker.__init__(self, **params)
|
192 |
try:
|
193 |
metadata = MetaData(self.engine)
|
194 |
self.nodes = Table('nodes', metadata, autoload=True) |
195 |
self.policy = Table('policy', metadata, autoload=True) |
196 |
self.statistics = Table('statistics', metadata, autoload=True) |
197 |
self.versions = Table('versions', metadata, autoload=True) |
198 |
self.attributes = Table('attributes', metadata, autoload=True) |
199 |
except NoSuchTableError:
|
200 |
tables = create_tables(self.engine)
|
201 |
map(lambda t: self.__setattr__(t.name, t), tables) |
202 |
|
203 |
s = self.nodes.select().where(and_(self.nodes.c.node == ROOTNODE, |
204 |
self.nodes.c.parent == ROOTNODE))
|
205 |
rp = self.conn.execute(s)
|
206 |
r = rp.fetchone() |
207 |
rp.close() |
208 |
if not r: |
209 |
s = self.nodes.insert().values(node=ROOTNODE, parent=ROOTNODE, path='') |
210 |
self.conn.execute(s)
|
211 |
|
212 |
def node_create(self, parent, path): |
213 |
"""Create a new node from the given properties.
|
214 |
Return the node identifier of the new node.
|
215 |
"""
|
216 |
#TODO catch IntegrityError?
|
217 |
s = self.nodes.insert().values(parent=parent, path=path)
|
218 |
r = self.conn.execute(s)
|
219 |
inserted_primary_key = r.inserted_primary_key[0]
|
220 |
r.close() |
221 |
return inserted_primary_key
|
222 |
|
223 |
def node_lookup(self, path): |
224 |
"""Lookup the current node of the given path.
|
225 |
Return None if the path is not found.
|
226 |
"""
|
227 |
|
228 |
# Use LIKE for comparison to avoid MySQL problems with trailing spaces.
|
229 |
s = select([self.nodes.c.node], self.nodes.c.path.like(self.escape_like(path), escape='\\')) |
230 |
r = self.conn.execute(s)
|
231 |
row = r.fetchone() |
232 |
r.close() |
233 |
if row:
|
234 |
return row[0] |
235 |
return None |
236 |
|
237 |
def node_lookup_bulk(self, paths): |
238 |
"""Lookup the current nodes for the given paths.
|
239 |
Return () if the path is not found.
|
240 |
"""
|
241 |
|
242 |
# Use LIKE for comparison to avoid MySQL problems with trailing spaces.
|
243 |
s = select([self.nodes.c.node], self.nodes.c.path.in_(paths)) |
244 |
r = self.conn.execute(s)
|
245 |
rows = r.fetchall() |
246 |
r.close() |
247 |
return [row[0] for row in rows] |
248 |
|
249 |
def node_get_properties(self, node): |
250 |
"""Return the node's (parent, path).
|
251 |
Return None if the node is not found.
|
252 |
"""
|
253 |
|
254 |
s = select([self.nodes.c.parent, self.nodes.c.path]) |
255 |
s = s.where(self.nodes.c.node == node)
|
256 |
r = self.conn.execute(s)
|
257 |
l = r.fetchone() |
258 |
r.close() |
259 |
return l
|
260 |
|
261 |
def node_get_versions(self, node, keys=(), propnames=_propnames): |
262 |
"""Return the properties of all versions at node.
|
263 |
If keys is empty, return all properties in the order
|
264 |
(serial, node, hash, size, type, source, mtime, muser, uuid, checksum, cluster).
|
265 |
"""
|
266 |
|
267 |
s = select([self.versions.c.serial,
|
268 |
self.versions.c.node,
|
269 |
self.versions.c.hash,
|
270 |
self.versions.c.size,
|
271 |
self.versions.c.type,
|
272 |
self.versions.c.source,
|
273 |
self.versions.c.mtime,
|
274 |
self.versions.c.muser,
|
275 |
self.versions.c.uuid,
|
276 |
self.versions.c.checksum,
|
277 |
self.versions.c.cluster], self.versions.c.node == node) |
278 |
s = s.order_by(self.versions.c.serial)
|
279 |
r = self.conn.execute(s)
|
280 |
rows = r.fetchall() |
281 |
r.close() |
282 |
if not rows: |
283 |
return rows
|
284 |
|
285 |
if not keys: |
286 |
return rows
|
287 |
|
288 |
return [[p[propnames[k]] for k in keys if k in propnames] for p in rows] |
289 |
|
290 |
def node_count_children(self, node): |
291 |
"""Return node's child count."""
|
292 |
|
293 |
s = select([func.count(self.nodes.c.node)])
|
294 |
s = s.where(and_(self.nodes.c.parent == node,
|
295 |
self.nodes.c.node != ROOTNODE))
|
296 |
r = self.conn.execute(s)
|
297 |
row = r.fetchone() |
298 |
r.close() |
299 |
return row[0] |
300 |
|
301 |
def node_purge_children(self, parent, before=inf, cluster=0): |
302 |
"""Delete all versions with the specified
|
303 |
parent and cluster, and return
|
304 |
the hashes and size of versions deleted.
|
305 |
Clears out nodes with no remaining versions.
|
306 |
"""
|
307 |
#update statistics
|
308 |
c1 = select([self.nodes.c.node],
|
309 |
self.nodes.c.parent == parent)
|
310 |
where_clause = and_(self.versions.c.node.in_(c1),
|
311 |
self.versions.c.cluster == cluster)
|
312 |
s = select([func.count(self.versions.c.serial),
|
313 |
func.sum(self.versions.c.size)])
|
314 |
s = s.where(where_clause) |
315 |
if before != inf:
|
316 |
s = s.where(self.versions.c.mtime <= before)
|
317 |
r = self.conn.execute(s)
|
318 |
row = r.fetchone() |
319 |
r.close() |
320 |
if not row: |
321 |
return (), 0 |
322 |
nr, size = row[0], -row[1] if row[1] else 0 |
323 |
mtime = time() |
324 |
self.statistics_update(parent, -nr, size, mtime, cluster)
|
325 |
self.statistics_update_ancestors(parent, -nr, size, mtime, cluster)
|
326 |
|
327 |
s = select([self.versions.c.hash])
|
328 |
s = s.where(where_clause) |
329 |
r = self.conn.execute(s)
|
330 |
hashes = [row[0] for row in r.fetchall()] |
331 |
r.close() |
332 |
|
333 |
#delete versions
|
334 |
s = self.versions.delete().where(where_clause)
|
335 |
r = self.conn.execute(s)
|
336 |
r.close() |
337 |
|
338 |
#delete nodes
|
339 |
s = select([self.nodes.c.node],
|
340 |
and_(self.nodes.c.parent == parent,
|
341 |
select([func.count(self.versions.c.serial)],
|
342 |
self.versions.c.node == self.nodes.c.node).as_scalar() == 0)) |
343 |
rp = self.conn.execute(s)
|
344 |
nodes = [r[0] for r in rp.fetchall()] |
345 |
rp.close() |
346 |
s = self.nodes.delete().where(self.nodes.c.node.in_(nodes)) |
347 |
self.conn.execute(s).close()
|
348 |
|
349 |
return hashes, size
|
350 |
|
351 |
def node_purge(self, node, before=inf, cluster=0): |
352 |
"""Delete all versions with the specified
|
353 |
node and cluster, and return
|
354 |
the hashes and size of versions deleted.
|
355 |
Clears out the node if it has no remaining versions.
|
356 |
"""
|
357 |
|
358 |
#update statistics
|
359 |
s = select([func.count(self.versions.c.serial),
|
360 |
func.sum(self.versions.c.size)])
|
361 |
where_clause = and_(self.versions.c.node == node,
|
362 |
self.versions.c.cluster == cluster)
|
363 |
s = s.where(where_clause) |
364 |
if before != inf:
|
365 |
s = s.where(self.versions.c.mtime <= before)
|
366 |
r = self.conn.execute(s)
|
367 |
row = r.fetchone() |
368 |
nr, size = row[0], row[1] |
369 |
r.close() |
370 |
if not nr: |
371 |
return (), 0 |
372 |
mtime = time() |
373 |
self.statistics_update_ancestors(node, -nr, -size, mtime, cluster)
|
374 |
|
375 |
s = select([self.versions.c.hash])
|
376 |
s = s.where(where_clause) |
377 |
r = self.conn.execute(s)
|
378 |
hashes = [r[0] for r in r.fetchall()] |
379 |
r.close() |
380 |
|
381 |
#delete versions
|
382 |
s = self.versions.delete().where(where_clause)
|
383 |
r = self.conn.execute(s)
|
384 |
r.close() |
385 |
|
386 |
#delete nodes
|
387 |
s = select([self.nodes.c.node],
|
388 |
and_(self.nodes.c.node == node,
|
389 |
select([func.count(self.versions.c.serial)],
|
390 |
self.versions.c.node == self.nodes.c.node).as_scalar() == 0)) |
391 |
r = self.conn.execute(s)
|
392 |
nodes = r.fetchall() |
393 |
r.close() |
394 |
s = self.nodes.delete().where(self.nodes.c.node.in_(nodes)) |
395 |
self.conn.execute(s).close()
|
396 |
|
397 |
return hashes, size
|
398 |
|
399 |
def node_remove(self, node): |
400 |
"""Remove the node specified.
|
401 |
Return false if the node has children or is not found.
|
402 |
"""
|
403 |
|
404 |
if self.node_count_children(node): |
405 |
return False |
406 |
|
407 |
mtime = time() |
408 |
s = select([func.count(self.versions.c.serial),
|
409 |
func.sum(self.versions.c.size),
|
410 |
self.versions.c.cluster])
|
411 |
s = s.where(self.versions.c.node == node)
|
412 |
s = s.group_by(self.versions.c.cluster)
|
413 |
r = self.conn.execute(s)
|
414 |
for population, size, cluster in r.fetchall(): |
415 |
self.statistics_update_ancestors(node, -population, -size, mtime, cluster)
|
416 |
r.close() |
417 |
|
418 |
s = self.nodes.delete().where(self.nodes.c.node == node) |
419 |
self.conn.execute(s).close()
|
420 |
return True |
421 |
|
422 |
def policy_get(self, node): |
423 |
s = select([self.policy.c.key, self.policy.c.value], |
424 |
self.policy.c.node==node)
|
425 |
r = self.conn.execute(s)
|
426 |
d = dict(r.fetchall())
|
427 |
r.close() |
428 |
return d
|
429 |
|
430 |
def policy_set(self, node, policy): |
431 |
#insert or replace
|
432 |
for k, v in policy.iteritems(): |
433 |
s = self.policy.update().where(and_(self.policy.c.node == node, |
434 |
self.policy.c.key == k))
|
435 |
s = s.values(value = v) |
436 |
rp = self.conn.execute(s)
|
437 |
rp.close() |
438 |
if rp.rowcount == 0: |
439 |
s = self.policy.insert()
|
440 |
values = {'node':node, 'key':k, 'value':v} |
441 |
r = self.conn.execute(s, values)
|
442 |
r.close() |
443 |
|
444 |
def statistics_get(self, node, cluster=0): |
445 |
"""Return population, total size and last mtime
|
446 |
for all versions under node that belong to the cluster.
|
447 |
"""
|
448 |
|
449 |
s = select([self.statistics.c.population,
|
450 |
self.statistics.c.size,
|
451 |
self.statistics.c.mtime])
|
452 |
s = s.where(and_(self.statistics.c.node == node,
|
453 |
self.statistics.c.cluster == cluster))
|
454 |
r = self.conn.execute(s)
|
455 |
row = r.fetchone() |
456 |
r.close() |
457 |
return row
|
458 |
|
459 |
def statistics_update(self, node, population, size, mtime, cluster=0): |
460 |
"""Update the statistics of the given node.
|
461 |
Statistics keep track the population, total
|
462 |
size of objects and mtime in the node's namespace.
|
463 |
May be zero or positive or negative numbers.
|
464 |
"""
|
465 |
s = select([self.statistics.c.population, self.statistics.c.size], |
466 |
and_(self.statistics.c.node == node,
|
467 |
self.statistics.c.cluster == cluster))
|
468 |
rp = self.conn.execute(s)
|
469 |
r = rp.fetchone() |
470 |
rp.close() |
471 |
if not r: |
472 |
prepopulation, presize = (0, 0) |
473 |
else:
|
474 |
prepopulation, presize = r |
475 |
population += prepopulation |
476 |
size += presize |
477 |
|
478 |
#insert or replace
|
479 |
#TODO better upsert
|
480 |
u = self.statistics.update().where(and_(self.statistics.c.node==node, |
481 |
self.statistics.c.cluster==cluster))
|
482 |
u = u.values(population=population, size=size, mtime=mtime) |
483 |
rp = self.conn.execute(u)
|
484 |
rp.close() |
485 |
if rp.rowcount == 0: |
486 |
ins = self.statistics.insert()
|
487 |
ins = ins.values(node=node, population=population, size=size, |
488 |
mtime=mtime, cluster=cluster) |
489 |
self.conn.execute(ins).close()
|
490 |
|
491 |
def statistics_update_ancestors(self, node, population, size, mtime, cluster=0): |
492 |
"""Update the statistics of the given node's parent.
|
493 |
Then recursively update all parents up to the root.
|
494 |
Population is not recursive.
|
495 |
"""
|
496 |
|
497 |
while True: |
498 |
if node == ROOTNODE:
|
499 |
break
|
500 |
props = self.node_get_properties(node)
|
501 |
if props is None: |
502 |
break
|
503 |
parent, path = props |
504 |
self.statistics_update(parent, population, size, mtime, cluster)
|
505 |
node = parent |
506 |
population = 0 # Population isn't recursive |
507 |
|
508 |
def statistics_latest(self, node, before=inf, except_cluster=0): |
509 |
"""Return population, total size and last mtime
|
510 |
for all latest versions under node that
|
511 |
do not belong to the cluster.
|
512 |
"""
|
513 |
|
514 |
# The node.
|
515 |
props = self.node_get_properties(node)
|
516 |
if props is None: |
517 |
return None |
518 |
parent, path = props |
519 |
|
520 |
# The latest version.
|
521 |
s = select([self.versions.c.serial,
|
522 |
self.versions.c.node,
|
523 |
self.versions.c.hash,
|
524 |
self.versions.c.size,
|
525 |
self.versions.c.type,
|
526 |
self.versions.c.source,
|
527 |
self.versions.c.mtime,
|
528 |
self.versions.c.muser,
|
529 |
self.versions.c.uuid,
|
530 |
self.versions.c.checksum,
|
531 |
self.versions.c.cluster])
|
532 |
if before != inf:
|
533 |
filtered = select([func.max(self.versions.c.serial)],
|
534 |
self.versions.c.node == node)
|
535 |
filtered = filtered.where(self.versions.c.mtime < before)
|
536 |
else:
|
537 |
filtered = select([self.nodes.c.latest_version],
|
538 |
self.versions.c.node == node)
|
539 |
s = s.where(and_(self.versions.c.cluster != except_cluster,
|
540 |
self.versions.c.serial == filtered))
|
541 |
r = self.conn.execute(s)
|
542 |
props = r.fetchone() |
543 |
r.close() |
544 |
if not props: |
545 |
return None |
546 |
mtime = props[MTIME] |
547 |
|
548 |
# First level, just under node (get population).
|
549 |
v = self.versions.alias('v') |
550 |
s = select([func.count(v.c.serial), |
551 |
func.sum(v.c.size), |
552 |
func.max(v.c.mtime)]) |
553 |
if before != inf:
|
554 |
c1 = select([func.max(self.versions.c.serial)])
|
555 |
c1 = c1.where(self.versions.c.mtime < before)
|
556 |
c1.where(self.versions.c.node == v.c.node)
|
557 |
else:
|
558 |
c1 = select([self.nodes.c.latest_version])
|
559 |
c1.where(self.nodes.c.node == v.c.node)
|
560 |
c2 = select([self.nodes.c.node], self.nodes.c.parent == node) |
561 |
s = s.where(and_(v.c.serial == c1, |
562 |
v.c.cluster != except_cluster, |
563 |
v.c.node.in_(c2))) |
564 |
rp = self.conn.execute(s)
|
565 |
r = rp.fetchone() |
566 |
rp.close() |
567 |
if not r: |
568 |
return None |
569 |
count = r[0]
|
570 |
mtime = max(mtime, r[2]) |
571 |
if count == 0: |
572 |
return (0, 0, mtime) |
573 |
|
574 |
# All children (get size and mtime).
|
575 |
# This is why the full path is stored.
|
576 |
s = select([func.count(v.c.serial), |
577 |
func.sum(v.c.size), |
578 |
func.max(v.c.mtime)]) |
579 |
if before != inf:
|
580 |
c1 = select([func.max(self.versions.c.serial)],
|
581 |
self.versions.c.node == v.c.node)
|
582 |
c1 = c1.where(self.versions.c.mtime < before)
|
583 |
else:
|
584 |
c1 = select([self.nodes.c.serial],
|
585 |
self.nodes.c.node == v.c.node)
|
586 |
c2 = select([self.nodes.c.node], self.nodes.c.path.like(self.escape_like(path) + '%', escape='\\')) |
587 |
s = s.where(and_(v.c.serial == c1, |
588 |
v.c.cluster != except_cluster, |
589 |
v.c.node.in_(c2))) |
590 |
rp = self.conn.execute(s)
|
591 |
r = rp.fetchone() |
592 |
rp.close() |
593 |
if not r: |
594 |
return None |
595 |
size = r[1] - props[SIZE]
|
596 |
mtime = max(mtime, r[2]) |
597 |
return (count, size, mtime)
|
598 |
|
599 |
def nodes_set_latest_version(self, node, serial): |
600 |
s = self.nodes.update().where(self.nodes.c.node == node) |
601 |
s = s.values(latest_version = serial) |
602 |
self.conn.execute(s).close()
|
603 |
|
604 |
def version_create(self, node, hash, size, type, source, muser, uuid, checksum, cluster=0): |
605 |
"""Create a new version from the given properties.
|
606 |
Return the (serial, mtime) of the new version.
|
607 |
"""
|
608 |
|
609 |
mtime = time() |
610 |
s = self.versions.insert().values(node=node, hash=hash, size=size, type=type, source=source, |
611 |
mtime=mtime, muser=muser, uuid=uuid, checksum=checksum, cluster=cluster) |
612 |
serial = self.conn.execute(s).inserted_primary_key[0] |
613 |
self.statistics_update_ancestors(node, 1, size, mtime, cluster) |
614 |
|
615 |
self.nodes_set_latest_version(node, serial)
|
616 |
|
617 |
return serial, mtime
|
618 |
|
619 |
def version_lookup(self, node, before=inf, cluster=0, all_props=True): |
620 |
"""Lookup the current version of the given node.
|
621 |
Return a list with its properties:
|
622 |
(serial, node, hash, size, type, source, mtime, muser, uuid, checksum, cluster)
|
623 |
or None if the current version is not found in the given cluster.
|
624 |
"""
|
625 |
|
626 |
v = self.versions.alias('v') |
627 |
if not all_props: |
628 |
s = select([v.c.serial]) |
629 |
else:
|
630 |
s = select([v.c.serial, v.c.node, v.c.hash, |
631 |
v.c.size, v.c.type, v.c.source, |
632 |
v.c.mtime, v.c.muser, v.c.uuid, |
633 |
v.c.checksum, v.c.cluster]) |
634 |
if before != inf:
|
635 |
c = select([func.max(self.versions.c.serial)],
|
636 |
self.versions.c.node == node)
|
637 |
c = c.where(self.versions.c.mtime < before)
|
638 |
else:
|
639 |
c = select([self.nodes.c.latest_version],
|
640 |
self.nodes.c.node == node)
|
641 |
s = s.where(and_(v.c.serial == c, |
642 |
v.c.cluster == cluster)) |
643 |
r = self.conn.execute(s)
|
644 |
props = r.fetchone() |
645 |
r.close() |
646 |
if props:
|
647 |
return props
|
648 |
return None |
649 |
|
650 |
def version_lookup_bulk(self, nodes, before=inf, cluster=0, all_props=True): |
651 |
"""Lookup the current versions of the given nodes.
|
652 |
Return a list with their properties:
|
653 |
(serial, node, hash, size, type, source, mtime, muser, uuid, checksum, cluster).
|
654 |
"""
|
655 |
if not nodes: |
656 |
return ()
|
657 |
v = self.versions.alias('v') |
658 |
if not all_props: |
659 |
s = select([v.c.serial]) |
660 |
else:
|
661 |
s = select([v.c.serial, v.c.node, v.c.hash, |
662 |
v.c.size, v.c.type, v.c.source, |
663 |
v.c.mtime, v.c.muser, v.c.uuid, |
664 |
v.c.checksum, v.c.cluster]) |
665 |
if before != inf:
|
666 |
c = select([func.max(self.versions.c.serial)],
|
667 |
self.versions.c.node.in_(nodes))
|
668 |
c = c.where(self.versions.c.mtime < before)
|
669 |
c = c.group_by(self.versions.c.node)
|
670 |
else:
|
671 |
c = select([self.nodes.c.latest_version],
|
672 |
self.nodes.c.node.in_(nodes))
|
673 |
s = s.where(and_(v.c.serial.in_(c), |
674 |
v.c.cluster == cluster)) |
675 |
s = s.order_by(v.c.node) |
676 |
r = self.conn.execute(s)
|
677 |
rproxy = r.fetchall() |
678 |
r.close() |
679 |
return (tuple(row.values()) for row in rproxy) |
680 |
|
681 |
def version_get_properties(self, serial, keys=(), propnames=_propnames): |
682 |
"""Return a sequence of values for the properties of
|
683 |
the version specified by serial and the keys, in the order given.
|
684 |
If keys is empty, return all properties in the order
|
685 |
(serial, node, hash, size, type, source, mtime, muser, uuid, checksum, cluster).
|
686 |
"""
|
687 |
|
688 |
v = self.versions.alias()
|
689 |
s = select([v.c.serial, v.c.node, v.c.hash, |
690 |
v.c.size, v.c.type, v.c.source, |
691 |
v.c.mtime, v.c.muser, v.c.uuid, |
692 |
v.c.checksum, v.c.cluster], v.c.serial == serial) |
693 |
rp = self.conn.execute(s)
|
694 |
r = rp.fetchone() |
695 |
rp.close() |
696 |
if r is None: |
697 |
return r
|
698 |
|
699 |
if not keys: |
700 |
return r
|
701 |
return [r[propnames[k]] for k in keys if k in propnames] |
702 |
|
703 |
def version_put_property(self, serial, key, value): |
704 |
"""Set value for the property of version specified by key."""
|
705 |
|
706 |
if key not in _propnames: |
707 |
return
|
708 |
s = self.versions.update()
|
709 |
s = s.where(self.versions.c.serial == serial)
|
710 |
s = s.values(**{key: value}) |
711 |
self.conn.execute(s).close()
|
712 |
|
713 |
def version_recluster(self, serial, cluster): |
714 |
"""Move the version into another cluster."""
|
715 |
|
716 |
props = self.version_get_properties(serial)
|
717 |
if not props: |
718 |
return
|
719 |
node = props[NODE] |
720 |
size = props[SIZE] |
721 |
oldcluster = props[CLUSTER] |
722 |
if cluster == oldcluster:
|
723 |
return
|
724 |
|
725 |
mtime = time() |
726 |
self.statistics_update_ancestors(node, -1, -size, mtime, oldcluster) |
727 |
self.statistics_update_ancestors(node, 1, size, mtime, cluster) |
728 |
|
729 |
s = self.versions.update()
|
730 |
s = s.where(self.versions.c.serial == serial)
|
731 |
s = s.values(cluster = cluster) |
732 |
self.conn.execute(s).close()
|
733 |
|
734 |
def version_remove(self, serial): |
735 |
"""Remove the serial specified."""
|
736 |
|
737 |
props = self.version_get_properties(serial)
|
738 |
if not props: |
739 |
return
|
740 |
node = props[NODE] |
741 |
hash = props[HASH] |
742 |
size = props[SIZE] |
743 |
cluster = props[CLUSTER] |
744 |
|
745 |
mtime = time() |
746 |
self.statistics_update_ancestors(node, -1, -size, mtime, cluster) |
747 |
|
748 |
s = self.versions.delete().where(self.versions.c.serial == serial) |
749 |
self.conn.execute(s).close()
|
750 |
|
751 |
props = self.version_lookup(node, cluster=cluster, all_props=False) |
752 |
if props:
|
753 |
self.nodes_set_latest_version(v.node, serial)
|
754 |
|
755 |
return hash, size |
756 |
|
757 |
def attribute_get(self, serial, domain, keys=()): |
758 |
"""Return a list of (key, value) pairs of the version specified by serial.
|
759 |
If keys is empty, return all attributes.
|
760 |
Othwerise, return only those specified.
|
761 |
"""
|
762 |
|
763 |
if keys:
|
764 |
attrs = self.attributes.alias()
|
765 |
s = select([attrs.c.key, attrs.c.value]) |
766 |
s = s.where(and_(attrs.c.key.in_(keys), |
767 |
attrs.c.serial == serial, |
768 |
attrs.c.domain == domain)) |
769 |
else:
|
770 |
attrs = self.attributes.alias()
|
771 |
s = select([attrs.c.key, attrs.c.value]) |
772 |
s = s.where(and_(attrs.c.serial == serial, |
773 |
attrs.c.domain == domain)) |
774 |
r = self.conn.execute(s)
|
775 |
l = r.fetchall() |
776 |
r.close() |
777 |
return l
|
778 |
|
779 |
def attribute_set(self, serial, domain, items): |
780 |
"""Set the attributes of the version specified by serial.
|
781 |
Receive attributes as an iterable of (key, value) pairs.
|
782 |
"""
|
783 |
#insert or replace
|
784 |
#TODO better upsert
|
785 |
for k, v in items: |
786 |
s = self.attributes.update()
|
787 |
s = s.where(and_(self.attributes.c.serial == serial,
|
788 |
self.attributes.c.domain == domain,
|
789 |
self.attributes.c.key == k))
|
790 |
s = s.values(value = v) |
791 |
rp = self.conn.execute(s)
|
792 |
rp.close() |
793 |
if rp.rowcount == 0: |
794 |
s = self.attributes.insert()
|
795 |
s = s.values(serial=serial, domain=domain, key=k, value=v) |
796 |
self.conn.execute(s).close()
|
797 |
|
798 |
def attribute_del(self, serial, domain, keys=()): |
799 |
"""Delete attributes of the version specified by serial.
|
800 |
If keys is empty, delete all attributes.
|
801 |
Otherwise delete those specified.
|
802 |
"""
|
803 |
|
804 |
if keys:
|
805 |
#TODO more efficient way to do this?
|
806 |
for key in keys: |
807 |
s = self.attributes.delete()
|
808 |
s = s.where(and_(self.attributes.c.serial == serial,
|
809 |
self.attributes.c.domain == domain,
|
810 |
self.attributes.c.key == key))
|
811 |
self.conn.execute(s).close()
|
812 |
else:
|
813 |
s = self.attributes.delete()
|
814 |
s = s.where(and_(self.attributes.c.serial == serial,
|
815 |
self.attributes.c.domain == domain))
|
816 |
self.conn.execute(s).close()
|
817 |
|
818 |
def attribute_copy(self, source, dest): |
819 |
s = select([dest, self.attributes.c.domain, self.attributes.c.key, self.attributes.c.value], |
820 |
self.attributes.c.serial == source)
|
821 |
rp = self.conn.execute(s)
|
822 |
attributes = rp.fetchall() |
823 |
rp.close() |
824 |
for dest, domain, k, v in attributes: |
825 |
#insert or replace
|
826 |
s = self.attributes.update().where(and_(
|
827 |
self.attributes.c.serial == dest,
|
828 |
self.attributes.c.domain == domain,
|
829 |
self.attributes.c.key == k))
|
830 |
rp = self.conn.execute(s, value=v)
|
831 |
rp.close() |
832 |
if rp.rowcount == 0: |
833 |
s = self.attributes.insert()
|
834 |
values = {'serial':dest, 'domain':domain, 'key':k, 'value':v} |
835 |
self.conn.execute(s, values).close()
|
836 |
|
837 |
def latest_attribute_keys(self, parent, domain, before=inf, except_cluster=0, pathq=[]): |
838 |
"""Return a list with all keys pairs defined
|
839 |
for all latest versions under parent that
|
840 |
do not belong to the cluster.
|
841 |
"""
|
842 |
|
843 |
# TODO: Use another table to store before=inf results.
|
844 |
a = self.attributes.alias('a') |
845 |
v = self.versions.alias('v') |
846 |
n = self.nodes.alias('n') |
847 |
s = select([a.c.key]).distinct() |
848 |
if before != inf:
|
849 |
filtered = select([func.max(self.versions.c.serial)])
|
850 |
filtered = filtered.where(self.versions.c.mtime < before)
|
851 |
filtered = filtered.where(self.versions.c.node == v.c.node)
|
852 |
else:
|
853 |
filtered = select([self.nodes.c.latest_version])
|
854 |
filtered = filtered.where(self.nodes.c.node == v.c.node)
|
855 |
s = s.where(v.c.serial == filtered) |
856 |
s = s.where(v.c.cluster != except_cluster) |
857 |
s = s.where(v.c.node.in_(select([self.nodes.c.node],
|
858 |
self.nodes.c.parent == parent)))
|
859 |
s = s.where(a.c.serial == v.c.serial) |
860 |
s = s.where(a.c.domain == domain) |
861 |
s = s.where(n.c.node == v.c.node) |
862 |
conj = [] |
863 |
for path, match in pathq: |
864 |
if match == MATCH_PREFIX:
|
865 |
conj.append(n.c.path.like(self.escape_like(path) + '%', escape='\\')) |
866 |
elif match == MATCH_EXACT:
|
867 |
conj.append(n.c.path == path) |
868 |
if conj:
|
869 |
s = s.where(or_(*conj)) |
870 |
rp = self.conn.execute(s)
|
871 |
rows = rp.fetchall() |
872 |
rp.close() |
873 |
return [r[0] for r in rows] |
874 |
|
875 |
def latest_version_list(self, parent, prefix='', delimiter=None, |
876 |
start='', limit=10000, before=inf, |
877 |
except_cluster=0, pathq=[], domain=None, |
878 |
filterq=[], sizeq=None, all_props=False): |
879 |
"""Return a (list of (path, serial) tuples, list of common prefixes)
|
880 |
for the current versions of the paths with the given parent,
|
881 |
matching the following criteria.
|
882 |
|
883 |
The property tuple for a version is returned if all
|
884 |
of these conditions are true:
|
885 |
|
886 |
a. parent matches
|
887 |
|
888 |
b. path > start
|
889 |
|
890 |
c. path starts with prefix (and paths in pathq)
|
891 |
|
892 |
d. version is the max up to before
|
893 |
|
894 |
e. version is not in cluster
|
895 |
|
896 |
f. the path does not have the delimiter occuring
|
897 |
after the prefix, or ends with the delimiter
|
898 |
|
899 |
g. serial matches the attribute filter query.
|
900 |
|
901 |
A filter query is a comma-separated list of
|
902 |
terms in one of these three forms:
|
903 |
|
904 |
key
|
905 |
an attribute with this key must exist
|
906 |
|
907 |
!key
|
908 |
an attribute with this key must not exist
|
909 |
|
910 |
key ?op value
|
911 |
the attribute with this key satisfies the value
|
912 |
where ?op is one of ==, != <=, >=, <, >.
|
913 |
|
914 |
h. the size is in the range set by sizeq
|
915 |
|
916 |
The list of common prefixes includes the prefixes
|
917 |
matching up to the first delimiter after prefix,
|
918 |
and are reported only once, as "virtual directories".
|
919 |
The delimiter is included in the prefixes.
|
920 |
|
921 |
If arguments are None, then the corresponding matching rule
|
922 |
will always match.
|
923 |
|
924 |
Limit applies to the first list of tuples returned.
|
925 |
|
926 |
If all_props is True, return all properties after path, not just serial.
|
927 |
"""
|
928 |
|
929 |
if not start or start < prefix: |
930 |
start = strprevling(prefix) |
931 |
nextling = strnextling(prefix) |
932 |
|
933 |
v = self.versions.alias('v') |
934 |
n = self.nodes.alias('n') |
935 |
if not all_props: |
936 |
s = select([n.c.path, v.c.serial]).distinct() |
937 |
else:
|
938 |
s = select([n.c.path, |
939 |
v.c.serial, v.c.node, v.c.hash, |
940 |
v.c.size, v.c.type, v.c.source, |
941 |
v.c.mtime, v.c.muser, v.c.uuid, |
942 |
v.c.checksum, v.c.cluster]).distinct() |
943 |
if before != inf:
|
944 |
filtered = select([func.max(self.versions.c.serial)])
|
945 |
filtered = filtered.where(self.versions.c.mtime < before)
|
946 |
else:
|
947 |
filtered = select([self.nodes.c.latest_version])
|
948 |
s = s.where(v.c.serial == filtered.where(self.nodes.c.node == v.c.node))
|
949 |
s = s.where(v.c.cluster != except_cluster) |
950 |
s = s.where(v.c.node.in_(select([self.nodes.c.node],
|
951 |
self.nodes.c.parent == parent)))
|
952 |
|
953 |
s = s.where(n.c.node == v.c.node) |
954 |
s = s.where(and_(n.c.path > bindparam('start'), n.c.path < nextling))
|
955 |
conj = [] |
956 |
for path, match in pathq: |
957 |
if match == MATCH_PREFIX:
|
958 |
conj.append(n.c.path.like(self.escape_like(path) + '%', escape='\\')) |
959 |
elif match == MATCH_EXACT:
|
960 |
conj.append(n.c.path == path) |
961 |
if conj:
|
962 |
s = s.where(or_(*conj)) |
963 |
|
964 |
if sizeq and len(sizeq) == 2: |
965 |
if sizeq[0]: |
966 |
s = s.where(v.c.size >= sizeq[0])
|
967 |
if sizeq[1]: |
968 |
s = s.where(v.c.size < sizeq[1])
|
969 |
|
970 |
if domain and filterq: |
971 |
a = self.attributes.alias('a') |
972 |
included, excluded, opers = parse_filters(filterq) |
973 |
if included:
|
974 |
subs = select([1])
|
975 |
subs = subs.where(a.c.serial == v.c.serial).correlate(v) |
976 |
subs = subs.where(a.c.domain == domain) |
977 |
subs = subs.where(or_(*[a.c.key.op('=')(x) for x in included])) |
978 |
s = s.where(exists(subs)) |
979 |
if excluded:
|
980 |
subs = select([1])
|
981 |
subs = subs.where(a.c.serial == v.c.serial).correlate(v) |
982 |
subs = subs.where(a.c.domain == domain) |
983 |
subs = subs.where(or_(*[a.c.key.op('=')(x) for x in excluded])) |
984 |
s = s.where(not_(exists(subs))) |
985 |
if opers:
|
986 |
for k, o, val in opers: |
987 |
subs = select([1])
|
988 |
subs = subs.where(a.c.serial == v.c.serial).correlate(v) |
989 |
subs = subs.where(a.c.domain == domain) |
990 |
subs = subs.where(and_(a.c.key.op('=')(k), a.c.value.op(o)(val)))
|
991 |
s = s.where(exists(subs)) |
992 |
|
993 |
s = s.order_by(n.c.path) |
994 |
|
995 |
if not delimiter: |
996 |
s = s.limit(limit) |
997 |
rp = self.conn.execute(s, start=start)
|
998 |
r = rp.fetchall() |
999 |
rp.close() |
1000 |
return r, ()
|
1001 |
|
1002 |
pfz = len(prefix)
|
1003 |
dz = len(delimiter)
|
1004 |
count = 0
|
1005 |
prefixes = [] |
1006 |
pappend = prefixes.append |
1007 |
matches = [] |
1008 |
mappend = matches.append |
1009 |
|
1010 |
rp = self.conn.execute(s, start=start)
|
1011 |
while True: |
1012 |
props = rp.fetchone() |
1013 |
if props is None: |
1014 |
break
|
1015 |
path = props[0]
|
1016 |
serial = props[1]
|
1017 |
idx = path.find(delimiter, pfz) |
1018 |
|
1019 |
if idx < 0: |
1020 |
mappend(props) |
1021 |
count += 1
|
1022 |
if count >= limit:
|
1023 |
break
|
1024 |
continue
|
1025 |
|
1026 |
if idx + dz == len(path): |
1027 |
mappend(props) |
1028 |
count += 1
|
1029 |
continue # Get one more, in case there is a path. |
1030 |
pf = path[:idx + dz] |
1031 |
pappend(pf) |
1032 |
if count >= limit:
|
1033 |
break
|
1034 |
|
1035 |
rp = self.conn.execute(s, start=strnextling(pf)) # New start. |
1036 |
rp.close() |
1037 |
|
1038 |
return matches, prefixes
|
1039 |
|
1040 |
def latest_uuid(self, uuid): |
1041 |
"""Return a (path, serial) tuple, for the latest version of the given uuid."""
|
1042 |
|
1043 |
v = self.versions.alias('v') |
1044 |
n = self.nodes.alias('n') |
1045 |
s = select([n.c.path, v.c.serial]) |
1046 |
filtered = select([func.max(self.versions.c.serial)])
|
1047 |
s = s.where(v.c.serial == filtered.where(self.versions.c.uuid == uuid))
|
1048 |
s = s.where(n.c.node == v.c.node) |
1049 |
|
1050 |
r = self.conn.execute(s)
|
1051 |
l = r.fetchone() |
1052 |
r.close() |
1053 |
return l
|