id: teamcity-build-queue-stall-gate
namespace: company.team
description: |
TeamCity queues that stall leave pending builds sitting for hours while
nobody notices the artifact never arrives. An observer POSTs a queue
snapshot with each build's state and queued duration to a keyed webhook,
Python scores every queued build against a configurable SLA, and an If
escalates only when builds have waited past it. Stalled queues alert Slack
with the offending build types and can fail the run, while healthy or
unreadable queues are logged. The verdict, the stall count, the oldest wait
and the stalled build rows are published as outputs.
triggers:
- id: on_queue_snapshot
type: io.kestra.plugin.core.trigger.Webhook
description: A TeamCity observer or polling job POSTs the build queue snapshot
here so the stall gate runs as soon as the queue is captured.
key: "{{ secret('TEAMCITY_QUEUE_WEBHOOK_KEY') }}"
- id: hourly_queue_sweep
type: io.kestra.plugin.core.trigger.Schedule
description: Hourly fallback net that rescores the staged queue snapshot,
shipped disabled until an operator switches it on.
cron: "0 * * * *"
disabled: true
inputs:
- id: queue_sla_minutes
type: INT
defaults: 30
description: Minutes a build may sit in the queued state before the gate counts
it as stalled.
- id: server_name
type: STRING
defaults: "teamcity.example.internal:8111"
description: TeamCity server address echoed in alerts so estates running more
than one server stay distinguishable.
- id: fail_on_stall
type: BOOL
defaults: true
description: Whether a stalled queue turns the execution red after the Slack
alert, flip to false for report only runs.
tasks:
# --- 1. queue workspace ---
- id: queue_workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the staged queue snapshot and the scorer
read the same file for the whole run.
tasks:
# --- 2. queue fixture ---
- id: stage_queue_snapshot
type: io.kestra.plugin.scripts.shell.Commands
description: Write a TeamCity queue snapshot with a heredoc, three queued builds
where one has waited past the SLA plus a running build the scorer must
ignore, so trial runs always have a queue to read.
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
entryPoint: []
containerImage: alpine:3.20
commands:
- |
set -u
cat > teamcity_queue.json <<'JSON'
{
"project": "platform-core",
"builds": [
{"id": 4312, "build_type": "Nightly Integration Tests", "state": "queued", "queued_minutes": 47},
{"id": 4313, "build_type": "Deploy Service Catalog", "state": "queued", "queued_minutes": 4},
{"id": 4314, "build_type": "Agent Health Probe", "state": "queued", "queued_minutes": 12},
{"id": 4315, "build_type": "Nightly Performance Suite", "state": "running", "queued_minutes": 9}
]
}
JSON
echo "staged $(wc -c < teamcity_queue.json) bytes of queue json"
# --- 3. queue score ---
- id: score_queue
type: io.kestra.plugin.scripts.python.Script
description: Keep the builds in the queued state, clamp negative waits to zero,
flag every build whose wait reached the SLA, and emit the verdict, the
stall count, the oldest wait and the stalled rows through the outputs
protocol.
containerImage: python:3.12-slim
env:
QUEUE_JSON: "{{ trigger.body ?? '' }}"
QUEUE_SLA_MINUTES: "{{ inputs.queue_sla_minutes }}"
script: |
import json
import os
DEFAULT_QUEUE = """
{
"project": "platform-core",
"builds": [
{"id": 4312, "build_type": "Nightly Integration Tests", "state": "queued", "queued_minutes": 47},
{"id": 4313, "build_type": "Deploy Service Catalog", "state": "queued", "queued_minutes": 4},
{"id": 4314, "build_type": "Agent Health Probe", "state": "queued", "queued_minutes": 12},
{"id": 4315, "build_type": "Nightly Performance Suite", "state": "running", "queued_minutes": 9}
]
}
"""
def as_int(value, fallback=0):
try:
return int(value)
except (TypeError, ValueError):
try:
return int(float(value))
except (TypeError, ValueError):
return fallback
raw = (os.environ.get("QUEUE_JSON") or "").strip() or DEFAULT_QUEUE.strip()
sla = max(1, as_int(os.environ.get("QUEUE_SLA_MINUTES"), 30))
outputs = {
"queue_ok": False,
"queue_status": "UNKNOWN",
"project": "unknown",
"queued_count": 0,
"stalled_count": 0,
"oldest_queued_minutes": 0,
"stalled_builds": [],
}
try:
document = json.loads(raw)
except ValueError:
document = None
if isinstance(document, dict):
builds = document.get("builds")
if not isinstance(builds, list):
builds = []
queued = []
stalled = []
oldest = 0
for build in builds:
if not isinstance(build, dict):
continue
if str(build.get("state") or "").strip().lower() != "queued":
continue
minutes = max(0, as_int(build.get("queued_minutes")))
row = {
"id": as_int(build.get("id"), -1),
"build_type": str(build.get("build_type") or "unknown"),
"queued_minutes": minutes,
"stalled": minutes >= sla,
}
queued.append(row)
if minutes > oldest:
oldest = minutes
if row["stalled"]:
stalled.append(row)
outputs.update({
"queue_ok": True,
"queue_status": "STALLED" if stalled else "HEALTHY",
"project": str(document.get("project") or "unknown"),
"queued_count": len(queued),
"stalled_count": len(stalled),
"oldest_queued_minutes": oldest,
"stalled_builds": stalled,
})
print("queue_ok=%s status=%s queued=%d stalled=%d oldest=%d sla=%d" % (
outputs["queue_ok"], outputs["queue_status"], outputs["queued_count"],
outputs["stalled_count"], outputs["oldest_queued_minutes"], sla))
print("::" + json.dumps({"outputs": outputs}) + "::")
# --- 4. stall gate ---
- id: stall_gate
type: io.kestra.plugin.core.flow.If
description: Branch on a parseable queue that actually stalled, so alerts and
failure fire only when a build waited past the SLA.
condition: "{{ outputs.score_queue.vars.queue_ok and
outputs.score_queue.vars.stalled_count > 0 }}"
then:
# --- 5. stall escalation ---
- id: alert_stall
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the server, the stalled build count, the oldest wait and the
stalled build types so the on call can free agents or rebalance the
queue.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "TeamCity queue STALL on {{ inputs.server_name }} - {{ outputs.score_queue.vars.stalled_count }} build(s) pending past the {{ inputs.queue_sla_minutes }} minute SLA, oldest wait {{ outputs.score_queue.vars.oldest_queued_minutes }} minutes. Stalled builds {{ outputs.score_queue.vars.stalled_builds | map(attribute='build_type') | join(', ') }}. Agents are offline or the queue is starved. Execution {{ execution.id }}."
}
- id: enforce_gate
type: io.kestra.plugin.core.flow.If
description: Apply the fail_on_stall policy, turning the run red for gating
pipelines and staying report only when the input is flipped off.
condition: "{{ inputs.fail_on_stall }}"
then:
- id: fail_execution
type: io.kestra.plugin.core.execution.Fail
description: Fail the execution so the pipeline watching this gate stops instead
of letting the queue drain silently.
errorMessage: "TeamCity queue stalled with {{
outputs.score_queue.vars.stalled_count }} build(s) past the {{
inputs.queue_sla_minutes }} minute SLA, oldest wait {{
outputs.score_queue.vars.oldest_queued_minutes }} minutes."
else:
- id: log_gate_softened
type: io.kestra.plugin.core.log.Log
description: Record that the queue stalled but the fail policy is off, keeping
the run green for report only estates.
message: "TeamCity queue stall on {{ inputs.server_name }} not enforced -
fail_on_stall is false, {{ outputs.score_queue.vars.stalled_count
}} stalled build(s) alerted only."
else:
- id: log_queue_healthy
type: io.kestra.plugin.core.log.Log
description: Record the healthy or unreadable outcome so a quiet queue still
leaves evidence the gate ran.
message: "TeamCity queue on {{ inputs.server_name }} clear - {{
outputs.score_queue.vars.queued_count }} queued build(s), none past
the {{ inputs.queue_sla_minutes }} minute SLA, oldest wait {{
outputs.score_queue.vars.oldest_queued_minutes }} minutes."
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: stalled_count
type: INT
description: Number of queued builds whose wait reached the SLA, for example 1
when only the 47 minute nightly sat past the limit.
value: "{{ outputs.score_queue.vars.stalled_count }}"
- id: oldest_queued_minutes
type: INT
description: Longest wait among the queued builds in the snapshot, in minutes,
whether or not it stalled.
value: "{{ outputs.score_queue.vars.oldest_queued_minutes }}"
- id: queue_status
type: STRING
description: Verdict string for the snapshot, one of STALLED, HEALTHY or UNKNOWN
when the posted body could not be parsed.
value: "{{ outputs.score_queue.vars.queue_status }}"
- id: queued_count
type: INT
description: Builds found in the queued state in the scored snapshot, excluding
running or finished builds.
value: "{{ outputs.score_queue.vars.queued_count }}"
- id: stalled_builds
type: ARRAY
description: Rows for every stalled build with id, build type, queued minutes
and the stalled flag for ticket automation.
value: "{{ outputs.score_queue.vars.stalled_builds }}"