-
Notifications
You must be signed in to change notification settings - Fork 244
/
corebulk.go
414 lines (366 loc) · 11.5 KB
/
corebulk.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
// Copyright 2013 Matthew Baird
// 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 elastigo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"sync"
"sync/atomic"
"time"
)
const (
// Max buffer size in bytes before flushing to elasticsearch
BulkMaxBuffer = 16384
// Max number of Docs to hold in buffer before forcing flush
BulkMaxDocs = 100
// Max delay before forcing a flush to Elasticearch
BulkDelaySeconds = 5
// maximum wait shutdown seconds
MAX_SHUTDOWN_SECS = 5
)
type ErrorBuffer struct {
Err error
Buf *bytes.Buffer
}
// A bulk indexer creates goroutines, and channels for connecting and sending data
// to elasticsearch in bulk, using buffers.
type BulkIndexer struct {
conn *Conn
// We are creating a variable defining the func responsible for sending
// to allow a mock sendor for test purposes
Sender func(*bytes.Buffer) error
// The refresh parameter can be set to true in order to refresh the
// relevant primary and replica shards immediately after the bulk
// operation has occurred
Refresh bool
// If we encounter an error in sending, we are going to retry for this long
// before returning an error
// if 0 it will not retry
RetryForSeconds int
// channel for getting errors
ErrorChannel chan *ErrorBuffer
// channel for sending to background indexer
bulkChannel chan []byte
// numErrors is a running total of errors seen
numErrors uint64
// shutdown channel
shutdownChan chan chan struct{}
// channel to shutdown timer
timerDoneChan chan struct{}
// Channel to send a complete byte.Buffer to the http sendor
sendBuf chan *bytes.Buffer
// byte buffer for docs that have been converted to bytes, but not yet sent
buf *bytes.Buffer
// Buffer for Max number of time before forcing flush
BufferDelayMax time.Duration
// Max buffer size in bytes before flushing to elasticsearch
BulkMaxBuffer int // 1048576
// Max number of Docs to hold in buffer before forcing flush
BulkMaxDocs int // 100
// Number of documents we have send through so far on this session
docCt int
// Max number of http conns in flight at one time
maxConns int
// If we are indexing enough docs per bufferdelaymax, we won't need to do time
// based eviction, else we do.
needsTimeBasedFlush bool
// Lock for document writes/operations
mu sync.Mutex
// Wait Group for the http sends
sendWg *sync.WaitGroup
}
func (b *BulkIndexer) NumErrors() uint64 {
return atomic.LoadUint64(&b.numErrors)
}
func (c *Conn) NewBulkIndexer(maxConns int) *BulkIndexer {
b := BulkIndexer{conn: c, sendBuf: make(chan *bytes.Buffer, maxConns)}
b.needsTimeBasedFlush = true
b.buf = new(bytes.Buffer)
b.maxConns = maxConns
b.BulkMaxBuffer = BulkMaxBuffer
b.BulkMaxDocs = BulkMaxDocs
b.BufferDelayMax = time.Duration(BulkDelaySeconds) * time.Second
b.bulkChannel = make(chan []byte, 100)
b.sendWg = new(sync.WaitGroup)
b.timerDoneChan = make(chan struct{})
return &b
}
// A bulk indexer with more control over error handling
// @maxConns is the max number of in flight http requests
// @retrySeconds is # of seconds to wait before retrying falied requests
//
// done := make(chan bool)
// BulkIndexerGlobalRun(100, done)
func (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer {
b := c.NewBulkIndexer(maxConns)
b.RetryForSeconds = retrySeconds
b.ErrorChannel = make(chan *ErrorBuffer, 20)
return b
}
// Starts this bulk Indexer running, this Run opens a go routine so is
// Non blocking
func (b *BulkIndexer) Start() {
b.shutdownChan = make(chan chan struct{})
go func() {
// XXX(j): Refactor this stuff to use an interface.
if b.Sender == nil {
b.Sender = b.Send
}
// Backwards compatibility
b.startHttpSender()
b.startDocChannel()
b.startTimer()
ch := <-b.shutdownChan
time.Sleep(2 * time.Millisecond)
b.Flush()
b.shutdown()
ch <- struct{}{}
}()
}
// Stop stops the bulk indexer, blocking the caller until it is complete.
func (b *BulkIndexer) Stop() {
ch := make(chan struct{}, 1)
b.shutdownChan <- ch
select {
case <-ch:
// done
case <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)):
// timeout!
}
}
func (b *BulkIndexer) PendingDocuments() int {
return b.docCt
}
// Flush all current documents to ElasticSearch
func (b *BulkIndexer) Flush() {
b.mu.Lock()
if b.docCt > 0 {
b.send(b.buf)
}
b.mu.Unlock()
}
func (b *BulkIndexer) startHttpSender() {
// this sends http requests to elasticsearch it uses maxConns to open up that
// many goroutines, each of which will synchronously call ElasticSearch
// in theory, the whole set will cause a backup all the way to IndexBulk if
// we have consumed all maxConns
for i := 0; i < b.maxConns; i++ {
b.sendWg.Add(1)
go func() {
for buf := range b.sendBuf {
// Copy for the potential re-send.
bufCopy := bytes.NewBuffer(buf.Bytes())
err := b.Sender(buf)
// Perhaps a b.FailureStrategy(err) ?? with different types of strategies
// 1. Retry, then panic
// 2. Retry then return error and let runner decide
// 3. Retry, then log to disk? retry later?
if err != nil {
buf = bytes.NewBuffer(bufCopy.Bytes())
if b.RetryForSeconds > 0 {
time.Sleep(time.Second * time.Duration(b.RetryForSeconds))
err = b.Sender(bufCopy)
if err == nil {
// Successfully re-sent with no error
continue
}
}
if b.ErrorChannel != nil {
b.ErrorChannel <- &ErrorBuffer{err, buf}
}
}
}
b.sendWg.Done()
}()
}
}
// start a timer for checking back and forcing flush ever BulkDelaySeconds seconds
// even if we haven't hit max messages/size
func (b *BulkIndexer) startTimer() {
ticker := time.NewTicker(b.BufferDelayMax)
go func() {
for {
select {
case <-ticker.C:
b.mu.Lock()
// don't send unless last sendor was the time,
// otherwise an indication of other thresholds being hit
// where time isn't needed
if b.buf.Len() > 0 && b.needsTimeBasedFlush {
b.needsTimeBasedFlush = true
b.send(b.buf)
} else if b.buf.Len() > 0 {
b.needsTimeBasedFlush = true
}
b.mu.Unlock()
case <-b.timerDoneChan:
// shutdown this go routine
ticker.Stop()
return
}
}
}()
}
func (b *BulkIndexer) startDocChannel() {
// This goroutine accepts incoming byte arrays from the IndexBulk function and
// writes to buffer
go func() {
for docBytes := range b.bulkChannel {
b.mu.Lock()
b.docCt += 1
b.buf.Write(docBytes)
if b.buf.Len() >= b.BulkMaxBuffer || b.docCt >= b.BulkMaxDocs {
b.needsTimeBasedFlush = false
//log.Printf("Send due to size: docs=%d bufsize=%d", b.docCt, b.buf.Len())
b.send(b.buf)
}
b.mu.Unlock()
}
}()
}
func (b *BulkIndexer) send(buf *bytes.Buffer) {
//b2 := *b.buf
b.sendBuf <- buf
b.buf = new(bytes.Buffer)
// b.buf.Reset()
b.docCt = 0
}
func (b *BulkIndexer) shutdown() {
// This must be called after Flush()
close(b.timerDoneChan)
close(b.sendBuf)
close(b.bulkChannel)
b.sendWg.Wait()
}
// The index bulk API adds or updates a typed JSON document to a specific index, making it searchable.
// it operates by buffering requests, and ocassionally flushing to elasticsearch
// http://www.elasticsearch.org/guide/reference/api/bulk.html
func (b *BulkIndexer) Index(index string, _type string, id, parent, ttl string, date *time.Time, data interface{}) error {
//{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
by, err := WriteBulkBytes("index", index, _type, id, parent, ttl, date, data)
if err != nil {
return err
}
b.bulkChannel <- by
return nil
}
func (b *BulkIndexer) Update(index string, _type string, id, parent, ttl string, date *time.Time, data interface{}) error {
//{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
by, err := WriteBulkBytes("update", index, _type, id, parent, ttl, date, data)
if err != nil {
return err
}
b.bulkChannel <- by
return nil
}
func (b *BulkIndexer) Delete(index, _type, id string) {
queryLine := fmt.Sprintf("{\"delete\":{\"_index\":%q,\"_type\":%q,\"_id\":%q}}\n", index, _type, id)
b.bulkChannel <- []byte(queryLine)
return
}
func (b *BulkIndexer) UpdateWithWithScript(index string, _type string, id, parent, ttl string, date *time.Time, script string) error {
var data map[string]interface{} = make(map[string]interface{})
data["script"] = script
return b.Update(index, _type, id, parent, ttl, date, data)
}
func (b *BulkIndexer) UpdateWithPartialDoc(index string, _type string, id, parent, ttl string, date *time.Time, partialDoc interface{}, upsert bool) error {
var data map[string]interface{} = make(map[string]interface{})
data["doc"] = partialDoc
if upsert {
data["doc_as_upsert"] = true
}
return b.Update(index, _type, id, parent, ttl, date, data)
}
// This does the actual send of a buffer, which has already been formatted
// into bytes of ES formatted bulk data
func (b *BulkIndexer) Send(buf *bytes.Buffer) error {
type responseStruct struct {
Took int64 `json:"took"`
Errors bool `json:"errors"`
Items []map[string]interface{} `json:"items"`
}
response := responseStruct{}
body, err := b.conn.DoCommand("POST", fmt.Sprintf("/_bulk?refresh=%t", b.Refresh), nil, buf)
if err != nil {
atomic.AddUint64(&b.numErrors, 1)
return err
}
// check for response errors, bulk insert will give 200 OK but then include errors in response
jsonErr := json.Unmarshal(body, &response)
if jsonErr == nil {
if response.Errors {
atomic.AddUint64(&b.numErrors, uint64(len(response.Items)))
return fmt.Errorf("Bulk Insertion Error. Failed item count [%d]", len(response.Items))
}
}
return nil
}
// Given a set of arguments for index, type, id, data create a set of bytes that is formatted for bulkd index
// http://www.elasticsearch.org/guide/reference/api/bulk.html
func WriteBulkBytes(op string, index string, _type string, id, parent, ttl string, date *time.Time, data interface{}) ([]byte, error) {
// only index and update are currently supported
if op != "index" && op != "update" {
return nil, errors.New(fmt.Sprintf("Operation '%s' is not yet supported", op))
}
// First line
buf := bytes.Buffer{}
buf.WriteString(fmt.Sprintf(`{"%s":{"_index":"`, op))
buf.WriteString(index)
buf.WriteString(`","_type":"`)
buf.WriteString(_type)
buf.WriteString(`"`)
if len(id) > 0 {
buf.WriteString(`,"_id":"`)
buf.WriteString(id)
buf.WriteString(`"`)
}
if len(parent) > 0 {
buf.WriteString(`,"_parent":"`)
buf.WriteString(parent)
buf.WriteString(`"`)
}
if op == "update" {
buf.WriteString(`,"_retry_on_conflict":3`)
}
if len(ttl) > 0 {
buf.WriteString(`,"ttl":"`)
buf.WriteString(ttl)
buf.WriteString(`"`)
}
if date != nil {
buf.WriteString(`,"_timestamp":"`)
buf.WriteString(strconv.FormatInt(date.UnixNano()/1e6, 10))
buf.WriteString(`"`)
}
buf.WriteString(`}}`)
buf.WriteRune('\n')
//buf.WriteByte('\n')
switch v := data.(type) {
case *bytes.Buffer:
io.Copy(&buf, v)
case []byte:
buf.Write(v)
case string:
buf.WriteString(v)
default:
body, jsonErr := json.Marshal(data)
if jsonErr != nil {
return nil, jsonErr
}
buf.Write(body)
}
buf.WriteRune('\n')
return buf.Bytes(), nil
}