noodcon's picture mondk's picture
Duplicate from mondk/TerminalBench-DockerLess
b199558
Raw History Blame Contribute Delete
2.58 kB
#!/usr/bin/env bash
# Oracle solution: a regex-based parser that survives escaped quotes in the
# user-agent field, plus deterministic JSON/gzip output.
set -euo pipefail
cd "$TB_WORK"
mkdir -p tools
cat > tools/report.py <<'PYEOF'
import gzip
import json
import math
import re
from collections import Counter
from pathlib import Path
LINE = re.compile(
r'^(?P<ip>\S+) - - \[(?P<ts>[^\]]+)\] '
r'"(?P<method>[A-Z]+) (?P<path>\S+) HTTP/1\.1" '
r'(?P<status>\d{3}) (?P<size>\d+|-) '
r'"(?P<ref>(?:[^"\\]|\\.)*)" "(?P<ua>(?:[^"\\]|\\.)*)" '
r'(?P<ms>\d+)$'
)
def main():
root = Path(__file__).resolve().parent.parent
log = root / "logs" / "access.log"
raw = log.read_bytes()
lines = raw.decode("utf-8").split("\n")
if lines and lines[-1] == "":
lines.pop()
paths, statuses, durations, bad = [], [], [], []
total_bytes = 0
for number, line in enumerate(lines, 1):
match = LINE.match(line)
if match is None:
bad.append(number)
continue
paths.append(match.group("path").split("?")[0])
statuses.append(match.group("status"))
size = match.group("size")
total_bytes += 0 if size == "-" else int(size)
durations.append(int(match.group("ms")))
durations.sort()
count = len(durations)
p95 = durations[math.ceil(0.95 * count) - 1] if count else 0
path_counts = Counter(paths)
top = sorted(path_counts.items(), key=lambda item: (-item[1], item[0]))[:3]
report = {
"total_requests": count,
"unique_paths": len(path_counts),
"status_counts": dict(sorted(Counter(statuses).items())),
"top_paths": [{"path": path, "count": hits} for path, hits in top],
"bytes_total": total_bytes,
"p95_ms": p95,
}
out = root / "out"
out.mkdir(parents=True, exist_ok=True)
with open(out / "report.json", "w", encoding="utf-8", newline="\n") as handle:
handle.write(json.dumps(report, indent=2, sort_keys=True) + "\n")
with open(out / "malformed.txt", "w", encoding="utf-8", newline="\n") as handle:
handle.write("".join("%d\n" % number for number in bad))
with open(out / "access.log.gz", "wb") as handle:
with gzip.GzipFile(fileobj=handle, mode="wb", mtime=0) as gz:
gz.write(raw)
if __name__ == "__main__":
main()
PYEOF
cat > tools/report.sh <<'SHEOF'
#!/usr/bin/env bash
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
exec python "$here/tools/report.py"
SHEOF
chmod +x tools/report.sh
bash tools/report.sh