id: druid-supervisor-stalled-ingestion-auto-reset-guard
namespace: company.analytics
description: |
Audit Apache Druid streaming ingestion supervisors for stalled Kafka/Kinesis consumers,
classify task failure causes, track health history across runs in Kestra KV, safely reset
and resume wedged supervisors behind human approval, and verify ingestion recovery.
inputs:
- id: druid_url
type: STRING
displayName: Druid Avatica JDBC URL
description: JDBC Avatica connection URL for the Apache Druid router or broker service.
defaults: "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/;\
transparent_reconnection=true"
- id: overlord_url
type: STRING
displayName: Druid Overlord REST URL
description: Base HTTP URL of the Druid Overlord or Router coordinating
supervisor lifecycle operations.
defaults: "http://localhost:8888"
- id: target_supervisor_id
type: STRING
displayName: Target Supervisor ID
description: Optional specific supervisor identifier to audit (e.g.
'wikipedia_kafka'). Leave empty to audit all active supervisors.
defaults: ""
- id: stalled_runs_threshold
type: INT
displayName: Stalled Runs Threshold
description: Number of consecutive runs a supervisor must remain unhealthy or
failed before flagging for automated reset.
defaults: 1
- id: auto_reset
type: BOOL
displayName: Auto Reset
description: When true and dry_run is false, dispatches reset and resume
requests to unwedge stuck supervisors.
defaults: true
- id: dry_run
type: BOOL
displayName: Dry Run Mode
description: When true, compiles the triage assessment and logs proposed
remediation actions without mutating supervisor state.
defaults: true
triggers:
- id: hourly_supervisor_guard
type: io.kestra.plugin.core.trigger.Schedule
description: Periodic scheduled audit scanning managed Druid ingestion
supervisors every hour.
cron: "0 * * * *"
disabled: true
- id: on_demand_supervisor_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Authenticated on-demand webhook trigger for incident response and
alerting integrations.
key: "{{ secret('DRUID_GUARD_WEBHOOK_KEY') }}"
tasks:
- id: validate_inputs
type: io.kestra.plugin.core.execution.Assert
description: Assert operational inputs satisfy threshold and connectivity requirements.
conditions:
- "{{ inputs.druid_url | length > 0 }}"
- "{{ inputs.overlord_url | length > 0 }}"
- "{{ inputs.stalled_runs_threshold >= 1 }}"
errorMessage: "Invalid configuration inputs. Provide a valid Druid JDBC URL,
Overlord REST URL, and positive threshold."
- id: query_unhealthy_supervisors
type: io.kestra.plugin.jdbc.druid.Query
description: Query Druid metadata table sys.supervisors for ingestion
supervisors in unhealthy or suspended states.
url: "{{ inputs.druid_url }}"
username: "{{ secret('DRUID_USER') }}"
password: "{{ secret('DRUID_PASSWORD') }}"
sql: |
SELECT supervisor_id, state, detailed_state, healthy
FROM sys.supervisors
WHERE healthy = 0 OR state IN ('UNHEALTHY_SUPERVISOR', 'UNHEALTHY_TASKS', 'SUSPENDED')
fetchType: FETCH
- id: query_recent_failed_tasks
type: io.kestra.plugin.jdbc.druid.Query
description: Query Druid metadata table sys.tasks for recent failed ingestion
worker tasks and root-cause stack traces.
url: "{{ inputs.druid_url }}"
username: "{{ secret('DRUID_USER') }}"
password: "{{ secret('DRUID_PASSWORD') }}"
sql: |
SELECT task_id, datasource, status, error_msg, host, created_time
FROM sys.tasks
WHERE status = 'FAILED'
ORDER BY created_time DESC
LIMIT 15
fetchType: FETCH
- id: load_previous_guard_state
type: io.kestra.plugin.core.kv.Get
description: Retrieve previous run supervisor health status and stall counters
from Kestra KV store.
key: "druid_supervisor_stalled_guard_state"
errorOnMissing: false
- id: triage_supervisor_failures
type: io.kestra.plugin.scripts.python.Script
description: Correlate unhealthy supervisors with failed worker tasks, calculate
consecutive stall runs, and compile remediation plan.
containerImage: python:3.11-slim
inputFiles:
supervisors.json: "{{ (outputs.query_unhealthy_supervisors.rows ?? []) | toJson }}"
failed_tasks.json: "{{ (outputs.query_recent_failed_tasks.rows ?? []) | toJson }}"
previous_kv.json: "{{ (outputs.load_previous_guard_state.value ?? {}) | toJson }}"
env:
TARGET_SUPERVISOR_ID: "{{ inputs.target_supervisor_id }}"
STALLED_RUNS_THRESHOLD: "{{ inputs.stalled_runs_threshold }}"
AUTO_RESET: "{{ inputs.auto_reset }}"
EXECUTION_ID: "{{ execution.id }}"
script: |
import json
import os
from datetime import datetime, timezone
try:
from kestra import Kestra
except ImportError:
Kestra = None
target_supervisor_id = os.environ.get("TARGET_SUPERVISOR_ID", "").strip()
stalled_runs_threshold = int(os.environ.get("STALLED_RUNS_THRESHOLD", "1"))
auto_reset = os.environ.get("AUTO_RESET", "true").lower() == "true"
execution_id = os.environ.get("EXECUTION_ID", "manual-run")
def load_json_file(filename, fallback):
try:
if os.path.exists(filename):
with open(filename, "r", encoding="utf-8") as f:
content = f.read().strip()
return json.loads(content) if content else fallback
except Exception:
pass
return fallback
supervisors_data = load_json_file("supervisors.json", [])
failed_tasks_data = load_json_file("failed_tasks.json", [])
previous_kv_raw = load_json_file("previous_kv.json", {})
previous_kv = previous_kv_raw if isinstance(previous_kv_raw, dict) else {}
if isinstance(previous_kv, str):
try:
previous_kv = json.loads(previous_kv)
except Exception:
previous_kv = {}
# Filter supervisors if target specified
filtered_supervisors = []
for s in supervisors_data:
if not isinstance(s, dict):
continue
s_id = str(s.get("supervisor_id", s.get("SUPERVISOR_ID", "")))
if target_supervisor_id and s_id != target_supervisor_id:
continue
filtered_supervisors.append({
"supervisor_id": s_id,
"state": str(s.get("state", s.get("STATE", "UNKNOWN"))),
"detailed_state": str(s.get("detailed_state", s.get("DETAILED_STATE", ""))),
"healthy": int(s.get("healthy", s.get("HEALTHY", 0)))
})
# Map recent failed tasks by datasource/supervisor hints
task_errors_by_datasource = {}
for t in failed_tasks_data:
if not isinstance(t, dict):
continue
ds = str(t.get("datasource", t.get("DATASOURCE", "unknown")))
err = str(t.get("error_msg", t.get("ERROR_MSG", "Unknown task failure")))[:300]
task_errors_by_datasource.setdefault(ds, []).append(err)
updated_kv = {}
supervisors_to_reset = []
remediation_required = False
for s in filtered_supervisors:
s_id = s["supervisor_id"]
prev_entry = previous_kv.get(s_id, {})
stalled_runs = prev_entry.get("stalled_runs", 0) if isinstance(prev_entry, dict) else 0
# Increment stall run counter
stalled_runs += 1
is_qualified = (stalled_runs >= stalled_runs_threshold)
matched_errors = task_errors_by_datasource.get(s_id, ["No direct task errors recorded in recent sample"])
updated_kv[s_id] = {
"state": s["state"],
"detailed_state": s["detailed_state"],
"healthy": s["healthy"],
"stalled_runs": stalled_runs,
"last_evaluated": datetime.now(timezone.utc).isoformat(),
"sample_task_errors": matched_errors[:2]
}
if is_qualified:
remediation_required = True
supervisors_to_reset.append({
"supervisor_id": s_id,
"state": s["state"],
"detailed_state": s["detailed_state"],
"stalled_runs": stalled_runs,
"sample_error": matched_errors[0] if matched_errors else ""
})
# Format triage report
summary_lines = [
f"*Unhealthy Supervisors Detected:* {len(filtered_supervisors)}",
f"*Supervisors Flagged for Reset:* {len(supervisors_to_reset)}",
f"*Auto Reset Enabled:* `{auto_reset}` (Threshold: `{stalled_runs_threshold}` runs)"
]
if supervisors_to_reset:
summary_lines.append("*Remediation Queue:*")
for item in supervisors_to_reset:
summary_lines.append(f"- `{item['supervisor_id']}`: state `{item['state']}` ({item['detailed_state']}), stalled `{item['stalled_runs']}` run(s). Sample error: `{item['sample_error'][:120]}`")
output_data = {
"remediation_required": remediation_required,
"unhealthy_count": len(filtered_supervisors),
"stalled_count": len(supervisors_to_reset),
"supervisors_to_reset": supervisors_to_reset,
"kv_payload": updated_kv,
"summary_markdown": "\n".join(summary_lines)
}
if Kestra:
Kestra.outputs(output_data)
else:
print("::" + json.dumps({"outputs": output_data}) + "::")
- id: persist_guard_state_kv
type: io.kestra.plugin.core.kv.Set
description: Persist updated supervisor health tracking and stall telemetry into
Kestra namespace KV store.
key: "druid_supervisor_stalled_guard_state"
kvType: JSON
overwrite: true
value: "{{ outputs.triage_supervisor_failures.vars.kv_payload | toJson }}"
- id: gate_remediation
type: io.kestra.plugin.core.flow.If
description: Evaluate if stalled Druid supervisors require operator approval and
automated reset requests.
condition: "{{ outputs.triage_supervisor_failures.vars.remediation_required }}"
then:
- id: check_dry_run_mode
type: io.kestra.plugin.core.flow.If
description: Branch between dry-run/audit simulation and active cluster
remediation. Both dry_run=false and auto_reset=true are required to
actually mutate supervisor state.
condition: "{{ inputs.dry_run or not inputs.auto_reset }}"
then:
- id: log_dry_run_plan
type: io.kestra.plugin.core.log.Log
description: Log proposed supervisor reset operations without mutating cluster
state in dry-run or audit-only mode.
message: |
[DRY RUN / AUDIT] Identified {{ outputs.triage_supervisor_failures.vars.stalled_count }} stalled Druid supervisor(s).
Proposed remediation actions:
{{ outputs.triage_supervisor_failures.vars.supervisors_to_reset | toJson }}
Set dry_run=false and auto_reset=true, then approve the pause gate, to dispatch reset/resume requests to the Druid Overlord.
else:
- id: approval_gate
type: io.kestra.plugin.core.flow.Pause
description: Pause workflow execution for operator verification before resetting
Druid streaming supervisors. Resume to execute or kill to abort.
onResume:
- id: approved
type: BOOL
displayName: Approve Supervisor Reset
description: Confirm authorization to dispatch reset and resume requests to the
Druid Overlord.
defaults: true
- id: remediate_supervisors
type: io.kestra.plugin.core.flow.Loop
description: Iterate sequentially over each stalled supervisor to issue reset
and resume calls against Overlord REST API.
values: "{{ outputs.triage_supervisor_failures.vars.supervisors_to_reset }}"
concurrencyLimit: 1
tasks:
- id: reset_supervisor
type: io.kestra.plugin.core.http.Request
description: Issue POST /druid/indexer/v1/supervisor/{id}/reset to discard
wedged checkpoints and restart ingestion.
uri: "{{ inputs.overlord_url }}/druid/indexer/v1/supervisor/{{
item.value.supervisor_id }}/reset"
method: POST
headers:
Authorization: "Basic {{ (secret('DRUID_USER') ~ ':' ~ secret('DRUID_PASSWORD'))
| base64Encode }}"
Accept: "application/json"
options:
allowFailed: true
- id: check_if_suspended
type: io.kestra.plugin.core.flow.If
description: Issue resume request if supervisor is in SUSPENDED state.
condition: "{{ item.value.state == 'SUSPENDED' }}"
then:
- id: resume_supervisor
type: io.kestra.plugin.core.http.Request
description: Issue POST /druid/indexer/v1/supervisor/{id}/resume to restart
suspended ingestion.
uri: "{{ inputs.overlord_url }}/druid/indexer/v1/supervisor/{{
item.value.supervisor_id }}/resume"
method: POST
headers:
Authorization: "Basic {{ (secret('DRUID_USER') ~ ':' ~ secret('DRUID_PASSWORD'))
| base64Encode }}"
Accept: "application/json"
options:
allowFailed: true
- id: log_supervisor_reset_action
type: io.kestra.plugin.core.log.Log
description: Log supervisor reset HTTP outcome.
message: "Dispatched reset request for supervisor '{{ item.value.supervisor_id
}}'. Overlord response code: {{ outputs.reset_supervisor.code
}}."
- id: verify_supervisors_remediation
type: io.kestra.plugin.jdbc.druid.Query
description: Post-remediation verification re-querying sys.supervisors to
confirm that remediated supervisors have recovered.
url: "{{ inputs.druid_url }}"
username: "{{ secret('DRUID_USER') }}"
password: "{{ secret('DRUID_PASSWORD') }}"
sql: |
SELECT supervisor_id, state, detailed_state, healthy
FROM sys.supervisors
WHERE healthy = 0 OR state IN ('UNHEALTHY_SUPERVISOR', 'UNHEALTHY_TASKS')
fetchType: FETCH
- id: check_remaining_unhealthy
type: io.kestra.plugin.core.flow.If
description: Check if any supervisor remains in an unhealthy state following
remediation.
condition: "{{ (outputs.verify_supervisors_remediation.rows ?? []) | length > 0
}}"
then:
- id: warn_remaining_unhealthy
type: io.kestra.plugin.core.log.Log
description: Log warning that one or more supervisors require further
investigation or upstream partition repair.
message: "Warning: {{ (outputs.verify_supervisors_remediation.rows ?? []) |
length }} supervisor(s) remain unhealthy following reset.
Inspect Kafka broker lag and Druid worker task logs."
else:
- id: log_remediation_success
type: io.kestra.plugin.core.log.Log
description: Confirm that all remediated supervisors have successfully recovered
to healthy running state.
message: "All targeted Apache Druid supervisors successfully recovered to
healthy state."
- id: notify_if_unhealthy
type: io.kestra.plugin.core.flow.If
description: Only post to Slack when at least one supervisor is actually
unhealthy, so a clean hourly poll produces no notification noise.
condition: "{{ outputs.triage_supervisor_failures.vars.unhealthy_count > 0 }}"
then:
- id: dispatch_slack_notification
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatch structured incident triage and remediation report to Slack.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {
"text": "*Apache Druid Ingestion Supervisor Health & Recovery Report*\n" ~ outputs.triage_supervisor_failures.vars.summary_markdown ~ "\n\n*Execution Mode:* dry_run=" ~ inputs.dry_run ~ ", auto_reset=" ~ inputs.auto_reset ~ " (Execution: `" ~ execution.id ~ "`)"
} | toJson }}
errors:
- id: alert_on_flow_error
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatch emergency alert to Slack if an unexpected execution error occurs.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: >-
{{ {
"text": ":rotating_light: *Flow Execution Failed*: `druid-supervisor-stalled-ingestion-auto-reset-guard` (Execution: `" ~ execution.id ~ "`). Failed to complete supervisor health scan or remediation pass. Check Druid cluster reachability and Overlord credentials."
} | toJson }}