package modhost import ( "bytes" "encoding/json" "fmt" "os" "os/exec" "strings" ) // prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load // panel-store module.yaml. Module builds that call EffectiveModulesDir (or // ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the // panel module.yaml when describe returns no channels. func prepareModuleCmd(cmd *exec.Cmd) { ov := ModulesDirOverride() if ov == "" { return } cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"), "STREAMD_MODULES_DIR="+ov) } func withoutEnvKeys(env []string, keys ...string) []string { drop := map[string]struct{}{} for _, k := range keys { drop[strings.ToUpper(k)] = struct{}{} } out := make([]string, 0, len(env)) for _, e := range env { key, _, _ := strings.Cut(e, "=") if _, skip := drop[strings.ToUpper(key)]; skip { continue } out = append(out, e) } return out } // Run executes the module binary with args, inheriting stdout/stderr. func Run(bin string, args ...string) error { cmd := exec.Command(bin, args...) prepareModuleCmd(cmd) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin if err := cmd.Run(); err != nil { return fmt.Errorf("%s %s: %w", bin, strings.Join(args, " "), err) } return nil } // RunOutput executes the module binary and returns combined stdout. func RunOutput(bin string, args ...string) (string, error) { cmd := exec.Command(bin, args...) prepareModuleCmd(cmd) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if err := cmd.Run(); err != nil { return stdout.String(), fmt.Errorf("%s %s: %w\n%s", bin, strings.Join(args, " "), err, stderr.String()) } return stdout.String(), nil } // RunDescribe runs `bin describe` and parses JSON. func RunDescribe(bin string) (Describe, error) { out, err := RunOutput(bin, "describe") if err != nil { return Describe{}, err } // Allow log lines before JSON: find first '{'. out = strings.TrimSpace(out) if i := strings.IndexByte(out, '{'); i > 0 { out = out[i:] } var d Describe if err := json.Unmarshal([]byte(out), &d); err != nil { return Describe{}, fmt.Errorf("describe JSON: %w\noutput: %s", err, out) } if d.Protocol != 0 && d.Protocol != ProtocolVersion { return d, fmt.Errorf("module protocol %d unsupported (host wants %d)", d.Protocol, ProtocolVersion) } if d.Protocol == 0 { d.Protocol = ProtocolVersion } return d, nil } // Load builds (if needed) and describes a module by name. func Load(root, name string) (Module, string, Describe, error) { m, err := Find(root, name) if err != nil { return Module{}, "", Describe{}, err } bin, err := EnsureBuilt(m) if err != nil { return m, "", Describe{}, err } d, err := RunDescribe(bin) if err != nil { return m, bin, Describe{}, err } if d.Name == "" { d.Name = m.Name } return m, bin, d, nil }