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