Debian Codegraph @

src/test/perl/PostgreSQL/Test/Cluster.pm

raw ◀ ▶
1 Debian patch touch this file
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 =pod
5
6 =head1 NAME
7
8 PostgreSQL::Test::Cluster - class representing PostgreSQL server instance
9
10 =head1 SYNOPSIS
11
12 use PostgreSQL::Test::Cluster;
13
14 my $node = PostgreSQL::Test::Cluster->new('mynode');
15
16 # Create a data directory with initdb
17 $node->init();
18
19 # Start the PostgreSQL server
20 $node->start();
21
22 # Add a setting and restart
23 $node->append_conf('postgresql.conf', 'hot_standby = on');
24 $node->restart();
25
26 # Modify or delete an existing setting
27 $node->adjust_conf('postgresql.conf', 'max_wal_senders', '10');
28
29 # get pg_config settings
30 # all the settings in one string
31 $pgconfig = $node->config_data;
32 # all the settings as a map
33 %config_map = ($node->config_data);
34 # specified settings
35 ($incdir, $sharedir) = $node->config_data(qw(--includedir --sharedir));
36
37 # run a query with psql, like:
38 # echo 'SELECT 1' | psql -qAXt postgres -v ON_ERROR_STOP=1
39 $psql_stdout = $node->safe_psql('postgres', 'SELECT 1');
40
41 # Run psql with a timeout, capturing stdout and stderr
42 # as well as the psql exit code. Pass some extra psql
43 # options. If there's an error from psql raise an exception.
44 my ($stdout, $stderr, $timed_out);
45 my $cmdret = $node->psql('postgres', 'SELECT pg_sleep(600)',
46 stdout => \$stdout, stderr => \$stderr,
47 timeout => $PostgreSQL::Test::Utils::timeout_default,
48 timed_out => \$timed_out,
49 extra_params => ['--single-transaction'],
50 on_error_die => 1)
51 print "Sleep timed out" if $timed_out;
52
53 # Similar thing, more convenient in common cases
54 my ($cmdret, $stdout, $stderr) =
55 $node->psql('postgres', 'SELECT 1');
56
57 # run query every second until it returns 't'
58 # or times out
59 $node->poll_query_until('postgres', q|SELECT random() < 0.1;|')
60 or die "timed out";
61
62 # Do an online pg_basebackup
63 my $ret = $node->backup('testbackup1');
64
65 # Take a backup of a stopped server
66 $node->stop;
67 my $ret = $node->backup_fs_cold('testbackup3')
68
69 # Restore it to create a new independent node (not a replica)
70 my $other_node = PostgreSQL::Test::Cluster->new('mycopy');
71 $other_node->init_from_backup($node, 'testbackup');
72 $other_node->start;
73
74 # Stop the server
75 $node->stop('fast');
76
77 # Find a free, unprivileged TCP port to bind some other service to
78 my $port = PostgreSQL::Test::Cluster::get_free_port();
79
80 =head1 DESCRIPTION
81
82 PostgreSQL::Test::Cluster contains a set of routines able to work on a PostgreSQL node,
83 allowing to start, stop, backup and initialize it with various options.
84 The set of nodes managed by a given test is also managed by this module.
85
86 In addition to node management, PostgreSQL::Test::Cluster instances have some wrappers
87 around Test::More functions to run commands with an environment set up to
88 point to the instance.
89
90 The IPC::Run module is required.
91
92 =cut
93
94 package PostgreSQL::Test::Cluster;
95
96 use strict;
97 use warnings FATAL => 'all';
98
99 use Carp;
100 use Config;
101 use Fcntl qw(:mode :flock :seek :DEFAULT);
102 use File::Basename;
103 use File::Path qw(rmtree mkpath);
104 use File::Spec;
105 use File::stat qw(stat);
106 use File::Temp ();
107 use IO::Socket::INET;
108 use IPC::Run;
109 use PostgreSQL::Version;
110 use PostgreSQL::Test::RecursiveCopy;
111 use Socket;
112 use Test::More;
113 use PostgreSQL::Test::Utils ();
114 use PostgreSQL::Test::BackgroundPsql ();
115 use Text::ParseWords qw(shellwords);
116 use Time::HiRes qw(usleep);
117 use Scalar::Util qw(blessed);
118
119 our ($use_tcp, $test_localhost, $test_pghost, $last_host_assigned,
120 $last_port_assigned, @all_nodes, $died, $portdir);
121
122 # the minimum version we believe to be compatible with this package without
123 # subclassing.
124 our $min_compat = 12;
125
126 # list of file reservations made by get_free_port
127 my @port_reservation_files;
128
129 # We want to choose a server port above the range that servers typically use
130 # on Unix systems and below the range those systems typically use for ephemeral
131 # client ports.
132 # That way we minimize the risk of getting a port collision. These two values
133 # are chosen to reflect that. We will always choose a port in this range.
134 my $port_lower_bound = 10200;
135 my $port_upper_bound = 32767;
136
137 INIT
138 {
139
140 # Set PGHOST for backward compatibility. This doesn't work for own_host
141 # nodes, so prefer to not rely on this when writing new tests.
142 $use_tcp = !$PostgreSQL::Test::Utils::use_unix_sockets;
143 $test_localhost = "127.0.0.1";
144 $last_host_assigned = 1;
145 if ($use_tcp)
146 {
147 $test_pghost = $test_localhost;
148 }
149 else
150 {
151 # On windows, replace windows-style \ path separators with / when
152 # putting socket directories either in postgresql.conf or libpq
153 # connection strings, otherwise they are interpreted as escapes.
154 $test_pghost = PostgreSQL::Test::Utils::tempdir_short;
155 $test_pghost =~ s!\\!/!g if $PostgreSQL::Test::Utils::windows_os;
156 }
157 $ENV{PGHOST} = $test_pghost;
158 $ENV{PGDATABASE} = 'postgres';
159
160 # Tracking of last port value assigned to accelerate free port lookup.
161 my $num_ports = $port_upper_bound - $port_lower_bound;
162 $last_port_assigned = int(rand() * $num_ports) + $port_lower_bound;
163
164 # Set the port lock directory
165
166 # If we're told to use a directory (e.g. from a buildfarm client)
167 # explicitly, use that
168 $portdir = $ENV{PG_TEST_PORT_DIR};
169 # Otherwise, try to use a directory at the top of the build tree
170 # or as a last resort use the tmp_check directory
171 my $build_dir = $ENV{top_builddir}
172 || $PostgreSQL::Test::Utils::tmp_check;
173 $portdir ||= "$build_dir/portlock";
174 $portdir =~ s!\\!/!g;
175 # Make sure the directory exists
176 mkpath($portdir) unless -d $portdir;
177
178 #
179 # Signal handlers
180 #
181 $SIG{TERM} = $SIG{INT} = sub { die "death by signal"; };
182 }
183
184 =pod
185
186 =head1 METHODS
187
188 =over
189
190 =item $node->port()
191
192 Get the port number assigned to the host. This won't necessarily be a TCP port
193 open on the local host since we prefer to use unix sockets if possible.
194
195 Use $node->connstr() if you want a connection string.
196
197 =cut
198
199 sub port
200 {
201 my ($self) = @_;
202 return $self->{_port};
203 }
204
205 =pod
206
207 =item $node->host()
208
209 Return the host (like PGHOST) for this instance. May be a UNIX socket path.
210
211 Use $node->connstr() if you want a connection string.
212
213 =cut
214
215 sub host
216 {
217 my ($self) = @_;
218 return $self->{_host};
219 }
220
221 =pod
222
223 =item $node->basedir()
224
225 The directory all the node's files will be within - datadir, archive directory,
226 backups, etc.
227
228 =cut
229
230 sub basedir
231 {
232 my ($self) = @_;
233 return $self->{_basedir};
234 }
235
236 =pod
237
238 =item $node->name()
239
240 The name assigned to the node at creation time.
241
242 =cut
243
244 sub name
245 {
246 my ($self) = @_;
247 return $self->{_name};
248 }
249
250 =pod
251
252 =item $node->logfile()
253
254 Path to the PostgreSQL log file for this instance.
255
256 =cut
257
258 sub logfile
259 {
260 my ($self) = @_;
261 return $self->{_logfile};
262 }
263
264 =pod
265
266 =item $node->connstr()
267
268 Get a libpq connection string that will establish a connection to
269 this node. Suitable for passing to psql, DBD::Pg, etc.
270
271 =cut
272
273 sub connstr
274 {
275 my ($self, $dbname) = @_;
276 my $pgport = $self->port;
277 my $pghost = $self->host;
278 if (!defined($dbname))
279 {
280 return "port=$pgport host=$pghost";
281 }
282
283 # Escape properly the database string before using it, only
284 # single quotes and backslashes need to be treated this way.
285 $dbname =~ s#\\#\\\\#g;
286 $dbname =~ s#\'#\\\'#g;
287
288 return "port=$pgport host=$pghost dbname='$dbname'";
289 }
290
291 =pod
292
293 =item $node->raw_connect()
294
295 Open a raw TCP or Unix domain socket connection to the server. This is
296 used by low-level protocol and connection limit tests.
297
298 =cut
299
300 sub raw_connect
301 {
302 my ($self) = @_;
303 my $pgport = $self->port;
304 my $pghost = $self->host;
305
306 my $socket;
307 if ($PostgreSQL::Test::Utils::use_unix_sockets)
308 {
309 require IO::Socket::UNIX;
310 my $path = "$pghost/.s.PGSQL.$pgport";
311
312 $socket = IO::Socket::UNIX->new(
313 Type => SOCK_STREAM(),
314 Peer => $path,
315 ) or die "Cannot create socket - $IO::Socket::errstr\n";
316 }
317 else
318 {
319 $socket = IO::Socket::INET->new(
320 PeerHost => $pghost,
321 PeerPort => $pgport,
322 Proto => 'tcp'
323 ) or die "Cannot create socket - $IO::Socket::errstr\n";
324 }
325 return $socket;
326 }
327
328 =pod
329
330 =item $node->raw_connect_works()
331
332 Check if raw_connect() function works on this platform. This should
333 be called to SKIP any tests that require raw_connect().
334
335 This tries to connect to the server, to test whether it works or not,,
336 so the server is up and running. Otherwise this can return 0 even if
337 there's nothing wrong with raw_connect() itself.
338
339 Notably, raw_connect() does not work on Unix domain sockets on
340 Strawberry perl 5.26.3.1 on Windows, which we use in Cirrus CI images
341 as of this writing. It dies with "not implemented on this
342 architecture".
343
344 =cut
345
346 sub raw_connect_works
347 {
348 my ($self) = @_;
349
350 # If we're using Unix domain sockets, we need a working
351 # IO::Socket::UNIX implementation.
352 if ($PostgreSQL::Test::Utils::use_unix_sockets)
353 {
354 eval {
355 my $sock = $self->raw_connect();
•356 $sock->send('foo');
357 $sock->close();
358 };
•359 if ($@ =~ /not implemented/ or $@ =~ /Cannot determine peer address/)
360 {
361 diag "IO::Socket::UNIX does not work: $@";
362 return 0;
363 }
364 }
365 return 1;
366 }
367
368 =pod
369
370 =item $node->group_access()
371
372 Does the data dir allow group access?
373
374 =cut
375
376 sub group_access
377 {
378 my ($self) = @_;
379
380 my $dir_stat = stat($self->data_dir);
381
382 defined($dir_stat)
383 or die('unable to stat ' . $self->data_dir);
384
385 return (S_IMODE($dir_stat->mode) == 0750);
386 }
387
388 =pod
389
390 =item $node->data_dir()
391
392 Returns the path to the data directory. postgresql.conf and pg_hba.conf are
393 always here.
394
395 =cut
396
397 sub data_dir
398 {
399 my ($self) = @_;
400 my $res = $self->basedir;
401 return "$res/pgdata";
402 }
403
404 =pod
405
406 =item $node->archive_dir()
407
408 If archiving is enabled, WAL files go here.
409
410 =cut
411
412 sub archive_dir
413 {
414 my ($self) = @_;
415 my $basedir = $self->basedir;
416 return "$basedir/archives";
417 }
418
419 =pod
420
421 =item $node->backup_dir()
422
423 The output path for backups taken with $node->backup()
424
425 =cut
426
427 sub backup_dir
428 {
429 my ($self) = @_;
430 my $basedir = $self->basedir;
431 return "$basedir/backup";
432 }
433
434 =pod
435
436 =item $node->install_path()
437
438 The configured install path (if any) for the node.
439
440 =cut
441
442 sub install_path
443 {
444 my ($self) = @_;
445 return $self->{_install_path};
446 }
447
448 =pod
449
450 =item $node->pg_version()
451
452 The version number for the node, from PostgreSQL::Version.
453
454 =cut
455
456 sub pg_version
457 {
458 my ($self) = @_;
459 return $self->{_pg_version};
460 }
461
462 =pod
463
464 =item $node->config_data( option ...)
465
466 Return configuration data from pg_config, using options (if supplied).
467 The options will be things like '--sharedir'.
468
469 If no options are supplied, return a string in scalar context or a map in
470 array context.
471
472 If options are supplied, return the list of values.
473
474 =cut
475
476 sub config_data
477 {
478 my ($self, @options) = @_;
479 local %ENV = $self->_get_env();
480
481 my ($stdout, $stderr);
482 my $result =
483 IPC::Run::run [ $self->installed_command('pg_config'), @options ],
484 '>', \$stdout, '2>', \$stderr
485 or die "could not execute pg_config";
486 # standardize line endings
487 $stdout =~ s/\r(?=\n)//g;
488 # no options, scalar context: just hand back the output
489 return $stdout unless (wantarray || @options);
490 chomp($stdout);
491 # exactly one option: hand back the output (minus LF)
492 return $stdout if (@options == 1);
493 my @lines = split(/\n/, $stdout);
494 # more than one option: hand back the list of values;
495 return @lines if (@options);
496 # no options, array context: return a map
497 my @map;
498 foreach my $line (@lines)
499 {
500 my ($k, $v) = split(/ = /, $line, 2);
501 push(@map, $k, $v);
502 }
503 return @map;
504 }
505
506 =pod
507
508 =item $node->info()
509
510 Return a string containing human-readable diagnostic information (paths, etc)
511 about this node.
512
513 =cut
514
515 sub info
516 {
517 my ($self) = @_;
518 my $_info = '';
519 open my $fh, '>', \$_info or die;
520 print $fh "Name: " . $self->name . "\n";
521 print $fh "Version: " . $self->{_pg_version} . "\n"
522 if $self->{_pg_version};
523 print $fh "Data directory: " . $self->data_dir . "\n";
524 print $fh "Backup directory: " . $self->backup_dir . "\n";
525 print $fh "Archive directory: " . $self->archive_dir . "\n";
526 print $fh "Connection string: " . $self->connstr . "\n";
527 print $fh "Log file: " . $self->logfile . "\n";
528 print $fh "Install Path: ", $self->{_install_path} . "\n"
529 if $self->{_install_path};
530 close $fh or die;
531 return $_info;
532 }
533
534 =pod
535
536 =item $node->dump_info()
537
538 Print $node->info()
539
540 =cut
541
542 sub dump_info
543 {
544 my ($self) = @_;
545 print $self->info;
546 return;
547 }
548
549
550 # Internal method to set up trusted pg_hba.conf for replication. Not
551 # documented because you shouldn't use it, it's called automatically if needed.
552 sub set_replication_conf
553 {
554 my ($self) = @_;
555 my $pgdata = $self->data_dir;
556
557 $self->host eq $test_pghost
558 or croak "set_replication_conf only works with the default host";
559
560 open my $hba, '>>', "$pgdata/pg_hba.conf" or die $!;
561 print $hba
562 "\n# Allow replication (set up by PostgreSQL::Test::Cluster.pm)\n";
563 if ($PostgreSQL::Test::Utils::windows_os
564 && !$PostgreSQL::Test::Utils::use_unix_sockets)
565 {
566 print $hba
567 "host replication all $test_localhost/32 sspi include_realm=1 map=regress\n";
568 }
569 close $hba;
570 return;
571 }
572
573 =pod
574
575 =item $node->init(...)
576
577 Initialize a new cluster for testing.
578
579 Authentication is set up so that only the current OS user can access the
580 cluster. On Unix, we use Unix domain socket connections, with the socket in
581 a directory that's only accessible to the current user to ensure that.
582 On Windows, we use SSPI authentication to ensure the same (by pg_regress
583 --config-auth).
584
585 WAL archiving can be enabled on this node by passing the keyword parameter
586 has_archiving => 1. This is disabled by default.
587
588 Data checksums can be forced off by passing no_data_checksums => 1.
589
590 postgresql.conf can be set up for replication by passing the keyword
591 parameter allows_streaming => 'logical' or 'physical' (passing 1 will also
592 suffice for physical replication) depending on type of replication that
593 should be enabled. This is disabled by default.
594
595 force_initdb => 1 will force the initialization of the cluster with a new
596 initdb rather than copying the data folder from a template.
597
598 The new node is set up in a fast but unsafe configuration where fsync is
599 disabled.
600
601 =cut
602
603 sub init
604 {
605 my ($self, %params) = @_;
606 my $port = $self->port;
607 my $pgdata = $self->data_dir;
608 my $host = $self->host;
609
610 local %ENV = $self->_get_env();
611
612 $params{allows_streaming} = 0 unless defined $params{allows_streaming};
613 $params{force_initdb} = 0 unless defined $params{force_initdb};
614 $params{has_archiving} = 0 unless defined $params{has_archiving};
615
616 my $initdb_extra_opts_env = $ENV{PG_TEST_INITDB_EXTRA_OPTS};
617 if (defined $initdb_extra_opts_env)
618 {
619 push @{ $params{extra} }, shellwords($initdb_extra_opts_env);
620 }
621
622 # This should override user-supplied initdb options.
623 if ($params{no_data_checksums})
624 {
625 push @{ $params{extra} }, '--no-data-checksums';
626 }
627
628 mkdir $self->backup_dir;
629 mkdir $self->archive_dir;
630
631 # If available, if there aren't any parameters and if force_initdb is
632 # disabled, use a previously initdb'd cluster as a template by copying it.
633 # For a lot of tests, that's substantially cheaper. It does not seem
634 # worth figuring out whether extra parameters affect compatibility, so
635 # initdb is forced if any are defined.
636 #
637 # There's very similar code in pg_regress.c, but we can't easily
638 # deduplicate it until we require perl at build time.
639 if ( $params{force_initdb}
640 or defined $params{extra}
641 or !defined $ENV{INITDB_TEMPLATE})
642 {
643 note("initializing database system by running initdb");
644 PostgreSQL::Test::Utils::system_or_bail(
645 'initdb', '--no-sync',
646 '--pgdata' => $pgdata,
647 '--auth' => 'trust',
648 @{ $params{extra} });
649 }
650 else
651 {
652 my @copycmd;
653 my $expected_exitcode;
654
655 note("initializing database system by copying initdb template");
656
657 if ($PostgreSQL::Test::Utils::windows_os)
658 {
659 @copycmd = qw(robocopy /E /NJS /NJH /NFL /NDL /NP);
660 $expected_exitcode = 1; # 1 denotes files were copied
661 }
662 else
663 {
664 @copycmd = qw(cp -RPp);
665 $expected_exitcode = 0;
666 }
667
668 @copycmd = (@copycmd, $ENV{INITDB_TEMPLATE}, $pgdata);
669
670 my $ret = PostgreSQL::Test::Utils::system_log(@copycmd);
671
672 # See http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR
673 if ($ret & 127 or $ret >> 8 != $expected_exitcode)
674 {
675 BAIL_OUT(
676 sprintf("failed to execute command \"%s\": $ret",
677 join(" ", @copycmd)));
678 }
679 }
680
681 PostgreSQL::Test::Utils::system_or_bail($ENV{PG_REGRESS},
682 '--config-auth', $pgdata, @{ $params{auth_extra} });
683
684 open my $conf, '>>', "$pgdata/postgresql.conf" or die $!;
685 print $conf "\n# Added by PostgreSQL::Test::Cluster.pm\n";
686 print $conf "fsync = off\n";
687 print $conf "restart_after_crash = off\n";
688 print $conf "log_line_prefix = '%m [%p] %q%a '\n";
689 print $conf "log_statement = all\n";
690 print $conf "log_replication_commands = on\n";
691 print $conf "wal_retrieve_retry_interval = '500ms'\n";
692
693 # If a setting tends to affect whether tests pass or fail, print it after
694 # TEMP_CONFIG. Otherwise, print it before TEMP_CONFIG, thereby permitting
695 # overrides. Settings that merely improve performance or ease debugging
696 # belong before TEMP_CONFIG.
697 print $conf PostgreSQL::Test::Utils::slurp_file($ENV{TEMP_CONFIG})
698 if defined $ENV{TEMP_CONFIG};
699
700 if ($params{allows_streaming})
701 {
702 if ($params{allows_streaming} eq "logical")
703 {
704 print $conf "wal_level = logical\n";
705 }
706 else
707 {
708 print $conf "wal_level = replica\n";
709 }
710 print $conf "max_wal_senders = 10\n";
711 print $conf "max_replication_slots = 10\n";
712 print $conf "autovacuum_worker_slots = 3\n";
713 print $conf "wal_log_hints = on\n";
714 print $conf "hot_standby = on\n";
715 # conservative settings to ensure we can run multiple postmasters:
716 print $conf "shared_buffers = 1MB\n";
717 print $conf "max_connections = 10\n";
718 # limit disk space consumption, too:
719 print $conf "max_wal_size = 128MB\n";
720 }
721 else
722 {
723 print $conf "wal_level = minimal\n";
724 print $conf "max_wal_senders = 0\n";
725 }
726
727 print $conf "port = $port\n";
728 if ($use_tcp)
729 {
730 print $conf "unix_socket_directories = ''\n";
731 print $conf "listen_addresses = '$host'\n";
732 }
733 else
734 {
735 print $conf "unix_socket_directories = '$host'\n";
736 print $conf "listen_addresses = ''\n";
737 }
738 close $conf;
739
740 chmod($self->group_access ? 0640 : 0600, "$pgdata/postgresql.conf")
741 or die("unable to set permissions for $pgdata/postgresql.conf");
742
743 $self->set_replication_conf if $params{allows_streaming};
744 $self->enable_archiving if $params{has_archiving};
745 return;
746 }
747
748 =pod
749
750 =item $node->append_conf(filename, str)
751
752 A shortcut method to append to files like pg_hba.conf and postgresql.conf.
753
754 Does no validation or sanity checking. Does not reload the configuration
755 after writing.
756
757 A newline is automatically appended to the string.
758
759 =cut
760
761 sub append_conf
762 {
763 my ($self, $filename, $str) = @_;
764
765 my $conffile = $self->data_dir . '/' . $filename;
766
767 PostgreSQL::Test::Utils::append_to_file($conffile, $str . "\n");
768
769 chmod($self->group_access() ? 0640 : 0600, $conffile)
770 or die("unable to set permissions for $conffile");
771
772 return;
773 }
774
775 =pod
776
777 =item $node->adjust_conf(filename, setting, value, skip_equals)
778
779 Modify the named config file setting with the value. If the value is undefined,
780 instead delete the setting. If the setting is not present no action is taken.
781
782 This will write "$setting = $value\n" in place of the existing line,
783 unless skip_equals is true, in which case it will write
784 "$setting $value\n". If the value needs to be quoted it is the caller's
785 responsibility to do that.
786
787 =cut
788
789 sub adjust_conf
790 {
791 my ($self, $filename, $setting, $value, $skip_equals) = @_;
792
793 my $conffile = $self->data_dir . '/' . $filename;
794
795 my $contents = PostgreSQL::Test::Utils::slurp_file($conffile);
796 my @lines = split(/\n/, $contents);
797 my @result;
798 my $eq = $skip_equals ? '' : '= ';
799 foreach my $line (@lines)
800 {
801 if ($line !~ /^$setting\W/)
802 {
803 push(@result, "$line\n");
804 }
805 elsif (defined $value)
806 {
807 push(@result, "$setting $eq$value\n");
808 }
809 }
810 open my $fh, ">", $conffile
811 or croak "could not write \"$conffile\": $!";
812 print $fh @result;
813 close $fh;
814
815 chmod($self->group_access() ? 0640 : 0600, $conffile)
816 or die("unable to set permissions for $conffile");
817 }
818
819 =pod
820
821 =item $node->backup(backup_name)
822
823 Create a hot backup with B<pg_basebackup> in subdirectory B<backup_name> of
824 B<< $node->backup_dir >>, including the WAL.
825
826 By default, WAL files are fetched at the end of the backup, not streamed.
827 You can adjust that and other things by passing an array of additional
828 B<pg_basebackup> command line options in the keyword parameter backup_options.
829
830 You'll have to configure a suitable B<max_wal_senders> on the
831 target server since it isn't done by default.
832
833 =cut
834
835 sub backup
836 {
837 my ($self, $backup_name, %params) = @_;
838 my $backup_path = $self->backup_dir . '/' . $backup_name;
839 my $name = $self->name;
840
841 local %ENV = $self->_get_env();
842
843 print "# Taking pg_basebackup $backup_name from node \"$name\"\n";
844 PostgreSQL::Test::Utils::system_or_bail(
845 'pg_basebackup', '--no-sync',
846 '--pgdata' => $backup_path,
847 '--host' => $self->host,
848 '--port' => $self->port,
849 '--checkpoint' => 'fast',
850 @{ $params{backup_options} });
851 print "# Backup finished\n";
852 return;
853 }
854
855 =item $node->backup_fs_cold(backup_name)
856
857 Create a backup with a filesystem level copy in subdirectory B<backup_name> of
858 B<< $node->backup_dir >>, including WAL. The server must be
859 stopped as no attempt to handle concurrent writes is made.
860
861 Use B<backup> if you want to back up a running server.
862
863 =cut
864
865 sub backup_fs_cold
866 {
867 my ($self, $backup_name) = @_;
868
869 PostgreSQL::Test::RecursiveCopy::copypath(
870 $self->data_dir,
871 $self->backup_dir . '/' . $backup_name,
872 filterfn => sub {
873 my $src = shift;
874 return ($src ne 'log' and $src ne 'postmaster.pid');
875 });
876
877 return;
878 }
879
880 =pod
881
882 =item $node->init_from_backup(root_node, backup_name, %params)
883
884 Initialize a node from a backup, which may come from this node or a different
885 node. root_node must be a PostgreSQL::Test::Cluster reference, backup_name the string name
886 of a backup previously created on that node with $node->backup.
887
888 Does not start the node after initializing it.
889
890 By default, the backup is assumed to be plain format. To restore from
891 a tar-format backup, pass the name of the tar program to use in the
892 keyword parameter tar_program.
893
894 If there are tablespace present in the backup, include tablespace_map as
895 a keyword parameter whose values is a hash. When combine_with_prior is used,
896 the hash keys are the tablespace pathnames used in the backup; otherwise,
897 they are tablespace OIDs. In either case, the values are the tablespace
898 pathnames that should be used for the target cluster.
899
900 To restore from an incremental backup, pass the parameter combine_with_prior
901 as a reference to an array of prior backup names with which this backup
902 is to be combined using pg_combinebackup.
903
904 Streaming replication can be enabled on this node by passing the keyword
905 parameter has_streaming => 1. This is disabled by default.
906
907 Restoring WAL segments from archives using restore_command can be enabled
908 by passing the keyword parameter has_restoring => 1. This is disabled by
909 default.
910
911 If has_restoring is used, standby mode is used by default. To use
912 recovery mode instead, pass the keyword parameter standby => 0.
913
914 The backup is copied, leaving the original unmodified. pg_hba.conf is
915 unconditionally set to enable replication connections.
916
917 =cut
918
919 sub init_from_backup
920 {
921 my ($self, $root_node, $backup_name, %params) = @_;
922 my $backup_path = $root_node->backup_dir . '/' . $backup_name;
923 my $host = $self->host;
924 my $port = $self->port;
925 my $node_name = $self->name;
926 my $root_name = $root_node->name;
927
928 $params{has_streaming} = 0 unless defined $params{has_streaming};
929 $params{has_restoring} = 0 unless defined $params{has_restoring};
930 $params{standby} = 1 unless defined $params{standby};
931
932 print
933 "# Initializing node \"$node_name\" from backup \"$backup_name\" of node \"$root_name\"\n";
934 croak "Backup \"$backup_name\" does not exist at $backup_path"
935 unless -d $backup_path;
936
937 mkdir $self->backup_dir;
938 mkdir $self->archive_dir;
939
940 my $data_path = $self->data_dir;
941 if (defined $params{combine_with_prior})
942 {
943 my @prior_backups = @{ $params{combine_with_prior} };
944 my @prior_backup_path;
945
946 for my $prior_backup_name (@prior_backups)
947 {
948 push @prior_backup_path,
949 $root_node->backup_dir . '/' . $prior_backup_name;
950 }
951
952 local %ENV = $self->_get_env();
953 my @combineargs = ('pg_combinebackup', '--debug');
954 if (exists $params{tablespace_map})
955 {
956 while (my ($olddir, $newdir) = each %{ $params{tablespace_map} })
957 {
958 push @combineargs, "-T$olddir=$newdir";
959 }
960 }
961 # use the combine mode (clone/copy-file-range) if specified
962 if (defined $params{combine_mode})
963 {
964 push @combineargs, $params{combine_mode};
965 }
966 push @combineargs, @prior_backup_path, $backup_path,
967 '--output' => $data_path;
968 PostgreSQL::Test::Utils::system_or_bail(@combineargs);
969 }
970 elsif (defined $params{tar_program})
971 {
972 mkdir($data_path) || die "mkdir $data_path: $!";
973 PostgreSQL::Test::Utils::system_or_bail(
974 $params{tar_program},
975 'xf' => $backup_path . '/base.tar',
976 '-C' => $data_path);
977 PostgreSQL::Test::Utils::system_or_bail(
978 $params{tar_program},
979 'xf' => $backup_path . '/pg_wal.tar',
980 '-C' => $data_path . '/pg_wal');
981
982 # We need to generate a tablespace_map file.
983 open(my $tsmap, ">", "$data_path/tablespace_map")
984 || die "$data_path/tablespace_map: $!";
985
986 # Extract tarfiles and add tablespace_map entries
987 my @tstars = grep { /^\d+.tar/ }
988 PostgreSQL::Test::Utils::slurp_dir($backup_path);
989 for my $tstar (@tstars)
990 {
991 my $tsoid = $tstar;
992 $tsoid =~ s/\.tar$//;
993
994 die "no tablespace mapping for $tstar"
995 if !exists $params{tablespace_map}
996 || !exists $params{tablespace_map}{$tsoid};
997 my $newdir = $params{tablespace_map}{$tsoid};
998
999 mkdir($newdir) || die "mkdir $newdir: $!";
1000 PostgreSQL::Test::Utils::system_or_bail(
1001 $params{tar_program},
1002 'xf' => $backup_path . '/' . $tstar,
1003 '-C' => $newdir);
1004
1005 my $escaped_newdir = $newdir;
1006 $escaped_newdir =~ s/\\/\\\\/g;
1007 print $tsmap "$tsoid $escaped_newdir\n";
1008 }
1009
1010 # Close tablespace_map.
1011 close($tsmap);
1012 }
1013 else
1014 {
1015 my @tsoids;
1016 rmdir($data_path);
1017
1018 # Copy the main backup. If we see a tablespace directory for which we
1019 # have a tablespace mapping, skip it, but remember that we saw it.
1020 PostgreSQL::Test::RecursiveCopy::copypath(
1021 $backup_path,
1022 $data_path,
1023 filterfn => sub {
1024 my ($path) = @_;
1025 if ($path =~ /^pg_tblspc\/(\d+)$/
1026 && exists $params{tablespace_map}{$1})
1027 {
1028 push @tsoids, $1;
1029 return 0;
1030 }
1031 return 1;
1032 });
1033
1034 if (@tsoids > 0)
1035 {
1036 # We need to generate a tablespace_map file.
1037 open(my $tsmap, ">", "$data_path/tablespace_map")
1038 || die "$data_path/tablespace_map: $!";
1039
1040 # Now use the list of tablespace links to copy each tablespace.
1041 for my $tsoid (@tsoids)
1042 {
1043 die "no tablespace mapping for $tsoid"
1044 if !exists $params{tablespace_map}
1045 || !exists $params{tablespace_map}{$tsoid};
1046
1047 my $olddir = $backup_path . '/pg_tblspc/' . $tsoid;
1048 my $newdir = $params{tablespace_map}{$tsoid};
1049 PostgreSQL::Test::RecursiveCopy::copypath($olddir, $newdir);
1050
1051 my $escaped_newdir = $newdir;
1052 $escaped_newdir =~ s/\\/\\\\/g;
1053 print $tsmap "$tsoid $escaped_newdir\n";
1054 }
1055
1056 # Close tablespace_map.
1057 close($tsmap);
1058 }
1059 }
1060 chmod(0700, $data_path) or die $!;
1061
1062 # Base configuration for this node
1063 $self->append_conf(
1064 'postgresql.conf',
1065 qq(
1066 port = $port
1067 ));
1068 if ($use_tcp)
1069 {
1070 $self->append_conf('postgresql.conf', "listen_addresses = '$host'");
1071 }
1072 else
1073 {
1074 $self->append_conf('postgresql.conf',
1075 "unix_socket_directories = '$host'");
1076 }
1077 $self->enable_streaming($root_node) if $params{has_streaming};
1078 $self->enable_restoring($root_node, $params{standby})
1079 if $params{has_restoring};
1080 return;
1081 }
1082
1083 =pod
1084
1085 =item $node->rotate_logfile()
1086
1087 Switch to a new PostgreSQL log file. This does not alter any running
1088 PostgreSQL process. Subsequent method calls, including pg_ctl invocations,
1089 will use the new name. Return the new name.
1090
1091 =cut
1092
1093 sub rotate_logfile
1094 {
1095 my ($self) = @_;
1096 $self->{_logfile} = sprintf('%s_%d.log',
1097 $self->{_logfile_base},
1098 ++$self->{_logfile_generation});
1099 return $self->{_logfile};
1100 }
1101
1102 =pod
1103
1104 =item $node->start(%params) => success_or_failure
1105
1106 Wrapper for pg_ctl start
1107
1108 Start the node and wait until it is ready to accept connections.
1109
1110 =over
1111
1112 =item fail_ok => 1
1113
1114 By default, failure terminates the entire F<prove> invocation. If given,
1115 instead return a true or false value to indicate success or failure.
1116
1117 =back
1118
1119 =cut
1120
1121 sub start
1122 {
1123 my ($self, %params) = @_;
1124 my $port = $self->port;
1125 my $pgdata = $self->data_dir;
1126 my $name = $self->name;
1127 my $ret;
1128
1129 BAIL_OUT("node \"$name\" is already running") if defined $self->{_pid};
1130
1131 print("### Starting node \"$name\"\n");
1132
1133 # Temporarily unset PGAPPNAME so that the server doesn't
1134 # inherit it. Otherwise this could affect libpqwalreceiver
1135 # connections in confusing ways.
1136 local %ENV = $self->_get_env(PGAPPNAME => undef);
1137
1138 # Note: We set the cluster_name here, not in postgresql.conf (in
1139 # sub init) so that it does not get copied to standbys.
1140 # -w is now the default but having it here does no harm and helps
1141 # compatibility with older versions.
1142 $ret = PostgreSQL::Test::Utils::system_log(
1143 'pg_ctl', '--wait',
1144 '--pgdata' => $self->data_dir,
1145 '--log' => $self->logfile,
1146 '--options' => "--cluster-name=$name",
1147 'start');
1148
1149 if ($ret != 0)
1150 {
1151 print "# pg_ctl start failed; see logfile for details: "
1152 . $self->logfile . "\n";
1153
1154 # pg_ctl could have timed out, so check to see if there's a pid file;
1155 # otherwise our END block will fail to shut down the new postmaster.
1156 $self->_update_pid(-1);
1157
1158 BAIL_OUT("pg_ctl start failed") unless $params{fail_ok};
1159 return 0;
1160 }
1161
1162 $self->_update_pid(1);
1163 return 1;
1164 }
1165
1166 =pod
1167
1168 =item $node->kill9()
1169
1170 Send SIGKILL (signal 9) to the postmaster.
1171
1172 Note: if the node is already known stopped, this does nothing.
1173 However, if we think it's running and it's not, it's important for
1174 this to fail. Otherwise, tests might fail to detect server crashes.
1175
1176 =cut
1177
1178 sub kill9
1179 {
1180 my ($self) = @_;
1181 my $name = $self->name;
1182 return unless defined $self->{_pid};
1183
1184 local %ENV = $self->_get_env();
1185
1186 print "### Killing node \"$name\" using signal 9\n";
1187 kill(9, $self->{_pid});
1188 $self->{_pid} = undef;
1189 return;
1190 }
1191
1192 =pod
1193
1194 =item $node->stop(mode)
1195
1196 Stop the node using pg_ctl -m $mode and wait for it to stop.
1197
1198 Note: if the node is already known stopped, this does nothing.
1199 However, if we think it's running and it's not, it's important for
1200 this to fail. Otherwise, tests might fail to detect server crashes.
1201
1202 With optional extra param fail_ok => 1, returns 0 for failure
1203 instead of bailing out.
1204
1205 The optional extra param timeout can be used to pass the pg_ctl
1206 --timeout option.
1207
1208 =cut
1209
1210 sub stop
1211 {
1212 my ($self, $mode, %params) = @_;
1213 my $pgdata = $self->data_dir;
1214 my $name = $self->name;
1215 my $ret;
1216
1217 local %ENV = $self->_get_env();
1218
1219 $mode = 'fast' unless defined $mode;
1220 return 1 unless defined $self->{_pid};
1221
1222 print "### Stopping node \"$name\" using mode $mode\n";
1223 my @cmd = ('pg_ctl', '--pgdata' => $pgdata, '--mode' => $mode, 'stop');
1224 if ($params{timeout})
1225 {
1226 push(@cmd, ('--timeout' => $params{timeout}));
1227 }
1228 $ret = PostgreSQL::Test::Utils::system_log(@cmd);
1229
1230 if ($ret != 0)
1231 {
1232 print "# pg_ctl stop failed: $ret\n";
1233
1234 # Check to see if we still have a postmaster or not.
1235 $self->_update_pid(-1);
1236
1237 BAIL_OUT("pg_ctl stop failed") unless $params{fail_ok};
1238 return 0;
1239 }
1240
1241 $self->_update_pid(0);
1242 return 1;
1243 }
1244
1245 =pod
1246
1247 =item $node->reload()
1248
1249 Reload configuration parameters on the node.
1250
1251 =cut
1252
1253 sub reload
1254 {
1255 my ($self) = @_;
1256 my $port = $self->port;
1257 my $pgdata = $self->data_dir;
1258 my $name = $self->name;
1259
1260 local %ENV = $self->_get_env();
1261
1262 print "### Reloading node \"$name\"\n";
1263 PostgreSQL::Test::Utils::system_or_bail(
1264 'pg_ctl',
1265 '--pgdata' => $pgdata,
1266 'reload');
1267 return;
1268 }
1269
1270 =pod
1271
1272 =item $node->restart()
1273
1274 Wrapper for pg_ctl restart.
1275
1276 With optional extra param fail_ok => 1, returns 0 for failure
1277 instead of bailing out.
1278
1279 =cut
1280
1281 sub restart
1282 {
1283 my ($self, %params) = @_;
1284 my $name = $self->name;
1285 my $ret;
1286
1287 local %ENV = $self->_get_env(PGAPPNAME => undef);
1288
1289 print "### Restarting node \"$name\"\n";
1290
1291 # -w is now the default but having it here does no harm and helps
1292 # compatibility with older versions.
1293 $ret = PostgreSQL::Test::Utils::system_log(
1294 'pg_ctl', '--wait',
1295 '--pgdata' => $self->data_dir,
1296 '--log' => $self->logfile,
1297 'restart');
1298
1299 if ($ret != 0)
1300 {
1301 print "# pg_ctl restart failed; see logfile for details: "
1302 . $self->logfile . "\n";
1303
1304 # pg_ctl could have timed out, so check to see if there's a pid file;
1305 # otherwise our END block will fail to shut down the new postmaster.
1306 $self->_update_pid(-1);
1307
1308 BAIL_OUT("pg_ctl restart failed") unless $params{fail_ok};
1309 return 0;
1310 }
1311
1312 $self->_update_pid(1);
1313 return 1;
1314 }
1315
1316 =pod
1317
1318 =item $node->promote()
1319
1320 Wrapper for pg_ctl promote
1321
1322 =cut
1323
1324 sub promote
1325 {
1326 my ($self) = @_;
1327 my $port = $self->port;
1328 my $pgdata = $self->data_dir;
1329 my $logfile = $self->logfile;
1330 my $name = $self->name;
1331
1332 local %ENV = $self->_get_env();
1333
1334 print "### Promoting node \"$name\"\n";
1335 PostgreSQL::Test::Utils::system_or_bail(
1336 'pg_ctl',
1337 '--pgdata' => $pgdata,
1338 '--log' => $logfile,
1339 'promote');
1340 return;
1341 }
1342
1343 =pod
1344
1345 =item $node->logrotate()
1346
1347 Wrapper for pg_ctl logrotate
1348
1349 =cut
1350
1351 sub logrotate
1352 {
1353 my ($self) = @_;
1354 my $port = $self->port;
1355 my $pgdata = $self->data_dir;
1356 my $logfile = $self->logfile;
1357 my $name = $self->name;
1358
1359 local %ENV = $self->_get_env();
1360
1361 print "### Rotating log in node \"$name\"\n";
1362 PostgreSQL::Test::Utils::system_or_bail(
1363 'pg_ctl',
1364 '--pgdata' => $pgdata,
1365 '--log' => $logfile,
1366 'logrotate');
1367 return;
1368 }
1369
1370 # Internal routine to enable streaming replication on a standby node.
1371 sub enable_streaming
1372 {
1373 my ($self, $root_node) = @_;
1374 my $root_connstr = $root_node->connstr;
1375 my $name = $self->name;
1376
1377 print "### Enabling streaming replication for node \"$name\"\n";
1378 $self->append_conf(
1379 $self->_recovery_file, qq(
1380 primary_conninfo='$root_connstr'
1381 ));
1382 $self->set_standby_mode();
1383 return;
1384 }
1385
1386 # Internal routine to enable archive recovery command on a standby node
1387 sub enable_restoring
1388 {
1389 my ($self, $root_node, $standby) = @_;
1390 my $path = $root_node->archive_dir;
1391 my $name = $self->name;
1392
1393 print "### Enabling WAL restore for node \"$name\"\n";
1394
1395 # On Windows, the path specified in the restore command needs to use
1396 # double back-slashes to work properly and to be able to detect properly
1397 # the file targeted by the copy command, so the directory value used
1398 # in this routine, using only one back-slash, need to be properly changed
1399 # first. Paths also need to be double-quoted to prevent failures where
1400 # the path contains spaces.
1401 $path =~ s{\\}{\\\\}g if ($PostgreSQL::Test::Utils::windows_os);
1402 my $copy_command =
1403 $PostgreSQL::Test::Utils::windows_os
1404 ? qq{copy "$path\\\\%f" "%p"}
1405 : qq{cp "$path/%f" "%p"};
1406
1407 $self->append_conf(
1408 $self->_recovery_file, qq(
1409 restore_command = '$copy_command'
1410 ));
1411 if ($standby)
1412 {
1413 $self->set_standby_mode();
1414 }
1415 else
1416 {
1417 $self->set_recovery_mode();
1418 }
1419 return;
1420 }
1421
1422 sub _recovery_file { return "postgresql.conf"; }
1423
1424 =pod
1425
1426 =item $node->set_recovery_mode()
1427
1428 Place recovery.signal file.
1429
1430 =cut
1431
1432 sub set_recovery_mode
1433 {
1434 my ($self) = @_;
1435
1436 $self->append_conf('recovery.signal', '');
1437 return;
1438 }
1439
1440 =pod
1441
1442 =item $node->set_standby_mode()
1443
1444 Place standby.signal file.
1445
1446 =cut
1447
1448 sub set_standby_mode
1449 {
1450 my ($self) = @_;
1451
1452 $self->append_conf('standby.signal', '');
1453 return;
1454 }
1455
1456 # Internal routine to enable archiving
1457 sub enable_archiving
1458 {
1459 my ($self) = @_;
1460 my $path = $self->archive_dir;
1461 my $name = $self->name;
1462
1463 print "### Enabling WAL archiving for node \"$name\"\n";
1464
1465 # On Windows, the path specified in the restore command needs to use
1466 # double back-slashes to work properly and to be able to detect properly
1467 # the file targeted by the copy command, so the directory value used
1468 # in this routine, using only one back-slash, need to be properly changed
1469 # first. Paths also need to be double-quoted to prevent failures where
1470 # the path contains spaces.
1471 $path =~ s{\\}{\\\\}g if ($PostgreSQL::Test::Utils::windows_os);
1472 my $copy_command =
1473 $PostgreSQL::Test::Utils::windows_os
1474 ? qq{copy "%p" "$path\\\\%f"}
1475 : qq{cp "%p" "$path/%f"};
1476
1477 # Enable archive_mode and archive_command on node
1478 $self->append_conf(
1479 'postgresql.conf', qq(
1480 archive_mode = on
1481 archive_command = '$copy_command'
1482 ));
1483 return;
1484 }
1485
1486 # Internal method to update $self->{_pid}
1487 # $is_running = 1: pid file should be there
1488 # $is_running = 0: pid file should NOT be there
1489 # $is_running = -1: we aren't sure
1490 sub _update_pid
1491 {
1492 my ($self, $is_running) = @_;
1493 my $name = $self->name;
1494
1495 # If we can open the PID file, read its first line and that's the PID we
1496 # want.
1497 if (open my $pidfile, '<', $self->data_dir . "/postmaster.pid")
1498 {
1499 chomp($self->{_pid} = <$pidfile>);
1500 close $pidfile;
1501
1502 # If we aren't sure what to expect, validate the PID using kill().
1503 # This protects against stale PID files left by crashed postmasters.
1504 if ($is_running == -1 && kill(0, $self->{_pid}) == 0)
1505 {
1506 print
1507 "# Stale postmaster.pid file for node \"$name\": PID $self->{_pid} no longer exists\n";
1508 $self->{_pid} = undef;
1509 return;
1510 }
1511
1512 print "# Postmaster PID for node \"$name\" is $self->{_pid}\n";
1513
1514 # If we found a pidfile when there shouldn't be one, complain.
1515 BAIL_OUT("postmaster.pid unexpectedly present") if $is_running == 0;
1516 return;
1517 }
1518
1519 $self->{_pid} = undef;
1520 print "# No postmaster PID for node \"$name\"\n";
1521
1522 # Complain if we expected to find a pidfile.
1523 BAIL_OUT("postmaster.pid unexpectedly not present") if $is_running == 1;
1524 return;
1525 }
1526
1527 =pod
1528
1529 =item PostgreSQL::Test::Cluster->new(node_name, %params)
1530
1531 Build a new object of class C<PostgreSQL::Test::Cluster> (or of a subclass, if you have
1532 one), assigning a free port number. Remembers the node, to prevent its port
1533 number from being reused for another node, and to ensure that it gets
1534 shut down when the test script exits.
1535
1536 =over
1537
1538 =item port => [1,65535]
1539
1540 By default, this function assigns a port number to each node. Specify this to
1541 force a particular port number. The caller is responsible for evaluating
1542 potential conflicts and privilege requirements.
1543
1544 =item own_host => 1
1545
1546 By default, all nodes use the same PGHOST value. If specified, generate a
1547 PGHOST specific to this node. This allows multiple nodes to use the same
1548 port.
1549
1550 =item install_path => '/path/to/postgres/installation'
1551
1552 Using this parameter is it possible to have nodes pointing to different
1553 installations, for testing different versions together or the same version
1554 with different build parameters. The provided path must be the parent of the
1555 installation's 'bin' and 'lib' directories. In the common case where this is
1556 not provided, Postgres binaries will be found in the caller's PATH.
1557
1558 =back
1559
1560 =cut
1561
1562 sub new
1563 {
1564 my $class = shift;
1565 my ($name, %params) = @_;
1566
1567 # Select a port.
1568 my $port;
1569 if (defined $params{port})
1570 {
1571 $port = $params{port};
1572 }
1573 else
1574 {
1575 # When selecting a port, we look for an unassigned TCP port number,
1576 # even if we intend to use only Unix-domain sockets. This is clearly
1577 # necessary on $use_tcp (Windows) configurations, and it seems like a
1578 # good idea on Unixen as well.
1579 $port = get_free_port();
1580 }
1581
1582 # Select a host.
1583 my $host = $test_pghost;
1584 if ($params{own_host})
1585 {
1586 if ($use_tcp)
1587 {
1588 $last_host_assigned++;
1589 $last_host_assigned > 254 and BAIL_OUT("too many own_host nodes");
1590 $host = '127.0.0.' . $last_host_assigned;
1591 }
1592 else
1593 {
1594 $host = "$test_pghost/$name"; # Assume $name =~ /^[-_a-zA-Z0-9]+$/
1595 mkdir $host;
1596 }
1597 }
1598
1599 my $testname = basename($0);
1600 $testname =~ s/\.[^.]+$//;
1601 my $node = {
1602 _port => $port,
1603 _host => $host,
1604 _basedir =>
1605 "$PostgreSQL::Test::Utils::tmp_check/t_${testname}_${name}_data",
1606 _name => $name,
1607 _logfile_generation => 0,
1608 _logfile_base =>
1609 "$PostgreSQL::Test::Utils::log_path/${testname}_${name}",
1610 _logfile =>
1611 "$PostgreSQL::Test::Utils::log_path/${testname}_${name}.log"
1612 };
1613
1614 if ($params{install_path})
1615 {
1616 $node->{_install_path} = $params{install_path};
1617 }
1618
1619 bless $node, $class;
1620 mkdir $node->{_basedir}
1621 or
1622 BAIL_OUT("could not create data directory \"$node->{_basedir}\": $!");
1623
1624 $node->_set_pg_version;
1625
1626 $node->dump_info;
1627
1628 my $ver = $node->{_pg_version};
1629
1630 # Use a subclass as defined below (or elsewhere) if this version
1631 # isn't fully compatible. Warn if the version is too old and thus we don't
1632 # have a subclass of this class.
1633 if (ref $ver && $ver < $min_compat)
1634 {
1635 my $maj = $ver->major(separator => '_');
1636 my $subclass = $class . "::V_$maj";
1637 if ($subclass->isa($class))
1638 {
1639 bless $node, $subclass;
1640 }
1641 else
1642 {
1643 carp
1644 "PostgreSQL::Test::Cluster isn't fully compatible with version $ver";
1645 }
1646 }
1647
1648 # Add node to list of nodes
1649 push(@all_nodes, $node);
1650
1651 return $node;
1652 }
1653
1654 # Private routine to run the pg_config binary found in our environment (or in
1655 # our install_path, if we have one), and set the version from it
1656 #
1657 sub _set_pg_version
1658 {
1659 my ($self) = @_;
1660 my $inst = $self->{_install_path};
1661 my $pg_config = "pg_config";
1662
1663 if (defined $inst)
1664 {
1665 # If the _install_path is invalid, our PATH variables might find an
1666 # unrelated pg_config executable elsewhere. Sanity check the
1667 # directory.
1668 BAIL_OUT("directory not found: $inst")
1669 unless -d $inst;
1670
1671 # If the directory exists but is not the root of a postgresql
1672 # installation, or if the user configured using
1673 # --bindir=$SOMEWHERE_ELSE, we're not going to find pg_config, so
1674 # complain about that, too.
1675 $pg_config = "$inst/bin/pg_config";
1676 BAIL_OUT("pg_config not found: $pg_config")
1677 unless -e $pg_config
1678 or ($PostgreSQL::Test::Utils::windows_os and -e "$pg_config.exe");
1679 BAIL_OUT("pg_config not executable: $pg_config")
1680 unless $PostgreSQL::Test::Utils::windows_os or -x $pg_config;
1681
1682 # Leave $pg_config install_path qualified, to be sure we get the right
1683 # version information, below, or die trying
1684 }
1685
1686 local %ENV = $self->_get_env();
1687
1688 # We only want the version field
1689 my $version_line = qx{$pg_config --version};
1690 BAIL_OUT("$pg_config failed: $!") if $?;
1691
1692 $self->{_pg_version} = PostgreSQL::Version->new($version_line);
1693
1694 BAIL_OUT("could not parse pg_config --version output: $version_line")
1695 unless defined $self->{_pg_version};
1696 }
1697
1698 # Private routine to return a copy of the environment with the PATH and
1699 # (DY)LD_LIBRARY_PATH correctly set when there is an install path set for
1700 # the node.
1701 #
1702 # Routines that call Postgres binaries need to call this routine like this:
1703 #
1704 # local %ENV = $self->_get_env([%extra_settings]);
1705 #
1706 # A copy of the environment is taken and node's host and port settings are
1707 # added as PGHOST and PGPORT, then the extra settings (if any) are applied.
1708 # Any setting in %extra_settings with a value that is undefined is deleted;
1709 # the remainder are set. Then the PATH and (DY)LD_LIBRARY_PATH are adjusted
1710 # if the node's install path is set, and the copy environment is returned.
1711 #
1712 # The install path set in new() needs to be a directory containing
1713 # bin and lib subdirectories as in a standard PostgreSQL installation, so this
1714 # can't be used with installations where the bin and lib directories don't have
1715 # a common parent directory.
1716 sub _get_env
1717 {
1718 my $self = shift;
1719 my %inst_env = (%ENV, PGHOST => $self->{_host}, PGPORT => $self->{_port});
1720 # the remaining arguments are modifications to make to the environment
1721 my %mods = (@_);
1722 while (my ($k, $v) = each %mods)
1723 {
1724 if (defined $v)
1725 {
1726 $inst_env{$k} = "$v";
1727 }
1728 else
1729 {
1730 delete $inst_env{$k};
1731 }
1732 }
1733 # now fix up the new environment for the install path
1734 my $inst = $self->{_install_path};
1735 if ($inst)
1736 {
1737 if ($PostgreSQL::Test::Utils::windows_os)
1738 {
1739 # Windows picks up DLLs from the PATH rather than *LD_LIBRARY_PATH
1740 # choose the right path separator
1741 if ($Config{osname} eq 'MSWin32')
1742 {
1743 $inst_env{PATH} = "$inst/bin;$inst/lib;$ENV{PATH}";
1744 }
1745 else
1746 {
1747 $inst_env{PATH} = "$inst/bin:$inst/lib:$ENV{PATH}";
1748 }
1749 }
1750 else
1751 {
1752 my $dylib_name =
1753 $Config{osname} eq 'darwin'
1754 ? "DYLD_LIBRARY_PATH"
1755 : "LD_LIBRARY_PATH";
1756 $inst_env{PATH} = "$inst/bin:$ENV{PATH}";
1757 if (exists $ENV{$dylib_name})
1758 {
1759 $inst_env{$dylib_name} = "$inst/lib:$ENV{$dylib_name}";
1760 }
1761 else
1762 {
1763 $inst_env{$dylib_name} = "$inst/lib";
1764 }
1765 }
1766 }
1767 return (%inst_env);
1768 }
1769
1770 # Private routine to get an installation path qualified command.
1771 #
1772 # IPC::Run maintains a cache, %cmd_cache, mapping commands to paths. Tests
1773 # which use nodes spanning more than one postgres installation path need to
1774 # avoid confusing which installation's binaries get run. Setting $ENV{PATH} is
1775 # insufficient, as IPC::Run does not check to see if the path has changed since
1776 # caching a command.
1777 sub installed_command
1778 {
1779 my ($self, $cmd) = @_;
1780
1781 # Nodes using alternate installation locations use their installation's
1782 # bin/ directory explicitly
1783 return join('/', $self->{_install_path}, 'bin', $cmd)
1784 if defined $self->{_install_path};
1785
1786 # Nodes implicitly using the default installation location rely on IPC::Run
1787 # to find the right binary, which should not cause %cmd_cache confusion,
1788 # because no nodes with other installation paths do it that way.
1789 return $cmd;
1790 }
1791
1792 =pod
1793
1794 =item get_free_port()
1795
1796 Locate an unprivileged (high) TCP port that's not currently bound to
1797 anything. This is used by C<new()>, and also by some test cases that need to
1798 start other, non-Postgres servers.
1799
1800 Ports assigned to existing PostgreSQL::Test::Cluster objects are automatically
1801 excluded, even if those servers are not currently running.
1802
1803 The port number is reserved so that other concurrent test programs will not
1804 try to use the same port.
1805
1806 Note: this is not an instance method. As it's not exported it should be
1807 called from outside the module as C<PostgreSQL::Test::Cluster::get_free_port()>.
1808
1809 =cut
1810
1811 sub get_free_port
1812 {
1813 my $found = 0;
1814 my $port = $last_port_assigned;
1815
1816 while ($found == 0)
1817 {
1818
1819 # advance $port, wrapping correctly around range end
1820 $port = $port_lower_bound if ++$port > $port_upper_bound;
1821 print "# Checking port $port\n";
1822
1823 # Check first that candidate port number is not included in
1824 # the list of already-registered nodes.
1825 $found = 1;
1826 foreach my $node (@all_nodes)
1827 {
1828 $found = 0 if ($node->port == $port);
1829 }
1830
1831 # Check to see if anything else is listening on this TCP port.
1832 # Seek a port available for all possible listen_addresses values,
1833 # so callers can harness this port for the widest range of purposes.
1834 # The 0.0.0.0 test achieves that for MSYS, which automatically sets
1835 # SO_EXCLUSIVEADDRUSE. Testing 0.0.0.0 is insufficient for Windows
1836 # native Perl (https://stackoverflow.com/a/14388707), so we also
1837 # have to test individual addresses. Doing that for 127.0.0/24
1838 # addresses other than 127.0.0.1 might fail with EADDRNOTAVAIL on
1839 # non-Linux, non-Windows kernels.
1840 #
1841 # Thus, 0.0.0.0 and individual 127.0.0/24 addresses are tested
1842 # only on Windows and only when TCP usage is requested.
1843 if ($found == 1)
1844 {
1845 foreach my $addr (qw(127.0.0.1),
1846 ($use_tcp && $PostgreSQL::Test::Utils::windows_os)
1847 ? qw(127.0.0.2 127.0.0.3 0.0.0.0)
1848 : ())
1849 {
1850 if (!can_bind($addr, $port))
1851 {
1852 $found = 0;
1853 last;
1854 }
1855 }
1856 $found = _reserve_port($port) if $found;
1857 }
1858 }
1859
1860 print "# Found port $port\n";
1861
1862 # Update port for next time
1863 $last_port_assigned = $port;
1864
1865 return $port;
1866 }
1867
1868 # Internal routine to check whether a host:port is available to bind
1869 sub can_bind
1870 {
1871 my ($host, $port) = @_;
1872 my $iaddr = inet_aton($host);
1873 my $paddr = sockaddr_in($port, $iaddr);
1874
1875 socket(SOCK, PF_INET, SOCK_STREAM, 0)
1876 or die "socket failed: $!";
1877
1878 # As in postmaster, don't use SO_REUSEADDR on Windows
1879 setsockopt(SOCK, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
1880 unless $PostgreSQL::Test::Utils::windows_os;
1881 my $ret = bind(SOCK, $paddr) && listen(SOCK, SOMAXCONN);
1882 close(SOCK);
1883 return $ret;
1884 }
1885
1886 # Internal routine to reserve a port number
1887 # Returns 1 if successful, 0 if port is already reserved.
1888 sub _reserve_port
1889 {
1890 my $port = shift;
1891 # open in rw mode so we don't have to reopen it and lose the lock
1892 my $filename = "$portdir/$port.rsv";
1893 sysopen(my $portfile, $filename, O_RDWR | O_CREAT)
1894 || die "opening port file $filename: $!";
1895 # take an exclusive lock to avoid concurrent access
1896 flock($portfile, LOCK_EX) || die "locking port file $filename: $!";
1897 # see if someone else has or had a reservation of this port
1898 my $pid = <$portfile> || "0";
1899 chomp $pid;
1900 if ($pid + 0 > 0)
1901 {
1902 if (kill 0, $pid)
1903 {
1904 # process exists and is owned by us, so we can't reserve this port
1905 flock($portfile, LOCK_UN) || die $!;
1906 close($portfile);
1907 return 0;
1908 }
1909 }
1910 # All good, go ahead and reserve the port
1911 seek($portfile, 0, SEEK_SET) || die $!;
1912 # print the pid with a fixed width so we don't leave any trailing junk
1913 print $portfile sprintf("%10d\n", $$);
1914 flock($portfile, LOCK_UN) || die $!;
1915 close($portfile);
1916 push(@port_reservation_files, $filename);
1917 return 1;
1918 }
1919
1920 # Automatically shut down any still-running nodes (in the same order the nodes
1921 # were created in) when the test script exits.
1922 END
1923 {
1924
1925 # take care not to change the script's exit value
1926 my $exit_code = $?;
1927
1928 foreach my $node (@all_nodes)
1929 {
1930 # During unclean termination (which could be a signal or some
1931 # other failure), we're not sure that the status of our nodes
1932 # has been correctly set up already, so try and update it to
1933 # improve our chances of shutting them down.
1934 $node->_update_pid(-1) if $exit_code != 0;
1935
1936 # If that fails, don't let that foil other nodes' shutdown
1937 $node->teardown_node(fail_ok => 1);
1938
1939 # skip clean if we are requested to retain the basedir
1940 next if defined $ENV{'PG_TEST_NOCLEAN'};
1941
1942 # clean basedir on clean test invocation
1943 $node->clean_node
1944 if $exit_code == 0 && PostgreSQL::Test::Utils::all_tests_passing();
1945 }
1946
1947 unlink @port_reservation_files;
1948
1949 $? = $exit_code;
1950 }
1951
1952 =pod
1953
1954 =item $node->teardown_node()
1955
1956 Do an immediate stop of the node
1957
1958 Any optional extra parameter is passed to ->stop.
1959
1960 =cut
1961
1962 sub teardown_node
1963 {
1964 my ($self, %params) = @_;
1965
1966 $self->stop('immediate', %params);
1967 return;
1968 }
1969
1970 =pod
1971
1972 =item $node->clean_node()
1973
1974 Remove the base directory of the node if the node has been stopped.
1975
1976 =cut
1977
1978 sub clean_node
1979 {
1980 my $self = shift;
1981
1982 rmtree $self->{_basedir} unless defined $self->{_pid};
1983 return;
1984 }
1985
1986 =pod
1987
1988 =item $node->safe_psql($dbname, $sql) => stdout
1989
1990 Invoke B<psql> to run B<sql> on B<dbname> and return its stdout on success.
1991 Die if the SQL produces an error. Runs with B<ON_ERROR_STOP> set.
1992
1993 Takes optional extra params like timeout and timed_out parameters with the same
1994 options as psql.
1995
1996 =cut
1997
1998 sub safe_psql
1999 {
2000 my ($self, $dbname, $sql, %params) = @_;
2001
2002 local %ENV = $self->_get_env();
2003
2004 my ($stdout, $stderr);
2005
2006 my $ret = $self->psql(
2007 $dbname, $sql,
2008 %params,
2009 stdout => \$stdout,
2010 stderr => \$stderr,
2011 on_error_die => 1,
2012 on_error_stop => 1);
2013
2014 # psql can emit stderr from NOTICEs etc
2015 if ($stderr ne "")
2016 {
2017 print "#### Begin standard error\n";
2018 print $stderr;
2019 print "\n#### End standard error\n";
2020 }
2021
2022 return $stdout;
2023 }
2024
2025 =pod
2026
2027 =item $node->psql($dbname, $sql, %params) => psql_retval
2028
2029 Invoke B<psql> to execute B<$sql> on B<$dbname> and return the return value
2030 from B<psql>, which is run with on_error_stop by default so that it will
2031 stop running sql and return 3 if the passed SQL results in an error.
2032
2033 As a convenience, if B<psql> is called in array context it returns an
2034 array containing ($retval, $stdout, $stderr).
2035
2036 psql is invoked in tuples-only unaligned mode with reading of B<.psqlrc>
2037 disabled. That may be overridden by passing extra psql parameters.
2038
2039 stdout and stderr are transformed to UNIX line endings if on Windows. Any
2040 trailing newline is removed.
2041
2042 Dies on failure to invoke psql but not if psql exits with a nonzero
2043 return code (unless on_error_die specified).
2044
2045 If psql exits because of a signal, an exception is raised.
2046
2047 =over
2048
2049 =item stdout => \$stdout
2050
2051 B<stdout>, if given, must be a scalar reference to which standard output is
2052 written. If not given, standard output is not redirected and will be printed
2053 unless B<psql> is called in array context, in which case it's captured and
2054 returned.
2055
2056 =item stderr => \$stderr
2057
2058 Same as B<stdout> but gets standard error. If the same scalar is passed for
2059 both B<stdout> and B<stderr> the results may be interleaved unpredictably.
2060
2061 =item on_error_stop => 1
2062
2063 By default, the B<psql> method invokes the B<psql> program with ON_ERROR_STOP=1
2064 set, so SQL execution is stopped at the first error and exit code 3 is
2065 returned. Set B<on_error_stop> to 0 to ignore errors instead.
2066
2067 =item on_error_die => 0
2068
2069 By default, this method returns psql's result code. Pass on_error_die to
2070 instead die with an informative message.
2071
2072 =item timeout => 'interval'
2073
2074 Set a timeout for the psql call as an interval accepted by B<IPC::Run::timer>
2075 (integer seconds is fine). This method raises an exception on timeout, unless
2076 the B<timed_out> parameter is also given.
2077
2078 =item timed_out => \$timed_out
2079
2080 If B<timeout> is set and this parameter is given, the scalar it references
2081 is set to true if the psql call times out.
2082
2083 =item connstr => B<value>
2084
2085 If set, use this as the connection string for the connection to the
2086 backend.
2087
2088 =item replication => B<value>
2089
2090 If set, add B<replication=value> to the conninfo string.
2091 Passing the literal value C<database> results in a logical replication
2092 connection.
2093
2094 =item extra_params => ['--single-transaction']
2095
2096 If given, it must be an array reference containing additional parameters to B<psql>.
2097
2098 =back
2099
2100 e.g.
2101
2102 my ($stdout, $stderr, $timed_out);
2103 my $cmdret = $node->psql('postgres', 'SELECT pg_sleep(600)',
2104 stdout => \$stdout, stderr => \$stderr,
2105 timeout => $PostgreSQL::Test::Utils::timeout_default,
2106 timed_out => \$timed_out,
2107 extra_params => ['--single-transaction'])
2108
2109 will set $cmdret to undef and $timed_out to a true value.
2110
2111 $node->psql('postgres', $sql, on_error_die => 1);
2112
2113 dies with an informative message if $sql fails.
2114
2115 =cut
2116
2117 sub psql
2118 {
2119 my ($self, $dbname, $sql, %params) = @_;
2120
2121 local %ENV = $self->_get_env();
2122
2123 my $stdout = $params{stdout};
2124 my $stderr = $params{stderr};
2125 my $replication = $params{replication};
2126 my $timeout = undef;
2127 my $timeout_exception = 'psql timed out';
2128
2129 # Build the connection string.
2130 my $psql_connstr;
2131 if (defined $params{connstr})
2132 {
2133 $psql_connstr = $params{connstr};
2134 }
2135 else
2136 {
2137 $psql_connstr = $self->connstr($dbname);
2138 }
2139 $psql_connstr .= defined $replication ? " replication=$replication" : "";
2140
2141 my @psql_params = (
2142 $self->installed_command('psql'),
2143 '--no-psqlrc', '--no-align', '--tuples-only', '--quiet',
2144 '--dbname' => $psql_connstr,
2145 '--file' => '-');
2146
2147 # If the caller wants an array and hasn't passed stdout/stderr
2148 # references, allocate temporary ones to capture them so we
2149 # can return them. Otherwise we won't redirect them at all.
2150 if (wantarray)
2151 {
2152 if (!defined($stdout))
2153 {
2154 my $temp_stdout = "";
2155 $stdout = \$temp_stdout;
2156 }
2157 if (!defined($stderr))
2158 {
2159 my $temp_stderr = "";
2160 $stderr = \$temp_stderr;
2161 }
2162 }
2163
2164 $params{on_error_stop} = 1 unless defined $params{on_error_stop};
2165 $params{on_error_die} = 0 unless defined $params{on_error_die};
2166
2167 push @psql_params, '--variable' => 'ON_ERROR_STOP=1'
2168 if $params{on_error_stop};
2169 push @psql_params, @{ $params{extra_params} }
2170 if defined $params{extra_params};
2171
2172 $timeout =
2173 IPC::Run::timeout($params{timeout}, exception => $timeout_exception)
2174 if (defined($params{timeout}));
2175
2176 ${ $params{timed_out} } = 0 if defined $params{timed_out};
2177
2178 # IPC::Run would otherwise append to existing contents:
2179 $$stdout = "" if ref($stdout);
2180 $$stderr = "" if ref($stderr);
2181
2182 my $ret;
2183
2184 # Run psql and capture any possible exceptions. If the exception is
2185 # because of a timeout and the caller requested to handle that, just return
2186 # and set the flag. Otherwise, and for any other exception, rethrow.
2187 #
2188 # For background, see
2189 # https://metacpan.org/release/ETHER/Try-Tiny-0.24/view/lib/Try/Tiny.pm
2190 do
2191 {
2192 local $@;
2193 eval {
2194 my @ipcrun_opts = (\@psql_params, '<' => \$sql);
2195 push @ipcrun_opts, '>' => $stdout if defined $stdout;
2196 push @ipcrun_opts, '2>' => $stderr if defined $stderr;
2197 push @ipcrun_opts, $timeout if defined $timeout;
2198
2199 IPC::Run::run @ipcrun_opts;
2200 $ret = $?;
2201 };
2202 my $exc_save = $@;
2203 if ($exc_save)
2204 {
2205
2206 # IPC::Run::run threw an exception. re-throw unless it's a
2207 # timeout, which we'll handle by testing is_expired
2208 die $exc_save
2209 if (blessed($exc_save)
2210 || $exc_save !~ /^\Q$timeout_exception\E/);
2211
2212 $ret = undef;
2213
2214 die "Got timeout exception '$exc_save' but timer not expired?!"
2215 unless $timeout->is_expired;
2216
2217 if (defined($params{timed_out}))
2218 {
2219 ${ $params{timed_out} } = 1;
2220 }
2221 else
2222 {
2223 die "psql timed out: stderr: '$$stderr'\n"
2224 . "while running '@psql_params'";
2225 }
2226 }
2227 };
2228
2229 if (defined $$stdout)
2230 {
2231 chomp $$stdout;
2232 }
2233
2234 if (defined $$stderr)
2235 {
2236 chomp $$stderr;
2237 }
2238
2239 # See http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR
2240 # We don't use IPC::Run::Simple to limit dependencies.
2241 #
2242 # We always die on signal.
2243 if (defined $ret)
2244 {
2245 my $core = $ret & 128 ? " (core dumped)" : "";
2246 die "psql exited with signal "
2247 . ($ret & 127)
2248 . "$core: '$$stderr' while running '@psql_params'"
2249 if $ret & 127;
2250 $ret = $ret >> 8;
2251 }
2252
2253 if ($ret && $params{on_error_die})
2254 {
2255 die "psql error: stderr: '$$stderr'\nwhile running '@psql_params'"
2256 if $ret == 1;
2257 die "connection error: '$$stderr'\nwhile running '@psql_params'"
2258 if $ret == 2;
2259 die
2260 "error running SQL: '$$stderr'\nwhile running '@psql_params' with sql '$sql'"
2261 if $ret == 3;
2262 die "psql returns $ret: '$$stderr'\nwhile running '@psql_params'";
2263 }
2264
2265 if (wantarray)
2266 {
2267 return ($ret, $$stdout, $$stderr);
2268 }
2269 else
2270 {
2271 return $ret;
2272 }
2273 }
2274
2275 =pod
2276
2277 =item $node->background_psql($dbname, %params) => PostgreSQL::Test::BackgroundPsql instance
2278
2279 Invoke B<psql> on B<$dbname> and return a BackgroundPsql object.
2280
2281 psql is invoked in tuples-only unaligned mode with reading of B<.psqlrc>
2282 disabled. That may be overridden by passing extra psql parameters.
2283
2284 Dies on failure to invoke psql, or if psql fails to connect. Errors occurring
2285 later are the caller's problem. psql runs with on_error_stop by default so
2286 that it will stop running sql and return 3 if passed SQL results in an error.
2287
2288 Be sure to "quit" the returned object when done with it.
2289
2290 =over
2291
2292 =item on_error_stop => 1
2293
2294 By default, the B<psql> method invokes the B<psql> program with ON_ERROR_STOP=1
2295 set, so SQL execution is stopped at the first error and exit code 3 is
2296 returned. Set B<on_error_stop> to 0 to ignore errors instead.
2297
2298 =item timeout => 'interval'
2299
2300 Set a timeout for a background psql session. By default, timeout of
2301 $PostgreSQL::Test::Utils::timeout_default is set up.
2302
2303 =item connstr => B<value>
2304
2305 If set, use this as the connection string for the connection to the
2306 backend.
2307
2308 =item replication => B<value>
2309
2310 If set, add B<replication=value> to the conninfo string.
2311 Passing the literal value C<database> results in a logical replication
2312 connection.
2313
2314 =item extra_params => ['--single-transaction']
2315
2316 If given, it must be an array reference containing additional parameters to B<psql>.
2317
2318 =item wait => 1
2319
2320 By default, this method will not return until connection has completed (or
2321 failed). Set B<wait> to 0 to return immediately instead. (Clients can call the
2322 session's C<wait_connect> method manually when needed.)
2323
2324 =back
2325
2326 =cut
2327
2328 sub background_psql
2329 {
2330 my ($self, $dbname, %params) = @_;
2331
2332 local %ENV = $self->_get_env();
2333
2334 my $replication = $params{replication};
2335 my $timeout = undef;
2336
2337 # Build the connection string.
2338 my $psql_connstr;
2339 if (defined $params{connstr})
2340 {
2341 $psql_connstr = $params{connstr};
2342 }
2343 else
2344 {
2345 $psql_connstr = $self->connstr($dbname);
2346 }
2347 $psql_connstr .= defined $replication ? " replication=$replication" : "";
2348
2349 my @psql_params = (
2350 $self->installed_command('psql'),
2351 '--no-psqlrc', '--no-align',
2352 '--tuples-only', '--quiet',
2353 '--dbname' => $psql_connstr,
2354 '--file' => '-');
2355
2356 $params{on_error_stop} = 1 unless defined $params{on_error_stop};
2357 $params{wait} = 1 unless defined $params{wait};
2358 $timeout = $params{timeout} if defined $params{timeout};
2359
2360 push @psql_params, '--set' => 'ON_ERROR_STOP=1' if $params{on_error_stop};
2361 push @psql_params, @{ $params{extra_params} }
2362 if defined $params{extra_params};
2363
2364 return PostgreSQL::Test::BackgroundPsql->new(0, \@psql_params, $timeout,
2365 $params{wait});
2366 }
2367
2368 =pod
2369
2370 =item $node->interactive_psql($dbname, %params) => BackgroundPsql instance
2371
2372 Invoke B<psql> on B<$dbname> and return a BackgroundPsql object, which the
2373 caller may use to send interactive input to B<psql>.
2374
2375 A timeout of $PostgreSQL::Test::Utils::timeout_default is set up.
2376
2377 psql is invoked in tuples-only unaligned mode with reading of B<.psqlrc>
2378 disabled. That may be overridden by passing extra psql parameters.
2379
2380 Dies on failure to invoke psql, or if psql fails to connect.
2381 Errors occurring later are the caller's problem.
2382
2383 Be sure to "quit" the returned object when done with it.
2384
2385 =over
2386
2387 =item extra_params => ['--single-transaction']
2388
2389 If given, it must be an array reference containing additional parameters to B<psql>.
2390
2391 =item history_file => B<path>
2392
2393 Cause the interactive B<psql> session to write its command history to B<path>.
2394 If not given, the history is sent to B</dev/null>.
2395
2396 =back
2397
2398 This requires IO::Pty in addition to IPC::Run.
2399
2400 =cut
2401
2402 sub interactive_psql
2403 {
2404 my ($self, $dbname, %params) = @_;
2405
2406 local %ENV = $self->_get_env();
2407
2408 # Since the invoked psql will believe it's interactive, it will use
2409 # readline/libedit if available. We need to adjust some environment
2410 # settings to prevent unwanted side-effects.
2411
2412 # Developers would not appreciate tests adding a bunch of junk to
2413 # their ~/.psql_history, so redirect readline history somewhere else.
2414 # If the calling script doesn't specify anything, just bit-bucket it.
2415 $ENV{PSQL_HISTORY} = $params{history_file} || '/dev/null';
2416
2417 # Another pitfall for developers is that they might have a ~/.inputrc
2418 # file that changes readline's behavior enough to affect the test.
2419 # So ignore any such file.
2420 $ENV{INPUTRC} = '/dev/null';
2421
2422 # Unset TERM so that readline/libedit won't use any terminal-dependent
2423 # escape sequences; that leads to way too many cross-version variations
2424 # in the output.
2425 delete $ENV{TERM};
2426 # Some versions of readline inspect LS_COLORS, so for luck unset that too.
2427 delete $ENV{LS_COLORS};
2428
2429 my @psql_params = (
2430 $self->installed_command('psql'),
2431 '--no-psqlrc', '--no-align', '--tuples-only',
2432 '--dbname' => $self->connstr($dbname));
2433
2434 push @psql_params, @{ $params{extra_params} }
2435 if defined $params{extra_params};
2436
2437 return PostgreSQL::Test::BackgroundPsql->new(1, \@psql_params);
2438 }
2439
2440 # Common sub of pgbench-invoking interfaces. Makes any requested script files
2441 # and returns pgbench command-line options causing use of those files.
2442 sub _pgbench_make_files
2443 {
2444 my ($self, $files) = @_;
2445 my @file_opts;
2446
2447 if (defined $files)
2448 {
2449
2450 # note: files are ordered for determinism
2451 for my $fn (sort keys %$files)
2452 {
2453 my $filename = $self->basedir . '/' . $fn;
2454 push @file_opts, '--file' => $filename;
2455
2456 # cleanup file weight
2457 $filename =~ s/\@\d+$//;
2458
2459 # filenames are expected to be unique on a test
2460 if (-e $filename)
2461 {
2462 ok(0, "$filename must not already exist");
2463 unlink $filename or die "cannot unlink $filename: $!";
2464 }
2465 PostgreSQL::Test::Utils::append_to_file($filename, $$files{$fn});
2466 }
2467 }
2468
2469 return @file_opts;
2470 }
2471
2472 =pod
2473
2474 =item $node->pgbench($opts, $stat, $out, $err, $name, $files, @args)
2475
2476 Invoke B<pgbench>, with parameters and files.
2477
2478 =over
2479
2480 =item $opts
2481
2482 Options as a string to be split on spaces.
2483
2484 =item $stat
2485
2486 Expected exit status.
2487
2488 =item $out
2489
2490 Reference to a regexp list that must match stdout.
2491
2492 =item $err
2493
2494 Reference to a regexp list that must match stderr.
2495
2496 =item $name
2497
2498 Name of test for error messages.
2499
2500 =item $files
2501
2502 Reference to filename/contents dictionary.
2503
2504 =item @args
2505
2506 Further raw options or arguments.
2507
2508 =back
2509
2510 =cut
2511
2512 sub pgbench
2513 {
2514 local $Test::Builder::Level = $Test::Builder::Level + 1;
2515
2516 my ($self, $opts, $stat, $out, $err, $name, $files, @args) = @_;
2517 my @cmd = (
2518 'pgbench',
2519 split(/\s+/, $opts),
2520 $self->_pgbench_make_files($files), @args);
2521
2522 $self->command_checks_all(\@cmd, $stat, $out, $err, $name);
2523 }
2524
2525 =pod
2526
2527 =item $node->connect_ok($connstr, $test_name, %params)
2528
2529 Attempt a connection with a custom connection string. This is expected
2530 to succeed.
2531
2532 =over
2533
2534 =item sql => B<value>
2535
2536 If this parameter is set, this query is used for the connection attempt
2537 instead of the default.
2538
2539 =item expected_stdout => B<value>
2540
2541 If this regular expression is set, matches it with the output generated.
2542
2543 =item expected_stderr => B<value>
2544
2545 If this regular expression is set, matches it against the standard error
2546 stream; otherwise stderr must be empty.
2547
2548 =item log_like => [ qr/required message/ ]
2549
2550 =item log_unlike => [ qr/prohibited message/ ]
2551
2552 See C<log_check(...)>.
2553
2554 =back
2555
2556 =cut
2557
2558 sub connect_ok
2559 {
2560 local $Test::Builder::Level = $Test::Builder::Level + 1;
2561 my ($self, $connstr, $test_name, %params) = @_;
2562
2563 my $sql;
2564 if (defined($params{sql}))
2565 {
2566 $sql = $params{sql};
2567 }
2568 else
2569 {
2570 $sql = "SELECT \$\$connected with $connstr\$\$";
2571 }
2572
2573 my $log_location = -s $self->logfile;
2574
2575 # Never prompt for a password, any callers of this routine should
2576 # have set up things properly, and this should not block.
2577 my ($ret, $stdout, $stderr) = $self->psql(
2578 'postgres',
2579 $sql,
2580 extra_params => ['-w'],
2581 connstr => "$connstr",
2582 on_error_stop => 0);
2583
2584 is($ret, 0, $test_name);
2585
2586 if (defined($params{expected_stdout}))
2587 {
2588 like($stdout, $params{expected_stdout}, "$test_name: stdout matches");
2589 }
2590
2591 if (defined($params{expected_stderr}))
2592 {
2593 if (like(
2594 $stderr, $params{expected_stderr},
2595 "$test_name: stderr matches")
2596 && ($ret != 0))
2597 {
2598 # In this case (failing test but matching stderr) we'll have
2599 # swallowed the output needed to debug. Put it back into the logs.
2600 diag("$test_name: full stderr:\n" . $stderr);
2601 }
2602 }
2603 else
2604 {
2605 is($stderr, "", "$test_name: no stderr");
2606 }
2607
2608 $self->log_check($test_name, $log_location, %params);
2609 }
2610
2611 =pod
2612
2613 =item $node->connect_fails($connstr, $test_name, %params)
2614
2615 Attempt a connection with a custom connection string. This is expected
2616 to fail.
2617
2618 =over
2619
2620 =item expected_stderr => B<value>
2621
2622 If this regular expression is set, matches it to the output generated
2623 by B<psql>.
2624
2625 =item log_like => [ qr/required message/ ]
2626
2627 =item log_unlike => [ qr/prohibited message/ ]
2628
2629 See C<log_check(...)>. CAUTION: use of either option requires that
2630 the server's log_min_messages be at least DEBUG2, and that no other
2631 client backend is launched concurrently. These requirements allow
2632 C<connect_fails> to wait to see the postmaster-log report of backend
2633 exit, without which there is a race condition as to whether we will
2634 see the expected backend log output.
2635
2636 =back
2637
2638 =cut
2639
2640 sub connect_fails
2641 {
2642 local $Test::Builder::Level = $Test::Builder::Level + 1;
2643 my ($self, $connstr, $test_name, %params) = @_;
2644
2645 my $log_location = -s $self->logfile;
2646
2647 # Never prompt for a password, any callers of this routine should
2648 # have set up things properly, and this should not block.
2649 my ($ret, $stdout, $stderr) = $self->psql(
2650 'postgres',
2651 undef,
2652 extra_params => ['-w'],
2653 connstr => "$connstr");
2654
2655 isnt($ret, 0, $test_name);
2656
2657 if (defined($params{expected_stderr}))
2658 {
2659 like($stderr, $params{expected_stderr}, "$test_name: matches");
2660 }
2661
2662 if (defined($params{log_like}) or defined($params{log_unlike}))
2663 {
2664 $self->wait_for_log(
2665 qr/DEBUG: (?:00000: )?forked new client backend, pid=(\d+) socket.*DEBUG: (?:00000: )?client backend \(PID \1\) exited with exit code \d/s,
2666 $log_location);
2667
2668 $self->log_check($test_name, $log_location, %params);
2669 }
2670 }
2671
2672 =pod
2673
2674 =item $node->poll_query_until($dbname, $query [, $expected ])
2675
2676 Run B<$query> repeatedly, until it returns the B<$expected> result
2677 ('t', or SQL boolean true, by default).
2678 Continues polling if B<psql> returns an error result.
2679 Times out after $PostgreSQL::Test::Utils::timeout_default seconds.
2680 Returns 1 if successful, 0 if timed out.
2681
2682 =cut
2683
2684 sub poll_query_until
2685 {
2686 my ($self, $dbname, $query, $expected) = @_;
2687
2688 local %ENV = $self->_get_env();
2689
2690 $expected = 't' unless defined($expected); # default value
2691
2692 my $cmd = [
2693 $self->installed_command('psql'), '--no-psqlrc',
2694 '--no-align', '--tuples-only',
2695 '--dbname' => $self->connstr($dbname)
2696 ];
2697 my ($stdout, $stderr);
2698 my $max_attempts = 10 * $PostgreSQL::Test::Utils::timeout_default;
2699 my $attempts = 0;
2700
2701 while ($attempts < $max_attempts)
2702 {
2703 my $result = IPC::Run::run $cmd,
2704 '<' => \$query,
2705 '>' => \$stdout,
2706 '2>' => \$stderr;
2707
2708 chomp($stdout);
2709 chomp($stderr);
2710
2711 if ($stdout eq $expected && $stderr eq '')
2712 {
2713 return 1;
2714 }
2715
2716 # Wait 0.1 second before retrying.
2717 usleep(100_000);
2718
2719 $attempts++;
2720 }
2721
2722 # Give up. Print the output from the last attempt, hopefully that's useful
2723 # for debugging.
2724 diag qq(poll_query_until timed out executing this query:
2725 $query
2726 expecting this output:
2727 $expected
2728 last actual query output:
2729 $stdout
2730 with stderr:
2731 $stderr);
2732 return 0;
2733 }
2734
2735 =pod
2736
2737 =item $node->command_ok(...)
2738
2739 Runs a shell command like PostgreSQL::Test::Utils::command_ok, but with PGHOST and PGPORT set
2740 so that the command will default to connecting to this PostgreSQL::Test::Cluster.
2741
2742 =cut
2743
2744 sub command_ok
2745 {
2746 local $Test::Builder::Level = $Test::Builder::Level + 1;
2747
2748 my $self = shift;
2749
2750 local %ENV = $self->_get_env();
2751
2752 PostgreSQL::Test::Utils::command_ok(@_);
2753 return;
2754 }
2755
2756 =pod
2757
2758 =item $node->command_fails(...)
2759
2760 PostgreSQL::Test::Utils::command_fails with our connection parameters. See command_ok(...)
2761
2762 =cut
2763
2764 sub command_fails
2765 {
2766 local $Test::Builder::Level = $Test::Builder::Level + 1;
2767
2768 my $self = shift;
2769
2770 local %ENV = $self->_get_env();
2771
2772 PostgreSQL::Test::Utils::command_fails(@_);
2773 return;
2774 }
2775
2776 =pod
2777
2778 =item $node->command_like(...)
2779
2780 PostgreSQL::Test::Utils::command_like with our connection parameters. See command_ok(...)
2781
2782 =cut
2783
2784 sub command_like
2785 {
2786 local $Test::Builder::Level = $Test::Builder::Level + 1;
2787
2788 my $self = shift;
2789
2790 local %ENV = $self->_get_env();
2791
2792 PostgreSQL::Test::Utils::command_like(@_);
2793 return;
2794 }
2795
2796 =pod
2797
2798 =item $node->command_fails_like(...)
2799
2800 PostgreSQL::Test::Utils::command_fails_like with our connection parameters. See command_ok(...)
2801
2802 =cut
2803
2804 sub command_fails_like
2805 {
2806 local $Test::Builder::Level = $Test::Builder::Level + 1;
2807
2808 my $self = shift;
2809
2810 local %ENV = $self->_get_env();
2811
2812 PostgreSQL::Test::Utils::command_fails_like(@_);
2813 return;
2814 }
2815
2816 =pod
2817
2818 =item $node->command_ok_or_fails_like(...)
2819
2820 PostgreSQL::Test::Utils::command_ok_or_fails_like with our connection parameters. See command_ok(...)
2821
2822 =cut
2823
2824 sub command_ok_or_fails_like
2825 {
2826 local $Test::Builder::Level = $Test::Builder::Level + 1;
2827
2828 my $self = shift;
2829
2830 local %ENV = $self->_get_env();
2831
2832 return PostgreSQL::Test::Utils::command_ok_or_fails_like(@_);
2833 }
2834
2835 =pod
2836
2837 =item $node->command_checks_all(...)
2838
2839 PostgreSQL::Test::Utils::command_checks_all with our connection parameters. See
2840 command_ok(...)
2841
2842 =cut
2843
2844 sub command_checks_all
2845 {
2846 local $Test::Builder::Level = $Test::Builder::Level + 1;
2847
2848 my $self = shift;
2849
2850 local %ENV = $self->_get_env();
2851
2852 PostgreSQL::Test::Utils::command_checks_all(@_);
2853 return;
2854 }
2855
2856 =pod
2857
2858 =item $node->issues_sql_like(cmd, expected_sql, test_name)
2859
2860 Run a command on the node, then verify that $expected_sql appears in the
2861 server log file.
2862
2863 =cut
2864
2865 sub issues_sql_like
2866 {
2867 local $Test::Builder::Level = $Test::Builder::Level + 1;
2868
2869 my ($self, $cmd, $expected_sql, $test_name) = @_;
2870
2871 local %ENV = $self->_get_env();
2872
2873 my $log_location = -s $self->logfile;
2874
2875 my $result = PostgreSQL::Test::Utils::run_log($cmd);
2876 ok($result, "@$cmd exit code 0");
2877 my $log =
2878 PostgreSQL::Test::Utils::slurp_file($self->logfile, $log_location);
2879 like($log, $expected_sql, "$test_name: SQL found in server log");
2880 return;
2881 }
2882
2883 =pod
2884
2885 =item $node->issues_sql_unlike(cmd, unexpected_sql, test_name)
2886
2887 Run a command on the node, then verify that $unexpected_sql does not appear in
2888 the server log file.
2889
2890 =cut
2891
2892 sub issues_sql_unlike
2893 {
2894 local $Test::Builder::Level = $Test::Builder::Level + 1;
2895
2896 my ($self, $cmd, $unexpected_sql, $test_name) = @_;
2897
2898 local %ENV = $self->_get_env();
2899
2900 my $log_location = -s $self->logfile;
2901
2902 my $result = PostgreSQL::Test::Utils::run_log($cmd);
2903 ok($result, "@$cmd exit code 0");
2904 my $log =
2905 PostgreSQL::Test::Utils::slurp_file($self->logfile, $log_location);
2906 unlike($log, $unexpected_sql, "$test_name: SQL not found in server log");
2907 return;
2908 }
2909
2910 =pod
2911
2912 =item $node->log_content()
2913
2914 Returns the contents of log of the node
2915
2916 =cut
2917
2918 sub log_content
2919 {
2920 my ($self) = @_;
2921 return PostgreSQL::Test::Utils::slurp_file($self->logfile);
2922 }
2923
2924 =pod
2925
2926 =item $node->log_check($test_name, $offset, %params)
2927
2928 Check contents of server logs.
2929
2930 =over
2931
2932 =item $test_name
2933
2934 Name of test for error messages.
2935
2936 =item $offset
2937
2938 Offset of the log file.
2939
2940 =item log_like => [ qr/required message/ ]
2941
2942 If given, it must be an array reference containing a list of regular
2943 expressions that must match against the server log, using
2944 C<Test::More::like()>.
2945
2946 =item log_unlike => [ qr/prohibited message/ ]
2947
2948 If given, it must be an array reference containing a list of regular
2949 expressions that must NOT match against the server log. They will be
2950 passed to C<Test::More::unlike()>.
2951
2952 =back
2953
2954 =cut
2955
2956 sub log_check
2957 {
2958 my ($self, $test_name, $offset, %params) = @_;
2959
2960 my (@log_like, @log_unlike);
2961 if (defined($params{log_like}))
2962 {
2963 @log_like = @{ $params{log_like} };
2964 }
2965 if (defined($params{log_unlike}))
2966 {
2967 @log_unlike = @{ $params{log_unlike} };
2968 }
2969
2970 if (@log_like or @log_unlike)
2971 {
2972 my $log_contents =
2973 PostgreSQL::Test::Utils::slurp_file($self->logfile, $offset);
2974
2975 while (my $regex = shift @log_like)
2976 {
2977 like($log_contents, $regex, "$test_name: log matches");
2978 }
2979 while (my $regex = shift @log_unlike)
2980 {
2981 unlike($log_contents, $regex, "$test_name: log does not match");
2982 }
2983 }
2984 }
2985
2986 =pod
2987
2988 =item log_contains(pattern, offset)
2989
2990 Find pattern in logfile of node after offset byte.
2991
2992 =cut
2993
2994 sub log_contains
2995 {
2996 my ($self, $pattern, $offset) = @_;
2997
2998 return PostgreSQL::Test::Utils::slurp_file($self->logfile, $offset) =~
2999 m/$pattern/;
3000 }
3001
3002 =pod
3003
3004 =item $node->run_log(...)
3005
3006 Runs a shell command like PostgreSQL::Test::Utils::run_log, but with connection parameters set
3007 so that the command will default to connecting to this PostgreSQL::Test::Cluster.
3008
3009 =cut
3010
3011 sub run_log
3012 {
3013 my $self = shift;
3014
3015 local %ENV = $self->_get_env();
3016
3017 return PostgreSQL::Test::Utils::run_log(@_);
3018 }
3019
3020 =pod
3021
3022 =item $node->lsn(mode)
3023
3024 Look up WAL locations on the server:
3025
3026 * insert location (primary only, error on replica)
3027 * write location (primary only, error on replica)
3028 * flush location (primary only, error on replica)
3029 * receive location (always undef on primary)
3030 * replay location (always undef on primary)
3031
3032 mode must be specified.
3033
3034 =cut
3035
3036 sub lsn
3037 {
3038 my ($self, $mode) = @_;
3039 my %modes = (
3040 'insert' => 'pg_current_wal_insert_lsn()',
3041 'flush' => 'pg_current_wal_flush_lsn()',
3042 'write' => 'pg_current_wal_lsn()',
3043 'receive' => 'pg_last_wal_receive_lsn()',
3044 'replay' => 'pg_last_wal_replay_lsn()');
3045
3046 $mode = '<undef>' if !defined($mode);
3047 croak "unknown mode for 'lsn': '$mode', valid modes are "
3048 . join(', ', keys %modes)
3049 if !defined($modes{$mode});
3050
3051 my $result = $self->safe_psql('postgres', "SELECT $modes{$mode}");
3052 chomp($result);
3053 if ($result eq '')
3054 {
3055 return;
3056 }
3057 else
3058 {
3059 return $result;
3060 }
3061 }
3062
3063 =pod
3064
3065 =item $node->write_wal($tli, $lsn, $segment_size, $data)
3066
3067 Write some arbitrary data in WAL for the given segment at $lsn (in bytes).
3068 This should be called while the cluster is not running.
3069
3070 Returns the path of the WAL segment written to.
3071
3072 =cut
3073
3074 sub write_wal
3075 {
3076 my ($self, $tli, $lsn, $segment_size, $data) = @_;
3077
3078 # Calculate segment number and offset position in segment based on the
3079 # input LSN.
3080 my $segment = $lsn / $segment_size;
3081 my $offset = $lsn % $segment_size;
3082 my $path =
3083 sprintf("%s/pg_wal/%08X%08X%08X", $self->data_dir, $tli, 0, $segment);
3084
3085 open my $fh, "+<:raw", $path or die "could not open WAL segment $path";
3086 seek($fh, $offset, SEEK_SET) or die "could not seek WAL segment $path";
3087 print $fh $data;
3088 close $fh;
3089
3090 return $path;
3091 }
3092
3093 =pod
3094
3095 =item $node->emit_wal($size)
3096
3097 Emit a WAL record of arbitrary size, using pg_logical_emit_message().
3098
3099 Returns the end LSN of the record inserted, in bytes.
3100
3101 =cut
3102
3103 sub emit_wal
3104 {
3105 my ($self, $size) = @_;
3106
3107 return int(
3108 $self->safe_psql(
3109 'postgres',
3110 "SELECT pg_logical_emit_message(true, '', repeat('a', $size)) - '0/0'"
3111 ));
3112 }
3113
3114
3115 # Private routine returning the current insert LSN of a node, in bytes.
3116 # Used by the routines below in charge of advancing WAL to arbitrary
3117 # positions. The insert LSN is returned in bytes.
3118 sub _get_insert_lsn
3119 {
3120 my ($self) = @_;
3121 return int(
3122 $self->safe_psql(
3123 'postgres', "SELECT pg_current_wal_insert_lsn() - '0/0'"));
3124 }
3125
3126 =pod
3127
3128 =item $node->advance_wal_out_of_record_splitting_zone($wal_block_size)
3129
3130 Advance WAL at the end of a page, making sure that we are far away enough
3131 from the end of a page that we could insert a couple of small records.
3132
3133 This inserts a few records of a fixed size, until the threshold gets close
3134 enough to the end of the WAL page inserting records to.
3135
3136 Returns the end LSN up to which WAL has advanced, in bytes.
3137
3138 =cut
3139
3140 sub advance_wal_out_of_record_splitting_zone
3141 {
3142 my ($self, $wal_block_size) = @_;
3143
3144 my $page_threshold = $wal_block_size / 4;
3145 my $end_lsn = $self->_get_insert_lsn();
3146 my $page_offset = $end_lsn % $wal_block_size;
3147 while ($page_offset >= $wal_block_size - $page_threshold)
3148 {
3149 $self->emit_wal($page_threshold);
3150 $end_lsn = $self->_get_insert_lsn();
3151 $page_offset = $end_lsn % $wal_block_size;
3152 }
3153 return $end_lsn;
3154 }
3155
3156 =pod
3157
3158 =item $node->advance_wal_to_record_splitting_zone($wal_block_size)
3159
3160 Advance WAL so close to the end of a page that an XLogRecordHeader would not
3161 fit on it.
3162
3163 Returns the end LSN up to which WAL has advanced, in bytes.
3164
3165 =cut
3166
3167 sub advance_wal_to_record_splitting_zone
3168 {
3169 my ($self, $wal_block_size) = @_;
3170
3171 # Size of record header.
3172 my $RECORD_HEADER_SIZE = 24;
3173
3174 my $end_lsn = $self->_get_insert_lsn();
3175 my $page_offset = $end_lsn % $wal_block_size;
3176
3177 # Get fairly close to the end of a page in big steps
3178 while ($page_offset <= $wal_block_size - 512)
3179 {
3180 $self->emit_wal($wal_block_size - $page_offset - 256);
3181 $end_lsn = $self->_get_insert_lsn();
3182 $page_offset = $end_lsn % $wal_block_size;
3183 }
3184
3185 # Calibrate our message size so that we can get closer 8 bytes at
3186 # a time.
3187 my $message_size = $wal_block_size - 80;
3188 while ($page_offset <= $wal_block_size - $RECORD_HEADER_SIZE)
3189 {
3190 $self->emit_wal($message_size);
3191 $end_lsn = $self->_get_insert_lsn();
3192
3193 my $old_offset = $page_offset;
3194 $page_offset = $end_lsn % $wal_block_size;
3195
3196 # Adjust the message size until it causes 8 bytes changes in
3197 # offset, enough to be able to split a record header.
3198 my $delta = $page_offset - $old_offset;
3199 if ($delta > 8)
3200 {
3201 $message_size -= 8;
3202 }
3203 elsif ($delta <= 0)
3204 {
3205 $message_size += 8;
3206 }
3207 }
3208 return $end_lsn;
3209 }
3210
3211 =pod
3212
3213 =item $node->check_extension(extension_name)
3214
3215 Scan pg_available_extensions to check that an extension is available in an
3216 installation.
3217
3218 Returns 1 if the extension is available, 0 otherwise.
3219
3220 =cut
3221
3222 sub check_extension
3223 {
3224 my ($self, $extension_name) = @_;
3225
3226 my $result = $self->safe_psql('postgres',
3227 "SELECT count(*) > 0 FROM pg_available_extensions WHERE name = '$extension_name';"
3228 );
3229
3230 return $result eq 't' ? 1 : 0;
3231 }
3232
3233 =pod
3234
3235 =item $node->wait_for_event(backend_type, wait_event_name)
3236
3237 Poll pg_stat_activity until backend_type reaches wait_event_name.
3238
3239 =cut
3240
3241 sub wait_for_event
3242 {
3243 my ($self, $backend_type, $wait_event_name) = @_;
3244
3245 $self->poll_query_until(
3246 'postgres', qq[
3247 SELECT count(*) > 0 FROM pg_stat_activity
3248 WHERE backend_type = '$backend_type' AND wait_event = '$wait_event_name'
3249 ])
3250 or die
3251 qq(timed out when waiting for $backend_type to reach wait event '$wait_event_name');
3252
3253 return;
3254 }
3255
3256 =pod
3257
3258 =item $node->wait_for_catchup(standby_name, mode, target_lsn)
3259
3260 Wait for the replication connection with application_name standby_name until
3261 its 'mode' replication column in pg_stat_replication equals or passes the
3262 specified or default target_lsn. By default the replay_lsn is waited for,
3263 but 'mode' may be specified to wait for any of sent|write|flush|replay.
3264 The replication connection must be in a streaming state.
3265
3266 When doing physical replication, the standby is usually identified by
3267 passing its PostgreSQL::Test::Cluster instance. When doing logical
3268 replication, standby_name identifies a subscription.
3269
3270 When not in recovery, the default value of target_lsn is $node->lsn('write'),
3271 which ensures that the standby has caught up to what has been committed on
3272 the primary.
3273
3274 When in recovery, the default value of target_lsn is $node->lsn('replay')
3275 instead which ensures that the cascaded standby has caught up to what has been
3276 replayed on the standby.
3277
3278 If you pass an explicit value of target_lsn, it should almost always be
3279 the primary's write LSN; so this parameter is seldom needed except when
3280 querying some intermediate replication node rather than the primary.
3281
3282 If there is no active replication connection from this peer, waits until
3283 poll_query_until timeout.
3284
3285 Requires that the 'postgres' db exists and is accessible.
3286
3287 This is not a test. It die()s on failure.
3288
3289 =cut
3290
3291 sub wait_for_catchup
3292 {
3293 my ($self, $standby_name, $mode, $target_lsn) = @_;
3294 $mode = defined($mode) ? $mode : 'replay';
3295 my %valid_modes =
3296 ('sent' => 1, 'write' => 1, 'flush' => 1, 'replay' => 1);
3297 croak "unknown mode $mode for 'wait_for_catchup', valid modes are "
3298 . join(', ', keys(%valid_modes))
3299 unless exists($valid_modes{$mode});
3300
3301 # Allow passing of a PostgreSQL::Test::Cluster instance as shorthand
3302 if (blessed($standby_name)
3303 && $standby_name->isa("PostgreSQL::Test::Cluster"))
3304 {
3305 $standby_name = $standby_name->name;
3306 }
3307 if (!defined($target_lsn))
3308 {
3309 my $isrecovery =
3310 $self->safe_psql('postgres', "SELECT pg_is_in_recovery()");
3311 chomp($isrecovery);
3312 if ($isrecovery eq 't')
3313 {
3314 $target_lsn = $self->lsn('replay');
3315 }
3316 else
3317 {
3318 $target_lsn = $self->lsn('write');
3319 }
3320 }
3321 print "Waiting for replication conn "
3322 . $standby_name . "'s "
3323 . $mode
3324 . "_lsn to pass "
3325 . $target_lsn . " on "
3326 . $self->name . "\n";
3327 # Before release 12 walreceiver just set the application name to
3328 # "walreceiver"
3329 my $query = qq[SELECT '$target_lsn' <= ${mode}_lsn AND state = 'streaming'
3330 FROM pg_catalog.pg_stat_replication
3331 WHERE application_name IN ('$standby_name', 'walreceiver')];
3332 if (!$self->poll_query_until('postgres', $query))
3333 {
3334 if (PostgreSQL::Test::Utils::has_wal_read_bug)
3335 {
3336 # Mimic having skipped the test file. If >0 tests have run, the
3337 # harness won't accept a skip; otherwise, it won't accept
3338 # done_testing(). Force a nonzero count by running one test.
3339 ok(1, 'dummy test before skip for filesystem bug');
3340 carp "skip rest: timed out waiting for catchup & filesystem bug";
3341 done_testing();
3342 exit 0;
3343 }
3344 else
3345 {
3346 # Fetch additional detail for debugging purposes
3347 $query = qq[SELECT * FROM pg_catalog.pg_stat_replication];
3348 my $details = $self->safe_psql('postgres', $query);
3349 diag qq(Last pg_stat_replication contents:
3350 ${details});
3351 croak "timed out waiting for catchup";
3352 }
3353 }
3354 print "done\n";
3355 return;
3356 }
3357
3358 =pod
3359
3360 =item $node->wait_for_replay_catchup($standby_name [, $base_node ])
3361
3362 Wait for the replication connection with application_name I<$standby_name>
3363 until its B<replay> replication column in pg_stat_replication in I<$node>
3364 equals or passes the I<$base_node>'s B<replay_lsn>. If I<$base_node> is
3365 omitted, the LSN to wait for is obtained from I<$node>.
3366
3367 The replication connection must be in a streaming state.
3368
3369 Requires that the 'postgres' db exists and is accessible.
3370
3371 This is not a test. It die()s on failure.
3372
3373 =cut
3374
3375 sub wait_for_replay_catchup
3376 {
3377 my ($self, $standby_name, $node) = @_;
3378 $node = defined($node) ? $node : $self;
3379
3380 $self->wait_for_catchup($standby_name, 'replay', $node->lsn('flush'));
3381 }
3382
3383 =item $node->wait_for_slot_catchup(slot_name, mode, target_lsn)
3384
3385 Wait for the named replication slot to equal or pass the supplied target_lsn.
3386 The location used is the restart_lsn unless mode is given, in which case it may
3387 be 'restart' or 'confirmed_flush'.
3388
3389 Requires that the 'postgres' db exists and is accessible.
3390
3391 This is not a test. It die()s on failure.
3392
3393 If the slot is not active, will time out after poll_query_until's timeout.
3394
3395 target_lsn may be any arbitrary lsn, but is typically $primary_node->lsn('insert').
3396
3397 Note that for logical slots, restart_lsn is held down by the oldest in-progress tx.
3398
3399 =cut
3400
3401 sub wait_for_slot_catchup
3402 {
3403 my ($self, $slot_name, $mode, $target_lsn) = @_;
3404 $mode = defined($mode) ? $mode : 'restart';
3405 if (!($mode eq 'restart' || $mode eq 'confirmed_flush'))
3406 {
3407 croak "valid modes are restart, confirmed_flush";
3408 }
3409 croak 'target lsn must be specified' unless defined($target_lsn);
3410 print "Waiting for replication slot "
3411 . $slot_name . "'s "
3412 . $mode
3413 . "_lsn to pass "
3414 . $target_lsn . " on "
3415 . $self->name . "\n";
3416 my $query =
3417 qq[SELECT '$target_lsn' <= ${mode}_lsn FROM pg_catalog.pg_replication_slots WHERE slot_name = '$slot_name';];
3418 if (!$self->poll_query_until('postgres', $query))
3419 {
3420 # Fetch additional detail for debugging purposes
3421 $query = qq[SELECT * FROM pg_catalog.pg_replication_slots];
3422 my $details = $self->safe_psql('postgres', $query);
3423 diag qq(Last pg_replication_slots contents:
3424 ${details});
3425 croak "timed out waiting for catchup";
3426 }
3427 print "done\n";
3428 return;
3429 }
3430
3431 =pod
3432
3433 =item $node->wait_for_subscription_sync(publisher, subname, dbname)
3434
3435 Wait for all tables in pg_subscription_rel to complete the initial
3436 synchronization (i.e to be either in 'syncdone' or 'ready' state).
3437
3438 If the publisher node is given, additionally, check if the subscriber has
3439 caught up to what has been committed on the primary. This is useful to
3440 ensure that the initial data synchronization has been completed after
3441 creating a new subscription.
3442
3443 If there is no active replication connection from this peer, wait until
3444 poll_query_until timeout.
3445
3446 This is not a test. It die()s on failure.
3447
3448 =cut
3449
3450 sub wait_for_subscription_sync
3451 {
3452 my ($self, $publisher, $subname, $dbname) = @_;
3453 my $name = $self->name;
3454
3455 $dbname = defined($dbname) ? $dbname : 'postgres';
3456
3457 # Wait for all tables to finish initial sync.
3458 print "Waiting for all subscriptions in \"$name\" to synchronize data\n";
3459 my $query =
3460 qq[SELECT count(1) = 0 FROM pg_subscription_rel WHERE srsubstate NOT IN ('r', 's');];
3461 if (!$self->poll_query_until($dbname, $query))
3462 {
3463 # Fetch additional detail for debugging purposes
3464 $query = qq[SELECT * FROM pg_subscription_rel];
3465 my $details = $self->safe_psql($dbname, $query);
3466 diag qq(Last pg_subscription_rel contents:
3467 ${details});
3468 croak "timed out waiting for subscriber to synchronize data";
3469 }
3470
3471 # Then, wait for the replication to catchup if required.
3472 if (defined($publisher))
3473 {
3474 croak 'subscription name must be specified' unless defined($subname);
3475 $publisher->wait_for_catchup($subname);
3476 }
3477
3478 print "done\n";
3479 return;
3480 }
3481
3482 =pod
3483
3484 =item $node->wait_for_log(regexp, offset)
3485
3486 Waits for the contents of the server log file, starting at the given offset, to
3487 match the supplied regular expression. Checks the entire log if no offset is
3488 given. Times out after $PostgreSQL::Test::Utils::timeout_default seconds.
3489
3490 If successful, returns the length of the entire log file, in bytes.
3491
3492 =cut
3493
3494 sub wait_for_log
3495 {
3496 my ($self, $regexp, $offset) = @_;
3497 $offset = 0 unless defined $offset;
3498
3499 my $max_attempts = 10 * $PostgreSQL::Test::Utils::timeout_default;
3500 my $attempts = 0;
3501
3502 while ($attempts < $max_attempts)
3503 {
3504 my $log =
3505 PostgreSQL::Test::Utils::slurp_file($self->logfile, $offset);
3506
3507 return $offset + length($log) if ($log =~ m/$regexp/);
3508
3509 # Wait 0.1 second before retrying.
3510 usleep(100_000);
3511
3512 $attempts++;
3513 }
3514
3515 croak "timed out waiting for match: $regexp";
3516 }
3517
3518 =pod
3519
3520 =item $node->query_hash($dbname, $query, @columns)
3521
3522 Execute $query on $dbname, replacing any appearance of the string __COLUMNS__
3523 within the query with a comma-separated list of @columns.
3524
3525 If __COLUMNS__ does not appear in the query, its result columns must EXACTLY
3526 match the order and number (but not necessarily alias) of supplied @columns.
3527
3528 The query must return zero or one rows.
3529
3530 Return a hash-ref representation of the results of the query, with any empty
3531 or null results as defined keys with an empty-string value. There is no way
3532 to differentiate between null and empty-string result fields.
3533
3534 If the query returns zero rows, return a hash with all columns empty. There
3535 is no way to differentiate between zero rows returned and a row with only
3536 null columns.
3537
3538 =cut
3539
3540 sub query_hash
3541 {
3542 my ($self, $dbname, $query, @columns) = @_;
3543 croak 'calls in array context for multi-row results not supported yet'
3544 if (wantarray);
3545
3546 # Replace __COLUMNS__ if found
3547 substr($query, index($query, '__COLUMNS__'), length('__COLUMNS__')) =
3548 join(', ', @columns)
3549 if index($query, '__COLUMNS__') >= 0;
3550 my $result = $self->safe_psql($dbname, $query);
3551
3552 # hash slice, see http://stackoverflow.com/a/16755894/398670 .
3553 #
3554 # Fills the hash with empty strings produced by x-operator element
3555 # duplication if result is an empty row
3556 #
3557 my %val;
3558 @val{@columns} =
3559 $result ne '' ? split(qr/\|/, $result, -1) : ('',) x scalar(@columns);
3560 return \%val;
3561 }
3562
3563 =pod
3564
3565 =item $node->slot(slot_name)
3566
3567 Return hash-ref of replication slot data for the named slot, or a hash-ref with
3568 all values '' if not found. Does not differentiate between null and empty string
3569 for fields, no field is ever undef.
3570
3571 The restart_lsn and confirmed_flush_lsn fields are returned verbatim, and also
3572 as a 2-list of [highword, lowword] integer. Since we rely on Perl 5.14 we can't
3573 "use bigint", it's from 5.20, and we can't assume we have Math::Bigint from CPAN
3574 either.
3575
3576 =cut
3577
3578 sub slot
3579 {
3580 my ($self, $slot_name) = @_;
3581 my @columns = (
3582 'plugin', 'slot_type', 'datoid', 'database',
3583 'active', 'active_pid', 'xmin', 'catalog_xmin',
3584 'restart_lsn');
3585 return $self->query_hash(
3586 'postgres',
3587 "SELECT __COLUMNS__ FROM pg_catalog.pg_replication_slots WHERE slot_name = '$slot_name'",
3588 @columns);
3589 }
3590
3591 =pod
3592
3593 =item $node->pg_recvlogical_upto(self, dbname, slot_name, endpos, timeout_secs, ...)
3594
3595 Invoke pg_recvlogical to read from slot_name on dbname until LSN endpos, which
3596 corresponds to pg_recvlogical --endpos. Gives up after timeout (if nonzero).
3597
3598 Disallows pg_recvlogical from internally retrying on error by passing --no-loop.
3599
3600 Plugin options are passed as additional keyword arguments.
3601
3602 If called in scalar context, returns stdout, and die()s on timeout or nonzero return.
3603
3604 If called in array context, returns a tuple of (retval, stdout, stderr, timeout).
3605 timeout is the IPC::Run::Timeout object whose is_expired method can be tested
3606 to check for timeout. retval is undef on timeout.
3607
3608 =cut
3609
3610 sub pg_recvlogical_upto
3611 {
3612 my ($self, $dbname, $slot_name, $endpos, $timeout_secs, %plugin_options)
3613 = @_;
3614
3615 local %ENV = $self->_get_env();
3616
3617 my ($stdout, $stderr);
3618
3619 my $timeout_exception = 'pg_recvlogical timed out';
3620
3621 croak 'slot name must be specified' unless defined($slot_name);
3622 croak 'endpos must be specified' unless defined($endpos);
3623
3624 my @cmd = (
3625 $self->installed_command('pg_recvlogical'),
3626 '--slot' => $slot_name,
3627 '--dbname' => $self->connstr($dbname),
3628 '--endpos' => $endpos,
3629 '--file' => '-',
3630 '--no-loop', '--start');
3631
3632 while (my ($k, $v) = each %plugin_options)
3633 {
3634 croak "= is not permitted to appear in replication option name"
3635 if ($k =~ qr/=/);
3636 push @cmd, "--option" => "$k=$v";
3637 }
3638
3639 my $timeout;
3640 $timeout =
3641 IPC::Run::timeout($timeout_secs, exception => $timeout_exception)
3642 if $timeout_secs;
3643 my $ret = 0;
3644
3645 do
3646 {
3647 local $@;
3648 eval {
3649 IPC::Run::run(\@cmd, '>' => \$stdout, '2>' => \$stderr, $timeout);
3650 $ret = $?;
3651 };
3652 my $exc_save = $@;
3653 if ($exc_save)
3654 {
3655
3656 # IPC::Run::run threw an exception. re-throw unless it's a
3657 # timeout, which we'll handle by testing is_expired
3658 die $exc_save
3659 if (blessed($exc_save) || $exc_save !~ qr/$timeout_exception/);
3660
3661 $ret = undef;
3662
3663 die "Got timeout exception '$exc_save' but timer not expired?!"
3664 unless $timeout->is_expired;
3665
3666 die
3667 "$exc_save waiting for endpos $endpos with stdout '$stdout', stderr '$stderr'"
3668 unless wantarray;
3669 }
3670 };
3671
3672 if (wantarray)
3673 {
3674 return ($ret, $stdout, $stderr, $timeout);
3675 }
3676 else
3677 {
3678 die
3679 "pg_recvlogical exited with code '$ret', stdout '$stdout' and stderr '$stderr'"
3680 if $ret;
3681 return $stdout;
3682 }
3683 }
3684
3685 =pod
3686
3687 =item $node->corrupt_page_checksum(self, file, page_offset)
3688
3689 Intentionally corrupt the checksum field of one page in a file.
3690 The server must be stopped for this to work reliably.
3691
3692 The file name should be specified relative to the cluster datadir.
3693 page_offset had better be a multiple of the cluster's block size.
3694
3695 =cut
3696
3697 sub corrupt_page_checksum
3698 {
3699 my ($self, $file, $page_offset) = @_;
3700 my $pgdata = $self->data_dir;
3701 my $pageheader;
3702
3703 open my $fh, '+<', "$pgdata/$file" or die "open($file) failed: $!";
3704 binmode $fh;
3705 sysseek($fh, $page_offset, 0) or die "sysseek failed: $!";
3706 sysread($fh, $pageheader, 24) or die "sysread failed: $!";
3707 # This inverts the pd_checksum field (only); see struct PageHeaderData
3708 $pageheader ^= "\0\0\0\0\0\0\0\0\xff\xff";
3709 sysseek($fh, $page_offset, 0) or die "sysseek failed: $!";
3710 syswrite($fh, $pageheader) or die "syswrite failed: $!";
3711 close $fh;
3712
3713 return;
3714 }
3715
3716 =pod
3717
3718 =item $node->log_standby_snapshot(self, standby, slot_name)
3719
3720 Log a standby snapshot on primary once the slot restart_lsn is determined on
3721 the standby.
3722
3723 =cut
3724
3725 sub log_standby_snapshot
3726 {
3727 my ($self, $standby, $slot_name) = @_;
3728
3729 # Once the slot's restart_lsn is determined, the standby looks for
3730 # xl_running_xacts WAL record from the restart_lsn onwards. First wait
3731 # until the slot restart_lsn is determined.
3732
3733 $standby->poll_query_until(
3734 'postgres', qq[
3735 SELECT restart_lsn IS NOT NULL
3736 FROM pg_catalog.pg_replication_slots WHERE slot_name = '$slot_name'
3737 ])
3738 or die
3739 "timed out waiting for logical slot to calculate its restart_lsn";
3740
3741 # Then arrange for the xl_running_xacts record for which the standby is
3742 # waiting.
3743 $self->safe_psql('postgres', 'SELECT pg_log_standby_snapshot()');
3744 }
3745
3746 =pod
3747
3748 =item $node->create_logical_slot_on_standby(self, primary, slot_name, dbname)
3749
3750 Create logical replication slot on given standby
3751
3752 =cut
3753
3754 sub create_logical_slot_on_standby
3755 {
3756 my ($self, $primary, $slot_name, $dbname) = @_;
3757 my ($stdout, $stderr);
3758
3759 my $handle;
3760
3761 $handle = IPC::Run::start(
3762 [
3763 'pg_recvlogical',
3764 '--dbname' => $self->connstr($dbname),
3765 '--plugin' => 'test_decoding',
3766 '--slot' => $slot_name,
3767 '--create-slot'
3768 ],
3769 '>' => \$stdout,
3770 '2>' => \$stderr);
3771
3772 # Arrange for the xl_running_xacts record for which pg_recvlogical is
3773 # waiting.
3774 $primary->log_standby_snapshot($self, $slot_name);
3775
3776 $handle->finish();
3777
3778 is($self->slot($slot_name)->{'slot_type'},
3779 'logical', $slot_name . ' on standby created')
3780 or die "could not create slot" . $slot_name;
3781 }
3782
3783 =pod
3784
3785 =item $node->validate_slot_inactive_since(self, slot_name, reference_time)
3786
3787 Validate inactive_since value of a given replication slot against the reference
3788 time and return it.
3789
3790 =cut
3791
3792 sub validate_slot_inactive_since
3793 {
3794 my ($self, $slot_name, $reference_time) = @_;
3795 my $name = $self->name;
3796
3797 my $inactive_since = $self->safe_psql(
3798 'postgres',
3799 qq(SELECT inactive_since FROM pg_replication_slots
3800 WHERE slot_name = '$slot_name' AND inactive_since IS NOT NULL;)
3801 );
3802
3803 # Check that the inactive_since is sane
3804 is( $self->safe_psql(
3805 'postgres',
3806 qq[SELECT '$inactive_since'::timestamptz > to_timestamp(0) AND
3807 '$inactive_since'::timestamptz > '$reference_time'::timestamptz;]
3808 ),
3809 't',
3810 "last inactive time for slot $slot_name is valid on node $name")
3811 or die "could not validate captured inactive_since for slot $slot_name";
3812
3813 return $inactive_since;
3814 }
3815
3816 =pod
3817
3818 =item $node->advance_wal(num)
3819
3820 Advance WAL of node by given number of segments.
3821
3822 =cut
3823
3824 sub advance_wal
3825 {
3826 my ($self, $num) = @_;
3827
3828 # Advance by $n segments (= (wal_segment_size * $num) bytes).
3829 # pg_switch_wal() forces a WAL flush, making pg_logical_emit_message()
3830 # safe to use in non-transactional mode.
3831 for (my $i = 0; $i < $num; $i++)
3832 {
3833 $self->safe_psql(
3834 'postgres', qq{
3835 SELECT pg_logical_emit_message(false, '', 'foo');
3836 SELECT pg_switch_wal();
3837 });
3838 }
3839 }
3840
3841 =pod
3842
3843 =back
3844
3845 =cut
3846
3847 ##########################################################################
3848
3849 package PostgreSQL::Test::Cluster::V_11
3850 ; ## no critic (ProhibitMultiplePackages)
3851
3852 use parent -norequire, qw(PostgreSQL::Test::Cluster);
3853
3854 # https://www.postgresql.org/docs/11/release-11.html
3855
3856 # max_wal_senders + superuser_reserved_connections must be < max_connections
3857 # uses recovery.conf
3858
3859 sub _recovery_file { return "recovery.conf"; }
3860
3861 sub set_standby_mode
3862 {
3863 my $self = shift;
3864 $self->append_conf("recovery.conf", "standby_mode = on\n");
3865 }
3866
3867 sub init
3868 {
3869 my ($self, %params) = @_;
3870 $self->SUPER::init(%params);
3871 $self->adjust_conf('postgresql.conf', 'max_wal_senders',
3872 $params{allows_streaming} ? 5 : 0);
3873 }
3874
3875 ##########################################################################
3876
3877 package PostgreSQL::Test::Cluster::V_10
3878 ; ## no critic (ProhibitMultiplePackages)
3879
3880 use parent -norequire, qw(PostgreSQL::Test::Cluster::V_11);
3881
3882 # https://www.postgresql.org/docs/10/release-10.html
3883
3884 ########################################################################
3885
3886 1;