forked from mtusi2026/mtusi2026lab3
205 lines
6.8 KiB
Go
205 lines
6.8 KiB
Go
// A fixed-rate HTTP workload for the lab 3 scaling experiment.
|
|
// Credentials are read from a local file and never written to output.
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type credentials struct {
|
|
Token string `json:"token"`
|
|
ChatID string `json:"chat_id"`
|
|
}
|
|
|
|
type result struct {
|
|
kind string
|
|
status int
|
|
latency time.Duration
|
|
lag time.Duration
|
|
full time.Duration
|
|
instanceID string
|
|
}
|
|
|
|
type percentiles struct {
|
|
P50 float64 `json:"p50"`
|
|
P95 float64 `json:"p95"`
|
|
P99 float64 `json:"p99"`
|
|
}
|
|
|
|
func quantiles(values []float64) percentiles {
|
|
if len(values) == 0 {
|
|
return percentiles{}
|
|
}
|
|
sort.Float64s(values)
|
|
get := func(p float64) float64 {
|
|
index := int(math.Ceil(p*float64(len(values)))) - 1
|
|
return math.Round(values[index]*1000) / 1000
|
|
}
|
|
return percentiles{P50: get(.50), P95: get(.95), P99: get(.99)}
|
|
}
|
|
|
|
func main() {
|
|
baseURL := flag.String("base-url", "", "public load balancer URL")
|
|
authFile := flag.String("auth-file", "", "local JSON file with token and chat_id")
|
|
rate := flag.Float64("rate", 0, "scheduled requests per second")
|
|
duration := flag.Duration("duration", 20*time.Second, "scheduling window")
|
|
maxInFlight := flag.Int("max-inflight", 256, "maximum concurrent requests")
|
|
timeout := flag.Duration("timeout", 5*time.Second, "per-request timeout")
|
|
flag.Parse()
|
|
if *baseURL == "" || *authFile == "" || *rate <= 0 || *duration <= 0 || *maxInFlight <= 0 || *timeout <= 0 {
|
|
fmt.Fprintln(os.Stderr, "base-url, auth-file, positive rate, duration, max-inflight and timeout are required")
|
|
os.Exit(2)
|
|
}
|
|
content, err := os.ReadFile(*authFile)
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "could not read auth file")
|
|
os.Exit(2)
|
|
}
|
|
var auth credentials
|
|
if err := json.Unmarshal(content, &auth); err != nil || auth.Token == "" || auth.ChatID == "" {
|
|
fmt.Fprintln(os.Stderr, "invalid auth file")
|
|
os.Exit(2)
|
|
}
|
|
nonce := make([]byte, 8)
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
fmt.Fprintln(os.Stderr, "could not create workload identifier")
|
|
os.Exit(2)
|
|
}
|
|
runID := hex.EncodeToString(nonce)
|
|
payload, _ := json.Marshal(map[string]string{"text": "grade5-" + runID})
|
|
transport := &http.Transport{
|
|
MaxIdleConns: *maxInFlight,
|
|
MaxIdleConnsPerHost: *maxInFlight,
|
|
IdleConnTimeout: 90 * time.Second,
|
|
}
|
|
client := &http.Client{Transport: transport}
|
|
defer transport.CloseIdleConnections()
|
|
url := strings.TrimRight(*baseURL, "/") + "/api/v1/chats/" + auth.ChatID + "/messages"
|
|
count := int(math.Round(*rate * duration.Seconds()))
|
|
if count <= 0 || count > 2_000_000 {
|
|
fmt.Fprintln(os.Stderr, "request count is outside 1..2000000")
|
|
os.Exit(2)
|
|
}
|
|
results := make(chan result, count)
|
|
semaphore := make(chan struct{}, *maxInFlight)
|
|
var workers sync.WaitGroup
|
|
started := time.Now()
|
|
for i := 0; i < count; i++ {
|
|
planned := started.Add(time.Duration(float64(i) / *rate * float64(time.Second)))
|
|
if delay := time.Until(planned); delay > 0 {
|
|
time.Sleep(delay)
|
|
}
|
|
lag := time.Since(planned)
|
|
if lag > 250*time.Millisecond {
|
|
results <- result{kind: "dropped_scheduler", lag: lag}
|
|
continue
|
|
}
|
|
select {
|
|
case semaphore <- struct{}{}:
|
|
default:
|
|
results <- result{kind: "dropped_inflight", lag: lag}
|
|
continue
|
|
}
|
|
workers.Add(1)
|
|
go func(sequence int, planned time.Time) {
|
|
defer workers.Done()
|
|
defer func() { <-semaphore }()
|
|
scheduleLag := time.Since(planned)
|
|
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
|
defer cancel()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
|
if err != nil {
|
|
results <- result{kind: "client_request", lag: scheduleLag}
|
|
return
|
|
}
|
|
req.Header.Set("Accept", "application/json")
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+auth.Token)
|
|
req.Header.Set("Idempotency-Key", "g5-"+runID+"-"+strconv.Itoa(sequence))
|
|
requestStarted := time.Now()
|
|
response, err := client.Do(req)
|
|
if err != nil {
|
|
kind := "connection"
|
|
var networkError net.Error
|
|
if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &networkError) && networkError.Timeout() {
|
|
kind = "timeout"
|
|
}
|
|
results <- result{kind: kind, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned)}
|
|
return
|
|
}
|
|
_, readErr := io.Copy(io.Discard, io.LimitReader(response.Body, 1<<20))
|
|
response.Body.Close()
|
|
if readErr != nil {
|
|
results <- result{kind: "response_read", status: response.StatusCode, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned)}
|
|
return
|
|
}
|
|
results <- result{kind: "response", status: response.StatusCode, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned), instanceID: response.Header.Get("X-Instance-Id")}
|
|
}(i, planned)
|
|
}
|
|
workers.Wait()
|
|
close(results)
|
|
wall := time.Since(started)
|
|
counts := map[string]int{}
|
|
instances := map[string]int{}
|
|
latencies := make([]float64, 0, count)
|
|
lags := make([]float64, 0, count)
|
|
fullLatencies := make([]float64, 0, count)
|
|
success := 0
|
|
for item := range results {
|
|
if item.full > 0 {
|
|
fullLatencies = append(fullLatencies, float64(item.full)/float64(time.Millisecond))
|
|
}
|
|
if item.kind == "response" && item.status == http.StatusCreated {
|
|
success++
|
|
latencies = append(latencies, float64(item.latency)/float64(time.Millisecond))
|
|
if item.instanceID != "" {
|
|
instances[item.instanceID]++
|
|
}
|
|
} else if item.kind == "response" {
|
|
counts["http_"+strconv.Itoa(item.status)]++
|
|
} else {
|
|
counts[item.kind]++
|
|
}
|
|
lags = append(lags, float64(item.lag)/float64(time.Millisecond))
|
|
}
|
|
report := map[string]any{
|
|
"workload": "fixed-rate POST messages, unique Idempotency-Key, no retries",
|
|
"started_at_utc": started.UTC().Format(time.RFC3339Nano),
|
|
"run_id": runID,
|
|
"scheduled_rps": *rate,
|
|
"scheduled_duration_s": duration.Seconds(),
|
|
"wall_duration_s": math.Round(wall.Seconds()*1000) / 1000,
|
|
"scheduled_requests": count,
|
|
"successful_requests": success,
|
|
"failure_counts": counts,
|
|
"success_ratio": math.Round(float64(success)/float64(count)*1_000_000) / 1_000_000,
|
|
"successful_rps_window": math.Round(float64(success)/duration.Seconds()*1000) / 1000,
|
|
"successful_rps_wall": math.Round(float64(success)/wall.Seconds()*1000) / 1000,
|
|
"success_latency_ms": quantiles(latencies),
|
|
"schedule_lag_ms": quantiles(lags),
|
|
"completed_full_latency_ms": quantiles(fullLatencies),
|
|
"instance_responses": instances,
|
|
"max_inflight": *maxInFlight,
|
|
"request_timeout_s": timeout.Seconds(),
|
|
}
|
|
output, _ := json.MarshalIndent(report, "", " ")
|
|
fmt.Println(string(output))
|
|
}
|