/
bulk_indexer.go
442 lines (390 loc) · 12.3 KB
/
bulk_indexer.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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 docappender
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"slices"
"strings"
"unsafe"
"github.com/klauspost/compress/gzip"
"go.elastic.co/fastjson"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
jsoniter "github.com/json-iterator/go"
)
// At the time of writing, the go-elasticsearch BulkIndexer implementation
// sends all items to a channel, and multiple persistent worker goroutines will
// receive those items and independently fill up their own buffers. Each one
// will independently flush when their buffer is filled up, or when the flush
// interval elapses. If there are many workers, then this may lead to sparse
// bulk requests.
//
// We take a different approach, where we fill up one bulk request at a time.
// When the buffer is filled up, or the flush interval elapses, we start a new
// goroutine to send the request in the background, with a limit on the number
// of concurrent bulk requests. This way we can ensure bulk requests have the
// maximum possible size, based on configuration and throughput.
type BulkIndexer struct {
client *elasticsearch.Client
maxDocumentRetry int
itemsAdded int
bytesFlushed int
jsonw fastjson.Writer
writer io.Writer
gzipw *gzip.Writer
copyBuf []byte
buf bytes.Buffer
retryCounts map[int]int
}
type BulkIndexerResponseStat struct {
Indexed int64
RetriedDocs int64
FailedDocs []BulkIndexerResponseItem
}
// BulkIndexerResponseItem represents the Elasticsearch response item.
type BulkIndexerResponseItem struct {
Index string `json:"_index"`
Status int `json:"status"`
Position int
Error struct {
Type string `json:"type"`
Reason string `json:"reason"`
} `json:"error,omitempty"`
}
func init() {
jsoniter.RegisterTypeDecoderFunc("docappender.BulkIndexerResponseStat", func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
iter.ReadObjectCB(func(i *jsoniter.Iterator, s string) bool {
switch s {
case "items":
var idx int
iter.ReadArrayCB(func(i *jsoniter.Iterator) bool {
return i.ReadMapCB(func(i *jsoniter.Iterator, s string) bool {
var item BulkIndexerResponseItem
i.ReadObjectCB(func(i *jsoniter.Iterator, s string) bool {
switch s {
case "_index":
item.Index = i.ReadString()
case "status":
item.Status = i.ReadInt()
case "error":
i.ReadObjectCB(func(i *jsoniter.Iterator, s string) bool {
switch s {
case "type":
item.Error.Type = i.ReadString()
case "reason":
// Match Elasticsearch field mapper field value:
// failed to parse field [%s] of type [%s] in %s. Preview of field's value: '%s'
// https://github.com/elastic/elasticsearch/blob/588eabe185ad319c0268a13480465966cef058cd/server/src/main/java/org/elasticsearch/index/mapper/FieldMapper.java#L234
item.Error.Reason, _, _ = strings.Cut(
i.ReadString(), ". Preview",
)
default:
i.Skip()
}
return true
})
default:
i.Skip()
}
return true
})
item.Position = idx
idx++
if item.Error.Type != "" || item.Status > 201 {
(*((*BulkIndexerResponseStat)(ptr))).FailedDocs = append((*((*BulkIndexerResponseStat)(ptr))).FailedDocs, item)
} else {
(*((*BulkIndexerResponseStat)(ptr))).Indexed = (*((*BulkIndexerResponseStat)(ptr))).Indexed + 1
}
return true
})
})
// no need to proceed further, return early
return false
default:
i.Skip()
return true
}
})
})
}
func NewBulkIndexer(client *elasticsearch.Client, compressionLevel int, maxDocRetry int) *BulkIndexer {
b := &BulkIndexer{
client: client,
maxDocumentRetry: maxDocRetry,
retryCounts: make(map[int]int),
}
if compressionLevel != gzip.NoCompression {
b.gzipw, _ = gzip.NewWriterLevel(&b.buf, compressionLevel)
b.writer = b.gzipw
} else {
b.writer = &b.buf
}
return b
}
// BulkIndexer resets b, ready for a new request.
func (b *BulkIndexer) Reset() {
b.bytesFlushed = 0
}
func (b *BulkIndexer) resetBuf() {
b.itemsAdded = 0
b.buf.Reset()
if b.gzipw != nil {
b.gzipw.Reset(&b.buf)
}
}
// Added returns the number of buffered items.
func (b *BulkIndexer) Items() int {
return b.itemsAdded
}
// Len returns the number of buffered bytes.
func (b *BulkIndexer) Len() int {
return b.buf.Len()
}
// BytesFlushed returns the number of bytes flushed by the bulk indexer.
func (b *BulkIndexer) BytesFlushed() int {
return b.bytesFlushed
}
type BulkIndexerItem struct {
Index string
DocumentID string
Body io.WriterTo
}
// Add encodes an item in the buffer.
func (b *BulkIndexer) Add(item BulkIndexerItem) error {
b.writeMeta(item.Index, item.DocumentID)
if _, err := item.Body.WriteTo(b.writer); err != nil {
return fmt.Errorf("failed to write bulk indexer item: %w", err)
}
if _, err := b.writer.Write([]byte("\n")); err != nil {
return fmt.Errorf("failed to write newline: %w", err)
}
b.itemsAdded++
return nil
}
func (b *BulkIndexer) writeMeta(index, documentID string) {
b.jsonw.RawString(`{"create":{`)
if documentID != "" {
b.jsonw.RawString(`"_id":`)
b.jsonw.String(documentID)
}
if index != "" {
if documentID != "" {
b.jsonw.RawByte(',')
}
b.jsonw.RawString(`"_index":`)
b.jsonw.String(index)
}
b.jsonw.RawString("}}\n")
b.writer.Write(b.jsonw.Bytes())
b.jsonw.Reset()
}
// Flush executes a bulk request if there are any items buffered, and clears out the buffer.
func (b *BulkIndexer) Flush(ctx context.Context) (BulkIndexerResponseStat, error) {
if b.itemsAdded == 0 {
return BulkIndexerResponseStat{}, nil
}
if b.gzipw != nil {
if err := b.gzipw.Close(); err != nil {
return BulkIndexerResponseStat{}, fmt.Errorf("failed closing the gzip writer: %w", err)
}
}
if b.maxDocumentRetry > 0 {
if cap(b.copyBuf) < b.buf.Len() {
b.copyBuf = slices.Grow(b.copyBuf, b.buf.Len()-cap(b.copyBuf))
b.copyBuf = b.copyBuf[:cap(b.copyBuf)]
}
n := copy(b.copyBuf, b.buf.Bytes())
b.copyBuf = b.copyBuf[:n]
}
req := esapi.BulkRequest{
Body: &b.buf,
Header: make(http.Header),
FilterPath: []string{"items.*._index", "items.*.status", "items.*.error.type", "items.*.error.reason"},
}
if b.gzipw != nil {
req.Header.Set("Content-Encoding", "gzip")
}
bytesFlushed := b.buf.Len()
res, err := req.Do(ctx, b.client)
if err != nil {
b.resetBuf()
return BulkIndexerResponseStat{}, fmt.Errorf("failed to execute the request: %w", err)
}
defer res.Body.Close()
// Reset the buffer and gzip writer so they can be reused in case 429s
// were received.
b.resetBuf()
// Record the number of flushed bytes only when err == nil. The body may
// not have been sent otherwise.
b.bytesFlushed = bytesFlushed
var resp BulkIndexerResponseStat
if res.IsError() {
if res.StatusCode == http.StatusTooManyRequests {
return resp, errorTooManyRequests{res: res}
}
return resp, fmt.Errorf("flush failed: %s", res.String())
}
if err := jsoniter.NewDecoder(res.Body).Decode(&resp); err != nil {
return resp, fmt.Errorf("error decoding bulk response: %w", err)
}
// Only run the retry logic if document retries are enabled
if b.maxDocumentRetry > 0 {
buf := make([]byte, 0, 1024)
// Eliminate previous retry counts that aren't present in the bulk
// request response.
for k := range b.retryCounts {
found := false
for _, res := range resp.FailedDocs {
if res.Position == k {
found = true
break
}
}
if !found {
// Retried request succeeded, remove from retry counts
delete(b.retryCounts, k)
}
}
tmp := resp.FailedDocs[:0]
lastln := 0
lastIdx := 0
var gr *gzip.Reader
if b.gzipw != nil {
gr, err = gzip.NewReader(bytes.NewReader(b.copyBuf))
if err != nil {
return resp, fmt.Errorf("failed to decompress request payload: %w", err)
}
defer gr.Close()
}
// keep track of the previous newlines
// the buffer is being read lazily
seen := 0
for _, res := range resp.FailedDocs {
if res.Status == http.StatusTooManyRequests {
// there are two lines for each document:
// - action
// - document
//
// Find the document by looking up the newline separators.
// First the newline (if exists) before the 'action' then the
// newline at the end of the 'document' line.
startln := res.Position * 2
endln := startln + 2
// Increment 429 count for the positions found.
count := b.retryCounts[res.Position] + 1
// check if we are above the maxDocumentRetry setting
if count > b.maxDocumentRetry {
// do not retry, return the document as failed
tmp = append(tmp, res)
continue
}
// Since some items may have succeeded, counter positions need
// to be updated to match the next current buffer position.
b.retryCounts[b.itemsAdded] = count
if b.gzipw != nil {
// First loop, read from the gzip reader
if len(buf) == 0 {
n, err := gr.Read(buf[:cap(buf)])
if err != nil && err != io.EOF {
return resp, fmt.Errorf("failed to read from compressed buffer: %w", err)
}
buf = buf[:n]
}
// newlines in the current buf
newlines := bytes.Count(buf, []byte{'\n'})
// loop until we've seen the start newline
for seen+newlines < startln {
seen += newlines
n, err := gr.Read(buf[:cap(buf)])
if err != nil && err != io.EOF {
return resp, fmt.Errorf("failed to read from compressed buffer: %w", err)
}
buf = buf[:n]
newlines = bytes.Count(buf, []byte{'\n'})
}
startIdx := indexnth(buf, startln-seen, '\n') + 1
endIdx := indexnth(buf, endln-seen, '\n') + 1
// If the end newline is not in the buffer read more data
if endIdx == 0 {
// Write what we have
b.writer.Write(buf[startIdx:])
// loop until we've seen the end newline
for seen+newlines < endln {
seen += newlines
n, err := gr.Read(buf[:cap(buf)])
if err != nil && err != io.EOF {
return resp, fmt.Errorf("failed to read from compressed buffer: %w", err)
}
buf = buf[:n]
newlines = bytes.Count(buf, []byte{'\n'})
if seen+newlines < endln {
// endln is not here, write what we have and keep going
b.writer.Write(buf)
}
}
// try again to find the end newline in the extra data
// we just read.
endIdx = indexnth(buf, endln-seen, '\n') + 1
b.writer.Write(buf[:endIdx])
} else {
// If the end newline is in the buffer write the event
b.writer.Write(buf[startIdx:endIdx])
}
} else {
startIdx := indexnth(b.copyBuf[lastIdx:], startln-lastln, '\n') + 1
endIdx := indexnth(b.copyBuf[lastIdx:], endln-lastln, '\n') + 1
b.writer.Write(b.copyBuf[lastIdx:][startIdx:endIdx])
lastln = endln
lastIdx += endIdx
}
resp.RetriedDocs++
b.itemsAdded++
} else {
// If it's not a 429 treat the document as failed
tmp = append(tmp, res)
}
}
if len(tmp) > 0 {
resp.FailedDocs = tmp
}
}
return resp, nil
}
// indexnth returns the index of the nth instance of sep in s.
// It returns -1 if sep is not present in s or nth is 0.
func indexnth(s []byte, nth int, sep rune) int {
if nth == 0 {
return -1
}
count := 0
return bytes.IndexFunc(s, func(r rune) bool {
if r == sep {
count++
}
return nth == count
})
}
type errorTooManyRequests struct {
res *esapi.Response
}
func (e errorTooManyRequests) Error() string {
return fmt.Sprintf("flush failed: %s", e.res.String())
}