id: zabbix-problem-event-correlation-gate
namespace: company.team
description: |
Zabbix problem events fire uncorrelated, so one broken switch pages on-call
dozens of times before anyone correlates the root cause. A keyed webhook
accepts the problem event batch, a Python normalizer groups in window events
by host group, problem name and tag signature, a second Python pass collapses
those groups into incidents and grades storm conditions, and an If escalates
a storm to Slack with the dedup summary. Quiet batches are logged, an
unreadable batch pages Slack on its own branch, and the event, incident and
storm verdict is published as outputs.
triggers:
- id: post_problem_events
type: io.kestra.plugin.core.trigger.Webhook
description: The Zabbix media type or a reporting sidecar POSTs a problem event
batch here the moment problems open, so correlation starts before the
pages pile up.
key: "{{ secret('ZABBIX_EVENTS_WEBHOOK_KEY') }}"
- id: hourly_event_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Hourly 00 minute net that rescores the last event batch, shipped
disabled until the webhook path is trusted in your environment.
cron: "0 * * * *"
disabled: true
inputs:
- id: window_minutes
type: INT
defaults: 15
description: Correlation window in minutes measured back from the newest event
clock, events older than the window are dropped as stale before grouping.
- id: storm_group_size
type: INT
defaults: 5
description: Number of identical events sharing one signature that mark the
batch as a storm worth a dedup summary page.
- id: min_batch_events
type: INT
defaults: 6
description: Lowest scored event count a batch needs before storm verdict can
fire, so a two event blip never pages anyone.
tasks:
# --- 1. event signature grouping ---
- id: group_problem_events
type: io.kestra.plugin.scripts.python.Script
description: Read the posted problem event batch or the bundled example batch,
drop events outside the correlation window, group the rest by host group,
problem name and tag signature, and emit the signature groups through the
outputs protocol.
containerImage: python:3.12-slim
env:
EVENTS_JSON: "{{ trigger.body ?? '' }}"
WINDOW_MINUTES: "{{ inputs.window_minutes }}"
script: |
import json
import os
DEFAULT_EVENTS = """
{"batch_id": "zbx-batch-20261014-0200",
"events": [
{"eventid": "30101", "clock": 1780000000, "name": "Interface eth0 down", "host_group": "Network", "hosts": ["core-sw-01"], "severity": 4, "tags": [{"tag": "component", "value": "net"}]},
{"eventid": "30102", "clock": 1780000060, "name": "Interface eth0 down", "host_group": "Network", "hosts": ["core-sw-02"], "severity": 4, "tags": [{"tag": "component", "value": "net"}]},
{"eventid": "30103", "clock": 1780000120, "name": "Interface eth0 down", "host_group": "Network", "hosts": ["core-sw-03"], "severity": 4, "tags": [{"tag": "component", "value": "net"}]},
{"eventid": "30104", "clock": 1780000180, "name": "Interface eth0 down", "host_group": "Network", "hosts": ["core-sw-01"], "severity": 4, "tags": [{"tag": "component", "value": "net"}]},
{"eventid": "30105", "clock": 1780000240, "name": "Interface eth0 down", "host_group": "Network", "hosts": ["core-sw-02"], "severity": 4, "tags": [{"tag": "component", "value": "net"}]},
{"eventid": "30106", "clock": 1780000300, "name": "Interface eth0 down", "host_group": "Network", "hosts": ["core-sw-03"], "severity": 4, "tags": [{"tag": "component", "value": "net"}]},
{"eventid": "30111", "clock": 1780000030, "name": "High CPU utilization", "host_group": "Compute", "hosts": ["app-01"], "severity": 3, "tags": [{"tag": "component", "value": "cpu"}]},
{"eventid": "30112", "clock": 1780000090, "name": "High CPU utilization", "host_group": "Compute", "hosts": ["app-02"], "severity": 3, "tags": [{"tag": "component", "value": "cpu"}]},
{"eventid": "30113", "clock": 1780000150, "name": "High CPU utilization", "host_group": "Compute", "hosts": ["app-03"], "severity": 3, "tags": [{"tag": "component", "value": "cpu"}]},
{"eventid": "30121", "clock": 1780000210, "name": "Disk /var at 95 percent", "host_group": "Storage", "hosts": ["db-01"], "severity": 2, "tags": [{"tag": "component", "value": "disk"}]},
{"eventid": "30122", "clock": 1780000270, "name": "Disk /var at 95 percent", "host_group": "Storage", "hosts": ["db-02"], "severity": 2, "tags": [{"tag": "component", "value": "disk"}]},
{"eventid": "30131", "clock": 1780000330, "name": "Certificate expires in 14 days", "host_group": "Security", "hosts": ["edge-01"], "severity": 1, "tags": [{"tag": "component", "value": "pki"}]}
]}
"""
def env_int(name, default):
try:
return int(float(os.environ.get(name, default)))
except (TypeError, ValueError):
return int(default)
WINDOW_MINUTES = env_int("WINDOW_MINUTES", 15)
raw = os.environ.get("EVENTS_JSON")
if raw is None or not raw.strip():
raw = DEFAULT_EVENTS.strip()
payload = {
"parse_ok": False, "groups": [], "group_count": 0,
"events_scored": 0, "stale_dropped": 0, "error": "",
}
def tag_signature(tags):
pairs = []
for tag in tags if isinstance(tags, list) else []:
if isinstance(tag, dict):
pairs.append(str(tag.get("tag") or "unnamed") + "=" + str(tag.get("value") or ""))
return ",".join(sorted(pairs))
try:
document = json.loads(raw)
except ValueError:
document = None
events = None
if isinstance(document, dict):
events = document.get("events")
elif isinstance(document, list):
events = document
if not isinstance(events, list):
payload["error"] = "problem event batch carries no events array"
else:
rows = [entry for entry in events if isinstance(entry, dict)]
if not rows:
payload["error"] = "problem event batch contains no events"
else:
clocks = []
for row in rows:
try:
clocks.append(int(row.get("clock") or 0))
except (TypeError, ValueError):
clocks.append(0)
reference = max(clocks) if clocks else 0
window_seconds = max(0, WINDOW_MINUTES) * 60
grouped = {}
stale = 0
for row, clock in zip(rows, clocks):
if reference > 0 and clock > 0 and (reference - clock) > window_seconds:
stale += 1
continue
host_group = str(row.get("host_group") or "unknown-group")
trigger_name = str(row.get("name") or "unnamed-problem")
signature = host_group + "|" + trigger_name + "|" + tag_signature(row.get("tags"))
entry = grouped.get(signature)
if entry is None:
entry = {
"signature": signature,
"host_group": host_group,
"trigger": trigger_name,
"count": 0,
"hosts": [],
"severity": 0,
"first_seen": clock or reference,
"last_seen": clock or reference,
}
grouped[signature] = entry
entry["count"] += 1
for host in row.get("hosts") if isinstance(row.get("hosts"), list) else []:
entry["hosts"].append(str(host))
try:
entry["severity"] = max(entry["severity"], int(row.get("severity") or 0))
except (TypeError, ValueError):
pass
if clock:
entry["first_seen"] = min(entry["first_seen"], clock)
entry["last_seen"] = max(entry["last_seen"], clock)
groups = []
for entry in grouped.values():
entry["hosts"] = sorted(set(entry["hosts"]))
groups.append(entry)
groups.sort(key=lambda item: (-item["count"], item["signature"]))
payload.update({
"parse_ok": True,
"groups": groups,
"group_count": len(groups),
"events_scored": sum(entry["count"] for entry in groups),
"stale_dropped": stale,
})
if not payload["parse_ok"] and not payload["error"]:
payload["error"] = "problem event batch could not be grouped"
print("parse_ok=%s events=%d groups=%d stale=%d" % (
payload["parse_ok"], payload["events_scored"], payload["group_count"], payload["stale_dropped"]))
print("::" + json.dumps({"outputs": payload}) + "::")
# --- 2. incident collapse and storm grade ---
- id: collapse_incidents
type: io.kestra.plugin.scripts.python.Script
description: Collapse the signature groups into one incident each, measure how
far the batch shrank, and grade the storm verdict against the batch floor
and the identical event group size.
containerImage: python:3.12-slim
env:
GROUPS_JSON: "{{ outputs.group_problem_events.vars.groups | toJson }}"
PARSE_OK: "{{ outputs.group_problem_events.vars.parse_ok }}"
STALE_DROPPED: "{{ outputs.group_problem_events.vars.stale_dropped }}"
STORM_GROUP_SIZE: "{{ inputs.storm_group_size }}"
MIN_BATCH_EVENTS: "{{ inputs.min_batch_events }}"
script: |
import json
import os
def env_int(name, default):
try:
return int(float(os.environ.get(name, default)))
except (TypeError, ValueError):
return int(default)
STORM_GROUP_SIZE = max(1, env_int("STORM_GROUP_SIZE", 5))
MIN_BATCH_EVENTS = max(1, env_int("MIN_BATCH_EVENTS", 6))
STALE_DROPPED = max(0, env_int("STALE_DROPPED", 0))
PARSE_OK = str(os.environ.get("PARSE_OK") or "false").strip().lower() in ("true", "1", "yes")
raw_groups = os.environ.get("GROUPS_JSON") or "[]"
try:
groups = json.loads(raw_groups)
except ValueError:
groups = None
if not isinstance(groups, list):
groups = []
payload = {
"collapse_ok": False, "events": 0, "incidents": 0,
"storm_detected": False, "largest_incident": 0,
"storm_signature": "", "reduction_pct": 0.0,
"stale_dropped": STALE_DROPPED, "error": "",
}
if not PARSE_OK:
payload["error"] = "problem event batch could not be grouped, correlation skipped"
else:
scored = [entry for entry in groups if isinstance(entry, dict)]
events = 0
largest = 0
largest_signature = ""
for entry in scored:
try:
count = int(entry.get("count") or 0)
except (TypeError, ValueError):
count = 0
events += count
if count > largest:
largest = count
largest_signature = str(entry.get("signature") or "")
incidents = len(scored)
reduction = round((events - incidents) * 100.0 / events, 1) if events > 0 else 0.0
storm = events >= MIN_BATCH_EVENTS and largest >= STORM_GROUP_SIZE
payload.update({
"collapse_ok": True,
"events": events,
"incidents": incidents,
"storm_detected": bool(storm),
"largest_incident": largest,
"storm_signature": largest_signature if storm else "",
"reduction_pct": reduction,
})
print("collapse_ok=%s events=%d incidents=%d storm=%s largest=%d" % (
payload["collapse_ok"], payload["events"], payload["incidents"],
payload["storm_detected"], payload["largest_incident"]))
print("::" + json.dumps({"outputs": payload}) + "::")
# --- 3. storm gate ---
- id: storm_gate
type: io.kestra.plugin.core.flow.If
description: Branch on a batch that actually correlated into a storm, so the
dedup summary page fires only when identical events multiplied.
condition: "{{ outputs.collapse_incidents.vars.collapse_ok and
outputs.collapse_incidents.vars.storm_detected }}"
then:
# --- 4. storm escalation ---
- id: notify_dedup_summary
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the event to incident reduction, the largest identical group
and its signature so on call sees one page per incident instead of one
per event.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "Zabbix problem storm deduplicated - {{ outputs.collapse_incidents.vars.events }} problem events collapsed into {{ outputs.collapse_incidents.vars.incidents }} incidents over the {{ inputs.window_minutes }} minute correlation window, a {{ outputs.collapse_incidents.vars.reduction_pct }} percent reduction. Largest identical group {{ outputs.collapse_incidents.vars.largest_incident }} events with signature {{ outputs.collapse_incidents.vars.storm_signature }}, {{ outputs.collapse_incidents.vars.stale_dropped }} stale event(s) dropped. Execution {{ execution.id }}."
}
else:
- id: check_batch_health
type: io.kestra.plugin.core.flow.If
description: Split a batch that graded quietly from one that could not be
grouped, so a broken payload never reads as a calm monitoring estate.
condition: "{{ outputs.collapse_incidents.vars.collapse_ok }}"
then:
- id: log_quiet_batch
type: io.kestra.plugin.core.log.Log
description: Record the quiet verdict with the event and incident counts so the
history doubles as evidence the correlation ran.
message: "zabbix batch quiet - {{ outputs.collapse_incidents.vars.events }}
event(s) collapsed into {{
outputs.collapse_incidents.vars.incidents }} incident(s), largest
group {{ outputs.collapse_incidents.vars.largest_incident }}
against {{ inputs.storm_group_size }} identical events and a {{
inputs.min_batch_events }} event batch floor, {{
outputs.collapse_incidents.vars.stale_dropped }} stale event(s)
dropped"
else:
- id: alert_unreadable_batch
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Tell the ops channel the problem event batch could not be grouped
and name the correlation problem.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "Zabbix problem batch unreadable - {{ outputs.collapse_incidents.vars.error }}. Correlation skipped, nothing was collapsed. Execution {{ execution.id }}."}
errors:
- id: notify_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Escalate any failure to the ops channel with the execution url.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{"text": "FAILED: {{ flow.id }} {{ execution.id }}"}
outputs:
- id: events
type: INT
description: Problem events that fell inside the correlation window and were
scored, for example 12 when one batch carried twelve in window events.
value: "{{ outputs.collapse_incidents.vars.events }}"
- id: incidents
type: INT
description: Incidents after identical events collapsed into one entry per host
group, problem name and tag signature, for example 4.
value: "{{ outputs.collapse_incidents.vars.incidents }}"
- id: storm_detected
type: BOOL
description: True when the scored batch met the batch floor and held one
identical group at or above the storm group size, false otherwise.
value: "{{ outputs.collapse_incidents.vars.storm_detected }}"
- id: largest_incident
type: INT
description: Size of the largest identical event group in the batch, for example
6 when one switch down event fired on six hosts.
value: "{{ outputs.collapse_incidents.vars.largest_incident }}"
- id: storm_signature
type: STRING
description: Signature of the largest identical group when a storm fired, for
example Network|Interface eth0 down|component=net, empty when quiet.
value: "{{ outputs.collapse_incidents.vars.storm_signature }}"