-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
212 lines (168 loc) · 4.82 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
"bufio"
"context"
"fmt"
"log/slog"
"os"
"sync"
"time"
"github.com/josephcopenhaver/loadtester-go/v5/loadtester"
)
type task struct{}
func (t *task) Do(ctx context.Context, workerID int) error {
return nil
}
type myTaskReader struct{}
func (tr *myTaskReader) ReadTasks(p []loadtester.Doer) int {
// make sure you only fill up to len
// filling less than len will signal that the loadtest is over
var i int
for i < len(p) {
p[i] = &task{}
i++
}
return i
}
func newMyTaskReader() *myTaskReader {
return &myTaskReader{}
}
func main() {
var logger loadtester.StructuredLogger
{
level := slog.LevelInfo
if s := os.Getenv("LOG_LEVEL"); s != "" {
var v slog.Level
err := v.UnmarshalText([]byte(s))
if err != nil {
panic(fmt.Errorf("failed to parse LOG_LEVEL environment variable: %w", err))
}
level = v
}
v, err := loadtester.NewLogger(level)
if err != nil {
panic(err)
}
slog.SetDefault(v)
logger = v
}
ctx, cancel := loadtester.RootContext(logger)
defer cancel()
tr := newMyTaskReader()
numWorkers := 5
op := loadtester.NewOpts()
lt, err := loadtester.NewLoadtest(
op.TaskReader(tr),
op.Logger(logger),
op.NumWorkers(numWorkers),
op.NumIntervalTasks(25),
op.Interval(1*time.Second),
op.Retry(false), // default is true; not required for this example since no tasks can be retried, plus saves some minor compute and disk io
// op.MetricsLatencyPercentile(true), // default is false
// op.MetricsLatencyVarianceEnabled(true), // default is false
// op.FlushRetriesOnShutdown(true), // default is false
// op.MetricsCsv(false) // default is true; set to false to stop creating a metrics.csv file on loadtest run
)
if err != nil {
panic(err)
}
// TODO: defer any loadtest cleanup here
var wg sync.WaitGroup
defer func() {
// just to ensure all child workers exit before any cleanup runs
//
// it's duplicated on the positive path and does no harm to be called twice on the positive path
logger.LogAttrs(ctx, slog.LevelDebug, "post-wg-decl: waiting for all goroutines to finish")
wg.Wait()
logger.LogAttrs(ctx, slog.LevelDebug, "post-wg-decl: all goroutines finished")
}()
//
// start loadtest routine
//
wg.Add(1)
go func() {
defer wg.Done()
// ensure the parent context is canceled when this critical goroutine ends
defer cancel()
// note, if you do not want to support user input then just end main by starting
// the loadtest and don't use a wait group or goroutine for it
if err := lt.Run(ctx); err != nil {
logger.LogAttrs(ctx, slog.LevelError,
"loadtest errored",
slog.Any("error", err),
slog.Bool("panic", true),
)
panic(err)
}
}()
//
// support user input to adjust the loadtest config
//
// define input handling channel and closer
inputChan, closeInputChan := func() (chan string, func()) {
c := make(chan string)
closer := sync.OnceFunc(func() {
close(c)
})
return c, closer
}()
//
// start example user line input handling routines
//
// routine that listens for context done and closes input channel
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
closeInputChan()
}()
// routine that offers user strings to input channel
go func() {
// note routine intentionally allowed to leak because
// there is no way to make the reader context aware
defer closeInputChan()
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanLines)
for sc.Scan() {
s := sc.Text()
if s == "" {
continue
}
// note it's possible for this channel
// write to panic due to the user
// doing things really fast and pressing control-c afterward
//
// but in that case we're still going through the stop procedure so meh
inputChan <- s
}
}()
// user input channel processing loop
func() {
for s := range inputChan {
var cu loadtester.ConfigUpdate
// note when calling SetNumWorkers() you likely also want to call SetNumIntervalTasks() to increase
// the concurrent throughput for a given interval-segment of time for the change in parallelism SetNumWorkers provides
//
// most people will choose to keep these two values exactly the same because their goal is to
// increase parallelism as well as concurrency and such a lock-step approach ensures that no
// single outlier task affects the throughput of all the others in the same interval-segment of time.
switch s {
case "stop", "exit", "quit":
return
case "set workers":
cu.SetNumWorkers(numWorkers)
case "del worker", "remove worker":
numWorkers -= 1
cu.SetNumWorkers(numWorkers)
case "add worker":
numWorkers += 1
cu.SetNumWorkers(numWorkers)
}
_ = lt.UpdateConfig(cu)
}
}()
cancel()
logger.LogAttrs(ctx, slog.LevelWarn, "waiting for all goroutines to finish")
wg.Wait()
logger.LogAttrs(ctx, slog.LevelWarn, "all goroutines finished")
}