Skip to content

Commit b47d7b9

Browse files
hughcapetavandras
authored andcommitted
Convert roles to enums (patroni#3303)
1 parent d3d1e47 commit b47d7b9

22 files changed

+377
-231
lines changed

patroni/__main__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,13 +216,15 @@ def _run_cycle(self) -> None:
216216
the change and cache the new dynamic configuration values in ``patroni.dynamic.json`` file under Postgres data
217217
directory.
218218
"""
219+
from patroni.postgresql.misc import PostgresqlRole
220+
219221
logger.info(self.ha.run_cycle())
220222

221223
if self.dcs.cluster and self.dcs.cluster.config and self.dcs.cluster.config.data \
222224
and self.config.set_dynamic_configuration(self.dcs.cluster.config):
223225
self.reload_config()
224226

225-
if self.postgresql.role != 'uninitialized':
227+
if self.postgresql.role != PostgresqlRole.UNINITIALIZED:
226228
self.config.save_cache()
227229

228230
self.schedule_next_run()

patroni/api.py

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
from .__main__ import Patroni
3131
from .dcs import Cluster
3232
from .exceptions import PostgresConnectionException, PostgresException
33-
from .postgresql.misc import postgres_version_to_int
33+
from .postgresql.misc import postgres_version_to_int, PostgresqlRole, PostgresqlState
3434
from .utils import cluster_as_json, deep_compare, enable_keepalive, parse_bool, \
3535
parse_int, patch_config, Retry, RetryFailedError, split_host_port, tzutc, uri
3636

@@ -323,17 +323,19 @@ def do_GET(self, write_status_code_only: bool = False) -> None:
323323
is_lagging = leader_optime and leader_optime > replayed_location + max_replica_lag
324324

325325
replica_status_code = 200 if not patroni.noloadbalance and not is_lagging and \
326-
response.get('role') == 'replica' and response.get('state') == 'running' else 503
326+
response.get('role') == PostgresqlRole.REPLICA and response.get('state') == PostgresqlState.RUNNING else 503
327327

328328
if not cluster and response.get('pause'):
329-
leader_status_code = 200 if response.get('role') in ('primary', 'standby_leader') else 503
330-
primary_status_code = 200 if response.get('role') == 'primary' else 503
331-
standby_leader_status_code = 200 if response.get('role') == 'standby_leader' else 503
329+
leader_status_code = 200 if response.get('role') in (PostgresqlRole.PRIMARY,
330+
PostgresqlRole.STANDBY_LEADER) else 503
331+
primary_status_code = 200 if response.get('role') == PostgresqlRole.PRIMARY else 503
332+
standby_leader_status_code = 200 if response.get('role') == PostgresqlRole.STANDBY_LEADER else 503
332333
elif patroni.ha.is_leader():
333334
leader_status_code = 200
334335
if config.is_standby_cluster:
335336
primary_status_code = replica_status_code = 503
336-
standby_leader_status_code = 200 if response.get('role') in ('replica', 'standby_leader') else 503
337+
standby_leader_status_code =\
338+
200 if response.get('role') in (PostgresqlRole.REPLICA, PostgresqlRole.STANDBY_LEADER) else 503
337339
else:
338340
primary_status_code = 200
339341
standby_leader_status_code = 503
@@ -435,7 +437,7 @@ def do_GET_liveness(self) -> None:
435437
436438
"""
437439
patroni: Patroni = self.server.patroni
438-
is_primary = patroni.postgresql.role == 'primary' and patroni.postgresql.is_running()
440+
is_primary = patroni.postgresql.role == PostgresqlRole.PRIMARY and patroni.postgresql.is_running()
439441
# We can tolerate Patroni problems longer on the replica.
440442
# On the primary the liveness probe most likely will start failing only after the leader key expired.
441443
# It should not be a big problem because replicas will see that the primary is still alive via REST API call.
@@ -581,7 +583,7 @@ def do_GET_metrics(self) -> None:
581583

582584
metrics.append("# HELP patroni_primary Value is 1 if this node is the leader, 0 otherwise.")
583585
metrics.append("# TYPE patroni_primary gauge")
584-
metrics.append("patroni_primary{0} {1}".format(labels, int(postgres['role'] == 'primary')))
586+
metrics.append("patroni_primary{0} {1}".format(labels, int(postgres['role'] == PostgresqlRole.PRIMARY)))
585587

586588
metrics.append("# HELP patroni_xlog_location Current location of the Postgres"
587589
" transaction log, 0 if this node is not the leader.")
@@ -590,11 +592,12 @@ def do_GET_metrics(self) -> None:
590592

591593
metrics.append("# HELP patroni_standby_leader Value is 1 if this node is the standby_leader, 0 otherwise.")
592594
metrics.append("# TYPE patroni_standby_leader gauge")
593-
metrics.append("patroni_standby_leader{0} {1}".format(labels, int(postgres['role'] == 'standby_leader')))
595+
metrics.append("patroni_standby_leader{0} {1}".format(labels,
596+
int(postgres['role'] == PostgresqlRole.STANDBY_LEADER)))
594597

595598
metrics.append("# HELP patroni_replica Value is 1 if this node is a replica, 0 otherwise.")
596599
metrics.append("# TYPE patroni_replica gauge")
597-
metrics.append("patroni_replica{0} {1}".format(labels, int(postgres['role'] == 'replica')))
600+
metrics.append("patroni_replica{0} {1}".format(labels, int(postgres['role'] == PostgresqlRole.REPLICA)))
598601

599602
metrics.append("# HELP patroni_sync_standby Value is 1 if this node is a sync standby, 0 otherwise.")
600603
metrics.append("# TYPE patroni_sync_standby gauge")
@@ -916,7 +919,7 @@ def do_POST_restart(self) -> None:
916919
status_code = _
917920
break
918921
elif k == 'role':
919-
if request[k] not in ('primary', 'standby_leader', 'replica'):
922+
if request[k] not in (PostgresqlRole.PRIMARY, PostgresqlRole.STANDBY_LEADER, PostgresqlRole.REPLICA):
920923
status_code = 400
921924
data = "PostgreSQL role should be either primary, standby_leader, or replica"
922925
break
@@ -1299,15 +1302,16 @@ def get_postgresql_status(self, retry: bool = False) -> Dict[str, Any]:
12991302
``initdb failed``, ``running custom bootstrap script``, ``custom bootstrap failed``,
13001303
``creating replica``, or ``unknown``;
13011304
* ``postmaster_start_time``: ``pg_postmaster_start_time()``;
1302-
* ``role``: ``replica`` or ``primary`` based on ``pg_is_in_recovery()`` output;
1305+
* ``role``: :class:`~patroni.postgresql.misc.PostgresqlRole.REPLICA` or
1306+
:class:`~patroni.postgresql.misc.PostgresqlRole.PRIMARY` based on ``pg_is_in_recovery()`` output;
13031307
* ``server_version``: Postgres version without periods, e.g. ``150002`` for Postgres ``15.2``;
13041308
* ``xlog``: dictionary. Its structure depends on ``role``:
13051309
1306-
* If ``primary``:
1310+
* If :class:`~patroni.postgresql.misc.PostgresqlRole.PRIMARY`:
13071311
13081312
* ``location``: ``pg_current_wal_flush_lsn()``
13091313
1310-
* If ``replica``:
1314+
* If :class:`~patroni.postgresql.misc.PostgresqlRole.REPLICA`:
13111315
13121316
* ``received_location``: ``pg_wal_lsn_diff(pg_last_wal_receive_lsn(), '0/0')``;
13131317
* ``replayed_location``: ``pg_wal_lsn_diff(pg_last_wal_replay_lsn(), '0/0)``;
@@ -1355,7 +1359,7 @@ def get_postgresql_status(self, retry: bool = False) -> Dict[str, Any]:
13551359
result = {
13561360
'state': postgresql.state,
13571361
'postmaster_start_time': row[0],
1358-
'role': 'replica' if row[1] == 0 else 'primary',
1362+
'role': PostgresqlRole.REPLICA if row[1] == 0 else PostgresqlRole.PRIMARY,
13591363
'server_version': postgresql.server_version,
13601364
'xlog': ({
13611365
'received_location': row[4] or row[3],
@@ -1366,10 +1370,10 @@ def get_postgresql_status(self, retry: bool = False) -> Dict[str, Any]:
13661370
})
13671371
}
13681372

1369-
if result['role'] == 'replica' and config.is_standby_cluster:
1373+
if result['role'] == PostgresqlRole.REPLICA and config.is_standby_cluster:
13701374
result['role'] = postgresql.role
13711375

1372-
if result['role'] == 'replica' and config.is_synchronous_mode\
1376+
if result['role'] == PostgresqlRole.REPLICA and config.is_synchronous_mode\
13731377
and cluster and cluster.sync.matches(postgresql.name):
13741378
result['quorum_standby' if global_config.is_quorum_commit_mode else 'sync_standby'] = True
13751379

0 commit comments

Comments
 (0)