// Command loadgen is a synthetic HTTP load generator for the lab3 experiment. // It is not part of the public API contract. It creates its own synthetic user // and chat through the load balancer, then measures message POST throughput // (or a mixed read/write profile) with per-second buckets and X-Instance-Id // attribution. // // The default profile is closed-loop: `-concurrency` workers each send the // next request as soon as the previous one finishes. `-rate` switches to an // open-loop target rate. Both are reported honestly as HTTP acknowledgement // throughput, not as a count of PostgreSQL commits. package main import ( "bytes" "context" "crypto/rand" "encoding/hex" "encoding/json" "flag" "fmt" "io" "math" "net/http" "os" "os/exec" "sort" "sync" "sync/atomic" "time" ) var version = "dev" type config struct { baseURL string duration time.Duration warmup time.Duration concurrency int rate float64 readRatio float64 timeout time.Duration output string retryUncertain bool note string stopInstance string stopScript string stopAfter time.Duration } type seriesBucket struct { Second int64 `json:"second"` Success int64 `json:"success"` Errors int64 `json:"errors"` P50 float64 `json:"p50_ms"` P95 float64 `json:"p95_ms"` P99 float64 `json:"p99_ms"` latency []float64 } type summary struct { Tool string `json:"tool"` Version string `json:"version"` StartedAt string `json:"started_at"` FinishedAt string `json:"finished_at"` MeasuredSeconds float64 `json:"measured_seconds"` WarmupSeconds float64 `json:"warmup_seconds"` Concurrency int `json:"concurrency"` RateLimit float64 `json:"rate_limit_per_second"` ReadRatio float64 `json:"read_ratio"` RetryUncertain bool `json:"retry_uncertain"` Profile string `json:"profile"` Successful int64 `json:"successful_requests"` Failed int64 `json:"failed_requests"` ErrorRatio float64 `json:"error_ratio"` SuccessfulRPS float64 `json:"successful_rps"` OfferedRPS float64 `json:"offered_rps"` LatencyMS latencySummary `json:"successful_latency_ms"` StatusCounts map[string]int64 `json:"status_counts"` Instances map[string]int64 `json:"instances"` AppVersions map[string]int64 `json:"app_versions"` Kinds map[string]int64 `json:"kinds"` Series []seriesBucket `json:"series"` Retries int64 `json:"uncertain_retries"` Violations []string `json:"idempotency_violations,omitempty"` Note string `json:"note"` Failover *failoverSummary `json:"failover,omitempty"` } type failoverSummary struct { TargetInstance string `json:"target_instance"` StopStartedAt string `json:"stop_started_at"` StopFinishedAt string `json:"stop_finished_at"` StopScriptExit int `json:"stop_script_exit"` StopDurationSeconds float64 `json:"stop_duration_seconds"` FirstSuccessAfterStopSec float64 `json:"first_success_after_stop_seconds"` FirstWriteAfterStopSec float64 `json:"first_write_after_stop_seconds"` FirstOtherSuccessSec float64 `json:"first_success_on_other_replica_seconds"` SuccessesAfterStop int64 `json:"successes_after_stop"` OtherSuccessesAfterStop int64 `json:"successes_on_other_replica_after_stop"` ErrorsAfterStop int64 `json:"errors_after_stop"` TargetResponsesAfterStop int64 `json:"target_responses_after_stop"` TargetLastResponseAt string `json:"target_last_response_at"` } type latencySummary struct { P50 float64 `json:"p50"` P95 float64 `json:"p95"` P99 float64 `json:"p99"` Max float64 `json:"max"` Mean float64 `json:"mean"` } func main() { cfg := config{} flag.StringVar(&cfg.baseURL, "base-url", "http://127.0.0.1:8083", "LB base URL") flag.DurationVar(&cfg.duration, "duration", 20*time.Second, "measured duration") flag.DurationVar(&cfg.warmup, "warmup", 5*time.Second, "warmup before measurement") flag.IntVar(&cfg.concurrency, "concurrency", 32, "workers (closed loop) or max in-flight (rate mode)") flag.Float64Var(&cfg.rate, "rate", 0, "open-loop target requests/second; 0 = closed loop") flag.Float64Var(&cfg.readRatio, "read-ratio", 0, "fraction of GET /users/me requests (failover probe)") flag.DurationVar(&cfg.timeout, "timeout", 5*time.Second, "per-request timeout") flag.StringVar(&cfg.output, "output", "", "write JSON summary to this path") flag.BoolVar(&cfg.retryUncertain, "retry-uncertain", false, "retry failed POSTs with the same Idempotency-Key (failover probe)") flag.StringVar(&cfg.note, "note", "", "free-form note stored in the summary") flag.StringVar(&cfg.stopInstance, "stop-instance", "", "failover probe: stop this X-Instance-Id during the run") flag.StringVar(&cfg.stopScript, "stop-script", "", "failover probe: executable that stops TARGET_INSTANCE_ID") flag.DurationVar(&cfg.stopAfter, "stop-after", 0, "failover probe: stop after this much measured time") flag.StringVar(&version, "version", "dev", "generator revision label") flag.Parse() if cfg.duration <= 0 || cfg.concurrency < 1 || cfg.readRatio < 0 || cfg.readRatio > 1 || cfg.rate < 0 { fmt.Fprintln(os.Stderr, "invalid load parameters") os.Exit(2) } client := &http.Client{ Timeout: cfg.timeout, Transport: &http.Transport{ MaxIdleConns: cfg.concurrency*2 + 8, MaxIdleConnsPerHost: cfg.concurrency*2 + 8, IdleConnTimeout: 30 * time.Second, DisableCompression: true, }, } actor, chat := bootstrap(client, cfg.baseURL) runID := randomHex(8) measureStart := time.Now().Add(cfg.warmup) deadline := measureStart.Add(cfg.duration) var failover *failoverState if cfg.stopScript != "" { target := cfg.stopInstance if target == "" { target = observeAnyInstance(client, cfg.baseURL, actor) } if target == "" { fail("no X-Instance-Id observed for failover target") } failover = &failoverState{target: target, script: cfg.stopScript} go failover.run(measureStart.Add(cfg.stopAfter)) } var ( mu sync.Mutex samples []result series = map[int64]*seriesBucket{} retries int64 ) worker := func(id int) { seq := 0 for { now := time.Now() if !now.Before(deadline) { return } // Warmup traffic is sent but excluded from every summary number. measured := !now.Before(measureStart) kind := "write" if cfg.readRatio > 0 && float64((id+seq)%1000)/1000.0 < cfg.readRatio { kind = "read" } start := time.Now() result := oneRequest(client, cfg.baseURL, actor, chat, kind, fmt.Sprintf("%s-%d-%d", runID, id, seq), cfg.retryUncertain) elapsed := time.Since(start) seq++ if !measured { continue } result.at = start result.done = time.Now() result.latency = elapsed mu.Lock() samples = append(samples, result) if result.err != "" && result.ok { retries++ } bucket := series[start.Unix()] if bucket == nil { bucket = &seriesBucket{Second: start.Unix()} series[start.Unix()] = bucket } if result.ok { bucket.Success++ bucket.latency = append(bucket.latency, float64(result.latency.Microseconds())/1000.0) } else { bucket.Errors++ } mu.Unlock() if cfg.rate > 0 { // Spread a fixed offered rate across workers. This is a // best-effort pacing, not a hard scheduler; lateness is // visible in the latency distribution. interval := time.Duration(float64(time.Second) * float64(cfg.concurrency) / cfg.rate) if sleep := interval - time.Since(start); sleep > 0 { time.Sleep(sleep) } } } } var wg sync.WaitGroup for i := 0; i < cfg.concurrency; i++ { wg.Add(1) go func(id int) { defer wg.Done() worker(id) }(i) } wg.Wait() finished := time.Now() measuredSeconds := finished.Sub(measureStart).Seconds() var failoverSnapshot *failoverState if failover != nil { failoverSnapshot = failover } sum := summarize(cfg, runID, measureStart, finished, measuredSeconds, samples, series, atomic.LoadInt64(&retries), failoverSnapshot) if cfg.output != "" { data, _ := json.MarshalIndent(sum, "", " ") if err := os.WriteFile(cfg.output, append(data, '\n'), 0o644); err != nil { fmt.Fprintln(os.Stderr, "cannot write output:", err) os.Exit(1) } } encoded, _ := json.MarshalIndent(sum, "", " ") fmt.Println(string(encoded)) if sum.Successful == 0 { os.Exit(1) } } type credentials struct { token string user string } type chatInfo struct { id string } type result struct { at time.Time done time.Time latency time.Duration ok bool status int instance string appVer string kind string key string message string err string } func oneRequest(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string, retry bool) result { deadline := time.Now().Add(10 * time.Second) for { res := requestOnce(client, base, actor, chat, kind, key) if res.ok || !retry || kind != "write" || time.Now().After(deadline) { return res } // A timeout or LB 502/503 after SIGTERM is an uncertain result. The // same key is safe to retry only because the server's idempotency // record and message are committed atomically. res.err = "retry:" + res.err time.Sleep(30 * time.Millisecond) } } func requestOnce(client *http.Client, base string, actor credentials, chat chatInfo, kind, key string) result { method, path := http.MethodPost, "/api/v1/chats/"+chat.id+"/messages" var body io.Reader if kind == "read" { method, path = http.MethodGet, "/api/v1/users/me" } else { payload, _ := json.Marshal(map[string]string{"text": "load " + key}) body = bytes.NewReader(payload) } req, err := http.NewRequestWithContext(context.Background(), method, base+path, body) if err != nil { return result{status: 0, err: "build_request"} } req.Header.Set("Authorization", "Bearer "+actor.token) if kind == "write" { req.Header.Set("Content-Type", "application/json") req.Header.Set("Idempotency-Key", key) } response, err := client.Do(req) if err != nil { return result{status: 0, err: "transport"} } defer response.Body.Close() data, readErr := io.ReadAll(io.LimitReader(response.Body, 1<<20)) res := result{ status: response.StatusCode, instance: response.Header.Get("X-Instance-Id"), appVer: response.Header.Get("X-App-Version"), kind: kind, key: key, } if readErr != nil { res.err = "read_body" return res } if response.StatusCode == http.StatusCreated || response.StatusCode == http.StatusOK { res.ok = true if kind == "write" { var message struct { ID string `json:"id"` } if err := json.Unmarshal(data, &message); err != nil || message.ID == "" { res.ok = false res.err = "bad_json" } else { res.message = message.ID } } return res } res.err = "status" return res } func bootstrap(client *http.Client, base string) (credentials, chatInfo) { // /health/ready is retried until the stack is up. waitReady(client, base) username := "lg_" + randomHex(10) password := "Loadgen-" + randomHex(12) registered := struct { ID string `json:"id"` }{} postJSON(client, base+"/api/v1/users", "", map[string]string{ "username": username, "display_name": "Load generator", "password": password, }, ®istered) basic := basicAuth(username, password) session := struct { Token string `json:"token"` }{} postJSON(client, base+"/api/v1/auth/sessions", "Basic "+basic, nil, &session) if session.Token == "" || registered.ID == "" { fail("bootstrap failed") } chat := struct { ID string `json:"id"` }{} postJSON(client, base+"/api/v1/chats", "Bearer "+session.Token, map[string]interface{}{ "title": "loadgen " + randomHex(6), "member_ids": []string{registered.ID}, }, &chat) if chat.ID == "" { fail("chat bootstrap failed") } return credentials{token: session.Token, user: registered.ID}, chatInfo{id: chat.ID} } func waitReady(client *http.Client, base string) { deadline := time.Now().Add(90 * time.Second) for time.Now().Before(deadline) { response, err := client.Get(base + "/health/ready") if err == nil { io.Copy(io.Discard, response.Body) response.Body.Close() if response.StatusCode == http.StatusOK { return } } time.Sleep(250 * time.Millisecond) } fail("stack did not become ready") } func postJSON(client *http.Client, url, authorization string, body interface{}, out interface{}) { var reader io.Reader if body != nil { data, _ := json.Marshal(body) reader = bytes.NewReader(data) } req, err := http.NewRequest(http.MethodPost, url, reader) if err != nil { fail("build bootstrap request") } if body != nil { req.Header.Set("Content-Type", "application/json") } if authorization != "" { req.Header.Set("Authorization", authorization) } response, err := client.Do(req) if err != nil { fail("bootstrap transport failure") } defer response.Body.Close() data, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20)) if response.StatusCode != http.StatusCreated { fail(fmt.Sprintf("bootstrap status %d", response.StatusCode)) } if out != nil { if err := json.Unmarshal(data, out); err != nil { fail("bootstrap JSON") } } } func basicAuth(username, password string) string { const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" raw := []byte(username + ":" + password) var encoded []byte for i := 0; i < len(raw); i += 3 { var chunk [3]byte n := copy(chunk[:], raw[i:]) value := uint(chunk[0])<<16 | uint(chunk[1])<<8 | uint(chunk[2]) encoded = append(encoded, alphabet[value>>18&63], alphabet[value>>12&63]) if n > 1 { encoded = append(encoded, alphabet[value>>6&63]) } else { encoded = append(encoded, '=') } if n > 2 { encoded = append(encoded, alphabet[value&63]) } else { encoded = append(encoded, '=') } } return string(encoded) } func summarize(cfg config, runID string, start, finished time.Time, seconds float64, samples []result, series map[int64]*seriesBucket, retries int64, failover *failoverState) summary { sum := summary{ Tool: "mtusi-lab3-loadgen", Version: version, StartedAt: start.UTC().Format(time.RFC3339Nano), FinishedAt: finished.UTC().Format(time.RFC3339Nano), MeasuredSeconds: round(seconds, 3), WarmupSeconds: cfg.warmup.Seconds(), Concurrency: cfg.concurrency, RateLimit: cfg.rate, ReadRatio: cfg.readRatio, RetryUncertain: cfg.retryUncertain, Profile: "closed-loop", StatusCounts: map[string]int64{}, Instances: map[string]int64{}, AppVersions: map[string]int64{}, Kinds: map[string]int64{}, Retries: retries, Note: cfg.note, } if cfg.rate > 0 { sum.Profile = fmt.Sprintf("open-loop target %.1f req/s (best effort)", cfg.rate) } sum.Note = cfg.note + "; synthetic messages created by loadgen, no retries unless -retry-uncertain" var latencies []float64 idByKey := map[string]string{} summaryFailover := buildFailoverSummary(failover, samples) for _, item := range samples { sum.Kinds[item.kind]++ statusKey := fmt.Sprintf("%d", item.status) if item.status == 0 { statusKey = "error:" + item.err } sum.StatusCounts[statusKey]++ if item.ok { sum.Successful++ latencies = append(latencies, float64(item.latency.Microseconds())/1000.0) if item.instance == "" { item.instance = "(missing)" } sum.Instances[item.instance]++ ver := item.appVer if ver == "" { ver = "(missing)" } sum.AppVersions[ver]++ if item.kind == "write" && item.message != "" { if previous, seen := idByKey[item.key]; seen && previous != item.message { sum.Violations = append(sum.Violations, "same key returned different message ids") } idByKey[item.key] = item.message } } else { sum.Failed++ } } sum.OfferedRPS = round(float64(sum.Successful+sum.Failed)/seconds, 3) sum.SuccessfulRPS = round(float64(sum.Successful)/seconds, 3) if total := sum.Successful + sum.Failed; total > 0 { sum.ErrorRatio = round(float64(sum.Failed)/float64(total), 6) } sort.Float64s(latencies) sum.LatencyMS = latencyPercentiles(latencies) sum.Failover = summaryFailover keys := make([]int64, 0, len(series)) for second := range series { keys = append(keys, second) } sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] }) for _, second := range keys { bucket := series[second] sort.Float64s(bucket.latency) bucket.P50 = percentile(bucket.latency, 0.50) bucket.P95 = percentile(bucket.latency, 0.95) bucket.P99 = percentile(bucket.latency, 0.99) sum.Series = append(sum.Series, *bucket) } return sum } func percentile(sorted []float64, p float64) float64 { if len(sorted) == 0 { return 0 } index := int(math.Ceil(p*float64(len(sorted)))) - 1 if index < 0 { index = 0 } if index >= len(sorted) { index = len(sorted) - 1 } return round(sorted[index], 3) } func latencyPercentiles(sorted []float64) latencySummary { if len(sorted) == 0 { return latencySummary{} } pick := func(p float64) float64 { return percentile(sorted, p) } var total float64 for _, value := range sorted { total += value } return latencySummary{ P50: pick(0.50), P95: pick(0.95), P99: pick(0.99), Max: round(sorted[len(sorted)-1], 3), Mean: round(total/float64(len(sorted)), 3), } } func round(value float64, digits int) float64 { scale := math.Pow(10, float64(digits)) return math.Round(value*scale) / scale } func randomHex(n int) string { buf := make([]byte, n) if _, err := rand.Read(buf); err != nil { fail("random") } return hex.EncodeToString(buf) } func fail(message string) { fmt.Fprintln(os.Stderr, "loadgen:", message) os.Exit(2) } type failoverState struct { target string script string mu sync.Mutex started time.Time finished time.Time exitCode int err string } func (f *failoverState) run(at time.Time) { if delay := time.Until(at); delay > 0 { time.Sleep(delay) } f.mu.Lock() f.started = time.Now() f.mu.Unlock() command := exec.Command(f.script) command.Env = append(os.Environ(), "TARGET_INSTANCE_ID="+f.target) command.Stdout = io.Discard command.Stderr = io.Discard err := command.Run() f.mu.Lock() defer f.mu.Unlock() f.finished = time.Now() if err == nil { f.exitCode = 0 return } if exitError, ok := err.(*exec.ExitError); ok { f.exitCode = exitError.ExitCode() } else { f.exitCode = -1 f.err = err.Error() } } func (f *failoverState) snapshot() failoverState { f.mu.Lock() defer f.mu.Unlock() return failoverState{ target: f.target, started: f.started, finished: f.finished, exitCode: f.exitCode, err: f.err, } } func observeAnyInstance(client *http.Client, base string, actor credentials) string { deadline := time.Now().Add(30 * time.Second) for time.Now().Before(deadline) { req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/users/me", nil) req.Header.Set("Authorization", "Bearer "+actor.token) response, err := client.Do(req) if err == nil { io.Copy(io.Discard, response.Body) response.Body.Close() if instance := response.Header.Get("X-Instance-Id"); instance != "" { return instance } } time.Sleep(100 * time.Millisecond) } return "" } func buildFailoverSummary(failover *failoverState, samples []result) *failoverSummary { if failover == nil { return nil } state := failover.snapshot() if state.started.IsZero() { return nil } summary := &failoverSummary{ TargetInstance: state.target, StopStartedAt: state.started.UTC().Format(time.RFC3339Nano), StopFinishedAt: state.finished.UTC().Format(time.RFC3339Nano), StopScriptExit: state.exitCode, StopDurationSeconds: round(state.finished.Sub(state.started).Seconds(), 3), FirstSuccessAfterStopSec: -1, FirstWriteAfterStopSec: -1, FirstOtherSuccessSec: -1, } var firstSuccess, firstWrite, firstOther time.Time var lastTarget time.Time for _, item := range samples { if item.instance == state.target && item.done.After(lastTarget) { lastTarget = item.done } if !item.at.After(state.started) { continue } if item.ok { summary.SuccessesAfterStop++ if firstSuccess.IsZero() || item.done.Before(firstSuccess) { firstSuccess = item.done } if item.kind == "write" && (firstWrite.IsZero() || item.done.Before(firstWrite)) { firstWrite = item.done } if item.instance != state.target { summary.OtherSuccessesAfterStop++ if firstOther.IsZero() || item.done.Before(firstOther) { firstOther = item.done } } } else { summary.ErrorsAfterStop++ } if item.at.After(state.finished.Add(500*time.Millisecond)) && item.instance == state.target { summary.TargetResponsesAfterStop++ } } if !firstSuccess.IsZero() { summary.FirstSuccessAfterStopSec = round(firstSuccess.Sub(state.started).Seconds(), 3) } if !firstWrite.IsZero() { summary.FirstWriteAfterStopSec = round(firstWrite.Sub(state.started).Seconds(), 3) } if !firstOther.IsZero() { summary.FirstOtherSuccessSec = round(firstOther.Sub(state.started).Seconds(), 3) } if !lastTarget.IsZero() { summary.TargetLastResponseAt = lastTarget.UTC().Format(time.RFC3339Nano) } return summary }