Files

71 lines
2.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Locust 统计落盘插件:run 结束时把 stats 序列化为 JSON 到 results/。
供 python worker 与 go worker(master 侧)共用 —— go 压测时统计也在 master 汇总,
所以两份 locustfile 都 import 本模块。文件名前缀由环境变量 PERF_WORKER 决定。
"""
import json
import os
import time
from locust import events
RESULTS_DIR = os.path.join(os.path.dirname(os.path.dirname(
os.path.abspath(__file__))), "results")
def _serialize(environment):
stats = environment.stats
entries = []
for e in stats.entries.values():
entries.append({
"name": e.name,
"method": e.method,
"num_requests": e.num_requests,
"num_failures": e.num_failures,
"avg_response_time": round(e.avg_response_time, 3),
"min_response_time": e.min_response_time,
"max_response_time": e.max_response_time,
"p50": round(e.get_response_time_percentile(0.50), 3),
"p95": round(e.get_response_time_percentile(0.95), 3),
"p99": round(e.get_response_time_percentile(0.99), 3),
"rps": round(e.total_rps, 3),
})
total = stats.total
doc = {
"worker": os.environ.get("PERF_WORKER", "unknown"),
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
"load": {
"users": getattr(environment.parsed_options, "num_users", None),
"run_time": getattr(environment.parsed_options, "run_time", None),
"host": getattr(environment.parsed_options, "host", None),
},
"total": {
"num_requests": total.num_requests,
"num_failures": total.num_failures,
"avg_response_time": round(total.avg_response_time, 3),
"p50": round(total.get_response_time_percentile(0.50), 3),
"p95": round(total.get_response_time_percentile(0.95), 3),
"p99": round(total.get_response_time_percentile(0.99), 3),
"rps": round(total.total_rps, 3),
},
"entries": entries,
}
label = os.environ.get("PERF_LABEL")
if label:
# 实验参数透传(如 scale 实验的 instances/max_qps),写进结果便于报告核对
doc["label"] = label
return doc
@events.quitting.add_listener
def _dump(environment, **kwargs):
if environment.parsed_options and environment.parsed_options.worker:
return # worker 进程不落盘
os.makedirs(RESULTS_DIR, exist_ok=True)
worker = os.environ.get("PERF_WORKER", "unknown")
path = os.path.join(RESULTS_DIR, f"{worker}-{int(time.time())}.json")
with open(path, "w", encoding="utf-8") as f:
json.dump(_serialize(environment), f, ensure_ascii=False, indent=2)
print(f"\n[stats] written to {path}")