-
-
Notifications
You must be signed in to change notification settings - Fork 931
/
loadtest.go
269 lines (224 loc) · 7.22 KB
/
loadtest.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package argon2
import (
"context"
"fmt"
"math/rand"
"runtime"
"strconv"
"time"
"github.com/ory/x/flagx"
"github.com/fatih/color"
"github.com/inhies/go-bytesize"
"github.com/montanaflynn/stats"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
"github.com/ory/kratos/hash"
"github.com/ory/x/cmdx"
"github.com/ory/x/configx"
)
type resultTable struct {
TotalTime time.Duration `json:"total_time"`
MedianTime time.Duration `json:"median_request_time"`
StdDev time.Duration `json:"std_deviation"`
MinTime time.Duration `json:"min_request_time"`
MaxTime time.Duration `json:"max_request_time"`
MaxMem bytesize.ByteSize `json:"mem_used"`
}
var (
ErrSampleTimeExceeded = fmt.Errorf("the sample time was exceeded")
ErrMemoryConsumptionExceeded = fmt.Errorf("the memory consumption was exceeded")
_ cmdx.TableRow = &resultTable{}
)
func (r *resultTable) Header() []string {
return []string{"TOTAL SAMPLE TIME", "MEDIAN REQUEST TIME", "STANDARD DEVIATION", "MIN REQUEST TIME", "MAX REQUEST TIME", "MEMOry USED"}
}
func (r *resultTable) Columns() []string {
return []string{
r.TotalTime.String(),
r.MedianTime.String(),
r.StdDev.String(),
r.MinTime.String(),
r.MaxTime.String(),
r.MaxMem.String(),
}
}
func (r *resultTable) Interface() interface{} {
return r
}
func newLoadTestCmd() *cobra.Command {
flagConf := &argon2Config{}
cmd := &cobra.Command{
Use: "load-test <authentication-requests-per-minute>",
Short: "Simulate the password hashing with a number of concurrent requests/minute.",
Long: "Simulates a number of concurrent authentication requests per minute. Gives statistical data about the measured performance and resource consumption. Can be used to tune and test the hashing parameters for peak demand situations.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
perMinute, err := strconv.ParseInt(args[0], 0, 0)
if err != nil {
return err
}
flagConf.ctx = cmd.Context()
conf, err := configProvider(cmd, flagConf)
if err != nil {
return err
}
if !flagx.MustGetBool(cmd, cmdx.FlagQuiet) {
fmt.Fprintln(cmd.ErrOrStderr(), "The hashing configuration used is:")
cmdx.PrintRow(cmd, conf)
}
res, err := runLoadTest(cmd, conf, int(perMinute))
if err != nil {
return err
}
cmdx.PrintRow(cmd, res)
return nil
},
}
registerArgon2ConfigFlags(cmd.Flags(), flagConf)
configx.RegisterFlags(cmd.Flags())
cmdx.RegisterFormatFlags(cmd.Flags())
return cmd
}
func runLoadTest(cmd *cobra.Command, conf *argon2Config, reqPerMin int) (*resultTable, error) {
// force GC at the start of the experiment
runtime.GC()
sampleTime := time.Minute / 3
reqNum := reqPerMin / int(time.Minute/sampleTime)
progressPrinter := cmdx.NewLoudErrPrinter(cmd)
_, _ = progressPrinter.Printf("It takes about %s to collect all necessary data, please be patient.\n", sampleTime)
ctx, cancel := context.WithCancel(cmd.Context())
hasher := hash.NewHasherArgon2(conf)
allDone := make(chan struct{})
startAll := time.Now()
var cancelReason error
var memStats []uint64
go func() {
clock := time.NewTicker(time.Second)
defer func() {
clock.Stop()
}()
for {
select {
case <-cmd.Context().Done():
return
case <-allDone:
return
case <-clock.C:
// cancel if the allowed time is exceeded by 110%
if time.Since(startAll) > ((sampleTime+conf.localConfig.ExpectedDuration+conf.localConfig.ExpectedDeviation)/100)*110 {
cancelReason = ErrSampleTimeExceeded
cancel()
return
}
ms := runtime.MemStats{}
runtime.ReadMemStats(&ms)
// cancel if memory is exceeded by 110%
if ms.HeapAlloc > (uint64(conf.localConfig.DedicatedMemory)/100)*110 {
cancelReason = ErrMemoryConsumptionExceeded
cancel()
return
}
memStats = append(memStats, ms.HeapAlloc)
}
}
}()
go func() {
// don't read std_in when quiet
if flagx.MustGetBool(cmd, cmdx.FlagQuiet) {
return
}
input := make([]byte, 1)
for {
n, err := cmd.InOrStdin().Read(input)
if err != nil {
return
}
if n != 0 {
_, _ = color.New(color.FgRed).Fprintln(cmd.ErrOrStderr(), "I SAID BE PATIENT!!!")
return
}
select {
case <-allDone:
return
case <-cmd.Context().Done():
return
case <-time.After(time.Millisecond):
}
}
}()
calcTimes := make([]time.Duration, reqNum)
eg, _ := errgroup.WithContext(ctx)
for i := 0; i < reqNum; i++ {
eg.Go(func(i int) func() error {
return func() error {
// wait randomly before starting, max. sample time
// #nosec G404 - just a timeout to collect statistical data
t := time.Duration(rand.Intn(int(sampleTime)))
timer := time.NewTimer(t)
defer timer.Stop()
select {
case <-ctx.Done():
return nil
case <-timer.C:
}
start := time.Now()
done := make(chan struct{})
var err error
go func() {
_, err = hasher.Generate(ctx, []byte("password"))
close(done)
}()
select {
case <-ctx.Done():
return nil
case <-done:
if err != nil {
return err
}
calcTimes[i] = time.Since(start)
return nil
}
}
}(i))
}
if err := eg.Wait(); err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Error during hashing: %+v\n", err)
return nil, cmdx.FailSilently(cmd)
}
switch cancelReason {
case ErrSampleTimeExceeded:
memUsed, err2 := stats.LoadRawData(memStats).Max()
if err2 != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "Unexpected maths error: %+v\nRaw Data: %+v\n", cancelReason, memStats)
}
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "The hashing load test took too long. This indicates that you don't have enough resources to handle %d login requests per minute with the desired minimal time of %s. The memory used was %s. Either dedicate more CPU/memory, or decrease the hashing cost (memory and iterations parameters).\n", reqPerMin, conf.localConfig.ExpectedDuration, bytesize.ByteSize(memUsed))
return nil, cmdx.FailSilently(cmd)
case ErrMemoryConsumptionExceeded:
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "The hashing load test exceeded the memory limit of %s. This indicates that you don't have enough resources to handle %d login requests per minute with the desired minimal time of %s. Either dedicate more memory, or decrease the hashing cost (memory and iterations parameters).\n", conf.localConfig.DedicatedMemory, reqPerMin, conf.localConfig.ExpectedDuration)
return nil, cmdx.FailSilently(cmd)
}
totalTime := time.Since(startAll)
close(allDone)
calcData := stats.LoadRawData(calcTimes)
duration := func(f func() (float64, error)) time.Duration {
v, err := f()
if err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "Unexpected maths error: %+v\nRaw Data: %+v\n", err, calcTimes)
}
return time.Duration(int64(v))
}
memUsed, err := stats.LoadRawData(memStats).Max()
if err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "Unexpected maths error: %+v\nRaw Data: %+v\n", err, memStats)
}
return &resultTable{
TotalTime: totalTime,
MedianTime: duration(calcData.Mean),
StdDev: duration(calcData.StandardDeviation),
MinTime: duration(calcData.Min),
MaxTime: duration(calcData.Max),
MaxMem: bytesize.ByteSize(memUsed),
}, nil
}