/
loadsim.go
73 lines (61 loc) · 1.18 KB
/
loadsim.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package loadsim
import (
"net/http"
"sync"
"time"
)
type Task struct {
Request *http.Request
Result chan Result
}
type Result struct {
StatusCode int
Start, WorkStart, End time.Time
Err error
AgentID string
}
func Simulate(agents []Agent, worker Worker, clock Clock, duration time.Duration) <-chan Result {
workerDone := make(chan struct{})
agentStop := make(chan struct{})
queue := make(chan Task)
results := make(chan Result)
var wg sync.WaitGroup
go func() {
worker.Run(queue)
close(workerDone)
}()
for _, agent := range agents {
wg.Add(1)
go func(a Agent) {
a.Run(queue, results, agentStop)
wg.Done()
}(agent)
}
go func() {
ticker, tickStop := clock.Tick()
start := clock.Now()
end := start.Add(duration)
for {
select {
case <-agentStop:
break
case now := <-ticker:
if now.Before(end) {
continue
}
close(agentStop)
}
break
}
close(tickStop)
// Wait for all agents to stop
wg.Wait()
// Close the queue to stop the worker
close(queue)
// Wait for the worker to stop
<-workerDone
// Stop listening for results
close(results)
}()
return results
}