forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtarget.go
306 lines (264 loc) · 7.41 KB
/
target.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
package promtail
import (
"os"
"path/filepath"
"time"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/hpcloud/tail"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
fsnotify "gopkg.in/fsnotify.v1"
"github.com/grafana/loki/pkg/helpers"
)
var (
readBytes = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "promtail",
Name: "read_bytes_total",
Help: "Number of bytes read.",
}, []string{"path"})
readLines = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "promtail",
Name: "read_lines_total",
Help: "Number of lines read.",
}, []string{"path"})
filesActive = promauto.NewGauge(prometheus.GaugeOpts{
Namespace: "promtail",
Name: "files_active_total",
Help: "Number of active files.",
})
)
const (
filename = "__filename__"
)
// Target describes a particular set of logs.
type Target struct {
logger log.Logger
handler EntryHandler
positions *Positions
watcher *fsnotify.Watcher
path string
quit chan struct{}
done chan struct{}
tails map[string]*tailer
}
// NewTarget create a new Target.
func NewTarget(logger log.Logger, handler EntryHandler, positions *Positions, path string, labels model.LabelSet) (*Target, error) {
var err error
path, err = filepath.Abs(path)
if err != nil {
return nil, errors.Wrap(err, "filepath.Abs")
}
matches, err := filepath.Glob(path)
if err != nil {
return nil, errors.Wrap(err, "filepath.Glob")
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, errors.Wrap(err, "fsnotify.NewWatcher")
}
// get the current unique set of dirs to watch.
dirs := make(map[string]struct{})
for _, p := range matches {
dirs[filepath.Dir(p)] = struct{}{}
}
// If no files exist yet watch the directory specified in the path.
if matches == nil {
dirs[filepath.Dir(path)] = struct{}{}
}
// watch each dir for any new files.
for dir := range dirs {
level.Debug(logger).Log("msg", "watching new directory", "directory", dir)
if err := watcher.Add(dir); err != nil {
helpers.LogError("closing watcher", watcher.Close)
return nil, errors.Wrap(err, "watcher.Add")
}
}
t := &Target{
logger: logger,
watcher: watcher,
path: path,
handler: addLabelsMiddleware(labels).Wrap(handler),
positions: positions,
quit: make(chan struct{}),
done: make(chan struct{}),
tails: map[string]*tailer{},
}
// start tailing all of the matched files
for _, p := range matches {
fi, err := os.Stat(p)
if err != nil {
level.Error(t.logger).Log("msg", "failed to stat file", "error", err, "filename", p)
continue
}
if fi.IsDir() {
level.Debug(t.logger).Log("msg", "skipping matched dir", "filename", p)
continue
}
tailer, err := newTailer(t.logger, t.handler, t.positions, p)
if err != nil {
level.Error(t.logger).Log("msg", "failed to tail file", "error", err, "filename", p)
continue
}
t.tails[p] = tailer
}
go t.run()
return t, nil
}
// Stop the target.
func (t *Target) Stop() {
close(t.quit)
<-t.done
}
func (t *Target) run() {
defer func() {
helpers.LogError("closing watcher", t.watcher.Close)
for _, v := range t.tails {
helpers.LogError("updating tailer last position", v.markPosition)
helpers.LogError("stopping tailer", v.stop)
}
level.Debug(t.logger).Log("msg", "watcher closed, tailer stopped, positions saved")
close(t.done)
}()
for {
select {
case event := <-t.watcher.Events:
switch event.Op {
case fsnotify.Create:
// protect against double Creates.
if _, ok := t.tails[event.Name]; ok {
level.Info(t.logger).Log("msg", "got 'create' for existing file", "filename", event.Name)
continue
}
matched, err := filepath.Match(t.path, event.Name)
if err != nil {
level.Error(t.logger).Log("msg", "failed to match file", "error", err, "filename", event.Name)
continue
}
if !matched {
level.Debug(t.logger).Log("msg", "new file does not match glob", "filename", event.Name)
continue
}
tailer, err := newTailer(t.logger, t.handler, t.positions, event.Name)
if err != nil {
level.Error(t.logger).Log("msg", "failed to tail file", "error", err, "filename", event.Name)
continue
}
level.Debug(t.logger).Log("msg", "tailing new file", "filename", event.Name)
t.tails[event.Name] = tailer
case fsnotify.Remove:
tailer, ok := t.tails[event.Name]
if ok {
helpers.LogError("stopping tailer", tailer.stop)
tailer.cleanup()
delete(t.tails, event.Name)
}
case fsnotify.Rename:
// Rename is only issued on the original file path; the new name receives a Create event
tailer, ok := t.tails[event.Name]
if ok {
helpers.LogError("stopping tailer", tailer.stop)
tailer.cleanup()
delete(t.tails, event.Name)
}
default:
level.Debug(t.logger).Log("msg", "got unknown event", "event", event)
}
case err := <-t.watcher.Errors:
level.Error(t.logger).Log("msg", "error from fswatch", "error", err)
case <-t.quit:
return
}
}
}
type tailer struct {
logger log.Logger
handler EntryHandler
positions *Positions
path string
tail *tail.Tail
quit chan struct{}
done chan struct{}
}
func newTailer(logger log.Logger, handler EntryHandler, positions *Positions, path string) (*tailer, error) {
tail, err := tail.TailFile(path, tail.Config{
Follow: true,
Location: &tail.SeekInfo{
Offset: positions.Get(path),
Whence: 0,
},
})
if err != nil {
return nil, err
}
tailer := &tailer{
logger: logger,
handler: addLabelsMiddleware(model.LabelSet{filename: model.LabelValue(path)}).Wrap(handler),
positions: positions,
path: path,
tail: tail,
quit: make(chan struct{}),
done: make(chan struct{}),
}
go tailer.run()
filesActive.Add(1.)
return tailer, nil
}
func (t *tailer) run() {
level.Info(t.logger).Log("msg", "start tailing file", "filename", t.path)
positionSyncPeriod := t.positions.cfg.SyncPeriod
positionWait := time.NewTicker(positionSyncPeriod)
defer func() {
level.Info(t.logger).Log("msg", "stopping tailing file", "filename", t.path)
positionWait.Stop()
err := t.markPosition()
if err != nil {
level.Error(t.logger).Log("msg", "error getting tail position", "filename", t.path, "error", err)
}
close(t.done)
}()
for {
select {
case <-positionWait.C:
err := t.markPosition()
if err != nil {
level.Error(t.logger).Log("msg", "error getting tail position", "filename", t.path, "error", err)
continue
}
case line, ok := <-t.tail.Lines:
if !ok {
return
}
if line.Err != nil {
level.Error(t.logger).Log("msg", "error reading line", "filename", t.path, "error", line.Err)
}
readLines.WithLabelValues(t.path).Inc()
readBytes.WithLabelValues(t.path).Add(float64(len(line.Text)))
if err := t.handler.Handle(model.LabelSet{}, line.Time, line.Text); err != nil {
level.Error(t.logger).Log("msg", "error handling line", "filename", t.path, "error", err)
}
case <-t.quit:
return
}
}
}
func (t *tailer) markPosition() error {
pos, err := t.tail.Tell()
if err != nil {
return err
}
level.Debug(t.logger).Log("path", t.path, "current_position", pos)
t.positions.Put(t.path, pos)
return nil
}
func (t *tailer) stop() error {
close(t.quit)
<-t.done
filesActive.Add(-1.)
return t.tail.Stop()
}
func (t *tailer) cleanup() {
t.positions.Remove(t.path)
}