streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
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:
404errordeveloper 2026-10-10 19:26:39 +02:00
parent 3ae1dd58b3
commit a091922efa
34 changed files with 2391 additions and 154 deletions

View file

@ -28,14 +28,16 @@ expire by themselves if the agent dies.
# terminal 1 — control plane
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
# terminal 2 — agent (operator API key from streamd Settings → API keys)
# terminal 2 — agent in the background (Linux / macOS / Windows)
export STREAMD_API_KEY=ndk_…
# or legacy: export STREAMD_TOKEN=…
./bin/streamd agent run --config apps/agent/agent.yaml
./bin/streamd agent start --config apps/agent/agent.yaml
./bin/streamd agent status --config apps/agent/agent.yaml
# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
# stop / restart: ./bin/streamd agent stop|restart --config …
# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
```
```bash
./bin/streamd agent status
./bin/streamd agent devices
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
./bin/streamd agent cancel --job 3
@ -52,12 +54,18 @@ whichever module a stream names and contains no provider logic.
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`.
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`,
`job_backoff` (default false — exponential delays only when several agents
share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
`keep_old` for `agent start|stop|update`.
Create the key in the streamd dashboard (role **operator**). The legacy shared
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
`wvd` must be set or key fetches fail.
`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
bootstraps `apps/wvkey/` and creates `<install>/.venv` with `pywidevine` using
the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
a hand-made venv.
## Build

View file

@ -19,8 +19,18 @@ sync_modules: true
# modules_dir: # optional; default <data_dir>/modules
# modules_sync_interval_sec: 300
# modules_prune: false # delete local modules absent from the panel
# Required for key fetch. Relative paths resolve from the repo root
# (DRM-Decryption/), not from C:\Users\admin\Programming\.
wvd:
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
# Set true only when several agents share the same streams.
# job_backoff: false
# Background daemon (streamd agent start|stop|update):
# log_file: agent.log
# pid_file: agent.pid
# channel: stable # or beta — used by agent update
# asset: # optional streamd-* override
# keep_old: 10
# Required for key fetch. Relative paths resolve from the install/repo root.
# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
# python: # optional override; default = <root>/.venv/…
wvd: data/device.wvd
# user_agent: "" # optional license-request User-Agent

View file

@ -9,6 +9,7 @@ import (
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"text/tabwriter"
@ -21,6 +22,8 @@ import (
"streamd/apps/agent/internal/worker"
"streamd/apps/agent/internal/wsclient"
"streamd/modhost"
"streamd/repo"
"streamd/wvkey"
)
// Run dispatches an agent subcommand. args[0] is the subcommand name.
@ -36,6 +39,14 @@ func Run(args []string) error {
switch sub {
case "run":
runCmd(sub, rest)
case "start":
return startDaemonCmd(rest)
case "stop":
return stopDaemonCmd(rest)
case "restart":
return restartDaemonCmd(rest)
case "update":
return updateDaemonCmd(rest)
case "status":
statusCmd(sub, rest)
case "devices":
@ -58,8 +69,13 @@ func Usage() {
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
Usage:
agent run [--config apps/agent/agent.yaml]
agent status [--config ...]
agent start [--config agent.yaml] # background (pid + log)
agent stop [--config ...]
agent restart [--config ...]
agent status [--config ...] # process + recent jobs
agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
agent run [--config ...] # foreground (debug)
agent devices [--config ...]
agent enqueue --stream NAME [--reason manual] [--config ...]
agent cancel --job ID [--config ...]
@ -68,6 +84,9 @@ Polls streamd for enabled streams that are down / missing credentials,
enqueues jobs, claims a free phone that already has the app, captures
via MITM, POSTs credentials, then force-stops the app.
Job retries default to immediate (job_backoff: false). Set job_backoff: true
in agent.yaml for exponential delays when several agents share work.
Does not install apps. Does not run NRE/ffmpeg.
`)
}
@ -117,6 +136,18 @@ func runCmd(sub string, args []string) {
"create an operator API key in the streamd dashboard", me.Role)
}
log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
// Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
// once per install root so Windows / Linux / macOS agents all work.
if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
log.Fatalf("widevine helper: %v", err)
} else {
log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
if strings.TrimSpace(cfg.Python) == "" {
cfg.Python = rt.Python
}
}
q := openQueue(cfg)
defer q.Close()
@ -125,6 +156,16 @@ func runCmd(sub string, args []string) {
} else if n > 0 {
log.Printf("re-queued %d stuck running job(s) from previous run", n)
}
if n, err := q.ClearAllBackoffs(); err != nil {
log.Printf("clear backoffs: %v", err)
} else if n > 0 {
log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
}
if cfg.JobBackoffEnabled() {
log.Printf("job_backoff=true (exponential delays after failures)")
} else {
log.Printf("job_backoff=false (retry failed captures immediately)")
}
pool := device.New("", cfg.Devices)
stop := make(chan struct{})
@ -205,6 +246,7 @@ func runCmd(sub string, args []string) {
Python: cfg.Python,
WVD: cfg.WVD,
UserAgent: cfg.UserAgent,
JobBackoff: cfg.JobBackoffEnabled(),
Log: log.Default(),
}
go w.Loop(stop)
@ -225,6 +267,7 @@ func runCmd(sub string, args []string) {
func statusCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args)
printDaemonStatus(cfg)
q := openQueue(cfg)
defer q.Close()
jobs, err := q.ListRecent(40)

View file

@ -0,0 +1,177 @@
package agentcmd
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"streamd/apps/agent/internal/config"
"streamd/repo"
)
func readPID(pidFile string) (int, error) {
b, err := os.ReadFile(pidFile)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(b)))
}
func writePID(pidFile string, pid int) error {
if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
return err
}
return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
}
func removePID(pidFile string) { _ = os.Remove(pidFile) }
func runningPID(cfg config.Config) (int, bool) {
pid, err := readPID(cfg.PIDFile)
if err != nil || pid <= 0 {
return 0, false
}
if !signalAlive(pid) {
removePID(cfg.PIDFile)
return pid, false
}
return pid, true
}
func printDaemonStatus(cfg config.Config) {
fmt.Printf("config: %s\n", cfgPathHint(cfg))
fmt.Printf("pid: %s\n", cfg.PIDFile)
fmt.Printf("log: %s\n", cfg.LogFile)
if pid, ok := runningPID(cfg); ok {
fmt.Printf("agent: running pid=%d\n", pid)
} else {
fmt.Println("agent: stopped")
}
}
func cfgPathHint(cfg config.Config) string {
// Best-effort: show data dir; exact yaml path was already resolved by Load.
return cfg.DataDir
}
func startDaemonCmd(args []string) error {
cfg, cfgFile := loadCfgWithPath("start", args)
if pid, ok := runningPID(cfg); ok {
fmt.Printf("agent already running (pid %d)\n", pid)
return nil
}
exe, err := os.Executable()
if err != nil {
return err
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
runArgs := []string{"agent", "run"}
if cfgFile != "" {
runArgs = append(runArgs, "--config", cfgFile)
}
cmd := exec.Command(exe, runArgs...)
if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
return err
}
logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
cmd.Stdout = logF
cmd.Stderr = logF
cmd.Stdin = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
_ = logF.Close()
return fmt.Errorf("start agent: %w", err)
}
pid := cmd.Process.Pid
_ = cmd.Process.Release()
_ = logF.Close()
if err := writePID(cfg.PIDFile, pid); err != nil {
return err
}
time.Sleep(400 * time.Millisecond)
if !signalAlive(pid) {
removePID(cfg.PIDFile)
return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
}
fmt.Printf("agent started pid=%d\n", pid)
fmt.Printf("logs: %s\n", cfg.LogFile)
return nil
}
func stopDaemonCmd(args []string) error {
cfg, _ := loadCfgWithPath("stop", args)
pid, err := readPID(cfg.PIDFile)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("agent is not running")
return nil
}
return err
}
if !signalAlive(pid) {
removePID(cfg.PIDFile)
fmt.Println("agent is not running (stale pid file removed)")
return nil
}
if err := signalTerminate(pid); err != nil {
return fmt.Errorf("stop pid %d: %w", pid, err)
}
deadline := time.Now().Add(8 * time.Second)
for time.Now().Before(deadline) {
if !signalAlive(pid) {
removePID(cfg.PIDFile)
fmt.Printf("agent stopped (was pid %d)\n", pid)
return nil
}
time.Sleep(200 * time.Millisecond)
}
_ = signalKill(pid)
time.Sleep(200 * time.Millisecond)
removePID(cfg.PIDFile)
fmt.Printf("agent killed (pid %d)\n", pid)
return nil
}
func restartDaemonCmd(args []string) error {
_ = stopDaemonCmd(args)
return startDaemonCmd(args)
}
// loadCfgWithPath returns config and the resolved --config path (may be empty).
func loadCfgWithPath(sub string, args []string) (config.Config, string) {
fs := flag.NewFlagSet(sub, flag.ExitOnError)
cfgPath := fs.String("config", "", "path to agent.yaml")
_ = fs.Parse(args)
path := strings.TrimSpace(*cfgPath)
cfg, err := config.Load(path)
if err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
if path == "" {
// Mirror config.Load default discovery for daemon child argv.
path = defaultConfigPath()
} else if !filepath.IsAbs(path) {
abs, err := filepath.Abs(path)
if err == nil {
path = abs
}
}
return cfg, path
}
// defaultConfigPath matches config.Load("") discovery so the background child
// reopens the same yaml the parent resolved.
func defaultConfigPath() string {
return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
}

View file

@ -0,0 +1,37 @@
//go:build unix
package agentcmd
import (
"os"
"os/exec"
"syscall"
)
func detachProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
}
func signalAlive(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
return false
}
return p.Signal(syscall.Signal(0)) == nil
}
func signalTerminate(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGTERM)
}
func signalKill(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGKILL)
}

View file

@ -0,0 +1,46 @@
//go:build windows
package agentcmd
import (
"os"
"os/exec"
"syscall"
"golang.org/x/sys/windows"
)
func detachProcess(cmd *exec.Cmd) {
// CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
// stdout/stderr still reach the log file opened by the parent.
cmd.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
}
}
func signalAlive(pid int) bool {
// On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return false
}
defer windows.CloseHandle(h)
var code uint32
if err := windows.GetExitCodeProcess(h, &code); err != nil {
return false
}
const stillActive = 259 // STILL_ACTIVE
return code == stillActive
}
func signalTerminate(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Kill()
}
func signalKill(pid int) error {
return signalTerminate(pid)
}

View file

@ -0,0 +1,282 @@
package agentcmd
import (
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"streamd/apps/agent/internal/config"
"streamd/repo"
)
const (
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
defaultChannel = "stable"
)
// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
func defaultAssetName() string {
switch runtime.GOOS {
case "linux":
switch runtime.GOARCH {
case "amd64":
return "streamd-linux-amd64"
case "arm64":
return "streamd-linux-arm64"
}
case "darwin":
switch runtime.GOARCH {
case "amd64":
return "streamd-darwin-amd64"
case "arm64":
return "streamd-darwin-arm64"
}
case "windows":
switch runtime.GOARCH {
case "amd64":
return "streamd-windows-amd64.exe"
case "arm64":
return "streamd-windows-arm64.exe"
}
}
return ""
}
func updateURL(base, ref, asset string) string {
base = strings.TrimRight(base, "/")
return fmt.Sprintf("%s/%s/%s", base, ref, asset)
}
func updateDaemonCmd(args []string) error {
fs := flag.NewFlagSet("update", flag.ExitOnError)
cfgPath := fs.String("config", "", "path to agent.yaml")
beta := fs.Bool("beta", false, "use beta channel")
tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
_ = fs.Parse(args)
path := strings.TrimSpace(*cfgPath)
cfg, err := config.Load(path)
if err != nil {
return err
}
if path == "" {
path = defaultConfigPath()
} else if !filepath.IsAbs(path) {
if abs, err := filepath.Abs(path); err == nil {
path = abs
}
}
channel := cfg.Channel
if channel == "" {
channel = defaultChannel
}
if *beta {
channel = "beta"
}
ref := channel
if strings.TrimSpace(*tag) != "" {
ref = strings.TrimSpace(*tag)
}
asset := cfg.Asset
if asset == "" {
asset = defaultAssetName()
}
if asset == "" {
return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
}
keepN := 10
if cfg.KeepOld != nil {
keepN = *cfg.KeepOld
}
if *keep >= 0 {
keepN = *keep
}
installRoot := repo.Root()
url := updateURL(releaseBaseURL, ref, asset)
fmt.Printf("agent update: downloading %s\n", url)
tmp, err := downloadToTemp(installRoot, url)
if err != nil {
return err
}
defer os.Remove(tmp)
if err := smokeTestBinary(tmp); err != nil {
return err
}
exe, err := os.Executable()
if err != nil {
return err
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
target := exe
wantName := "streamd"
if runtime.GOOS == "windows" {
wantName = "streamd.exe"
}
// Prefer well-known names in the install / Downloads tree.
for _, candidate := range []string{
filepath.Join(installRoot, wantName),
filepath.Join(installRoot, "streamd-windows-amd64.exe"),
filepath.Join(installRoot, "streamd-linux-amd64"),
filepath.Join(installRoot, "bin", wantName),
} {
if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
target = candidate
break
}
}
// If the running exe is already a streamd binary in this tree, prefer it.
if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
if st, err := os.Stat(exe); err == nil && !st.IsDir() {
target = exe
}
}
if _, ok := runningPID(cfg); ok {
fmt.Println("agent update: stopping running agent…")
if err := stopDaemonCmd([]string{"--config", path}); err != nil {
return err
}
}
oldDir := filepath.Join(filepath.Dir(target), "old")
if err := os.MkdirAll(oldDir, 0o755); err != nil {
return err
}
stamp := time.Now().UTC().Format("20060102T150405Z")
archive := filepath.Join(oldDir, "streamd."+stamp)
if runtime.GOOS == "windows" {
archive += ".exe"
}
if _, err := os.Stat(archive); err == nil {
archive += "." + fmt.Sprint(os.Getpid())
}
if *noRestart {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
} else {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
_ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
}
if err := replaceBinary(target, tmp, archive); err != nil {
if err == errUpdateDeferred {
return nil // helper finishes after exit; treat as success for CLI
}
return err
}
fmt.Printf("agent update: archived previous → %s\n", archive)
fmt.Printf("agent update: installed %s (%s)\n", target, ref)
pruneOldBinaries(oldDir, keepN)
if *noRestart {
fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
return nil
}
fmt.Println("agent update: starting…")
return startDaemonCmd([]string{"--config", path})
}
func downloadToTemp(dir, url string) (string, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
f, err := os.CreateTemp(dir, ".streamd-download-*")
if err != nil {
return "", err
}
path := f.Name()
resp, err := http.Get(url)
if err != nil {
_ = f.Close()
_ = os.Remove(path)
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
_ = f.Close()
_ = os.Remove(path)
return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
}
n, err := io.Copy(f, resp.Body)
closeErr := f.Close()
if err != nil {
_ = os.Remove(path)
return "", err
}
if closeErr != nil {
_ = os.Remove(path)
return "", closeErr
}
if n < 1024 {
_ = os.Remove(path)
return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
}
head, _ := os.ReadFile(path)
if len(head) > 32 {
h := strings.ToLower(string(head[:32]))
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
_ = os.Remove(path)
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
}
}
_ = os.Chmod(path, 0o755)
return path, nil
}
func smokeTestBinary(path string) error {
cmd := exec.Command(path, "help")
out, err := cmd.CombinedOutput()
text := string(out)
if err != nil {
if !strings.Contains(text, "serve") && !strings.Contains(text, "agent") && !strings.Contains(text, "streamd") {
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
}
}
return nil
}
func pruneOldBinaries(oldDir string, keep int) {
if keep <= 0 {
return
}
ents, err := os.ReadDir(oldDir)
if err != nil {
return
}
var names []string
for _, e := range ents {
if e.IsDir() {
continue
}
n := e.Name()
if strings.HasPrefix(n, "streamd.") {
names = append(names, n)
}
}
sort.Strings(names)
if len(names) <= keep {
return
}
for _, n := range names[:len(names)-keep] {
_ = os.Remove(filepath.Join(oldDir, n))
fmt.Printf("agent update: pruned %s\n", filepath.Join(oldDir, n))
}
}

View file

@ -0,0 +1,21 @@
//go:build unix
package agentcmd
import (
"fmt"
"os"
)
// replaceBinary moves the live binary to archive, then moves next into place.
func replaceBinary(target, next, archive string) error {
if err := os.Rename(target, archive); err != nil {
return fmt.Errorf("archive current binary: %w", err)
}
if err := os.Rename(next, target); err != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %w", err)
}
_ = os.Chmod(target, 0o755)
return nil
}

View file

@ -0,0 +1,125 @@
//go:build windows
package agentcmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
)
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
// 1. Move target → archive when target is not our own running image.
// 2. If target is us, write next beside as *.new and spawn a helper cmd that
// waits for this PID to exit, then swaps and optionally starts the agent.
func replaceBinary(target, next, archive string) error {
self, _ := os.Executable()
if resolved, err := filepath.EvalSymlinks(self); err == nil {
self = resolved
}
same, _ := sameFile(self, target)
if !same {
if err := os.Rename(target, archive); err != nil {
if err2 := copyFile(target, archive); err2 != nil {
return fmt.Errorf("archive current binary: %v / %w", err, err2)
}
_ = os.Remove(target)
}
if err := os.Rename(next, target); err != nil {
if err2 := copyFile(next, target); err2 != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
return nil
}
newPath := target + ".new"
_ = os.Remove(newPath)
if err := os.Rename(next, newPath); err != nil {
if err2 := copyFile(next, newPath); err2 != nil {
return fmt.Errorf("stage new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
helper := filepath.Join(filepath.Dir(target), "streamd-agent-update-finish.cmd")
pid := os.Getpid()
startLine := ""
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
cfg := os.Getenv("STREAMD_UPDATE_AGENT_CONFIG")
if cfg != "" {
startLine = fmt.Sprintf("\"%s\" agent start --config \"%s\"\r\n", escapeCmd(target), escapeCmd(cfg))
} else {
startLine = fmt.Sprintf("\"%s\" agent start\r\n", escapeCmd(target))
}
}
script := fmt.Sprintf(""+
"@echo off\r\n"+
":wait\r\n"+
"timeout /t 1 /nobreak >nul\r\n"+
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
"if not errorlevel 1 goto wait\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"%s"+
"del \"%%~f0\"\r\n",
pid, pid,
escapeCmd(target), escapeCmd(archive),
escapeCmd(newPath), escapeCmd(target),
startLine,
)
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
return err
}
cmd := exec.Command("cmd.exe", "/C", helper)
cmd.Stdout = nil
cmd.Stderr = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
return fmt.Errorf("start update helper: %w", err)
}
_ = cmd.Process.Release()
fmt.Println("agent update: scheduled file swap after this process exits")
fmt.Println("agent update: agent will restart automatically in 1–2s")
time.Sleep(300 * time.Millisecond)
return errUpdateDeferred
}
func escapeCmd(p string) string {
return p
}
func sameFile(a, b string) (bool, error) {
absA, err := filepath.Abs(a)
if err != nil {
return false, err
}
absB, err := filepath.Abs(b)
if err != nil {
return false, err
}
return filepath.Clean(absA) == filepath.Clean(absB), nil
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
if err != nil {
return err
}
_, copyErr := out.ReadFrom(in)
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}

View file

@ -36,6 +36,16 @@ type Config struct {
// an on-demand stream, or a scheduled event about to start — jump ahead
// of routine refreshes in the queue.
OnDemandPriority *bool `yaml:"ondemand_priority"`
// JobBackoff enables exponential retry delays after a failed capture
// (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP.
// Set job_backoff: true when several agents share the same streams.
JobBackoff *bool `yaml:"job_backoff"`
// Daemon / update (streamd agent start|stop|update)
LogFile string `yaml:"log_file"` // default agent.log next to config / install root
PIDFile string `yaml:"pid_file"` // default agent.pid
Channel string `yaml:"channel"` // stable|beta for agent update
Asset string `yaml:"asset"` // optional streamd-* asset override
KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10)
}
// PushedCapturesArePriority reports whether pushed captures jump the queue.
@ -44,6 +54,12 @@ func (c Config) PushedCapturesArePriority() bool {
return c.OnDemandPriority == nil || *c.OnDemandPriority
}
// JobBackoffEnabled is the exponential multi-agent retry delay.
// Defaults to false so a lone agent retries immediately after a failure.
func (c Config) JobBackoffEnabled() bool {
return c.JobBackoff != nil && *c.JobBackoff
}
func (c Config) PollInterval() time.Duration {
if c.PollIntervalSec <= 0 {
return 30 * time.Second
@ -125,6 +141,9 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
cfg.WVD = filepath.Join(root, cfg.WVD)
}
if cfg.Python != "" && !filepath.IsAbs(cfg.Python) {
cfg.Python = filepath.Join(root, cfg.Python)
}
if cfg.ModulesDir == "" {
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
} else if !filepath.IsAbs(cfg.ModulesDir) {
@ -133,6 +152,25 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.ModulesSyncIntervalSec <= 0 {
cfg.ModulesSyncIntervalSec = 300
}
if cfg.LogFile == "" {
cfg.LogFile = "agent.log"
}
if !filepath.IsAbs(cfg.LogFile) {
cfg.LogFile = filepath.Join(root, cfg.LogFile)
}
if cfg.PIDFile == "" {
cfg.PIDFile = "agent.pid"
}
if !filepath.IsAbs(cfg.PIDFile) {
cfg.PIDFile = filepath.Join(root, cfg.PIDFile)
}
if cfg.Channel == "" {
cfg.Channel = "stable"
}
if cfg.KeepOld == nil {
k := 10
cfg.KeepOld = &k
}
return cfg
}

View file

@ -232,17 +232,18 @@ func (s *Store) MarkOK(id int64) error {
return err
}
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
// MarkFailed increments attempts. Re-queues unless maxed out.
// waitingDevice=true keeps status queued without burning an attempt.
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
// backoff is how long to wait before the job is runnable again (0 = immediate).
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
j, err := s.Get(id)
if err != nil {
return err
}
if waitingDevice {
_, err = s.DB.Exec(`
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
msg, id)
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
msg, now(), id)
return err
}
attempts := j.Attempts + 1
@ -252,9 +253,8 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
attempts, msg, now(), id)
return err
}
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
if backoff > 15*time.Minute {
backoff = 15 * time.Minute
if backoff < 0 {
backoff = 0
}
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
_, err = s.DB.Exec(`
@ -263,6 +263,29 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
return err
}
// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
func ExponentialBackoff(attempts int) time.Duration {
if attempts < 1 {
attempts = 1
}
d := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
if d > 15*time.Minute {
d = 15 * time.Minute
}
return d
}
// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
// after fixing modules, or when job_backoff is disabled).
func (s *Store) ClearAllBackoffs() (int, error) {
res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
func min(a, b int) int {
if a < b {
return a

View file

@ -27,7 +27,10 @@ type Worker struct {
Python string
WVD string
UserAgent string
Log *log.Logger
// JobBackoff enables exponential delays between failed capture attempts.
// When false (default), failed jobs are re-queued immediately.
JobBackoff bool
Log *log.Logger
lastDelayLog time.Time
}
@ -67,13 +70,18 @@ func (w *Worker) tick() {
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
// Config/environment issues — do not burn attempts or multi-minute backoff.
w.logf("job=%d waiting: %v", job.ID, err)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
return
}
w.logf("job=%d failed: %v", job.ID, err)
w.event(job, client.EventCaptureFailed, err.Error(),
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
backoff := time.Duration(0)
if w.JobBackoff {
backoff = queue.ExponentialBackoff(job.Attempts + 1)
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
}
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
return
}
_ = w.Queue.MarkOK(job.ID)
@ -119,8 +127,8 @@ func (w *Worker) runJob(job queue.Job) error {
_ = w.Queue.SetDevice(job.ID, serial)
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
// Short TTL; /ws/agent heartbeats renew while this process is alive.
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
return fmt.Errorf("streamd claim: %w", err)
}
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
@ -140,6 +148,19 @@ func (w *Worker) runJob(job queue.Job) error {
return err
}
needsKeys := true
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
needsKeys = false
}
hasKey := poller.ValidKeyPair(res.Key)
if needsKeys && !hasKey {
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
}
if strings.TrimSpace(res.MPD) == "" {
return fmt.Errorf("refusing to post credentials without mpd")
}
cred := client.Credentials{
MPD: res.MPD,
Key: res.Key,
@ -150,15 +171,25 @@ func (w *Worker) runJob(job queue.Job) error {
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
return fmt.Errorf("post credentials: %w", err)
}
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
// Report what was captured, never the key itself.
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
"device": serial,
"has_key": strings.TrimSpace(res.Key) != "",
"key_valid": poller.ValidKeyPair(res.Key),
"key_valid": hasKey,
})
return nil
}
func trimURL(s string) string {
s = strings.TrimSpace(s)
if len(s) <= 96 {
return s
}
return s[:96] + "…"
}
// event posts a stream event to streamd. A timeline entry is never worth
// failing a capture over, so errors are logged and dropped.
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {