129
130
_STREAM_MIN_BUFFER_SIZE = 5*1024*1024
133
class KnitError(InternalBzrError):
138
class KnitCorrupt(KnitError):
140
_fmt = "Knit %(filename)s corrupt: %(how)s"
142
def __init__(self, filename, how):
143
KnitError.__init__(self)
144
self.filename = filename
148
class SHA1KnitCorrupt(KnitCorrupt):
150
_fmt = ("Knit %(filename)s corrupt: sha-1 of reconstructed text does not "
151
"match expected sha-1. key %(key)s expected sha %(expected)s actual "
154
def __init__(self, filename, actual, expected, key, content):
155
KnitError.__init__(self)
156
self.filename = filename
158
self.expected = expected
160
self.content = content
163
class KnitDataStreamIncompatible(KnitError):
164
# Not raised anymore, as we can convert data streams. In future we may
165
# need it again for more exotic cases, so we're keeping it around for now.
167
_fmt = "Cannot insert knit data stream of format \"%(stream_format)s\" into knit of format \"%(target_format)s\"."
169
def __init__(self, stream_format, target_format):
170
self.stream_format = stream_format
171
self.target_format = target_format
174
class KnitDataStreamUnknown(KnitError):
175
# Indicates a data stream we don't know how to handle.
177
_fmt = "Cannot parse knit data stream of format \"%(stream_format)s\"."
179
def __init__(self, stream_format):
180
self.stream_format = stream_format
183
class KnitHeaderError(KnitError):
185
_fmt = 'Knit header error: %(badline)r unexpected for file "%(filename)s".'
187
def __init__(self, badline, filename):
188
KnitError.__init__(self)
189
self.badline = badline
190
self.filename = filename
193
class KnitIndexUnknownMethod(KnitError):
194
"""Raised when we don't understand the storage method.
196
Currently only 'fulltext' and 'line-delta' are supported.
199
_fmt = ("Knit index %(filename)s does not have a known method"
200
" in options: %(options)r")
202
def __init__(self, filename, options):
203
KnitError.__init__(self)
204
self.filename = filename
205
self.options = options
132
208
class KnitAdapter(object):
133
209
"""Base class for knit record adaption."""
632
708
# loop to minimise any performance impact
634
710
for header in lines:
635
start, end, count = [int(n) for n in header.split(',')]
636
contents = [next().split(' ', 1)[1] for i in xrange(count)]
711
start, end, count = [int(n) for n in header.split(b',')]
712
contents = [next(lines).split(b' ', 1)[1] for _ in range(count)]
637
713
result.append((start, end, count, contents))
639
715
for header in lines:
640
start, end, count = [int(n) for n in header.split(',')]
641
contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
716
start, end, count = [int(n) for n in header.split(b',')]
717
contents = [tuple(next(lines).split(b' ', 1))
718
for _ in range(count)]
642
719
result.append((start, end, count, contents))
645
722
def get_fulltext_content(self, lines):
646
723
"""Extract just the content lines from a fulltext."""
647
return (line.split(' ', 1)[1] for line in lines)
724
return (line.split(b' ', 1)[1] for line in lines)
649
726
def get_linedelta_content(self, lines):
650
727
"""Extract just the content from a line delta.
909
990
# indexes can't directly store that, so we give them
910
991
# an empty tuple instead.
912
line_bytes = ''.join(lines)
993
line_bytes = b''.join(lines)
913
994
return self._add(key, lines, parents,
914
995
parent_texts, left_matching_blocks, nostore_sha, random_id,
915
996
line_bytes=line_bytes)
917
def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
918
"""See VersionedFiles._add_text()."""
919
self._index._check_write_ok()
920
self._check_add(key, None, random_id, check_content=False)
921
if text.__class__ is not str:
922
raise errors.BzrBadParameterUnicode("text")
924
# The caller might pass None if there is no graph data, but kndx
925
# indexes can't directly store that, so we give them
926
# an empty tuple instead.
928
return self._add(key, None, parents,
929
None, None, nostore_sha, random_id,
932
998
def _add(self, key, lines, parents, parent_texts,
933
999
left_matching_blocks, nostore_sha, random_id,
988
1054
lines = lines[:]
989
1055
# Replace the last line with one that ends in a final newline
990
lines[-1] = lines[-1] + '\n'
1056
lines[-1] = lines[-1] + b'\n'
991
1057
if lines is None:
992
1058
lines = osutils.split_lines(line_bytes)
994
1060
for element in key[:-1]:
995
if type(element) is not str:
996
raise TypeError("key contains non-strings: %r" % (key,))
1061
if not isinstance(element, bytes):
1062
raise TypeError("key contains non-bytestrings: %r" % (key,))
997
1063
if key[-1] is None:
998
key = key[:-1] + ('sha1:' + digest,)
999
elif type(key[-1]) is not str:
1000
raise TypeError("key contains non-strings: %r" % (key,))
1064
key = key[:-1] + (b'sha1:' + digest,)
1065
elif not isinstance(key[-1], bytes):
1066
raise TypeError("key contains non-bytestrings: %r" % (key,))
1001
1067
# Knit hunks are still last-element only
1002
1068
version_id = key[-1]
1003
1069
content = self._factory.make(lines, version_id)
1012
1078
left_matching_blocks)
1015
options.append('line-delta')
1081
options.append(b'line-delta')
1016
1082
store_lines = self._factory.lower_line_delta(delta_hunks)
1017
size, bytes = self._record_to_data(key, digest,
1083
size, data = self._record_to_data(key, digest,
1020
options.append('fulltext')
1086
options.append(b'fulltext')
1021
1087
# isinstance is slower and we have no hierarchy.
1022
1088
if self._factory.__class__ is KnitPlainFactory:
1023
1089
# Use the already joined bytes saving iteration time in
1024
1090
# _record_to_data.
1025
1091
dense_lines = [line_bytes]
1027
dense_lines.append('\n')
1028
size, bytes = self._record_to_data(key, digest,
1093
dense_lines.append(b'\n')
1094
size, data = self._record_to_data(key, digest,
1029
1095
lines, dense_lines)
1031
1097
# get mixed annotation + content and feed it into the
1033
1099
store_lines = self._factory.lower_fulltext(content)
1034
size, bytes = self._record_to_data(key, digest,
1100
size, data = self._record_to_data(key, digest,
1037
access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
1103
access_memo = self._access.add_raw_records([(key, size)], data)[0]
1038
1104
self._index.add_records(
1039
1105
((key, options, access_memo, parents),),
1040
1106
random_id=random_id)
1894
1947
# 4168 calls in 2880 217 internal
1895
1948
# 4168 calls to _parse_record_header in 2121
1896
1949
# 4168 calls to readlines in 330
1897
df = tuned_gzip.GzipFile(mode='rb', fileobj=StringIO(data))
1899
record_contents = df.readlines()
1900
except Exception, e:
1901
raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1902
(data, e.__class__.__name__, str(e)))
1903
header = record_contents.pop(0)
1904
rec = self._split_header(header)
1905
last_line = record_contents.pop()
1906
if len(record_contents) != int(rec[2]):
1907
raise KnitCorrupt(self,
1908
'incorrect number of lines %s != %s'
1909
' for version {%s} %s'
1910
% (len(record_contents), int(rec[2]),
1911
rec[1], record_contents))
1912
if last_line != 'end %s\n' % rec[1]:
1913
raise KnitCorrupt(self,
1914
'unexpected version end line %r, wanted %r'
1915
% (last_line, rec[1]))
1950
with gzip.GzipFile(mode='rb', fileobj=BytesIO(data)) as df:
1952
record_contents = df.readlines()
1953
except Exception as e:
1954
raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1955
(data, e.__class__.__name__, str(e)))
1956
header = record_contents.pop(0)
1957
rec = self._split_header(header)
1958
last_line = record_contents.pop()
1959
if len(record_contents) != int(rec[2]):
1960
raise KnitCorrupt(self,
1961
'incorrect number of lines %s != %s'
1962
' for version {%s} %s'
1963
% (len(record_contents), int(rec[2]),
1964
rec[1], record_contents))
1965
if last_line != b'end %s\n' % rec[1]:
1966
raise KnitCorrupt(self,
1967
'unexpected version end line %r, wanted %r'
1968
% (last_line, rec[1]))
1917
1969
return rec, record_contents
1919
1971
def _read_records_iter(self, records):
1985
2037
:param key: The key of the record. Currently keys are always serialised
1986
2038
using just the trailing component.
1987
2039
:param dense_lines: The bytes of lines but in a denser form. For
1988
instance, if lines is a list of 1000 bytestrings each ending in \n,
1989
dense_lines may be a list with one line in it, containing all the
1990
1000's lines and their \n's. Using dense_lines if it is already
1991
known is a win because the string join to create bytes in this
1992
function spends less time resizing the final string.
1993
:return: (len, a StringIO instance with the raw data ready to read.)
2040
instance, if lines is a list of 1000 bytestrings each ending in
2041
\\n, dense_lines may be a list with one line in it, containing all
2042
the 1000's lines and their \\n's. Using dense_lines if it is
2043
already known is a win because the string join to create bytes in
2044
this function spends less time resizing the final string.
2045
:return: (len, a BytesIO instance with the raw data ready to read.)
1995
chunks = ["version %s %d %s\n" % (key[-1], len(lines), digest)]
2047
chunks = [b"version %s %d %s\n" % (key[-1], len(lines), digest)]
1996
2048
chunks.extend(dense_lines or lines)
1997
chunks.append("end %s\n" % key[-1])
2049
chunks.append(b"end " + key[-1] + b"\n")
1998
2050
for chunk in chunks:
1999
if type(chunk) is not str:
2051
if not isinstance(chunk, bytes):
2000
2052
raise AssertionError(
2001
2053
'data must be plain bytes was %s' % type(chunk))
2002
if lines and lines[-1][-1] != '\n':
2054
if lines and not lines[-1].endswith(b'\n'):
2003
2055
raise ValueError('corrupt lines value %r' % lines)
2004
compressed_bytes = tuned_gzip.chunks_to_gzip(chunks)
2056
compressed_bytes = b''.join(tuned_gzip.chunks_to_gzip(chunks))
2005
2057
return len(compressed_bytes), compressed_bytes
2007
2059
def _split_header(self, line):
2175
2227
# one line with next ('' for None)
2176
2228
# one line with byte count of the record bytes
2177
2229
# the record bytes
2178
for key, (record_bytes, (method, noeol), next) in \
2179
self._raw_record_map.iteritems():
2180
key_bytes = '\x00'.join(key)
2230
for key, (record_bytes, (method, noeol), next) in viewitems(
2231
self._raw_record_map):
2232
key_bytes = b'\x00'.join(key)
2181
2233
parents = self.global_map.get(key, None)
2182
2234
if parents is None:
2183
parent_bytes = 'None:'
2235
parent_bytes = b'None:'
2185
parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2186
method_bytes = method
2237
parent_bytes = b'\t'.join(b'\x00'.join(key) for key in parents)
2238
method_bytes = method.encode('ascii')
2192
next_bytes = '\x00'.join(next)
2244
next_bytes = b'\x00'.join(next)
2195
map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2196
key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2197
len(record_bytes), record_bytes))
2198
map_bytes = ''.join(map_byte_list)
2247
map_byte_list.append(b'\n'.join(
2248
[key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2249
b'%d' % len(record_bytes), record_bytes]))
2250
map_bytes = b''.join(map_byte_list)
2199
2251
lines.append(map_bytes)
2200
bytes = '\n'.join(lines)
2252
bytes = b'\n'.join(lines)
2282
2334
end = len(bytes)
2283
2335
while start < end:
2284
2336
# 1 line with key
2285
line_end = bytes.find('\n', start)
2286
key = tuple(bytes[start:line_end].split('\x00'))
2337
line_end = bytes.find(b'\n', start)
2338
key = tuple(bytes[start:line_end].split(b'\x00'))
2287
2339
start = line_end + 1
2288
2340
# 1 line with parents (None: for None, '' for ())
2289
line_end = bytes.find('\n', start)
2341
line_end = bytes.find(b'\n', start)
2290
2342
line = bytes[start:line_end]
2343
if line == b'None:':
2294
2346
parents = tuple(
2295
[tuple(segment.split('\x00')) for segment in line.split('\t')
2347
tuple(segment.split(b'\x00')) for segment in line.split(b'\t')
2297
2349
self.global_map[key] = parents
2298
2350
start = line_end + 1
2299
2351
# one line with method
2300
line_end = bytes.find('\n', start)
2352
line_end = bytes.find(b'\n', start)
2301
2353
line = bytes[start:line_end]
2354
method = line.decode('ascii')
2303
2355
start = line_end + 1
2304
2356
# one line with noeol
2305
line_end = bytes.find('\n', start)
2357
line_end = bytes.find(b'\n', start)
2306
2358
line = bytes[start:line_end]
2359
noeol = line == b"T"
2308
2360
start = line_end + 1
2309
# one line with next ('' for None)
2310
line_end = bytes.find('\n', start)
2361
# one line with next (b'' for None)
2362
line_end = bytes.find(b'\n', start)
2311
2363
line = bytes[start:line_end]
2315
next = tuple(bytes[start:line_end].split('\x00'))
2367
next = tuple(bytes[start:line_end].split(b'\x00'))
2316
2368
start = line_end + 1
2317
2369
# one line with byte count of the record bytes
2318
line_end = bytes.find('\n', start)
2370
line_end = bytes.find(b'\n', start)
2319
2371
line = bytes[start:line_end]
2320
2372
count = int(line)
2321
2373
start = line_end + 1
2442
2494
for key, options, (_, pos, size), parents in path_keys:
2495
if not all(isinstance(option, bytes) for option in options):
2496
raise TypeError(options)
2443
2497
if parents is None:
2444
2498
# kndx indices cannot be parentless.
2446
line = "\n%s %s %s %s %s :" % (
2447
key[-1], ','.join(options), pos, size,
2448
self._dictionary_compress(parents))
2449
if type(line) is not str:
2501
b'\n' + key[-1], b','.join(options), b'%d' % pos, b'%d' % size,
2502
self._dictionary_compress(parents), b':'])
2503
if not isinstance(line, bytes):
2450
2504
raise AssertionError(
2451
2505
'data must be utf8 was %s' % type(line))
2452
2506
lines.append(line)
2453
2507
self._cache_key(key, options, pos, size, parents)
2454
2508
if len(orig_history):
2455
self._transport.append_bytes(path, ''.join(lines))
2509
self._transport.append_bytes(path, b''.join(lines))
2457
2511
self._init_index(path, lines)
2784
2837
def _split_key(self, key):
2785
2838
"""Split key into a prefix and suffix."""
2839
# GZ 2018-07-03: This is intentionally either a sequence or bytes?
2840
if isinstance(key, bytes):
2841
return key[:-1], key[-1:]
2786
2842
return key[:-1], key[-1]
2789
class _KeyRefs(object):
2791
def __init__(self, track_new_keys=False):
2792
# dict mapping 'key' to 'set of keys referring to that key'
2795
# set remembering all new keys
2796
self.new_keys = set()
2798
self.new_keys = None
2804
self.new_keys.clear()
2806
def add_references(self, key, refs):
2807
# Record the new references
2808
for referenced in refs:
2810
needed_by = self.refs[referenced]
2812
needed_by = self.refs[referenced] = set()
2814
# Discard references satisfied by the new key
2817
def get_new_keys(self):
2818
return self.new_keys
2820
def get_unsatisfied_refs(self):
2821
return self.refs.iterkeys()
2823
def _satisfy_refs_for_key(self, key):
2827
# No keys depended on this key. That's ok.
2830
def add_key(self, key):
2831
# satisfy refs for key, and remember that we've seen this key.
2832
self._satisfy_refs_for_key(key)
2833
if self.new_keys is not None:
2834
self.new_keys.add(key)
2836
def satisfy_refs_for_keys(self, keys):
2838
self._satisfy_refs_for_key(key)
2840
def get_referrers(self):
2842
for referrers in self.refs.itervalues():
2843
result.update(referrers)
2847
2845
class _KnitGraphIndex(object):
2848
2846
"""A KnitVersionedFiles index layered on GraphIndex."""
3281
class _DirectPackAccess(object):
3282
"""Access to data in one or more packs with less translation."""
3284
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
3285
"""Create a _DirectPackAccess object.
3287
:param index_to_packs: A dict mapping index objects to the transport
3288
and file names for obtaining data.
3289
:param reload_func: A function to call if we determine that the pack
3290
files have moved and we need to reload our caches. See
3291
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
3293
self._container_writer = None
3294
self._write_index = None
3295
self._indices = index_to_packs
3296
self._reload_func = reload_func
3297
self._flush_func = flush_func
3299
def add_raw_records(self, key_sizes, raw_data):
3300
"""Add raw knit bytes to a storage area.
3302
The data is spooled to the container writer in one bytes-record per
3305
:param sizes: An iterable of tuples containing the key and size of each
3307
:param raw_data: A bytestring containing the data.
3308
:return: A list of memos to retrieve the record later. Each memo is an
3309
opaque index memo. For _DirectPackAccess the memo is (index, pos,
3310
length), where the index field is the write_index object supplied
3311
to the PackAccess object.
3313
if type(raw_data) is not str:
3314
raise AssertionError(
3315
'data must be plain bytes was %s' % type(raw_data))
3318
for key, size in key_sizes:
3319
p_offset, p_length = self._container_writer.add_bytes_record(
3320
raw_data[offset:offset+size], [])
3322
result.append((self._write_index, p_offset, p_length))
3326
"""Flush pending writes on this access object.
3328
This will flush any buffered writes to a NewPack.
3330
if self._flush_func is not None:
3333
def get_raw_records(self, memos_for_retrieval):
3334
"""Get the raw bytes for a records.
3336
:param memos_for_retrieval: An iterable containing the (index, pos,
3337
length) memo for retrieving the bytes. The Pack access method
3338
looks up the pack to use for a given record in its index_to_pack
3340
:return: An iterator over the bytes of the records.
3342
# first pass, group into same-index requests
3344
current_index = None
3345
for (index, offset, length) in memos_for_retrieval:
3346
if current_index == index:
3347
current_list.append((offset, length))
3349
if current_index is not None:
3350
request_lists.append((current_index, current_list))
3351
current_index = index
3352
current_list = [(offset, length)]
3353
# handle the last entry
3354
if current_index is not None:
3355
request_lists.append((current_index, current_list))
3356
for index, offsets in request_lists:
3358
transport, path = self._indices[index]
3360
# A KeyError here indicates that someone has triggered an index
3361
# reload, and this index has gone missing, we need to start
3363
if self._reload_func is None:
3364
# If we don't have a _reload_func there is nothing that can
3367
raise errors.RetryWithNewPacks(index,
3368
reload_occurred=True,
3369
exc_info=sys.exc_info())
3371
reader = pack.make_readv_reader(transport, path, offsets)
3372
for names, read_func in reader.iter_records():
3373
yield read_func(None)
3374
except errors.NoSuchFile:
3375
# A NoSuchFile error indicates that a pack file has gone
3376
# missing on disk, we need to trigger a reload, and start over.
3377
if self._reload_func is None:
3379
raise errors.RetryWithNewPacks(transport.abspath(path),
3380
reload_occurred=False,
3381
exc_info=sys.exc_info())
3383
def set_writer(self, writer, index, transport_packname):
3384
"""Set a writer to use for adding data."""
3385
if index is not None:
3386
self._indices[index] = transport_packname
3387
self._container_writer = writer
3388
self._write_index = index
3390
def reload_or_raise(self, retry_exc):
3391
"""Try calling the reload function, or re-raise the original exception.
3393
This should be called after _DirectPackAccess raises a
3394
RetryWithNewPacks exception. This function will handle the common logic
3395
of determining when the error is fatal versus being temporary.
3396
It will also make sure that the original exception is raised, rather
3397
than the RetryWithNewPacks exception.
3399
If this function returns, then the calling function should retry
3400
whatever operation was being performed. Otherwise an exception will
3403
:param retry_exc: A RetryWithNewPacks exception.
3406
if self._reload_func is None:
3408
elif not self._reload_func():
3409
# The reload claimed that nothing changed
3410
if not retry_exc.reload_occurred:
3411
# If there wasn't an earlier reload, then we really were
3412
# expecting to find changes. We didn't find them, so this is a
3416
exc_class, exc_value, exc_traceback = retry_exc.exc_info
3417
raise exc_class, exc_value, exc_traceback
3420
# Deprecated, use PatienceSequenceMatcher instead
3421
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
3424
3279
def annotate_knit(knit, revision_id):
3425
3280
"""Annotate a knit with no cached annotations.