id: rqlite-dead-raft-node-removal-guard
namespace: company.data
description: |
Audit an rqlite cluster's Raft node list for members that have been unreachable
across multiple consecutive checks, a permanently dead node left in the
configuration silently degrades quorum fault tolerance. Track unreachability
persistence in Kestra KV, pause for operator approval, remove the dead node via
rqlite's HTTP API, and verify it no longer appears in the cluster.
inputs:
- id: rqlite_url
type: STRING
displayName: rqlite HTTP API URL
description: Base HTTP(S) URL of an rqlite node's HTTP API (default port 4001),
e.g. http://rqlite.internal:4001. Any node can be queried; /nodes returns
the view from whichever node answers.
defaults: "http://localhost:4001"
- id: rqlite_username
type: STRING
displayName: rqlite Username
description: Username for rqlite HTTP Basic authentication. Leave the username
and password secrets empty if the cluster runs without auth enabled.
defaults: "{{ secret('RQLITE_USERNAME') }}"
- id: rqlite_password
type: STRING
displayName: rqlite Password
description: Password for rqlite HTTP Basic authentication.
defaults: "{{ secret('RQLITE_PASSWORD') }}"
- id: min_consecutive_unreachable_runs
type: INT
displayName: Minimum Consecutive Unreachable Runs
description: Number of consecutive audit passes a node must be reported
unreachable before it is treated as permanently dead rather than a
transient network blip.
defaults: 3
- id: max_removals_per_run
type: INT
displayName: Max Removals Per Run
description: Safety ceiling on the number of nodes removed from the Raft
configuration in a single execution pass. When more nodes qualify, the
longest-unreachable ones are prioritized and the rest deferred to the next
run.
defaults: 1
- id: cursor_key
type: STRING
displayName: KV Cursor Key
description: Kestra KV key used to persist per-node unreachability trend state
across runs.
defaults: "rqlite_node_reachability_tracker"
- id: dry_run
type: BOOL
displayName: Dry Run Mode
description: When true, audits node reachability and logs the proposed removal
without mutating the Raft cluster configuration.
defaults: true
- id: auto_remediate
type: BOOL
displayName: Auto Remediate
description: When true and dry_run is false, pauses for operator approval and
then calls the rqlite remove-node API on verified dead nodes.
defaults: false
triggers:
- id: periodic_node_audit
type: io.kestra.plugin.core.trigger.Schedule
description: Audit rqlite cluster node reachability every 15 minutes. Shipped
disabled so the flow can be verified manually in safe mode first.
cron: "*/15 * * * *"
disabled: true
- id: on_demand_node_audit_webhook
type: io.kestra.plugin.core.trigger.Webhook
description: Authenticated HTTP endpoint invoked by monitoring alerts or
incident runbooks.
key: "{{ secret('RQLITE_GUARD_WEBHOOK_KEY') }}"
tasks:
- id: validate_inputs
type: io.kestra.plugin.core.execution.Assert
description: Assert operational thresholds satisfy sanity constraints before
querying the rqlite HTTP API.
conditions:
- "{{ inputs.min_consecutive_unreachable_runs >= 1 }}"
- "{{ inputs.max_removals_per_run >= 1 }}"
errorMessage: "Invalid configuration: min_consecutive_unreachable_runs and
max_removals_per_run must both be at least 1."
- id: fetch_nodes
type: io.kestra.plugin.core.http.Request
description: Fetch the cluster's Raft node list, including reachability, voter,
and leader status, from rqlite's /nodes endpoint.
uri: "{{ inputs.rqlite_url }}/nodes"
method: GET
headers:
Accept: application/json
options:
auth:
type: BASIC
username: "{{ inputs.rqlite_username }}"
password: "{{ inputs.rqlite_password }}"
- id: triage_nodes
type: io.kestra.plugin.scripts.python.Script
description: Classify nodes into removal candidates, deferred candidates, and
healthy, diffed against historical KV state, and apply the
max_removals_per_run safety cap.
containerImage: python:3.11-slim
env:
NODES_BODY: "{{ outputs.fetch_nodes.body is defined ? outputs.fetch_nodes.body :
'[]' }}"
MIN_CONSECUTIVE_UNREACHABLE_RUNS: "{{ inputs.min_consecutive_unreachable_runs }}"
MAX_REMOVALS_PER_RUN: "{{ inputs.max_removals_per_run }}"
EXECUTION_ID: "{{ execution.id }}"
PREVIOUS_STATE_JSON: "{{ kv(inputs.cursor_key, errorOnMissing=false) ?? '{}' }}"
script: |
import json
import os
from datetime import datetime, timezone
try:
from kestra import Kestra
except ImportError:
Kestra = None
now_iso = datetime.now(timezone.utc).isoformat()
nodes_body_raw = os.environ.get("NODES_BODY", "[]")
min_consecutive_unreachable_runs = int(os.environ.get("MIN_CONSECUTIVE_UNREACHABLE_RUNS", "3"))
max_removals_per_run = int(os.environ.get("MAX_REMOVALS_PER_RUN", "1"))
execution_id = os.environ.get("EXECUTION_ID", "manual")
prev_state_raw = os.environ.get("PREVIOUS_STATE_JSON", "{}")
try:
prev_state = json.loads(prev_state_raw) if prev_state_raw.strip() else {}
except Exception:
prev_state = {}
try:
nodes_data = json.loads(nodes_body_raw) if nodes_body_raw.strip() else []
except Exception:
nodes_data = []
# GET /nodes can return either a JSON array (older rqlite) or an object keyed
# by node ID (newer rqlite "ver=2" style); handle both shapes defensively
# rather than assuming one.
if isinstance(nodes_data, dict):
node_list = list(nodes_data.values())
elif isinstance(nodes_data, list):
node_list = nodes_data
else:
node_list = []
new_state_snapshot = {}
unreachable_pending = []
healthy_nodes = []
for node in node_list:
if not isinstance(node, dict):
continue
node_id = str(node.get("id", ""))
if not node_id:
continue
reachable = bool(node.get("reachable", True))
is_voter = bool(node.get("voter", False))
is_leader = bool(node.get("leader", False))
addr = str(node.get("addr", ""))
api_addr = str(node.get("api_addr", ""))
error_msg = str(node.get("error", ""))
prev_entry = prev_state.get(node_id, {})
prev_consecutive = int(prev_entry.get("consecutive_unreachable_runs", 0))
# A leader must have answered our request to be in this list at all, so
# it is reachable by definition; the explicit check is a second,
# independent guard against ever targeting it for removal.
is_unreachable = (not reachable) and (not is_leader)
consecutive_unreachable_runs = prev_consecutive + 1 if is_unreachable else 0
new_state_snapshot[node_id] = {
"reachable": reachable,
"voter": is_voter,
"consecutive_unreachable_runs": consecutive_unreachable_runs,
"last_evaluated_at": now_iso,
}
if is_unreachable and consecutive_unreachable_runs >= min_consecutive_unreachable_runs:
unreachable_pending.append({
"node_id": node_id,
"addr": addr,
"api_addr": api_addr,
"voter": is_voter,
"consecutive_unreachable_runs": consecutive_unreachable_runs,
"error": error_msg,
})
elif is_unreachable:
healthy_nodes.append({"node_id": node_id, "addr": addr, "note": "unreachable but below consecutive-run threshold"})
else:
healthy_nodes.append({"node_id": node_id, "addr": addr, "note": "reachable"})
# Cap at max_removals_per_run, oldest-standing (most consecutive runs) first.
unreachable_pending.sort(key=lambda n: n["consecutive_unreachable_runs"], reverse=True)
removal_candidates = unreachable_pending[:max_removals_per_run]
deferred_candidates = unreachable_pending[max_removals_per_run:]
has_candidates = len(removal_candidates) > 0
overall_status = "WARNING" if has_candidates else ("INFO" if deferred_candidates else "HEALTHY")
summary_lines = [
f"- `{n['node_id']}` ({n['addr']}): unreachable for {n['consecutive_unreachable_runs']} consecutive audit(s), voter={n['voter']}"
for n in removal_candidates
]
if deferred_candidates:
summary_lines.append(f"Deferred by max_removals_per_run cap: {len(deferred_candidates)} additional unreachable node(s) not included this pass.")
summary_text = (
f"rqlite Dead Node Guard: {overall_status} | "
f"Audited {len(node_list)} node(s). Removal candidates: {len(removal_candidates)}. "
f"Deferred: {len(deferred_candidates)}."
)
print(summary_text)
audit_manifest = {
"overall_status": overall_status,
"nodes_audited": len(node_list),
"removal_candidate_count": len(removal_candidates),
"deferred_count": len(deferred_candidates),
"removal_candidates": removal_candidates,
"execution_id": execution_id,
"evaluated_at": now_iso,
"summary": summary_text,
}
output_data = {
"has_removal_candidates": has_candidates,
"removal_candidate_count": len(removal_candidates),
"overall_status": overall_status,
"removal_candidates": removal_candidates,
"summary": summary_text,
"summary_details": "\n".join(summary_lines) if summary_lines else "None",
"new_state_snapshot": new_state_snapshot,
"audit_manifest": audit_manifest,
}
if Kestra:
Kestra.outputs(output_data)
else:
print("::" + json.dumps({"outputs": output_data}) + "::")
- id: save_tracker_kv
type: io.kestra.plugin.core.kv.Set
description: Persist updated per-node unreachability trend into Kestra KV for
cross-run differential tracking.
key: "{{ inputs.cursor_key }}"
value: "{{ outputs.triage_nodes.vars.new_state_snapshot | toJson }}"
kvType: JSON
- id: evaluate_dead_nodes
type: io.kestra.plugin.core.flow.If
description: Branch execution based on whether any node qualifies for removal
after the consecutive-run confirmation and the per-run cap.
condition: "{{ outputs.triage_nodes.vars.has_removal_candidates == true }}"
then:
- id: dispatch_slack_alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Deliver triage notification to Slack detailing nodes qualified for
removal from the Raft configuration.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"attachments": [
{
"color": "warning",
"title": ":warning: rqlite Dead Raft Node Alert",
"text": "*Status:* `{{ outputs.triage_nodes.vars.overall_status }}`\n*Cluster:* `{{ inputs.rqlite_url }}`\n*Removal Candidates:* {{ outputs.triage_nodes.vars.removal_candidate_count }}\n*Mode:* auto_remediate={{ inputs.auto_remediate }}, dry_run={{ inputs.dry_run }}\n*Execution:* `{{ execution.id }}`\n\n*Details:*\n{{ outputs.triage_nodes.vars.summary_details }}\n\n*Summary:* {{ outputs.triage_nodes.vars.summary }}"
}
]
}
- id: remediation_mode_gate
type: io.kestra.plugin.core.flow.If
description: Gate automated remediation behind auto_remediate and dry_run
configuration flags.
condition: "{{ inputs.auto_remediate and not inputs.dry_run }}"
then:
- id: pause_for_operator_approval
type: io.kestra.plugin.core.flow.Pause
description: Pause workflow execution for operator review before removing nodes
from the Raft cluster configuration. Resume to apply or kill to
abort; no timeout is set so this waits indefinitely for a human
decision.
onResume:
- id: approved
type: BOOL
defaults: false
description: Set true to confirm the rqlite remove-node call should be issued
against the flagged dead nodes.
- id: branch_on_approval
type: io.kestra.plugin.core.flow.If
description: Execute removal only if explicit human approval was provided during
the pause gate.
condition: "{{ outputs.pause_for_operator_approval.onResume.approved == true }}"
then:
- id: remove_dead_nodes
type: io.kestra.plugin.core.flow.Loop
description: Iterate sequentially over removal candidates, remove each from the
Raft configuration, and verify it no longer appears in the
node list.
concurrencyLimit: 1
values: "{{ outputs.triage_nodes.vars.removal_candidates | toJson }}"
tasks:
- id: remove_node
type: io.kestra.plugin.core.http.Request
description: Call rqlite's DELETE /remove endpoint with the dead node's ID to
remove it from the Raft cluster configuration.
uri: "{{ inputs.rqlite_url }}/remove"
method: DELETE
contentType: application/json
body: "{{ {'id': fromJson(item.value).node_id} | toJson }}"
options:
auth:
type: BASIC
username: "{{ inputs.rqlite_username }}"
password: "{{ inputs.rqlite_password }}"
- id: settle_removal
type: io.kestra.plugin.core.flow.Sleep
description: Allow the Raft configuration change to propagate before re-checking
the node list.
duration: PT5S
- id: verify_node_removed
type: io.kestra.plugin.core.http.Request
description: Re-fetch the node list to confirm the removed node no longer
appears in it.
uri: "{{ inputs.rqlite_url }}/nodes"
method: GET
headers:
Accept: application/json
options:
auth:
type: BASIC
username: "{{ inputs.rqlite_username }}"
password: "{{ inputs.rqlite_password }}"
- id: assert_node_removed
type: io.kestra.plugin.core.flow.If
description: Fail loudly if the node still appears in the cluster's node list
after the remove call. Passes the target ID alongside the
node list as data rather than interpolating it into the jq
program string, so a node ID containing a quote or other
jq-special character cannot break the expression.
condition: "{{ ({'nodes': fromJson(outputs.verify_node_removed.body),
'target_id': fromJson(item.value).node_id} | toJson |
jq('. as $in | any($in.nodes[]; .id == $in.target_id)') |
first) == true }}"
then:
- id: fail_node_still_present
type: io.kestra.plugin.core.execution.Fail
description: Abort with explicit error details identifying the node that was not
actually removed.
errorMessage: "rqlite still reports node {{ fromJson(item.value).node_id }} ({{
fromJson(item.value).addr }}) in /nodes after a remove
call. Check rqlite leader connectivity and whether the
remove request reached the leader."
else:
- id: log_node_removed
type: io.kestra.plugin.core.log.Log
description: Record successful removal for this node.
message: "Removed dead node {{ fromJson(item.value).node_id }} ({{
fromJson(item.value).addr }}) from the Raft
configuration after {{
fromJson(item.value).consecutive_unreachable_runs }}
consecutive unreachable audit(s)."
- id: save_recovery_audit_kv
type: io.kestra.plugin.core.kv.Set
description: Persist the remediation audit manifest into Kestra KV for incident
review.
key: "rqlite_node_removal_audit_{{ execution.id }}"
value: "{{ outputs.triage_nodes.vars.audit_manifest | toJson }}"
kvType: JSON
- id: notify_resolution_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatch resolution confirmation to Slack once all approved dead
nodes have been removed and verified.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"attachments": [
{
"color": "#2EB67D",
"title": ":white_check_mark: rqlite Dead Raft Node(s) Removed",
"text": "*Cluster:* `{{ inputs.rqlite_url }}`\n*Nodes Removed:* `{{ outputs.triage_nodes.vars.removal_candidate_count }}`\n*Execution:* `{{ execution.id }}`"
}
]
}
else:
- id: log_approval_declined
type: io.kestra.plugin.core.log.Log
description: Record that the operator declined approval for removing dead nodes.
message: "Operator declined approval for rqlite dead node removal. Flagged nodes
were left in the Raft configuration."
else:
- id: log_dry_run_plan
type: io.kestra.plugin.core.log.Log
description: Log the planned removal without mutating the Raft cluster
configuration.
message: |
Dry run active or auto_remediate disabled (dry_run={{ inputs.dry_run }}, auto_remediate={{ inputs.auto_remediate }}).
Planned removal for {{ outputs.triage_nodes.vars.removal_candidate_count }} node(s):
{{ outputs.triage_nodes.vars.removal_candidates | toJson }}
else:
- id: log_healthy_state
type: io.kestra.plugin.core.log.Log
description: Confirm nominal state when no node qualifies for removal.
message: "rqlite cluster nominal on {{ inputs.rqlite_url }}. No node unreachable
for {{ inputs.min_consecutive_unreachable_runs }}+ consecutive
audits."
errors:
- id: alert_on_workflow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Dispatch emergency alert to Slack if the guard encounters an
unhandled execution error.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"attachments": [
{
"color": "danger",
"title": ":rotating_light: rqlite Dead Node Guard Execution Failed",
"text": "Failed execution `{{ execution.id }}` while auditing or remediating `{{ inputs.rqlite_url }}`. Check rqlite connectivity, credentials, and worker logs."
}
]
}
outputs:
- id: nodes_audited
type: INT
value: "{{ outputs.triage_nodes.vars.audit_manifest.nodes_audited ?? 0 }}"
- id: removal_candidate_count
type: INT
value: "{{ outputs.triage_nodes.vars.removal_candidate_count ?? 0 }}"
- id: status
type: STRING
value: "{{ (outputs.triage_nodes.vars.removal_candidate_count ?? 0) > 0 ?
((inputs.auto_remediate and not inputs.dry_run and
(outputs.pause_for_operator_approval.onResume.approved ?? false)) ?
'REMEDIATED' : 'DEAD_NODES_DETECTED') : 'HEALTHY' }}"