#!/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('= 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()