跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

fs_suite.py

852 行 · 27.6 KB历史下载
1#!/usr/bin/env python3
2"""Differential file system tests for sshocker's rooted SFTP server, through real sshfs.
3
4 fs_suite.py <harness binary> <workdir> [case-substring...]
5
6<harness binary> is a build.sh harness, or openssh_harness.sh as a control.
7<workdir> must be on the VM's own disk. Each case runs once in <workdir>/mnt
8(sshfs served by the harness from <workdir>/host) and once in <workdir>/ref (a
9plain directory). Reported per case:
10 CRASH the server died during the case (in Lima: the hostagent and the vz VM)
11 HANG the case did not finish in time
12 DIFF results or the resulting tree differ from the plain directory
13 FDLEAK the server holds more fds after the case than before
14 ok same as the plain directory
15SFTP v3 cannot express everything POSIX can: many DIFFs are expected, triage them.
16"""
17import ctypes
18import errno
19import fcntl
20import hashlib
21import mmap
22import multiprocessing as mp
23import os
24import random
25import shutil
26import stat
27import subprocess
28import sys
29import threading
30import time
31
32CASE_TIMEOUT = 60
33CASES = []
34
35
36def case(fn):
37 CASES.append(fn)
38 return fn
39
40
41def op(f, *a, **kw):
42 """('ok', value) or ('err', errno name), comparable between the two runs."""
43 try:
44 v = f(*a, **kw)
45 if isinstance(v, os.stat_result): # inode and device numbers differ between file systems
46 return ("ok", ("stat", stat.filemode(v.st_mode), v.st_nlink, v.st_size))
47 return ("ok", v if isinstance(v, (int, str, bytes, bool, type(None), tuple)) else type(v).__name__)
48 except OSError as e:
49 return ("err", errno.errorcode.get(e.errno, str(e.errno)))
50
51
52def wfile(p, data, mode=0o644):
53 fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
54 try:
55 os.write(fd, data)
56 finally:
57 os.close(fd)
58
59
60def rfile(p):
61 with open(p, "rb") as f:
62 return f.read()
63
64
65def mode_of(p):
66 return oct(stat.S_IMODE(os.lstat(p).st_mode))
67
68
69# ---------------------------------------------------------------- open flags and appends
70
71@case
72def append_existing_wronly(d):
73 wfile(f"{d}/f", b"head\n")
74 fd = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND)
75 r = [op(os.write, fd, b"tail\n")]
76 os.close(fd)
77 return r + [rfile(f"{d}/f")]
78
79
80@case
81def append_new_file(d):
82 fd = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
83 r = [op(os.write, fd, b"x")]
84 os.close(fd)
85 return r + [rfile(f"{d}/f"), mode_of(f"{d}/f")]
86
87
88@case
89def append_rdwr(d):
90 wfile(f"{d}/f", b"abc")
91 fd = os.open(f"{d}/f", os.O_RDWR | os.O_APPEND)
92 r = [op(os.write, fd, b"def"), op(os.pread, fd, 6, 0)]
93 os.close(fd)
94 return r
95
96
97@case
98def append_after_seek(d):
99 # O_APPEND must write at the end whatever the file position
100 wfile(f"{d}/f", b"0123456789")
101 fd = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND)
102 os.lseek(fd, 0, os.SEEK_SET)
103 r = [op(os.write, fd, b"X")]
104 os.close(fd)
105 return r + [rfile(f"{d}/f")]
106
107
108@case
109def append_two_fds_interleaved(d):
110 wfile(f"{d}/f", b"")
111 a = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND)
112 b = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND)
113 for i in range(20):
114 os.write(a if i % 2 == 0 else b, b"%02d\n" % i)
115 os.close(a)
116 os.close(b)
117 return [rfile(f"{d}/f")]
118
119
120@case
121def append_shell_redirect(d):
122 wfile(f"{d}/f", b"header\n")
123 r = subprocess.run(["bash", "-c", "printf 'a\\n' >> f && seq 1 500 >> f && echo z >> f"], cwd=d)
124 return [r.returncode, hashlib.sha256(rfile(f"{d}/f")).hexdigest()]
125
126
127@case
128def append_after_host_change(d):
129 # The host (here: the other side of the share) grows the file, then the guest appends.
130 # Through sshfs's attribute cache the guest may append at the old end and overwrite.
131 wfile(f"{d}/f", b"guest1\n")
132 os.stat(f"{d}/f")
133 host = HOST_OF(d)
134 with open(f"{host}/f", "ab") as f:
135 f.write(b"host-wrote-this-line\n")
136 fd = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND)
137 os.write(fd, b"guest2\n")
138 os.close(fd)
139 return [rfile(f"{host}/f")]
140
141
142@case
143def open_flag_matrix(d):
144 out = []
145 flags = {"RDONLY": os.O_RDONLY, "WRONLY": os.O_WRONLY, "RDWR": os.O_RDWR}
146 extra = {"": 0, "CREAT": os.O_CREAT, "TRUNC": os.O_TRUNC, "CREAT|EXCL": os.O_CREAT | os.O_EXCL,
147 "CREAT|TRUNC": os.O_CREAT | os.O_TRUNC, "APPEND": os.O_APPEND,
148 "APPEND|TRUNC": os.O_APPEND | os.O_TRUNC, "CREAT|APPEND|EXCL": os.O_CREAT | os.O_APPEND | os.O_EXCL}
149 for an, a in flags.items():
150 for en, e in extra.items():
151 for target in ["exists", "new"]:
152 p = f"{d}/{an}_{en.replace('|', '_')}_{target}"
153 if target == "exists":
154 wfile(p, b"orig")
155 r = op(os.open, p, a | e, 0o600)
156 if r[0] == "ok":
157 fd = r[1]
158 out.append((an, en, target, "open ok", op(os.write, fd, b"W"), op(os.pread, fd, 8, 0)))
159 os.close(fd)
160 else:
161 out.append((an, en, target, r))
162 if os.path.exists(p):
163 out.append((an, en, target, rfile(p), mode_of(p)))
164 return out
165
166
167@case
168def create_modes(d):
169 old = os.umask(0)
170 try:
171 out = []
172 for m in [0o755, 0o700, 0o644, 0o600, 0o444, 0o000, 0o4755, 0o2755, 0o1777]:
173 p = f"{d}/m{m:o}"
174 out.append((oct(m), op(os.close, os.open(p, os.O_WRONLY | os.O_CREAT, m)), mode_of(p)))
175 for m in [0o755, 0o700, 0o1777, 0o000]:
176 p = f"{d}/d{m:o}"
177 out.append(("dir", oct(m), op(os.mkdir, p, m), mode_of(p)))
178 os.chmod(p, 0o755)
179 return out
180 finally:
181 os.umask(old)
182
183
184# ---------------------------------------------------------------- sizes, holes, big files
185
186@case
187def truncate_grow_shrink(d):
188 wfile(f"{d}/f", b"0123456789")
189 r = [op(os.truncate, f"{d}/f", 4), rfile(f"{d}/f"), op(os.truncate, f"{d}/f", 12), rfile(f"{d}/f")]
190 fd = os.open(f"{d}/f", os.O_RDWR)
191 r += [op(os.ftruncate, fd, 2), op(os.pread, fd, 20, 0)]
192 os.close(fd)
193 return r + [op(os.truncate, f"{d}/f", 0), rfile(f"{d}/f")]
194
195
196@case
197def truncate_after_chmod_readonly(d):
198 wfile(f"{d}/f", b"0123456789")
199 fd = os.open(f"{d}/f", os.O_RDWR)
200 os.chmod(f"{d}/f", 0o444)
201 r = [op(os.ftruncate, fd, 3), op(os.write, fd, b"ab")]
202 os.close(fd)
203 os.chmod(f"{d}/f", 0o644)
204 return r + [rfile(f"{d}/f")]
205
206
207@case
208def sparse_write(d):
209 fd = os.open(f"{d}/f", os.O_RDWR | os.O_CREAT, 0o644)
210 r = [op(os.pwrite, fd, b"end", 1 << 30), op(os.pread, fd, 4, 100), os.fstat(fd).st_size,
211 os.stat(f"{d}/f").st_size, op(os.pread, fd, 3, 1 << 30)]
212 os.ftruncate(fd, 0)
213 os.close(fd)
214 return r
215
216
217@case
218def huge_offsets(d):
219 fd = os.open(f"{d}/f", os.O_RDWR | os.O_CREAT, 0o644)
220 r = []
221 for off in [(1 << 40), (1 << 62), (1 << 63) - 2]:
222 r.append((off, op(os.pwrite, fd, b"x", off)))
223 r.append((off, op(os.pread, fd, 1, off)))
224 r.append(op(os.ftruncate, fd, (1 << 62)))
225 r.append(os.stat(f"{d}/f").st_size)
226 os.ftruncate(fd, 0)
227 os.close(fd)
228 return r
229
230
231@case
232def big_file_roundtrip(d):
233 data = random.Random(1).randbytes(1 << 20) * 64
234 wfile(f"{d}/f", data)
235 return [hashlib.sha256(rfile(f"{d}/f")).hexdigest() == hashlib.sha256(data).hexdigest()]
236
237
238@case
239def write_read_unaligned(d):
240 fd = os.open(f"{d}/f", os.O_RDWR | os.O_CREAT, 0o644)
241 blob = bytes(range(256)) * 1000
242 for off in [0, 1, 4095, 4096, 65535, 131071, 200001]:
243 os.pwrite(fd, blob[:off % 7919 + 1], off)
244 os.close(fd)
245 return [hashlib.sha256(rfile(f"{d}/f")).hexdigest()]
246
247
248@case
249def concurrent_region_writes(d):
250 wfile(f"{d}/f", b"\0" * (64 * 65536))
251
252 def w(i):
253 fd = os.open(f"{d}/f", os.O_WRONLY)
254 for k in range(16):
255 os.pwrite(fd, bytes([i]) * 4096, i * 65536 + k * 4096)
256 os.close(fd)
257 ts = [threading.Thread(target=w, args=(i,)) for i in range(64)]
258 [t.start() for t in ts]
259 [t.join() for t in ts]
260 return [hashlib.sha256(rfile(f"{d}/f")).hexdigest()]
261
262
263@case
264def concurrent_appends(d):
265 wfile(f"{d}/f", b"")
266
267 def w(i):
268 fd = os.open(f"{d}/f", os.O_WRONLY | os.O_APPEND)
269 for k in range(50):
270 os.write(fd, b"%03d-%03d\n" % (i, k))
271 os.close(fd)
272 ts = [threading.Thread(target=w, args=(i,)) for i in range(8)]
273 [t.start() for t in ts]
274 [t.join() for t in ts]
275 lines = rfile(f"{d}/f").splitlines()
276 os.unlink(f"{d}/f") # line order depends on thread scheduling
277 return [len(lines), len(set(lines))]
278
279
280# ---------------------------------------------------------------- request ordering
281# pkg/sftp's RequestServer runs reads and writes on parallel workers, and everything
282# else on another one: without WithRSSequential these come out wrong most of the time.
283
284@case
285def order_rewrite_same_block(d):
286 bad = 0
287 for i in range(100):
288 fd = os.open(f"{d}/w{i}", os.O_RDWR | os.O_CREAT, 0o644)
289 for k in range(8):
290 os.pwrite(fd, bytes([65 + k]) * 4096, 0)
291 os.close(fd)
292 if rfile(f"{HOST_OF(d)}/w{i}") != b"H" * 4096:
293 bad += 1
294 os.unlink(f"{d}/w{i}")
295 return [("host files with an older write last", bad)]
296
297
298@case
299def order_write_then_ftruncate(d):
300 bad = 0
301 for i in range(100):
302 fd = os.open(f"{d}/t{i}", os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o644)
303 os.write(fd, b"hello world")
304 os.ftruncate(fd, 2)
305 os.close(fd)
306 if rfile(f"{HOST_OF(d)}/t{i}") != b"he":
307 bad += 1
308 os.unlink(f"{d}/t{i}")
309 return [("host files not truncated", bad)]
310
311
312@case
313def order_write_then_fstat_and_read(d):
314 bad_size = bad_read = 0
315 for i in range(100):
316 fd = os.open(f"{d}/s{i}", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
317 os.write(fd, b"x" * 100)
318 if os.fstat(fd).st_size != 100:
319 bad_size += 1
320 os.close(fd)
321 if rfile(f"{d}/s{i}") != b"x" * 100:
322 bad_read += 1
323 os.unlink(f"{d}/s{i}")
324 return [("fstat size wrong", bad_size), ("read back wrong", bad_read)]
325
326
327# ---------------------------------------------------------------- metadata
328
329@case
330def chmod_matrix(d):
331 wfile(f"{d}/f", b"x")
332 out = []
333 for m in [0o000, 0o200, 0o400, 0o755, 0o4755, 0o7777, 0o644]:
334 out.append((oct(m), op(os.chmod, f"{d}/f", m), mode_of(f"{d}/f")))
335 os.mkdir(f"{d}/dir")
336 out.append(("dir 000", op(os.chmod, f"{d}/dir", 0)))
337 out.append(("create in 000 dir", op(wfile, f"{d}/dir/x", b"")))
338 out.append(("list 000 dir", op(os.listdir, f"{d}/dir")))
339 os.chmod(f"{d}/dir", 0o755)
340 return out
341
342
343@case
344def unreadable_file(d):
345 wfile(f"{d}/f", b"secret")
346 os.chmod(f"{d}/f", 0)
347 r = [op(rfile, f"{d}/f"), op(wfile, f"{d}/f", b"x")]
348 os.chmod(f"{d}/f", 0o644)
349 return r
350
351
352@case
353def chown_ops(d):
354 wfile(f"{d}/f", b"x")
355 me = os.getuid(), os.getgid()
356 return [op(os.chown, f"{d}/f", -1, -1), op(os.chown, f"{d}/f", 0, 0), op(os.chown, f"{d}/f", 12345, 12345)
357 ] + [os.stat(f"{d}/f").st_uid == me[0]]
358
359
360@case
361def utimes_ranges(d):
362 wfile(f"{d}/f", b"x")
363 out = []
364 for ns in [1_500_000_000_123_456_789, 0, -86400 * 10**9, 2**31 * 10**9, (2**32 + 5) * 10**9, 4_000_000_000 * 10**9]:
365 r = op(os.utime, f"{d}/f", ns=(ns, ns))
366 st = os.stat(f"{d}/f")
367 out.append((ns, r, st.st_mtime_ns, st.st_atime_ns))
368 return out
369
370
371@case
372def utime_now_and_touch(d):
373 wfile(f"{d}/f", b"x")
374 os.utime(f"{d}/f", (1, 1))
375 r = [op(os.utime, f"{d}/f", None)]
376 return r + [abs(os.stat(f"{d}/f").st_mtime - time.time()) < 5,
377 subprocess.run(["touch", "-d", "1960-01-01", f"{d}/f"]).returncode, os.stat(f"{d}/f").st_mtime]
378
379
380@case
381def utime_symlink_nofollow(d):
382 wfile(f"{d}/f", b"x")
383 os.symlink("f", f"{d}/l")
384 os.utime(f"{d}/f", (1000, 1000))
385 r = [op(os.utime, f"{d}/l", (5000, 5000), follow_symlinks=False)]
386 return r + [os.stat(f"{d}/f").st_mtime, os.lstat(f"{d}/l").st_mtime]
387
388
389@case
390def stat_while_writing(d):
391 fd = os.open(f"{d}/f", os.O_WRONLY | os.O_CREAT, 0o644)
392 os.write(fd, b"x" * 10000)
393 r = [os.stat(f"{d}/f").st_size, os.fstat(fd).st_size]
394 os.close(fd)
395 return r + [os.stat(f"{d}/f").st_size]
396
397
398@case
399def statvfs_root(d):
400 st = os.statvfs(d)
401 return [st.f_bsize > 0, st.f_namemax]
402
403
404# ---------------------------------------------------------------- names and directories
405
406@case
407def rename_matrix(d):
408 out = []
409 wfile(f"{d}/a", b"a")
410 wfile(f"{d}/b", b"b")
411 out.append(("file->new", op(os.rename, f"{d}/a", f"{d}/c")))
412 out.append(("file->existing", op(os.rename, f"{d}/c", f"{d}/b")))
413 out.append(("content", rfile(f"{d}/b")))
414 out.append(("replace", op(os.replace, f"{d}/b", f"{d}/b2")))
415 os.makedirs(f"{d}/d1/sub")
416 os.makedirs(f"{d}/d2")
417 os.makedirs(f"{d}/d3/x")
418 out.append(("dir->empty dir", op(os.rename, f"{d}/d1", f"{d}/d2")))
419 out.append(("dir->nonempty dir", op(os.rename, f"{d}/d2", f"{d}/d3")))
420 out.append(("dir->own child", op(os.rename, f"{d}/d3", f"{d}/d3/x/y")))
421 out.append(("file->dir", op(os.rename, f"{d}/b2", f"{d}/d3")))
422 out.append(("dir->file", op(os.rename, f"{d}/d3", f"{d}/b2")))
423 out.append(("missing", op(os.rename, f"{d}/nope", f"{d}/x")))
424 out.append(("same", op(os.rename, f"{d}/b2", f"{d}/b2")))
425 wfile(f"{d}/h1", b"h")
426 os.link(f"{d}/h1", f"{d}/h2")
427 out.append(("hardlinks same inode", op(os.rename, f"{d}/h1", f"{d}/h2"), sorted(os.listdir(d))))
428 return out
429
430
431@case
432def renameat2_flags(d):
433 libc = ctypes.CDLL(None, use_errno=True)
434 out = []
435 for name, flags in [("NOREPLACE", 1), ("EXCHANGE", 2)]:
436 wfile(f"{d}/x", b"x")
437 wfile(f"{d}/y", b"y")
438 rc = libc.renameat2(-100, f"{d}/x".encode(), -100, f"{d}/y".encode(), flags)
439 out.append((name, rc, errno.errorcode.get(ctypes.get_errno(), 0) if rc else "",
440 op(rfile, f"{d}/x"), op(rfile, f"{d}/y")))
441 return out
442
443
444@case
445def links(d):
446 wfile(f"{d}/f", b"x")
447 out = [op(os.link, f"{d}/f", f"{d}/h"), os.stat(f"{d}/f").st_nlink,
448 op(os.symlink, "f", f"{d}/rel"), op(os.symlink, f"{d}/f", f"{d}/abs"),
449 op(os.symlink, "missing", f"{d}/dangling"), op(os.symlink, "a" * 4000, f"{d}/longtarget"),
450 op(os.symlink, "f", f"{d}/rel"), op(os.readlink, f"{d}/rel"), op(rfile, f"{d}/rel"),
451 op(rfile, f"{d}/dangling"), op(os.readlink, f"{d}/longtarget"),
452 op(os.link, f"{d}/rel", f"{d}/hardlink_to_symlink"), op(os.link, d, f"{d}/dirlink")]
453 os.mkdir(f"{d}/sub")
454 out += [op(os.symlink, "../f", f"{d}/sub/up"), op(rfile, f"{d}/sub/up")]
455 out += [op(os.symlink, "self", f"{d}/self"), op(rfile, f"{d}/self")]
456 return out
457
458
459@case
460def dir_ops(d):
461 os.mkdir(f"{d}/x")
462 wfile(f"{d}/x/f", b"")
463 wfile(f"{d}/file", b"")
464 return [op(os.mkdir, f"{d}/x"), op(os.rmdir, f"{d}/x"), op(os.rmdir, f"{d}/file"),
465 op(os.unlink, f"{d}/x"), op(os.mkdir, f"{d}/file/sub"), op(os.rmdir, f"{d}/x/."),
466 op(os.mkdir, f"{d}/missing/sub"), op(os.listdir, f"{d}/file")]
467
468
469@case
470def names(d):
471 out = []
472 for n in ["café", "café", "😀", "a b", " lead", "trail ", "new\nline", "tab\t", "back\\slash",
473 "co:lon", "q?uest", "star*", "pipe|", "lt<gt>", "dquote\"", "%25", "-dash", "~tilde",
474 "x" * 255, "y" * 256, "\x01ctl", "\x7f", "\udcff".encode("utf-8", "surrogateescape").decode("utf-8", "surrogateescape")]:
475 p = f"{d}/{n}"
476 r = op(wfile, p, n.encode("utf-8", "surrogateescape"))
477 out.append((repr(n)[:40], r, op(rfile, p) if r[0] == "ok" else None))
478 raw = os.fsencode(d) + b"/\xff\xfe-invalid-utf8"
479 r = op(wfile, raw, b"bin")
480 out.append(("invalid utf8", r))
481 out.append(sorted(os.listdir(d)))
482 return out
483
484
485@case
486def deep_path(d):
487 p = d
488 out = []
489 for i in range(60):
490 p = f"{p}/{'d' * 60}"
491 r = op(os.mkdir, p)
492 if r[0] != "ok":
493 out.append((i, len(p), r))
494 break
495 out.append(op(wfile, f"{p}/leaf", b"x"))
496 return out
497
498
499@case
500def big_directory(d):
501 for i in range(3000):
502 wfile(f"{d}/f{i:05d}", b"")
503 names = os.listdir(d)
504 r = [len(names), len(set(names))]
505 with os.scandir(d) as it:
506 r.append(sum(1 for e in it if e.is_file()))
507 for i in range(0, 3000, 2):
508 os.unlink(f"{d}/f{i:05d}")
509 return r + [len(os.listdir(d))]
510
511
512@case
513def readdir_while_modifying(d):
514 for i in range(500):
515 wfile(f"{d}/f{i}", b"")
516 seen = []
517 with os.scandir(d) as it:
518 for k, e in enumerate(it):
519 seen.append(e.name)
520 if k == 10:
521 for j in range(500, 600):
522 wfile(f"{d}/f{j}", b"")
523 for j in range(0, 100):
524 os.unlink(f"{d}/f{j}")
525 return [len(os.listdir(d)), len(seen) > 0]
526
527
528# ---------------------------------------------------------------- lifecycle of open files
529
530@case
531def unlink_open_file(d):
532 wfile(f"{d}/f", b"data")
533 fd = os.open(f"{d}/f", os.O_RDWR)
534 os.unlink(f"{d}/f")
535 r = [op(os.pread, fd, 4, 0), op(os.pwrite, fd, b"more", 4), op(os.fstat, fd)]
536 os.close(fd)
537 return r + [sorted(os.listdir(d))]
538
539
540@case
541def rename_open_file(d):
542 wfile(f"{d}/f", b"data")
543 fd = os.open(f"{d}/f", os.O_RDWR)
544 os.rename(f"{d}/f", f"{d}/g")
545 r = [op(os.pwrite, fd, b"X", 0), op(os.fchmod, fd, 0o600), op(os.ftruncate, fd, 2)]
546 wfile(f"{d}/f", b"new file at old path")
547 r += [op(os.fchmod, fd, 0o640), op(os.ftruncate, fd, 1), op(os.fstat, fd)]
548 os.close(fd)
549 return r + [rfile(f"{d}/g"), rfile(f"{d}/f"), mode_of(f"{d}/f"), mode_of(f"{d}/g")]
550
551
552@case
553def replace_open_file_atomic_save(d):
554 # editor-style atomic save while a reader holds the old file
555 wfile(f"{d}/f", b"v1")
556 fd = os.open(f"{d}/f", os.O_RDONLY)
557 wfile(f"{d}/.f.tmp", b"v2-longer")
558 os.replace(f"{d}/.f.tmp", f"{d}/f")
559 r = [op(os.pread, fd, 20, 0)]
560 os.close(fd)
561 return r + [rfile(f"{d}/f")]
562
563
564@case
565def many_open_fds(d):
566 fds = []
567 for i in range(1500):
568 fds.append(os.open(f"{d}/f{i}", os.O_RDWR | os.O_CREAT, 0o644))
569 for fd in fds:
570 os.write(fd, b"x")
571 for fd in fds:
572 os.close(fd)
573 return [len(os.listdir(d))]
574
575
576@case
577def fsync_and_friends(d):
578 fd = os.open(f"{d}/f", os.O_RDWR | os.O_CREAT, 0o644)
579 os.write(fd, b"x" * 100)
580 r = [op(os.fsync, fd), op(os.fdatasync, fd), op(os.posix_fallocate, fd, 0, 1 << 20),
581 op(os.posix_fadvise, fd, 0, 0, os.POSIX_FADV_DONTNEED)]
582 r.append(os.fstat(fd).st_size)
583 os.close(fd)
584 dfd = os.open(d, os.O_RDONLY)
585 r.append(op(os.fsync, dfd))
586 os.close(dfd)
587 return r
588
589
590@case
591def locks(d):
592 wfile(f"{d}/f", b"x")
593 fd = os.open(f"{d}/f", os.O_RDWR)
594 r = [op(fcntl.flock, fd, fcntl.LOCK_EX | fcntl.LOCK_NB), op(fcntl.lockf, fd, fcntl.LOCK_EX | fcntl.LOCK_NB)]
595 os.close(fd)
596 return r
597
598
599@case
600def mmap_write(d):
601 wfile(f"{d}/f", b"\0" * 8192)
602 fd = os.open(f"{d}/f", os.O_RDWR)
603 try:
604 m = mmap.mmap(fd, 8192)
605 m[100:105] = b"hello"
606 m.flush()
607 m.close()
608 r = ["mapped"]
609 except OSError as e:
610 r = [("err", errno.errorcode.get(e.errno))]
611 os.close(fd)
612 return r + [rfile(f"{d}/f")[100:105]]
613
614
615@case
616def special_files(d):
617 return [op(os.mkfifo, f"{d}/fifo"), op(os.mknod, f"{d}/node", 0o600 | stat.S_IFREG),
618 op(os.open, d, os.O_TMPFILE | os.O_RDWR, 0o600),
619 op(os.setxattr, d, "user.k", b"v"), op(os.listxattr, d)]
620
621
622@case
623def copy_paths(d):
624 data = random.Random(2).randbytes(300000)
625 wfile(f"{d}/src", data)
626 s = os.open(f"{d}/src", os.O_RDONLY)
627 t = os.open(f"{d}/dst", os.O_WRONLY | os.O_CREAT, 0o644)
628 r = [op(os.copy_file_range, s, t, len(data))]
629 t2 = os.open(f"{d}/dst2", os.O_WRONLY | os.O_CREAT, 0o644)
630 r.append(op(os.sendfile, t2, s, 0, len(data)))
631 for fd in (s, t, t2):
632 os.close(fd)
633 return r + [rfile(f"{d}/dst") == data, rfile(f"{d}/dst2") == data]
634
635
636# ---------------------------------------------------------------- tool workloads
637
638@case
639def tool_tar_roundtrip(d):
640 src = f"{d}/src"
641 os.makedirs(f"{src}/a/b")
642 wfile(f"{src}/a/b/x.sh", b"#!/bin/sh\n", 0o755)
643 wfile(f"{src}/a/y", b"y" * 5000)
644 os.symlink("b/x.sh", f"{src}/a/link")
645 os.utime(f"{src}/a/y", (1_000_000_000, 1_000_000_000))
646 r = subprocess.run(f"tar -C {src} -cf - . | (mkdir {d}/out && tar -C {d}/out -xpf -)", shell=True,
647 capture_output=True)
648 return [r.returncode, r.stderr[-300:]]
649
650
651@case
652def tool_cp_a_and_rm_rf(d):
653 src = f"{d}/src"
654 for i in range(30):
655 os.makedirs(f"{src}/d{i}/e")
656 wfile(f"{src}/d{i}/e/f", b"%d" % i, 0o640)
657 r1 = subprocess.run(["cp", "-a", src, f"{d}/copy"], capture_output=True)
658 r2 = subprocess.run(["rm", "-rf", src], capture_output=True)
659 return [r1.returncode, r1.stderr[-300:], r2.returncode, r2.stderr[-300:]]
660
661
662@case
663def tool_patch_and_sed_inplace(d):
664 wfile(f"{d}/f", b"one\ntwo\nthree\n")
665 wfile(f"{d}/p", b"--- a/f\n+++ b/f\n@@ -1,3 +1,3 @@\n one\n-two\n+TWO\n three\n")
666 r1 = subprocess.run(["patch", "-p1", "-i", "p"], cwd=d, capture_output=True)
667 r2 = subprocess.run(["sed", "-i", "s/one/ONE/", "f"], cwd=d, capture_output=True)
668 return [r1.returncode, r2.returncode, r2.stderr[-200:]]
669
670
671@case
672def tool_git_worktree_outside_dotgit(d):
673 # .git is read-only on the share by design: keep the repository elsewhere, work tree here
674 gd = f"{SCRATCH}/gitdir-{os.path.basename(os.path.dirname(d))}-{os.getpid()}"
675 shutil.rmtree(gd, ignore_errors=True)
676 env = dict(os.environ, GIT_DIR=gd, GIT_WORK_TREE=d, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t",
677 GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@t")
678 for i in range(50):
679 wfile(f"{d}/f{i}", b"%d\n" % i)
680 cmds = ["git init -q", "git add -A", "git commit -qm one", "git rm -q f1", "git mv f2 g2",
681 "git commit -qam two", "git checkout -q HEAD~1 -- .", "git status --porcelain"]
682 out = []
683 for c in cmds:
684 r = subprocess.run(c, shell=True, cwd=d, env=env, capture_output=True)
685 out.append((c, r.returncode, r.stderr[-200:]))
686 shutil.rmtree(gd, ignore_errors=True)
687 return out
688
689
690@case
691def tool_python_logging_append(d):
692 code = ("import logging; logging.basicConfig(filename='app.log', filemode='a', level=10); "
693 "[logging.info('line %d', i) for i in range(200)]")
694 r = subprocess.run([sys.executable, "-c", code], cwd=d, capture_output=True)
695 return [r.returncode, len(rfile(f"{d}/app.log").splitlines()) if os.path.exists(f"{d}/app.log") else None]
696
697
698# ---------------------------------------------------------------- runner
699
700def snapshot(base):
701 snap = {}
702 for dirpath, dirnames, filenames in os.walk(base):
703 for n in sorted(dirnames + filenames):
704 p = os.path.join(dirpath, n)
705 st = os.lstat(p)
706 entry = [stat.filemode(st.st_mode), st.st_nlink if stat.S_ISREG(st.st_mode) else 0]
707 if stat.S_ISREG(st.st_mode):
708 entry.append(st.st_size)
709 if st.st_size > 256 << 20:
710 entry.append("not hashed")
711 else:
712 try:
713 with open(p, "rb") as f:
714 entry.append(hashlib.sha256(f.read()).hexdigest()[:16])
715 except OSError as e:
716 entry.append(errno.errorcode.get(e.errno))
717 elif stat.S_ISLNK(st.st_mode):
718 entry.append(os.readlink(p))
719 snap[os.path.relpath(p, base)] = entry
720 return snap
721
722
723def norm(v, d):
724 """Replaces the case directory with <d> in reported values."""
725 if isinstance(v, (list, tuple)):
726 return type(v)(norm(x, d) for x in v)
727 if isinstance(v, str):
728 return v.replace(d, "<d>")
729 if isinstance(v, bytes):
730 return v.replace(os.fsencode(d), b"<d>")
731 return v
732
733
734def _child(fn, d, q):
735 try:
736 q.put(("done", norm(fn(d), d)))
737 except Exception as e: # noqa: BLE001
738 q.put(("exception", f"{type(e).__name__}: {e}"))
739
740
741def run_case(fn, d):
742 q = mp.Queue()
743 p = mp.Process(target=_child, args=(fn, d, q))
744 p.start()
745 p.join(CASE_TIMEOUT)
746 if p.is_alive():
747 p.kill()
748 p.join()
749 return ("hang", None)
750 try:
751 return q.get(timeout=5)
752 except Exception: # noqa: BLE001
753 return ("no result", p.exitcode)
754
755
756class Harness:
757 def __init__(self, binary, host, mnt, log):
758 self.binary, self.host, self.mnt, self.log = binary, host, mnt, log
759 self.p = None
760
761 def start(self):
762 subprocess.run(["fusermount", "-u", "-z", self.mnt], capture_output=True)
763 self.logf = open(self.log, "ab")
764 self.p = subprocess.Popen([self.binary, "mount", self.host, self.mnt], stderr=self.logf, stdout=self.logf)
765 for _ in range(100):
766 if os.path.ismount(self.mnt):
767 return
768 time.sleep(0.05)
769 raise RuntimeError("mount did not come up")
770
771 def alive(self):
772 return self.p.poll() is None and os.path.ismount(self.mnt)
773
774 def fds(self):
775 try:
776 return len(os.listdir(f"/proc/{self.p.pid}/fd"))
777 except OSError:
778 return -1
779
780 def stop(self):
781 subprocess.run(["fusermount", "-u", "-z", self.mnt], capture_output=True)
782 if self.p and self.p.poll() is None:
783 self.p.kill()
784 if self.p:
785 self.p.wait()
786 self.logf.close()
787
788
789def main():
790 global SCRATCH, HOST_OF
791 binary, work = os.path.abspath(sys.argv[1]), os.path.abspath(sys.argv[2])
792 filters = sys.argv[3:]
793 host, mnt, ref, SCRATCH = (os.path.join(work, x) for x in ("host", "mnt", "ref", "scratch"))
794 log = os.path.join(work, "harness.log")
795 subprocess.run(["fusermount", "-u", "-z", mnt], capture_output=True)
796 for x in (host, ref, SCRATCH):
797 shutil.rmtree(x, ignore_errors=True)
798 for x in (host, mnt, ref, SCRATCH):
799 os.makedirs(x, exist_ok=True)
800 open(log, "wb").close()
801 HOST_OF = lambda d: d.replace(mnt, host, 1) if d.startswith(mnt) else d # noqa: E731
802 h = Harness(binary, host, mnt, log)
803 h.start()
804 print(f"# {binary}\n")
805 counts = {}
806 for fn in CASES:
807 name = fn.__name__
808 if filters and not any(f in name for f in filters):
809 continue
810 for x in (f"{mnt}/{name}", f"{ref}/{name}"):
811 os.makedirs(x)
812 fds_before = h.fds()
813 log_before = os.path.getsize(log)
814 got = run_case(fn, f"{mnt}/{name}")
815 crashed = not h.alive()
816 want = run_case(fn, f"{ref}/{name}")
817 status, detail = "ok", ""
818 if crashed:
819 status = "CRASH"
820 with open(log, "rb") as f:
821 f.seek(log_before)
822 tail = f.read().decode(errors="replace")
823 lines = tail.splitlines()
824 at = next((lines[i + 1].strip() for i, l in enumerate(lines)
825 if "reversesshfs" in l and i + 1 < len(lines)), "")
826 detail = (next((l for l in lines if l.startswith("panic") or "fatal error" in l), "server exited")
827 + f" at {at}")
828 h.stop()
829 h.start()
830 elif got[0] == "hang":
831 status = "HANG"
832 else:
833 snap_m, snap_r = snapshot(f"{host}/{name}"), snapshot(f"{ref}/{name}")
834 if got != want or snap_m != snap_r:
835 status = "DIFF"
836 if got != want:
837 detail += f"\n sshfs: {got}\n local: {want}"
838 for k in sorted(set(snap_m) | set(snap_r)):
839 if snap_m.get(k) != snap_r.get(k):
840 detail += f"\n tree {k}: sshfs={snap_m.get(k)} local={snap_r.get(k)}"
841 fds_after = h.fds()
842 if fds_after > fds_before:
843 status += f" FDLEAK({fds_before}->{fds_after})"
844 counts[status.split()[0]] = counts.get(status.split()[0], 0) + 1
845 print(f"{status:6} {name}{(': ' + detail) if detail else ''}", flush=True)
846 h.stop()
847 print(f"\n# {counts}")
848
849
850if __name__ == "__main__":
851 mp.set_start_method("fork")
852 main()