forked from mtusi2026/mtusi2026lab3
160 lines
5.4 KiB
Go
160 lines
5.4 KiB
Go
// Closed-loop load generator with persistent HTTP connections. No POST retries.
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"os"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
func nonce() string {
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
panic(err)
|
|
}
|
|
return hex.EncodeToString(b)
|
|
}
|
|
|
|
type result struct {
|
|
latencies []float64
|
|
errors map[string]int
|
|
instances map[string]int
|
|
}
|
|
|
|
func main() {
|
|
base := flag.String("base-url", "http://lb:8080", "LB URL")
|
|
duration := flag.Duration("duration", 15*time.Second, "measurement duration")
|
|
warmup := flag.Duration("warmup", 3*time.Second, "warmup duration")
|
|
concurrency := flag.Int("concurrency", 32, "workers")
|
|
flag.Parse()
|
|
if *concurrency < 1 || *concurrency > 512 || *duration < time.Second || *warmup < 0 {
|
|
panic("invalid load configuration")
|
|
}
|
|
transport := &http.Transport{MaxIdleConns: 2 * (*concurrency), MaxIdleConnsPerHost: 2 * (*concurrency), MaxConnsPerHost: 2 * (*concurrency), IdleConnTimeout: 30 * time.Second}
|
|
client := &http.Client{Transport: transport, Timeout: 6 * time.Second}
|
|
defer transport.CloseIdleConnections()
|
|
call := func(path string, body any, username, password, token string) map[string]any {
|
|
raw, _ := json.Marshal(body)
|
|
req, _ := http.NewRequest("POST", *base+path, bytes.NewReader(raw))
|
|
if body == nil {
|
|
req.Body = nil
|
|
req.ContentLength = 0
|
|
} else {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if username != "" {
|
|
req.SetBasicAuth(username, password)
|
|
}
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
response, err := client.Do(req)
|
|
if err != nil {
|
|
panic("bootstrap connection failed")
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != 201 {
|
|
panic(fmt.Sprintf("bootstrap status %d", response.StatusCode))
|
|
}
|
|
var value map[string]any
|
|
if json.NewDecoder(response.Body).Decode(&value) != nil {
|
|
panic("bootstrap invalid JSON")
|
|
}
|
|
return value
|
|
}
|
|
username := "load_" + nonce()[:20]
|
|
password := "Synthetic-" + nonce()
|
|
user := call("/api/v1/users", map[string]any{"username": username, "display_name": "Synthetic load", "password": password}, "", "", "")
|
|
session := call("/api/v1/auth/sessions", nil, username, password, "")
|
|
token := session["token"].(string)
|
|
chat := call("/api/v1/chats", map[string]any{"title": "Research load", "member_ids": []string{user["id"].(string)}}, "", "", token)
|
|
path := *base + "/api/v1/chats/" + chat["id"].(string) + "/messages"
|
|
body, _ := json.Marshal(map[string]string{"text": strings.Repeat("x", 128)})
|
|
batch := func(d time.Duration) (result, float64) {
|
|
start := time.Now()
|
|
deadline := start.Add(d)
|
|
values := make(chan result, *concurrency)
|
|
var group sync.WaitGroup
|
|
prefix := nonce()
|
|
for worker := 0; worker < *concurrency; worker++ {
|
|
group.Add(1)
|
|
go func(worker int) {
|
|
defer group.Done()
|
|
r := result{errors: map[string]int{}, instances: map[string]int{}}
|
|
for index := 0; time.Now().Before(deadline); index++ {
|
|
req, _ := http.NewRequest("POST", path, bytes.NewReader(body))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
req.Header.Set("Idempotency-Key", fmt.Sprintf("%s-%d-%d", prefix, worker, index))
|
|
begin := time.Now()
|
|
response, err := client.Do(req)
|
|
if err != nil {
|
|
r.errors["transport"]++
|
|
continue
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(response.Body, 65536))
|
|
response.Body.Close()
|
|
if response.StatusCode != 201 {
|
|
r.errors[fmt.Sprint(response.StatusCode)]++
|
|
continue
|
|
}
|
|
var message struct {
|
|
ID string `json:"id"`
|
|
}
|
|
if err != nil || json.Unmarshal(raw, &message) != nil || message.ID == "" {
|
|
r.errors["body"]++
|
|
continue
|
|
}
|
|
r.latencies = append(r.latencies, float64(time.Since(begin).Microseconds())/1000)
|
|
r.instances[response.Header.Get("X-Instance-Id")]++
|
|
}
|
|
values <- r
|
|
}(worker)
|
|
}
|
|
group.Wait()
|
|
close(values)
|
|
merged := result{errors: map[string]int{}, instances: map[string]int{}}
|
|
for r := range values {
|
|
merged.latencies = append(merged.latencies, r.latencies...)
|
|
for k, v := range r.errors {
|
|
merged.errors[k] += v
|
|
}
|
|
for k, v := range r.instances {
|
|
merged.instances[k] += v
|
|
}
|
|
}
|
|
return merged, time.Since(start).Seconds()
|
|
}
|
|
if *warmup > 0 {
|
|
batch(*warmup)
|
|
}
|
|
measured, elapsed := batch(*duration)
|
|
sort.Float64s(measured.latencies)
|
|
percentile := func(p float64) any {
|
|
if len(measured.latencies) == 0 {
|
|
return nil
|
|
}
|
|
return measured.latencies[int(math.Ceil(float64(len(measured.latencies))*p))-1]
|
|
}
|
|
failures := 0
|
|
for _, n := range measured.errors {
|
|
failures += n
|
|
}
|
|
report := map[string]any{"workload": "closed-loop POST 128 ASCII characters, unique keys, persistent connections, no retries", "concurrency": *concurrency, "warmup_seconds": warmup.Seconds(), "requested_duration_seconds": duration.Seconds(), "elapsed_seconds": elapsed, "successful_requests": len(measured.latencies), "failed_requests": failures, "errors": measured.errors, "successful_rps": float64(len(measured.latencies)) / elapsed, "latency_ms": map[string]any{"p50": percentile(.5), "p95": percentile(.95), "p99": percentile(.99)}, "instances": measured.instances, "note": "Success-only latency; closed-loop has coordinated omission. Counts HTTP confirmations, not unique DB commits."}
|
|
json.NewEncoder(os.Stdout).Encode(report)
|
|
if len(measured.latencies) == 0 {
|
|
os.Exit(1)
|
|
}
|
|
}
|