streamd: preview quality picker, dashboard polish, C4 wrap keys
All checks were successful
release / build-and-upload (push) Successful in 6m18s
modules-release / build-and-upload (push) Successful in 5m18s

- Preview player can select FHD/HD/SD (or ABR master) from publish links
- Embed dashboard screenshots in README; Linux streamd+agent setup guide
- C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH
- Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
This commit is contained in:
404errordeveloper 2026-10-09 20:57:43 +02:00
parent b3955bd81e
commit 066e018749
113 changed files with 19002 additions and 1541 deletions

View file

@ -0,0 +1,211 @@
// 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
}

View file

@ -0,0 +1,192 @@
package logfile
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func TestRotatesAtSizeCap(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "stream-nre.log")
w, err := Open(path, 1024, 3)
if err != nil {
t.Fatal(err)
}
defer w.Close()
line := strings.Repeat("x", 100) + "\n"
for i := 0; i < 50; i++ {
if _, err := w.Write([]byte(line)); err != nil {
t.Fatal(err)
}
}
// The live file must stay near the cap, not grow to 5 KiB.
st, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if st.Size() > 1024+int64(len(line)) {
t.Errorf("live log is %d bytes, cap is 1024", st.Size())
}
// Generations exist, and no more than were asked for.
if _, err := os.Stat(path + ".1"); err != nil {
t.Errorf("expected a rotated generation: %v", err)
}
if _, err := os.Stat(path + ".3"); err == nil {
t.Error("generation 3 should not exist with generations=3 (0,1,2)")
}
}
func TestGenerationCountRespected(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "x.log")
w, err := Open(path, 200, 2)
if err != nil {
t.Fatal(err)
}
defer w.Close()
for i := 0; i < 40; i++ {
_, _ = w.Write([]byte(strings.Repeat("y", 50) + "\n"))
}
ents, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
// generations=2 means x.log and x.log.1 only.
if len(ents) > 2 {
var names []string
for _, e := range ents {
names = append(names, e.Name())
}
t.Errorf("want at most 2 files, got %v", names)
}
}
// Reopening must append, not truncate: a restart has to leave the previous
// run's output in place, which is the whole point of this package.
func TestReopenAppendsAndBannerMarksRuns(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "run.log")
w1, err := OpenWithBanner(path, 1<<20, 3, "nre")
if err != nil {
t.Fatal(err)
}
_, _ = w1.Write([]byte("first run output\n"))
_ = w1.Close()
w2, err := OpenWithBanner(path, 1<<20, 3, "nre")
if err != nil {
t.Fatal(err)
}
_, _ = w2.Write([]byte("second run output\n"))
_ = w2.Close()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
body := string(b)
if !strings.Contains(body, "first run output") {
t.Error("the previous run's output was lost — this is the O_TRUNC bug")
}
if !strings.Contains(body, "second run output") {
t.Error("the new run's output is missing")
}
if n := strings.Count(body, "==== nre start "); n != 2 {
t.Errorf("want 2 start banners, got %d", n)
}
}
func TestTail(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "t.log")
var buf bytes.Buffer
for i := 0; i < 500; i++ {
fmt.Fprintf(&buf, "line %d\n", i)
}
if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil {
t.Fatal(err)
}
out, err := Tail(path, 10)
if err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
if len(lines) != 10 {
t.Fatalf("want 10 lines, got %d: %q", len(lines), string(out))
}
if lines[9] != "line 499" {
t.Errorf("last line = %q, want %q", lines[9], "line 499")
}
if lines[0] != "line 490" {
t.Errorf("first line = %q, want %q", lines[0], "line 490")
}
// Asking for more lines than exist returns the whole file.
out, err = Tail(path, 10000)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(out, buf.Bytes()) {
t.Error("tail of a short file should return all of it")
}
}
func TestTailEmptyAndMissing(t *testing.T) {
dir := t.TempDir()
empty := filepath.Join(dir, "empty.log")
if err := os.WriteFile(empty, nil, 0o644); err != nil {
t.Fatal(err)
}
if out, err := Tail(empty, 10); err != nil || len(out) != 0 {
t.Errorf("empty file: got %q %v", out, err)
}
if _, err := Tail(filepath.Join(dir, "nope.log"), 10); err == nil {
t.Error("a missing file should error")
}
}
func TestWriteAfterCloseDoesNotPanic(t *testing.T) {
path := filepath.Join(t.TempDir(), "c.log")
w, err := Open(path, 1<<20, 2)
if err != nil {
t.Fatal(err)
}
_ = w.Close()
if _, err := w.Write([]byte("x")); err == nil {
t.Error("writing to a closed writer should error, not panic")
}
// Double close is harmless.
if err := w.Close(); err != nil {
t.Errorf("second Close should be a no-op, got %v", err)
}
}
func TestConcurrentWrites(t *testing.T) {
path := filepath.Join(t.TempDir(), "p.log")
// An exec.Cmd gets this same writer as both Stdout and Stderr, so
// concurrent writes are the normal case, not an edge case.
w, err := Open(path, 4096, 3)
if err != nil {
t.Fatal(err)
}
defer w.Close()
done := make(chan struct{})
for g := 0; g < 4; g++ {
go func(g int) {
defer func() { done <- struct{}{} }()
for i := 0; i < 100; i++ {
_, _ = w.Write([]byte(fmt.Sprintf("writer %d line %d\n", g, i)))
}
}(g)
}
for i := 0; i < 4; i++ {
<-done
}
}