All checks were successful
release / build-and-upload (push) Successful in 6m56s
Wrap N_m3u8DL-RE with util-linux script so Spectre gets a real TTY; drop subtitles; pin COLUMNS/LINES; kill process group on stop. Fixes immediate 'downloader exited before any media arrived' on serve start.
239 lines
6.2 KiB
Go
239 lines
6.2 KiB
Go
// 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
|
|
}
|
|
|
|
// OpenCmdLog prepares a rotating append log and returns the live *os.File for
|
|
// exec.Cmd Stdout/Stderr. Go only inherits a real FD for *os.File; any other
|
|
// io.Writer becomes a pipe, and N_m3u8DL-RE's Spectre progress UI crashes on
|
|
// pipe-backed consoles (ArgumentException in LiveRenderable.RemoveRange).
|
|
//
|
|
// The caller owns the file and must Close it. Mid-run size rotation is skipped
|
|
// (rotation still happens at open when the prior file is already over the cap).
|
|
func OpenCmdLog(path string, maxBytes int64, generations int, what string) (*os.File, error) {
|
|
w, err := OpenWithBanner(path, maxBytes, generations, what)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return w.DetachFile()
|
|
}
|
|
|
|
// DetachFile transfers ownership of the underlying *os.File to the caller.
|
|
// The Writer becomes inert; do not Write or Close it afterward.
|
|
func (w *Writer) DetachFile() (*os.File, error) {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
if w.f == nil {
|
|
return nil, os.ErrClosed
|
|
}
|
|
f := w.f
|
|
w.f = nil
|
|
return f, 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
|
|
}
|