KtvSetup/scripts/heartbeat.ps1

85 lines
2.4 KiB
PowerShell

$logPath = "C:\scripts\heartbeat.log"
function Log($msg) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $logPath -Value "[$timestamp] $msg"
}
# Load config
$configPath = "C:\scripts\config.json"
if (!(Test-Path $configPath)) {
Log "error Config file not found: $configPath"
exit 1
}
$config = Get-Content $configPath | ConvertFrom-Json
# Config values
$apiUrl = $config.apiUrl.TrimEnd('/') # 移除結尾的 /
$branchName = $config.branchName
$email = $config.email
$password = $config.password
Log "📡 Using API URL: $apiUrl"
# Get IP address
$ip = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object {
$_.IPAddress -notlike "169.*" -and $_.IPAddress -notlike "127.*"
}).IPAddress
function Get-Token {
$body = @{
branch_name = $branchName
room_name = $env:COMPUTERNAME
room_ip = $ip
email = $email
password = $password
} | ConvertTo-Json -Depth 3
$url = "$apiUrl/api/room/receiveRegister"
Log "curl Requesting token from: $url"
try {
$response = Invoke-RestMethod -Uri $url -Method Post `
-Body $body -ContentType "application/json"
if ($response.data.token) {
Log "ok Token acquired: $($response.data.token)"
return $response.data.token
} else {
Log "error Failed to acquire token (no token in response)"
exit 1
}
} catch {
Log "error Token request failed: $($_.Exception.Message)"
exit 1
}
}
function Send-Heartbeat($token, $ip) {
while ($true) {
$heartbeat = @{
hostname = $env:COMPUTERNAME
ip = $ip
cpu = [math]::Round((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue, 2)
memory = [math]::Round((Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue, 2)
disk = [math]::Round((Get-PSDrive -Name C).Used / 1MB, 2)
} | ConvertTo-Json -Depth 3
try {
Invoke-RestMethod -Uri "$apiUrl/api/room/heartbeat" -Method Post `
-Headers @{ Authorization = "Bearer $token" } `
-Body $heartbeat -ContentType "application/json"
Log "ok Heartbeat sent successfully"
} catch {
Log "error Heartbeat failed: $($_.Exception.Message)"
}
Start-Sleep -Seconds 60
}
}
# Main
$token = Get-Token
Send-Heartbeat -token $token -ip $ip