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
|
|
@ -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)
|
||||
|
|
|
|||
177
apps/agent/agentcmd/daemon.go
Normal file
177
apps/agent/agentcmd/daemon.go
Normal 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")
|
||||
}
|
||||
37
apps/agent/agentcmd/daemon_unix.go
Normal file
37
apps/agent/agentcmd/daemon_unix.go
Normal 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)
|
||||
}
|
||||
46
apps/agent/agentcmd/daemon_windows.go
Normal file
46
apps/agent/agentcmd/daemon_windows.go
Normal 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)
|
||||
}
|
||||
282
apps/agent/agentcmd/update.go
Normal file
282
apps/agent/agentcmd/update.go
Normal 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))
|
||||
}
|
||||
}
|
||||
21
apps/agent/agentcmd/update_unix.go
Normal file
21
apps/agent/agentcmd/update_unix.go
Normal 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
|
||||
}
|
||||
125
apps/agent/agentcmd/update_windows.go
Normal file
125
apps/agent/agentcmd/update_windows.go
Normal 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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue