github.com/liumingmin/tail@v1.0.0/tail.go (about) 1 // Copyright (c) 2015 HPE Software Inc. All rights reserved. 2 // Copyright (c) 2013 ActiveState Software Inc. All rights reserved. 3 4 package tail 5 6 import ( 7 "bufio" 8 "errors" 9 "fmt" 10 "io" 11 "io/ioutil" 12 "log" 13 "os" 14 "strings" 15 "sync" 16 "time" 17 18 "github.com/hpcloud/tail/ratelimiter" 19 "github.com/hpcloud/tail/util" 20 "github.com/hpcloud/tail/watch" 21 "gopkg.in/tomb.v1" 22 ) 23 24 var ( 25 ErrStop = errors.New("tail should now stop") 26 ) 27 28 type Line struct { 29 Text string 30 Time time.Time 31 Err error // Error from tail 32 } 33 34 // NewLine returns a Line with present time. 35 func NewLine(text string) *Line { 36 return &Line{text, time.Now(), nil} 37 } 38 39 // SeekInfo represents arguments to `os.Seek` 40 type SeekInfo struct { 41 Offset int64 42 Whence int // os.SEEK_* 43 } 44 45 type logger interface { 46 Fatal(v ...interface{}) 47 Fatalf(format string, v ...interface{}) 48 Fatalln(v ...interface{}) 49 Panic(v ...interface{}) 50 Panicf(format string, v ...interface{}) 51 Panicln(v ...interface{}) 52 Print(v ...interface{}) 53 Printf(format string, v ...interface{}) 54 Println(v ...interface{}) 55 } 56 57 // Config is used to specify how a file must be tailed. 58 type Config struct { 59 // File-specifc 60 Location *SeekInfo // Seek to this location before tailing 61 ReOpen bool // Reopen recreated files (tail -F) 62 MustExist bool // Fail early if the file does not exist 63 Poll bool // Poll for file changes instead of using inotify 64 Pipe bool // Is a named pipe (mkfifo) 65 RateLimiter *ratelimiter.LeakyBucket 66 67 // Generic IO 68 Follow bool // Continue looking for new lines (tail -f) 69 MaxLineSize int // If non-zero, split longer lines into multiple lines 70 71 // Logger, when nil, is set to tail.DefaultLogger 72 // To disable logging: set field to tail.DiscardingLogger 73 Logger logger 74 } 75 76 type Tail struct { 77 Filename string 78 Lines chan *Line 79 Config 80 81 file *os.File 82 reader *bufio.Reader 83 84 watcher watch.FileWatcher 85 changes *watch.FileChanges 86 87 tomb.Tomb // provides: Done, Kill, Dying 88 89 lk sync.Mutex 90 } 91 92 var ( 93 // DefaultLogger is used when Config.Logger == nil 94 DefaultLogger = log.New(os.Stderr, "", log.LstdFlags) 95 // DiscardingLogger can be used to disable logging output 96 DiscardingLogger = log.New(ioutil.Discard, "", 0) 97 ) 98 99 // TailFile begins tailing the file. Output stream is made available 100 // via the `Tail.Lines` channel. To handle errors during tailing, 101 // invoke the `Wait` or `Err` method after finishing reading from the 102 // `Lines` channel. 103 func TailFile(filename string, config Config) (*Tail, error) { 104 if config.ReOpen && !config.Follow { 105 util.Fatal("cannot set ReOpen without Follow.") 106 } 107 108 t := &Tail{ 109 Filename: filename, 110 Lines: make(chan *Line), 111 Config: config, 112 } 113 114 // when Logger was not specified in config, use default logger 115 if t.Logger == nil { 116 t.Logger = log.New(os.Stderr, "", log.LstdFlags) 117 } 118 119 if t.Poll { 120 t.watcher = watch.NewPollingFileWatcher(filename) 121 } else { 122 t.watcher = watch.NewInotifyFileWatcher(filename) 123 } 124 125 if t.MustExist { 126 var err error 127 t.file, err = OpenFile(t.Filename) 128 if err != nil { 129 return nil, err 130 } 131 } 132 133 go t.tailFileSync() 134 135 return t, nil 136 } 137 138 // Return the file's current position, like stdio's ftell(). 139 // But this value is not very accurate. 140 // it may readed one line in the chan(tail.Lines), 141 // so it may lost one line. 142 func (tail *Tail) Tell() (offset int64, err error) { 143 if tail.file == nil { 144 return 145 } 146 offset, err = tail.file.Seek(0, os.SEEK_CUR) 147 if err != nil { 148 return 149 } 150 151 tail.lk.Lock() 152 defer tail.lk.Unlock() 153 if tail.reader == nil { 154 return 155 } 156 157 offset -= int64(tail.reader.Buffered()) 158 return 159 } 160 161 // Stop stops the tailing activity. 162 func (tail *Tail) Stop() error { 163 tail.Kill(nil) 164 return tail.Wait() 165 } 166 167 // StopAtEOF stops tailing as soon as the end of the file is reached. 168 func (tail *Tail) StopAtEOF() error { 169 tail.Kill(errStopAtEOF) 170 return tail.Wait() 171 } 172 173 var errStopAtEOF = errors.New("tail: stop at eof") 174 175 func (tail *Tail) close() { 176 close(tail.Lines) 177 tail.closeFile() 178 } 179 180 func (tail *Tail) closeFile() { 181 if tail.file != nil { 182 tail.file.Close() 183 tail.file = nil 184 } 185 } 186 187 func (tail *Tail) reopen() error { 188 tail.closeFile() 189 for { 190 var err error 191 tail.file, err = OpenFile(tail.Filename) 192 if err != nil { 193 if os.IsNotExist(err) { 194 tail.Logger.Printf("Waiting for %s to appear...", tail.Filename) 195 if err := tail.watcher.BlockUntilExists(&tail.Tomb); err != nil { 196 if err == tomb.ErrDying { 197 return err 198 } 199 return fmt.Errorf("Failed to detect creation of %s: %s", tail.Filename, err) 200 } 201 continue 202 } 203 return fmt.Errorf("Unable to open file %s: %s", tail.Filename, err) 204 } 205 break 206 } 207 return nil 208 } 209 210 func (tail *Tail) readLine() (string, error) { 211 tail.lk.Lock() 212 line, err := tail.reader.ReadString('\n') 213 tail.lk.Unlock() 214 if err != nil { 215 // Note ReadString "returns the data read before the error" in 216 // case of an error, including EOF, so we return it as is. The 217 // caller is expected to process it if err is EOF. 218 return line, err 219 } 220 221 line = strings.TrimRight(line, "\n") 222 223 return line, err 224 } 225 226 func (tail *Tail) tailFileSync() { 227 defer func() { 228 recover() 229 }() 230 231 defer tail.Done() 232 defer tail.close() 233 234 if !tail.MustExist { 235 // deferred first open. 236 err := tail.reopen() 237 if err != nil { 238 if err != tomb.ErrDying { 239 tail.Kill(err) 240 } 241 return 242 } 243 } 244 245 // Seek to requested location on first open of the file. 246 if tail.Location != nil { 247 _, err := tail.file.Seek(tail.Location.Offset, tail.Location.Whence) 248 tail.Logger.Printf("Seeked %s - %+v\n", tail.Filename, tail.Location) 249 if err != nil { 250 tail.Killf("Seek error on %s: %s", tail.Filename, err) 251 return 252 } 253 } 254 255 tail.openReader() 256 257 var offset int64 258 var err error 259 260 // Read line by line. 261 for { 262 // do not seek in named pipes 263 if !tail.Pipe { 264 // grab the position in case we need to back up in the event of a half-line 265 offset, err = tail.Tell() 266 if err != nil { 267 tail.Kill(err) 268 return 269 } 270 } 271 272 line, err := tail.readLine() 273 274 // Process `line` even if err is EOF. 275 if err == nil { 276 cooloff := !tail.sendLine(line) 277 if cooloff { 278 // Wait a second before seeking till the end of 279 // file when rate limit is reached. 280 msg := ("Too much log activity; waiting a second " + 281 "before resuming tailing") 282 tail.Lines <- &Line{msg, time.Now(), errors.New(msg)} 283 select { 284 case <-time.After(time.Second): 285 case <-tail.Dying(): 286 return 287 } 288 if err := tail.seekEnd(); err != nil { 289 tail.Kill(err) 290 return 291 } 292 } 293 } else if err == io.EOF { 294 if !tail.Follow { 295 if line != "" { 296 tail.sendLine(line) 297 } 298 return 299 } 300 301 if tail.Follow && line != "" { 302 // this has the potential to never return the last line if 303 // it's not followed by a newline; seems a fair trade here 304 err := tail.seekTo(SeekInfo{Offset: offset, Whence: 0}) 305 if err != nil { 306 tail.Kill(err) 307 return 308 } 309 } 310 311 // When EOF is reached, wait for more data to become 312 // available. Wait strategy is based on the `tail.watcher` 313 // implementation (inotify or polling). 314 err := tail.waitForChanges() 315 if err != nil { 316 if err != ErrStop { 317 tail.Kill(err) 318 } 319 return 320 } 321 } else { 322 // non-EOF error 323 tail.Killf("Error reading %s: %s", tail.Filename, err) 324 return 325 } 326 327 select { 328 case <-tail.Dying(): 329 if tail.Err() == errStopAtEOF { 330 continue 331 } 332 return 333 default: 334 } 335 } 336 } 337 338 // waitForChanges waits until the file has been appended, deleted, 339 // moved or truncated. When moved or deleted - the file will be 340 // reopened if ReOpen is true. Truncated files are always reopened. 341 func (tail *Tail) waitForChanges() error { 342 if tail.changes == nil { 343 pos, err := tail.file.Seek(0, os.SEEK_CUR) 344 if err != nil { 345 return err 346 } 347 tail.changes, err = tail.watcher.ChangeEvents(&tail.Tomb, pos) 348 if err != nil { 349 return err 350 } 351 } 352 353 select { 354 case <-tail.changes.Modified: 355 return nil 356 case <-tail.changes.Deleted: 357 tail.changes = nil 358 if tail.ReOpen { 359 // XXX: we must not log from a library. 360 tail.Logger.Printf("Re-opening moved/deleted file %s ...", tail.Filename) 361 if err := tail.reopen(); err != nil { 362 return err 363 } 364 tail.Logger.Printf("Successfully reopened %s", tail.Filename) 365 tail.openReader() 366 return nil 367 } else { 368 tail.Logger.Printf("Stopping tail as file no longer exists: %s", tail.Filename) 369 return ErrStop 370 } 371 case <-tail.changes.Truncated: 372 // Always reopen truncated files (Follow is true) 373 tail.Logger.Printf("Re-opening truncated file %s ...", tail.Filename) 374 if err := tail.reopen(); err != nil { 375 return err 376 } 377 tail.Logger.Printf("Successfully reopened truncated %s", tail.Filename) 378 tail.openReader() 379 return nil 380 case <-tail.Dying(): 381 return ErrStop 382 } 383 panic("unreachable") 384 } 385 386 func (tail *Tail) openReader() { 387 if tail.MaxLineSize > 0 { 388 // add 2 to account for newline characters 389 tail.reader = bufio.NewReaderSize(tail.file, tail.MaxLineSize+2) 390 } else { 391 tail.reader = bufio.NewReader(tail.file) 392 } 393 } 394 395 func (tail *Tail) seekEnd() error { 396 return tail.seekTo(SeekInfo{Offset: 0, Whence: os.SEEK_END}) 397 } 398 399 func (tail *Tail) seekTo(pos SeekInfo) error { 400 _, err := tail.file.Seek(pos.Offset, pos.Whence) 401 if err != nil { 402 return fmt.Errorf("Seek error on %s: %s", tail.Filename, err) 403 } 404 // Reset the read buffer whenever the file is re-seek'ed 405 tail.reader.Reset(tail.file) 406 return nil 407 } 408 409 // sendLine sends the line(s) to Lines channel, splitting longer lines 410 // if necessary. Return false if rate limit is reached. 411 func (tail *Tail) sendLine(line string) bool { 412 now := time.Now() 413 lines := []string{line} 414 415 // Split longer lines 416 if tail.MaxLineSize > 0 && len(line) > tail.MaxLineSize { 417 lines = util.PartitionString(line, tail.MaxLineSize) 418 } 419 420 for _, line := range lines { 421 tail.Lines <- &Line{line, now, nil} 422 } 423 424 if tail.Config.RateLimiter != nil { 425 ok := tail.Config.RateLimiter.Pour(uint16(len(lines))) 426 if !ok { 427 tail.Logger.Printf("Leaky bucket full (%v); entering 1s cooloff period.\n", 428 tail.Filename) 429 return false 430 } 431 } 432 433 return true 434 } 435 436 // Cleanup removes inotify watches added by the tail package. This function is 437 // meant to be invoked from a process's exit handler. Linux kernel may not 438 // automatically remove inotify watches after the process exits. 439 func (tail *Tail) Cleanup() { 440 watch.Cleanup(tail.Filename) 441 }