Debian Codegraph @

tests/testlib/persistent-nodemap-race-ext.py

raw
1 r"""Create the race condition for issue6554
2
3 The persistent nodemap issues had an issue where a second writer could
4 overwrite the data that a previous write just wrote. The would break the append
5 only garantee of the persistent nodemap and could confuse reader. This
6 extensions create all the necessary synchronisation point to the race condition
7 to happen.
8
9 It involves 3 process <LEFT> (a writer) <RIGHT> (a writer) and <READER>
10
11 [1] <LEFT> take the lock and start a transaction
12 [2] <LEFT> updated `00changelog.i` with the new data
13 [3] <RIGHT> reads:
14 - the new changelog index `00changelog.i`
15 - the old `00changelog.n`
16 [4] <LEFT> update the persistent nodemap:
17 - writing new data from the last valid offset
18 - updating the docket (00changelog.n)
19 [5] <LEFT> release the lock
20 [6] <RIGHT> grab the lock and run `repo.invalidate`
21 [7] <READER> reads:
22 - the changelog index after <LEFT> write
23 - the nodemap docket after <LEFT> write
24 [8] <RIGHT> reload the changelog since `00changelog.n` changed
25 /!\ This is the faulty part in issue 6554, the outdated docket is kept
26 [9] <RIGHT> write:
27 - the changelog index (00changelog.i)
28 - the nodemap data (00changelog*.nd)
29 /!\ if the outdated docket is used, the write starts from the same ofset
30 /!\ as in [4], overwriting data that <LEFT> wrote in step [4].
31 - the nodemap docket (00changelog.n)
32 [10] <READER> reads the nodemap data from `00changelog*.nd`
33 /!\ if step [9] was wrong, the data matching the docket that <READER>
34 /!\ loaded have been overwritten and the expected root-nodes is no longer
35 /!\ valid.
36 """
37
38
39 import os
40
41 from mercurial.revlogutils.constants import KIND_CHANGELOG
42
43 from mercurial import (
44 changelog,
45 encoding,
46 extensions,
47 node,
48 pycompat,
49 registrar,
50 scmutil,
51 testing,
52 util,
53 )
54
55 from mercurial.revlogutils import (
56 nodemap as nodemaputil,
57 )
58
59 configtable = {}
60 configitem = registrar.configitem(configtable)
61
62 configitem(b'devel', b'nodemap-race.role', default=None)
63
64 cmdtable = {}
65 command = registrar.command(cmdtable)
66
67 LEFT = b'left'
68 RIGHT = b'right'
69 READER = b'reader'
70
71 SYNC_DIR = os.path.join(encoding.environ[b'TESTTMP'], b'sync-files')
72
73 # mark the end of step [1]
74 FILE_LEFT_LOCKED = os.path.join(SYNC_DIR, b'left-locked')
75 # mark that step [3] is ready to run.
76 FILE_RIGHT_READY_TO_LOCK = os.path.join(SYNC_DIR, b'right-ready-to-lock')
77
78 # mark the end of step [2]
79 FILE_LEFT_CL_DATA_WRITE = os.path.join(SYNC_DIR, b'left-data')
80 # mark the end of step [4]
81 FILE_LEFT_CL_NODEMAP_WRITE = os.path.join(SYNC_DIR, b'left-nodemap')
82 # mark the end of step [3]
83 FILE_RIGHT_CL_NODEMAP_READ = os.path.join(SYNC_DIR, b'right-nodemap')
84 # mark that step [9] is read to run
85 FILE_RIGHT_CL_NODEMAP_PRE_WRITE = os.path.join(
86 SYNC_DIR, b'right-pre-nodemap-write'
87 )
88 # mark that step [9] has run.
89 FILE_RIGHT_CL_NODEMAP_POST_WRITE = os.path.join(
90 SYNC_DIR, b'right-post-nodemap-write'
91 )
92 # mark that step [7] is ready to run
93 FILE_READER_READY = os.path.join(SYNC_DIR, b'reader-ready')
94 # mark that step [7] has run
95 FILE_READER_READ_DOCKET = os.path.join(SYNC_DIR, b'reader-read-docket')
96
97
98 SYNC_READ = [False]
99
100 # by default, use builtin "print" for display
101 #
102 # don't seem to be able to use print with chg
103 _print = print
104
105
106 def _role(repo):
107 """find the role associated with the process"""
108 return repo.ui.config(b'devel', b'nodemap-race.role')
109
110
111 def wrap_changelog_finalize(orig, cl, tr):
112 """wrap the update of `00changelog.i` during transaction finalization
113
114 This is useful for synchronisation before or after the file is updated on disk.
115 """
116 role = getattr(tr, '_race_role', None)
117 if role == RIGHT:
118 _print('right ready to write, waiting for reader')
119 testing.wait_file(FILE_READER_READY)
120 testing.write_file(FILE_RIGHT_CL_NODEMAP_PRE_WRITE)
121 testing.wait_file(FILE_READER_READ_DOCKET)
122 _print('right proceeding with writing its changelog index and nodemap')
123 ret = orig(cl, tr)
124 _print("finalized changelog write")
125 if role == LEFT:
126 testing.write_file(FILE_LEFT_CL_DATA_WRITE)
127 return ret
128
129
130 def wrap_persist_nodemap(orig, tr, revlog, *args, **kwargs):
131 """wrap the update of `00changelog.n` and `*.nd` during tr finalization
132
133 This is useful for synchronisation before or after the files are updated on
134 disk.
135 """
136 is_cl = revlog.target[0] == KIND_CHANGELOG
137 role = getattr(tr, '_race_role', None)
138 if is_cl:
139 if role == LEFT:
140 testing.wait_file(FILE_RIGHT_CL_NODEMAP_READ)
141 if is_cl:
142 _print("persisting changelog nodemap")
143 _print(" new data start at", revlog._nodemap_docket.data_length)
144 ret = orig(tr, revlog, *args, **kwargs)
145 if is_cl:
146 _print("persisted changelog nodemap")
147 print_nodemap_details(revlog)
148 if role == LEFT:
149 testing.write_file(FILE_LEFT_CL_NODEMAP_WRITE)
150 elif role == RIGHT:
151 testing.write_file(FILE_RIGHT_CL_NODEMAP_POST_WRITE)
152 return ret
153
154
155 def print_nodemap_details(cl):
156 """print relevant information about the nodemap docket currently in memory"""
157 dkt = cl._nodemap_docket
158 _print('docket-details:')
159 if dkt is None:
160 _print(' <no-docket>')
161 return
162 _print(' uid: ', pycompat.sysstr(dkt.uid))
163 _print(' actual-tip: ', cl.tiprev())
164 _print(' tip-rev: ', dkt.tip_rev)
165 _print(' data-length:', dkt.data_length)
166
167
168 def wrap_persisted_data(orig, revlog):
169 """print some information about the nodemap information we just read
170
171 Used by the <READER> process only.
172 """
173 role = revlog.opener.options.get('_race_role')
174 if role == READER:
175 SYNC_READ[0] = True
176 ret = orig(revlog)
177 if role == READER:
178 SYNC_READ[0] = False
179 if ret is not None:
180 docket, data = ret
181 file_path = nodemaputil._rawdata_filepath(revlog, docket)
182 file_path = revlog.opener.join(file_path)
183 file_size = os.path.getsize(file_path)
184 _print('record-data-length:', docket.data_length)
185 _print('actual-data-length:', len(data))
186 _print('file-actual-length:', file_size)
187 return ret
188
189
190 def sync_read(orig):
191 """used by <READER> to force the race window
192
193 This make sure we read the docker from <LEFT> while reading the datafile
194 after <RIGHT> write.
195 """
196 orig()
197 if SYNC_READ[0]:
198 testing.write_file(FILE_READER_READ_DOCKET)
199 _print('reader: nodemap docket read')
200 testing.wait_file(FILE_RIGHT_CL_NODEMAP_POST_WRITE)
201
202
203 def make_print(ui):
204 def ui_print(*args):
205 pieces = []
206 for a in args:
207 if isinstance(a, int):
208 a = b"%d" % a
209 elif hasattr(a, 'encode'):
210 a = a.encode("ascii")
211 pieces.append(a)
212 ui.write(b' '.join(pieces) + b'\n')
213
214 return ui_print
215
216
217 def wrap_printer(orig, ui, func):
218 global _print
219 old_print = _print
220 try:
221 _print = make_print(ui)
222 return orig(ui, func)
223 finally:
224 _print = old_print
225
226
227 class RacedRepoMixin:
228 def lock(self, wait=True):
229 # make sure <RIGHT> as the "Wrong" information in memory before
230 # grabbing the lock
231 newlock = self._currentlock(self._lockref) is None
232 if newlock and _role(self) == LEFT:
233 cl = self.unfiltered().changelog
234 print_nodemap_details(cl)
235 elif newlock and _role(self) == RIGHT:
236 testing.write_file(FILE_RIGHT_READY_TO_LOCK)
237 _print('nodemap-race: right side start of the locking sequence')
238 testing.wait_file(FILE_LEFT_LOCKED)
239 testing.wait_file(FILE_LEFT_CL_DATA_WRITE)
240 self.invalidate(clearfilecache=True)
241 _print('nodemap-race: right side reading changelog')
242 cl = self.unfiltered().changelog
243 tiprev = cl.tiprev()
244 tip = cl.node(tiprev)
245 tiprev2 = cl.rev(tip)
246 if tiprev != tiprev2:
247 msg = 'bad tip -round-trip %d %d'
248 msg %= (tiprev, tiprev2)
249 raise RuntimeError(msg)
250 testing.write_file(FILE_RIGHT_CL_NODEMAP_READ)
251 _print('nodemap-race: right side reading of changelog is done')
252 print_nodemap_details(cl)
253 testing.wait_file(FILE_LEFT_CL_NODEMAP_WRITE)
254 _print('nodemap-race: right side ready to wait for the lock')
255 ret = super().lock(wait=wait)
256 if newlock and _role(self) == LEFT:
257 _print('nodemap-race: left side locked and ready to commit')
258 testing.write_file(FILE_LEFT_LOCKED)
259 testing.wait_file(FILE_RIGHT_READY_TO_LOCK)
260 cl = self.unfiltered().changelog
261 print_nodemap_details(cl)
262 elif newlock and _role(self) == RIGHT:
263 _print('nodemap-race: right side locked and ready to commit')
264 cl = self.unfiltered().changelog
265 print_nodemap_details(cl)
266 return ret
267
268 def transaction(self, *args, **kwargs):
269 # duck punch the role on the transaction to help other pieces of code
270 tr = super().transaction(*args, **kwargs)
271 tr._race_role = _role(self)
272 return tr
273
274 @util.propertycache
275 def changelog(self):
276 self.svfs.options['_race_role'] = _role(self)
277 if _role(self) == READER:
278 _print('reader ready to read the changelog, waiting for right')
279 testing.write_file(FILE_READER_READY)
280 testing.wait_file(FILE_RIGHT_CL_NODEMAP_PRE_WRITE)
281 cl = super().changelog
282 cl._role = _role(self)
283 return cl
284
285
286 def uisetup(ui):
287 extensions.wrapfunction(
288 nodemaputil,
289 'persist_nodemap',
290 wrap_persist_nodemap,
291 )
292 extensions.wrapfunction(
293 changelog.changelog,
294 '_finalize',
295 wrap_changelog_finalize,
296 )
297 extensions.wrapfunction(
298 nodemaputil,
299 'persisted_data',
300 wrap_persisted_data,
301 )
302 extensions.wrapfunction(nodemaputil, 'test_race_hook_1', sync_read)
303
304 extensions.wrapfunction(scmutil, 'callcatch', wrap_printer)
305
306
307 def reposetup(ui, repo):
308 if not isinstance(repo, RacedRepoMixin):
309
310 class Wrapped(RacedRepoMixin, repo.__class__):
311 pass
312
313 repo.__class__ = Wrapped
314
315
316 @command(b'check-nodemap-race')
317 def cmd_check_nodemap_race(ui, repo):
318 """Run proper <READER> access in the race Windows and check nodemap content"""
319 repo = repo.unfiltered()
320 _print('reader: reading changelog')
321 cl = repo.changelog
322 _print('reader: changelog read')
323 print_nodemap_details(cl)
324 tip_rev = cl.tiprev()
325 tip_node = cl.node(tip_rev)
326 _print('tip-rev: ', tip_rev)
327 _print('tip-node:', node.short(tip_node).decode('ascii'))
328 _print('node-rev:', cl.rev(tip_node))
329 for r in cl.revs():
330 n = cl.node(r)
331 try:
332 r2 = cl.rev(n)
333 except ValueError as exc:
334 _print('error while checking revision:', r)
335 _print(' ', exc)
336 return 1
337 else:
338 if r2 != r:
339 _print('revision %d is missing from the nodemap' % r)
340 return 1