-
Notifications
You must be signed in to change notification settings - Fork 484
/
Copy pathCluster.pm
4330 lines (3340 loc) · 101 KB
/
Cluster.pm
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
# Copyright (c) 2021-2022, PostgreSQL Global Development Group
=pod
=head1 NAME
PostgreSQL::Test::Cluster - class representing PostgreSQL server instance
=head1 SYNOPSIS
use PostgreSQL::Test::Cluster;
my $node = PostgreSQL::Test::Cluster->new('mynode');
# Create a data directory with initdb
$node->init();
# Start the PostgreSQL server
$node->start();
# Add a setting and restart
$node->append_conf('postgresql.conf', 'hot_standby = on');
$node->restart();
# Modify or delete an existing setting
$node->adjust_conf('postgresql.conf', 'max_wal_senders', '10');
# get pg_config settings
# all the settings in one string
$pgconfig = $node->config_data;
# all the settings as a map
%config_map = ($node->config_data);
# specified settings
($incdir, $sharedir) = $node->config_data(qw(--includedir --sharedir));
# run a query with psql, like:
# echo 'SELECT 1' | psql -qAXt postgres -v ON_ERROR_STOP=1
$psql_stdout = $node->safe_psql('postgres', 'SELECT 1');
# Run psql with a timeout, capturing stdout and stderr
# as well as the psql exit code. Pass some extra psql
# options. If there's an error from psql raise an exception.
my ($stdout, $stderr, $timed_out);
my $cmdret = $node->psql('postgres', 'SELECT pg_sleep(600)',
stdout => \$stdout, stderr => \$stderr,
timeout => $PostgreSQL::Test::Utils::timeout_default,
timed_out => \$timed_out,
extra_params => ['--single-transaction'],
on_error_die => 1)
print "Sleep timed out" if $timed_out;
# Similar thing, more convenient in common cases
my ($cmdret, $stdout, $stderr) =
$node->psql('postgres', 'SELECT 1');
# run query every second until it returns 't'
# or times out
$node->poll_query_until('postgres', q|SELECT random() < 0.1;|')
or die "timed out";
# Do an online pg_basebackup
my $ret = $node->backup('testbackup1');
# Take a backup of a running server
my $ret = $node->backup_fs_hot('testbackup2');
# Take a backup of a stopped server
$node->stop;
my $ret = $node->backup_fs_cold('testbackup3')
# Restore it to create a new independent node (not a replica)
my $other_node = PostgreSQL::Test::Cluster->new('mycopy');
$other_node->init_from_backup($node, 'testbackup');
$other_node->start;
# Stop the server
$node->stop('fast');
# Find a free, unprivileged TCP port to bind some other service to
my $port = PostgreSQL::Test::Cluster::get_free_port();
=head1 DESCRIPTION
PostgreSQL::Test::Cluster contains a set of routines able to work on a PostgreSQL node,
allowing to start, stop, backup and initialize it with various options.
The set of nodes managed by a given test is also managed by this module.
In addition to node management, PostgreSQL::Test::Cluster instances have some wrappers
around Test::More functions to run commands with an environment set up to
point to the instance.
The IPC::Run module is required.
=cut
package PostgreSQL::Test::Cluster;
use strict;
use warnings;
use Carp;
use Config;
use Fcntl qw(:mode :flock :seek :DEFAULT);
use File::Basename;
use File::Path qw(rmtree mkpath);
use File::Spec;
use File::stat qw(stat);
use File::Temp ();
use IPC::Run;
use PostgreSQL::Version;
use PostgreSQL::Test::RecursiveCopy;
use Socket;
use Test::More;
use PostgreSQL::Test::Utils ();
use PostgreSQL::Test::BackgroundPsql ();
use Time::HiRes qw(usleep);
use Scalar::Util qw(blessed);
use POSIX qw(strftime);
our ($use_tcp, $test_localhost, $test_pghost, $last_host_assigned,
$last_port_assigned, @all_nodes, $died, $portdir);
our ($polar_global_hostid, $main_pid);
# the minimum version we believe to be compatible with this package without
# subclassing.
our $min_compat = 12;
# list of file reservations made by get_free_port
my @port_reservation_files;
# We want to choose a server port above the range that servers typically use
# on Unix systems and below the range those systems typically use for ephemeral
# client ports.
# That way we minimize the risk of getting a port collision. These two values
# are chosen to reflect that. We will always choose a port in this range.
my $port_lower_bound = 10200;
my $port_upper_bound = 32767;
INIT
{
# Set PGHOST for backward compatibility. This doesn't work for own_host
# nodes, so prefer to not rely on this when writing new tests.
$use_tcp = !$PostgreSQL::Test::Utils::use_unix_sockets;
$test_localhost = "127.0.0.1";
$last_host_assigned = 1;
if ($use_tcp)
{
$test_pghost = $test_localhost;
}
else
{
# On windows, replace windows-style \ path separators with / when
# putting socket directories either in postgresql.conf or libpq
# connection strings, otherwise they are interpreted as escapes.
$test_pghost = PostgreSQL::Test::Utils::tempdir_short;
$test_pghost =~ s!\\!/!g if $PostgreSQL::Test::Utils::windows_os;
}
$ENV{PGHOST} = $test_pghost;
$ENV{PGDATABASE} = 'postgres';
# Tracking of last port value assigned to accelerate free port lookup.
my $num_ports = $port_upper_bound - $port_lower_bound;
$last_port_assigned = int(rand() * $num_ports) + $port_lower_bound;
# Set the port lock directory
# If we're told to use a directory (e.g. from a buildfarm client)
# explicitly, use that
$portdir = $ENV{PG_TEST_PORT_DIR};
# Otherwise, try to use a directory at the top of the build tree
# or as a last resort use the tmp_check directory
my $build_dir = $ENV{top_builddir}
|| $PostgreSQL::Test::Utils::tmp_check;
$portdir ||= "$build_dir/portlock";
$portdir =~ s!\\!/!g;
# Make sure the directory exists
mkpath($portdir) unless -d $portdir;
$polar_global_hostid = 0;
}
=pod
=head1 METHODS
=over
=item $node->port()
Get the port number assigned to the host. This won't necessarily be a TCP port
open on the local host since we prefer to use unix sockets if possible.
Use $node->connstr() if you want a connection string.
=cut
sub port
{
my ($self) = @_;
return $self->{_port};
}
=pod
=item $node->host()
Return the host (like PGHOST) for this instance. May be a UNIX socket path.
Use $node->connstr() if you want a connection string.
=cut
sub host
{
my ($self) = @_;
return $self->{_host};
}
=pod
=item $node->basedir()
The directory all the node's files will be within - datadir, archive directory,
backups, etc.
=cut
sub basedir
{
my ($self) = @_;
return $self->{_basedir};
}
=pod
=item $node->name()
The name assigned to the node at creation time.
=cut
sub name
{
my ($self) = @_;
return $self->{_name};
}
=pod
=item $node->logfile()
Path to the PostgreSQL log file for this instance.
=cut
sub logfile
{
my ($self) = @_;
return $self->{_logfile};
}
=pod
=item $node->connstr()
Get a libpq connection string that will establish a connection to
this node. Suitable for passing to psql, DBD::Pg, etc.
=cut
sub connstr
{
my ($self, $dbname) = @_;
my $pgport = $self->port;
my $pghost = $self->host;
if (!defined($dbname))
{
return "port=$pgport host=$pghost";
}
# Escape properly the database string before using it, only
# single quotes and backslashes need to be treated this way.
$dbname =~ s#\\#\\\\#g;
$dbname =~ s#\'#\\\'#g;
return "port=$pgport host=$pghost dbname='$dbname'";
}
=pod
=item $node->group_access()
Does the data dir allow group access?
=cut
sub group_access
{
my ($self) = @_;
my $dir_stat = stat($self->data_dir);
defined($dir_stat)
or die('unable to stat ' . $self->data_dir);
return (S_IMODE($dir_stat->mode) == 0750);
}
=pod
=item $node->data_dir()
Returns the path to the data directory. postgresql.conf and pg_hba.conf are
always here.
=cut
sub data_dir
{
my ($self) = @_;
my $res = $self->basedir;
return "$res/pgdata";
}
=pod
=item $node->archive_dir()
If archiving is enabled, WAL files go here.
=cut
sub archive_dir
{
my ($self) = @_;
my $basedir = $self->basedir;
return "$basedir/archives";
}
=pod
=item $node->backup_dir()
The output path for backups taken with $node->backup()
=cut
sub backup_dir
{
my ($self) = @_;
my $basedir = $self->basedir;
return "$basedir/backup";
}
=pod
=item $node->install_path()
The configured install path (if any) for the node.
=cut
sub install_path
{
my ($self) = @_;
return $self->{_install_path};
}
=pod
=item $node->pg_version()
The version number for the node, from PostgreSQL::Version.
=cut
sub pg_version
{
my ($self) = @_;
return $self->{_pg_version};
}
=pod
=item $node->config_data( option ...)
Return configuration data from pg_config, using options (if supplied).
The options will be things like '--sharedir'.
If no options are supplied, return a string in scalar context or a map in
array context.
If options are supplied, return the list of values.
=cut
sub config_data
{
my ($self, @options) = @_;
local %ENV = $self->_get_env();
my ($stdout, $stderr);
my $result =
IPC::Run::run [ $self->installed_command('pg_config'), @options ],
'>', \$stdout, '2>', \$stderr
or die "could not execute pg_config";
# standardize line endings
$stdout =~ s/\r(?=\n)//g;
# no options, scalar context: just hand back the output
return $stdout unless (wantarray || @options);
chomp($stdout);
# exactly one option: hand back the output (minus LF)
return $stdout if (@options == 1);
my @lines = split(/\n/, $stdout);
# more than one option: hand back the list of values;
return @lines if (@options);
# no options, array context: return a map
my @map;
foreach my $line (@lines)
{
my ($k, $v) = split(/ = /, $line, 2);
push(@map, $k, $v);
}
return @map;
}
=pod
=item $node->info()
Return a string containing human-readable diagnostic information (paths, etc)
about this node.
=cut
sub info
{
my ($self) = @_;
my $_info = '';
open my $fh, '>', \$_info or die;
print $fh "Name: " . $self->name . "\n";
print $fh "Version: " . $self->{_pg_version} . "\n"
if $self->{_pg_version};
print $fh "Data directory: " . $self->data_dir . "\n";
print $fh "Backup directory: " . $self->backup_dir . "\n";
print $fh "Archive directory: " . $self->archive_dir . "\n";
print $fh "Connection string: " . $self->connstr . "\n";
print $fh "Log file: " . $self->logfile . "\n";
print $fh "Install Path: ", $self->{_install_path} . "\n"
if $self->{_install_path};
close $fh or die;
return $_info;
}
=pod
=item $node->dump_info()
Print $node->info()
=cut
sub dump_info
{
my ($self) = @_;
print $self->info;
return;
}
# Internal method to set up trusted pg_hba.conf for replication. Not
# documented because you shouldn't use it, it's called automatically if needed.
sub set_replication_conf
{
my ($self) = @_;
my $pgdata = $self->data_dir;
$self->host eq $test_pghost
or croak "set_replication_conf only works with the default host";
open my $hba, '>>', "$pgdata/pg_hba.conf";
print $hba
"\n# Allow replication (set up by PostgreSQL::Test::Cluster.pm)\n";
if ($PostgreSQL::Test::Utils::windows_os
&& !$PostgreSQL::Test::Utils::use_unix_sockets)
{
print $hba
"host replication all $test_localhost/32 sspi include_realm=1 map=regress\n";
}
close $hba;
return;
}
=pod
=item $node->init(...)
Initialize a new cluster for testing.
Authentication is set up so that only the current OS user can access the
cluster. On Unix, we use Unix domain socket connections, with the socket in
a directory that's only accessible to the current user to ensure that.
On Windows, we use SSPI authentication to ensure the same (by pg_regress
--config-auth).
WAL archiving can be enabled on this node by passing the keyword parameter
has_archiving => 1. This is disabled by default.
postgresql.conf can be set up for replication by passing the keyword
parameter allows_streaming => 'logical' or 'physical' (passing 1 will also
suffice for physical replication) depending on type of replication that
should be enabled. This is disabled by default.
The new node is set up in a fast but unsafe configuration where fsync is
disabled.
=cut
sub init
{
my ($self, %params) = @_;
my $port = $self->port;
my $pgdata = $self->data_dir;
my $host = $self->host;
local %ENV = $self->_get_env();
$params{allows_streaming} = 0 unless defined $params{allows_streaming};
$params{has_archiving} = 0 unless defined $params{has_archiving};
mkdir $self->backup_dir;
mkdir $self->archive_dir;
if (defined $ENV{INITDB_TEMPLATE} && !defined $params{extra})
{
my $template_dir = $ENV{INITDB_TEMPLATE} . "-pg";
if (defined $params{init_polar_node} and $params{init_polar_node})
{
$template_dir = $ENV{INITDB_TEMPLATE} . "-chksum-pg";
$self->{_enable_data_checksums} = 1;
}
print "initializing database system by copying initdb template\n";
PostgreSQL::Test::Utils::system_or_bail('cp', '-RPp',
$template_dir, $pgdata);
}
else
{
print "initializing database system by running initdb\n";
if (defined $params{init_polar_node} and $params{init_polar_node})
{
$params{extra} = [] unless defined $params{extra};
push @{ $params{extra} }, '-k';
$self->{_enable_data_checksums} = 1;
}
PostgreSQL::Test::Utils::system_or_bail('initdb', '-D', $pgdata, '-A',
'trust', '-N', @{ $params{extra} });
}
PostgreSQL::Test::Utils::system_or_bail($ENV{PG_REGRESS},
'--config-auth', $pgdata, @{ $params{auth_extra} });
open my $conf, '>>', "$pgdata/postgresql.conf";
print $conf "\n# Added by PostgreSQL::Test::Cluster.pm\n";
print $conf "fsync = off\n";
print $conf "restart_after_crash = off\n";
print $conf "log_line_prefix = '%m [%p] %q%a '\n";
print $conf "log_statement = all\n";
print $conf "log_replication_commands = on\n";
print $conf "wal_retrieve_retry_interval = '500ms'\n";
print $conf "polar_enable_multi_syslogger = off\n";
print $conf "log_destination = stderr\n";
print $conf "polar_enable_output_search_path_to_log = off\n";
# If a setting tends to affect whether tests pass or fail, print it after
# TEMP_CONFIG. Otherwise, print it before TEMP_CONFIG, thereby permitting
# overrides. Settings that merely improve performance or ease debugging
# belong before TEMP_CONFIG.
print $conf PostgreSQL::Test::Utils::slurp_file($ENV{TEMP_CONFIG})
if defined $ENV{TEMP_CONFIG};
if ($params{allows_streaming})
{
if ($params{allows_streaming} eq "logical")
{
print $conf "wal_level = logical\n";
}
else
{
print $conf "wal_level = replica\n";
}
print $conf "max_wal_senders = 10\n";
print $conf "max_replication_slots = 10\n";
print $conf "wal_log_hints = on\n";
print $conf "hot_standby = on\n";
# conservative settings to ensure we can run multiple postmasters:
print $conf "shared_buffers = 1MB\n";
print $conf "max_connections = 10\n";
# limit disk space consumption, too:
print $conf "max_wal_size = 4GB\n";
}
else
{
print $conf "wal_level = minimal\n";
print $conf "max_wal_senders = 0\n";
}
print $conf "port = $port\n";
if ($use_tcp)
{
print $conf "unix_socket_directories = ''\n";
print $conf "listen_addresses = '$host'\n";
}
else
{
print $conf "unix_socket_directories = '$host'\n";
print $conf "listen_addresses = ''\n";
}
if (defined $params{init_polar_node} and $params{init_polar_node})
{
$polar_global_hostid++;
print $conf $self->polar_default_conf;
}
close $conf;
chmod($self->group_access ? 0640 : 0600, "$pgdata/postgresql.conf")
or die("unable to set permissions for $pgdata/postgresql.conf");
$self->set_replication_conf if $params{allows_streaming};
$self->enable_archiving if $params{has_archiving};
return;
}
=pod
=item $node->append_conf(filename, str)
A shortcut method to append to files like pg_hba.conf and postgresql.conf.
Does no validation or sanity checking. Does not reload the configuration
after writing.
A newline is automatically appended to the string.
=cut
sub append_conf
{
my ($self, $filename, $str) = @_;
my $conffile = $self->data_dir . '/' . $filename;
PostgreSQL::Test::Utils::append_to_file($conffile, $str . "\n");
chmod($self->group_access() ? 0640 : 0600, $conffile)
or die("unable to set permissions for $conffile");
return;
}
=pod
=item $node->adjust_conf(filename, setting, value, skip_equals)
Modify the named config file setting with the value. If the value is undefined,
instead delete the setting. If the setting is not present no action is taken.
This will write "$setting = $value\n" in place of the existing line,
unless skip_equals is true, in which case it will write
"$setting $value\n". If the value needs to be quoted it is the caller's
responsibility to do that.
=cut
sub adjust_conf
{
my ($self, $filename, $setting, $value, $skip_equals) = @_;
my $conffile = $self->data_dir . '/' . $filename;
my $contents = PostgreSQL::Test::Utils::slurp_file($conffile);
my @lines = split(/\n/, $contents);
my @result;
my $eq = $skip_equals ? '' : '= ';
foreach my $line (@lines)
{
if ($line !~ /^$setting\W/)
{
push(@result, "$line\n");
}
elsif (defined $value)
{
push(@result, "$setting $eq$value\n");
}
}
open my $fh, ">", $conffile
or croak "could not write \"$conffile\": $!";
print $fh @result;
close $fh;
chmod($self->group_access() ? 0640 : 0600, $conffile)
or die("unable to set permissions for $conffile");
}
=pod
=item $node->backup(backup_name)
Create a hot backup with B<pg_basebackup> in subdirectory B<backup_name> of
B<< $node->backup_dir >>, including the WAL.
By default, WAL files are fetched at the end of the backup, not streamed.
You can adjust that and other things by passing an array of additional
B<pg_basebackup> command line options in the keyword parameter backup_options.
You'll have to configure a suitable B<max_wal_senders> on the
target server since it isn't done by default.
=cut
sub backup
{
my ($self, $backup_name, %params) = @_;
my $backup_path = $self->backup_dir . '/' . $backup_name;
my $name = $self->name;
local %ENV = $self->_get_env();
print "# Taking pg_basebackup $backup_name from node \"$name\"\n";
PostgreSQL::Test::Utils::system_or_bail(
'pg_basebackup', '-D',
$backup_path, '-h',
$self->host, '-p',
$self->port, '--checkpoint',
'fast', '--no-sync',
@{ $params{backup_options} });
print "# Backup finished\n";
return;
}
sub polar_backup
{
my ($self, $backup_name, $polardata) = @_;
my $backup_path = $self->backup_dir . '/' . $backup_name;
my $name = $self->name;
print "# Taking polar_basebackup $backup_name from node \"$name\"\n";
PostgreSQL::Test::Utils::system_or_bail(
'polar_basebackup', '-D',
$backup_path, '-h',
$self->host, '-p',
$self->port, '--no-sync',
'--polardata=' . $polardata, '-v');
print "# Polar backup finished\n";
return;
}
=item $node->backup_fs_cold(backup_name)
Create a backup with a filesystem level copy in subdirectory B<backup_name> of
B<< $node->backup_dir >>, including WAL. The server must be
stopped as no attempt to handle concurrent writes is made.
Use B<backup> or B<backup_fs_hot> if you want to back up a running server.
=cut
sub backup_fs_cold
{
my ($self, $backup_name) = @_;
PostgreSQL::Test::RecursiveCopy::copypath(
$self->data_dir,
$self->backup_dir . '/' . $backup_name,
filterfn => sub {
my $src = shift;
return ($src ne 'log' and $src ne 'postmaster.pid');
});
return;
}
=pod
=item $node->init_from_backup(root_node, backup_name)
Initialize a node from a backup, which may come from this node or a different
node. root_node must be a PostgreSQL::Test::Cluster reference, backup_name the string name
of a backup previously created on that node with $node->backup.
Does not start the node after initializing it.
By default, the backup is assumed to be plain format. To restore from
a tar-format backup, pass the name of the tar program to use in the
keyword parameter tar_program. Note that tablespace tar files aren't
handled here.
Streaming replication can be enabled on this node by passing the keyword
parameter has_streaming => 1. This is disabled by default.
Restoring WAL segments from archives using restore_command can be enabled
by passing the keyword parameter has_restoring => 1. This is disabled by
default.
If has_restoring is used, standby mode is used by default. To use
recovery mode instead, pass the keyword parameter standby => 0.
The backup is copied, leaving the original unmodified. pg_hba.conf is
unconditionally set to enable replication connections.
=cut
sub init_from_backup
{
my ($self, $root_node, $backup_name, %params) = @_;
my $backup_path = $root_node->backup_dir . '/' . $backup_name;
my $host = $self->host;
my $port = $self->port;
my $node_name = $self->name;
my $root_name = $root_node->name;
$params{has_streaming} = 0 unless defined $params{has_streaming};
$params{has_restoring} = 0 unless defined $params{has_restoring};
$params{standby} = 1 unless defined $params{standby};
print
"# Initializing node \"$node_name\" from backup \"$backup_name\" of node \"$root_name\"\n";
croak "Backup \"$backup_name\" does not exist at $backup_path"
unless -d $backup_path;
mkdir $self->backup_dir;
mkdir $self->archive_dir;
my $data_path = $self->data_dir;
if (defined $params{tar_program})
{
mkdir($data_path);
PostgreSQL::Test::Utils::system_or_bail($params{tar_program}, 'xf',
$backup_path . '/base.tar',
'-C', $data_path);
PostgreSQL::Test::Utils::system_or_bail(
$params{tar_program}, 'xf',
$backup_path . '/pg_wal.tar', '-C',
$data_path . '/pg_wal');
}
else
{
rmdir($data_path);
PostgreSQL::Test::RecursiveCopy::copypath($backup_path, $data_path);
}
chmod(0700, $data_path);
# Base configuration for this node
$self->append_conf(
'postgresql.conf',
qq(
port = $port
));
if ($use_tcp)
{
$self->append_conf('postgresql.conf', "listen_addresses = '$host'");
}
else
{
$self->append_conf('postgresql.conf',
"unix_socket_directories = '$host'");
}
$self->enable_streaming($root_node) if $params{has_streaming};
$self->enable_restoring($root_node, $params{standby})
if $params{has_restoring};
return;
}
=pod
=item $node->rotate_logfile()
Switch to a new PostgreSQL log file. This does not alter any running
PostgreSQL process. Subsequent method calls, including pg_ctl invocations,
will use the new name. Return the new name.
=cut
sub rotate_logfile
{
my ($self) = @_;
$self->{_logfile} = sprintf('%s_%d.log',
$self->{_logfile_base},
++$self->{_logfile_generation});
return $self->{_logfile};
}
=pod
=item $node->start(%params) => success_or_failure
Wrapper for pg_ctl start
Start the node and wait until it is ready to accept connections.
=over
=item fail_ok => 1
By default, failure terminates the entire F<prove> invocation. If given,
instead return a true or false value to indicate success or failure.
=back
=cut
sub start
{
my ($self, %params) = @_;
my $port = $self->port;
my $pgdata = $self->data_dir;
my $name = $self->name;
my $ret;
BAIL_OUT("node \"$name\" is already running") if defined $self->{_pid};
print("### Starting node \"$name\"\n");
# Temporarily unset PGAPPNAME so that the server doesn't
# inherit it. Otherwise this could affect libpqwalreceiver
# connections in confusing ways.
local %ENV = $self->_get_env(PGAPPNAME => undef);
# Note: We set the cluster_name here, not in postgresql.conf (in
# sub init) so that it does not get copied to standbys.
# -w is now the default but having it here does no harm and helps
# compatibility with older versions.
$ret = PostgreSQL::Test::Utils::system_log(
'pg_ctl', '-w', '-D', $self->data_dir,
'-l', $self->logfile, '-o', "--cluster-name=$name",
'start');
if ($ret != 0)
{
print "# pg_ctl start failed; logfile:\n";
print PostgreSQL::Test::Utils::slurp_file($self->logfile);
# pg_ctl could have timed out, so check to see if there's a pid file;
# otherwise our END block will fail to shut down the new postmaster.
$self->_update_pid(-1);
BAIL_OUT("pg_ctl start failed") unless $params{fail_ok};
return 0;
}
$self->_update_pid(1);
return 1;
}
=pod
=item $node->kill9()
Send SIGKILL (signal 9) to the postmaster.
Note: if the node is already known stopped, this does nothing.
However, if we think it's running and it's not, it's important for
this to fail. Otherwise, tests might fail to detect server crashes.
=cut
sub kill9
{
my ($self) = @_;
my $name = $self->name;
return unless defined $self->{_pid};
local %ENV = $self->_get_env();
print "### Killing node \"$name\" using signal 9\n";
kill(9, $self->{_pid});
$self->{_pid} = undef;
return;
}
=pod
=item $node->stop(mode)
Stop the node using pg_ctl -m $mode and wait for it to stop.
Note: if the node is already known stopped, this does nothing.
However, if we think it's running and it's not, it's important for
this to fail. Otherwise, tests might fail to detect server crashes.
With optional extra param fail_ok => 1, returns 0 for failure
instead of bailing out.
=cut
sub stop