-
Notifications
You must be signed in to change notification settings - Fork 198
/
benchmark.go
876 lines (750 loc) · 24.1 KB
/
benchmark.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
// Copyright 2014-2022 Aerospike, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"encoding/binary"
"errors"
"flag"
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
as "github.com/aerospike/aerospike-client-go/v7"
asl "github.com/aerospike/aerospike-client-go/v7/logger"
ast "github.com/aerospike/aerospike-client-go/v7/types"
)
// TStats is a goroutine's statistics values
type TStats struct {
Exit bool
W, R int // write and read counts
WE, RE int // write and read errors
WTO, RTO int // write and read timeouts
WMin, WMax int64
RMin, RMax int64
WLat, RLat int64
Wn, Rn []int64
}
var countReportChan chan *TStats
var host = flag.String("h", "127.0.0.1", "Aerospike server seed hostnames or IP addresses.")
var port = flag.Int("p", 3000, "Aerospike server seed hostname or IP address port number.")
var namespace = flag.String("n", "test", "Aerospike namespace.")
var set = flag.String("s", "testset", "Aerospike set name.")
var keyCount = flag.Int("k", 1000000, "Key/record count or key/record range.")
var user = flag.String("U", "", "User name.")
var password = flag.String("P", "", "User password.")
var authMode = flag.String("A", "internal", "Authentication mode: internal | external | pki")
var tlsName = flag.String("tlsName", "", "TLS name.")
var rootCA = flag.String("tlsCAFile", "", "Root CA to validate client certificates (for mutual TLS).")
var certFile = flag.String("tlsCertFile", "", "Server certificate.")
var keyFile = flag.String("tlsKeyFile", "", "Private key associated with server certificate.")
var keyFilePassphrase = flag.String("keyFilePass", "", `Passphrase for encrypted keyFile. Supports:
1. "<secret>" (secret directly)
2. "file:<file-that-contains-secret>" (file containing secret)
3. "env:<environment-variable-that-contains-secret>" (environment variable containing secret)
4. "env-b64:<environment-variable-that-contains-base64-encoded-secret>" (environment variable containing base64 encoded secret)
5. "b64:<base64-encoded-secret>" (base64 encoded secret)
`)
var binDef = flag.String("o", "I", "Bin object specification.\n\tI\t: Read/write integer bin.\n\tB:200\t: Read/write byte array bin of length 200.\n\tS:50\t: Read/write string bin of length 50.")
var concurrency = flag.Int("c", 32, "Number of goroutines to generate load.")
var workloadDef = flag.String("w", "I:100", "Desired workload.\n\tI:60\t: Linear 'insert' workload initializing 60% of the keys.\n\tRU:80\t: Random read/update workload with 80% reads and 20% writes.")
var latency = flag.String("L", "", "Latency <columns>,<shift>.\n\tShow transaction latency percentages using elapsed time ranges.\n\t<columns> Number of elapsed time ranges.\n\t<shift> Power of 2 multiple between each range starting at column 3.")
var throughput = flag.Int64("g", 0, "Throttle transactions per second to a maximum value.\n\tIf tps is zero, do not throttle throughput.")
var timeout = flag.Int("T", 0, "Read/Write timeout in milliseconds.")
var maxRetries = flag.Int("maxRetries", 2, "Maximum number of retries before aborting the current transaction.")
var connQueueSize = flag.Int("queueSize", 128, "Maximum number of connections to pool.")
var maxErrorRate = flag.Int("maxErrorRate", 50, "Maximum Error Rate for the Circuit-Breaker to trigger.")
var errorRateWindow = flag.Int("errorRateWindow", 1, "Error Rate Window for the Circuit-Breaker to trigger.")
var openingConnectionThreshold = flag.Int("openingConnectionThreshold", 64, "Maximum number of connections allowed to open simultaneously.")
var warmUp = flag.Int("warmUp", 128, "Number of connections to open on start up.")
var useCompression = flag.Bool("compress", false, "Use compression to send and receive data from the server.")
var minConnsPerNode = flag.Int("minConnsPerNode", 0, "Minimum connections to maintain to each node.")
var randBinData = flag.Bool("R", false, "Use dynamically generated random bin values instead of default static fixed bin values.")
var useMarshalling = flag.Bool("M", false, "Use marshaling a struct instead of simple key/value operations")
var debugMode = flag.Bool("d", false, "Run benchmarks in debug mode.")
var grpc = flag.Bool("grpc", false, "Enable GRPC mode.")
var profileMode = flag.Bool("profile", false, "Run benchmarks with profiler active on port 6060 by default.")
var profilePort = flag.Int("profilePort", 6060, "Profile port.")
var showUsage = flag.Bool("u", false, "Show usage information.")
// parsed data
var binDataType string
var binDataSize int
var workloadType string
var workloadPercent int
var latBase, latCols int
// group mutex to wait for all load generating go routines to finish
var wg sync.WaitGroup
// throughput counter
var currThroughput int64
var lastReport int64
// Underscores are there so that the field name is the same as key/value mode
type dataStruct struct {
I int64
S string
B []byte
}
var logger *log.Logger
func main() {
var buf bytes.Buffer
logger = log.New(&buf, "", log.LstdFlags|log.Lshortfile)
logger.SetOutput(os.Stdout)
// use all cpus in the system for concurrency
log.Printf("Setting number of CPUs to use: %d", runtime.NumCPU())
runtime.GOMAXPROCS(runtime.NumCPU())
readFlags()
countReportChan = make(chan *TStats, 4*(*concurrency)) // async chan
if *debugMode {
asl.Logger.SetLogger(logger)
asl.Logger.SetLevel(asl.DEBUG)
}
// launch profiler if in profile mode
if *profileMode {
runtime.SetBlockProfileRate(1)
go func() {
logger.Println(http.ListenAndServe(fmt.Sprintf(":%d", *profilePort), nil))
}()
}
printBenchmarkParams()
clientPolicy := as.NewClientPolicy()
*authMode = strings.ToLower(strings.TrimSpace(*authMode))
switch *authMode {
case "internal":
clientPolicy.AuthMode = as.AuthModeInternal
case "external":
clientPolicy.AuthMode = as.AuthModeExternal
case "pki":
clientPolicy.AuthMode = as.AuthModePKI
default:
log.Fatalln("Invalid auth mode: only `internal` and `external` values are accepted.")
}
// cache lots of connections
clientPolicy.ConnectionQueueSize = *connQueueSize
clientPolicy.MaxErrorRate = *maxErrorRate
clientPolicy.ErrorRateWindow = *errorRateWindow
clientPolicy.User = *user
clientPolicy.Password = *password
clientPolicy.Timeout = 10 * time.Second
clientPolicy.OpeningConnectionThreshold = *openingConnectionThreshold
clientPolicy.MinConnectionsPerNode = *minConnsPerNode
clientPolicy.TlsConfig = initAerospikeTLS()
dbHost := as.NewHost(*host, *port)
dbHost.TLSName = *tlsName
var client as.ClientIfc
if *grpc {
gclient, err := as.NewProxyClientWithPolicyAndHost(clientPolicy, dbHost)
if err != nil {
logger.Fatal(err)
}
client = gclient
} else {
nclient, err := as.NewClientWithPolicyAndHost(clientPolicy, dbHost)
if err != nil {
logger.Fatal(err)
}
cc, _ := nclient.WarmUp(*warmUp)
logger.Printf("Warm-up conns.:\t%d", cc)
logger.Println("Nodes Found:", nclient.GetNodeNames())
client = nclient
}
go reporter()
switch workloadType {
case "I":
wg.Add(*concurrency)
for i := 1; i < *concurrency; i++ {
go runBench_I(client, i-1, *keyCount / *concurrency)
}
go runBench_I(client, *concurrency-1, *keyCount / *concurrency + *keyCount%*concurrency)
wg.Wait()
case "RU":
for i := 1; i < *concurrency; i++ {
go runBench_RU(client, i-1, *keyCount / *concurrency)
}
runBench_RU(client, *concurrency-1, *keyCount / *concurrency + *keyCount%*concurrency)
default:
log.Fatal("Invalid workload type " + workloadType)
}
// send term to reporter, and wait for it to terminate
countReportChan <- &TStats{Exit: true}
time.Sleep(10 * time.Millisecond)
<-countReportChan
}
func workloadToString() string {
switch workloadType {
case "RU":
return fmt.Sprintf("Read %d%%, Write %d%%", workloadPercent, 100-workloadPercent)
default:
return fmt.Sprintf("Initialize %d%% of records", workloadPercent)
}
}
func throughputToString() string {
if *throughput <= 0 {
return "unlimited"
}
return fmt.Sprintf("%d", *throughput)
}
func printBenchmarkParams() {
logger.Printf("host:\t\t%s", *host)
logger.Printf("tls name:\t\t%s", *tlsName)
logger.Printf("port:\t\t%d", *port)
logger.Printf("namespace:\t%s", *namespace)
logger.Printf("set:\t\t%s", *set)
logger.Printf("keys/records:\t%d", *keyCount)
logger.Printf("object spec:\t%s, size: %d", binDataType, binDataSize)
logger.Printf("rnd bin values:\t%v", *randBinData)
logger.Printf("workload:\t\t%s", workloadToString())
logger.Printf("concurrency:\t%d", *concurrency)
logger.Printf("max throughput:\t%s", throughputToString())
logger.Printf("timeout:\t\t%v ms", *timeout)
logger.Printf("max retries:\t%d", *maxRetries)
logger.Printf("debug:\t\t%v", *debugMode)
logger.Printf("latency:\t\t%d:%d", latBase, latCols)
logger.Printf("conn. pool size:\t%d", *connQueueSize)
logger.Printf("conn. threshold:\t%d", *openingConnectionThreshold)
logger.Printf("root CA file:\t%s", *rootCA)
logger.Printf("cert file:\t%s", *certFile)
logger.Printf("key file:\t\t%s", *keyFile)
logger.Printf("auth mode:\t%s", *authMode)
logger.Printf("user:\t\t%s", *user)
logger.Printf("password:\t\t%s", *password)
}
// parses an string of (key:value) type
func parseValuedParam(param string) (string, *int) {
re := regexp.MustCompile(`(\w+)([:,](\d+))?`)
values := re.FindStringSubmatch(param)
parStr := strings.ToUpper(strings.Trim(values[1], " "))
// see if the value is supplied
if len(values) > 3 && strings.Trim(values[3], " ") != "" {
if value, err := strconv.Atoi(strings.Trim(values[3], " ")); err == nil {
return parStr, &value
}
}
return parStr, nil
}
func parseLatency(param string) (int, int) {
re := regexp.MustCompile(`(\d+)[:,](\d+)`)
values := re.FindStringSubmatch(param)
// see if the value is supplied
if len(values) > 2 && strings.Trim(values[1], " ") != "" && strings.Trim(values[2], " ") != "" {
if value1, err := strconv.Atoi(strings.Trim(values[1], " ")); err == nil {
if value2, err := strconv.Atoi(strings.Trim(values[2], " ")); err == nil {
return value1, value2
}
}
}
logger.Fatal("Wrong latency values requested.")
return 0, 0
}
// reads input flags and interprets the complex ones
func readFlags() {
flag.Parse()
if *showUsage {
flag.Usage()
os.Exit(0)
}
if *debugMode {
asl.Logger.SetLevel(asl.INFO)
}
if *latency != "" {
latCols, latBase = parseLatency(*latency)
}
var binDataSz, workloadPct *int
binDataType, binDataSz = parseValuedParam(*binDef)
if binDataSz != nil {
binDataSize = *binDataSz
} else {
switch binDataType {
case "B":
binDataSize = 200
case "S":
binDataSize = 50
}
}
workloadType, workloadPct = parseValuedParam(*workloadDef)
if workloadPct != nil {
workloadPercent = *workloadPct
} else {
switch workloadType {
case "I":
workloadPercent = 100
case "RU":
workloadPercent = 50
}
}
}
// new random bin generator based on benchmark specs
func getRandValue(xr *XorRand) as.Value {
switch binDataType {
case "B":
return as.NewBytesValue(randBytes(binDataSize, xr))
case "S":
return as.NewStringValue(string(randBytes(binDataSize, xr)))
default:
return as.NewLongValue(xr.Int64())
}
}
// new random bin generator based on benchmark specs
func getBin(xr *XorRand) *as.Bin {
var bin *as.Bin
switch binDataType {
case "B":
bin = &as.Bin{Name: "B", Value: getRandValue(xr)}
case "S":
bin = &as.Bin{Name: "S", Value: getRandValue(xr)}
default:
bin = &as.Bin{Name: "I", Value: getRandValue(xr)}
}
return bin
}
func setBin(bin *as.Bin, xr *XorRand) {
switch binDataType {
case "B":
bin.Value = getRandValue(xr)
case "S":
bin.Value = getRandValue(xr)
default:
bin.Value = getRandValue(xr)
}
}
// new random bin generator based on benchmark specs
func getDataStruct(xr *XorRand) *dataStruct {
var ds *dataStruct
switch binDataType {
case "B":
ds = &dataStruct{B: randBytes(binDataSize, xr)}
case "S":
ds = &dataStruct{S: string(randBytes(binDataSize, xr))}
default:
ds = &dataStruct{I: xr.Int64()}
}
return ds
}
// new random bin generator based on benchmark specs
func setDataStruct(ds *dataStruct, xr *XorRand) {
switch binDataType {
case "B":
ds.B = randBytes(binDataSize, xr)
case "S":
ds.S = string(randBytes(binDataSize, xr))
default:
ds.I = xr.Int64()
}
}
const random_alpha_num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const l = 62
func randBytes(size int, xr *XorRand) []byte {
buf := make([]byte, size, size)
xr.Read(buf)
return buf
}
func incOnError(op, timeout *int, err error) {
ae := &as.AerospikeError{}
if errors.As(err, &ae) && ae.Matches(ast.TIMEOUT, as.ErrConnectionPoolEmpty.ResultCode, as.ErrTooManyConnectionsForNode.ResultCode, as.ErrTooManyOpeningConnections.ResultCode) {
*timeout++
} else {
*op++
}
}
func runBench_I(client as.ClientIfc, ident int, times int) {
defer wg.Done()
xr := NewXorRand()
var err error
var forceReport bool
writepolicy := as.NewWritePolicy(0, 0)
writepolicy.TotalTimeout = time.Duration(*timeout) * time.Millisecond
writepolicy.MaxRetries = *maxRetries
writepolicy.UseCompression = *useCompression
defaultBin := getBin(xr)
defaultObj := getDataStruct(xr)
t := time.Now()
var WCount int
var writeErr int
var writeTOErr int
var tm time.Time
var wLat int64
var wLatTotal int64
var wMinLat int64
var wMaxLat int64
wLatList := make([]int64, latCols+1)
bin := defaultBin
obj := defaultObj
key, _ := as.NewKey(*namespace, *set, 0)
partition := ident * times
for i := 1; i <= times; i++ {
wLat = 0
key.SetValue(as.IntegerValue(partition + (i % times)))
if !*useMarshalling {
// if randomBin data has been requested
if *randBinData {
setBin(bin, xr)
}
tm = time.Now()
if err = client.PutBins(writepolicy, key, bin); err != nil {
incOnError(&writeErr, &writeTOErr, err)
// log.Fatalln(err)
continue
}
} else {
// if randomBin data has been requested
if *randBinData {
setDataStruct(obj, xr)
}
tm = time.Now()
if err = client.PutObject(writepolicy, key, obj); err != nil {
incOnError(&writeErr, &writeTOErr, err)
continue
}
}
WCount++
wLat = int64(time.Now().Sub(tm) / time.Millisecond)
wLatTotal += wLat
// under 1 ms
if wLat <= int64(latBase) {
wLatList[0]++
}
for i := 1; i <= latCols; i++ {
if wLat > int64(latBase<<uint(i-1)) {
wLatList[i]++
}
}
wMinLat = min(wLat, wMinLat)
wMaxLat = max(wLat, wMaxLat)
// if throughput is set, check for threshold. All goroutines add a record on first iteration,
// so take that into account as well
if *throughput > 0 {
forceReport = atomic.LoadInt64(&currThroughput) >= (*throughput - int64(*concurrency))
if !forceReport {
atomic.AddInt64(&currThroughput, 1)
}
}
if forceReport || (time.Now().Sub(t) > (99 * time.Millisecond)) {
countReportChan <- &TStats{false, WCount, 0, writeErr, 0, writeTOErr, 0, wMinLat, wMaxLat, 0, 0, wLatTotal, 0, wLatList, nil}
WCount = 0
writeErr = 0
writeTOErr = 0
// reset stats
wLatTotal = 0
wMinLat, wMaxLat = 0, 0
wLatList = make([]int64, latCols+1)
t = time.Now()
}
if forceReport {
forceReport = false
// sleep till next report
time.Sleep(time.Second - time.Duration(time.Now().UnixNano()-atomic.LoadInt64(&lastReport)))
}
}
countReportChan <- &TStats{false, WCount, 0, writeErr, 0, writeTOErr, 0, wMinLat, wMaxLat, 0, 0, wLatTotal, 0, wLatList, nil}
}
func runBench_RU(client as.ClientIfc, ident int, times int) {
defer wg.Done()
xr := NewXorRand()
// var r *as.Record
var err error
var forceReport bool
writepolicy := as.NewWritePolicy(0, 0)
writepolicy.TotalTimeout = time.Duration(*timeout) * time.Millisecond
writepolicy.MaxRetries = *maxRetries
writepolicy.UseCompression = *useCompression
readpolicy := writepolicy.GetBasePolicy()
defaultBin := getBin(xr)
defaultObj := getDataStruct(xr)
t := time.Now()
var WCount, RCount int
var writeErr, readErr int
var writeTOErr, readTOErr int
var tm time.Time
var wLat, rLat int64
var wLatTotal, rLatTotal int64
var wMinLat, rMinLat int64
var wMaxLat, rMaxLat int64
wLatList := make([]int64, latCols+1)
rLatList := make([]int64, latCols+1)
bin := defaultBin
obj := defaultObj
i := 0
key, _ := as.NewKey(*namespace, *set, 0)
partition := ident * times
for {
i++
rLat, wLat = 0, 0
key.SetValue(as.IntegerValue(partition + (i % times)))
// key, _ := as.NewKey(*namespace, *set, as.IntegerValue(partition+(i%times)))
if int(xr.Uint64()%100) >= workloadPercent {
if !*useMarshalling {
// if randomBin data has been requested
if *randBinData {
setBin(bin, xr)
}
tm = time.Now()
err = client.PutBins(writepolicy, key, bin)
} else {
// if randomBin data has been requested
if *randBinData {
setDataStruct(obj, xr)
}
tm = time.Now()
err = client.PutObject(writepolicy, key, obj)
}
wLat = int64(time.Now().Sub(tm) / time.Millisecond)
wLatTotal += wLat
if err != nil {
incOnError(&writeErr, &writeTOErr, err)
continue
}
WCount++
// under 1 ms
if wLat <= int64(latBase) {
wLatList[0]++
}
for i := 1; i <= latCols; i++ {
if wLat > int64(latBase<<uint(i-1)) {
wLatList[i]++
}
}
wMinLat = min(wLat, wMinLat)
wMaxLat = max(wLat, wMaxLat)
} else {
if !*useMarshalling {
tm = time.Now()
_, err = client.Get(readpolicy, key, bin.Name)
} else {
tm = time.Now()
err = client.GetObject(readpolicy, key, obj)
}
rLat = int64(time.Now().Sub(tm) / time.Millisecond)
rLatTotal += rLat
if err != nil {
incOnError(&readErr, &readTOErr, err)
continue
}
RCount++
// under 1 ms
if rLat <= int64(latBase) {
rLatList[0]++
}
for i := 1; i <= latCols; i++ {
if rLat > int64(latBase<<uint(i-1)) {
rLatList[i]++
}
}
rMinLat = min(rLat, rMinLat)
rMaxLat = max(rLat, rMaxLat)
}
// if throughput is set, check for threshold. All goroutines add a record on first iteration,
// so take that into account as well
if *throughput > 0 {
forceReport = atomic.LoadInt64(&currThroughput) >= (*throughput - int64(*concurrency))
if !forceReport {
atomic.AddInt64(&currThroughput, 1)
}
}
if forceReport || (time.Now().Sub(t) > (99 * time.Millisecond)) {
countReportChan <- &TStats{false, WCount, RCount, writeErr, readErr, writeTOErr, readTOErr, wMinLat, wMaxLat, rMinLat, rMaxLat, wLatTotal, rLatTotal, wLatList, rLatList}
WCount, RCount = 0, 0
writeErr, readErr = 0, 0
writeTOErr, readTOErr = 0, 0
// reset stats
wLatTotal, rLatTotal = 0, 0
wMinLat, wMaxLat = 0, 0
rMinLat, rMaxLat = 0, 0
wLatList = make([]int64, latCols+1)
rLatList = make([]int64, latCols+1)
t = time.Now()
}
if forceReport {
forceReport = false
// sleep till next report
time.Sleep(time.Second - time.Duration(time.Now().UnixNano()-atomic.LoadInt64(&lastReport)))
}
}
}
// calculates transactions per second
func calcTPS(count int, duration time.Duration) int {
return int(float64(count) / (float64(duration) / float64(time.Second)))
}
func max(a, b int64) int64 {
if a > b {
return a
}
return b
}
func min(a, b int64) int64 {
if a < b {
return a
}
return b
}
// listens to transaction report channel, and print them out on intervals
func reporter() {
var totalWCount, totalRCount int
var totalWErrCount, totalRErrCount int
var totalWTOCount, totalRTOCount int
var totalCount, totalTOCount, totalErrCount int
lastReportTime := time.Now()
var memStats = new(runtime.MemStats)
var lastTotalAllocs, lastPauseNs uint64
// var wLat, rLat int64
var wTotalLat, rTotalLat int64
var wMinLat, rMinLat int64
var wMaxLat, rMaxLat int64
wLatList := make([]int64, latCols+1)
rLatList := make([]int64, latCols+1)
var strBuff bytes.Buffer
memProfileStr := func() string {
var res string
if *debugMode {
// GC stats
runtime.ReadMemStats(memStats)
allocMem := (memStats.TotalAlloc - lastTotalAllocs) / (1024)
pauseNs := (memStats.PauseTotalNs - lastPauseNs) / 1e6
res = fmt.Sprintf(" (malloc (KiB): %d, GC pause(ms): %d)",
allocMem,
pauseNs,
)
// GC
lastPauseNs = memStats.PauseTotalNs
lastTotalAllocs = memStats.TotalAlloc
}
return res
}
Loop:
for {
select {
case stats := <-countReportChan:
totalWCount += stats.W
totalRCount += stats.R
totalWErrCount += stats.WE
totalRErrCount += stats.RE
totalWTOCount += stats.WTO
totalRTOCount += stats.RTO
totalCount += (stats.W + stats.R)
totalErrCount += (stats.WE + stats.RE)
totalTOCount += (stats.WTO + stats.RTO)
wTotalLat += stats.WLat
rTotalLat += stats.RLat
for i := 0; i <= latCols; i++ {
if stats.Wn != nil {
wLatList[i] += stats.Wn[i]
}
if stats.Rn != nil {
rLatList[i] += stats.Rn[i]
}
}
if stats.RMax > rMaxLat {
rMaxLat = stats.RMax
}
if stats.RMin < rMinLat {
rMinLat = stats.RMin
}
if stats.WMax > wMaxLat {
wMaxLat = stats.WMax
}
if stats.WMin < wMinLat {
wMinLat = stats.WMin
}
if stats.Exit || time.Now().Sub(lastReportTime) >= time.Second {
// reset throughput
atomic.StoreInt64(&currThroughput, 0)
atomic.StoreInt64(&lastReport, time.Now().UnixNano())
if workloadType == "I" {
logger.Printf("write(tps=%d timeouts=%d errors=%d totalCount=%d)%s",
totalWCount, totalTOCount, totalErrCount, totalCount,
memProfileStr(),
)
} else {
logger.Printf(
"write(tps=%d timeouts=%d errors=%d) read(tps=%d timeouts=%d errors=%d) total(tps=%d timeouts=%d errors=%d, count=%d)%s",
totalWCount, totalWTOCount, totalWErrCount,
totalRCount, totalRTOCount, totalRErrCount,
totalWCount+totalRCount, totalTOCount, totalErrCount, totalCount,
memProfileStr(),
)
}
if *latency != "" {
strBuff.WriteString(fmt.Sprintf("\t\tMin(ms)\tAvg(ms)\tMax(ms)\t|<=%4d ms\t", latBase))
for i := 0; i < latCols; i++ {
strBuff.WriteString(fmt.Sprintf("|>%4d ms\t", latBase<<uint(i)))
}
logger.Println(strBuff.String())
strBuff.Reset()
strBuff.WriteString(fmt.Sprintf("\tREAD\t%d\t%3.3f\t%d", rMinLat, float64(rTotalLat)/float64(totalRCount+1), rMaxLat))
for i := 0; i <= latCols; i++ {
strBuff.WriteString(fmt.Sprintf("\t|% 6d/%4.2f%%", rLatList[i], float64(rLatList[i])/float64(totalRCount+1)*100))
}
logger.Println(strBuff.String())
strBuff.Reset()
strBuff.WriteString(fmt.Sprintf("\tWRITE\t%d\t%3.3f\t%d", wMinLat, float64(wTotalLat)/float64(totalWCount+1), wMaxLat))
for i := 0; i <= latCols; i++ {
strBuff.WriteString(fmt.Sprintf("\t|% 6d/%4.2f%%", wLatList[i], float64(wLatList[i])/float64(totalWCount+1)*100))
}
logger.Println(strBuff.String())
strBuff.Reset()
}
// reset stats
wTotalLat, rTotalLat = 0, 0
wMinLat, wMaxLat = 0, 0
rMinLat, rMaxLat = 0, 0
for i := 0; i <= latCols; i++ {
wLatList[i] = 0
rLatList[i] = 0
}
totalWCount, totalRCount = 0, 0
totalWErrCount, totalRErrCount = 0, 0
totalTOCount, totalWTOCount, totalRTOCount = 0, 0, 0
lastReportTime = time.Now()
if stats.Exit {
break Loop
}
}
}
}
countReportChan <- &TStats{}
}
// XorRand is a XOR Shift random number generator
type XorRand struct {
src [2]uint64
}
// NewXorRand creates a random number generator
func NewXorRand() *XorRand {
return &XorRand{[2]uint64{uint64(time.Now().UnixNano()), uint64(time.Now().UnixNano())}}
}
// Int64 returns a random int64 value
func (r *XorRand) Int64() int64 {
return int64(r.Uint64())
}
// Uint64 returns a random uint64 value
func (r *XorRand) Uint64() uint64 {
s1 := r.src[0]
s0 := r.src[1]
r.src[0] = s0
s1 ^= s1 << 23
r.src[1] = (s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26))
return r.src[1] + s0
}
// Read fills p with random bytes
func (r *XorRand) Read(p []byte) (n int, err error) {
l := len(p) / 8
for i := 0; i < l; i += 8 {
binary.PutUvarint(p[i:], r.Uint64())
}
return len(p), nil
}