-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatch-proxy.ps1
More file actions
83 lines (70 loc) · 2.47 KB
/
Copy pathwatch-proxy.ps1
File metadata and controls
83 lines (70 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
if (-not $env:PORT) {
$env:PORT = "8787"
}
if ((-not $env:UPSTREAM_ORIGIN) -or ($env:UPSTREAM_ORIGIN -eq "http://y3.ainiaini.xyz")) {
$env:UPSTREAM_ORIGIN = "https://api.finalval.com"
}
$Port = [int]$env:PORT
$IntervalRaw = if ($env:WATCHDOG_INTERVAL_SECONDS) { $env:WATCHDOG_INTERVAL_SECONDS } else { "5" }
$IntervalSeconds = [int]$IntervalRaw
$ProxyPidFile = Join-Path $Root ".proxy.pid"
$WatchdogPidFile = Join-Path $Root ".watchdog.pid"
$WatchdogLog = Join-Path $Root "watchdog.log"
$StartScript = Join-Path $Root "start-proxy.ps1"
function Write-Log {
param([string]$Message)
$line = "[{0}] {1}" -f ([DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss")), $Message
Add-Content -LiteralPath $WatchdogLog -Value $line -Encoding UTF8
}
function Get-ListeningPid {
$conn = Get-NetTCPConnection -LocalAddress 127.0.0.1 -LocalPort $Port -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1
if ($conn) { return [int]$conn.OwningProcess }
return 0
}
function Is-ProcessAlive {
param([int]$TargetPid)
if ($TargetPid -le 0) { return $false }
return [bool](Get-Process -Id $TargetPid -ErrorAction SilentlyContinue)
}
function Read-PidFile {
param([string]$Path)
if (-not (Test-Path $Path)) { return 0 }
try {
return [int](Get-Content -LiteralPath $Path -ErrorAction Stop)
} catch {
return 0
}
}
Set-Content -LiteralPath $WatchdogPidFile -Value $PID -Encoding ASCII
Write-Log "watchdog started on port $Port"
while ($true) {
try {
$proxyPid = Read-PidFile $ProxyPidFile
$listeningPid = Get-ListeningPid
if ($proxyPid -gt 0 -and -not (Is-ProcessAlive $proxyPid)) {
Remove-Item -LiteralPath $ProxyPidFile -Force -ErrorAction SilentlyContinue
Write-Log "removed stale proxy pid file ($proxyPid)"
$proxyPid = 0
}
if ($listeningPid -gt 0) {
if ($proxyPid -le 0 -or $proxyPid -ne $listeningPid) {
Set-Content -LiteralPath $ProxyPidFile -Value $listeningPid -Encoding ASCII
}
} else {
Write-Log "proxy not listening, starting"
try {
$output = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $StartScript 2>&1
foreach ($line in $output) {
Write-Log ([string]$line)
}
} catch {
Write-Log ("start failed: " + $_.Exception.Message)
}
}
} catch {
Write-Log ("watchdog loop error: " + $_.Exception.Message)
}
Start-Sleep -Seconds $IntervalSeconds
}