-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
filelog_test.go
312 lines (264 loc) · 8.91 KB
/
filelog_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
// Copyright The OpenTelemetry Authors
//
// 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 filelogreceiver
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/observiq/nanojack"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/component/componenttest"
"go.opentelemetry.io/collector/config"
"go.opentelemetry.io/collector/config/configtest"
"go.opentelemetry.io/collector/consumer/consumertest"
"go.opentelemetry.io/collector/pdata/plog"
"go.opentelemetry.io/collector/service/servicetest"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/adapter"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/entry"
)
func TestDefaultConfig(t *testing.T) {
factory := NewFactory()
cfg := factory.CreateDefaultConfig()
require.NotNil(t, cfg, "failed to create default config")
require.NoError(t, configtest.CheckConfigStruct(cfg))
}
func TestLoadConfig(t *testing.T) {
factories, err := componenttest.NopFactories()
assert.Nil(t, err)
factory := NewFactory()
factories.Receivers[typeStr] = factory
cfg, err := servicetest.LoadConfigAndValidate(filepath.Join("testdata", "config.yaml"), factories)
require.NoError(t, err)
require.NotNil(t, cfg)
assert.Equal(t, len(cfg.Receivers), 1)
assert.Equal(t, testdataConfigYamlAsMap(), cfg.Receivers[config.NewComponentID("filelog")])
}
func TestCreateWithInvalidInputConfig(t *testing.T) {
t.Parallel()
cfg := testdataConfigYamlAsMap()
cfg.Input["include"] = "not an array"
_, err := NewFactory().CreateLogsReceiver(
context.Background(),
componenttest.NewNopReceiverCreateSettings(),
cfg,
new(consumertest.LogsSink),
)
require.Error(t, err, "receiver creation should fail if given invalid input config")
}
func TestReadStaticFile(t *testing.T) {
t.Parallel()
expectedTimestamp, _ := time.ParseInLocation("2006-01-02", "2020-08-25", time.Local)
f := NewFactory()
sink := new(consumertest.LogsSink)
cfg := testdataConfigYamlAsMap()
cfg.Converter.MaxFlushCount = 10
cfg.Converter.FlushInterval = time.Millisecond
converter := adapter.NewConverter()
converter.Start()
defer converter.Stop()
var wg sync.WaitGroup
wg.Add(1)
go consumeNLogsFromConverter(converter.OutChannel(), 3, &wg)
rcvr, err := f.CreateLogsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, sink)
require.NoError(t, err, "failed to create receiver")
require.NoError(t, rcvr.Start(context.Background(), componenttest.NewNopHost()))
// Build the expected set by using adapter.Converter to translate entries
// to pdata Logs.
queueEntry := func(t *testing.T, c *adapter.Converter, msg string, severity entry.Severity) {
e := entry.New()
e.Timestamp = expectedTimestamp
require.NoError(t, e.Set(entry.NewBodyField("msg"), msg))
e.Severity = severity
e.AddAttribute("file_name", "simple.log")
require.NoError(t, c.Batch([]*entry.Entry{e}))
}
queueEntry(t, converter, "Something routine", entry.Info)
queueEntry(t, converter, "Something bad happened!", entry.Error)
queueEntry(t, converter, "Some details...", entry.Debug)
dir, err := os.Getwd()
require.NoError(t, err)
t.Logf("Working Directory: %s", dir)
wg.Wait()
require.Eventually(t, expectNLogs(sink, 3), 2*time.Second, 5*time.Millisecond,
"expected %d but got %d logs",
3, sink.LogRecordCount(),
)
// TODO: Figure out a nice way to assert each logs entry content.
// require.Equal(t, expectedLogs, sink.AllLogs())
require.NoError(t, rcvr.Shutdown(context.Background()))
}
func TestReadRotatingFiles(t *testing.T) {
tests := []rotationTest{
{
name: "CopyTruncateTimestamped",
copyTruncate: true,
sequential: false,
},
{
name: "MoveCreateTimestamped",
copyTruncate: false,
sequential: false,
},
{
name: "CopyTruncateSequential",
copyTruncate: true,
sequential: true,
},
{
name: "MoveCreateSequential",
copyTruncate: false,
sequential: true,
},
}
for _, tc := range tests {
t.Run(tc.name, tc.Run)
}
}
type rotationTest struct {
name string
copyTruncate bool
sequential bool
}
func (rt *rotationTest) Run(t *testing.T) {
t.Parallel()
tempDir := t.TempDir()
f := NewFactory()
sink := new(consumertest.LogsSink)
cfg := testdataRotateTestYamlAsMap(tempDir)
cfg.Converter.MaxFlushCount = 1
cfg.Converter.FlushInterval = time.Millisecond
// With a max of 100 logs per file and 1 backup file, rotation will occur
// when more than 100 logs are written, and deletion when more than 200 are written.
// Write 300 and validate that we got the all despite rotation and deletion.
logger := newRotatingLogger(t, tempDir, 100, 1, rt.copyTruncate, rt.sequential)
numLogs := 300
// Build expected outputs
expectedTimestamp, _ := time.ParseInLocation("2006-01-02", "2020-08-25", time.Local)
converter := adapter.NewConverter()
converter.Start()
var wg sync.WaitGroup
wg.Add(1)
go consumeNLogsFromConverter(converter.OutChannel(), numLogs, &wg)
rcvr, err := f.CreateLogsReceiver(context.Background(), componenttest.NewNopReceiverCreateSettings(), cfg, sink)
require.NoError(t, err, "failed to create receiver")
require.NoError(t, rcvr.Start(context.Background(), componenttest.NewNopHost()))
for i := 0; i < numLogs; i++ {
msg := fmt.Sprintf("This is a simple log line with the number %3d", i)
// Build the expected set by converting entries to pdata Logs...
e := entry.New()
e.Timestamp = expectedTimestamp
require.NoError(t, e.Set(entry.NewBodyField("msg"), msg))
require.NoError(t, converter.Batch([]*entry.Entry{e}))
// ... and write the logs lines to the actual file consumed by receiver.
logger.Printf("2020-08-25 %s", msg)
time.Sleep(time.Millisecond)
}
wg.Wait()
require.Eventually(t, expectNLogs(sink, numLogs), 2*time.Second, 10*time.Millisecond,
"expected %d but got %d logs",
numLogs, sink.LogRecordCount(),
)
// TODO: Figure out a nice way to assert each logs entry content.
// require.Equal(t, expectedLogs, sink.AllLogs())
require.NoError(t, rcvr.Shutdown(context.Background()))
converter.Stop()
}
func consumeNLogsFromConverter(ch <-chan plog.Logs, count int, wg *sync.WaitGroup) {
defer wg.Done()
n := 0
for pLog := range ch {
n += pLog.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().Len()
if n == count {
return
}
}
}
func newRotatingLogger(t *testing.T, tempDir string, maxLines, maxBackups int, copyTruncate, sequential bool) *log.Logger {
path := filepath.Join(tempDir, "test.log")
rotator := &nanojack.Logger{
Filename: path,
MaxLines: maxLines,
MaxBackups: maxBackups,
CopyTruncate: copyTruncate,
Sequential: sequential,
}
t.Cleanup(func() { _ = rotator.Close() })
return log.New(rotator, "", 0)
}
func expectNLogs(sink *consumertest.LogsSink, expected int) func() bool {
return func() bool { return sink.LogRecordCount() == expected }
}
func testdataConfigYamlAsMap() *FileLogConfig {
return &FileLogConfig{
BaseConfig: adapter.BaseConfig{
ReceiverSettings: config.NewReceiverSettings(config.NewComponentID(typeStr)),
Operators: adapter.OperatorConfigs{
map[string]interface{}{
"type": "regex_parser",
"regex": "^(?P<time>\\d{4}-\\d{2}-\\d{2}) (?P<sev>[A-Z]*) (?P<msg>.*)$",
"severity": map[string]interface{}{
"parse_from": "attributes.sev",
},
"timestamp": map[string]interface{}{
"layout": "%Y-%m-%d",
"parse_from": "attributes.time",
},
},
},
Converter: adapter.ConverterConfig{
MaxFlushCount: 100,
FlushInterval: 100 * time.Millisecond,
},
},
Input: adapter.InputConfig{
"include": []interface{}{
"testdata/simple.log",
},
"start_at": "beginning",
},
}
}
func testdataRotateTestYamlAsMap(tempDir string) *FileLogConfig {
return &FileLogConfig{
BaseConfig: adapter.BaseConfig{
ReceiverSettings: config.NewReceiverSettings(config.NewComponentID(typeStr)),
Operators: adapter.OperatorConfigs{
map[string]interface{}{
"type": "regex_parser",
"regex": "^(?P<ts>\\d{4}-\\d{2}-\\d{2}) (?P<msg>[^\n]+)",
"timestamp": map[interface{}]interface{}{
"layout": "%Y-%m-%d",
"parse_from": "body.ts",
},
},
},
Converter: adapter.ConverterConfig{},
},
Input: adapter.InputConfig{
"type": "file_input",
"include": []interface{}{
fmt.Sprintf("%s/*", tempDir),
},
"include_file_name": false,
"poll_interval": "10ms",
"start_at": "beginning",
},
}
}