id: cockroachdb-range-underreplication-guard
namespace: company.team
description: |
Find CockroachDB ranges that have fewer replicas than their zone asks for, name the database and
table they belong to. Then it says which of three states the cluster is in: ranges with no quorum,
zones still catching up. The third is a zone config that asks for more replicas than there are live nodes.
The last one never fixes itself. With approval, lower that zone's num_replicas to the live node
count, then read the replication report again and fail the run if the count did not fall.
inputs:
- id: jdbc_url
type: STRING
displayName: JDBC URL
description: Any CockroachDB node. The SQL port is 26257 by default.
defaults: "jdbc:postgresql://localhost:26257/defaultdb?sslmode=require"
- id: include_internal_zones
type: BOOL
displayName: Also fix CockroachDB internal zones
description: >-
CockroachDB asks for 5 replicas on its own system zones, so every cluster
with fewer than 5 nodes reports them as under-replicated. They are always
listed. Turn this on to let the remediation lower them too, which reduces
the durability of cluster metadata.
defaults: false
- id: max_report_age_seconds
type: INT
displayName: Maximum replication report age
description: The replication report is rebuilt every
kv.replication_reports.interval, one minute by default. Fail rather than
audit a report older than this.
defaults: 900
- id: settle_duration
type: DURATION
displayName: Settle time before re-verify
description: How long to wait after the zone change for the next replication
report. Must be longer than kv.replication_reports.interval.
defaults: PT150S
- id: auto_remediate
type: BOOL
displayName: Auto remediate
defaults: false
- id: dry_run
type: BOOL
displayName: Dry run
description: Must be false, together with auto_remediate, before any zone is changed.
defaults: true
variables:
cluster_sql: |
WITH nodes AS (
SELECT count(*) FILTER (WHERE n.is_live)::INT8 AS live_nodes,
count(*) FILTER (WHERE NOT n.is_live AND coalesce(l.membership, 'active') = 'active')::INT8 AS dead_nodes,
count(*) FILTER (WHERE coalesce(l.membership, 'active') != 'active')::INT8 AS leaving_nodes
FROM crdb_internal.gossip_nodes n
LEFT JOIN crdb_internal.gossip_liveness l ON l.node_id = n.node_id
), zc AS (
SELECT target,
coalesce(substring(full_config_sql, 'num_replicas = ([0-9]+)')::INT8, 0) AS num_replicas,
((target LIKE 'RANGE %' AND target != 'RANGE default') OR coalesce(database_name, '') = 'system') AS internal_zone
FROM crdb_internal.zones
), agg AS (
SELECT coalesce(sum(s.total_ranges), 0)::INT8 AS total_ranges,
coalesce(sum(s.unavailable_ranges), 0)::INT8 AS unavailable_ranges,
coalesce(sum(s.under_replicated_ranges), 0)::INT8 AS under_replicated_ranges,
coalesce(sum(s.over_replicated_ranges), 0)::INT8 AS over_replicated_ranges,
max(m.generated) AS generated
FROM system.replication_stats s JOIN system.reports_meta m ON m.id = s.report_id
)
SELECT n.live_nodes, n.dead_nodes, n.leaving_nodes,
a.total_ranges, a.unavailable_ranges, a.under_replicated_ranges, a.over_replicated_ranges,
(SELECT count(*) FROM zc z, nodes nn
WHERE z.num_replicas > nn.live_nodes
AND (NOT z.internal_zone OR {{ inputs.include_internal_zones }}))::INT8 AS impossible_zones,
(SELECT count(*) FROM zc z, nodes nn WHERE z.num_replicas > nn.live_nodes)::INT8 AS impossible_zones_all,
coalesce(extract(EPOCH FROM a.generated)::INT8, -1) AS report_epoch,
coalesce(extract(EPOCH FROM (now() - a.generated))::INT8, -1) AS report_age_seconds
FROM nodes n CROSS JOIN agg a
audit_sql: |
WITH nodes AS (
SELECT count(*) FILTER (WHERE n.is_live)::INT8 AS live_nodes,
count(*) FILTER (WHERE NOT n.is_live AND coalesce(l.membership, 'active') = 'active')::INT8 AS dead_nodes
FROM crdb_internal.gossip_nodes n
LEFT JOIN crdb_internal.gossip_liveness l ON l.node_id = n.node_id
), zc AS (
SELECT zone_id, subzone_id, target,
coalesce(database_name, '') AS database_name,
coalesce(table_name, '') AS table_name,
coalesce(index_name, '') AS index_name,
coalesce(partition_name, '') AS partition_name,
coalesce(substring(full_config_sql, 'num_replicas = ([0-9]+)')::INT8, 0) AS num_replicas,
((target LIKE 'RANGE %' AND target != 'RANGE default') OR coalesce(database_name, '') = 'system') AS internal_zone
FROM crdb_internal.zones
), report AS (
SELECT s.zone_id, s.subzone_id, s.total_ranges, s.unavailable_ranges,
s.under_replicated_ranges, s.over_replicated_ranges
FROM system.replication_stats s
)
SELECT r.zone_id, r.subzone_id,
coalesce(z.target, 'ZONE ' || r.zone_id::STRING) AS zone_target,
coalesce(z.database_name, '') AS database_name,
coalesce(z.table_name, '') AS table_name,
coalesce(z.index_name, '') AS index_name,
coalesce(z.partition_name, '') AS partition_name,
coalesce(z.internal_zone, true) AS internal_zone,
r.total_ranges, r.unavailable_ranges, r.under_replicated_ranges, r.over_replicated_ranges,
coalesce(z.num_replicas, 0) AS num_replicas, n.live_nodes, n.dead_nodes,
CASE
WHEN r.unavailable_ranges > 0 THEN 'UNAVAILABLE'
WHEN coalesce(z.num_replicas, 0) > n.live_nodes THEN 'ZONE_IMPOSSIBLE'
WHEN r.under_replicated_ranges > 0 THEN 'UNDER_REPLICATED_TRANSIENT'
ELSE 'OVER_REPLICATED'
END AS state,
CASE
WHEN coalesce(z.num_replicas, 0) > n.live_nodes AND z.target IS NOT NULL
AND (NOT z.internal_zone OR {{ inputs.include_internal_zones }})
THEN 'ALTER ' || z.target || ' CONFIGURE ZONE USING num_replicas = ' || n.live_nodes::STRING
END AS fix_sql
FROM report r
LEFT JOIN zc z ON z.zone_id = r.zone_id AND z.subzone_id = r.subzone_id
CROSS JOIN nodes n
WHERE r.unavailable_ranges > 0 OR r.under_replicated_ranges > 0
OR r.over_replicated_ranges > 0 OR coalesce(z.num_replicas, 0) > n.live_nodes
ORDER BY r.unavailable_ranges DESC, r.under_replicated_ranges DESC, r.zone_id, r.subzone_id
tables_sql: |
WITH ln AS (
SELECT node_id FROM crdb_internal.gossip_nodes WHERE is_live
), zc AS (
SELECT target, database_name, schema_name, table_name, index_name, partition_name,
substring(full_config_sql, 'num_replicas = ([0-9]+)')::INT8 AS num_replicas
FROM crdb_internal.zones
), dflt AS (
SELECT max(num_replicas) AS num_replicas FROM zc WHERE target = 'RANGE default'
), tz AS (
SELECT database_name, schema_name, table_name, max(num_replicas) AS num_replicas
FROM zc WHERE table_name IS NOT NULL AND index_name IS NULL AND partition_name IS NULL
GROUP BY 1, 2, 3
), dz AS (
SELECT database_name, max(num_replicas) AS num_replicas
FROM zc WHERE database_name IS NOT NULL AND table_name IS NULL GROUP BY 1
), rr AS (
SELECT range_id,
coalesce(database_name, '(cluster internal)') AS database_name,
coalesce(schema_name, '') AS schema_name,
coalesce(table_name, '(system ranges)') AS table_name,
voting_replicas, learner_replicas
FROM [SHOW CLUSTER RANGES WITH TABLES]
), rv AS (
SELECT r.range_id, count(*)::INT8 AS voters,
count(*) FILTER (WHERE ln.node_id IS NOT NULL)::INT8 AS live_voters
FROM (SELECT range_id, unnest(voting_replicas) AS nid FROM rr) r
LEFT JOIN ln ON ln.node_id = r.nid
GROUP BY 1
), rng AS (
SELECT r.range_id, r.database_name, r.schema_name, r.table_name,
coalesce(rv.voters, 0)::INT8 AS voters,
coalesce(rv.live_voters, 0)::INT8 AS live_voters,
coalesce(array_length(r.learner_replicas, 1), 0)::INT8 AS learners,
(r.database_name IN ('system', '(cluster internal)')) AS internal_table
FROM rr r LEFT JOIN rv ON rv.range_id = r.range_id
)
SELECT r.database_name, r.schema_name, r.table_name, r.internal_table,
coalesce(tz.num_replicas, dz.num_replicas, d.num_replicas)::INT8 AS target_replicas,
count(*)::INT8 AS ranges_affected,
min(r.live_voters)::INT8 AS min_live_voters,
max(r.live_voters)::INT8 AS max_live_voters,
min(r.voters)::INT8 AS min_assigned_voters,
sum(r.learners)::INT8 AS learners,
count(*) FILTER (WHERE r.live_voters * 2 <= r.voters)::INT8 AS ranges_without_quorum,
left(string_agg(r.range_id::STRING, ',' ORDER BY r.range_id), 60) AS sample_range_ids
FROM rng r
LEFT JOIN tz ON tz.database_name = r.database_name AND tz.schema_name = r.schema_name AND tz.table_name = r.table_name
LEFT JOIN dz ON dz.database_name = r.database_name
CROSS JOIN dflt d
WHERE r.live_voters < coalesce(tz.num_replicas, dz.num_replicas, d.num_replicas)
GROUP BY 1, 2, 3, 4, 5
ORDER BY ranges_without_quorum DESC, r.internal_table, min_live_voters, ranges_affected DESC, 1, 3
LIMIT 50
tasks:
- id: cluster_before
type: io.kestra.plugin.jdbc.postgresql.Query
description: >-
Read-only. Node liveness from crdb_internal.gossip_nodes and
gossip_liveness, the cluster totals from the replication report. It also
counts how many zones ask for more replicas than there are live nodes.
url: "{{ inputs.jdbc_url }}"
username: "{{ secret('COCKROACHDB_USERNAME') }}"
password: "{{ secret('COCKROACHDB_PASSWORD') }}"
fetchType: FETCH_ONE
sql: "{{ render(vars.cluster_sql) }}"
- id: report_freshness
type: io.kestra.plugin.core.flow.If
description: The whole audit reads one report. A report that was never built
would read as a healthy cluster. So would one far older than its interval.
condition: "{{ outputs.cluster_before.row.report_epoch < 0 or
outputs.cluster_before.row.report_age_seconds >
inputs.max_report_age_seconds }}"
then:
- id: stale_report
type: io.kestra.plugin.core.execution.Fail
errorMessage: "The replication report is {{
outputs.cluster_before.row.report_age_seconds }}s old (report_epoch {{
outputs.cluster_before.row.report_epoch }}; -1 means it was never
built). Check SHOW CLUSTER SETTING kv.replication_reports.interval,
which must not be zero. Check also that the audit role can read
system.replication_stats."
- id: audit
type: io.kestra.plugin.jdbc.postgresql.Query
description: >-
Read-only. One row per zone with a replication problem, classified
UNAVAILABLE, ZONE_IMPOSSIBLE, UNDER_REPLICATED_TRANSIENT or
OVER_REPLICATED. Only ZONE_IMPOSSIBLE gets a fix. Internal zones are fixed
only when include_internal_zones is on.
url: "{{ inputs.jdbc_url }}"
username: "{{ secret('COCKROACHDB_USERNAME') }}"
password: "{{ secret('COCKROACHDB_PASSWORD') }}"
fetchType: FETCH
sql: "{{ render(vars.audit_sql) }}"
- id: affected_tables
type: io.kestra.plugin.jdbc.postgresql.Query
description: >-
Read-only. The replication report is keyed by zone, so a table with no
zone config of its own is counted under RANGE default. This names the
databases and tables whose ranges hold fewer voting replicas ON LIVE NODES
than their effective zone asks for, so a range whose replicas are assigned
to a dead node is named rather than counted as healthy.
url: "{{ inputs.jdbc_url }}"
username: "{{ secret('COCKROACHDB_USERNAME') }}"
password: "{{ secret('COCKROACHDB_PASSWORD') }}"
fetchType: FETCH
sql: "{{ render(vars.tables_sql) }}"
- id: summary
type: io.kestra.plugin.core.log.Log
message: >-
CockroachDB replication: {{ outputs.cluster_before.row.live_nodes }} live
nodes, {{ outputs.cluster_before.row.dead_nodes }} dead, {{
outputs.cluster_before.row.leaving_nodes }} leaving or decommissioned. {{
outputs.cluster_before.row.total_ranges }} ranges in the report ({{
outputs.cluster_before.row.report_age_seconds }}s old): {{
outputs.cluster_before.row.unavailable_ranges }} unavailable, {{
outputs.cluster_before.row.under_replicated_ranges }} under-replicated, {{
outputs.cluster_before.row.over_replicated_ranges }} over-replicated. {{
outputs.cluster_before.row.impossible_zones_all }} zones ask for more
replicas than there are live nodes, {{
outputs.cluster_before.row.impossible_zones }} of them in scope. {% for r
in outputs.audit.rows %}{{ r.state }} {{ r.zone_target }}: {{
r.under_replicated_ranges }} under-replicated and {{ r.unavailable_ranges
}} unavailable of {{ r.total_ranges }} ranges, num_replicas {{
r.num_replicas }} vs {{ r.live_nodes }} live nodes{{ (r.fix_sql ?? '') ==
'' ? ' (report only)' : ', fix: ' ~ r.fix_sql }}. {% endfor %} {% for t in
outputs.affected_tables.rows %}Table {{ t.database_name }}.{{ t.table_name
}}: {{ t.ranges_affected }} ranges at {{ t.min_live_voters }} to {{
t.max_live_voters }} live voting replicas against a target of {{
t.target_replicas }}, {{ t.ranges_without_quorum }} without quorum, ranges
{{ t.sample_range_ids }}. {% endfor %}
- id: route
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.audit.size > 0 }}"
then:
- id: alert
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'CockroachDB ' ~ inputs.jdbc_url ~ ': ' ~ outputs.cluster_before.row.under_replicated_ranges ~ ' under-replicated and ' ~ outputs.cluster_before.row.unavailable_ranges ~ ' unavailable ranges across ' ~ outputs.cluster_before.row.total_ranges ~ ', on ' ~ outputs.cluster_before.row.live_nodes ~ ' live nodes and ' ~ outputs.cluster_before.row.dead_nodes ~ ' dead. ' ~ (outputs.audit.rows | jq('map("\(.state) \(.zone_target) (\(.under_replicated_ranges) under-replicated, \(.unavailable_ranges) unavailable, num_replicas \(.num_replicas))") | join("; ")') | first) ~ '. Tables: ' ~ (outputs.affected_tables.rows | jq('if length == 0 then "none named" else map("\(.database_name).\(.table_name) x\(.ranges_affected) at \(.min_live_voters) live voters") | join("; ") end') | first) ~ '.' ~ (inputs.auto_remediate and not inputs.dry_run ? ' Asking for approval to lower num_replicas.' : ' No change applied (auto_remediate=' ~ inputs.auto_remediate ~ ', dry_run=' ~ inputs.dry_run ~ ').')} | toJson }}
- id: remediate_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.auto_remediate and not inputs.dry_run and
(outputs.audit.rows | jq('map(select((.fix_sql // \"\") != \"\")) |
length') | first) > 0 }}"
then:
- id: approve
type: io.kestra.plugin.core.flow.Pause
description: >-
num_replicas is a durability setting, so the run holds here.
CockroachDB wants an odd replication factor, so on an even live
node count consider the next lower odd number instead. Another
option is to bring the dead node back rather than lower the target
at all.
pauseDuration: PT1H
behavior: FAIL
onResume:
- id: approved
type: BOOL
displayName: Approve the zone change
description: Set to true to lower num_replicas to the live node count on every
zone listed as in scope.
defaults: false
- id: change_ticket
type: STRING
displayName: Change record
defaults: ""
- id: approval_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approve.onResume.approved }}"
then:
- id: remediate
type: io.kestra.plugin.core.flow.Loop
description: One ALTER CONFIGURE ZONE at a time. Zone configs are written to a
single system table, so parallel writes would conflict.
concurrencyLimit: 1
values: "{{ outputs.audit.rows | jq('map(select((.fix_sql // \"\") != \"\") |
.fix_sql) | unique') | first | toJson }}"
tasks:
- id: apply_zone_change
type: io.kestra.plugin.jdbc.postgresql.Query
allowFailure: true
url: "{{ inputs.jdbc_url }}"
username: "{{ secret('COCKROACHDB_USERNAME') }}"
password: "{{ secret('COCKROACHDB_PASSWORD') }}"
fetchType: NONE
sql: "{{ item.value }}"
- id: settle
type: io.kestra.plugin.core.flow.Sleep
description: The replication report is rebuilt on an interval, so the next read
has to be of a newer report.
duration: "{{ inputs.settle_duration }}"
- id: cluster_after
type: io.kestra.plugin.jdbc.postgresql.Query
url: "{{ inputs.jdbc_url }}"
username: "{{ secret('COCKROACHDB_USERNAME') }}"
password: "{{ secret('COCKROACHDB_PASSWORD') }}"
fetchType: FETCH_ONE
sql: "{{ render(vars.cluster_sql) }}"
- id: verify_result
type: io.kestra.plugin.core.flow.If
condition: >-
{{ outputs.cluster_after.row.impossible_zones > 0
or outputs.cluster_after.row.report_epoch <= outputs.cluster_before.row.report_epoch
or outputs.cluster_after.row.under_replicated_ranges >= outputs.cluster_before.row.under_replicated_ranges }}
then:
- id: remediation_failed
type: io.kestra.plugin.core.execution.Fail
errorMessage: >-
Zone change did not land. In scope zones still asking for
more replicas than live nodes: {{
outputs.cluster_after.row.impossible_zones }} (was {{
outputs.cluster_before.row.impossible_zones }}).
Under-replicated ranges {{
outputs.cluster_before.row.under_replicated_ranges }}
before, {{
outputs.cluster_after.row.under_replicated_ranges }}
after. Report epoch {{
outputs.cluster_before.row.report_epoch }} before, {{
outputs.cluster_after.row.report_epoch }} after; when
those are equal the re-verify read the same report and
settle_duration needs to be longer than
kv.replication_reports.interval. Check the
apply_zone_change logs for a rejected ALTER.
else:
- id: remediated
type: io.kestra.plugin.core.log.Log
message: >-
Applied: {{ outputs.audit.rows | jq('map(select((.fix_sql
// "") != "") | .fix_sql) | unique | join("; ")') | first
}}. Change record {{
outputs.approve.onResume.change_ticket == '' ? 'not given'
: outputs.approve.onResume.change_ticket }}.
Under-replicated ranges {{
outputs.cluster_before.row.under_replicated_ranges }} to
{{ outputs.cluster_after.row.under_replicated_ranges }},
unavailable {{
outputs.cluster_before.row.unavailable_ranges }} to {{
outputs.cluster_after.row.unavailable_ranges }}, in scope
impossible zones {{
outputs.cluster_before.row.impossible_zones }} to {{
outputs.cluster_after.row.impossible_zones }}, measured
against a report {{
outputs.cluster_after.row.report_age_seconds }}s old.
else:
- id: approval_declined
type: io.kestra.plugin.core.log.Log
message: "Approval declined. No zone changed. {{
outputs.cluster_before.row.impossible_zones }} zones still ask
for more replicas than there are live nodes."
else:
- id: clean
type: io.kestra.plugin.core.log.Log
message: "Every range in the report has the replicas its zone asks for, on {{
outputs.cluster_before.row.live_nodes }} live nodes."
errors:
- id: alert_flow_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{{ {'text': 'CockroachDB range under-replication guard failed on ' ~ inputs.jdbc_url ~ ' (execution ' ~ execution.id ~ '). A cluster that cannot answer the audit is itself worth looking at. Check the logs.'} | toJson }}
triggers:
- id: every_15_minutes
type: io.kestra.plugin.core.trigger.Schedule
description: Shipped disabled. Always runs in safe mode.
cron: "*/15 * * * *"
disabled: true
inputs:
auto_remediate: false
dry_run: true