forked from influxdata/influxdb-comparisons
/
main.go
399 lines (350 loc) · 11.3 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
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
// query_benchmarker speed tests ElasticSearch using requests from stdin.
//
// It reads encoded Query objects from stdin, and makes concurrent requests
// to the provided HTTP endpoint. This program currently has no knowledge of
// the internals of the endpoint.
//
// TODO(rw): On my machine, this only decodes 700k/sec messages from stdin.
package main
import (
"bufio"
"encoding/gob"
"flag"
"fmt"
"io"
"log"
"os"
"runtime/pprof"
"sort"
"strings"
"sync"
"time"
"github.com/influxdata/influxdb-comparisons/util/report"
)
// Program option vars:
var (
csvDaemonUrls string
daemonUrls []string
workers int
debug int
prettyPrintResponses bool
limit int64
burnIn uint64
printInterval uint64
memProfile string
telemetryHost string
telemetryStderr bool
telemetryBatchSize uint64
telemetryTagsCSV string
telemetryBasicAuth string
reportDatabase string
reportHost string
reportUser string
reportPassword string
reportTagsCSV string
)
// Global vars:
var (
queryPool sync.Pool
queryChan chan *Query
statPool sync.Pool
statChan chan *Stat
workersGroup sync.WaitGroup
statGroup sync.WaitGroup
telemetryChanPoints chan *report.Point
telemetryChanDone chan struct{}
telemetrySrcAddr string
telemetryTags [][2]string
statMapping statsMap
reportTags [][2]string
reportHostname string
)
type statsMap map[string]*StatGroup
const allQueriesLabel = "all queries"
// Parse args:
func init() {
flag.StringVar(&csvDaemonUrls, "urls", "http://localhost:9200", "Daemon URLs, comma-separated. Will be used in a round-robin fashion.")
flag.IntVar(&workers, "workers", 1, "Number of concurrent requests to make.")
flag.IntVar(&debug, "debug", 0, "Whether to print debug messages.")
flag.Int64Var(&limit, "limit", -1, "Limit the number of queries to send.")
flag.Uint64Var(&burnIn, "burn-in", 0, "Number of queries to ignore before collecting statistics.")
flag.Uint64Var(&printInterval, "print-interval", 100, "Print timing stats to stderr after this many queries (0 to disable)")
flag.BoolVar(&prettyPrintResponses, "print-responses", false, "Pretty print JSON response bodies (for correctness checking) (default false).")
flag.StringVar(&memProfile, "memprofile", "", "Write a memory profile to this file.")
flag.StringVar(&telemetryHost, "telemetry-host", "", "InfluxDB host to write telegraf telemetry to (optional).")
flag.StringVar(&telemetryTagsCSV, "telemetry-tags", "", "Tag(s) for telemetry. Format: key0:val0,key1:val1,...")
flag.BoolVar(&telemetryStderr, "telemetry-stderr", false, "Whether to write telemetry also to stderr.")
flag.Uint64Var(&telemetryBatchSize, "telemetry-batch-size", 1000, "Telemetry batch size (lines).")
flag.StringVar(&telemetryBasicAuth, "telemetry-basic-auth", "", "basic auth (username:password) for telemetry.")
flag.StringVar(&reportDatabase, "report-database", "database_benchmarks", "Database name where to store result metrics.")
flag.StringVar(&reportHost, "report-host", "", "Host to send result metrics.")
flag.StringVar(&reportUser, "report-user", "", "User for Host to send result metrics.")
flag.StringVar(&reportPassword, "report-password", "", "User password for Host to send result metrics.")
flag.StringVar(&reportTagsCSV, "report-tags", "", "Comma separated k:v tags to send alongside result metrics.")
flag.Parse()
daemonUrls = strings.Split(csvDaemonUrls, ",")
if len(daemonUrls) == 0 {
log.Fatal("missing 'urls' flag")
}
fmt.Printf("daemon URLs: %v\n", daemonUrls)
if telemetryHost != "" {
fmt.Printf("telemetry destination: %v\n", telemetryHost)
if telemetryBatchSize == 0 {
panic("invalid telemetryBatchSize")
}
var err error
telemetrySrcAddr, err = os.Hostname()
if err != nil {
log.Fatalf("os.Hostname() error: %s", err.Error())
}
fmt.Printf("src addr for telemetry: %v\n", telemetrySrcAddr)
if telemetryTagsCSV != "" {
pairs := strings.Split(telemetryTagsCSV, ",")
for _, pair := range pairs {
fields := strings.SplitN(pair, ":", 2)
tagpair := [2]string{fields[0], fields[1]}
telemetryTags = append(telemetryTags, tagpair)
}
}
fmt.Printf("telemetry tags: %v\n", telemetryTags)
}
if reportHost != "" {
fmt.Printf("results report destination: %v\n", reportHost)
fmt.Printf("results report database: %v\n", reportDatabase)
var err error
reportHostname, err = os.Hostname()
if err != nil {
log.Fatalf("os.Hostname() error: %s", err.Error())
}
fmt.Printf("hostname for results report: %v\n", reportHostname)
if reportTagsCSV != "" {
pairs := strings.Split(reportTagsCSV, ",")
for _, pair := range pairs {
fields := strings.SplitN(pair, ":", 2)
tagpair := [2]string{fields[0], fields[1]}
reportTags = append(reportTags, tagpair)
}
}
fmt.Printf("results report tags: %v\n", reportTags)
}
}
func main() {
// Make pools to minimize heap usage:
queryPool = sync.Pool{
New: func() interface{} {
return &Query{
HumanLabel: make([]byte, 0, 1024),
HumanDescription: make([]byte, 0, 1024),
Method: make([]byte, 0, 1024),
Path: make([]byte, 0, 1024),
Body: make([]byte, 0, 1024),
}
},
}
statPool = sync.Pool{
New: func() interface{} {
return &Stat{
Label: make([]byte, 0, 1024),
Value: 0.0,
}
},
}
// Make data and control channels:
queryChan = make(chan *Query, workers)
statChan = make(chan *Stat, workers)
// Launch the stats processor:
statGroup.Add(1)
go processStats()
if telemetryHost != "" {
telemetryCollector := report.NewCollector(telemetryHost, "telegraf", telemetryBasicAuth)
telemetryChanPoints, telemetryChanDone = report.TelemetryRunAsync(telemetryCollector, telemetryBatchSize, telemetryStderr, burnIn)
}
// Launch the query processors:
for i := 0; i < workers; i++ {
daemonUrl := daemonUrls[i%len(daemonUrls)]
workersGroup.Add(1)
w := NewHTTPClient(daemonUrl, debug)
go processQueries(w, telemetryChanPoints, fmt.Sprintf("%d", i))
}
// Read in jobs, closing the job channel when done:
input := bufio.NewReaderSize(os.Stdin, 1<<20)
wallStart := time.Now()
scan(input)
close(queryChan)
// Block for workers to finish sending requests, closing the stats
// channel when done:
workersGroup.Wait()
close(statChan)
// Wait on the stat collector to finish (and print its results):
statGroup.Wait()
wallEnd := time.Now()
wallTook := wallEnd.Sub(wallStart)
_, err := fmt.Printf("wall clock time: %fsec\n", float64(wallTook.Nanoseconds())/1e9)
if err != nil {
log.Fatal(err)
}
if telemetryHost != "" {
fmt.Println("shutting down telemetry...")
close(telemetryChanPoints)
<-telemetryChanDone
fmt.Println("done shutting down telemetry.")
}
// (Optional) create a memory profile:
if memProfile != "" {
f, err := os.Create(memProfile)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
f.Close()
}
//if reportHost != "" {
// reportParams := &report.QueryReportParams{
// ReportParams: report.ReportParams{
// DBType: "ElasticSearch",
// ReportDatabaseName: reportDatabase,
// ReportHost: reportHost,
// ReportUser: reportUser,
// ReportPassword: reportPassword,
// ReportTags: reportTags,
// Hostname: reportHostname,
// DestinationUrl: csvDaemonUrls,
// Workers: workers,
// ItemLimit: int(limit),
// },
// BurnIn: int64(burnIn),
// }
// stat := statMapping[allQueriesLabel]
// err = report.ReportQueryResult(reportParams, stat.Min, stat.Mean, stat.Max, stat.Count, wallTook)
//
// if err != nil {
// log.Fatal(err)
// }
//}
}
// scan reads encoded Queries and places them onto the workqueue.
func scan(r io.Reader) {
dec := gob.NewDecoder(r)
n := int64(0)
for {
if limit >= 0 && n >= limit {
break
}
q := queryPool.Get().(*Query)
err := dec.Decode(q)
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
q.ID = n
queryChan <- q
n++
}
}
// processQueries reads byte buffers from queryChan and writes them to the
// target server, while tracking latency.
func processQueries(w *HTTPClient, telemetrySink chan *report.Point, telemetryWorkerLabel string) {
opts := &HTTPClientDoOptions{
Debug: debug,
PrettyPrintResponses: prettyPrintResponses,
}
var queriesSeen int64
for q := range queryChan {
ts := time.Now().UnixNano()
lagMillis, err := w.Do(q, opts)
stat := statPool.Get().(*Stat)
stat.Init(q.HumanLabel, lagMillis)
statChan <- stat
queryPool.Put(q)
if err != nil {
log.Fatalf("Error during request: %s\n", err.Error())
}
// Report telemetry, if applicable:
if telemetrySink != nil {
p := report.GetPointFromGlobalPool()
p.Init("benchmark_query", ts)
p.AddTag("src_addr", telemetrySrcAddr)
p.AddTag("dst_addr", w.HostString)
p.AddTag("worker_id", telemetryWorkerLabel)
p.AddFloat64Field("rtt_ms", lagMillis)
p.AddInt64Field("worker_req_num", queriesSeen)
telemetrySink <- p
}
queriesSeen++
}
workersGroup.Done()
}
// processStats collects latency results, aggregating them into summary
// statistics. Optionally, they are printed to stderr at regular intervals.
func processStats() {
statMapping = statsMap{
allQueriesLabel: &StatGroup{},
}
i := uint64(0)
for stat := range statChan {
if i < burnIn {
i++
statPool.Put(stat)
continue
} else if i == burnIn && burnIn > 0 {
_, err := fmt.Fprintf(os.Stderr, "burn-in complete after %d queries with %d workers\n", burnIn, workers)
if err != nil {
log.Fatal(err)
}
}
if _, ok := statMapping[string(stat.Label)]; !ok {
statMapping[string(stat.Label)] = &StatGroup{}
}
statMapping[allQueriesLabel].Push(stat.Value)
statMapping[string(stat.Label)].Push(stat.Value)
statPool.Put(stat)
i++
// print stats to stderr (if printInterval is greater than zero):
if printInterval > 0 && i > 0 && i%printInterval == 0 && (int64(i) < limit || limit < 0) {
_, err := fmt.Fprintf(os.Stderr, "after %d queries with %d workers:\n", i-burnIn, workers)
if err != nil {
log.Fatal(err)
}
fprintStats(os.Stderr, statMapping)
_, err = fmt.Fprintf(os.Stderr, "\n")
if err != nil {
log.Fatal(err)
}
}
}
// the final stats output goes to stdout:
_, err := fmt.Printf("run complete after %d queries with %d workers:\n", i-burnIn, workers)
if err != nil {
log.Fatal(err)
}
fprintStats(os.Stdout, statMapping)
statGroup.Done()
}
// fprintStats pretty-prints stats to the given writer.
func fprintStats(w io.Writer, statGroups statsMap) {
maxKeyLength := 0
keys := make([]string, 0, len(statGroups))
for k := range statGroups {
if len(k) > maxKeyLength {
maxKeyLength = len(k)
}
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := statGroups[k]
minRate := 1e3 / v.Min
meanRate := 1e3 / v.Mean
maxRate := 1e3 / v.Max
paddedKey := fmt.Sprintf("%s", k)
for len(paddedKey) < maxKeyLength {
paddedKey += " "
}
_, err := fmt.Fprintf(w, "%s : min: %8.2fms (%7.2f/sec), mean: %8.2fms (%7.2f/sec), max: %7.2fms (%6.2f/sec), count: %8d, sum: %5.1fsec \n", paddedKey, v.Min, minRate, v.Mean, meanRate, v.Max, maxRate, v.Count, v.Sum/1e3)
if err != nil {
log.Fatal(err)
}
}
}