Debian Codegraph @

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

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