// Package logfile provides a size-capped rotating writer for the per-stream // downloader and packager logs. // // It replaces two patterns that both lost information: the N_m3u8DL-RE log was // opened with O_TRUNC on every start, which erased the evidence from the crash // you were about to investigate, and the ffmpeg logs were opened O_APPEND with // no bound, which grew without limit on a long-running stream. package logfile import ( "fmt" "os" "path/filepath" "sync" "time" ) // Defaults for a per-stream log. const ( DefaultMaxBytes = 8 << 20 // 8 MiB per generation DefaultGenerations = 3 // name.log, name.log.1, name.log.2 ) // Writer is an io.WriteCloser that rotates when the file passes MaxBytes. // It is safe for concurrent use, and for being handed to an exec.Cmd as // Stdout and Stderr at the same time. type Writer struct { path string maxBytes int64 generations int mu sync.Mutex f *os.File size int64 } // Open opens path for appending, rotating it if it is already over the cap. // maxBytes and generations fall back to the defaults when not positive. func Open(path string, maxBytes int64, generations int) (*Writer, error) { if maxBytes <= 0 { maxBytes = DefaultMaxBytes } if generations <= 0 { generations = DefaultGenerations } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return nil, err } w := &Writer{path: path, maxBytes: maxBytes, generations: generations} if err := w.reopen(); err != nil { return nil, err } return w, nil } // OpenWithBanner opens the log and writes a start marker, so one file can hold // several runs and still be readable. This is what replaces truncating. func OpenWithBanner(path string, maxBytes int64, generations int, what string) (*Writer, error) { w, err := Open(path, maxBytes, generations) if err != nil { return nil, err } _, _ = fmt.Fprintf(w, "\n==== %s start %s ====\n", what, time.Now().UTC().Format(time.RFC3339)) return w, nil } func (w *Writer) reopen() error { f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { return err } w.f = f if st, err := f.Stat(); err == nil { w.size = st.Size() } else { w.size = 0 } return nil } func (w *Writer) Write(p []byte) (int, error) { w.mu.Lock() defer w.mu.Unlock() if w.f == nil { return 0, os.ErrClosed } // Rotate before the write that would cross the cap, so a generation never // greatly exceeds MaxBytes. if w.size > 0 && w.size+int64(len(p)) > w.maxBytes { if err := w.rotateLocked(); err != nil { // Rotation failing (a Windows file lock, say) must not lose the // log line: keep writing to the current file. _, _ = fmt.Fprintf(w.f, "==== rotate failed: %v ====\n", err) } } n, err := w.f.Write(p) w.size += int64(n) return n, err } // rotateLocked shifts name.log.N-1 -> name.log.N and starts a fresh file. func (w *Writer) rotateLocked() error { if err := w.f.Close(); err != nil { // Still try to rotate; reopen below will surface a real problem. _ = err } // Drop the oldest, then walk down so each generation moves up one. oldest := fmt.Sprintf("%s.%d", w.path, w.generations-1) _ = os.Remove(oldest) for i := w.generations - 2; i >= 1; i-- { from := fmt.Sprintf("%s.%d", w.path, i) to := fmt.Sprintf("%s.%d", w.path, i+1) if _, err := os.Stat(from); err == nil { _ = os.Rename(from, to) } } if w.generations > 1 { if err := os.Rename(w.path, w.path+".1"); err != nil && !os.IsNotExist(err) { // Could not move the live file; reopen it and carry on appending. if rerr := w.reopen(); rerr != nil { return rerr } return err } } else { _ = os.Remove(w.path) } return w.reopen() } func (w *Writer) Close() error { w.mu.Lock() defer w.mu.Unlock() if w.f == nil { return nil } err := w.f.Close() w.f = nil return err } // Path is the live file's path. func (w *Writer) Path() string { return w.path } // Tail returns the last n lines of path. Reads from the end rather than // loading the file, so an 8 MiB log is cheap to tail. func Tail(path string, lines int) ([]byte, error) { if lines <= 0 { lines = 200 } f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() st, err := f.Stat() if err != nil { return nil, err } size := st.Size() if size == 0 { return nil, nil } const chunk = 64 << 10 var ( buf []byte newlines int pos = size ) for pos > 0 && newlines <= lines { readSize := int64(chunk) if pos < readSize { readSize = pos } pos -= readSize part := make([]byte, readSize) if _, err := f.ReadAt(part, pos); err != nil { return nil, err } for _, b := range part { if b == '\n' { newlines++ } } buf = append(part, buf...) // Guard against a single enormous line eating memory. if int64(len(buf)) > 8<<20 { break } } // Trim to the requested number of trailing lines. count := 0 for i := len(buf) - 1; i >= 0; i-- { if buf[i] != '\n' { continue } // Ignore a trailing newline at the very end of the file. if i == len(buf)-1 { continue } // The content after the Nth newline from the end is exactly N lines, // so stop on the Nth, not past it. count++ if count == lines { return buf[i+1:], nil } } return buf, nil }