tools/stress/main.go (9874B)
1 // Command stress drives disposable e2e servers through the real game protocol. 2 package main 3 4 import ( 5 "bytes" 6 "context" 7 "encoding/json" 8 "flag" 9 "fmt" 10 "io" 11 "net/http" 12 "os" 13 "os/signal" 14 "runtime" 15 "strings" 16 "sync" 17 "syscall" 18 "time" 19 ) 20 21 type placement struct { 22 Activity string 23 Weight int 24 Playfield uint32 25 Position [3]float32 26 Rotation [4]float32 27 } 28 29 type visitor struct { 30 ID uint32 31 Cookie string 32 Place placement 33 } 34 35 type event struct { 36 playfield uint32 37 kind string 38 at time.Time 39 elapsed time.Duration 40 missed int 41 packets, bytes int 42 err error 43 } 44 45 func main() { 46 address := flag.String("url", "", "URL of a disposable server built with -tags=e2e") 47 clients := flag.Int("clients", 100, "number of clients, up to 20000") 48 ramp := flag.Duration("ramp", time.Minute, "time over which connections are scheduled") 49 duration := flag.Duration("duration", time.Minute, "steady load duration after the ramp") 50 scenario := flag.String("scenario", "tools/stress/distributed.json", "JSON file of weighted spawn locations and activities") 51 flag.Parse() 52 if *address == "" || *clients < 1 || *clients > 20000 || *ramp <= 0 || *duration <= 0 || flag.NArg() != 0 { 53 fmt.Fprintln(os.Stderr, "provide -url, 1..20000 clients, and positive ramp/duration") 54 os.Exit(2) 55 } 56 ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) 57 defer cancel() 58 if err := run(ctx, strings.TrimRight(*address, "/"), *clients, *ramp, *duration, *scenario); err != nil { 59 fmt.Fprintln(os.Stderr, err) 60 os.Exit(1) 61 } 62 } 63 64 func run(ctx context.Context, address string, count int, ramp, duration time.Duration, scenario string) error { 65 data, err := os.ReadFile(scenario) 66 if err != nil { 67 return err 68 } 69 var places []placement 70 if err := json.Unmarshal(data, &places); err != nil { 71 return err 72 } 73 weight := 0 74 for _, place := range places { 75 if place.Activity != "crowd" && place.Activity != "idle" && place.Activity != "walk" { 76 return fmt.Errorf("each placement needs Activity crowd, idle or walk") 77 } 78 if place.Weight <= 0 || place.Playfield == 0 || place.Rotation == [4]float32{} { 79 return fmt.Errorf("each placement needs positive Weight, Playfield and a nonzero Rotation") 80 } 81 weight += place.Weight 82 } 83 if weight == 0 { 84 return fmt.Errorf("scenario has no placements") 85 } 86 // Provisioning is separate from the measured ramp. Fixture requests never 87 // mutate connected players. Every run should use a fresh disposable database. 88 started := time.Now() 89 visitors := make([]visitor, count) 90 httpClient := &http.Client{Timeout: 30 * time.Second} 91 defer httpClient.CloseIdleConnections() 92 for index := range visitors { 93 place, slot := places[0], index%weight 94 for _, candidate := range places { 95 place = candidate 96 if slot < candidate.Weight { 97 break 98 } 99 slot -= candidate.Weight 100 } 101 visitors[index], err = provision(ctx, httpClient, address, place) 102 if err != nil { 103 return fmt.Errorf("provision client %d: %w", index, err) 104 } 105 if (index+1)%100 == 0 { 106 fmt.Fprintf(os.Stderr, "provisioned %d/%d\n", index+1, count) 107 } 108 } 109 json.NewEncoder(os.Stdout).Encode(map[string]any{"phase": "provisioned", "clients": count, "seconds": time.Since(started).Seconds(), "placements": places}) 110 111 started = time.Now() 112 load, cancel := context.WithDeadline(ctx, started.Add(ramp+duration)) 113 defer cancel() 114 events := make(chan event, 1024) 115 var workers sync.WaitGroup 116 for index, person := range visitors { 117 workers.Add(1) 118 go func(index int, person visitor) { 119 defer workers.Done() 120 scheduled := started.Add(time.Duration(index) * ramp / time.Duration(count)) 121 if !waitUntil(load, scheduled) { 122 events <- event{playfield: person.Place.Playfield, kind: "not_started"} 123 return 124 } 125 events <- event{playfield: person.Place.Playfield, kind: "attempted"} 126 if err := exercise(load, address, person, scheduled, events); err != nil && load.Err() == nil { 127 events <- event{playfield: person.Place.Playfield, kind: "failed", err: fmt.Errorf("client %d: %w", person.ID, err)} 128 } 129 }(index, person) 130 } 131 go func() { workers.Wait(); close(events) }() 132 err = collect(os.Stdout, events, started, ramp) 133 if ctx.Err() != nil { 134 return ctx.Err() 135 } 136 return err 137 } 138 139 func provision(ctx context.Context, client *http.Client, address string, place placement) (visitor, error) { 140 person := visitor{Place: place} 141 request, err := http.NewRequestWithContext(ctx, "POST", address+"/browser-launch", nil) 142 if err != nil { 143 return person, err 144 } 145 response, err := client.Do(request) 146 if err != nil { 147 return person, err 148 } 149 defer response.Body.Close() 150 body, err := io.ReadAll(io.LimitReader(response.Body, 4096)) 151 if err != nil { 152 return person, err 153 } 154 if response.StatusCode != http.StatusOK { 155 return person, fmt.Errorf("launch: %s: %s", response.Status, body) 156 } 157 for _, cookie := range response.Cookies() { 158 if cookie.Name == "ao_client" { 159 person.Cookie = cookie.Name + "=" + cookie.Value 160 } 161 } 162 if person.Cookie == "" { 163 return person, fmt.Errorf("launch did not create a visitor cookie") 164 } 165 data, err := json.Marshal(struct { 166 Playfield uint32 167 Position [3]float32 168 Rotation [4]float32 169 }{place.Playfield, place.Position, place.Rotation}) 170 if err != nil { 171 return person, err 172 } 173 request, err = http.NewRequestWithContext(ctx, "POST", address+"/_test/player/position", bytes.NewReader(data)) 174 if err != nil { 175 return person, err 176 } 177 request.Header.Set("Cookie", person.Cookie) 178 request.Header.Set("Content-Type", "application/json") 179 response, err = client.Do(request) 180 if err != nil { 181 return person, err 182 } 183 defer response.Body.Close() 184 if response.StatusCode != http.StatusOK { 185 body, _ := io.ReadAll(io.LimitReader(response.Body, 4096)) 186 return person, fmt.Errorf("fixture: %s: %s", response.Status, body) 187 } 188 if err := json.NewDecoder(response.Body).Decode(&person); err != nil { 189 return person, err 190 } 191 if person.ID == 0 { 192 return person, fmt.Errorf("fixture returned no player ID") 193 } 194 return person, nil 195 } 196 197 func waitUntil(ctx context.Context, at time.Time) bool { 198 timer := time.NewTimer(time.Until(at)) 199 defer timer.Stop() 200 select { 201 case <-timer.C: 202 return true 203 case <-ctx.Done(): 204 return false 205 } 206 } 207 208 // Histograms use millisecond buckets, capped at 60 seconds. Memory stays bounded 209 // at 20k connections; the last bucket explicitly includes larger observations. 210 type histogram [60001]uint64 211 212 func (h *histogram) add(elapsed time.Duration) { 213 h[min(max(elapsed.Milliseconds(), 0), 60000)]++ 214 } 215 216 func (h *histogram) percentiles() map[string]int { 217 var total uint64 218 for _, count := range h { 219 total += count 220 } 221 result := map[string]int{} 222 for _, percentile := range []int{50, 95, 99} { 223 var seen uint64 224 for ms, count := range h { 225 seen += count 226 if total != 0 && seen >= (total*uint64(percentile)+99)/100 { 227 result[fmt.Sprintf("p%d_ms", percentile)] = ms 228 break 229 } 230 } 231 } 232 return result 233 } 234 235 type measurements struct { 236 counts map[string]int 237 admission, action, scheduled, steady histogram 238 } 239 240 func (measurements *measurements) add(result event, steadyAt time.Time) { 241 measurements.counts[result.kind]++ 242 measurements.counts["missed_actions"] += result.missed 243 measurements.counts["received_packets"] += result.packets 244 measurements.counts["received_bytes"] += result.bytes 245 switch result.kind { 246 case "ready": 247 measurements.admission.add(result.elapsed) 248 case "action": 249 measurements.action.add(result.elapsed) 250 if !result.at.Before(steadyAt) { 251 measurements.steady.add(result.elapsed) 252 measurements.counts["steady_actions"]++ 253 } 254 case "scheduled_action": 255 measurements.scheduled.add(result.elapsed) 256 } 257 } 258 259 func (measurements *measurements) report() map[string]any { 260 return map[string]any{"counts": measurements.counts, 261 "active": measurements.counts["ready"] - measurements.counts["disconnected"], 262 "admission": measurements.admission.percentiles(), "action": measurements.action.percentiles(), 263 "scheduled_action": measurements.scheduled.percentiles(), "steady_action": measurements.steady.percentiles()} 264 } 265 266 func collect(output io.Writer, events <-chan event, started time.Time, ramp time.Duration) error { 267 total := measurements{counts: make(map[string]int)} 268 zones := make(map[uint32]*measurements) 269 steadyAt := started.Add(ramp) 270 var outputError error 271 ticker := time.NewTicker(5 * time.Second) 272 defer ticker.Stop() 273 write := func(phase string) error { 274 var memory runtime.MemStats 275 runtime.ReadMemStats(&memory) 276 report := total.report() 277 report["phase"], report["seconds"] = phase, time.Since(started).Seconds() 278 report["generator_heap_bytes"], report["generator_goroutines"] = memory.HeapAlloc, runtime.NumGoroutine() 279 zoneReports := make(map[uint32]map[string]any, len(zones)) 280 for playfield, zone := range zones { 281 zoneReports[playfield] = zone.report() 282 } 283 report["zones"] = zoneReports 284 return json.NewEncoder(output).Encode(report) 285 } 286 for { 287 select { 288 case result, ok := <-events: 289 if !ok { 290 if err := write("complete"); err != nil { 291 return err 292 } 293 if outputError != nil { 294 return outputError 295 } 296 if total.counts["failed"] != 0 || total.counts["not_started"] != 0 || total.counts["attempted"] != total.counts["ready"] { 297 return fmt.Errorf("load incomplete: %d failed, %d not started, %d unready", total.counts["failed"], total.counts["not_started"], total.counts["attempted"]-total.counts["ready"]) 298 } 299 return nil 300 } 301 total.add(result, steadyAt) 302 if zones[result.playfield] == nil { 303 zones[result.playfield] = &measurements{counts: make(map[string]int)} 304 } 305 zones[result.playfield].add(result, steadyAt) 306 if result.kind == "failed" && total.counts["failed"] <= 10 { 307 fmt.Fprintln(os.Stderr, result.err) 308 } 309 case <-ticker.C: 310 if outputError == nil { 311 outputError = write("running") 312 } 313 } 314 } 315 }