Debian Codegraph @

testsuite/variety_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Differential regression test: introducing the current rsync on EITHER side of
3 # a transfer must not change the destination tree that an all-old (e.g. 3.2.7)
4 # transfer would produce, for a "variety tree" exercising every inode type rsync
5 # handles -- directories, regular files, symlinks (heavy coverage: to each type,
6 # escaping ../.. links, absolute links, links transiting outside the tree),
7 # fifos, sockets, char/block devices -- with varied permissions, xattrs, ACLs,
8 # hard links and (as root) mixed ownership. See make_variety_tree.
9 #
10 # Peer-agnostic: RSYNC is the current binary, RSYNC_PEER the --rsync-bin2 peer.
11 # With no peer (RSYNC_PEER == RSYNC) it degrades to a self-consistency check.
12 # Enabled first for the 3.2.7 peer via testsuite/expect/rsync_3.2.7.expect.
13 #
14 # ORACLE: for each (transport, direction, option-profile) the ALL-OLD pairing is
15 # the reference ("what 3.2.7 does"); the new->old, old->new and new->new pairings
16 # must all reproduce it byte-for-byte (tls listing + contents + xattrs + ACLs +
17 # hard-link grouping). A per-scenario reference is essential because some
18 # transports legitimately transform the tree (a daemon receiver sanitizes
19 # absolute/escaping symlinks) -- that transform is version-independent, so it
20 # must be compared against the same transport, not against a local copy.
21 #
22 # The symlinked-PATH-COMPONENT traversal cases (where the current build's
23 # hardened resolver intentionally diverges from 3.2.7) live in the separate
24 # variety-symlink-traversal_test.py so they can be xfailed without masking this.
25
26 import os
27 import re
28 import shlex
29 import subprocess
30 import sys
31
32 from rsyncfns import (
33 RSYNC, RSYNC_PEER, SRCDIR, SCRATCHDIR, USE_TCP,
34 make_variety_tree, compare_trees, rmtree,
35 xattrs_supported, acls_supported, devices_supported, owners_supported,
36 write_daemon_conf, start_test_daemon,
37 test_fail, split_rsync_cmd, rsh_cmd,
38 )
39
40 SSH = rsh_cmd()
41 DAEMON_PORT_OLD = 12931
42 DAEMON_PORT_NEW = 12932
43
44 def _peer_has(feature):
45 """True if the peer binary advertises `feature` ('xattrs'/'ACLs') in -VV.
46 Pre-3.2.0 peers have no -VV, so this is False -- we then skip -X/-A for
47 them, which is correct (we can't compare a feature one side can't carry)."""
48 try:
49 vv = subprocess.run(split_rsync_cmd(RSYNC_PEER) + ['-VV'],
50 capture_output=True, text=True)
51 return f'"{feature}": true' in vv.stdout
52 except OSError:
53 return False
54
55
56 def _forced_proto(cmd):
57 """The --protocol=N pinned on a binary's command string, else None (used by
58 the fleet's check29/check30 passes)."""
59 m = re.search(r'--protocol[ =](\d+)', cmd)
60 return int(m.group(1)) if m else None
61
62
63 # ACLs and xattrs require protocol 30+; a forced --protocol=29 (the fleet's
64 # check29 pass) negotiates 29 and rsync aborts on -A/-X, so drop them then.
65 _pinned = [p for p in (_forced_proto(RSYNC), _forced_proto(RSYNC_PEER)) if p]
66 _AX_PROTO_OK = not _pinned or min(_pinned) >= 30
67
68 # Use a feature only when BOTH the current binary and the peer support it (and
69 # the negotiated protocol can carry it).
70 WITH_X = xattrs_supported() and _peer_has('xattrs') and _AX_PROTO_OK
71 WITH_A = acls_supported() and _peer_has('ACLs') and _AX_PROTO_OK
72 WITH_DEV = devices_supported()
73 WITH_OWN = owners_supported()
74
75 # Daemon/remote paths resolve against HOME (-> scratch dir); cd there.
76 os.chdir(SCRATCHDIR)
77
78 # One read-only source for the whole run, so every case compares copies of the
79 # exact same bytes. We transfer transfer_root/; the escape/ links point up into
80 # the (untransferred) above/ siblings, so on the dest they are copied as link
81 # strings -- identical for both binaries.
82 SRC = SCRATCHDIR / 'variety-src'
83 info = make_variety_tree(SRC, with_acls=WITH_A, with_xattrs=WITH_X,
84 with_devices=WITH_DEV, with_owners=WITH_OWN)
85 TR = info['transfer_root']
86 SRC_SLASH = f'{TR}/'
87 print(f"variety source: {sum(info['counts'].values())} entries "
88 f"{info['counts']} (xattrs={WITH_X} acls={WITH_A} devices={WITH_DEV} "
89 f"owners={WITH_OWN})")
90
91 DESTBASE = SCRATCHDIR / 'dest'
92 DESTBASE.mkdir(exist_ok=True)
93 VDST_BASE = SCRATCHDIR / 'vdst'
94 VDST_BASE.mkdir(exist_ok=True)
95
96 OK_CODES = (0, 23, 24) # specials without -D -> rsync warns and returns 23/24
97
98 # -A/-X only when supported (3.2.7 has both). -L/--copy-links is excluded: the
99 # absolute/escape links point into the SOURCE scratch, so dereferencing tests
100 # source layout, not transfer fidelity.
101 _full = ['-a', '-H'] + (['-A'] if WITH_A else []) + (['-X'] if WITH_X else [])
102 PROFILES = {
103 'P1-full': _full + ['--specials', '--devices'],
104 'P2-links': ['-a', '--links'],
105 'P3-copyunsafe': ['-a', '--copy-unsafe-links'],
106 'P4-safelinks': ['-a', '--safe-links'],
107 'P5-noimplied': _full + ['-D', '--no-implied-dirs'],
108 }
109 WIRE_PROFILES = ('P1-full', 'P2-links', 'P5-noimplied') # over the wire
110 PAIRINGS = (('old', 'old'), ('new', 'old'), ('old', 'new'), ('new', 'new'))
111
112 results = [] # (case_label, [diff, ...])
113
114
115 def binof(role):
116 return RSYNC_PEER if role == 'old' else RSYNC
117
118
119 def run(binary_cmd, args, label):
120 argv = shlex.split(binary_cmd) + args
121 proc = subprocess.run(argv, capture_output=True, text=True)
122 if proc.returncode not in OK_CODES:
123 sys.stdout.write(proc.stdout)
124 sys.stderr.write(proc.stderr)
125 test_fail(f"{label}: rsync exited {proc.returncode}: {' '.join(argv)}")
126
127
128 def newdir(base, name):
129 d = base / name
130 rmtree(d)
131 d.mkdir(parents=True)
132 return d
133
134
135 def compare(dest, ref, label):
136 diffs = compare_trees(dest, ref, label,
137 with_acls=WITH_A, with_xattrs=WITH_X)
138 if diffs:
139 results.append((label, diffs))
140
141
142 # --- daemon plumbing: a config + daemon per role on demand ---
143 # munge symlinks defaults ON for a module (prepends /rsyncd-munged/); disable so
144 # the only daemon symlink transform is the standard absolute-link sanitisation,
145 # which both binaries do identically. Each role gets its own pid/log file so the
146 # old and new daemons can run concurrently in --use-tcp mode without a pid-lock
147 # clash.
148 def _make_conf(role):
149 return write_daemon_conf([
150 ('vsrc', {'path': str(TR), 'read only': 'yes'}),
151 ('vdst', {'path': str(VDST_BASE), 'read only': 'no'}),
152 ], globals={
153 'munge symlinks': 'no',
154 'pid file': str(SCRATCHDIR / f'rsyncd-{role}.pid'),
155 'log file': str(SCRATCHDIR / f'rsyncd-{role}.log'),
156 }, name=f'vd-{role}.conf')
157
158
159 _conf_for = {'old': _make_conf('old'), 'new': _make_conf('new')}
160 _daemon_url = {}
161
162
163 def daemon_url(drole):
164 """URL for a daemon running `drole`'s binary. In --use-tcp mode each role
165 gets its own listener (cached); in pipe mode this resets RSYNC_CONNECT_PROG
166 on every call, so call it immediately before the client run."""
167 if USE_TCP:
168 if drole not in _daemon_url:
169 port = DAEMON_PORT_OLD if drole == 'old' else DAEMON_PORT_NEW
170 _daemon_url[drole] = start_test_daemon(_conf_for[drole], port,
171 rsync_cmd=binof(drole))
172 return _daemon_url[drole]
173 return start_test_daemon(_conf_for[drole], 0, rsync_cmd=binof(drole))
174
175
176 def do_transfer(transport, direction, crole, srole, prof, name):
177 """Run one pairing and return the destination dir to compare."""
178 args = PROFILES[prof]
179 if transport == 'local':
180 d = newdir(DESTBASE, name)
181 run(binof(crole), args + [SRC_SLASH, f'{d}/'], name)
182 return d
183 if transport == 'remote':
184 d = newdir(DESTBASE, name)
185 common = args + ['-e', SSH, f'--rsync-path={binof(srole)}']
186 if direction == 'push':
187 run(binof(crole), common + [SRC_SLASH, f'localhost:{d}/'], name)
188 else:
189 run(binof(crole), common + [f'localhost:{SRC_SLASH}', f'{d}/'], name)
190 return d
191 # daemon
192 url = daemon_url(srole)
193 if direction == 'push':
194 d = newdir(VDST_BASE, name)
195 run(binof(crole), args + [SRC_SLASH, f'{url}vdst/{name}/'], name)
196 return d
197 d = newdir(DESTBASE, name)
198 run(binof(crole), args + [f'{url}vsrc/', f'{d}/'], name)
199 return d
200
201
202 def run_scenario(transport, direction, prof, pairings):
203 """Run all `pairings` for one scenario; compare each non-ref to the all-old
204 reference (pairings[0] must be the all-old pair)."""
205 ref = None
206 for crole, srole in pairings:
207 tag = f"{transport}-{direction}-c{crole}-s{srole}/{prof}"
208 dest = do_transfer(transport, direction, crole, srole, prof,
209 tag.replace('/', '_'))
210 if ref is None:
211 ref = dest # all-old reference
212 else:
213 compare(dest, ref, tag)
214
215
216 # Local: single binary per run -> just old (ref) vs new, every profile.
217 for prof in PROFILES:
218 run_scenario('local', 'push', prof, (('old', 'old'), ('new', 'new')))
219
220 # Remote-shell and daemon: all four client/server pairings, both directions.
221 for prof in WIRE_PROFILES:
222 for direction in ('push', 'pull'):
223 run_scenario('remote', direction, prof, PAIRINGS)
224 run_scenario('daemon', direction, prof, PAIRINGS)
225
226
227 # --- verdict ---
228 if results:
229 msg = [f"variety: {len(results)} case(s) diverged from the all-old "
230 f"reference (peer={RSYNC_PEER!r}):"]
231 for label, diffs in results:
232 msg.append(f"\n========== {label} ==========")
233 msg.extend(diffs)
234 test_fail('\n'.join(msg))
235
236 print("variety: OK -- current rsync reproduces the all-old result on every "
237 "local/remote/daemon scenario and new/old role pairing")