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."""
23
'GraphIndexPrefixAdapter',
27
from bisect import bisect_right
28
from cStringIO import StringIO
31
from bzrlib.lazy_import import lazy_import
32
lazy_import(globals(), """
33
from bzrlib import trace
34
from bzrlib.bisect_multi import bisect_multi_bytes
35
from bzrlib.revision import NULL_REVISION
36
from bzrlib.trace import mutter
44
_HEADER_READV = (0, 200)
45
_OPTION_KEY_ELEMENTS = "key_elements="
47
_OPTION_NODE_REFS = "node_ref_lists="
48
_SIGNATURE = "Bazaar Graph Index 1\n"
51
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
52
_newline_null_re = re.compile('[\n\0]')
55
class GraphIndexBuilder(object):
56
"""A builder that can build a GraphIndex.
58
The resulting graph has the structure:
60
_SIGNATURE OPTIONS NODES NEWLINE
61
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
62
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
64
NODE := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
65
KEY := Not-whitespace-utf8
67
REFERENCES := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
68
REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
69
REFERENCE := DIGITS ; digits is the byte offset in the index of the
71
VALUE := no-newline-no-null-bytes
74
def __init__(self, reference_lists=0, key_elements=1):
75
"""Create a GraphIndex builder.
77
:param reference_lists: The number of node references lists for each
79
:param key_elements: The number of bytestrings in each key.
81
self.reference_lists = reference_lists
83
# A dict of {key: (absent, ref_lists, value)}
85
self._nodes_by_key = None
86
self._key_length = key_elements
88
def _check_key(self, key):
89
"""Raise BadIndexKey if key is not a valid key for this index."""
90
if type(key) != tuple:
91
raise errors.BadIndexKey(key)
92
if self._key_length != len(key):
93
raise errors.BadIndexKey(key)
95
if not element or _whitespace_re.search(element) is not None:
96
raise errors.BadIndexKey(element)
98
def _get_nodes_by_key(self):
99
if self._nodes_by_key is None:
101
if self.reference_lists:
102
for key, (absent, references, value) in self._nodes.iteritems():
105
key_dict = nodes_by_key
106
for subkey in key[:-1]:
107
key_dict = key_dict.setdefault(subkey, {})
108
key_dict[key[-1]] = key, value, references
110
for key, (absent, references, value) in self._nodes.iteritems():
113
key_dict = nodes_by_key
114
for subkey in key[:-1]:
115
key_dict = key_dict.setdefault(subkey, {})
116
key_dict[key[-1]] = key, value
117
self._nodes_by_key = nodes_by_key
118
return self._nodes_by_key
120
def _update_nodes_by_key(self, key, value, node_refs):
121
"""Update the _nodes_by_key dict with a new key.
123
For a key of (foo, bar, baz) create
124
_nodes_by_key[foo][bar][baz] = key_value
126
if self._nodes_by_key is None:
128
key_dict = self._nodes_by_key
129
if self.reference_lists:
130
key_value = key, value, node_refs
132
key_value = key, value
133
for subkey in key[:-1]:
134
key_dict = key_dict.setdefault(subkey, {})
135
key_dict[key[-1]] = key_value
137
def _check_key_ref_value(self, key, references, value):
138
"""Check that 'key' and 'references' are all valid.
140
:param key: A key tuple. Must conform to the key interface (be a tuple,
141
be of the right length, not have any whitespace or nulls in any key
143
:param references: An iterable of reference lists. Something like
144
[[(ref, key)], [(ref, key), (other, key)]]
145
:param value: The value associate with this key. Must not contain
146
newlines or null characters.
147
:return: (node_refs, absent_references)
148
node_refs basically a packed form of 'references' where all
150
absent_references reference keys that are not in self._nodes.
151
This may contain duplicates if the same key is
152
referenced in multiple lists.
155
if _newline_null_re.search(value) is not None:
156
raise errors.BadIndexValue(value)
157
if len(references) != self.reference_lists:
158
raise errors.BadIndexValue(references)
160
absent_references = []
161
for reference_list in references:
162
for reference in reference_list:
163
# If reference *is* in self._nodes, then we know it has already
165
if reference not in self._nodes:
166
self._check_key(reference)
167
absent_references.append(reference)
168
node_refs.append(tuple(reference_list))
169
return tuple(node_refs), absent_references
171
def add_node(self, key, value, references=()):
172
"""Add a node to the index.
174
:param key: The key. keys are non-empty tuples containing
175
as many whitespace-free utf8 bytestrings as the key length
176
defined for this index.
177
:param references: An iterable of iterables of keys. Each is a
178
reference to another key.
179
:param value: The value to associate with the key. It may be any
180
bytes as long as it does not contain \0 or \n.
183
absent_references) = self._check_key_ref_value(key, references, value)
184
if key in self._nodes and self._nodes[key][0] != 'a':
185
raise errors.BadIndexDuplicateKey(key, self)
186
for reference in absent_references:
187
# There may be duplicates, but I don't think it is worth worrying
189
self._nodes[reference] = ('a', (), '')
190
self._nodes[key] = ('', node_refs, value)
192
if self._nodes_by_key is not None and self._key_length > 1:
193
self._update_nodes_by_key(key, value, node_refs)
197
lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
198
lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
199
lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
200
prefix_length = sum(len(x) for x in lines)
201
# references are byte offsets. To avoid having to do nasty
202
# polynomial work to resolve offsets (references to later in the
203
# file cannot be determined until all the inbetween references have
204
# been calculated too) we pad the offsets with 0's to make them be
205
# of consistent length. Using binary offsets would break the trivial
207
# to calculate the width of zero's needed we do three passes:
208
# one to gather all the non-reference data and the number of references.
209
# one to pad all the data with reference-length and determine entry
213
# forward sorted by key. In future we may consider topological sorting,
214
# at the cost of table scans for direct lookup, or a second index for
216
nodes = sorted(self._nodes.items())
217
# if we do not prepass, we don't know how long it will be up front.
218
expected_bytes = None
219
# we only need to pre-pass if we have reference lists at all.
220
if self.reference_lists:
222
non_ref_bytes = prefix_length
224
# TODO use simple multiplication for the constants in this loop.
225
for key, (absent, references, value) in nodes:
226
# record the offset known *so far* for this key:
227
# the non reference bytes to date, and the total references to
228
# date - saves reaccumulating on the second pass
229
key_offset_info.append((key, non_ref_bytes, total_references))
230
# key is literal, value is literal, there are 3 null's, 1 NL
231
# key is variable length tuple, \x00 between elements
232
non_ref_bytes += sum(len(element) for element in key)
233
if self._key_length > 1:
234
non_ref_bytes += self._key_length - 1
235
# value is literal bytes, there are 3 null's, 1 NL.
236
non_ref_bytes += len(value) + 3 + 1
237
# one byte for absent if set.
240
elif self.reference_lists:
241
# (ref_lists -1) tabs
242
non_ref_bytes += self.reference_lists - 1
243
# (ref-1 cr's per ref_list)
244
for ref_list in references:
245
# how many references across the whole file?
246
total_references += len(ref_list)
247
# accrue reference separators
249
non_ref_bytes += len(ref_list) - 1
250
# how many digits are needed to represent the total byte count?
252
possible_total_bytes = non_ref_bytes + total_references*digits
253
while 10 ** digits < possible_total_bytes:
255
possible_total_bytes = non_ref_bytes + total_references*digits
256
expected_bytes = possible_total_bytes + 1 # terminating newline
257
# resolve key addresses.
259
for key, non_ref_bytes, total_references in key_offset_info:
260
key_addresses[key] = non_ref_bytes + total_references*digits
262
format_string = '%%0%sd' % digits
263
for key, (absent, references, value) in nodes:
264
flattened_references = []
265
for ref_list in references:
267
for reference in ref_list:
268
ref_addresses.append(format_string % key_addresses[reference])
269
flattened_references.append('\r'.join(ref_addresses))
270
string_key = '\x00'.join(key)
271
lines.append("%s\x00%s\x00%s\x00%s\n" % (string_key, absent,
272
'\t'.join(flattened_references), value))
274
result = StringIO(''.join(lines))
275
if expected_bytes and len(result.getvalue()) != expected_bytes:
276
raise errors.BzrError('Failed index creation. Internal error:'
277
' mismatched output length and expected length: %d %d' %
278
(len(result.getvalue()), expected_bytes))
282
class GraphIndex(object):
283
"""An index for data with embedded graphs.
285
The index maps keys to a list of key reference lists, and a value.
286
Each node has the same number of key reference lists. Each key reference
287
list can be empty or an arbitrary length. The value is an opaque NULL
288
terminated string without any newlines. The storage of the index is
289
hidden in the interface: keys and key references are always tuples of
290
bytestrings, never the internal representation (e.g. dictionary offsets).
292
It is presumed that the index will not be mutated - it is static data.
294
Successive iter_all_entries calls will read the entire index each time.
295
Additionally, iter_entries calls will read the index linearly until the
296
desired keys are found. XXX: This must be fixed before the index is
297
suitable for production use. :XXX
300
def __init__(self, transport, name, size):
301
"""Open an index called name on transport.
303
:param transport: A bzrlib.transport.Transport.
304
:param name: A path to provide to transport API calls.
305
:param size: The size of the index in bytes. This is used for bisection
306
logic to perform partial index reads. While the size could be
307
obtained by statting the file this introduced an additional round
308
trip as well as requiring stat'able transports, both of which are
309
avoided by having it supplied. If size is None, then bisection
310
support will be disabled and accessing the index will just stream
313
self._transport = transport
315
# Becomes a dict of key:(value, reference-list-byte-locations) used by
316
# the bisection interface to store parsed but not resolved keys.
317
self._bisect_nodes = None
318
# Becomes a dict of key:(value, reference-list-keys) which are ready to
319
# be returned directly to callers.
321
# a sorted list of slice-addresses for the parsed bytes of the file.
322
# e.g. (0,1) would mean that byte 0 is parsed.
323
self._parsed_byte_map = []
324
# a sorted list of keys matching each slice address for parsed bytes
325
# e.g. (None, 'foo@bar') would mean that the first byte contained no
326
# key, and the end byte of the slice is the of the data for 'foo@bar'
327
self._parsed_key_map = []
328
self._key_count = None
329
self._keys_by_offset = None
330
self._nodes_by_key = None
333
def __eq__(self, other):
334
"""Equal when self and other were created with the same parameters."""
336
type(self) == type(other) and
337
self._transport == other._transport and
338
self._name == other._name and
339
self._size == other._size)
341
def __ne__(self, other):
342
return not self.__eq__(other)
345
return "%s(%r)" % (self.__class__.__name__,
346
self._transport.abspath(self._name))
348
def _buffer_all(self):
349
"""Buffer all the index data.
351
Mutates self._nodes and self.keys_by_offset.
353
if 'index' in debug.debug_flags:
354
mutter('Reading entire index %s', self._transport.abspath(self._name))
355
stream = self._transport.get(self._name)
356
self._read_prefix(stream)
357
self._expected_elements = 3 + self._key_length
359
# raw data keyed by offset
360
self._keys_by_offset = {}
361
# ready-to-return key:value or key:value, node_ref_lists
363
self._nodes_by_key = {}
366
lines = stream.read().split('\n')
368
_, _, _, trailers = self._parse_lines(lines, pos)
369
for key, absent, references, value in self._keys_by_offset.itervalues():
372
# resolve references:
373
if self.node_ref_lists:
374
node_value = (value, self._resolve_references(references))
377
self._nodes[key] = node_value
378
if self._key_length > 1:
379
# TODO: We may want to do this lazily, but if we are calling
380
# _buffer_all, we are likely to be doing
381
# iter_entries_prefix
382
key_dict = self._nodes_by_key
383
if self.node_ref_lists:
384
key_value = key, node_value[0], node_value[1]
386
key_value = key, node_value
387
# For a key of (foo, bar, baz) create
388
# _nodes_by_key[foo][bar][baz] = key_value
389
for subkey in key[:-1]:
390
key_dict = key_dict.setdefault(subkey, {})
391
key_dict[key[-1]] = key_value
392
# cache the keys for quick set intersections
393
self._keys = set(self._nodes)
395
# there must be one line - the empty trailer line.
396
raise errors.BadIndexData(self)
398
def iter_all_entries(self):
399
"""Iterate over all keys within the index.
401
:return: An iterable of (index, key, value) or (index, key, value, reference_lists).
402
The former tuple is used when there are no reference lists in the
403
index, making the API compatible with simple key:value index types.
404
There is no defined order for the result iteration - it will be in
405
the most efficient order for the index.
407
if 'evil' in debug.debug_flags:
408
trace.mutter_callsite(3,
409
"iter_all_entries scales with size of history.")
410
if self._nodes is None:
412
if self.node_ref_lists:
413
for key, (value, node_ref_lists) in self._nodes.iteritems():
414
yield self, key, value, node_ref_lists
416
for key, value in self._nodes.iteritems():
417
yield self, key, value
419
def _read_prefix(self, stream):
420
signature = stream.read(len(self._signature()))
421
if not signature == self._signature():
422
raise errors.BadIndexFormatSignature(self._name, GraphIndex)
423
options_line = stream.readline()
424
if not options_line.startswith(_OPTION_NODE_REFS):
425
raise errors.BadIndexOptions(self)
427
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
429
raise errors.BadIndexOptions(self)
430
options_line = stream.readline()
431
if not options_line.startswith(_OPTION_KEY_ELEMENTS):
432
raise errors.BadIndexOptions(self)
434
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1])
436
raise errors.BadIndexOptions(self)
437
options_line = stream.readline()
438
if not options_line.startswith(_OPTION_LEN):
439
raise errors.BadIndexOptions(self)
441
self._key_count = int(options_line[len(_OPTION_LEN):-1])
443
raise errors.BadIndexOptions(self)
445
def _resolve_references(self, references):
446
"""Return the resolved key references for references.
448
References are resolved by looking up the location of the key in the
449
_keys_by_offset map and substituting the key name, preserving ordering.
451
:param references: An iterable of iterables of key locations. e.g.
453
:return: A tuple of tuples of keys.
456
for ref_list in references:
457
node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
458
return tuple(node_refs)
460
def _find_index(self, range_map, key):
461
"""Helper for the _parsed_*_index calls.
463
Given a range map - [(start, end), ...], finds the index of the range
464
in the map for key if it is in the map, and if it is not there, the
465
immediately preceeding range in the map.
467
result = bisect_right(range_map, key) - 1
468
if result + 1 < len(range_map):
469
# check the border condition, it may be in result + 1
470
if range_map[result + 1][0] == key[0]:
474
def _parsed_byte_index(self, offset):
475
"""Return the index of the entry immediately before offset.
477
e.g. if the parsed map has regions 0,10 and 11,12 parsed, meaning that
478
there is one unparsed byte (the 11th, addressed as[10]). then:
479
asking for 0 will return 0
480
asking for 10 will return 0
481
asking for 11 will return 1
482
asking for 12 will return 1
485
return self._find_index(self._parsed_byte_map, key)
487
def _parsed_key_index(self, key):
488
"""Return the index of the entry immediately before key.
490
e.g. if the parsed map has regions (None, 'a') and ('b','c') parsed,
491
meaning that keys from None to 'a' inclusive, and 'b' to 'c' inclusive
492
have been parsed, then:
493
asking for '' will return 0
494
asking for 'a' will return 0
495
asking for 'b' will return 1
496
asking for 'e' will return 1
498
search_key = (key, None)
499
return self._find_index(self._parsed_key_map, search_key)
501
def _is_parsed(self, offset):
502
"""Returns True if offset has been parsed."""
503
index = self._parsed_byte_index(offset)
504
if index == len(self._parsed_byte_map):
505
return offset < self._parsed_byte_map[index - 1][1]
506
start, end = self._parsed_byte_map[index]
507
return offset >= start and offset < end
509
def _iter_entries_from_total_buffer(self, keys):
510
"""Iterate over keys when the entire index is parsed."""
511
keys = keys.intersection(self._keys)
512
if self.node_ref_lists:
514
value, node_refs = self._nodes[key]
515
yield self, key, value, node_refs
518
yield self, key, self._nodes[key]
520
def iter_entries(self, keys):
521
"""Iterate over keys within the index.
523
:param keys: An iterable providing the keys to be retrieved.
524
:return: An iterable as per iter_all_entries, but restricted to the
525
keys supplied. No additional keys will be returned, and every
526
key supplied that is in the index will be returned.
531
if self._size is None and self._nodes is None:
533
# We fit about 20 keys per minimum-read (4K), so if we are looking for
534
# more than 1/20th of the index its likely (assuming homogenous key
535
# spread) that we'll read the entire index. If we're going to do that,
536
# buffer the whole thing. A better analysis might take key spread into
537
# account - but B+Tree indices are better anyway.
538
# We could look at all data read, and use a threshold there, which will
539
# trigger on ancestry walks, but that is not yet fully mapped out.
540
if self._nodes is None and len(keys) * 20 > self.key_count():
542
if self._nodes is not None:
543
return self._iter_entries_from_total_buffer(keys)
545
return (result[1] for result in bisect_multi_bytes(
546
self._lookup_keys_via_location, self._size, keys))
548
def iter_entries_prefix(self, keys):
549
"""Iterate over keys within the index using prefix matching.
551
Prefix matching is applied within the tuple of a key, not to within
552
the bytestring of each key element. e.g. if you have the keys ('foo',
553
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
554
only the former key is returned.
556
WARNING: Note that this method currently causes a full index parse
557
unconditionally (which is reasonably appropriate as it is a means for
558
thunking many small indices into one larger one and still supplies
559
iter_all_entries at the thunk layer).
561
:param keys: An iterable providing the key prefixes to be retrieved.
562
Each key prefix takes the form of a tuple the length of a key, but
563
with the last N elements 'None' rather than a regular bytestring.
564
The first element cannot be 'None'.
565
:return: An iterable as per iter_all_entries, but restricted to the
566
keys with a matching prefix to those supplied. No additional keys
567
will be returned, and every match that is in the index will be
573
# load data - also finds key lengths
574
if self._nodes is None:
576
if self._key_length == 1:
580
raise errors.BadIndexKey(key)
581
if len(key) != self._key_length:
582
raise errors.BadIndexKey(key)
583
if self.node_ref_lists:
584
value, node_refs = self._nodes[key]
585
yield self, key, value, node_refs
587
yield self, key, self._nodes[key]
592
raise errors.BadIndexKey(key)
593
if len(key) != self._key_length:
594
raise errors.BadIndexKey(key)
595
# find what it refers to:
596
key_dict = self._nodes_by_key
598
# find the subdict whose contents should be returned.
600
while len(elements) and elements[0] is not None:
601
key_dict = key_dict[elements[0]]
604
# a non-existant lookup.
609
key_dict = dicts.pop(-1)
610
# can't be empty or would not exist
611
item, value = key_dict.iteritems().next()
612
if type(value) == dict:
614
dicts.extend(key_dict.itervalues())
617
for value in key_dict.itervalues():
618
# each value is the key:value:node refs tuple
620
yield (self, ) + value
622
# the last thing looked up was a terminal element
623
yield (self, ) + key_dict
626
"""Return an estimate of the number of keys in this index.
628
For GraphIndex the estimate is exact.
630
if self._key_count is None:
631
self._read_and_parse([_HEADER_READV])
632
return self._key_count
634
def _lookup_keys_via_location(self, location_keys):
635
"""Public interface for implementing bisection.
637
If _buffer_all has been called, then all the data for the index is in
638
memory, and this method should not be called, as it uses a separate
639
cache because it cannot pre-resolve all indices, which buffer_all does
642
:param location_keys: A list of location(byte offset), key tuples.
643
:return: A list of (location_key, result) tuples as expected by
644
bzrlib.bisect_multi.bisect_multi_bytes.
646
# Possible improvements:
647
# - only bisect lookup each key once
648
# - sort the keys first, and use that to reduce the bisection window
650
# this progresses in three parts:
653
# attempt to answer the question from the now in memory data.
654
# build the readv request
655
# for each location, ask for 800 bytes - much more than rows we've seen
658
for location, key in location_keys:
659
# can we answer from cache?
660
if self._bisect_nodes and key in self._bisect_nodes:
661
# We have the key parsed.
663
index = self._parsed_key_index(key)
664
if (len(self._parsed_key_map) and
665
self._parsed_key_map[index][0] <= key and
666
(self._parsed_key_map[index][1] >= key or
667
# end of the file has been parsed
668
self._parsed_byte_map[index][1] == self._size)):
669
# the key has been parsed, so no lookup is needed even if its
672
# - if we have examined this part of the file already - yes
673
index = self._parsed_byte_index(location)
674
if (len(self._parsed_byte_map) and
675
self._parsed_byte_map[index][0] <= location and
676
self._parsed_byte_map[index][1] > location):
677
# the byte region has been parsed, so no read is needed.
680
if location + length > self._size:
681
length = self._size - location
682
# todo, trim out parsed locations.
684
readv_ranges.append((location, length))
685
# read the header if needed
686
if self._bisect_nodes is None:
687
readv_ranges.append(_HEADER_READV)
688
self._read_and_parse(readv_ranges)
690
# - figure out <, >, missing, present
691
# - result present references so we can return them.
693
# keys that we cannot answer until we resolve references
694
pending_references = []
695
pending_locations = set()
696
for location, key in location_keys:
697
# can we answer from cache?
698
if key in self._bisect_nodes:
699
# the key has been parsed, so no lookup is needed
700
if self.node_ref_lists:
701
# the references may not have been all parsed.
702
value, refs = self._bisect_nodes[key]
703
wanted_locations = []
704
for ref_list in refs:
706
if ref not in self._keys_by_offset:
707
wanted_locations.append(ref)
709
pending_locations.update(wanted_locations)
710
pending_references.append((location, key))
712
result.append(((location, key), (self, key,
713
value, self._resolve_references(refs))))
715
result.append(((location, key),
716
(self, key, self._bisect_nodes[key])))
719
# has the region the key should be in, been parsed?
720
index = self._parsed_key_index(key)
721
if (self._parsed_key_map[index][0] <= key and
722
(self._parsed_key_map[index][1] >= key or
723
# end of the file has been parsed
724
self._parsed_byte_map[index][1] == self._size)):
725
result.append(((location, key), False))
727
# no, is the key above or below the probed location:
728
# get the range of the probed & parsed location
729
index = self._parsed_byte_index(location)
730
# if the key is below the start of the range, its below
731
if key < self._parsed_key_map[index][0]:
735
result.append(((location, key), direction))
737
# lookup data to resolve references
738
for location in pending_locations:
740
if location + length > self._size:
741
length = self._size - location
742
# TODO: trim out parsed locations (e.g. if the 800 is into the
743
# parsed region trim it, and dont use the adjust_for_latency
746
readv_ranges.append((location, length))
747
self._read_and_parse(readv_ranges)
748
for location, key in pending_references:
749
# answer key references we had to look-up-late.
750
index = self._parsed_key_index(key)
751
value, refs = self._bisect_nodes[key]
752
result.append(((location, key), (self, key,
753
value, self._resolve_references(refs))))
756
def _parse_header_from_bytes(self, bytes):
757
"""Parse the header from a region of bytes.
759
:param bytes: The data to parse.
760
:return: An offset, data tuple such as readv yields, for the unparsed
761
data. (which may length 0).
763
signature = bytes[0:len(self._signature())]
764
if not signature == self._signature():
765
raise errors.BadIndexFormatSignature(self._name, GraphIndex)
766
lines = bytes[len(self._signature()):].splitlines()
767
options_line = lines[0]
768
if not options_line.startswith(_OPTION_NODE_REFS):
769
raise errors.BadIndexOptions(self)
771
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):])
773
raise errors.BadIndexOptions(self)
774
options_line = lines[1]
775
if not options_line.startswith(_OPTION_KEY_ELEMENTS):
776
raise errors.BadIndexOptions(self)
778
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):])
780
raise errors.BadIndexOptions(self)
781
options_line = lines[2]
782
if not options_line.startswith(_OPTION_LEN):
783
raise errors.BadIndexOptions(self)
785
self._key_count = int(options_line[len(_OPTION_LEN):])
787
raise errors.BadIndexOptions(self)
788
# calculate the bytes we have processed
789
header_end = (len(signature) + len(lines[0]) + len(lines[1]) +
791
self._parsed_bytes(0, None, header_end, None)
792
# setup parsing state
793
self._expected_elements = 3 + self._key_length
794
# raw data keyed by offset
795
self._keys_by_offset = {}
796
# keys with the value and node references
797
self._bisect_nodes = {}
798
return header_end, bytes[header_end:]
800
def _parse_region(self, offset, data):
801
"""Parse node data returned from a readv operation.
803
:param offset: The byte offset the data starts at.
804
:param data: The data to parse.
808
end = offset + len(data)
811
# Trivial test - if the current index's end is within the
812
# low-matching parsed range, we're done.
813
index = self._parsed_byte_index(high_parsed)
814
if end < self._parsed_byte_map[index][1]:
816
# print "[%d:%d]" % (offset, end), \
817
# self._parsed_byte_map[index:index + 2]
818
high_parsed, last_segment = self._parse_segment(
819
offset, data, end, index)
823
def _parse_segment(self, offset, data, end, index):
824
"""Parse one segment of data.
826
:param offset: Where 'data' begins in the file.
827
:param data: Some data to parse a segment of.
828
:param end: Where data ends
829
:param index: The current index into the parsed bytes map.
830
:return: True if the parsed segment is the last possible one in the
832
:return: high_parsed_byte, last_segment.
833
high_parsed_byte is the location of the highest parsed byte in this
834
segment, last_segment is True if the parsed segment is the last
835
possible one in the data block.
837
# default is to use all data
839
# accomodate overlap with data before this.
840
if offset < self._parsed_byte_map[index][1]:
841
# overlaps the lower parsed region
842
# skip the parsed data
843
trim_start = self._parsed_byte_map[index][1] - offset
844
# don't trim the start for \n
845
start_adjacent = True
846
elif offset == self._parsed_byte_map[index][1]:
847
# abuts the lower parsed region
850
# do not trim anything
851
start_adjacent = True
853
# does not overlap the lower parsed region
856
# but trim the leading \n
857
start_adjacent = False
858
if end == self._size:
859
# lines up to the end of all data:
862
# do not strip to the last \n
865
elif index + 1 == len(self._parsed_byte_map):
866
# at the end of the parsed data
869
# but strip to the last \n
872
elif end == self._parsed_byte_map[index + 1][0]:
873
# buts up against the next parsed region
876
# do not strip to the last \n
879
elif end > self._parsed_byte_map[index + 1][0]:
880
# overlaps into the next parsed region
881
# only consider the unparsed data
882
trim_end = self._parsed_byte_map[index + 1][0] - offset
883
# do not strip to the last \n as we know its an entire record
885
last_segment = end < self._parsed_byte_map[index + 1][1]
887
# does not overlap into the next region
890
# but strip to the last \n
893
# now find bytes to discard if needed
894
if not start_adjacent:
895
# work around python bug in rfind
896
if trim_start is None:
897
trim_start = data.find('\n') + 1
899
trim_start = data.find('\n', trim_start) + 1
900
if not (trim_start != 0):
901
raise AssertionError('no \n was present')
902
# print 'removing start', offset, trim_start, repr(data[:trim_start])
904
# work around python bug in rfind
906
trim_end = data.rfind('\n') + 1
908
trim_end = data.rfind('\n', None, trim_end) + 1
909
if not (trim_end != 0):
910
raise AssertionError('no \n was present')
911
# print 'removing end', offset, trim_end, repr(data[trim_end:])
912
# adjust offset and data to the parseable data.
913
trimmed_data = data[trim_start:trim_end]
914
if not (trimmed_data):
915
raise AssertionError('read unneeded data [%d:%d] from [%d:%d]'
916
% (trim_start, trim_end, offset, offset + len(data)))
919
# print "parsing", repr(trimmed_data)
920
# splitlines mangles the \r delimiters.. don't use it.
921
lines = trimmed_data.split('\n')
924
first_key, last_key, nodes, _ = self._parse_lines(lines, pos)
925
for key, value in nodes:
926
self._bisect_nodes[key] = value
927
self._parsed_bytes(offset, first_key,
928
offset + len(trimmed_data), last_key)
929
return offset + len(trimmed_data), last_segment
931
def _parse_lines(self, lines, pos):
940
if not (self._size == pos + 1):
941
raise AssertionError("%s %s" % (self._size, pos))
944
elements = line.split('\0')
945
if len(elements) != self._expected_elements:
946
raise errors.BadIndexData(self)
947
# keys are tuples. Each element is a string that may occur many
948
# times, so we intern them to save space. AB, RC, 200807
949
key = tuple(intern(element) for element in elements[:self._key_length])
950
if first_key is None:
952
absent, references, value = elements[-3:]
954
for ref_string in references.split('\t'):
955
ref_lists.append(tuple([
956
int(ref) for ref in ref_string.split('\r') if ref
958
ref_lists = tuple(ref_lists)
959
self._keys_by_offset[pos] = (key, absent, ref_lists, value)
960
pos += len(line) + 1 # +1 for the \n
963
if self.node_ref_lists:
964
node_value = (value, ref_lists)
967
nodes.append((key, node_value))
968
# print "parsed ", key
969
return first_key, key, nodes, trailers
971
def _parsed_bytes(self, start, start_key, end, end_key):
972
"""Mark the bytes from start to end as parsed.
974
Calling self._parsed_bytes(1,2) will mark one byte (the one at offset
977
:param start: The start of the parsed region.
978
:param end: The end of the parsed region.
980
index = self._parsed_byte_index(start)
981
new_value = (start, end)
982
new_key = (start_key, end_key)
984
# first range parsed is always the beginning.
985
self._parsed_byte_map.insert(index, new_value)
986
self._parsed_key_map.insert(index, new_key)
990
# extend lower region
991
# extend higher region
992
# combine two regions
993
if (index + 1 < len(self._parsed_byte_map) and
994
self._parsed_byte_map[index][1] == start and
995
self._parsed_byte_map[index + 1][0] == end):
996
# combine two regions
997
self._parsed_byte_map[index] = (self._parsed_byte_map[index][0],
998
self._parsed_byte_map[index + 1][1])
999
self._parsed_key_map[index] = (self._parsed_key_map[index][0],
1000
self._parsed_key_map[index + 1][1])
1001
del self._parsed_byte_map[index + 1]
1002
del self._parsed_key_map[index + 1]
1003
elif self._parsed_byte_map[index][1] == start:
1004
# extend the lower entry
1005
self._parsed_byte_map[index] = (
1006
self._parsed_byte_map[index][0], end)
1007
self._parsed_key_map[index] = (
1008
self._parsed_key_map[index][0], end_key)
1009
elif (index + 1 < len(self._parsed_byte_map) and
1010
self._parsed_byte_map[index + 1][0] == end):
1011
# extend the higher entry
1012
self._parsed_byte_map[index + 1] = (
1013
start, self._parsed_byte_map[index + 1][1])
1014
self._parsed_key_map[index + 1] = (
1015
start_key, self._parsed_key_map[index + 1][1])
1018
self._parsed_byte_map.insert(index + 1, new_value)
1019
self._parsed_key_map.insert(index + 1, new_key)
1021
def _read_and_parse(self, readv_ranges):
1022
"""Read the the ranges and parse the resulting data.
1024
:param readv_ranges: A prepared readv range list.
1027
readv_data = self._transport.readv(self._name, readv_ranges, True,
1030
for offset, data in readv_data:
1031
if self._bisect_nodes is None:
1032
# this must be the start
1033
if not (offset == 0):
1034
raise AssertionError()
1035
offset, data = self._parse_header_from_bytes(data)
1036
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1037
self._parse_region(offset, data)
1039
def _signature(self):
1040
"""The file signature for this index type."""
1044
"""Validate that everything in the index can be accessed."""
1045
# iter_all validates completely at the moment, so just do that.
1046
for node in self.iter_all_entries():
1050
class CombinedGraphIndex(object):
1051
"""A GraphIndex made up from smaller GraphIndices.
1053
The backing indices must implement GraphIndex, and are presumed to be
1056
Queries against the combined index will be made against the first index,
1057
and then the second and so on. The order of index's can thus influence
1058
performance significantly. For example, if one index is on local disk and a
1059
second on a remote server, the local disk index should be before the other
1063
def __init__(self, indices):
1064
"""Create a CombinedGraphIndex backed by indices.
1066
:param indices: An ordered list of indices to query for data.
1068
self._indices = indices
1072
self.__class__.__name__,
1073
', '.join(map(repr, self._indices)))
1075
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
1076
def get_parents(self, revision_ids):
1077
"""See graph._StackedParentsProvider.get_parents.
1079
This implementation thunks the graph.Graph.get_parents api across to
1082
:param revision_ids: An iterable of graph keys for this graph.
1083
:return: A list of parent details for each key in revision_ids.
1084
Each parent details will be one of:
1085
* None when the key was missing
1086
* (NULL_REVISION,) when the key has no parents.
1087
* (parent_key, parent_key...) otherwise.
1089
parent_map = self.get_parent_map(revision_ids)
1090
return [parent_map.get(r, None) for r in revision_ids]
1092
def get_parent_map(self, keys):
1093
"""See graph._StackedParentsProvider.get_parent_map"""
1094
search_keys = set(keys)
1095
if NULL_REVISION in search_keys:
1096
search_keys.discard(NULL_REVISION)
1097
found_parents = {NULL_REVISION:[]}
1100
for index, key, value, refs in self.iter_entries(search_keys):
1103
parents = (NULL_REVISION,)
1104
found_parents[key] = parents
1105
return found_parents
1107
def insert_index(self, pos, index):
1108
"""Insert a new index in the list of indices to query.
1110
:param pos: The position to insert the index.
1111
:param index: The index to insert.
1113
self._indices.insert(pos, index)
1115
def iter_all_entries(self):
1116
"""Iterate over all keys within the index
1118
Duplicate keys across child indices are presumed to have the same
1119
value and are only reported once.
1121
:return: An iterable of (index, key, reference_lists, value).
1122
There is no defined order for the result iteration - it will be in
1123
the most efficient order for the index.
1126
for index in self._indices:
1127
for node in index.iter_all_entries():
1128
if node[1] not in seen_keys:
1130
seen_keys.add(node[1])
1132
def iter_entries(self, keys):
1133
"""Iterate over keys within the index.
1135
Duplicate keys across child indices are presumed to have the same
1136
value and are only reported once.
1138
:param keys: An iterable providing the keys to be retrieved.
1139
:return: An iterable of (index, key, reference_lists, value). There is no
1140
defined order for the result iteration - it will be in the most
1141
efficient order for the index.
1144
for index in self._indices:
1147
for node in index.iter_entries(keys):
1148
keys.remove(node[1])
1151
def iter_entries_prefix(self, keys):
1152
"""Iterate over keys within the index using prefix matching.
1154
Duplicate keys across child indices are presumed to have the same
1155
value and are only reported once.
1157
Prefix matching is applied within the tuple of a key, not to within
1158
the bytestring of each key element. e.g. if you have the keys ('foo',
1159
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1160
only the former key is returned.
1162
:param keys: An iterable providing the key prefixes to be retrieved.
1163
Each key prefix takes the form of a tuple the length of a key, but
1164
with the last N elements 'None' rather than a regular bytestring.
1165
The first element cannot be 'None'.
1166
:return: An iterable as per iter_all_entries, but restricted to the
1167
keys with a matching prefix to those supplied. No additional keys
1168
will be returned, and every match that is in the index will be
1175
for index in self._indices:
1176
for node in index.iter_entries_prefix(keys):
1177
if node[1] in seen_keys:
1179
seen_keys.add(node[1])
1182
def key_count(self):
1183
"""Return an estimate of the number of keys in this index.
1185
For CombinedGraphIndex this is approximated by the sum of the keys of
1186
the child indices. As child indices may have duplicate keys this can
1187
have a maximum error of the number of child indices * largest number of
1190
return sum((index.key_count() for index in self._indices), 0)
1193
"""Validate that everything in the index can be accessed."""
1194
for index in self._indices:
1198
class InMemoryGraphIndex(GraphIndexBuilder):
1199
"""A GraphIndex which operates entirely out of memory and is mutable.
1201
This is designed to allow the accumulation of GraphIndex entries during a
1202
single write operation, where the accumulated entries need to be immediately
1203
available - for example via a CombinedGraphIndex.
1206
def add_nodes(self, nodes):
1207
"""Add nodes to the index.
1209
:param nodes: An iterable of (key, node_refs, value) entries to add.
1211
if self.reference_lists:
1212
for (key, value, node_refs) in nodes:
1213
self.add_node(key, value, node_refs)
1215
for (key, value) in nodes:
1216
self.add_node(key, value)
1218
def iter_all_entries(self):
1219
"""Iterate over all keys within the index
1221
:return: An iterable of (index, key, reference_lists, value). There is no
1222
defined order for the result iteration - it will be in the most
1223
efficient order for the index (in this case dictionary hash order).
1225
if 'evil' in debug.debug_flags:
1226
trace.mutter_callsite(3,
1227
"iter_all_entries scales with size of history.")
1228
if self.reference_lists:
1229
for key, (absent, references, value) in self._nodes.iteritems():
1231
yield self, key, value, references
1233
for key, (absent, references, value) in self._nodes.iteritems():
1235
yield self, key, value
1237
def iter_entries(self, keys):
1238
"""Iterate over keys within the index.
1240
:param keys: An iterable providing the keys to be retrieved.
1241
:return: An iterable of (index, key, value, reference_lists). There is no
1242
defined order for the result iteration - it will be in the most
1243
efficient order for the index (keys iteration order in this case).
1246
if self.reference_lists:
1247
for key in keys.intersection(self._keys):
1248
node = self._nodes[key]
1250
yield self, key, node[2], node[1]
1252
for key in keys.intersection(self._keys):
1253
node = self._nodes[key]
1255
yield self, key, node[2]
1257
def iter_entries_prefix(self, keys):
1258
"""Iterate over keys within the index using prefix matching.
1260
Prefix matching is applied within the tuple of a key, not to within
1261
the bytestring of each key element. e.g. if you have the keys ('foo',
1262
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1263
only the former key is returned.
1265
:param keys: An iterable providing the key prefixes to be retrieved.
1266
Each key prefix takes the form of a tuple the length of a key, but
1267
with the last N elements 'None' rather than a regular bytestring.
1268
The first element cannot be 'None'.
1269
:return: An iterable as per iter_all_entries, but restricted to the
1270
keys with a matching prefix to those supplied. No additional keys
1271
will be returned, and every match that is in the index will be
1274
# XXX: To much duplication with the GraphIndex class; consider finding
1275
# a good place to pull out the actual common logic.
1279
if self._key_length == 1:
1283
raise errors.BadIndexKey(key)
1284
if len(key) != self._key_length:
1285
raise errors.BadIndexKey(key)
1286
node = self._nodes[key]
1289
if self.reference_lists:
1290
yield self, key, node[2], node[1]
1292
yield self, key, node[2]
1294
nodes_by_key = self._get_nodes_by_key()
1298
raise errors.BadIndexKey(key)
1299
if len(key) != self._key_length:
1300
raise errors.BadIndexKey(key)
1301
# find what it refers to:
1302
key_dict = nodes_by_key
1303
elements = list(key)
1304
# find the subdict to return
1306
while len(elements) and elements[0] is not None:
1307
key_dict = key_dict[elements[0]]
1310
# a non-existant lookup.
1315
key_dict = dicts.pop(-1)
1316
# can't be empty or would not exist
1317
item, value = key_dict.iteritems().next()
1318
if type(value) == dict:
1320
dicts.extend(key_dict.itervalues())
1323
for value in key_dict.itervalues():
1324
yield (self, ) + value
1326
yield (self, ) + key_dict
1328
def key_count(self):
1329
"""Return an estimate of the number of keys in this index.
1331
For InMemoryGraphIndex the estimate is exact.
1333
return len(self._keys)
1336
"""In memory index's have no known corruption at the moment."""
1339
class GraphIndexPrefixAdapter(object):
1340
"""An adapter between GraphIndex with different key lengths.
1342
Queries against this will emit queries against the adapted Graph with the
1343
prefix added, queries for all items use iter_entries_prefix. The returned
1344
nodes will have their keys and node references adjusted to remove the
1345
prefix. Finally, an add_nodes_callback can be supplied - when called the
1346
nodes and references being added will have prefix prepended.
1349
def __init__(self, adapted, prefix, missing_key_length,
1350
add_nodes_callback=None):
1351
"""Construct an adapter against adapted with prefix."""
1352
self.adapted = adapted
1353
self.prefix_key = prefix + (None,)*missing_key_length
1354
self.prefix = prefix
1355
self.prefix_len = len(prefix)
1356
self.add_nodes_callback = add_nodes_callback
1358
def add_nodes(self, nodes):
1359
"""Add nodes to the index.
1361
:param nodes: An iterable of (key, node_refs, value) entries to add.
1363
# save nodes in case its an iterator
1364
nodes = tuple(nodes)
1365
translated_nodes = []
1367
# Add prefix_key to each reference node_refs is a tuple of tuples,
1368
# so split it apart, and add prefix_key to the internal reference
1369
for (key, value, node_refs) in nodes:
1370
adjusted_references = (
1371
tuple(tuple(self.prefix + ref_node for ref_node in ref_list)
1372
for ref_list in node_refs))
1373
translated_nodes.append((self.prefix + key, value,
1374
adjusted_references))
1376
# XXX: TODO add an explicit interface for getting the reference list
1377
# status, to handle this bit of user-friendliness in the API more
1379
for (key, value) in nodes:
1380
translated_nodes.append((self.prefix + key, value))
1381
self.add_nodes_callback(translated_nodes)
1383
def add_node(self, key, value, references=()):
1384
"""Add a node to the index.
1386
:param key: The key. keys are non-empty tuples containing
1387
as many whitespace-free utf8 bytestrings as the key length
1388
defined for this index.
1389
:param references: An iterable of iterables of keys. Each is a
1390
reference to another key.
1391
:param value: The value to associate with the key. It may be any
1392
bytes as long as it does not contain \0 or \n.
1394
self.add_nodes(((key, value, references), ))
1396
def _strip_prefix(self, an_iter):
1397
"""Strip prefix data from nodes and return it."""
1398
for node in an_iter:
1400
if node[1][:self.prefix_len] != self.prefix:
1401
raise errors.BadIndexData(self)
1402
for ref_list in node[3]:
1403
for ref_node in ref_list:
1404
if ref_node[:self.prefix_len] != self.prefix:
1405
raise errors.BadIndexData(self)
1406
yield node[0], node[1][self.prefix_len:], node[2], (
1407
tuple(tuple(ref_node[self.prefix_len:] for ref_node in ref_list)
1408
for ref_list in node[3]))
1410
def iter_all_entries(self):
1411
"""Iterate over all keys within the index
1413
iter_all_entries is implemented against the adapted index using
1414
iter_entries_prefix.
1416
:return: An iterable of (index, key, reference_lists, value). There is no
1417
defined order for the result iteration - it will be in the most
1418
efficient order for the index (in this case dictionary hash order).
1420
return self._strip_prefix(self.adapted.iter_entries_prefix([self.prefix_key]))
1422
def iter_entries(self, keys):
1423
"""Iterate over keys within the index.
1425
:param keys: An iterable providing the keys to be retrieved.
1426
:return: An iterable of (index, key, value, reference_lists). There is no
1427
defined order for the result iteration - it will be in the most
1428
efficient order for the index (keys iteration order in this case).
1430
return self._strip_prefix(self.adapted.iter_entries(
1431
self.prefix + key for key in keys))
1433
def iter_entries_prefix(self, keys):
1434
"""Iterate over keys within the index using prefix matching.
1436
Prefix matching is applied within the tuple of a key, not to within
1437
the bytestring of each key element. e.g. if you have the keys ('foo',
1438
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1439
only the former key is returned.
1441
:param keys: An iterable providing the key prefixes to be retrieved.
1442
Each key prefix takes the form of a tuple the length of a key, but
1443
with the last N elements 'None' rather than a regular bytestring.
1444
The first element cannot be 'None'.
1445
:return: An iterable as per iter_all_entries, but restricted to the
1446
keys with a matching prefix to those supplied. No additional keys
1447
will be returned, and every match that is in the index will be
1450
return self._strip_prefix(self.adapted.iter_entries_prefix(
1451
self.prefix + key for key in keys))
1453
def key_count(self):
1454
"""Return an estimate of the number of keys in this index.
1456
For GraphIndexPrefixAdapter this is relatively expensive - key
1457
iteration with the prefix is done.
1459
return len(list(self.iter_all_entries()))
1462
"""Call the adapted's validate."""
1463
self.adapted.validate()