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

@ -0,0 +1,336 @@
package servecmd
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v3"
"streamd/bootstrap"
)
const (
defaultBind = "127.0.0.1:8083"
defaultLogLevel = "info"
defaultLogFile = "streamd.log"
defaultPIDFile = "streamd.pid"
defaultChannel = "stable"
defaultKeepOld = 10
configFileName = "streamd.yaml"
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
)
// FileConfig is the on-disk streamd.yaml next to the binary.
type FileConfig struct {
Bind string `yaml:"bind,omitempty"`
Data string `yaml:"data,omitempty"`
LogLevel string `yaml:"log_level,omitempty"`
LogFile string `yaml:"log_file,omitempty"`
PIDFile string `yaml:"pid_file,omitempty"`
Channel string `yaml:"channel,omitempty"` // stable | beta
Asset string `yaml:"asset,omitempty"`
KeepOld *int `yaml:"keep_old,omitempty"`
TrustedProxies string `yaml:"trusted_proxies,omitempty"`
AllowedOrigins string `yaml:"allowed_origins,omitempty"`
CookieSecure *bool `yaml:"cookie_secure,omitempty"`
SkipDeps *bool `yaml:"skip_deps,omitempty"`
BinDir string `yaml:"bin_dir,omitempty"`
NRE string `yaml:"nre,omitempty"`
FFmpeg string `yaml:"ffmpeg,omitempty"`
MP4Decrypt string `yaml:"mp4decrypt,omitempty"`
Token string `yaml:"token,omitempty"` // legacy; prefer dashboard keys
SessionTTL string `yaml:"session_ttl,omitempty"`
AuditRetain string `yaml:"audit_retain,omitempty"`
OnDemandWait string `yaml:"ondemand_wait,omitempty"`
CaptureWait string `yaml:"ondemand_capture_wait,omitempty"`
SchedulePreroll string `yaml:"schedule_preroll,omitempty"`
TSFanoutBuffer *int `yaml:"ts_fanout_buffer,omitempty"`
}
// ServeOptions is the fully resolved runtime config for serve run/start/update.
type ServeOptions struct {
InstallRoot string
ConfigPath string // path used or written; may be empty if --config pointed elsewhere missing
Bind string
Data string // absolute after resolve
LogLevel string
LogFile string // absolute
PIDFile string // absolute
Channel string
Asset string
KeepOld int
TrustedProxies string
AllowedOrigins string
CookieSecure bool
SkipDeps bool
BinDir string
NRE string
FFmpeg string
MP4Decrypt string
Token string
AdminUser string
AdminPass string
SessionTTL time.Duration
AuditRetain time.Duration
OnDemandWait time.Duration
CaptureWait time.Duration
SchedulePreroll time.Duration
TSFanoutBuffer int
// FlagSet / write tracking
WroteConfig bool
}
func defaultFileConfig() FileConfig {
keep := defaultKeepOld
cookie := false
skip := false
return FileConfig{
Bind: defaultBind,
Data: filepath.Join(".cache", "streamd"),
LogLevel: defaultLogLevel,
LogFile: defaultLogFile,
PIDFile: defaultPIDFile,
Channel: defaultChannel,
KeepOld: &keep,
CookieSecure: &cookie,
SkipDeps: &skip,
}
}
func installRoot() string {
root, err := bootstrap.InstallRoot()
if err != nil || root == "" {
wd, _ := os.Getwd()
return wd
}
return root
}
// findConfigPath returns the config path to use and whether the file exists.
func findConfigPath(explicit string) (path string, exists bool) {
if strings.TrimSpace(explicit) != "" {
abs, err := filepath.Abs(explicit)
if err != nil {
abs = explicit
}
_, err = os.Stat(abs)
return abs, err == nil
}
if env := strings.TrimSpace(os.Getenv("STREAMD_CONFIG")); env != "" {
abs, err := filepath.Abs(env)
if err != nil {
abs = env
}
_, err = os.Stat(abs)
return abs, err == nil
}
cwd := filepath.Join(".", configFileName)
if st, err := os.Stat(cwd); err == nil && !st.IsDir() {
abs, _ := filepath.Abs(cwd)
return abs, true
}
root := installRoot()
p := filepath.Join(root, configFileName)
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p, true
}
// Default write target: next to the binary.
return p, false
}
func loadFileConfig(path string) (FileConfig, error) {
b, err := os.ReadFile(path)
if err != nil {
return FileConfig{}, err
}
var fc FileConfig
if err := yaml.Unmarshal(b, &fc); err != nil {
return FileConfig{}, fmt.Errorf("%s: %w", path, err)
}
return fc, nil
}
func writeFileConfig(path string, fc FileConfig) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
b, err := yaml.Marshal(&fc)
if err != nil {
return err
}
header := []byte("# streamd.yaml — server settings (auto-written on first serve).\n" +
"# Edit bind/data/channel here; streamd serve start|update reuse this file.\n")
return os.WriteFile(path, append(header, b...), 0o644)
}
func absUnderRoot(root, p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
if filepath.IsAbs(p) {
return p
}
return filepath.Join(root, p)
}
func parseDuration(s string, fallback time.Duration) time.Duration {
s = strings.TrimSpace(s)
if s == "" {
return fallback
}
d, err := time.ParseDuration(s)
if err != nil {
return fallback
}
return d
}
func mergeFileIntoOptions(opt *ServeOptions, fc FileConfig) {
if fc.Bind != "" {
opt.Bind = fc.Bind
}
if fc.Data != "" {
opt.Data = absUnderRoot(opt.InstallRoot, fc.Data)
}
if fc.LogLevel != "" {
opt.LogLevel = fc.LogLevel
}
if fc.LogFile != "" {
opt.LogFile = absUnderRoot(opt.InstallRoot, fc.LogFile)
}
if fc.PIDFile != "" {
opt.PIDFile = absUnderRoot(opt.InstallRoot, fc.PIDFile)
}
if fc.Channel != "" {
opt.Channel = fc.Channel
}
if fc.Asset != "" {
opt.Asset = fc.Asset
}
if fc.KeepOld != nil {
opt.KeepOld = *fc.KeepOld
}
if fc.TrustedProxies != "" {
opt.TrustedProxies = fc.TrustedProxies
}
if fc.AllowedOrigins != "" {
opt.AllowedOrigins = fc.AllowedOrigins
}
if fc.CookieSecure != nil {
opt.CookieSecure = *fc.CookieSecure
}
if fc.SkipDeps != nil {
opt.SkipDeps = *fc.SkipDeps
}
if fc.BinDir != "" {
opt.BinDir = absUnderRoot(opt.InstallRoot, fc.BinDir)
}
if fc.NRE != "" {
opt.NRE = fc.NRE
}
if fc.FFmpeg != "" {
opt.FFmpeg = fc.FFmpeg
}
if fc.MP4Decrypt != "" {
opt.MP4Decrypt = fc.MP4Decrypt
}
if fc.Token != "" {
opt.Token = fc.Token
}
opt.SessionTTL = parseDuration(fc.SessionTTL, opt.SessionTTL)
opt.AuditRetain = parseDuration(fc.AuditRetain, opt.AuditRetain)
opt.OnDemandWait = parseDuration(fc.OnDemandWait, opt.OnDemandWait)
opt.CaptureWait = parseDuration(fc.CaptureWait, opt.CaptureWait)
opt.SchedulePreroll = parseDuration(fc.SchedulePreroll, opt.SchedulePreroll)
if fc.TSFanoutBuffer != nil {
opt.TSFanoutBuffer = *fc.TSFanoutBuffer
}
}
func relOrAbs(root, p string) string {
if p == "" {
return ""
}
if rel, err := filepath.Rel(root, p); err == nil && !strings.HasPrefix(rel, "..") {
return filepath.ToSlash(rel)
}
return p
}
func optionsToFileConfig(opt ServeOptions) FileConfig {
keep := opt.KeepOld
cookie := opt.CookieSecure
skip := opt.SkipDeps
data := relOrAbs(opt.InstallRoot, opt.Data)
if data == "" {
data = filepath.ToSlash(filepath.Join(".cache", "streamd"))
}
logFile := relOrAbs(opt.InstallRoot, opt.LogFile)
if logFile == "" {
logFile = defaultLogFile
}
pidFile := relOrAbs(opt.InstallRoot, opt.PIDFile)
if pidFile == "" {
pidFile = defaultPIDFile
}
fc := FileConfig{
Bind: opt.Bind,
Data: data,
LogLevel: opt.LogLevel,
LogFile: logFile,
PIDFile: pidFile,
Channel: opt.Channel,
Asset: opt.Asset,
KeepOld: &keep,
TrustedProxies: opt.TrustedProxies,
AllowedOrigins: opt.AllowedOrigins,
CookieSecure: &cookie,
SkipDeps: &skip,
}
if opt.BinDir != "" {
fc.BinDir = relOrAbs(opt.InstallRoot, opt.BinDir)
}
return fc
}
// ensureConfigLoaded applies discovered yaml (if any) and optionally writes a
// default file when missing. explicitConfig is the --config value (may be empty).
func ensureConfigLoaded(opt *ServeOptions, explicitConfig string, writeIfMissing bool) error {
opt.InstallRoot = installRoot()
path, exists := findConfigPath(explicitConfig)
opt.ConfigPath = path
if exists {
fc, err := loadFileConfig(path)
if err != nil {
return err
}
mergeFileIntoOptions(opt, fc)
return nil
}
if !writeIfMissing {
return nil
}
// Don't write when user passed --config to a missing path outside install root
// unless it's the default install-root path.
if strings.TrimSpace(explicitConfig) != "" {
abs, _ := filepath.Abs(explicitConfig)
def := filepath.Join(opt.InstallRoot, configFileName)
if abs != def {
return fmt.Errorf("config file not found: %s", abs)
}
path = abs
opt.ConfigPath = path
}
fc := optionsToFileConfig(*opt)
if err := writeFileConfig(path, fc); err != nil {
return err
}
opt.WroteConfig = true
return nil
}

View file

@ -0,0 +1,101 @@
package servecmd
import (
"os"
"path/filepath"
"testing"
)
func TestWriteAndLoadFileConfig(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "streamd.yaml")
keep := 5
cookie := true
fc := FileConfig{
Bind: "0.0.0.0:8083",
Data: ".cache/streamd",
LogLevel: "debug",
LogFile: "streamd.log",
PIDFile: "streamd.pid",
Channel: "beta",
KeepOld: &keep,
CookieSecure: &cookie,
}
if err := writeFileConfig(path, fc); err != nil {
t.Fatal(err)
}
got, err := loadFileConfig(path)
if err != nil {
t.Fatal(err)
}
if got.Bind != "0.0.0.0:8083" || got.Channel != "beta" || got.LogLevel != "debug" {
t.Fatalf("got %+v", got)
}
if got.KeepOld == nil || *got.KeepOld != 5 {
t.Fatalf("keep_old=%v", got.KeepOld)
}
}
func TestMergeRelativePaths(t *testing.T) {
root := t.TempDir()
opt := ServeOptions{InstallRoot: root, Bind: defaultBind, KeepOld: 10}
fc := FileConfig{Data: ".cache/streamd", LogFile: "streamd.log", PIDFile: "streamd.pid", Bind: "0.0.0.0:9"}
mergeFileIntoOptions(&opt, fc)
if opt.Bind != "0.0.0.0:9" {
t.Fatalf("bind=%s", opt.Bind)
}
wantData := filepath.Join(root, ".cache", "streamd")
if opt.Data != wantData {
t.Fatalf("data=%s want %s", opt.Data, wantData)
}
}
func TestEnsureConfigWritesOnce(t *testing.T) {
root := t.TempDir()
// Point InstallRoot via a fake by writing to root/streamd.yaml through ensure
opt := ServeOptions{
InstallRoot: root,
Bind: "0.0.0.0:8083",
Data: filepath.Join(root, ".cache", "streamd"),
LogLevel: "info",
LogFile: filepath.Join(root, "streamd.log"),
PIDFile: filepath.Join(root, "streamd.pid"),
Channel: "stable",
KeepOld: 10,
}
path := filepath.Join(root, configFileName)
if err := writeFileConfig(path, optionsToFileConfig(opt)); err != nil {
t.Fatal(err)
}
// Second ensure should not set WroteConfig when loading existing.
opt2 := baseServeOptions()
opt2.InstallRoot = root
// findConfigPath uses real installRoot(); test loadFileConfig merge instead.
fc, err := loadFileConfig(path)
if err != nil {
t.Fatal(err)
}
mergeFileIntoOptions(&opt2, fc)
if opt2.Bind != "0.0.0.0:8083" {
t.Fatalf("bind=%s", opt2.Bind)
}
// Existing file must not be clobbered by a second write of defaults.
before, _ := os.ReadFile(path)
_ = writeFileConfig(path, optionsToFileConfig(opt2))
after, _ := os.ReadFile(path)
if len(before) == 0 || len(after) == 0 {
t.Fatal("empty config")
}
}
func TestUpdateURL(t *testing.T) {
u := updateURL(releaseBaseURL, "stable", "streamd-linux-amd64")
want := releaseBaseURL + "/stable/streamd-linux-amd64"
if u != want {
t.Fatalf("%s != %s", u, want)
}
u = updateURL(releaseBaseURL, "v0.2.0", "streamd-linux-arm64")
if u != releaseBaseURL+"/v0.2.0/streamd-linux-arm64" {
t.Fatal(u)
}
}

View file

@ -0,0 +1,200 @@
package servecmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
func readPID(pidFile string) (int, error) {
b, err := os.ReadFile(pidFile)
if err != nil {
return 0, err
}
s := strings.TrimSpace(string(b))
if s == "" {
return 0, fmt.Errorf("empty pid file")
}
return strconv.Atoi(s)
}
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 processAlive(pid int) bool {
if pid <= 0 {
return false
}
return signalAlive(pid)
}
func runningPID(opt ServeOptions) (pid int, ok bool) {
pid, err := readPID(opt.PIDFile)
if err != nil {
return 0, false
}
if !processAlive(pid) {
removePID(opt.PIDFile)
return pid, false
}
return pid, true
}
func statusCmd(opt ServeOptions) error {
fmt.Printf("config: %s\n", opt.ConfigPath)
fmt.Printf("bind: %s\n", opt.Bind)
fmt.Printf("data: %s\n", opt.Data)
fmt.Printf("log: %s\n", opt.LogFile)
fmt.Printf("pid: %s\n", opt.PIDFile)
if pid, ok := runningPID(opt); ok {
fmt.Printf("streamd: running pid=%d\n", pid)
return nil
}
fmt.Println("streamd: stopped")
return nil
}
func stopCmd(opt ServeOptions) error {
pid, err := readPID(opt.PIDFile)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("streamd is not running")
return nil
}
return err
}
if !processAlive(pid) {
removePID(opt.PIDFile)
fmt.Println("streamd 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(5 * time.Second)
for time.Now().Before(deadline) {
if !processAlive(pid) {
removePID(opt.PIDFile)
fmt.Printf("streamd stopped (was pid %d)\n", pid)
return nil
}
time.Sleep(200 * time.Millisecond)
}
_ = signalKill(pid)
time.Sleep(200 * time.Millisecond)
removePID(opt.PIDFile)
fmt.Printf("streamd killed (pid %d)\n", pid)
return nil
}
func startCmd(opt ServeOptions) error {
if pid, ok := runningPID(opt); ok {
fmt.Printf("streamd 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
}
args := buildDaemonArgs(opt)
cmd := exec.Command(exe, args...)
if err := os.MkdirAll(filepath.Dir(opt.LogFile), 0o755); err != nil {
return err
}
logF, err := os.OpenFile(opt.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 daemon: %w", err)
}
pid := cmd.Process.Pid
// Release so the child is not tied to this process on Unix.
_ = cmd.Process.Release()
_ = logF.Close()
if err := writePID(opt.PIDFile, pid); err != nil {
return err
}
time.Sleep(400 * time.Millisecond)
if !processAlive(pid) {
removePID(opt.PIDFile)
return fmt.Errorf("daemon exited immediately — see %s", opt.LogFile)
}
fmt.Printf("streamd started pid=%d bind=%s data=%s\n", pid, opt.Bind, opt.Data)
fmt.Printf("logs: %s\n", opt.LogFile)
if opt.WroteConfig {
fmt.Printf("wrote config %s\n", opt.ConfigPath)
}
return nil
}
func restartCmd(opt ServeOptions) error {
_ = stopCmd(opt)
return startCmd(opt)
}
func buildDaemonArgs(opt ServeOptions) []string {
args := []string{"serve", "run", "--daemon-child"}
if opt.ConfigPath != "" {
args = append(args, "--config", opt.ConfigPath)
}
args = append(args,
"--bind", opt.Bind,
"--data", opt.Data,
"--log-level", opt.LogLevel,
)
if opt.BinDir != "" {
args = append(args, "--bin-dir", opt.BinDir)
}
if opt.NRE != "" {
args = append(args, "--nre", opt.NRE)
}
if opt.FFmpeg != "" {
args = append(args, "--ffmpeg", opt.FFmpeg)
}
if opt.MP4Decrypt != "" {
args = append(args, "--mp4decrypt", opt.MP4Decrypt)
}
if opt.SkipDeps {
args = append(args, "--skip-deps")
}
if opt.TrustedProxies != "" {
args = append(args, "--trusted-proxies", opt.TrustedProxies)
}
if opt.AllowedOrigins != "" {
args = append(args, "--allowed-origins", opt.AllowedOrigins)
}
if opt.CookieSecure {
args = append(args, "--cookie-secure")
}
if opt.Token != "" {
args = append(args, "--token", opt.Token)
}
if opt.AdminUser != "" {
args = append(args, "--admin-user", opt.AdminUser)
}
if opt.AdminPass != "" {
args = append(args, "--admin-pass", opt.AdminPass)
}
return args
}

View file

@ -0,0 +1,37 @@
//go:build unix
package servecmd
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 servecmd
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,71 @@
package servecmd
import (
"os"
"path/filepath"
"testing"
)
func TestResolveDataDirFlagWins(t *testing.T) {
t.Setenv("STREAMD_DATA", "")
dir, src := resolveDataDir("/explicit/data")
if dir != "/explicit/data" || src != "flag" {
t.Fatalf("got dir=%q src=%q", dir, src)
}
}
func TestResolveDataDirEnv(t *testing.T) {
t.Setenv("STREAMD_DATA", "/from/env")
dir, src := resolveDataDir("")
if dir != "/from/env" || src != "env" {
t.Fatalf("got dir=%q src=%q", dir, src)
}
}
func TestResolveDataDirExistingCwd(t *testing.T) {
t.Setenv("STREAMD_DATA", "")
tmp := t.TempDir()
old, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
if err := os.Chdir(tmp); err != nil {
t.Fatal(err)
}
want := filepath.Join(".", ".cache", "streamd")
if err := os.MkdirAll(want, 0o755); err != nil {
t.Fatal(err)
}
dir, src := resolveDataDir("")
if src != "cwd" {
t.Fatalf("src=%q want cwd", src)
}
absGot, _ := filepath.Abs(dir)
absWant, _ := filepath.Abs(want)
if absGot != absWant {
t.Fatalf("dir=%q want %q", absGot, absWant)
}
}
func TestResolveDataDirDefaultWhenMissing(t *testing.T) {
t.Setenv("STREAMD_DATA", "")
tmp := t.TempDir()
old, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
if err := os.Chdir(tmp); err != nil {
t.Fatal(err)
}
dir, src := resolveDataDir("")
if src != "default" && src != "install" {
// install may win if the test binary's InstallRoot already has a cache;
// either way we must not invent a random path.
t.Fatalf("src=%q want default or install", src)
}
if filepath.Base(dir) != "streamd" {
t.Fatalf("dir=%q", dir)
}
}

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)

View file

@ -0,0 +1,243 @@
package servecmd
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
type updateFlags struct {
Channel string // stable|beta or empty → config
Tag string
NoRestart bool
Keep int // -1 = use config
}
// 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 updateCmd(opt ServeOptions, uf updateFlags) error {
channel := opt.Channel
if channel == "" {
channel = defaultChannel
}
if uf.Channel != "" {
channel = uf.Channel
}
ref := channel
if uf.Tag != "" {
ref = uf.Tag
}
asset := opt.Asset
if asset == "" {
asset = defaultAssetName()
}
if asset == "" {
return fmt.Errorf("unsupported platform %s/%s — set asset: in streamd.yaml", runtime.GOOS, runtime.GOARCH)
}
keep := opt.KeepOld
if uf.Keep >= 0 {
keep = uf.Keep
}
url := updateURL(releaseBaseURL, ref, asset)
fmt.Printf("streamd update: downloading %s\n", url)
tmp, err := downloadToTemp(opt.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
}
// Prefer replacing the install-root binary named streamd[.exe] when that is
// where operators keep the release asset.
target := exe
wantName := "streamd"
if runtime.GOOS == "windows" {
wantName = "streamd.exe"
}
installBin := filepath.Join(opt.InstallRoot, wantName)
if st, err := os.Stat(installBin); err == nil && !st.IsDir() {
target = installBin
}
if _, ok := runningPID(opt); ok {
fmt.Println("streamd update: stopping running serve…")
if err := stopCmd(opt); err != nil {
return err
}
}
oldDir := filepath.Join(opt.InstallRoot, "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 uf.NoRestart {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
} else {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
}
if err := replaceBinary(target, tmp, archive); err != nil {
if err == errUpdateDeferred {
return err
}
return err
}
fmt.Printf("streamd update: archived previous → %s\n", archive)
fmt.Printf("streamd update: installed %s (%s)\n", target, ref)
pruneOldBinaries(oldDir, keep)
if uf.NoRestart {
fmt.Println("streamd update: done (--no-restart). Start with: streamd serve start")
return nil
}
fmt.Println("streamd update: starting…")
return startCmd(opt)
}
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)
}
// Reject HTML error pages.
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()
if err != nil {
// help may exit 0; some builds exit 2 — accept if output mentions serve.
if !strings.Contains(string(out), "serve") && !strings.Contains(string(out), "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("streamd update: pruned %s\n", filepath.Join(oldDir, n))
}
}

View file

@ -0,0 +1,22 @@
//go:build unix
package servecmd
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 {
// Best-effort rollback.
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %w", err)
}
_ = os.Chmod(target, 0o755)
return nil
}

View file

@ -0,0 +1,123 @@
//go:build windows
package servecmd
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 streamd.exe.new and spawn a helper
// cmd that waits for this PID to exit, then swaps and optionally starts.
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 {
// Fall through to copy-based replace if rename fails (file locked).
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
}
// Self-replace: leave next as target+".new", archive current after exit via helper.
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-update-finish.cmd")
pid := os.Getpid()
startLine := ""
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
startLine = fmt.Sprintf("\"%s\" serve 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("streamd update: scheduled file swap after this process exits")
fmt.Println("streamd update: run `streamd serve start` once the swap finishes (1–2s)")
// Give the helper a moment to spawn, then return so the caller can exit.
time.Sleep(300 * time.Millisecond)
return errUpdateDeferred
}
func escapeCmd(p string) string {
return p // paths used in quotes; avoid extra escaping of %
}
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
}