-
Notifications
You must be signed in to change notification settings - Fork 1
/
btail.go
233 lines (196 loc) · 4.02 KB
/
btail.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
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strings"
"time"
"github.com/fsnotify/fsnotify"
)
type Config struct {
Lines int
Follow bool
}
type Tail struct {
Filename string
Lines chan Line
Config Config
file *os.File
fileSize int64
watcher *fsnotify.Watcher
done chan struct{}
}
type Line struct {
Text string
Time time.Time
}
func TailFile(Filename string, config Config) (*Tail, error) {
if config.Lines <= 0 {
config.Lines = 10
}
t := &Tail{
Filename: Filename,
Lines: make(chan Line),
Config: config,
done: make(chan struct{}),
}
var err error
if err = t.openFile(); err != nil {
return nil, err
}
if config.Follow {
t.watcher, err = fsnotify.NewWatcher()
if err != nil {
t.file.Close()
return nil, fmt.Errorf("failed to create watcher: %v", err)
}
err = t.watcher.Add(Filename)
if err != nil {
t.file.Close()
t.watcher.Close()
return nil, fmt.Errorf("failed to add file to watcher: %v", err)
}
}
go t.tail()
return t, nil
}
func (t *Tail) openFile() error {
file, err := os.Open(t.Filename)
if err != nil {
return fmt.Errorf("failed to open file %s: %v", t.Filename, err)
}
t.file = file
info, err := file.Stat()
if err != nil {
t.file.Close()
return fmt.Errorf("failed to stat file %s: %v", t.Filename, err)
}
t.fileSize = info.Size()
return nil
}
func (t *Tail) reopen() {
var err error
for {
t.file, err = os.Open(t.Filename)
if err != nil {
if os.IsNotExist(err) {
time.Sleep(time.Second)
}
} else {
break
}
time.Sleep(250 * time.Millisecond)
}
}
func (t *Tail) tail() {
defer close(t.Lines)
defer t.file.Close()
if t.watcher != nil {
defer t.watcher.Close()
}
lines, err := t.readLastNLines()
if err != nil {
log.Printf("failed to read lines from file: %v", err)
return
}
for _, line := range lines {
t.Lines <- line
}
if t.Config.Follow {
if err := t.followFile(); err != nil {
log.Printf("failed to follow file: %v", err)
}
}
}
func (t *Tail) readLastNLines() ([]Line, error) {
buffer := make([]byte, 1024*1024)
offset := t.fileSize
lineCount := 0
lines := make([]Line, 0, t.Config.Lines)
for lineCount < t.Config.Lines*2 && offset > 0 {
readSize := int64(len(buffer))
if offset < readSize {
readSize = offset
}
offset -= readSize
_, err := t.file.Seek(offset, io.SeekStart)
if err != nil {
return nil, err
}
bytesRead, err := t.file.Read(buffer[:readSize])
if err != nil && err != io.EOF {
return nil, err
}
for i := bytesRead - 1; i >= 0; i-- {
if buffer[i] == '\n' {
lineCount++
if lineCount > t.Config.Lines*2 {
offset += int64(i) + 1
break
}
}
}
}
_, err := t.file.Seek(offset, io.SeekStart)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(t.file)
for scanner.Scan() && len(lines) < t.Config.Lines {
trimmedText := strings.TrimSpace(scanner.Text())
if trimmedText != "" {
lines = append(lines, Line{Text: trimmedText, Time: time.Now()})
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
func (t *Tail) readNewLines(reader *bufio.Reader) {
for {
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
// show error in info area
return
}
t.Lines <- Line{line, time.Now()}
t.fileSize += int64(len(line))
}
}
func (t *Tail) followFile() error {
reader := bufio.NewReader(t.file)
for {
select {
case event, ok := <-t.watcher.Events:
if !ok {
return nil
}
if event.Op&fsnotify.Write == fsnotify.Write {
t.readNewLines(reader)
}
if event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename {
// TODO: handle this probably (show in status bar)
_ = t.watcher.Remove(t.Filename)
t.reopen()
_ = t.watcher.Add(t.Filename)
reader = bufio.NewReader(t.file)
}
case _, ok := <-t.watcher.Errors:
if !ok {
return nil
}
// show error in info area
case <-t.done:
return nil
}
}
}
func (t *Tail) Stop() {
close(t.done)
}