forked from influxdata/influxdb-comparisons
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
232 lines (195 loc) · 5.44 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
// bulk_load_opentsdb loads an OpenTSDB 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/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
)
// Global vars
var (
bufPool sync.Pool
batchChan chan *bytes.Buffer
inputDone chan struct{}
workersGroup sync.WaitGroup
backingOffChan chan bool
backingOffDone chan struct{}
)
// Parse args:
func init() {
flag.StringVar(&csvDaemonUrls, "urls", "http://localhost:8086", "OpenTSDB 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.Parse()
daemonUrls = strings.Split(csvDaemonUrls, ",")
if len(daemonUrls) == 0 {
log.Fatal("missing 'urls' flag")
}
fmt.Printf("daemon URLs: %v\n", daemonUrls)
}
func main() {
if memprofile {
p := profile.Start(profile.MemProfile)
defer p.Stop()
}
if doLoad {
// check that there are no pre-existing databases:
existingDatabases, err := listDatabases(daemonUrls[0])
if err != nil {
log.Fatal(err)
}
if len(existingDatabases) > 0 {
log.Fatalf("There are databases already in the data store. If you know what you are doing, run the command:\ncurl 'http://localhost:8086/query?q=drop%%20database%%20%s'\n", existingDatabases[0])
}
}
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 rate %f/sec)\n", itemsRead, took.Seconds(), workers, rate)
}
// 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("[")
closebracket := []byte("]")
commaspace := []byte(", ")
newline := []byte("\n")
zw.Write(openbracket)
zw.Write(newline)
scanner := bufio.NewScanner(bufio.NewReaderSize(os.Stdin, 4*1024*1024))
for scanner.Scan() {
itemsRead++
if n > 0 {
zw.Write(commaspace)
zw.Write(newline)
}
zw.Write(scanner.Bytes())
n++
if n >= linesPerBatch {
zw.Write(newline)
zw.Write(closebracket)
zw.Close()
batchChan <- buf
buf = bufPool.Get().(*bytes.Buffer)
zw = gzip.NewWriter(buf)
zw.Write(openbracket)
zw.Write(newline)
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(newline)
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 {
_, 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())
}
}
//fmt.Println(string(batch.Bytes()))
// 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{}{}
}
// TODO(rw): listDatabases lists the existing data in OpenTSDB.
func listDatabases(daemonUrl string) ([]string, error) {
return nil, nil
}