79
115
if not element or _whitespace_re.search(element) is not None:
80
116
raise errors.BadIndexKey(element)
82
def add_node(self, key, value, references=()):
83
"""Add a node to the index.
85
:param key: The key. keys are non-empty tuples containing
86
as many whitespace-free utf8 bytestrings as the key length
87
defined for this index.
88
:param references: An iterable of iterables of keys. Each is a
89
reference to another key.
90
:param value: The value to associate with the key. It may be any
91
bytes as long as it does not contain \0 or \n.
118
def _external_references(self):
119
"""Return references that are not present in this index.
123
# TODO: JAM 2008-11-21 This makes an assumption about how the reference
124
# lists are used. It is currently correct for pack-0.92 through
125
# 1.9, which use the node references (3rd column) second
126
# reference list as the compression parent. Perhaps this should
127
# be moved into something higher up the stack, since it
128
# makes assumptions about how the index is used.
129
if self.reference_lists > 1:
130
for node in self.iter_all_entries():
132
refs.update(node[3][1])
135
# If reference_lists == 0 there can be no external references, and
136
# if reference_lists == 1, then there isn't a place to store the
140
def _get_nodes_by_key(self):
141
if self._nodes_by_key is None:
143
if self.reference_lists:
144
for key, (absent, references, value) in self._nodes.iteritems():
147
key_dict = nodes_by_key
148
for subkey in key[:-1]:
149
key_dict = key_dict.setdefault(subkey, {})
150
key_dict[key[-1]] = key, value, references
152
for key, (absent, references, value) in self._nodes.iteritems():
155
key_dict = nodes_by_key
156
for subkey in key[:-1]:
157
key_dict = key_dict.setdefault(subkey, {})
158
key_dict[key[-1]] = key, value
159
self._nodes_by_key = nodes_by_key
160
return self._nodes_by_key
162
def _update_nodes_by_key(self, key, value, node_refs):
163
"""Update the _nodes_by_key dict with a new key.
165
For a key of (foo, bar, baz) create
166
_nodes_by_key[foo][bar][baz] = key_value
168
if self._nodes_by_key is None:
170
key_dict = self._nodes_by_key
171
if self.reference_lists:
172
key_value = StaticTuple(key, value, node_refs)
174
key_value = StaticTuple(key, value)
175
for subkey in key[:-1]:
176
key_dict = key_dict.setdefault(subkey, {})
177
key_dict[key[-1]] = key_value
179
def _check_key_ref_value(self, key, references, value):
180
"""Check that 'key' and 'references' are all valid.
182
:param key: A key tuple. Must conform to the key interface (be a tuple,
183
be of the right length, not have any whitespace or nulls in any key
185
:param references: An iterable of reference lists. Something like
186
[[(ref, key)], [(ref, key), (other, key)]]
187
:param value: The value associate with this key. Must not contain
188
newlines or null characters.
189
:return: (node_refs, absent_references)
191
* node_refs: basically a packed form of 'references' where all
193
* absent_references: reference keys that are not in self._nodes.
194
This may contain duplicates if the same key is referenced in
197
as_st = StaticTuple.from_sequence
93
198
self._check_key(key)
94
199
if _newline_null_re.search(value) is not None:
95
200
raise errors.BadIndexValue(value)
96
201
if len(references) != self.reference_lists:
97
202
raise errors.BadIndexValue(references)
204
absent_references = []
99
205
for reference_list in references:
100
206
for reference in reference_list:
101
self._check_key(reference)
207
# If reference *is* in self._nodes, then we know it has already
102
209
if reference not in self._nodes:
103
self._nodes[reference] = ('a', (), '')
104
node_refs.append(tuple(reference_list))
105
if key in self._nodes and self._nodes[key][0] == '':
210
self._check_key(reference)
211
absent_references.append(reference)
212
reference_list = as_st([as_st(ref).intern()
213
for ref in reference_list])
214
node_refs.append(reference_list)
215
return as_st(node_refs), absent_references
217
def add_node(self, key, value, references=()):
218
"""Add a node to the index.
220
:param key: The key. keys are non-empty tuples containing
221
as many whitespace-free utf8 bytestrings as the key length
222
defined for this index.
223
:param references: An iterable of iterables of keys. Each is a
224
reference to another key.
225
:param value: The value to associate with the key. It may be any
226
bytes as long as it does not contain \\0 or \\n.
229
absent_references) = self._check_key_ref_value(key, references, value)
230
if key in self._nodes and self._nodes[key][0] != 'a':
106
231
raise errors.BadIndexDuplicateKey(key, self)
107
self._nodes[key] = ('', tuple(node_refs), value)
108
if self._key_length > 1:
109
key_dict = self._nodes_by_key
110
if self.reference_lists:
111
key_value = key, value, tuple(node_refs)
113
key_value = key, value
114
# possibly should do this on-demand, but it seems likely it is
116
# For a key of (foo, bar, baz) create
117
# _nodes_by_key[foo][bar][baz] = key_value
118
for subkey in key[:-1]:
119
key_dict = key_dict.setdefault(subkey, {})
120
key_dict[key[-1]] = key_value
232
for reference in absent_references:
233
# There may be duplicates, but I don't think it is worth worrying
235
self._nodes[reference] = ('a', (), '')
236
self._absent_keys.update(absent_references)
237
self._absent_keys.discard(key)
238
self._nodes[key] = ('', node_refs, value)
239
if self._nodes_by_key is not None and self._key_length > 1:
240
self._update_nodes_by_key(key, value, node_refs)
242
def clear_cache(self):
243
"""See GraphIndex.clear_cache()
245
This is a no-op, but we need the api to conform to a generic 'Index'
122
249
def finish(self):
252
:returns: cStringIO holding the full context of the index as it
253
should be written to disk.
123
255
lines = [_SIGNATURE]
124
256
lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
125
257
lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
258
key_count = len(self._nodes) - len(self._absent_keys)
259
lines.append(_OPTION_LEN + str(key_count) + '\n')
126
260
prefix_length = sum(len(x) for x in lines)
127
261
# references are byte offsets. To avoid having to do nasty
128
# polynomial work to resolve offsets (references to later in the
262
# polynomial work to resolve offsets (references to later in the
129
263
# file cannot be determined until all the inbetween references have
130
264
# been calculated too) we pad the offsets with 0's to make them be
131
265
# of consistent length. Using binary offsets would break the trivial
223
391
suitable for production use. :XXX
226
def __init__(self, transport, name):
394
def __init__(self, transport, name, size, unlimited_cache=False, offset=0):
227
395
"""Open an index called name on transport.
229
397
:param transport: A bzrlib.transport.Transport.
230
398
:param name: A path to provide to transport API calls.
399
:param size: The size of the index in bytes. This is used for bisection
400
logic to perform partial index reads. While the size could be
401
obtained by statting the file this introduced an additional round
402
trip as well as requiring stat'able transports, both of which are
403
avoided by having it supplied. If size is None, then bisection
404
support will be disabled and accessing the index will just stream
406
:param offset: Instead of starting the index data at offset 0, start it
407
at an arbitrary offset.
232
409
self._transport = transport
233
410
self._name = name
411
# Becomes a dict of key:(value, reference-list-byte-locations) used by
412
# the bisection interface to store parsed but not resolved keys.
413
self._bisect_nodes = None
414
# Becomes a dict of key:(value, reference-list-keys) which are ready to
415
# be returned directly to callers.
234
416
self._nodes = None
417
# a sorted list of slice-addresses for the parsed bytes of the file.
418
# e.g. (0,1) would mean that byte 0 is parsed.
419
self._parsed_byte_map = []
420
# a sorted list of keys matching each slice address for parsed bytes
421
# e.g. (None, 'foo@bar') would mean that the first byte contained no
422
# key, and the end byte of the slice is the of the data for 'foo@bar'
423
self._parsed_key_map = []
424
self._key_count = None
235
425
self._keys_by_offset = None
236
426
self._nodes_by_key = None
238
def _buffer_all(self):
428
# The number of bytes we've read so far in trying to process this file
430
self._base_offset = offset
432
def __eq__(self, other):
433
"""Equal when self and other were created with the same parameters."""
435
type(self) == type(other) and
436
self._transport == other._transport and
437
self._name == other._name and
438
self._size == other._size)
440
def __ne__(self, other):
441
return not self.__eq__(other)
444
return "%s(%r)" % (self.__class__.__name__,
445
self._transport.abspath(self._name))
447
def _buffer_all(self, stream=None):
239
448
"""Buffer all the index data.
241
450
Mutates self._nodes and self.keys_by_offset.
243
stream = self._transport.get(self._name)
452
if self._nodes is not None:
453
# We already did this
455
if 'index' in debug.debug_flags:
456
trace.mutter('Reading entire index %s',
457
self._transport.abspath(self._name))
459
stream = self._transport.get(self._name)
460
if self._base_offset != 0:
461
# This is wasteful, but it is better than dealing with
462
# adjusting all the offsets, etc.
463
stream = StringIO(stream.read()[self._base_offset:])
244
464
self._read_prefix(stream)
245
expected_elements = 3 + self._key_length
465
self._expected_elements = 3 + self._key_length
247
467
# raw data keyed by offset
248
468
self._keys_by_offset = {}
249
469
# ready-to-return key:value or key:value, node_ref_lists
251
self._nodes_by_key = {}
471
self._nodes_by_key = None
253
473
pos = stream.tell()
254
for line in stream.readlines():
258
elements = line.split('\0')
259
if len(elements) != expected_elements:
260
raise errors.BadIndexData(self)
262
key = tuple(elements[:self._key_length])
263
absent, references, value = elements[-3:]
264
value = value[:-1] # remove the newline
266
for ref_string in references.split('\t'):
267
ref_lists.append(tuple([
268
int(ref) for ref in ref_string.split('\r') if ref
270
ref_lists = tuple(ref_lists)
271
self._keys_by_offset[pos] = (key, absent, ref_lists, value)
474
lines = stream.read().split('\n')
475
# GZ 2009-09-20: Should really use a try/finally block to ensure close
478
_, _, _, trailers = self._parse_lines(lines, pos)
273
479
for key, absent, references, value in self._keys_by_offset.itervalues():
276
482
# resolve references:
277
483
if self.node_ref_lists:
279
for ref_list in references:
280
node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
281
node_value = (value, tuple(node_refs))
484
node_value = (value, self._resolve_references(references))
283
486
node_value = value
284
487
self._nodes[key] = node_value
285
if self._key_length > 1:
286
subkey = list(reversed(key[:-1]))
287
key_dict = self._nodes_by_key
288
if self.node_ref_lists:
289
key_value = key, node_value[0], node_value[1]
291
key_value = key, node_value
292
# possibly should do this on-demand, but it seems likely it is
294
# For a key of (foo, bar, baz) create
295
# _nodes_by_key[foo][bar][baz] = key_value
296
for subkey in key[:-1]:
297
key_dict = key_dict.setdefault(subkey, {})
298
key_dict[key[-1]] = key_value
299
self._keys = set(self._nodes)
488
# cache the keys for quick set intersections
300
489
if trailers != 1:
301
490
# there must be one line - the empty trailer line.
302
491
raise errors.BadIndexData(self)
493
def clear_cache(self):
494
"""Clear out any cached/memoized values.
496
This can be called at any time, but generally it is used when we have
497
extracted some information, but don't expect to be requesting any more
501
def external_references(self, ref_list_num):
502
"""Return references that are not present in this index.
505
if ref_list_num + 1 > self.node_ref_lists:
506
raise ValueError('No ref list %d, index has %d ref lists'
507
% (ref_list_num, self.node_ref_lists))
510
for key, (value, ref_lists) in nodes.iteritems():
511
ref_list = ref_lists[ref_list_num]
512
refs.update([ref for ref in ref_list if ref not in nodes])
515
def _get_nodes_by_key(self):
516
if self._nodes_by_key is None:
518
if self.node_ref_lists:
519
for key, (value, references) in self._nodes.iteritems():
520
key_dict = nodes_by_key
521
for subkey in key[:-1]:
522
key_dict = key_dict.setdefault(subkey, {})
523
key_dict[key[-1]] = key, value, references
525
for key, value in self._nodes.iteritems():
526
key_dict = nodes_by_key
527
for subkey in key[:-1]:
528
key_dict = key_dict.setdefault(subkey, {})
529
key_dict[key[-1]] = key, value
530
self._nodes_by_key = nodes_by_key
531
return self._nodes_by_key
304
533
def iter_all_entries(self):
305
534
"""Iterate over all keys within the index.
307
:return: An iterable of (key, value) or (key, value, reference_lists).
536
:return: An iterable of (index, key, value) or (index, key, value, reference_lists).
308
537
The former tuple is used when there are no reference lists in the
309
538
index, making the API compatible with simple key:value index types.
310
539
There is no defined order for the result iteration - it will be in
311
540
the most efficient order for the index.
542
if 'evil' in debug.debug_flags:
543
trace.mutter_callsite(3,
544
"iter_all_entries scales with size of history.")
313
545
if self._nodes is None:
314
546
self._buffer_all()
315
547
if self.node_ref_lists:
337
569
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1])
338
570
except ValueError:
339
571
raise errors.BadIndexOptions(self)
572
options_line = stream.readline()
573
if not options_line.startswith(_OPTION_LEN):
574
raise errors.BadIndexOptions(self)
576
self._key_count = int(options_line[len(_OPTION_LEN):-1])
578
raise errors.BadIndexOptions(self)
580
def _resolve_references(self, references):
581
"""Return the resolved key references for references.
583
References are resolved by looking up the location of the key in the
584
_keys_by_offset map and substituting the key name, preserving ordering.
586
:param references: An iterable of iterables of key locations. e.g.
588
:return: A tuple of tuples of keys.
591
for ref_list in references:
592
node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
593
return tuple(node_refs)
595
def _find_index(self, range_map, key):
596
"""Helper for the _parsed_*_index calls.
598
Given a range map - [(start, end), ...], finds the index of the range
599
in the map for key if it is in the map, and if it is not there, the
600
immediately preceeding range in the map.
602
result = bisect_right(range_map, key) - 1
603
if result + 1 < len(range_map):
604
# check the border condition, it may be in result + 1
605
if range_map[result + 1][0] == key[0]:
609
def _parsed_byte_index(self, offset):
610
"""Return the index of the entry immediately before offset.
612
e.g. if the parsed map has regions 0,10 and 11,12 parsed, meaning that
613
there is one unparsed byte (the 11th, addressed as[10]). then:
614
asking for 0 will return 0
615
asking for 10 will return 0
616
asking for 11 will return 1
617
asking for 12 will return 1
620
return self._find_index(self._parsed_byte_map, key)
622
def _parsed_key_index(self, key):
623
"""Return the index of the entry immediately before key.
625
e.g. if the parsed map has regions (None, 'a') and ('b','c') parsed,
626
meaning that keys from None to 'a' inclusive, and 'b' to 'c' inclusive
627
have been parsed, then:
628
asking for '' will return 0
629
asking for 'a' will return 0
630
asking for 'b' will return 1
631
asking for 'e' will return 1
633
search_key = (key, None)
634
return self._find_index(self._parsed_key_map, search_key)
636
def _is_parsed(self, offset):
637
"""Returns True if offset has been parsed."""
638
index = self._parsed_byte_index(offset)
639
if index == len(self._parsed_byte_map):
640
return offset < self._parsed_byte_map[index - 1][1]
641
start, end = self._parsed_byte_map[index]
642
return offset >= start and offset < end
644
def _iter_entries_from_total_buffer(self, keys):
645
"""Iterate over keys when the entire index is parsed."""
646
# Note: See the note in BTreeBuilder.iter_entries for why we don't use
647
# .intersection() here
649
keys = [key for key in keys if key in nodes]
650
if self.node_ref_lists:
652
value, node_refs = nodes[key]
653
yield self, key, value, node_refs
656
yield self, key, nodes[key]
341
658
def iter_entries(self, keys):
342
659
"""Iterate over keys within the index.
432
762
# the last thing looked up was a terminal element
433
763
yield (self, ) + key_dict
765
def _find_ancestors(self, keys, ref_list_num, parent_map, missing_keys):
766
"""See BTreeIndex._find_ancestors."""
767
# The api can be implemented as a trivial overlay on top of
768
# iter_entries, it is not an efficient implementation, but it at least
772
for index, key, value, refs in self.iter_entries(keys):
773
parent_keys = refs[ref_list_num]
775
parent_map[key] = parent_keys
776
search_keys.update(parent_keys)
777
# Figure out what, if anything, was missing
778
missing_keys.update(set(keys).difference(found_keys))
779
search_keys = search_keys.difference(parent_map)
783
"""Return an estimate of the number of keys in this index.
785
For GraphIndex the estimate is exact.
787
if self._key_count is None:
788
self._read_and_parse([_HEADER_READV])
789
return self._key_count
791
def _lookup_keys_via_location(self, location_keys):
792
"""Public interface for implementing bisection.
794
If _buffer_all has been called, then all the data for the index is in
795
memory, and this method should not be called, as it uses a separate
796
cache because it cannot pre-resolve all indices, which buffer_all does
799
:param location_keys: A list of location(byte offset), key tuples.
800
:return: A list of (location_key, result) tuples as expected by
801
bzrlib.bisect_multi.bisect_multi_bytes.
803
# Possible improvements:
804
# - only bisect lookup each key once
805
# - sort the keys first, and use that to reduce the bisection window
807
# this progresses in three parts:
810
# attempt to answer the question from the now in memory data.
811
# build the readv request
812
# for each location, ask for 800 bytes - much more than rows we've seen
815
for location, key in location_keys:
816
# can we answer from cache?
817
if self._bisect_nodes and key in self._bisect_nodes:
818
# We have the key parsed.
820
index = self._parsed_key_index(key)
821
if (len(self._parsed_key_map) and
822
self._parsed_key_map[index][0] <= key and
823
(self._parsed_key_map[index][1] >= key or
824
# end of the file has been parsed
825
self._parsed_byte_map[index][1] == self._size)):
826
# the key has been parsed, so no lookup is needed even if its
829
# - if we have examined this part of the file already - yes
830
index = self._parsed_byte_index(location)
831
if (len(self._parsed_byte_map) and
832
self._parsed_byte_map[index][0] <= location and
833
self._parsed_byte_map[index][1] > location):
834
# the byte region has been parsed, so no read is needed.
837
if location + length > self._size:
838
length = self._size - location
839
# todo, trim out parsed locations.
841
readv_ranges.append((location, length))
842
# read the header if needed
843
if self._bisect_nodes is None:
844
readv_ranges.append(_HEADER_READV)
845
self._read_and_parse(readv_ranges)
847
if self._nodes is not None:
848
# _read_and_parse triggered a _buffer_all because we requested the
850
for location, key in location_keys:
851
if key not in self._nodes: # not present
852
result.append(((location, key), False))
853
elif self.node_ref_lists:
854
value, refs = self._nodes[key]
855
result.append(((location, key),
856
(self, key, value, refs)))
858
result.append(((location, key),
859
(self, key, self._nodes[key])))
862
# - figure out <, >, missing, present
863
# - result present references so we can return them.
864
# keys that we cannot answer until we resolve references
865
pending_references = []
866
pending_locations = set()
867
for location, key in location_keys:
868
# can we answer from cache?
869
if key in self._bisect_nodes:
870
# the key has been parsed, so no lookup is needed
871
if self.node_ref_lists:
872
# the references may not have been all parsed.
873
value, refs = self._bisect_nodes[key]
874
wanted_locations = []
875
for ref_list in refs:
877
if ref not in self._keys_by_offset:
878
wanted_locations.append(ref)
880
pending_locations.update(wanted_locations)
881
pending_references.append((location, key))
883
result.append(((location, key), (self, key,
884
value, self._resolve_references(refs))))
886
result.append(((location, key),
887
(self, key, self._bisect_nodes[key])))
890
# has the region the key should be in, been parsed?
891
index = self._parsed_key_index(key)
892
if (self._parsed_key_map[index][0] <= key and
893
(self._parsed_key_map[index][1] >= key or
894
# end of the file has been parsed
895
self._parsed_byte_map[index][1] == self._size)):
896
result.append(((location, key), False))
898
# no, is the key above or below the probed location:
899
# get the range of the probed & parsed location
900
index = self._parsed_byte_index(location)
901
# if the key is below the start of the range, its below
902
if key < self._parsed_key_map[index][0]:
906
result.append(((location, key), direction))
908
# lookup data to resolve references
909
for location in pending_locations:
911
if location + length > self._size:
912
length = self._size - location
913
# TODO: trim out parsed locations (e.g. if the 800 is into the
914
# parsed region trim it, and dont use the adjust_for_latency
917
readv_ranges.append((location, length))
918
self._read_and_parse(readv_ranges)
919
if self._nodes is not None:
920
# The _read_and_parse triggered a _buffer_all, grab the data and
922
for location, key in pending_references:
923
value, refs = self._nodes[key]
924
result.append(((location, key), (self, key, value, refs)))
926
for location, key in pending_references:
927
# answer key references we had to look-up-late.
928
value, refs = self._bisect_nodes[key]
929
result.append(((location, key), (self, key,
930
value, self._resolve_references(refs))))
933
def _parse_header_from_bytes(self, bytes):
934
"""Parse the header from a region of bytes.
936
:param bytes: The data to parse.
937
:return: An offset, data tuple such as readv yields, for the unparsed
938
data. (which may length 0).
940
signature = bytes[0:len(self._signature())]
941
if not signature == self._signature():
942
raise errors.BadIndexFormatSignature(self._name, GraphIndex)
943
lines = bytes[len(self._signature()):].splitlines()
944
options_line = lines[0]
945
if not options_line.startswith(_OPTION_NODE_REFS):
946
raise errors.BadIndexOptions(self)
948
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):])
950
raise errors.BadIndexOptions(self)
951
options_line = lines[1]
952
if not options_line.startswith(_OPTION_KEY_ELEMENTS):
953
raise errors.BadIndexOptions(self)
955
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):])
957
raise errors.BadIndexOptions(self)
958
options_line = lines[2]
959
if not options_line.startswith(_OPTION_LEN):
960
raise errors.BadIndexOptions(self)
962
self._key_count = int(options_line[len(_OPTION_LEN):])
964
raise errors.BadIndexOptions(self)
965
# calculate the bytes we have processed
966
header_end = (len(signature) + len(lines[0]) + len(lines[1]) +
968
self._parsed_bytes(0, None, header_end, None)
969
# setup parsing state
970
self._expected_elements = 3 + self._key_length
971
# raw data keyed by offset
972
self._keys_by_offset = {}
973
# keys with the value and node references
974
self._bisect_nodes = {}
975
return header_end, bytes[header_end:]
977
def _parse_region(self, offset, data):
978
"""Parse node data returned from a readv operation.
980
:param offset: The byte offset the data starts at.
981
:param data: The data to parse.
985
end = offset + len(data)
988
# Trivial test - if the current index's end is within the
989
# low-matching parsed range, we're done.
990
index = self._parsed_byte_index(high_parsed)
991
if end < self._parsed_byte_map[index][1]:
993
# print "[%d:%d]" % (offset, end), \
994
# self._parsed_byte_map[index:index + 2]
995
high_parsed, last_segment = self._parse_segment(
996
offset, data, end, index)
1000
def _parse_segment(self, offset, data, end, index):
1001
"""Parse one segment of data.
1003
:param offset: Where 'data' begins in the file.
1004
:param data: Some data to parse a segment of.
1005
:param end: Where data ends
1006
:param index: The current index into the parsed bytes map.
1007
:return: True if the parsed segment is the last possible one in the
1009
:return: high_parsed_byte, last_segment.
1010
high_parsed_byte is the location of the highest parsed byte in this
1011
segment, last_segment is True if the parsed segment is the last
1012
possible one in the data block.
1014
# default is to use all data
1016
# accomodate overlap with data before this.
1017
if offset < self._parsed_byte_map[index][1]:
1018
# overlaps the lower parsed region
1019
# skip the parsed data
1020
trim_start = self._parsed_byte_map[index][1] - offset
1021
# don't trim the start for \n
1022
start_adjacent = True
1023
elif offset == self._parsed_byte_map[index][1]:
1024
# abuts the lower parsed region
1027
# do not trim anything
1028
start_adjacent = True
1030
# does not overlap the lower parsed region
1033
# but trim the leading \n
1034
start_adjacent = False
1035
if end == self._size:
1036
# lines up to the end of all data:
1039
# do not strip to the last \n
1042
elif index + 1 == len(self._parsed_byte_map):
1043
# at the end of the parsed data
1046
# but strip to the last \n
1047
end_adjacent = False
1049
elif end == self._parsed_byte_map[index + 1][0]:
1050
# buts up against the next parsed region
1053
# do not strip to the last \n
1056
elif end > self._parsed_byte_map[index + 1][0]:
1057
# overlaps into the next parsed region
1058
# only consider the unparsed data
1059
trim_end = self._parsed_byte_map[index + 1][0] - offset
1060
# do not strip to the last \n as we know its an entire record
1062
last_segment = end < self._parsed_byte_map[index + 1][1]
1064
# does not overlap into the next region
1067
# but strip to the last \n
1068
end_adjacent = False
1070
# now find bytes to discard if needed
1071
if not start_adjacent:
1072
# work around python bug in rfind
1073
if trim_start is None:
1074
trim_start = data.find('\n') + 1
1076
trim_start = data.find('\n', trim_start) + 1
1077
if not (trim_start != 0):
1078
raise AssertionError('no \n was present')
1079
# print 'removing start', offset, trim_start, repr(data[:trim_start])
1080
if not end_adjacent:
1081
# work around python bug in rfind
1082
if trim_end is None:
1083
trim_end = data.rfind('\n') + 1
1085
trim_end = data.rfind('\n', None, trim_end) + 1
1086
if not (trim_end != 0):
1087
raise AssertionError('no \n was present')
1088
# print 'removing end', offset, trim_end, repr(data[trim_end:])
1089
# adjust offset and data to the parseable data.
1090
trimmed_data = data[trim_start:trim_end]
1091
if not (trimmed_data):
1092
raise AssertionError('read unneeded data [%d:%d] from [%d:%d]'
1093
% (trim_start, trim_end, offset, offset + len(data)))
1095
offset += trim_start
1096
# print "parsing", repr(trimmed_data)
1097
# splitlines mangles the \r delimiters.. don't use it.
1098
lines = trimmed_data.split('\n')
1101
first_key, last_key, nodes, _ = self._parse_lines(lines, pos)
1102
for key, value in nodes:
1103
self._bisect_nodes[key] = value
1104
self._parsed_bytes(offset, first_key,
1105
offset + len(trimmed_data), last_key)
1106
return offset + len(trimmed_data), last_segment
1108
def _parse_lines(self, lines, pos):
1115
# must be at the end
1117
if not (self._size == pos + 1):
1118
raise AssertionError("%s %s" % (self._size, pos))
1121
elements = line.split('\0')
1122
if len(elements) != self._expected_elements:
1123
raise errors.BadIndexData(self)
1124
# keys are tuples. Each element is a string that may occur many
1125
# times, so we intern them to save space. AB, RC, 200807
1126
key = tuple([intern(element) for element in elements[:self._key_length]])
1127
if first_key is None:
1129
absent, references, value = elements[-3:]
1131
for ref_string in references.split('\t'):
1132
ref_lists.append(tuple([
1133
int(ref) for ref in ref_string.split('\r') if ref
1135
ref_lists = tuple(ref_lists)
1136
self._keys_by_offset[pos] = (key, absent, ref_lists, value)
1137
pos += len(line) + 1 # +1 for the \n
1140
if self.node_ref_lists:
1141
node_value = (value, ref_lists)
1144
nodes.append((key, node_value))
1145
# print "parsed ", key
1146
return first_key, key, nodes, trailers
1148
def _parsed_bytes(self, start, start_key, end, end_key):
1149
"""Mark the bytes from start to end as parsed.
1151
Calling self._parsed_bytes(1,2) will mark one byte (the one at offset
1154
:param start: The start of the parsed region.
1155
:param end: The end of the parsed region.
1157
index = self._parsed_byte_index(start)
1158
new_value = (start, end)
1159
new_key = (start_key, end_key)
1161
# first range parsed is always the beginning.
1162
self._parsed_byte_map.insert(index, new_value)
1163
self._parsed_key_map.insert(index, new_key)
1167
# extend lower region
1168
# extend higher region
1169
# combine two regions
1170
if (index + 1 < len(self._parsed_byte_map) and
1171
self._parsed_byte_map[index][1] == start and
1172
self._parsed_byte_map[index + 1][0] == end):
1173
# combine two regions
1174
self._parsed_byte_map[index] = (self._parsed_byte_map[index][0],
1175
self._parsed_byte_map[index + 1][1])
1176
self._parsed_key_map[index] = (self._parsed_key_map[index][0],
1177
self._parsed_key_map[index + 1][1])
1178
del self._parsed_byte_map[index + 1]
1179
del self._parsed_key_map[index + 1]
1180
elif self._parsed_byte_map[index][1] == start:
1181
# extend the lower entry
1182
self._parsed_byte_map[index] = (
1183
self._parsed_byte_map[index][0], end)
1184
self._parsed_key_map[index] = (
1185
self._parsed_key_map[index][0], end_key)
1186
elif (index + 1 < len(self._parsed_byte_map) and
1187
self._parsed_byte_map[index + 1][0] == end):
1188
# extend the higher entry
1189
self._parsed_byte_map[index + 1] = (
1190
start, self._parsed_byte_map[index + 1][1])
1191
self._parsed_key_map[index + 1] = (
1192
start_key, self._parsed_key_map[index + 1][1])
1195
self._parsed_byte_map.insert(index + 1, new_value)
1196
self._parsed_key_map.insert(index + 1, new_key)
1198
def _read_and_parse(self, readv_ranges):
1199
"""Read the ranges and parse the resulting data.
1201
:param readv_ranges: A prepared readv range list.
1203
if not readv_ranges:
1205
if self._nodes is None and self._bytes_read * 2 >= self._size:
1206
# We've already read more than 50% of the file and we are about to
1207
# request more data, just _buffer_all() and be done
1211
base_offset = self._base_offset
1212
if base_offset != 0:
1213
# Rewrite the ranges for the offset
1214
readv_ranges = [(start+base_offset, size)
1215
for start, size in readv_ranges]
1216
readv_data = self._transport.readv(self._name, readv_ranges, True,
1217
self._size + self._base_offset)
1219
for offset, data in readv_data:
1220
offset -= base_offset
1221
self._bytes_read += len(data)
1223
# transport.readv() expanded to extra data which isn't part of
1225
data = data[-offset:]
1227
if offset == 0 and len(data) == self._size:
1228
# We read the whole range, most likely because the
1229
# Transport upcast our readv ranges into one long request
1230
# for enough total data to grab the whole index.
1231
self._buffer_all(StringIO(data))
1233
if self._bisect_nodes is None:
1234
# this must be the start
1235
if not (offset == 0):
1236
raise AssertionError()
1237
offset, data = self._parse_header_from_bytes(data)
1238
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1239
self._parse_region(offset, data)
435
1241
def _signature(self):
436
1242
"""The file signature for this index type."""
437
1243
return _SIGNATURE
533
1402
seen_keys = set()
534
for index in self._indices:
535
for node in index.iter_entries_prefix(keys):
536
if node[1] in seen_keys:
538
seen_keys.add(node[1])
1406
for index in self._indices:
1408
for node in index.iter_entries_prefix(keys):
1409
if node[1] in seen_keys:
1411
seen_keys.add(node[1])
1415
hit_indices.append(index)
1417
except errors.NoSuchFile:
1418
self._reload_or_raise()
1419
self._move_to_front(hit_indices)
1421
def _move_to_front(self, hit_indices):
1422
"""Rearrange self._indices so that hit_indices are first.
1424
Order is maintained as much as possible, e.g. the first unhit index
1425
will be the first index in _indices after the hit_indices, and the
1426
hit_indices will be present in exactly the order they are passed to
1429
_move_to_front propagates to all objects in self._sibling_indices by
1430
calling _move_to_front_by_name.
1432
if self._indices[:len(hit_indices)] == hit_indices:
1433
# The 'hit_indices' are already at the front (and in the same
1434
# order), no need to re-order
1436
hit_names = self._move_to_front_by_index(hit_indices)
1437
for sibling_idx in self._sibling_indices:
1438
sibling_idx._move_to_front_by_name(hit_names)
1440
def _move_to_front_by_index(self, hit_indices):
1441
"""Core logic for _move_to_front.
1443
Returns a list of names corresponding to the hit_indices param.
1445
indices_info = zip(self._index_names, self._indices)
1446
if 'index' in debug.debug_flags:
1447
trace.mutter('CombinedGraphIndex reordering: currently %r, '
1448
'promoting %r', indices_info, hit_indices)
1451
new_hit_indices = []
1454
for offset, (name, idx) in enumerate(indices_info):
1455
if idx in hit_indices:
1456
hit_names.append(name)
1457
new_hit_indices.append(idx)
1458
if len(new_hit_indices) == len(hit_indices):
1459
# We've found all of the hit entries, everything else is
1461
unhit_names.extend(self._index_names[offset+1:])
1462
unhit_indices.extend(self._indices[offset+1:])
1465
unhit_names.append(name)
1466
unhit_indices.append(idx)
1468
self._indices = new_hit_indices + unhit_indices
1469
self._index_names = hit_names + unhit_names
1470
if 'index' in debug.debug_flags:
1471
trace.mutter('CombinedGraphIndex reordered: %r', self._indices)
1474
def _move_to_front_by_name(self, hit_names):
1475
"""Moves indices named by 'hit_names' to front of the search order, as
1476
described in _move_to_front.
1478
# Translate names to index instances, and then call
1479
# _move_to_front_by_index.
1480
indices_info = zip(self._index_names, self._indices)
1482
for name, idx in indices_info:
1483
if name in hit_names:
1484
hit_indices.append(idx)
1485
self._move_to_front_by_index(hit_indices)
1487
def find_ancestry(self, keys, ref_list_num):
1488
"""Find the complete ancestry for the given set of keys.
1490
Note that this is a whole-ancestry request, so it should be used
1493
:param keys: An iterable of keys to look for
1494
:param ref_list_num: The reference list which references the parents
1496
:return: (parent_map, missing_keys)
1498
# XXX: make this call _move_to_front?
1499
missing_keys = set()
1501
keys_to_lookup = set(keys)
1503
while keys_to_lookup:
1504
# keys that *all* indexes claim are missing, stop searching them
1506
all_index_missing = None
1507
# print 'gen\tidx\tsub\tn_keys\tn_pmap\tn_miss'
1508
# print '%4d\t\t\t%4d\t%5d\t%5d' % (generation, len(keys_to_lookup),
1510
# len(missing_keys))
1511
for index_idx, index in enumerate(self._indices):
1512
# TODO: we should probably be doing something with
1513
# 'missing_keys' since we've already determined that
1514
# those revisions have not been found anywhere
1515
index_missing_keys = set()
1516
# Find all of the ancestry we can from this index
1517
# keep looking until the search_keys set is empty, which means
1518
# things we didn't find should be in index_missing_keys
1519
search_keys = keys_to_lookup
1521
# print ' \t%2d\t\t%4d\t%5d\t%5d' % (
1522
# index_idx, len(search_keys),
1523
# len(parent_map), len(index_missing_keys))
1526
# TODO: ref_list_num should really be a parameter, since
1527
# CombinedGraphIndex does not know what the ref lists
1529
search_keys = index._find_ancestors(search_keys,
1530
ref_list_num, parent_map, index_missing_keys)
1531
# print ' \t \t%2d\t%4d\t%5d\t%5d' % (
1532
# sub_generation, len(search_keys),
1533
# len(parent_map), len(index_missing_keys))
1534
# Now set whatever was missing to be searched in the next index
1535
keys_to_lookup = index_missing_keys
1536
if all_index_missing is None:
1537
all_index_missing = set(index_missing_keys)
1539
all_index_missing.intersection_update(index_missing_keys)
1540
if not keys_to_lookup:
1542
if all_index_missing is None:
1543
# There were no indexes, so all search keys are 'missing'
1544
missing_keys.update(keys_to_lookup)
1545
keys_to_lookup = None
1547
missing_keys.update(all_index_missing)
1548
keys_to_lookup.difference_update(all_index_missing)
1549
return parent_map, missing_keys
1551
def key_count(self):
1552
"""Return an estimate of the number of keys in this index.
1554
For CombinedGraphIndex this is approximated by the sum of the keys of
1555
the child indices. As child indices may have duplicate keys this can
1556
have a maximum error of the number of child indices * largest number of
1561
return sum((index.key_count() for index in self._indices), 0)
1562
except errors.NoSuchFile:
1563
self._reload_or_raise()
1565
missing_keys = _missing_keys_from_parent_map
1567
def _reload_or_raise(self):
1568
"""We just got a NoSuchFile exception.
1570
Try to reload the indices, if it fails, just raise the current
1573
if self._reload_func is None:
1575
exc_type, exc_value, exc_traceback = sys.exc_info()
1576
trace.mutter('Trying to reload after getting exception: %s',
1578
if not self._reload_func():
1579
# We tried to reload, but nothing changed, so we fail anyway
1580
trace.mutter('_reload_func indicated nothing has changed.'
1581
' Raising original exception.')
1582
raise exc_type, exc_value, exc_traceback
1584
def set_sibling_indices(self, sibling_combined_graph_indices):
1585
"""Set the CombinedGraphIndex objects to reorder after reordering self.
1587
self._sibling_indices = sibling_combined_graph_indices
541
1589
def validate(self):
542
1590
"""Validate that everything in the index can be accessed."""
543
for index in self._indices:
1593
for index in self._indices:
1596
except errors.NoSuchFile:
1597
self._reload_or_raise()
547
1600
class InMemoryGraphIndex(GraphIndexBuilder):