Commit inicial
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxLineLen = 64 * 1024
|
||||
|
||||
// Tail sigue un archivo por sondeo (funciona igual en Windows, Linux y macOS).
|
||||
// Detecta rotación (archivo reemplazado) y truncado, y llama a emit por línea.
|
||||
func Tail(ctx context.Context, path string, fromStart bool, poll time.Duration, emit func(string)) {
|
||||
first := true
|
||||
for ctx.Err() == nil {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
if first {
|
||||
log.Printf("[tail] no se puede abrir %s: %v (reintentando)", path, err)
|
||||
}
|
||||
first = false
|
||||
if !sleepCtx(ctx, time.Second) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
start := !first || fromStart
|
||||
first = false
|
||||
err = follow(ctx, f, path, start, poll, emit)
|
||||
f.Close()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Printf("[tail] %s: %v; reabriendo", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var errRotated = errors.New("archivo rotado")
|
||||
|
||||
func follow(ctx context.Context, f *os.File, path string, fromStart bool, poll time.Duration, emit func(string)) error {
|
||||
var offset int64
|
||||
if !fromStart {
|
||||
off, err := f.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
offset = off
|
||||
}
|
||||
openedInfo, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("[tail] siguiendo %s desde el byte %d", path, offset)
|
||||
|
||||
r := bufio.NewReaderSize(f, maxLineLen)
|
||||
var partial []byte
|
||||
skipping := false
|
||||
|
||||
readAvailable := func() error {
|
||||
for {
|
||||
chunk, err := r.ReadSlice('\n')
|
||||
offset += int64(len(chunk))
|
||||
switch {
|
||||
case err == nil:
|
||||
if skipping { // final de una línea demasiado larga
|
||||
skipping = false
|
||||
partial = partial[:0]
|
||||
continue
|
||||
}
|
||||
line := chunk
|
||||
if len(partial) > 0 {
|
||||
partial = append(partial, chunk...)
|
||||
line = partial
|
||||
}
|
||||
emit(string(trimEOL(line)))
|
||||
partial = partial[:0]
|
||||
case errors.Is(err, bufio.ErrBufferFull):
|
||||
skipping = true
|
||||
partial = partial[:0]
|
||||
case err == io.EOF:
|
||||
if !skipping {
|
||||
partial = append(partial, chunk...)
|
||||
if len(partial) > maxLineLen {
|
||||
skipping = true
|
||||
partial = partial[:0]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
if err := readAvailable(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !sleepCtx(ctx, poll) {
|
||||
return nil
|
||||
}
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
continue // puede estar en plena rotación
|
||||
}
|
||||
if !os.SameFile(openedInfo, fi) {
|
||||
_ = readAvailable() // lo que quede en el archivo viejo
|
||||
return errRotated
|
||||
}
|
||||
if fi.Size() < offset { // truncado
|
||||
log.Printf("[tail] %s truncado; leyendo desde el inicio", path)
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
offset = 0
|
||||
r.Reset(f)
|
||||
partial = partial[:0]
|
||||
skipping = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func trimEOL(b []byte) []byte {
|
||||
for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r') {
|
||||
b = b[:len(b)-1]
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user