feat: Python(Locust) + Go(boomer) 混合压测框架(演示版)
This commit is contained in:
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
@@ -0,0 +1,96 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// newTunedTransport 返回调优后的 Transport。
|
||||
// 注意:调优参数必须落在**真正被 client 引用**的那个 Transport 上 —— 若参数
|
||||
// 写在一个从未被使用的变量上,默认 MaxIdleConnsPerHost=2 会让压测根本压不上去,
|
||||
// 而且**不报任何错**,最难查。因此本文件配套 TestTransportPool,
|
||||
// 断言「client 实际使用的 transport 就是调优过的那个」。
|
||||
func newTunedTransport() *http.Transport {
|
||||
return &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
MaxIdleConns: 2000,
|
||||
MaxIdleConnsPerHost: 1000,
|
||||
MaxConnsPerHost: 1000,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// APIClient 是被测 mock 网关的 HTTP 客户端。
|
||||
type APIClient struct {
|
||||
base string
|
||||
hc *http.Client
|
||||
}
|
||||
|
||||
func NewAPIClient(base string) *APIClient {
|
||||
return &APIClient{
|
||||
base: base,
|
||||
hc: &http.Client{
|
||||
Transport: newTunedTransport(), // ← 调优对象就在这里被引用
|
||||
Timeout: 10 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Transport 暴露 client 实际使用的 transport(供断言测试用)。
|
||||
func (c *APIClient) Transport() *http.Transport {
|
||||
return c.hc.Transport.(*http.Transport)
|
||||
}
|
||||
|
||||
type apiResponse struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
// do 发起请求并返回 (httpStatus, bizCode, err)。latency 由调用方统计。
|
||||
func (c *APIClient) do(method, path string, body any) (int, int, error) {
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return 0, -1, err
|
||||
}
|
||||
reader = bytes.NewReader(raw)
|
||||
}
|
||||
req, err := http.NewRequest(method, c.base+path, reader)
|
||||
if err != nil {
|
||||
return 0, -1, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return 0, -1, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return resp.StatusCode, -1, err
|
||||
}
|
||||
var ar apiResponse
|
||||
if err := json.Unmarshal(raw, &ar); err != nil {
|
||||
return resp.StatusCode, -1, fmt.Errorf("decode: %w", err)
|
||||
}
|
||||
return resp.StatusCode, ar.Code, nil
|
||||
}
|
||||
|
||||
func (c *APIClient) OpenOrder(path string, p OrderPayload) (int, int, error) {
|
||||
return c.do(http.MethodPost, path, p)
|
||||
}
|
||||
|
||||
func (c *APIClient) BatchCancel(userID int, orderIDs []int64) (int, int, error) {
|
||||
return c.do(http.MethodDelete, "/api/v1/order/batch/cancel",
|
||||
map[string]any{"user_id": userID, "order_ids": orderIDs})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestTransportPool:连接池调优参数必须落在 client 实际使用的 transport 上,
|
||||
// 而不是一个从未被引用的变量(否则调优静默失效)。
|
||||
func TestTransportPool(t *testing.T) {
|
||||
c := NewAPIClient("http://127.0.0.1:1")
|
||||
tr := c.Transport()
|
||||
if tr == nil {
|
||||
t.Fatal("client.Transport 为 nil:连接池配置根本没有被引用")
|
||||
}
|
||||
if tr.MaxIdleConnsPerHost < 1000 {
|
||||
t.Fatalf("MaxIdleConnsPerHost = %d,期望 >= 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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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=
|
||||
+26
@@ -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...)
|
||||
}
|
||||
+104
@@ -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
|
||||
}
|
||||
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019 myzhan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+280
@@ -0,0 +1,280 @@
|
||||
package boomer
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/asaskevich/EventBus"
|
||||
)
|
||||
|
||||
// Events is the global event bus instance.
|
||||
var Events = EventBus.New()
|
||||
|
||||
var defaultBoomer = &Boomer{}
|
||||
|
||||
// Mode is the running mode of boomer, both standalone and distributed are supported.
|
||||
type Mode int
|
||||
|
||||
const (
|
||||
// DistributedMode requires connecting to a master.
|
||||
DistributedMode Mode = iota
|
||||
// StandaloneMode will run without a master.
|
||||
StandaloneMode
|
||||
)
|
||||
|
||||
// A Boomer is used to run tasks.
|
||||
// This type is exposed, so users can create and control a Boomer instance programmatically.
|
||||
type Boomer struct {
|
||||
masterHost string
|
||||
masterPort int
|
||||
mode Mode
|
||||
rateLimiter RateLimiter
|
||||
slaveRunner *slaveRunner
|
||||
|
||||
localRunner *localRunner
|
||||
spawnCount int
|
||||
spawnRate float64
|
||||
|
||||
cpuProfile string
|
||||
cpuProfileDuration time.Duration
|
||||
|
||||
memoryProfile string
|
||||
memoryProfileDuration time.Duration
|
||||
|
||||
outputs []Output
|
||||
}
|
||||
|
||||
// NewBoomer returns a new Boomer.
|
||||
func NewBoomer(masterHost string, masterPort int) *Boomer {
|
||||
return &Boomer{
|
||||
masterHost: masterHost,
|
||||
masterPort: masterPort,
|
||||
mode: DistributedMode,
|
||||
}
|
||||
}
|
||||
|
||||
// NewStandaloneBoomer returns a new Boomer, which can run without master.
|
||||
func NewStandaloneBoomer(spawnCount int, spawnRate float64) *Boomer {
|
||||
return &Boomer{
|
||||
spawnCount: spawnCount,
|
||||
spawnRate: spawnRate,
|
||||
mode: StandaloneMode,
|
||||
}
|
||||
}
|
||||
|
||||
// SetRateLimiter allows user to use their own rate limiter.
|
||||
// It must be called before the test is started.
|
||||
func (b *Boomer) SetRateLimiter(rateLimiter RateLimiter) {
|
||||
b.rateLimiter = rateLimiter
|
||||
}
|
||||
|
||||
// SetMode only accepts boomer.DistributedMode and boomer.StandaloneMode.
|
||||
func (b *Boomer) SetMode(mode Mode) {
|
||||
switch mode {
|
||||
case DistributedMode:
|
||||
b.mode = DistributedMode
|
||||
case StandaloneMode:
|
||||
b.mode = StandaloneMode
|
||||
default:
|
||||
log.Println("Invalid mode, ignored!")
|
||||
}
|
||||
}
|
||||
|
||||
// AddOutput accepts outputs which implements the boomer.Output interface.
|
||||
func (b *Boomer) AddOutput(o Output) {
|
||||
b.outputs = append(b.outputs, o)
|
||||
}
|
||||
|
||||
// EnableCPUProfile will start cpu profiling after run.
|
||||
func (b *Boomer) EnableCPUProfile(cpuProfile string, duration time.Duration) {
|
||||
b.cpuProfile = cpuProfile
|
||||
b.cpuProfileDuration = duration
|
||||
}
|
||||
|
||||
// EnableMemoryProfile will start memory profiling after run.
|
||||
func (b *Boomer) EnableMemoryProfile(memoryProfile string, duration time.Duration) {
|
||||
b.memoryProfile = memoryProfile
|
||||
b.memoryProfileDuration = duration
|
||||
}
|
||||
|
||||
// Run accepts a slice of Task and connects to the locust master.
|
||||
func (b *Boomer) Run(tasks ...*Task) {
|
||||
if b.cpuProfile != "" {
|
||||
err := StartCPUProfile(b.cpuProfile, b.cpuProfileDuration)
|
||||
if err != nil {
|
||||
log.Printf("Error starting cpu profiling, %v", err)
|
||||
}
|
||||
}
|
||||
if b.memoryProfile != "" {
|
||||
err := StartMemoryProfile(b.memoryProfile, b.memoryProfileDuration)
|
||||
if err != nil {
|
||||
log.Printf("Error starting memory profiling, %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
switch b.mode {
|
||||
case DistributedMode:
|
||||
b.slaveRunner = newSlaveRunner(b.masterHost, b.masterPort, tasks, b.rateLimiter)
|
||||
for _, o := range b.outputs {
|
||||
b.slaveRunner.addOutput(o)
|
||||
}
|
||||
b.slaveRunner.run()
|
||||
case StandaloneMode:
|
||||
b.localRunner = newLocalRunner(tasks, b.rateLimiter, b.spawnCount, b.spawnRate)
|
||||
for _, o := range b.outputs {
|
||||
b.localRunner.addOutput(o)
|
||||
}
|
||||
b.localRunner.run()
|
||||
default:
|
||||
log.Println("Invalid mode, expected boomer.DistributedMode or boomer.StandaloneMode")
|
||||
}
|
||||
}
|
||||
|
||||
// RecordSuccess reports a success.
|
||||
func (b *Boomer) RecordSuccess(requestType, name string, responseTime int64, responseLength int64) {
|
||||
if b.localRunner == nil && b.slaveRunner == nil {
|
||||
return
|
||||
}
|
||||
switch b.mode {
|
||||
case DistributedMode:
|
||||
b.slaveRunner.stats.requestSuccessChan <- &requestSuccess{
|
||||
requestType: requestType,
|
||||
name: name,
|
||||
responseTime: responseTime,
|
||||
responseLength: responseLength,
|
||||
}
|
||||
case StandaloneMode:
|
||||
b.localRunner.stats.requestSuccessChan <- &requestSuccess{
|
||||
requestType: requestType,
|
||||
name: name,
|
||||
responseTime: responseTime,
|
||||
responseLength: responseLength,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RecordFailure reports a failure.
|
||||
func (b *Boomer) RecordFailure(requestType, name string, responseTime int64, exception string) {
|
||||
if b.localRunner == nil && b.slaveRunner == nil {
|
||||
return
|
||||
}
|
||||
switch b.mode {
|
||||
case DistributedMode:
|
||||
b.slaveRunner.stats.requestFailureChan <- &requestFailure{
|
||||
requestType: requestType,
|
||||
name: name,
|
||||
responseTime: responseTime,
|
||||
error: exception,
|
||||
}
|
||||
case StandaloneMode:
|
||||
b.localRunner.stats.requestFailureChan <- &requestFailure{
|
||||
requestType: requestType,
|
||||
name: name,
|
||||
responseTime: responseTime,
|
||||
error: exception,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Quit will send a quit message to the master.
|
||||
func (b *Boomer) Quit() {
|
||||
Events.Publish("boomer:quit")
|
||||
var ticker = time.NewTicker(3 * time.Second)
|
||||
|
||||
switch b.mode {
|
||||
case DistributedMode:
|
||||
// wait for quit message is sent to master
|
||||
select {
|
||||
case <-b.slaveRunner.client.disconnectedChannel():
|
||||
break
|
||||
case <-ticker.C:
|
||||
log.Println("Timeout waiting for sending quit message to master, boomer will quit any way.")
|
||||
break
|
||||
}
|
||||
b.slaveRunner.close()
|
||||
case StandaloneMode:
|
||||
b.localRunner.close()
|
||||
}
|
||||
}
|
||||
|
||||
// Run tasks without connecting to the master.
|
||||
func runTasksForTest(tasks ...*Task) {
|
||||
taskNames := strings.Split(runTasks, ",")
|
||||
for _, task := range tasks {
|
||||
if task.Name == "" {
|
||||
continue
|
||||
} else {
|
||||
for _, name := range taskNames {
|
||||
if name == task.Name {
|
||||
log.Println("Running " + task.Name)
|
||||
task.Fn()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run accepts a slice of Task and connects to a locust master.
|
||||
// It's a convenience function to use the defaultBoomer.
|
||||
func Run(tasks ...*Task) {
|
||||
if !flag.Parsed() {
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
if runTasks != "" {
|
||||
runTasksForTest(tasks...)
|
||||
return
|
||||
}
|
||||
|
||||
initLegacyEventHandlers()
|
||||
|
||||
rateLimiter, err := createRateLimiter(maxRPS, requestIncreaseRate)
|
||||
if err != nil {
|
||||
log.Fatalf("%v\n", err)
|
||||
}
|
||||
defaultBoomer.SetRateLimiter(rateLimiter)
|
||||
defaultBoomer.masterHost = masterHost
|
||||
defaultBoomer.masterPort = masterPort
|
||||
defaultBoomer.EnableMemoryProfile(memoryProfile, memoryProfileDuration)
|
||||
defaultBoomer.EnableCPUProfile(cpuProfile, cpuProfileDuration)
|
||||
|
||||
defaultBoomer.Run(tasks...)
|
||||
|
||||
quitByMe := false
|
||||
quitChan := make(chan bool)
|
||||
|
||||
Events.SubscribeOnce("boomer:quit", func() {
|
||||
if !quitByMe {
|
||||
close(quitChan)
|
||||
}
|
||||
})
|
||||
|
||||
c := make(chan os.Signal)
|
||||
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
select {
|
||||
case <-c:
|
||||
quitByMe = true
|
||||
defaultBoomer.Quit()
|
||||
case <-quitChan:
|
||||
}
|
||||
|
||||
log.Println("shut down")
|
||||
}
|
||||
|
||||
// RecordSuccess reports a success.
|
||||
// It's a convenience function to use the defaultBoomer.
|
||||
func RecordSuccess(requestType, name string, responseTime int64, responseLength int64) {
|
||||
defaultBoomer.RecordSuccess(requestType, name, responseTime, responseLength)
|
||||
}
|
||||
|
||||
// RecordFailure reports a failure.
|
||||
// It's a convenience function to use the defaultBoomer.
|
||||
func RecordFailure(requestType, name string, responseTime int64, exception string) {
|
||||
defaultBoomer.RecordFailure(requestType, name, responseTime, exception)
|
||||
}
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
package boomer
|
||||
|
||||
type client interface {
|
||||
connect() (err error)
|
||||
close()
|
||||
recvChannel() chan *message
|
||||
sendChannel() chan *message
|
||||
disconnectedChannel() chan bool
|
||||
}
|
||||
Vendored
+127
@@ -0,0 +1,127 @@
|
||||
// +build goczmq
|
||||
|
||||
package boomer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/zeromq/goczmq"
|
||||
)
|
||||
|
||||
type czmqSocketClient struct {
|
||||
masterHost string
|
||||
masterPort int
|
||||
identity string
|
||||
|
||||
dealerSocket *goczmq.Sock
|
||||
|
||||
fromMaster chan *message
|
||||
toMaster chan *message
|
||||
disconnectedFromMaster chan bool
|
||||
shutdownChan chan bool
|
||||
}
|
||||
|
||||
func newClient(masterHost string, masterPort int, identity string) (client *czmqSocketClient) {
|
||||
log.Println("Boomer is built with goczmq support.")
|
||||
client = &czmqSocketClient{
|
||||
masterHost: masterHost,
|
||||
masterPort: masterPort,
|
||||
identity: identity,
|
||||
fromMaster: make(chan *message, 100),
|
||||
toMaster: make(chan *message, 100),
|
||||
disconnectedFromMaster: make(chan bool),
|
||||
shutdownChan: make(chan bool),
|
||||
}
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) connect() (err error) {
|
||||
addr := fmt.Sprintf("tcp://%s:%d", c.masterHost, c.masterPort)
|
||||
dealer := goczmq.NewSock(goczmq.Dealer)
|
||||
dealer.SetOption(goczmq.SockSetIdentity(c.identity))
|
||||
err = dealer.Connect(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.dealerSocket = dealer
|
||||
|
||||
log.Printf("Boomer is connected to master(%s) press Ctrl+c to quit.\n", addr)
|
||||
|
||||
go c.recv()
|
||||
go c.send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) close() {
|
||||
close(c.shutdownChan)
|
||||
if c.dealerSocket != nil {
|
||||
c.dealerSocket.Destroy()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) recvChannel() chan *message {
|
||||
return c.fromMaster
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) recv() {
|
||||
for {
|
||||
select {
|
||||
case <-c.shutdownChan:
|
||||
return
|
||||
default:
|
||||
msg, _, err := c.dealerSocket.RecvFrame()
|
||||
if err != nil {
|
||||
log.Printf("Error reading: %v\n", err)
|
||||
continue
|
||||
}
|
||||
decodedMsg, err := newMessageFromBytes(msg)
|
||||
if err != nil {
|
||||
log.Printf("Msgpack decode fail: %v\n", err)
|
||||
continue
|
||||
}
|
||||
if decodedMsg.NodeID != c.identity {
|
||||
log.Printf("Recv a %s message for node(%s), not for me(%s), dropped.\n", decodedMsg.Type, decodedMsg.NodeID, c.identity)
|
||||
continue
|
||||
}
|
||||
c.fromMaster <- decodedMsg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) sendChannel() chan *message {
|
||||
return c.toMaster
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) send() {
|
||||
for {
|
||||
select {
|
||||
case <-c.shutdownChan:
|
||||
return
|
||||
case msg := <-c.toMaster:
|
||||
c.sendMessage(msg)
|
||||
if msg.Type == "quit" {
|
||||
c.disconnectedFromMaster <- true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) sendMessage(msg *message) {
|
||||
serializedMessage, err := msg.serialize()
|
||||
if err != nil {
|
||||
log.Printf("Msgpack encode fail: %v\n", err)
|
||||
return
|
||||
}
|
||||
err = c.dealerSocket.SendFrame(serializedMessage, goczmq.FlagNone)
|
||||
if err != nil {
|
||||
log.Printf("Error sending: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *czmqSocketClient) disconnectedChannel() chan bool {
|
||||
return c.disconnectedFromMaster
|
||||
}
|
||||
Vendored
+129
@@ -0,0 +1,129 @@
|
||||
// +build !goczmq
|
||||
|
||||
package boomer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/zeromq/gomq"
|
||||
"github.com/zeromq/gomq/zmtp"
|
||||
)
|
||||
|
||||
type gomqSocketClient struct {
|
||||
masterHost string
|
||||
masterPort int
|
||||
identity string
|
||||
|
||||
dealerSocket gomq.Dealer
|
||||
|
||||
fromMaster chan *message
|
||||
toMaster chan *message
|
||||
disconnectedFromMaster chan bool
|
||||
shutdownChan chan bool
|
||||
}
|
||||
|
||||
func newClient(masterHost string, masterPort int, identity string) (client *gomqSocketClient) {
|
||||
log.Println("Boomer is built with gomq support.")
|
||||
client = &gomqSocketClient{
|
||||
masterHost: masterHost,
|
||||
masterPort: masterPort,
|
||||
identity: identity,
|
||||
fromMaster: make(chan *message, 100),
|
||||
toMaster: make(chan *message, 100),
|
||||
disconnectedFromMaster: make(chan bool),
|
||||
shutdownChan: make(chan bool),
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) connect() (err error) {
|
||||
addr := fmt.Sprintf("tcp://%s:%d", c.masterHost, c.masterPort)
|
||||
c.dealerSocket = gomq.NewDealer(zmtp.NewSecurityNull(), c.identity)
|
||||
|
||||
if err = c.dealerSocket.Connect(addr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("Boomer is connected to master(%s) press Ctrl+c to quit.\n", addr)
|
||||
go c.recv()
|
||||
go c.send()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) close() {
|
||||
close(c.shutdownChan)
|
||||
if c.dealerSocket != nil {
|
||||
c.dealerSocket.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) recvChannel() chan *message {
|
||||
return c.fromMaster
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) recv() {
|
||||
for {
|
||||
select {
|
||||
case <-c.shutdownChan:
|
||||
return
|
||||
case msg := <-c.dealerSocket.RecvChannel():
|
||||
if msg.MessageType == zmtp.CommandMessage {
|
||||
continue
|
||||
}
|
||||
if len(msg.Body) == 0 {
|
||||
continue
|
||||
}
|
||||
body, err := msg.Body[0], msg.Err
|
||||
if err != nil {
|
||||
log.Printf("Error reading: %v\n", err)
|
||||
continue
|
||||
}
|
||||
decodedMsg, err := newMessageFromBytes(body)
|
||||
if err != nil {
|
||||
log.Printf("Msgpack decode fail: %v\n", err)
|
||||
continue
|
||||
}
|
||||
if decodedMsg.NodeID != c.identity {
|
||||
log.Printf("Recv a %s message for node(%s), not for me(%s), dropped.\n", decodedMsg.Type, decodedMsg.NodeID, c.identity)
|
||||
continue
|
||||
}
|
||||
c.fromMaster <- decodedMsg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) sendChannel() chan *message {
|
||||
return c.toMaster
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) send() {
|
||||
for {
|
||||
select {
|
||||
case <-c.shutdownChan:
|
||||
return
|
||||
case msg := <-c.toMaster:
|
||||
c.sendMessage(msg)
|
||||
if msg.Type == "quit" {
|
||||
c.disconnectedFromMaster <- true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) sendMessage(msg *message) {
|
||||
serializedMessage, err := msg.serialize()
|
||||
if err != nil {
|
||||
log.Printf("Msgpack encode fail: %v\n", err)
|
||||
return
|
||||
}
|
||||
err = c.dealerSocket.Send(serializedMessage)
|
||||
if err != nil {
|
||||
log.Printf("Error sending: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *gomqSocketClient) disconnectedChannel() chan bool {
|
||||
return c.disconnectedFromMaster
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
module github.com/myzhan/boomer
|
||||
|
||||
go 1.21
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
// This file is kept to ensure backward compatibility.
|
||||
|
||||
package boomer
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var masterHost string
|
||||
var masterPort int
|
||||
var maxRPS int64
|
||||
var requestIncreaseRate string
|
||||
var runTasks string
|
||||
var memoryProfile string
|
||||
var memoryProfileDuration time.Duration
|
||||
var cpuProfile string
|
||||
var cpuProfileDuration time.Duration
|
||||
|
||||
var successRetiredWarning = &sync.Once{}
|
||||
var failureRetiredWarning = &sync.Once{}
|
||||
|
||||
func createRateLimiter(maxRPS int64, requestIncreaseRate string) (rateLimiter RateLimiter, err error) {
|
||||
if requestIncreaseRate != "-1" {
|
||||
if maxRPS > 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.")
|
||||
}
|
||||
Vendored
+38
@@ -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
|
||||
}
|
||||
Vendored
+146
@@ -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()
|
||||
}
|
||||
Vendored
+213
@@ -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)
|
||||
}
|
||||
Vendored
+555
@@ -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)
|
||||
}
|
||||
Vendored
+309
@@ -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
|
||||
}
|
||||
Vendored
+13
@@ -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
|
||||
}
|
||||
Vendored
+107
@@ -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()
|
||||
}
|
||||
Vendored
+110
@@ -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())
|
||||
}
|
||||
Reference in New Issue
Block a user