From b414d7e3202135e7e36916f4686989a81961c2e0 Mon Sep 17 00:00:00 2001 From: WbiubiuW Date: Tue, 22 Sep 2026 14:28:45 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20Python(Locust)=20+=20Go(boomer)=20?= =?UTF-8?q?=E6=B7=B7=E5=90=88=E5=8E=8B=E6=B5=8B=E6=A1=86=E6=9E=B6=EF=BC=88?= =?UTF-8?q?=E6=BC=94=E7=A4=BA=E7=89=88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ._.git | Bin 0 -> 163 bytes ._.gitignore | Bin 0 -> 163 bytes ._README.md | Bin 0 -> 163 bytes ._THIRD_PARTY.md | Bin 0 -> 163 bytes ._compare.py | Bin 0 -> 163 bytes ._go | Bin 0 -> 163 bytes ._python | Bin 0 -> 163 bytes ._report.md | Bin 0 -> 163 bytes ._results | Bin 0 -> 163 bytes ._run.sh | Bin 0 -> 163 bytes ._scenarios | Bin 0 -> 163 bytes ._target | Bin 0 -> 163 bytes ._tests | Bin 0 -> 163 bytes .gitignore | 7 + README.md | 219 ++++++++++ THIRD_PARTY.md | 68 +++ compare.py | 211 +++++++++ go/._client.go | Bin 0 -> 163 bytes go/._client_test.go | Bin 0 -> 163 bytes go/._go.mod | Bin 0 -> 163 bytes go/._go.sum | Bin 0 -> 163 bytes go/._main.go | Bin 0 -> 163 bytes go/._tasks.go | Bin 0 -> 163 bytes go/._third_party | Bin 0 -> 163 bytes go/client.go | 96 ++++ go/client_test.go | 23 + go/go.mod | 26 ++ go/go.sum | 38 ++ go/main.go | 26 ++ go/tasks.go | 104 +++++ go/third_party/._boomer | Bin 0 -> 163 bytes go/third_party/boomer/._LICENSE | Bin 0 -> 163 bytes go/third_party/boomer/._boomer.go | Bin 0 -> 163 bytes go/third_party/boomer/._client.go | Bin 0 -> 163 bytes go/third_party/boomer/._client_czmq.go | Bin 0 -> 163 bytes go/third_party/boomer/._client_gomq.go | Bin 0 -> 163 bytes go/third_party/boomer/._go.mod | Bin 0 -> 163 bytes go/third_party/boomer/._legacy.go | Bin 0 -> 163 bytes go/third_party/boomer/._message.go | Bin 0 -> 163 bytes go/third_party/boomer/._output.go | Bin 0 -> 163 bytes go/third_party/boomer/._ratelimiter.go | Bin 0 -> 163 bytes go/third_party/boomer/._runner.go | Bin 0 -> 163 bytes go/third_party/boomer/._stats.go | Bin 0 -> 163 bytes go/third_party/boomer/._task.go | Bin 0 -> 163 bytes go/third_party/boomer/._taskset.go | Bin 0 -> 163 bytes go/third_party/boomer/._utils.go | Bin 0 -> 163 bytes go/third_party/boomer/LICENSE | 21 + go/third_party/boomer/boomer.go | 280 ++++++++++++ go/third_party/boomer/client.go | 9 + go/third_party/boomer/client_czmq.go | 127 ++++++ go/third_party/boomer/client_gomq.go | 129 ++++++ go/third_party/boomer/go.mod | 3 + go/third_party/boomer/legacy.go | 89 ++++ go/third_party/boomer/message.go | 38 ++ go/third_party/boomer/output.go | 146 +++++++ go/third_party/boomer/ratelimiter.go | 213 +++++++++ go/third_party/boomer/runner.go | 555 ++++++++++++++++++++++++ go/third_party/boomer/stats.go | 309 +++++++++++++ go/third_party/boomer/task.go | 13 + go/third_party/boomer/taskset.go | 107 +++++ go/third_party/boomer/utils.go | 110 +++++ python/._locustfile.py | Bin 0 -> 163 bytes python/._master_locustfile.py | Bin 0 -> 163 bytes python/._stats_dump.py | Bin 0 -> 163 bytes python/locustfile.py | 75 ++++ python/master_locustfile.py | 21 + python/stats_dump.py | 70 +++ report.md | 94 ++++ results/._go-1789962012.json | Bin 0 -> 163 bytes results/._go-1790009273.json | Bin 0 -> 163 bytes results/._go-1790010541.json | Bin 0 -> 163 bytes results/._go-1790054848.json | Bin 0 -> 163 bytes results/._go-1790055182.json | Bin 0 -> 163 bytes results/._live_trigger-1790009033.json | Bin 0 -> 163 bytes results/._live_trigger-1790010331.json | Bin 0 -> 163 bytes results/._live_trigger-1790054558.json | Bin 0 -> 163 bytes results/._python-1789961949.json | Bin 0 -> 163 bytes results/._python-1790009211.json | Bin 0 -> 163 bytes results/._python-1790010434.json | Bin 0 -> 163 bytes results/._python-1790054714.json | Bin 0 -> 163 bytes results/._python-1790055119.json | Bin 0 -> 163 bytes results/._scale-1-1790009085.json | Bin 0 -> 163 bytes results/._scale-1-1790010617.json | Bin 0 -> 163 bytes results/._scale-1-1790054950.json | Bin 0 -> 163 bytes results/._scale-1-1790055215.json | Bin 0 -> 163 bytes results/._scale-4-1790009118.json | Bin 0 -> 163 bytes results/._scale-4-1790010691.json | Bin 0 -> 163 bytes results/._scale-4-1790055053.json | Bin 0 -> 163 bytes results/._scale-4-1790055249.json | Bin 0 -> 163 bytes results/._stale_trigger-1790009032.json | Bin 0 -> 163 bytes results/._stale_trigger-1790010330.json | Bin 0 -> 163 bytes results/._stale_trigger-1790054558.json | Bin 0 -> 163 bytes results/go-1789962012.json | 72 +++ results/go-1790009273.json | 72 +++ results/go-1790010541.json | 72 +++ results/go-1790054848.json | 72 +++ results/go-1790055182.json | 72 +++ results/live_trigger-1790009033.json | 47 ++ results/live_trigger-1790010331.json | 47 ++ results/live_trigger-1790054558.json | 47 ++ results/python-1789961949.json | 72 +++ results/python-1790009211.json | 72 +++ results/python-1790010434.json | 72 +++ results/python-1790054714.json | 72 +++ results/python-1790055119.json | 72 +++ results/scale-1-1790009085.json | 73 ++++ results/scale-1-1790010617.json | 73 ++++ results/scale-1-1790054950.json | 73 ++++ results/scale-1-1790055215.json | 73 ++++ results/scale-4-1790009118.json | 73 ++++ results/scale-4-1790010691.json | 73 ++++ results/scale-4-1790055053.json | 73 ++++ results/scale-4-1790055249.json | 73 ++++ results/stale_trigger-1790009032.json | 58 +++ results/stale_trigger-1790010330.json | 58 +++ results/stale_trigger-1790054558.json | 58 +++ run.sh | 148 +++++++ scenarios/._verify_trigger.py | Bin 0 -> 163 bytes scenarios/verify_trigger.py | 319 ++++++++++++++ target/._dispatcher.py | Bin 0 -> 163 bytes target/._http_server.py | Bin 0 -> 163 bytes target/._mark_price_service.py | Bin 0 -> 163 bytes target/dispatcher.py | 141 ++++++ target/http_server.py | 203 +++++++++ target/mark_price_service.py | 219 ++++++++++ tests/._conftest.py | Bin 0 -> 163 bytes tests/._test_condition_trigger.py | Bin 0 -> 163 bytes tests/._test_dispatcher.py | Bin 0 -> 163 bytes tests/._test_mark_price_service.py | Bin 0 -> 163 bytes tests/._test_pacer.py | Bin 0 -> 163 bytes tests/conftest.py | 9 + tests/test_condition_trigger.py | 51 +++ tests/test_dispatcher.py | 81 ++++ tests/test_mark_price_service.py | 116 +++++ tests/test_pacer.py | 38 ++ 135 files changed, 6171 insertions(+) create mode 100755 ._.git create mode 100644 ._.gitignore create mode 100644 ._README.md create mode 100644 ._THIRD_PARTY.md create mode 100644 ._compare.py create mode 100755 ._go create mode 100755 ._python create mode 100644 ._report.md create mode 100755 ._results create mode 100644 ._run.sh create mode 100755 ._scenarios create mode 100755 ._target create mode 100755 ._tests create mode 100644 .gitignore create mode 100644 README.md create mode 100644 THIRD_PARTY.md create mode 100644 compare.py create mode 100644 go/._client.go create mode 100644 go/._client_test.go create mode 100644 go/._go.mod create mode 100644 go/._go.sum create mode 100644 go/._main.go create mode 100644 go/._tasks.go create mode 100755 go/._third_party create mode 100644 go/client.go create mode 100644 go/client_test.go create mode 100644 go/go.mod create mode 100644 go/go.sum create mode 100644 go/main.go create mode 100644 go/tasks.go create mode 100755 go/third_party/._boomer create mode 100644 go/third_party/boomer/._LICENSE create mode 100644 go/third_party/boomer/._boomer.go create mode 100644 go/third_party/boomer/._client.go create mode 100644 go/third_party/boomer/._client_czmq.go create mode 100644 go/third_party/boomer/._client_gomq.go create mode 100644 go/third_party/boomer/._go.mod create mode 100644 go/third_party/boomer/._legacy.go create mode 100644 go/third_party/boomer/._message.go create mode 100644 go/third_party/boomer/._output.go create mode 100644 go/third_party/boomer/._ratelimiter.go create mode 100644 go/third_party/boomer/._runner.go create mode 100644 go/third_party/boomer/._stats.go create mode 100644 go/third_party/boomer/._task.go create mode 100644 go/third_party/boomer/._taskset.go create mode 100644 go/third_party/boomer/._utils.go create mode 100644 go/third_party/boomer/LICENSE create mode 100644 go/third_party/boomer/boomer.go create mode 100644 go/third_party/boomer/client.go create mode 100644 go/third_party/boomer/client_czmq.go create mode 100644 go/third_party/boomer/client_gomq.go create mode 100644 go/third_party/boomer/go.mod create mode 100644 go/third_party/boomer/legacy.go create mode 100644 go/third_party/boomer/message.go create mode 100644 go/third_party/boomer/output.go create mode 100644 go/third_party/boomer/ratelimiter.go create mode 100644 go/third_party/boomer/runner.go create mode 100644 go/third_party/boomer/stats.go create mode 100644 go/third_party/boomer/task.go create mode 100644 go/third_party/boomer/taskset.go create mode 100644 go/third_party/boomer/utils.go create mode 100644 python/._locustfile.py create mode 100644 python/._master_locustfile.py create mode 100644 python/._stats_dump.py create mode 100644 python/locustfile.py create mode 100644 python/master_locustfile.py create mode 100644 python/stats_dump.py create mode 100644 report.md create mode 100644 results/._go-1789962012.json create mode 100644 results/._go-1790009273.json create mode 100644 results/._go-1790010541.json create mode 100644 results/._go-1790054848.json create mode 100644 results/._go-1790055182.json create mode 100644 results/._live_trigger-1790009033.json create mode 100644 results/._live_trigger-1790010331.json create mode 100644 results/._live_trigger-1790054558.json create mode 100644 results/._python-1789961949.json create mode 100644 results/._python-1790009211.json create mode 100644 results/._python-1790010434.json create mode 100644 results/._python-1790054714.json create mode 100644 results/._python-1790055119.json create mode 100644 results/._scale-1-1790009085.json create mode 100644 results/._scale-1-1790010617.json create mode 100644 results/._scale-1-1790054950.json create mode 100644 results/._scale-1-1790055215.json create mode 100644 results/._scale-4-1790009118.json create mode 100644 results/._scale-4-1790010691.json create mode 100644 results/._scale-4-1790055053.json create mode 100644 results/._scale-4-1790055249.json create mode 100644 results/._stale_trigger-1790009032.json create mode 100644 results/._stale_trigger-1790010330.json create mode 100644 results/._stale_trigger-1790054558.json create mode 100644 results/go-1789962012.json create mode 100644 results/go-1790009273.json create mode 100644 results/go-1790010541.json create mode 100644 results/go-1790054848.json create mode 100644 results/go-1790055182.json create mode 100644 results/live_trigger-1790009033.json create mode 100644 results/live_trigger-1790010331.json create mode 100644 results/live_trigger-1790054558.json create mode 100644 results/python-1789961949.json create mode 100644 results/python-1790009211.json create mode 100644 results/python-1790010434.json create mode 100644 results/python-1790054714.json create mode 100644 results/python-1790055119.json create mode 100644 results/scale-1-1790009085.json create mode 100644 results/scale-1-1790010617.json create mode 100644 results/scale-1-1790054950.json create mode 100644 results/scale-1-1790055215.json create mode 100644 results/scale-4-1790009118.json create mode 100644 results/scale-4-1790010691.json create mode 100644 results/scale-4-1790055053.json create mode 100644 results/scale-4-1790055249.json create mode 100644 results/stale_trigger-1790009032.json create mode 100644 results/stale_trigger-1790010330.json create mode 100644 results/stale_trigger-1790054558.json create mode 100644 run.sh create mode 100644 scenarios/._verify_trigger.py create mode 100644 scenarios/verify_trigger.py create mode 100644 target/._dispatcher.py create mode 100644 target/._http_server.py create mode 100644 target/._mark_price_service.py create mode 100644 target/dispatcher.py create mode 100644 target/http_server.py create mode 100644 target/mark_price_service.py create mode 100644 tests/._conftest.py create mode 100644 tests/._test_condition_trigger.py create mode 100644 tests/._test_dispatcher.py create mode 100644 tests/._test_mark_price_service.py create mode 100644 tests/._test_pacer.py create mode 100644 tests/conftest.py create mode 100644 tests/test_condition_trigger.py create mode 100644 tests/test_dispatcher.py create mode 100644 tests/test_mark_price_service.py create mode 100644 tests/test_pacer.py diff --git a/._.git b/._.git new file mode 100755 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K macOS 上 `python3` 常指向一个没装这些包的解释器。确认一下: +> `python3 -c "import locust, pytest"` 不报错再往下走;否则换成你实际装了依赖的那个解释器 +> (本机是 `~/miniconda3/bin/python3`)。 + +**跑一遍** + +```bash +bash run.sh target # 起本机 mock(HTTP :18099) +bash run.sh python --users 50 --duration 60s # 判断①:Python worker +bash run.sh go --users 50 --duration 60s # 判断①:Go worker(master/slave) + +python3 scenarios/verify_trigger.py # 判断②:写死 vs 缓存驱动,一次跑完两组 + +bash run.sh scale-1 # 判断③:1 实例 +bash run.sh scale-4 # 判断③:4 实例 + +bash run.sh report # 汇总 results/*.json → report.md +``` + +每条压测命令都会往 `results/` 落一份 JSON,报告的数字**只从这些 JSON 里读**,不手写。 + +**验证** + +```bash +python3 -m pytest tests/ -q # 21 passed +(cd go && go test ./...) # Go 侧:连接池断言 +``` + +单测钉住的是最容易做假、且做假了没人看得见的语义:滑动窗口去重(含 A-B-A 交替)、 +断流回退、触发判定方向、限流器、分流器、连接池断言。 + +--- + +## 架构 + +``` + run.sh python run.sh go + ───────────── ────────── + Locust 单进程直跑 Locust master(控制面 + 统计汇总) + (不经 master) │ ZMQ :5557 + │ ▼ + │ Go worker (boomer slave) + │ goroutine × N + │ │ + └──────────────┬──────────────────────┘ + │ HTTP /api/v1/order/...(同场景、同请求体) + ▼ + ┌──────────────────────┐ + │ HTTP mock :18099│ 条件单 endpoint + TARGET_MAX_QPS 上限 + └──────────┬───────────┘ + ▲ 行情轮询 + ┌──────────┴───────────┐ ┌────────────────────────┐ + │ mark_price_service │ │ dispatcher :18100│ + │ :18097 标记价缓存 │ │ 扩展实验的入口分流 │ + └──────────────────────┘ └────────────────────────┘ +``` + +两种 worker 的统计都汇到同一个 Locust master,保证**同口径出数**。 +任务表是配置驱动的(`python/locustfile.py` 的 `TASK_WEIGHTS`、`go/tasks.go` 的 `taskTable()`), +增删任务不动框架。 + +--- + +## 关键技术点 + +1. **GIL 取舍**:Python 单进程内所有协程共享一个 GIL,JSON 编解码、locust 统计、gevent 调度 + 都是纯 CPU 段,并发上去单核打满、TPS 触顶。Go 的 goroutine 由 runtime 多线程调度、 + 网络 I/O 走 netpoller,没有这个天花板。 + +2. **连接池调优必须落在"真身"上**:手写 `http.Transport` 时,参数很容易落在一个 + **从未被 `client.Transport` 引用**的变量上 —— 于是默认的 `MaxIdleConnsPerHost=2` 生效, + 压不上去,却极易被误归因到被测服务。`TestTransportPool` **断言 client 实际使用的 + transport 就是调优过的那个**,把「我调优了」从错觉变成事实。 + +3. **标记价缓存的两条硬语义**(`target/mark_price_service.py`,由 `tests/` 钉死): + - **滑动窗口去重**:窗口必须保存最近两个**已接受**的价格。只存"最后一个值"的伪窗口 + 识别不了 A-B-A 交替重复(100→105→100 时第三笔会被误判为新变化),等于没去重。 + - **断流回退**:行情源挂掉时**回退默认价继续出价**,不是报错退出 —— 压测不能中断。 + +4. **单实例上限要可测量**:mock 支持 `TARGET_MAX_QPS`(超限请求排队等位,表现为 TPS 封顶 + + 延迟上升,而**不是**错误率上升)与 `TARGET_EXTRA_LATENCY_MS`。`run.sh scale-N` 起 N 个实例 + + 入口分流器,用**除实例数外完全一致**的参数对比 —— 扩展是有依据的决策,不是"感觉慢了加机器"。 + +5. **boomer 与 locust 2.x 的协议补丁**(`go/third_party/boomer`,3 处,见 + [THIRD_PARTY.md](THIRD_PARTY.md)):`client_ready` data `nil → -1`;`spawn` 消息迁移到 + `user_classes_count/parsed_options`;`stats` / `spawning_complete` 上报 + `user_classes_count`(否则被当 unknown worker 踢掉)。 + +--- + +## 背景:这套东西是怎么来的 + +> 这一节讲的是**动机**,不是本仓库能提供的证据。下面那些生产数字来自我此前的合约交易系统 +> 压测经历,**本仓库不承载、也无法复现它们**;本仓库只复现方法论。 + +当时的指标是:10 个用户并发下单,下单接口 TPS 达到 10 万。用阶梯压测(1h → 2h → 4/8/12/24h) +验证长期稳定性,而不是测瞬时峰值。过程中撞了三次瓶颈: + +| # | 瓶颈 | 破局 | +|---|---|---| +| 1 | 压测脚本自己失真:条件单触发价写死 → 全触发或全不触发,整批数据作废 | 自建标记价格缓存服务:订阅行情 → 滑动窗口去重 → 本地缓存 TTL;**断流时回退默认价**保证压测不中断 | +| 2 | Python GIL:Locust 动态参数灵活,但单机打不满并发 | 用 Go + boomer 重写压力机,Python 只留 Locust master 做控制;另用 gRPC 客户端直压绕过 HTTP 层(**这条 gRPC 通道本仓库没有复刻**) | +| 3 | 单服务集群上限约 12000,撑不起指标 | 横向扩展:委托/结算/权益 40 实例、撮合/风控 10、入口 Nginx 20 | + +结果:10 用户并发、平均响应 1-2s、24h 稳定运行、实测 10-12 万 TPS。 + +**工具选型的试错路径**(JMeter → Locust → Go + boomer): + +| 方案 | 为什么没走到最后 | +|---|---| +| JMeter | 参数化机制很难表达「按实时行情动态触发」,要写复杂预处理器 | +| Locust(Python) | 用代码表达动态参数很自然,但受 GIL 限制,单机并发有瓶颈 | +| **Go + boomer 重写 worker** | 保住动态参数的灵活性,同时突破并发瓶颈 —— 最终选它 | + +**一个取舍**:换引擎不难,难的是选对切换时机。第一轮交付沿用原方案保进度, +把调研结论整理成文档同步给团队,后续轮次才切到 Go 方案。 + +**另一条经验**:本机压测会撞到多层瓶颈(mock 网关、loopback、worker 自身)。 +归因时必须说清「这次测出来的瓶颈在哪一层」—— 能定位瓶颈比能跑高 TPS 更值钱。 + +--- + +## 目录 + +``` +python/locustfile.py Python worker(4 类订单请求,权重 4:2:2:1) +python/master_locustfile.py Go 压测时的 master 入口(复用统计落盘) +python/stats_dump.py 统计落盘(results/*.json) +go/ boomer worker(编译产物压测,非 go run) +go/third_party/boomer/ vendored boomer v1.6.0 + locust 2.x 协议补丁(MIT) + 仅保留编译所需文件,见 THIRD_PARTY.md +target/http_server.py 本机被测 mock(:18099;条件单 endpoint + + 可配置单实例上限 TARGET_MAX_QPS / TARGET_EXTRA_LATENCY_MS) +target/mark_price_service.py 标记价格缓存服务(:18097) +target/dispatcher.py 入口分流器(:18100),扩展实验用 +scenarios/verify_trigger.py 失真对比实验(写死 vs 缓存驱动,一次跑完两组) +tests/ 21 条单测(去重 / 断流回退 / 触发判定 / 限流 / 分流) +compare.py 报告生成器(数字只来自 results/) +results/ 原始 JSON +report.md 对比报告(由 compare.py 生成) +``` + +--- + +## 边界与口径 + +- 只压本机 mock(`127.0.0.1`),**绝不对外发压**。 +- 报告里的数字**必须真实跑出**;`compare.py` 只读 `results/*.json`。 +- 两种 worker 必须**同场景、同并发、同请求体**;扩展实验除实例数外参数必须完全一致。 +- 接口路径与合约 ID 均为中性自造值,无凭据、无真实域名。 +- **口径分栏**:本仓库跑出的数字一律属「**本机演示实测**」;「背景」一节提到的历史业绩属 + 「**生产真实业绩**」,只作动机,本仓库不提供其证据。两者**不可混写**,也不可互相换算。 + +--- + +## 第三方 + +`go/third_party/boomer` 是 [boomer](https://github.com/myzhan/boomer) v1.6.0 的 vendored 副本 +(MIT License, Copyright (c) 2019 myzhan),其上打了 3 处 locust 2.x 协议补丁。 +许可证与补丁明细见 [THIRD_PARTY.md](THIRD_PARTY.md)。 + +副本**只保留了编译与运行所需的 15 个文件**(13 个 `.go` + `go.mod` + `LICENSE`); +上游自带的 `examples/`、`docs/`、自测与 CI 配置已移出(本项目从不引用)。 +保留文件的内容未做任何改动(3 处协议补丁除外)。 + +本仓库自身的 LICENSE 尚未选定 —— 若要公开,需要先补一个。 diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000..3a9cd23 --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,68 @@ +# 第三方组件与补丁 / Third-party Components & Patches + +## boomer v1.6.0 + +| 项 | 值 | +|---|---| +| 名称 | boomer(Locust 的 Go 兼容实现,用 Go 写 Locust worker) | +| 版本 | v1.6.0 | +| 上游 | https://github.com/myzhan/boomer | +| 许可证 | **MIT License, Copyright (c) 2019 myzhan** | +| 本地位置 | `go/third_party/boomer/` | +| 引入方式 | vendored 源码副本;`go/go.mod` 里用 `replace github.com/myzhan/boomer => ./third_party/boomer` 指过来 | + +`LICENSE` 原样保留在 `go/third_party/boomer/LICENSE`,未做任何修改。 + +## 为什么 vendored + +上游 boomer v1.6.0 只兼容 **locust 1.x** 的 master/slave 通信协议,而本项目的 +Locust master 是 **2.x**。不改协议就没法握手,因此把源码放进仓库直接打补丁。 + +## 关于裁剪(2026-09-22) + +上游仓库是整仓复制过来的,其中大部分文件与「编译出一个 Go worker」无关。 +本项目**只保留编译与运行所需的文件**(15 个:13 个 `.go` + `go.mod` + `LICENSE`), +移出了上游自带的 `examples/`、`docs/`、`_test.go`、`README*.md`、CI 配置等约 50 个文件。 + +- 移出的都是**上游自带的示例、文档与自测**,本项目从不引用、也从不运行它们 + (`third_party/boomer` 是独立 module,`go test ./...` 不会进入)。 +- **没有改动任何被保留文件的内容**(3 处协议补丁除外,见下节)。 +- 判据:裁剪前后 `go build` 产出的二进制 **md5 完全一致**,`go mod verify` 通过。 +- 若要对照上游原文,去 https://github.com/myzhan/boomer 取 v1.6.0 全量源码即可。 + +## 打了哪 3 处补丁 + +全部集中在 `runner.go`(另 `message.go` 有配套小改),补丁位置按行号列出,便于日后 +升级 boomer 时对照重打。 + +| # | 位置 | 改了什么 | 为什么 | +|---|---|---|---| +| 1 | `runner.go:463`、`runner.go:516` | `newMessage("client_ready", nil, ...)` → `newMessage("client_ready", -1, ...)` | locust 2.x 约定用 `-1` 表示「跳过版本检查」;传 `nil` 会被拒绝 | +| 2 | `runner.go:337-342`、`runner.go:259/314/526` | `spawn` 消息从旧的 `num_users` / `spawn_rate` 迁移到 `user_classes_count` / `parsed_options` | locust 2.x 改了 spawn 消息结构,旧字段被忽略 | +| 3 | `runner.go:259/314/526`、`runner.go:315` | `stats` 与 `spawning_complete` 上报 `user_classes_count`(`{"BoomerWorker": numClients}`) | 不上报会被 master 当成 unknown worker 踢掉,表现为「连上了但不发压」 | + +> 三处都不改动 boomer 的业务逻辑,只补协议字段 —— 属于「让它能接上 2.x master」的最小改动。 + +## 如何验证补丁在位 + +```bash +cd go/third_party/boomer + +# 补丁 1 +grep -n 'client_ready' runner.go # 期望看到 -1,而不是 nil + +# 补丁 2 + 3 +grep -n 'user_classes_count' runner.go # 期望 5 处命中: + # 259 / 314 / 526 = 赋值上报 + # 337 = 说明注释,342 = 读取 spawn 消息里的值 + +# 补丁 3 +grep -n 'spawning_complete' runner.go +``` + +端到端验证(起 master 与 go worker,看 worker 是否被认领并出数): + +```bash +bash run.sh target +bash run.sh go --users 50 --duration 60s # 若协议不通,master 会一直等 worker +``` diff --git a/compare.py b/compare.py new file mode 100644 index 0000000..20c3c03 --- /dev/null +++ b/compare.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""perf-harness-demo 对比报告生成器。 + +用法:python3 compare.py results/*.json → 输出 markdown 到 stdout +(run.sh / 验收命令里重定向为 report.md) + +报告内容:负载参数核对(公平性)→ worker 指标对比 → 归因分析 +→ 失真对比实验(触发率)→ 横向扩展实验(TPS vs 实例数)。 +所有数字来自 results/ 下真实跑出来的 JSON,不编造。 +""" + +import json +import re +import sys + + +def load(paths): + runs = [] + for p in sorted(paths): + with open(p) as f: + d = json.load(f) + d["_file"] = p + runs.append(d) + return runs + + +def fmt_pct(num, den): + return f"{100.0 * num / den:.2f}%" if den else "0.00%" + + +def _section_trigger(out, trigger_runs): + """§5 失真对比实验:写死触发价 vs 缓存服务驱动 的触发率对照。""" + latest = {} + for r in trigger_runs: + latest[r["trigger"]["mode"]] = r # 文件按时间排序,后者覆盖前者 = 最近一轮 + out.append("## 5. 失真对比实验(条件单触发率)\n") + out.append("两种脚本打**同一个**条件单 endpoint(`POST /api/v1/order/condition/open`)," + "负载参数相同,唯一变量是**触发价的来源**。mock 标记价随时间波动" + "(contract 1 ≈ 31000 ± 1%)。\n") + out.append("| 脚本 | 相位 | 触发价策略 | 请求数 | 失败 | 触发数 | 触发率 |") + out.append("|---|---|---|---|---|---|---|") + for mode in ("stale", "live"): + r = latest.get(mode) + if not r: + continue + for ph in r["trigger"]["phases"]: + out.append(f"| {r['worker']} | {ph['name']} | {ph['detail']} | " + f"{ph['requests']} | {ph['failures']} | {ph['triggered']} | " + f"{ph['trigger_rate']:.2%} |") + out.append("") + stale, live = latest.get("stale"), latest.get("live") + out.append("**判读**:") + out.append("- 所有相位失败数都是 0 —— 单看压测报表(TPS / 错误率 / 延迟)," + "**每一轮都「一切正常」**。") + if stale: + rates = " 与 ".join(f"{ph['trigger_rate']:.0%}" + for ph in stale["trigger"]["phases"]) + out.append(f"- 但写死触发价的相位触发率塌缩到 **{rates}**:市场状态稍偏离" + "写死的值,结论整个翻转 —— 这批数据对条件单链路的容量评估毫无意义," + "而报表上看不出任何问题(「数据是错的,但看起来是对的」)。") + if live: + rate = live["trigger"]["phases"][0]["trigger_rate"] + out.append(f"- 缓存服务实时驱动的触发率为 **{rate:.2%}**,落在由行情波动决定的" + "中间区间(不退化到 0/1),压测数据才对触发链路有评估意义。") + out.append("- 缓存服务的滑动窗口去重 / 断流回退语义由 " + "`tests/test_mark_price_service.py` 钉死;触发判定方向由 " + "`tests/test_condition_trigger.py` 钉死。") + out.append("") + + +def _section_scale(out, scale_runs): + """§6 横向扩展实验:TPS 随实例数变化(除实例数外参数完全一致)。""" + latest = {} + for r in scale_runs: + m = re.match(r"scale-(\d+)$", r["worker"]) + if m: + latest[int(m.group(1))] = r + if not latest: + return + out.append("## 6. 横向扩展实验(单实例上限 → 多实例)\n") + out.append("被测 mock 设了单实例能力上限(`TARGET_MAX_QPS`,超限请求排队等位、" + "延迟上升),入口分流器轮询分发。各组实验**除实例数外参数完全一致**" + "(worker / 并发 / 时长 / 单实例上限,见「参数」列)。\n") + out.append("| 实例数 | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | 参数 |") + out.append("|---|---|---|---|---|---|---|---|") + for n in sorted(latest): + r = latest[n] + t = r["total"] + out.append(f"| {n} | {t['num_requests']} | " + f"{fmt_pct(t['num_failures'], t['num_requests'])} | " + f"{t['rps']:.1f} | {t['p50']} | {t['p95']} | {t['p99']} | " + f"{r.get('label', '')} |") + out.append("") + if 1 in latest and len(latest) > 1: + base = latest[1]["total"]["rps"] + top_n = max(latest) + top = latest[top_n]["total"]["rps"] + if base > 0: + out.append(f"**{top_n} 实例 TPS / 1 实例 TPS = {top / base:.2f}**" + f"({top:.0f} vs {base:.0f};不要求线性 —— 分流器与 loopback " + "也会吃一份,TPS 随实例数上升即说明扩展是有效的)。") + out.append("- 单实例触顶时 P99 被排队显著拉高 —— 「上限」是**测出来的能力边界**," + "不是一句「慢」;扩展实例数的决策依据正是这个数字。") + out.append("") + + +def main(paths): + runs = load(paths) + # 三类结果分开渲染:worker 对比(python/go)、失真实验、扩展实验 + bench, trigger_runs, scale_runs = [], [], [] + for r in runs: + if "trigger" in r: + trigger_runs.append(r) + elif r["worker"].startswith("scale-"): + scale_runs.append(r) + else: + bench.append(r) + by_worker = {} + for r in bench: + by_worker.setdefault(r["worker"], []).append(r) + + out = [] + out.append("# perf-harness-demo 对比报告\n") + out.append(f"> 生成自 {len(runs)} 份真实压测结果:" + + ", ".join(f"`{r['_file']}`" for r in runs) + "\n") + + # ★ 数字口径:生产业绩与本机实测必须物理分栏,禁止混写(见 README §数字口径) + out.append("## 0. 数字口径(先读这一节)\n") + out.append("| 口径 | 环境 | 数字 |") + out.append("|---|---|---|") + out.append("| **生产真实业绩** | 公司环境 · 多机集群 —— **不可由本仓库复现** " + "| 10 用户并发 · 平均响应 1-2s · 24h 稳定 · 实测 10-12 万 TPS |") + out.append("| **本机演示实测** | 单机 —— 由本仓库跑出,见下方第 2 节 | 见第 2 节表格 |") + out.append("") + out.append("> 生产数字是**背景**,不是本仓库的产出。本仓库是复现方法论的实验台," + "单机量级与生产环境不可比;**可比的是 Python 与 Go 两种 worker 的倍数差**。\n") + + # 负载参数(公平性核对) + out.append("## 1. 负载参数(公平性核对)\n") + out.append("| worker | users | run_time | host |") + out.append("|---|---|---|---|") + for r in bench: + l = r["load"] + out.append(f"| {r['worker']} | {l['users']} | {l['run_time']} | {l['host']} |") + out.append("\n两种 worker 跑**同一场景、同一并发、同一请求体**(4 类订单请求," + "权重 4:2:2:1,用户池 1000),唯一变量是执行引擎。\n") + + # 指标对比 + out.append("## 2. 指标对比(每 worker 取最近一轮)\n") + out.append("| worker | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) |") + out.append("|---|---|---|---|---|---|---|") + latest = {} + for w, rs in by_worker.items(): + latest[w] = rs[-1] + for w, r in latest.items(): + t = r["total"] + out.append(f"| {w} | {t['num_requests']} | " + f"{fmt_pct(t['num_failures'], t['num_requests'])} | " + f"{t['rps']:.1f} | {t['p50']} | {t['p95']} | {t['p99']} |") + + ratio = None + if "python" in latest and "go" in latest: + p, g = latest["python"]["total"], latest["go"]["total"] + if p["rps"] > 0: + ratio = g["rps"] / p["rps"] + out.append(f"\n**Go worker TPS 是 Python worker 的 {ratio:.2f} 倍**" + f"({g['rps']:.0f} vs {p['rps']:.0f},同并发同场景)。") + + # 分 endpoint 明细 + out.append("\n## 3. 分 endpoint 明细\n") + for w, r in latest.items(): + out.append(f"### {w}\n") + out.append("| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) |") + out.append("|---|---|---|---|---|---|") + for e in sorted(r["entries"], key=lambda x: x["name"]): + out.append(f"| {e['method']} {e['name']} | {e['num_requests']} | " + f"{e['num_failures']} | {e['rps']:.1f} | {e['p95']} | {e['p99']} |") + out.append("") + + # 归因分析 + out.append("## 4. 归因分析\n") + out.append("- **GIL 瓶颈**:Python worker 单进程内所有用户协程共享一个 GIL," + "requests 库虽然 I/O 多,但 JSON 编解码、locust 统计、gevent 调度都是" + "纯 CPU 段;并发越高,GIL 争抢越明显,单核打满后 TPS 触顶。") + out.append("- **Go 怎么绕开**:goroutine 由 Go runtime 多线程调度(GOMAXPROCS=核数)," + "网络 I/O 走 netpoller,无全局锁;连接池调优后" + "(MaxIdleConnsPerHost=1000,且有断言测试保证配置真的生效)," + "单机轻松压出数倍 TPS。") + out.append("- **瓶颈定位**:本机压测会撞到多层瓶颈(mock 网关的 Python HTTP 层、" + "loopback、worker 自身)。若两种 worker 的 P99 都高,瓶颈在被测服务侧;" + "若 Go 的 TPS 显著高于 Python 且 P99 更低,瓶颈在 worker 侧(GIL)。" + "本报告数字即按此判读。") + if ratio is not None: + verdict = ("瓶颈在 **Python worker 侧(GIL)**" if ratio > 1.3 + else "本轮瓶颈大概率在**被测 mock 服务侧**(两种 worker 都压不满它)" + if ratio <= 1.3 else "不确定") + out.append(f"- **本轮判读**:TPS 比 {ratio:.2f} → {verdict}。") + out.append("") + + # 实验分节(失真实验 / 扩展实验),数据缺省时自动跳过 + if trigger_runs: + _section_trigger(out, trigger_runs) + if scale_runs: + _section_scale(out, scale_runs) + print("\n".join(out)) + + +if __name__ == "__main__": + if len(sys.argv) < 2: + sys.exit("usage: compare.py results/*.json") + main(sys.argv[1:]) diff --git a/go/._client.go b/go/._client.go new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K= 1000(调优未生效)", + tr.MaxIdleConnsPerHost) + } + if tr.MaxConnsPerHost < 1000 { + t.Fatalf("MaxConnsPerHost = %d,期望 >= 1000", tr.MaxConnsPerHost) + } + if tr.MaxIdleConns < 1000 { + t.Fatalf("MaxIdleConns = %d,期望 >= 1000", tr.MaxIdleConns) + } +} diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..0c67524 --- /dev/null +++ b/go/go.mod @@ -0,0 +1,26 @@ +module perf-harness-demo/go + +go 1.25.0 + +require github.com/myzhan/boomer v1.6.0 + +require ( + github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef // indirect + github.com/clipperhouse/uax29/v2 v2.6.0 // indirect + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-runewidth v0.0.19 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/shirou/gopsutil v3.21.11+incompatible // indirect + github.com/stretchr/testify v1.12.1 // indirect + github.com/tklauser/go-sysconf v0.4.0 // indirect + github.com/tklauser/numcpus v0.12.0 // indirect + github.com/ugorji/go/codec v1.3.2 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect + github.com/zeromq/goczmq v4.1.0+incompatible // indirect + github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e // indirect + github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e // indirect + golang.org/x/sys v0.44.0 // indirect +) + +replace github.com/myzhan/boomer => ./third_party/boomer diff --git a/go/go.sum b/go/go.sum new file mode 100644 index 0000000..8285755 --- /dev/null +++ b/go/go.sum @@ -0,0 +1,38 @@ +github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef h1:2JGTg6JapxP9/R33ZaagQtAM4EkkSYnIAlOG5EI8gkM= +github.com/asaskevich/EventBus v0.0.0-20200907212545-49d423059eef/go.mod h1:JS7hed4L1fj0hXcyEejnW57/7LCetXggd+vwrRnYeII= +github.com/clipperhouse/uax29/v2 v2.6.0 h1:z0cDbUV+aPASdFb2/ndFnS9ts/WNXgTNNGFoKXuhpos= +github.com/clipperhouse/uax29/v2 v2.6.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= +github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= +github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= +github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= +github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= +github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= +github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= +github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc= +github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +github.com/zeromq/goczmq v4.1.0+incompatible h1:cGVQaU6kIwwrGso0Pgbl84tzAz/h7FJ3wYQjSonjFFc= +github.com/zeromq/goczmq v4.1.0+incompatible/go.mod h1:1uZybAJoSRCvZMH2rZxEwWBSmC4T7CB/xQOfChwPEzg= +github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e h1:vGjfCnWv/zWeO1ivv4+OUPgTzG/WV1iGfZwVdtUpLkM= +github.com/zeromq/gomq v0.0.0-20201031135124-cef4e507bb8e/go.mod h1:SkCxcSQ7BQEA9FvDzbj+3hV6EMhSywyxWnHwUXVIyLY= +github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e h1:pjp04/sSr2TYuaPdt+u6Cc1M38Aocp+3er0akr3auFg= +github.com/zeromq/gomq/zmtp v0.0.0-20201031135124-cef4e507bb8e/go.mod h1:LBjWEodY/ESvKRwLw3bc7mhn49oiI8qlXUqeqLn0pcU= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ= +golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= diff --git a/go/main.go b/go/main.go new file mode 100644 index 0000000..43c9cc1 --- /dev/null +++ b/go/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "flag" + "log" + + "github.com/myzhan/boomer" +) + +func main() { + // 注意:boomer 在 init 里已注册 --master-host/--master-port 等 flag, + // 这里只新增自己的 flag,绝不能重复定义(会 panic)。 + target := flag.String("target", "http://127.0.0.1:18099", "被测 mock 地址(只打本机)") + flag.Parse() + + client := NewAPIClient(*target) + + tasks := buildBoomerTasks(client) + log.Printf("[go-worker] target=%s, tasks=%d", *target, len(tasks)) + + boomer.Events.Subscribe("boomer:spawn", func(workers int, spawnRate float64) { + log.Printf("[go-worker] master asks to spawn %d workers (rate %.0f)", workers, spawnRate) + }) + + boomer.Run(tasks...) +} diff --git a/go/tasks.go b/go/tasks.go new file mode 100644 index 0000000..4bc18b3 --- /dev/null +++ b/go/tasks.go @@ -0,0 +1,104 @@ +package main + +import ( + "sync/atomic" + "time" + + "github.com/myzhan/boomer" +) + +// OrderPayload 与 python/locustfile.py 的请求体**完全一致**(公平对比前提)。 +type OrderPayload struct { + UserID int `json:"user_id"` + ContractID int `json:"contract_id"` + Side string `json:"side"` + MarginType int `json:"margin_type"` + Quantity string `json:"quantity"` + Price string `json:"price,omitempty"` +} + +const userPoolSize = 1000 + +var ( + rngMu atomic.Int64 // 简单计数即可,payload 随机性不影响正确性 + openOrder atomic.Int64 // 记录一个最近开仓的 order_id 供撤单用 +) + +func randIntn(n int) int { + // 压测下用原子计数打散即可,不追求密码学随机 + return int(rngMu.Add(1) * 2654435761 % (int64(n) * 9973) % int64(n)) +} + +func payload(withPrice bool) OrderPayload { + p := OrderPayload{ + UserID: randIntn(userPoolSize) + 1, // 真随机用户池:避免全员压同一用户导致分布失真 + ContractID: randIntn(3) + 1, + MarginType: randIntn(2) + 1, + Quantity: "10", + } + if randIntn(2) == 0 { + p.Side = "ask" + } else { + p.Side = "bid" + } + if withPrice { + p.Price = "30000.5" + } + return p +} + +// TaskDef 配置驱动的任务注册。若把任务硬写死在 boomer.Run(t1, t2) 里, +// 新增任务极易漏注册,且不会有任何报错提示。增删任务只改这张表。 +type TaskDef struct { + Name string + Weight int + Fn func(c *APIClient) (method, name string, httpStatus, bizCode int, err error) +} + +func taskTable() []TaskDef { + return []TaskDef{ + {"limit_open", 4, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.OpenOrder("/api/v1/order/limit/open", payload(true)) + return "POST", "/api/v1/order/limit/open", s, b, err + }}, + {"market_quantity_open", 2, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.OpenOrder("/api/v1/order/market/quantity/open", payload(false)) + return "POST", "/api/v1/order/market/quantity/open", s, b, err + }}, + {"market_amount_open", 2, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.OpenOrder("/api/v1/order/market/amount/open", payload(false)) + return "POST", "/api/v1/order/market/amount/open", s, b, err + }}, + {"batch_cancel", 1, func(c *APIClient) (string, string, int, int, error) { + s, b, err := c.BatchCancel(randIntn(userPoolSize)+1, + []int64{openOrder.Load()}) + return "DELETE", "/api/v1/order/batch/cancel", s, b, err + }}, + } +} + +// buildBoomerTasks 把任务表转成 boomer.Task 列表。 +func buildBoomerTasks(c *APIClient) []*boomer.Task { + var tasks []*boomer.Task + for _, d := range taskTable() { + def := d + tasks = append(tasks, &boomer.Task{ + Name: def.Name, + Weight: def.Weight, + Fn: func() { + start := time.Now() + method, name, httpStatus, bizCode, err := def.Fn(c) + elapsed := time.Since(start).Milliseconds() + switch { + case err != nil: + boomer.RecordFailure(method, name, elapsed, err.Error()) + case httpStatus != 200 || bizCode != 0: + boomer.RecordFailure(method, name, elapsed, "biz error") + default: + boomer.RecordSuccess(method, name, elapsed, 0) + } + }, + }) + } + return tasks +} diff --git a/go/third_party/._boomer b/go/third_party/._boomer new file mode 100755 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K 0 { + log.Println("The max RPS that boomer may generate is limited to", maxRPS, "with a increase rate", requestIncreaseRate) + rateLimiter, err = NewRampUpRateLimiter(maxRPS, requestIncreaseRate, time.Second) + } else { + log.Println("The max RPS that boomer may generate is limited by a increase rate", requestIncreaseRate) + rateLimiter, err = NewRampUpRateLimiter(math.MaxInt64, requestIncreaseRate, time.Second) + } + } else { + if maxRPS > 0 { + log.Println("The max RPS that boomer may generate is limited to", maxRPS) + rateLimiter = NewStableRateLimiter(maxRPS, time.Second) + } + } + return rateLimiter, err +} + +// According to locust, responseTime should be int64, in milliseconds. +// But previous version of boomer required responseTime to be float64, so sad. +func convertResponseTime(origin interface{}) int64 { + responseTime := int64(0) + if _, ok := origin.(float64); ok { + responseTime = int64(origin.(float64)) + } else if _, ok := origin.(int64); ok { + responseTime = origin.(int64) + } else { + panic(fmt.Sprintf("responseTime should be float64 or int64, not %s", reflect.TypeOf(origin))) + } + return responseTime +} + +func legacySuccessHandler(requestType string, name string, responseTime interface{}, responseLength int64) { + successRetiredWarning.Do(func() { + log.Println("boomer.Events.Publish(\"request_success\") is less performant and deprecated, use boomer.RecordSuccess() instead.") + }) + defaultBoomer.RecordSuccess(requestType, name, convertResponseTime(responseTime), responseLength) +} + +func legacyFailureHandler(requestType string, name string, responseTime interface{}, exception string) { + failureRetiredWarning.Do(func() { + log.Println("boomer.Events.Publish(\"request_failure\") is less performant and deprecated, use boomer.RecordFailure() instead.") + }) + defaultBoomer.RecordFailure(requestType, name, convertResponseTime(responseTime), exception) +} + +func initLegacyEventHandlers() { + Events.Subscribe("request_success", legacySuccessHandler) + Events.Subscribe("request_failure", legacyFailureHandler) +} + +func init() { + flag.Int64Var(&maxRPS, "max-rps", 0, "Max RPS that boomer can generate, disabled by default.") + flag.StringVar(&requestIncreaseRate, "request-increase-rate", "-1", "Request increase rate, disabled by default.") + flag.StringVar(&runTasks, "run-tasks", "", "Run tasks without connecting to the master, multiply tasks is separated by comma. Usually, it's for debug purpose.") + flag.StringVar(&masterHost, "master-host", "127.0.0.1", "Host or IP address of locust master for distributed load testing.") + flag.IntVar(&masterPort, "master-port", 5557, "The port to connect to that is used by the locust master for distributed load testing.") + flag.StringVar(&memoryProfile, "mem-profile", "", "Enable memory profiling.") + flag.DurationVar(&memoryProfileDuration, "mem-profile-duration", 30*time.Second, "Memory profile duration.") + flag.StringVar(&cpuProfile, "cpu-profile", "", "Enable CPU profiling.") + flag.DurationVar(&cpuProfileDuration, "cpu-profile-duration", 30*time.Second, "CPU profile duration.") +} diff --git a/go/third_party/boomer/message.go b/go/third_party/boomer/message.go new file mode 100644 index 0000000..7962c05 --- /dev/null +++ b/go/third_party/boomer/message.go @@ -0,0 +1,38 @@ +package boomer + +import ( + "github.com/ugorji/go/codec" +) + +var ( + mh codec.MsgpackHandle +) + +type message struct { + Type string `codec:"type"` + Data interface{} `codec:"data"` + NodeID string `codec:"node_id"` +} + +func newMessage(t string, data interface{}, nodeID string) (msg *message) { + return &message{ + Type: t, + Data: data, + NodeID: nodeID, + } +} + +func (m *message) serialize() (out []byte, err error) { + mh.StructToArray = true + enc := codec.NewEncoderBytes(&out, &mh) + err = enc.Encode(m) + return out, err +} + +func newMessageFromBytes(raw []byte) (newMsg *message, err error) { + mh.StructToArray = true + dec := codec.NewDecoderBytes(raw, &mh) + newMsg = &message{} + err = dec.Decode(newMsg) + return newMsg, err +} diff --git a/go/third_party/boomer/output.go b/go/third_party/boomer/output.go new file mode 100644 index 0000000..e4e20f0 --- /dev/null +++ b/go/third_party/boomer/output.go @@ -0,0 +1,146 @@ +package boomer + +import ( + "fmt" + "os" + "sort" + "strconv" + "time" + + "github.com/olekukonko/tablewriter" +) + +// Output is primarily responsible for printing test results to different destinations +// such as consoles, files. You can write you own output and add to boomer. +// When running in standalone mode, the default output is ConsoleOutput, you can add more. +// When running in distribute mode, test results will be reported to master with or without +// an output. +// All the OnXXX function will be call in a separated goroutine, just in case some output will block. +// But it will wait for all outputs return to avoid data lost. +type Output interface { + // OnStart will be call before the test starts. + OnStart() + + // By default, each output receive stats data from runner every three seconds. + // OnEvent is responsible for dealing with the data. + OnEvent(data map[string]interface{}) + + // OnStop will be called before the test ends. + OnStop() +} + +// ConsoleOutput is the default output for standalone mode. +type ConsoleOutput struct { +} + +// NewConsoleOutput returns a ConsoleOutput. +func NewConsoleOutput() *ConsoleOutput { + return &ConsoleOutput{} +} + +func getMedianResponseTime(numRequests int64, responseTimes map[int64]int64) int64 { + medianResponseTime := int64(0) + if len(responseTimes) != 0 { + pos := (numRequests - 1) / 2 + var sortedKeys []int64 + for k := range responseTimes { + sortedKeys = append(sortedKeys, k) + } + sort.Slice(sortedKeys, func(i, j int) bool { + return sortedKeys[i] < sortedKeys[j] + }) + for _, k := range sortedKeys { + if pos < responseTimes[k] { + medianResponseTime = k + break + } + pos -= responseTimes[k] + } + } + return medianResponseTime +} + +func getAvgResponseTime(numRequests int64, totalResponseTime int64) (avgResponseTime float64) { + avgResponseTime = float64(0) + if numRequests != 0 { + avgResponseTime = float64(totalResponseTime) / float64(numRequests) + } + return avgResponseTime +} + +func getAvgContentLength(numRequests int64, totalContentLength int64) (avgContentLength int64) { + avgContentLength = int64(0) + if numRequests != 0 { + avgContentLength = totalContentLength / numRequests + } + return avgContentLength +} + +func getCurrentRps(numRequests int64, numReqsPerSecond map[int64]int64) (currentRps int64) { + currentRps = int64(0) + numReqsPerSecondLength := int64(len(numReqsPerSecond)) + if numReqsPerSecondLength != 0 { + currentRps = numRequests / numReqsPerSecondLength + } + return currentRps +} + +// OnStart of ConsoleOutput has nothing to do. +func (o *ConsoleOutput) OnStart() { + +} + +// OnStop of ConsoleOutput has nothing to do. +func (o *ConsoleOutput) OnStop() { + +} + +// OnEvent will print to the console. +func (o *ConsoleOutput) OnEvent(data map[string]interface{}) { + stats, ok := data["stats"].([]interface{}) + if !ok { + return + } + + currentTime := time.Now() + println(fmt.Sprintf("Current time: %s", currentTime.Format("2006/01/02 15:04:05"))) + table := tablewriter.NewWriter(os.Stdout) + table.SetHeader([]string{"Type", "Name", "# requests", "# fails", "Median", "Average", "Min", "Max", "Content Size", "# reqs/sec"}) + + for _, stat := range stats { + s := stat.(map[string]interface{}) + row := make([]string, 10) + row[0], row[1] = s["name"].(string), s["method"].(string) + + numRequests := s["num_requests"].(int64) + row[2] = strconv.FormatInt(numRequests, 10) + + numFailures := s["num_failures"].(int64) + row[3] = strconv.FormatInt(numFailures, 10) + + medianResponseTime := getMedianResponseTime(numRequests, s["response_times"].(map[int64]int64)) + row[4] = strconv.FormatInt(medianResponseTime, 10) + + totalResponseTime := s["total_response_time"].(int64) + avgResponseTime := getAvgResponseTime(numRequests, totalResponseTime) + row[5] = strconv.FormatFloat(avgResponseTime, 'f', 2, 64) + + minResponseTime := s["min_response_time"].(int64) + row[6] = strconv.FormatInt(minResponseTime, 10) + + maxResponseTime := s["max_response_time"].(int64) + row[7] = strconv.FormatInt(maxResponseTime, 10) + + totalContentLength := s["total_content_length"].(int64) + avgContentLength := getAvgContentLength(numRequests, totalContentLength) + row[8] = strconv.FormatInt(avgContentLength, 10) + + numReqsPerSecond := s["num_reqs_per_sec"].(map[int64]int64) + currentRps := getCurrentRps(numRequests, numReqsPerSecond) + row[9] = strconv.FormatInt(currentRps, 10) + + table.Append(row) + } + table.Render() + println() +} diff --git a/go/third_party/boomer/ratelimiter.go b/go/third_party/boomer/ratelimiter.go new file mode 100644 index 0000000..5cf98b9 --- /dev/null +++ b/go/third_party/boomer/ratelimiter.go @@ -0,0 +1,213 @@ +package boomer + +import ( + "errors" + "math" + "strconv" + "strings" + "sync/atomic" + "time" +) + +// RateLimiter is used to put limits on task executions. +type RateLimiter interface { + // Start is used to enable the rate limiter. + // It can be implemented as a noop if not needed. + Start() + + // Acquire() is called before executing a task.Fn function. + // If Acquire() returns true, the task.Fn function will be executed. + // If Acquire() returns false, the task.Fn function won't be executed this time, but Acquire() will be called very soon. + // It works like: + // for { + // blocked := rateLimiter.Acquire() + // if !blocked { + // task.Fn() + // } + // } + // Acquire() should block the caller until execution is allowed. + Acquire() bool + + // Stop is used to disable the rate limiter. + // It can be implemented as a noop if not needed. + Stop() +} + +// A StableRateLimiter uses the token bucket algorithm. +// the bucket is refilled according to the refill period, no burst is allowed. +type StableRateLimiter struct { + threshold int64 + currentThreshold int64 + refillPeriod time.Duration + broadcastChannel chan bool + quitChannel chan bool +} + +// NewStableRateLimiter returns a StableRateLimiter. +func NewStableRateLimiter(threshold int64, refillPeriod time.Duration) (rateLimiter *StableRateLimiter) { + rateLimiter = &StableRateLimiter{ + threshold: threshold, + currentThreshold: threshold, + refillPeriod: refillPeriod, + broadcastChannel: make(chan bool), + } + return rateLimiter +} + +// Start to refill the bucket periodically. +func (limiter *StableRateLimiter) Start() { + limiter.quitChannel = make(chan bool) + quitChannel := limiter.quitChannel + go func() { + for { + select { + case <-quitChannel: + return + default: + atomic.StoreInt64(&limiter.currentThreshold, limiter.threshold) + time.Sleep(limiter.refillPeriod) + close(limiter.broadcastChannel) + limiter.broadcastChannel = make(chan bool) + } + } + }() +} + +// Acquire a token from the bucket, returns true if the bucket is exhausted. +func (limiter *StableRateLimiter) Acquire() (blocked bool) { + permit := atomic.AddInt64(&limiter.currentThreshold, -1) + if permit < 0 { + blocked = true + // block until the bucket is refilled + <-limiter.broadcastChannel + } else { + blocked = false + } + return blocked +} + +// Stop the rate limiter. +func (limiter *StableRateLimiter) Stop() { + close(limiter.quitChannel) +} + +// ErrParsingRampUpRate is the error returned if the format of rampUpRate is invalid. +var ErrParsingRampUpRate = errors.New("ratelimiter: invalid format of rampUpRate, try \"1\" or \"1/1s\"") + +// A RampUpRateLimiter uses the token bucket algorithm. +// the threshold is updated according to the warm up rate. +// the bucket is refilled according to the refill period, no burst is allowed. +type RampUpRateLimiter struct { + maxThreshold int64 + nextThreshold int64 + currentThreshold int64 + refillPeriod time.Duration + rampUpRate string + rampUpStep int64 + rampUpPeroid time.Duration + broadcastChannel chan bool + rampUpChannel chan bool + quitChannel chan bool +} + +// NewRampUpRateLimiter returns a RampUpRateLimiter. +// Valid formats of rampUpRate are "1", "1/1s". +func NewRampUpRateLimiter(maxThreshold int64, rampUpRate string, refillPeriod time.Duration) (rateLimiter *RampUpRateLimiter, err error) { + rateLimiter = &RampUpRateLimiter{ + maxThreshold: maxThreshold, + nextThreshold: 0, + currentThreshold: 0, + rampUpRate: rampUpRate, + refillPeriod: refillPeriod, + broadcastChannel: make(chan bool), + } + rateLimiter.rampUpStep, rateLimiter.rampUpPeroid, err = rateLimiter.parseRampUpRate(rateLimiter.rampUpRate) + if err != nil { + return nil, err + } + return rateLimiter, nil +} + +func (limiter *RampUpRateLimiter) parseRampUpRate(rampUpRate string) (rampUpStep int64, rampUpPeroid time.Duration, err error) { + if strings.Contains(rampUpRate, "/") { + tmp := strings.Split(rampUpRate, "/") + if len(tmp) != 2 { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + rampUpStep, err := strconv.ParseInt(tmp[0], 10, 64) + if err != nil { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + rampUpPeroid, err := time.ParseDuration(tmp[1]) + if err != nil { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + return rampUpStep, rampUpPeroid, nil + } + + rampUpStep, err = strconv.ParseInt(rampUpRate, 10, 64) + if err != nil { + return rampUpStep, rampUpPeroid, ErrParsingRampUpRate + } + rampUpPeroid = time.Second + return rampUpStep, rampUpPeroid, nil +} + +// Start to refill the bucket periodically. +func (limiter *RampUpRateLimiter) Start() { + limiter.quitChannel = make(chan bool) + quitChannel := limiter.quitChannel + // bucket updater + go func() { + for { + select { + case <-quitChannel: + return + default: + atomic.StoreInt64(&limiter.currentThreshold, limiter.nextThreshold) + time.Sleep(limiter.refillPeriod) + close(limiter.broadcastChannel) + limiter.broadcastChannel = make(chan bool) + } + } + }() + // threshold updater + go func() { + for { + select { + case <-quitChannel: + return + default: + nextValue := limiter.nextThreshold + limiter.rampUpStep + if nextValue < 0 { + // int64 overflow + nextValue = int64(math.MaxInt64) + } + if nextValue > limiter.maxThreshold { + nextValue = limiter.maxThreshold + } + atomic.StoreInt64(&limiter.nextThreshold, nextValue) + time.Sleep(limiter.rampUpPeroid) + } + } + }() +} + +// Acquire a token from the bucket, returns true if the bucket is exhausted. +func (limiter *RampUpRateLimiter) Acquire() (blocked bool) { + permit := atomic.AddInt64(&limiter.currentThreshold, -1) + if permit < 0 { + blocked = true + // block until the bucket is refilled + <-limiter.broadcastChannel + } else { + blocked = false + } + return blocked +} + +// Stop the rate limiter. +func (limiter *RampUpRateLimiter) Stop() { + limiter.nextThreshold = 0 + close(limiter.quitChannel) +} diff --git a/go/third_party/boomer/runner.go b/go/third_party/boomer/runner.go new file mode 100644 index 0000000..cc2d31e --- /dev/null +++ b/go/third_party/boomer/runner.go @@ -0,0 +1,555 @@ +package boomer + +import ( + "fmt" + "log" + "math/rand" + "os" + "runtime/debug" + "strings" + "sync" + "sync/atomic" + "time" +) + +const ( + stateInit = "ready" + stateSpawning = "spawning" + stateRunning = "running" + stateStopped = "stopped" + stateQuitting = "quitting" +) + +const ( + slaveReportInterval = 3 * time.Second + heartbeatInterval = 1 * time.Second +) + +type runner struct { + state string + + tasks []*Task + totalTaskWeight int + + rateLimiter RateLimiter + rateLimitEnabled bool + stats *requestStats + + numClients int32 + spawnRate float64 + + // all running workers(goroutines) will select on this channel. + // close this channel will stop all running workers. + stopChan chan bool + + // close this channel will stop all goroutines used in runner. + closeChan chan bool + + outputs []Output +} + +// safeRun runs fn and recovers from unexpected panics. +// it prevents panics from Task.Fn crashing boomer. +func (r *runner) safeRun(fn func()) { + defer func() { + // don't panic + err := recover() + if err != nil { + stackTrace := debug.Stack() + errMsg := fmt.Sprintf("%v", err) + os.Stderr.Write([]byte(errMsg)) + os.Stderr.Write([]byte("\n")) + os.Stderr.Write(stackTrace) + } + }() + fn() +} + +func (r *runner) addOutput(o Output) { + r.outputs = append(r.outputs, o) +} + +func (r *runner) outputOnStart() { + size := len(r.outputs) + if size == 0 { + return + } + wg := sync.WaitGroup{} + wg.Add(size) + for _, output := range r.outputs { + go func(o Output) { + o.OnStart() + wg.Done() + }(output) + } + wg.Wait() +} + +func (r *runner) outputOnEevent(data map[string]interface{}) { + size := len(r.outputs) + if size == 0 { + return + } + wg := sync.WaitGroup{} + wg.Add(size) + for _, output := range r.outputs { + go func(o Output) { + o.OnEvent(data) + wg.Done() + }(output) + } + wg.Wait() +} + +func (r *runner) outputOnStop() { + size := len(r.outputs) + if size == 0 { + return + } + wg := sync.WaitGroup{} + wg.Add(size) + for _, output := range r.outputs { + go func(o Output) { + o.OnStop() + wg.Done() + }(output) + } + wg.Wait() +} + +func (r *runner) spawnWorkers(spawnCount int, quit chan bool, spawnCompleteFunc func()) { + log.Println("Spawning", spawnCount, "clients at the rate", r.spawnRate, "clients/s...") + + for i := 1; i <= spawnCount; i++ { + sleepTime := time.Duration(1000000/r.spawnRate) * time.Microsecond + time.Sleep(sleepTime) + + select { + case <-quit: + // quit spawning goroutine + return + default: + atomic.AddInt32(&r.numClients, 1) + go func() { + for { + select { + case <-quit: + return + default: + if r.rateLimitEnabled { + blocked := r.rateLimiter.Acquire() + if !blocked { + task := r.getTask() + r.safeRun(task.Fn) + } + } else { + task := r.getTask() + r.safeRun(task.Fn) + } + } + } + }() + } + } + + if spawnCompleteFunc != nil { + spawnCompleteFunc() + } +} + +// setTasks will set the runner's task list AND the total task weight +// which is used to get a random task later +func (r *runner) setTasks(t []*Task) { + r.tasks = t + + weightSum := 0 + for _, task := range r.tasks { + weightSum += task.Weight + } + r.totalTaskWeight = weightSum +} + +func (r *runner) getTask() *Task { + tasksCount := len(r.tasks) + if tasksCount == 1 { + // Fast path + return r.tasks[0] + } + + rs := rand.New(rand.NewSource(time.Now().UnixNano())) + + totalWeight := r.totalTaskWeight + if totalWeight <= 0 { + // If all the tasks have not weights defined, they have the same chance to run + randNum := rs.Intn(tasksCount) + return r.tasks[randNum] + } + + randNum := rs.Intn(totalWeight) + runningSum := 0 + for _, task := range r.tasks { + runningSum += task.Weight + if runningSum > randNum { + return task + } + } + + return nil +} + +func (r *runner) startSpawning(spawnCount int, spawnRate float64, spawnCompleteFunc func()) { + Events.Publish("boomer:hatch", spawnCount, spawnRate) + Events.Publish("boomer:spawn", spawnCount, spawnRate) + + r.stats.clearStatsChan <- true + r.stopChan = make(chan bool) + + r.spawnRate = spawnRate + r.numClients = 0 + + go r.spawnWorkers(spawnCount, r.stopChan, spawnCompleteFunc) +} + +func (r *runner) stop() { + // publish the boomer stop event + // user's code can subscribe to this event and do thins like cleaning up + Events.Publish("boomer:stop") + + // stop previous goroutines without blocking + // those goroutines will exit when r.safeRun returns + close(r.stopChan) + if r.rateLimitEnabled { + r.rateLimiter.Stop() + } +} + +type localRunner struct { + runner + + spawnCount int +} + +func newLocalRunner(tasks []*Task, rateLimiter RateLimiter, spawnCount int, spawnRate float64) (r *localRunner) { + r = &localRunner{} + r.setTasks(tasks) + r.spawnRate = spawnRate + r.spawnCount = spawnCount + r.closeChan = make(chan bool) + r.addOutput(NewConsoleOutput()) + + if rateLimiter != nil { + r.rateLimitEnabled = true + r.rateLimiter = rateLimiter + } + + r.stats = newRequestStats() + return r +} + +func (r *localRunner) run() { + r.state = stateInit + r.stats.start() + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for { + select { + case data := <-r.stats.messageToRunnerChan: + data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)} + r.outputOnEevent(data) + case <-r.closeChan: + Events.Publish("boomer:quit") + r.stop() + wg.Done() + return + } + } + }() + + if r.rateLimitEnabled { + r.rateLimiter.Start() + } + r.startSpawning(r.spawnCount, r.spawnRate, nil) + + wg.Wait() +} + +func (r *localRunner) close() { + if r.stats != nil { + r.stats.close() + } + close(r.closeChan) +} + +// SlaveRunner connects to the master, spawns goroutines and collects stats. +type slaveRunner struct { + runner + + nodeID string + masterHost string + masterPort int + client client +} + +func newSlaveRunner(masterHost string, masterPort int, tasks []*Task, rateLimiter RateLimiter) (r *slaveRunner) { + r = &slaveRunner{} + r.masterHost = masterHost + r.masterPort = masterPort + r.setTasks(tasks) + r.nodeID = getNodeID() + r.closeChan = make(chan bool) + + if rateLimiter != nil { + r.rateLimitEnabled = true + r.rateLimiter = rateLimiter + } + + r.stats = newRequestStats() + return r +} + +func (r *slaveRunner) spawnComplete() { + data := make(map[string]interface{}) + data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)} + r.client.sendChannel() <- newMessage("spawning_complete", data, r.nodeID) + r.state = stateRunning +} + +func (r *slaveRunner) onQuiting() { + if r.state != stateQuitting { + r.client.sendChannel() <- newMessage("quit", nil, r.nodeID) + } +} + +func (r *slaveRunner) close() { + if r.stats != nil { + r.stats.close() + } + if r.client != nil { + r.client.close() + } + close(r.closeChan) +} + +func (r *slaveRunner) onSpawnMessage(msg *message) { + r.client.sendChannel() <- newMessage("spawning", nil, r.nodeID) + // locust >= 2.0: user_classes_count is a map[class]count; spawn_rate lives + // in parsed_options. Fall back to legacy num_users/spawn_rate fields. + var spawnRate float64 + workers := 0 + data := msgDataMap(msg) + if ucc, ok := data["user_classes_count"]; ok { + switch m := ucc.(type) { + case map[string]interface{}: + for _, v := range m { + workers += int(toInt64(v)) + } + case map[interface{}]interface{}: + for _, v := range m { + workers += int(toInt64(v)) + } + } + if po, ok := data["parsed_options"]; ok { + switch pm := po.(type) { + case map[string]interface{}: + if sr, ok := pm["spawn_rate"]; ok { + spawnRate = toFloat64(sr) + } + case map[interface{}]interface{}: + if sr, ok := pm["spawn_rate"]; ok { + spawnRate = toFloat64(sr) + } + } + } + } else { + rate := data["spawn_rate"] + users := data["num_users"] + spawnRate = rate.(float64) + if _, ok := users.(uint64); ok { + workers = int(users.(uint64)) + } else { + workers = int(users.(int64)) + } + } + if spawnRate <= 0 { + spawnRate = float64(workers) + } + + if r.rateLimitEnabled { + r.rateLimiter.Start() + } + r.startSpawning(workers, spawnRate, r.spawnComplete) +} + + +func msgDataMap(msg *message) map[string]interface{} { + switch m := msg.Data.(type) { + case map[string]interface{}: + return m + case map[interface{}]interface{}: + out := make(map[string]interface{}, len(m)) + for k, v := range m { + if ks, ok := k.(string); ok { + out[ks] = v + } + } + return out + } + return nil +} + +func toInt64(v interface{}) int64 { + switch n := v.(type) { + case int64: + return n + case uint64: + return int64(n) + case int: + return int64(n) + case int32: + return int64(n) + case uint32: + return int64(n) + case float64: + return int64(n) + } + return 0 +} + +func toFloat64(v interface{}) float64 { + switch n := v.(type) { + case float64: + return n + case int64: + return float64(n) + case uint64: + return float64(n) + case int: + return float64(n) + } + return 0 +} + +// Runner acts as a state machine. +func (r *slaveRunner) onMessage(msg *message) { + if msg.Type == "hatch" { + log.Println("The master sent a 'hatch' message, you are using an unsupported locust version, please update locust to 1.2.") + return + } + + switch r.state { + case stateInit: + switch msg.Type { + case "spawn": + r.state = stateSpawning + r.onSpawnMessage(msg) + case "quit": + Events.Publish("boomer:quit") + } + case stateSpawning: + fallthrough + case stateRunning: + switch msg.Type { + case "spawn": + r.state = stateSpawning + r.stop() + r.onSpawnMessage(msg) + case "stop": + r.stop() + r.state = stateStopped + log.Println("Recv stop message from master, all the goroutines are stopped") + r.client.sendChannel() <- newMessage("client_stopped", nil, r.nodeID) + r.client.sendChannel() <- newMessage("client_ready", -1, r.nodeID) + r.state = stateInit + case "quit": + r.stop() + log.Println("Recv quit message from master, all the goroutines are stopped") + Events.Publish("boomer:quit") + r.state = stateInit + } + case stateStopped: + switch msg.Type { + case "spawn": + r.state = stateSpawning + r.onSpawnMessage(msg) + case "quit": + Events.Publish("boomer:quit") + r.state = stateInit + } + } +} + +func (r *slaveRunner) startListener() { + go func() { + for { + select { + case msg := <-r.client.recvChannel(): + r.onMessage(msg) + case <-r.closeChan: + return + } + } + }() +} + +func (r *slaveRunner) run() { + r.state = stateInit + r.client = newClient(r.masterHost, r.masterPort, r.nodeID) + + err := r.client.connect() + if err != nil { + if strings.Contains(err.Error(), "Socket type DEALER is not compatible with PULL") { + log.Println("Newer version of locust changes ZMQ socket to DEALER and ROUTER, you should update your locust version.") + } else { + log.Printf("Failed to connect to master(%s:%d) with error %v\n", r.masterHost, r.masterPort, err) + } + return + } + + // listen to master + r.startListener() + + r.stats.start() + + // tell master, I'm ready + r.client.sendChannel() <- newMessage("client_ready", -1, r.nodeID) + + // report to master + go func() { + for { + select { + case data := <-r.stats.messageToRunnerChan: + if r.state == stateInit || r.state == stateStopped { + continue + } + data["user_classes_count"] = map[string]int{"BoomerWorker": int(r.numClients)} + r.client.sendChannel() <- newMessage("stats", data, r.nodeID) + r.outputOnEevent(data) + case <-r.closeChan: + return + } + } + }() + + // heartbeat + // See: https://github.com/locustio/locust/commit/a8c0d7d8c588f3980303358298870f2ea394ab93 + go func() { + var ticker = time.NewTicker(heartbeatInterval) + for { + select { + case <-ticker.C: + CPUUsage := GetCurrentCPUUsage() + data := map[string]interface{}{ + "state": r.state, + "current_cpu_usage": CPUUsage, + } + r.client.sendChannel() <- newMessage("heartbeat", data, r.nodeID) + case <-r.closeChan: + return + } + } + }() + + Events.Subscribe("boomer:quit", r.onQuiting) +} diff --git a/go/third_party/boomer/stats.go b/go/third_party/boomer/stats.go new file mode 100644 index 0000000..be5b63a --- /dev/null +++ b/go/third_party/boomer/stats.go @@ -0,0 +1,309 @@ +package boomer + +import ( + "time" +) + +type requestSuccess struct { + requestType string + name string + responseTime int64 + responseLength int64 +} + +type requestFailure struct { + requestType string + name string + responseTime int64 + error string +} + +type requestStats struct { + entries map[string]*statsEntry + errors map[string]*statsError + total *statsEntry + startTime int64 + + requestSuccessChan chan *requestSuccess + requestFailureChan chan *requestFailure + clearStatsChan chan bool + messageToRunnerChan chan map[string]interface{} + shutdownChan chan bool +} + +func newRequestStats() (stats *requestStats) { + entries := make(map[string]*statsEntry) + errors := make(map[string]*statsError) + + stats = &requestStats{ + entries: entries, + errors: errors, + } + stats.requestSuccessChan = make(chan *requestSuccess, 100) + stats.requestFailureChan = make(chan *requestFailure, 100) + stats.clearStatsChan = make(chan bool) + stats.messageToRunnerChan = make(chan map[string]interface{}, 10) + stats.shutdownChan = make(chan bool) + + stats.total = &statsEntry{ + name: "Total", + method: "", + } + stats.total.reset() + + return stats +} + +func (s *requestStats) logRequest(method, name string, responseTime int64, contentLength int64) { + s.total.log(responseTime, contentLength) + s.get(name, method).log(responseTime, contentLength) +} + +func (s *requestStats) logError(method, name, err string) { + s.total.logError(err) + s.get(name, method).logError(err) + + // store error in errors map + key := MD5(method, name, err) + entry, ok := s.errors[key] + if !ok { + entry = &statsError{ + name: name, + method: method, + error: err, + } + s.errors[key] = entry + } + entry.occured() +} + +func (s *requestStats) get(name string, method string) (entry *statsEntry) { + entry, ok := s.entries[name+method] + if !ok { + newEntry := &statsEntry{ + name: name, + method: method, + numReqsPerSec: make(map[int64]int64), + responseTimes: make(map[int64]int64), + } + newEntry.reset() + s.entries[name+method] = newEntry + return newEntry + } + return entry +} + +func (s *requestStats) clearAll() { + s.total = &statsEntry{ + name: "Total", + method: "", + } + s.total.reset() + + s.entries = make(map[string]*statsEntry) + s.errors = make(map[string]*statsError) + s.startTime = time.Now().Unix() +} + +func (s *requestStats) serializeStats() []interface{} { + entries := make([]interface{}, 0, len(s.entries)) + for _, v := range s.entries { + if !(v.numRequests == 0 && v.numFailures == 0) { + entries = append(entries, v.getStrippedReport()) + } + } + return entries +} + +func (s *requestStats) serializeErrors() map[string]map[string]interface{} { + errors := make(map[string]map[string]interface{}) + for k, v := range s.errors { + errors[k] = v.toMap() + } + return errors +} + +func (s *requestStats) collectReportData() map[string]interface{} { + data := make(map[string]interface{}) + data["stats"] = s.serializeStats() + data["stats_total"] = s.total.getStrippedReport() + data["errors"] = s.serializeErrors() + s.errors = make(map[string]*statsError) + return data +} + +func (s *requestStats) start() { + go func() { + var ticker = time.NewTicker(slaveReportInterval) + for { + select { + case m := <-s.requestSuccessChan: + s.logRequest(m.requestType, m.name, m.responseTime, m.responseLength) + case n := <-s.requestFailureChan: + s.logRequest(n.requestType, n.name, n.responseTime, 0) + s.logError(n.requestType, n.name, n.error) + case <-s.clearStatsChan: + s.clearAll() + case <-ticker.C: + data := s.collectReportData() + // send data to channel, no network IO in this goroutine + s.messageToRunnerChan <- data + case <-s.shutdownChan: + return + } + } + }() +} + +// close is used by unit tests to avoid leakage of goroutines +func (s *requestStats) close() { + close(s.shutdownChan) +} + +type statsEntry struct { + name string + method string + numRequests int64 + numFailures int64 + totalResponseTime int64 + minResponseTime int64 + maxResponseTime int64 + numReqsPerSec map[int64]int64 + numFailPerSec map[int64]int64 + responseTimes map[int64]int64 + totalContentLength int64 + startTime int64 + lastRequestTimestamp int64 +} + +func (s *statsEntry) reset() { + s.startTime = time.Now().Unix() + s.numRequests = 0 + s.numFailures = 0 + s.totalResponseTime = 0 + s.responseTimes = make(map[int64]int64) + s.minResponseTime = 0 + s.maxResponseTime = 0 + s.lastRequestTimestamp = time.Now().Unix() + s.numReqsPerSec = make(map[int64]int64) + s.numFailPerSec = make(map[int64]int64) + s.totalContentLength = 0 +} + +func (s *statsEntry) log(responseTime int64, contentLength int64) { + s.numRequests++ + + s.logTimeOfRequest() + s.logResponseTime(responseTime) + + s.totalContentLength += contentLength +} + +func (s *statsEntry) logTimeOfRequest() { + key := time.Now().Unix() + _, ok := s.numReqsPerSec[key] + if !ok { + s.numReqsPerSec[key] = 1 + } else { + s.numReqsPerSec[key]++ + } + + s.lastRequestTimestamp = key +} + +func (s *statsEntry) logResponseTime(responseTime int64) { + s.totalResponseTime += responseTime + + if s.minResponseTime == 0 { + s.minResponseTime = responseTime + } + + if responseTime < s.minResponseTime { + s.minResponseTime = responseTime + } + + if responseTime > s.maxResponseTime { + s.maxResponseTime = responseTime + } + + var roundedResponseTime int64 + + // to avoid to much data that has to be transferred to the master node when + // running in distributed mode, we save the response time rounded in a dict + // so that 147 becomes 150, 3432 becomes 3400 and 58760 becomes 59000 + // see also locust's stats.py + if responseTime < 100 { + roundedResponseTime = responseTime + } else if responseTime < 1000 { + roundedResponseTime = int64(round(float64(responseTime), .5, -1)) + } else if responseTime < 10000 { + roundedResponseTime = int64(round(float64(responseTime), .5, -2)) + } else { + roundedResponseTime = int64(round(float64(responseTime), .5, -3)) + } + + _, ok := s.responseTimes[roundedResponseTime] + if !ok { + s.responseTimes[roundedResponseTime] = 1 + } else { + s.responseTimes[roundedResponseTime]++ + } +} + +func (s *statsEntry) logError(err string) { + s.numFailures++ + key := time.Now().Unix() + _, ok := s.numFailPerSec[key] + if !ok { + s.numFailPerSec[key] = 1 + } else { + s.numFailPerSec[key]++ + } +} + +func (s *statsEntry) serialize() map[string]interface{} { + result := make(map[string]interface{}) + result["name"] = s.name + result["method"] = s.method + result["last_request_timestamp"] = s.lastRequestTimestamp + result["start_time"] = s.startTime + result["num_requests"] = s.numRequests + // Boomer doesn't allow None response time for requests like locust. + // num_none_requests is added to keep compatible with locust. + result["num_none_requests"] = 0 + result["num_failures"] = s.numFailures + result["total_response_time"] = s.totalResponseTime + result["max_response_time"] = s.maxResponseTime + result["min_response_time"] = s.minResponseTime + result["total_content_length"] = s.totalContentLength + result["response_times"] = s.responseTimes + result["num_reqs_per_sec"] = s.numReqsPerSec + result["num_fail_per_sec"] = s.numFailPerSec + return result +} + +func (s *statsEntry) getStrippedReport() map[string]interface{} { + report := s.serialize() + s.reset() + return report +} + +type statsError struct { + name string + method string + error string + occurrences int64 +} + +func (err *statsError) occured() { + err.occurrences++ +} + +func (err *statsError) toMap() map[string]interface{} { + m := make(map[string]interface{}) + m["method"] = err.method + m["name"] = err.name + m["error"] = err.error + m["occurrences"] = err.occurrences + return m +} diff --git a/go/third_party/boomer/task.go b/go/third_party/boomer/task.go new file mode 100644 index 0000000..e913d09 --- /dev/null +++ b/go/third_party/boomer/task.go @@ -0,0 +1,13 @@ +package boomer + +// Task is like the "Locust object" in locust, the python version. +// When boomer receives a start message from master, it will spawn several goroutines to run Task.Fn. +// But users can keep some information in the python version, they can't do the same things in boomer. +// Because Task.Fn is a pure function. +type Task struct { + // The weight is used to distribute goroutines over multiple tasks. + Weight int + // Fn is called by the goroutines allocated to this task, in a loop. + Fn func() + Name string +} diff --git a/go/third_party/boomer/taskset.go b/go/third_party/boomer/taskset.go new file mode 100644 index 0000000..112332c --- /dev/null +++ b/go/third_party/boomer/taskset.go @@ -0,0 +1,107 @@ +package boomer + +import ( + "math/rand" + "sync" + "time" +) + +// TaskSet is an experimental feature, the API is not stabilized. +// It needs to be more considered and tested. +type TaskSet interface { + // Add a Task to the TaskSet. + AddTask(task *Task) + // Set the weight of the TaskSet. + SetWeight(weight int) + // Get the weight of the TaskSet. + GetWeight() (weight int) + // Run will pick up a Task from the TaskSet and run. + Run() +} + +// WeighingTaskSet is a implementation of the TaskSet interface. +// When a Task is added to WeighingTaskSet, it's weight is used +// to calculate the probability to be called. +type WeighingTaskSet struct { + weight int + offset int + tasks []*Task + index []int + lock sync.RWMutex +} + +// NewWeighingTaskSet returns a new WeighingTaskSet. +func NewWeighingTaskSet() *WeighingTaskSet { + return &WeighingTaskSet{ + weight: 0, + offset: 0, + tasks: make([]*Task, 0), + index: make([]int, 0), + } +} + +// AddTask add a Task to the Weighing TaskSet. +// If the task's weight is <=0, it will be ignored. +func (ts *WeighingTaskSet) AddTask(task *Task) { + if task.Weight <= 0 { + return + } + ts.lock.Lock() + ts.tasks = append(ts.tasks, task) + ts.offset = ts.offset + task.Weight + ts.index = append(ts.index, ts.offset) + ts.lock.Unlock() +} + +func (ts *WeighingTaskSet) binarySearch(roll int) (task *Task) { + left := 0 + right := len(ts.index) - 1 + for left <= right { + mid := (left + right) / 2 + if left == mid { + if roll < ts.index[mid] { + return ts.tasks[mid] + } + return ts.tasks[mid+1] + } + if ts.index[mid-1] <= roll && roll < ts.index[mid] { + return ts.tasks[mid] + } + if roll < ts.index[mid-1] { + right = mid - 1 + } else { + left = mid + 1 + } + } + return nil +} + +// GetTask returns a task in the task set. +func (ts *WeighingTaskSet) GetTask(roll int) (task *Task) { + if roll < 0 || roll >= ts.offset { + return nil + } + ts.lock.RLock() + task = ts.binarySearch(roll) + ts.lock.RUnlock() + return task +} + +// SetWeight sets the weight of the task set. +func (ts *WeighingTaskSet) SetWeight(weight int) { + ts.weight = weight +} + +// GetWeight returns the weight of the task set. +func (ts *WeighingTaskSet) GetWeight() (weight int) { + return ts.weight +} + +// Run will pick up a task in the task set randomly and run. +// It can is used as a Task.Fn. +func (ts *WeighingTaskSet) Run() { + r := rand.New(rand.NewSource(time.Now().UnixNano())) + roll := r.Intn(ts.offset) + task := ts.GetTask(roll) + task.Fn() +} diff --git a/go/third_party/boomer/utils.go b/go/third_party/boomer/utils.go new file mode 100644 index 0000000..69599e8 --- /dev/null +++ b/go/third_party/boomer/utils.go @@ -0,0 +1,110 @@ +package boomer + +import ( + "crypto/md5" + "fmt" + "io" + "log" + "math" + "os" + "runtime" + "runtime/pprof" + "strings" + "time" + + "github.com/google/uuid" + "github.com/shirou/gopsutil/process" +) + +func round(val float64, roundOn float64, places int) (newVal float64) { + var round float64 + pow := math.Pow(10, float64(places)) + digit := pow * val + _, div := math.Modf(digit) + if div >= roundOn { + round = math.Ceil(digit) + } else { + round = math.Floor(digit) + } + newVal = round / pow + return +} + +// MD5 returns the md5 hash of strings. +func MD5(slice ...string) string { + h := md5.New() + for _, v := range slice { + io.WriteString(h, v) + } + return fmt.Sprintf("%x", h.Sum(nil)) +} + +// generate a random nodeID like locust does, using the same algorithm. +func getNodeID() (nodeID string) { + hostname, _ := os.Hostname() + id := strings.Replace(uuid.New().String(), "-", "", -1) + nodeID = fmt.Sprintf("%s_%s", hostname, id) + return +} + +// Now returns the current timestamp in milliseconds. +func Now() int64 { + return time.Now().UnixNano() / int64(time.Millisecond) +} + +// StartMemoryProfile starts memory profiling and save the results in file. +func StartMemoryProfile(file string, duration time.Duration) (err error) { + f, err := os.Create(file) + if err != nil { + return err + } + + log.Println("Start memory profiling for", duration) + time.AfterFunc(duration, func() { + err = pprof.WriteHeapProfile(f) + if err != nil { + log.Println(err) + } + f.Close() + log.Println("Stop memory profiling after", duration) + }) + return nil +} + +// StartCPUProfile starts cpu profiling and save the results in file. +func StartCPUProfile(file string, duration time.Duration) (err error) { + f, err := os.Create(file) + if err != nil { + return err + } + + log.Println("Start cpu profiling for", duration) + err = pprof.StartCPUProfile(f) + if err != nil { + f.Close() + return err + } + + time.AfterFunc(duration, func() { + pprof.StopCPUProfile() + f.Close() + log.Println("Stop CPU profiling after", duration) + }) + return nil +} + +// GetCurrentCPUUsage get current CPU usage +func GetCurrentCPUUsage() float64 { + currentPid := os.Getpid() + p, err := process.NewProcess(int32(currentPid)) + if err != nil { + log.Printf("Fail to get CPU percent, %v\n", err) + return 0.0 + } + percent, err := p.CPUPercent() + if err != nil { + log.Printf("Fail to get CPU percent, %v\n", err) + return 0.0 + } + return percent / float64(runtime.NumCPU()) +} diff --git a/python/._locustfile.py b/python/._locustfile.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K 生成自 24 份真实压测结果:`results/go-1789962012.json`, `results/go-1790009273.json`, `results/go-1790010541.json`, `results/go-1790054848.json`, `results/go-1790055182.json`, `results/live_trigger-1790009033.json`, `results/live_trigger-1790010331.json`, `results/live_trigger-1790054558.json`, `results/python-1789961949.json`, `results/python-1790009211.json`, `results/python-1790010434.json`, `results/python-1790054714.json`, `results/python-1790055119.json`, `results/scale-1-1790009085.json`, `results/scale-1-1790010617.json`, `results/scale-1-1790054950.json`, `results/scale-1-1790055215.json`, `results/scale-4-1790009118.json`, `results/scale-4-1790010691.json`, `results/scale-4-1790055053.json`, `results/scale-4-1790055249.json`, `results/stale_trigger-1790009032.json`, `results/stale_trigger-1790010330.json`, `results/stale_trigger-1790054558.json` + +## 0. 数字口径(先读这一节) + +| 口径 | 环境 | 数字 | +|---|---|---| +| **生产真实业绩** | 公司环境 · 多机集群 —— **不可由本仓库复现** | 10 用户并发 · 平均响应 1-2s · 24h 稳定 · 实测 10-12 万 TPS | +| **本机演示实测** | 单机 —— 由本仓库跑出,见下方第 2 节 | 见第 2 节表格 | + +> 生产数字是**背景**,不是本仓库的产出。本仓库是复现方法论的实验台,单机量级与生产环境不可比;**可比的是 Python 与 Go 两种 worker 的倍数差**。 + +## 1. 负载参数(公平性核对) + +| worker | users | run_time | host | +|---|---|---|---| +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| go | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | +| python | 50 | 60 | http://127.0.0.1:18099 | + +两种 worker 跑**同一场景、同一并发、同一请求体**(4 类订单请求,权重 4:2:2:1,用户池 1000),唯一变量是执行引擎。 + +## 2. 指标对比(每 worker 取最近一轮) + +| worker | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | +|---|---|---|---|---|---|---| +| go | 1181444 | 0.00% | 20024.5 | 2 | 5 | 8 | +| python | 298351 | 0.00% | 4980.2 | 5 | 7 | 9 | + +**Go worker TPS 是 Python worker 的 4.02 倍**(20024 vs 4980,同并发同场景)。 + +## 3. 分 endpoint 明细 + +### go + +| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) | +|---|---|---|---|---|---| +| DELETE /api/v1/order/batch/cancel | 131815 | 0 | 2234.2 | 5 | 8 | +| POST /api/v1/order/limit/open | 523948 | 0 | 8880.5 | 5 | 8 | +| POST /api/v1/order/market/amount/open | 262600 | 0 | 4450.8 | 5 | 8 | +| POST /api/v1/order/market/quantity/open | 263081 | 0 | 4459.0 | 5 | 8 | + +### python + +| endpoint | 请求数 | 错误 | TPS | P95 (ms) | P99 (ms) | +|---|---|---|---|---|---| +| DELETE /api/v1/order/batch/cancel | 33109 | 0 | 552.7 | 7 | 9 | +| POST /api/v1/order/limit/open | 132585 | 0 | 2213.2 | 7 | 9 | +| POST /api/v1/order/market/amount/open | 66841 | 0 | 1115.7 | 7 | 9 | +| POST /api/v1/order/market/quantity/open | 65816 | 0 | 1098.6 | 7 | 9 | + +## 4. 归因分析 + +- **GIL 瓶颈**:Python worker 单进程内所有用户协程共享一个 GIL,requests 库虽然 I/O 多,但 JSON 编解码、locust 统计、gevent 调度都是纯 CPU 段;并发越高,GIL 争抢越明显,单核打满后 TPS 触顶。 +- **Go 怎么绕开**:goroutine 由 Go runtime 多线程调度(GOMAXPROCS=核数),网络 I/O 走 netpoller,无全局锁;连接池调优后(MaxIdleConnsPerHost=1000,且有断言测试保证配置真的生效),单机轻松压出数倍 TPS。 +- **瓶颈定位**:本机压测会撞到多层瓶颈(mock 网关的 Python HTTP 层、loopback、worker 自身)。若两种 worker 的 P99 都高,瓶颈在被测服务侧;若 Go 的 TPS 显著高于 Python 且 P99 更低,瓶颈在 worker 侧(GIL)。本报告数字即按此判读。 +- **本轮判读**:TPS 比 4.02 → 瓶颈在 **Python worker 侧(GIL)**。 + +## 5. 失真对比实验(条件单触发率) + +两种脚本打**同一个**条件单 endpoint(`POST /api/v1/order/condition/open`),负载参数相同,唯一变量是**触发价的来源**。mock 标记价随时间波动(contract 1 ≈ 31000 ± 1%)。 + +| 脚本 | 相位 | 触发价策略 | 请求数 | 失败 | 触发数 | 触发率 | +|---|---|---|---|---|---|---| +| stale_trigger | hardcoded_low | 触发价写死 30500(低于行情区间) | 300 | 0 | 300 | 100.00% | +| stale_trigger | hardcoded_high | 触发价写死 31500(高于行情区间) | 300 | 0 | 0 | 0.00% | +| live_trigger | cache_driven | 触发价=实时标记价±20(缓存服务驱动) | 300 | 0 | 166 | 55.33% | + +**判读**: +- 所有相位失败数都是 0 —— 单看压测报表(TPS / 错误率 / 延迟),**每一轮都「一切正常」**。 +- 但写死触发价的相位触发率塌缩到 **100% 与 0%**:市场状态稍偏离写死的值,结论整个翻转 —— 这批数据对条件单链路的容量评估毫无意义,而报表上看不出任何问题(「数据是错的,但看起来是对的」)。 +- 缓存服务实时驱动的触发率为 **55.33%**,落在由行情波动决定的中间区间(不退化到 0/1),压测数据才对触发链路有评估意义。 +- 缓存服务的滑动窗口去重 / 断流回退语义由 `tests/test_mark_price_service.py` 钉死;触发判定方向由 `tests/test_condition_trigger.py` 钉死。 + +## 6. 横向扩展实验(单实例上限 → 多实例) + +被测 mock 设了单实例能力上限(`TARGET_MAX_QPS`,超限请求排队等位、延迟上升),入口分流器轮询分发。各组实验**除实例数外参数完全一致**(worker / 并发 / 时长 / 单实例上限,见「参数」列)。 + +| 实例数 | 请求数 | 错误率 | TPS | P50 (ms) | P95 (ms) | P99 (ms) | 参数 | +|---|---|---|---|---|---|---|---| +| 1 | 14696 | 0.00% | 506.8 | 200 | 200 | 200 | instances=1 max_qps=500/instance extra_latency=2ms users=100 | +| 4 | 58752 | 0.00% | 2025.9 | 49 | 52 | 53 | instances=4 max_qps=500/instance extra_latency=2ms users=100 | + +**4 实例 TPS / 1 实例 TPS = 4.00**(2026 vs 507;不要求线性 —— 分流器与 loopback 也会吃一份,TPS 随实例数上升即说明扩展是有效的)。 +- 单实例触顶时 P99 被排队显著拉高 —— 「上限」是**测出来的能力边界**,不是一句「慢」;扩展实例数的决策依据正是这个数字。 + diff --git a/results/._go-1789962012.json b/results/._go-1789962012.json new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K/dev/null 2>&1; then + return + fi + mkdir -p "$PID_DIR" + nohup python3 target/http_server.py >"$PID_DIR/http.log" 2>&1 & + echo $! >"$PID_DIR/http.pid" + for i in $(seq 1 30); do + curl -sf "http://127.0.0.1:${HTTP_PORT}/health" >/dev/null 2>&1 && return + sleep 0.3 + done + echo "http target failed to start" >&2; exit 1 +} + +parse_args() { + USERS=50; DURATION="60s" + while [ $# -gt 0 ]; do + case "$1" in + --users) USERS="$2"; shift 2;; + --duration) DURATION="$2"; shift 2;; + *) echo "unknown arg: $1" >&2; usage;; + esac + done +} + +scale_teardown() { + local f + for f in "$PID_DIR"/scale-*.pid; do + [ -f "$f" ] || continue + kill "$(cat "$f")" 2>/dev/null || true + rm -f "$f" + done +} + +scale_run() { + local n="$1" i port backends="" + mkdir -p "$PID_DIR" results + scale_teardown + trap scale_teardown EXIT # 失败/中断也不留残留进程 + for i in $(seq 1 "$n"); do + port=$((SCALE_PORT + i)) + TARGET_PORT=$port TARGET_MAX_QPS=$SCALE_MAX_QPS \ + TARGET_EXTRA_LATENCY_MS=$SCALE_EXTRA_LATENCY_MS \ + nohup python3 target/http_server.py >"$PID_DIR/scale-backend-$port.log" 2>&1 & + echo $! >"$PID_DIR/scale-backend-$port.pid" + backends="${backends:+$backends,}$port" + done + nohup python3 target/dispatcher.py --port "$SCALE_PORT" --backends "$backends" \ + >"$PID_DIR/scale-dispatcher.log" 2>&1 & + echo $! >"$PID_DIR/scale-dispatcher.pid" + for i in $(seq 1 50); do + curl -sf "http://127.0.0.1:${SCALE_PORT}/health" >/dev/null 2>&1 && break + sleep 0.2 + done + if ! curl -sf "http://127.0.0.1:${SCALE_PORT}/health" >/dev/null 2>&1; then + echo "scale dispatcher failed to start" >&2; exit 1 + fi + echo "[scale-$n] backends=$backends max_qps=${SCALE_MAX_QPS}/instance " \ + "users=$SCALE_USERS duration=$SCALE_DURATION" + (cd go && go build -o ../bin/go-worker .) + PERF_WORKER="scale-$n" \ + PERF_LABEL="instances=$n max_qps=${SCALE_MAX_QPS}/instance extra_latency=${SCALE_EXTRA_LATENCY_MS}ms users=$SCALE_USERS" \ + locust -f python/master_locustfile.py --master \ + --master-bind-port "$MASTER_PORT" --expect-workers 1 \ + --headless -u "$SCALE_USERS" -r "$SCALE_USERS" -t "$SCALE_DURATION" \ + --host "http://127.0.0.1:${SCALE_PORT}" --only-summary & + MASTER_PID=$! + for i in $(seq 1 30); do + nc -z 127.0.0.1 "$MASTER_PORT" 2>/dev/null && break + sleep 0.3 + done + ./bin/go-worker -target "http://127.0.0.1:${SCALE_PORT}" \ + >"$PID_DIR/go-worker-scale.log" 2>&1 & + WORKER_PID=$! + wait "$MASTER_PID" + kill "$WORKER_PID" 2>/dev/null || true + scale_teardown + trap - EXIT + echo "[scale-$n] done → results/scale-$n-*.json" +} + +cmd="${1:-}"; shift || true +case "$cmd" in + target) + ensure_http_target + echo "targets up: http=:${HTTP_PORT}" + ;; + python) + parse_args "$@" + ensure_http_target + PERF_WORKER=python locust -f python/locustfile.py \ + --headless -u "$USERS" -r "$USERS" -t "$DURATION" \ + --host "$TARGET_HOST" --only-summary + ;; + go) + parse_args "$@" + ensure_http_target + (cd go && go build -o ../bin/go-worker .) + PERF_WORKER=go locust -f python/master_locustfile.py --master \ + --master-bind-port "$MASTER_PORT" --expect-workers 1 \ + --headless -u "$USERS" -r "$USERS" -t "$DURATION" \ + --host "$TARGET_HOST" --only-summary & + MASTER_PID=$! + mkdir -p "$PID_DIR" + for i in $(seq 1 30); do + nc -z 127.0.0.1 "$MASTER_PORT" 2>/dev/null && break + sleep 0.3 + done + ./bin/go-worker -target "$TARGET_HOST" >"$PID_DIR/go-worker.log" 2>&1 & + WORKER_PID=$! + wait "$MASTER_PID" + kill "$WORKER_PID" 2>/dev/null || true + ;; + report) + python3 compare.py results/*.json > report.md + echo "report.md generated" + ;; + scale-*) + n="${cmd#scale-}" + [[ "$n" =~ ^[0-9]+$ ]] && [ "$n" -ge 1 ] || usage + scale_run "$n" + ;; + *) usage;; +esac diff --git a/scenarios/._verify_trigger.py b/scenarios/._verify_trigger.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K.json; +compare.py 的 §5 按 trigger.mode 分组,直接读它们出对照表。 + +用法:python3 scenarios/verify_trigger.py +""" + +import itertools +import json +import math +import os +import random +import subprocess +import sys +import threading +import time +import urllib.request + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +RESULTS_DIR = os.path.join(ROOT, "results") +TARGET_BASE = "http://127.0.0.1:18099" +MARK_SERVICE_BASE = "http://127.0.0.1:18097" + +CONTRACT_ID = 1 +SIDE = "bid" +WORKERS = 10 +REQUESTS_PER_PHASE = 300 +BAND = 20.0 # live 组:触发价相对实时标记价的偏移带宽(约 0.06%) + +# stale 组的两个相位:写死的触发价,分别落在行情区间下方 / 上方 +STALE_PHASES = [ + ("hardcoded_low", 30500.0, "触发价写死 30500(低于行情区间)"), + ("hardcoded_high", 31500.0, "触发价写死 31500(高于行情区间)"), +] + +# ---------------------------------------------------------------- 基础设施 + +def http_json(method, url, payload=None, timeout=5.0): + data = json.dumps(payload).encode() if payload is not None else None + req = urllib.request.Request(url, data=data, method=method, + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode()) + + +def is_healthy(base): + try: + http_json("GET", base + "/health", timeout=1.0) + return True + except Exception: + return False + + +def ensure_process(base, script, tag): + """依赖进程自检:已在跑就复用;没在跑就在本机拉起(日志进 .pids/)。""" + if is_healthy(base): + return None + os.makedirs(os.path.join(ROOT, ".pids"), exist_ok=True) + log = open(os.path.join(ROOT, ".pids", f"{tag}.log"), "ab") + proc = subprocess.Popen([sys.executable, os.path.join(ROOT, script)], + cwd=ROOT, stdout=log, stderr=subprocess.STDOUT) + for _ in range(50): + if is_healthy(base): + return proc + if proc.poll() is not None: + raise SystemExit(f"{script} 启动即退出,见 .pids/{tag}.log") + time.sleep(0.2) + proc.kill() + raise SystemExit(f"{script} 10s 内未就绪,见 .pids/{tag}.log") + + +class Stats: + """单相位统计:请求数 / 失败数 / 触发数 / 延迟样本(毫秒)。""" + + def __init__(self): + self._lock = threading.Lock() + self.requests = 0 + self.failures = 0 + self.triggered = 0 + self.latencies = [] + + def record(self, latency_ms, ok, triggered=False): + with self._lock: + self.requests += 1 + if not ok: + self.failures += 1 + if triggered: + self.triggered += 1 + self.latencies.append(latency_ms) + + def summary(self): + with self._lock: + lat = sorted(self.latencies) + return { + "requests": self.requests, + "failures": self.failures, + "triggered": self.triggered, + "trigger_rate": (round(self.triggered / self.requests, 4) + if self.requests else 0.0), + "p50": _pct(lat, 0.50), + "p95": _pct(lat, 0.95), + "p99": _pct(lat, 0.99), + } + + +def _pct(sorted_vals, p): + if not sorted_vals: + return 0.0 + k = (len(sorted_vals) - 1) * p + f = math.floor(k) + c = math.ceil(k) + if f == c: + return round(sorted_vals[int(k)], 3) + return round(sorted_vals[f] + (sorted_vals[c] - sorted_vals[f]) * (k - f), 3) + + +def run_phase(workers, total_requests, make_request): + """workers 个线程抢索引,共执行 total_requests 次 make_request(i)。 + + make_request(i) 返回 (latency_ms, ok, triggered);抛异常按失败计。 + 返回 (Stats, elapsed_seconds)。 + """ + stats = Stats() + counter = itertools.count() + started = time.perf_counter() + + def work(): + while True: + i = next(counter) + if i >= total_requests: + return + try: + lat, ok, trig = make_request(i) + except Exception: + lat, ok, trig = 0.0, False, False + stats.record(lat, ok, trig) + + threads = [threading.Thread(target=work) for _ in range(workers)] + for t in threads: + t.start() + for t in threads: + t.join() + return stats, time.perf_counter() - started + + +def write_result(worker, host, users, run_time_desc, phases, mode): + """落一份与 compare.py 兼容的 JSON(多一个 trigger 字段承载实验数据)。 + + phases: [{"name", "detail", "stats": Stats, "elapsed": float}] + """ + total_req = sum(p["stats"].requests for p in phases) + total_fail = sum(p["stats"].failures for p in phases) + all_lat = sorted(lat for p in phases for lat in p["stats"].latencies) + elapsed = sum(p["elapsed"] for p in phases) + avg = round(sum(all_lat) / len(all_lat), 3) if all_lat else 0.0 + rps = round(total_req / elapsed, 3) if elapsed > 0 else 0.0 + result = { + "worker": worker, + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), + "load": {"users": users, "run_time": run_time_desc, "host": host}, + "total": { + "num_requests": total_req, + "num_failures": total_fail, + "avg_response_time": avg, + "p50": _pct(all_lat, 0.50), + "p95": _pct(all_lat, 0.95), + "p99": _pct(all_lat, 0.99), + "rps": rps, + }, + "entries": [{ + "name": "/api/v1/order/condition/open", + "method": "POST", + "num_requests": total_req, + "num_failures": total_fail, + "avg_response_time": avg, + "p50": _pct(all_lat, 0.50), + "p95": _pct(all_lat, 0.95), + "p99": _pct(all_lat, 0.99), + "rps": rps, + }], + "trigger": { + "mode": mode, + "phases": [{"name": p["name"], "detail": p["detail"], + **p["stats"].summary()} for p in phases], + }, + } + os.makedirs(RESULTS_DIR, exist_ok=True) + path = os.path.join(RESULTS_DIR, f"{worker}-{int(time.time())}.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(result, f, ensure_ascii=False, indent=2) + return path + + +# ---------------------------------------------------------------- 实验本体 + +def make_request(price_source): + """构造一次条件单请求。**两组唯一差异就是这个 price_source 参数。**""" + + def call(_i): + trigger_price = price_source() + t0 = time.perf_counter() + resp = http_json( + "POST", TARGET_BASE + "/api/v1/order/condition/open", + payload={ + "user_id": 1 + (_i % 1000), + "contract_id": CONTRACT_ID, + "side": SIDE, + "trigger_price": trigger_price, + "quantity": "1", + }) + lat = (time.perf_counter() - t0) * 1000 + data = resp.get("data") or {} + return lat, resp.get("code") == 0, bool(data.get("triggered")) + + return call + + +def smoke_check(): + """冒烟:条件单 endpoint 必须存在(否则 18099 上跑的是旧版 mock)。""" + probe = http_json( + "POST", TARGET_BASE + "/api/v1/order/condition/open", + payload={"user_id": 0, "contract_id": CONTRACT_ID, "side": SIDE, + "trigger_price": 31000.0}) + if probe.get("code") != 0 or "triggered" not in (probe.get("data") or {}): + raise SystemExit("18099 上的 mock 不含条件单 endpoint,请重启 target") + + +def fetch_live_price(): + """从缓存服务取实时标记价(断流时服务自动回退默认价,不中断)。""" + quote = http_json("GET", MARK_SERVICE_BASE + + f"/mark/price?contract_id={CONTRACT_ID}") + return float(quote["price"]) + + +def wait_live_price(timeout=5.0): + """等缓存服务从行情源拿到第一笔实时价(stale=False 即缓存已激活)。""" + deadline = time.time() + timeout + while time.time() < deadline: + try: + q = http_json("GET", MARK_SERVICE_BASE + + f"/mark/price?contract_id={CONTRACT_ID}", timeout=1.0) + if not q.get("stale", True): + return q["price"] + except Exception: + pass + time.sleep(0.2) + raise SystemExit("缓存服务未在限时内取到实时价(行情源 18099 是否在跑?)") + + +def run_stale(): + """对照组:触发价写死 —— 两个相位分别全触发 / 全不触发。""" + phases = [] + for name, price, detail in STALE_PHASES: + stats, elapsed = run_phase( + WORKERS, REQUESTS_PER_PHASE, make_request(lambda p=price: p)) + phases.append({"name": name, "detail": detail, + "stats": stats, "elapsed": elapsed}) + s = stats.summary() + print(f"[{name}] requests={s['requests']} failures={s['failures']} " + f"triggered={s['triggered']} trigger_rate={s['trigger_rate']:.2%} " + f"p95={s['p95']}ms") + path = write_result("stale_trigger", TARGET_BASE, WORKERS, + f"{len(STALE_PHASES)} phases x {REQUESTS_PER_PHASE} req", + phases, mode="stale") + total_fail = sum(p["stats"].failures for p in phases) + print(f"\n结果已写入 {os.path.relpath(path, ROOT)}") + print(f"★ 失败数={total_fail}(报表一切正常),但两个相位触发率塌缩到 " + f"0%/100% —— 这就是「数据是错的,但看起来是对的」。") + + +def run_live(): + """实验组:触发价由缓存服务的实时标记价驱动 —— 触发率落在中间区间。""" + price0 = wait_live_price() + print(f"[live] 缓存服务已激活,实时标记价 ≈ {price0}") + + def price_source(): + return round(fetch_live_price() + random.uniform(-BAND, BAND), 2) + + stats, elapsed = run_phase(WORKERS, REQUESTS_PER_PHASE, + make_request(price_source)) + s = stats.summary() + print(f"[cache_driven] requests={s['requests']} failures={s['failures']} " + f"triggered={s['triggered']} trigger_rate={s['trigger_rate']:.2%} " + f"p95={s['p95']}ms") + + phases = [{"name": "cache_driven", + "detail": f"触发价=实时标记价±{BAND:.0f}(缓存服务驱动)", + "stats": stats, "elapsed": elapsed}] + path = write_result("live_trigger", TARGET_BASE, WORKERS, + f"{REQUESTS_PER_PHASE} req", phases, mode="live") + print(f"\n结果已写入 {os.path.relpath(path, ROOT)}") + print(f"★ 触发率 {s['trigger_rate']:.2%} 落在中间区间 —— 跟随行情的" + f"触发价让数据有业务意义。") + + +def main(): + ensure_process(TARGET_BASE, os.path.join("target", "http_server.py"), "http") + smoke_check() + ensure_process(MARK_SERVICE_BASE, + os.path.join("target", "mark_price_service.py"), "mark-service") + run_stale() + print() + run_live() + + +if __name__ == "__main__": + main() diff --git a/target/._dispatcher.py b/target/._dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K order +_next_order_id = [1] +_start_ts = time.time() + + +def evaluate_trigger(side, trigger_price, mark_price): + """条件单触发判定(纯函数,便于单测)。 + + 演示简化:在请求时刻按当前标记价评估(真实系统是未来价格触碰时触发)。 + side=bid:标记价上穿/触及触发价 → mark >= trigger + side=ask:标记价下穿/触及触发价 → mark <= trigger + """ + if side == "bid": + return mark_price >= trigger_price + return mark_price <= trigger_price + + +class _Pacer: + """等距放行器:把请求放行时刻排到间隔 1/qps 的槽位上。 + + 超过上限的请求不失败,而是排队到后续槽位 —— 延迟升高、TPS 封顶在 + qps 附近,这正好把「单实例能力边界」变成可测量的数字。 + """ + + def __init__(self, qps): + self._interval = 1.0 / qps + self._lock = threading.Lock() + self._next_slot = time.monotonic() + + def wait(self): + with self._lock: + now = time.monotonic() + slot = self._next_slot if self._next_slot > now else now + self._next_slot = slot + self._interval + delay = slot - now + if delay > 0: + time.sleep(delay) + + +_pacer = _Pacer(_MAX_QPS) if _MAX_QPS > 0 else None + + +def _mark_price(contract_id: int) -> float: + """伪标记价:base + 正弦波动 + 微小随机抖动。""" + base = 30000.0 + contract_id * 1000.0 + t = time.time() - _start_ts + return round(base + base * 0.005 * math.sin(t / 10.0) + random.uniform(-5, 5), 2) + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): # 静默 + pass + + def handle_error(self, request, client_address): + # 压测结束时对端(worker)先断连是常态;BrokenPipe/ConnectionReset + # 不刷 traceback(traceback 会带本机绝对路径,污染日志) + err = sys.exc_info()[1] + if isinstance(err, (BrokenPipeError, ConnectionResetError)): + return + super().handle_error(request, client_address) + + def _reply(self, code, msg, data): + body = json.dumps({"code": code, "msg": msg, "data": data}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _read_json(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + try: + return json.loads(raw.decode() or "{}") + except json.JSONDecodeError: + return None + + def _throttle(self): + """限流 + 附加延迟;/health 不参与(保持就绪探针轻量)。""" + if self.path.startswith("/health"): + return + if _pacer is not None: + _pacer.wait() + if _EXTRA_LATENCY > 0: + time.sleep(_EXTRA_LATENCY) + + def _open_order(self, order_type): + payload = self._read_json() + if payload is None: + return self._reply(400, "bad json", None) + if "user_id" not in payload or "contract_id" not in payload: + return self._reply(400, "missing field", None) + with _lock: + oid = _next_order_id[0] + _next_order_id[0] += 1 + _orders[oid] = {"order_id": oid, "order_type": order_type, **payload} + self._reply(0, "ok", {"order_id": oid}) + + def _open_condition_order(self): + payload = self._read_json() + if payload is None: + return self._reply(400, "bad json", None) + try: + trigger_price = float(payload["trigger_price"]) + cid = int(payload["contract_id"]) + side = payload.get("side", "bid") + except (KeyError, TypeError, ValueError): + return self._reply(400, "missing/bad field", None) + mark = _mark_price(cid) + triggered = evaluate_trigger(side, trigger_price, mark) + with _lock: + oid = _next_order_id[0] + _next_order_id[0] += 1 + _orders[oid] = {"order_id": oid, "order_type": "condition", + "triggered": triggered, **payload} + # 注意:triggered 是业务结果,不是错误 —— code 恒为 0。 + # 这正是「触发价写死」难以被发现的原因:报表全绿,业务数据却是退化的。 + self._reply(0, "ok", {"order_id": oid, "triggered": triggered, + "mark_price": mark}) + + def do_POST(self): + self._throttle() + path = self.path.split("?")[0] + if path == "/api/v1/order/condition/open": + self._open_condition_order() + elif path == "/api/v1/order/limit/open": + self._open_order("limit") + elif path == "/api/v1/order/market/quantity/open": + self._open_order("market_quantity") + elif path == "/api/v1/order/market/amount/open": + self._open_order("market_amount") + else: + self._reply(404, "not found", None) + + def do_DELETE(self): + self._throttle() + path = self.path.split("?")[0] + if path == "/api/v1/order/batch/cancel": + payload = self._read_json() or {} + ids = payload.get("order_ids", []) + with _lock: + canceled = sum(1 for i in ids if _orders.pop(i, None)) + self._reply(0, "ok", {"canceled": canceled}) + else: + self._reply(404, "not found", None) + + def do_GET(self): + self._throttle() + if self.path.startswith("/api/v1/mark/price"): + qs = dict(p.split("=", 1) for p in + self.path.split("?", 1)[-1].split("&") if "=" in p) + cid = int(qs.get("contract_id", 1)) + self._reply(0, "ok", {"contract_id": cid, "price": _mark_price(cid)}) + elif self.path.startswith("/health"): + self._reply(0, "ok", {"status": "up"}) + else: + self._reply(404, "not found", None) + + +def main(): + srv = ThreadingHTTPServer((_HOST, _PORT), Handler) + print(f"[target] http mock listening on http://{_HOST}:{_PORT}") + srv.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/target/mark_price_service.py b/target/mark_price_service.py new file mode 100644 index 0000000..7281d46 --- /dev/null +++ b/target/mark_price_service.py @@ -0,0 +1,219 @@ +"""标记价格缓存服务(独立进程,perf-harness-demo 专用)。 + +链路:轮询行情源(本机 mock 的 /api/v1/mark/price,扮演「行情推送」) +→ 双元素滑动窗口去重 → 本地缓存(TTL)→ 对压测脚本提供 GET /mark/price。 + +两条硬语义(对应 tests/ 下的用例): + +1. 断流回退 —— 行情源不可用时**压测不中断**: + 出价顺序为 新鲜缓存(TTL 内)→ 默认价(stale=True,source=default)。 + 进程不因源故障退出,接口不因源故障报错。 + +2. 滑动窗口去重 —— 窗口保存最近两个**已接受**的价格(量化到 tick 后比较): + 新报价与窗口内任一值相同 → 重复推送,丢弃;都不同 → 真实变化,接受。 + ★ 只存「最后一个值」的伪窗口识别不了 A-B-A 交替重复(100→105→100 时 + 第三笔会被误判为新变化)—— 那样等于没去重。 + +端口默认 18097(env MARK_SERVICE_PORT);行情源默认 http://127.0.0.1:18099 +(env MARK_SOURCE)。零第三方依赖,只监听本机,绝不对外。 +""" + +import json +import os +import sys +import threading +import time +import urllib.request +from collections import deque +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +_DEFAULT_PORT = 18097 + + +def default_price_for(contract_id): + """默认兜底价:与 mock 的标记价基准同式(行情未接入时的静态参考价)。""" + return 30000.0 + contract_id * 1000.0 + + +class PriceCache: + """单合约的标记价缓存:去重窗口 + TTL + 断流回退。时钟可注入,便于测试。""" + + def __init__(self, contract_id, ttl=120.0, tick_size=1.0, window_size=2, + now=time.monotonic): + self.contract_id = contract_id + self.default_price = default_price_for(contract_id) + self.ttl = ttl + self.tick_size = tick_size + self.window_size = window_size + self._now = now + self._lock = threading.Lock() + self._window = deque(maxlen=window_size) + self._price = None # 最近一笔被接受的价格(原始值) + self._updated_at = None + self.stats = {"ticks": 0, "accepted": 0, "dups": 0, "fetch_errors": 0, + "served_cache": 0, "served_default": 0} + + def _quantize(self, price): + return round(round(price / self.tick_size) * self.tick_size, 6) + + def ingest_tick(self, price): + """喂入一笔行情。True=真实变化已接受;False=重复推送已丢弃。""" + with self._lock: + self.stats["ticks"] += 1 + q = self._quantize(price) + if q in self._window: + self.stats["dups"] += 1 + return False + self._window.append(q) + self._price = price + self._updated_at = self._now() + self.stats["accepted"] += 1 + return True + + def note_source_error(self): + with self._lock: + self.stats["fetch_errors"] += 1 + + def get_price(self): + """断流回退出价:TTL 内缓存 → 默认价。任何情况下不抛异常。""" + with self._lock: + if (self._price is not None + and self._now() - self._updated_at <= self.ttl): + self.stats["served_cache"] += 1 + return {"contract_id": self.contract_id, "price": self._price, + "stale": False, "source": "cache"} + self.stats["served_default"] += 1 + return {"contract_id": self.contract_id, "price": self.default_price, + "stale": True, "source": "default"} + + +class Poller: + """后台轮询行情源并喂给缓存;源故障只计数,绝不向外抛(断流≠进程死亡)。""" + + def __init__(self, source, cache, interval=0.2, timeout=1.0): + self.source = source.rstrip("/") + self.cache = cache + self.interval = interval + self.timeout = timeout + self._stop = threading.Event() + self._thread = None + + def poll_once(self): + url = (f"{self.source}/api/v1/mark/price" + f"?contract_id={self.cache.contract_id}") + try: + with urllib.request.urlopen(url, timeout=self.timeout) as r: + body = json.loads(r.read().decode()) + self.cache.ingest_tick(float(body["data"]["price"])) + except Exception: + self.cache.note_source_error() + + def start(self): + def loop(): + while not self._stop.is_set(): + self.poll_once() + self._stop.wait(self.interval) + + self._thread = threading.Thread(target=loop, daemon=True) + self._thread.start() + + def stop(self): + self._stop.set() + + +class Service: + """按合约懒加载 PriceCache + Poller;聚合 stats 供观测。""" + + def __init__(self, source, ttl=120.0, tick_size=1.0, poll_interval=0.2): + self.source = source + self.ttl = ttl + self.tick_size = tick_size + self.poll_interval = poll_interval + self._lock = threading.Lock() + self._caches = {} + self._pollers = {} + + def cache_for(self, contract_id): + with self._lock: + cache = self._caches.get(contract_id) + if cache is None: + cache = PriceCache(contract_id, ttl=self.ttl, + tick_size=self.tick_size) + poller = Poller(self.source, cache, interval=self.poll_interval) + poller.start() + self._caches[contract_id] = cache + self._pollers[contract_id] = poller + return cache + + def get_price(self, contract_id): + return self.cache_for(contract_id).get_price() + + def stats(self): + with self._lock: + return {str(cid): dict(c.stats) for cid, c in self._caches.items()} + + def stop_all(self): + with self._lock: + for p in self._pollers.values(): + p.stop() + + +def make_handler(service): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): # 静默 + pass + + def handle_error(self, request, client_address): + # 对端先断连(压测收尾)是常态,不刷 traceback(会带本机绝对路径) + err = sys.exc_info()[1] + if isinstance(err, (BrokenPipeError, ConnectionResetError)): + return + super().handle_error(request, client_address) + + def _json(self, obj): + body = json.dumps(obj).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path.startswith("/mark/price"): + qs = dict(p.split("=", 1) for p in + self.path.split("?", 1)[-1].split("&") if "=" in p) + cid = int(qs.get("contract_id", 1)) + self._json(service.get_price(cid)) + elif self.path.startswith("/stats"): + self._json(service.stats()) + elif self.path.startswith("/health"): + self._json({"status": "up"}) + else: + self._json({"error": "not found"}) + + return Handler + + +def main(): + port = int(os.environ.get("MARK_SERVICE_PORT", str(_DEFAULT_PORT))) + source = os.environ.get("MARK_SOURCE", "http://127.0.0.1:18099") + ttl = float(os.environ.get("MARK_CACHE_TTL", "120")) + tick_size = float(os.environ.get("MARK_TICK_SIZE", "1")) + interval = float(os.environ.get("MARK_POLL_INTERVAL", "0.2")) + service = Service(source, ttl=ttl, tick_size=tick_size, + poll_interval=interval) + srv = ThreadingHTTPServer(("127.0.0.1", port), make_handler(service)) + print(f"[mark-service] listening on http://127.0.0.1:{port} " + f"source={source} ttl={ttl}s") + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + finally: + service.stop_all() + + +if __name__ == "__main__": + main() diff --git a/tests/._conftest.py b/tests/._conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..4bcda6db8ece664b2cea20ee16ef78ed2a268af9 GIT binary patch literal 163 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K$Vqox1Ojhs@R)|o50+1L3ClDI}aUl?c_=|y<2;dkJ5(HHS(lG;wxzV&S oBE&_L^K= 29 * 0.001 * 0.8 # 留 20% 调度余量,防 CI 抖动误报 + assert elapsed < 1.0 # 但也不能离谱(实现有 bug 时会卡死) + + +def test_pacer_first_slot_immediate(): + """第一个请求不应排队。""" + pacer = _Pacer(100) + t0 = time.monotonic() + pacer.wait() + assert time.monotonic() - t0 < 0.05 + + +def test_pacer_recovers_after_idle(): + """空闲一段时间后时隙立即给,不累积旧债(槽位取 max(now, next))。""" + pacer = _Pacer(100) # 10ms 槽位 + pacer.wait() + time.sleep(0.2) + t0 = time.monotonic() + pacer.wait() + assert time.monotonic() - t0 < 0.05