Streamd v0.2.0: rename, modules panel, stable/beta channels
All checks were successful
release / build-and-upload (push) Successful in 7m5s
All checks were successful
release / build-and-upload (push) Successful in 7m5s
- Rename product/host binary to streamd (drm compat copy still shipped) - Go module path streamd; STREAMD_* env aliases; agent UA streamd-agent - Panel Modules store + agent pull sync (modstore / modsync) - Rolling stable + beta download tags; README/docs channel curl blocks - Release notes in docs/releases/v0.2.0.md attached by Forgejo Actions
This commit is contained in:
parent
066e018749
commit
da8e1123ec
140 changed files with 2949 additions and 851 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# agent
|
||||
|
||||
Always-on credentials refresher, hosted by the single binary as `drm agent`.
|
||||
Always-on credentials refresher, hosted by the single binary as `streamd agent`.
|
||||
|
||||
```text
|
||||
apps/agent/
|
||||
|
|
@ -26,30 +26,33 @@ expire by themselves if the agent dies.
|
|||
|
||||
```bash
|
||||
# terminal 1 — control plane
|
||||
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
|
||||
# terminal 2 — agent (operator API key from streamd Settings → API keys)
|
||||
export STREAMD_API_KEY=ndk_…
|
||||
# or legacy: export STREAMD_TOKEN=…
|
||||
./bin/drm agent run --config apps/agent/agent.yaml
|
||||
./bin/streamd agent run --config apps/agent/agent.yaml
|
||||
```
|
||||
|
||||
```bash
|
||||
./bin/drm agent status
|
||||
./bin/drm agent devices
|
||||
./bin/drm agent enqueue --stream tg4-ioi --reason manual
|
||||
./bin/drm agent cancel --job 3
|
||||
./bin/streamd agent status
|
||||
./bin/streamd agent devices
|
||||
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
|
||||
./bin/streamd agent cancel --job 3
|
||||
```
|
||||
|
||||
App modules are discovered under `modules/`. The agent drives whichever module a
|
||||
stream names and contains no provider logic.
|
||||
With `sync_modules: true` (default in the sample config), the agent **pulls**
|
||||
provider modules from the streamd Modules page into `<data_dir>/modules/`. You do
|
||||
not need a hand-maintained `modules/` tree on each agent host. The agent drives
|
||||
whichever module a stream names and contains no provider logic.
|
||||
|
||||
## Config
|
||||
|
||||
`agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
|
||||
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`.
|
||||
`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
|
||||
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`.
|
||||
|
||||
Create the key in the streamd dashboard (role **operator**). The legacy shared
|
||||
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
|
||||
|
|
@ -59,10 +62,10 @@ Create the key in the streamd dashboard (role **operator**). The legacy shared
|
|||
## Build
|
||||
|
||||
```bash
|
||||
go -C apps/cli build -o ../../bin/drm .
|
||||
go -C apps/cli build -o ../../bin/streamd .
|
||||
|
||||
# cross-compile
|
||||
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
|
||||
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
|
||||
```
|
||||
|
||||
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
||||
|
|
|
|||
|
|
@ -14,10 +14,11 @@ workers: 1 # concurrent ADB jobs
|
|||
max_attempts: 5
|
||||
capture_wait_sec: 180
|
||||
devices: [] # empty = all adb "device" serials; never installs apps
|
||||
# Push local modules/<name>/module.yaml to streamd when missing or SHA differs.
|
||||
# Pull modules from the streamd panel into the local cache (package.zip + yaml).
|
||||
sync_modules: true
|
||||
# modules_dir: modules # optional override (default: repo modules/)
|
||||
# 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:
|
||||
|
|
|
|||
|
|
@ -12,14 +12,15 @@ import (
|
|||
"syscall"
|
||||
"text/tabwriter"
|
||||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/config"
|
||||
"drmdecryption/apps/agent/internal/device"
|
||||
"drmdecryption/apps/agent/internal/modsync"
|
||||
"drmdecryption/apps/agent/internal/poller"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
"drmdecryption/apps/agent/internal/worker"
|
||||
"drmdecryption/apps/agent/internal/wsclient"
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/config"
|
||||
"streamd/apps/agent/internal/device"
|
||||
"streamd/apps/agent/internal/modsync"
|
||||
"streamd/apps/agent/internal/poller"
|
||||
"streamd/apps/agent/internal/queue"
|
||||
"streamd/apps/agent/internal/worker"
|
||||
"streamd/apps/agent/internal/wsclient"
|
||||
"streamd/modhost"
|
||||
)
|
||||
|
||||
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
||||
|
|
@ -137,15 +138,25 @@ func runCmd(sub string, args []string) {
|
|||
}
|
||||
go p.Loop(stop)
|
||||
|
||||
// Prefer the panel-synced modules cache for capture jobs.
|
||||
if cfg.ModulesDir != "" {
|
||||
if err := modhost.SetModulesDir(cfg.ModulesDir); err != nil {
|
||||
log.Fatalf("modules dir: %v", err)
|
||||
}
|
||||
log.Printf("modules dir %s", cfg.ModulesDir)
|
||||
}
|
||||
|
||||
var ms *modsync.Syncer
|
||||
if cfg.SyncModules {
|
||||
ms := &modsync.Syncer{
|
||||
ms = &modsync.Syncer{
|
||||
API: api,
|
||||
ModulesDir: cfg.ModulesDir,
|
||||
Interval: cfg.ModulesSyncInterval(),
|
||||
Prune: cfg.ModulesPrune,
|
||||
Log: log.Default(),
|
||||
}
|
||||
go ms.Loop(stop)
|
||||
log.Printf("modules sync enabled interval=%s", cfg.ModulesSyncInterval())
|
||||
log.Printf("modules pull sync enabled interval=%s dir=%s", cfg.ModulesSyncInterval(), cfg.ModulesDir)
|
||||
}
|
||||
|
||||
ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default())
|
||||
|
|
@ -171,6 +182,16 @@ func runCmd(sub string, args []string) {
|
|||
}
|
||||
}()
|
||||
}
|
||||
ws.OnModulesChanged = func(name, reason string) {
|
||||
if ms == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
if err := ms.Once(); err != nil {
|
||||
log.Printf("modules sync after change to %s: %v", name, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
go ws.Loop()
|
||||
|
||||
for i := 0; i < cfg.Workers; i++ {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
module drmdecryption/apps/agent
|
||||
module streamd/apps/agent
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
drmdecryption v0.0.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.34.5
|
||||
streamd v0.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
|
@ -15,11 +15,10 @@ require (
|
|||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
)
|
||||
|
||||
replace drmdecryption => ../pkg
|
||||
replace streamd => ../pkg
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
|
|
@ -14,8 +12,6 @@ github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdh
|
|||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
|
||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
|
@ -23,8 +19,6 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
|||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
|
@ -180,9 +181,13 @@ func (c *Client) PostEvent(streamID int64, kind, message string, detail map[stri
|
|||
|
||||
// ModuleInfo is one modules/<name>/ entry from GET /api/modules.
|
||||
type ModuleInfo struct {
|
||||
Name string `json:"name"`
|
||||
HasYAML bool `json:"has_yaml"`
|
||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||
Name string `json:"name"`
|
||||
HasYAML bool `json:"has_yaml"`
|
||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||
HasPackage bool `json:"has_package"`
|
||||
PackageSHA256 string `json:"package_sha256,omitempty"`
|
||||
Arches []string `json:"arches,omitempty"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) ListModules() ([]ModuleInfo, error) {
|
||||
|
|
@ -199,30 +204,64 @@ func (c *Client) ListModules() ([]ModuleInfo, error) {
|
|||
return wrap.Modules, nil
|
||||
}
|
||||
|
||||
// PutModuleYAML uploads raw module.yaml bytes for name (Content-Type text/yaml).
|
||||
func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error {
|
||||
req, err := http.NewRequest(http.MethodPut, c.BaseURL+"/api/modules/"+name, bytes.NewReader(yamlBytes))
|
||||
// GetModuleYAML downloads raw module.yaml bytes for name.
|
||||
func (c *Client) GetModuleYAML(name string) ([]byte, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.setHeaders(req)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
if resp.StatusCode >= 300 {
|
||||
return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// DownloadModulePackage writes the module zip to destPath.
|
||||
func (c *Client) DownloadModulePackage(name, destPath string) error {
|
||||
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/yaml")
|
||||
c.setHeaders(req)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode >= 300 {
|
||||
return c.statusError(http.MethodPut, "/api/modules/"+name, resp, body)
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
|
||||
}
|
||||
return nil
|
||||
tmp := destPath + ".partial"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20))
|
||||
closeErr := f.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return closeErr
|
||||
}
|
||||
_ = os.Remove(destPath)
|
||||
return os.Rename(tmp, destPath)
|
||||
}
|
||||
|
||||
func (c *Client) setHeaders(req *http.Request) {
|
||||
ua := c.UserAgent
|
||||
if ua == "" {
|
||||
ua = "drm-agent/" + Version
|
||||
ua = "streamd-agent/" + Version
|
||||
}
|
||||
req.Header.Set("User-Agent", ua)
|
||||
if c.Token != "" {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import (
|
|||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"drmdecryption/repo"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
|
@ -27,10 +27,11 @@ type Config struct {
|
|||
WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch)
|
||||
UserAgent string `yaml:"user_agent"`
|
||||
AgentID string `yaml:"agent_id"`
|
||||
// SyncModules pushes local modules/<name>/module.yaml to streamd when missing/stale.
|
||||
// SyncModules pulls modules from streamd into the local cache when missing/stale.
|
||||
SyncModules bool `yaml:"sync_modules"`
|
||||
ModulesDir string `yaml:"modules_dir"` // empty = repo modules/
|
||||
ModulesDir string `yaml:"modules_dir"` // empty = <data_dir>/modules
|
||||
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
|
||||
ModulesPrune bool `yaml:"modules_prune"` // remove local modules absent from panel
|
||||
// OnDemandPriority lets a capture that streamd pushed — a viewer waking
|
||||
// an on-demand stream, or a scheduled event about to start — jump ahead
|
||||
// of routine refreshes in the queue.
|
||||
|
|
@ -124,7 +125,9 @@ func applyDefaults(cfg Config, root string) Config {
|
|||
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
||||
cfg.WVD = filepath.Join(root, cfg.WVD)
|
||||
}
|
||||
if cfg.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) {
|
||||
if cfg.ModulesDir == "" {
|
||||
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
|
||||
} else if !filepath.IsAbs(cfg.ModulesDir) {
|
||||
cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
|
||||
}
|
||||
if cfg.ModulesSyncIntervalSec <= 0 {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"fmt"
|
||||
"sync"
|
||||
|
||||
"drmdecryption/adb"
|
||||
"streamd/adb"
|
||||
)
|
||||
|
||||
// Pool tracks free/busy ADB devices. Never installs apps.
|
||||
|
|
|
|||
|
|
@ -1,26 +1,32 @@
|
|||
// Package modsync pushes local modules/<name>/module.yaml to streamd
|
||||
// when the remote copy is missing or the SHA-256 differs.
|
||||
// Package modsync pulls provider modules from streamd into a local cache.
|
||||
// The panel is the source of truth: agents download package.zip when the
|
||||
// package hash changes, and module.yaml alone when only YAML changed.
|
||||
package modsync
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
// Syncer compares local module.yaml files to streamd and PUTs updates.
|
||||
// Syncer keeps the local modules cache aligned with streamd.
|
||||
type Syncer struct {
|
||||
API *client.Client
|
||||
ModulesDir string // empty = modhost.ModulesDir(repo.Root())
|
||||
ModulesDir string // empty = <data_dir>/modules resolved by caller, or modhost default
|
||||
Interval time.Duration
|
||||
Prune bool // remove local modules absent from the panel
|
||||
Log *log.Logger
|
||||
}
|
||||
|
||||
|
|
@ -31,15 +37,10 @@ func (s *Syncer) modulesDir() string {
|
|||
return modhost.ModulesDir(repo.Root())
|
||||
}
|
||||
|
||||
// Once uploads every local module.yaml that is missing or stale on streamd.
|
||||
// Once pulls every remote module that is missing or stale locally.
|
||||
func (s *Syncer) Once() error {
|
||||
dir := s.modulesDir()
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
s.logf("modules sync: no local dir %s", dir)
|
||||
return nil
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -47,42 +48,139 @@ func (s *Syncer) Once() error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byName := make(map[string]client.ModuleInfo, len(remote))
|
||||
seen := map[string]struct{}{}
|
||||
for _, m := range remote {
|
||||
byName[m.Name] = m
|
||||
seen[m.Name] = struct{}{}
|
||||
if err := s.syncOne(dir, m); err != nil {
|
||||
s.logf("modules sync: %s: %v", m.Name, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if s.Prune {
|
||||
s.pruneLocal(dir, seen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Syncer) syncOne(dir string, m client.ModuleInfo) error {
|
||||
modDir := filepath.Join(dir, m.Name)
|
||||
localPkg := localSHA(filepath.Join(modDir, "package.sha256"))
|
||||
localYAML := ""
|
||||
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
|
||||
sum := sha256.Sum256(raw)
|
||||
localYAML = hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
needPackage := m.HasPackage && (localPkg == "" || !strings.EqualFold(localPkg, m.PackageSHA256))
|
||||
needYAML := m.HasYAML && (localYAML == "" || !strings.EqualFold(localYAML, m.YAMLSHA256))
|
||||
|
||||
if !needPackage && !needYAML {
|
||||
return nil
|
||||
}
|
||||
|
||||
if needPackage {
|
||||
if !m.HasPackage {
|
||||
return fmt.Errorf("panel has no package.zip")
|
||||
}
|
||||
if err := s.pullPackage(modDir, m); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logf("modules sync: pulled package %s", m.Name)
|
||||
// Package extract includes yaml; refresh localYAML check.
|
||||
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
|
||||
sum := sha256.Sum256(raw)
|
||||
localYAML = hex.EncodeToString(sum[:])
|
||||
needYAML = m.HasYAML && !strings.EqualFold(localYAML, m.YAMLSHA256)
|
||||
} else {
|
||||
needYAML = m.HasYAML
|
||||
}
|
||||
}
|
||||
|
||||
if needYAML {
|
||||
raw, err := s.API.GetModuleYAML(m.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(modDir, "module.yaml"), raw, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logf("modules sync: updated yaml %s", m.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Syncer) pullPackage(modDir string, m client.ModuleInfo) error {
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
zipPath := filepath.Join(modDir, "package.zip")
|
||||
if err := s.API.DownloadModulePackage(m.Name, zipPath); err != nil {
|
||||
return err
|
||||
}
|
||||
sum, err := fileSHA256(zipPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.PackageSHA256 != "" && !strings.EqualFold(sum, m.PackageSHA256) {
|
||||
return fmt.Errorf("package sha mismatch: got %s want %s", sum, m.PackageSHA256)
|
||||
}
|
||||
|
||||
extractDir := filepath.Join(modDir, ".extract-tmp")
|
||||
_ = os.RemoveAll(extractDir)
|
||||
if err := os.MkdirAll(extractDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(extractDir)
|
||||
|
||||
if err := unzipSafe(zipPath, extractDir); err != nil {
|
||||
return err
|
||||
}
|
||||
// Flatten a single top-level folder (bbc/...) into extractDir root.
|
||||
if err := flattenSingleRoot(extractDir); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := promoteHostBinary(extractDir, m.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Move extracted contents into modDir (keep package.zip + sha sidecar).
|
||||
ents, err := os.ReadDir(extractDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range ents {
|
||||
src := filepath.Join(extractDir, e.Name())
|
||||
dst := filepath.Join(modDir, e.Name())
|
||||
_ = os.RemoveAll(dst)
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return atomicWrite(filepath.Join(modDir, "package.sha256"), []byte(sum+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func (s *Syncer) pruneLocal(dir string, keep map[string]struct{}) {
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, e := range ents {
|
||||
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
name := e.Name()
|
||||
yamlPath := filepath.Join(dir, name, "module.yaml")
|
||||
raw, err := os.ReadFile(yamlPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
s.logf("modules sync: read %s: %v", yamlPath, err)
|
||||
if _, ok := keep[e.Name()]; ok {
|
||||
continue
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
localSHA := hex.EncodeToString(sum[:])
|
||||
rm, ok := byName[name]
|
||||
if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
|
||||
path := filepath.Join(dir, e.Name())
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
s.logf("modules sync: prune %s: %v", e.Name(), err)
|
||||
continue
|
||||
}
|
||||
if err := s.API.PutModuleYAML(name, raw); err != nil {
|
||||
s.logf("modules sync: PUT %s: %v", name, err)
|
||||
continue
|
||||
}
|
||||
if !ok || !rm.HasYAML {
|
||||
s.logf("modules sync: uploaded %s (new)", name)
|
||||
} else {
|
||||
s.logf("modules sync: updated %s", name)
|
||||
}
|
||||
s.logf("modules sync: pruned %s", e.Name())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Loop runs Once immediately, then on Interval until stop closes.
|
||||
|
|
@ -119,3 +217,161 @@ func (s *Syncer) logf(format string, args ...any) {
|
|||
}
|
||||
log.Printf(format, args...)
|
||||
}
|
||||
|
||||
func localSHA(path string) string {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func fileSHA256(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func atomicWrite(path string, data []byte, mode os.FileMode) error {
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unzipSafe(zipPath, destDir string) error {
|
||||
r, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer r.Close()
|
||||
absDest, err := filepath.Abs(destDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range r.File {
|
||||
name := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
name = strings.TrimPrefix(name, "./")
|
||||
if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(name, "..") {
|
||||
return fmt.Errorf("zip slip: %s", f.Name)
|
||||
}
|
||||
target := filepath.Join(destDir, filepath.FromSlash(name))
|
||||
absTarget, err := filepath.Abs(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, err := filepath.Rel(absDest, absTarget)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return fmt.Errorf("zip slip: %s", f.Name)
|
||||
}
|
||||
if f.FileInfo().IsDir() || strings.HasSuffix(name, "/") {
|
||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := os.FileMode(0o644)
|
||||
if f.Mode()&0o111 != 0 {
|
||||
mode = 0o755
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
|
||||
if err != nil {
|
||||
_ = rc.Close()
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(out, rc)
|
||||
_ = out.Close()
|
||||
_ = rc.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func flattenSingleRoot(dir string) error {
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var dirs []os.DirEntry
|
||||
var files []os.DirEntry
|
||||
for _, e := range ents {
|
||||
if strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
if e.IsDir() {
|
||||
dirs = append(dirs, e)
|
||||
} else {
|
||||
files = append(files, e)
|
||||
}
|
||||
}
|
||||
if len(files) > 0 || len(dirs) != 1 {
|
||||
return nil
|
||||
}
|
||||
root := filepath.Join(dir, dirs[0].Name())
|
||||
inner, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range inner {
|
||||
src := filepath.Join(root, e.Name())
|
||||
dst := filepath.Join(dir, e.Name())
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.RemoveAll(root)
|
||||
}
|
||||
|
||||
func promoteHostBinary(modDir, name string) error {
|
||||
want := name
|
||||
if runtime.GOOS == "windows" {
|
||||
want += ".exe"
|
||||
}
|
||||
dest := filepath.Join(modDir, ".bin", want)
|
||||
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
|
||||
return nil
|
||||
}
|
||||
src := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH, want)
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return nil // soft: host arch may be missing
|
||||
}
|
||||
defer in.Close()
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(out, in)
|
||||
closeErr := out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
|
|
|||
154
apps/agent/internal/modsync/sync_test.go
Normal file
154
apps/agent/internal/modsync/sync_test.go
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
package modsync
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
)
|
||||
|
||||
func TestPullPackageThenYAMLOnly(t *testing.T) {
|
||||
arch := runtime.GOOS + "-" + runtime.GOARCH
|
||||
binName := "demo"
|
||||
if runtime.GOOS == "windows" {
|
||||
binName += ".exe"
|
||||
}
|
||||
zip1 := mustZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: a\n"),
|
||||
".bin/" + arch + "/" + binName: []byte("bin-v1"),
|
||||
})
|
||||
sum1 := sha256.Sum256(zip1)
|
||||
pkgSHA1 := hex.EncodeToString(sum1[:])
|
||||
yaml1SHA := sha256Hex([]byte("package: a\n"))
|
||||
|
||||
zip2 := mustZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: a\n"),
|
||||
".bin/" + arch + "/" + binName: []byte("bin-v2"),
|
||||
})
|
||||
sum2 := sha256.Sum256(zip2)
|
||||
pkgSHA2 := hex.EncodeToString(sum2[:])
|
||||
|
||||
yamlEdited := []byte("package: a\nchannels: {}\n")
|
||||
yamlEditedSHA := sha256Hex(yamlEdited)
|
||||
|
||||
state := struct {
|
||||
pkg []byte
|
||||
pkgSHA string
|
||||
yaml []byte
|
||||
yamlSHA string
|
||||
}{pkg: zip1, pkgSHA: pkgSHA1, yaml: []byte("package: a\n"), yamlSHA: yaml1SHA}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/modules" && r.Method == http.MethodGet:
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"modules": []map[string]any{{
|
||||
"name": "demo",
|
||||
"has_yaml": true,
|
||||
"yaml_sha256": state.yamlSHA,
|
||||
"has_package": true,
|
||||
"package_sha256": state.pkgSHA,
|
||||
}},
|
||||
})
|
||||
case r.URL.Path == "/api/modules/demo/package":
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(state.pkg)
|
||||
case r.URL.Path == "/api/modules/demo/yaml":
|
||||
w.Header().Set("Content-Type", "text/yaml")
|
||||
_, _ = w.Write(state.yaml)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
api := &client.Client{BaseURL: srv.URL, HTTP: srv.Client()}
|
||||
s := &Syncer{API: api, ModulesDir: dir}
|
||||
|
||||
if err := s.Once(); err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "demo", "module.yaml")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
promoted := filepath.Join(dir, "demo", ".bin", binName)
|
||||
if b, err := os.ReadFile(promoted); err != nil || string(b) != "bin-v1" {
|
||||
t.Fatalf("promoted binary: %v %q", err, b)
|
||||
}
|
||||
|
||||
// YAML-only change on panel.
|
||||
state.yaml = yamlEdited
|
||||
state.yamlSHA = yamlEditedSHA
|
||||
if err := s.Once(); err != nil {
|
||||
t.Fatalf("yaml sync: %v", err)
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(dir, "demo", "module.yaml"))
|
||||
if !bytes.Equal(raw, yamlEdited) {
|
||||
t.Fatalf("yaml not updated: %s", raw)
|
||||
}
|
||||
if b, _ := os.ReadFile(promoted); string(b) != "bin-v1" {
|
||||
t.Fatalf("binary should be unchanged after yaml-only sync, got %q", b)
|
||||
}
|
||||
|
||||
// Package change.
|
||||
state.pkg = zip2
|
||||
state.pkgSHA = pkgSHA2
|
||||
state.yaml = []byte("package: a\n")
|
||||
state.yamlSHA = yaml1SHA
|
||||
if err := s.Once(); err != nil {
|
||||
t.Fatalf("package sync: %v", err)
|
||||
}
|
||||
if b, _ := os.ReadFile(promoted); string(b) != "bin-v2" {
|
||||
t.Fatalf("binary not updated: %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
func mustZip(t *testing.T, files map[string][]byte) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
for name, body := range files {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func sha256Hex(b []byte) string {
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func TestUnzipSlip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
w, _ := zw.Create("../evil")
|
||||
_, _ = w.Write([]byte("x"))
|
||||
_ = zw.Close()
|
||||
zipPath := filepath.Join(dir, "bad.zip")
|
||||
_ = os.WriteFile(zipPath, buf.Bytes(), 0o644)
|
||||
err := unzipSafe(zipPath, filepath.Join(dir, "out"))
|
||||
if err == nil || !strings.Contains(err.Error(), "slip") {
|
||||
t.Fatalf("want zip slip error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -6,8 +6,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/queue"
|
||||
)
|
||||
|
||||
type Poller struct {
|
||||
|
|
|
|||
|
|
@ -7,14 +7,14 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/phonecap"
|
||||
"drmdecryption/repo"
|
||||
"streamd/modhost"
|
||||
"streamd/phonecap"
|
||||
"streamd/repo"
|
||||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/device"
|
||||
"drmdecryption/apps/agent/internal/poller"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/device"
|
||||
"streamd/apps/agent/internal/poller"
|
||||
"streamd/apps/agent/internal/queue"
|
||||
)
|
||||
|
||||
type Worker struct {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/client"
|
||||
)
|
||||
|
||||
// Message is one push from streamd.
|
||||
|
|
@ -42,6 +42,9 @@ type Client struct {
|
|||
// OnStreamChanged is called when a stream was edited, so the agent can
|
||||
// re-poll instead of waiting out its interval.
|
||||
OnStreamChanged func(name, reason string)
|
||||
// OnModulesChanged is called when the panel uploaded/edited/deleted a
|
||||
// module, so the agent can pull without waiting for the sync interval.
|
||||
OnModulesChanged func(name, reason string)
|
||||
|
||||
stop chan struct{}
|
||||
}
|
||||
|
|
@ -111,7 +114,7 @@ func (c *Client) session() error {
|
|||
if c.AgentID != "" {
|
||||
hdr.Set("X-Agent-ID", c.AgentID)
|
||||
}
|
||||
hdr.Set("User-Agent", "drm-agent/"+client.Version)
|
||||
hdr.Set("User-Agent", "streamd-agent/"+client.Version)
|
||||
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
|
||||
conn, resp, err := dialer.Dial(u.String(), hdr)
|
||||
if err != nil {
|
||||
|
|
@ -190,6 +193,11 @@ func (c *Client) handle(msg Message) {
|
|||
if c.OnStreamChanged != nil {
|
||||
c.OnStreamChanged(msg.StreamName, msg.Reason)
|
||||
}
|
||||
case "modules_changed":
|
||||
c.Log.Printf("ws: modules changed module=%s reason=%s", msg.StreamName, msg.Reason)
|
||||
if c.OnModulesChanged != nil {
|
||||
c.OnModulesChanged(msg.StreamName, msg.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue