id: windows-service-restart-storm-and-recovery-audit
namespace: company.team
description: |
Audit the Windows System event log for services that terminate unexpectedly in
bursts, resolve each culprit to its service name, check whether recovery actions
are configured, and alert Slack only when a restart storm is confirmed.
triggers:
- id: daily
type: io.kestra.plugin.core.trigger.Schedule
description: Run every morning so overnight restart storms are visible at the
start of the shift.
cron: "0 6 * * *"
inputs:
- id: windowHours
type: INT
description: How many hours back into the System log the audit looks.
defaults: 24
- id: stormThreshold
type: INT
description: Terminations of the same service inside the window that count as a
restart storm.
defaults: 3
- id: includeUnexpectedShutdowns
type: BOOL
description: Also collect event 6008 unexpected shutdown records for correlation.
defaults: true
tasks:
- id: collect_and_score
type: io.kestra.plugin.scripts.powershell.Script
description: Pull System log events 7031, 7034, 7000 and optionally 6008, parse
the service names, resolve display names to service names, score restart
storms, and audit recovery actions for every storm service.
taskRunner:
type: io.kestra.plugin.core.runner.Process
outputFiles:
- service_events.json
env:
WINDOW_HOURS: "{{ inputs.windowHours }}"
STORM_THRESHOLD: "{{ inputs.stormThreshold }}"
INCLUDE_SHUTDOWNS: "{{ inputs.includeUnexpectedShutdowns }}"
script: |
$windowHours = [int]$env:WINDOW_HOURS
$threshold = [int]$env:STORM_THRESHOLD
$includeShutdowns = $env:INCLUDE_SHUTDOWNS -eq 'true'
$since = (Get-Date).ToUniversalTime().AddHours(-$windowHours)
$ids = @(7031, 7034, 7000)
if ($includeShutdowns) { $ids += 6008 }
$events = Get-WinEvent -FilterHashtable @{ LogName = 'System'; StartTime = $since; Id = $ids } -ErrorAction SilentlyContinue
$records = @()
foreach ($e in $events) {
$msg = ($e.Message -replace '\s+', ' ').Trim()
$svc = $null
$kind = 'unknown'
if ($e.Id -in 7031, 7034) {
$kind = 'service-terminated'
if ($msg -match '^The (.+?) service terminated') { $svc = $Matches[1] }
} elseif ($e.Id -eq 7000) {
$kind = 'service-start-failed'
if ($msg -match '^The (.+?) service failed to start') { $svc = $Matches[1] }
} elseif ($e.Id -eq 6008) {
$kind = 'unexpected-shutdown'
}
$records += [pscustomobject]@{
timeUtc = $e.TimeCreated.ToUniversalTime().ToString('o')
eventId = $e.Id
kind = $kind
service = $svc
machine = $env:COMPUTERNAME
message = $msg.Substring(0, [Math]::Min(240, $msg.Length))
}
}
$svcMap = @{}
Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | ForEach-Object {
if ($_.DisplayName) { $svcMap[$_.DisplayName] = $_.Name }
if ($_.Name) { $svcMap[$_.Name] = $_.Name }
}
$terminated = @($records | Where-Object { $_.kind -eq 'service-terminated' -and $_.service })
$shutdowns = @($records | Where-Object { $_.kind -eq 'unexpected-shutdown' })
$groups = $terminated | Group-Object service | Sort-Object Count -Descending
$stormServices = @()
$recoveryGaps = @()
$worst = ''
$worstCount = 0
foreach ($g in $groups) {
if ($g.Count -ge $threshold) {
$stormServices += $g.Name
if ($worstCount -eq 0) { $worst = $g.Name; $worstCount = $g.Count }
$scName = if ($svcMap.ContainsKey($g.Name)) { $svcMap[$g.Name] } else { $g.Name }
$qf = & sc.exe qfailure $scName 2>$null | Out-String
$hasCmd = $qf -match 'COMMAND_LINE\s*:\s*\S'
if (-not $hasCmd) { $recoveryGaps += $g.Name }
}
}
$verdict = if ($stormServices.Count -gt 0) { 'STORM' } else { 'CLEAR' }
$report = [pscustomobject]@{
machine = $env:COMPUTERNAME
windowHours = $windowHours
threshold = $threshold
collectedAtUtc = (Get-Date).ToUniversalTime().ToString('o')
events = $records
stormServices = $stormServices
recoveryGaps = $recoveryGaps
}
$reportPath = Join-Path '{{ outputDir }}' 'service_events.json'
$report | ConvertTo-Json -Depth 6 | Set-Content -Path $reportPath -Force
$payload = @{
outputs = @{
verdict = $verdict
storm_detected = ($stormServices.Count -gt 0)
events_total = $records.Count
terminated_total = $terminated.Count
shutdowns_total = $shutdowns.Count
storm_count = $stormServices.Count
worst_service = $worst
worst_count = $worstCount
storm_services = $stormServices
recovery_gaps = $recoveryGaps
machine = $env:COMPUTERNAME
window_hours = $windowHours
collected_at = (Get-Date).ToUniversalTime().ToString('o')
}
}
Write-Output ('::' + ($payload | ConvertTo-Json -Compress -Depth 5) + '::')
- id: per_service_recovery_audit
type: io.kestra.plugin.core.flow.Loop
description: Re-check every storm service with sc.exe and log its current state,
start mode, and whether a recovery command line is configured.
values: "{{ outputs.collect_and_score.vars.storm_services }}"
concurrencyLimit: 1
tasks:
- id: audit_service_recovery
type: io.kestra.plugin.scripts.powershell.Script
description: Resolve one storm service, read its recovery configuration, and
emit the result.
allowFailure: true
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
SERVICE_DISPLAY: "{{ item }}"
script: |
$display = $env:SERVICE_DISPLAY
$svc = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -eq $display -or $_.Name -eq $display } | Select-Object -First 1
$name = if ($svc) { $svc.Name } else { $display }
$state = if ($svc) { (Get-Service -Name $name -ErrorAction SilentlyContinue).Status.ToString() } else { 'NOT_FOUND' }
$startup = if ($svc) { $svc.StartMode } else { 'UNKNOWN' }
$qf = & sc.exe qfailure $name 2>$null | Out-String
$hasCmd = $qf -match 'COMMAND_LINE\s*:\s*\S'
$payload = @{
outputs = @{
service_display = $display
service_name = $name
current_state = $state
startup_type = $startup
recovery_actions = [bool]$hasCmd
}
}
Write-Output ('::' + ($payload | ConvertTo-Json -Compress -Depth 4) + '::')
Write-Output ('recovery audit: ' + $display + ' (service ' + $name + ') state=' + $state + ' startup=' + $startup + ' recovery_actions=' + $hasCmd)
- id: alert_if_storm
type: io.kestra.plugin.core.flow.If
description: Alert only when at least one service crossed the restart threshold,
otherwise record a clean result.
condition: "{{ outputs.collect_and_score.vars.storm_detected }}"
then:
- id: alert_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the storm summary, the worst offender and the services missing
recovery actions to the ops channel.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Windows restart storm on {{ outputs.collect_and_score.vars.machine }}: {{ outputs.collect_and_score.vars.storm_count }} service(s) crossed {{ inputs.stormThreshold }} termination(s) in {{ inputs.windowHours }}h. Worst offender {{ outputs.collect_and_score.vars.worst_service }} with {{ outputs.collect_and_score.vars.worst_count }} termination(s). No recovery command line configured on {{ outputs.collect_and_score.vars.recovery_gaps }}. Events audited {{ outputs.collect_and_score.vars.events_total }}. Execution {{ execution.id }}."}
- id: log_storm_summary
type: io.kestra.plugin.core.log.Log
description: Record the storm verdict in the execution log for the shift handover.
message: "Restart storm verdict STORM on {{
outputs.collect_and_score.vars.machine }}: {{
outputs.collect_and_score.vars.storm_count }} storm service(s), worst
{{ outputs.collect_and_score.vars.worst_service }} at {{
outputs.collect_and_score.vars.worst_count }} termination(s), recovery
gaps {{ outputs.collect_and_score.vars.recovery_gaps }}, {{
outputs.collect_and_score.vars.terminated_total }} termination(s) and
{{ outputs.collect_and_score.vars.shutdowns_total }} unexpected
shutdown(s) in the last {{ inputs.windowHours }}h."
else:
- id: log_all_clear
type: io.kestra.plugin.core.log.Log
description: Record that no service crossed the threshold in the audited window.
message: "Restart storm verdict CLEAR on {{
outputs.collect_and_score.vars.machine }}: {{
outputs.collect_and_score.vars.events_total }} event(s) audited over
{{ inputs.windowHours }}h, no service reached {{ inputs.stormThreshold
}} termination(s)."
errors:
- id: alert_slack_on_error
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Ping the on-call channel when the audit itself fails so a broken
collector never stays silent.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
allowFailure: true
payload: |
{"text": "Windows restart storm audit failed on {{ outputs.collect_and_score.vars.machine ?? execution.id }}: {{ errorLogs() }}. Execution {{ execution.id }}."}
outputs:
- id: verdict
type: STRING
value: "{{ outputs.collect_and_score.vars.verdict }}"
- id: storm_detected
type: BOOL
value: "{{ outputs.collect_and_score.vars.storm_detected }}"
- id: events_total
type: INT
value: "{{ outputs.collect_and_score.vars.events_total }}"
- id: worst_service
type: STRING
value: "{{ outputs.collect_and_score.vars.worst_service }}"
- id: storm_services
type: JSON
value: "{{ outputs.collect_and_score.vars.storm_services }}"
- id: machine
type: STRING
value: "{{ outputs.collect_and_score.vars.machine }}"