-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
prospector.go
322 lines (269 loc) · 9.13 KB
/
prospector.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
// 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 filestream
import (
"errors"
"fmt"
"time"
loginp "github.com/elastic/beats/v7/filebeat/input/filestream/internal/input-logfile"
input "github.com/elastic/beats/v7/filebeat/input/v2"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/go-concert/unison"
)
type ignoreInactiveType uint8
const (
InvalidIgnoreInactive = iota
IgnoreInactiveSinceLastStart
IgnoreInactiveSinceFirstStart
ignoreInactiveSinceLastStartStr = "since_last_start"
ignoreInactiveSinceFirstStartStr = "since_first_start"
prospectorDebugKey = "file_prospector"
)
var ignoreInactiveSettings = map[string]ignoreInactiveType{
ignoreInactiveSinceLastStartStr: IgnoreInactiveSinceLastStart,
ignoreInactiveSinceFirstStartStr: IgnoreInactiveSinceFirstStart,
}
// fileProspector implements the Prospector interface.
// It contains a file scanner which returns file system events.
// The FS events then trigger either new Harvester runs or updates
// the statestore.
type fileProspector struct {
filewatcher loginp.FSWatcher
identifier fileIdentifier
ignoreOlder time.Duration
ignoreInactiveSince ignoreInactiveType
cleanRemoved bool
stateChangeCloser stateChangeCloserConfig
}
func (p *fileProspector) Init(
cleaner,
globalCleaner loginp.ProspectorCleaner,
newID func(loginp.Source) string,
) error {
files := p.filewatcher.GetFiles()
// If this fileProspector belongs to an input that did not have an ID
// this will find its files in the registry and update them to use the
// new ID.
globalCleaner.FixUpIdentifiers(func(v loginp.Value) (id string, val interface{}) {
var fm fileMeta
err := v.UnpackCursorMeta(&fm)
if err != nil {
return "", nil
}
fd, ok := files[fm.Source]
if !ok {
return "", fm
}
newKey := newID(p.identifier.GetSource(loginp.FSEvent{NewPath: fm.Source, Descriptor: fd}))
return newKey, fm
})
if p.cleanRemoved {
cleaner.CleanIf(func(v loginp.Value) bool {
var fm fileMeta
err := v.UnpackCursorMeta(&fm)
if err != nil {
// remove faulty entries
return true
}
_, ok := files[fm.Source]
return !ok
})
}
identifierName := p.identifier.Name()
cleaner.UpdateIdentifiers(func(v loginp.Value) (string, interface{}) {
var fm fileMeta
err := v.UnpackCursorMeta(&fm)
if err != nil {
return "", nil
}
fd, ok := files[fm.Source]
if !ok {
return "", fm
}
if fm.IdentifierName != identifierName {
newKey := p.identifier.GetSource(loginp.FSEvent{NewPath: fm.Source, Descriptor: fd}).Name()
fm.IdentifierName = identifierName
return newKey, fm
}
return "", fm
})
return nil
}
// Run starts the fileProspector which accepts FS events from a file watcher.
//
//nolint:dupl // Different prospectors have a similar run method
func (p *fileProspector) Run(ctx input.Context, s loginp.StateMetadataUpdater, hg loginp.HarvesterGroup) {
log := ctx.Logger.With("prospector", prospectorDebugKey)
log.Debug("Starting prospector")
defer log.Debug("Prospector has stopped")
defer p.stopHarvesterGroup(log, hg)
var tg unison.MultiErrGroup
tg.Go(func() error {
p.filewatcher.Run(ctx.Cancelation)
return nil
})
tg.Go(func() error {
ignoreInactiveSince := getIgnoreSince(p.ignoreInactiveSince, ctx.Agent)
for ctx.Cancelation.Err() == nil {
fe := p.filewatcher.Event()
if fe.Op == loginp.OpDone {
return nil
}
src := p.identifier.GetSource(fe)
p.onFSEvent(loggerWithEvent(log, fe, src), ctx, fe, src, s, hg, ignoreInactiveSince)
}
return nil
})
errs := tg.Wait()
if len(errs) > 0 {
log.Errorf("running prospector failed: %v", errors.Join(errs...))
}
}
func (p *fileProspector) onFSEvent(
log *logp.Logger,
ctx input.Context,
event loginp.FSEvent,
src loginp.Source,
updater loginp.StateMetadataUpdater,
group loginp.HarvesterGroup,
ignoreSince time.Time,
) {
switch event.Op {
case loginp.OpCreate, loginp.OpWrite:
if event.Op == loginp.OpCreate {
log.Debugf("A new file %s has been found", event.NewPath)
err := updater.UpdateMetadata(src, fileMeta{Source: event.NewPath, IdentifierName: p.identifier.Name()})
if err != nil {
log.Errorf("Failed to set cursor meta data of entry %s: %v", src.Name(), err)
}
} else if event.Op == loginp.OpWrite {
log.Debugf("File %s has been updated", event.NewPath)
}
if p.isFileIgnored(log, event, ignoreSince) {
err := updater.ResetCursor(src, state{Offset: event.Descriptor.Info.Size()})
if err != nil {
log.Errorf("setting cursor for ignored file: %v", err)
}
return
}
group.Start(ctx, src)
case loginp.OpTruncate:
log.Debugf("File %s has been truncated setting offset to 0", event.NewPath)
err := updater.ResetCursor(src, state{Offset: 0})
if err != nil {
log.Errorf("resetting cursor on truncated file: %v", err)
}
group.Restart(ctx, src)
case loginp.OpDelete:
log.Debugf("File %s has been removed", event.OldPath)
p.onRemove(log, event, src, updater, group)
case loginp.OpRename:
log.Debugf("File %s has been renamed to %s", event.OldPath, event.NewPath)
p.onRename(log, ctx, event, src, updater, group)
default:
log.Error("Unknown return value %v", event.Op)
}
}
func (p *fileProspector) isFileIgnored(log *logp.Logger, fe loginp.FSEvent, ignoreInactiveSince time.Time) bool {
if p.ignoreOlder > 0 {
now := time.Now()
if now.Sub(fe.Descriptor.Info.ModTime()) > p.ignoreOlder {
log.Debugf("Ignore file because ignore_older reached. File %s", fe.NewPath)
return true
}
}
if !ignoreInactiveSince.IsZero() && fe.Descriptor.Info.ModTime().Sub(ignoreInactiveSince) <= 0 {
log.Debugf("Ignore file because ignore_since.* reached time %v. File %s", p.ignoreInactiveSince, fe.NewPath)
return true
}
return false
}
func (p *fileProspector) onRemove(log *logp.Logger, fe loginp.FSEvent, src loginp.Source, s loginp.StateMetadataUpdater, hg loginp.HarvesterGroup) {
if p.stateChangeCloser.Removed {
log.Debugf("Stopping harvester as file %s has been removed and close.on_state_change.removed is enabled.", src.Name())
hg.Stop(src)
}
if p.cleanRemoved {
log.Debugf("Remove state for file as file removed: %s", fe.OldPath)
err := s.Remove(src)
if err != nil {
log.Errorf("Error while removing state from statestore: %v", err)
}
}
}
func (p *fileProspector) onRename(log *logp.Logger, ctx input.Context, fe loginp.FSEvent, src loginp.Source, s loginp.StateMetadataUpdater, hg loginp.HarvesterGroup) {
// if file_identity is based on path, the current reader has to be cancelled
// and a new one has to start.
if !p.identifier.Supports(trackRename) {
prevSrc := p.identifier.GetSource(loginp.FSEvent{NewPath: fe.OldPath})
hg.Stop(prevSrc)
log.Debugf("Remove state for file as file renamed and path file_identity is configured: %s", fe.OldPath)
err := s.Remove(prevSrc)
if err != nil {
log.Errorf("Error while removing old state of renamed file (%s): %v", fe.OldPath, err)
}
hg.Start(ctx, src)
} else {
// update file metadata as the path has changed
var meta fileMeta
err := s.FindCursorMeta(src, &meta)
if err != nil {
meta.IdentifierName = p.identifier.Name()
log.Warnf("Error while getting cursor meta data of entry '%s': '%w'"+
", using prospector's identifier: '%s'",
src.Name(), err, meta.IdentifierName)
}
err = s.UpdateMetadata(src, fileMeta{Source: fe.NewPath, IdentifierName: meta.IdentifierName})
if err != nil {
log.Errorf("Failed to update cursor meta data of entry %s: %v", src.Name(), err)
}
if p.stateChangeCloser.Renamed {
log.Debugf("Stopping harvester as file %s has been renamed and close.on_state_change.renamed is enabled.", src.Name())
fe.Op = loginp.OpDelete
srcToClose := p.identifier.GetSource(fe)
hg.Stop(srcToClose)
}
}
}
func (p *fileProspector) stopHarvesterGroup(log *logp.Logger, hg loginp.HarvesterGroup) {
err := hg.StopHarvesters()
if err != nil {
log.Errorf("Error while stopping harvester group: %v", err)
}
}
func (p *fileProspector) Test() error {
panic("TODO: implement me")
}
func getIgnoreSince(t ignoreInactiveType, info beat.Info) time.Time {
switch t {
case IgnoreInactiveSinceLastStart:
return info.StartTime
case IgnoreInactiveSinceFirstStart:
return info.FirstStart
default:
return time.Time{}
}
}
func (t *ignoreInactiveType) Unpack(v string) error {
val, ok := ignoreInactiveSettings[v]
if !ok {
return fmt.Errorf("invalid ignore_inactive setting: %s", v)
}
*t = val
return nil
}