1
# Copyright (C) 2007 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Indexing facilities."""
26
from cStringIO import StringIO
29
from bzrlib import errors
31
_OPTION_KEY_ELEMENTS = "key_elements="
32
_OPTION_NODE_REFS = "node_ref_lists="
33
_SIGNATURE = "Bazaar Graph Index 1\n"
36
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
37
_newline_null_re = re.compile('[\n\0]')
40
class GraphIndexBuilder(object):
41
"""A builder that can build a GraphIndex.
43
The resulting graph has the structure:
45
_SIGNATURE OPTIONS NODES NEWLINE
46
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
47
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
49
NODE := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
50
KEY := Not-whitespace-utf8
52
REFERENCES := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
53
REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
54
REFERENCE := DIGITS ; digits is the byte offset in the index of the
56
VALUE := no-newline-no-null-bytes
59
def __init__(self, reference_lists=0, key_elements=1):
60
"""Create a GraphIndex builder.
62
:param reference_lists: The number of node references lists for each
64
:param key_elements: The number of bytestrings in each key.
66
self.reference_lists = reference_lists
68
self._nodes_by_key = {}
69
self._key_length = key_elements
71
def _check_key(self, key):
72
"""Raise BadIndexKey if key is not a valid key for this index."""
73
if type(key) != tuple:
74
raise errors.BadIndexKey(key)
75
if self._key_length != len(key):
76
raise errors.BadIndexKey(key)
78
if not element or _whitespace_re.search(element) is not None:
79
raise errors.BadIndexKey(element)
81
def add_node(self, key, value, references=()):
82
"""Add a node to the index.
84
:param key: The key. keys are non-empty tuples containing
85
as many whitespace-free utf8 bytestrings as the key length
86
defined for this index.
87
:param references: An iterable of iterables of keys. Each is a
88
reference to another key.
89
:param value: The value to associate with the key. It may be any
90
bytes as long as it does not contain \0 or \n.
93
if _newline_null_re.search(value) is not None:
94
raise errors.BadIndexValue(value)
95
if len(references) != self.reference_lists:
96
raise errors.BadIndexValue(references)
98
for reference_list in references:
99
for reference in reference_list:
100
self._check_key(reference)
101
if reference not in self._nodes:
102
self._nodes[reference] = ('a', (), '')
103
node_refs.append(tuple(reference_list))
104
if key in self._nodes and self._nodes[key][0] == '':
105
raise errors.BadIndexDuplicateKey(key, self)
106
self._nodes[key] = ('', tuple(node_refs), value)
107
if self._key_length > 1:
108
key_dict = self._nodes_by_key
109
if self.reference_lists:
110
key_value = key, value, tuple(node_refs)
112
key_value = key, value
113
# possibly should do this on-demand, but it seems likely it is
115
# For a key of (foo, bar, baz) create
116
# _nodes_by_key[foo][bar][baz] = key_value
117
for subkey in key[:-1]:
118
key_dict = key_dict.setdefault(subkey, {})
119
key_dict[key[-1]] = key_value
123
lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
124
lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
125
prefix_length = sum(len(x) for x in lines)
126
# references are byte offsets. To avoid having to do nasty
127
# polynomial work to resolve offsets (references to later in the
128
# file cannot be determined until all the inbetween references have
129
# been calculated too) we pad the offsets with 0's to make them be
130
# of consistent length. Using binary offsets would break the trivial
132
# to calculate the width of zero's needed we do three passes:
133
# one to gather all the non-reference data and the number of references.
134
# one to pad all the data with reference-length and determine entry
138
# forward sorted by key. In future we may consider topological sorting,
139
# at the cost of table scans for direct lookup, or a second index for
141
nodes = sorted(self._nodes.items())
142
# if we do not prepass, we don't know how long it will be up front.
143
expected_bytes = None
144
# we only need to pre-pass if we have reference lists at all.
145
if self.reference_lists:
147
non_ref_bytes = prefix_length
149
# TODO use simple multiplication for the constants in this loop.
150
for key, (absent, references, value) in nodes:
151
# record the offset known *so far* for this key:
152
# the non reference bytes to date, and the total references to
153
# date - saves reaccumulating on the second pass
154
key_offset_info.append((key, non_ref_bytes, total_references))
155
# key is literal, value is literal, there are 3 null's, 1 NL
156
# key is variable length tuple, \x00 between elements
157
non_ref_bytes += sum(len(element) for element in key)
158
if self._key_length > 1:
159
non_ref_bytes += self._key_length - 1
160
# value is literal bytes, there are 3 null's, 1 NL.
161
non_ref_bytes += len(value) + 3 + 1
162
# one byte for absent if set.
165
elif self.reference_lists:
166
# (ref_lists -1) tabs
167
non_ref_bytes += self.reference_lists - 1
168
# (ref-1 cr's per ref_list)
169
for ref_list in references:
170
# how many references across the whole file?
171
total_references += len(ref_list)
172
# accrue reference separators
174
non_ref_bytes += len(ref_list) - 1
175
# how many digits are needed to represent the total byte count?
177
possible_total_bytes = non_ref_bytes + total_references*digits
178
while 10 ** digits < possible_total_bytes:
180
possible_total_bytes = non_ref_bytes + total_references*digits
181
expected_bytes = possible_total_bytes + 1 # terminating newline
182
# resolve key addresses.
184
for key, non_ref_bytes, total_references in key_offset_info:
185
key_addresses[key] = non_ref_bytes + total_references*digits
187
format_string = '%%0%sd' % digits
188
for key, (absent, references, value) in nodes:
189
flattened_references = []
190
for ref_list in references:
192
for reference in ref_list:
193
ref_addresses.append(format_string % key_addresses[reference])
194
flattened_references.append('\r'.join(ref_addresses))
195
string_key = '\x00'.join(key)
196
lines.append("%s\x00%s\x00%s\x00%s\n" % (string_key, absent,
197
'\t'.join(flattened_references), value))
199
result = StringIO(''.join(lines))
200
if expected_bytes and len(result.getvalue()) != expected_bytes:
201
raise errors.BzrError('Failed index creation. Internal error:'
202
' mismatched output length and expected length: %d %d' %
203
(len(result.getvalue()), expected_bytes))
204
return StringIO(''.join(lines))
207
class GraphIndex(object):
208
"""An index for data with embedded graphs.
210
The index maps keys to a list of key reference lists, and a value.
211
Each node has the same number of key reference lists. Each key reference
212
list can be empty or an arbitrary length. The value is an opaque NULL
213
terminated string without any newlines. The storage of the index is
214
hidden in the interface: keys and key references are always tuples of
215
bytestrings, never the internal representation (e.g. dictionary offsets).
217
It is presumed that the index will not be mutated - it is static data.
219
Successive iter_all_entries calls will read the entire index each time.
220
Additionally, iter_entries calls will read the index linearly until the
221
desired keys are found. XXX: This must be fixed before the index is
222
suitable for production use. :XXX
225
def __init__(self, transport, name):
226
"""Open an index called name on transport.
228
:param transport: A bzrlib.transport.Transport.
229
:param name: A path to provide to transport API calls.
231
self._transport = transport
234
self._keys_by_offset = None
235
self._nodes_by_key = None
237
def _buffer_all(self):
238
"""Buffer all the index data.
240
Mutates self._nodes and self.keys_by_offset.
242
stream = self._transport.get(self._name)
243
self._read_prefix(stream)
244
expected_elements = 3 + self._key_length
246
# raw data keyed by offset
247
self._keys_by_offset = {}
248
# ready-to-return key:value or key:value, node_ref_lists
250
self._nodes_by_key = {}
253
for line in stream.readlines():
257
elements = line.split('\0')
258
if len(elements) != expected_elements:
259
raise errors.BadIndexData(self)
261
key = tuple(elements[:self._key_length])
262
absent, references, value = elements[-3:]
263
value = value[:-1] # remove the newline
265
for ref_string in references.split('\t'):
266
ref_lists.append(tuple([
267
int(ref) for ref in ref_string.split('\r') if ref
269
ref_lists = tuple(ref_lists)
270
self._keys_by_offset[pos] = (key, absent, ref_lists, value)
272
for key, absent, references, value in self._keys_by_offset.itervalues():
275
# resolve references:
276
if self.node_ref_lists:
278
for ref_list in references:
279
node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
280
node_value = (value, tuple(node_refs))
283
self._nodes[key] = node_value
284
if self._key_length > 1:
285
subkey = list(reversed(key[:-1]))
286
key_dict = self._nodes_by_key
287
if self.node_ref_lists:
288
key_value = key, node_value[0], node_value[1]
290
key_value = key, node_value
291
# possibly should do this on-demand, but it seems likely it is
293
# For a key of (foo, bar, baz) create
294
# _nodes_by_key[foo][bar][baz] = key_value
295
for subkey in key[:-1]:
296
key_dict = key_dict.setdefault(subkey, {})
297
key_dict[key[-1]] = key_value
298
self._keys = set(self._nodes)
300
# there must be one line - the empty trailer line.
301
raise errors.BadIndexData(self)
303
def iter_all_entries(self):
304
"""Iterate over all keys within the index.
306
:return: An iterable of (key, value) or (key, value, reference_lists).
307
The former tuple is used when there are no reference lists in the
308
index, making the API compatible with simple key:value index types.
309
There is no defined order for the result iteration - it will be in
310
the most efficient order for the index.
312
if self._nodes is None:
314
if self.node_ref_lists:
315
for key, (value, node_ref_lists) in self._nodes.iteritems():
316
yield key, value, node_ref_lists
318
for key, value in self._nodes.iteritems():
321
def _read_prefix(self, stream):
322
signature = stream.read(len(self._signature()))
323
if not signature == self._signature():
324
raise errors.BadIndexFormatSignature(self._name, GraphIndex)
325
options_line = stream.readline()
326
if not options_line.startswith(_OPTION_NODE_REFS):
327
raise errors.BadIndexOptions(self)
329
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
331
raise errors.BadIndexOptions(self)
332
options_line = stream.readline()
333
if not options_line.startswith(_OPTION_KEY_ELEMENTS):
334
raise errors.BadIndexOptions(self)
336
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1])
338
raise errors.BadIndexOptions(self)
340
def iter_entries(self, keys):
341
"""Iterate over keys within the index.
343
:param keys: An iterable providing the keys to be retrieved.
344
:return: An iterable as per iter_all_entries, but restricted to the
345
keys supplied. No additional keys will be returned, and every
346
key supplied that is in the index will be returned.
351
if self._nodes is None:
353
keys = keys.intersection(self._keys)
354
if self.node_ref_lists:
356
value, node_refs = self._nodes[key]
357
yield key, value, node_refs
360
yield key, self._nodes[key]
362
def iter_entries_prefix(self, keys):
363
"""Iterate over keys within the index using prefix matching.
365
Prefix matching is applied within the tuple of a key, not to within
366
the bytestring of each key element. e.g. if you have the keys ('foo',
367
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
368
only the former key is returned.
370
:param keys: An iterable providing the key prefixes to be retrieved.
371
Each key prefix takes the form of a tuple the length of a key, but
372
with the last N elements 'None' rather than a regular bytestring.
373
The first element cannot be 'None'.
374
:return: An iterable as per iter_all_entries, but restricted to the
375
keys with a matching prefix to those supplied. No additional keys
376
will be returned, and every match that is in the index will be
382
# load data - also finds key lengths
383
if self._nodes is None:
385
if self._key_length == 1:
389
raise errors.BadIndexKey(key)
390
if len(key) != self._key_length:
391
raise errors.BadIndexKey(key)
392
if self.node_ref_lists:
393
value, node_refs = self._nodes[key]
394
yield key, value, node_refs
396
yield key, self._nodes[key]
401
raise errors.BadIndexKey(key)
402
if len(key) != self._key_length:
403
raise errors.BadIndexKey(key)
404
# find what it refers to:
405
key_dict = self._nodes_by_key
407
# find the subdict whose contents should be returned.
409
while len(elements) and elements[0] is not None:
410
key_dict = key_dict[elements[0]]
413
# a non-existant lookup.
418
key_dict = dicts.pop(-1)
419
# can't be empty or would not exist
420
item, value = key_dict.iteritems().next()
421
if type(value) == dict:
423
dicts.extend(key_dict.itervalues())
426
for value in key_dict.itervalues():
427
# each value is the key:value:node refs tuple
431
# the last thing looked up was a terminal element
434
def _signature(self):
435
"""The file signature for this index type."""
439
"""Validate that everything in the index can be accessed."""
440
# iter_all validates completely at the moment, so just do that.
441
for node in self.iter_all_entries():
445
class CombinedGraphIndex(object):
446
"""A GraphIndex made up from smaller GraphIndices.
448
The backing indices must implement GraphIndex, and are presumed to be
451
Queries against the combined index will be made against the first index,
452
and then the second and so on. The order of index's can thus influence
453
performance significantly. For example, if one index is on local disk and a
454
second on a remote server, the local disk index should be before the other
458
def __init__(self, indices):
459
"""Create a CombinedGraphIndex backed by indices.
461
:param indices: An ordered list of indices to query for data.
463
self._indices = indices
465
def insert_index(self, pos, index):
466
"""Insert a new index in the list of indices to query.
468
:param pos: The position to insert the index.
469
:param index: The index to insert.
471
self._indices.insert(pos, index)
473
def iter_all_entries(self):
474
"""Iterate over all keys within the index
476
Duplicate keys across child indices are presumed to have the same
477
value and are only reported once.
479
:return: An iterable of (key, reference_lists, value). There is no
480
defined order for the result iteration - it will be in the most
481
efficient order for the index.
484
for index in self._indices:
485
for node in index.iter_all_entries():
486
if node[0] not in seen_keys:
488
seen_keys.add(node[0])
490
def iter_entries(self, keys):
491
"""Iterate over keys within the index.
493
Duplicate keys across child indices are presumed to have the same
494
value and are only reported once.
496
:param keys: An iterable providing the keys to be retrieved.
497
:return: An iterable of (key, reference_lists, value). There is no
498
defined order for the result iteration - it will be in the most
499
efficient order for the index.
502
for index in self._indices:
505
for node in index.iter_entries(keys):
509
def iter_entries_prefix(self, keys):
510
"""Iterate over keys within the index using prefix matching.
512
Duplicate keys across child indices are presumed to have the same
513
value and are only reported once.
515
Prefix matching is applied within the tuple of a key, not to within
516
the bytestring of each key element. e.g. if you have the keys ('foo',
517
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
518
only the former key is returned.
520
:param keys: An iterable providing the key prefixes to be retrieved.
521
Each key prefix takes the form of a tuple the length of a key, but
522
with the last N elements 'None' rather than a regular bytestring.
523
The first element cannot be 'None'.
524
:return: An iterable as per iter_all_entries, but restricted to the
525
keys with a matching prefix to those supplied. No additional keys
526
will be returned, and every match that is in the index will be
533
for index in self._indices:
534
for node in index.iter_entries_prefix(keys):
535
if node[0] in seen_keys:
537
seen_keys.add(node[0])
541
"""Validate that everything in the index can be accessed."""
542
for index in self._indices:
546
class InMemoryGraphIndex(GraphIndexBuilder):
547
"""A GraphIndex which operates entirely out of memory and is mutable.
549
This is designed to allow the accumulation of GraphIndex entries during a
550
single write operation, where the accumulated entries need to be immediately
551
available - for example via a CombinedGraphIndex.
554
def add_nodes(self, nodes):
555
"""Add nodes to the index.
557
:param nodes: An iterable of (key, node_refs, value) entries to add.
559
if self.reference_lists:
560
for (key, value, node_refs) in nodes:
561
self.add_node(key, value, node_refs)
563
for (key, value) in nodes:
564
self.add_node(key, value)
566
def iter_all_entries(self):
567
"""Iterate over all keys within the index
569
:return: An iterable of (key, reference_lists, value). There is no
570
defined order for the result iteration - it will be in the most
571
efficient order for the index (in this case dictionary hash order).
573
if self.reference_lists:
574
for key, (absent, references, value) in self._nodes.iteritems():
576
yield key, value, references
578
for key, (absent, references, value) in self._nodes.iteritems():
582
def iter_entries(self, keys):
583
"""Iterate over keys within the index.
585
:param keys: An iterable providing the keys to be retrieved.
586
:return: An iterable of (key, reference_lists, value). There is no
587
defined order for the result iteration - it will be in the most
588
efficient order for the index (keys iteration order in this case).
591
if self.reference_lists:
592
for key in keys.intersection(self._nodes):
593
node = self._nodes[key]
595
yield key, node[2], node[1]
597
for key in keys.intersection(self._nodes):
598
node = self._nodes[key]
602
def iter_entries_prefix(self, keys):
603
"""Iterate over keys within the index using prefix matching.
605
Prefix matching is applied within the tuple of a key, not to within
606
the bytestring of each key element. e.g. if you have the keys ('foo',
607
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
608
only the former key is returned.
610
:param keys: An iterable providing the key prefixes to be retrieved.
611
Each key prefix takes the form of a tuple the length of a key, but
612
with the last N elements 'None' rather than a regular bytestring.
613
The first element cannot be 'None'.
614
:return: An iterable as per iter_all_entries, but restricted to the
615
keys with a matching prefix to those supplied. No additional keys
616
will be returned, and every match that is in the index will be
619
# XXX: To much duplication with the GraphIndex class; consider finding
620
# a good place to pull out the actual common logic.
624
if self._key_length == 1:
628
raise errors.BadIndexKey(key)
629
if len(key) != self._key_length:
630
raise errors.BadIndexKey(key)
631
node = self._nodes[key]
634
if self.reference_lists:
635
yield key, node[2], node[1]
642
raise errors.BadIndexKey(key)
643
if len(key) != self._key_length:
644
raise errors.BadIndexKey(key)
645
# find what it refers to:
646
key_dict = self._nodes_by_key
648
# find the subdict to return
650
while len(elements) and elements[0] is not None:
651
key_dict = key_dict[elements[0]]
654
# a non-existant lookup.
659
key_dict = dicts.pop(-1)
660
# can't be empty or would not exist
661
item, value = key_dict.iteritems().next()
662
if type(value) == dict:
664
dicts.extend(key_dict.itervalues())
667
for value in key_dict.itervalues():
673
"""In memory index's have no known corruption at the moment."""