PostgreSQL Source Code git master
Loading...
Searching...
No Matches
pg_regress.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * pg_regress --- regression test driver
4 *
5 * This is a C implementation of the previous shell script for running
6 * the regression tests, and should be mostly compatible with it.
7 * Initial author of C translation: Magnus Hagander
8 *
9 * This code is released under the terms of the PostgreSQL License.
10 *
11 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
12 * Portions Copyright (c) 1994, Regents of the University of California
13 *
14 * src/test/regress/pg_regress.c
15 *
16 *-------------------------------------------------------------------------
17 */
18
19#include "postgres_fe.h"
20
21#include <ctype.h>
22#include <sys/resource.h>
23#include <sys/stat.h>
24#include <sys/time.h>
25#include <sys/wait.h>
26#include <signal.h>
27#include <unistd.h>
28
29#include "common/logging.h"
31#include "common/username.h"
32#include "getopt_long.h"
33#include "lib/stringinfo.h"
34#include "libpq-fe.h"
35#include "libpq/pqcomm.h" /* needed for UNIXSOCK_PATH() */
36#include "pg_config_paths.h"
37#include "pg_regress.h"
39
40/* for resultmap we need a list of pairs of strings */
41typedef struct _resultmap
42{
43 char *test;
44 char *type;
48
49/*
50 * Values obtained from Makefile.
51 */
53
54#ifndef WIN32 /* not used in WIN32 case */
55static char *shellprog = SHELLPROG;
56#endif
57
58/*
59 * On Windows we use -w in diff switches to avoid problems with inconsistent
60 * newline representation. The actual result files will generally have
61 * Windows-style newlines, but the comparison files might or might not.
62 */
63#ifndef WIN32
64const char *basic_diff_opts = "";
65const char *pretty_diff_opts = "-U3";
66#else
67const char *basic_diff_opts = "--strip-trailing-cr";
68const char *pretty_diff_opts = "--strip-trailing-cr -U3";
69#endif
70
71/*
72 * The width of the testname field when printing to ensure vertical alignment
73 * of test runtimes. This number is somewhat arbitrarily chosen to match the
74 * older pre-TAP output format.
75 */
76#define TESTNAME_WIDTH 36
77
78/*
79 * The number times per second that pg_regress checks to see if the test
80 * instance server has started and is available for connection.
81 */
82#define WAIT_TICKS_PER_SECOND 20
83
97
98/* options settable from command line */
100bool debug = false;
101char *inputdir = ".";
102char *outputdir = ".";
103char *expecteddir = ".";
107static int max_connections = 0;
108static int max_concurrent_tests = 0;
109static char *encoding = NULL;
112static char *temp_instance = NULL;
114static bool nolocale = false;
115static bool use_existing = false;
116static char *hostname = NULL;
117static int port = -1;
118static char portstr[16];
119static bool port_specified_by_user = false;
120static char *dlpath = PKGLIBDIR;
121static char *user = NULL;
124
125/* internal variables */
126static const char *progname;
127static char *logfilename;
128static FILE *logfile;
129static char *difffilename;
130static const char *sockdir;
131static const char *temp_sockdir;
132static char sockself[MAXPGPATH];
133static char socklock[MAXPGPATH];
135static bool in_note = false;
136static bool in_diag = false;
137
139
141static bool postmaster_running = false;
142
143static int success_count = 0;
144static int fail_count = 0;
145
146static bool directory_exists(const char *dir);
147static void make_directory(const char *dir);
148
149static void test_status_print(bool ok, const char *testname, double runtime, bool parallel);
150static void test_status_ok(const char *testname, double runtime, bool parallel);
151static void test_status_failed(const char *testname, double runtime, bool parallel);
152static void bail_out(bool noatexit, const char *fmt,...) pg_attribute_printf(2, 3);
155
158static void psql_end_command(StringInfo buf, const char *database);
159
160/*
161 * Convenience macros for printing TAP output with a more shorthand syntax
162 * aimed at making the code more readable.
163 */
164#define plan(x) emit_tap_output(PLAN, "1..%i", (x))
165#define note(...) emit_tap_output(NOTE, __VA_ARGS__)
166#define note_detail(...) emit_tap_output(NOTE_DETAIL, __VA_ARGS__)
167#define diag(...) emit_tap_output(DIAG, __VA_ARGS__)
168#define diag_detail(...) emit_tap_output(DIAG_DETAIL, __VA_ARGS__)
169#define diag_end() emit_tap_output(DIAG_END, "\n");
170#define note_end() emit_tap_output(NOTE_END, "\n");
171#define bail_noatexit(...) bail_out(true, __VA_ARGS__)
172#define bail(...) bail_out(false, __VA_ARGS__)
173
174/*
175 * allow core files if possible.
176 */
177#if defined(HAVE_GETRLIMIT)
178static void
180{
181 struct rlimit lim;
182
184 if (lim.rlim_max == 0)
185 {
186 diag("could not set core size: disallowed by hard limit");
187 return;
188 }
189 else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
190 {
191 lim.rlim_cur = lim.rlim_max;
193 }
194}
195#endif
196
197
198/*
199 * Add an item at the end of a stringlist.
200 */
201void
203{
206
208 newentry->next = NULL;
209 if (*listhead == NULL)
211 else
212 {
213 for (oldentry = *listhead; oldentry->next; oldentry = oldentry->next)
214 /* skip */ ;
215 oldentry->next = newentry;
216 }
217}
218
219/*
220 * Free a stringlist.
221 */
222static void
224{
225 if (listhead == NULL || *listhead == NULL)
226 return;
227 if ((*listhead)->next != NULL)
228 free_stringlist(&((*listhead)->next));
229 free((*listhead)->str);
230 free(*listhead);
231 *listhead = NULL;
232}
233
234/*
235 * Split a delimited string into a stringlist
236 */
237static void
238split_to_stringlist(const char *s, const char *delim, _stringlist **listhead)
239{
240 char *token;
241 char *sc;
242 char *tofree;
243
244 tofree = sc = pg_strdup(s);
245
246 while ((token = strsep(&sc, delim)))
247 {
249 }
250 free(tofree);
251}
252
253/*
254 * Bailing out is for unrecoverable errors which prevents further testing to
255 * occur and after which the test run should be aborted. By passing noatexit
256 * as true the process will terminate with _exit(2) and skipping registered
257 * exit handlers, thus avoid any risk of bottomless recursion calls to exit.
258 */
259static void
260bail_out(bool noatexit, const char *fmt,...)
261{
262 va_list ap;
263
264 va_start(ap, fmt);
266 va_end(ap);
267
268 if (noatexit)
269 _exit(2);
270
271 exit(2);
272}
273
274/*
275 * Print the result of a test run and associated metadata like runtime. Care
276 * is taken to align testnames and runtimes vertically to ensure the output
277 * is human readable while still TAP compliant. Tests run in parallel are
278 * prefixed with a '+' and sequential tests with a '-'. This distinction was
279 * previously indicated by 'test' prefixing sequential tests while parallel
280 * tests were indented by four leading spaces. The meson TAP parser consumes
281 * leading space however, so a non-whitespace prefix of the same length is
282 * required for both.
283 */
284static void
285test_status_print(bool ok, const char *testname, double runtime, bool parallel)
286{
288
289 /*
290 * Testnumbers are padded to 5 characters to ensure that testnames align
291 * vertically (assuming at most 9999 tests). Testnames are prefixed with
292 * a leading character to indicate being run in parallel or not. A leading
293 * '+' indicates a parallel test, '-' indicates a single test.
294 */
295 emit_tap_output(TEST_STATUS, "%sok %-5i%*s %c %-*s %8.0f ms",
296 (ok ? "" : "not "),
298 /* If ok, indent with four spaces matching "not " */
299 (ok ? (int) strlen("not ") : 0), "",
300 /* Prefix a parallel test '+' and a single test with '-' */
301 (parallel ? '+' : '-'),
302 /* Testnames are padded to align runtimes */
304 runtime);
305}
306
307static void
308test_status_ok(const char *testname, double runtime, bool parallel)
309{
311
313}
314
315static void
316test_status_failed(const char *testname, double runtime, bool parallel)
317{
318 /*
319 * Save failed tests in a buffer such that we can print a summary at the
320 * end with diag() to ensure it's shown even under test harnesses.
321 */
322 if (!failed_tests)
324 else
326
328
329 fail_count++;
330
332}
333
334
335static void
337{
339
340 va_start(argp, fmt);
342 va_end(argp);
343}
344
345static void
347{
349 FILE *fp;
350 int save_errno;
351
352 /*
353 * The fprintf() calls used to output TAP-protocol elements might clobber
354 * errno, so save it here and restore it before vfprintf()-ing the user's
355 * format string, in case it contains %m placeholders.
356 */
358
359 /*
360 * Diagnostic output will be hidden by prove unless printed to stderr. The
361 * Bail message is also printed to stderr to aid debugging under a harness
362 * which might otherwise not emit such an important message.
363 */
364 if (type == DIAG || type == DIAG_DETAIL || type == DIAG_END || type == BAIL)
365 fp = stderr;
366 else
367 fp = stdout;
368
369 /*
370 * If we are ending a note_detail line we can avoid further processing and
371 * immediately return following a newline.
372 */
373 if (type == NOTE_END || type == DIAG_END)
374 {
375 if (type == NOTE_END)
376 in_note = false;
377 else
378 in_diag = false;
379 fprintf(fp, "\n");
380 if (logfile)
381 fprintf(logfile, "\n");
382 return;
383 }
384
385 /* Make a copy of the va args for printing to the logfile */
387
388 /*
389 * Non-protocol output such as diagnostics or notes must be prefixed by a
390 * '#' character. We print the Bail message like this too.
391 */
392 if ((type == NOTE || type == DIAG || type == BAIL)
393 || (type == NOTE_DETAIL && !in_note)
394 || (type == DIAG_DETAIL && !in_diag))
395 {
396 fprintf(fp, "# ");
397 if (logfile)
398 fprintf(logfile, "# ");
399 }
401 vfprintf(fp, fmt, argp);
402 if (logfile)
403 {
406 }
407
408 /*
409 * If we are entering into a note with more details to follow, register
410 * that the leading '#' has been printed such that subsequent details
411 * aren't prefixed as well.
412 */
413 if (type == NOTE_DETAIL)
414 in_note = true;
415 if (type == DIAG_DETAIL)
416 in_diag = true;
417
418 /*
419 * If this was a Bail message, the bail protocol message must go to stdout
420 * separately.
421 */
422 if (type == BAIL)
423 {
424 fprintf(stdout, "Bail out!");
425 if (logfile)
426 fprintf(logfile, "Bail out!");
427 }
428
430
431 if (type != NOTE_DETAIL && type != DIAG_DETAIL)
432 {
433 fprintf(fp, "\n");
434 if (logfile)
435 fprintf(logfile, "\n");
436 }
437 fflush(NULL);
438}
439
440/*
441 * shut down temp postmaster
442 */
443static void
445{
447 {
448 /* We use pg_ctl to issue the kill and wait for stop */
449 char buf[MAXPGPATH * 2];
450 int r;
451
452 snprintf(buf, sizeof(buf),
453 "\"%s%spg_ctl\" stop -D \"%s/data\" -s",
454 bindir ? bindir : "",
455 bindir ? "/" : "",
457 fflush(NULL);
458 r = system(buf);
459 if (r != 0)
460 {
461 /* Not using the normal bail() as we want _exit */
462 bail_noatexit(_("could not stop postmaster: exit code was %d"), r);
463 }
464
465 postmaster_running = false;
466 }
467}
468
469/*
470 * Remove the socket temporary directory. pg_regress never waits for a
471 * postmaster exit, so it is indeterminate whether the postmaster has yet to
472 * unlink the socket and lock file. Unlink them here so we can proceed to
473 * remove the directory. Ignore errors; leaking a temporary directory is
474 * unimportant. This can run from a signal handler. The code is not
475 * acceptable in a Windows signal handler (see initdb.c:trapsig()), but
476 * on Windows, pg_regress does not use Unix sockets by default.
477 */
478static void
486
487/*
488 * Signal handler that calls remove_temp() and reraises the signal.
489 */
490static void
498
499/*
500 * Create a temporary directory suitable for the server's Unix-domain socket.
501 * The directory will have mode 0700 or stricter, so no other OS user can open
502 * our socket to exploit our use of trust authentication. Most systems
503 * constrain the length of socket paths well below _POSIX_PATH_MAX, so we
504 * place the directory under /tmp rather than relative to the possibly-deep
505 * current working directory.
506 *
507 * Compared to using the compiled-in DEFAULT_PGSOCKET_DIR, this also permits
508 * testing to work in builds that relocate it to a directory not writable to
509 * the build/test user.
510 */
511static const char *
513{
514 char *template = psprintf("%s/pg_regress-XXXXXX",
515 getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp");
516
517 temp_sockdir = mkdtemp(template);
518 if (temp_sockdir == NULL)
519 bail("could not create directory \"%s\": %m", template);
520
521 /* Stage file names for remove_temp(). Unsafe in a signal handler. */
523 snprintf(socklock, sizeof(socklock), "%s.lock", sockself);
524
525 /* Remove the directory during clean exit. */
527
528 /*
529 * Remove the directory before dying to the usual signals. Omit SIGQUIT,
530 * preserving it as a quick, untidy exit.
531 */
534
535 /* the following are not valid on Windows */
536#ifndef WIN32
539#endif
540
541 return temp_sockdir;
542}
543
544/*
545 * Check whether string matches pattern
546 *
547 * In the original shell script, this function was implemented using expr(1),
548 * which provides basic regular expressions restricted to match starting at
549 * the string start (in conventional regex terms, there's an implicit "^"
550 * at the start of the pattern --- but no implicit "$" at the end).
551 *
552 * For now, we only support "." and ".*" as non-literal metacharacters,
553 * because that's all that anyone has found use for in resultmap. This
554 * code could be extended if more functionality is needed.
555 */
556static bool
557string_matches_pattern(const char *str, const char *pattern)
558{
559 while (*str && *pattern)
560 {
561 if (*pattern == '.' && pattern[1] == '*')
562 {
563 pattern += 2;
564 /* Trailing .* matches everything. */
565 if (*pattern == '\0')
566 return true;
567
568 /*
569 * Otherwise, scan for a text position at which we can match the
570 * rest of the pattern.
571 */
572 while (*str)
573 {
574 /*
575 * Optimization to prevent most recursion: don't recurse
576 * unless first pattern char might match this text char.
577 */
578 if (*str == *pattern || *pattern == '.')
579 {
580 if (string_matches_pattern(str, pattern))
581 return true;
582 }
583
584 str++;
585 }
586
587 /*
588 * End of text with no match.
589 */
590 return false;
591 }
592 else if (*pattern != '.' && *str != *pattern)
593 {
594 /*
595 * Not the single-character wildcard and no explicit match? Then
596 * time to quit...
597 */
598 return false;
599 }
600
601 str++;
602 pattern++;
603 }
604
605 if (*pattern == '\0')
606 return true; /* end of pattern, so declare match */
607
608 /* End of input string. Do we have matching pattern remaining? */
609 while (*pattern == '.' && pattern[1] == '*')
610 pattern += 2;
611 if (*pattern == '\0')
612 return true; /* end of pattern, so declare match */
613
614 return false;
615}
616
617/*
618 * Scan resultmap file to find which platform-specific expected files to use.
619 *
620 * The format of each line of the file is
621 * testname/hostplatformpattern=substitutefile
622 * where the hostplatformpattern is evaluated per the rules of expr(1),
623 * namely, it is a standard regular expression with an implicit ^ at the start.
624 * (We currently support only a very limited subset of regular expressions,
625 * see string_matches_pattern() above.) What hostplatformpattern will be
626 * matched against is the config.guess output. (In the shell-script version,
627 * we also provided an indication of whether gcc or another compiler was in
628 * use, but that facility isn't used anymore.)
629 */
630static void
632{
633 char buf[MAXPGPATH];
634 FILE *f;
635
636 /* scan the file ... */
637 snprintf(buf, sizeof(buf), "%s/resultmap", inputdir);
638 f = fopen(buf, "r");
639 if (!f)
640 {
641 /* OK if it doesn't exist, else complain */
642 if (errno == ENOENT)
643 return;
644 bail("could not open file \"%s\" for reading: %m", buf);
645 }
646
647 while (fgets(buf, sizeof(buf), f))
648 {
649 char *platform;
650 char *file_type;
651 char *expected;
652 int i;
653
654 /* strip trailing whitespace, especially the newline */
655 i = strlen(buf);
656 while (i > 0 && isspace((unsigned char) buf[i - 1]))
657 buf[--i] = '\0';
658
659 /* parse out the line fields */
660 file_type = strchr(buf, ':');
661 if (!file_type)
662 {
663 bail("incorrectly formatted resultmap entry: %s", buf);
664 }
665 *file_type++ = '\0';
666
667 platform = strchr(file_type, ':');
668 if (!platform)
669 {
670 bail("incorrectly formatted resultmap entry: %s", buf);
671 }
672 *platform++ = '\0';
673 expected = strchr(platform, '=');
674 if (!expected)
675 {
676 bail("incorrectly formatted resultmap entry: %s", buf);
677 }
678 *expected++ = '\0';
679
680 /*
681 * if it's for current platform, save it in resultmap list. Note: by
682 * adding at the front of the list, we ensure that in ambiguous cases,
683 * the last match in the resultmap file is used. This mimics the
684 * behavior of the old shell script.
685 */
687 {
689
690 entry->test = pg_strdup(buf);
691 entry->type = pg_strdup(file_type);
692 entry->resultfile = pg_strdup(expected);
693 entry->next = resultmap;
694 resultmap = entry;
695 }
696 }
697 fclose(f);
698}
699
700/*
701 * Check in resultmap if we should be looking at a different file
702 */
703static
704const char *
705get_expectfile(const char *testname, const char *file)
706{
707 const char *file_type;
708 _resultmap *rm;
709
710 /*
711 * Determine the file type from the file name. This is just what is
712 * following the last dot in the file name.
713 */
714 if (!file || !(file_type = strrchr(file, '.')))
715 return NULL;
716
717 file_type++;
718
719 for (rm = resultmap; rm != NULL; rm = rm->next)
720 {
721 if (strcmp(testname, rm->test) == 0 && strcmp(file_type, rm->type) == 0)
722 {
723 return rm->resultfile;
724 }
725 }
726
727 return NULL;
728}
729
730/*
731 * Prepare environment variables for running regression tests
732 */
733static void
735{
736 /*
737 * Set default application_name. (The test_start_function may choose to
738 * override this, but if it doesn't, we have something useful in place.)
739 */
740 setenv("PGAPPNAME", "pg_regress", 1);
741
742 /*
743 * Set variables that the test scripts may need to refer to.
744 */
745 setenv("PG_ABS_SRCDIR", inputdir, 1);
746 setenv("PG_ABS_BUILDDIR", outputdir, 1);
747 setenv("PG_LIBDIR", dlpath, 1);
748 setenv("PG_DLSUFFIX", DLSUFFIX, 1);
749
750 if (nolocale)
751 {
752 /*
753 * Clear out any non-C locale settings
754 */
755 unsetenv("LC_COLLATE");
756 unsetenv("LC_CTYPE");
757 unsetenv("LC_MONETARY");
758 unsetenv("LC_NUMERIC");
759 unsetenv("LC_TIME");
760 unsetenv("LANG");
761
762 /*
763 * Most platforms have adopted the POSIX locale as their
764 * implementation-defined default locale. Exceptions include native
765 * Windows, macOS with --enable-nls, and Cygwin with --enable-nls.
766 * (Use of --enable-nls matters because libintl replaces setlocale().)
767 * Also, PostgreSQL does not support macOS with locale environment
768 * variables unset; see PostmasterMain().
769 */
770#if defined(WIN32) || defined(__CYGWIN__) || defined(__darwin__)
771 setenv("LANG", "C", 1);
772#endif
773 }
774
775 /*
776 * Set translation-related settings to English; otherwise psql will
777 * produce translated messages and produce diffs. (XXX If we ever support
778 * translation of pg_regress, this needs to be moved elsewhere, where psql
779 * is actually called.)
780 */
781 unsetenv("LANGUAGE");
782 unsetenv("LC_ALL");
783 setenv("LC_MESSAGES", "C", 1);
784
785 /*
786 * Set encoding as requested
787 */
788 if (encoding)
789 setenv("PGCLIENTENCODING", encoding, 1);
790 else
791 unsetenv("PGCLIENTENCODING");
792
793 /*
794 * Set timezone and datestyle for datetime-related tests
795 */
796 setenv("PGTZ", "America/Los_Angeles", 1);
797 setenv("PGDATESTYLE", "Postgres, MDY", 1);
798
799 /*
800 * Likewise set intervalstyle to ensure consistent results. This is a bit
801 * more painful because we must use PGOPTIONS, and we want to preserve the
802 * user's ability to set other variables through that.
803 */
804 {
805 const char *my_pgoptions = "-c intervalstyle=postgres_verbose";
806 const char *old_pgoptions = getenv("PGOPTIONS");
807 char *new_pgoptions;
808
809 if (!old_pgoptions)
810 old_pgoptions = "";
811 new_pgoptions = psprintf("%s %s",
813 setenv("PGOPTIONS", new_pgoptions, 1);
815 }
816
817 if (temp_instance)
818 {
819 /*
820 * Clear out any environment vars that might cause psql to connect to
821 * the wrong postmaster, or otherwise behave in nondefault ways. (Note
822 * we also use psql's -X switch consistently, so that ~/.psqlrc files
823 * won't mess things up.) Also, set PGPORT to the temp port, and set
824 * PGHOST depending on whether we are using TCP or Unix sockets.
825 *
826 * This list should be kept in sync with PostgreSQL/Test/Utils.pm.
827 */
828 unsetenv("PGCHANNELBINDING");
829 /* PGCLIENTENCODING, see above */
830 unsetenv("PGCONNECT_TIMEOUT");
831 unsetenv("PGDATA");
832 unsetenv("PGDATABASE");
833 unsetenv("PGGSSDELEGATION");
834 unsetenv("PGGSSENCMODE");
835 unsetenv("PGGSSLIB");
836 /* PGHOSTADDR, see below */
837 unsetenv("PGKRBSRVNAME");
838 unsetenv("PGPASSFILE");
839 unsetenv("PGPASSWORD");
840 unsetenv("PGREQUIREPEER");
841 unsetenv("PGREQUIRESSL");
842 unsetenv("PGSERVICE");
843 unsetenv("PGSERVICEFILE");
844 unsetenv("PGSSLCERT");
845 unsetenv("PGSSLCRL");
846 unsetenv("PGSSLCRLDIR");
847 unsetenv("PGSSLKEY");
848 unsetenv("PGSSLMAXPROTOCOLVERSION");
849 unsetenv("PGSSLMINPROTOCOLVERSION");
850 unsetenv("PGSSLMODE");
851 unsetenv("PGSSLROOTCERT");
852 unsetenv("PGSSLSNI");
853 unsetenv("PGTARGETSESSIONATTRS");
854 unsetenv("PGUSER");
855 /* PGPORT, see below */
856 /* PGHOST, see below */
857
858 if (hostname != NULL)
859 setenv("PGHOST", hostname, 1);
860 else
861 {
862 sockdir = getenv("PG_REGRESS_SOCK_DIR");
863 if (!sockdir)
865 setenv("PGHOST", sockdir, 1);
866 }
867 unsetenv("PGHOSTADDR");
868 if (port != -1)
869 {
870 char s[16];
871
872 snprintf(s, sizeof(s), "%d", port);
873 setenv("PGPORT", s, 1);
874 }
875 }
876 else
877 {
878 const char *pghost;
879 const char *pgport;
880
881 /*
882 * When testing an existing install, we honor existing environment
883 * variables, except if they're overridden by command line options.
884 */
885 if (hostname != NULL)
886 {
887 setenv("PGHOST", hostname, 1);
888 unsetenv("PGHOSTADDR");
889 }
890 if (port != -1)
891 {
892 char s[16];
893
894 snprintf(s, sizeof(s), "%d", port);
895 setenv("PGPORT", s, 1);
896 }
897 if (user != NULL)
898 setenv("PGUSER", user, 1);
899
900 /*
901 * However, we *don't* honor PGDATABASE, since we certainly don't wish
902 * to connect to whatever database the user might like as default.
903 * (Most tests override PGDATABASE anyway, but there are some ECPG
904 * test cases that don't.)
905 */
906 unsetenv("PGDATABASE");
907
908 /*
909 * Report what we're connecting to
910 */
911 pghost = getenv("PGHOST");
912 pgport = getenv("PGPORT");
913 if (!pghost)
914 {
915 /* Keep this bit in sync with libpq's default host location: */
917 /* do nothing, we'll print "Unix socket" below */ ;
918 else
919 pghost = "localhost"; /* DefaultHost in fe-connect.c */
920 }
921
922 if (pghost && pgport)
923 note("using postmaster on %s, port %s", pghost, pgport);
924 if (pghost && !pgport)
925 note("using postmaster on %s, default port", pghost);
926 if (!pghost && pgport)
927 note("using postmaster on Unix socket, port %s", pgport);
928 if (!pghost && !pgport)
929 note("using postmaster on Unix socket, default port");
930 }
931
933}
934
935#ifdef ENABLE_SSPI
936
937/* support for config_sspi_auth() */
938static const char *
939fmtHba(const char *raw)
940{
941 static char *ret;
942 const char *rp;
943 char *wp;
944
945 wp = ret = pg_realloc(ret, 3 + strlen(raw) * 2);
946
947 *wp++ = '"';
948 for (rp = raw; *rp; rp++)
949 {
950 if (*rp == '"')
951 *wp++ = '"';
952 *wp++ = *rp;
953 }
954 *wp++ = '"';
955 *wp++ = '\0';
956
957 return ret;
958}
959
960/*
961 * Get account and domain/realm names for the current user. This is based on
962 * pg_SSPI_recvauth(). The returned strings use static storage.
963 */
964static void
965current_windows_user(const char **acct, const char **dom)
966{
967 static char accountname[MAXPGPATH];
968 static char domainname[MAXPGPATH];
973 DWORD domainnamesize = sizeof(domainname);
975
977 {
978 bail("could not open process token: error code %lu", GetLastError());
979 }
980
982 {
983 bail("could not get token information buffer size: error code %lu",
984 GetLastError());
985 }
988 {
989 bail("could not get token information: error code %lu",
990 GetLastError());
991 }
992
994 domainname, &domainnamesize, &accountnameuse))
995 {
996 bail("could not look up account SID: error code %lu",
997 GetLastError());
998 }
999
1000 free(tokenuser);
1001
1002 *acct = accountname;
1003 *dom = domainname;
1004}
1005
1006/*
1007 * Rewrite pg_hba.conf and pg_ident.conf to use SSPI authentication. Permit
1008 * the current OS user to authenticate as the bootstrap superuser and as any
1009 * user named in a --create-role option.
1010 *
1011 * In --config-auth mode, the --user switch can be used to specify the
1012 * bootstrap superuser's name, otherwise we assume it is the default.
1013 */
1014static void
1015config_sspi_auth(const char *pgdata, const char *superuser_name)
1016{
1017 const char *accountname,
1018 *domainname;
1019 char *errstr;
1020 bool have_ipv6;
1021 char fname[MAXPGPATH];
1022 int res;
1023 FILE *hba,
1024 *ident;
1025 _stringlist *sl;
1026
1027 /* Find out the name of the current OS user */
1028 current_windows_user(&accountname, &domainname);
1029
1030 /* Determine the bootstrap superuser's name */
1031 if (superuser_name == NULL)
1032 {
1033 /*
1034 * Compute the default superuser name the same way initdb does.
1035 *
1036 * It's possible that this result always matches "accountname", the
1037 * value SSPI authentication discovers. But the underlying system
1038 * functions do not clearly guarantee that.
1039 */
1041 if (superuser_name == NULL)
1042 {
1043 bail("%s", errstr);
1044 }
1045 }
1046
1047 /*
1048 * Like initdb.c:setup_config(), determine whether the platform recognizes
1049 * ::1 (IPv6 loopback) as a numeric host address string.
1050 */
1051 {
1052 struct addrinfo *gai_result;
1053 struct addrinfo hints;
1055
1056 hints.ai_flags = AI_NUMERICHOST;
1057 hints.ai_family = AF_UNSPEC;
1058 hints.ai_socktype = 0;
1059 hints.ai_protocol = 0;
1060 hints.ai_addrlen = 0;
1061 hints.ai_canonname = NULL;
1062 hints.ai_addr = NULL;
1063 hints.ai_next = NULL;
1064
1065 have_ipv6 = (WSAStartup(MAKEWORD(2, 2), &wsaData) == 0 &&
1066 getaddrinfo("::1", NULL, &hints, &gai_result) == 0);
1067 }
1068
1069 /* Check a Write outcome and report any error. */
1070#define CW(cond) \
1071 do { \
1072 if (!(cond)) \
1073 bail("could not write to file \"%s\": %m", fname); \
1074 } while (0)
1075
1076 res = snprintf(fname, sizeof(fname), "%s/pg_hba.conf", pgdata);
1077 if (res < 0 || res >= sizeof(fname))
1078 {
1079 /*
1080 * Truncating this name is a fatal error, because we must not fail to
1081 * overwrite an original trust-authentication pg_hba.conf.
1082 */
1083 bail("directory name too long");
1084 }
1085 hba = fopen(fname, "w");
1086 if (hba == NULL)
1087 {
1088 bail("could not open file \"%s\" for writing: %m", fname);
1089 }
1090 CW(fputs("# Configuration written by config_sspi_auth()\n", hba) >= 0);
1091 CW(fputs("host all all 127.0.0.1/32 sspi include_realm=1 map=regress\n",
1092 hba) >= 0);
1093 if (have_ipv6)
1094 CW(fputs("host all all ::1/128 sspi include_realm=1 map=regress\n",
1095 hba) >= 0);
1096 CW(fclose(hba) == 0);
1097
1098 snprintf(fname, sizeof(fname), "%s/pg_ident.conf", pgdata);
1099 ident = fopen(fname, "w");
1100 if (ident == NULL)
1101 {
1102 bail("could not open file \"%s\" for writing: %m", fname);
1103 }
1104 CW(fputs("# Configuration written by config_sspi_auth()\n", ident) >= 0);
1105
1106 /*
1107 * Double-quote for the benefit of account names containing whitespace or
1108 * '#'. Windows forbids the double-quote character itself, so don't
1109 * bother escaping embedded double-quote characters.
1110 */
1111 CW(fprintf(ident, "regress \"%s@%s\" %s\n",
1112 accountname, domainname, fmtHba(superuser_name)) >= 0);
1113 for (sl = extraroles; sl; sl = sl->next)
1114 CW(fprintf(ident, "regress \"%s@%s\" %s\n",
1115 accountname, domainname, fmtHba(sl->str)) >= 0);
1116 CW(fclose(ident) == 0);
1117}
1118
1119#endif /* ENABLE_SSPI */
1120
1121/*
1122 * psql_start_command, psql_add_command, psql_end_command
1123 *
1124 * Issue one or more commands within one psql call.
1125 * Set up with psql_start_command, then add commands one at a time
1126 * with psql_add_command, and finally execute with psql_end_command.
1127 *
1128 * Since we use system(), this doesn't return until the operation finishes
1129 */
1130static StringInfo
1132{
1134
1136 "\"%s%spsql\" -X -q",
1137 bindir ? bindir : "",
1138 bindir ? "/" : "");
1139 return buf;
1140}
1141
1142static void
1143psql_add_command(StringInfo buf, const char *query,...)
1144{
1146 const char *cmdptr;
1147
1148 /* Add each command as a -c argument in the psql call */
1149 appendStringInfoString(buf, " -c \"");
1150
1151 /* Generate the query with insertion of sprintf arguments */
1153 for (;;)
1154 {
1155 va_list args;
1156 int needed;
1157
1158 va_start(args, query);
1159 needed = appendStringInfoVA(&cmdbuf, query, args);
1160 va_end(args);
1161 if (needed == 0)
1162 break; /* success */
1164 }
1165
1166 /* Now escape any shell double-quote metacharacters */
1167 for (cmdptr = cmdbuf.data; *cmdptr; cmdptr++)
1168 {
1169 if (strchr("\\\"$`", *cmdptr))
1172 }
1173
1175
1176 pfree(cmdbuf.data);
1177}
1178
1179static void
1180psql_end_command(StringInfo buf, const char *database)
1181{
1182 /* Add the database name --- assume it needs no extra escaping */
1184 " \"%s\"",
1185 database);
1186
1187 /* And now we can execute the shell command */
1188 fflush(NULL);
1189 if (system(buf->data) != 0)
1190 {
1191 /* psql probably already reported the error */
1192 bail("command failed: %s", buf->data);
1193 }
1194
1195 /* Clean up */
1197}
1198
1199/*
1200 * Shorthand macro for the common case of a single command
1201 */
1202#define psql_command(database, ...) \
1203 do { \
1204 StringInfo cmdbuf = psql_start_command(); \
1205 psql_add_command(cmdbuf, __VA_ARGS__); \
1206 psql_end_command(cmdbuf, database); \
1207 } while (0)
1208
1209/*
1210 * Spawn a process to execute the given shell command; don't wait for it
1211 *
1212 * Returns the process ID (or HANDLE) so we can wait for it later
1213 */
1216{
1217#ifndef WIN32
1218 pid_t pid;
1219
1220 /*
1221 * Must flush I/O buffers before fork.
1222 */
1223 fflush(NULL);
1224
1225#ifdef EXEC_BACKEND
1227#endif
1228
1229 pid = fork();
1230 if (pid == -1)
1231 {
1232 bail("could not fork: %m");
1233 }
1234 if (pid == 0)
1235 {
1236 /*
1237 * In child
1238 *
1239 * Instead of using system(), exec the shell directly, and tell it to
1240 * "exec" the command too. This saves two useless processes per
1241 * parallel test case.
1242 */
1243 char *cmdline2;
1244
1245 cmdline2 = psprintf("exec %s", cmdline);
1246 execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
1247 /* Not using the normal bail() here as we want _exit */
1248 bail_noatexit("could not exec \"%s\": %m", shellprog);
1249 }
1250 /* in parent */
1251 return pid;
1252#else
1254 char *cmdline2;
1255 const char *comspec;
1256
1257 /* Find CMD.EXE location using COMSPEC, if it's set */
1258 comspec = getenv("COMSPEC");
1259 if (comspec == NULL)
1260 comspec = "CMD";
1261
1262 memset(&pi, 0, sizeof(pi));
1263 cmdline2 = psprintf("\"%s\" /c \"%s\"", comspec, cmdline);
1264
1266 exit(2);
1267
1268 CloseHandle(pi.hThread);
1269 return pi.hProcess;
1270#endif
1271}
1272
1273/*
1274 * Count bytes in file
1275 */
1276static long
1277file_size(const char *file)
1278{
1279 long r;
1280 FILE *f = fopen(file, "r");
1281
1282 if (!f)
1283 {
1284 diag("could not open file \"%s\" for reading: %m", file);
1285 return -1;
1286 }
1287 fseek(f, 0, SEEK_END);
1288 r = ftell(f);
1289 fclose(f);
1290 return r;
1291}
1292
1293/*
1294 * Count lines in file
1295 */
1296static int
1297file_line_count(const char *file)
1298{
1299 int c;
1300 int l = 0;
1301 FILE *f = fopen(file, "r");
1302
1303 if (!f)
1304 {
1305 diag("could not open file \"%s\" for reading: %m", file);
1306 return -1;
1307 }
1308 while ((c = fgetc(f)) != EOF)
1309 {
1310 if (c == '\n')
1311 l++;
1312 }
1313 fclose(f);
1314 return l;
1315}
1316
1317bool
1318file_exists(const char *file)
1319{
1320 FILE *f = fopen(file, "r");
1321
1322 if (!f)
1323 return false;
1324 fclose(f);
1325 return true;
1326}
1327
1328static bool
1329directory_exists(const char *dir)
1330{
1331 struct stat st;
1332
1333 if (stat(dir, &st) != 0)
1334 return false;
1335 if (S_ISDIR(st.st_mode))
1336 return true;
1337 return false;
1338}
1339
1340/* Create a directory */
1341static void
1342make_directory(const char *dir)
1343{
1344 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) < 0)
1345 bail("could not create directory \"%s\": %m", dir);
1346}
1347
1348/*
1349 * In: filename.ext, Return: filename_i.ext, where 0 <= i <= 9
1350 */
1351static char *
1353{
1354 char *last_dot;
1355 int ssize = strlen(expectfile) + 2 + 1;
1356 char *tmp;
1357 char *s;
1358
1359 if (!(tmp = (char *) malloc(ssize)))
1360 return NULL;
1361
1362 if (!(s = (char *) malloc(ssize)))
1363 {
1364 free(tmp);
1365 return NULL;
1366 }
1367
1368 strcpy(tmp, expectfile);
1369 last_dot = strrchr(tmp, '.');
1370 if (!last_dot)
1371 {
1372 free(tmp);
1373 free(s);
1374 return NULL;
1375 }
1376 *last_dot = '\0';
1377 snprintf(s, ssize, "%s_%d.%s", tmp, i, last_dot + 1);
1378 free(tmp);
1379 return s;
1380}
1381
1382/*
1383 * Run a "diff" command and also check that it didn't crash
1384 */
1385static int
1386run_diff(const char *cmd, const char *filename)
1387{
1388 int r;
1389
1390 fflush(NULL);
1391 r = system(cmd);
1392 if (!WIFEXITED(r) || WEXITSTATUS(r) > 1)
1393 {
1394 bail("diff command failed with status %d: %s", r, cmd);
1395 }
1396#ifdef WIN32
1397
1398 /*
1399 * On WIN32, if the 'diff' command cannot be found, system() returns 1,
1400 * but produces nothing to stdout, so we check for that here.
1401 */
1402 if (WEXITSTATUS(r) == 1 && file_size(filename) <= 0)
1403 {
1404 bail("diff command not found: %s", cmd);
1405 }
1406#endif
1407
1408 return WEXITSTATUS(r);
1409}
1410
1411/*
1412 * Check the actual result file for the given test against expected results
1413 *
1414 * Returns true if different (failure), false if correct match found.
1415 * In the true case, the diff is appended to the diffs file.
1416 */
1417static bool
1418results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)
1419{
1420 char expectfile[MAXPGPATH];
1421 char diff[MAXPGPATH];
1422 char cmd[MAXPGPATH * 3];
1424 FILE *difffile;
1425 int best_line_count;
1426 int i;
1427 int l;
1428 long startpos;
1429 const char *platform_expectfile;
1430
1431 /*
1432 * We can pass either the resultsfile or the expectfile, they should have
1433 * the same type (filename.type) anyway.
1434 */
1436
1439 {
1440 /*
1441 * Replace everything after the last slash in expectfile with what the
1442 * platform_expectfile contains.
1443 */
1444 char *p = strrchr(expectfile, '/');
1445
1446 if (p)
1448 }
1449
1450 /* Name to use for temporary diff file */
1451 snprintf(diff, sizeof(diff), "%s.diff", resultsfile);
1452
1453 /* OK, run the diff */
1454 snprintf(cmd, sizeof(cmd),
1455 "diff %s \"%s\" \"%s\" > \"%s\"",
1457
1458 /* Is the diff file empty? */
1459 if (run_diff(cmd, diff) == 0)
1460 {
1461 unlink(diff);
1462 return false;
1463 }
1464
1465 /* There may be secondary comparison files that match better */
1468
1469 for (i = 0; i <= 9; i++)
1470 {
1471 char *alt_expectfile;
1472
1474 if (!alt_expectfile)
1475 bail("Unable to check secondary comparison files: %m");
1476
1478 {
1480 continue;
1481 }
1482
1483 snprintf(cmd, sizeof(cmd),
1484 "diff %s \"%s\" \"%s\" > \"%s\"",
1486
1487 if (run_diff(cmd, diff) == 0)
1488 {
1489 unlink(diff);
1491 return false;
1492 }
1493
1494 l = file_line_count(diff);
1495 if (l < best_line_count)
1496 {
1497 /* This diff was a better match than the last one */
1498 best_line_count = l;
1500 }
1502 }
1503
1504 /*
1505 * fall back on the canonical results file if we haven't tried it yet and
1506 * haven't found a complete match yet.
1507 */
1508
1510 {
1511 snprintf(cmd, sizeof(cmd),
1512 "diff %s \"%s\" \"%s\" > \"%s\"",
1514
1515 if (run_diff(cmd, diff) == 0)
1516 {
1517 /* No diff = no changes = good */
1518 unlink(diff);
1519 return false;
1520 }
1521
1522 l = file_line_count(diff);
1523 if (l < best_line_count)
1524 {
1525 /* This diff was a better match than the last one */
1526 best_line_count = l;
1528 }
1529 }
1530
1531 /*
1532 * Use the best comparison file to generate the "pretty" diff, which we
1533 * append to the diffs summary file.
1534 */
1535
1536 difffile = fopen(difffilename, "a");
1537 if (difffile)
1538 {
1540
1541 /* Write diff header */
1543 "diff %s %s %s\n",
1546
1547 /* Run diff */
1548 snprintf(cmd, sizeof(cmd),
1549 "diff %s \"%s\" \"%s\" >> \"%s\"",
1551 run_diff(cmd, difffilename);
1552
1553 /*
1554 * Reopen the file for reading to emit the diff as TAP diagnostics. We
1555 * can't keep the file open while diff appends to it, because on
1556 * Windows the file lock prevents diff from writing.
1557 */
1558 difffile = fopen(difffilename, "r");
1559 }
1560
1561 if (difffile)
1562 {
1563 /*
1564 * In case of a crash the diff can be huge and all of the subsequent
1565 * tests will fail with essentially useless diffs too. So to avoid
1566 * flooding the output, while still providing useful info in most
1567 * cases we output only the first 80 lines of the *combined* diff. The
1568 * number 80 is chosen so that we output less than 100 lines of
1569 * diagnostics per pg_regress run. Otherwise if meson is run with the
1570 * --quiet flag only the last 100 lines are shown and usually the most
1571 * useful information is actually in the first few lines.
1572 */
1573 static int nlines = 0;
1574 const int max_diff_lines = 80;
1575 char line[1024];
1576
1578 while (nlines < max_diff_lines &&
1579 fgets(line, sizeof(line), difffile))
1580 {
1581 size_t len = strlen(line);
1582 bool newline_found = (len > 0 && line[len - 1] == '\n');
1583
1584 if (newline_found)
1585 line[len - 1] = '\0';
1586
1587 diag_detail("%s", line);
1588 if (newline_found)
1589 {
1590 diag_end();
1591 nlines++;
1592 }
1593 }
1594
1595 if (in_diag)
1596 {
1597 /*
1598 * If there was no final newline for some reason, we should still
1599 * end the diagnostic.
1600 */
1601 diag_end();
1602 nlines++;
1603 }
1604
1605 if (nlines >= max_diff_lines)
1606 diag("(diff output truncated and silencing output for further failing tests...)");
1607
1609 }
1610
1611 unlink(diff);
1612 return true;
1613}
1614
1615/*
1616 * Wait for specified subprocesses to finish, and return their exit
1617 * statuses into statuses[] and stop times into stoptimes[]
1618 *
1619 * If names isn't NULL, print each subprocess's name as it finishes
1620 *
1621 * Note: it's OK to scribble on the pids array, but not on the names array
1622 */
1623static void
1625 char **names, int num_tests)
1626{
1627 int tests_left;
1628 int i;
1629
1630#ifdef WIN32
1632
1634#endif
1635
1637 while (tests_left > 0)
1638 {
1639 PID_TYPE p;
1640
1641#ifndef WIN32
1642 int exit_status;
1643
1644 p = wait(&exit_status);
1645
1646 if (p == INVALID_PID)
1647 bail("failed to wait for subprocesses: %m");
1648#else
1650 int r;
1651
1654 {
1655 bail("failed to wait for subprocesses: error code %lu",
1656 GetLastError());
1657 }
1658 p = active_pids[r - WAIT_OBJECT_0];
1659 /* compact the active_pids array */
1661#endif /* WIN32 */
1662
1663 for (i = 0; i < num_tests; i++)
1664 {
1665 if (p == pids[i])
1666 {
1667#ifdef WIN32
1669 CloseHandle(pids[i]);
1670#endif
1671 pids[i] = INVALID_PID;
1674 if (names)
1675 note_detail(" %s", names[i]);
1676 tests_left--;
1677 break;
1678 }
1679 }
1680 }
1681
1682#ifdef WIN32
1684#endif
1685}
1686
1687/*
1688 * report nonzero exit code from a test process
1689 */
1690static void
1692{
1693 if (WIFEXITED(exitstatus))
1694 diag("(test process exited with exit code %d)",
1696 else if (WIFSIGNALED(exitstatus))
1697 {
1698#if defined(WIN32)
1699 diag("(test process was terminated by exception 0x%X)",
1701#else
1702 diag("(test process was terminated by signal %d: %s)",
1704#endif
1705 }
1706 else
1707 diag("(test process exited with unrecognized status %d)", exitstatus);
1708}
1709
1710/*
1711 * Run all the tests specified in one schedule file
1712 */
1713static void
1716{
1717#define MAX_PARALLEL_TESTS 100
1726 char scbuf[1024];
1727 FILE *scf;
1728 int line_num = 0;
1729
1730 memset(tests, 0, sizeof(tests));
1731 memset(resultfiles, 0, sizeof(resultfiles));
1732 memset(expectfiles, 0, sizeof(expectfiles));
1733 memset(tags, 0, sizeof(tags));
1734
1735 scf = fopen(schedule, "r");
1736 if (!scf)
1737 bail("could not open file \"%s\" for reading: %m", schedule);
1738
1739 while (fgets(scbuf, sizeof(scbuf), scf))
1740 {
1741 char *test = NULL;
1742 char *c;
1743 int num_tests;
1744 bool inword;
1745 int i;
1746
1747 line_num++;
1748
1749 /* strip trailing whitespace, especially the newline */
1750 i = strlen(scbuf);
1751 while (i > 0 && isspace((unsigned char) scbuf[i - 1]))
1752 scbuf[--i] = '\0';
1753
1754 if (scbuf[0] == '\0' || scbuf[0] == '#')
1755 continue;
1756 if (strncmp(scbuf, "test: ", 6) == 0)
1757 test = scbuf + 6;
1758 else
1759 {
1760 bail("syntax error in schedule file \"%s\" line %d: %s",
1761 schedule, line_num, scbuf);
1762 }
1763
1764 num_tests = 0;
1765 inword = false;
1766 for (c = test;; c++)
1767 {
1768 if (*c == '\0' || isspace((unsigned char) *c))
1769 {
1770 if (inword)
1771 {
1772 /* Reached end of a test name */
1773 char sav;
1774
1776 {
1777 bail("too many parallel tests (more than %d) in schedule file \"%s\" line %d: %s",
1778 MAX_PARALLEL_TESTS, schedule, line_num, scbuf);
1779 }
1780 sav = *c;
1781 *c = '\0';
1783 num_tests++;
1784 *c = sav;
1785 inword = false;
1786 }
1787 if (*c == '\0')
1788 break; /* loop exit is here */
1789 }
1790 else if (!inword)
1791 {
1792 /* Start of a test name */
1793 test = c;
1794 inword = true;
1795 }
1796 }
1797
1798 if (num_tests == 0)
1799 {
1800 bail("syntax error in schedule file \"%s\" line %d: %s",
1801 schedule, line_num, scbuf);
1802 }
1803
1804 if (num_tests == 1)
1805 {
1806 pids[0] = (startfunc) (tests[0], &resultfiles[0], &expectfiles[0], &tags[0]);
1809 /* status line is finished below */
1810 }
1812 {
1813 bail("too many parallel tests (more than %d) in schedule file \"%s\" line %d: %s",
1814 max_concurrent_tests, schedule, line_num, scbuf);
1815 }
1816 else if (max_connections > 0 && max_connections < num_tests)
1817 {
1818 int oldest = 0;
1819
1820 note_detail("parallel group (%d tests, in groups of %d): ",
1822 for (i = 0; i < num_tests; i++)
1823 {
1824 if (i - oldest >= max_connections)
1825 {
1827 stoptimes + oldest,
1828 tests + oldest, i - oldest);
1829 oldest = i;
1830 }
1831 pids[i] = (startfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1833 }
1835 stoptimes + oldest,
1836 tests + oldest, i - oldest);
1837 note_end();
1838 }
1839 else
1840 {
1841 note_detail("parallel group (%d tests): ", num_tests);
1842 for (i = 0; i < num_tests; i++)
1843 {
1844 pids[i] = (startfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1846 }
1848 note_end();
1849 }
1850
1851 /* Check results for all tests */
1852 for (i = 0; i < num_tests; i++)
1853 {
1854 _stringlist *rl,
1855 *el,
1856 *tl;
1857 bool differ = false;
1858
1860
1861 /*
1862 * Advance over all three lists simultaneously.
1863 *
1864 * Compare resultfiles[j] with expectfiles[j] always. Tags are
1865 * optional but if there are tags, the tag list has the same
1866 * length as the other two lists.
1867 */
1868 for (rl = resultfiles[i], el = expectfiles[i], tl = tags[i];
1869 rl != NULL; /* rl and el have the same length */
1870 rl = rl->next, el = el->next,
1871 tl = tl ? tl->next : NULL)
1872 {
1873 bool newdiff;
1874
1875 if (postfunc)
1876 (*postfunc) (rl->str);
1877 newdiff = results_differ(tests[i], rl->str, el->str);
1878 if (newdiff && tl)
1879 {
1880 diag("tag: %s", tl->str);
1881 }
1882 differ |= newdiff;
1883 }
1884
1885 if (statuses[i] != 0)
1886 {
1889 }
1890 else
1891 {
1892 if (differ)
1893 {
1895 }
1896 else
1897 {
1899 }
1900 }
1901 }
1902
1903 for (i = 0; i < num_tests; i++)
1904 {
1905 pg_free(tests[i]);
1906 tests[i] = NULL;
1910 }
1911 }
1912
1913 fclose(scf);
1914}
1915
1916/*
1917 * Run a single test
1918 */
1919static void
1922{
1923 PID_TYPE pid;
1924 instr_time starttime;
1925 instr_time stoptime;
1926 int exit_status;
1930 _stringlist *rl,
1931 *el,
1932 *tl;
1933 bool differ = false;
1934
1935 pid = (startfunc) (test, &resultfiles, &expectfiles, &tags);
1936 INSTR_TIME_SET_CURRENT(starttime);
1937 wait_for_tests(&pid, &exit_status, &stoptime, NULL, 1);
1938
1939 /*
1940 * Advance over all three lists simultaneously.
1941 *
1942 * Compare resultfiles[j] with expectfiles[j] always. Tags are optional
1943 * but if there are tags, the tag list has the same length as the other
1944 * two lists.
1945 */
1946 for (rl = resultfiles, el = expectfiles, tl = tags;
1947 rl != NULL; /* rl and el have the same length */
1948 rl = rl->next, el = el->next,
1949 tl = tl ? tl->next : NULL)
1950 {
1951 bool newdiff;
1952
1953 if (postfunc)
1954 (*postfunc) (rl->str);
1955 newdiff = results_differ(test, rl->str, el->str);
1956 if (newdiff && tl)
1957 {
1958 diag("tag: %s", tl->str);
1959 }
1960 differ |= newdiff;
1961 }
1962
1963 INSTR_TIME_SUBTRACT(stoptime, starttime);
1964
1965 if (exit_status != 0)
1966 {
1969 }
1970 else
1971 {
1972 if (differ)
1973 {
1975 }
1976 else
1977 {
1978 test_status_ok(test, INSTR_TIME_GET_MILLISEC(stoptime), false);
1979 }
1980 }
1981}
1982
1983/*
1984 * Create the summary-output files (making them empty if already existing)
1985 */
1986static void
1988{
1989 char file[MAXPGPATH];
1990 FILE *difffile;
1991
1992 /* create outputdir directory if not present */
1995
1996 /* create the log file (copy of running status output) */
1997 snprintf(file, sizeof(file), "%s/regression.out", outputdir);
1998 logfilename = pg_strdup(file);
1999 logfile = fopen(logfilename, "w");
2000 if (!logfile)
2001 bail("could not open file \"%s\" for writing: %m", logfilename);
2002
2003 /* create the diffs file as empty */
2004 snprintf(file, sizeof(file), "%s/regression.diffs", outputdir);
2005 difffilename = pg_strdup(file);
2006 difffile = fopen(difffilename, "w");
2007 if (!difffile)
2008 bail("could not open file \"%s\" for writing: %m", difffilename);
2009
2010 /* we don't keep the diffs file open continuously */
2012
2013 /* also create the results directory if not present */
2014 snprintf(file, sizeof(file), "%s/results", outputdir);
2015 if (!directory_exists(file))
2016 make_directory(file);
2017}
2018
2019static void
2021{
2023
2024 /* Set warning level so we don't see chatter about nonexistent DB */
2025 psql_add_command(buf, "SET client_min_messages = warning");
2026 psql_add_command(buf, "DROP DATABASE IF EXISTS \"%s\"", dbname);
2027 psql_end_command(buf, "postgres");
2028}
2029
2030static void
2032{
2034 _stringlist *sl;
2035
2036 /*
2037 * We use template0 so that any installation-local cruft in template1 will
2038 * not mess up the tests.
2039 */
2040 if (encoding)
2041 psql_add_command(buf, "CREATE DATABASE \"%s\" TEMPLATE=template0 ENCODING='%s'%s", dbname, encoding,
2042 (nolocale) ? " LOCALE='C' LOCALE_PROVIDER='builtin'" : "");
2043 else
2044 psql_add_command(buf, "CREATE DATABASE \"%s\" TEMPLATE=template0%s", dbname,
2045 (nolocale) ? " LOCALE='C' LOCALE_PROVIDER='builtin'" : "");
2047 "ALTER DATABASE \"%s\" SET lc_messages TO 'C';"
2048 "ALTER DATABASE \"%s\" SET lc_monetary TO 'C';"
2049 "ALTER DATABASE \"%s\" SET lc_numeric TO 'C';"
2050 "ALTER DATABASE \"%s\" SET lc_time TO 'C';"
2051 "ALTER DATABASE \"%s\" SET bytea_output TO 'hex';"
2052 "ALTER DATABASE \"%s\" SET timezone_abbreviations TO 'Default';",
2054 psql_end_command(buf, "postgres");
2055
2056 /*
2057 * Install any requested extensions. We use CREATE IF NOT EXISTS so that
2058 * this will work whether or not the extension is preinstalled.
2059 */
2060 for (sl = loadextension; sl != NULL; sl = sl->next)
2061 psql_command(dbname, "CREATE EXTENSION IF NOT EXISTS \"%s\"", sl->str);
2062}
2063
2064static void
2065drop_role_if_exists(const char *rolename)
2066{
2068
2069 /* Set warning level so we don't see chatter about nonexistent role */
2070 psql_add_command(buf, "SET client_min_messages = warning");
2071 psql_add_command(buf, "DROP ROLE IF EXISTS \"%s\"", rolename);
2072 psql_end_command(buf, "postgres");
2073}
2074
2075static void
2076create_role(const char *rolename, const _stringlist *granted_dbs)
2077{
2079
2080 psql_add_command(buf, "CREATE ROLE \"%s\" WITH LOGIN", rolename);
2081 for (; granted_dbs != NULL; granted_dbs = granted_dbs->next)
2082 {
2083 psql_add_command(buf, "GRANT ALL ON DATABASE \"%s\" TO \"%s\"",
2084 granted_dbs->str, rolename);
2085 }
2086 psql_end_command(buf, "postgres");
2087}
2088
2089static void
2090help(void)
2091{
2092 printf(_("PostgreSQL regression test driver\n"));
2093 printf(_("\n"));
2094 printf(_("Usage:\n %s [OPTION]... [EXTRA-TEST]...\n"), progname);
2095 printf(_("\n"));
2096 printf(_("Options:\n"));
2097 printf(_(" --bindir=BINPATH use BINPATH for programs that are run;\n"));
2098 printf(_(" if empty, use PATH from the environment\n"));
2099 printf(_(" --config-auth=DATADIR update authentication settings for DATADIR\n"));
2100 printf(_(" --create-role=ROLE create the specified role before testing\n"));
2101 printf(_(" --dbname=DB use database DB (default \"regression\")\n"));
2102 printf(_(" --debug turn on debug mode in programs that are run\n"));
2103 printf(_(" --dlpath=DIR look for dynamic libraries in DIR\n"));
2104 printf(_(" --encoding=ENCODING use ENCODING as the encoding\n"));
2105 printf(_(" --expecteddir=DIR take expected files from DIR (default \".\")\n"));
2106 printf(_(" -h, --help show this help, then exit\n"));
2107 printf(_(" --inputdir=DIR take input files from DIR (default \".\")\n"));
2108 printf(_(" --launcher=CMD use CMD as launcher of psql\n"));
2109 printf(_(" --load-extension=EXT load the named extension before running the\n"));
2110 printf(_(" tests; can appear multiple times\n"));
2111 printf(_(" --max-connections=N maximum number of concurrent connections\n"));
2112 printf(_(" (default is 0, meaning unlimited)\n"));
2113 printf(_(" --max-concurrent-tests=N maximum number of concurrent tests in schedule\n"));
2114 printf(_(" (default is 0, meaning unlimited)\n"));
2115 printf(_(" --outputdir=DIR place output files in DIR (default \".\")\n"));
2116 printf(_(" --schedule=FILE use test ordering schedule from FILE\n"));
2117 printf(_(" (can be used multiple times to concatenate)\n"));
2118 printf(_(" --temp-instance=DIR create a temporary instance in DIR\n"));
2119 printf(_(" --use-existing use an existing installation\n"));
2120 printf(_(" -V, --version output version information, then exit\n"));
2121 printf(_("\n"));
2122 printf(_("Options for \"temp-instance\" mode:\n"));
2123 printf(_(" --no-locale use C locale\n"));
2124 printf(_(" --port=PORT start postmaster on PORT\n"));
2125 printf(_(" --temp-config=FILE append contents of FILE to temporary config\n"));
2126 printf(_("\n"));
2127 printf(_("Options for using an existing installation:\n"));
2128 printf(_(" --host=HOST use postmaster running on HOST\n"));
2129 printf(_(" --port=PORT use postmaster running at PORT\n"));
2130 printf(_(" --user=USER connect as USER\n"));
2131 printf(_("\n"));
2132 printf(_("The exit status is 0 if all tests passed, 1 if some tests failed, and 2\n"));
2133 printf(_("if the tests could not be run for some reason.\n"));
2134 printf(_("\n"));
2135 printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2136 printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
2137}
2138
2139int
2140regression_main(int argc, char *argv[],
2144{
2145 static struct option long_options[] = {
2146 {"help", no_argument, NULL, 'h'},
2147 {"version", no_argument, NULL, 'V'},
2148 {"dbname", required_argument, NULL, 1},
2149 {"debug", no_argument, NULL, 2},
2150 {"inputdir", required_argument, NULL, 3},
2151 {"max-connections", required_argument, NULL, 5},
2152 {"encoding", required_argument, NULL, 6},
2153 {"outputdir", required_argument, NULL, 7},
2154 {"schedule", required_argument, NULL, 8},
2155 {"temp-instance", required_argument, NULL, 9},
2156 {"no-locale", no_argument, NULL, 10},
2157 {"host", required_argument, NULL, 13},
2158 {"port", required_argument, NULL, 14},
2159 {"user", required_argument, NULL, 15},
2160 {"bindir", required_argument, NULL, 16},
2161 {"dlpath", required_argument, NULL, 17},
2162 {"create-role", required_argument, NULL, 18},
2163 {"temp-config", required_argument, NULL, 19},
2164 {"use-existing", no_argument, NULL, 20},
2165 {"launcher", required_argument, NULL, 21},
2166 {"load-extension", required_argument, NULL, 22},
2167 {"config-auth", required_argument, NULL, 24},
2168 {"max-concurrent-tests", required_argument, NULL, 25},
2169 {"expecteddir", required_argument, NULL, 26},
2170 {NULL, 0, NULL, 0}
2171 };
2172
2173 bool use_unix_sockets;
2174 _stringlist *sl;
2175 int c;
2176 int i;
2177 int option_index;
2178 char buf[MAXPGPATH * 4];
2179
2180 pg_logging_init(argv[0]);
2181 progname = get_progname(argv[0]);
2182 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_regress"));
2183
2185
2187
2189
2190#if defined(WIN32)
2191
2192 /*
2193 * We don't use Unix-domain sockets on Windows by default (see comment at
2194 * remove_temp() for a reason). Override at your own risk.
2195 */
2196 use_unix_sockets = getenv("PG_TEST_USE_UNIX_SOCKETS") ? true : false;
2197#else
2198 use_unix_sockets = true;
2199#endif
2200
2201 if (!use_unix_sockets)
2202 hostname = "localhost";
2203
2204 /*
2205 * We call the initialization function here because that way we can set
2206 * default parameters and let them be overwritten by the commandline.
2207 */
2208 ifunc(argc, argv);
2209
2210 if (getenv("PG_REGRESS_DIFF_OPTS"))
2211 pretty_diff_opts = getenv("PG_REGRESS_DIFF_OPTS");
2212
2213 while ((c = getopt_long(argc, argv, "hV", long_options, &option_index)) != -1)
2214 {
2215 switch (c)
2216 {
2217 case 'h':
2218 help();
2219 exit(0);
2220 case 'V':
2221 puts("pg_regress (PostgreSQL) " PG_VERSION);
2222 exit(0);
2223 case 1:
2224
2225 /*
2226 * If a default database was specified, we need to remove it
2227 * before we add the specified one.
2228 */
2231 break;
2232 case 2:
2233 debug = true;
2234 break;
2235 case 3:
2237 break;
2238 case 5:
2240 break;
2241 case 6:
2243 break;
2244 case 7:
2246 break;
2247 case 8:
2249 break;
2250 case 9:
2252 break;
2253 case 10:
2254 nolocale = true;
2255 break;
2256 case 13:
2258 break;
2259 case 14:
2260 port = atoi(optarg);
2262 break;
2263 case 15:
2265 break;
2266 case 16:
2267 /* "--bindir=" means to use PATH */
2268 if (strlen(optarg))
2270 else
2271 bindir = NULL;
2272 break;
2273 case 17:
2275 break;
2276 case 18:
2278 break;
2279 case 19:
2281 break;
2282 case 20:
2283 use_existing = true;
2284 break;
2285 case 21:
2287 break;
2288 case 22:
2290 break;
2291 case 24:
2293 break;
2294 case 25:
2296 break;
2297 case 26:
2299 break;
2300 default:
2301 /* getopt_long already emitted a complaint */
2302 pg_log_error_hint("Try \"%s --help\" for more information.",
2303 progname);
2304 exit(2);
2305 }
2306 }
2307
2308 /*
2309 * if we still have arguments, they are extra tests to run
2310 */
2311 while (argc - optind >= 1)
2312 {
2314 optind++;
2315 }
2316
2317 /*
2318 * We must have a database to run the tests in; either a default name, or
2319 * one supplied by the --dbname switch.
2320 */
2321 if (!(dblist && dblist->str && dblist->str[0]))
2322 {
2323 bail("no database name was specified");
2324 }
2325
2327 {
2328#ifdef ENABLE_SSPI
2329 if (!use_unix_sockets)
2331#endif
2332 exit(0);
2333 }
2334
2336
2337 /*
2338 * To reduce chances of interference with parallel installations, use
2339 * a port number starting in the private range (49152-65535)
2340 * calculated from the version number. This aids non-Unix socket mode
2341 * systems; elsewhere, the use of a private socket directory already
2342 * prevents interference.
2343 */
2344 port = 0xC000 | (PG_VERSION_NUM & 0x3FFF);
2345
2350
2351 /*
2352 * Initialization
2353 */
2355
2357
2358#if defined(HAVE_GETRLIMIT)
2360#endif
2361
2362 if (temp_instance)
2363 {
2364 StringInfoData cmd;
2365 FILE *pg_conf;
2366 const char *env_wait;
2367 int wait_seconds;
2368 const char *initdb_template_dir;
2369 const char *keywords[4];
2370 const char *values[4];
2371 PGPing rv;
2372 const char *initdb_extra_opts_env;
2373
2374 /*
2375 * Prepare the temp instance
2376 */
2377
2379 {
2380 if (!rmtree(temp_instance, true))
2381 {
2382 bail("could not remove temp instance \"%s\"", temp_instance);
2383 }
2384 }
2385
2386 /* make the temp instance top directory */
2388
2389 /* and a directory for log files */
2390 snprintf(buf, sizeof(buf), "%s/log", outputdir);
2391 if (!directory_exists(buf))
2393
2394 initdb_extra_opts_env = getenv("PG_TEST_INITDB_EXTRA_OPTS");
2395
2396 initStringInfo(&cmd);
2397
2398 /*
2399 * Create data directory.
2400 *
2401 * If available, use a previously initdb'd cluster as a template by
2402 * copying it. For a lot of tests, that's substantially cheaper.
2403 *
2404 * There's very similar code in Cluster.pm, but we can't easily de
2405 * duplicate it until we require perl at build time.
2406 */
2407 initdb_template_dir = getenv("INITDB_TEMPLATE");
2409 {
2410 note("initializing database system by running initdb");
2411
2412 appendStringInfo(&cmd,
2413 "\"%s%sinitdb\" -D \"%s/data\" --no-clean --no-sync",
2414 bindir ? bindir : "",
2415 bindir ? "/" : "",
2417 if (debug)
2418 appendStringInfoString(&cmd, " --debug");
2419 if (nolocale)
2420 appendStringInfoString(&cmd, " --no-locale");
2423 appendStringInfo(&cmd, " > \"%s/log/initdb.log\" 2>&1", outputdir);
2424 fflush(NULL);
2425 if (system(cmd.data))
2426 {
2427 bail("initdb failed\n"
2428 "# Examine \"%s/log/initdb.log\" for the reason.\n"
2429 "# Command was: %s",
2430 outputdir, cmd.data);
2431 }
2432 }
2433 else
2434 {
2435#ifndef WIN32
2436 const char *copycmd = "cp -RPp \"%s\" \"%s/data\"";
2437 int expected_exitcode = 0;
2438#else
2439 const char *copycmd = "robocopy /E /NJS /NJH /NFL /NDL /NP \"%s\" \"%s/data\"";
2440 int expected_exitcode = 1; /* 1 denotes files were copied */
2441#endif
2442
2443 note("initializing database system by copying initdb template");
2444
2445 appendStringInfo(&cmd,
2446 copycmd,
2449 appendStringInfo(&cmd, " > \"%s/log/initdb.log\" 2>&1", outputdir);
2450 fflush(NULL);
2451 if (system(cmd.data) != expected_exitcode)
2452 {
2453 bail("copying of initdb template failed\n"
2454 "# Examine \"%s/log/initdb.log\" for the reason.\n"
2455 "# Command was: %s",
2456 outputdir, cmd.data);
2457 }
2458 }
2459
2460 pfree(cmd.data);
2461
2462 /*
2463 * Adjust the default postgresql.conf for regression testing. The user
2464 * can specify a file to be appended; in any case we expand logging
2465 * and set max_prepared_transactions to enable testing of prepared
2466 * xacts. (Note: to reduce the probability of unexpected shmmax
2467 * failures, don't set max_prepared_transactions any higher than
2468 * actually needed by the prepared_xacts regression test.)
2469 */
2470 snprintf(buf, sizeof(buf), "%s/data/postgresql.conf", temp_instance);
2471 pg_conf = fopen(buf, "a");
2472 if (pg_conf == NULL)
2473 bail("could not open \"%s\" for adding extra config: %m", buf);
2474
2475 fputs("\n# Configuration added by pg_regress\n\n", pg_conf);
2476 fputs("log_autovacuum_min_duration = 0\n", pg_conf);
2477 fputs("log_autoanalyze_min_duration = 0\n", pg_conf);
2478 fputs("log_checkpoints = on\n", pg_conf);
2479 fputs("log_line_prefix = '%m %b[%p] %q%a '\n", pg_conf);
2480 fputs("log_lock_waits = on\n", pg_conf);
2481 fputs("log_temp_files = 128kB\n", pg_conf);
2482 fputs("max_prepared_transactions = 2\n", pg_conf);
2483
2484 for (sl = temp_configs; sl != NULL; sl = sl->next)
2485 {
2486 char *temp_config = sl->str;
2488 char line_buf[1024];
2489
2491 if (extra_conf == NULL)
2492 {
2493 bail("could not open \"%s\" to read extra config: %m",
2494 temp_config);
2495 }
2496 while (fgets(line_buf, sizeof(line_buf), extra_conf) != NULL)
2497 fputs(line_buf, pg_conf);
2499 }
2500
2501 fclose(pg_conf);
2502
2503#ifdef ENABLE_SSPI
2504 if (!use_unix_sockets)
2505 {
2506 /*
2507 * Since we successfully used the same buffer for the much-longer
2508 * "initdb" command, this can't truncate.
2509 */
2510 snprintf(buf, sizeof(buf), "%s/data", temp_instance);
2512 }
2513#endif
2514
2515 /*
2516 * Prepare the connection params for checking the state of the server
2517 * before starting the tests.
2518 */
2519 sprintf(portstr, "%d", port);
2520 keywords[0] = "dbname";
2521 values[0] = "postgres";
2522 keywords[1] = "port";
2523 values[1] = portstr;
2524 keywords[2] = "host";
2526 keywords[3] = NULL;
2527 values[3] = NULL;
2528
2529 /*
2530 * Check if there is a postmaster running already.
2531 */
2532 for (i = 0; i < 16; i++)
2533 {
2534 rv = PQpingParams(keywords, values, 1);
2535
2536 if (rv == PQPING_OK)
2537 {
2538 if (port_specified_by_user || i == 15)
2539 {
2540 note("port %d apparently in use", port);
2542 note("could not determine an available port");
2543 bail("Specify an unused port using the --port option or shut down any conflicting PostgreSQL servers.");
2544 }
2545
2546 note("port %d apparently in use, trying %d", port, port + 1);
2547 port++;
2548 sprintf(portstr, "%d", port);
2549 setenv("PGPORT", portstr, 1);
2550 }
2551 else
2552 break;
2553 }
2554
2555 /*
2556 * Start the temp postmaster
2557 */
2558 snprintf(buf, sizeof(buf),
2559 "\"%s%spostgres\" -D \"%s/data\" -F%s "
2560 "-c \"listen_addresses=%s\" -k \"%s\" "
2561 "> \"%s/log/postmaster.log\" 2>&1",
2562 bindir ? bindir : "",
2563 bindir ? "/" : "",
2564 temp_instance, debug ? " -d 5" : "",
2565 hostname ? hostname : "", sockdir ? sockdir : "",
2566 outputdir);
2569 bail("could not spawn postmaster: %m");
2570
2571 /*
2572 * Wait till postmaster is able to accept connections; normally takes
2573 * only a fraction of a second or so, but Cygwin is reportedly *much*
2574 * slower, and test builds using Valgrind or similar tools might be
2575 * too. Hence, allow the default timeout of 60 seconds to be
2576 * overridden from the PGCTLTIMEOUT environment variable.
2577 */
2578 env_wait = getenv("PGCTLTIMEOUT");
2579 if (env_wait != NULL)
2580 {
2582 if (wait_seconds <= 0)
2583 wait_seconds = 60;
2584 }
2585 else
2586 wait_seconds = 60;
2587
2588 for (i = 0; i < wait_seconds * WAIT_TICKS_PER_SECOND; i++)
2589 {
2590 /*
2591 * It's fairly unlikely that the server is responding immediately
2592 * so we start with sleeping before checking instead of the other
2593 * way around.
2594 */
2595 pg_usleep(1000000L / WAIT_TICKS_PER_SECOND);
2596
2597 rv = PQpingParams(keywords, values, 1);
2598
2599 /* Done if the server is running and accepts connections */
2600 if (rv == PQPING_OK)
2601 break;
2602
2603 if (rv == PQPING_NO_ATTEMPT)
2604 bail("attempting to connect to postmaster failed");
2605
2606 /*
2607 * Fail immediately if postmaster has exited
2608 */
2609#ifndef WIN32
2611#else
2613#endif
2614 {
2615 bail("postmaster failed, examine \"%s/log/postmaster.log\" for the reason",
2616 outputdir);
2617 }
2618 }
2620 {
2621 diag("postmaster did not respond within %d seconds, examine \"%s/log/postmaster.log\" for the reason",
2623
2624 /*
2625 * If we get here, the postmaster is probably wedged somewhere in
2626 * startup. Try to kill it ungracefully rather than leaving a
2627 * stuck postmaster that might interfere with subsequent test
2628 * attempts.
2629 */
2630#ifndef WIN32
2631 if (kill(postmaster_pid, SIGKILL) != 0 && errno != ESRCH)
2632 bail("could not kill failed postmaster: %m");
2633#else
2634 if (TerminateProcess(postmaster_pid, 255) == 0)
2635 bail("could not kill failed postmaster: error code %lu",
2636 GetLastError());
2637#endif
2638 bail("postmaster failed");
2639 }
2640
2641 postmaster_running = true;
2642
2643#ifdef _WIN64
2644/* need a series of two casts to convert HANDLE without compiler warning */
2645#define ULONGPID(x) (unsigned long) (unsigned long long) (x)
2646#else
2647#define ULONGPID(x) (unsigned long) (x)
2648#endif
2649 note("using temp instance on port %d with PID %lu",
2651 }
2652 else
2653 {
2654 /*
2655 * Using an existing installation, so may need to get rid of
2656 * pre-existing database(s) and role(s)
2657 */
2658 if (!use_existing)
2659 {
2660 for (sl = dblist; sl; sl = sl->next)
2662 for (sl = extraroles; sl; sl = sl->next)
2663 drop_role_if_exists(sl->str);
2664 }
2665 }
2666
2667 /*
2668 * Create the test database(s) and role(s)
2669 */
2670 if (!use_existing)
2671 {
2672 for (sl = dblist; sl; sl = sl->next)
2673 create_database(sl->str);
2674 for (sl = extraroles; sl; sl = sl->next)
2675 create_role(sl->str, dblist);
2676 }
2677
2678 /*
2679 * Ready to run the tests
2680 */
2681 for (sl = schedulelist; sl != NULL; sl = sl->next)
2682 {
2684 }
2685
2686 for (sl = extra_tests; sl != NULL; sl = sl->next)
2687 {
2689 }
2690
2691 /*
2692 * Shut down temp installation's postmaster
2693 */
2694 if (temp_instance)
2695 {
2697 }
2698
2699 /*
2700 * If there were no errors, remove the temp instance immediately to
2701 * conserve disk space. (If there were errors, we leave the instance in
2702 * place for possible manual investigation.)
2703 */
2704 if (temp_instance && fail_count == 0)
2705 {
2706 if (!rmtree(temp_instance, true))
2707 diag("could not remove temp instance \"%s\"",
2709 }
2710
2711 /*
2712 * Emit a TAP compliant Plan
2713 */
2715
2716 /*
2717 * Emit nice-looking summary message
2718 */
2719 if (fail_count == 0)
2720 note("All %d tests passed.", success_count);
2721 else
2722 diag("%d of %d tests failed.", fail_count, success_count + fail_count);
2723
2724 if (file_size(difffilename) > 0)
2725 {
2726 diag("The differences that caused some tests to fail can be viewed in the file \"%s\".",
2727 difffilename);
2728 diag("A copy of the test summary that you see above is saved in the file \"%s\".",
2729 logfilename);
2730 }
2731 else
2732 {
2735 }
2736
2737 fclose(logfile);
2738 logfile = NULL;
2739
2740 if (fail_count != 0)
2741 exit(1);
2742
2743 return 0;
2744}
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define SIGNAL_ARGS
Definition c.h:1462
#define Assert(condition)
Definition c.h:943
#define PG_TEXTDOMAIN(domain)
Definition c.h:1303
#define pg_attribute_printf(f, a)
Definition c.h:268
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition exec.c:430
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
#define _(x)
Definition elog.c:96
PGPing PQpingParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition fe-connect.c:793
void * pg_malloc(size_t size)
Definition fe_memutils.c:47
char * pg_strdup(const char *in)
Definition fe_memutils.c:85
void pg_free(void *ptr)
void * pg_realloc(void *ptr, size_t size)
Definition fe_memutils.c:65
#define pg_malloc_array(type, count)
Definition fe_memutils.h:56
#define pg_malloc_object(type)
Definition fe_memutils.h:50
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition getopt_long.c:60
#define no_argument
Definition getopt_long.h:25
#define required_argument
Definition getopt_long.h:26
const char * str
#define ident
#define token
void pg_initialize_timing(void)
Definition instr_time.c:82
#define INSTR_TIME_SET_CURRENT(t)
Definition instr_time.h:426
#define INSTR_TIME_SUBTRACT(x, y)
Definition instr_time.h:436
#define INSTR_TIME_GET_MILLISEC(t)
Definition instr_time.h:451
return true
Definition isn.c:130
int i
Definition isn.c:77
static const JsonPathKeyword keywords[]
PGPing
Definition libpq-fe.h:181
@ PQPING_OK
Definition libpq-fe.h:182
@ PQPING_NO_ATTEMPT
Definition libpq-fe.h:185
void pg_logging_init(const char *argv0)
Definition logging.c:85
#define pg_log_error_hint(...)
Definition logging.h:114
void pfree(void *pointer)
Definition mcxt.c:1616
#define MAXPGPATH
#define DEFAULT_PGSOCKET_DIR
const void size_t len
static int wait_seconds
Definition pg_ctl.c:77
static char * filename
Definition pg_dumpall.c:133
PGDLLIMPORT int optind
Definition getopt.c:47
PGDLLIMPORT char * optarg
Definition getopt.c:49
static XLogRecPtr startpos
#define plan(x)
Definition pg_regress.c:164
static bool use_existing
Definition pg_regress.c:115
static void open_result_files(void)
static int max_connections
Definition pg_regress.c:107
static bool in_note
Definition pg_regress.c:135
#define diag_detail(...)
Definition pg_regress.c:168
#define diag_end()
Definition pg_regress.c:169
static char * user
Definition pg_regress.c:121
static bool port_specified_by_user
Definition pg_regress.c:119
static int file_line_count(const char *file)
static bool nolocale
Definition pg_regress.c:114
#define note_detail(...)
Definition pg_regress.c:166
#define diag(...)
Definition pg_regress.c:167
static char * get_alternative_expectfile(const char *expectfile, int i)
static void load_resultmap(void)
Definition pg_regress.c:631
static void psql_add_command(StringInfo buf, const char *query,...) pg_attribute_printf(2
static void static void static void static StringInfo psql_start_command(void)
bool file_exists(const char *file)
static void signal_remove_temp(SIGNAL_ARGS)
Definition pg_regress.c:491
static void remove_temp(void)
Definition pg_regress.c:479
static void stop_postmaster(void)
Definition pg_regress.c:444
static int max_concurrent_tests
Definition pg_regress.c:108
static void create_database(const char *dbname)
static void free_stringlist(_stringlist **listhead)
Definition pg_regress.c:223
static void drop_role_if_exists(const char *rolename)
#define MAX_PARALLEL_TESTS
static const char * get_expectfile(const char *testname, const char *file)
Definition pg_regress.c:705
static void static void psql_end_command(StringInfo buf, const char *database)
bool debug
Definition pg_regress.c:100
static void static void emit_tap_output(TAPtype type, const char *fmt,...) pg_attribute_printf(2
Definition pg_regress.c:336
static StringInfo failed_tests
Definition pg_regress.c:134
static char * shellprog
Definition pg_regress.c:55
static void unlimit_core_size(void)
Definition pg_regress.c:179
static const char * temp_sockdir
Definition pg_regress.c:131
static bool directory_exists(const char *dir)
static _stringlist * schedulelist
Definition pg_regress.c:110
TAPtype
Definition pg_regress.c:85
@ PLAN
Definition pg_regress.c:94
@ NOTE
Definition pg_regress.c:90
@ DIAG
Definition pg_regress.c:86
@ NOTE_DETAIL
Definition pg_regress.c:91
@ DIAG_END
Definition pg_regress.c:88
@ NONE
Definition pg_regress.c:95
@ TEST_STATUS
Definition pg_regress.c:93
@ BAIL
Definition pg_regress.c:89
@ NOTE_END
Definition pg_regress.c:92
@ DIAG_DETAIL
Definition pg_regress.c:87
#define WAIT_TICKS_PER_SECOND
Definition pg_regress.c:82
static _stringlist * loadextension
Definition pg_regress.c:106
static char * logfilename
Definition pg_regress.c:127
static _stringlist * temp_configs
Definition pg_regress.c:113
static _stringlist * extra_tests
Definition pg_regress.c:111
static void test_status_ok(const char *testname, double runtime, bool parallel)
Definition pg_regress.c:308
static int port
Definition pg_regress.c:117
static bool in_diag
Definition pg_regress.c:136
char * outputdir
Definition pg_regress.c:102
static void make_directory(const char *dir)
static void split_to_stringlist(const char *s, const char *delim, _stringlist **listhead)
Definition pg_regress.c:238
#define note(...)
Definition pg_regress.c:165
#define TESTNAME_WIDTH
Definition pg_regress.c:76
static int run_diff(const char *cmd, const char *filename)
static void run_single_test(const char *test, test_start_function startfunc, postprocess_result_function postfunc)
char * launcher
Definition pg_regress.c:105
const char * pretty_diff_opts
Definition pg_regress.c:65
char * inputdir
Definition pg_regress.c:101
static void log_child_failure(int exitstatus)
int regression_main(int argc, char *argv[], init_function ifunc, test_start_function startfunc, postprocess_result_function postfunc)
#define bail_noatexit(...)
Definition pg_regress.c:171
static char * difffilename
Definition pg_regress.c:129
static void bail_out(bool noatexit, const char *fmt,...) pg_attribute_printf(2
Definition pg_regress.c:260
static const char * make_temp_sockdir(void)
Definition pg_regress.c:512
static _resultmap * resultmap
Definition pg_regress.c:138
char * expecteddir
Definition pg_regress.c:103
static char * config_auth_datadir
Definition pg_regress.c:123
char * host_platform
Definition pg_regress.c:52
static void drop_database_if_exists(const char *dbname)
static FILE * logfile
Definition pg_regress.c:128
static void test_status_failed(const char *testname, double runtime, bool parallel)
Definition pg_regress.c:316
const char * basic_diff_opts
Definition pg_regress.c:64
static char portstr[16]
Definition pg_regress.c:118
static void initialize_environment(void)
Definition pg_regress.c:734
static char * temp_instance
Definition pg_regress.c:112
static char sockself[MAXPGPATH]
Definition pg_regress.c:132
static char * encoding
Definition pg_regress.c:109
static void wait_for_tests(PID_TYPE *pids, int *statuses, instr_time *stoptimes, char **names, int num_tests)
static void help(void)
static const char * sockdir
Definition pg_regress.c:130
static long file_size(const char *file)
static bool postmaster_running
Definition pg_regress.c:141
_stringlist * dblist
Definition pg_regress.c:99
static char socklock[MAXPGPATH]
Definition pg_regress.c:133
static const char * progname
Definition pg_regress.c:126
static char * dlpath
Definition pg_regress.c:120
static _stringlist * extraroles
Definition pg_regress.c:122
static bool results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)
PID_TYPE spawn_process(const char *cmdline)
char * bindir
Definition pg_regress.c:104
#define bail(...)
Definition pg_regress.c:172
static void test_status_print(bool ok, const char *testname, double runtime, bool parallel)
Definition pg_regress.c:285
static void create_role(const char *rolename, const _stringlist *granted_dbs)
static void run_schedule(const char *schedule, test_start_function startfunc, postprocess_result_function postfunc)
void add_stringlist_item(_stringlist **listhead, const char *str)
Definition pg_regress.c:202
static int success_count
Definition pg_regress.c:143
static bool string_matches_pattern(const char *str, const char *pattern)
Definition pg_regress.c:557
static void static void static void emit_tap_output_v(TAPtype type, const char *fmt, va_list argp) pg_attribute_printf(2
Definition pg_regress.c:346
#define psql_command(database,...)
#define ULONGPID(x)
#define note_end()
Definition pg_regress.c:170
static char * hostname
Definition pg_regress.c:116
static int fail_count
Definition pg_regress.c:144
static PID_TYPE postmaster_pid
Definition pg_regress.c:140
void(* init_function)(int argc, char **argv)
Definition pg_regress.h:33
#define PID_TYPE
Definition pg_regress.h:14
PID_TYPE(* test_start_function)(const char *testname, _stringlist **resultfiles, _stringlist **expectfiles, _stringlist **tags)
Definition pg_regress.h:36
#define INVALID_PID
Definition pg_regress.h:15
void(* postprocess_result_function)(const char *filename)
Definition pg_regress.h:42
static char buf[DEFAULT_XLOG_SEG_SIZE]
static const char * pghost
Definition pgbench.c:295
static const char * pgport
Definition pgbench.c:296
#define pqsignal
Definition port.h:547
char * strsep(char **stringp, const char *delim)
Definition strsep.c:49
#define sprintf
Definition port.h:262
const char * pg_strsignal(int signum)
Definition pgstrsignal.c:39
#define vfprintf
Definition port.h:263
#define snprintf
Definition port.h:260
char * make_absolute_path(const char *path)
Definition path.c:807
char * mkdtemp(char *path)
Definition mkdtemp.c:286
const char * get_progname(const char *argv0)
Definition path.c:652
#define printf(...)
Definition port.h:266
#define PG_SIG_DFL
Definition port.h:550
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
#define UNIXSOCK_PATH(path, port, sockdir)
Definition pqcomm.h:43
static void test(void)
char * c
static int fb(int x)
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
void get_restricted_token(void)
bool rmtree(const char *path, bool rmtopdir)
Definition rmtree.c:50
void pg_usleep(long microsec)
Definition signal.c:53
#define free(a)
#define malloc(a)
char * dbname
Definition streamutil.c:49
int appendStringInfoVA(StringInfo str, const char *fmt, va_list args)
Definition stringinfo.c:187
void destroyStringInfo(StringInfo str)
Definition stringinfo.c:409
StringInfo makeStringInfo(void)
Definition stringinfo.c:72
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void enlargeStringInfo(StringInfo str, int needed)
Definition stringinfo.c:337
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
char * resultfile
Definition pg_regress.c:45
struct _resultmap * next
Definition pg_regress.c:46
char * test
Definition pg_regress.c:43
char * type
Definition pg_regress.c:44
char * str
Definition initdb.c:92
struct _stringlist * next
Definition initdb.c:93
unsigned short st_mode
Definition win32_port.h:258
const char * get_user_name(char **errstr)
Definition username.c:31
const char * type
#define SIGHUP
Definition win32_port.h:158
#define stat
Definition win32_port.h:74
#define unsetenv(x)
Definition win32_port.h:543
#define S_IRWXG
Definition win32_port.h:300
#define SIGPIPE
Definition win32_port.h:163
#define S_IRWXO
Definition win32_port.h:312
#define S_ISDIR(m)
Definition win32_port.h:315
#define mkdir(a, b)
Definition win32_port.h:80
#define kill(pid, sig)
Definition win32_port.h:490
#define WIFEXITED(w)
Definition win32_port.h:150
#define setenv(x, y, z)
Definition win32_port.h:542
#define WIFSIGNALED(w)
Definition win32_port.h:151
#define WTERMSIG(w)
Definition win32_port.h:153
#define SIGKILL
Definition win32_port.h:162
#define WEXITSTATUS(w)
Definition win32_port.h:152
#define S_IRWXU
Definition win32_port.h:288