streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
All checks were successful
release / build-and-upload (push) Successful in 7m2s
All checks were successful
release / build-and-upload (push) Successful in 7m2s
Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions. WireGuard netns resolv.conf + missing-deps WARN. Support donations card. Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries, modhost YAML enrich, DRM SetCredentials requires keys.
This commit is contained in:
parent
3ae1dd58b3
commit
a091922efa
34 changed files with 2391 additions and 154 deletions
|
|
@ -363,6 +363,10 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
_ = h.Store.FlushHistory()
|
||||
recent, _ := h.Store.RecentEvents(25)
|
||||
sessions, _ := h.Store.ListRecentSessions(50)
|
||||
if sessions == nil {
|
||||
sessions = []db.StreamSession{}
|
||||
}
|
||||
out := map[string]any{
|
||||
"totals": map[string]any{
|
||||
"streams": len(list),
|
||||
|
|
@ -374,7 +378,8 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
|
|||
"viewers": viewers,
|
||||
"needs_capture": needCapture,
|
||||
},
|
||||
"recent_events": recent,
|
||||
"recent_events": recent,
|
||||
"recent_sessions": sessions,
|
||||
}
|
||||
if h.Scheduler != nil {
|
||||
out["upcoming"] = h.Scheduler.Upcoming(10)
|
||||
|
|
|
|||
|
|
@ -247,7 +247,10 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
|||
if err := s.migrateSchedules(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateEgress()
|
||||
if err := s.migrateEgress(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateSessions()
|
||||
}
|
||||
|
||||
func now() string {
|
||||
|
|
@ -791,7 +794,16 @@ func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
|
|||
if mpd == "" {
|
||||
return Stream{}, fmt.Errorf("mpd required")
|
||||
}
|
||||
_, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
|
||||
st, err := s.GetStream(id)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
// Encrypted streams must receive usable KID:KEY lines — MPD alone leaves
|
||||
// the packager rainbow-decrypting forever.
|
||||
if st.DRMRequired && !ValidKeyPairs(key) {
|
||||
return Stream{}, fmt.Errorf("key required for DRM stream %q (got mpd but no valid KID:KEY)", st.Name)
|
||||
}
|
||||
_, err = s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
|
||||
mpd, key, now(), id)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
|
|
|
|||
|
|
@ -408,6 +408,13 @@ GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
|
|||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
sessionCutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
|
||||
if _, err := tx.Exec(`
|
||||
DELETE FROM stream_sessions
|
||||
WHERE ended_at <> '' AND ended_at < ?`, sessionCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
|
|
|
|||
211
apps/streamd/internal/db/sessions.go
Normal file
211
apps/streamd/internal/db/sessions.go
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Session end reasons recorded when a run closes.
|
||||
const (
|
||||
SessionStopped = "stopped"
|
||||
SessionNREExit = "nre_exit"
|
||||
SessionOrphaned = "orphaned"
|
||||
SessionTimeout = "timeout"
|
||||
)
|
||||
|
||||
// SessionRetention is how long closed run history is kept.
|
||||
const SessionRetention = 90 * 24 * time.Hour
|
||||
|
||||
// StreamSession is one media worker run: start → stop/crash with a duration.
|
||||
type StreamSession struct {
|
||||
ID int64 `json:"id"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
StreamTitle string `json:"stream_title,omitempty"`
|
||||
StartedAt string `json:"started_at"`
|
||||
EndedAt string `json:"ended_at,omitempty"`
|
||||
DurationS float64 `json:"duration_s"`
|
||||
EndReason string `json:"end_reason,omitempty"`
|
||||
HealthAtEnd string `json:"health_at_end,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Store) migrateSessions() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS stream_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
started_at TEXT NOT NULL,
|
||||
ended_at TEXT NOT NULL DEFAULT '',
|
||||
duration_s REAL NOT NULL DEFAULT 0,
|
||||
end_reason TEXT NOT NULL DEFAULT '',
|
||||
health_at_end TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_stream_started ON stream_sessions(stream_id, started_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_ended ON stream_sessions(ended_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_open ON stream_sessions(stream_id, ended_at);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// OpenSession records a new run for streamID. Any previously open row for the
|
||||
// same stream is closed as orphaned (e.g. process crash without a clean stop).
|
||||
func (s *Store) OpenSession(streamID int64) (int64, error) {
|
||||
if streamID == 0 {
|
||||
return 0, fmt.Errorf("stream id required")
|
||||
}
|
||||
_ = s.CloseOpenSessions(streamID, SessionOrphaned, "stopped")
|
||||
started := now()
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO stream_sessions(stream_id, started_at)
|
||||
VALUES(?, ?)`, streamID, started)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// CloseSession ends one open session by id. Already-closed rows are a no-op.
|
||||
func (s *Store) CloseSession(id int64, reason, healthAtEnd string) error {
|
||||
if id == 0 {
|
||||
return nil
|
||||
}
|
||||
var started string
|
||||
var ended string
|
||||
err := s.DB.QueryRow(`SELECT started_at, ended_at FROM stream_sessions WHERE id=?`, id).
|
||||
Scan(&started, &ended)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ended != "" {
|
||||
return nil
|
||||
}
|
||||
endedAt := now()
|
||||
dur := durationSeconds(started, endedAt)
|
||||
if reason == "" {
|
||||
reason = SessionStopped
|
||||
}
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE stream_sessions
|
||||
SET ended_at=?, duration_s=?, end_reason=?, health_at_end=?
|
||||
WHERE id=? AND ended_at=''`,
|
||||
endedAt, dur, reason, healthAtEnd, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// CloseOpenSessions ends every open session for a stream.
|
||||
func (s *Store) CloseOpenSessions(streamID int64, reason, healthAtEnd string) error {
|
||||
if streamID == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT id FROM stream_sessions WHERE stream_id=? AND ended_at=''`, streamID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := s.CloseSession(id, reason, healthAtEnd); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListRecentSessions returns the newest closed runs across all streams.
|
||||
func (s *Store) ListRecentSessions(limit int) ([]StreamSession, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
|
||||
ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
|
||||
FROM stream_sessions ss
|
||||
LEFT JOIN streams st ON st.id = ss.stream_id
|
||||
WHERE ss.ended_at <> ''
|
||||
ORDER BY ss.ended_at DESC, ss.id DESC
|
||||
LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StreamSession
|
||||
for rows.Next() {
|
||||
var ss StreamSession
|
||||
if err := rows.Scan(
|
||||
&ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
|
||||
&ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ss)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListStreamSessions returns recent closed runs for one stream.
|
||||
func (s *Store) ListStreamSessions(streamID int64, limit int) ([]StreamSession, error) {
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
|
||||
ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
|
||||
FROM stream_sessions ss
|
||||
LEFT JOIN streams st ON st.id = ss.stream_id
|
||||
WHERE ss.stream_id=? AND ss.ended_at <> ''
|
||||
ORDER BY ss.ended_at DESC, ss.id DESC
|
||||
LIMIT ?`, streamID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StreamSession
|
||||
for rows.Next() {
|
||||
var ss StreamSession
|
||||
if err := rows.Scan(
|
||||
&ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
|
||||
&ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, ss)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// PruneSessions drops closed sessions older than SessionRetention.
|
||||
func (s *Store) PruneSessions() error {
|
||||
cutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
|
||||
_, err := s.DB.Exec(`
|
||||
DELETE FROM stream_sessions
|
||||
WHERE ended_at <> '' AND ended_at < ?`, cutoff)
|
||||
return err
|
||||
}
|
||||
|
||||
func durationSeconds(startedAt, endedAt string) float64 {
|
||||
start, err1 := time.Parse(time.RFC3339, startedAt)
|
||||
end, err2 := time.Parse(time.RFC3339, endedAt)
|
||||
if err1 != nil || err2 != nil {
|
||||
return 0
|
||||
}
|
||||
d := end.Sub(start).Seconds()
|
||||
if d < 0 {
|
||||
return 0
|
||||
}
|
||||
return d
|
||||
}
|
||||
114
apps/streamd/internal/db/sessions_test.go
Normal file
114
apps/streamd/internal/db/sessions_test.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestStreamSessionsOpenCloseList(t *testing.T) {
|
||||
store, err := Open(filepath.Join(t.TempDir(), "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
st, err := store.CreateStream(CreateStream{
|
||||
Name: "bbc1", Title: "BBC One", MPD: "https://example.test/a.mpd",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
id1, err := store.OpenSession(st.ID)
|
||||
if err != nil || id1 == 0 {
|
||||
t.Fatalf("OpenSession: id=%d err=%v", id1, err)
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if err := store.CloseSession(id1, SessionStopped, "stopped"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Second open should orphan-close nothing (already closed) and create a new row.
|
||||
id2, err := store.OpenSession(st.ID)
|
||||
if err != nil || id2 == 0 || id2 == id1 {
|
||||
t.Fatalf("second OpenSession: id=%d (first=%d) err=%v", id2, id1, err)
|
||||
}
|
||||
if err := store.CloseSession(id2, SessionNREExit, "down"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Idempotent close.
|
||||
if err := store.CloseSession(id2, SessionStopped, "stopped"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
recent, err := store.ListRecentSessions(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recent) != 2 {
|
||||
t.Fatalf("recent len=%d want 2", len(recent))
|
||||
}
|
||||
// Newest ended first.
|
||||
if recent[0].ID != id2 || recent[0].EndReason != SessionNREExit {
|
||||
t.Fatalf("newest = %+v", recent[0])
|
||||
}
|
||||
if recent[1].ID != id1 || recent[1].EndReason != SessionStopped {
|
||||
t.Fatalf("older = %+v", recent[1])
|
||||
}
|
||||
if recent[0].StreamName != "bbc1" || recent[0].DurationS < 0 {
|
||||
t.Fatalf("row fields: %+v", recent[0])
|
||||
}
|
||||
|
||||
per, err := store.ListStreamSessions(st.ID, 5)
|
||||
if err != nil || len(per) != 2 {
|
||||
t.Fatalf("ListStreamSessions: len=%d err=%v", len(per), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenSessionClosesOrphan(t *testing.T) {
|
||||
store, err := Open(filepath.Join(t.TempDir(), "data"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
st, err := store.CreateStream(CreateStream{
|
||||
Name: "rte1", MPD: "https://example.test/b.mpd",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
orphan, err := store.OpenSession(st.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := store.OpenSession(st.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next == orphan {
|
||||
t.Fatal("expected a new session id")
|
||||
}
|
||||
|
||||
var ended, reason string
|
||||
if err := store.DB.QueryRow(
|
||||
`SELECT ended_at, end_reason FROM stream_sessions WHERE id=?`, orphan,
|
||||
).Scan(&ended, &reason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ended == "" || reason != SessionOrphaned {
|
||||
t.Fatalf("orphan close: ended=%q reason=%q", ended, reason)
|
||||
}
|
||||
|
||||
_ = store.CloseSession(next, SessionStopped, "stopped")
|
||||
recent, err := store.ListRecentSessions(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recent) != 2 {
|
||||
t.Fatalf("want 2 closed sessions, got %d", len(recent))
|
||||
}
|
||||
}
|
||||
|
|
@ -55,6 +55,23 @@ func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Ma
|
|||
}
|
||||
}
|
||||
|
||||
// WarnMissingDeps logs once when WireGuard host tools are absent. Safe to call
|
||||
// on every platform; non-Linux hosts skip the check.
|
||||
func (m *Manager) WarnMissingDeps() {
|
||||
if runtime.GOOS != "linux" {
|
||||
return
|
||||
}
|
||||
for _, bin := range []string{"ip", "wg"} {
|
||||
if _, err := exec.LookPath(bin); err != nil {
|
||||
m.logger().Warn("egress: tool missing from PATH (WireGuard profiles need it)",
|
||||
"bin", bin)
|
||||
}
|
||||
}
|
||||
if _, err := m.findSocksBin(); err != nil {
|
||||
m.logger().Warn("egress: microsocks or gost missing from PATH (WireGuard profiles need a SOCKS forwarder in the netns)")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) logger() *slog.Logger {
|
||||
if m.Log != nil {
|
||||
return m.Log
|
||||
|
|
|
|||
|
|
@ -77,6 +77,13 @@ func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
|
|||
return err
|
||||
}
|
||||
}
|
||||
// DNS inside the netns: host /etc/resolv.conf often points at
|
||||
// 127.0.0.53 (systemd-resolved), which is unreachable from the ns.
|
||||
// ip netns exec bind-mounts /etc/netns/<name>/resolv.conf over /etc/resolv.conf.
|
||||
if err := writeNetnsResolv(nsName); err != nil {
|
||||
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
|
||||
return err
|
||||
}
|
||||
// Loopback inside ns.
|
||||
_ = nsExec("ip", "link", "set", "lo", "up")
|
||||
|
||||
|
|
@ -221,6 +228,26 @@ func (m *Manager) teardownWireGuard(name string, _ int64) error {
|
|||
runQuiet("ip", "link", "del", wgDev) // if still in init ns
|
||||
runQuiet("ip", "netns", "del", nsName)
|
||||
_ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf"))
|
||||
_ = os.RemoveAll(filepath.Join("/etc/netns", nsName))
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeNetnsResolv installs public resolvers for processes inside the netns
|
||||
// (microsocks, curl probe). Without this, SOCKS5 hostname connects fail with
|
||||
// error 0x01 when the host uses systemd-resolved's 127.0.0.53 stub.
|
||||
func writeNetnsResolv(nsName string) error {
|
||||
dir := filepath.Join("/etc/netns", nsName)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return fmt.Errorf("netns resolv dir: %w", err)
|
||||
}
|
||||
body := "# streamd egress — public DNS (host 127.0.0.53 is unreachable in netns)\n" +
|
||||
"nameserver 1.1.1.1\n" +
|
||||
"nameserver 1.0.0.1\n" +
|
||||
"nameserver 8.8.8.8\n"
|
||||
path := filepath.Join(dir, "resolv.conf")
|
||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
||||
return fmt.Errorf("netns resolv.conf: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -247,16 +274,29 @@ func hostVethName(name string) string {
|
|||
|
||||
func probeEgressIP(nsName string) string {
|
||||
// Best-effort: ask a public echo over the ns default route.
|
||||
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||
"curl", "-4", "-fsS", "--max-time", "5", "https://ifconfig.me/ip")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
cmd = exec.Command("ip", "netns", "exec", nsName,
|
||||
"wget", "-qO-", "--timeout=5", "https://ifconfig.me/ip")
|
||||
out, err = cmd.Output()
|
||||
for _, url := range []string{
|
||||
"https://api.ipify.org",
|
||||
"https://ifconfig.me/ip",
|
||||
"https://1.1.1.1/cdn-cgi/trace", // fallback parse below if needed
|
||||
} {
|
||||
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||
"curl", "-4", "-fsS", "--max-time", "5", url)
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
continue
|
||||
}
|
||||
s := strings.TrimSpace(string(out))
|
||||
if strings.Contains(url, "cdn-cgi/trace") {
|
||||
for _, line := range strings.Split(s, "\n") {
|
||||
if strings.HasPrefix(line, "ip=") {
|
||||
return strings.TrimPrefix(line, "ip=")
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if s != "" && !strings.Contains(s, " ") {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
return ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ type streamProc struct {
|
|||
nre *exec.Cmd
|
||||
ffmpeg *exec.Cmd
|
||||
started time.Time
|
||||
sessionID int64 // stream_sessions row opened when NRE starts
|
||||
workDir string
|
||||
wwwDir string
|
||||
tsPath string
|
||||
|
|
@ -337,17 +338,19 @@ func (m *Media) Start(id int64) error {
|
|||
}
|
||||
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
|
||||
|
||||
sessionID, _ := m.Store.OpenSession(id)
|
||||
sp := &streamProc{
|
||||
id: id,
|
||||
name: st.Name,
|
||||
nre: nreCmd,
|
||||
started: time.Now(),
|
||||
workDir: workDir,
|
||||
wwwDir: wwwDir,
|
||||
tsPath: tsPath,
|
||||
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
|
||||
nreLog: nreLog,
|
||||
mpdProxy: mpdProxy,
|
||||
id: id,
|
||||
name: st.Name,
|
||||
nre: nreCmd,
|
||||
started: time.Now(),
|
||||
sessionID: sessionID,
|
||||
workDir: workDir,
|
||||
wwwDir: wwwDir,
|
||||
tsPath: tsPath,
|
||||
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
|
||||
nreLog: nreLog,
|
||||
mpdProxy: mpdProxy,
|
||||
|
||||
variantSpecs: variantSpecs,
|
||||
outputSpecs: outputSpecs,
|
||||
|
|
@ -438,6 +441,7 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
|
|||
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
|
||||
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
|
||||
})
|
||||
m.closeSession(sp, db.SessionNREExit, "down")
|
||||
m.cleanupProc(sp.id)
|
||||
return
|
||||
}
|
||||
|
|
@ -589,9 +593,11 @@ func (m *Media) Stop(id int64) error {
|
|||
if st.Name != "" {
|
||||
name = st.Name
|
||||
}
|
||||
_ = m.Store.CloseOpenSessions(id, db.SessionStopped, "stopped")
|
||||
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"})
|
||||
return nil
|
||||
}
|
||||
m.closeSession(sp, db.SessionStopped, "stopped")
|
||||
m.stopAllVariants(sp)
|
||||
nrePID, ffPID := 0, 0
|
||||
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
|
||||
|
|
@ -624,6 +630,15 @@ func (m *Media) Stop(id int64) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// closeSession ends the open stream_sessions row for this process, if any.
|
||||
func (m *Media) closeSession(sp *streamProc, reason, health string) {
|
||||
if sp == nil || sp.sessionID == 0 {
|
||||
return
|
||||
}
|
||||
_ = m.Store.CloseSession(sp.sessionID, reason, health)
|
||||
sp.sessionID = 0
|
||||
}
|
||||
|
||||
func (m *Media) Restart(id int64) error {
|
||||
m.Log.Info("hard restart", "stream_id", id)
|
||||
_ = m.Stop(id)
|
||||
|
|
@ -702,6 +717,7 @@ func (m *Media) refreshHealth(id int64) {
|
|||
Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
|
||||
})
|
||||
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
|
||||
m.closeSession(sp, db.SessionNREExit, "down")
|
||||
m.report(sp, "down")
|
||||
m.cleanupProc(id)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export const state = {
|
|||
agents: [],
|
||||
deps: null,
|
||||
uptimeS: 0,
|
||||
refreshedAt: 0,
|
||||
connected: false,
|
||||
lastError: "",
|
||||
};
|
||||
|
|
@ -57,6 +58,7 @@ export async function refresh(reason = "poll") {
|
|||
state.uptimeS = health.uptime_s || 0;
|
||||
if (health.deps) state.deps = health.deps;
|
||||
}
|
||||
state.refreshedAt = Date.now();
|
||||
state.lastError = "";
|
||||
} catch (err) {
|
||||
state.lastError = err.message || String(err);
|
||||
|
|
|
|||
|
|
@ -1,15 +1,26 @@
|
|||
// Dashboard: the headline numbers, what is scheduled next, and recent events.
|
||||
|
||||
import { el, pill, fmtRelative, fmtDateTime, setText, reconcile } from "../util.js";
|
||||
import {
|
||||
el, pill, fmtRelative, fmtDateTime, fmtSeconds, setText, reconcile, copyText,
|
||||
} from "../util.js";
|
||||
import { state, subscribe, refresh } from "../store.js";
|
||||
import { timeline } from "../components.js";
|
||||
|
||||
const DONATIONS = [
|
||||
{ coin: "ETH", addr: "0xa6314ce4deaa8329abba301802e3f511b3fa80a6" },
|
||||
{ coin: "LTC", addr: "ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6" },
|
||||
{ coin: "BTC", addr: "bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha" },
|
||||
];
|
||||
|
||||
export function dashboard(root) {
|
||||
const alarmTiles = el("div.tiles");
|
||||
const trafficTiles = el("div.tiles");
|
||||
const upcomingBody = el("tbody");
|
||||
const feed = el("div");
|
||||
const attention = el("div.stack");
|
||||
const uptimeBody = el("tbody");
|
||||
const sessionsBody = el("tbody");
|
||||
const supportBody = el("div.stack");
|
||||
|
||||
root.append(el("div.stack",
|
||||
el("div.tile-band",
|
||||
|
|
@ -24,6 +35,38 @@ export function dashboard(root) {
|
|||
el("div.card-head", el("h2", { text: "Needs attention" })),
|
||||
attention,
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: "Live uptimes" }),
|
||||
el("span.spacer"),
|
||||
el("a", { href: "#/streams", text: "All streams" }),
|
||||
),
|
||||
el("div.table-wrap",
|
||||
el("table",
|
||||
el("thead", el("tr",
|
||||
el("th", { text: "Stream" }),
|
||||
el("th", { text: "Health" }),
|
||||
el("th", { text: "Uptime" }),
|
||||
)),
|
||||
uptimeBody,
|
||||
),
|
||||
),
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head", el("h2", { text: "Recent runs" })),
|
||||
el("div.table-wrap",
|
||||
el("table",
|
||||
el("thead", el("tr",
|
||||
el("th", { text: "Stream" }),
|
||||
el("th", { text: "Started" }),
|
||||
el("th", { text: "Ended" }),
|
||||
el("th", { text: "Duration" }),
|
||||
el("th", { text: "Reason" }),
|
||||
)),
|
||||
sessionsBody,
|
||||
),
|
||||
),
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head",
|
||||
el("h2", { text: "Coming up" }),
|
||||
|
|
@ -46,8 +89,36 @@ export function dashboard(root) {
|
|||
el("div.card-head", el("h2", { text: "Recent activity" })),
|
||||
feed,
|
||||
),
|
||||
el("div.card",
|
||||
el("div.card-head", el("h2", { text: "Support the project" })),
|
||||
el("p.sub", {
|
||||
text: "If Streamd saves you time, donations keep development going.",
|
||||
}),
|
||||
supportBody,
|
||||
),
|
||||
));
|
||||
|
||||
supportBody.replaceChildren(...DONATIONS.map((d) =>
|
||||
el("div.row",
|
||||
el("span.pill", { text: d.coin }),
|
||||
el("code.mono", { text: d.addr }),
|
||||
el("span.spacer"),
|
||||
el("button.tiny.ghost", {
|
||||
type: "button",
|
||||
text: "Copy",
|
||||
onclick: (ev) => copyText(d.addr, d.coin + " address", ev.currentTarget),
|
||||
}),
|
||||
),
|
||||
));
|
||||
|
||||
function liveUptimeSeconds(s) {
|
||||
const health = s.health || "";
|
||||
if (health !== "ok" && health !== "starting") return null;
|
||||
const base = Number(s.uptime_s) || 0;
|
||||
const fetched = state.refreshedAt || Date.now();
|
||||
return base + Math.max(0, (Date.now() - fetched) / 1000);
|
||||
}
|
||||
|
||||
function paint() {
|
||||
const t = (state.overview && state.overview.totals) || {};
|
||||
const streams = state.streams || [];
|
||||
|
|
@ -126,6 +197,75 @@ export function dashboard(root) {
|
|||
);
|
||||
}
|
||||
|
||||
// Live uptimes: prefer enabled streams; fall back to all if none enabled.
|
||||
const uptimeRows = (() => {
|
||||
const enabled = streams.filter((s) => s.enabled);
|
||||
return (enabled.length ? enabled : streams).slice().sort((a, b) =>
|
||||
String(a.title || a.name).localeCompare(String(b.title || b.name)));
|
||||
})();
|
||||
if (!uptimeRows.length) {
|
||||
reconcile(uptimeBody, [{ id: "none" }], (x) => x.id,
|
||||
() => el("tr", el("td.empty", { colspan: "3", text: "No streams yet." })), () => {});
|
||||
} else {
|
||||
reconcile(uptimeBody, uptimeRows, (s) => s.id,
|
||||
() => el("tr",
|
||||
el("td.who"),
|
||||
el("td.health"),
|
||||
el("td.uptime.mono"),
|
||||
),
|
||||
(tr, s) => {
|
||||
const who = tr.querySelector(".who");
|
||||
who.replaceChildren(el("a", {
|
||||
href: `#/stream/${s.id}`, text: s.title || s.name,
|
||||
}));
|
||||
tr.querySelector(".health").replaceChildren(pill(s.health || "stopped"));
|
||||
const live = liveUptimeSeconds(s);
|
||||
setText(tr.querySelector(".uptime"),
|
||||
live == null ? "—" : fmtSeconds(live));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const sessions = (state.overview && state.overview.recent_sessions) || [];
|
||||
if (!sessions.length) {
|
||||
reconcile(sessionsBody, [{ id: "none" }], (x) => x.id,
|
||||
() => el("tr", el("td.empty", {
|
||||
colspan: "5",
|
||||
text: "No completed runs yet — start a stream to begin history.",
|
||||
})), () => {});
|
||||
} else {
|
||||
reconcile(sessionsBody, sessions, (s) => s.id,
|
||||
() => el("tr",
|
||||
el("td.who"),
|
||||
el("td.started"),
|
||||
el("td.ended"),
|
||||
el("td.dur.mono"),
|
||||
el("td.reason"),
|
||||
),
|
||||
(tr, s) => {
|
||||
const who = tr.querySelector(".who");
|
||||
who.replaceChildren(el("a", {
|
||||
href: `#/stream/${s.stream_id}`,
|
||||
text: s.stream_title || s.stream_name || `#${s.stream_id}`,
|
||||
}));
|
||||
const started = tr.querySelector(".started");
|
||||
started.replaceChildren(
|
||||
el("div", { text: fmtRelative(s.started_at) }),
|
||||
el("div.sub", { text: fmtDateTime(s.started_at) }),
|
||||
);
|
||||
const ended = tr.querySelector(".ended");
|
||||
ended.replaceChildren(
|
||||
el("div", { text: fmtRelative(s.ended_at) }),
|
||||
el("div.sub", { text: fmtDateTime(s.ended_at) }),
|
||||
);
|
||||
setText(tr.querySelector(".dur"), fmtSeconds(s.duration_s));
|
||||
tr.querySelector(".reason").replaceChildren(
|
||||
pill(s.end_reason || s.health_at_end || "—"),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const upcoming = (state.overview && state.overview.upcoming) || [];
|
||||
if (!upcoming.length) {
|
||||
reconcile(upcomingBody, [{ id: "none" }], (x) => x.id,
|
||||
|
|
@ -160,8 +300,8 @@ export function dashboard(root) {
|
|||
const off = subscribe(paint);
|
||||
paint();
|
||||
refresh("dashboard");
|
||||
// Keep the relative times honest without a full refetch.
|
||||
const tick = setInterval(paint, 30000);
|
||||
// Keep relative times and live uptimes honest without a full refetch.
|
||||
const tick = setInterval(paint, 1000);
|
||||
return () => {
|
||||
off();
|
||||
clearInterval(tick);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue