bzr branch
http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
1 |
# Copyright (C) 2007 Canonical Ltd
|
2 |
#
|
|
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.
|
|
7 |
#
|
|
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.
|
|
12 |
#
|
|
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
|
|
16 |
||
17 |
"""Indexing facilities."""
|
|
18 |
||
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
19 |
__all__ = [ |
20 |
'CombinedGraphIndex', |
|
21 |
'GraphIndex', |
|
22 |
'GraphIndexBuilder', |
|
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
23 |
'GraphIndexPrefixAdapter', |
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
24 |
'InMemoryGraphIndex', |
25 |
]
|
|
|
2592.1.32
by Robert Collins
Add __all__ to index. |
26 |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
27 |
from bisect import bisect_right |
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
28 |
from cStringIO import StringIO |
|
2592.1.12
by Robert Collins
Handle basic node adds. |
29 |
import re |
|
3789.1.3
by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count(). |
30 |
import sys |
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
31 |
|
|
2624.2.15
by Robert Collins
Add useful -Dindex flag. |
32 |
from bzrlib.lazy_import import lazy_import |
33 |
lazy_import(globals(), """ |
|
|
2745.1.2
by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly. |
34 |
from bzrlib import trace
|
|
2890.2.7
by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a |
35 |
from bzrlib.bisect_multi import bisect_multi_bytes
|
|
2979.2.2
by Robert Collins
Per-file graph heads detection during commit for pack repositories. |
36 |
from bzrlib.revision import NULL_REVISION
|
|
2745.1.2
by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly. |
37 |
from bzrlib.trace import mutter
|
|
2624.2.15
by Robert Collins
Add useful -Dindex flag. |
38 |
""") |
|
3099.3.3
by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map() |
39 |
from bzrlib import ( |
40 |
debug, |
|
41 |
errors, |
|
42 |
symbol_versioning, |
|
43 |
)
|
|
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
44 |
|
|
2979.1.1
by Robert Collins
Use the GraphIndex header to answer key_count queries rather than parsing the entire index unnecessarily. |
45 |
_HEADER_READV = (0, 200) |
|
2624.2.8
by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files. |
46 |
_OPTION_KEY_ELEMENTS = "key_elements=" |
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
47 |
_OPTION_LEN = "len=" |
|
2592.1.6
by Robert Collins
Record the number of node reference lists a particular index has. |
48 |
_OPTION_NODE_REFS = "node_ref_lists=" |
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
49 |
_SIGNATURE = "Bazaar Graph Index 1\n" |
50 |
||
51 |
||
|
2592.1.14
by Robert Collins
Detect bad reference key values. |
52 |
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]') |
|
2592.1.12
by Robert Collins
Handle basic node adds. |
53 |
_newline_null_re = re.compile('[\n\0]') |
54 |
||
55 |
||
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
56 |
class GraphIndexBuilder(object): |
|
2592.1.18
by Robert Collins
Add space to mark absent nodes. |
57 |
"""A builder that can build a GraphIndex. |
58 |
|
|
59 |
The resulting graph has the structure:
|
|
60 |
|
|
61 |
_SIGNATURE OPTIONS NODES NEWLINE
|
|
62 |
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
|
|
63 |
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
|
|
64 |
NODES := NODE*
|
|
65 |
NODE := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
|
|
66 |
KEY := Not-whitespace-utf8
|
|
67 |
ABSENT := 'a'
|
|
|
2592.1.19
by Robert Collins
Node references are tab separated. |
68 |
REFERENCES := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
|
69 |
REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
|
|
70 |
REFERENCE := DIGITS ; digits is the byte offset in the index of the
|
|
71 |
; referenced key.
|
|
|
2592.1.18
by Robert Collins
Add space to mark absent nodes. |
72 |
VALUE := no-newline-no-null-bytes
|
73 |
"""
|
|
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
74 |
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
75 |
def __init__(self, reference_lists=0, key_elements=1): |
|
2592.1.6
by Robert Collins
Record the number of node reference lists a particular index has. |
76 |
"""Create a GraphIndex builder. |
77 |
||
78 |
:param reference_lists: The number of node references lists for each
|
|
79 |
entry.
|
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
80 |
:param key_elements: The number of bytestrings in each key.
|
|
2592.1.6
by Robert Collins
Record the number of node reference lists a particular index has. |
81 |
"""
|
82 |
self.reference_lists = reference_lists |
|
|
2592.3.62
by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration. |
83 |
self._keys = set() |
|
3644.2.1
by John Arbash Meinel
Change the IndexBuilders to not generate the nodes_by_key unless needed. |
84 |
# A dict of {key: (absent, ref_lists, value)}
|
|
2592.1.15
by Robert Collins
Detect duplicate key insertion. |
85 |
self._nodes = {} |
|
3644.2.1
by John Arbash Meinel
Change the IndexBuilders to not generate the nodes_by_key unless needed. |
86 |
self._nodes_by_key = None |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
87 |
self._key_length = key_elements |
|
2624.2.5
by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings. |
88 |
|
89 |
def _check_key(self, key): |
|
90 |
"""Raise BadIndexKey if key is not a valid key for this index.""" |
|
91 |
if type(key) != tuple: |
|
92 |
raise errors.BadIndexKey(key) |
|
93 |
if self._key_length != len(key): |
|
94 |
raise errors.BadIndexKey(key) |
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
95 |
for element in key: |
96 |
if not element or _whitespace_re.search(element) is not None: |
|
97 |
raise errors.BadIndexKey(element) |
|
|
2592.1.12
by Robert Collins
Handle basic node adds. |
98 |
|
|
3644.2.4
by John Arbash Meinel
Change GraphIndex to also have a _get_nodes_by_key |
99 |
def _get_nodes_by_key(self): |
100 |
if self._nodes_by_key is None: |
|
101 |
nodes_by_key = {} |
|
102 |
if self.reference_lists: |
|
103 |
for key, (absent, references, value) in self._nodes.iteritems(): |
|
104 |
if absent: |
|
105 |
continue
|
|
106 |
key_dict = nodes_by_key |
|
107 |
for subkey in key[:-1]: |
|
108 |
key_dict = key_dict.setdefault(subkey, {}) |
|
109 |
key_dict[key[-1]] = key, value, references |
|
110 |
else: |
|
111 |
for key, (absent, references, value) in self._nodes.iteritems(): |
|
112 |
if absent: |
|
113 |
continue
|
|
114 |
key_dict = nodes_by_key |
|
115 |
for subkey in key[:-1]: |
|
116 |
key_dict = key_dict.setdefault(subkey, {}) |
|
117 |
key_dict[key[-1]] = key, value |
|
118 |
self._nodes_by_key = nodes_by_key |
|
119 |
return self._nodes_by_key |
|
120 |
||
|
3644.2.3
by John Arbash Meinel
Do a bit more work to get all the tests to pass. |
121 |
def _update_nodes_by_key(self, key, value, node_refs): |
122 |
"""Update the _nodes_by_key dict with a new key. |
|
123 |
||
124 |
For a key of (foo, bar, baz) create
|
|
125 |
_nodes_by_key[foo][bar][baz] = key_value
|
|
126 |
"""
|
|
127 |
if self._nodes_by_key is None: |
|
128 |
return
|
|
129 |
key_dict = self._nodes_by_key |
|
130 |
if self.reference_lists: |
|
131 |
key_value = key, value, node_refs |
|
132 |
else: |
|
133 |
key_value = key, value |
|
134 |
for subkey in key[:-1]: |
|
135 |
key_dict = key_dict.setdefault(subkey, {}) |
|
136 |
key_dict[key[-1]] = key_value |
|
137 |
||
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
138 |
def _check_key_ref_value(self, key, references, value): |
139 |
"""Check that 'key' and 'references' are all valid. |
|
|
2592.1.12
by Robert Collins
Handle basic node adds. |
140 |
|
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
141 |
:param key: A key tuple. Must conform to the key interface (be a tuple,
|
142 |
be of the right length, not have any whitespace or nulls in any key
|
|
143 |
element.)
|
|
144 |
:param references: An iterable of reference lists. Something like
|
|
145 |
[[(ref, key)], [(ref, key), (other, key)]]
|
|
146 |
:param value: The value associate with this key. Must not contain
|
|
147 |
newlines or null characters.
|
|
148 |
:return: (node_refs, absent_references)
|
|
149 |
node_refs basically a packed form of 'references' where all
|
|
150 |
iterables are tuples
|
|
151 |
absent_references reference keys that are not in self._nodes.
|
|
152 |
This may contain duplicates if the same key is
|
|
153 |
referenced in multiple lists.
|
|
|
2592.1.12
by Robert Collins
Handle basic node adds. |
154 |
"""
|
|
2624.2.5
by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings. |
155 |
self._check_key(key) |
|
2592.1.12
by Robert Collins
Handle basic node adds. |
156 |
if _newline_null_re.search(value) is not None: |
157 |
raise errors.BadIndexValue(value) |
|
|
2592.1.13
by Robert Collins
Handle mismatched numbers of reference lists. |
158 |
if len(references) != self.reference_lists: |
159 |
raise errors.BadIndexValue(references) |
|
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
160 |
node_refs = [] |
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
161 |
absent_references = [] |
|
2592.1.14
by Robert Collins
Detect bad reference key values. |
162 |
for reference_list in references: |
163 |
for reference in reference_list: |
|
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
164 |
# If reference *is* in self._nodes, then we know it has already
|
165 |
# been checked.
|
|
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
166 |
if reference not in self._nodes: |
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
167 |
self._check_key(reference) |
168 |
absent_references.append(reference) |
|
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
169 |
node_refs.append(tuple(reference_list)) |
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
170 |
return tuple(node_refs), absent_references |
171 |
||
172 |
def add_node(self, key, value, references=()): |
|
173 |
"""Add a node to the index. |
|
174 |
||
175 |
:param key: The key. keys are non-empty tuples containing
|
|
176 |
as many whitespace-free utf8 bytestrings as the key length
|
|
177 |
defined for this index.
|
|
178 |
:param references: An iterable of iterables of keys. Each is a
|
|
179 |
reference to another key.
|
|
180 |
:param value: The value to associate with the key. It may be any
|
|
181 |
bytes as long as it does not contain \0 or \n.
|
|
182 |
"""
|
|
183 |
(node_refs, |
|
184 |
absent_references) = self._check_key_ref_value(key, references, value) |
|
185 |
if key in self._nodes and self._nodes[key][0] != 'a': |
|
|
2592.1.15
by Robert Collins
Detect duplicate key insertion. |
186 |
raise errors.BadIndexDuplicateKey(key, self) |
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
187 |
for reference in absent_references: |
188 |
# There may be duplicates, but I don't think it is worth worrying
|
|
189 |
# about
|
|
190 |
self._nodes[reference] = ('a', (), '') |
|
|
3644.2.3
by John Arbash Meinel
Do a bit more work to get all the tests to pass. |
191 |
self._nodes[key] = ('', node_refs, value) |
|
2592.3.62
by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration. |
192 |
self._keys.add(key) |
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
193 |
if self._nodes_by_key is not None and self._key_length > 1: |
|
3644.2.3
by John Arbash Meinel
Do a bit more work to get all the tests to pass. |
194 |
self._update_nodes_by_key(key, value, node_refs) |
|
2592.1.6
by Robert Collins
Record the number of node reference lists a particular index has. |
195 |
|
|
2592.1.4
by Robert Collins
Create a GraphIndexBuilder. |
196 |
def finish(self): |
|
2592.1.6
by Robert Collins
Record the number of node reference lists a particular index has. |
197 |
lines = [_SIGNATURE] |
198 |
lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n') |
|
|
2624.2.8
by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files. |
199 |
lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n') |
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
200 |
lines.append(_OPTION_LEN + str(len(self._keys)) + '\n') |
|
2624.2.11
by Robert Collins
Review comments. |
201 |
prefix_length = sum(len(x) for x in lines) |
|
2592.1.22
by Robert Collins
Node references are byte offsets. |
202 |
# references are byte offsets. To avoid having to do nasty
|
|
3644.2.9
by John Arbash Meinel
Refactor some code. |
203 |
# polynomial work to resolve offsets (references to later in the
|
|
2592.1.22
by Robert Collins
Node references are byte offsets. |
204 |
# file cannot be determined until all the inbetween references have
|
205 |
# been calculated too) we pad the offsets with 0's to make them be
|
|
206 |
# of consistent length. Using binary offsets would break the trivial
|
|
207 |
# file parsing.
|
|
208 |
# to calculate the width of zero's needed we do three passes:
|
|
209 |
# one to gather all the non-reference data and the number of references.
|
|
210 |
# one to pad all the data with reference-length and determine entry
|
|
211 |
# addresses.
|
|
212 |
# One to serialise.
|
|
|
2592.1.40
by Robert Collins
Reverse index ordering - we do not have date prefixed revids. |
213 |
|
214 |
# forward sorted by key. In future we may consider topological sorting,
|
|
215 |
# at the cost of table scans for direct lookup, or a second index for
|
|
216 |
# direct lookup
|
|
217 |
nodes = sorted(self._nodes.items()) |
|
|
2592.1.42
by Robert Collins
Check the index length is as expected, when we have done preprocessing. |
218 |
# if we do not prepass, we don't know how long it will be up front.
|
219 |
expected_bytes = None |
|
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
220 |
# we only need to pre-pass if we have reference lists at all.
|
221 |
if self.reference_lists: |
|
|
2592.1.41
by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion. |
222 |
key_offset_info = [] |
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
223 |
non_ref_bytes = prefix_length |
224 |
total_references = 0 |
|
225 |
# TODO use simple multiplication for the constants in this loop.
|
|
226 |
for key, (absent, references, value) in nodes: |
|
|
2592.1.41
by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion. |
227 |
# record the offset known *so far* for this key:
|
228 |
# the non reference bytes to date, and the total references to
|
|
229 |
# date - saves reaccumulating on the second pass
|
|
230 |
key_offset_info.append((key, non_ref_bytes, total_references)) |
|
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
231 |
# key is literal, value is literal, there are 3 null's, 1 NL
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
232 |
# key is variable length tuple, \x00 between elements
|
|
2624.2.5
by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings. |
233 |
non_ref_bytes += sum(len(element) for element in key) |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
234 |
if self._key_length > 1: |
235 |
non_ref_bytes += self._key_length - 1 |
|
|
2624.2.5
by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings. |
236 |
# value is literal bytes, there are 3 null's, 1 NL.
|
237 |
non_ref_bytes += len(value) + 3 + 1 |
|
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
238 |
# one byte for absent if set.
|
239 |
if absent: |
|
240 |
non_ref_bytes += 1 |
|
|
2592.1.36
by Robert Collins
Bugfix incorrect offset generation when an absent record is before a referenced record. |
241 |
elif self.reference_lists: |
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
242 |
# (ref_lists -1) tabs
|
243 |
non_ref_bytes += self.reference_lists - 1 |
|
244 |
# (ref-1 cr's per ref_list)
|
|
245 |
for ref_list in references: |
|
246 |
# how many references across the whole file?
|
|
247 |
total_references += len(ref_list) |
|
248 |
# accrue reference separators
|
|
249 |
if ref_list: |
|
250 |
non_ref_bytes += len(ref_list) - 1 |
|
251 |
# how many digits are needed to represent the total byte count?
|
|
252 |
digits = 1 |
|
|
2592.1.22
by Robert Collins
Node references are byte offsets. |
253 |
possible_total_bytes = non_ref_bytes + total_references*digits |
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
254 |
while 10 ** digits < possible_total_bytes: |
255 |
digits += 1 |
|
256 |
possible_total_bytes = non_ref_bytes + total_references*digits |
|
|
2592.1.42
by Robert Collins
Check the index length is as expected, when we have done preprocessing. |
257 |
expected_bytes = possible_total_bytes + 1 # terminating newline |
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
258 |
# resolve key addresses.
|
259 |
key_addresses = {} |
|
|
2592.1.41
by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion. |
260 |
for key, non_ref_bytes, total_references in key_offset_info: |
261 |
key_addresses[key] = non_ref_bytes + total_references*digits |
|
|
2592.1.25
by Robert Collins
Fix and tune node offset calculation. |
262 |
# serialise
|
263 |
format_string = '%%0%sd' % digits |
|
264 |
for key, (absent, references, value) in nodes: |
|
|
2592.1.19
by Robert Collins
Node references are tab separated. |
265 |
flattened_references = [] |
266 |
for ref_list in references: |
|
|
2592.1.22
by Robert Collins
Node references are byte offsets. |
267 |
ref_addresses = [] |
268 |
for reference in ref_list: |
|
269 |
ref_addresses.append(format_string % key_addresses[reference]) |
|
270 |
flattened_references.append('\r'.join(ref_addresses)) |
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
271 |
string_key = '\x00'.join(key) |
|
2624.2.11
by Robert Collins
Review comments. |
272 |
lines.append("%s\x00%s\x00%s\x00%s\n" % (string_key, absent, |
|
2592.1.19
by Robert Collins
Node references are tab separated. |
273 |
'\t'.join(flattened_references), value)) |
|
2592.1.6
by Robert Collins
Record the number of node reference lists a particular index has. |
274 |
lines.append('\n') |
|
2592.1.42
by Robert Collins
Check the index length is as expected, when we have done preprocessing. |
275 |
result = StringIO(''.join(lines)) |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
276 |
if expected_bytes and len(result.getvalue()) != expected_bytes: |
277 |
raise errors.BzrError('Failed index creation. Internal error:' |
|
278 |
' mismatched output length and expected length: %d %d' % |
|
279 |
(len(result.getvalue()), expected_bytes)) |
|
|
3498.1.1
by James Westby
Don't join the lines of the index twice. |
280 |
return result |
|
2592.1.5
by Robert Collins
Trivial index reading. |
281 |
|
282 |
||
283 |
class GraphIndex(object): |
|
284 |
"""An index for data with embedded graphs. |
|
|
2592.1.10
by Robert Collins
Make validate detect node reference parsing errors. |
285 |
|
286 |
The index maps keys to a list of key reference lists, and a value.
|
|
287 |
Each node has the same number of key reference lists. Each key reference
|
|
288 |
list can be empty or an arbitrary length. The value is an opaque NULL
|
|
|
2592.1.45
by Robert Collins
Tweak documentation as per Aaron's review. |
289 |
terminated string without any newlines. The storage of the index is
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
290 |
hidden in the interface: keys and key references are always tuples of
|
291 |
bytestrings, never the internal representation (e.g. dictionary offsets).
|
|
|
2592.1.30
by Robert Collins
Absent entries are not yeilded. |
292 |
|
293 |
It is presumed that the index will not be mutated - it is static data.
|
|
|
2592.1.34
by Robert Collins
Cleanup docs. |
294 |
|
|
2592.1.44
by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review. |
295 |
Successive iter_all_entries calls will read the entire index each time.
|
296 |
Additionally, iter_entries calls will read the index linearly until the
|
|
297 |
desired keys are found. XXX: This must be fixed before the index is
|
|
|
2592.1.34
by Robert Collins
Cleanup docs. |
298 |
suitable for production use. :XXX
|
|
2592.1.5
by Robert Collins
Trivial index reading. |
299 |
"""
|
300 |
||
|
2890.2.1
by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the |
301 |
def __init__(self, transport, name, size): |
|
2592.1.5
by Robert Collins
Trivial index reading. |
302 |
"""Open an index called name on transport. |
303 |
||
304 |
:param transport: A bzrlib.transport.Transport.
|
|
305 |
:param name: A path to provide to transport API calls.
|
|
|
2890.2.1
by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the |
306 |
:param size: The size of the index in bytes. This is used for bisection
|
307 |
logic to perform partial index reads. While the size could be
|
|
308 |
obtained by statting the file this introduced an additional round
|
|
|
2890.2.8
by Robert Collins
Make the size of the index optionally None for the pack-names index. |
309 |
trip as well as requiring stat'able transports, both of which are
|
310 |
avoided by having it supplied. If size is None, then bisection
|
|
311 |
support will be disabled and accessing the index will just stream
|
|
312 |
all the data.
|
|
|
2592.1.5
by Robert Collins
Trivial index reading. |
313 |
"""
|
314 |
self._transport = transport |
|
315 |
self._name = name |
|
|
2890.2.16
by Robert Collins
Review feedback. |
316 |
# Becomes a dict of key:(value, reference-list-byte-locations) used by
|
317 |
# the bisection interface to store parsed but not resolved keys.
|
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
318 |
self._bisect_nodes = None |
|
2890.2.16
by Robert Collins
Review feedback. |
319 |
# Becomes a dict of key:(value, reference-list-keys) which are ready to
|
320 |
# be returned directly to callers.
|
|
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
321 |
self._nodes = None |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
322 |
# a sorted list of slice-addresses for the parsed bytes of the file.
|
323 |
# e.g. (0,1) would mean that byte 0 is parsed.
|
|
|
2890.2.2
by Robert Collins
Opening an index creates a map for the parsed bytes. |
324 |
self._parsed_byte_map = [] |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
325 |
# a sorted list of keys matching each slice address for parsed bytes
|
326 |
# e.g. (None, 'foo@bar') would mean that the first byte contained no
|
|
327 |
# key, and the end byte of the slice is the of the data for 'foo@bar'
|
|
328 |
self._parsed_key_map = [] |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
329 |
self._key_count = None |
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
330 |
self._keys_by_offset = None |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
331 |
self._nodes_by_key = None |
|
2890.2.1
by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the |
332 |
self._size = size |
|
3665.3.3
by John Arbash Meinel
If we read more than 50% of the whole index, |
333 |
# The number of bytes we've read so far in trying to process this file
|
334 |
self._bytes_read = 0 |
|
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
335 |
|
|
2592.3.176
by Robert Collins
Various pack refactorings. |
336 |
def __eq__(self, other): |
|
2592.3.215
by Robert Collins
Review feedback. |
337 |
"""Equal when self and other were created with the same parameters.""" |
|
2592.3.176
by Robert Collins
Various pack refactorings. |
338 |
return ( |
339 |
type(self) == type(other) and |
|
340 |
self._transport == other._transport and |
|
341 |
self._name == other._name and |
|
342 |
self._size == other._size) |
|
343 |
||
344 |
def __ne__(self, other): |
|
345 |
return not self.__eq__(other) |
|
346 |
||
|
3517.4.13
by Martin Pool
Add repr methods |
347 |
def __repr__(self): |
348 |
return "%s(%r)" % (self.__class__.__name__, |
|
349 |
self._transport.abspath(self._name)) |
|
350 |
||
|
3665.3.1
by John Arbash Meinel
Updates to GraphIndex processing. |
351 |
def _buffer_all(self, stream=None): |
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
352 |
"""Buffer all the index data. |
353 |
||
354 |
Mutates self._nodes and self.keys_by_offset.
|
|
|
2592.1.5
by Robert Collins
Trivial index reading. |
355 |
"""
|
|
3665.3.1
by John Arbash Meinel
Updates to GraphIndex processing. |
356 |
if self._nodes is not None: |
357 |
# We already did this
|
|
358 |
return
|
|
|
2624.2.15
by Robert Collins
Add useful -Dindex flag. |
359 |
if 'index' in debug.debug_flags: |
360 |
mutter('Reading entire index %s', self._transport.abspath(self._name)) |
|
|
3665.3.1
by John Arbash Meinel
Updates to GraphIndex processing. |
361 |
if stream is None: |
362 |
stream = self._transport.get(self._name) |
|
|
2592.1.27
by Robert Collins
Test missing end lines with non-empty indices. |
363 |
self._read_prefix(stream) |
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
364 |
self._expected_elements = 3 + self._key_length |
|
2592.1.27
by Robert Collins
Test missing end lines with non-empty indices. |
365 |
line_count = 0 |
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
366 |
# raw data keyed by offset
|
367 |
self._keys_by_offset = {} |
|
368 |
# ready-to-return key:value or key:value, node_ref_lists
|
|
369 |
self._nodes = {} |
|
|
3711.3.13
by John Arbash Meinel
Shave off another 5s by not building 'node_by_key' |
370 |
self._nodes_by_key = None |
|
2592.1.27
by Robert Collins
Test missing end lines with non-empty indices. |
371 |
trailers = 0 |
372 |
pos = stream.tell() |
|
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
373 |
lines = stream.read().split('\n') |
374 |
del lines[-1] |
|
375 |
_, _, _, trailers = self._parse_lines(lines, pos) |
|
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
376 |
for key, absent, references, value in self._keys_by_offset.itervalues(): |
|
2592.1.30
by Robert Collins
Absent entries are not yeilded. |
377 |
if absent: |
378 |
continue
|
|
|
2592.1.28
by Robert Collins
Basic two pass iter_all_entries. |
379 |
# resolve references:
|
380 |
if self.node_ref_lists: |
|
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
381 |
node_value = (value, self._resolve_references(references)) |
|
2592.1.28
by Robert Collins
Basic two pass iter_all_entries. |
382 |
else: |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
383 |
node_value = value |
384 |
self._nodes[key] = node_value |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
385 |
# cache the keys for quick set intersections
|
|
2592.3.54
by Robert Collins
Fix remaining performance discrepancy with regular repositories. |
386 |
self._keys = set(self._nodes) |
|
2592.1.27
by Robert Collins
Test missing end lines with non-empty indices. |
387 |
if trailers != 1: |
388 |
# there must be one line - the empty trailer line.
|
|
389 |
raise errors.BadIndexData(self) |
|
390 |
||
|
3711.3.21
by John Arbash Meinel
Fix GraphIndex to properly generate _nodes_by_keys on demand. |
391 |
def _get_nodes_by_key(self): |
392 |
if self._nodes_by_key is None: |
|
393 |
nodes_by_key = {} |
|
394 |
if self.node_ref_lists: |
|
395 |
for key, (value, references) in self._nodes.iteritems(): |
|
396 |
key_dict = nodes_by_key |
|
397 |
for subkey in key[:-1]: |
|
398 |
key_dict = key_dict.setdefault(subkey, {}) |
|
399 |
key_dict[key[-1]] = key, value, references |
|
400 |
else: |
|
401 |
for key, value in self._nodes.iteritems(): |
|
402 |
key_dict = nodes_by_key |
|
403 |
for subkey in key[:-1]: |
|
404 |
key_dict = key_dict.setdefault(subkey, {}) |
|
405 |
key_dict[key[-1]] = key, value |
|
406 |
self._nodes_by_key = nodes_by_key |
|
407 |
return self._nodes_by_key |
|
408 |
||
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
409 |
def iter_all_entries(self): |
410 |
"""Iterate over all keys within the index. |
|
411 |
||
|
2592.5.1
by Martin Pool
Fix docstrings for Index.iter_entries etc |
412 |
:return: An iterable of (index, key, value) or (index, key, value, reference_lists).
|
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
413 |
The former tuple is used when there are no reference lists in the
|
414 |
index, making the API compatible with simple key:value index types.
|
|
415 |
There is no defined order for the result iteration - it will be in
|
|
416 |
the most efficient order for the index.
|
|
417 |
"""
|
|
|
2745.1.1
by Robert Collins
Add a number of -Devil checkpoints. |
418 |
if 'evil' in debug.debug_flags: |
|
2592.3.112
by Robert Collins
Various fixups found dogfooding. |
419 |
trace.mutter_callsite(3, |
|
2745.1.2
by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly. |
420 |
"iter_all_entries scales with size of history.") |
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
421 |
if self._nodes is None: |
422 |
self._buffer_all() |
|
423 |
if self.node_ref_lists: |
|
424 |
for key, (value, node_ref_lists) in self._nodes.iteritems(): |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
425 |
yield self, key, value, node_ref_lists |
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
426 |
else: |
427 |
for key, value in self._nodes.iteritems(): |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
428 |
yield self, key, value |
|
2624.2.2
by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram. |
429 |
|
|
2592.1.27
by Robert Collins
Test missing end lines with non-empty indices. |
430 |
def _read_prefix(self, stream): |
431 |
signature = stream.read(len(self._signature())) |
|
432 |
if not signature == self._signature(): |
|
433 |
raise errors.BadIndexFormatSignature(self._name, GraphIndex) |
|
434 |
options_line = stream.readline() |
|
435 |
if not options_line.startswith(_OPTION_NODE_REFS): |
|
436 |
raise errors.BadIndexOptions(self) |
|
437 |
try: |
|
438 |
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1]) |
|
439 |
except ValueError: |
|
440 |
raise errors.BadIndexOptions(self) |
|
|
2624.2.8
by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files. |
441 |
options_line = stream.readline() |
442 |
if not options_line.startswith(_OPTION_KEY_ELEMENTS): |
|
443 |
raise errors.BadIndexOptions(self) |
|
444 |
try: |
|
445 |
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1]) |
|
446 |
except ValueError: |
|
447 |
raise errors.BadIndexOptions(self) |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
448 |
options_line = stream.readline() |
449 |
if not options_line.startswith(_OPTION_LEN): |
|
450 |
raise errors.BadIndexOptions(self) |
|
451 |
try: |
|
452 |
self._key_count = int(options_line[len(_OPTION_LEN):-1]) |
|
453 |
except ValueError: |
|
454 |
raise errors.BadIndexOptions(self) |
|
|
2592.1.5
by Robert Collins
Trivial index reading. |
455 |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
456 |
def _resolve_references(self, references): |
|
2890.2.16
by Robert Collins
Review feedback. |
457 |
"""Return the resolved key references for references. |
458 |
|
|
459 |
References are resolved by looking up the location of the key in the
|
|
460 |
_keys_by_offset map and substituting the key name, preserving ordering.
|
|
461 |
||
462 |
:param references: An iterable of iterables of key locations. e.g.
|
|
463 |
[[123, 456], [123]]
|
|
464 |
:return: A tuple of tuples of keys.
|
|
465 |
"""
|
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
466 |
node_refs = [] |
467 |
for ref_list in references: |
|
468 |
node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list])) |
|
469 |
return tuple(node_refs) |
|
470 |
||
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
471 |
def _find_index(self, range_map, key): |
472 |
"""Helper for the _parsed_*_index calls. |
|
473 |
||
474 |
Given a range map - [(start, end), ...], finds the index of the range
|
|
475 |
in the map for key if it is in the map, and if it is not there, the
|
|
476 |
immediately preceeding range in the map.
|
|
477 |
"""
|
|
478 |
result = bisect_right(range_map, key) - 1 |
|
479 |
if result + 1 < len(range_map): |
|
480 |
# check the border condition, it may be in result + 1
|
|
481 |
if range_map[result + 1][0] == key[0]: |
|
482 |
return result + 1 |
|
483 |
return result |
|
484 |
||
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
485 |
def _parsed_byte_index(self, offset): |
486 |
"""Return the index of the entry immediately before offset. |
|
487 |
||
488 |
e.g. if the parsed map has regions 0,10 and 11,12 parsed, meaning that
|
|
489 |
there is one unparsed byte (the 11th, addressed as[10]). then:
|
|
490 |
asking for 0 will return 0
|
|
491 |
asking for 10 will return 0
|
|
492 |
asking for 11 will return 1
|
|
493 |
asking for 12 will return 1
|
|
494 |
"""
|
|
495 |
key = (offset, 0) |
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
496 |
return self._find_index(self._parsed_byte_map, key) |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
497 |
|
498 |
def _parsed_key_index(self, key): |
|
499 |
"""Return the index of the entry immediately before key. |
|
500 |
||
501 |
e.g. if the parsed map has regions (None, 'a') and ('b','c') parsed,
|
|
502 |
meaning that keys from None to 'a' inclusive, and 'b' to 'c' inclusive
|
|
503 |
have been parsed, then:
|
|
504 |
asking for '' will return 0
|
|
505 |
asking for 'a' will return 0
|
|
506 |
asking for 'b' will return 1
|
|
507 |
asking for 'e' will return 1
|
|
508 |
"""
|
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
509 |
search_key = (key, None) |
510 |
return self._find_index(self._parsed_key_map, search_key) |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
511 |
|
512 |
def _is_parsed(self, offset): |
|
513 |
"""Returns True if offset has been parsed.""" |
|
514 |
index = self._parsed_byte_index(offset) |
|
515 |
if index == len(self._parsed_byte_map): |
|
516 |
return offset < self._parsed_byte_map[index - 1][1] |
|
517 |
start, end = self._parsed_byte_map[index] |
|
518 |
return offset >= start and offset < end |
|
519 |
||
|
2890.2.7
by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a |
520 |
def _iter_entries_from_total_buffer(self, keys): |
521 |
"""Iterate over keys when the entire index is parsed.""" |
|
|
2592.3.54
by Robert Collins
Fix remaining performance discrepancy with regular repositories. |
522 |
keys = keys.intersection(self._keys) |
|
2624.2.3
by Robert Collins
Make GraphIndex.iter_entries do hash lookups rather than table scans. |
523 |
if self.node_ref_lists: |
524 |
for key in keys: |
|
525 |
value, node_refs = self._nodes[key] |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
526 |
yield self, key, value, node_refs |
|
2624.2.3
by Robert Collins
Make GraphIndex.iter_entries do hash lookups rather than table scans. |
527 |
else: |
528 |
for key in keys: |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
529 |
yield self, key, self._nodes[key] |
|
2592.1.7
by Robert Collins
A validate that goes boom. |
530 |
|
|
2890.2.7
by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a |
531 |
def iter_entries(self, keys): |
532 |
"""Iterate over keys within the index. |
|
533 |
||
534 |
:param keys: An iterable providing the keys to be retrieved.
|
|
535 |
:return: An iterable as per iter_all_entries, but restricted to the
|
|
536 |
keys supplied. No additional keys will be returned, and every
|
|
537 |
key supplied that is in the index will be returned.
|
|
538 |
"""
|
|
539 |
keys = set(keys) |
|
540 |
if not keys: |
|
541 |
return [] |
|
|
2890.2.8
by Robert Collins
Make the size of the index optionally None for the pack-names index. |
542 |
if self._size is None and self._nodes is None: |
543 |
self._buffer_all() |
|
|
3665.3.3
by John Arbash Meinel
If we read more than 50% of the whole index, |
544 |
|
|
3606.6.1
by Robert Collins
Cherry-pick Robert's index buffering. |
545 |
# We fit about 20 keys per minimum-read (4K), so if we are looking for
|
546 |
# more than 1/20th of the index its likely (assuming homogenous key
|
|
547 |
# spread) that we'll read the entire index. If we're going to do that,
|
|
548 |
# buffer the whole thing. A better analysis might take key spread into
|
|
549 |
# account - but B+Tree indices are better anyway.
|
|
550 |
# We could look at all data read, and use a threshold there, which will
|
|
551 |
# trigger on ancestry walks, but that is not yet fully mapped out.
|
|
552 |
if self._nodes is None and len(keys) * 20 > self.key_count(): |
|
553 |
self._buffer_all() |
|
|
2890.2.7
by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a |
554 |
if self._nodes is not None: |
555 |
return self._iter_entries_from_total_buffer(keys) |
|
556 |
else: |
|
557 |
return (result[1] for result in bisect_multi_bytes( |
|
|
2890.2.18
by Robert Collins
Review feedback. |
558 |
self._lookup_keys_via_location, self._size, keys)) |
|
2890.2.7
by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a |
559 |
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
560 |
def iter_entries_prefix(self, keys): |
561 |
"""Iterate over keys within the index using prefix matching. |
|
562 |
||
563 |
Prefix matching is applied within the tuple of a key, not to within
|
|
564 |
the bytestring of each key element. e.g. if you have the keys ('foo',
|
|
565 |
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
|
|
566 |
only the former key is returned.
|
|
567 |
||
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
568 |
WARNING: Note that this method currently causes a full index parse
|
569 |
unconditionally (which is reasonably appropriate as it is a means for
|
|
570 |
thunking many small indices into one larger one and still supplies
|
|
571 |
iter_all_entries at the thunk layer).
|
|
572 |
||
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
573 |
:param keys: An iterable providing the key prefixes to be retrieved.
|
574 |
Each key prefix takes the form of a tuple the length of a key, but
|
|
575 |
with the last N elements 'None' rather than a regular bytestring.
|
|
576 |
The first element cannot be 'None'.
|
|
577 |
:return: An iterable as per iter_all_entries, but restricted to the
|
|
578 |
keys with a matching prefix to those supplied. No additional keys
|
|
579 |
will be returned, and every match that is in the index will be
|
|
580 |
returned.
|
|
581 |
"""
|
|
582 |
keys = set(keys) |
|
583 |
if not keys: |
|
584 |
return
|
|
585 |
# load data - also finds key lengths
|
|
586 |
if self._nodes is None: |
|
587 |
self._buffer_all() |
|
588 |
if self._key_length == 1: |
|
589 |
for key in keys: |
|
590 |
# sanity check
|
|
591 |
if key[0] is None: |
|
592 |
raise errors.BadIndexKey(key) |
|
593 |
if len(key) != self._key_length: |
|
594 |
raise errors.BadIndexKey(key) |
|
595 |
if self.node_ref_lists: |
|
596 |
value, node_refs = self._nodes[key] |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
597 |
yield self, key, value, node_refs |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
598 |
else: |
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
599 |
yield self, key, self._nodes[key] |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
600 |
return
|
|
3711.3.21
by John Arbash Meinel
Fix GraphIndex to properly generate _nodes_by_keys on demand. |
601 |
nodes_by_key = self._get_nodes_by_key() |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
602 |
for key in keys: |
603 |
# sanity check
|
|
604 |
if key[0] is None: |
|
605 |
raise errors.BadIndexKey(key) |
|
606 |
if len(key) != self._key_length: |
|
607 |
raise errors.BadIndexKey(key) |
|
608 |
# find what it refers to:
|
|
|
3711.3.21
by John Arbash Meinel
Fix GraphIndex to properly generate _nodes_by_keys on demand. |
609 |
key_dict = nodes_by_key |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
610 |
elements = list(key) |
|
2624.2.11
by Robert Collins
Review comments. |
611 |
# find the subdict whose contents should be returned.
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
612 |
try: |
613 |
while len(elements) and elements[0] is not None: |
|
614 |
key_dict = key_dict[elements[0]] |
|
615 |
elements.pop(0) |
|
616 |
except KeyError: |
|
617 |
# a non-existant lookup.
|
|
618 |
continue
|
|
619 |
if len(elements): |
|
620 |
dicts = [key_dict] |
|
621 |
while dicts: |
|
622 |
key_dict = dicts.pop(-1) |
|
623 |
# can't be empty or would not exist
|
|
624 |
item, value = key_dict.iteritems().next() |
|
625 |
if type(value) == dict: |
|
626 |
# push keys
|
|
627 |
dicts.extend(key_dict.itervalues()) |
|
628 |
else: |
|
629 |
# yield keys
|
|
630 |
for value in key_dict.itervalues(): |
|
|
2624.2.11
by Robert Collins
Review comments. |
631 |
# each value is the key:value:node refs tuple
|
632 |
# ready to yield.
|
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
633 |
yield (self, ) + value |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
634 |
else: |
|
2624.2.11
by Robert Collins
Review comments. |
635 |
# the last thing looked up was a terminal element
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
636 |
yield (self, ) + key_dict |
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
637 |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
638 |
def key_count(self): |
639 |
"""Return an estimate of the number of keys in this index. |
|
640 |
|
|
641 |
For GraphIndex the estimate is exact.
|
|
642 |
"""
|
|
643 |
if self._key_count is None: |
|
|
2979.1.1
by Robert Collins
Use the GraphIndex header to answer key_count queries rather than parsing the entire index unnecessarily. |
644 |
self._read_and_parse([_HEADER_READV]) |
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
645 |
return self._key_count |
646 |
||
|
2890.2.18
by Robert Collins
Review feedback. |
647 |
def _lookup_keys_via_location(self, location_keys): |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
648 |
"""Public interface for implementing bisection. |
649 |
||
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
650 |
If _buffer_all has been called, then all the data for the index is in
|
651 |
memory, and this method should not be called, as it uses a separate
|
|
652 |
cache because it cannot pre-resolve all indices, which buffer_all does
|
|
653 |
for performance.
|
|
654 |
||
|
2890.2.16
by Robert Collins
Review feedback. |
655 |
:param location_keys: A list of location(byte offset), key tuples.
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
656 |
:return: A list of (location_key, result) tuples as expected by
|
657 |
bzrlib.bisect_multi.bisect_multi_bytes.
|
|
658 |
"""
|
|
659 |
# Possible improvements:
|
|
660 |
# - only bisect lookup each key once
|
|
661 |
# - sort the keys first, and use that to reduce the bisection window
|
|
662 |
# -----
|
|
663 |
# this progresses in three parts:
|
|
664 |
# read data
|
|
665 |
# parse it
|
|
666 |
# attempt to answer the question from the now in memory data.
|
|
667 |
# build the readv request
|
|
668 |
# for each location, ask for 800 bytes - much more than rows we've seen
|
|
669 |
# anywhere.
|
|
670 |
readv_ranges = [] |
|
671 |
for location, key in location_keys: |
|
672 |
# can we answer from cache?
|
|
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
673 |
if self._bisect_nodes and key in self._bisect_nodes: |
674 |
# We have the key parsed.
|
|
675 |
continue
|
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
676 |
index = self._parsed_key_index(key) |
677 |
if (len(self._parsed_key_map) and |
|
678 |
self._parsed_key_map[index][0] <= key and |
|
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
679 |
(self._parsed_key_map[index][1] >= key or |
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
680 |
# end of the file has been parsed
|
681 |
self._parsed_byte_map[index][1] == self._size)): |
|
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
682 |
# the key has been parsed, so no lookup is needed even if its
|
683 |
# not present.
|
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
684 |
continue
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
685 |
# - if we have examined this part of the file already - yes
|
686 |
index = self._parsed_byte_index(location) |
|
687 |
if (len(self._parsed_byte_map) and |
|
688 |
self._parsed_byte_map[index][0] <= location and |
|
689 |
self._parsed_byte_map[index][1] > location): |
|
690 |
# the byte region has been parsed, so no read is needed.
|
|
691 |
continue
|
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
692 |
length = 800 |
693 |
if location + length > self._size: |
|
694 |
length = self._size - location |
|
695 |
# todo, trim out parsed locations.
|
|
696 |
if length > 0: |
|
697 |
readv_ranges.append((location, length)) |
|
698 |
# read the header if needed
|
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
699 |
if self._bisect_nodes is None: |
|
2979.1.1
by Robert Collins
Use the GraphIndex header to answer key_count queries rather than parsing the entire index unnecessarily. |
700 |
readv_ranges.append(_HEADER_READV) |
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
701 |
self._read_and_parse(readv_ranges) |
|
3665.3.1
by John Arbash Meinel
Updates to GraphIndex processing. |
702 |
result = [] |
703 |
if self._nodes is not None: |
|
704 |
# _read_and_parse triggered a _buffer_all because we requested the
|
|
705 |
# whole data range
|
|
706 |
for location, key in location_keys: |
|
707 |
if key not in self._nodes: # not present |
|
708 |
result.append(((location, key), False)) |
|
709 |
elif self.node_ref_lists: |
|
710 |
value, refs = self._nodes[key] |
|
711 |
result.append(((location, key), |
|
712 |
(self, key, value, refs))) |
|
713 |
else: |
|
714 |
result.append(((location, key), |
|
715 |
(self, key, self._nodes[key]))) |
|
716 |
return result |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
717 |
# generate results:
|
718 |
# - figure out <, >, missing, present
|
|
719 |
# - result present references so we can return them.
|
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
720 |
# keys that we cannot answer until we resolve references
|
721 |
pending_references = [] |
|
722 |
pending_locations = set() |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
723 |
for location, key in location_keys: |
724 |
# can we answer from cache?
|
|
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
725 |
if key in self._bisect_nodes: |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
726 |
# the key has been parsed, so no lookup is needed
|
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
727 |
if self.node_ref_lists: |
728 |
# the references may not have been all parsed.
|
|
729 |
value, refs = self._bisect_nodes[key] |
|
730 |
wanted_locations = [] |
|
731 |
for ref_list in refs: |
|
732 |
for ref in ref_list: |
|
733 |
if ref not in self._keys_by_offset: |
|
734 |
wanted_locations.append(ref) |
|
735 |
if wanted_locations: |
|
736 |
pending_locations.update(wanted_locations) |
|
737 |
pending_references.append((location, key)) |
|
738 |
continue
|
|
739 |
result.append(((location, key), (self, key, |
|
740 |
value, self._resolve_references(refs)))) |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
741 |
else: |
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
742 |
result.append(((location, key), |
743 |
(self, key, self._bisect_nodes[key]))) |
|
744 |
continue
|
|
745 |
else: |
|
746 |
# has the region the key should be in, been parsed?
|
|
747 |
index = self._parsed_key_index(key) |
|
748 |
if (self._parsed_key_map[index][0] <= key and |
|
749 |
(self._parsed_key_map[index][1] >= key or |
|
750 |
# end of the file has been parsed
|
|
751 |
self._parsed_byte_map[index][1] == self._size)): |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
752 |
result.append(((location, key), False)) |
|
2911.3.1
by Robert Collins
(robertc) Improve index bisection lookup performance looking for keys in the parsed dict before doing bisection searches in the parsed ranges. (Robert Collins). |
753 |
continue
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
754 |
# no, is the key above or below the probed location:
|
755 |
# get the range of the probed & parsed location
|
|
756 |
index = self._parsed_byte_index(location) |
|
757 |
# if the key is below the start of the range, its below
|
|
758 |
if key < self._parsed_key_map[index][0]: |
|
759 |
direction = -1 |
|
760 |
else: |
|
761 |
direction = +1 |
|
762 |
result.append(((location, key), direction)) |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
763 |
readv_ranges = [] |
764 |
# lookup data to resolve references
|
|
765 |
for location in pending_locations: |
|
766 |
length = 800 |
|
767 |
if location + length > self._size: |
|
768 |
length = self._size - location |
|
769 |
# TODO: trim out parsed locations (e.g. if the 800 is into the
|
|
|
2890.2.16
by Robert Collins
Review feedback. |
770 |
# parsed region trim it, and dont use the adjust_for_latency
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
771 |
# facility)
|
772 |
if length > 0: |
|
773 |
readv_ranges.append((location, length)) |
|
774 |
self._read_and_parse(readv_ranges) |
|
|
3665.3.5
by John Arbash Meinel
Move the point at which we 'buffer_all' if we've read >50% of the index. |
775 |
if self._nodes is not None: |
776 |
# The _read_and_parse triggered a _buffer_all, grab the data and
|
|
777 |
# return it
|
|
778 |
for location, key in pending_references: |
|
779 |
value, refs = self._nodes[key] |
|
780 |
result.append(((location, key), (self, key, value, refs))) |
|
781 |
return result |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
782 |
for location, key in pending_references: |
783 |
# answer key references we had to look-up-late.
|
|
784 |
value, refs = self._bisect_nodes[key] |
|
785 |
result.append(((location, key), (self, key, |
|
786 |
value, self._resolve_references(refs)))) |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
787 |
return result |
788 |
||
789 |
def _parse_header_from_bytes(self, bytes): |
|
790 |
"""Parse the header from a region of bytes. |
|
791 |
||
792 |
:param bytes: The data to parse.
|
|
793 |
:return: An offset, data tuple such as readv yields, for the unparsed
|
|
794 |
data. (which may length 0).
|
|
795 |
"""
|
|
796 |
signature = bytes[0:len(self._signature())] |
|
797 |
if not signature == self._signature(): |
|
798 |
raise errors.BadIndexFormatSignature(self._name, GraphIndex) |
|
799 |
lines = bytes[len(self._signature()):].splitlines() |
|
800 |
options_line = lines[0] |
|
801 |
if not options_line.startswith(_OPTION_NODE_REFS): |
|
802 |
raise errors.BadIndexOptions(self) |
|
803 |
try: |
|
804 |
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):]) |
|
805 |
except ValueError: |
|
806 |
raise errors.BadIndexOptions(self) |
|
807 |
options_line = lines[1] |
|
808 |
if not options_line.startswith(_OPTION_KEY_ELEMENTS): |
|
809 |
raise errors.BadIndexOptions(self) |
|
810 |
try: |
|
811 |
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):]) |
|
812 |
except ValueError: |
|
813 |
raise errors.BadIndexOptions(self) |
|
814 |
options_line = lines[2] |
|
815 |
if not options_line.startswith(_OPTION_LEN): |
|
816 |
raise errors.BadIndexOptions(self) |
|
817 |
try: |
|
818 |
self._key_count = int(options_line[len(_OPTION_LEN):]) |
|
819 |
except ValueError: |
|
820 |
raise errors.BadIndexOptions(self) |
|
821 |
# calculate the bytes we have processed
|
|
822 |
header_end = (len(signature) + len(lines[0]) + len(lines[1]) + |
|
823 |
len(lines[2]) + 3) |
|
824 |
self._parsed_bytes(0, None, header_end, None) |
|
825 |
# setup parsing state
|
|
826 |
self._expected_elements = 3 + self._key_length |
|
827 |
# raw data keyed by offset
|
|
828 |
self._keys_by_offset = {} |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
829 |
# keys with the value and node references
|
830 |
self._bisect_nodes = {} |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
831 |
return header_end, bytes[header_end:] |
832 |
||
833 |
def _parse_region(self, offset, data): |
|
834 |
"""Parse node data returned from a readv operation. |
|
835 |
||
836 |
:param offset: The byte offset the data starts at.
|
|
837 |
:param data: The data to parse.
|
|
838 |
"""
|
|
839 |
# trim the data.
|
|
840 |
# end first:
|
|
841 |
end = offset + len(data) |
|
|
2890.2.15
by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that. |
842 |
high_parsed = offset |
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
843 |
while True: |
844 |
# Trivial test - if the current index's end is within the
|
|
845 |
# low-matching parsed range, we're done.
|
|
|
2890.2.15
by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that. |
846 |
index = self._parsed_byte_index(high_parsed) |
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
847 |
if end < self._parsed_byte_map[index][1]: |
848 |
return
|
|
|
2890.2.15
by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that. |
849 |
# print "[%d:%d]" % (offset, end), \
|
850 |
# self._parsed_byte_map[index:index + 2]
|
|
851 |
high_parsed, last_segment = self._parse_segment( |
|
852 |
offset, data, end, index) |
|
853 |
if last_segment: |
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
854 |
return
|
855 |
||
856 |
def _parse_segment(self, offset, data, end, index): |
|
857 |
"""Parse one segment of data. |
|
858 |
||
859 |
:param offset: Where 'data' begins in the file.
|
|
860 |
:param data: Some data to parse a segment of.
|
|
861 |
:param end: Where data ends
|
|
862 |
:param index: The current index into the parsed bytes map.
|
|
863 |
:return: True if the parsed segment is the last possible one in the
|
|
864 |
range of data.
|
|
|
2890.2.15
by Robert Collins
Corner case when parsing repeated sections - the bottom section of a region may not be parsed, so we need to manually advance past that. |
865 |
:return: high_parsed_byte, last_segment.
|
866 |
high_parsed_byte is the location of the highest parsed byte in this
|
|
867 |
segment, last_segment is True if the parsed segment is the last
|
|
868 |
possible one in the data block.
|
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
869 |
"""
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
870 |
# default is to use all data
|
871 |
trim_end = None |
|
872 |
# accomodate overlap with data before this.
|
|
873 |
if offset < self._parsed_byte_map[index][1]: |
|
874 |
# overlaps the lower parsed region
|
|
875 |
# skip the parsed data
|
|
876 |
trim_start = self._parsed_byte_map[index][1] - offset |
|
877 |
# don't trim the start for \n
|
|
878 |
start_adjacent = True |
|
879 |
elif offset == self._parsed_byte_map[index][1]: |
|
880 |
# abuts the lower parsed region
|
|
881 |
# use all data
|
|
882 |
trim_start = None |
|
883 |
# do not trim anything
|
|
884 |
start_adjacent = True |
|
885 |
else: |
|
886 |
# does not overlap the lower parsed region
|
|
887 |
# use all data
|
|
888 |
trim_start = None |
|
889 |
# but trim the leading \n
|
|
890 |
start_adjacent = False |
|
891 |
if end == self._size: |
|
892 |
# lines up to the end of all data:
|
|
893 |
# use it all
|
|
894 |
trim_end = None |
|
895 |
# do not strip to the last \n
|
|
896 |
end_adjacent = True |
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
897 |
last_segment = True |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
898 |
elif index + 1 == len(self._parsed_byte_map): |
899 |
# at the end of the parsed data
|
|
900 |
# use it all
|
|
901 |
trim_end = None |
|
902 |
# but strip to the last \n
|
|
903 |
end_adjacent = False |
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
904 |
last_segment = True |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
905 |
elif end == self._parsed_byte_map[index + 1][0]: |
906 |
# buts up against the next parsed region
|
|
907 |
# use it all
|
|
908 |
trim_end = None |
|
909 |
# do not strip to the last \n
|
|
910 |
end_adjacent = True |
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
911 |
last_segment = True |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
912 |
elif end > self._parsed_byte_map[index + 1][0]: |
913 |
# overlaps into the next parsed region
|
|
914 |
# only consider the unparsed data
|
|
915 |
trim_end = self._parsed_byte_map[index + 1][0] - offset |
|
916 |
# do not strip to the last \n as we know its an entire record
|
|
917 |
end_adjacent = True |
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
918 |
last_segment = end < self._parsed_byte_map[index + 1][1] |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
919 |
else: |
920 |
# does not overlap into the next region
|
|
921 |
# use it all
|
|
922 |
trim_end = None |
|
923 |
# but strip to the last \n
|
|
924 |
end_adjacent = False |
|
|
2890.2.14
by Robert Collins
Parse more than one segment of data from a single readv response if needed. |
925 |
last_segment = True |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
926 |
# now find bytes to discard if needed
|
927 |
if not start_adjacent: |
|
928 |
# work around python bug in rfind
|
|
929 |
if trim_start is None: |
|
930 |
trim_start = data.find('\n') + 1 |
|
931 |
else: |
|
932 |
trim_start = data.find('\n', trim_start) + 1 |
|
|
3376.2.4
by Martin Pool
Remove every assert statement from bzrlib! |
933 |
if not (trim_start != 0): |
934 |
raise AssertionError('no \n was present') |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
935 |
# print 'removing start', offset, trim_start, repr(data[:trim_start])
|
936 |
if not end_adjacent: |
|
937 |
# work around python bug in rfind
|
|
938 |
if trim_end is None: |
|
939 |
trim_end = data.rfind('\n') + 1 |
|
940 |
else: |
|
941 |
trim_end = data.rfind('\n', None, trim_end) + 1 |
|
|
3376.2.4
by Martin Pool
Remove every assert statement from bzrlib! |
942 |
if not (trim_end != 0): |
943 |
raise AssertionError('no \n was present') |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
944 |
# print 'removing end', offset, trim_end, repr(data[trim_end:])
|
945 |
# adjust offset and data to the parseable data.
|
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
946 |
trimmed_data = data[trim_start:trim_end] |
|
3376.2.4
by Martin Pool
Remove every assert statement from bzrlib! |
947 |
if not (trimmed_data): |
948 |
raise AssertionError('read unneeded data [%d:%d] from [%d:%d]' |
|
949 |
% (trim_start, trim_end, offset, offset + len(data))) |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
950 |
if trim_start: |
951 |
offset += trim_start |
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
952 |
# print "parsing", repr(trimmed_data)
|
|
2890.2.10
by Robert Collins
Add test coverage to ensure \r's are not mangled by bisection parsing. |
953 |
# splitlines mangles the \r delimiters.. don't use it.
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
954 |
lines = trimmed_data.split('\n') |
|
2890.2.9
by Robert Collins
Don't use splitlines for index data parsing, we embed \r. |
955 |
del lines[-1] |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
956 |
pos = offset |
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
957 |
first_key, last_key, nodes, _ = self._parse_lines(lines, pos) |
958 |
for key, value in nodes: |
|
959 |
self._bisect_nodes[key] = value |
|
960 |
self._parsed_bytes(offset, first_key, |
|
961 |
offset + len(trimmed_data), last_key) |
|
962 |
return offset + len(trimmed_data), last_segment |
|
963 |
||
964 |
def _parse_lines(self, lines, pos): |
|
965 |
key = None |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
966 |
first_key = None |
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
967 |
trailers = 0 |
968 |
nodes = [] |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
969 |
for line in lines: |
970 |
if line == '': |
|
971 |
# must be at the end
|
|
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
972 |
if self._size: |
|
3376.2.4
by Martin Pool
Remove every assert statement from bzrlib! |
973 |
if not (self._size == pos + 1): |
974 |
raise AssertionError("%s %s" % (self._size, pos)) |
|
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
975 |
trailers += 1 |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
976 |
continue
|
977 |
elements = line.split('\0') |
|
978 |
if len(elements) != self._expected_elements: |
|
979 |
raise errors.BadIndexData(self) |
|
|
3530.3.3
by Robert Collins
Credit and explanation for interning. |
980 |
# keys are tuples. Each element is a string that may occur many
|
981 |
# times, so we intern them to save space. AB, RC, 200807
|
|
|
3711.3.13
by John Arbash Meinel
Shave off another 5s by not building 'node_by_key' |
982 |
key = tuple([intern(element) for element in elements[:self._key_length]]) |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
983 |
if first_key is None: |
984 |
first_key = key |
|
985 |
absent, references, value = elements[-3:] |
|
986 |
ref_lists = [] |
|
987 |
for ref_string in references.split('\t'): |
|
988 |
ref_lists.append(tuple([ |
|
989 |
int(ref) for ref in ref_string.split('\r') if ref |
|
990 |
]))
|
|
991 |
ref_lists = tuple(ref_lists) |
|
992 |
self._keys_by_offset[pos] = (key, absent, ref_lists, value) |
|
993 |
pos += len(line) + 1 # +1 for the \n |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
994 |
if absent: |
995 |
continue
|
|
996 |
if self.node_ref_lists: |
|
997 |
node_value = (value, ref_lists) |
|
998 |
else: |
|
999 |
node_value = value |
|
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
1000 |
nodes.append((key, node_value)) |
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
1001 |
# print "parsed ", key
|
|
2890.2.17
by Robert Collins
Split _parse_segment out into a _parse_lines helper, reducing duplication with full index parsing. |
1002 |
return first_key, key, nodes, trailers |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
1003 |
|
1004 |
def _parsed_bytes(self, start, start_key, end, end_key): |
|
1005 |
"""Mark the bytes from start to end as parsed. |
|
1006 |
||
1007 |
Calling self._parsed_bytes(1,2) will mark one byte (the one at offset
|
|
1008 |
1) as parsed.
|
|
1009 |
||
1010 |
:param start: The start of the parsed region.
|
|
1011 |
:param end: The end of the parsed region.
|
|
1012 |
"""
|
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
1013 |
index = self._parsed_byte_index(start) |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
1014 |
new_value = (start, end) |
1015 |
new_key = (start_key, end_key) |
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
1016 |
if index == -1: |
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
1017 |
# first range parsed is always the beginning.
|
1018 |
self._parsed_byte_map.insert(index, new_value) |
|
1019 |
self._parsed_key_map.insert(index, new_key) |
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
1020 |
return
|
1021 |
# four cases:
|
|
1022 |
# new region
|
|
1023 |
# extend lower region
|
|
1024 |
# extend higher region
|
|
1025 |
# combine two regions
|
|
1026 |
if (index + 1 < len(self._parsed_byte_map) and |
|
1027 |
self._parsed_byte_map[index][1] == start and |
|
1028 |
self._parsed_byte_map[index + 1][0] == end): |
|
1029 |
# combine two regions
|
|
1030 |
self._parsed_byte_map[index] = (self._parsed_byte_map[index][0], |
|
1031 |
self._parsed_byte_map[index + 1][1]) |
|
1032 |
self._parsed_key_map[index] = (self._parsed_key_map[index][0], |
|
1033 |
self._parsed_key_map[index + 1][1]) |
|
|
2890.2.12
by Robert Collins
More index tweaks. |
1034 |
del self._parsed_byte_map[index + 1] |
1035 |
del self._parsed_key_map[index + 1] |
|
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
1036 |
elif self._parsed_byte_map[index][1] == start: |
1037 |
# extend the lower entry
|
|
1038 |
self._parsed_byte_map[index] = ( |
|
1039 |
self._parsed_byte_map[index][0], end) |
|
1040 |
self._parsed_key_map[index] = ( |
|
1041 |
self._parsed_key_map[index][0], end_key) |
|
1042 |
elif (index + 1 < len(self._parsed_byte_map) and |
|
1043 |
self._parsed_byte_map[index + 1][0] == end): |
|
1044 |
# extend the higher entry
|
|
1045 |
self._parsed_byte_map[index + 1] = ( |
|
1046 |
start, self._parsed_byte_map[index + 1][1]) |
|
1047 |
self._parsed_key_map[index + 1] = ( |
|
1048 |
start_key, self._parsed_key_map[index + 1][1]) |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
1049 |
else: |
|
2890.2.11
by Robert Collins
Bisection improvements after integrating with packs. |
1050 |
# new entry
|
1051 |
self._parsed_byte_map.insert(index + 1, new_value) |
|
1052 |
self._parsed_key_map.insert(index + 1, new_key) |
|
|
2890.2.5
by Robert Collins
Create a content lookup function for bisection in GraphIndex. |
1053 |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
1054 |
def _read_and_parse(self, readv_ranges): |
1055 |
"""Read the the ranges and parse the resulting data. |
|
1056 |
||
1057 |
:param readv_ranges: A prepared readv range list.
|
|
1058 |
"""
|
|
|
3665.3.5
by John Arbash Meinel
Move the point at which we 'buffer_all' if we've read >50% of the index. |
1059 |
if not readv_ranges: |
1060 |
return
|
|
1061 |
if self._nodes is None and self._bytes_read * 2 >= self._size: |
|
1062 |
# We've already read more than 50% of the file and we are about to
|
|
1063 |
# request more data, just _buffer_all() and be done
|
|
1064 |
self._buffer_all() |
|
1065 |
return
|
|
1066 |
||
1067 |
readv_data = self._transport.readv(self._name, readv_ranges, True, |
|
1068 |
self._size) |
|
1069 |
# parse
|
|
1070 |
for offset, data in readv_data: |
|
1071 |
self._bytes_read += len(data) |
|
1072 |
if offset == 0 and len(data) == self._size: |
|
1073 |
# We read the whole range, most likely because the
|
|
1074 |
# Transport upcast our readv ranges into one long request
|
|
1075 |
# for enough total data to grab the whole index.
|
|
1076 |
self._buffer_all(StringIO(data)) |
|
1077 |
return
|
|
1078 |
if self._bisect_nodes is None: |
|
1079 |
# this must be the start
|
|
1080 |
if not (offset == 0): |
|
1081 |
raise AssertionError() |
|
1082 |
offset, data = self._parse_header_from_bytes(data) |
|
1083 |
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
|
|
1084 |
self._parse_region(offset, data) |
|
|
2890.2.6
by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface. |
1085 |
|
|
2592.1.8
by Robert Collins
Empty files should validate ok. |
1086 |
def _signature(self): |
1087 |
"""The file signature for this index type.""" |
|
1088 |
return _SIGNATURE |
|
1089 |
||
|
2592.1.7
by Robert Collins
A validate that goes boom. |
1090 |
def validate(self): |
1091 |
"""Validate that everything in the index can be accessed.""" |
|
|
2592.1.27
by Robert Collins
Test missing end lines with non-empty indices. |
1092 |
# iter_all validates completely at the moment, so just do that.
|
1093 |
for node in self.iter_all_entries(): |
|
1094 |
pass
|
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1095 |
|
1096 |
||
1097 |
class CombinedGraphIndex(object): |
|
1098 |
"""A GraphIndex made up from smaller GraphIndices. |
|
1099 |
|
|
1100 |
The backing indices must implement GraphIndex, and are presumed to be
|
|
1101 |
static data.
|
|
|
2592.1.45
by Robert Collins
Tweak documentation as per Aaron's review. |
1102 |
|
1103 |
Queries against the combined index will be made against the first index,
|
|
1104 |
and then the second and so on. The order of index's can thus influence
|
|
1105 |
performance significantly. For example, if one index is on local disk and a
|
|
1106 |
second on a remote server, the local disk index should be before the other
|
|
1107 |
in the index list.
|
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1108 |
"""
|
1109 |
||
|
3789.1.3
by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count(). |
1110 |
def __init__(self, indices, reload_func=None): |
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1111 |
"""Create a CombinedGraphIndex backed by indices. |
1112 |
||
|
2592.1.45
by Robert Collins
Tweak documentation as per Aaron's review. |
1113 |
:param indices: An ordered list of indices to query for data.
|
|
3789.1.3
by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count(). |
1114 |
:param reload_func: A function to call if we find we are missing an
|
1115 |
index. Should have the form reload_func() => True/False to indicate
|
|
1116 |
if reloading actually changed anything.
|
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1117 |
"""
|
1118 |
self._indices = indices |
|
|
3789.1.3
by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count(). |
1119 |
self._reload_func = reload_func |
|
2592.1.37
by Robert Collins
Add CombinedGraphIndex.insert_index. |
1120 |
|
|
2592.5.4
by Martin Pool
Add CombinedGraphIndex repr |
1121 |
def __repr__(self): |
1122 |
return "%s(%s)" % ( |
|
1123 |
self.__class__.__name__, |
|
1124 |
', '.join(map(repr, self._indices))) |
|
1125 |
||
|
3099.3.3
by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map() |
1126 |
@symbol_versioning.deprecated_method(symbol_versioning.one_one) |
|
2979.2.2
by Robert Collins
Per-file graph heads detection during commit for pack repositories. |
1127 |
def get_parents(self, revision_ids): |
|
3099.3.1
by John Arbash Meinel
Implement get_parent_map for ParentProviders |
1128 |
"""See graph._StackedParentsProvider.get_parents. |
|
2979.2.2
by Robert Collins
Per-file graph heads detection during commit for pack repositories. |
1129 |
|
1130 |
This implementation thunks the graph.Graph.get_parents api across to
|
|
1131 |
GraphIndex.
|
|
1132 |
||
1133 |
:param revision_ids: An iterable of graph keys for this graph.
|
|
1134 |
:return: A list of parent details for each key in revision_ids.
|
|
1135 |
Each parent details will be one of:
|
|
1136 |
* None when the key was missing
|
|
1137 |
* (NULL_REVISION,) when the key has no parents.
|
|
1138 |
* (parent_key, parent_key...) otherwise.
|
|
1139 |
"""
|
|
|
3099.3.1
by John Arbash Meinel
Implement get_parent_map for ParentProviders |
1140 |
parent_map = self.get_parent_map(revision_ids) |
1141 |
return [parent_map.get(r, None) for r in revision_ids] |
|
1142 |
||
1143 |
def get_parent_map(self, keys): |
|
1144 |
"""See graph._StackedParentsProvider.get_parent_map""" |
|
1145 |
search_keys = set(keys) |
|
1146 |
if NULL_REVISION in search_keys: |
|
1147 |
search_keys.discard(NULL_REVISION) |
|
1148 |
found_parents = {NULL_REVISION:[]} |
|
1149 |
else: |
|
1150 |
found_parents = {} |
|
|
2979.2.2
by Robert Collins
Per-file graph heads detection during commit for pack repositories. |
1151 |
for index, key, value, refs in self.iter_entries(search_keys): |
1152 |
parents = refs[0] |
|
1153 |
if not parents: |
|
1154 |
parents = (NULL_REVISION,) |
|
1155 |
found_parents[key] = parents |
|
|
3099.3.1
by John Arbash Meinel
Implement get_parent_map for ParentProviders |
1156 |
return found_parents |
|
2979.2.2
by Robert Collins
Per-file graph heads detection during commit for pack repositories. |
1157 |
|
|
2592.1.37
by Robert Collins
Add CombinedGraphIndex.insert_index. |
1158 |
def insert_index(self, pos, index): |
1159 |
"""Insert a new index in the list of indices to query. |
|
1160 |
||
1161 |
:param pos: The position to insert the index.
|
|
1162 |
:param index: The index to insert.
|
|
1163 |
"""
|
|
1164 |
self._indices.insert(pos, index) |
|
1165 |
||
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1166 |
def iter_all_entries(self): |
1167 |
"""Iterate over all keys within the index |
|
1168 |
||
|
2592.1.44
by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review. |
1169 |
Duplicate keys across child indices are presumed to have the same
|
1170 |
value and are only reported once.
|
|
1171 |
||
|
2592.5.1
by Martin Pool
Fix docstrings for Index.iter_entries etc |
1172 |
:return: An iterable of (index, key, reference_lists, value).
|
1173 |
There is no defined order for the result iteration - it will be in
|
|
1174 |
the most efficient order for the index.
|
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1175 |
"""
|
1176 |
seen_keys = set() |
|
|
3789.1.5
by John Arbash Meinel
CombinedGraphIndex.iter_all_entries() can now reload when needed. |
1177 |
while True: |
1178 |
try: |
|
1179 |
for index in self._indices: |
|
1180 |
for node in index.iter_all_entries(): |
|
1181 |
if node[1] not in seen_keys: |
|
1182 |
yield node |
|
1183 |
seen_keys.add(node[1]) |
|
1184 |
return
|
|
1185 |
except errors.NoSuchFile: |
|
1186 |
self._reload_or_raise() |
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1187 |
|
1188 |
def iter_entries(self, keys): |
|
1189 |
"""Iterate over keys within the index. |
|
1190 |
||
|
2592.1.44
by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review. |
1191 |
Duplicate keys across child indices are presumed to have the same
|
1192 |
value and are only reported once.
|
|
1193 |
||
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1194 |
:param keys: An iterable providing the keys to be retrieved.
|
|
2592.5.1
by Martin Pool
Fix docstrings for Index.iter_entries etc |
1195 |
:return: An iterable of (index, key, reference_lists, value). There is no
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1196 |
defined order for the result iteration - it will be in the most
|
1197 |
efficient order for the index.
|
|
1198 |
"""
|
|
1199 |
keys = set(keys) |
|
|
3789.1.4
by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request. |
1200 |
while True: |
1201 |
try: |
|
1202 |
for index in self._indices: |
|
1203 |
if not keys: |
|
1204 |
return
|
|
1205 |
for node in index.iter_entries(keys): |
|
1206 |
keys.remove(node[1]) |
|
1207 |
yield node |
|
|
2592.1.44
by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review. |
1208 |
return
|
|
3789.1.4
by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request. |
1209 |
except errors.NoSuchFile: |
1210 |
self._reload_or_raise() |
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1211 |
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
1212 |
def iter_entries_prefix(self, keys): |
1213 |
"""Iterate over keys within the index using prefix matching. |
|
1214 |
||
1215 |
Duplicate keys across child indices are presumed to have the same
|
|
1216 |
value and are only reported once.
|
|
1217 |
||
1218 |
Prefix matching is applied within the tuple of a key, not to within
|
|
1219 |
the bytestring of each key element. e.g. if you have the keys ('foo',
|
|
1220 |
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
|
|
1221 |
only the former key is returned.
|
|
1222 |
||
1223 |
:param keys: An iterable providing the key prefixes to be retrieved.
|
|
1224 |
Each key prefix takes the form of a tuple the length of a key, but
|
|
1225 |
with the last N elements 'None' rather than a regular bytestring.
|
|
1226 |
The first element cannot be 'None'.
|
|
1227 |
:return: An iterable as per iter_all_entries, but restricted to the
|
|
1228 |
keys with a matching prefix to those supplied. No additional keys
|
|
1229 |
will be returned, and every match that is in the index will be
|
|
1230 |
returned.
|
|
1231 |
"""
|
|
1232 |
keys = set(keys) |
|
1233 |
if not keys: |
|
1234 |
return
|
|
1235 |
seen_keys = set() |
|
|
3789.1.6
by John Arbash Meinel
CombinedGraphIndex.iter_entries_prefix can now reload when needed. |
1236 |
while True: |
1237 |
try: |
|
1238 |
for index in self._indices: |
|
1239 |
for node in index.iter_entries_prefix(keys): |
|
1240 |
if node[1] in seen_keys: |
|
1241 |
continue
|
|
1242 |
seen_keys.add(node[1]) |
|
1243 |
yield node |
|
1244 |
return
|
|
1245 |
except errors.NoSuchFile: |
|
1246 |
self._reload_or_raise() |
|
|
2624.2.9
by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one. |
1247 |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
1248 |
def key_count(self): |
1249 |
"""Return an estimate of the number of keys in this index. |
|
|
3789.1.3
by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count(). |
1250 |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
1251 |
For CombinedGraphIndex this is approximated by the sum of the keys of
|
1252 |
the child indices. As child indices may have duplicate keys this can
|
|
1253 |
have a maximum error of the number of child indices * largest number of
|
|
1254 |
keys in any index.
|
|
1255 |
"""
|
|
|
3789.1.4
by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request. |
1256 |
while True: |
|
3789.1.3
by John Arbash Meinel
CombinedGraphIndex can now reload when calling key_count(). |
1257 |
try: |
1258 |
return sum((index.key_count() for index in self._indices), 0) |
|
1259 |
except errors.NoSuchFile: |
|
|
3789.1.4
by John Arbash Meinel
CombinedGraphIndex.iter_entries() is now able to reload on request. |
1260 |
self._reload_or_raise() |
1261 |
||
1262 |
def _reload_or_raise(self): |
|
1263 |
"""We just got a NoSuchFile exception. |
|
1264 |
||
1265 |
Try to reload the indices, if it fails, just raise the current
|
|
1266 |
exception.
|
|
1267 |
"""
|
|
1268 |
if self._reload_func is None: |
|
1269 |
raise
|
|
1270 |
exc_type, exc_value, exc_traceback = sys.exc_info() |
|
1271 |
if not self._reload_func(): |
|
1272 |
# We tried to reload, but nothing changed, so we fail anyway
|
|
1273 |
raise exc_type, exc_value, exc_traceback |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
1274 |
|
|
2592.1.31
by Robert Collins
Build a combined graph index to use multiple indices at once. |
1275 |
def validate(self): |
1276 |
"""Validate that everything in the index can be accessed.""" |
|
|
3789.1.7
by John Arbash Meinel
CombinedGraphIndex.validate() will now reload. |
1277 |
while True: |
1278 |
try: |
|
1279 |
for index in self._indices: |
|
1280 |
index.validate() |
|
1281 |
return
|
|
1282 |
except errors.NoSuchFile: |
|
1283 |
self._reload_or_raise() |
|
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1284 |
|
1285 |
||
1286 |
class InMemoryGraphIndex(GraphIndexBuilder): |
|
1287 |
"""A GraphIndex which operates entirely out of memory and is mutable. |
|
1288 |
||
1289 |
This is designed to allow the accumulation of GraphIndex entries during a
|
|
1290 |
single write operation, where the accumulated entries need to be immediately
|
|
1291 |
available - for example via a CombinedGraphIndex.
|
|
1292 |
"""
|
|
1293 |
||
1294 |
def add_nodes(self, nodes): |
|
1295 |
"""Add nodes to the index. |
|
1296 |
||
1297 |
:param nodes: An iterable of (key, node_refs, value) entries to add.
|
|
1298 |
"""
|
|
|
2592.3.39
by Robert Collins
Fugly version to remove signatures.kndx |
1299 |
if self.reference_lists: |
1300 |
for (key, value, node_refs) in nodes: |
|
1301 |
self.add_node(key, value, node_refs) |
|
1302 |
else: |
|
1303 |
for (key, value) in nodes: |
|
1304 |
self.add_node(key, value) |
|
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1305 |
|
1306 |
def iter_all_entries(self): |
|
1307 |
"""Iterate over all keys within the index |
|
1308 |
||
|
2592.5.1
by Martin Pool
Fix docstrings for Index.iter_entries etc |
1309 |
:return: An iterable of (index, key, reference_lists, value). There is no
|
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1310 |
defined order for the result iteration - it will be in the most
|
1311 |
efficient order for the index (in this case dictionary hash order).
|
|
1312 |
"""
|
|
|
2745.1.1
by Robert Collins
Add a number of -Devil checkpoints. |
1313 |
if 'evil' in debug.debug_flags: |
|
2592.3.112
by Robert Collins
Various fixups found dogfooding. |
1314 |
trace.mutter_callsite(3, |
|
2745.1.2
by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly. |
1315 |
"iter_all_entries scales with size of history.") |
|
2592.1.46
by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method |
1316 |
if self.reference_lists: |
1317 |
for key, (absent, references, value) in self._nodes.iteritems(): |
|
1318 |
if not absent: |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1319 |
yield self, key, value, references |
|
2592.1.46
by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method |
1320 |
else: |
1321 |
for key, (absent, references, value) in self._nodes.iteritems(): |
|
1322 |
if not absent: |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1323 |
yield self, key, value |
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1324 |
|
1325 |
def iter_entries(self, keys): |
|
1326 |
"""Iterate over keys within the index. |
|
1327 |
||
1328 |
:param keys: An iterable providing the keys to be retrieved.
|
|
|
2979.2.4
by Robert Collins
Docstring fixes from review. |
1329 |
:return: An iterable of (index, key, value, reference_lists). There is no
|
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1330 |
defined order for the result iteration - it will be in the most
|
1331 |
efficient order for the index (keys iteration order in this case).
|
|
1332 |
"""
|
|
1333 |
keys = set(keys) |
|
|
2592.1.46
by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method |
1334 |
if self.reference_lists: |
|
2592.3.62
by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration. |
1335 |
for key in keys.intersection(self._keys): |
|
2592.1.46
by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method |
1336 |
node = self._nodes[key] |
1337 |
if not node[0]: |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1338 |
yield self, key, node[2], node[1] |
|
2592.1.46
by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method |
1339 |
else: |
|
2592.3.62
by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration. |
1340 |
for key in keys.intersection(self._keys): |
|
2592.1.46
by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method |
1341 |
node = self._nodes[key] |
1342 |
if not node[0]: |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1343 |
yield self, key, node[2] |
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1344 |
|
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1345 |
def iter_entries_prefix(self, keys): |
1346 |
"""Iterate over keys within the index using prefix matching. |
|
1347 |
||
1348 |
Prefix matching is applied within the tuple of a key, not to within
|
|
1349 |
the bytestring of each key element. e.g. if you have the keys ('foo',
|
|
1350 |
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
|
|
1351 |
only the former key is returned.
|
|
1352 |
||
1353 |
:param keys: An iterable providing the key prefixes to be retrieved.
|
|
1354 |
Each key prefix takes the form of a tuple the length of a key, but
|
|
1355 |
with the last N elements 'None' rather than a regular bytestring.
|
|
1356 |
The first element cannot be 'None'.
|
|
1357 |
:return: An iterable as per iter_all_entries, but restricted to the
|
|
1358 |
keys with a matching prefix to those supplied. No additional keys
|
|
1359 |
will be returned, and every match that is in the index will be
|
|
1360 |
returned.
|
|
1361 |
"""
|
|
1362 |
# XXX: To much duplication with the GraphIndex class; consider finding
|
|
1363 |
# a good place to pull out the actual common logic.
|
|
1364 |
keys = set(keys) |
|
1365 |
if not keys: |
|
1366 |
return
|
|
1367 |
if self._key_length == 1: |
|
1368 |
for key in keys: |
|
1369 |
# sanity check
|
|
1370 |
if key[0] is None: |
|
1371 |
raise errors.BadIndexKey(key) |
|
1372 |
if len(key) != self._key_length: |
|
1373 |
raise errors.BadIndexKey(key) |
|
1374 |
node = self._nodes[key] |
|
1375 |
if node[0]: |
|
1376 |
continue
|
|
1377 |
if self.reference_lists: |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1378 |
yield self, key, node[2], node[1] |
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1379 |
else: |
|
2624.2.17
by Robert Collins
Review feedback. |
1380 |
yield self, key, node[2] |
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1381 |
return
|
|
3644.2.4
by John Arbash Meinel
Change GraphIndex to also have a _get_nodes_by_key |
1382 |
nodes_by_key = self._get_nodes_by_key() |
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1383 |
for key in keys: |
1384 |
# sanity check
|
|
1385 |
if key[0] is None: |
|
1386 |
raise errors.BadIndexKey(key) |
|
1387 |
if len(key) != self._key_length: |
|
1388 |
raise errors.BadIndexKey(key) |
|
1389 |
# find what it refers to:
|
|
|
3644.2.4
by John Arbash Meinel
Change GraphIndex to also have a _get_nodes_by_key |
1390 |
key_dict = nodes_by_key |
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1391 |
elements = list(key) |
1392 |
# find the subdict to return
|
|
1393 |
try: |
|
1394 |
while len(elements) and elements[0] is not None: |
|
1395 |
key_dict = key_dict[elements[0]] |
|
1396 |
elements.pop(0) |
|
1397 |
except KeyError: |
|
1398 |
# a non-existant lookup.
|
|
1399 |
continue
|
|
1400 |
if len(elements): |
|
1401 |
dicts = [key_dict] |
|
1402 |
while dicts: |
|
1403 |
key_dict = dicts.pop(-1) |
|
1404 |
# can't be empty or would not exist
|
|
1405 |
item, value = key_dict.iteritems().next() |
|
1406 |
if type(value) == dict: |
|
1407 |
# push keys
|
|
1408 |
dicts.extend(key_dict.itervalues()) |
|
1409 |
else: |
|
1410 |
# yield keys
|
|
1411 |
for value in key_dict.itervalues(): |
|
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1412 |
yield (self, ) + value |
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1413 |
else: |
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1414 |
yield (self, ) + key_dict |
|
2624.2.10
by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex. |
1415 |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
1416 |
def key_count(self): |
1417 |
"""Return an estimate of the number of keys in this index. |
|
1418 |
|
|
1419 |
For InMemoryGraphIndex the estimate is exact.
|
|
1420 |
"""
|
|
1421 |
return len(self._keys) |
|
1422 |
||
|
2592.1.38
by Robert Collins
Create an InMemoryGraphIndex for temporary indexing. |
1423 |
def validate(self): |
1424 |
"""In memory index's have no known corruption at the moment.""" |
|
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1425 |
|
1426 |
||
1427 |
class GraphIndexPrefixAdapter(object): |
|
1428 |
"""An adapter between GraphIndex with different key lengths. |
|
1429 |
||
1430 |
Queries against this will emit queries against the adapted Graph with the
|
|
1431 |
prefix added, queries for all items use iter_entries_prefix. The returned
|
|
1432 |
nodes will have their keys and node references adjusted to remove the
|
|
1433 |
prefix. Finally, an add_nodes_callback can be supplied - when called the
|
|
1434 |
nodes and references being added will have prefix prepended.
|
|
1435 |
"""
|
|
1436 |
||
|
2624.2.17
by Robert Collins
Review feedback. |
1437 |
def __init__(self, adapted, prefix, missing_key_length, |
1438 |
add_nodes_callback=None): |
|
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1439 |
"""Construct an adapter against adapted with prefix.""" |
1440 |
self.adapted = adapted |
|
|
2624.2.19
by Robert Collins
Why we should always test before committing. |
1441 |
self.prefix_key = prefix + (None,)*missing_key_length |
|
2624.2.17
by Robert Collins
Review feedback. |
1442 |
self.prefix = prefix |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1443 |
self.prefix_len = len(prefix) |
1444 |
self.add_nodes_callback = add_nodes_callback |
|
1445 |
||
|
2624.2.13
by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter. |
1446 |
def add_nodes(self, nodes): |
1447 |
"""Add nodes to the index. |
|
1448 |
||
1449 |
:param nodes: An iterable of (key, node_refs, value) entries to add.
|
|
1450 |
"""
|
|
1451 |
# save nodes in case its an iterator
|
|
1452 |
nodes = tuple(nodes) |
|
1453 |
translated_nodes = [] |
|
1454 |
try: |
|
|
2624.2.17
by Robert Collins
Review feedback. |
1455 |
# Add prefix_key to each reference node_refs is a tuple of tuples,
|
1456 |
# so split it apart, and add prefix_key to the internal reference
|
|
|
2624.2.13
by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter. |
1457 |
for (key, value, node_refs) in nodes: |
1458 |
adjusted_references = ( |
|
|
2624.2.17
by Robert Collins
Review feedback. |
1459 |
tuple(tuple(self.prefix + ref_node for ref_node in ref_list) |
|
2624.2.13
by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter. |
1460 |
for ref_list in node_refs)) |
|
2624.2.17
by Robert Collins
Review feedback. |
1461 |
translated_nodes.append((self.prefix + key, value, |
|
2624.2.13
by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter. |
1462 |
adjusted_references)) |
1463 |
except ValueError: |
|
1464 |
# XXX: TODO add an explicit interface for getting the reference list
|
|
1465 |
# status, to handle this bit of user-friendliness in the API more
|
|
1466 |
# explicitly.
|
|
1467 |
for (key, value) in nodes: |
|
|
2624.2.17
by Robert Collins
Review feedback. |
1468 |
translated_nodes.append((self.prefix + key, value)) |
|
2624.2.13
by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter. |
1469 |
self.add_nodes_callback(translated_nodes) |
1470 |
||
1471 |
def add_node(self, key, value, references=()): |
|
1472 |
"""Add a node to the index. |
|
1473 |
||
1474 |
:param key: The key. keys are non-empty tuples containing
|
|
1475 |
as many whitespace-free utf8 bytestrings as the key length
|
|
1476 |
defined for this index.
|
|
1477 |
:param references: An iterable of iterables of keys. Each is a
|
|
1478 |
reference to another key.
|
|
1479 |
:param value: The value to associate with the key. It may be any
|
|
1480 |
bytes as long as it does not contain \0 or \n.
|
|
1481 |
"""
|
|
1482 |
self.add_nodes(((key, value, references), )) |
|
1483 |
||
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1484 |
def _strip_prefix(self, an_iter): |
1485 |
"""Strip prefix data from nodes and return it.""" |
|
1486 |
for node in an_iter: |
|
1487 |
# cross checks
|
|
|
2624.2.17
by Robert Collins
Review feedback. |
1488 |
if node[1][:self.prefix_len] != self.prefix: |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1489 |
raise errors.BadIndexData(self) |
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1490 |
for ref_list in node[3]: |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1491 |
for ref_node in ref_list: |
|
2624.2.17
by Robert Collins
Review feedback. |
1492 |
if ref_node[:self.prefix_len] != self.prefix: |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1493 |
raise errors.BadIndexData(self) |
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1494 |
yield node[0], node[1][self.prefix_len:], node[2], ( |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1495 |
tuple(tuple(ref_node[self.prefix_len:] for ref_node in ref_list) |
|
2624.2.14
by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data. |
1496 |
for ref_list in node[3])) |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1497 |
|
1498 |
def iter_all_entries(self): |
|
1499 |
"""Iterate over all keys within the index |
|
1500 |
||
1501 |
iter_all_entries is implemented against the adapted index using
|
|
1502 |
iter_entries_prefix.
|
|
1503 |
||
|
2592.5.1
by Martin Pool
Fix docstrings for Index.iter_entries etc |
1504 |
:return: An iterable of (index, key, reference_lists, value). There is no
|
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1505 |
defined order for the result iteration - it will be in the most
|
1506 |
efficient order for the index (in this case dictionary hash order).
|
|
1507 |
"""
|
|
|
2624.2.19
by Robert Collins
Why we should always test before committing. |
1508 |
return self._strip_prefix(self.adapted.iter_entries_prefix([self.prefix_key])) |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1509 |
|
1510 |
def iter_entries(self, keys): |
|
1511 |
"""Iterate over keys within the index. |
|
1512 |
||
1513 |
:param keys: An iterable providing the keys to be retrieved.
|
|
|
2979.2.4
by Robert Collins
Docstring fixes from review. |
1514 |
:return: An iterable of (index, key, value, reference_lists). There is no
|
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1515 |
defined order for the result iteration - it will be in the most
|
1516 |
efficient order for the index (keys iteration order in this case).
|
|
1517 |
"""
|
|
1518 |
return self._strip_prefix(self.adapted.iter_entries( |
|
|
2624.2.17
by Robert Collins
Review feedback. |
1519 |
self.prefix + key for key in keys)) |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1520 |
|
1521 |
def iter_entries_prefix(self, keys): |
|
1522 |
"""Iterate over keys within the index using prefix matching. |
|
1523 |
||
1524 |
Prefix matching is applied within the tuple of a key, not to within
|
|
1525 |
the bytestring of each key element. e.g. if you have the keys ('foo',
|
|
1526 |
'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
|
|
1527 |
only the former key is returned.
|
|
1528 |
||
1529 |
:param keys: An iterable providing the key prefixes to be retrieved.
|
|
1530 |
Each key prefix takes the form of a tuple the length of a key, but
|
|
1531 |
with the last N elements 'None' rather than a regular bytestring.
|
|
1532 |
The first element cannot be 'None'.
|
|
1533 |
:return: An iterable as per iter_all_entries, but restricted to the
|
|
1534 |
keys with a matching prefix to those supplied. No additional keys
|
|
1535 |
will be returned, and every match that is in the index will be
|
|
1536 |
returned.
|
|
1537 |
"""
|
|
1538 |
return self._strip_prefix(self.adapted.iter_entries_prefix( |
|
|
2624.2.17
by Robert Collins
Review feedback. |
1539 |
self.prefix + key for key in keys)) |
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1540 |
|
|
2624.2.16
by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index. |
1541 |
def key_count(self): |
1542 |
"""Return an estimate of the number of keys in this index. |
|
1543 |
|
|
1544 |
For GraphIndexPrefixAdapter this is relatively expensive - key
|
|
1545 |
iteration with the prefix is done.
|
|
1546 |
"""
|
|
1547 |
return len(list(self.iter_all_entries())) |
|
1548 |
||
|
2624.2.12
by Robert Collins
Create an adapter between indices with differing key lengths. |
1549 |
def validate(self): |
1550 |
"""Call the adapted's validate.""" |
|
1551 |
self.adapted.validate() |