-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
utils_test.go
279 lines (231 loc) · 6.95 KB
/
utils_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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package elasticsearchexporter
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/plog"
"go.opentelemetry.io/collector/pdata/ptrace"
)
type itemRequest struct {
Action json.RawMessage
Document json.RawMessage
}
type itemResponse struct {
Status int `json:"status"`
}
type bulkResult struct {
Took int `json:"took"`
HasErrors bool `json:"errors"`
Items []itemResponse `json:"items"`
}
type bulkHandler func([]itemRequest) ([]itemResponse, error)
type httpTestError struct {
status int
message string
cause error
}
const currentESVersion = "7.17.7"
func (e *httpTestError) Error() string {
return fmt.Sprintf("http request failed (status=%v): %v", e.Status(), e.Message())
}
func (e *httpTestError) Status() int {
if e.status == 0 {
return http.StatusInternalServerError
}
return e.status
}
func (e *httpTestError) Message() string {
var buf strings.Builder
if e.message != "" {
buf.WriteString(e.message)
}
if e.cause != nil {
if buf.Len() > 0 {
buf.WriteString(": ")
}
buf.WriteString(e.cause.Error())
}
return buf.String()
}
type bulkRecorder struct {
mu sync.Mutex
cond *sync.Cond
recordings [][]itemRequest
}
func newBulkRecorder() *bulkRecorder {
r := &bulkRecorder{}
r.cond = sync.NewCond(&r.mu)
return r
}
func (r *bulkRecorder) Record(bulk []itemRequest) {
r.mu.Lock()
defer r.mu.Unlock()
r.recordings = append(r.recordings, bulk)
r.cond.Broadcast()
}
func (r *bulkRecorder) WaitItems(n int) {
r.mu.Lock()
defer r.mu.Unlock()
for n > r.countItems() {
r.cond.Wait()
}
}
func (r *bulkRecorder) Requests() [][]itemRequest {
r.mu.Lock()
defer r.mu.Unlock()
return r.recordings
}
func (r *bulkRecorder) Items() (docs []itemRequest) {
for _, rec := range r.Requests() {
docs = append(docs, rec...)
}
return docs
}
func (r *bulkRecorder) NumItems() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.countItems()
}
func (r *bulkRecorder) countItems() (count int) {
for _, docs := range r.recordings {
count += len(docs)
}
return count
}
func newESTestServer(t *testing.T, bulkHandler bulkHandler) *httptest.Server {
mux := http.NewServeMux()
mux.HandleFunc("/", handleErr(func(w http.ResponseWriter, _ *http.Request) error {
w.Header().Add("X-Elastic-Product", "Elasticsearch")
enc := json.NewEncoder(w)
return enc.Encode(map[string]any{
"version": map[string]any{
"number": currentESVersion,
},
})
}))
mux.HandleFunc("/_bulk", handleErr(func(w http.ResponseWriter, req *http.Request) error {
tsStart := time.Now()
var items []itemRequest
w.Header().Add("X-Elastic-Product", "Elasticsearch")
dec := json.NewDecoder(req.Body)
for dec.More() {
var action, doc json.RawMessage
if err := dec.Decode(&action); err != nil {
return &httpTestError{status: http.StatusBadRequest, cause: err}
}
if !dec.More() {
return &httpTestError{status: http.StatusBadRequest, message: "action without document"}
}
if err := dec.Decode(&doc); err != nil {
return &httpTestError{status: http.StatusBadRequest, cause: err}
}
items = append(items, itemRequest{Action: action, Document: doc})
}
resp, err := bulkHandler(items)
if err != nil {
return err
}
took := int(time.Since(tsStart) / time.Microsecond)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(w)
return enc.Encode(bulkResult{Took: took, Items: resp, HasErrors: itemsHasError(resp)})
}))
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
return server
}
func handleErr(fn func(http.ResponseWriter, *http.Request) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := fn(w, r)
if err != nil {
httpError := &httpTestError{}
if errors.As(err, &httpError) {
http.Error(w, httpError.Message(), httpError.Status())
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
}
func (item *itemResponse) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
fmt.Fprintf(&buf, `{"create": {"status": %v}}`, item.Status)
return buf.Bytes(), nil
}
func itemsAllOK(docs []itemRequest) ([]itemResponse, error) {
return itemsReportStatus(docs, http.StatusOK)
}
func itemsReportStatus(docs []itemRequest, status int) ([]itemResponse, error) {
responses := make([]itemResponse, len(docs))
for i := range docs {
responses[i].Status = status
}
return responses, nil
}
func itemsHasError(resp []itemResponse) bool {
for _, r := range resp {
if r.Status != http.StatusOK {
return true
}
}
return false
}
func newLogsWithAttributeAndResourceMap(attrMp map[string]string, resMp map[string]string) plog.Logs {
logs := plog.NewLogs()
resourceSpans := logs.ResourceLogs()
rs := resourceSpans.AppendEmpty()
scopeAttr := rs.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes()
fillResourceAttributeMap(scopeAttr, attrMp)
resAttr := rs.Resource().Attributes()
fillResourceAttributeMap(resAttr, resMp)
return logs
}
func newTracesWithAttributeAndResourceMap(attrMp map[string]string, resMp map[string]string) ptrace.Traces {
traces := ptrace.NewTraces()
resourceSpans := traces.ResourceSpans()
rs := resourceSpans.AppendEmpty()
scopeAttr := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes()
fillResourceAttributeMap(scopeAttr, attrMp)
resAttr := rs.Resource().Attributes()
fillResourceAttributeMap(resAttr, resMp)
return traces
}
func fillResourceAttributeMap(attrs pcommon.Map, mp map[string]string) {
attrs.EnsureCapacity(len(mp))
for k, v := range mp {
attrs.PutStr(k, v)
}
}
func TestGetSuffixTime(t *testing.T) {
defaultCfg := createDefaultConfig().(*Config)
defaultCfg.LogstashFormat.Enabled = true
testTime := time.Date(2023, 12, 2, 10, 10, 10, 1, time.UTC)
index, err := generateIndexWithLogstashFormat(defaultCfg.LogsIndex, &defaultCfg.LogstashFormat, testTime)
assert.NoError(t, err)
assert.Equal(t, index, "logs-generic-default-2023.12.02")
defaultCfg.LogsIndex = "logstash"
defaultCfg.LogstashFormat.PrefixSeparator = "."
otelLogsIndex, err := generateIndexWithLogstashFormat(defaultCfg.LogsIndex, &defaultCfg.LogstashFormat, testTime)
assert.NoError(t, err)
assert.Equal(t, otelLogsIndex, "logstash.2023.12.02")
defaultCfg.LogstashFormat.DateFormat = "%Y-%m-%d"
newOtelLogsIndex, err := generateIndexWithLogstashFormat(defaultCfg.LogsIndex, &defaultCfg.LogstashFormat, testTime)
assert.NoError(t, err)
assert.Equal(t, newOtelLogsIndex, "logstash.2023-12-02")
defaultCfg.LogstashFormat.DateFormat = "%d/%m/%Y"
newOtelLogsIndexWithSpecDataFormat, err := generateIndexWithLogstashFormat(defaultCfg.LogsIndex, &defaultCfg.LogstashFormat, testTime)
assert.NoError(t, err)
assert.Equal(t, newOtelLogsIndexWithSpecDataFormat, "logstash.02/12/2023")
}