-
Notifications
You must be signed in to change notification settings - Fork 822
/
__init__.py
1932 lines (1462 loc) · 80 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Abstract classes for Distributed Configuration Store."""
import abc
import datetime
import json
import logging
import re
import time
from collections import defaultdict
from copy import deepcopy
from random import randint
from threading import Event, Lock
from typing import Any, Callable, Collection, Dict, Iterator, List, \
NamedTuple, Optional, Tuple, Type, TYPE_CHECKING, Union
from urllib.parse import urlparse, urlunparse, parse_qsl
import dateutil.parser
from .. import global_config
from ..dynamic_loader import iter_classes, iter_modules
from ..exceptions import PatroniFatalException
from ..utils import deep_compare, uri
from ..tags import Tags
from ..utils import parse_int
if TYPE_CHECKING: # pragma: no cover
from ..config import Config
from ..postgresql import Postgresql
from ..postgresql.mpp import AbstractMPP
SLOT_ADVANCE_AVAILABLE_VERSION = 110000
slot_name_re = re.compile('^[a-z0-9_]{1,63}$')
logger = logging.getLogger(__name__)
def slot_name_from_member_name(member_name: str) -> str:
"""Translate member name to valid PostgreSQL slot name.
.. note::
PostgreSQL's replication slot names must be valid PostgreSQL names. This function maps the wider space of
member names to valid PostgreSQL names. Names have their case lowered, dashes and periods common in hostnames
are replaced with underscores, other characters are encoded as their unicode codepoint. Name is truncated
to 64 characters. Multiple different member names may map to a single slot name.
:param member_name: The string to convert to a slot name.
:returns: The string converted using the rules described above.
"""
def replace_char(match: Any) -> str:
c = match.group(0)
return '_' if c in '-.' else f"u{ord(c):04d}"
slot_name = re.sub('[^a-z0-9_]', replace_char, member_name.lower())
return slot_name[0:63]
def parse_connection_string(value: str) -> Tuple[str, Union[str, None]]:
"""Split and rejoin a URL string into a connection URL and an API URL.
.. note::
Original Governor stores connection strings for each cluster members in a following format:
postgres://{username}:{password}@{connect_address}/postgres
Since each of our patroni instances provides their own REST API endpoint, it's good to store this information
in DCS along with PostgreSQL connection string. In order to not introduce new keys and be compatible with
original Governor we decided to extend original connection string in a following way:
postgres://{username}:{password}@{connect_address}/postgres?application_name={api_url}
This way original Governor could use such connection string as it is, because of feature of ``libpq`` library.
:param value: The URL string to split.
:returns: the connection string stored in DCS split into two parts, ``conn_url`` and ``api_url``.
"""
scheme, netloc, path, params, query, fragment = urlparse(value)
conn_url = urlunparse((scheme, netloc, path, params, '', fragment))
api_url = ([v for n, v in parse_qsl(query) if n == 'application_name'] or [None])[0]
return conn_url, api_url
def dcs_modules() -> List[str]:
"""Get names of DCS modules, depending on execution environment.
:returns: list of known module names with absolute python module path namespace, e.g. ``patroni.dcs.etcd``.
"""
if TYPE_CHECKING: # pragma: no cover
assert isinstance(__package__, str)
return iter_modules(__package__)
def iter_dcs_classes(
config: Optional[Union['Config', Dict[str, Any]]] = None
) -> Iterator[Tuple[str, Type['AbstractDCS']]]:
"""Attempt to import DCS modules that are present in the given configuration.
.. note::
If a module successfully imports we can assume that all its requirements are installed.
:param config: configuration information with possible DCS names as keys. If given, only attempt to import DCS
modules defined in the configuration. Else, if ``None``, attempt to import any supported DCS module.
:returns: an iterator of tuples, each containing the module ``name`` and the imported DCS class object.
"""
if TYPE_CHECKING: # pragma: no cover
assert isinstance(__package__, str)
return iter_classes(__package__, AbstractDCS, config)
def get_dcs(config: Union['Config', Dict[str, Any]]) -> 'AbstractDCS':
"""Attempt to load a Distributed Configuration Store from known available implementations.
.. note::
Using the list of available DCS classes returned by :func:`iter_classes` attempt to dynamically
instantiate the class that implements a DCS using the abstract class :class:`AbstractDCS`.
Basic top-level configuration parameters retrieved from *config* are propagated to the DCS specific config
before being passed to the module DCS class.
If no module is found to satisfy configuration then report and log an error. This will cause Patroni to exit.
:raises :exc:`PatroniFatalException`: if a load of all available DCS modules have been tried and none succeeded.
:param config: object or dictionary with Patroni configuration. This is normally a representation of the main
Patroni
:returns: The first successfully loaded DCS module which is an implementation of :class:`AbstractDCS`.
"""
for name, dcs_class in iter_dcs_classes(config):
# Propagate some parameters from top level of config if defined to the DCS specific config section.
config[name].update({
p: config[p] for p in ('namespace', 'name', 'scope', 'loop_wait',
'patronictl', 'ttl', 'retry_timeout')
if p in config})
from patroni.postgresql.mpp import get_mpp
return dcs_class(config[name], get_mpp(config))
available_implementations = ', '.join(sorted([n for n, _ in iter_dcs_classes()]))
raise PatroniFatalException("Can not find suitable configuration of distributed configuration store\n"
f"Available implementations: {available_implementations}")
_Version = Union[int, str]
_Session = Union[int, float, str, None]
class Member(Tags, NamedTuple('Member',
[('version', _Version),
('name', str),
('session', _Session),
('data', Dict[str, Any])])):
"""Immutable object (namedtuple) which represents single member of PostgreSQL cluster.
.. note::
We are using an old-style attribute declaration here because otherwise it is not possible to override
``__new__`` method in the :class:`RemoteMember` class.
.. note::
These two keys in data are always written to the DCS, but care is taken to maintain consistency and resilience
from data that is read:
``conn_url``: connection string containing host, user and password which could be used to access this member.
``api_url``: REST API url of patroni instance
Consists of the following fields:
:ivar version: modification version of a given member key in a Configuration Store.
:ivar name: name of PostgreSQL cluster member.
:ivar session: either session id or just ttl in seconds.
:ivar data: dictionary containing arbitrary data i.e. ``conn_url``, ``api_url``, ``xlog_location``, ``state``,
``role``, ``tags``, etc...
"""
@staticmethod
def from_node(version: _Version, name: str, session: _Session, value: str) -> 'Member':
"""Factory method for instantiating :class:`Member` from a JSON serialised string or object.
:param version: modification version of a given member key in a Configuration Store.
:param name: name of PostgreSQL cluster member.
:param session: either session id or just ttl in seconds.
:param value: JSON encoded string containing arbitrary data i.e. ``conn_url``, ``api_url``,
``xlog_location``, ``state``, ``role``, ``tags``, etc. OR a connection URL
starting with ``postgres://``.
:returns: an :class:`Member` instance built with the given arguments.
:Example:
>>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None
True
>>> Member.from_node(-1, '', '', '{')
Member(version=-1, name='', session='', data={})
"""
if value.startswith('postgres'):
conn_url, api_url = parse_connection_string(value)
data = {'conn_url': conn_url, 'api_url': api_url}
else:
try:
data = json.loads(value)
assert isinstance(data, dict)
except (AssertionError, TypeError, ValueError):
data: Dict[str, Any] = {}
return Member(version, name, session, data)
@property
def conn_url(self) -> Optional[str]:
"""The ``conn_url`` value from :attr:`~Member.data` if defined or constructed from ``conn_kwargs``."""
conn_url = self.data.get('conn_url')
if conn_url:
return conn_url
conn_kwargs = self.data.get('conn_kwargs')
if conn_kwargs:
conn_url = uri('postgresql', (conn_kwargs.get('host'), conn_kwargs.get('port', 5432)))
self.data['conn_url'] = conn_url
return conn_url
return None
def conn_kwargs(self, auth: Union[Any, Dict[str, Any], None] = None) -> Dict[str, Any]:
"""Give keyword arguments used for PostgreSQL connection settings.
:param auth: Authentication properties - can be defined as anything supported by the ``psycopg2`` or
``psycopg`` modules.
Converts a key of ``username`` to ``user`` if supplied.
:returns: A dictionary containing a merge of default parameter keys ``host``, ``port`` and ``dbname``, with
the contents of :attr:`~Member.data` ``conn_kwargs`` key. If those are not defined will
parse and reform connection parameters from :attr:`~Member.conn_url`. One of these two attributes
needs to have data defined to construct the output dictionary. Finally, *auth* parameters are merged
with the dictionary before returned.
"""
defaults = {
"host": None,
"port": None,
"dbname": None
}
ret: Optional[Dict[str, Any]] = self.data.get('conn_kwargs')
if ret:
defaults.update(ret)
ret = defaults
else:
conn_url = self.conn_url
if not conn_url:
return {} # due to the invalid conn_url we don't care about authentication parameters
r = urlparse(conn_url)
ret = {
'host': r.hostname,
'port': r.port or 5432,
'dbname': r.path[1:]
}
self.data['conn_kwargs'] = ret.copy()
# apply any remaining authentication parameters
if auth and isinstance(auth, dict):
ret.update({k: v for k, v in auth.items() if v is not None})
if 'username' in auth:
ret['user'] = ret.pop('username')
return ret
@property
def api_url(self) -> Optional[str]:
"""The ``api_url`` value from :attr:`~Member.data` if defined."""
return self.data.get('api_url')
@property
def tags(self) -> Dict[str, Any]:
"""The ``tags`` value from :attr:`~Member.data` if defined, otherwise an empty dictionary."""
return self.data.get('tags', {})
@property
def clonefrom(self) -> bool:
"""``True`` if both ``clonefrom`` tag is ``True`` and a connection URL is defined."""
return super().clonefrom and bool(self.conn_url)
@property
def state(self) -> str:
"""The ``state`` value of :attr:`~Member.data`."""
return self.data.get('state', 'unknown')
@property
def is_running(self) -> bool:
"""``True`` if the member :attr:`~Member.state` is ``running``."""
return self.state == 'running'
@property
def patroni_version(self) -> Optional[Tuple[int, ...]]:
"""The ``version`` string value from :attr:`~Member.data` converted to tuple.
:Example:
>>> Member.from_node(1, '', '', '{"version":"1.2.3"}').patroni_version
(1, 2, 3)
"""
version = self.data.get('version')
if version:
try:
return tuple(map(int, version.split('.')))
except Exception:
logger.debug('Failed to parse Patroni version %s', version)
return None
@property
def lsn(self) -> Optional[int]:
"""Current LSN (receive/flush/replay)."""
return parse_int(self.data.get('xlog_location'))
class RemoteMember(Member):
"""Represents a remote member (typically a primary) for a standby cluster.
:cvar ALLOWED_KEYS: Controls access to relevant key names that could be in stored :attr:`~RemoteMember.data`.
"""
ALLOWED_KEYS: Tuple[str, ...] = (
'primary_slot_name',
'create_replica_methods',
'restore_command',
'archive_cleanup_command',
'recovery_min_apply_delay',
'no_replication_slot'
)
def __new__(cls, name: str, data: Dict[str, Any]) -> 'RemoteMember':
"""Factory method to construct instance from given *name* and *data*.
:param name: name of the remote member.
:param data: dictionary of member information, which can contain keys from :const:`~RemoteMember.ALLOWED_KEYS`
but also member connection information ``api_url`` and ``conn_kwargs``, and slot information.
:returns: constructed instance using supplied parameters.
"""
return super(RemoteMember, cls).__new__(cls, -1, name, None, data)
def __getattr__(self, name: str) -> Any:
"""Dictionary style key lookup.
:param name: key to lookup.
:returns: value of *name* key in :attr:`~RemoteMember.data` if key *name* is in
:cvar:`~RemoteMember.ALLOWED_KEYS`, else ``None``.
"""
return self.data.get(name) if name in RemoteMember.ALLOWED_KEYS else None
class Leader(NamedTuple):
"""Immutable object (namedtuple) which represents leader key.
Consists of the following fields:
:ivar version: modification version of a leader key in a Configuration Store
:ivar session: either session id or just ttl in seconds
:ivar member: reference to a :class:`Member` object which represents current leader (see :attr:`Cluster.members`)
"""
version: _Version
session: _Session
member: Member
@property
def name(self) -> str:
"""The leader "member" name."""
return self.member.name
def conn_kwargs(self, auth: Optional[Dict[str, str]] = None) -> Dict[str, str]:
"""Connection keyword arguments.
:param auth: an optional dictionary containing authentication information.
:returns: the result of the called :meth:`Member.conn_kwargs` method.
"""
return self.member.conn_kwargs(auth)
@property
def conn_url(self) -> Optional[str]:
"""Connection URL value of the :class:`Member` instance."""
return self.member.conn_url
@property
def data(self) -> Dict[str, Any]:
"""Data value of the :class:`Member` instance."""
return self.member.data
@property
def timeline(self) -> Optional[int]:
"""Timeline value of :attr:`~Member.data`."""
return self.data.get('timeline')
@property
def checkpoint_after_promote(self) -> Optional[bool]:
"""Determine whether a checkpoint has occurred for this leader after promotion.
:returns: ``True`` if the role is ``master`` or ``primary`` and ``checkpoint_after_promote`` is not set,
``False`` if not a ``master`` or ``primary`` or if the checkpoint hasn't occurred.
If the version of Patroni is older than 1.5.6, return ``None``.
:Example:
>>> Leader(1, '', Member.from_node(1, '', '', '{"version":"z"}')).checkpoint_after_promote
"""
version = self.member.patroni_version
# 1.5.6 is the last version which doesn't expose checkpoint_after_promote: false
if version and version > (1, 5, 6):
return self.data.get('role') in ('master', 'primary') and 'checkpoint_after_promote' not in self.data
return None
class Failover(NamedTuple):
"""Immutable object (namedtuple) representing configuration information required for failover/switchover capability.
:ivar version: version of the object.
:ivar leader: name of the leader. If value isn't empty we treat it as a switchover from the specified node.
:ivar candidate: the name of the member node to be considered as a failover candidate.
:ivar scheduled_at: in the case of a switchover the :class:`~datetime.datetime` object to perform the scheduled
switchover.
:Example:
>>> 'Failover' in str(Failover.from_node(1, '{"leader": "cluster_leader"}'))
True
>>> 'Failover' in str(Failover.from_node(1, {"leader": "cluster_leader"}))
True
>>> 'Failover' in str(Failover.from_node(1, '{"leader": "cluster_leader", "member": "cluster_candidate"}'))
True
>>> Failover.from_node(1, 'null') is None
False
>>> n = '''{"leader": "cluster_leader", "member": "cluster_candidate",
... "scheduled_at": "2016-01-14T10:09:57.1394Z"}'''
>>> 'tzinfo=' in str(Failover.from_node(1, n))
True
>>> Failover.from_node(1, None) is None
False
>>> Failover.from_node(1, '{}') is None
False
>>> 'abc' in Failover.from_node(1, 'abc:def')
True
"""
version: _Version
leader: Optional[str]
candidate: Optional[str]
scheduled_at: Optional[datetime.datetime]
@staticmethod
def from_node(version: _Version, value: Union[str, Dict[str, str]]) -> 'Failover':
"""Factory method to parse *value* as failover configuration.
:param version: version number for the object.
:param value: JSON serialized data or a dictionary of configuration.
Can also be a colon ``:`` delimited list of leader, followed by candidate name (legacy format).
If ``scheduled_at`` key is defined the value will be parsed by :func:`dateutil.parser.parse`.
:returns: constructed :class:`Failover` information object
"""
if isinstance(value, dict):
data: Dict[str, Any] = value
elif value:
try:
data = json.loads(value)
assert isinstance(data, dict)
except AssertionError:
data = {}
except ValueError:
t = [a.strip() for a in value.split(':')]
leader = t[0]
candidate = t[1] if len(t) > 1 else None
return Failover(version, leader, candidate, None)
else:
data = {}
if data.get('scheduled_at'):
data['scheduled_at'] = dateutil.parser.parse(data['scheduled_at'])
return Failover(version, data.get('leader'), data.get('member'), data.get('scheduled_at'))
def __len__(self) -> int:
"""Implement ``len`` function capability.
.. note::
This magic method aids in the evaluation of "emptiness" of a :class:`Failover` instance. For example:
>>> failover = Failover.from_node(1, None)
>>> len(failover)
0
>>> assert bool(failover) is False
>>> failover = Failover.from_node(1, {"leader": "cluster_leader"})
>>> len(failover)
1
>>> assert bool(failover) is True
This makes it easier to write ``if cluster.failover`` rather than the longer statement.
"""
return int(bool(self.leader)) + int(bool(self.candidate))
class ClusterConfig(NamedTuple):
"""Immutable object (namedtuple) which represents cluster configuration.
:ivar version: version number for the object.
:ivar data: dictionary of configuration information.
:ivar modify_version: modified version number.
"""
version: _Version
data: Dict[str, Any]
modify_version: _Version
@staticmethod
def from_node(version: _Version, value: str, modify_version: Optional[_Version] = None) -> 'ClusterConfig':
"""Factory method to parse *value* as configuration information.
:param version: version number for object.
:param value: raw JSON serialized data, if not parsable replaced with an empty dictionary.
:param modify_version: optional modify version number, use *version* if not provided.
:returns: constructed :class:`ClusterConfig` instance.
:Example:
>>> ClusterConfig.from_node(1, '{') is None
False
"""
try:
data = json.loads(value)
assert isinstance(data, dict)
except (AssertionError, TypeError, ValueError):
data: Dict[str, Any] = {}
modify_version = 0
return ClusterConfig(version, data, version if modify_version is None else modify_version)
class SyncState(NamedTuple):
"""Immutable object (namedtuple) which represents last observed synchronous replication state.
:ivar version: modification version of a synchronization key in a Configuration Store.
:ivar leader: reference to member that was leader.
:ivar sync_standby: synchronous standby list (comma delimited) which are last synchronized to leader.
"""
version: Optional[_Version]
leader: Optional[str]
sync_standby: Optional[str]
@staticmethod
def from_node(version: Optional[_Version], value: Union[str, Dict[str, Any], None]) -> 'SyncState':
"""Factory method to parse *value* as synchronisation state information.
:param version: optional *version* number for the object.
:param value: (optionally JSON serialised) synchronisation state information
:returns: constructed :class:`SyncState` object.
:Example:
>>> SyncState.from_node(1, None).leader is None
True
>>> SyncState.from_node(1, '{}').leader is None
True
>>> SyncState.from_node(1, '{').leader is None
True
>>> SyncState.from_node(1, '[]').leader is None
True
>>> SyncState.from_node(1, '{"leader": "leader"}').leader == "leader"
True
>>> SyncState.from_node(1, {"leader": "leader"}).leader == "leader"
True
"""
try:
if value and isinstance(value, str):
value = json.loads(value)
assert isinstance(value, dict)
return SyncState(version, value.get('leader'), value.get('sync_standby'))
except (AssertionError, TypeError, ValueError):
return SyncState.empty(version)
@staticmethod
def empty(version: Optional[_Version] = None) -> 'SyncState':
"""Construct an empty :class:`SyncState` instance.
:param version: optional version number.
:returns: empty synchronisation state object.
"""
return SyncState(version, None, None)
@property
def is_empty(self) -> bool:
"""``True`` if ``/sync`` key is not valid (doesn't have a leader)."""
return not self.leader
@staticmethod
def _str_to_list(value: str) -> List[str]:
"""Splits a string by comma and returns list of strings.
:param value: a comma separated string.
:returns: list of non-empty strings after splitting an input value by comma.
"""
return list(filter(lambda a: a, [s.strip() for s in value.split(',')]))
@property
def members(self) -> List[str]:
""":attr:`~SyncState.sync_standby` as list or an empty list if undefined or object considered ``empty``."""
return self._str_to_list(self.sync_standby) if not self.is_empty and self.sync_standby else []
def matches(self, name: Optional[str], check_leader: bool = False) -> bool:
"""Checks if node is presented in the /sync state.
Since PostgreSQL does case-insensitive checks for synchronous_standby_name we do it also.
:param name: name of the node.
:param check_leader: by default the *name* is searched for only in members, a value of ``True`` will include the
leader to list.
:returns: ``True`` if the ``/sync`` key not :func:`is_empty` and the given *name* is among those presented in
the sync state.
:Example:
>>> s = SyncState(1, 'foo', 'bar,zoo')
>>> s.matches('foo')
False
>>> s.matches('fOo', True)
True
>>> s.matches('Bar')
True
>>> s.matches('zoO')
True
>>> s.matches('baz')
False
>>> s.matches(None)
False
>>> SyncState.empty(1).matches('foo')
False
"""
ret = False
if name and not self.is_empty:
search_str = (self.sync_standby or '') + (',' + (self.leader or '') if check_leader else '')
ret = name.lower() in self._str_to_list(search_str.lower())
return ret
def leader_matches(self, name: Optional[str]) -> bool:
"""Compare the given *name* to stored leader value.
:returns: ``True`` if *name* is matching the :attr:`~SyncState.leader` value.
"""
return bool(name and not self.is_empty and name.lower() == (self.leader or '').lower())
_HistoryTuple = Union[Tuple[int, int, str], Tuple[int, int, str, str], Tuple[int, int, str, str, str]]
class TimelineHistory(NamedTuple):
"""Object representing timeline history file.
.. note::
The content held in *lines* deserialized from *value* are lines parsed from PostgreSQL timeline history files,
consisting of the timeline number, the LSN where the timeline split and any other string held in the file.
The files are parsed by :func:`~patroni.postgresql.misc.parse_history`.
:ivar version: version number of the file.
:ivar value: raw JSON serialised data consisting of parsed lines from history files.
:ivar lines: ``List`` of ``Tuple`` parsed lines from history files.
"""
version: _Version
value: Any
lines: List[_HistoryTuple]
@staticmethod
def from_node(version: _Version, value: str) -> 'TimelineHistory':
"""Parse the given JSON serialized string as a list of timeline history lines.
:param version: version number
:param value: JSON serialized string, consisting of parsed lines of PostgreSQL timeline history files,
see :class:`TimelineHistory`.
:returns: composed timeline history object using parsed lines.
:Example:
If the passed *value* argument is not parsed an empty list of lines is returned:
>>> h = TimelineHistory.from_node(1, 2)
>>> h.lines
[]
"""
try:
lines = json.loads(value)
assert isinstance(lines, list)
except (AssertionError, TypeError, ValueError):
lines: List[_HistoryTuple] = []
return TimelineHistory(version, value, lines)
class Status(NamedTuple):
"""Immutable object (namedtuple) which represents `/status` key.
Consists of the following fields:
:ivar last_lsn: :class:`int` object containing position of last known leader LSN.
:ivar slots: state of permanent replication slots on the primary in the format: ``{"slot_name": int}``.
"""
last_lsn: int
slots: Optional[Dict[str, int]]
@staticmethod
def empty() -> 'Status':
"""Construct an empty :class:`Status` instance.
:returns: empty :class:`Status` object.
"""
return Status(0, None)
@staticmethod
def from_node(value: Union[str, Dict[str, Any], None]) -> 'Status':
"""Factory method to parse *value* as :class:`Status` object.
:param value: JSON serialized string
:returns: constructed :class:`Status` object.
"""
try:
if isinstance(value, str):
value = json.loads(value)
except Exception:
return Status.empty()
if isinstance(value, int): # legacy
return Status(value, None)
if not isinstance(value, dict):
return Status.empty()
try:
last_lsn = int(value.get('optime', ''))
except Exception:
last_lsn = 0
slots: Union[str, Dict[str, int], None] = value.get('slots')
if isinstance(slots, str):
try:
slots = json.loads(slots)
except Exception:
slots = None
if not isinstance(slots, dict):
slots = None
return Status(last_lsn, slots)
class Cluster(NamedTuple('Cluster',
[('initialize', Optional[str]),
('config', Optional[ClusterConfig]),
('leader', Optional[Leader]),
('status', Status),
('members', List[Member]),
('failover', Optional[Failover]),
('sync', SyncState),
('history', Optional[TimelineHistory]),
('failsafe', Optional[Dict[str, str]]),
('workers', Dict[int, 'Cluster'])])):
"""Immutable object (namedtuple) which represents PostgreSQL or MPP cluster.
.. note::
We are using an old-style attribute declaration here because otherwise it is not possible to override `__new__`
method. Without it the *workers* by default gets always the same :class:`dict` object that could be mutated.
Consists of the following fields:
:ivar initialize: shows whether this cluster has initialization key stored in DC or not.
:ivar config: global dynamic configuration, reference to `ClusterConfig` object.
:ivar leader: :class:`Leader` object which represents current leader of the cluster.
:ivar status: :class:`Status` object which represents the `/status` key.
:ivar members: list of:class:` Member` objects, all PostgreSQL cluster members including leader
:ivar failover: reference to :class:`Failover` object.
:ivar sync: reference to :class:`SyncState` object, last observed synchronous replication state.
:ivar history: reference to `TimelineHistory` object.
:ivar failsafe: failsafe topology. Node is allowed to become the leader only if its name is found in this list.
:ivar workers: dictionary of workers of the MPP cluster, optional. Each key representing the group and the
corresponding value is a :class:`Cluster` instance.
"""
def __new__(cls, *args: Any, **kwargs: Any):
"""Make workers argument optional and set it to an empty dict object."""
if len(args) < len(cls._fields) and 'workers' not in kwargs:
kwargs['workers'] = {}
return super(Cluster, cls).__new__(cls, *args, **kwargs)
@property
def last_lsn(self) -> int:
"""Last known leader LSN."""
return self.status.last_lsn
@property
def slots(self) -> Optional[Dict[str, int]]:
"""State of permanent replication slots on the primary in the format: ``{"slot_name": int}``."""
return self.status.slots
@staticmethod
def empty() -> 'Cluster':
"""Produce an empty :class:`Cluster` instance."""
return Cluster(None, None, None, Status.empty(), [], None, SyncState.empty(), None, None, {})
def is_empty(self):
"""Validate definition of all attributes of this :class:`Cluster` instance.
:returns: ``True`` if all attributes of the current :class:`Cluster` are unpopulated.
"""
return all((self.initialize is None, self.config is None, self.leader is None, self.last_lsn == 0,
self.members == [], self.failover is None, self.sync.version is None,
self.history is None, self.slots is None, self.failsafe is None, self.workers == {}))
def __len__(self) -> int:
"""Implement ``len`` function capability.
.. note::
This magic method aids in the evaluation of "emptiness" of a ``Cluster`` instance. For example:
>>> cluster = Cluster.empty()
>>> len(cluster)
0
>>> assert bool(cluster) is False
>>> cluster = Cluster(None, None, None, Status(0, None), [1, 2, 3], None, SyncState.empty(), None, None, {})
>>> len(cluster)
1
>>> assert bool(cluster) is True
This makes it easier to write ``if cluster`` rather than the longer statement.
"""
return int(not self.is_empty())
@property
def leader_name(self) -> Optional[str]:
"""The name of the leader if defined otherwise ``None``."""
return self.leader and self.leader.name
def is_unlocked(self) -> bool:
"""Check if the cluster does not have the leader.
:returns: ``True`` if a leader name is not defined.
"""
return not self.leader_name
def has_member(self, member_name: str) -> bool:
"""Check if the given member name is present in the cluster.
:param member_name: name to look up in the :attr:`~Cluster.members`.
:returns: ``True`` if the member name is found.
"""
return any(m for m in self.members if m.name == member_name)
def get_member(self, member_name: str, fallback_to_leader: bool = True) -> Union[Member, Leader, None]:
"""Get :class:`Member` object by name or the :class:`Leader`.
:param member_name: name of the member to retrieve.
:param fallback_to_leader: if ``True`` return the :class:`Leader` instead if the member cannot be found.
:returns: the :class:`Member` if found or :class:`Leader` object.
"""
return next((m for m in self.members if m.name == member_name),
self.leader if fallback_to_leader else None)
def get_clone_member(self, exclude_name: str) -> Union[Member, Leader, None]:
"""Get member or leader object to use as clone source.
:param exclude_name: name of a member name to exclude.
:returns: a randomly selected candidate member from available running members that are configured to as viable
sources for cloning (has tag ``clonefrom`` in configuration). If no member is appropriate the current
leader is used.
"""
exclude = [exclude_name] + ([self.leader.name] if self.leader else [])
candidates = [m for m in self.members if m.clonefrom and m.is_running and m.name not in exclude]
return candidates[randint(0, len(candidates) - 1)] if candidates else self.leader
@staticmethod
def is_physical_slot(value: Union[Any, Dict[str, Any]]) -> bool:
"""Check whether provided configuration is for permanent physical replication slot.
:param value: configuration of the permanent replication slot.
:returns: ``True`` if *value* is a physical replication slot, otherwise ``False``.
"""
return not value or isinstance(value, dict) and value.get('type', 'physical') == 'physical'
@staticmethod
def is_logical_slot(value: Union[Any, Dict[str, Any]]) -> bool:
"""Check whether provided configuration is for permanent logical replication slot.
:param value: configuration of the permanent replication slot.
:returns: ``True`` if *value* is a logical replication slot, otherwise ``False``.
"""
return isinstance(value, dict) \
and value.get('type', 'logical') == 'logical' \
and bool(value.get('database') and value.get('plugin'))
@property
def __permanent_slots(self) -> Dict[str, Union[Dict[str, Any], Any]]:
"""Dictionary of permanent replication slots with their known LSN."""
ret: Dict[str, Union[Dict[str, Any], Any]] = global_config.permanent_slots
members: Dict[str, int] = {slot_name_from_member_name(m.name): m.lsn or 0 for m in self.members}
slots: Dict[str, int] = {k: parse_int(v) or 0 for k, v in (self.slots or {}).items()}
for name, value in list(ret.items()):
if not value:
value = ret[name] = {}
if isinstance(value, dict):
# for permanent physical slots we want to get MAX LSN from the `Cluster.slots` and from the
# member with the matching name. It is necessary because we may have the replication slot on
# the primary that is streaming from the other standby node using the `replicatefrom` tag.
lsn = max(members.get(name, 0) if self.is_physical_slot(value) else 0, slots.get(name, 0))
if lsn:
value['lsn'] = lsn
else:
# Don't let anyone set 'lsn' in the global configuration :)
value.pop('lsn', None)
return ret
@property
def __permanent_physical_slots(self) -> Dict[str, Any]:
"""Dictionary of permanent ``physical`` replication slots."""
return {name: value for name, value in self.__permanent_slots.items() if self.is_physical_slot(value)}
@property
def __permanent_logical_slots(self) -> Dict[str, Any]:
"""Dictionary of permanent ``logical`` replication slots."""
return {name: value for name, value in self.__permanent_slots.items() if self.is_logical_slot(value)}
def get_replication_slots(self, postgresql: 'Postgresql', member: Tags, *,
role: Optional[str] = None, show_error: bool = False) -> Dict[str, Dict[str, Any]]:
"""Lookup configured slot names in the DCS, report issues found and merge with permanent slots.
Will log an error if:
* Any logical slots are disabled, due to version compatibility, and *show_error* is ``True``.
:param postgresql: reference to :class:`Postgresql` object.
:param member: reference to an object implementing :class:`Tags` interface.
:param role: role of the node, if not set will be taken from *postgresql*.
:param show_error: if ``True`` report error if any disabled logical slots or conflicting slot names are found.
:returns: final dictionary of slot names, after merging with permanent slots and performing sanity checks.
"""
name = member.name if isinstance(member, Member) else postgresql.name
role = role or postgresql.role
slots: Dict[str, Dict[str, str]] = self._get_members_slots(name, role)
permanent_slots: Dict[str, Any] = self._get_permanent_slots(postgresql, member, role)
disabled_permanent_logical_slots: List[str] = self._merge_permanent_slots(
slots, permanent_slots, name, postgresql.major_version)
if disabled_permanent_logical_slots and show_error:
logger.error("Permanent logical replication slots supported by Patroni only starting from PostgreSQL 11. "
"Following slots will not be created: %s.", disabled_permanent_logical_slots)
return slots
def _merge_permanent_slots(self, slots: Dict[str, Dict[str, str]], permanent_slots: Dict[str, Any], name: str,
major_version: int) -> List[str]:
"""Merge replication *slots* for members with *permanent_slots*.
Perform validation of configured permanent slot name, skipping invalid names.
Will update *slots* in-line based on ``type`` of slot, ``physical`` or ``logical``, and name of node.
Type is assumed to be ``physical`` if there are no attributes stored as the slot value.