Files
urutau/internal/tail/tail.go
T
Lucas RayanandClaude Opus 5.5 87178dbc94
CI / Format and vet (push) Successful in 1m15s
CI / Dependency audit (push) Successful in 36s
CI / Tests (Linux, race detector) (push) Successful in 2m7s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Skipped
Release / Build hub image (amd64) (push) Skipped
Release / Build probe image (amd64) (push) Skipped
Release / Build hub image (arm64) (push) Skipped
Release / Build probe image (arm64) (push) Skipped
Release / Publish tags (hub) (push) Successful in 18s
Release / Publish tags (probe) (push) Successful in 18s
Release / Gitea release (push) Successful in 4s
fix: head fingerprint covers the whole first line; hub no longer drops traefik generations whose first 64 bytes repeat (2.2.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:57:25 -03:00

393 lines
9.0 KiB
Go

// Package tail follows a log file across truncation and rotation, and reads
// rotated backups for backfill.
package tail
import (
"bufio"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
"sync"
"syscall"
"time"
)
// Pos is the resumable position inside a followed file.
type Pos struct {
Inode uint64
Offset int64
// FP fingerprints the first FPLen bytes of the file (FNV-1a). It catches
// copytruncate rotations where the file shrinks and regrows past the saved
// offset between two polls: the size alone would not show it.
FP uint64
FPLen int
}
// fpMax covers a whole first line: Traefik's first 64 bytes (client address and
// port of a keep-alive connection) repeat across rotations, so a short head
// cannot tell two generations of the file apart.
const fpMax = 1024
func fingerprint(b []byte) uint64 {
h := uint64(14695981039346656037)
for _, c := range b {
h ^= uint64(c)
h *= 1099511628211
}
return h
}
// headMatches reports whether the first fpLen bytes of fh still hash to fp.
func headMatches(fh *os.File, fp uint64, fpLen int) bool {
buf := make([]byte, fpLen)
n, err := fh.ReadAt(buf, 0)
return n == fpLen && (err == nil || err == io.EOF) && fingerprint(buf) == fp
}
// Follower reads complete lines from Path as they appear.
type Follower struct {
Path string
MaxLine int // lines longer than this are skipped and reported
Poll time.Duration // default 500ms
Handle func(line []byte) // must not retain line
// HandleAt, when set, is called instead of Handle with the position right
// after the line (newline included).
HandleAt func(line []byte, end Pos)
Oversize func() // called once per skipped oversized line
// Mu, when set, is held while Handle runs and the position advances, so a
// snapshot taking the same mutex sees state and offsets in agreement.
Mu *sync.Mutex
mu sync.Mutex
pos Pos
err error
f *os.File
rd *bufio.Reader
// tail of an unterminated line, and whether we are discarding an oversized one
partial []byte
pending int
discard bool
}
// NewFollower resumes from pos (zero value: start at the beginning).
func NewFollower(path string, pos Pos) *Follower {
return &Follower{Path: path, pos: pos, MaxLine: 64 * 1024, Poll: 500 * time.Millisecond}
}
// Pos returns the current position.
func (f *Follower) Pos() Pos { f.mu.Lock(); defer f.mu.Unlock(); return f.pos }
// Err returns the last open/read error, nil when the file is being followed.
func (f *Follower) Err() error { f.mu.Lock(); defer f.mu.Unlock(); return f.err }
func (f *Follower) setErr(err error) { f.mu.Lock(); f.err = err; f.mu.Unlock() }
func inodeOf(fi os.FileInfo) uint64 {
if st, ok := fi.Sys().(*syscall.Stat_t); ok {
return uint64(st.Ino)
}
return 0
}
func (f *Follower) closeFile() {
if f.f != nil {
f.f.Close()
f.f, f.rd = nil, nil
}
f.partial, f.discard, f.pending = nil, false, 0
}
func (f *Follower) open() error {
fh, err := os.Open(f.Path)
if err != nil {
return err
}
fi, err := fh.Stat()
if err != nil {
fh.Close()
return err
}
ino := inodeOf(fi)
p := f.Pos()
off := p.Offset
// A different inode than the saved one means the file was rotated while we
// were not looking; so does an offset past the end (truncation).
if (p.Inode != 0 && p.Inode != ino) || off > fi.Size() || off < 0 {
off = 0
}
if off > 0 && p.FPLen > 0 && !headMatches(fh, p.FP, p.FPLen) {
off = 0 // same inode, different content at the start: truncated and regrown while we were away
}
if off > 0 {
if _, err := fh.Seek(off, io.SeekStart); err != nil {
fh.Close()
return err
}
}
f.f = fh
f.rd = bufio.NewReaderSize(fh, 64*1024)
f.partial, f.discard, f.pending = nil, false, 0
f.mu.Lock()
f.pos = Pos{Inode: ino, Offset: off}
if off > 0 {
f.pos.FP, f.pos.FPLen = p.FP, p.FPLen
}
f.mu.Unlock()
return nil
}
func (f *Follower) emit(line []byte, consumed int) {
if f.Mu != nil {
f.Mu.Lock()
}
if line != nil {
if f.HandleAt != nil {
end := f.Pos()
end.Offset += int64(consumed)
f.HandleAt(line, end)
} else {
f.Handle(line)
}
}
f.mu.Lock()
f.pos.Offset += int64(consumed)
f.mu.Unlock()
if f.Mu != nil {
f.Mu.Unlock()
}
}
// drain reads until EOF, emitting complete lines. The offset only advances
// past whole lines, so a restart never resumes in the middle of one.
func (f *Follower) drain() error {
for {
chunk, err := f.rd.ReadSlice('\n')
if len(chunk) > 0 {
f.pending += len(chunk)
if !f.discard {
if len(f.partial)+len(chunk) > f.MaxLine+2 {
f.discard = true
f.partial = f.partial[:0]
if f.Oversize != nil {
f.Oversize()
}
} else {
f.partial = append(f.partial, chunk...)
}
}
if chunk[len(chunk)-1] == '\n' {
var line []byte
if !f.discard {
line = trimEOL(f.partial)
if line == nil {
line = []byte{}
}
}
f.emit(line, f.pending)
f.partial = f.partial[:0]
f.pending = 0
f.discard = false
}
}
switch {
case err == nil:
case errors.Is(err, bufio.ErrBufferFull):
case errors.Is(err, io.EOF):
return nil
default:
return err
}
}
}
// Run follows the file until ctx is done.
func (f *Follower) Run(ctx context.Context) {
poll := f.Poll
if poll <= 0 {
poll = 500 * time.Millisecond
}
t := time.NewTicker(poll)
defer t.Stop()
defer f.closeFile()
for {
f.step()
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
func (f *Follower) step() {
if f.f == nil {
if err := f.open(); err != nil {
f.setErr(err)
return
}
}
f.verifyHead()
if f.f == nil {
return
}
if err := f.drain(); err != nil {
f.setErr(err)
f.closeFile()
return
}
f.setErr(nil)
f.recordHead()
// Detect rotation: truncation in place or a different file at the path.
fi, err := os.Stat(f.Path)
if err != nil {
return // path gone: keep draining the old handle until a new file appears
}
cur, err := f.f.Stat()
if err != nil {
f.closeFile()
return
}
switch {
case inodeOf(fi) != inodeOf(cur):
_ = f.drain() // finish the old file first
f.closeFile()
f.mu.Lock()
f.pos = Pos{}
f.mu.Unlock()
case cur.Size() < f.Pos().Offset:
f.closeFile()
f.mu.Lock()
f.pos = Pos{Inode: inodeOf(cur), Offset: 0}
f.mu.Unlock()
}
}
func trimEOL(b []byte) []byte {
if n := len(b); n > 0 && b[n-1] == '\n' {
b = b[:n-1]
}
if n := len(b); n > 0 && b[n-1] == '\r' {
b = b[:n-1]
}
return b
}
// Backups returns the rotated copies of path ordered from oldest to newest:
// path.N.gz ... path.1.gz and path.1.
func Backups(path string) []string {
type item struct {
n int
name string
}
var found []item
for n := 1; n <= 9; n++ {
for _, suf := range []string{".gz", ""} {
name := fmt.Sprintf("%s.%d%s", path, n, suf)
if _, err := os.Stat(name); err == nil {
found = append(found, item{n, name})
break
}
}
}
sort.Slice(found, func(i, j int) bool { return found[i].n > found[j].n })
out := make([]string, len(found))
for i, it := range found {
out[i] = it.name
}
return out
}
// ReadAll feeds every line of a (possibly gzip) file to handle. Oversized
// lines are skipped and reported through oversize.
func ReadAll(path string, maxLine int, handle func(line []byte), oversize func()) error {
fh, err := os.Open(path)
if err != nil {
return err
}
defer fh.Close()
var r io.Reader = fh
if strings.HasSuffix(path, ".gz") {
gz, err := gzip.NewReader(fh)
if err != nil {
return err
}
defer gz.Close()
r = gz
}
br := bufio.NewReaderSize(r, 64*1024)
var buf []byte
skipping := false
for {
chunk, err := br.ReadSlice('\n')
complete := len(chunk) > 0 && chunk[len(chunk)-1] == '\n'
if len(chunk) > 0 && !skipping {
if len(buf)+len(chunk) > maxLine+2 {
skipping = true
buf = buf[:0]
if oversize != nil {
oversize()
}
} else {
buf = append(buf, chunk...)
}
}
if complete {
if !skipping && len(buf) > 0 {
handle(trimEOL(buf))
}
buf, skipping = buf[:0], false
}
if err != nil && !errors.Is(err, bufio.ErrBufferFull) {
if errors.Is(err, io.EOF) {
if !skipping && len(buf) > 0 {
handle(trimEOL(buf))
}
return nil
}
return err
}
}
}
// verifyHead resets the position when the head of the file changed under us
// (truncate-and-regrow with the same inode); it runs BEFORE reading, so the
// stale offset is never applied to the new content.
func (f *Follower) verifyHead() {
p := f.Pos()
if p.FPLen > 0 && !headMatches(f.f, p.FP, p.FPLen) {
f.closeFile()
if err := f.open(); err != nil {
f.setErr(err)
}
f.mu.Lock()
f.pos = Pos{Inode: f.pos.Inode}
f.mu.Unlock()
if f.f != nil {
f.f.Seek(0, io.SeekStart)
f.rd.Reset(f.f)
}
}
}
// recordHead keeps the fingerprint of the first bytes already consumed.
func (f *Follower) recordHead() {
p := f.Pos()
if p.FPLen < fpMax && p.Offset > int64(p.FPLen) {
n := int(p.Offset)
if n > fpMax {
n = fpMax
}
buf := make([]byte, n)
if m, err := f.f.ReadAt(buf, 0); m == n && (err == nil || err == io.EOF) {
f.mu.Lock()
f.pos.FP, f.pos.FPLen = fingerprint(buf), n
f.mu.Unlock()
}
}
}