streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes

- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml
- Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix
- Per-stream WireGuard/SOCKS egress profiles + Settings UI
- Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers
- Docs: streamd-server-setup lifecycle and update flow
This commit is contained in:
404errordeveloper 2026-10-10 18:05:51 +02:00
parent da8e1123ec
commit 8fc7e4c0b8
57 changed files with 4031 additions and 257 deletions

View file

@ -19,6 +19,7 @@ import (
"streamd/apps/streamd/internal/auth"
"streamd/apps/streamd/internal/db"
"streamd/apps/streamd/internal/deps"
"streamd/apps/streamd/internal/egress"
"streamd/apps/streamd/internal/hlsgate"
"streamd/apps/streamd/internal/httpx"
"streamd/apps/streamd/internal/modstore"
@ -27,6 +28,7 @@ import (
"streamd/apps/streamd/internal/tsfanout"
"streamd/apps/streamd/internal/ui"
"streamd/apps/streamd/internal/ws"
"streamd/bootstrap"
"streamd/modhost"
)
@ -56,11 +58,30 @@ func Usage() {
fmt.Fprintf(os.Stderr, `streamd — Go control plane for DRM restreams
Usage:
streamd serve [flags]
streamd serve start|stop|restart|status|update|run [flags]
streamd serve [flags] # foreground (same as run)
Lifecycle (uses streamd.yaml next to the binary; written on first run):
streamd serve start # background WebUI
streamd serve stop
streamd serve restart
streamd serve status
streamd serve update # download stable, archive old → ./old/, restart
streamd serve update --beta
streamd serve update --tag v0.2.0
streamd serve update --no-restart
streamd serve run # foreground (debug)
Config:
--config PATH streamd.yaml (default: $STREAMD_CONFIG, ./streamd.yaml,
or <install>/streamd.yaml next to the binary)
serve flags:
--bind listen address (default 127.0.0.1:8083)
--data data dir for sqlite + www + work (default .cache/streamd)
--data data dir for sqlite + www + work
(omit to reuse an existing .cache/streamd under cwd or
next to the binary; else create ./.cache/streamd.
STREAMD_DATA env is an alternate default.)
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
@ -90,61 +111,293 @@ set --trusted-proxies to that proxy. Use --bind 0.0.0.0:8083 only deliberately.
`)
}
// resolveDataDir picks the streamd data directory.
//
// Order when --data is empty:
// 1. $STREAMD_DATA if set
// 2. ./.cache/streamd if that directory already exists
// 3. <install-root>/.cache/streamd if that directory already exists
// (install root = directory of the binary, or its parent when the binary
// lives in bin/)
// 4. otherwise ./.cache/streamd (created on startup)
//
// Returns the path and a short source label for logs (flag|env|cwd|install|default).
func resolveDataDir(flagValue string) (dir, source string) {
if strings.TrimSpace(flagValue) != "" {
return flagValue, "flag"
}
if env := strings.TrimSpace(os.Getenv("STREAMD_DATA")); env != "" {
return env, "env"
}
cwdCandidate := filepath.Join(".", ".cache", "streamd")
if dirExists(cwdCandidate) {
return cwdCandidate, "cwd"
}
if root, err := bootstrap.InstallRoot(); err == nil {
installCandidate := filepath.Join(root, ".cache", "streamd")
if dirExists(installCandidate) {
return installCandidate, "install"
}
}
return cwdCandidate, "default"
}
func dirExists(path string) bool {
st, err := os.Stat(path)
return err == nil && st.IsDir()
}
func serveCmd(args []string) {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
// Loopback by default. This used to be 0.0.0.0, which published the API —
// and before redaction, the Widevine keys — to the whole network.
bind := fs.String("bind", "127.0.0.1:8083", "listen address")
data := fs.String("data", "", "data directory (sqlite, www, work, logs)")
token := fs.String("token", "", "legacy admin API token (default: STREAMD_TOKEN env)")
verb := ""
rest := args
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
switch args[0] {
case "start", "stop", "restart", "status", "update", "run", "help", "-h", "--help":
verb, rest = args[0], args[1:]
}
}
if verb == "help" || verb == "-h" || verb == "--help" {
Usage()
return
}
opt, uf, err := parseServeArgs(verb, rest)
if err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(2)
}
switch verb {
case "start":
if err := startCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "stop":
if err := stopCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "restart":
if err := restartCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "status":
if err := statusCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "update":
if err := updateCmd(opt, uf); err != nil {
if err == errUpdateDeferred {
fmt.Println(err.Error())
os.Exit(0)
}
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
default: // "", "run" — foreground
runServe(opt)
}
}
func baseServeOptions() ServeOptions {
root := installRoot()
return ServeOptions{
InstallRoot: root,
Bind: defaultBind,
LogLevel: defaultLogLevel,
LogFile: absUnderRoot(root, defaultLogFile),
PIDFile: absUnderRoot(root, defaultPIDFile),
Channel: defaultChannel,
KeepOld: defaultKeepOld,
SessionTTL: auth.DefaultSessionTTL,
AuditRetain: 90 * 24 * time.Hour,
OnDemandWait: hlsgate.DefaultWait,
CaptureWait: hlsgate.DefaultCaptureWait,
SchedulePreroll: scheduler.DefaultPreroll,
TSFanoutBuffer: tsfanout.DefaultBufferBytes,
}
}
func parseServeArgs(verb string, args []string) (ServeOptions, updateFlags, error) {
opt := baseServeOptions()
uf := updateFlags{Keep: -1}
fs := flag.NewFlagSet("serve", flag.ContinueOnError)
fs.SetOutput(os.Stderr)
configPath := fs.String("config", "", "path to streamd.yaml")
daemonChild := fs.Bool("daemon-child", false, "internal: spawned by serve start")
bind := fs.String("bind", "", "listen address")
data := fs.String("data", "", "data directory")
token := fs.String("token", "", "legacy admin API token")
nre := fs.String("nre", "", "N_m3u8DL-RE binary")
ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary")
mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary")
binDir := fs.String("bin-dir", "", "directory for media tool binaries (default <repo>/bin)")
binDir := fs.String("bin-dir", "", "directory for media tool binaries")
skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools")
logLevel := fs.String("log-level", "info", "debug | info | warn | error")
logLevel := fs.String("log-level", "", "debug | info | warn | error")
adminUser := fs.String("admin-user", "", "create this admin account on first run")
adminPass := fs.String("admin-pass", "", "password for --admin-user (or STREAMD_ADMIN_PASS)")
sessionTTL := fs.Duration("session-ttl", auth.DefaultSessionTTL, "login lifetime without activity")
adminPass := fs.String("admin-pass", "", "password for --admin-user")
sessionTTL := fs.Duration("session-ttl", 0, "login lifetime without activity")
trustedProxies := fs.String("trusted-proxies", "", "CIDRs allowed to set X-Forwarded-For")
allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins, comma separated")
allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins")
cookieSecure := fs.Bool("cookie-secure", false, "always mark cookies Secure")
auditRetain := fs.Duration("audit-retain", 90*24*time.Hour, "how long to keep audit rows")
tsBuffer := fs.Int("ts-fanout-buffer", tsfanout.DefaultBufferBytes,
"bytes of live MPEG-TS buffered per stream for /live/<name>.ts")
ondemandWait := fs.Duration("ondemand-wait", hlsgate.DefaultWait,
"how long to hold a viewer request while an on-demand stream starts")
ondemandCaptureWait := fs.Duration("ondemand-capture-wait", hlsgate.DefaultCaptureWait,
"as --ondemand-wait, but when credentials must be captured first")
preroll := fs.Duration("schedule-preroll", scheduler.DefaultPreroll,
"how far ahead of a scheduled start to refresh credentials")
_ = fs.Parse(args)
auditRetain := fs.Duration("audit-retain", 0, "how long to keep audit rows")
tsBuffer := fs.Int("ts-fanout-buffer", 0, "live MPEG-TS buffer bytes")
ondemandWait := fs.Duration("ondemand-wait", 0, "on-demand start wait")
ondemandCaptureWait := fs.Duration("ondemand-capture-wait", 0, "on-demand capture wait")
preroll := fs.Duration("schedule-preroll", 0, "schedule credential preroll")
lg := newLogger(*logLevel)
// update-only flags (harmless on other verbs)
beta := fs.Bool("beta", false, "update: use beta channel")
stable := fs.Bool("stable", false, "update: use stable channel")
tag := fs.String("tag", "", "update: pin release tag")
noRestart := fs.Bool("no-restart", false, "update: do not start after replace")
keep := fs.Int("keep", -1, "update: max binaries to keep in old/")
if err := fs.Parse(args); err != nil {
return opt, uf, err
}
visited := map[string]bool{}
fs.Visit(func(f *flag.Flag) { visited[f.Name] = true })
writeMissing := !*daemonChild && (verb == "" || verb == "run" || verb == "start" || verb == "update" || verb == "restart")
if err := ensureConfigLoaded(&opt, *configPath, writeMissing); err != nil {
return opt, uf, err
}
if *bind != "" {
opt.Bind = *bind
}
if *data != "" {
opt.Data = *data
if !filepath.IsAbs(opt.Data) {
opt.Data = absUnderRoot(opt.InstallRoot, opt.Data)
}
} else if opt.Data == "" {
dir, _ := resolveDataDir("")
opt.Data = dir
if !filepath.IsAbs(opt.Data) {
abs, err := filepath.Abs(opt.Data)
if err == nil {
opt.Data = abs
}
}
}
if *logLevel != "" {
opt.LogLevel = *logLevel
}
if *token != "" {
opt.Token = *token
}
if *nre != "" {
opt.NRE = *nre
}
if *ffmpeg != "" {
opt.FFmpeg = *ffmpeg
}
if *mp4decrypt != "" {
opt.MP4Decrypt = *mp4decrypt
}
if *binDir != "" {
opt.BinDir = *binDir
}
if visited["skip-deps"] {
opt.SkipDeps = *skipDeps
}
if *adminUser != "" {
opt.AdminUser = *adminUser
}
if *adminPass != "" {
opt.AdminPass = *adminPass
}
if visited["session-ttl"] {
opt.SessionTTL = *sessionTTL
}
if *trustedProxies != "" {
opt.TrustedProxies = *trustedProxies
}
if *allowedOrigins != "" {
opt.AllowedOrigins = *allowedOrigins
}
if visited["cookie-secure"] {
opt.CookieSecure = *cookieSecure
}
if visited["audit-retain"] {
opt.AuditRetain = *auditRetain
}
if visited["ts-fanout-buffer"] {
opt.TSFanoutBuffer = *tsBuffer
}
if visited["ondemand-wait"] {
opt.OnDemandWait = *ondemandWait
}
if visited["ondemand-capture-wait"] {
opt.CaptureWait = *ondemandCaptureWait
}
if visited["schedule-preroll"] {
opt.SchedulePreroll = *preroll
}
// Persist effective settings when we created the file, or when start/restart
// was given explicit bind/data so the next restart remembers them.
persist := opt.WroteConfig
if (verb == "start" || verb == "restart") && (visited["bind"] || visited["data"] || visited["log-level"]) {
persist = true
}
if persist && opt.ConfigPath != "" {
if err := writeFileConfig(opt.ConfigPath, optionsToFileConfig(opt)); err == nil && !opt.WroteConfig {
opt.WroteConfig = true
}
}
if *beta {
uf.Channel = "beta"
}
if *stable {
uf.Channel = "stable"
}
uf.Tag = strings.TrimSpace(*tag)
uf.NoRestart = *noRestart
uf.Keep = *keep
_ = daemonChild
return opt, uf, nil
}
func runServe(opt ServeOptions) {
lg := newLogger(opt.LogLevel)
slog.SetDefault(lg)
// deps still wants a *log.Logger; bridge it onto the same handler so one
// stream of output stays coherent.
depsLog := slog.NewLogLogger(lg.Handler(), slog.LevelInfo)
dataDir := *data
dataDir := opt.Data
if dataDir == "" {
dataDir = filepath.Join(".", ".cache", "streamd")
var src string
dataDir, src = resolveDataDir("")
if src != "flag" {
lg.Info("using data directory", "data", dataDir, "source", src)
}
}
tok := *token
if opt.WroteConfig {
lg.Info("wrote config", "path", opt.ConfigPath)
}
tok := opt.Token
if tok == "" {
tok = os.Getenv("STREAMD_TOKEN")
}
trust := httpx.Trust{}
if nets, err := httpx.ParseCIDRs(*trustedProxies); err != nil {
if nets, err := httpx.ParseCIDRs(opt.TrustedProxies); err != nil {
lg.Error("invalid --trusted-proxies", "err", err)
os.Exit(2)
} else {
trust.Proxies = nets
}
origins := splitList(*allowedOrigins)
origins := splitList(opt.AllowedOrigins)
for _, sub := range []string{"www", "work", "logs", "modules"} {
for _, sub := range []string{"www", "work", "logs", "modules", "egress"} {
if err := os.MkdirAll(filepath.Join(dataDir, sub), 0o755); err != nil {
lg.Error("create data dir", "err", err)
os.Exit(1)
@ -163,30 +416,35 @@ func serveCmd(args []string) {
lg.Error("init auth tables", "err", err)
os.Exit(1)
}
mw := auth.NewMiddleware(authStore, trust, *cookieSecure)
mw.SessionTTL = *sessionTTL
mw := auth.NewMiddleware(authStore, trust, opt.CookieSecure)
mw.SessionTTL = opt.SessionTTL
authH := auth.NewHandler(authStore, mw, lg)
bootstrapAdmin(lg, authStore, authH, *adminUser, *adminPass)
bootstrapAdmin(lg, authStore, authH, opt.AdminUser, opt.AdminPass)
depStatus, _ := deps.Ensure(deps.Options{
BinDir: *binDir,
SkipDownload: *skipDeps,
BinDir: opt.BinDir,
SkipDownload: opt.SkipDeps,
Log: depsLog,
}, *nre, *ffmpeg, *mp4decrypt)
}, opt.NRE, opt.FFmpeg, opt.MP4Decrypt)
fanout := tsfanout.NewSet(*tsBuffer)
fanout := tsfanout.NewSet(opt.TSFanoutBuffer)
hub := ws.NewHub(store, lg, origins)
eg := egress.New(dataDir, store, lg, "")
eg.StartEnabled()
defer eg.StopAll()
sup := supervisor.NewMedia(supervisor.Options{
Store: store,
DataDir: dataDir,
NRE: depStatus.NRE,
FFmpeg: depStatus.FFmpeg,
MP4Decrypt: depStatus.MP4Decrypt,
Log: lg,
Fanout: fanout,
Notifier: hub,
Store: store,
DataDir: dataDir,
NRE: depStatus.NRE,
FFmpeg: depStatus.FFmpeg,
MP4Decrypt: depStatus.MP4Decrypt,
Log: lg,
Fanout: fanout,
Notifier: hub,
ProxyResolver: eg,
})
defer sup.Close()
@ -198,18 +456,15 @@ func serveCmd(args []string) {
Capture: hub,
Trust: trust,
Log: lg,
Wait: *ondemandWait,
CaptureWait: *ondemandCaptureWait,
Wait: opt.OnDemandWait,
CaptureWait: opt.CaptureWait,
})
// The supervisor records viewer counts in its metrics series, and the
// gate is what knows them.
sup.ViewersFn = gate.ViewersFor
sched := scheduler.New(store, sup, hub, lg, *preroll)
sched := scheduler.New(store, sup, hub, lg, opt.SchedulePreroll)
modulesRoot := filepath.Join(dataDir, "modules")
modStore := modstore.New(modulesRoot)
// Panel-owned modules are the source of truth for /api/apps and describe.
if err := modhost.SetModulesDir(modulesRoot); err != nil {
lg.Error("set modules dir", "err", err)
os.Exit(1)
@ -232,6 +487,7 @@ func serveCmd(args []string) {
Notifier: hub,
Viewers: gate,
Scheduler: sched,
Egress: eg,
Log: lg,
}
@ -239,15 +495,10 @@ func serveCmd(args []string) {
apiH.Mount(mux)
authH.Mount(mux)
hub.Mount(mux)
// The media paths are served by the gate, not a bare FileServer: it wakes
// on-demand streams, counts viewers, sets cache headers per file kind and
// refuses directory listings.
gate.Mount(mux)
mux.Handle("/", ui.Handler())
mux.Handle("/static/", http.StripPrefix("/static/", ui.Static()))
// Order matters: the access log wraps everything so it sees final statuses,
// then CORS and security headers, then principal resolution, then the mux.
var handler http.Handler = mux
handler = mw.Attach(handler)
handler = httpx.SecurityHeaders(trust, handler)
@ -255,15 +506,13 @@ func serveCmd(args []string) {
handler = httpx.AccessLog(lg, trust, handler)
srv := &http.Server{
Addr: *bind,
Addr: opt.Bind,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
// No WriteTimeout: HLS responses, SSE log tails and websockets are all
// long-lived and a write deadline would cut them off.
IdleTimeout: 120 * time.Second,
IdleTimeout: 120 * time.Second,
}
lg.Info("streamd listening", "addr", *bind, "data", dataDir)
lg.Info("streamd listening", "addr", opt.Bind, "data", dataDir)
lg.Info("media tools", "nre", depStatus.NRE, "ffmpeg", depStatus.FFmpeg, "mp4decrypt", depStatus.MP4Decrypt)
if len(trust.Proxies) == 0 {
lg.Info("no --trusted-proxies set: forwarded headers are ignored and client IPs come from the peer address")
@ -271,19 +520,18 @@ func serveCmd(args []string) {
if tok != "" {
lg.Warn("--token / STREAMD_TOKEN is in use as an admin API key; create per-agent keys in the dashboard and drop it")
}
if host, _, err := net.SplitHostPort(*bind); err == nil {
if host, _, err := net.SplitHostPort(opt.Bind); err == nil {
switch strings.ToLower(host) {
case "127.0.0.1", "localhost", "::1":
// Loopback is the safe default.
default:
lg.Warn("listening on a non-loopback address — the dashboard and API are reachable on the network; put a TLS reverse proxy in front, or bind 127.0.0.1",
"bind", *bind)
"bind", opt.Bind)
}
}
stopBG := make(chan struct{})
go hub.RunExpireLoop(stopBG)
go authStore.RunMaintenance(stopBG, *auditRetain)
go authStore.RunMaintenance(stopBG, opt.AuditRetain)
go store.RunHistoryMaintenance(stopBG)
go gate.RunIdleLoop(stopBG)
go sched.Run(stopBG)