285 lines
8.3 KiB
Go
285 lines
8.3 KiB
Go
// Package check implements connection-check mode: it exercises the external
|
|
// dependencies a recording needs — the stream host and the NAS share — and
|
|
// reports pass/fail for each without downloading or transferring anything.
|
|
// Same spirit as `dbt debug`: prove the wiring before starting real work.
|
|
package check
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"m3u8-downloader/pkg/config"
|
|
"m3u8-downloader/pkg/constants"
|
|
"m3u8-downloader/pkg/httpClient"
|
|
"m3u8-downloader/pkg/logging"
|
|
"m3u8-downloader/pkg/media"
|
|
"m3u8-downloader/pkg/nas"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/grafov/m3u8"
|
|
)
|
|
|
|
// playlistTimeout bounds the master playlist fetch. Deliberately short: a
|
|
// stream host that takes longer than this is not usable for live recording.
|
|
const playlistTimeout = 15 * time.Second
|
|
|
|
// Run executes every applicable check and returns a process exit code, 0 only
|
|
// when nothing failed, so the command can gate a scripted recording start.
|
|
func Run(masterURL string) int {
|
|
fmt.Println("Running connection checks...")
|
|
fmt.Println()
|
|
|
|
cfg, err := constants.GetConfig()
|
|
if err != nil {
|
|
reportFail("configuration", nil, err)
|
|
fmt.Println()
|
|
fmt.Println("1 check failed.")
|
|
return 1
|
|
}
|
|
|
|
appLog := logging.MustGetFactory().App
|
|
appLog.Info("connection check starting", "url_provided", masterURL != "")
|
|
|
|
reportPass("configuration", []string{
|
|
"local output: " + cfg.Paths.LocalOutput,
|
|
"process output: " + cfg.Paths.ProcessOutput,
|
|
"log dir: " + cfg.Logging.Dir,
|
|
fmt.Sprintf("nas transfer: %s", enabledLabel(cfg.NAS.EnableTransfer)),
|
|
})
|
|
|
|
failures := 0
|
|
|
|
if masterURL == "" {
|
|
reportSkip("stream playlist", "no -url provided")
|
|
} else if details, err := checkMasterPlaylist(masterURL); err != nil {
|
|
reportFail("stream playlist", details, err)
|
|
appLog.Error("stream playlist check failed", logging.KeyError, err.Error())
|
|
failures++
|
|
} else {
|
|
reportPass("stream playlist", details)
|
|
appLog.Info("stream playlist check passed")
|
|
}
|
|
|
|
if !cfg.NAS.EnableTransfer {
|
|
reportSkip("nas storage", "transfer disabled in configuration")
|
|
} else if details, err := checkNAS(cfg); err != nil {
|
|
reportFail("nas storage", details, err)
|
|
appLog.Error("nas check failed", logging.KeyError, err.Error())
|
|
failures++
|
|
} else {
|
|
reportPass("nas storage", details)
|
|
appLog.Info("nas check passed", "path", cfg.NAS.OutputPath)
|
|
}
|
|
|
|
if failures > 0 {
|
|
fmt.Printf("%d check(s) failed.\n", failures)
|
|
appLog.Error("connection check finished with failures", "failures", failures)
|
|
return 1
|
|
}
|
|
|
|
fmt.Println("All checks passed.")
|
|
appLog.Info("connection check passed")
|
|
return 0
|
|
}
|
|
|
|
// checkMasterPlaylist fetches the master playlist exactly as the downloader
|
|
// would — same headers, same decoder — and summarizes what it found. Details
|
|
// gathered before the failure point are returned alongside the error so a
|
|
// failed check still shows how far it got.
|
|
func checkMasterPlaylist(masterURL string) ([]string, error) {
|
|
parsed, err := url.Parse(masterURL)
|
|
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
|
|
return nil, fmt.Errorf("not a valid absolute URL: %q", masterURL)
|
|
}
|
|
|
|
details := []string{"host: " + parsed.Host}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), playlistTimeout)
|
|
defer cancel()
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, masterURL, nil)
|
|
if err != nil {
|
|
return details, fmt.Errorf("failed to build request: %w", err)
|
|
}
|
|
req.Header.Set("User-Agent", constants.HTTPUserAgent)
|
|
req.Header.Set("Referer", constants.REFERRER)
|
|
|
|
client := &http.Client{Timeout: playlistTimeout}
|
|
start := time.Now()
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return details, fmt.Errorf("request failed: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
details = append(details, fmt.Sprintf("HTTP %d in %s", resp.StatusCode, formatDuration(time.Since(start))))
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return details, httpClient.NewHTTPError(resp.StatusCode, "unexpected status fetching master playlist")
|
|
}
|
|
|
|
playlist, listType, err := m3u8.DecodeFrom(resp.Body, true)
|
|
if err != nil {
|
|
return details, fmt.Errorf("response is not a valid m3u8 playlist: %w", err)
|
|
}
|
|
|
|
switch listType {
|
|
case m3u8.MASTER:
|
|
master, ok := playlist.(*m3u8.MasterPlaylist)
|
|
if !ok {
|
|
return details, fmt.Errorf("decoder returned an unexpected playlist type")
|
|
}
|
|
if len(master.Variants) == 0 {
|
|
return details, fmt.Errorf("master playlist contains no variants")
|
|
}
|
|
details = append(details, fmt.Sprintf("master playlist with %d variant(s):", len(master.Variants)))
|
|
for _, v := range master.Variants {
|
|
if v == nil {
|
|
continue
|
|
}
|
|
details = append(details, fmt.Sprintf(" %s (%d bps)", media.ExtractResolution(v), v.Bandwidth))
|
|
}
|
|
case m3u8.MEDIA:
|
|
mediaPlaylist, ok := playlist.(*m3u8.MediaPlaylist)
|
|
if !ok {
|
|
return details, fmt.Errorf("decoder returned an unexpected playlist type")
|
|
}
|
|
details = append(details,
|
|
fmt.Sprintf("media playlist with %d segment(s), recorded as a single \"unknown\" variant", mediaPlaylist.Count()))
|
|
default:
|
|
return details, fmt.Errorf("unrecognized playlist type")
|
|
}
|
|
|
|
return details, nil
|
|
}
|
|
|
|
// checkNAS runs the same attach/mkdir/write sequence the transfer service
|
|
// performs at startup, so the check exercises the real code path for this host
|
|
// — net use on Windows, mount resolution on Linux — rather than a simulation of
|
|
// it. It disconnects afterwards so the check leaves no mount behind.
|
|
func checkNAS(cfg *config.Config) ([]string, error) {
|
|
svc, err := nas.New(nas.NASConfig{
|
|
Path: cfg.NAS.OutputPath,
|
|
Username: cfg.NAS.Username,
|
|
Password: cfg.NAS.Password,
|
|
Timeout: cfg.NAS.Timeout,
|
|
RetryLimit: cfg.NAS.RetryLimit,
|
|
VerifySize: true,
|
|
AutoMount: cfg.NAS.AutoMount,
|
|
MountPoint: cfg.NAS.MountPoint,
|
|
})
|
|
if err != nil {
|
|
return []string{"path: " + cfg.NAS.OutputPath}, err
|
|
}
|
|
|
|
start := time.Now()
|
|
result := <-probeAsync(cfg.NAS.Timeout, func() ([]string, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), cfg.NAS.Timeout)
|
|
defer cancel()
|
|
|
|
if err := svc.Connect(ctx); err != nil {
|
|
return svc.ConnectionInfo(), err
|
|
}
|
|
defer func() {
|
|
if err := svc.Disconnect(context.Background()); err != nil {
|
|
log.Printf("Warning: failed to release NAS connection after check: %v", err)
|
|
}
|
|
}()
|
|
|
|
return append(svc.ConnectionInfo(), "attach, mkdir and write probe succeeded"), nil
|
|
})
|
|
|
|
details := result.details
|
|
if len(details) == 0 {
|
|
details = svc.ConnectionInfo()
|
|
}
|
|
if result.err != nil {
|
|
return details, result.err
|
|
}
|
|
|
|
return append(details, "completed in "+formatDuration(time.Since(start))), nil
|
|
}
|
|
|
|
func formatDuration(d time.Duration) string {
|
|
if d < time.Millisecond {
|
|
return "<1ms"
|
|
}
|
|
return d.Round(time.Millisecond).String()
|
|
}
|
|
|
|
type probeResult struct {
|
|
details []string
|
|
err error
|
|
}
|
|
|
|
// probeAsync bounds a filesystem probe with a timeout. An unresponsive SMB
|
|
// mount can block indefinitely in the kernel, which would otherwise hang the
|
|
// check with no output; the orphaned goroutine dies with the process.
|
|
func probeAsync(timeout time.Duration, probe func() ([]string, error)) <-chan probeResult {
|
|
out := make(chan probeResult, 1)
|
|
done := make(chan probeResult, 1)
|
|
|
|
go func() {
|
|
details, err := probe()
|
|
done <- probeResult{details: details, err: err}
|
|
}()
|
|
|
|
go func() {
|
|
select {
|
|
case res := <-done:
|
|
out <- res
|
|
case <-time.After(timeout):
|
|
out <- probeResult{err: fmt.Errorf("timed out after %s", timeout)}
|
|
}
|
|
}()
|
|
|
|
return out
|
|
}
|
|
|
|
func reportPass(name string, details []string) {
|
|
fmt.Printf("✓ %s\n", name)
|
|
printDetails(details)
|
|
}
|
|
|
|
func reportFail(name string, details []string, err error) {
|
|
fmt.Printf("✗ %s\n", name)
|
|
printDetails(append(details, "error: "+err.Error()))
|
|
}
|
|
|
|
func reportSkip(name, reason string) {
|
|
fmt.Printf("- %s (skipped: %s)\n", name, reason)
|
|
fmt.Println()
|
|
}
|
|
|
|
// maxDetailLines caps a single detail entry. Failures from `net use` and
|
|
// friends can carry a full usage dump, which buries the actual diagnosis.
|
|
const maxDetailLines = 8
|
|
|
|
func printDetails(details []string) {
|
|
for _, d := range details {
|
|
lines := strings.Split(strings.TrimRight(d, "\n"), "\n")
|
|
truncated := 0
|
|
if len(lines) > maxDetailLines {
|
|
truncated = len(lines) - maxDetailLines
|
|
lines = lines[:maxDetailLines]
|
|
}
|
|
for _, line := range lines {
|
|
fmt.Printf(" %s\n", line)
|
|
}
|
|
if truncated > 0 {
|
|
fmt.Printf(" ... (%d more line(s))\n", truncated)
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
func enabledLabel(enabled bool) string {
|
|
if enabled {
|
|
return "enabled"
|
|
}
|
|
return "disabled"
|
|
}
|