forked from open-telemetry/opentelemetry-collector-contrib
/
logs_exporter_test.go
489 lines (412 loc) · 13.3 KB
/
logs_exporter_test.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package elasticsearchexporter
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
"go.uber.org/zap/zaptest"
)
func TestExporter_New(t *testing.T) {
type validate func(*testing.T, *elasticsearchLogsExporter, error)
success := func(t *testing.T, exporter *elasticsearchLogsExporter, err error) {
require.NoError(t, err)
require.NotNil(t, exporter)
}
successWithInternalModel := func(expectedModel *encodeModel) validate {
return func(t *testing.T, exporter *elasticsearchLogsExporter, err error) {
assert.NoError(t, err)
assert.EqualValues(t, expectedModel, exporter.model)
}
}
successWithDeprecatedIndexOption := func(index string) validate {
return func(t *testing.T, exporter *elasticsearchLogsExporter, err error) {
require.NoError(t, err)
require.NotNil(t, exporter)
require.EqualValues(t, index, exporter.index)
}
}
failWith := func(want error) validate {
return func(t *testing.T, exporter *elasticsearchLogsExporter, err error) {
require.Nil(t, exporter)
require.Error(t, err)
if !errors.Is(err, want) {
t.Fatalf("Expected error '%v', but got '%v'", want, err)
}
}
}
failWithMessage := func(msg string) validate {
return func(t *testing.T, exporter *elasticsearchLogsExporter, err error) {
require.Nil(t, exporter)
require.Error(t, err)
require.Contains(t, err.Error(), msg)
}
}
tests := map[string]struct {
config *Config
want validate
env map[string]string
}{
"no endpoint": {
config: withDefaultConfig(),
want: failWith(errConfigNoEndpoint),
},
"create from default config with ELASTICSEARCH_URL environment variable": {
config: withDefaultConfig(),
want: success,
env: map[string]string{defaultElasticsearchEnvName: "localhost:9200"},
},
"create from default with endpoints": {
config: withDefaultConfig(func(cfg *Config) {
cfg.Endpoints = []string{"test:9200"}
}),
want: success,
},
"create from default config with endpoints and deprecated index_option": {
config: withDefaultConfig(func(cfg *Config) {
cfg.Index = "foo-index"
cfg.Endpoints = []string{"test:9200"}
}),
want: successWithDeprecatedIndexOption("foo-index"),
},
"create with cloudid": {
config: withDefaultConfig(func(cfg *Config) {
cfg.CloudID = "foo:YmFyLmNsb3VkLmVzLmlvJGFiYzEyMyRkZWY0NTY="
}),
want: success,
},
"create with invalid cloudid": {
config: withDefaultConfig(func(cfg *Config) {
cfg.CloudID = "invalid"
}),
want: failWithMessage("cannot parse CloudID"),
},
"fail if endpoint and cloudid are set": {
config: withDefaultConfig(func(cfg *Config) {
cfg.Endpoints = []string{"test:9200"}
cfg.CloudID = "foo:YmFyLmNsb3VkLmVzLmlvJGFiYzEyMyRkZWY0NTY="
}),
want: failWithMessage("Addresses and CloudID are set"),
},
"create with custom request header": {
config: withDefaultConfig(func(cfg *Config) {
cfg.Endpoints = []string{"test:9200"}
cfg.Headers = map[string]string{
"foo": "bah",
}
}),
want: success,
},
"create with custom dedup and dedot values": {
config: withDefaultConfig(func(cfg *Config) {
cfg.Endpoints = []string{"test:9200"}
cfg.Mapping.Dedot = false
cfg.Mapping.Dedup = true
}),
want: successWithInternalModel(&encodeModel{dedot: false, dedup: true, mode: MappingECS}),
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
env := test.env
if len(env) == 0 {
env = map[string]string{defaultElasticsearchEnvName: ""}
}
for k, v := range env {
t.Setenv(k, v)
}
exporter, err := newLogsExporter(zap.NewNop(), test.config)
if exporter != nil {
defer func() {
require.NoError(t, exporter.Shutdown(context.TODO()))
}()
}
test.want(t, exporter, err)
})
}
}
func TestExporter_PushEvent(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping test on Windows, see https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/10178")
}
t.Run("publish with success", func(t *testing.T) {
rec := newBulkRecorder()
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
rec.Record(docs)
return itemsAllOK(docs)
})
exporter := newTestExporter(t, server.URL)
mustSend(t, exporter, `{"message": "test1"}`)
mustSend(t, exporter, `{"message": "test2"}`)
rec.WaitItems(2)
})
t.Run("publish with dynamic index", func(t *testing.T) {
rec := newBulkRecorder()
var (
prefix = "resprefix-"
suffix = "-attrsuffix"
index = "someindex"
)
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
rec.Record(docs)
data, err := docs[0].Action.MarshalJSON()
assert.NoError(t, err)
jsonVal := map[string]any{}
err = json.Unmarshal(data, &jsonVal)
assert.NoError(t, err)
create := jsonVal["create"].(map[string]any)
expected := fmt.Sprintf("%s%s%s", prefix, index, suffix)
assert.Equal(t, expected, create["_index"].(string))
return itemsAllOK(docs)
})
exporter := newTestLogsExporter(t, server.URL, func(cfg *Config) {
cfg.LogsIndex = index
cfg.LogsDynamicIndex.Enabled = true
})
mustSendLogsWithAttributes(t, exporter,
map[string]string{
indexPrefix: "attrprefix-",
indexSuffix: suffix,
},
map[string]string{
indexPrefix: prefix,
},
)
rec.WaitItems(1)
})
t.Run("publish with logstash index format enabled and dynamic index disabled", func(t *testing.T) {
var defaultCfg Config
rec := newBulkRecorder()
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
rec.Record(docs)
data, err := docs[0].Action.MarshalJSON()
assert.NoError(t, err)
jsonVal := map[string]any{}
err = json.Unmarshal(data, &jsonVal)
assert.NoError(t, err)
create := jsonVal["create"].(map[string]any)
assert.Equal(t, strings.Contains(create["_index"].(string), defaultCfg.LogsIndex), true)
return itemsAllOK(docs)
})
exporter := newTestLogsExporter(t, server.URL, func(cfg *Config) {
cfg.LogstashFormat.Enabled = true
cfg.LogsIndex = "not-used-index"
defaultCfg = *cfg
})
mustSendLogsWithAttributes(t, exporter, nil, nil)
rec.WaitItems(1)
})
t.Run("publish with logstash index format enabled and dynamic index enabled", func(t *testing.T) {
var (
prefix = "resprefix-"
suffix = "-attrsuffix"
index = "someindex"
)
rec := newBulkRecorder()
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
rec.Record(docs)
data, err := docs[0].Action.MarshalJSON()
assert.NoError(t, err)
jsonVal := map[string]any{}
err = json.Unmarshal(data, &jsonVal)
assert.NoError(t, err)
create := jsonVal["create"].(map[string]any)
expected := fmt.Sprintf("%s%s%s", prefix, index, suffix)
assert.Equal(t, strings.Contains(create["_index"].(string), expected), true)
return itemsAllOK(docs)
})
exporter := newTestLogsExporter(t, server.URL, func(cfg *Config) {
cfg.LogsIndex = index
cfg.LogsDynamicIndex.Enabled = true
cfg.LogstashFormat.Enabled = true
})
mustSendLogsWithAttributes(t, exporter,
map[string]string{
indexPrefix: "attrprefix-",
indexSuffix: suffix,
},
map[string]string{
indexPrefix: prefix,
},
)
rec.WaitItems(1)
})
t.Run("retry http request", func(t *testing.T) {
failures := 0
rec := newBulkRecorder()
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
if failures == 0 {
failures++
return nil, &httpTestError{message: "oops"}
}
rec.Record(docs)
return itemsAllOK(docs)
})
exporter := newTestExporter(t, server.URL)
mustSend(t, exporter, `{"message": "test1"}`)
rec.WaitItems(1)
})
t.Run("no retry", func(t *testing.T) {
configurations := map[string]func(string) *Config{
"max_requests limited": withTestExporterConfig(func(cfg *Config) {
cfg.Retry.MaxRequests = 1
cfg.Retry.InitialInterval = 1 * time.Millisecond
cfg.Retry.MaxInterval = 10 * time.Millisecond
}),
"retry.enabled is false": withTestExporterConfig(func(cfg *Config) {
cfg.Retry.Enabled = false
cfg.Retry.MaxRequests = 10
cfg.Retry.InitialInterval = 1 * time.Millisecond
cfg.Retry.MaxInterval = 10 * time.Millisecond
}),
}
handlers := map[string]func(attempts *atomic.Int64) bulkHandler{
"fail http request": func(attempts *atomic.Int64) bulkHandler {
return func([]itemRequest) ([]itemResponse, error) {
attempts.Add(1)
return nil, &httpTestError{message: "oops"}
}
},
"fail item": func(attempts *atomic.Int64) bulkHandler {
return func(docs []itemRequest) ([]itemResponse, error) {
attempts.Add(1)
return itemsReportStatus(docs, http.StatusTooManyRequests)
}
},
}
for name, handler := range handlers {
t.Run(name, func(t *testing.T) {
t.Parallel()
for name, configurer := range configurations {
t.Run(name, func(t *testing.T) {
t.Parallel()
attempts := &atomic.Int64{}
server := newESTestServer(t, handler(attempts))
testConfig := configurer(server.URL)
exporter := newTestExporter(t, server.URL, func(cfg *Config) { *cfg = *testConfig })
mustSend(t, exporter, `{"message": "test1"}`)
time.Sleep(200 * time.Millisecond)
assert.Equal(t, int64(1), attempts.Load())
})
}
})
}
})
t.Run("do not retry invalid request", func(t *testing.T) {
attempts := &atomic.Int64{}
server := newESTestServer(t, func(_ []itemRequest) ([]itemResponse, error) {
attempts.Add(1)
return nil, &httpTestError{message: "oops", status: http.StatusBadRequest}
})
exporter := newTestExporter(t, server.URL)
mustSend(t, exporter, `{"message": "test1"}`)
time.Sleep(200 * time.Millisecond)
assert.Equal(t, int64(1), attempts.Load())
})
t.Run("retry single item", func(t *testing.T) {
var attempts int
rec := newBulkRecorder()
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
attempts++
if attempts == 1 {
return itemsReportStatus(docs, http.StatusTooManyRequests)
}
rec.Record(docs)
return itemsAllOK(docs)
})
exporter := newTestExporter(t, server.URL)
mustSend(t, exporter, `{"message": "test1"}`)
rec.WaitItems(1)
})
t.Run("do not retry bad item", func(t *testing.T) {
attempts := &atomic.Int64{}
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
attempts.Add(1)
return itemsReportStatus(docs, http.StatusBadRequest)
})
exporter := newTestExporter(t, server.URL)
mustSend(t, exporter, `{"message": "test1"}`)
time.Sleep(200 * time.Millisecond)
assert.Equal(t, int64(1), attempts.Load())
})
t.Run("only retry failed items", func(t *testing.T) {
var attempts [3]int
var wg sync.WaitGroup
wg.Add(1)
const retryIdx = 1
server := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {
resp := make([]itemResponse, len(docs))
for i, doc := range docs {
resp[i].Status = http.StatusOK
var idxInfo struct{ Idx int }
if err := json.Unmarshal(doc.Document, &idxInfo); err != nil {
panic(err)
}
if idxInfo.Idx == retryIdx {
if attempts[retryIdx] == 0 {
resp[i].Status = http.StatusTooManyRequests
} else {
defer wg.Done()
}
}
attempts[idxInfo.Idx]++
}
return resp, nil
})
exporter := newTestExporter(t, server.URL, func(cfg *Config) {
cfg.Flush.Interval = 50 * time.Millisecond
cfg.Retry.InitialInterval = 1 * time.Millisecond
cfg.Retry.MaxInterval = 10 * time.Millisecond
})
mustSend(t, exporter, `{"message": "test1", "idx": 0}`)
mustSend(t, exporter, `{"message": "test2", "idx": 1}`)
mustSend(t, exporter, `{"message": "test3", "idx": 2}`)
wg.Wait() // <- this blocks forever if the event is not retried
assert.Equal(t, [3]int{1, 2, 1}, attempts)
})
}
func newTestExporter(t *testing.T, url string, fns ...func(*Config)) *elasticsearchLogsExporter {
exporter, err := newLogsExporter(zaptest.NewLogger(t), withTestExporterConfig(fns...)(url))
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, exporter.Shutdown(context.TODO()))
})
return exporter
}
func withTestExporterConfig(fns ...func(*Config)) func(string) *Config {
return func(url string) *Config {
var configMods []func(*Config)
configMods = append(configMods, func(cfg *Config) {
cfg.Endpoints = []string{url}
cfg.NumWorkers = 1
cfg.Flush.Interval = 10 * time.Millisecond
})
configMods = append(configMods, fns...)
return withDefaultConfig(configMods...)
}
}
func mustSend(t *testing.T, exporter *elasticsearchLogsExporter, contents string) {
err := pushDocuments(context.TODO(), zap.L(), exporter.index, []byte(contents), exporter.bulkIndexer, exporter.maxAttempts)
require.NoError(t, err)
}
// send trace with span & resource attributes
func mustSendLogsWithAttributes(t *testing.T, exporter *elasticsearchLogsExporter, attrMp map[string]string, resMp map[string]string) {
logs := newLogsWithAttributeAndResourceMap(attrMp, resMp)
resLogs := logs.ResourceLogs().At(0)
logRecords := resLogs.ScopeLogs().At(0).LogRecords().At(0)
scopeLogs := resLogs.ScopeLogs().AppendEmpty()
scope := scopeLogs.Scope()
err := exporter.pushLogRecord(context.TODO(), resLogs.Resource(), logRecords, scope)
require.NoError(t, err)
}