#Requires -Version 5.1 <# .SYNOPSIS StreamCore service launcher: FastAPI backend (uvicorn) + nginx front end. .DESCRIPTION Starts the backend and nginx in the background with no console window and everything written to log files. The scheduled task "StreamCore-AutoStart" runs `-Action Start` at boot as the SYSTEM account, so the whole stack comes up without anyone logging in. Log files (D:\live\nvlive\live\runtime\logs): backend.err.log uvicorn output - startup banner and access log backend.out.log uvicorn stdout (normally empty) nginx-launch.err.log output of the nginx launch command nginx-launch.out.log output of the nginx launch command service.log what this script itself did, with timestamps nginx keeps its own request/error logs in D:\nginx-1.31.6\logs. NOTE ON PATH SYSTEM has a different PATH from the interactive Administrator account, and ffmpeg/ffprobe are installed per-user by winget. That directory is added to PATH explicitly below. Without it, transcoding fails with a bare "ffmpeg not found" - and only when running as a service, never by hand. NOTE ON NGINX RELOAD Because nginx runs as SYSTEM, `nginx -s reload` and `nginx -s stop` from an administrator shell fail with OpenEvent Access is denied. Use `-Action Restart` after editing nginx.conf instead: it replaces the whole worker tree. .EXAMPLE .\streamcore-service.ps1 # start (what the boot task runs) .\streamcore-service.ps1 -Action Status .\streamcore-service.ps1 -Action Doctor # what the service account sees .\streamcore-service.ps1 -Action Restart .\streamcore-service.ps1 -Action Install # register the boot task (admin) .\streamcore-service.ps1 -Action Uninstall # remove it (admin) #> [CmdletBinding()] param( [ValidateSet('Start', 'Stop', 'Restart', 'Status', 'Doctor', 'Install', 'Uninstall')] [string]$Action = 'Start' ) $ErrorActionPreference = 'Stop' # ------------------------------------------------------------------ constants $LiveRoot = 'D:\live\nvlive\live' $BackendDir = Join-Path $LiveRoot 'backend' $LogDir = Join-Path $LiveRoot 'runtime\logs' $NginxRoot = 'D:\nginx-1.31.6' $NginxExe = Join-Path $NginxRoot 'nginx.exe' $NginxLogs = Join-Path $NginxRoot 'logs' $PythonDir = 'C:\Users\Administrator\AppData\Local\Programs\Python\Python314' $UvicornExe = Join-Path $PythonDir 'Scripts\uvicorn.exe' # winget installs ffmpeg per-user; a service account never sees it on PATH. $FFmpegDir = 'C:\Users\Administrator\AppData\Local\Microsoft\WinGet\Links' $BackendPort = 8080 $TaskName = 'StreamCore-AutoStart' # Cloudflare Tunnel. The config and credentials live in ProgramData rather than a # user profile because the boot task runs as SYSTEM, which has no profile of its # own; `cloudflared tunnel login` writes to the calling user's profile only. $TunnelName = 'nvlive' $CloudflaredExe = 'C:\Program Files (x86)\cloudflared\cloudflared.exe' $TunnelConfig = 'C:\ProgramData\cloudflared\config.yml' $TunnelReadyUrl = 'http://127.0.0.1:20242/ready' $BackendOutLog = Join-Path $LogDir 'backend.out.log' $BackendErrLog = Join-Path $LogDir 'backend.err.log' $TunnelOutLog = Join-Path $LogDir 'tunnel.out.log' $TunnelErrLog = Join-Path $LogDir 'tunnel.err.log' $NginxOutLog = Join-Path $LogDir 'nginx-launch.out.log' $NginxErrLog = Join-Path $LogDir 'nginx-launch.err.log' $ServiceLog = Join-Path $LogDir 'service.log' $DoctorLog = Join-Path $LogDir 'doctor.log' $MaxLogBytes = 32MB $RestartDelaySeconds = 10 $HealthCheckSeconds = 15 $ScriptPath = $PSCommandPath # Make ffmpeg/ffprobe (and the Python Scripts dir) visible to a service account. $env:PATH = (@($FFmpegDir, (Join-Path $PythonDir 'Scripts'), $PythonDir) + $env:PATH) -join ';' # -------------------------------------------------------------------- helpers function Write-SvcLog { param( [Parameter(Mandatory)][string]$Message, [ValidateSet('INFO', 'WARN', 'ERROR')][string]$Level = 'INFO' ) $line = '{0} [{1}] {2}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $Level, $Message if (Test-Path -LiteralPath $LogDir) { try { Add-Content -LiteralPath $ServiceLog -Value $line -Encoding UTF8 } catch { } } Write-Host $line } function Test-PortListening { param([Parameter(Mandatory)][int]$Port) $conn = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue return [bool]$conn } function Rotate-Log { param([Parameter(Mandatory)][string]$Path) if (-not (Test-Path -LiteralPath $Path)) { return } if ((Get-Item -LiteralPath $Path).Length -lt $MaxLogBytes) { return } try { Move-Item -LiteralPath $Path -Destination "$Path.1" -Force } catch { # A still-running child holds the file open; keep appending instead. } } # ------------------------------------------------------------------- backend function Start-Backend { if (Test-PortListening -Port $BackendPort) { Write-SvcLog "backend already listening on port $BackendPort; not starting a second one" return $null } if (-not (Test-Path -LiteralPath $UvicornExe)) { Write-SvcLog "uvicorn.exe not found at $UvicornExe" 'ERROR' return $null } Rotate-Log -Path $BackendOutLog Rotate-Log -Path $BackendErrLog Write-SvcLog "starting backend: uvicorn main:app --port $BackendPort (cwd $BackendDir)" # Uvicorn logs to stderr, so backend.err.log is the interesting one; the two # streams cannot share a file, which is why stdout gets its own. $proc = Start-Process -FilePath $UvicornExe ` -ArgumentList 'main:app', '--port', "$BackendPort" ` -WorkingDirectory $BackendDir ` -WindowStyle Hidden ` -RedirectStandardOutput $BackendOutLog ` -RedirectStandardError $BackendErrLog ` -PassThru Write-SvcLog "backend started, pid $($proc.Id)" return $proc } function Stop-Backend { $conns = Get-NetTCPConnection -LocalPort $BackendPort -State Listen -ErrorAction SilentlyContinue if (-not $conns) { Write-SvcLog "backend is not listening on port $BackendPort" return } foreach ($procId in ($conns.OwningProcess | Sort-Object -Unique)) { try { Stop-Process -Id $procId -Force -ErrorAction Stop Write-SvcLog "stopped backend pid $procId" } catch { Write-SvcLog "could not stop backend pid ${procId}: $_" 'WARN' } } } # --------------------------------------------------------------------- nginx function Start-Nginx { param([switch]$Quiet) # Health is judged by the listening socket, not by "an nginx process exists". # A master that dies can leave workers behind that still hold 80/443 with # SO_REUSEADDR, and calling that healthy would keep a broken front end in # place forever - or let a second master bind alongside it. if ((Test-PortListening -Port 443) -or (Test-PortListening -Port 80)) { if (-not $Quiet) { Write-SvcLog 'nginx is already serving on port 80/443' } return } $stale = @(Get-Process -Name 'nginx' -ErrorAction SilentlyContinue) if ($stale.Count -gt 0) { Write-SvcLog "clearing stale nginx process(es) $(($stale.Id) -join ', ')" 'WARN' [void](Stop-NginxProcesses) } if (-not (Test-Path -LiteralPath $NginxExe)) { Write-SvcLog "nginx.exe not found at $NginxExe" 'ERROR' return } Rotate-Log -Path $NginxOutLog Rotate-Log -Path $NginxErrLog Write-SvcLog "starting nginx: `"$NginxExe`" -p $NginxRoot" # -p pins the prefix, so nginx.conf's relative paths (logs/, certs/, mime.types) # resolve inside the nginx install no matter how the task was launched. try { Start-Process -FilePath $NginxExe ` -ArgumentList '-p', $NginxRoot ` -WorkingDirectory $NginxRoot ` -WindowStyle Hidden ` -RedirectStandardOutput $NginxOutLog ` -RedirectStandardError $NginxErrLog ` -PassThru | Out-Null } catch { Write-SvcLog "nginx failed to launch: $_" 'ERROR' return } Start-Sleep -Seconds 2 if ((Test-PortListening -Port 443) -or (Test-PortListening -Port 80)) { $now = @(Get-Process -Name 'nginx' -ErrorAction SilentlyContinue) Write-SvcLog "nginx serving on 80/443 (pid $(($now.Id) -join ', '))" } else { Write-SvcLog "nginx is not serving; check $NginxErrLog and $NginxLogs\error.log" 'ERROR' } } function Stop-NginxProcesses { # Kill until none are left. A master part-way through shutdown can spawn a # fresh worker between the snapshot and the kill, so one pass is not enough - # and a surviving worker keeps holding ports 80/443. for ($attempt = 1; $attempt -le 4; $attempt++) { $left = @(Get-Process -Name 'nginx' -ErrorAction SilentlyContinue) if ($left.Count -eq 0) { return $true } foreach ($proc in $left) { try { Stop-Process -Id $proc.Id -Force -ErrorAction Stop } catch { } } Start-Sleep -Seconds 1 } return (@(Get-Process -Name 'nginx' -ErrorAction SilentlyContinue).Count -eq 0) } function Stop-Nginx { if (-not (Get-Process -Name 'nginx' -ErrorAction SilentlyContinue)) { Write-SvcLog 'nginx is not running' return } # `nginx -s stop` signals the master through the global event # Global\ngx_stop_. When nginx runs as SYSTEM (as it does here) an # administrator shell cannot open that event and nginx exits 1 with # "Access is denied" - so this is expected to fail, and the worker tree is # killed directly below. The attempt is kept because it does work when the # command happens to run as the same account that owns the master. $signalDelivered = $false try { $signal = Start-Process -FilePath $NginxExe -ArgumentList '-p', $NginxRoot, '-s', 'stop' ` -WorkingDirectory $NginxRoot -WindowStyle Hidden -PassThru -Wait $signalDelivered = ($signal.ExitCode -eq 0) } catch { Write-SvcLog "graceful nginx stop failed: $_" 'WARN' } if ($signalDelivered) { # Drain first: a graceful stop has a dozen workers to wind down. $deadline = (Get-Date).AddSeconds(8) while ((Get-Date) -lt $deadline) { if (-not (Get-Process -Name 'nginx' -ErrorAction SilentlyContinue)) { Write-SvcLog 'nginx stopped' return } Start-Sleep -Milliseconds 500 } } if (Stop-NginxProcesses) { Write-SvcLog 'nginx killed directly (the stop signal is not usable from this account)' 'WARN' } else { Write-SvcLog 'some nginx processes could not be stopped' 'ERROR' } } # ------------------------------------------------------------------- tunnel function Test-TunnelReady { # /ready is 200 only while the connector actually holds a connection to a # Cloudflare edge node, so it distinguishes "process alive" from "serving". try { $r = Invoke-WebRequest -Uri $TunnelReadyUrl -UseBasicParsing -TimeoutSec 5 -ErrorAction Stop return ($r.StatusCode -eq 200) } catch { return $false } } function Start-Tunnel { param([switch]$Quiet) if (Get-Process -Name 'cloudflared' -ErrorAction SilentlyContinue) { if (-not $Quiet) { Write-SvcLog 'tunnel is already running' } return } if (-not (Test-Path -LiteralPath $CloudflaredExe)) { Write-SvcLog "cloudflared.exe not found at $CloudflaredExe" 'ERROR' return } Rotate-Log -Path $TunnelOutLog Rotate-Log -Path $TunnelErrLog Write-SvcLog "starting tunnel '$TunnelName'" try { Start-Process -FilePath $CloudflaredExe ` -ArgumentList '--config', $TunnelConfig, 'tunnel', 'run' ` -WorkingDirectory (Split-Path -Parent $TunnelConfig) ` -WindowStyle Hidden ` -RedirectStandardOutput $TunnelOutLog ` -RedirectStandardError $TunnelErrLog ` -PassThru | Out-Null } catch { Write-SvcLog "tunnel failed to launch: $_" 'ERROR' return } Start-Sleep -Seconds 6 if (Test-TunnelReady) { Write-SvcLog 'tunnel connected to the Cloudflare edge' } elseif (Get-Process -Name 'cloudflared' -ErrorAction SilentlyContinue) { Write-SvcLog 'tunnel process is up but not ready yet; see tunnel.err.log' 'WARN' } else { Write-SvcLog "tunnel exited immediately; check $TunnelErrLog" 'ERROR' } } function Stop-Tunnel { $procs = @(Get-Process -Name 'cloudflared' -ErrorAction SilentlyContinue) if ($procs.Count -eq 0) { Write-SvcLog 'tunnel is not running' return } foreach ($proc in $procs) { try { Stop-Process -Id $proc.Id -Force -ErrorAction Stop } catch { } } Start-Sleep -Seconds 2 if (Get-Process -Name 'cloudflared' -ErrorAction SilentlyContinue) { Write-SvcLog 'tunnel did not stop' 'ERROR' } else { Write-SvcLog "tunnel stopped (pid $(($procs.Id) -join ', '))" } } function Stop-MediaOrigin { # The backend autostarts MediaMTX; only kill the repo copy, never an origin # somebody else is managing. $procs = @(Get-Process -Name 'mediamtx' -ErrorAction SilentlyContinue | Where-Object { $_.Path -and $_.Path.StartsWith($LiveRoot, 'OrdinalIgnoreCase') }) foreach ($p in $procs) { try { Stop-Process -Id $p.Id -Force -ErrorAction Stop Write-SvcLog "stopped mediamtx pid $($p.Id)" } catch { } } } # ---------------------------------------------------------------------- start function Start-Stack { New-Item -ItemType Directory -Force -Path $LogDir | Out-Null Write-SvcLog '--- start requested ---' Start-Nginx Start-Tunnel # Supervise uvicorn: if it dies, bring it straight back instead of waiting # for the scheduler's one-minute restart interval. while ($true) { $proc = Start-Backend if ($null -eq $proc) { # Something already owns the port; there is nothing to supervise. break } # Poll rather than WaitForExit so nginx and the tunnel are re-checked on # the same tick: if either lost a race at boot, this puts it back within # the poll interval. while (-not $proc.HasExited) { Start-Sleep -Seconds $HealthCheckSeconds Start-Nginx -Quiet Start-Tunnel -Quiet } Write-SvcLog "backend pid $($proc.Id) exited with code $($proc.ExitCode); restarting in ${RestartDelaySeconds}s" 'WARN' Start-Sleep -Seconds $RestartDelaySeconds } Write-SvcLog 'start finished' } function Stop-Stack { Write-SvcLog '--- stop requested ---' # The boot task supervises the backend and would restart it ten seconds from # now, so it has to go first. Stop-Stack is also its own cleanup path. $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue Write-SvcLog "stopped scheduled task '$TaskName'" Start-Sleep -Seconds 3 } Stop-Nginx Stop-Tunnel Stop-Backend Stop-MediaOrigin Write-SvcLog 'stop finished' } # -------------------------------------------------------------------- status function Show-Status { Write-Host '' Write-Host "StreamCore service status ($(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'))" Write-Host ('-' * 62) foreach ($item in @( @{ Name = 'nginx (80/443)'; Port = 443 }, @{ Name = 'backend (8080)'; Port = $BackendPort }, @{ Name = 'mediamtx api (9997)'; Port = 9997 }, @{ Name = 'mediamtx rtmp (1935)'; Port = 1935 } )) { $up = Test-PortListening -Port $item.Port $mark = if ($up) { 'UP ' } else { 'DOWN' } Write-Host (" [{0}] {1}" -f $mark, $item.Name) } # The tunnel is an outbound connector, so there is no listening port to test; # readiness comes from its own /ready endpoint. $mark = if (Test-TunnelReady) { 'UP ' } else { 'DOWN' } Write-Host (" [{0}] cloudflare tunnel '{1}'" -f $mark, $TunnelName) foreach ($name in 'nginx', 'mediamtx', 'cloudflared') { $p = @(Get-Process -Name $name -ErrorAction SilentlyContinue) Write-Host (" {0,-12} process: {1}" -f $name, $(if ($p.Count) { ($p.Id -join ', ') } else { 'not running' })) } $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue if ($task) { $info = Get-ScheduledTaskInfo -TaskName $TaskName -ErrorAction SilentlyContinue Write-Host (" boot task: {0} (last run {1}, result {2})" -f $task.State, $info.LastRunTime, $info.LastTaskResult) } else { Write-Host ' boot task: not installed' } Write-Host '' Write-Host ' logs:' foreach ($log in @($BackendErrLog, $BackendOutLog, $TunnelErrLog, $ServiceLog, $NginxErrLog)) { $size = if (Test-Path -LiteralPath $log) { '{0,10:N0} B' -f (Get-Item -LiteralPath $log).Length } else { ' absent' } Write-Host (" {0,12} {1}" -f $size, $log) } Write-Host (" {0,12} {1}" -f 'nginx logs', $NginxLogs) Write-Host '' } # ------------------------------------------------------------------- install function Install-Autostart { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $elevated = (New-Object Security.Principal.WindowsPrincipal $identity).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator) if (-not $elevated) { throw 'Registering a boot task needs an elevated PowerShell window.' } $powershellExe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $argument = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "{0}" -Action Start' -f $ScriptPath $taskAction = New-ScheduledTaskAction -Execute $powershellExe -Argument $argument -WorkingDirectory $LiveRoot $trigger = New-ScheduledTaskTrigger -AtStartup # Give the network stack a moment; binding 0.0.0.0 does not need an address, # so this is insurance rather than a requirement. try { $trigger.Delay = 'PT20S' } catch { } # SYSTEM + Highest: starts at boot with no login, and can bind ports 80/443. $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest $settings = New-ScheduledTaskSettingsSet ` -AllowStartIfOnBatteries ` -DontStopIfGoingOnBatteries ` -DontStopOnIdleEnd ` -StartWhenAvailable ` -MultipleInstances IgnoreNew ` -ExecutionTimeLimit ([TimeSpan]::Zero) ` -RestartCount 3 ` -RestartInterval (New-TimeSpan -Minutes 1) Register-ScheduledTask -TaskName $TaskName ` -Action $taskAction ` -Trigger $trigger ` -Principal $principal ` -Settings $settings ` -Description 'Starts the StreamCore backend (uvicorn, port 8080) and the nginx front end at boot.' ` -Force | Out-Null Write-SvcLog "installed scheduled task '$TaskName' (trigger: at startup, user: SYSTEM)" Show-Status } function Uninstall-Autostart { $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue if (-not $task) { Write-SvcLog "scheduled task '$TaskName' is not installed" return } Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false Write-SvcLog "removed scheduled task '$TaskName'" } function Restart-Stack { Stop-Stack # Prefer the boot task, so restarting by hand leaves the stack under the same # supervisor that will own it after the next reboot. if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) { Start-ScheduledTask -TaskName $TaskName Write-SvcLog "restart requested through scheduled task '$TaskName'" } else { Start-Stack } } # -------------------------------------------------------------------- doctor function Show-Doctor { # Reports what this script's environment actually resolves to, from inside # whichever account runs it. Run it as SYSTEM after a reboot to prove the # service account can see ffmpeg; nothing else in the stack checks that. $lines = @() $lines += 'StreamCore doctor' $lines += ' run as : {0}' -f [Security.Principal.WindowsIdentity]::GetCurrent().Name $lines += ' run at : {0}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $lines += '' $lines += ' executables:' foreach ($tool in 'ffmpeg', 'ffprobe', 'uvicorn', 'python', 'nginx', 'mediamtx', 'cloudflared') { $cmd = Get-Command $tool -ErrorAction SilentlyContinue $resolved = if ($cmd) { $cmd.Source } else { '' } $lines += ' {0,-10} {1}' -f $tool, $resolved } $lines += '' $lines += ' listening ports:' foreach ($entry in @( @{ Name = 'nginx http'; Port = 80 }, @{ Name = 'nginx https'; Port = 443 }, @{ Name = 'backend'; Port = $BackendPort }, @{ Name = 'mediamtx hls'; Port = 8888 }, @{ Name = 'mediamtx api'; Port = 9997 } )) { $lines += ' {0,-14} {1,-5} {2}' -f $entry.Name, $entry.Port, $(if (Test-PortListening -Port $entry.Port) { 'UP' } else { 'DOWN' }) } $lines += '' $lines += ' cloudflare tunnel {0}: {1}' -f $TunnelName, $(if (Test-TunnelReady) { 'connected' } else { 'NOT connected' }) $lines += '' $lines += ' PATH:' foreach ($dir in ($env:PATH -split ';' | Where-Object { $_ })) { $lines += " $dir" } $lines += '' $lines += ' log files:' foreach ($log in @($BackendErrLog, $BackendOutLog, $TunnelErrLog, $NginxErrLog, $ServiceLog)) { $exists = Test-Path -LiteralPath $log $lines += ' {0,-34} {1}' -f $log, $(if ($exists) { '{0:N0} bytes' -f (Get-Item -LiteralPath $log).Length } else { 'absent' }) } New-Item -ItemType Directory -Force -Path $LogDir | Out-Null $lines | Set-Content -LiteralPath $DoctorLog -Encoding UTF8 $lines | ForEach-Object { Write-Host $_ } } # ---------------------------------------------------------------------- main switch ($Action) { 'Start' { Start-Stack } 'Stop' { Stop-Stack } 'Restart' { Restart-Stack } 'Status' { Show-Status } 'Doctor' { Show-Doctor } 'Install' { Install-Autostart } 'Uninstall' { Uninstall-Autostart } }