Debian Codegraph @

tests/artifacts/scripts/generate-churning-bundle.py

raw
1 #!/usr/bin/env python3
2 #
3 # generate-branchy-bundle - generate a branch for a "large" branchy repository
4 #
5 # Copyright 2018 Octobus, [email protected]
6 #
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
9 #
10 # This script generates a repository suitable for testing delta computation
11 # strategies.
12 #
13 # The repository update a single "large" file with many updates. One fixed part
14 # of the files always get updated while the rest of the lines get updated over
15 # time. This update happens over many topological branches, some getting merged
16 # back.
17 #
18 # --lazy will skip generating the file if one exist with the right content
19 # already.
20 # --validate make sure the generated bundle has the expected content.
21
22
23 import hashlib
24 import os
25 import shutil
26 import subprocess
27 import sys
28 import tempfile
29
30 import mercurial.context
31 import mercurial.repo.factory
32 import mercurial.ui
33
34 BUNDLE_NAME = 'big-file-churn.hg'
35
36 # constants for generating the repository
37 NB_CHANGESET = 5000
38 PERIOD_MERGING = 8
39 PERIOD_BRANCHING = 7
40 MOVE_BACK_MIN = 3
41 MOVE_BACK_RANGE = 5
42
43 # constants for generating the large file we keep updating
44 #
45 # At each revision, the beginning on the file change,
46 # and set of other lines changes too.
47 FILENAME = 'SPARSE-REVLOG-TEST-FILE'
48 NB_LINES = 10500
49 ALWAYS_CHANGE_LINES = 50
50 OTHER_CHANGES = 300
51
52
53 def build_graph():
54 heads = {0}
55 graph = {0: (None, None)}
56 for idx in range(1, NB_CHANGESET + 1):
57 p, _ = parents = [idx - 1, None]
58 if (idx % PERIOD_BRANCHING) == 0:
59 back = MOVE_BACK_MIN + (idx % MOVE_BACK_RANGE)
60 for _ in range(back):
61 p = graph.get(p, (p,))[0]
62 parents[0] = p
63 if (idx % PERIOD_MERGING) == 0:
64 parents[1] = min(heads)
65 for p in parents:
66 heads.discard(p)
67 heads.add(idx)
68 graph[idx] = tuple(parents)
69 return graph
70
71
72 GRAPH = build_graph()
73
74
75 def nextcontent(previous_content):
76 """utility to produce a new file content from the previous one"""
77 return hashlib.md5(previous_content).hexdigest().encode('ascii')
78
79
80 # make sure some of the revision change the same lines, to let the delta
81 # folding have overwritten line to play with.
82
83 SHIFT_GROUP = [
84 17,
85 13,
86 11,
87 7,
88 17,
89 13,
90 5,
91 17,
92 11,
93 7,
94 13,
95 17,
96 3,
97 11,
98 17,
99 13,
100 5,
101 17,
102 7,
103 11,
104 13,
105 17,
106 ]
107
108
109 def filecontent(iteridx, oldcontent):
110 """generate a new file content
111
112 The content is generated according the iteration index and previous
113 content"""
114
115 # initial call
116 if iteridx == 0:
117 current = b''
118 else:
119 current = b"%d" % iteridx
120
121 for idx in range(NB_LINES):
122 iter_shift = iteridx // SHIFT_GROUP[idx % len(SHIFT_GROUP)]
123 do_change_line = True
124 if oldcontent is not None and ALWAYS_CHANGE_LINES < idx:
125 do_change_line = not ((idx - iter_shift) % OTHER_CHANGES)
126
127 if do_change_line:
128 to_write = current + b'\n'
129 current = nextcontent(current)
130 else:
131 to_write = oldcontent[idx]
132 yield to_write
133
134
135 def merge_content(base, left, right):
136 """merge two file content to produce a new one
137
138 use unambiguous update on each side when possible, and produce a new line
139 whenever a merge is needed. Similar to what the manifest would do.
140 """
141 for old, left, right in zip(base, left, right):
142 if old == left and old == right:
143 yield old
144 elif old == left and old != right:
145 yield right
146 elif old != left and old == right:
147 yield left
148 else:
149 yield nextcontent(left + right)
150
151
152 def ancestors(graph, rev):
153 """return the set of ancestors of revision <rev>"""
154 to_proceed = {rev}
155 seen = set(to_proceed)
156 while to_proceed:
157 current = to_proceed.pop()
158 for p in graph[current]:
159 if p is None:
160 continue
161 if p in seen:
162 continue
163 to_proceed.add(p)
164 seen.add(p)
165 return seen
166
167
168 def gca(graph, left, right):
169 """find the greater common ancestors of left and right
170
171 Note that the algorithm is stupid and N² when run on all merge, however
172 this should not be a too much issue given the current scale.
173 """
174 return max(ancestors(graph, left) & ancestors(graph, right))
175
176
177 def make_one_content_fn(idx, base, left, right):
178 """build a function that build the content on demand
179
180 The dependency are kept are reference to make sure they are not
181 garbage-collected until we use them. Once we computed the current content,
182 we make sure to drop their reference to allow them to be garbage collected.
183 """
184
185 def content_fn(idx=idx, base=base, left=left, right=right):
186 if left is None:
187 new = filecontent(idx, None)
188 elif base is None:
189 new = filecontent(idx, left())
190 else:
191 merged = merge_content(base(), left(), right())
192 new = filecontent(idx, list(merged))
193 return list(new)
194
195 del idx
196 del base
197 del left
198 del right
199
200 value = None
201 cf = [content_fn]
202 del content_fn
203
204 def final_fn():
205 nonlocal value
206 if value is None:
207 content_fn = cf.pop()
208 value = list(content_fn())
209 del content_fn
210 return value
211
212 return final_fn
213
214
215 def build_content_graph(graph):
216 """produce file content for all revision
217
218 The content will be generated on demande and cached. Cleanup the
219 dictionnary are you use it to reduce memory usage.
220 """
221 content = {}
222 for idx, (p1, p2) in graph.items():
223 base = left = right = None
224 if p1 is not None:
225 left = content[p1]
226 if p2 is not None:
227 right = content[p2]
228 base_rev = gca(graph, p1, p2)
229 base = content[base_rev]
230 content[idx] = make_one_content_fn(idx, base, left, right)
231 return content
232
233
234 CONTENT = build_content_graph(GRAPH)
235
236
237 def hg(command, *args):
238 """call a mercurial command with appropriate config and argument"""
239 env = os.environ.copy()
240 if 'CHGHG' in env:
241 full_cmd = ['chg']
242 else:
243 full_cmd = ['hg']
244 full_cmd.append('--quiet')
245 full_cmd.append(command)
246 if command == 'commit':
247 # reproducible commit metadata
248 full_cmd.extend(['--date', '0 0', '--user', 'test'])
249 elif command == 'merge':
250 # avoid conflicts by picking the local variant
251 full_cmd.extend(['--tool', ':merge-local'])
252 full_cmd.extend(args)
253 env['HGRCPATH'] = ''
254 return subprocess.check_call(full_cmd, env=env)
255
256
257 def write_repo(path):
258 """write repository content in memory"""
259 repo = mercurial.repo.factory.repository(
260 mercurial.ui.ui.load(),
261 path=path.encode('utf-8'),
262 )
263 nodemap = {None: repo.nodeconstants.nullid}
264 with repo.lock(), repo.transaction(b'bundle-generation'):
265 for idx, (p1, p2) in GRAPH.items():
266 if sys.stdout.isatty():
267 print("generating commit #%d/%d" % (idx, NB_CHANGESET))
268
269 file_fn = lambda repo, memctx, path: mercurial.context.memfilectx(
270 repo,
271 memctx,
272 path,
273 data=b''.join(CONTENT.pop(idx)()),
274 )
275
276 mc = mercurial.context.memctx(
277 repo,
278 (nodemap[p1], nodemap[p2]),
279 b'commit #%d' % idx if idx else b'initial commit',
280 [FILENAME.encode('ascii')],
281 file_fn,
282 user=b"test",
283 date=(0, 0),
284 )
285 nodemap[idx] = repo.commitctx(mc)
286
287
288 def compute_md5(target):
289 with open(target, 'rb') as bundle:
290 data = bundle.read()
291 return hashlib.md5(data).hexdigest()
292
293
294 def write_md5(target, md5):
295 with open(target + '.md5', 'wb') as md5file:
296 md5file.write(md5.encode('ascii') + b'\n')
297
298
299 def read_md5(target):
300 with open(target + '.md5', 'rb') as md5file:
301 return md5file.read().strip().decode('ascii')
302
303
304 def up_to_date_target(target):
305 """return true if the file already exist at the right"""
306 try:
307 found = compute_md5(target)
308 expected = read_md5(target)
309 except OSError:
310 return False
311 return found == expected
312
313
314 def run(target, validate=False):
315 tmpdir = tempfile.mkdtemp(prefix='tmp-hg-test-big-file-bundle-')
316 cwd = os.getcwd()
317
318 tmp_name = "%s-%d" % (target, os.getpid())
319 try:
320 os.chdir(tmpdir)
321 hg(
322 'init',
323 '--config',
324 'format.maxchainlen=%d' % NB_CHANGESET,
325 )
326 write_repo(tmpdir)
327 hg('bundle', '--all', tmp_name, '--config', 'devel.bundle.delta=p1')
328 os.replace(tmp_name, target)
329 digest = compute_md5(target)
330 if not validate:
331 write_md5(target, digest)
332 else:
333 expected = read_md5(target)
334 if expected != digest:
335 msg = "bundle generated does not match the expected content\n"
336 msg += " expected: %s\n" % expected
337 msg += " got: %s" % digest
338 print(msg, file=sys.stderr)
339 return 1
340 finally:
341 # Windows does not let you remove the current working directory
342 os.chdir(cwd)
343 shutil.rmtree(tmpdir)
344 if os.path.exists(tmp_name):
345 os.remove(tmp_name)
346 return 0
347
348
349 if __name__ == '__main__':
350 orig = os.path.realpath(os.path.dirname(sys.argv[0]))
351 target = os.path.join(orig, os.pardir, 'cache', BUNDLE_NAME)
352 lazy = '--lazy' in sys.argv[1:]
353 validate = '--validate' in sys.argv[1:]
354
355 if lazy and up_to_date_target(target):
356 sys.exit(0)
357 sys.exit(run(target, validate=validate))