Skip to content

Commit 21fadd1

Browse files
committed
reinit PostgreSQL only if there is a healthy majority
1 parent 8e98f55 commit 21fadd1

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

src/cluster.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -425,11 +425,16 @@ def is_creating_backup(self) -> bool:
425425
for member in r.json()["members"]
426426
)
427427

428-
def is_replication_healthy(self) -> bool:
428+
def is_replication_healthy(self, majority_check: bool = False) -> bool:
429429
"""Return whether the replication is healthy."""
430+
expected_healthy_replicas_count = self.planned_units - 1
431+
if majority_check:
432+
expected_healthy_replicas_count = self.planned_units // 2
430433
try:
431434
for attempt in Retrying(stop=stop_after_delay(60), wait=wait_fixed(3)):
432435
with attempt:
436+
healthy_primary = False
437+
healthy_replicas_count = 0
433438
primary = self.get_primary()
434439
primary_ip = self.get_member_ip(primary)
435440
members_ips = {self.unit_ip}
@@ -447,7 +452,16 @@ def is_replication_healthy(self) -> bool:
447452
logger.debug(
448453
f"Failed replication check for {members_ip} with code {member_status.status_code}"
449454
)
450-
raise Exception
455+
continue
456+
if members_ip == primary_ip:
457+
healthy_primary = True
458+
else:
459+
healthy_replicas_count += 1
460+
if (
461+
not healthy_primary
462+
or healthy_replicas_count < expected_healthy_replicas_count
463+
):
464+
raise Exception
451465
except RetryError:
452466
logger.exception("replication is not healthy")
453467
return False
@@ -816,6 +830,12 @@ def restart_postgresql(self) -> None:
816830
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
817831
def reinitialize_postgresql(self) -> None:
818832
"""Reinitialize PostgreSQL."""
833+
834+
if not self.is_replication_healthy(majority_check=True):
835+
logger.debug("skipping reinitialize PostgreSQL, because of lack of healthy majority")
836+
raise Exception
837+
838+
logger.debug("reinitialize PostgreSQL")
819839
requests.post(
820840
f"{self._patroni_url}/reinitialize",
821841
verify=self.verify,

0 commit comments

Comments
 (0)