Files
CephfsMig/dev/million.py
T
Sebastian UnterschützandClaude Opus 5.5 82c64f9908 test(dev): make the million test worker count configurable
WORKERS sets the copier workers (default 8). The driver no longer
removes the mount field, which the configuration does not have anymore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 22:03:22 +01:00

548 lines
24 KiB
Python

#!/usr/bin/env python3
"""Persistent, bounded-memory million-file CephFS snapshot migration test.
The Python SDK acts as application writer and independent verifier. Expected
contents and metadata are derived from a deterministic model, not the Go reader.
"""
import concurrent.futures
from collections import deque
import datetime
import hashlib
import json
import os
from pathlib import Path
import signal
import sqlite3
import stat
import subprocess
import threading
import time
import uuid
import cephfs
from smallfiles import ceph, volume, snap, payload, posix_acl
RUN_LABEL = os.environ.get('RUN_LABEL', 'main')
if not RUN_LABEL or not all(c.isascii() and (c.isalnum() or c == '-') for c in RUN_LABEL):
raise ValueError('RUN_LABEL must consist of letters, digits and hyphens')
REPORT = Path('/report') / RUN_LABEL
WORK = Path('/state') / ('million-' + RUN_LABEL)
COUNT = int(os.environ.get('FILES', '1000000'))
PER_DIR = 1000
STAMP = 1700000000
STOP = threading.Event()
STATUS_LOCK = threading.RLock()
state = {}
def atomic_json(path, value):
temporary = path.with_suffix(path.suffix + '.tmp')
with temporary.open('w') as f:
json.dump(value, f, indent=2)
f.write('\n')
f.flush()
os.fsync(f.fileno())
temporary.replace(path)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
def progress(**changes):
with STATUS_LOCK:
state.update(changes)
state['updated_at'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
atomic_json(REPORT / 'status.json', state)
print(json.dumps(changes), flush=True)
def timed(step, function, *args):
"""Run function and record its duration under timings[step]."""
started = time.monotonic()
result = function(*args)
timings = dict(state.get('timings', {}))
timings[step] = round(time.monotonic() - started, 3)
progress(timings=timings)
return result
def guard():
if STOP.is_set():
raise RuntimeError('test stopped')
usage = os.statvfs('/state')
if usage.f_bavail * usage.f_frsize < 20 * 1024**3:
raise RuntimeError('host reserve below 20 GiB; stopping further test writes')
memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines())
if int(memory['MemAvailable'].split()[0]) < 3 * 1024**2:
raise RuntimeError('host available memory below 3 GiB')
def space_guard():
guard()
for cluster in ('source', 'target'):
s = json.loads(ceph(cluster, 'df', '--format', 'json'))['stats']
if s['total_avail_bytes'] < 3 * 1024**3:
raise RuntimeError(f'{cluster} has less than 3 GiB reserve')
class FS:
def __init__(self, cluster):
self.fs = cephfs.LibCephFS(conffile=f'/clusters/{cluster}/ceph.conf')
self.fs.conf_set('keyring', f'/clusters/{cluster}/ceph.client.admin.keyring')
self.fs.conf_set('client_acl_type', 'posix_acl')
self.fs.conf_set('client_cache_size', '4096')
self.fs.conf_set('client_oc', 'false')
self.fs.mount()
def __enter__(self):
return self.fs
def __exit__(self, *_):
self.fs.shutdown()
def names(fs, path):
d = fs.opendir(path)
try:
result = set()
while entry := fs.readdir(d):
name = entry.d_name.decode()
if name not in ('.', '..', '.snap'):
result.add(name)
return result
finally:
fs.closedir(d)
def mkdir(fs, path):
try:
fs.mkdir(path, 0o755)
except cephfs.ObjectExists:
if not stat.S_ISDIR(fs.lstat(path).st_mode):
raise
def exists(fs, path):
try:
fs.lstat(path)
return True
except cephfs.ObjectNotFound:
return False
def relative(i):
return f'data/d{i // PER_DIR:04d}/f{i % PER_DIR:06d}'
def object_attrs(i, changed):
result = {}
if i < COUNT and i // PER_DIR == 0:
acl = posix_acl()
if changed and i % 100 == 3:
# Change the ACL mask to match chmod 0660.
import struct
acl = bytearray(acl)
struct.pack_into('<H', acl, 4 + 3 * 8 + 2, 6)
acl = bytes(acl)
result['system.posix_acl_access'] = acl
if i < COUNT and i % 100 == 4 and not changed:
result['user.remove'] = b'original'
if i < COUNT and i % 100 == 3 and changed:
result['user.generation'] = b'1'
return result
def actual_attrs(fs, path):
_, buffer = fs.listxattr(path, 256)
return {k.decode(): fs.getxattr(path, k, 4096) for k in buffer.split(b'\0') if k and
(not k.startswith(b'ceph.'))}
def create_file(fs, root, i, version):
path = root + '/' + relative(i)
fd = fs.open(path, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o644)
try:
if fs.write(fd, payload(i, version), 0) != 128:
raise RuntimeError(f'short fixture write: {path}')
finally:
fs.close(fd)
fs.utime(path, (STAMP + i, STAMP + i))
if i == 0:
fs.chown(path, 12345, 23456)
if i < COUNT and i % 100 == 4:
fs.setxattr(path, b'user.remove', b'original', 0)
def reset_dir_times(fs, root, count):
for i in range((count + PER_DIR - 1) // PER_DIR):
fs.utime(root + f'/data/d{i:04d}', (STAMP, STAMP))
for rel in ('data', 'links', '.'):
fs.utime(root + '/' + rel, (STAMP, STAMP))
def prepare():
progress(phase='preparing', total_files=COUNT, bytes_per_file=128, layout='1000 files per directory')
name = state['name']
for cluster in ('source', 'target'):
volume(cluster, 'create', 'cephfs', name)
roots = {c: volume(c, 'getpath', 'cephfs', name) for c in ('source', 'target')}
state['roots'] = roots
config = json.loads(Path('/lab/migration.example.json').read_text())
config.update(backend='native', workers=int(os.environ.get('WORKERS', '8')), bandwidth_kib=0)
for c in ('source', 'target'):
config[c]['subvolume'] = name
atomic_json(WORK / 'config.json', config)
with FS('source') as fs:
root = roots['source']
state['root_attrs'] = {key: value.hex() for key, value in actual_attrs(fs, root).items()}
mkdir(fs, root + '/data')
mkdir(fs, root + '/links')
directories = (COUNT + PER_DIR - 1) // PER_DIR
for d in range(directories):
mkdir(fs, root + f'/data/d{d:04d}')
fs.setxattr(root + '/data/d0000', b'system.posix_acl_default', posix_acl(), 0)
start = state.get('generated_directories', 0)
def generate(d):
for i in range(d * PER_DIR, min(COUNT, (d + 1) * PER_DIR)):
if STOP.is_set():
raise RuntimeError('generation stopped')
create_file(fs, root, i, 0)
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
for d in range(start, directories, 8):
space_guard()
list(pool.map(generate, range(d, min(directories, d + 8))))
fs.sync_fs()
progress(generated_directories=min(directories, d + 8),
generated_files=min(COUNT, (d + 8) * PER_DIR))
for i in range(100):
hard = root + f'/links/hard{i:03d}'
soft = root + f'/links/soft{i:03d}'
if not exists(fs, hard):
fs.link(root + '/' + relative(i), hard)
if not exists(fs, soft):
fs.symlink('../' + relative(i), soft)
state['symlink_times'] = {f'links/soft{i:03d}': fs.lstat(root + f'/links/soft{i:03d}').st_mtime.isoformat()
for i in range(100)}
fs.setxattr(root, b'ceph.quota.max_files', str(COUNT * 2 + 1000).encode(), 0)
fs.setxattr(root, b'ceph.quota.max_bytes', str(COUNT * 256 + 4194304).encode(), 0)
reset_dir_times(fs, root, COUNT)
fs.sync_fs()
if 'baseline' not in {x['name'] for x in json.loads(snap('source', 'ls', 'cephfs', name))}:
snap('source', 'create', 'cephfs', name, 'baseline')
snap('source', 'metadata', 'set', 'cephfs', name, 'baseline', 'fixture', 'million-v0')
progress(prepared=True, phase='prepared')
def mutate():
progress(phase='mutating')
root = state['roots']['source']
with FS('source') as fs:
for d in range(COUNT // PER_DIR):
guard()
for i in range(d * PER_DIR, (d + 1) * PER_DIR):
path = root + '/' + relative(i)
if i % 100 == 0:
fd = fs.open(path, os.O_WRONLY, 0)
try:
if fs.write(fd, payload(i, 1), 0) != 128:
raise RuntimeError('short mutation write')
finally:
fs.close(fd)
fs.utime(path, (STAMP + i, STAMP + i))
elif i % 100 == 1:
if exists(fs, path): fs.unlink(path)
elif i % 100 == 2:
if exists(fs, path): fs.rename(path, path + '-renamed')
elif i % 100 == 3:
fs.chmod(path, 0o660)
fs.setxattr(path, b'user.generation', b'1', 0)
elif i % 100 == 4:
if b'user.remove' in fs.listxattr(path, 256)[1].split(b'\0'):
fs.removexattr(path, b'user.remove')
if d % 10 == 0:
space_guard()
progress(mutated_directories=d + 1)
end = COUNT + COUNT // 100
for d in range(COUNT // PER_DIR, (end + PER_DIR - 1) // PER_DIR):
mkdir(fs, root + f'/data/d{d:04d}')
for i in range(COUNT, end):
create_file(fs, root, i, 2)
reset_dir_times(fs, root, end)
fs.sync_fs()
# A second application snapshot holds the changed state.
name = state['name']
if 'changed' not in {x['name'] for x in json.loads(snap('source', 'ls', 'cephfs', name))}:
snap('source', 'create', 'cephfs', name, 'changed')
snap('source', 'metadata', 'set', 'cephfs', name, 'changed', 'fixture', 'million-v1')
progress(mutated=True)
def counters(cluster):
d = json.loads(ceph(cluster, 'tell', 'mds.a', 'perf', 'dump'))
return {'requests': d['mds']['request'], 'getattr': d['mds_server']['req_getattr_latency']['avgcount'],
'lookupsnap': d['mds_server']['req_lookupsnap_latency']['avgcount']}
def run_phase(phase):
space_guard()
attempts = dict(state.get('phase_attempts', {}))
attempts[phase] = attempts.get(phase, 0) + 1
progress(phase=phase, phase_started=datetime.datetime.now(datetime.timezone.utc).isoformat(),
phase_attempts=attempts)
before = {c: counters(c) for c in ('source', 'target')}
command = {'final': 'finalize', 'cleanup': 'cleanup'}.get(phase, 'sync')
args = ['/usr/local/bin/cephmig-native', command,
'--config', str(WORK / 'config.json'), '--state', str(WORK / 'job.json')]
if phase == 'final': args.append('--writers-stopped')
started, wall_started, last = time.monotonic(), time.time(), 0
peak = 0
with (REPORT / f'{phase}.stdout.json').open('w') as out, (REPORT / f'{phase}.log').open('w') as log:
p = subprocess.Popen(args, stdout=out, stderr=subprocess.PIPE)
def stamp_lines():
# Prefix every engine log line with the UTC time and the phase time.
for raw in p.stderr:
now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds')
log.write(f'{now} +{time.monotonic() - started:9.3f}s {raw.decode(errors="replace")}')
log.flush()
logger = threading.Thread(target=stamp_lines, daemon=True)
logger.start()
try:
while p.poll() is None:
now = time.monotonic()
if now - last >= 15:
space_guard()
try:
for line in Path(f'/proc/{p.pid}/status').read_text().splitlines():
if line.startswith(('VmRSS:', 'VmHWM:')):
peak = max(peak, int(line.split()[1]))
except FileNotFoundError:
pass
with (REPORT / f'{phase}.log').open('rb') as tail:
tail.seek(max(0, os.fstat(tail.fileno()).st_size - 2048))
lines = tail.read().decode(errors='replace').splitlines()
progress(elapsed_seconds=round(now - started, 1), peak_rss_kib=peak,
last_engine_message=lines[-1] if lines else 'starting')
last = now
if STOP.is_set(): raise RuntimeError('migration stopped')
if now - started > 48 * 3600: raise RuntimeError('migration phase exceeded 48 hours')
time.sleep(1)
except BaseException:
p.terminate()
try: p.wait(timeout=30)
except subprocess.TimeoutExpired:
p.kill(); p.wait()
raise
finally:
logger.join(timeout=30)
if p.returncode:
raise RuntimeError(f'{phase} failed ({p.returncode}); see {phase}.log')
result = json.loads((WORK / 'job.json').read_text())
if not all(s['done'] for s in result['snapshots']): raise RuntimeError('unfinished snapshot')
after = {c: counters(c) for c in before}
metrics = dict(seconds=time.monotonic() - started, wall_seconds=time.time() - wall_started,
peak_rss_kib=peak, snapshots=result['snapshots'],
resumed=attempts[phase] > 1,
mds={c: {k: after[c][k] - before[c][k] for k in before[c]} for c in before})
atomic_json(REPORT / f'{phase}.metrics.json', metrics)
atomic_json(REPORT / 'migration-state.json', result)
if phase == 'final':
if result['phase'] != 'ready-for-cutover' or result['snapshots'][-1]['transfer']['bytes_copied']:
raise RuntimeError('unchanged final round must be ready and write zero payload bytes')
timings = dict(state.get('timings', {}))
timings[phase] = round(metrics['seconds'], 3)
state['timings'] = timings
completed = {phase + '_complete': True}
if phase == 'initial':
completed['initial_snapshots'] = [record['name'] for record in result['snapshots']]
progress(**completed)
def expected_mode(i, changed):
return 0o660 if changed and i < COUNT and i % 100 == 3 else (0o640 if i < PER_DIR else 0o644)
def check_regular(fs, root, rel, i, changed):
path = root + '/' + rel
s = fs.lstat(path)
if s.st_mode != stat.S_IFREG | expected_mode(i, changed) or s.st_size != 128:
raise RuntimeError(f'type/mode/size mismatch: {path}')
if (s.st_uid, s.st_gid) != ((12345, 23456) if i == 0 else (0, 0)):
raise RuntimeError(f'owner mismatch: {path}')
if s.st_mtime != datetime.datetime.fromtimestamp(STAMP + i, datetime.timezone.utc).replace(tzinfo=None):
raise RuntimeError(f'mtime mismatch: {path}')
if actual_attrs(fs, path) != object_attrs(i, changed):
raise RuntimeError(f'xattr/ACL mismatch: {path}')
version = 2 if i >= COUNT else (1 if changed and i % 100 == 0 else 0)
fd = fs.open(path, os.O_RDONLY | os.O_NOFOLLOW, 0)
try: data = fs.read(fd, 0, 129)
finally: fs.close(fd)
if data != payload(i, version): raise RuntimeError(f'content mismatch: {path}')
return i, str(s.st_ino)
def verify_view(label, root, changed):
if label in state.get('verified_views', []): return
progress(phase='verifying', view=label, verified_regular_paths=0)
dbpath = WORK / 'verify.sqlite'
dbpath.unlink(missing_ok=True)
db = sqlite3.connect(dbpath)
db.executescript('PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-16384;'
'CREATE TABLE links(object_id INTEGER PRIMARY KEY, inode TEXT UNIQUE NOT NULL);')
checked, last = 0, time.monotonic()
try:
with FS('target') as fs, concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
if names(fs, root) != {'data', 'links'}: raise RuntimeError('unexpected root entries')
for rel in ('.', 'data', 'links'):
s = fs.lstat(root + '/' + rel)
expected_attrs = ({key: bytes.fromhex(value) for key, value in state['root_attrs'].items()}
if rel == '.' else {})
if (s.st_mode != (stat.S_IFDIR | 0o755) or s.st_uid or s.st_gid or
s.st_mtime != datetime.datetime.utcfromtimestamp(STAMP) or
actual_attrs(fs, root + '/' + rel) != expected_attrs):
raise RuntimeError(f'root/parent metadata mismatch: {rel}')
end = COUNT + COUNT // 100 if changed else COUNT
directory_count = (end + PER_DIR - 1) // PER_DIR
if names(fs, root + '/data') != {f'd{i:04d}' for i in range(directory_count)}:
raise RuntimeError('data directory inventory mismatch')
def consume(future):
nonlocal checked
i, ino = future.result()
cursor = db.execute('INSERT OR IGNORE INTO links VALUES(?,?)', (i, ino))
if not cursor.rowcount:
row = db.execute('SELECT inode FROM links WHERE object_id=?', (i,)).fetchone()
if row != (ino,): raise RuntimeError('hardlink group split or unrelated objects merged')
checked += 1
for d in range(directory_count):
guard()
expected = {}
for i in range(d * PER_DIR, min(end, (d + 1) * PER_DIR)):
if changed and i < COUNT and i % 100 == 1: continue
rel = relative(i) + ('-renamed' if changed and i < COUNT and i % 100 == 2 else '')
expected[rel.rsplit('/', 1)[1]] = (rel, i)
path = root + f'/data/d{d:04d}'
if names(fs, path) != set(expected): raise RuntimeError(f'inventory mismatch: {path}')
s = fs.lstat(path)
if s.st_mode != stat.S_IFDIR | 0o755 or s.st_uid or s.st_gid or s.st_mtime != datetime.datetime.utcfromtimestamp(STAMP):
raise RuntimeError(f'directory metadata mismatch: {path}')
attrs = {'system.posix_acl_default': posix_acl()} if d == 0 else {}
if actual_attrs(fs, path) != attrs: raise RuntimeError(f'directory ACL mismatch: {path}')
pending = deque()
for rel, i in expected.values():
pending.append(pool.submit(check_regular, fs, root, rel, i, changed))
if len(pending) >= 64: consume(pending.popleft())
while pending: consume(pending.popleft())
db.commit()
if time.monotonic() - last >= 15:
progress(view=label, verified_regular_paths=checked)
last = time.monotonic()
expected_links = {f'{kind}{i:03d}' for kind in ('hard', 'soft') for i in range(100)}
if names(fs, root + '/links') != expected_links: raise RuntimeError('link inventory mismatch')
for i in range(100):
result = check_regular(fs, root, f'links/hard{i:03d}', i, changed)
done = concurrent.futures.Future(); done.set_result(result); consume(done)
path = root + f'/links/soft{i:03d}'
s = fs.lstat(path)
if not stat.S_ISLNK(s.st_mode) or s.st_uid or s.st_gid:
raise RuntimeError('symlink metadata mismatch')
if fs.readlink(path, 4096).decode() != '../' + relative(i): raise RuntimeError('symlink text mismatch')
if s.st_mtime.isoformat() != state['symlink_times'][f'links/soft{i:03d}']:
raise RuntimeError('symlink mtime mismatch')
for key, value in [('ceph.quota.max_files', COUNT * 2 + 1000), ('ceph.quota.max_bytes', COUNT * 256 + 4194304)]:
if fs.getxattr(root, key, 128) != str(value).encode(): raise RuntimeError('quota mismatch')
if checked != COUNT + 100: raise RuntimeError(f'wrong file count: {checked}')
state.setdefault('verified_views', []).append(label)
progress(verified_regular_paths=checked)
finally:
db.close()
dbpath.unlink(missing_ok=True)
def other_writer():
try:
with FS('source') as fs:
demo = volume('source', 'getpath', 'cephfs', 'demo')
path = demo + '/million-liveness'
fd = fs.open(path, os.O_CREAT | os.O_RDWR, 0o600)
try:
while not STOP.is_set():
value = state.get('other_subvolume_writes', 0) + 1
fs.write(fd, str(value).encode(), 0)
fs.fsync(fd, False)
with STATUS_LOCK: state['other_subvolume_writes'] = value
STOP.wait(2)
finally:
fs.close(fd)
fs.unlink(path)
except BaseException as e:
state['other_writer_error'] = str(e)
STOP.set()
def main():
global state
if COUNT < 1000 or COUNT > 1000000 or COUNT % PER_DIR:
raise ValueError('FILES must be a multiple of 1000, from 1000 to 1000000')
REPORT.mkdir(parents=True, exist_ok=True)
WORK.mkdir(mode=0o700, parents=True, exist_ok=True)
if (REPORT / 'status.json').exists():
state = json.loads((REPORT / 'status.json').read_text())
if state.get('total_files') != COUNT: raise RuntimeError('cannot change count on resume')
if state.get('result') == 'PASS': return
state.pop('result', None)
state.pop('error', None)
state.pop('other_writer_error', None)
else:
state = dict(name='million-itest-' + str(uuid.uuid4()), total_files=COUNT,
started_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
for sig in (signal.SIGTERM, signal.SIGINT): signal.signal(sig, lambda *_: STOP.set())
try:
if not state.get('prepared'): timed('prepare', prepare)
thread = threading.Thread(target=other_writer, daemon=True)
thread.start()
try:
if not state.get('initial_complete'): run_phase('initial')
if not state.get('mutated'): timed('mutate', mutate)
if not state.get('catchup_complete'): run_phase('catchup')
before = state.get('other_subvolume_writes', 0)
if not state.get('final_complete'):
run_phase('final')
if state.get('other_subvolume_writes', 0) <= before:
raise RuntimeError('other subvolume did not remain writable during finalization')
job = json.loads((WORK / 'job.json').read_text())
if len(job['snapshots']) < 4: raise RuntimeError('expected at least four snapshot stands')
initial = set(state.get('initial_snapshots', [x['name'] for x in job['snapshots'][:2]]))
timed('verify live', verify_view, 'live', state['roots']['target'], True)
# Round snapshots that sync already removed are not verifiable.
present = [record for record in job['snapshots'] if not record.get('removed')]
for record in present:
path = ceph('target', 'fs', 'subvolume', 'snapshot', 'getpath',
'cephfs', state['name'], record['name'], 'migration')
timed('verify ' + record['name'], verify_view, record['name'], path, record['name'] not in initial)
if snap('source', 'metadata', 'ls', 'cephfs', state['name'], record['name']) != snap(
'target', 'metadata', 'ls', 'cephfs', state['name'], record['name']):
raise RuntimeError('snapshot custom metadata mismatch')
if not state.get('cleanup_complete'): run_phase('cleanup')
application = {'baseline', 'changed'}
for cluster in ('source', 'target'):
left = {x['name'] for x in json.loads(snap(cluster, 'ls', 'cephfs', state['name']))}
if left != application:
raise RuntimeError(f'{cluster} snapshots after cleanup: {sorted(left)}')
if state.get('other_writer_error'): raise RuntimeError(state['other_writer_error'])
progress(phase='complete', result='PASS',
snapshot_count=len(job['snapshots']),
total_regular_paths_verified=(COUNT + 100) * (len(present) + 1))
finally:
STOP.set()
thread.join(timeout=30)
except BaseException as e:
progress(phase='failed', result='FAIL', error=repr(e))
raise
if __name__ == '__main__':
main()