forked from patroni/patroni
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1297 lines (982 loc) · 48.9 KB
/
utils.py
File metadata and controls
1297 lines (982 loc) · 48.9 KB
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
"""Utilitary objects and functions that can be used throughout Patroni code.
:var tzutc: UTC time zone info object.
:var logger: logger of this module.
:var USER_AGENT: identifies the Patroni version, Python version, and the underlying platform.
:var OCT_RE: regular expression to match octal numbers, signed or unsigned.
:var DEC_RE: regular expression to match decimal numbers, signed or unsigned.
:var HEX_RE: regular expression to match hex strings, signed or unsigned.
:var DBL_RE: regular expression to match double precision numbers, signed or unsigned. Matches scientific notation too.
:var WHITESPACE_RE: regular expression to match whitespace characters
"""
import errno
import itertools
import logging
import os
import platform
import random
import re
import socket
import subprocess
import sys
import tempfile
import time
from collections import OrderedDict
from json import JSONDecoder
from shlex import split
from typing import Any, Callable, cast, Dict, Iterator, List, Optional, Tuple, Type, TYPE_CHECKING, Union
from dateutil import tz
from urllib3.response import HTTPResponse
from .exceptions import PatroniException
from .version import __version__
if TYPE_CHECKING: # pragma: no cover
from .dcs import Cluster
tzutc = tz.tzutc()
logger = logging.getLogger(__name__)
USER_AGENT = 'Patroni/{0} Python/{1} {2}'.format(__version__, platform.python_version(), platform.system())
OCT_RE = re.compile(r'^[-+]?0[0-7]*')
DEC_RE = re.compile(r'^[-+]?(0|[1-9][0-9]*)')
HEX_RE = re.compile(r'^[-+]?0x[0-9a-fA-F]+')
DBL_RE = re.compile(r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?')
WHITESPACE_RE = re.compile(r'[ \t\n\r]*', re.VERBOSE | re.MULTILINE | re.DOTALL)
def get_conversion_table(base_unit: str) -> Dict[str, Dict[str, Union[int, float]]]:
"""Get conversion table for the specified base unit.
If no conversion table exists for the passed unit, return an empty :class:`OrderedDict`.
:param base_unit: unit to choose the conversion table for.
:returns: :class:`OrderedDict` object.
"""
memory_unit_conversion_table: Dict[str, Dict[str, Union[int, float]]] = OrderedDict([
('TB', {'B': 1024**4, 'kB': 1024**3, 'MB': 1024**2}),
('GB', {'B': 1024**3, 'kB': 1024**2, 'MB': 1024}),
('MB', {'B': 1024**2, 'kB': 1024, 'MB': 1}),
('kB', {'B': 1024, 'kB': 1, 'MB': 1024**-1}),
('B', {'B': 1, 'kB': 1024**-1, 'MB': 1024**-2})
])
time_unit_conversion_table: Dict[str, Dict[str, Union[int, float]]] = OrderedDict([
('d', {'ms': 1000 * 60**2 * 24, 's': 60**2 * 24, 'min': 60 * 24}),
('h', {'ms': 1000 * 60**2, 's': 60**2, 'min': 60}),
('min', {'ms': 1000 * 60, 's': 60, 'min': 1}),
('s', {'ms': 1000, 's': 1, 'min': 60**-1}),
('ms', {'ms': 1, 's': 1000**-1, 'min': 1 / (1000 * 60)}),
('us', {'ms': 1000**-1, 's': 1000**-2, 'min': 1 / (1000**2 * 60)})
])
if base_unit in ('B', 'kB', 'MB'):
return memory_unit_conversion_table
elif base_unit in ('ms', 's', 'min'):
return time_unit_conversion_table
return OrderedDict()
def deep_compare(obj1: Dict[Any, Any], obj2: Dict[Any, Any]) -> bool:
"""Recursively compare two dictionaries to check if they are equal in terms of keys and values.
.. note::
Values are compared based on their string representation.
:param obj1: dictionary to be compared with *obj2*.
:param obj2: dictionary to be compared with *obj1*.
:returns: ``True`` if all keys and values match between the two dictionaries.
:Example:
>>> deep_compare({'1': None}, {})
False
>>> deep_compare({'1': {}}, {'1': None})
False
>>> deep_compare({'1': [1]}, {'1': [2]})
False
>>> deep_compare({'1': 2}, {'1': '2'})
True
>>> deep_compare({'1': {'2': [3, 4]}}, {'1': {'2': [3, 4]}})
True
"""
if set(list(obj1.keys())) != set(list(obj2.keys())): # Objects have different sets of keys
return False
for key, value in obj1.items():
if isinstance(value, dict):
if not (isinstance(obj2[key], dict) and deep_compare(cast(Dict[Any, Any], value), obj2[key])):
return False
elif str(value) != str(obj2[key]):
return False
return True
def patch_config(config: Dict[Any, Any], data: Dict[Any, Any]) -> bool:
"""Update and append to dictionary *config* from overrides in *data*.
.. note::
* If the value of a given key in *data* is ``None``, then the key is removed from *config*;
* If a key is present in *data* but not in *config*, the key with the corresponding value is added to *config*
* For keys that are present on both sides it will compare the string representation of the corresponding values,
if the comparison doesn't match override the value
:param config: configuration to be patched.
:param data: new configuration values to patch *config* with.
:returns: ``True`` if *config* was changed.
"""
is_changed = False
for name, value in data.items():
if value is None:
if config.pop(name, None) is not None:
is_changed = True
elif name in config:
if isinstance(value, dict):
if isinstance(config[name], dict):
if patch_config(config[name], cast(Dict[Any, Any], value)):
is_changed = True
else:
config[name] = value
is_changed = True
elif str(config[name]) != str(value):
config[name] = value
is_changed = True
else:
config[name] = value
is_changed = True
return is_changed
def parse_bool(value: Any) -> Optional[bool]:
"""Parse a given value to a :class:`bool` object.
.. note::
The parsing is case-insensitive, and takes into consideration these values:
* ``on``, ``true``, ``yes``, and ``1`` as ``True``.
* ``off``, ``false``, ``no``, and ``0`` as ``False``.
:param value: value to be parsed to :class:`bool`.
:returns: the parsed value. If not able to parse, returns ``None``.
:Example:
>>> parse_bool(1)
True
>>> parse_bool('off')
False
>>> parse_bool('foo')
"""
value = str(value).lower()
if value in ('on', 'true', 'yes', '1'):
return True
if value in ('off', 'false', 'no', '0'):
return False
def strtol(value: Any, strict: Optional[bool] = True) -> Tuple[Optional[int], str]:
"""Extract the long integer part from the beginning of a string that represents a configuration value.
As most as possible close equivalent of ``strtol(3)`` C function (with base=0), which is used by postgres to parse
parameter values.
Takes into consideration numbers represented either as hex, octal or decimal formats.
:param value: any value from which we want to extract a long integer.
:param strict: dictates how the first item in the returning tuple is set when :func:`strtol` is not able to find a
long integer in *value*. If *strict* is ``True``, then the first item will be ``None``, else it will be ``1``.
:returns: the first item is the extracted long integer from *value*, and the second item is the remaining string of
*value*. If not able to match a long integer in *value*, then the first item will be either ``None`` or ``1``
(depending on *strict* argument), and the second item will be the original *value*.
:Example:
>>> strtol(0) == (0, '')
True
>>> strtol(1) == (1, '')
True
>>> strtol(9) == (9, '')
True
>>> strtol(' +0x400MB') == (1024, 'MB')
True
>>> strtol(' -070d') == (-56, 'd')
True
>>> strtol(' d ') == (None, 'd')
True
>>> strtol(' 1 d ') == (1, ' d')
True
>>> strtol('9s', False) == (9, 's')
True
>>> strtol(' s ', False) == (1, 's')
True
"""
value = str(value).strip()
for regex, base in ((HEX_RE, 16), (OCT_RE, 8), (DEC_RE, 10)):
match = regex.match(value)
if match:
end = match.end()
return int(value[:end], base), value[end:]
return (None if strict else 1), value
def strtod(value: Any) -> Tuple[Optional[float], str]:
"""Extract the double precision part from the beginning of a string that reprensents a configuration value.
As most as possible close equivalent of ``strtod(3)`` C function, which is used by postgres to parse parameter
values.
:param value: any value from which we want to extract a double precision.
:returns: the first item is the extracted double precision from *value*, and the second item is the remaining
string of *value*. If not able to match a double precision in *value*, then the first item will be ``None``,
and the second item will be the original *value*.
:Example:
>>> strtod(' A ') == (None, 'A')
True
>>> strtod('1 A ') == (1.0, ' A')
True
>>> strtod('1.5A') == (1.5, 'A')
True
>>> strtod('8.325e-10A B C') == (8.325e-10, 'A B C')
True
"""
value = str(value).strip()
match = DBL_RE.match(value)
if match:
end = match.end()
return float(value[:end]), value[end:]
return None, value
def convert_to_base_unit(value: Union[int, float], unit: str, base_unit: Optional[str]) -> Union[int, float, None]:
"""Convert *value* as a *unit* of compute information or time to *base_unit*.
:param value: value to be converted to the base unit.
:param unit: unit of *value*. Accepts these units (case sensitive):
* For space: ``B``, ``kB``, ``MB``, ``GB``, or ``TB``;
* For time: ``d``, ``h``, ``min``, ``s``, ``ms``, or ``us``.
:param base_unit: target unit in the conversion. May contain the target unit with an associated value, e.g
``512MB``. Accepts these units (case sensitive):
* For space: ``B``, ``kB``, or ``MB``;
* For time: ``ms``, ``s``, or ``min``.
:returns: *value* in *unit* converted to *base_unit*. Returns ``None`` if *unit* or *base_unit* is invalid.
:Example:
>>> convert_to_base_unit(1, 'GB', '256MB')
4
>>> convert_to_base_unit(1, 'GB', 'MB')
1024
>>> convert_to_base_unit(1, 'gB', '512MB') is None
True
>>> convert_to_base_unit(1, 'GB', '512 MB') is None
True
"""
base_value, base_unit = strtol(base_unit, False)
if TYPE_CHECKING: # pragma: no cover
assert isinstance(base_value, int)
convert_tbl = get_conversion_table(base_unit)
# {'TB': 'GB', 'GB': 'MB', ...}
round_order = dict(zip(convert_tbl, itertools.islice(convert_tbl, 1, None)))
if unit in convert_tbl and base_unit in convert_tbl[unit]:
value *= convert_tbl[unit][base_unit] / float(base_value)
if unit in round_order:
multiplier = convert_tbl[round_order[unit]][base_unit]
value = round(value / float(multiplier)) * multiplier
return value
def convert_int_from_base_unit(base_value: int, base_unit: Optional[str]) -> Optional[str]:
"""Convert an integer value in some base unit to a human-friendly unit.
The output unit is chosen so that it's the greatest unit that can represent
the value without loss.
:param base_value: value to be converted from a base unit
:param base_unit: unit of *value*. Should be one of the base units (case sensitive):
* For space: ``B``, ``kB``, ``MB``;
* For time: ``ms``, ``s``, ``min``.
:returns: :class:`str` value representing *base_value* converted from *base_unit* to the greatest
possible human-friendly unit, or ``None`` if conversion failed.
:Example:
>>> convert_int_from_base_unit(1024, 'kB')
'1MB'
>>> convert_int_from_base_unit(1025, 'kB')
'1025kB'
>>> convert_int_from_base_unit(4, '256MB')
'1GB'
>>> convert_int_from_base_unit(4, '256 MB') is None
True
>>> convert_int_from_base_unit(1024, 'KB') is None
True
"""
base_value_mult, base_unit = strtol(base_unit, False)
if TYPE_CHECKING: # pragma: no cover
assert isinstance(base_value_mult, int)
base_value *= base_value_mult
convert_tbl = get_conversion_table(base_unit)
for unit in convert_tbl:
multiplier = convert_tbl[unit][base_unit]
if multiplier <= 1.0 or base_value % multiplier == 0:
return str(round(base_value / multiplier)) + unit
def convert_real_from_base_unit(base_value: float, base_unit: Optional[str]) -> Optional[str]:
"""Convert an floating-point value in some base unit to a human-friendly unit.
Same as :func:`convert_int_from_base_unit`, except we have to do the math a bit differently,
and there's a possibility that we don't find any exact divisor.
:param base_value: value to be converted from a base unit
:param base_unit: unit of *value*. Should be one of the base units (case sensitive):
* For space: ``B``, ``kB``, ``MB``;
* For time: ``ms``, ``s``, ``min``.
:returns: :class:`str` value representing *base_value* converted from *base_unit* to the greatest
possible human-friendly unit, or ``None`` if conversion failed.
:Example:
>>> convert_real_from_base_unit(5, 'ms')
'5ms'
>>> convert_real_from_base_unit(2.5, 'ms')
'2500us'
>>> convert_real_from_base_unit(4.0, '256MB')
'1GB'
>>> convert_real_from_base_unit(4.0, '256 MB') is None
True
"""
base_value_mult, base_unit = strtol(base_unit, False)
if TYPE_CHECKING: # pragma: no cover
assert isinstance(base_value_mult, int)
base_value *= base_value_mult
result = None
convert_tbl = get_conversion_table(base_unit)
for unit in convert_tbl:
value = base_value / convert_tbl[unit][base_unit]
result = f'{value:g}{unit}'
if value > 0 and abs((round(value) / value) - 1.0) <= 1e-8:
break
return result
def maybe_convert_from_base_unit(base_value: str, vartype: str, base_unit: Optional[str]) -> str:
"""Try to convert integer or real value in a base unit to a human-readable unit.
Value is passed as a string. If parsing or subsequent conversion fails, the original
value is returned.
:param base_value: value to be converted from a base unit.
:param vartype: the target type to parse *base_value* before converting (``integer``
or ``real`` is expected, any other type results in return value being equal to the
*base_value* string).
:param base_unit: unit of *value*. Should be one of the base units (case sensitive):
* For space: ``B``, ``kB``, ``MB``;
* For time: ``ms``, ``s``, ``min``.
:returns: :class:`str` value representing *base_value* converted from *base_unit* to the greatest
possible human-friendly unit, or *base_value* string if conversion failed.
:Example:
>>> maybe_convert_from_base_unit('5', 'integer', 'ms')
'5ms'
>>> maybe_convert_from_base_unit('4.2', 'real', 'ms')
'4200us'
>>> maybe_convert_from_base_unit('on', 'bool', None)
'on'
>>> maybe_convert_from_base_unit('', 'integer', '256MB')
''
"""
converters: Dict[str, Tuple[Callable[[str, Optional[str]], Union[int, float, str, None]],
Callable[[Any, Optional[str]], Optional[str]]]] = {
'integer': (parse_int, convert_int_from_base_unit),
'real': (parse_real, convert_real_from_base_unit),
'default': (lambda v, _: v, lambda v, _: v)
}
parser, converter = converters.get(vartype, converters['default'])
parsed_value = parser(base_value, None)
if parsed_value:
return converter(parsed_value, base_unit) or base_value
return base_value
def parse_int(value: Any, base_unit: Optional[str] = None) -> Optional[int]:
"""Parse *value* as an :class:`int`.
:param value: any value that can be handled either by :func:`strtol` or :func:`strtod`. If *value* contains a
unit, then *base_unit* must be given.
:param base_unit: an optional base unit to convert *value* through :func:`convert_to_base_unit`. Not used if
*value* does not contain a unit.
:returns: the parsed value, if able to parse. Otherwise returns ``None``.
:Example:
>>> parse_int('1') == 1
True
>>> parse_int(' 0x400 MB ', '16384kB') == 64
True
>>> parse_int('1MB', 'kB') == 1024
True
>>> parse_int('1000 ms', 's') == 1
True
>>> parse_int('1TB', 'GB') is None
True
>>> parse_int(50, None) == 50
True
>>> parse_int("51", None) == 51
True
>>> parse_int("nonsense", None) == None
True
>>> parse_int("nonsense", "kB") == None
True
>>> parse_int("nonsense") == None
True
>>> parse_int(0) == 0
True
>>> parse_int('6GB', '16MB') == 384
True
>>> parse_int('4097.4kB', 'kB') == 4097
True
>>> parse_int('4097.5kB', 'kB') == 4098
True
"""
val, unit = strtol(value)
if val is None and unit.startswith('.') or unit and unit[0] in ('.', 'e', 'E'):
val, unit = strtod(value)
if val is not None:
unit = unit.strip()
if not unit:
return round(val)
val = convert_to_base_unit(val, unit, base_unit)
if val is not None:
return round(val)
def parse_real(value: Any, base_unit: Optional[str] = None) -> Optional[float]:
"""Parse *value* as a :class:`float`.
:param value: any value that can be handled by :func:`strtod`. If *value* contains a unit, then *base_unit* must
be given.
:param base_unit: an optional base unit to convert *value* through :func:`convert_to_base_unit`. Not used if
*value* does not contain a unit.
:returns: the parsed value, if able to parse. Otherwise returns ``None``.
:Example:
>>> parse_real(' +0.0005 ') == 0.0005
True
>>> parse_real('0.0005ms', 'ms') == 0.0
True
>>> parse_real('0.00051ms', 'ms') == 0.001
True
"""
val, unit = strtod(value)
if val is not None:
unit = unit.strip()
if not unit:
return val
return convert_to_base_unit(val, unit, base_unit)
def compare_values(vartype: str, unit: Optional[str], settings_value: Any, config_value: Any) -> bool:
"""Check if the value from ``pg_settings`` and from Patroni config are equivalent after parsing them as *vartype*.
:param vartype: the target type to parse *settings_value* and *config_value* before comparing them.
Accepts any among of the following (case sensitive):
* ``bool``: parse values using :func:`parse_bool`; or
* ``integer``: parse values using :func:`parse_int`; or
* ``real``: parse values using :func:`parse_real`; or
* ``enum``: parse values as lowercase strings; or
* ``string``: parse values as strings. This one is used by default if no valid value is passed as *vartype*.
:param unit: base unit to be used as argument when calling :func:`parse_int` or :func:`parse_real`
for *config_value*.
:param settings_value: value to be compared with *config_value*.
:param config_value: value to be compared with *settings_value*.
:returns: ``True`` if *settings_value* is equivalent to *config_value* when both are parsed as *vartype*.
:Example:
>>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE')
True
>>> compare_values('string', None, 'remote_write', 'REMOTE_WRITE')
False
>>> compare_values('real', None, '1e-06', 0.000001)
True
>>> compare_values('integer', 'MB', '6GB', '6GB')
False
>>> compare_values('integer', None, '6GB', '6GB')
False
>>> compare_values('integer', '16384kB', '64', ' 0x400 MB ')
True
>>> compare_values('integer', '2MB', 524288, '1TB')
True
>>> compare_values('integer', 'MB', 1048576, '1TB')
True
>>> compare_values('integer', 'kB', 4098, '4097.5kB')
True
"""
converters: Dict[str, Callable[[str, Optional[str]], Union[None, bool, int, float, str]]] = {
'bool': lambda v1, v2: parse_bool(v1),
'integer': parse_int,
'real': parse_real,
'enum': lambda v1, v2: str(v1).lower(),
'string': lambda v1, v2: str(v1)
}
converter = converters.get(vartype) or converters['string']
old_converted = converter(settings_value, None)
new_converted = converter(config_value, unit)
return old_converted is not None and new_converted is not None and old_converted == new_converted
def _sleep(interval: Union[int, float]) -> None:
"""Wrap :func:`~time.sleep`.
:param interval: Delay execution for a given number of seconds. The argument may be a floating point number for
subsecond precision.
"""
time.sleep(interval)
def read_stripped(file_path: str) -> Iterator[str]:
"""Iterate over stripped lines in the given file.
:param file_path: path to the file to read from
:yields: each line from the given file stripped
"""
with open(file_path) as f:
for line in f:
yield line.strip()
class RetryFailedError(PatroniException):
"""Maximum number of attempts exhausted in retry operation."""
class Retry(object):
"""Helper for retrying a method in the face of retryable exceptions.
:ivar max_tries: how many times to retry the command.
:ivar delay: initial delay between retry attempts.
:ivar backoff: backoff multiplier between retry attempts.
:ivar max_jitter: additional max jitter period to wait between retry attempts to avoid slamming the server.
:ivar max_delay: maximum delay in seconds, regardless of other backoff settings.
:ivar sleep_func: function used to introduce artificial delays.
:ivar deadline: timeout for operation retries.
:ivar retry_exceptions: single exception or tuple
"""
def __init__(self, max_tries: Optional[int] = 1, delay: float = 0.1, backoff: int = 2,
max_jitter: float = 0.8, max_delay: int = 3600,
sleep_func: Callable[[Union[int, float]], None] = _sleep,
deadline: Optional[Union[int, float]] = None,
retry_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = PatroniException) -> None:
"""Create a :class:`Retry` instance for retrying function calls.
:param max_tries: how many times to retry the command. ``-1`` means infinite tries.
:param delay: initial delay between retry attempts.
:param backoff: backoff multiplier between retry attempts. Defaults to ``2`` for exponential backoff.
:param max_jitter: additional max jitter period to wait between retry attempts to avoid slamming the server.
:param max_delay: maximum delay in seconds, regardless of other backoff settings.
:param sleep_func: function used to introduce artificial delays.
:param deadline: timeout for operation retries.
:param retry_exceptions: single exception or tuple
"""
self.max_tries = max_tries
self.delay = delay
self.backoff = backoff
self.max_jitter = int(max_jitter * 100)
self.max_delay = float(max_delay)
self._attempts = 0
self._cur_delay = delay
self.deadline = deadline
self._cur_stoptime = None
self.sleep_func = sleep_func
self.retry_exceptions = retry_exceptions
def reset(self) -> None:
"""Reset the attempt counter, delay and stop time."""
self._attempts = 0
self._cur_delay = self.delay
self._cur_stoptime = None
def copy(self) -> 'Retry':
"""Return a clone of this retry manager."""
return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff,
max_jitter=self.max_jitter / 100.0, max_delay=int(self.max_delay), sleep_func=self.sleep_func,
deadline=self.deadline, retry_exceptions=self.retry_exceptions)
@property
def sleeptime(self) -> float:
"""Get next cycle sleep time.
It is based on the current delay plus a number up to ``max_jitter``.
"""
return self._cur_delay + (random.randint(0, self.max_jitter) / 100.0)
def update_delay(self) -> None:
"""Set next cycle delay.
It will be the minimum value between:
* current delay with ``backoff``; or
* ``max_delay``.
"""
self._cur_delay = min(self._cur_delay * self.backoff, self.max_delay)
@property
def stoptime(self) -> float:
"""Get the current stop time."""
return self._cur_stoptime or 0
def ensure_deadline(self, timeout: float, raise_ex: Optional[Exception] = None) -> bool:
"""Calculates and checks the remaining deadline time.
:param timeout: if the *deadline* is smaller than the provided *timeout* value raise *raise_ex* exception.
:param raise_ex: the exception object that will be raised if the *deadline* is smaller than provided *timeout*.
:returns: ``False`` if *deadline* is smaller than a provided *timeout* and *raise_ex* isn't set. Otherwise
``True``.
:raises:
:class:`Exception`: *raise_ex* if calculated deadline is smaller than provided *timeout*.
"""
if self.stoptime - time.time() < timeout:
if raise_ex:
raise raise_ex
return False
return True
def __call__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
"""Call a function *func* with arguments ``*args`` and ``*kwargs`` in a loop.
*func* will be called until one of the following conditions is met:
* It completes without throwing one of the configured ``retry_exceptions``; or
* ``max_retries`` is exceeded.; or
* ``deadline`` is exceeded.
.. note::
* It will set loop stop time based on ``deadline`` attribute.
* It will adjust delay on each cycle.
:param func: function to call.
:param args: positional arguments to call *func* with.
:params kwargs: keyword arguments to call *func* with.
:raises:
:class:`RetryFailedError`:
* If ``max_tries`` is exceeded; or
* If ``deadline`` is exceeded.
"""
self.reset()
while True:
try:
if self.deadline is not None and self._cur_stoptime is None:
self._cur_stoptime = time.time() + self.deadline
return func(*args, **kwargs)
except self.retry_exceptions as e:
# Note: max_tries == -1 means infinite tries.
if self._attempts == self.max_tries:
logger.warning('Retry got exception: %s', e)
raise RetryFailedError("Too many retry attempts")
self._attempts += 1
sleeptime = getattr(e, 'sleeptime', None)
if not isinstance(sleeptime, (int, float)):
sleeptime = self.sleeptime
if self._cur_stoptime is not None and time.time() + sleeptime >= self._cur_stoptime:
logger.warning('Retry got exception: %s', e)
raise RetryFailedError("Exceeded retry deadline")
logger.debug('Retry got exception: %s', e)
self.sleep_func(sleeptime)
self.update_delay()
def polling_loop(timeout: Union[int, float], interval: Union[int, float] = 1) -> Iterator[int]:
"""Return an iterator that returns values every *interval* seconds until *timeout* has passed.
.. note::
Timeout is measured from start of iteration.
:param timeout: for how long (in seconds) from now it should keep returning values.
:param interval: for how long to sleep before returning a new value.
:yields: current iteration counter, starting from ``0``.
"""
start_time = time.time()
iteration = 0
end_time = start_time + timeout
while time.time() < end_time:
yield iteration
iteration += 1
time.sleep(float(interval))
def split_host_port(value: str, default_port: Optional[int]) -> Tuple[str, int]:
"""Extract host(s) and port from *value*.
:param value: string from where host(s) and port will be extracted. Accepts either of these formats:
* ``host:port``; or
* ``host1,host2,...,hostn:port``.
Each ``host`` portion of *value* can be either:
* A FQDN; or
* An IPv4 address; or
* An IPv6 address, with or without square brackets.
:param default_port: if no port can be found in *param*, use *default_port* instead.
:returns: the first item is composed of a CSV list of hosts from *value*, and the second item is either the port
from *value* or *default_port*.
:Example:
>>> split_host_port('127.0.0.1', 5432)
('127.0.0.1', 5432)
>>> split_host_port('127.0.0.1:5400', 5432)
('127.0.0.1', 5400)
>>> split_host_port('127.0.0.1,192.168.0.101:5400', 5432)
('127.0.0.1,192.168.0.101', 5400)
>>> split_host_port('127.0.0.1,www.mydomain.com,[fe80:0:0:0:213:72ff:fe3c:21bf], 0:0:0:0:0:0:0:0:5400', 5432)
('127.0.0.1,www.mydomain.com,fe80:0:0:0:213:72ff:fe3c:21bf,0:0:0:0:0:0:0:0', 5400)
"""
t = value.rsplit(':', 1)
# If *value* contains ``:`` we consider it to be an IPv6 address, so we attempt to remove possible square brackets
if ':' in t[0]:
t[0] = ','.join([h.strip().strip('[]') for h in t[0].split(',')])
t.append(str(default_port))
return t[0], int(t[1])
def uri(proto: str, netloc: Union[List[str], Tuple[str, Union[int, str]], str], path: Optional[str] = '',
user: Optional[str] = None) -> str:
"""Construct URI from given arguments.
:param proto: the URI protocol.
:param netloc: the URI host(s) and port. Can be specified in either way among
* A :class:`list` or :class:`tuple`. The second item should be a port, and the first item should be composed of
hosts in either of these formats:
* ``host``; or.
* ``host1,host2,...,hostn``.
* A :class:`str` in either of these formats:
* ``host:port``; or
* ``host1,host2,...,hostn:port``.
In all cases, each ``host`` portion of *netloc* can be either:
* An FQDN; or
* An IPv4 address; or
* An IPv6 address, with or without square brackets.
:param path: the URI path.
:param user: the authenticating user, if any.
:returns: constructed URI.
"""
host, port = netloc if isinstance(netloc, (list, tuple)) else split_host_port(netloc, 0)
# If ``host`` contains ``:`` we consider it to be an IPv6 address, so we add square brackets if they are missing
if host and ':' in host and host[0] != '[' and host[-1] != ']':
host = '[{0}]'.format(host)
port = ':{0}'.format(port) if port else ''
path = '/{0}'.format(path) if path and not path.startswith('/') else path
user = '{0}@'.format(user) if user else ''
return '{0}://{1}{2}{3}{4}'.format(proto, user, host, port, path)
def iter_response_objects(response: HTTPResponse) -> Iterator[Dict[str, Any]]:
"""Iterate over the chunks of a :class:`~urllib3.response.HTTPResponse` and yield each JSON document that is found.
:param response: the HTTP response from which JSON documents will be retrieved.
:yields: current JSON document.
"""
prev = ''
decoder = JSONDecoder()
for chunk in response.read_chunked(decode_content=False):
chunk = prev + chunk.decode('utf-8')
length = len(chunk)
# ``chunk`` is analyzed in parts. ``idx`` holds the position of the first character in the current part that is
# neither space nor tab nor line-break, or in other words, the position in the ``chunk`` where it is likely
# that a JSON document begins
idx = WHITESPACE_RE.match(chunk, 0).end() # pyright: ignore [reportOptionalMemberAccess]
while idx < length:
try:
# Get a JSON document from the chunk. ``message`` is a dictionary representing the JSON document, and
# ``idx`` becomes the position in the ``chunk`` where the retrieved JSON document ends
message, idx = decoder.raw_decode(chunk, idx)
except ValueError: # malformed or incomplete JSON, unlikely to happen
break
else:
yield message
idx = WHITESPACE_RE.match(chunk, idx).end() # pyright: ignore [reportOptionalMemberAccess]
# It is not usual that a ``chunk`` would contain more than one JSON document, but we handle that just in case
prev = chunk[idx:]
def cluster_as_json(cluster: 'Cluster') -> Dict[str, Any]:
"""Get a JSON representation of *cluster*.
:param cluster: the :class:`~patroni.dcs.Cluster` object to be parsed as JSON.
:returns: JSON representation of *cluster*.
These are the possible keys in the returning object depending on the available information in *cluster*:
* ``members``: list of members in the cluster. Each value is a :class:`dict` that may have the following keys:
* ``name``: the name of the host (unique in the cluster). The ``members`` list is sorted by this key;
* ``role``: ``leader``, ``standby_leader``, ``sync_standby``, ``quorum_standby``, or ``replica``;
* ``state``: one of :class:`~patroni.postgresql.misc.PostgresqlState`;
* ``api_url``: REST API URL based on ``restapi->connect_address`` configuration;
* ``host``: PostgreSQL host based on ``postgresql->connect_address``;
* ``port``: PostgreSQL port based on ``postgresql->connect_address``;
* ``timeline``: PostgreSQL current timeline;
* ``pending_restart``: ``True`` if PostgreSQL is pending to be restarted;
* ``scheduled_restart``: scheduled restart timestamp, if any;
* ``tags``: any tags that were set for this member;
* ``lsn``: current WAL position. See :meth:`Postgresql._wal_position`
* ``receive_lsn``: receive LSN (``pg_catalog.pg_last_(xlog|wal)_receive_(location|lsn)()``),
if applicable;
* ``replay_lsn``: replay LSN (``pg_catalog.pg_last_(xlog|wal)_replay_(location|lsn)()``),
if applicable;
* ``lag``: replication lag for ``lsn``, if applicable;
* ``receive_lag``: lag of the receive LSN;
* ``replay_lag``: lag of the replay LSN;
* ``pause``: ``True`` if cluster is in maintenance mode;
* ``scheduled_switchover``: if a switchover has been scheduled, then it contains this entry with these keys:
* ``at``: timestamp when switchover was scheduled to occur;
* ``from``: name of the member to be demoted;
* ``to``: name of the member to be promoted.
"""
from . import global_config
from .postgresql.misc import format_lsn
config = global_config.from_cluster(cluster)
leader_name = cluster.leader.name if cluster.leader else None
cluster_lsn = cluster.status.last_lsn
ret: Dict[str, Any] = {'members': []}
sync_role = 'quorum_standby' if config.is_quorum_commit_mode else 'sync_standby'
multisite_active = False
multisite_info = {'status': 'leaderless'}
for m in cluster.members:
multisite = m.data.get('multisite', {})
multisite_active = multisite_active or multisite.get('active', False)
if m.name == leader_name:
multisite_standby = multisite.get('status') == 'Standby'
multisite_info['status'] = multisite.get('status')
multisite_info['name'] = multisite.get('name')
multisite_info['standby_config'] = multisite.get('standby_config', {})
role = 'standby_leader' if config.is_standby_cluster or multisite_standby else 'leader'
elif config.is_synchronous_mode and cluster.sync.matches(m.name):
role = sync_role
else:
role = 'replica'
state = (m.data.get('replication_state', '') if role != 'leader' else '') or m.data.get('state', '')
member = {'name': m.name, 'role': role, 'state': state, 'api_url': m.api_url}
conn_kwargs = m.conn_kwargs()
if conn_kwargs.get('host'):
member['host'] = conn_kwargs['host']
if conn_kwargs.get('port'):
member['port'] = int(conn_kwargs['port'])
optional_attributes = ('timeline', 'pending_restart', 'pending_restart_reason', 'scheduled_restart', 'tags')
member.update({n: m.data[n] for n in optional_attributes if n in m.data})
if m.name != leader_name:
for location in ('receive_', 'replay_', ''):
lsn_type, lag_type = f'{location}lsn', f'{location}lag'
lsn = getattr(m, lsn_type)
if not lsn:
member[lsn_type] = member[lag_type] = 'unknown'
elif cluster_lsn >= lsn:
member[lag_type] = cluster_lsn - lsn
member[lsn_type] = format_lsn(lsn)
else:
member[lag_type] = 0
member[lsn_type] = format_lsn(lsn)
elif m.name == leader_name and (config.is_standby_cluster or multisite_active):
latest_end_lsn = getattr(m, 'latest_end_lsn')
member['latest_end_lsn'] = format_lsn(latest_end_lsn) if latest_end_lsn else ''