- 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
438 lines
12 KiB
Go
438 lines
12 KiB
Go
package db
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// Event kinds recorded against a stream. Together they are the stream's
|
|
// timeline: who or what acted, and what the supervisor saw happen.
|
|
const (
|
|
EventCreated = "created"
|
|
EventUpdated = "updated"
|
|
EventDeleted = "deleted"
|
|
EventStarted = "started"
|
|
EventStopped = "stopped"
|
|
EventRestarted = "restarted"
|
|
EventCrashed = "crashed"
|
|
EventFFRestart = "ff_restart"
|
|
EventVariantUp = "variant_up"
|
|
EventVariantDown = "variant_down"
|
|
EventOnDemandWake = "ondemand_wake"
|
|
EventIdleStop = "idle_stop"
|
|
EventScheduledStart = "scheduled_start"
|
|
EventScheduledStop = "scheduled_stop"
|
|
EventCredsSet = "creds_set"
|
|
EventClaimed = "claimed"
|
|
EventReleased = "released"
|
|
EventProbe = "probe"
|
|
EventCaptureStarted = "capture_started"
|
|
EventCaptureOK = "capture_ok"
|
|
EventCaptureFailed = "capture_failed"
|
|
)
|
|
|
|
// Severities.
|
|
const (
|
|
SevInfo = "info"
|
|
SevWarn = "warn"
|
|
SevError = "error"
|
|
)
|
|
|
|
// ActorSystem is the actor for anything streamd did by itself.
|
|
const ActorSystem = "system"
|
|
|
|
// StreamEvent is one entry on a stream's timeline.
|
|
type StreamEvent struct {
|
|
ID int64 `json:"id"`
|
|
StreamID int64 `json:"stream_id"`
|
|
StreamName string `json:"stream_name,omitempty"`
|
|
At string `json:"at"`
|
|
Kind string `json:"kind"`
|
|
Severity string `json:"severity"`
|
|
Actor string `json:"actor"`
|
|
Message string `json:"message"`
|
|
// Detail is raw JSON, passed through to the client as-is.
|
|
Detail json.RawMessage `json:"detail,omitempty"`
|
|
}
|
|
|
|
// MetricPoint is one health sample for a stream.
|
|
type MetricPoint struct {
|
|
At string `json:"at"`
|
|
Health string `json:"health"`
|
|
BitrateMbps float64 `json:"bitrate_mbps"`
|
|
PlaylistAgeS float64 `json:"playlist_age_s"`
|
|
Viewers int `json:"viewers"`
|
|
// Bucket is 0 for a raw sample and the rollup width in seconds for an
|
|
// aggregate (60 for the one-minute rollups kept beyond the raw window).
|
|
Bucket int `json:"bucket,omitempty"`
|
|
}
|
|
|
|
// Retention windows.
|
|
const (
|
|
// RawMetricWindow is how long per-tick samples are kept before being
|
|
// rolled up into one-minute averages.
|
|
RawMetricWindow = time.Hour
|
|
// RollupRetention is how long the one-minute rollups are kept.
|
|
RollupRetention = 7 * 24 * time.Hour
|
|
// EventRetention is how long a stream's timeline is kept.
|
|
EventRetention = 90 * 24 * time.Hour
|
|
rollupBucketS = 60
|
|
)
|
|
|
|
// history holds the buffered event and metric writes. The store runs on a
|
|
// single database connection shared with every stream write, so neither a
|
|
// 5-second metric tick nor a crash loop may write per occurrence.
|
|
type history struct {
|
|
mu sync.Mutex
|
|
events []StreamEvent
|
|
metrics []bufferedMetric
|
|
}
|
|
|
|
type bufferedMetric struct {
|
|
streamID int64
|
|
point MetricPoint
|
|
}
|
|
|
|
const maxHistoryBuffer = 20_000
|
|
|
|
func (s *Store) migrateHistory() error {
|
|
_, err := s.DB.Exec(`
|
|
CREATE TABLE IF NOT EXISTS stream_events (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
|
at TEXT NOT NULL,
|
|
kind TEXT NOT NULL,
|
|
severity TEXT NOT NULL DEFAULT 'info',
|
|
actor TEXT NOT NULL DEFAULT '',
|
|
message TEXT NOT NULL DEFAULT '',
|
|
detail_json TEXT NOT NULL DEFAULT ''
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_events_stream_at ON stream_events(stream_id, id DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_events_at ON stream_events(at);
|
|
|
|
CREATE TABLE IF NOT EXISTS stream_metrics (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
|
at TEXT NOT NULL,
|
|
health TEXT NOT NULL DEFAULT '',
|
|
bitrate_mbps REAL NOT NULL DEFAULT 0,
|
|
playlist_age_s REAL NOT NULL DEFAULT 0,
|
|
viewers INTEGER NOT NULL DEFAULT 0,
|
|
bucket INTEGER NOT NULL DEFAULT 0
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_metrics_stream_at ON stream_metrics(stream_id, at);
|
|
`)
|
|
return err
|
|
}
|
|
|
|
// AddEvent buffers one timeline entry.
|
|
func (s *Store) AddEvent(e StreamEvent) {
|
|
if e.StreamID == 0 || e.Kind == "" {
|
|
return
|
|
}
|
|
if e.At == "" {
|
|
e.At = now()
|
|
}
|
|
if e.Severity == "" {
|
|
e.Severity = SevInfo
|
|
}
|
|
if e.Actor == "" {
|
|
e.Actor = ActorSystem
|
|
}
|
|
e.Message = truncateStr(e.Message, 2000)
|
|
s.hist.mu.Lock()
|
|
defer s.hist.mu.Unlock()
|
|
if len(s.hist.events) >= maxHistoryBuffer {
|
|
s.hist.events = s.hist.events[1:]
|
|
}
|
|
s.hist.events = append(s.hist.events, e)
|
|
}
|
|
|
|
// Eventf is the common case: a system event with a formatted message.
|
|
func (s *Store) Eventf(streamID int64, kind, severity, format string, args ...any) {
|
|
s.AddEvent(StreamEvent{
|
|
StreamID: streamID,
|
|
Kind: kind,
|
|
Severity: severity,
|
|
Actor: ActorSystem,
|
|
Message: fmt.Sprintf(format, args...),
|
|
})
|
|
}
|
|
|
|
// AddMetric buffers one health sample.
|
|
func (s *Store) AddMetric(streamID int64, p MetricPoint) {
|
|
if streamID == 0 {
|
|
return
|
|
}
|
|
if p.At == "" {
|
|
p.At = now()
|
|
}
|
|
s.hist.mu.Lock()
|
|
defer s.hist.mu.Unlock()
|
|
if len(s.hist.metrics) >= maxHistoryBuffer {
|
|
s.hist.metrics = s.hist.metrics[1:]
|
|
}
|
|
s.hist.metrics = append(s.hist.metrics, bufferedMetric{streamID: streamID, point: p})
|
|
}
|
|
|
|
// FlushHistory writes buffered events and metrics in one transaction.
|
|
func (s *Store) FlushHistory() error {
|
|
s.hist.mu.Lock()
|
|
events := s.hist.events
|
|
metrics := s.hist.metrics
|
|
s.hist.events = nil
|
|
s.hist.metrics = nil
|
|
s.hist.mu.Unlock()
|
|
|
|
if len(events) == 0 && len(metrics) == 0 {
|
|
return nil
|
|
}
|
|
requeue := func() {
|
|
s.hist.mu.Lock()
|
|
s.hist.events = append(events, s.hist.events...)
|
|
s.hist.metrics = append(metrics, s.hist.metrics...)
|
|
if len(s.hist.events) > maxHistoryBuffer {
|
|
s.hist.events = s.hist.events[len(s.hist.events)-maxHistoryBuffer:]
|
|
}
|
|
if len(s.hist.metrics) > maxHistoryBuffer {
|
|
s.hist.metrics = s.hist.metrics[len(s.hist.metrics)-maxHistoryBuffer:]
|
|
}
|
|
s.hist.mu.Unlock()
|
|
}
|
|
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
requeue()
|
|
return err
|
|
}
|
|
if len(events) > 0 {
|
|
stmt, err := tx.Prepare(`
|
|
INSERT INTO stream_events(stream_id,at,kind,severity,actor,message,detail_json)
|
|
VALUES(?,?,?,?,?,?,?)`)
|
|
if err != nil {
|
|
_ = tx.Rollback()
|
|
requeue()
|
|
return err
|
|
}
|
|
for _, e := range events {
|
|
// A stream deleted between buffering and flushing takes its
|
|
// events with it; the foreign key makes that insert fail, which
|
|
// must not abort the whole batch.
|
|
_, _ = stmt.Exec(e.StreamID, e.At, e.Kind, e.Severity, e.Actor, e.Message, string(e.Detail))
|
|
}
|
|
_ = stmt.Close()
|
|
}
|
|
if len(metrics) > 0 {
|
|
stmt, err := tx.Prepare(`
|
|
INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
|
|
VALUES(?,?,?,?,?,?,?)`)
|
|
if err != nil {
|
|
_ = tx.Rollback()
|
|
requeue()
|
|
return err
|
|
}
|
|
for _, m := range metrics {
|
|
_, _ = stmt.Exec(m.streamID, m.point.At, m.point.Health,
|
|
m.point.BitrateMbps, m.point.PlaylistAgeS, m.point.Viewers, m.point.Bucket)
|
|
}
|
|
_ = stmt.Close()
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
requeue()
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ListEvents returns a stream's timeline, newest first.
|
|
func (s *Store) ListEvents(streamID int64, limit int, kind, since string) ([]StreamEvent, error) {
|
|
if limit <= 0 || limit > 1000 {
|
|
limit = 200
|
|
}
|
|
q := `SELECT id,stream_id,at,kind,severity,actor,message,detail_json
|
|
FROM stream_events WHERE stream_id = ?`
|
|
args := []any{streamID}
|
|
if k := strings.TrimSpace(kind); k != "" {
|
|
// Accept a comma-separated kind filter.
|
|
kinds := strings.Split(k, ",")
|
|
ph := make([]string, 0, len(kinds))
|
|
for _, one := range kinds {
|
|
if one = strings.TrimSpace(one); one != "" {
|
|
ph = append(ph, "?")
|
|
args = append(args, one)
|
|
}
|
|
}
|
|
if len(ph) > 0 {
|
|
q += ` AND kind IN (` + strings.Join(ph, ",") + `)`
|
|
}
|
|
}
|
|
if sv := strings.TrimSpace(since); sv != "" {
|
|
q += ` AND at >= ?`
|
|
args = append(args, sv)
|
|
}
|
|
q += ` ORDER BY id DESC LIMIT ?`
|
|
args = append(args, limit)
|
|
return s.queryEvents(q, args...)
|
|
}
|
|
|
|
// RecentEvents returns the newest events across every stream, for the
|
|
// dashboard's activity feed.
|
|
func (s *Store) RecentEvents(limit int) ([]StreamEvent, error) {
|
|
if limit <= 0 || limit > 500 {
|
|
limit = 50
|
|
}
|
|
return s.queryEvents(`
|
|
SELECT e.id, e.stream_id, e.at, e.kind, e.severity, e.actor, e.message, e.detail_json, s.name
|
|
FROM stream_events e LEFT JOIN streams s ON s.id = e.stream_id
|
|
ORDER BY e.id DESC LIMIT ?`, limit)
|
|
}
|
|
|
|
func (s *Store) queryEvents(q string, args ...any) ([]StreamEvent, error) {
|
|
rows, err := s.DB.Query(q, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
cols, err := rows.Columns()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
withName := len(cols) > 8
|
|
out := []StreamEvent{}
|
|
for rows.Next() {
|
|
var e StreamEvent
|
|
var detail string
|
|
var name *string
|
|
dest := []any{&e.ID, &e.StreamID, &e.At, &e.Kind, &e.Severity, &e.Actor, &e.Message, &detail}
|
|
if withName {
|
|
dest = append(dest, &name)
|
|
}
|
|
if err := rows.Scan(dest...); err != nil {
|
|
return nil, err
|
|
}
|
|
if detail != "" && json.Valid([]byte(detail)) {
|
|
e.Detail = json.RawMessage(detail)
|
|
}
|
|
if name != nil {
|
|
e.StreamName = *name
|
|
}
|
|
out = append(out, e)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// ListMetrics returns samples for a stream within the window, oldest first.
|
|
func (s *Store) ListMetrics(streamID int64, window time.Duration) ([]MetricPoint, error) {
|
|
if window <= 0 {
|
|
window = time.Hour
|
|
}
|
|
cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
|
|
rows, err := s.DB.Query(`
|
|
SELECT at,health,bitrate_mbps,playlist_age_s,viewers,bucket
|
|
FROM stream_metrics WHERE stream_id = ? AND at >= ?
|
|
ORDER BY at ASC`, streamID, cutoff)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []MetricPoint{}
|
|
for rows.Next() {
|
|
var p MetricPoint
|
|
if err := rows.Scan(&p.At, &p.Health, &p.BitrateMbps, &p.PlaylistAgeS, &p.Viewers, &p.Bucket); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, p)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// UptimeRatio is the fraction of samples in the window where the stream was
|
|
// healthy. Returns -1 when there is nothing to judge from.
|
|
func (s *Store) UptimeRatio(streamID int64, window time.Duration) (float64, error) {
|
|
if window <= 0 {
|
|
window = 24 * time.Hour
|
|
}
|
|
cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
|
|
var total, ok int
|
|
err := s.DB.QueryRow(`
|
|
SELECT COUNT(*), COALESCE(SUM(CASE WHEN health = 'ok' THEN 1 ELSE 0 END),0)
|
|
FROM stream_metrics WHERE stream_id = ? AND at >= ?`, streamID, cutoff).Scan(&total, &ok)
|
|
if err != nil {
|
|
return -1, err
|
|
}
|
|
if total == 0 {
|
|
return -1, nil
|
|
}
|
|
return float64(ok) / float64(total), nil
|
|
}
|
|
|
|
// RollupMetrics collapses raw samples older than RawMetricWindow into
|
|
// one-minute averages, then drops rollups and events past their retention.
|
|
// Keeping every 5-second sample for a week would be millions of rows per
|
|
// stream for no benefit at that zoom level.
|
|
func (s *Store) RollupMetrics() error {
|
|
rawCutoff := time.Now().UTC().Add(-RawMetricWindow).Format(time.RFC3339)
|
|
tx, err := s.DB.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// SQLite has no date_trunc, but the timestamps are fixed-width RFC3339
|
|
// (…THH:MM:SSZ), so truncating to the minute is a substring.
|
|
if _, err := tx.Exec(`
|
|
INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
|
|
SELECT stream_id,
|
|
substr(at, 1, 17) || '00Z',
|
|
-- the worst health in the minute, so an outage is never averaged away
|
|
CASE WHEN SUM(CASE WHEN health <> 'ok' THEN 1 ELSE 0 END) > 0 THEN 'degraded' ELSE 'ok' END,
|
|
AVG(bitrate_mbps), AVG(playlist_age_s), MAX(viewers), ?
|
|
FROM stream_metrics
|
|
WHERE bucket = 0 AND at < ?
|
|
GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
|
|
_ = tx.Rollback()
|
|
return err
|
|
}
|
|
if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE bucket = 0 AND at < ?`, rawCutoff); err != nil {
|
|
_ = tx.Rollback()
|
|
return err
|
|
}
|
|
rollupCutoff := time.Now().UTC().Add(-RollupRetention).Format(time.RFC3339)
|
|
if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE at < ?`, rollupCutoff); err != nil {
|
|
_ = tx.Rollback()
|
|
return err
|
|
}
|
|
eventCutoff := time.Now().UTC().Add(-EventRetention).Format(time.RFC3339)
|
|
if _, err := tx.Exec(`DELETE FROM stream_events WHERE at < ?`, eventCutoff); err != nil {
|
|
_ = tx.Rollback()
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
// RunHistoryMaintenance flushes buffered history and prunes on a schedule.
|
|
func (s *Store) RunHistoryMaintenance(stop <-chan struct{}) {
|
|
flush := time.NewTicker(5 * time.Second)
|
|
defer flush.Stop()
|
|
prune := time.NewTicker(15 * time.Minute)
|
|
defer prune.Stop()
|
|
for {
|
|
select {
|
|
case <-stop:
|
|
_ = s.FlushHistory()
|
|
return
|
|
case <-flush.C:
|
|
_ = s.FlushHistory()
|
|
case <-prune.C:
|
|
_ = s.RollupMetrics()
|
|
}
|
|
}
|
|
}
|
|
|
|
func truncateStr(s string, n int) string {
|
|
if len(s) <= n {
|
|
return s
|
|
}
|
|
return s[:n]
|
|
}
|