forked from postgrespro/testgres
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
2432 lines (1935 loc) · 75.5 KB
/
node.py
File metadata and controls
2432 lines (1935 loc) · 75.5 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
# coding: utf-8
from __future__ import annotations
import logging
import os
import signal
import subprocess
import time
import typing
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
# we support both pg8000 and psycopg2
try:
import psycopg2 as pglib
except ImportError:
try:
import pg8000 as pglib
except ImportError:
raise ImportError("You must have psycopg2 or pg8000 modules installed")
from six import raise_from, iteritems, text_type
from .enums import \
NodeStatus, \
ProcessType, \
DumpFormat
from .cache import cached_initdb
from .config import testgres_config
from .connection import NodeConnection
from .consts import \
DATA_DIR, \
LOGS_DIR, \
TMP_NODE, \
TMP_DUMP, \
PG_CONF_FILE, \
PG_AUTO_CONF_FILE, \
HBA_CONF_FILE, \
RECOVERY_CONF_FILE, \
PG_LOG_FILE, \
UTILS_LOG_FILE
from .consts import \
MAX_LOGICAL_REPLICATION_WORKERS, \
MAX_REPLICATION_SLOTS, \
MAX_WORKER_PROCESSES, \
MAX_WAL_SENDERS, \
WAL_KEEP_SEGMENTS, \
WAL_KEEP_SIZE
from .decorators import \
method_decorator, \
positional_args_hack
from .defaults import \
default_dbname, \
generate_app_name
from .exceptions import \
CatchUpException, \
ExecUtilException, \
QueryException, \
QueryTimeoutException, \
StartNodeException, \
TimeoutException, \
InitNodeException, \
TestgresException, \
BackupException, \
InvalidOperationException
from .port_manager import PortManager
from .impl.port_manager__this_host import PortManager__ThisHost
from .impl.port_manager__generic import PortManager__Generic
from .logger import TestgresLogger
from .pubsub import Publication, Subscription
from .standby import First
from . import utils
from .utils import \
PgVer, \
eprint, \
get_bin_path2, \
get_pg_version2, \
execute_utility2, \
options_string, \
clean_on_error
from .raise_error import RaiseError
from .backup import NodeBackup
from testgres.operations.os_ops import ConnectionParams
from testgres.operations.os_ops import OsOperations
from testgres.operations.local_ops import LocalOperations
InternalError = pglib.InternalError
ProgrammingError = pglib.ProgrammingError
OperationalError = pglib.OperationalError
assert TimeoutException == QueryTimeoutException
class ProcessProxy(object):
"""
Wrapper for psutil.Process
Attributes:
process: wrapped psutill.Process object
ptype: instance of ProcessType
"""
_process: typing.Any
_ptype: ProcessType
def __init__(self, process, ptype: typing.Optional[ProcessType] = None):
assert process is not None
assert ptype is None or type(ptype) is ProcessType
self._process = process
if ptype is not None:
self._ptype = ptype
else:
self._ptype = ProcessType.from_process(process)
assert type(self._ptype) is ProcessType
return
def __getattr__(self, name):
return getattr(self.process, name)
def __repr__(self):
return '{}(ptype={}, process={})'.format(
self.__class__.__name__,
str(self.ptype),
repr(self.process))
@property
def process(self) -> typing.Any:
assert self._process is not None
return self._process
@property
def ptype(self) -> ProcessType:
assert type(self._ptype) is ProcessType
return self._ptype
class PostgresNode(object):
# a max number of node start attempts
_C_MAX_START_ATEMPTS = 5
_C_PM_PID__IS_NOT_DETECTED = -1
_name: typing.Optional[str]
_port: typing.Optional[int]
_should_free_port: bool
_os_ops: OsOperations
_port_manager: typing.Optional[PortManager]
_manually_started_pm_pid: typing.Optional[int]
def __init__(self,
name=None,
base_dir=None,
port: typing.Optional[int] = None,
conn_params: typing.Optional[ConnectionParams] = None,
bin_dir=None,
prefix=None,
os_ops: typing.Optional[OsOperations] = None,
port_manager: typing.Optional[PortManager] = None):
"""
PostgresNode constructor.
Args:
name: node's application name.
port: port to accept connections.
base_dir: path to node's data directory.
bin_dir: path to node's binary directory.
os_ops: None or correct OS operation object.
port_manager: None or correct port manager object.
"""
assert port is None or type(port) is int
assert os_ops is None or isinstance(os_ops, OsOperations)
assert port_manager is None or isinstance(port_manager, PortManager)
if conn_params is not None:
assert type(conn_params) is ConnectionParams
raise InvalidOperationException("conn_params is deprecated, please use os_ops parameter instead.")
# private
if os_ops is None:
self._os_ops = __class__._get_os_ops()
else:
assert isinstance(os_ops, OsOperations)
self._os_ops = os_ops
pass
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
self._pg_version = PgVer(get_pg_version2(self._os_ops, bin_dir))
self._base_dir = base_dir
self._bin_dir = bin_dir
self._prefix = prefix
self._logger = None
self._master = None
# basic
self._name = name or generate_app_name()
if port is not None:
assert type(port) is int
assert port_manager is None
self._port = port
self._should_free_port = False
self._port_manager = None
else:
if port_manager is None:
self._port_manager = __class__._get_port_manager(self._os_ops)
elif os_ops is None:
raise InvalidOperationException("When port_manager is not None you have to define os_ops, too.")
else:
assert isinstance(port_manager, PortManager)
assert self._os_ops is os_ops
self._port_manager = port_manager
assert self._port_manager is not None
assert isinstance(self._port_manager, PortManager)
self._port = self._port_manager.reserve_port() # raises
assert type(self._port) is int
self._should_free_port = True
assert type(self._port) is int
# defaults for __exit__()
self.cleanup_on_good_exit = testgres_config.node_cleanup_on_good_exit
self.cleanup_on_bad_exit = testgres_config.node_cleanup_on_bad_exit
self.shutdown_max_attempts = 3
# NOTE: for compatibility
self.utils_log_name = self.utils_log_file
self.pg_log_name = self.pg_log_file
# Node state
self._manually_started_pm_pid = None
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
# NOTE: Ctrl+C does not count!
got_exception = type is not None and type is not KeyboardInterrupt
c1 = self.cleanup_on_good_exit and not got_exception
c2 = self.cleanup_on_bad_exit and got_exception
attempts = self.shutdown_max_attempts
if c1 or c2:
self.cleanup(attempts)
else:
self._try_shutdown(attempts)
self._release_resources()
def __repr__(self):
return "{}(name='{}', port={}, base_dir='{}')".format(
self.__class__.__name__,
self.name,
str(self._port) if self._port is not None else "None",
self.base_dir
)
@staticmethod
def _get_os_ops() -> OsOperations:
if testgres_config.os_ops:
return testgres_config.os_ops
return LocalOperations.get_single_instance()
@staticmethod
def _get_port_manager(os_ops: OsOperations) -> PortManager:
assert os_ops is not None
assert isinstance(os_ops, OsOperations)
if os_ops is LocalOperations.get_single_instance():
assert utils._old_port_manager is not None
assert type(utils._old_port_manager) is PortManager__Generic
assert utils._old_port_manager._os_ops is os_ops
return PortManager__ThisHost.get_single_instance()
# TODO: Throw the exception "Please define a port manager." ?
return PortManager__Generic(os_ops)
def clone_with_new_name_and_base_dir(self, name: str, base_dir: str):
assert name is None or type(name) is str
assert base_dir is None or type(base_dir) is str
assert __class__ == PostgresNode
if self._port_manager is None:
raise InvalidOperationException("PostgresNode without PortManager can't be cloned.")
assert self._port_manager is not None
assert isinstance(self._port_manager, PortManager)
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
node = PostgresNode(
name=name,
base_dir=base_dir,
bin_dir=self._bin_dir,
prefix=self._prefix,
os_ops=self._os_ops,
port_manager=self._port_manager)
return node
@property
def os_ops(self) -> OsOperations:
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
return self._os_ops
@property
def port_manager(self) -> typing.Optional[PortManager]:
assert self._port_manager is None or isinstance(self._port_manager, PortManager)
return self._port_manager
@property
def name(self) -> str:
if self._name is None:
raise InvalidOperationException("PostgresNode name is not defined.")
assert type(self._name) is str
return self._name
@property
def host(self) -> str:
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
return self._os_ops.host
@property
def port(self) -> int:
if self._port is None:
raise InvalidOperationException("PostgresNode port is not defined.")
assert type(self._port) is int
return self._port
@property
def ssh_key(self) -> typing.Optional[str]:
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
return self._os_ops.ssh_key
@property
def pid(self) -> int:
"""
Return postmaster's PID if node is running, else 0.
"""
x = self._get_node_state()
assert type(x) is utils.PostgresNodeState
if x.pid is None:
assert x.node_status != NodeStatus.Running
return 0
assert x.node_status == NodeStatus.Running
assert type(x.pid) is int
return x.pid
@property
def is_started(self) -> bool:
if self._manually_started_pm_pid is None:
return False
assert type(self._manually_started_pm_pid) is int
return True
@property
def auxiliary_pids(self) -> typing.Dict[ProcessType, typing.List[int]]:
"""
Returns a dict of { ProcessType : PID }.
"""
result = {}
for process in self.auxiliary_processes:
assert type(process) is ProcessProxy
if process.ptype not in result:
result[process.ptype] = []
result[process.ptype].append(process.pid)
return result
@property
def auxiliary_processes(self) -> typing.List[ProcessProxy]:
"""
Returns a list of auxiliary processes.
Each process is represented by :class:`.ProcessProxy` object.
"""
def is_aux(process: ProcessProxy) -> bool:
assert type(process) is ProcessProxy
return process.ptype != ProcessType.Unknown
return list(filter(is_aux, self.child_processes))
@property
def child_processes(self) -> typing.List[ProcessProxy]:
"""
Returns a list of all child processes.
Each process is represented by :class:`.ProcessProxy` object.
"""
# get a list of postmaster's children
x = self._get_node_state()
assert type(x) is utils.PostgresNodeState
if x.pid is None:
assert x.node_status != NodeStatus.Running
RaiseError.node_err__cant_enumerate_child_processes(
x.node_status
)
assert x.node_status == NodeStatus.Running
assert type(x.pid) is int
return self._get_child_processes(x.pid)
def _get_child_processes(self, pid: int) -> typing.List[ProcessProxy]:
assert type(pid) is int
assert isinstance(self._os_ops, OsOperations)
# get a list of postmaster's children
children = self._os_ops.get_process_children(pid)
return [ProcessProxy(p) for p in children]
@property
def source_walsender(self):
"""
Returns master's walsender feeding this replica.
"""
sql = """
select pid
from pg_catalog.pg_stat_replication
where application_name = %s
"""
if self.master is None:
raise TestgresException("Node doesn't have a master")
assert type(self.master) is PostgresNode
# master should be on the same host
assert self.master.host == self.host
with self.master.connect() as con:
for row in con.execute(sql, self.name):
for child in self.master.auxiliary_processes:
if child.pid == int(row[0]):
return child
msg = "Master doesn't send WAL to {}".format(self.name)
raise TestgresException(msg)
@property
def master(self):
return self._master
@property
def base_dir(self):
if not self._base_dir:
self._base_dir = self.os_ops.mkdtemp(prefix=self._prefix or TMP_NODE)
# NOTE: it's safe to create a new dir
if not self.os_ops.path_exists(self._base_dir):
self.os_ops.makedirs(self._base_dir)
return self._base_dir
@property
def bin_dir(self):
if not self._bin_dir:
self._bin_dir = os.path.dirname(get_bin_path2(self.os_ops, "pg_config"))
return self._bin_dir
@property
def logs_dir(self):
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
path = self._os_ops.build_path(self.base_dir, LOGS_DIR)
assert type(path) is str
# NOTE: it's safe to create a new dir
if not self.os_ops.path_exists(path):
self.os_ops.makedirs(path)
return path
@property
def data_dir(self):
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
# NOTE: we can't run initdb without user's args
path = self._os_ops.build_path(self.base_dir, DATA_DIR)
assert type(path) is str
return path
@property
def utils_log_file(self):
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
path = self._os_ops.build_path(self.logs_dir, UTILS_LOG_FILE)
assert type(path) is str
return path
@property
def pg_log_file(self):
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
path = self._os_ops.build_path(self.logs_dir, PG_LOG_FILE)
assert type(path) is str
return path
@property
def version(self):
"""
Return PostgreSQL version for this node.
Returns:
Instance of :class:`distutils.version.LooseVersion`.
"""
return self._pg_version
def _try_shutdown(self, max_attempts, with_force=False):
assert type(max_attempts) is int
assert type(with_force) is bool
assert max_attempts > 0
attempts = 0
# try stopping server N times
while attempts < max_attempts:
attempts += 1
try:
self.stop()
except ExecUtilException:
continue # one more time
except Exception:
eprint('cannot stop node {}'.format(self.name))
break
return # OK
# If force stopping is enabled and PID is valid
if not with_force:
return
node_pid = self.pid
assert node_pid is not None
assert type(node_pid) is int
if node_pid == 0:
return
# TODO: [2025-02-28] It is really the old ugly code. We have to rewrite it!
ps_command = ['ps', '-o', 'pid=', '-p', str(node_pid)]
ps_output = self.os_ops.exec_command(cmd=ps_command, shell=True, ignore_errors=True).decode('utf-8')
assert type(ps_output) is str
if ps_output == "":
return
if ps_output != str(node_pid):
__class__._throw_bugcheck__unexpected_result_of_ps(
ps_output,
ps_command)
try:
eprint('Force stopping node {0} with PID {1}'.format(self.name, node_pid))
self.os_ops.kill(node_pid, signal.SIGKILL)
except Exception:
# The node has already stopped
pass
# Check that node stopped - print only column pid without headers
ps_output = self.os_ops.exec_command(cmd=ps_command, shell=True, ignore_errors=True).decode('utf-8')
assert type(ps_output) is str
if ps_output == "":
eprint('Node {0} has been stopped successfully.'.format(self.name))
return
if ps_output == str(node_pid):
eprint('Failed to stop node {0}.'.format(self.name))
return
__class__._throw_bugcheck__unexpected_result_of_ps(
ps_output,
ps_command)
@staticmethod
def _throw_bugcheck__unexpected_result_of_ps(result, cmd):
assert type(result) is str
assert type(cmd) is list
errLines = []
errLines.append("[BUG CHECK] Unexpected result of command ps:")
errLines.append(result)
errLines.append("-----")
errLines.append("Command line is {0}".format(cmd))
raise RuntimeError("\n".join(errLines))
def _assign_master(self, master):
"""NOTE: this is a private method!"""
# now this node has a master
self._master = master
def _create_recovery_conf(self, username, slot=None):
"""NOTE: this is a private method!"""
# fetch master of this node
master = self.master
assert master is not None
conninfo = {
"application_name": self.name,
"port": master.port,
"user": username
} # yapf: disable
# host is tricky
try:
import ipaddress
ipaddress.ip_address(master.host)
conninfo["hostaddr"] = master.host
except ValueError:
conninfo["host"] = master.host
line = (
"primary_conninfo='{}'\n"
).format(options_string(**conninfo)) # yapf: disable
# Since 12 recovery.conf had disappeared
if self.version >= PgVer('12'):
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
signal_name = self._os_ops.build_path(self.data_dir, "standby.signal")
assert type(signal_name) is str
self.os_ops.touch(signal_name)
else:
line += "standby_mode=on\n"
if slot:
# Connect to master for some additional actions
with master.connect(username=username) as con:
# check if slot already exists
res = con.execute(
"""
select exists (
select from pg_catalog.pg_replication_slots
where slot_name = %s
)
""", slot)
if res[0][0]:
raise TestgresException(
"Slot '{}' already exists".format(slot))
# TODO: we should drop this slot after replica's cleanup()
con.execute(
"""
select pg_catalog.pg_create_physical_replication_slot(%s)
""", slot)
line += "primary_slot_name={}\n".format(slot)
if self.version >= PgVer('12'):
self.append_conf(line=line)
else:
self.append_conf(filename=RECOVERY_CONF_FILE, line=line)
def _maybe_start_logger(self):
if testgres_config.use_python_logging:
# spawn new logger if it doesn't exist or is stopped
if not self._logger or not self._logger.is_alive():
self._logger = TestgresLogger(self.name, self.pg_log_file)
self._logger.start()
def _maybe_stop_logger(self):
if self._logger:
self._logger.stop()
def _collect_special_files(self) -> typing.List[typing.Tuple[str, bytes]]:
result = []
# list of important files + last N lines
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
files = [
(self._os_ops.build_path(self.data_dir, PG_CONF_FILE), 0),
(self._os_ops.build_path(self.data_dir, PG_AUTO_CONF_FILE), 0),
(self._os_ops.build_path(self.data_dir, RECOVERY_CONF_FILE), 0),
(self._os_ops.build_path(self.data_dir, HBA_CONF_FILE), 0),
(self.pg_log_file, testgres_config.error_log_lines)
] # yapf: disable
for f, num_lines in files:
# skip missing files
if not self.os_ops.path_exists(f):
continue
file_lines = self.os_ops.readlines(f, num_lines, binary=True, encoding=None)
lines = b''.join(file_lines)
# fill list
result.append((f, lines))
return result
def init(self, initdb_params=None, cached=True, **kwargs):
"""
Perform initdb for this node.
Args:
initdb_params: parameters for initdb (list).
fsync: should this node use fsync to keep data safe?
unix_sockets: should we enable UNIX sockets?
allow_streaming: should this node add a hba entry for replication?
Returns:
This instance of :class:`.PostgresNode`
"""
# initialize this PostgreSQL node
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
cached_initdb(
data_dir=self.data_dir,
logfile=self.utils_log_file,
os_ops=self._os_ops,
params=initdb_params,
bin_path=self.bin_dir,
cached=False)
# initialize default config files
self.default_conf(**kwargs)
return self
def default_conf(self,
fsync=False,
unix_sockets=True,
allow_streaming=True,
allow_logical=False,
log_statement='all'):
"""
Apply default settings to this node.
Args:
fsync: should this node use fsync to keep data safe?
unix_sockets: should we enable UNIX sockets?
allow_streaming: should this node add a hba entry for replication?
allow_logical: can this node be used as a logical replication publisher?
log_statement: one of ('all', 'off', 'mod', 'ddl').
Returns:
This instance of :class:`.PostgresNode`.
"""
assert self._os_ops is not None
assert isinstance(self._os_ops, OsOperations)
postgres_conf = self._os_ops.build_path(self.data_dir, PG_CONF_FILE)
hba_conf = self._os_ops.build_path(self.data_dir, HBA_CONF_FILE)
# filter lines in hba file
# get rid of comments and blank lines
hba_conf_file = self.os_ops.readlines(hba_conf)
lines = [
s for s in hba_conf_file
if len(s.strip()) > 0 and not s.startswith('#')
]
# write filtered lines
self.os_ops.write(hba_conf, lines, truncate=True)
# replication-related settings
if allow_streaming:
# get auth method for host or local users
def get_auth_method(t):
return next((s.split()[-1]
for s in lines if s.startswith(t)), 'trust')
# get auth methods
auth_local = get_auth_method('local')
auth_host = get_auth_method('host')
subnet_base = ".".join(self.os_ops.host.split('.')[:-1] + ['0'])
new_lines = [
u"local\treplication\tall\t\t\t{}\n".format(auth_local),
u"host\treplication\tall\t127.0.0.1/32\t{}\n".format(auth_host),
u"host\treplication\tall\t::1/128\t\t{}\n".format(auth_host),
u"host\treplication\tall\t{}/24\t\t{}\n".format(subnet_base, auth_host),
u"host\tall\tall\t{}/24\t\t{}\n".format(subnet_base, auth_host),
u"host\tall\tall\tall\t{}\n".format(auth_host),
u"host\treplication\tall\tall\t{}\n".format(auth_host)
] # yapf: disable
# write missing lines
self.os_ops.write(hba_conf, new_lines)
# overwrite config file
self.os_ops.write(postgres_conf, '', truncate=True)
self.append_conf(fsync=fsync,
max_worker_processes=MAX_WORKER_PROCESSES,
log_statement=log_statement,
listen_addresses=self.host,
port=self.port) # yapf:disable
# common replication settings
if allow_streaming or allow_logical:
self.append_conf(max_replication_slots=MAX_REPLICATION_SLOTS,
max_wal_senders=MAX_WAL_SENDERS) # yapf: disable
# binary replication
if allow_streaming:
# select a proper wal_level for PostgreSQL
wal_level = 'replica' if self._pg_version >= PgVer('9.6') else 'hot_standby'
if self._pg_version < PgVer('13'):
self.append_conf(hot_standby=True,
wal_keep_segments=WAL_KEEP_SEGMENTS,
wal_level=wal_level) # yapf: disable
else:
self.append_conf(hot_standby=True,
wal_keep_size=WAL_KEEP_SIZE,
wal_level=wal_level) # yapf: disable
# logical replication
if allow_logical:
if self._pg_version < PgVer('10'):
raise InitNodeException("Logical replication is only "
"available on PostgreSQL 10 and newer")
self.append_conf(
max_logical_replication_workers=MAX_LOGICAL_REPLICATION_WORKERS,
wal_level='logical')
# disable UNIX sockets if asked to
if not unix_sockets:
self.append_conf(unix_socket_directories='')
return self
@method_decorator(positional_args_hack(['filename', 'line']))
def append_conf(self, line='', filename=PG_CONF_FILE, **kwargs):
"""
Append line to a config file.
Args:
line: string to be appended to config.
filename: config file (postgresql.conf by default).
**kwargs: named config options.
Returns:
This instance of :class:`.PostgresNode`.
Examples:
>>> append_conf(fsync=False)
>>> append_conf('log_connections = yes')
>>> append_conf(random_page_cost=1.5, fsync=True, ...)
>>> append_conf('postgresql.conf', 'synchronous_commit = off')
"""
lines = [line]
for option, value in iteritems(kwargs):
if isinstance(value, bool):
value = 'on' if value else 'off'
elif not str(value).replace('.', '', 1).isdigit():
value = "'{}'".format(value)
if value == '*':
lines.append("{} = '*'".format(option))
else:
# format a new config line
lines.append('{} = {}'.format(option, value))
config_name = self._os_ops.build_path(self.data_dir, filename)
conf_text = ''
for line in lines:
conf_text += text_type(line) + '\n'
self.os_ops.write(config_name, conf_text)
return self
def status(self):
"""
Check this node's status.
Returns:
An instance of :class:`.NodeStatus`.
"""
x = self._get_node_state()
assert type(x) is utils.PostgresNodeState
return x.node_status
def _get_node_state(self) -> utils.PostgresNodeState:
return utils.get_pg_node_state(
self._os_ops,
self.bin_dir,
self.data_dir,
self.utils_log_file
)
def get_control_data(self):
"""
Return contents of pg_control file.
"""
# this one is tricky (blame PG 9.4)
_params = [self._get_bin_path("pg_controldata")]
_params += ["-D"] if self._pg_version >= PgVer('9.5') else []
_params += [self.data_dir]
data = execute_utility2(self.os_ops, _params, self.utils_log_file)
out_dict = {}
for line in data.splitlines():
key, _, value = line.partition(':')
out_dict[key.strip()] = value.strip()
return out_dict
def slow_start(self, replica=False, dbname='template1', username=None, max_attempts=0, exec_env=None):
"""
Starts the PostgreSQL instance and then polls the instance
until it reaches the expected state (primary or replica). The state is checked
using the pg_is_in_recovery() function.
Args:
dbname:
username:
replica: If True, waits for the instance to be in recovery (i.e., replica mode).
If False, waits for the instance to be in primary mode. Default is False.
max_attempts:
"""
assert exec_env is None or type(exec_env) is dict
self.start(exec_env=exec_env)
try:
if replica:
query = 'SELECT pg_is_in_recovery()'
else:
query = 'SELECT not pg_is_in_recovery()'
# Call poll_query_until until the expected value is returned
suppressed_exceptions = {
InternalError,
QueryException,
ProgrammingError,
OperationalError
}
self.poll_query_until(
query=query,
dbname=dbname,
username=username or self.os_ops.username,
suppress=suppressed_exceptions,
max_attempts=max_attempts,
)
except: # noqa: E722
self.stop()