forked from scylladb/scylla-bench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodes.go
510 lines (436 loc) · 12.9 KB
/
modes.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
package main
import (
"bytes"
"fmt"
"log"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/codahale/hdrhistogram"
"github.com/gocql/gocql"
)
type RateLimiter interface {
Wait()
ExpectedInterval() int64
}
type UnlimitedRateLimiter struct{}
func (*UnlimitedRateLimiter) Wait() {}
func (*UnlimitedRateLimiter) ExpectedInterval() int64 {
return 0
}
type MaximumRateLimiter struct {
Period time.Duration
StartTime time.Time
CompletedOperations int64
}
func (mxrl *MaximumRateLimiter) Wait() {
mxrl.CompletedOperations++
nextRequest := mxrl.StartTime.Add(mxrl.Period * time.Duration(mxrl.CompletedOperations))
now := time.Now()
if now.Before(nextRequest) {
time.Sleep(nextRequest.Sub(now))
}
}
func (mxrl *MaximumRateLimiter) ExpectedInterval() int64 {
return mxrl.Period.Nanoseconds()
}
func NewRateLimiter(maximumRate int, timeOffset time.Duration) RateLimiter {
if maximumRate == 0 {
return &UnlimitedRateLimiter{}
}
period := time.Duration(int64(time.Second) / int64(maximumRate))
return &MaximumRateLimiter{period, time.Now(), 0}
}
type Result struct {
Final bool
ElapsedTime time.Duration
Operations int
ClusteringRows int
Errors int
Latency *hdrhistogram.Histogram
}
type MergedResult struct {
Time time.Duration
Operations int
ClusteringRows int
OperationsPerSecond float64
ClusteringRowsPerSecond float64
Errors int
Latency *hdrhistogram.Histogram
}
func NewMergedResult() *MergedResult {
result := &MergedResult{}
result.Latency = NewHistogram()
return result
}
func (mr *MergedResult) AddResult(result Result) {
mr.Time += result.ElapsedTime
mr.Operations += result.Operations
mr.ClusteringRows += result.ClusteringRows
mr.OperationsPerSecond += float64(result.Operations) / result.ElapsedTime.Seconds()
mr.ClusteringRowsPerSecond += float64(result.ClusteringRows) / result.ElapsedTime.Seconds()
mr.Errors += result.Errors
if measureLatency {
dropped := mr.Latency.Merge(result.Latency)
if dropped > 0 {
log.Print("dropped: ", dropped)
}
}
}
func NewHistogram() *hdrhistogram.Histogram {
if !measureLatency {
return nil
}
return hdrhistogram.New(time.Microsecond.Nanoseconds()*50, (timeout + timeout*2).Nanoseconds(), 3)
}
func HandleError(err error) {
if atomic.SwapUint32(&stopAll, 1) == 0 {
log.Print(err)
fmt.Println("\nstopping")
atomic.StoreUint32(&stopAll, 1)
}
}
func MergeResults(results []chan Result) (bool, *MergedResult) {
result := NewMergedResult()
final := false
for i, ch := range results {
res := <-ch
if !final && res.Final {
final = true
result = NewMergedResult()
for _, ch2 := range results[0:i] {
res = <-ch2
for !res.Final {
res = <-ch2
}
result.AddResult(res)
}
} else if final && !res.Final {
for !res.Final {
res = <-ch
}
}
result.AddResult(res)
}
result.Time /= time.Duration(concurrency)
return final, result
}
func RunConcurrently(maximumRate int, workload func(id int, resultChannel chan Result, rateLimiter RateLimiter)) *MergedResult {
var timeOffsetUnit int64
if maximumRate != 0 {
timeOffsetUnit = int64(time.Second) / int64(maximumRate)
maximumRate /= concurrency
} else {
timeOffsetUnit = 0
}
results := make([]chan Result, concurrency)
for i := range results {
results[i] = make(chan Result, 1)
}
startTime := time.Now()
for i := 0; i < concurrency; i++ {
go func(i int) {
timeOffset := time.Duration(timeOffsetUnit * int64(i))
workload(i, results[i], NewRateLimiter(maximumRate, timeOffset))
close(results[i])
}(i)
}
final, result := MergeResults(results)
for !final {
result.Time = time.Now().Sub(startTime)
PrintPartialResult(result)
final, result = MergeResults(results)
}
return result
}
type ResultBuilder struct {
FullResult *Result
PartialResult *Result
}
func NewResultBuilder() *ResultBuilder {
rb := &ResultBuilder{}
rb.FullResult = &Result{}
rb.PartialResult = &Result{}
rb.FullResult.Final = true
rb.FullResult.Latency = NewHistogram()
rb.PartialResult.Latency = NewHistogram()
return rb
}
func (rb *ResultBuilder) IncOps() {
rb.FullResult.Operations++
rb.PartialResult.Operations++
}
func (rb *ResultBuilder) IncRows() {
rb.FullResult.ClusteringRows++
rb.PartialResult.ClusteringRows++
}
func (rb *ResultBuilder) AddRows(n int) {
rb.FullResult.ClusteringRows += n
rb.PartialResult.ClusteringRows += n
}
func (rb *ResultBuilder) IncErrors() {
rb.FullResult.Errors++
rb.PartialResult.Errors++
}
func (rb *ResultBuilder) ResetPartialResult() {
rb.PartialResult = &Result{}
rb.PartialResult.Latency = NewHistogram()
}
func (rb *ResultBuilder) RecordLatency(latency time.Duration, rateLimiter RateLimiter) error {
if !measureLatency {
return nil
}
err := rb.FullResult.Latency.RecordCorrectedValue(latency.Nanoseconds(), rateLimiter.ExpectedInterval())
if err != nil {
return err
}
err = rb.PartialResult.Latency.RecordCorrectedValue(latency.Nanoseconds(), rateLimiter.ExpectedInterval())
if err != nil {
return err
}
return nil
}
var errorRecordingLatency bool
type TestIterator struct {
iteration uint
workload WorkloadGenerator
}
func NewTestIterator(workload WorkloadGenerator) *TestIterator {
return &TestIterator{0, workload}
}
func (ti *TestIterator) IsDone() bool {
if atomic.LoadUint32(&stopAll) != 0 {
return true;
}
if ti.workload.IsDone() {
if ti.iteration + 1 == iterations {
return true
} else {
ti.workload.Restart()
ti.iteration++
return false
}
} else {
return false
}
}
func RunTest(resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter, test func(rb *ResultBuilder) (error, time.Duration)) {
rb := NewResultBuilder()
start := time.Now()
partialStart := start
iter := NewTestIterator(workload)
for !iter.IsDone() {
rateLimiter.Wait()
err, latency := test(rb)
if err != nil {
log.Print(err)
rb.IncErrors()
continue
}
err = rb.RecordLatency(latency, rateLimiter)
if err != nil {
errorRecordingLatency = true
}
now := time.Now()
if now.Sub(partialStart) > time.Second {
resultChannel <- *rb.PartialResult
rb.ResetPartialResult()
partialStart = now
}
}
end := time.Now()
rb.FullResult.ElapsedTime = end.Sub(start)
resultChannel <- *rb.FullResult
}
func generateData(pk int64, ck int64, size int64) []byte {
value := make([]byte, size)
if validateData {
dataPattern := strconv.FormatInt(pk*ck*(pk+ck), 10)
dataLen := len(dataPattern)
cnt := int(size) / dataLen
tail := int(size) % dataLen
var data string
if cnt > 0 {
data = strings.Repeat(dataPattern, cnt)
}
if tail > 0 {
data += dataPattern[:tail]
}
copy(value, []byte(data))
}
return value
}
func DoWrites(session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
query := session.Query("INSERT INTO " + keyspaceName + "." + tableName + " (pk, ck, v) VALUES (?, ?, ?)")
RunTest(resultChannel, workload, rateLimiter, func(rb *ResultBuilder) (error, time.Duration) {
pk := workload.NextPartitionKey()
ck := workload.NextClusteringKey()
value := generateData(pk, ck, clusteringRowSize)
bound := query.Bind(pk, ck, value)
requestStart := time.Now()
err := bound.Exec()
requestEnd := time.Now()
if err != nil {
return err, time.Duration(0)
}
rb.IncOps()
rb.IncRows()
latency := requestEnd.Sub(requestStart)
return nil, latency
})
}
func DoBatchedWrites(session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
request := fmt.Sprintf("INSERT INTO %s.%s (pk, ck, v) VALUES (?, ?, ?)", keyspaceName, tableName)
RunTest(resultChannel, workload, rateLimiter, func(rb *ResultBuilder) (error, time.Duration) {
batch := gocql.NewBatch(gocql.UnloggedBatch)
batchSize := 0
currentPk := workload.NextPartitionKey()
for !workload.IsPartitionDone() && atomic.LoadUint32(&stopAll) == 0 && batchSize < rowsPerRequest {
ck := workload.NextClusteringKey()
batchSize++
value := generateData(currentPk, ck, clusteringRowSize)
batch.Query(request, currentPk, ck, value)
}
requestStart := time.Now()
err := session.ExecuteBatch(batch)
requestEnd := time.Now()
if err != nil {
return err, time.Duration(0)
}
rb.IncOps()
rb.AddRows(batchSize)
latency := requestEnd.Sub(requestStart)
return nil, latency
})
}
func DoCounterUpdates(session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
query := session.Query("UPDATE " + keyspaceName + "." + counterTableName +
" SET c1 = c1 + ?, c2 = c2 + ?, c3 = c3 + ?, c4 = c4 + ?, c5 = c5 + ? WHERE pk = ? AND ck = ?")
RunTest(resultChannel, workload, rateLimiter, func(rb *ResultBuilder) (error, time.Duration) {
pk := workload.NextPartitionKey()
ck := workload.NextClusteringKey()
bound := query.Bind(ck, ck+1, ck+2, ck+3, ck+4, pk, ck)
requestStart := time.Now()
err := bound.Exec()
requestEnd := time.Now()
if err != nil {
return err, time.Duration(0)
}
rb.IncOps()
rb.IncRows()
latency := requestEnd.Sub(requestStart)
return nil, latency
})
}
func DoReads(session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
DoReadsFromTable(tableName, session, resultChannel, workload, rateLimiter)
}
func DoCounterReads(session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
DoReadsFromTable(counterTableName, session, resultChannel, workload, rateLimiter)
}
func DoReadsFromTable(table string, session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
var request string
if inRestriction {
arr := make([]string, rowsPerRequest)
for i := 0; i < rowsPerRequest; i++ {
arr[i] = "?"
}
request = fmt.Sprintf("SELECT * from %s.%s WHERE pk = ? AND ck IN (%s)", keyspaceName, table, strings.Join(arr, ", "))
} else if provideUpperBound {
request = fmt.Sprintf("SELECT * FROM %s.%s WHERE pk = ? AND ck >= ? AND ck < ?", keyspaceName, table)
} else if noLowerBound {
request = fmt.Sprintf("SELECT * FROM %s.%s WHERE pk = ? LIMIT %d", keyspaceName, table, rowsPerRequest)
} else {
request = fmt.Sprintf("SELECT * FROM %s.%s WHERE pk = ? AND ck >= ? LIMIT %d", keyspaceName, table, rowsPerRequest)
}
query := session.Query(request)
RunTest(resultChannel, workload, rateLimiter, func(rb *ResultBuilder) (error, time.Duration) {
pk := workload.NextPartitionKey()
var bound *gocql.Query
if inRestriction {
args := make([]interface{}, 1, rowsPerRequest+1)
args[0] = pk
for i := 0; i < rowsPerRequest; i++ {
if workload.IsPartitionDone() {
args = append(args, 0)
} else {
args = append(args, workload.NextClusteringKey())
}
}
bound = query.Bind(args...)
} else if noLowerBound {
bound = query.Bind(pk)
} else {
ck := workload.NextClusteringKey()
if provideUpperBound {
bound = query.Bind(pk, ck, ck+int64(rowsPerRequest))
} else {
bound = query.Bind(pk, ck)
}
}
var resPk, resCk int64
var value []byte
requestStart := time.Now()
iter := bound.Iter()
if table == tableName {
for iter.Scan(&resPk, &resCk, &value) {
rb.IncRows()
if validateData {
valueExpected := generateData(resPk, resCk, clusteringRowSize)
if bytes.Compare(value, valueExpected) != 0 {
rb.IncErrors()
log.Print("data corruption:", resPk, resCk, value, valueExpected)
}
}
}
} else {
var c1, c2, c3, c4, c5 int64
for iter.Scan(&resPk, &resCk, &c1, &c2, &c3, &c4, &c5) {
rb.IncRows()
if validateData {
// in case of uniform workload the same row can be updated number of times
var updateNum int64
if resCk == 0 {
updateNum = c2
} else {
updateNum = c1 / resCk
}
if c1 != resCk*updateNum || c2 != c1+updateNum || c3 != c1+updateNum*2 || c4 != c1+updateNum*3 || c5 != c1+updateNum*4 {
rb.IncErrors()
log.Print("counter data corruption:", resPk, resCk, c1, c2, c3, c4, c5)
}
}
}
}
requestEnd := time.Now()
err := iter.Close()
if err != nil {
return err, time.Duration(0)
}
rb.IncOps()
latency := requestEnd.Sub(requestStart)
return nil, latency
})
}
func DoScanTable(session *gocql.Session, resultChannel chan Result, workload WorkloadGenerator, rateLimiter RateLimiter) {
request := fmt.Sprintf("SELECT * FROM %s.%s WHERE token(pk) >= ? AND token(pk) <= ?", keyspaceName, tableName)
query := session.Query(request)
RunTest(resultChannel, workload, rateLimiter, func(rb *ResultBuilder) (error, time.Duration) {
requestStart := time.Now()
currentRange := workload.NextTokenRange()
bound := query.Bind(currentRange.Start, currentRange.End)
iter := bound.Iter()
for iter.Scan(nil, nil, nil) {
rb.IncRows()
}
requestEnd := time.Now()
err := iter.Close()
if err != nil {
return err, time.Duration(0)
}
rb.IncOps()
latency := requestEnd.Sub(requestStart)
return nil, latency
})
}