10
10
import pwd
11
11
import re
12
12
import subprocess
13
- from typing import Any
13
+ from typing import Any , List
14
14
15
15
import requests
16
16
from charms .operator_libs_linux .v2 import snap
@@ -425,11 +425,16 @@ def is_creating_backup(self) -> bool:
425
425
for member in r .json ()["members" ]
426
426
)
427
427
428
- def is_replication_healthy (self ) -> bool :
428
+ def is_replication_healthy (self , majority_check : bool = False ) -> bool :
429
429
"""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
430
433
try :
431
434
for attempt in Retrying (stop = stop_after_delay (60 ), wait = wait_fixed (3 )):
432
435
with attempt :
436
+ healthy_primary = False
437
+ healthy_replicas_count = 0
433
438
primary = self .get_primary ()
434
439
primary_ip = self .get_member_ip (primary )
435
440
members_ips = {self .unit_ip }
@@ -447,7 +452,13 @@ def is_replication_healthy(self) -> bool:
447
452
logger .debug (
448
453
f"Failed replication check for { members_ip } with code { member_status .status_code } "
449
454
)
450
- raise Exception
455
+ continue
456
+ if members_ip == primary_ip :
457
+ healthy_primary = True
458
+ else :
459
+ healthy_replicas_count += 1
460
+ if not healthy_primary or healthy_replicas_count < expected_healthy_replicas_count :
461
+ raise Exception
451
462
except RetryError :
452
463
logger .exception ("replication is not healthy" )
453
464
return False
@@ -816,6 +827,12 @@ def restart_postgresql(self) -> None:
816
827
@retry (stop = stop_after_attempt (3 ), wait = wait_exponential (multiplier = 1 , min = 2 , max = 10 ))
817
828
def reinitialize_postgresql (self ) -> None :
818
829
"""Reinitialize PostgreSQL."""
830
+
831
+ if not self .is_replication_healthy (majority_check = True ):
832
+ logger .debug ("skipping reinitialize PostgreSQL, because of lack of healthy majority" )
833
+ raise Exception
834
+
835
+ logger .debug ("reinitialize PostgreSQL" )
819
836
requests .post (
820
837
f"{ self ._patroni_url } /reinitialize" ,
821
838
verify = self .verify ,
0 commit comments