-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.go
267 lines (230 loc) · 6.79 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
// bulk_load_bcetsdb loads an BceTSDB daemon with data from stdin.
//
// The caller is responsible for assuring that the database is empty before
// bulk load.
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"log"
"os"
"strings"
"sync"
"time"
"github.com/caict-benchmark/BDC-TS/util/report"
"github.com/klauspost/compress/gzip"
"github.com/pkg/profile"
)
// Program option vars:
var (
csvDaemonUrls string
daemonUrls []string
workers int
batchSize int
backoff time.Duration
doLoad bool
memprofile bool
reportDatabase string
reportHost string
reportUser string
reportPassword string
reportTagsCSV string
)
// Global vars
var (
bufPool sync.Pool
batchChan chan *bytes.Buffer
inputDone chan struct{}
workersGroup sync.WaitGroup
backingOffChan chan bool
backingOffDone chan struct{}
reportTags [][2]string
reportHostname string
)
// Parse args:
func init() {
flag.StringVar(&csvDaemonUrls, "urls", "http://localhost:8086", "BceTSDB URLs, comma-separated. Will be used in a round-robin fashion.")
flag.IntVar(&batchSize, "batch-size", 5000, "Batch size (input lines).")
flag.IntVar(&workers, "workers", 1, "Number of parallel requests to make.")
//flag.DurationVar(&backoff, "backoff", time.Second, "Time to sleep between requests when server indicates backpressure is needed.")
flag.BoolVar(&doLoad, "do-load", true, "Whether to write data. Set this flag to false to check input read speed.")
flag.BoolVar(&memprofile, "memprofile", false, "Whether to write a memprofile (file automatically determined).")
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 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() {
if memprofile {
p := profile.Start(profile.MemProfile)
defer p.Stop()
}
bufPool = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 4*1024*1024))
},
}
batchChan = make(chan *bytes.Buffer, workers)
inputDone = make(chan struct{})
backingOffChan = make(chan bool, 100)
backingOffDone = make(chan struct{})
for i := 0; i < workers; i++ {
daemonUrl := daemonUrls[i%len(daemonUrls)]
workersGroup.Add(1)
cfg := HTTPWriterConfig{
Host: daemonUrl,
}
go processBatches(NewHTTPWriter(cfg))
}
go processBackoffMessages()
start := time.Now()
itemsRead := scan(batchSize)
<-inputDone
close(batchChan)
workersGroup.Wait()
close(backingOffChan)
<-backingOffDone
end := time.Now()
took := end.Sub(start)
rate := float64(itemsRead) / float64(took.Seconds())
fmt.Printf("loaded %d items in %fsec with %d workers (mean values rate %f/sec)\n", itemsRead, took.Seconds(), workers, rate)
if reportHost != "" {
reportParams := &report.LoadReportParams{
ReportParams: report.ReportParams{
DBType: "BceTSDB",
ReportDatabaseName: reportDatabase,
ReportHost: reportHost,
ReportUser: reportUser,
ReportPassword: reportPassword,
ReportTags: reportTags,
Hostname: reportHostname,
DestinationUrl: daemonUrls[0],
Workers: workers,
ItemLimit: -1,
},
IsGzip: true,
BatchSize: batchSize,
}
err := report.ReportLoadResult(reportParams, itemsRead, rate, -1, took)
if err != nil {
log.Fatal(err)
}
}
}
// TODO
// scan reads one line at a time from stdin.
// When the requested number of lines per batch is met, send a batch over batchChan for the workers to write.
func scan(linesPerBatch int) int64 {
buf := bufPool.Get().(*bytes.Buffer)
zw := gzip.NewWriter(buf)
var n int
var itemsRead int64
openbracket := []byte("{\"datapoints\":[\"")
closebracket := []byte("\"]}")
commaspace := []byte("\", \"")
zw.Write(openbracket)
scanner := bufio.NewScanner(bufio.NewReaderSize(os.Stdin, 4*1024*1024))
for scanner.Scan() {
itemsRead++
if n > 0 {
zw.Write(commaspace)
}
zw.Write(scanner.Bytes())
n++
if n >= linesPerBatch {
zw.Write(closebracket)
zw.Close()
batchChan <- buf
buf = bufPool.Get().(*bytes.Buffer)
zw = gzip.NewWriter(buf)
zw.Write(openbracket)
n = 0
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("Error reading input: %s", err.Error())
}
// Finished reading input, make sure last batch goes out.
if n > 0 {
zw.Write(closebracket)
zw.Close()
batchChan <- buf
}
// Closing inputDone signals to the application that we've read everything and can now shut down.
close(inputDone)
return itemsRead
}
// processBatches reads byte buffers from batchChan and writes them to the target server, while tracking stats on the write.
func processBatches(w LineProtocolWriter) {
for batch := range batchChan {
// Write the batch: try until backoff is not needed.
if doLoad {
var err error
for {
//log.Print(batch.Bytes())
_, err = w.WriteLineProtocol(batch.Bytes())
if err == BackoffError {
backingOffChan <- true
time.Sleep(backoff)
} else {
backingOffChan <- false
break
}
}
if err != nil {
log.Fatalf("Error writing: %s\n", err.Error())
}
}
// Return the batch buffer to the pool.
batch.Reset()
bufPool.Put(batch)
}
workersGroup.Done()
}
func processBackoffMessages() {
var totalBackoffSecs float64
var start time.Time
last := false
for this := range backingOffChan {
if this && !last {
start = time.Now()
last = true
} else if !this && last {
took := time.Now().Sub(start)
fmt.Printf("backoff took %.02fsec\n", took.Seconds())
totalBackoffSecs += took.Seconds()
last = false
start = time.Now()
}
}
fmt.Printf("backoffs took a total of %fsec of runtime\n", totalBackoffSecs)
backingOffDone <- struct{}{}
}