#!/usr/bin/env python3 """Mandatory lab4 upload experiment: >=10 simultaneous uploads + API memory. Metrics and units (do not confuse them): * process RSS: VmRSS from /proc/1/status inside each API container, bytes. This is the resident set of the API process (PID 1), sampled by `docker exec`. * process peak RSS (HWM): VmHWM from the same file, bytes. The kernel high-water mark since that process started; the API is restarted before the run so the baseline is fresh. * cgroup memory.current / memory.peak: the whole container cgroup, bytes, including page cache and any other process. It is reported separately and is NOT presented as process RSS. The run uploads a reproducible profile of generated PNGs (no giant fixtures in Git), records real UTC timestamps, per-upload intervals, observed concurrency, HTTP results and the Sampled RSS of both API replicas. Raw samples and the compact summary are stored under evidence/experiment/. Python 3.9+, standard library only. Requires the running stand and Docker. """ import concurrent.futures import datetime as dt import hashlib import json import sys import threading import time import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'tests')) sys.path.insert(0, str(ROOT / 'scripts')) from client import Client, Failure, arguments, check # noqa: E402 import lab4_metrics as M # noqa: E402 EVIDENCE = ROOT / 'evidence' / 'experiment' CONCURRENCY = 12 SAMPLE_INTERVAL_SECONDS = 0.2 def iso_now(): return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z') def process_memory(container): process = M.run(['docker', 'exec', container, 'cat', '/proc/1/status'], check=False) if process.returncode != 0: return None values = {} for line in process.stdout.splitlines(): if line.startswith('VmRSS:'): values['rss_bytes'] = int(line.split()[1]) * 1024 elif line.startswith('VmHWM:'): values['hwm_bytes'] = int(line.split()[1]) * 1024 return values def cgroup_memory(container): result = {} current = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.current'], check=False) peak = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.peak'], check=False) if current.returncode == 0: result['current_bytes'] = int(current.stdout.strip()) if peak.returncode == 0: result['peak_bytes'] = int(peak.stdout.strip()) return result or None class Sampler(threading.Thread): def __init__(self, containers): super().__init__(daemon=True) self.containers = containers self.samples = [] self.error = None self._stop_event = threading.Event() # never name this Thread._stop def run(self): try: while not self._stop_event.is_set(): started = iso_now() monotonic = time.monotonic() row = {'sampled_at': started, 'monotonic_seconds': round(monotonic, 6), 'api': {}} for container in self.containers: row['api'][container['hostname']] = { 'process': process_memory(container['container_id']), 'cgroup': cgroup_memory(container['container_id']), } self.samples.append(row) self._stop_event.wait(SAMPLE_INTERVAL_SECONDS) except Exception as exc: # noqa: BLE001 - reported in the summary self.error = type(exc).__name__ + ': ' + str(exc) def stop(self): self._stop_event.set() def main(): args = arguments('Lab4 >=10 concurrent uploads with API process RSS sampling') EVIDENCE.mkdir(parents=True, exist_ok=True) api = M.containers('api') check(len(api) >= 2, 'the experiment needs at least two API replicas') api_limit = M.inspect(api[0]['container_id'])['HostConfig'].get('Memory') gomemlimit = api[0]['env'].get('GOMEMLIMIT', '') decode_concurrency = api[0]['env'].get('UPLOAD_DECODE_CONCURRENCY', '') put_concurrency = api[0]['env'].get('S3_PUT_CONCURRENCY', '') max_upload = api[0]['env'].get('MAX_UPLOAD_BYTES', '') max_pixels = api[0]['env'].get('MAX_IMAGE_PIXELS', '') revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip() image_id = api[0]['image_id'] print('== restart API replicas to reset the process high-water mark ==') M.compose('restart', 'api') M.wait_ready(120) api = M.containers('api') check(len(api) >= 2, 'API replicas did not come back') restarts_before = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api} baseline = {} for item in api: baseline[item['hostname']] = { 'process': process_memory(item['container_id']), 'cgroup': cgroup_memory(item['container_id']), } print('== generate the reproducible upload profile ==') profiles = [] for index in range(CONCURRENCY): if index < 6: width, height = 1000, 700 profile = 'small' elif index < 10: width, height = 1500, 1100 profile = 'medium' else: width, height = 1600, 2167 profile = 'near-max-bytes' data = M.png_random(width, height, seed=1000 + index) profiles.append({ 'index': index, 'profile': profile, 'filename': 'load-%02d.png' % index, 'width': width, 'height': height, 'pixels': width * height, 'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'content': data, }) check(all(item['pixels'] <= 40_000_000 and item['bytes'] <= 10 * 1024 * 1024 for item in profiles), 'generated profile violates contract limits') check(max(item['bytes'] for item in profiles) > 10 * 1024 * 1024 - 100000, 'profile does not include a near-limit file') client = Client(args.base_url, args.ca_file, timeout=60) alice, bob, eve, chat = client.bootstrap() barrier = threading.Barrier(CONCURRENCY) def upload(item): local = Client(args.base_url, args.ca_file, timeout=60) barrier.wait() started_monotonic = time.monotonic() started_utc = iso_now() response = local.call( 'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + item['filename'], 201, actor=alice, raw=item['content'], headers={'Content-Type': 'image/png'}, schema='Attachment') finished_monotonic = time.monotonic() return { 'index': item['index'], 'profile': item['profile'], 'filename': item['filename'], 'width': item['width'], 'height': item['height'], 'pixels': item['pixels'], 'bytes': item['bytes'], 'sha256': item['sha256'], 'started_at': started_utc, 'finished_at': iso_now(), 'started_monotonic': started_monotonic, 'finished_monotonic': finished_monotonic, 'duration_ms': round((finished_monotonic - started_monotonic) * 1000, 3), 'status': response['status'], 'instance_id': response['headers'].get('X-Instance-Id', ''), 'attachment_id': response['json']['id'], 'server_sha256': response['json']['sha256'], 'server_size_bytes': response['json']['size_bytes'], 'server_status': response['json']['status'], } sampler = Sampler(api) sampler.start() started_utc = iso_now() started_monotonic = time.monotonic() with concurrent.futures.ThreadPoolExecutor(max_workers=CONCURRENCY) as pool: results = list(pool.map(upload, profiles)) finished_monotonic = time.monotonic() finished_utc = iso_now() time.sleep(0.5) sampler.stop() sampler.join(timeout=5) check(sampler.error is None, 'memory sampler failed: ' + str(sampler.error)) # Observed concurrency from the real client intervals. events = [] for item in results: events.append((item['started_monotonic'], 1)) events.append((item['finished_monotonic'], -1)) active = peak = 0 for _, delta in sorted(events, key=lambda pair: (pair[0], -pair[1])): active += delta peak = max(peak, active) per_instance = {} for item in results: bucket = per_instance.setdefault(item['instance_id'], {'uploads': 0, 'bytes': 0}) bucket['uploads'] += 1 bucket['bytes'] += item['bytes'] memory = {} for hostname in baseline: rss = [row['api'][hostname]['process']['rss_bytes'] for row in sampler.samples if row['api'].get(hostname) and row['api'][hostname]['process']] hwm = [row['api'][hostname]['process']['hwm_bytes'] for row in sampler.samples if row['api'].get(hostname) and row['api'][hostname]['process']] cgroup = [row['api'][hostname]['cgroup']['current_bytes'] for row in sampler.samples if row['api'].get(hostname) and row['api'][hostname]['cgroup']] cgroup_peak = [row['api'][hostname]['cgroup']['peak_bytes'] for row in sampler.samples if row['api'].get(hostname) and row['api'][hostname]['cgroup']] memory[hostname] = { 'samples': len(rss), 'baseline_rss_bytes': baseline[hostname]['process']['rss_bytes'] if baseline[hostname]['process'] else None, 'baseline_hwm_bytes': baseline[hostname]['process']['hwm_bytes'] if baseline[hostname]['process'] else None, 'peak_sampled_rss_bytes': max(rss) if rss else None, 'peak_sampled_rss_delta_bytes': (max(rss) - baseline[hostname]['process']['rss_bytes']) if rss and baseline[hostname]['process'] else None, 'final_hwm_bytes': hwm[-1] if hwm else None, 'peak_cgroup_current_bytes': max(cgroup) if cgroup else None, 'peak_cgroup_memory_peak_bytes': max(cgroup_peak) if cgroup_peak else None, 'api_memory_limit_bytes': api_limit, } successes = [item for item in results if item['status'] == 201 and item['server_status'] == 'ready' and item['server_sha256'] == item['sha256'] and item['server_size_bytes'] == item['bytes']] failures = [item for item in results if item not in successes] restarts_after = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api} check(len(results) == CONCURRENCY, 'not all uploads returned') check(len(successes) == CONCURRENCY, 'some uploads failed') check(peak >= 10, 'observed concurrency below 10: %d' % peak) check(not failures, 'failed uploads: %r' % [(item['index'], item['status']) for item in failures]) check(restarts_after == restarts_before, 'an API container restarted during the experiment') for hostname, item in memory.items(): check(item['peak_sampled_rss_bytes'] and item['peak_sampled_rss_bytes'] < api_limit, 'process RSS exceeded the container limit on ' + hostname) summary = { 'experiment': 'lab4 concurrent upload: peak API process RSS', 'generated_at': iso_now(), 'git_revision': revision, 'api_image_id': image_id, 'base_url': args.base_url, 'started_at': started_utc, 'finished_at': finished_utc, 'wall_seconds': round(finished_monotonic - started_monotonic, 3), 'configured_concurrency': CONCURRENCY, 'observed_peak_concurrency': peak, 'successful_uploads': len(successes), 'failed_uploads': len(failures), 'api_instances': sorted(per_instance), 'uploads_per_instance': per_instance, 'profile': { 'files': len(profiles), 'total_bytes': sum(item['bytes'] for item in profiles), 'min_bytes': min(item['bytes'] for item in profiles), 'max_bytes': max(item['bytes'] for item in profiles), 'max_pixels': max(item['pixels'] for item in profiles), 'small': {'count': 6, 'width': 1000, 'height': 700}, 'medium': {'count': 4, 'width': 1500, 'height': 1100}, 'near_max_bytes': {'count': 2, 'width': 1600, 'height': 2167}, }, 'limits': { 'api_memory_limit_bytes': api_limit, 'GOMEMLIMIT': gomemlimit, 'UPLOAD_DECODE_CONCURRENCY': decode_concurrency, 'S3_PUT_CONCURRENCY': put_concurrency, 'MAX_UPLOAD_BYTES': max_upload, 'MAX_IMAGE_PIXELS': max_pixels, }, 'memory_metrics': { 'process_rss_source': '/proc/1/status VmRSS inside each API container, sampled by docker exec', 'process_hwm_source': '/proc/1/status VmHWM inside each API container', 'cgroup_source': '/sys/fs/cgroup/memory.current and memory.peak (whole container cgroup)', 'sample_interval_seconds': SAMPLE_INTERVAL_SECONDS, 'samples_taken': len(sampler.samples), 'first_sample_at': sampler.samples[0]['sampled_at'] if sampler.samples else None, 'last_sample_at': sampler.samples[-1]['sampled_at'] if sampler.samples else None, 'max_sample_gap_seconds': round(max( sampler.samples[index]['monotonic_seconds'] - sampler.samples[index - 1]['monotonic_seconds'] for index in range(1, len(sampler.samples))), 3) if len(sampler.samples) > 1 else None, 'per_instance': memory, }, 'uploads': [{key: value for key, value in item.items() if key != 'content'} for item in results], 'result': 'PASS', 'limitations': [ 'One local stand: RSS includes Go runtime and handler state, not a production profile.', 'The sampler uses docker exec every 200 ms; a shorter allocation spike between samples is ' 'bounded by VmHWM, which is also reported.', 'cgroup memory.current includes page cache and is not process RSS.', ], } M.write_json(EVIDENCE / 'uploads.json', summary['uploads']) M.write_json(EVIDENCE / 'rss-samples.json', {'samples': sampler.samples, 'baseline': baseline}) M.write_json(EVIDENCE / 'summary.json', summary) print(json.dumps({ 'result': 'PASS', 'observed_peak_concurrency': peak, 'successful_uploads': len(successes), 'wall_seconds': summary['wall_seconds'], 'process_peak_sampled_rss_bytes': {key: value['peak_sampled_rss_bytes'] for key, value in memory.items()}, 'process_final_hwm_bytes': {key: value['final_hwm_bytes'] for key, value in memory.items()}, 'api_memory_limit_bytes': api_limit, }, ensure_ascii=False)) print('PASS: >=10 concurrent uploads with bounded API process RSS') if __name__ == '__main__': try: main() except (Failure, ValueError, OSError) as exc: print('FAIL:', str(exc)) raise SystemExit(1)