id: patroni-planned-switchover-gate
namespace: company.team
description: |
A safe, approved Patroni switchover for planned maintenance (OS patching, a minor upgrade, moving the primary).
The flow reads the cluster from the Patroni REST API and refuses unless the candidate is streaming, on the
leader's timeline and within the lag limit. It asks for approval, checks everything again (the cluster can change
while it waits), calls POST /switchover, then verifies the new leader, the timeline increment and that every
replica follows the new leader.
triggers:
- id: maintenance_window
type: io.kestra.plugin.core.trigger.Webhook
description: Let a change-management tool request the switchover; a person still
approves it.
key: "{{ secret('PATRONI_SWITCHOVER_WEBHOOK_KEY') }}"
concurrency:
limit: 1
behavior: QUEUE
inputs:
- id: patroni_url
type: STRING
defaults: http://pg-node-1:8008
description: REST API of any cluster member.
- id: candidate
type: STRING
required: false
validator: ^[A-Za-z0-9_.-]*$
description: Member to promote. Empty picks the streaming replica with the least lag.
- id: max_lag_bytes
type: INT
defaults: 1048576
description: Refuse when the candidate is further behind the leader than this.
Keep it at or below Patroni's maximum_lag_on_failover.
- id: approval_timeout
type: DURATION
defaults: PT1H
description: No decision within this time means no switchover.
- id: verify_timeout
type: DURATION
defaults: PT2M
description: How long the new topology may take to settle (new leader, timeline
+ 1, replicas streaming).
variables:
checks: |
(.members | map(select(.role == "leader")) | first) as $l
| (.members | map(select(.role != "leader"))) as $r
| (if "CAND" == "" then ($r | map(select(.state == "streaming" and ((.tags.nofailover // false) | not))) | sort_by(if (.lag | type) == "number" then .lag else 1e18 end) | first) else ($r | map(select(.name == "CAND")) | first) end) as $c
| {leader: ($l.name // ""), timeline: ($l.timeline // 0), candidate: ($c.name // "CAND"), candidate_lag: ($c.lag // "unknown"),
members: (.members | map(.name + " " + .role + " " + .state + (if (.lag | type) == "number" then " lag " + (.lag | tostring) else "" end)) | join(", ")),
problems: [
(if $l == null then "the cluster has no leader" else empty end),
(if (.pause // false) then "the cluster is paused (maintenance mode), Patroni would not manage the switchover" else empty end),
(if (.scheduled_switchover // null) != null then "a switchover is already scheduled" else empty end),
(if $c == null then "no streaming replica " + ("CAND" | if . == "" then "to promote" else "named CAND" end)
elif $c.state != "streaming" then "candidate " + $c.name + " is " + $c.state + ", not streaming"
elif ($c.lag | type) != "number" then "candidate " + $c.name + " lag is unknown"
elif $c.lag > MAXLAG then "candidate " + $c.name + " is " + ($c.lag | tostring) + " bytes behind the leader (limit MAXLAG)"
else empty end),
(if $c != null and $l != null and $c.state == "streaming" and $c.timeline != $l.timeline then "candidate " + $c.name + " is on timeline " + ($c.timeline | tostring) + ", the leader on " + ($l.timeline | tostring) else empty end),
(if ($c.tags.nofailover // false) then "candidate " + $c.name + " has the nofailover tag" else empty end)
]}
settled: |
(.members | map(select(.role == "leader")) | first) as $l
| {leader: ($l.name // ""), timeline: ($l.timeline // 0),
followers: [.members[] | select(.role != "leader")] | length,
streaming: [.members[] | select(.role != "leader" and .state == "streaming" and .timeline == $l.timeline)] | length,
members: (.members | map(.name + " " + .role + " " + .state + " tl " + (.timeline | tostring)) | join(", "))}
tasks:
- id: read_cluster
type: io.kestra.plugin.core.http.Request
description: GET /cluster is served from the DCS (etcd, Consul, ZooKeeper). If
the DCS is down, this fails and nothing else runs.
uri: "{{ inputs.patroni_url }}/cluster"
options:
timeout:
connectTimeout: PT5S
readIdleTimeout: PT10S
- id: plan
type: io.kestra.plugin.core.output.OutputValues
values:
checks: "{{ outputs.read_cluster.body | jq(vars.checks | replace({'CAND':
inputs.candidate ?? '', 'MAXLAG': inputs.max_lag_bytes ~ ''})) | first |
toJson }}"
- id: precheck
type: io.kestra.plugin.core.flow.If
condition: "{{ (fromJson(outputs.plan.values.checks).problems | length) > 0 }}"
then:
- id: refuse
type: io.kestra.plugin.core.execution.Fail
errorMessage: "SWITCHOVER REFUSED before approval: {{
fromJson(outputs.plan.values.checks).problems | join('; ') }}.
Cluster: {{ fromJson(outputs.plan.values.checks).members }}"
- id: request_approval
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
Patroni switchover ready: {{ fromJson(outputs.plan.values.checks).leader }} -> {{ fromJson(outputs.plan.values.checks).candidate }} (candidate lag {{ fromJson(outputs.plan.values.checks).candidate_lag }} bytes, timeline {{ fromJson(outputs.plan.values.checks).timeline }}).
Cluster: {{ fromJson(outputs.plan.values.checks).members }}.
Writes stop for a few seconds while the leader changes. Resume execution {{ execution.id }} in Kestra to approve.
- id: approve
type: io.kestra.plugin.core.flow.Pause
pauseDuration: "{{ inputs.approval_timeout }}"
behavior: RESUME
onResume:
- id: switch_now
type: BOOL
displayName: Switch over now?
defaults: false
- id: note
type: STRING
- id: decision
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve.onResume.switch_now ?? false }}"
then:
- id: read_cluster_again
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.patroni_url }}/cluster"
options:
timeout:
connectTimeout: PT5S
readIdleTimeout: PT10S
- id: plan_again
type: io.kestra.plugin.core.output.OutputValues
values:
checks: "{{ outputs.read_cluster_again.body | jq(vars.checks | replace({'CAND':
fromJson(outputs.plan.values.checks).candidate, 'MAXLAG':
inputs.max_lag_bytes ~ ''})) | first | toJson }}"
- id: recheck
type: io.kestra.plugin.core.flow.If
description: The approval may be an hour old. Same checks, same leader, same
candidate, or no switchover.
condition: "{{ (fromJson(outputs.plan_again.values.checks).problems | length) >
0 or fromJson(outputs.plan_again.values.checks).leader !=
fromJson(outputs.plan.values.checks).leader }}"
then:
- id: refuse_after_approval
type: io.kestra.plugin.core.execution.Fail
errorMessage: "SWITCHOVER REFUSED after approval, the cluster changed while
waiting: {% if fromJson(outputs.plan_again.values.checks).leader
!= fromJson(outputs.plan.values.checks).leader %}the leader is now
{{ fromJson(outputs.plan_again.values.checks).leader }}; {% endif
%}{{ fromJson(outputs.plan_again.values.checks).problems | join(';
') }}. Cluster: {{
fromJson(outputs.plan_again.values.checks).members }}"
- id: switchover
type: io.kestra.plugin.core.http.Request
method: POST
uri: "{{ inputs.patroni_url }}/switchover"
contentType: application/json
body: "{{ {'leader': fromJson(outputs.plan.values.checks).leader, 'candidate':
fromJson(outputs.plan.values.checks).candidate} | toJson }}"
options:
allowFailed: true
auth:
type: BASIC
username: "{{ secret('PATRONI_API_USERNAME') }}"
password: "{{ secret('PATRONI_API_PASSWORD') }}"
timeout:
connectTimeout: PT5S
readIdleTimeout: PT2M
- id: switchover_answer
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.switchover.code != 200 }}"
then:
- id: who_leads_now
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.patroni_url }}/cluster"
options:
allowFailed: true
- id: switchover_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: "SWITCHOVER FAILED: Patroni answered HTTP {{
outputs.switchover.code }}: {{ outputs.switchover.body ?? '' }}.
Leader now: {{ outputs.who_leads_now.code == 200 ?
(outputs.who_leads_now.body | jq(vars.settled) | first).members :
'cluster state unreadable' }}"
- id: verify
type: io.kestra.plugin.core.flow.LoopUntil
description: Until the candidate leads on timeline + 1 and every other member
streams from it.
condition: "{{ fromJson(outputs.settle.values.state).leader ==
fromJson(outputs.plan.values.checks).candidate and
fromJson(outputs.settle.values.state).timeline ==
fromJson(outputs.plan.values.checks).timeline + 1 and
fromJson(outputs.settle.values.state).streaming ==
fromJson(outputs.settle.values.state).followers }}"
failOnMaxReached: true
checkFrequency:
interval: PT3S
maxDuration: "{{ inputs.verify_timeout }}"
tasks:
- id: read_topology
type: io.kestra.plugin.core.http.Request
uri: "{{ inputs.patroni_url }}/cluster"
options:
allowFailed: true
- id: settle
type: io.kestra.plugin.core.output.OutputValues
values:
state: "{{ (outputs.read_topology.code == 200 ? (outputs.read_topology.body |
jq(vars.settled) | first) : {'leader': '', 'timeline': 0,
'followers': 1, 'streaming': 0, 'members': 'HTTP ' ~
outputs.read_topology.code}) | toJson }}"
- id: record
type: io.kestra.plugin.core.kv.Set
key: patroni_last_switchover
kvType: JSON
value: "{{ {'at': execution.startDate, 'from':
fromJson(outputs.plan.values.checks).leader, 'to':
fromJson(outputs.settle.values.state).leader, 'timeline':
fromJson(outputs.settle.values.state).timeline, 'note':
outputs.approve.onResume.note ?? ''} | toJson }}"
- id: report_done
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "Patroni switchover DONE: {{
fromJson(outputs.plan.values.checks).leader }} -> {{
fromJson(outputs.settle.values.state).leader }}, timeline {{
fromJson(outputs.plan.values.checks).timeline }} -> {{
fromJson(outputs.settle.values.state).timeline }}, {{
fromJson(outputs.settle.values.state).streaming }} of {{
fromJson(outputs.settle.values.state).followers }} replicas streaming
from the new leader. {{ outputs.switchover.body }}{% if
(outputs.approve.onResume.note ?? '') != '' %} Note: {{
outputs.approve.onResume.note }}{% endif %}"
else:
- id: report_not_approved
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: "Patroni switchover NOT done ({% if
outputs.approve.onResume.switch_now is defined %}declined{% else %}no
decision within the approval window{% endif %}{% if
(outputs.approve.onResume.note ?? '') != '' %}: {{
outputs.approve.onResume.note }}{% endif %}). {{
fromJson(outputs.plan.values.checks).leader }} is still the leader."
errors:
- id: alert_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
messageText: |
Patroni switchover run {{ execution.id }} stopped{% if errorLogs() | length > 0 %} at `{{ errorLogs()[0]['taskId'] }}`: {{ errorLogs() | jq('([.[] | select(.message | test("SWITCHOVER"))] + .)[0].message | split("\n")[0]') | first }}{% endif %}
{% if (errorLogs() | length > 0) and errorLogs()[0]['taskId'] == 'read_cluster' %}{% if (errorLogs()[0]['message'] contains 'timed out') or (errorLogs()[0]['message'] contains 'failed to respond') or (errorLogs()[0]['message'] contains '503') %}Patroni answers GET /cluster from the DCS, so no answer here usually means etcd (or Consul, ZooKeeper) is unreachable.{% else %}The Patroni REST API at {{ inputs.patroni_url }} could not be reached.{% endif %} Nothing was attempted.{% else %}The leader was not changed by this run unless the message says otherwise.{% endif %}