pg_regress.c 56.5 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * pg_regress --- regression test driver
 *
 * This is a C implementation of the previous shell script for running
6
 * the regression tests, and should be mostly compatible with it.
7 8 9 10
 * Initial author of C translation: Magnus Hagander
 *
 * This code is released under the terms of the PostgreSQL License.
 *
B
Bruce Momjian 已提交
11
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
12 13
 * Portions Copyright (c) 1994, Regents of the University of California
 *
14
 * $PostgreSQL: pgsql/src/test/regress/pg_regress.c,v 1.58 2009/01/27 12:46:16 mha Exp $
15 16 17 18
 *
 *-------------------------------------------------------------------------
 */

19
#include "pg_regress.h"
20 21 22 23

#include <ctype.h>
#include <sys/stat.h>
#include <sys/wait.h>
24
#include <signal.h>
25 26
#include <unistd.h>

A
 
Andrew Dunstan 已提交
27 28 29 30 31
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
#endif

32
#include "getopt_long.h"
33
#include "pg_config_paths.h"
34 35 36 37

/* for resultmap we need a list of pairs of strings */
typedef struct _resultmap
{
B
Bruce Momjian 已提交
38
	char	   *test;
39
	char	   *type;
B
Bruce Momjian 已提交
40
	char	   *resultfile;
41
	struct _resultmap *next;
B
Bruce Momjian 已提交
42
}	_resultmap;
43 44

/*
45 46 47 48 49
 * Values obtained from pg_config_paths.h and Makefile.  The PG installation
 * paths are only used in temp_install mode: we use these strings to find
 * out where "make install" will put stuff under the temp_install directory.
 * In non-temp_install mode, the only thing we need is the location of psql,
 * which we expect to find in psqldir, or in the PATH if psqldir isn't given.
50 51 52 53
 *
 * XXX Because pg_regress is not installed in bindir, we can't support
 * this for relocatable trees as it is.  --psqldir would need to be
 * specified in those cases.
54
 */
B
Bruce Momjian 已提交
55 56 57 58 59
char	   *bindir = PGBINDIR;
char	   *libdir = LIBDIR;
char	   *datadir = PGSHAREDIR;
char	   *host_platform = HOST_TUPLE;

B
Bruce Momjian 已提交
60
#ifndef WIN32_ONLY_COMPILER
61
static char *makeprog = MAKEPROG;
B
Bruce Momjian 已提交
62
#endif
B
Bruce Momjian 已提交
63

64
#ifndef WIN32					/* not used in WIN32 case */
65
static char *shellprog = SHELLPROG;
66
#endif
67 68

/* currently we can use the same diff switches on all platforms */
69 70
const char *basic_diff_opts = "-w";
const char *pretty_diff_opts = "-w -C3";
71 72

/* options settable from command line */
73
_stringlist *dblist = NULL;
B
Bruce Momjian 已提交
74 75 76
bool		debug = false;
char	   *inputdir = ".";
char	   *outputdir = ".";
77
char	   *psqldir = PGBINDIR;
78
static _stringlist *loadlanguage = NULL;
B
Bruce Momjian 已提交
79
static int	max_connections = 0;
80 81 82 83
static char *encoding = NULL;
static _stringlist *schedulelist = NULL;
static _stringlist *extra_tests = NULL;
static char *temp_install = NULL;
84
static char *temp_config = NULL;
85 86 87
static char *top_builddir = NULL;
static bool nolocale = false;
static char *hostname = NULL;
B
Bruce Momjian 已提交
88
static int	port = -1;
89
static bool port_specified_by_user = false;
90
static char *dlpath = PKGLIBDIR;
91
static char *user = NULL;
92
static _stringlist *extraroles = NULL;
93 94 95 96 97 98 99 100 101 102 103 104

/* internal variables */
static const char *progname;
static char *logfilename;
static FILE *logfile;
static char *difffilename;

static _resultmap *resultmap = NULL;

static PID_TYPE postmaster_pid = INVALID_PID;
static bool postmaster_running = false;

B
Bruce Momjian 已提交
105 106 107
static int	success_count = 0;
static int	fail_count = 0;
static int	fail_ignore_count = 0;
108

109 110
static bool directory_exists(const char *dir);
static void make_directory(const char *dir);
111

112 113 114 115 116 117 118 119 120 121 122
static void
header(const char *fmt,...)
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
__attribute__((format(printf, 1, 2)));
static void
status(const char *fmt,...)
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
__attribute__((format(printf, 1, 2)));
static void
B
Bruce Momjian 已提交
123
psql_command(const char *database, const char *query,...)
124 125 126 127
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
__attribute__((format(printf, 2, 3)));

B
Bruce Momjian 已提交
128
#ifdef WIN32
B
Bruce Momjian 已提交
129
typedef		BOOL(WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
130 131 132

/* Windows API define missing from MingW headers */
#define DISABLE_MAX_PRIVILEGE	0x1
B
Bruce Momjian 已提交
133 134
#endif

A
 
Andrew Dunstan 已提交
135 136 137 138
/*
 * allow core files if possible.
 */
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
B
Bruce Momjian 已提交
139
static void
A
 
Andrew Dunstan 已提交
140 141 142
unlimit_core_size(void)
{
	struct rlimit lim;
B
Bruce Momjian 已提交
143 144

	getrlimit(RLIMIT_CORE, &lim);
A
 
Andrew Dunstan 已提交
145 146 147
	if (lim.rlim_max == 0)
	{
		fprintf(stderr,
148
				_("%s: could not set core size: disallowed by hard limit\n"),
A
 
Andrew Dunstan 已提交
149 150 151 152 153 154
				progname);
		return;
	}
	else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
	{
		lim.rlim_cur = lim.rlim_max;
B
Bruce Momjian 已提交
155 156
		setrlimit(RLIMIT_CORE, &lim);
	}
A
 
Andrew Dunstan 已提交
157 158 159
}
#endif

160 161 162 163

/*
 * Add an item at the end of a stringlist.
 */
164
void
B
Bruce Momjian 已提交
165
add_stringlist_item(_stringlist ** listhead, const char *str)
166 167 168 169 170 171 172 173 174 175 176
{
	_stringlist *newentry = malloc(sizeof(_stringlist));
	_stringlist *oldentry;

	newentry->str = strdup(str);
	newentry->next = NULL;
	if (*listhead == NULL)
		*listhead = newentry;
	else
	{
		for (oldentry = *listhead; oldentry->next; oldentry = oldentry->next)
B
Bruce Momjian 已提交
177
			 /* skip */ ;
178 179 180 181
		oldentry->next = newentry;
	}
}

182 183 184 185
/*
 * Free a stringlist.
 */
static void
B
Bruce Momjian 已提交
186
free_stringlist(_stringlist ** listhead)
187 188 189 190 191 192 193 194 195 196 197 198 199 200
{
	if (listhead == NULL || *listhead == NULL)
		return;
	if ((*listhead)->next != NULL)
		free_stringlist(&((*listhead)->next));
	free((*listhead)->str);
	free(*listhead);
	*listhead = NULL;
}

/*
 * Split a delimited string into a stringlist
 */
static void
B
Bruce Momjian 已提交
201
split_to_stringlist(const char *s, const char *delim, _stringlist ** listhead)
202
{
B
Bruce Momjian 已提交
203 204 205
	char	   *sc = strdup(s);
	char	   *token = strtok(sc, delim);

206 207 208 209 210 211 212 213
	while (token)
	{
		add_stringlist_item(listhead, token);
		token = strtok(NULL, delim);
	}
	free(sc);
}

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
/*
 * Print a progress banner on stdout.
 */
static void
header(const char *fmt,...)
{
	char		tmp[64];
	va_list		ap;

	va_start(ap, fmt);
	vsnprintf(tmp, sizeof(tmp), fmt, ap);
	va_end(ap);

	fprintf(stdout, "============== %-38s ==============\n", tmp);
	fflush(stdout);
}

/*
 * Print "doing something ..." --- supplied text should not end with newline
 */
static void
status(const char *fmt,...)
{
	va_list		ap;

	va_start(ap, fmt);
	vfprintf(stdout, fmt, ap);
	fflush(stdout);
	va_end(ap);

	if (logfile)
	{
		va_start(ap, fmt);
		vfprintf(logfile, fmt, ap);
		va_end(ap);
	}
}

/*
 * Done "doing something ..."
 */
static void
status_end(void)
{
	fprintf(stdout, "\n");
	fflush(stdout);
	if (logfile)
		fprintf(logfile, "\n");
}

/*
 * shut down temp postmaster
 */
static void
stop_postmaster(void)
{
	if (postmaster_running)
	{
		/* We use pg_ctl to issue the kill and wait for stop */
B
Bruce Momjian 已提交
273
		char		buf[MAXPGPATH * 2];
274
		int			r;
275

276 277 278 279
		/* On Windows, system() seems not to force fflush, so... */
		fflush(stdout);
		fflush(stderr);

280
		snprintf(buf, sizeof(buf),
281
				 SYSTEMQUOTE "\"%s/pg_ctl\" stop -D \"%s/data\" -s -m fast" SYSTEMQUOTE,
282
				 bindir, temp_install);
283 284 285 286 287 288 289 290
		r = system(buf);
		if (r != 0)
		{
			fprintf(stderr, _("\n%s: could not stop postmaster: exit code was %d\n"),
					progname, r);
			exit(2);   /* not exit_nicely(), that would be recursive */
		}

291 292 293 294 295 296 297 298
		postmaster_running = false;
	}
}

/*
 * Always exit through here, not through plain exit(), to ensure we make
 * an effort to shut down a temp postmaster
 */
299
void
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
exit_nicely(int code)
{
	stop_postmaster();
	exit(code);
}

/*
 * Check whether string matches pattern
 *
 * In the original shell script, this function was implemented using expr(1),
 * which provides basic regular expressions restricted to match starting at
 * the string start (in conventional regex terms, there's an implicit "^"
 * at the start of the pattern --- but no implicit "$" at the end).
 *
 * For now, we only support "." and ".*" as non-literal metacharacters,
 * because that's all that anyone has found use for in resultmap.  This
 * code could be extended if more functionality is needed.
 */
static bool
string_matches_pattern(const char *str, const char *pattern)
{
	while (*str && *pattern)
	{
		if (*pattern == '.' && pattern[1] == '*')
		{
			pattern += 2;
			/* Trailing .* matches everything. */
			if (*pattern == '\0')
				return true;

			/*
			 * Otherwise, scan for a text position at which we can match the
			 * rest of the pattern.
			 */
			while (*str)
			{
				/*
				 * Optimization to prevent most recursion: don't recurse
				 * unless first pattern char might match this text char.
				 */
				if (*str == *pattern || *pattern == '.')
				{
					if (string_matches_pattern(str, pattern))
						return true;
				}

				str++;
			}

			/*
			 * End of text with no match.
			 */
			return false;
		}
		else if (*pattern != '.' && *str != *pattern)
		{
			/*
			 * Not the single-character wildcard and no explicit match? Then
			 * time to quit...
			 */
			return false;
		}

		str++;
		pattern++;
	}

	if (*pattern == '\0')
		return true;			/* end of pattern, so declare match */

	/* End of input string.  Do we have matching pattern remaining? */
	while (*pattern == '.' && pattern[1] == '*')
		pattern += 2;
	if (*pattern == '\0')
		return true;			/* end of pattern, so declare match */

	return false;
}

379 380 381 382
/*
 * Replace all occurances of a string in a string with a different string.
 * NOTE: Assumes there is enough room in the target buffer!
 */
383
void
384 385
replace_string(char *string, char *replace, char *replacement)
{
B
Bruce Momjian 已提交
386
	char	   *ptr;
387

B
Bruce Momjian 已提交
388
	while ((ptr = strstr(string, replace)) != NULL)
389
	{
B
Bruce Momjian 已提交
390
		char	   *dup = strdup(string);
391

392
		strlcpy(string, dup, ptr - string + 1);
393 394 395 396 397 398 399 400 401 402 403 404 405
		strcat(string, replacement);
		strcat(string, dup + (ptr - string) + strlen(replace));
		free(dup);
	}
}

/*
 * Convert *.source found in the "source" directory, replacing certain tokens
 * in the file contents with their intended values, and put the resulting files
 * in the "dest" directory, replacing the ".source" prefix in their names with
 * the given suffix.
 */
static void
406
convert_sourcefiles_in(char *source_subdir, char *dest_subdir, char *suffix)
407
{
B
Bruce Momjian 已提交
408 409
	char		testtablespace[MAXPGPATH];
	char		indir[MAXPGPATH];
410 411
	struct stat	st;
	int			ret;
B
Bruce Momjian 已提交
412 413 414 415
	char	  **name;
	char	  **names;
	int			count = 0;

416
	snprintf(indir, MAXPGPATH, "%s/%s", inputdir, source_subdir);
417 418 419 420 421 422 423 424 425 426 427 428

	/* Check that indir actually exists and is a directory */
	ret = stat(indir, &st);
	if (ret != 0 || !S_ISDIR(st.st_mode))
	{
		/*
		 * No warning, to avoid noise in tests that do not have
		 * these directories; for example, ecpg, contrib and src/pl.
		 */
		return;
	}

429 430 431 432 433
	names = pgfnames(indir);
	if (!names)
		/* Error logged in pgfnames */
		exit_nicely(2);

434
	snprintf(testtablespace, MAXPGPATH, "%s/testtablespace", outputdir);
435 436 437 438 439 440 441 442 443 444 445 446

#ifdef WIN32
	/*
	 * On Windows only, clean out the test tablespace dir, or create it if it
	 * doesn't exist.  On other platforms we expect the Makefile to take
	 * care of that.  (We don't migrate that functionality in here because
	 * it'd be harder to cope with platform-specific issues such as SELinux.)
	 *
	 * XXX it would be better if pg_regress.c had nothing at all to do with
	 * testtablespace, and this were handled by a .BAT file or similar on
	 * Windows.  See pgsql-hackers discussion of 2008-01-18.
	 */
447 448 449
	if (directory_exists(testtablespace))
		rmtree(testtablespace, true);
	make_directory(testtablespace);
450
#endif
451 452 453 454

	/* finally loop on each file and do the replacement */
	for (name = names; *name; name++)
	{
B
Bruce Momjian 已提交
455 456 457 458 459 460
		char		srcfile[MAXPGPATH];
		char		destfile[MAXPGPATH];
		char		prefix[MAXPGPATH];
		FILE	   *infile,
				   *outfile;
		char		line[1024];
461 462 463 464 465 466 467 468 469 470 471 472

		/* reject filenames not finishing in ".source" */
		if (strlen(*name) < 8)
			continue;
		if (strcmp(*name + strlen(*name) - 7, ".source") != 0)
			continue;

		count++;

		/* build the full actual paths to open */
		snprintf(prefix, strlen(*name) - 6, "%s", *name);
		snprintf(srcfile, MAXPGPATH, "%s/%s", indir, *name);
473
		snprintf(destfile, MAXPGPATH, "%s/%s.%s", dest_subdir, prefix, suffix);
474 475 476 477 478 479 480 481 482 483 484 485

		infile = fopen(srcfile, "r");
		if (!infile)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
					progname, srcfile, strerror(errno));
			exit_nicely(2);
		}
		outfile = fopen(destfile, "w");
		if (!outfile)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
B
Bruce Momjian 已提交
486
					progname, destfile, strerror(errno));
487 488 489 490
			exit_nicely(2);
		}
		while (fgets(line, sizeof(line), infile))
		{
491 492
			replace_string(line, "@abs_srcdir@", inputdir);
			replace_string(line, "@abs_builddir@", outputdir);
493
			replace_string(line, "@testtablespace@", testtablespace);
494
			replace_string(line, "@libdir@", dlpath);
495 496 497 498 499 500 501 502 503
			replace_string(line, "@DLSUFFIX@", DLSUFFIX);
			fputs(line, outfile);
		}
		fclose(infile);
		fclose(outfile);
	}

	/*
	 * If we didn't process any files, complain because it probably means
504
	 * somebody neglected to pass the needed --inputdir argument.
505 506 507
	 */
	if (count <= 0)
	{
508
		fprintf(stderr, _("%s: no *.source files found in \"%s\"\n"),
509 510 511
				progname, indir);
		exit_nicely(2);
	}
B
Bruce Momjian 已提交
512 513

	pgfnames_cleanup(names);
514 515
}

516
/* Create the .sql and .out files from the .source files, if any */
517 518 519
static void
convert_sourcefiles(void)
{
520 521
	convert_sourcefiles_in("input", "sql", "sql");
	convert_sourcefiles_in("output", "expected", "out");
522 523
}

524 525 526 527
/*
 * Scan resultmap file to find which platform-specific expected files to use.
 *
 * The format of each line of the file is
B
Bruce Momjian 已提交
528
 *		   testname/hostplatformpattern=substitutefile
529 530 531 532
 * where the hostplatformpattern is evaluated per the rules of expr(1),
 * namely, it is a standard regular expression with an implicit ^ at the start.
 * (We currently support only a very limited subset of regular expressions,
 * see string_matches_pattern() above.)  What hostplatformpattern will be
B
Bruce Momjian 已提交
533
 * matched against is the config.guess output.	(In the shell-script version,
534 535 536 537 538 539
 * we also provided an indication of whether gcc or another compiler was in
 * use, but that facility isn't used anymore.)
 */
static void
load_resultmap(void)
{
B
Bruce Momjian 已提交
540 541
	char		buf[MAXPGPATH];
	FILE	   *f;
542 543 544

	/* scan the file ... */
	snprintf(buf, sizeof(buf), "%s/resultmap", inputdir);
B
Bruce Momjian 已提交
545
	f = fopen(buf, "r");
546 547 548 549 550 551 552 553 554
	if (!f)
	{
		/* OK if it doesn't exist, else complain */
		if (errno == ENOENT)
			return;
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, buf, strerror(errno));
		exit_nicely(2);
	}
555 556

	while (fgets(buf, sizeof(buf), f))
557
	{
B
Bruce Momjian 已提交
558
		char	   *platform;
559
		char	   *file_type;
B
Bruce Momjian 已提交
560 561
		char	   *expected;
		int			i;
562 563 564

		/* strip trailing whitespace, especially the newline */
		i = strlen(buf);
B
Bruce Momjian 已提交
565
		while (i > 0 && isspace((unsigned char) buf[i - 1]))
566 567 568
			buf[--i] = '\0';

		/* parse out the line fields */
569 570 571 572
		file_type = strchr(buf, ':');
		if (!file_type)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
B
Bruce Momjian 已提交
573
					buf);
574 575 576 577 578
			exit_nicely(2);
		}
		*file_type++ = '\0';

		platform = strchr(file_type, ':');
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
		if (!platform)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
			exit_nicely(2);
		}
		*platform++ = '\0';
		expected = strchr(platform, '=');
		if (!expected)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
			exit_nicely(2);
		}
		*expected++ = '\0';

		/*
B
Bruce Momjian 已提交
596 597 598 599
		 * if it's for current platform, save it in resultmap list. Note: by
		 * adding at the front of the list, we ensure that in ambiguous cases,
		 * the last match in the resultmap file is used. This mimics the
		 * behavior of the old shell script.
600 601 602 603 604 605
		 */
		if (string_matches_pattern(host_platform, platform))
		{
			_resultmap *entry = malloc(sizeof(_resultmap));

			entry->test = strdup(buf);
606
			entry->type = strdup(file_type);
607 608 609 610 611 612 613 614
			entry->resultfile = strdup(expected);
			entry->next = resultmap;
			resultmap = entry;
		}
	}
	fclose(f);
}

615 616 617 618
/*
 * Check in resultmap if we should be looking at a different file
 */
static
B
Bruce Momjian 已提交
619 620
const char *
get_expectfile(const char *testname, const char *file)
621
{
B
Bruce Momjian 已提交
622
	char	   *file_type;
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
	_resultmap *rm;

	/*
	 * Determine the file type from the file name. This is just what is
	 * following the last dot in the file name.
	 */
	if (!file || !(file_type = strrchr(file, '.')))
		return NULL;

	file_type++;

	for (rm = resultmap; rm != NULL; rm = rm->next)
	{
		if (strcmp(testname, rm->test) == 0 && strcmp(file_type, rm->type) == 0)
		{
			return rm->resultfile;
		}
	}

	return NULL;
}

645 646 647 648 649 650
/*
 * Handy subroutine for setting an environment variable "var" to "val"
 */
static void
doputenv(const char *var, const char *val)
{
B
Bruce Momjian 已提交
651
	char	   *s = malloc(strlen(var) + strlen(val) + 2);
652 653 654 655 656 657 658 659 660 661 662 663

	sprintf(s, "%s=%s", var, val);
	putenv(s);
}

/*
 * Set the environment variable "pathname", prepending "addval" to its
 * old value (if any).
 */
static void
add_to_path(const char *pathname, char separator, const char *addval)
{
B
Bruce Momjian 已提交
664 665
	char	   *oldval = getenv(pathname);
	char	   *newval;
666 667 668 669 670 671 672 673 674 675

	if (!oldval || !oldval[0])
	{
		/* no previous value */
		newval = malloc(strlen(pathname) + strlen(addval) + 2);
		sprintf(newval, "%s=%s", pathname, addval);
	}
	else
	{
		newval = malloc(strlen(pathname) + strlen(addval) + strlen(oldval) + 3);
B
Bruce Momjian 已提交
676
		sprintf(newval, "%s=%s%c%s", pathname, addval, separator, oldval);
677 678 679 680 681 682 683 684 685 686
	}
	putenv(newval);
}

/*
 * Prepare environment variables for running regression tests
 */
static void
initialize_environment(void)
{
B
Bruce Momjian 已提交
687
	char	   *tmp;
688 689 690 691 692 693 694 695 696 697 698 699 700

	/*
	 * Clear out any non-C locale settings
	 */
	unsetenv("LC_COLLATE");
	unsetenv("LC_CTYPE");
	unsetenv("LC_MONETARY");
	unsetenv("LC_MESSAGES");
	unsetenv("LC_NUMERIC");
	unsetenv("LC_TIME");
	unsetenv("LC_ALL");
	unsetenv("LANG");
	unsetenv("LANGUAGE");
701
	/* On Windows the default locale cannot be English, so force it */
702
#if defined(WIN32) || defined(__CYGWIN__)
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
	putenv("LANG=en");
#endif

	/*
	 * Set multibyte as requested
	 */
	if (encoding)
		doputenv("PGCLIENTENCODING", encoding);
	else
		unsetenv("PGCLIENTENCODING");

	/*
	 * Set timezone and datestyle for datetime-related tests
	 */
	putenv("PGTZ=PST8PDT");
	putenv("PGDATESTYLE=Postgres, MDY");
719 720 721 722 723 724 725

	/*
	 * Likewise set intervalstyle to ensure consistent results.  This is a
	 * bit more painful because we must use PGOPTIONS, and we want to preserve
	 * the user's ability to set other variables through that.
	 */
	{
726
		const char *my_pgoptions = "-c intervalstyle=postgres_verbose";
727 728 729 730 731 732 733 734 735
		const char *old_pgoptions = getenv("PGOPTIONS");
		char   *new_pgoptions;

		if (!old_pgoptions)
			old_pgoptions = "";
		new_pgoptions = malloc(strlen(old_pgoptions) + strlen(my_pgoptions) + 12);
		sprintf(new_pgoptions, "PGOPTIONS=%s %s", old_pgoptions, my_pgoptions);
		putenv(new_pgoptions);
	}
736 737 738 739

	if (temp_install)
	{
		/*
B
Bruce Momjian 已提交
740 741 742 743 744 745
		 * Clear out any environment vars that might cause psql to connect to
		 * the wrong postmaster, or otherwise behave in nondefault ways. (Note
		 * we also use psql's -X switch consistently, so that ~/.psqlrc files
		 * won't mess things up.)  Also, set PGPORT to the temp port, and set
		 * or unset PGHOST depending on whether we are using TCP or Unix
		 * sockets.
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
		 */
		unsetenv("PGDATABASE");
		unsetenv("PGUSER");
		unsetenv("PGSERVICE");
		unsetenv("PGSSLMODE");
		unsetenv("PGREQUIRESSL");
		unsetenv("PGCONNECT_TIMEOUT");
		unsetenv("PGDATA");
		if (hostname != NULL)
			doputenv("PGHOST", hostname);
		else
			unsetenv("PGHOST");
		unsetenv("PGHOSTADDR");
		if (port != -1)
		{
B
Bruce Momjian 已提交
761
			char		s[16];
762

B
Bruce Momjian 已提交
763 764
			sprintf(s, "%d", port);
			doputenv("PGPORT", s);
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
		}

		/*
		 * Adjust path variables to point into the temp-install tree
		 */
		tmp = malloc(strlen(temp_install) + 32 + strlen(bindir));
		sprintf(tmp, "%s/install/%s", temp_install, bindir);
		bindir = tmp;

		tmp = malloc(strlen(temp_install) + 32 + strlen(libdir));
		sprintf(tmp, "%s/install/%s", temp_install, libdir);
		libdir = tmp;

		tmp = malloc(strlen(temp_install) + 32 + strlen(datadir));
		sprintf(tmp, "%s/install/%s", temp_install, datadir);
		datadir = tmp;

782 783
		/* psql will be installed into temp-install bindir */
		psqldir = bindir;
B
Bruce Momjian 已提交
784

785 786 787 788
		/*
		 * Set up shared library paths to include the temp install.
		 *
		 * LD_LIBRARY_PATH covers many platforms.  DYLD_LIBRARY_PATH works on
B
Bruce Momjian 已提交
789
		 * Darwin, and maybe other Mach-based systems.	LIBPATH is for AIX.
790
		 * Windows needs shared libraries in PATH (only those linked into
B
Bruce Momjian 已提交
791 792
		 * executables, not dlopen'ed ones). Feel free to account for others
		 * as well.
793 794 795
		 */
		add_to_path("LD_LIBRARY_PATH", ':', libdir);
		add_to_path("DYLD_LIBRARY_PATH", ':', libdir);
796
		add_to_path("LIBPATH", ':', libdir);
797
#if defined(WIN32) || defined(__CYGWIN__)
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
		add_to_path("PATH", ';', libdir);
#endif
	}
	else
	{
		const char *pghost;
		const char *pgport;

		/*
		 * When testing an existing install, we honor existing environment
		 * variables, except if they're overridden by command line options.
		 */
		if (hostname != NULL)
		{
			doputenv("PGHOST", hostname);
			unsetenv("PGHOSTADDR");
		}
		if (port != -1)
		{
B
Bruce Momjian 已提交
817
			char		s[16];
818

B
Bruce Momjian 已提交
819 820
			sprintf(s, "%d", port);
			doputenv("PGPORT", s);
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
		}
		if (user != NULL)
			doputenv("PGUSER", user);

		/*
		 * Report what we're connecting to
		 */
		pghost = getenv("PGHOST");
		pgport = getenv("PGPORT");
#ifndef HAVE_UNIX_SOCKETS
		if (!pghost)
			pghost = "localhost";
#endif

		if (pghost && pgport)
			printf(_("(using postmaster on %s, port %s)\n"), pghost, pgport);
		if (pghost && !pgport)
			printf(_("(using postmaster on %s, default port)\n"), pghost);
		if (!pghost && pgport)
			printf(_("(using postmaster on Unix socket, port %s)\n"), pgport);
		if (!pghost && !pgport)
			printf(_("(using postmaster on Unix socket, default port)\n"));
	}

845
	convert_sourcefiles();
846 847 848 849 850 851 852 853 854
	load_resultmap();
}

/*
 * Issue a command via psql, connecting to the specified database
 *
 * Since we use system(), this doesn't return until the operation finishes
 */
static void
B
Bruce Momjian 已提交
855
psql_command(const char *database, const char *query,...)
856
{
B
Bruce Momjian 已提交
857 858 859 860 861 862
	char		query_formatted[1024];
	char		query_escaped[2048];
	char		psql_cmd[MAXPGPATH + 2048];
	va_list		args;
	char	   *s;
	char	   *d;
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

	/* Generate the query with insertion of sprintf arguments */
	va_start(args, query);
	vsnprintf(query_formatted, sizeof(query_formatted), query, args);
	va_end(args);

	/* Now escape any shell double-quote metacharacters */
	d = query_escaped;
	for (s = query_formatted; *s; s++)
	{
		if (strchr("\\\"$`", *s))
			*d++ = '\\';
		*d++ = *s;
	}
	*d = '\0';

	/* And now we can build and execute the shell command */
	snprintf(psql_cmd, sizeof(psql_cmd),
881 882 883 884 885
			 SYSTEMQUOTE "\"%s%spsql\" -X -c \"%s\" \"%s\"" SYSTEMQUOTE,
			 psqldir ? psqldir : "",
			 psqldir ? "/" : "",
			 query_escaped,
			 database);
886 887 888 889 890 891 892 893 894 895 896 897

	if (system(psql_cmd) != 0)
	{
		/* psql probably already reported the error */
		fprintf(stderr, _("command failed: %s\n"), psql_cmd);
		exit_nicely(2);
	}
}

/*
 * Spawn a process to execute the given shell command; don't wait for it
 *
898
 * Returns the process ID (or HANDLE) so we can wait for it later
899
 */
900
PID_TYPE
901 902 903
spawn_process(const char *cmdline)
{
#ifndef WIN32
B
Bruce Momjian 已提交
904
	pid_t		pid;
905 906

	/*
B
Bruce Momjian 已提交
907
	 * Must flush I/O buffers before fork.	Ideally we'd use fflush(NULL) here
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
	 * ... does anyone still care about systems where that doesn't work?
	 */
	fflush(stdout);
	fflush(stderr);
	if (logfile)
		fflush(logfile);

	pid = fork();
	if (pid == -1)
	{
		fprintf(stderr, _("%s: could not fork: %s\n"),
				progname, strerror(errno));
		exit_nicely(2);
	}
	if (pid == 0)
	{
924 925 926
		/*
		 * In child
		 *
B
Bruce Momjian 已提交
927 928 929
		 * Instead of using system(), exec the shell directly, and tell it to
		 * "exec" the command too.	This saves two useless processes per
		 * parallel test case.
930
		 */
B
Bruce Momjian 已提交
931
		char	   *cmdline2 = malloc(strlen(cmdline) + 6);
932 933

		sprintf(cmdline2, "exec %s", cmdline);
934
		execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
935 936 937
		fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
				progname, shellprog, strerror(errno));
		exit(1);				/* not exit_nicely here... */
938 939 940 941
	}
	/* in parent */
	return pid;
#else
B
Bruce Momjian 已提交
942
	char	   *cmdline2;
B
Bruce Momjian 已提交
943
	BOOL		b;
944 945
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
B
Bruce Momjian 已提交
946 947
	HANDLE		origToken;
	HANDLE		restrictedToken;
B
Bruce Momjian 已提交
948 949 950
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	SID_AND_ATTRIBUTES dropSids[2];
	__CreateRestrictedToken _CreateRestrictedToken = NULL;
B
Bruce Momjian 已提交
951
	HANDLE		Advapi32Handle;
952 953 954

	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
B
Bruce Momjian 已提交
955

B
Bruce Momjian 已提交
956 957 958
	Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
	if (Advapi32Handle != NULL)
	{
B
Bruce Momjian 已提交
959 960 961 962 963 964 965
		_CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
	}

	if (_CreateRestrictedToken == NULL)
	{
		if (Advapi32Handle != NULL)
			FreeLibrary(Advapi32Handle);
966 967
		fprintf(stderr, _("%s: cannot create restricted tokens on this platform\n"),
				progname);
B
Bruce Momjian 已提交
968 969 970 971 972 973
		exit_nicely(2);
	}

	/* Open the current token to use as base for the restricted one */
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
	{
974 975
		fprintf(stderr, _("could not open process token: %lu\n"),
				GetLastError());
B
Bruce Momjian 已提交
976 977
		exit_nicely(2);
	}
B
Bruce Momjian 已提交
978 979 980 981

	/* Allocate list of SIDs to remove */
	ZeroMemory(&dropSids, sizeof(dropSids));
	if (!AllocateAndInitializeSid(&NtAuthority, 2,
B
Bruce Momjian 已提交
982 983 984 985
								  SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &dropSids[0].Sid) ||
		!AllocateAndInitializeSid(&NtAuthority, 2,
								  SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_POWER_USERS, 0, 0, 0, 0, 0, 0, &dropSids[1].Sid))
	{
986
		fprintf(stderr, _("could not allocate SIDs: %lu\n"), GetLastError());
B
Bruce Momjian 已提交
987 988 989
		exit_nicely(2);
	}

B
Bruce Momjian 已提交
990
	b = _CreateRestrictedToken(origToken,
B
Bruce Momjian 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
							   DISABLE_MAX_PRIVILEGE,
							   sizeof(dropSids) / sizeof(dropSids[0]),
							   dropSids,
							   0, NULL,
							   0, NULL,
							   &restrictedToken);

	FreeSid(dropSids[1].Sid);
	FreeSid(dropSids[0].Sid);
	CloseHandle(origToken);
	FreeLibrary(Advapi32Handle);

	if (!b)
	{
1005 1006
		fprintf(stderr, _("could not create restricted token: %lu\n"),
				GetLastError());
B
Bruce Momjian 已提交
1007 1008
		exit_nicely(2);
	}
1009 1010 1011 1012

	cmdline2 = malloc(strlen(cmdline) + 8);
	sprintf(cmdline2, "cmd /c %s", cmdline);

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	if (!CreateProcessAsUser(restrictedToken,
						NULL,
						cmdline2,
						NULL,
						NULL,
						TRUE,
						CREATE_SUSPENDED,
						NULL,
						NULL,
						&si,
						&pi))
1024
	{
1025
		fprintf(stderr, _("could not start process for \"%s\": %lu\n"),
1026 1027 1028
				cmdline2, GetLastError());
		exit_nicely(2);
	}
1029 1030 1031 1032 1033

#ifndef __CYGWIN__
	AddUserToDacl(pi.hProcess);
#endif

1034 1035
	free(cmdline2);

1036
    ResumeThread(pi.hThread);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	CloseHandle(pi.hThread);
	return pi.hProcess;
#endif
}

/*
 * Count bytes in file
 */
static long
file_size(const char *file)
{
B
Bruce Momjian 已提交
1048 1049
	long		r;
	FILE	   *f = fopen(file, "r");
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

	if (!f)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, file, strerror(errno));
		return -1;
	}
	fseek(f, 0, SEEK_END);
	r = ftell(f);
	fclose(f);
	return r;
}

/*
 * Count lines in file
 */
static int
file_line_count(const char *file)
{
B
Bruce Momjian 已提交
1069 1070 1071
	int			c;
	int			l = 0;
	FILE	   *f = fopen(file, "r");
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

	if (!f)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, file, strerror(errno));
		return -1;
	}
	while ((c = fgetc(f)) != EOF)
	{
		if (c == '\n')
			l++;
	}
	fclose(f);
	return l;
}

1088
bool
1089 1090
file_exists(const char *file)
{
B
Bruce Momjian 已提交
1091
	FILE	   *f = fopen(file, "r");
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

	if (!f)
		return false;
	fclose(f);
	return true;
}

static bool
directory_exists(const char *dir)
{
	struct stat st;

	if (stat(dir, &st) != 0)
		return false;
1106
	if (S_ISDIR(st.st_mode))
1107 1108 1109 1110 1111 1112 1113 1114
		return true;
	return false;
}

/* Create a directory */
static void
make_directory(const char *dir)
{
1115
	if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) < 0)
1116 1117 1118 1119 1120 1121 1122
	{
		fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
				progname, dir, strerror(errno));
		exit_nicely(2);
	}
}

1123 1124 1125 1126 1127 1128
/*
 * In: filename.ext, Return: filename_i.ext, where 0 < i <= 9
 */
static char *
get_alternative_expectfile(const char *expectfile, int i)
{
B
Bruce Momjian 已提交
1129 1130 1131 1132 1133
	char	   *last_dot;
	int			ssize = strlen(expectfile) + 2 + 1;
	char	   *tmp = (char *) malloc(ssize);
	char	   *s = (char *) malloc(ssize);

1134
	strcpy(tmp, expectfile);
B
Bruce Momjian 已提交
1135
	last_dot = strrchr(tmp, '.');
1136
	if (!last_dot)
1137 1138 1139
	{
		free(tmp);
		free(s);
1140
		return NULL;
1141
	}
1142
	*last_dot = '\0';
B
Bruce Momjian 已提交
1143
	snprintf(s, ssize, "%s_%d.%s", tmp, i, last_dot + 1);
1144 1145 1146 1147
	free(tmp);
	return s;
}

1148
/*
1149
 * Run a "diff" command and also check that it didn't crash
1150
 */
1151 1152
static int
run_diff(const char *cmd, const char *filename)
1153
{
B
Bruce Momjian 已提交
1154
	int			r;
1155 1156 1157 1158 1159 1160 1161

	r = system(cmd);
	if (!WIFEXITED(r) || WEXITSTATUS(r) > 1)
	{
		fprintf(stderr, _("diff command failed with status %d: %s\n"), r, cmd);
		exit_nicely(2);
	}
1162
#ifdef WIN32
B
Bruce Momjian 已提交
1163

1164
	/*
B
Bruce Momjian 已提交
1165 1166
	 * On WIN32, if the 'diff' command cannot be found, system() returns 1,
	 * but produces nothing to stdout, so we check for that here.
1167 1168 1169 1170 1171 1172 1173
	 */
	if (WEXITSTATUS(r) == 1 && file_size(filename) <= 0)
	{
		fprintf(stderr, _("diff command not found: %s\n"), cmd);
		exit_nicely(2);
	}
#endif
B
Bruce Momjian 已提交
1174

1175
	return WEXITSTATUS(r);
1176 1177
}

1178 1179 1180 1181 1182 1183 1184
/*
 * Check the actual result file for the given test against expected results
 *
 * Returns true if different (failure), false if correct match found.
 * In the true case, the diff is appended to the diffs file.
 */
static bool
1185
results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)
1186
{
B
Bruce Momjian 已提交
1187 1188 1189 1190 1191 1192 1193 1194
	char		expectfile[MAXPGPATH];
	char		diff[MAXPGPATH];
	char		cmd[MAXPGPATH * 3];
	char		best_expect_file[MAXPGPATH];
	FILE	   *difffile;
	int			best_line_count;
	int			i;
	int			l;
1195
	const char *platform_expectfile;
B
Bruce Momjian 已提交
1196

1197
	/*
B
Bruce Momjian 已提交
1198 1199
	 * We can pass either the resultsfile or the expectfile, they should have
	 * the same type (filename.type) anyway.
1200 1201 1202 1203
	 */
	platform_expectfile = get_expectfile(testname, resultsfile);

	strcpy(expectfile, default_expectfile);
B
Bruce Momjian 已提交
1204
	if (platform_expectfile)
1205
	{
1206 1207 1208 1209
		/*
		 * Replace everything afer the last slash in expectfile with what the
		 * platform_expectfile contains.
		 */
B
Bruce Momjian 已提交
1210 1211
		char	   *p = strrchr(expectfile, '/');

1212 1213
		if (p)
			strcpy(++p, platform_expectfile);
1214 1215 1216
	}

	/* Name to use for temporary diff file */
1217
	snprintf(diff, sizeof(diff), "%s.diff", resultsfile);
1218 1219 1220

	/* OK, run the diff */
	snprintf(cmd, sizeof(cmd),
1221
			 SYSTEMQUOTE "diff %s \"%s\" \"%s\" > \"%s\"" SYSTEMQUOTE,
1222 1223 1224
			 basic_diff_opts, expectfile, resultsfile, diff);

	/* Is the diff file empty? */
1225
	if (run_diff(cmd, diff) == 0)
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
	{
		unlink(diff);
		return false;
	}

	/* There may be secondary comparison files that match better */
	best_line_count = file_line_count(diff);
	strcpy(best_expect_file, expectfile);

	for (i = 0; i <= 9; i++)
	{
B
Bruce Momjian 已提交
1237
		char	   *alt_expectfile;
1238 1239 1240

		alt_expectfile = get_alternative_expectfile(expectfile, i);
		if (!file_exists(alt_expectfile))
1241 1242 1243
			continue;

		snprintf(cmd, sizeof(cmd),
1244
				 SYSTEMQUOTE "diff %s \"%s\" \"%s\" > \"%s\"" SYSTEMQUOTE,
1245
				 basic_diff_opts, alt_expectfile, resultsfile, diff);
1246

1247
		if (run_diff(cmd, diff) == 0)
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
		{
			unlink(diff);
			return false;
		}

		l = file_line_count(diff);
		if (l < best_line_count)
		{
			/* This diff was a better match than the last one */
			best_line_count = l;
1258
			strcpy(best_expect_file, alt_expectfile);
1259
		}
1260
		free(alt_expectfile);
1261 1262
	}

B
Bruce Momjian 已提交
1263 1264 1265
	/*
	 * fall back on the canonical results file if we haven't tried it yet and
	 * haven't found a complete match yet.
A
 
Andrew Dunstan 已提交
1266 1267
	 */

1268
	if (platform_expectfile)
A
 
Andrew Dunstan 已提交
1269 1270 1271
	{
		snprintf(cmd, sizeof(cmd),
				 SYSTEMQUOTE "diff %s \"%s\" \"%s\" > \"%s\"" SYSTEMQUOTE,
1272
				 basic_diff_opts, default_expectfile, resultsfile, diff);
A
 
Andrew Dunstan 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

		if (run_diff(cmd, diff) == 0)
		{
			/* No diff = no changes = good */
			unlink(diff);
			return false;
		}

		l = file_line_count(diff);
		if (l < best_line_count)
		{
			/* This diff was a better match than the last one */
			best_line_count = l;
1286
			strcpy(best_expect_file, default_expectfile);
A
 
Andrew Dunstan 已提交
1287 1288 1289
		}
	}

1290
	/*
B
Bruce Momjian 已提交
1291 1292
	 * Use the best comparison file to generate the "pretty" diff, which we
	 * append to the diffs summary file.
1293 1294
	 */
	snprintf(cmd, sizeof(cmd),
1295
			 SYSTEMQUOTE "diff %s \"%s\" \"%s\" >> \"%s\"" SYSTEMQUOTE,
1296
			 pretty_diff_opts, best_expect_file, resultsfile, difffilename);
1297
	run_diff(cmd, difffilename);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

	/* And append a separator */
	difffile = fopen(difffilename, "a");
	if (difffile)
	{
		fprintf(difffile,
				"\n======================================================================\n\n");
		fclose(difffile);
	}

	unlink(diff);
	return true;
}

/*
1313 1314
 * Wait for specified subprocesses to finish, and return their exit
 * statuses into statuses[]
1315
 *
1316
 * If names isn't NULL, print each subprocess's name as it finishes
1317 1318
 *
 * Note: it's OK to scribble on the pids array, but not on the names array
1319 1320
 */
static void
1321
wait_for_tests(PID_TYPE *pids, int *statuses, char **names, int num_tests)
1322
{
B
Bruce Momjian 已提交
1323 1324
	int			tests_left;
	int			i;
1325

1326
#ifdef WIN32
B
Bruce Momjian 已提交
1327
	PID_TYPE   *active_pids = malloc(num_tests * sizeof(PID_TYPE));
1328 1329 1330 1331

	memcpy(active_pids, pids, num_tests * sizeof(PID_TYPE));
#endif

1332 1333 1334
	tests_left = num_tests;
	while (tests_left > 0)
	{
B
Bruce Momjian 已提交
1335
		PID_TYPE	p;
1336
		int			exit_status;
1337 1338

#ifndef WIN32
1339
		p = wait(&exit_status);
1340 1341 1342 1343 1344 1345 1346 1347

		if (p == INVALID_PID)
		{
			fprintf(stderr, _("failed to wait for subprocesses: %s\n"),
					strerror(errno));
			exit_nicely(2);
		}
#else
B
Bruce Momjian 已提交
1348
		int			r;
1349

1350 1351
		r = WaitForMultipleObjects(tests_left, active_pids, FALSE, INFINITE);
		if (r < WAIT_OBJECT_0 || r >= WAIT_OBJECT_0 + tests_left)
1352
		{
1353 1354
			fprintf(stderr, _("failed to wait for subprocesses: %lu\n"),
					GetLastError());
1355 1356
			exit_nicely(2);
		}
1357 1358 1359
		p = active_pids[r - WAIT_OBJECT_0];
		/* compact the active_pids array */
		active_pids[r - WAIT_OBJECT_0] = active_pids[tests_left - 1];
B
Bruce Momjian 已提交
1360
#endif   /* WIN32 */
1361

B
Bruce Momjian 已提交
1362
		for (i = 0; i < num_tests; i++)
1363 1364 1365
		{
			if (p == pids[i])
			{
1366
#ifdef WIN32
1367
				GetExitCodeProcess(pids[i], (LPDWORD) &exit_status);
1368 1369 1370
				CloseHandle(pids[i]);
#endif
				pids[i] = INVALID_PID;
1371
				statuses[i] = exit_status;
1372 1373
				if (names)
					status(" %s", names[i]);
1374
				tests_left--;
1375
				break;
1376 1377 1378 1379
			}
		}
	}

1380 1381
#ifdef WIN32
	free(active_pids);
1382 1383 1384
#endif
}

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
/*
 * report nonzero exit code from a test process
 */
static void
log_child_failure(int exitstatus)
{
	if (WIFEXITED(exitstatus))
		status(_(" (test process exited with exit code %d)"),
			   WEXITSTATUS(exitstatus));
	else if (WIFSIGNALED(exitstatus))
	{
#if defined(WIN32)
		status(_(" (test process was terminated by exception 0x%X)"),
			   WTERMSIG(exitstatus));
#elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
		status(_(" (test process was terminated by signal %d: %s)"),
			   WTERMSIG(exitstatus),
			   WTERMSIG(exitstatus) < NSIG ?
			   sys_siglist[WTERMSIG(exitstatus)] : "(unknown))");
#else
		status(_(" (test process was terminated by signal %d)"),
			   WTERMSIG(exitstatus));
#endif
	}
	else
		status(_(" (test process exited with unrecognized status %d)"),
			   exitstatus);
}

1414 1415 1416 1417
/*
 * Run all the tests specified in one schedule file
 */
static void
1418
run_schedule(const char *schedule, test_function tfunc)
1419 1420
{
#define MAX_PARALLEL_TESTS 100
B
Bruce Momjian 已提交
1421
	char	   *tests[MAX_PARALLEL_TESTS];
1422 1423 1424
	_stringlist *resultfiles[MAX_PARALLEL_TESTS];
	_stringlist *expectfiles[MAX_PARALLEL_TESTS];
	_stringlist *tags[MAX_PARALLEL_TESTS];
B
Bruce Momjian 已提交
1425
	PID_TYPE	pids[MAX_PARALLEL_TESTS];
1426
	int			statuses[MAX_PARALLEL_TESTS];
1427
	_stringlist *ignorelist = NULL;
B
Bruce Momjian 已提交
1428 1429 1430
	char		scbuf[1024];
	FILE	   *scf;
	int			line_num = 0;
1431

B
Bruce Momjian 已提交
1432 1433 1434
	memset(resultfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
	memset(expectfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
	memset(tags, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
1435

1436 1437 1438 1439 1440 1441 1442 1443
	scf = fopen(schedule, "r");
	if (!scf)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, schedule, strerror(errno));
		exit_nicely(2);
	}

1444
	while (fgets(scbuf, sizeof(scbuf), scf))
1445
	{
B
Bruce Momjian 已提交
1446 1447 1448 1449 1450
		char	   *test = NULL;
		char	   *c;
		int			num_tests;
		bool		inword;
		int			i;
1451 1452 1453

		line_num++;

1454 1455 1456 1457 1458 1459 1460 1461 1462
		for (i = 0; i < MAX_PARALLEL_TESTS; i++)
		{
			if (resultfiles[i] == NULL)
				break;
			free_stringlist(&resultfiles[i]);
			free_stringlist(&expectfiles[i]);
			free_stringlist(&tags[i]);
		}

1463 1464
		/* strip trailing whitespace, especially the newline */
		i = strlen(scbuf);
B
Bruce Momjian 已提交
1465
		while (i > 0 && isspace((unsigned char) scbuf[i - 1]))
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
			scbuf[--i] = '\0';

		if (scbuf[0] == '\0' || scbuf[0] == '#')
			continue;
		if (strncmp(scbuf, "test: ", 6) == 0)
			test = scbuf + 6;
		else if (strncmp(scbuf, "ignore: ", 8) == 0)
		{
			c = scbuf + 8;
			while (*c && isspace((unsigned char) *c))
				c++;
			add_stringlist_item(&ignorelist, c);
B
Bruce Momjian 已提交
1478

1479 1480
			/*
			 * Note: ignore: lines do not run the test, they just say that
B
Bruce Momjian 已提交
1481 1482
			 * failure of this test when run later on is to be ignored. A bit
			 * odd but that's how the shell-script version did it.
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
			 */
			continue;
		}
		else
		{
			fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
					schedule, line_num, scbuf);
			exit_nicely(2);
		}

		num_tests = 0;
		inword = false;
		for (c = test; *c; c++)
		{
			if (isspace((unsigned char) *c))
			{
				*c = '\0';
				inword = false;
			}
			else if (!inword)
			{
				if (num_tests >= MAX_PARALLEL_TESTS)
				{
					/* can't print scbuf here, it's already been trashed */
					fprintf(stderr, _("too many parallel tests in schedule file \"%s\", line %d\n"),
							schedule, line_num);
					exit_nicely(2);
				}
				tests[num_tests] = c;
				num_tests++;
				inword = true;
			}
		}

		if (num_tests == 0)
		{
			fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
					schedule, line_num, scbuf);
			exit_nicely(2);
		}

		if (num_tests == 1)
		{
			status(_("test %-20s ... "), tests[0]);
B
Bruce Momjian 已提交
1527
			pids[0] = (tfunc) (tests[0], &resultfiles[0], &expectfiles[0], &tags[0]);
1528
			wait_for_tests(pids, statuses, NULL, 1);
1529 1530 1531 1532
			/* status line is finished below */
		}
		else if (max_connections > 0 && max_connections < num_tests)
		{
B
Bruce Momjian 已提交
1533
			int			oldest = 0;
1534 1535 1536 1537 1538 1539 1540

			status(_("parallel group (%d tests, in groups of %d): "),
				   num_tests, max_connections);
			for (i = 0; i < num_tests; i++)
			{
				if (i - oldest >= max_connections)
				{
1541 1542
					wait_for_tests(pids + oldest, statuses + oldest,
								   tests + oldest, i - oldest);
1543 1544
					oldest = i;
				}
B
Bruce Momjian 已提交
1545
				pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1546
			}
1547 1548
			wait_for_tests(pids + oldest, statuses + oldest,
						   tests + oldest, i - oldest);
1549 1550 1551 1552 1553 1554 1555
			status_end();
		}
		else
		{
			status(_("parallel group (%d tests): "), num_tests);
			for (i = 0; i < num_tests; i++)
			{
B
Bruce Momjian 已提交
1556
				pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1557
			}
1558
			wait_for_tests(pids, statuses, tests, num_tests);
1559 1560 1561 1562 1563 1564
			status_end();
		}

		/* Check results for all tests */
		for (i = 0; i < num_tests; i++)
		{
B
Bruce Momjian 已提交
1565 1566 1567 1568
			_stringlist *rl,
					   *el,
					   *tl;
			bool		differ = false;
1569

1570 1571 1572
			if (num_tests > 1)
				status(_("     %-20s ... "), tests[i]);

1573 1574 1575
			/*
			 * Advance over all three lists simultaneously.
			 *
B
Bruce Momjian 已提交
1576 1577 1578
			 * Compare resultfiles[j] with expectfiles[j] always. Tags are
			 * optional but if there are tags, the tag list has the same
			 * length as the other two lists.
1579 1580
			 */
			for (rl = resultfiles[i], el = expectfiles[i], tl = tags[i];
B
Bruce Momjian 已提交
1581 1582
				 rl != NULL;	/* rl and el have the same length */
				 rl = rl->next, el = el->next)
1583
			{
B
Bruce Momjian 已提交
1584 1585
				bool		newdiff;

1586
				if (tl)
1587
					tl = tl->next;		/* tl has the same length as rl and el
B
Bruce Momjian 已提交
1588
										 * if it exists */
1589 1590

				newdiff = results_differ(tests[i], rl->str, el->str);
B
Bruce Momjian 已提交
1591
				if (newdiff && tl)
1592 1593 1594 1595 1596 1597 1598
				{
					printf("%s ", tl->str);
				}
				differ |= newdiff;
			}

			if (differ)
1599
			{
B
Bruce Momjian 已提交
1600
				bool		ignore = false;
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
				_stringlist *sl;

				for (sl = ignorelist; sl != NULL; sl = sl->next)
				{
					if (strcmp(tests[i], sl->str) == 0)
					{
						ignore = true;
						break;
					}
				}
				if (ignore)
				{
					status(_("failed (ignored)"));
					fail_ignore_count++;
				}
				else
				{
					status(_("FAILED"));
					fail_count++;
				}
			}
			else
			{
				status(_("ok"));
				success_count++;
			}

1628 1629 1630
			if (statuses[i] != 0)
				log_child_failure(statuses[i]);

1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
			status_end();
		}
	}

	fclose(scf);
}

/*
 * Run a single test
 */
static void
1642
run_single_test(const char *test, test_function tfunc)
1643
{
B
Bruce Momjian 已提交
1644
	PID_TYPE	pid;
1645
	int			exit_status;
1646 1647 1648
	_stringlist *resultfiles = NULL;
	_stringlist *expectfiles = NULL;
	_stringlist *tags = NULL;
B
Bruce Momjian 已提交
1649 1650 1651
	_stringlist *rl,
			   *el,
			   *tl;
1652
	bool		differ = false;
1653 1654

	status(_("test %-20s ... "), test);
B
Bruce Momjian 已提交
1655
	pid = (tfunc) (test, &resultfiles, &expectfiles, &tags);
1656
	wait_for_tests(&pid, &exit_status, NULL, 1);
1657

1658 1659 1660
	/*
	 * Advance over all three lists simultaneously.
	 *
B
Bruce Momjian 已提交
1661 1662 1663
	 * Compare resultfiles[j] with expectfiles[j] always. Tags are optional
	 * but if there are tags, the tag list has the same length as the other
	 * two lists.
1664 1665
	 */
	for (rl = resultfiles, el = expectfiles, tl = tags;
B
Bruce Momjian 已提交
1666 1667
		 rl != NULL;			/* rl and el have the same length */
		 rl = rl->next, el = el->next)
1668
	{
B
Bruce Momjian 已提交
1669 1670
		bool		newdiff;

1671
		if (tl)
1672
			tl = tl->next;		/* tl has the same length as rl and el if it
B
Bruce Momjian 已提交
1673
								 * exists */
1674 1675

		newdiff = results_differ(test, rl->str, el->str);
B
Bruce Momjian 已提交
1676
		if (newdiff && tl)
1677 1678 1679 1680 1681 1682 1683
		{
			printf("%s ", tl->str);
		}
		differ |= newdiff;
	}

	if (differ)
1684 1685 1686 1687 1688 1689 1690 1691 1692
	{
		status(_("FAILED"));
		fail_count++;
	}
	else
	{
		status(_("ok"));
		success_count++;
	}
1693 1694 1695 1696

	if (exit_status != 0)
		log_child_failure(exit_status);

1697 1698 1699 1700 1701 1702 1703 1704 1705
	status_end();
}

/*
 * Create the summary-output files (making them empty if already existing)
 */
static void
open_result_files(void)
{
B
Bruce Momjian 已提交
1706 1707
	char		file[MAXPGPATH];
	FILE	   *difffile;
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738

	/* create the log file (copy of running status output) */
	snprintf(file, sizeof(file), "%s/regression.out", outputdir);
	logfilename = strdup(file);
	logfile = fopen(logfilename, "w");
	if (!logfile)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, logfilename, strerror(errno));
		exit_nicely(2);
	}

	/* create the diffs file as empty */
	snprintf(file, sizeof(file), "%s/regression.diffs", outputdir);
	difffilename = strdup(file);
	difffile = fopen(difffilename, "w");
	if (!difffile)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
				progname, difffilename, strerror(errno));
		exit_nicely(2);
	}
	/* we don't keep the diffs file open continuously */
	fclose(difffile);

	/* also create the output directory if not present */
	snprintf(file, sizeof(file), "%s/results", outputdir);
	if (!directory_exists(file))
		make_directory(file);
}

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
static void
drop_database_if_exists(const char *dbname)
{
	header(_("dropping database \"%s\""), dbname);
	psql_command("postgres", "DROP DATABASE IF EXISTS \"%s\"", dbname);
}

static void
create_database(const char *dbname)
{
	_stringlist *sl;
B
Bruce Momjian 已提交
1750

1751 1752 1753 1754 1755 1756 1757 1758 1759
	/*
	 * We use template0 so that any installation-local cruft in template1 will
	 * not mess up the tests.
	 */
	header(_("creating database \"%s\""), dbname);
	if (encoding)
		psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0 ENCODING='%s'", dbname, encoding);
	else
		psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0", dbname);
B
Bruce Momjian 已提交
1760 1761 1762 1763 1764 1765 1766
	psql_command(dbname,
				 "ALTER DATABASE \"%s\" SET lc_messages TO 'C';"
				 "ALTER DATABASE \"%s\" SET lc_monetary TO 'C';"
				 "ALTER DATABASE \"%s\" SET lc_numeric TO 'C';"
				 "ALTER DATABASE \"%s\" SET lc_time TO 'C';"
			"ALTER DATABASE \"%s\" SET timezone_abbreviations TO 'Default';",
				 dbname, dbname, dbname, dbname, dbname);
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785

	/*
	 * Install any requested procedural languages
	 */
	for (sl = loadlanguage; sl != NULL; sl = sl->next)
	{
		header(_("installing %s"), sl->str);
		psql_command(dbname, "CREATE LANGUAGE \"%s\"", sl->str);
	}
}

static void
drop_role_if_exists(const char *rolename)
{
	header(_("dropping role \"%s\""), rolename);
	psql_command("postgres", "DROP ROLE IF EXISTS \"%s\"", rolename);
}

static void
B
Bruce Momjian 已提交
1786
create_role(const char *rolename, const _stringlist * granted_dbs)
1787 1788 1789 1790 1791 1792
{
	header(_("creating role \"%s\""), rolename);
	psql_command("postgres", "CREATE ROLE \"%s\" WITH LOGIN", rolename);
	for (; granted_dbs != NULL; granted_dbs = granted_dbs->next)
	{
		psql_command("postgres", "GRANT ALL ON DATABASE \"%s\" TO \"%s\"",
B
Bruce Momjian 已提交
1793
					 granted_dbs->str, rolename);
1794 1795 1796
	}
}

1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
static char *
make_absolute_path(const char *in)
{
	char *result;

	if (is_absolute_path(in))
		result = strdup(in);
	else
	{
		static char		cwdbuf[MAXPGPATH];

		if (!cwdbuf[0])
		{
			if (!getcwd(cwdbuf, sizeof(cwdbuf)))
			{
				fprintf(stderr, _("could not get current working directory: %s\n"), strerror(errno));
				exit_nicely(2);
			}
		}

		result = malloc(strlen(cwdbuf) + strlen(in) + 2);
		sprintf(result, "%s/%s", cwdbuf, in);
	}

	canonicalize_path(result);
	return result;
}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
static void
help(void)
{
	printf(_("PostgreSQL regression test driver\n"));
	printf(_("\n"));
	printf(_("Usage: %s [options...] [extra tests...]\n"), progname);
	printf(_("\n"));
	printf(_("Options:\n"));
	printf(_("  --dbname=DB               use database DB (default \"regression\")\n"));
	printf(_("  --debug                   turn on debug mode in programs that are run\n"));
	printf(_("  --inputdir=DIR            take input files from DIR (default \".\")\n"));
	printf(_("  --load-language=lang      load the named language before running the\n"));
	printf(_("                            tests; can appear multiple times\n"));
1838
	printf(_("  --create-role=ROLE        create the specified role before testing\n"));
1839 1840 1841 1842 1843
	printf(_("  --max-connections=N       maximum number of concurrent connections\n"));
	printf(_("                            (default is 0 meaning unlimited)\n"));
	printf(_("  --multibyte=ENCODING      use ENCODING as the multibyte encoding\n"));
	printf(_("  --outputdir=DIR           place output files in DIR (default \".\")\n"));
	printf(_("  --schedule=FILE           use test ordering schedule from FILE\n"));
1844
	printf(_("                            (can be used multiple times to concatenate)\n"));
1845
	printf(_("  --dlpath=DIR              look for dynamic libraries in DIR\n"));
1846 1847 1848
	printf(_("  --temp-install=DIR        create a temporary installation in DIR\n"));
	printf(_("\n"));
	printf(_("Options for \"temp-install\" mode:\n"));
1849
	printf(_("  --no-locale               use C locale\n"));
1850
	printf(_("  --top-builddir=DIR        (relative) path to top level build directory\n"));
1851
	printf(_("  --port=PORT               start postmaster on PORT\n"));
1852
	printf(_("  --temp-config=PATH        append contents of PATH to temporary config\n"));
1853 1854 1855 1856 1857
	printf(_("\n"));
	printf(_("Options for using an existing installation:\n"));
	printf(_("  --host=HOST               use postmaster running on HOST\n"));
	printf(_("  --port=PORT               use postmaster running at PORT\n"));
	printf(_("  --user=USER               connect as USER\n"));
1858
	printf(_("  --psqldir=DIR             use psql in DIR (default: find in PATH)\n"));
1859 1860 1861 1862 1863 1864 1865 1866
	printf(_("\n"));
	printf(_("The exit status is 0 if all tests passed, 1 if some tests failed, and 2\n"));
	printf(_("if the tests could not be run for some reason.\n"));
	printf(_("\n"));
	printf(_("Report bugs to <pgsql-bugs@postgresql.org>.\n"));
}

int
1867
regression_main(int argc, char *argv[], init_function ifunc, test_function tfunc)
1868 1869
{
	_stringlist *sl;
B
Bruce Momjian 已提交
1870 1871 1872 1873
	int			c;
	int			i;
	int			option_index;
	char		buf[MAXPGPATH * 4];
1874
	char		buf2[MAXPGPATH * 4];
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892

	static struct option long_options[] = {
		{"help", no_argument, NULL, 'h'},
		{"version", no_argument, NULL, 'V'},
		{"dbname", required_argument, NULL, 1},
		{"debug", no_argument, NULL, 2},
		{"inputdir", required_argument, NULL, 3},
		{"load-language", required_argument, NULL, 4},
		{"max-connections", required_argument, NULL, 5},
		{"multibyte", required_argument, NULL, 6},
		{"outputdir", required_argument, NULL, 7},
		{"schedule", required_argument, NULL, 8},
		{"temp-install", required_argument, NULL, 9},
		{"no-locale", no_argument, NULL, 10},
		{"top-builddir", required_argument, NULL, 11},
		{"host", required_argument, NULL, 13},
		{"port", required_argument, NULL, 14},
		{"user", required_argument, NULL, 15},
1893
		{"psqldir", required_argument, NULL, 16},
1894
		{"dlpath", required_argument, NULL, 17},
1895
		{"create-role", required_argument, NULL, 18},
1896
		{"temp-config", required_argument, NULL, 19},
1897 1898 1899 1900
		{NULL, 0, NULL, 0}
	};

	progname = get_progname(argv[0]);
1901
	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_regress"));
1902 1903 1904 1905 1906 1907

#ifndef HAVE_UNIX_SOCKETS
	/* no unix domain sockets available, so change default */
	hostname = "localhost";
#endif

1908 1909 1910 1911 1912 1913
	/*
	 * We call the initialization function here because that way we can set
	 * default parameters and let them be overwritten by the commandline.
	 */
	ifunc();

1914 1915 1916 1917 1918 1919 1920 1921
	while ((c = getopt_long(argc, argv, "hV", long_options, &option_index)) != -1)
	{
		switch (c)
		{
			case 'h':
				help();
				exit_nicely(0);
			case 'V':
1922
				puts("pg_regress (PostgreSQL) " PG_VERSION);
1923 1924
				exit_nicely(0);
			case 1:
B
Bruce Momjian 已提交
1925 1926 1927 1928

				/*
				 * If a default database was specified, we need to remove it
				 * before we add the specified one.
1929 1930
				 */
				free_stringlist(&dblist);
1931
				split_to_stringlist(strdup(optarg), ", ", &dblist);
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
				break;
			case 2:
				debug = true;
				break;
			case 3:
				inputdir = strdup(optarg);
				break;
			case 4:
				add_stringlist_item(&loadlanguage, optarg);
				break;
			case 5:
				max_connections = atoi(optarg);
				break;
			case 6:
				encoding = strdup(optarg);
				break;
			case 7:
				outputdir = strdup(optarg);
				break;
			case 8:
				add_stringlist_item(&schedulelist, optarg);
				break;
			case 9:
1955
				temp_install = make_absolute_path(optarg);
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
				break;
			case 10:
				nolocale = true;
				break;
			case 11:
				top_builddir = strdup(optarg);
				break;
			case 13:
				hostname = strdup(optarg);
				break;
			case 14:
				port = atoi(optarg);
1968
				port_specified_by_user = true;
1969 1970 1971 1972
				break;
			case 15:
				user = strdup(optarg);
				break;
1973 1974 1975 1976 1977
			case 16:
				/* "--psqldir=" should mean to use PATH */
				if (strlen(optarg))
					psqldir = strdup(optarg);
				break;
1978
			case 17:
1979
				dlpath = strdup(optarg);
1980
				break;
1981 1982 1983
			case 18:
				split_to_stringlist(strdup(optarg), ", ", &extraroles);
				break;
1984 1985 1986
			case 19:
				temp_config = strdup(optarg);
				break;
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
			default:
				/* getopt_long already emitted a complaint */
				fprintf(stderr, _("\nTry \"%s -h\" for more information.\n"),
						progname);
				exit_nicely(2);
		}
	}

	/*
	 * if we still have arguments, they are extra tests to run
	 */
	while (argc - optind >= 1)
	{
		add_stringlist_item(&extra_tests, argv[optind]);
		optind++;
	}

2004 2005 2006 2007 2008 2009 2010
	if (temp_install && !port_specified_by_user)
		/*
		 * To reduce chances of interference with parallel
		 * installations, use a port number starting in the private
		 * range (49152-65535) calculated from the version number.
		 */
		port = 0xC000 | (PG_VERSION_NUM & 0x3FFF);
2011

2012 2013 2014 2015
	inputdir = make_absolute_path(inputdir);
	outputdir = make_absolute_path(outputdir);
	dlpath = make_absolute_path(dlpath);

2016 2017 2018 2019 2020 2021 2022
	/*
	 * Initialization
	 */
	open_result_files();

	initialize_environment();

A
 
Andrew Dunstan 已提交
2023 2024 2025 2026
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
	unlimit_core_size();
#endif

2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
	if (temp_install)
	{
		/*
		 * Prepare the temp installation
		 */
		if (!top_builddir)
		{
			fprintf(stderr, _("--top-builddir must be specified when using --temp-install\n"));
			exit_nicely(2);
		}

		if (directory_exists(temp_install))
		{
			header(_("removing existing temp installation"));
B
Bruce Momjian 已提交
2041
			rmtree(temp_install, true);
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
		}

		header(_("creating temporary installation"));

		/* make the temp install top directory */
		make_directory(temp_install);

		/* and a directory for log files */
		snprintf(buf, sizeof(buf), "%s/log", outputdir);
		if (!directory_exists(buf))
			make_directory(buf);

		/* "make install" */
B
Bruce Momjian 已提交
2055
#ifndef WIN32_ONLY_COMPILER
2056
		snprintf(buf, sizeof(buf),
2057
				 SYSTEMQUOTE "\"%s\" -C \"%s\" DESTDIR=\"%s/install\" install with_perl=no with_python=no > \"%s/log/install.log\" 2>&1" SYSTEMQUOTE,
2058
				 makeprog, top_builddir, temp_install, outputdir);
B
Bruce Momjian 已提交
2059
#else
B
Bruce Momjian 已提交
2060 2061 2062
		snprintf(buf, sizeof(buf),
				 SYSTEMQUOTE "perl \"%s/src/tools/msvc/install.pl\" \"%s/install\" >\"%s/log/install.log\" 2>&1" SYSTEMQUOTE,
				 top_builddir, temp_install, outputdir);
B
Bruce Momjian 已提交
2063
#endif
2064 2065
		if (system(buf))
		{
2066
			fprintf(stderr, _("\n%s: installation failed\nExamine %s/log/install.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2067 2068 2069 2070 2071 2072
			exit_nicely(2);
		}

		/* initdb */
		header(_("initializing database system"));
		snprintf(buf, sizeof(buf),
2073
				 SYSTEMQUOTE "\"%s/initdb\" -D \"%s/data\" -L \"%s\" --noclean%s%s > \"%s/log/initdb.log\" 2>&1" SYSTEMQUOTE,
2074
				 bindir, temp_install, datadir,
2075 2076
				 debug ? " --debug" : "",
				 nolocale ? " --no-locale" : "",
2077 2078 2079
				 outputdir);
		if (system(buf))
		{
2080
			fprintf(stderr, _("\n%s: initdb failed\nExamine %s/log/initdb.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2081 2082 2083
			exit_nicely(2);
		}

2084 2085 2086
		/* add any extra config specified to the postgresql.conf */
		if (temp_config != NULL)
		{
B
Bruce Momjian 已提交
2087 2088 2089
			FILE	   *extra_conf;
			FILE	   *pg_conf;
			char		line_buf[1024];
2090

B
Bruce Momjian 已提交
2091 2092
			snprintf(buf, sizeof(buf), "%s/data/postgresql.conf", temp_install);
			pg_conf = fopen(buf, "a");
2093 2094
			if (pg_conf == NULL)
			{
2095
				fprintf(stderr, _("\n%s: could not open \"%s\" for adding extra config: %s\n"), progname, buf, strerror(errno));
B
Bruce Momjian 已提交
2096
				exit_nicely(2);
2097
			}
B
Bruce Momjian 已提交
2098
			extra_conf = fopen(temp_config, "r");
2099 2100
			if (extra_conf == NULL)
			{
2101
				fprintf(stderr, _("\n%s: could not open \"%s\" to read extra config: %s\n"), progname, temp_config, strerror(errno));
B
Bruce Momjian 已提交
2102
				exit_nicely(2);
2103
			}
B
Bruce Momjian 已提交
2104
			while (fgets(line_buf, sizeof(line_buf), extra_conf) != NULL)
2105 2106 2107 2108 2109
				fputs(line_buf, pg_conf);
			fclose(extra_conf);
			fclose(pg_conf);
		}

2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
		/*
		 * Check if there is a postmaster running already.
		 */
		snprintf(buf2, sizeof(buf2),
				 SYSTEMQUOTE "\"%s/psql\" -X postgres <%s 2>%s" SYSTEMQUOTE,
				 bindir, DEVNULL, DEVNULL);

		for (i = 0; i < 16; i++)
		{
			if (system(buf2) == 0)
			{
				char		s[16];

				if (port_specified_by_user || i == 15)
				{
					fprintf(stderr, _("port %d apparently in use\n"), port);
					if (!port_specified_by_user)
						fprintf(stderr, _("%s: could not determine an available port\n"), progname);
					fprintf(stderr, _("Specify an unused port using the --port option or shut down any conflicting PostgreSQL servers.\n"));
					exit_nicely(2);
				}

				fprintf(stderr, _("port %d apparently in use, trying %d\n"), port, port+1);
				port++;
				sprintf(s, "%d", port);
				doputenv("PGPORT", s);
			}
			else
				break;
		}

2141 2142 2143 2144 2145
		/*
		 * Start the temp postmaster
		 */
		header(_("starting postmaster"));
		snprintf(buf, sizeof(buf),
2146
				 SYSTEMQUOTE "\"%s/postgres\" -D \"%s/data\" -F%s -c \"listen_addresses=%s\" > \"%s/log/postmaster.log\" 2>&1" SYSTEMQUOTE,
2147
				 bindir, temp_install,
2148
				 debug ? " -d 5" : "",
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
				 hostname ? hostname : "",
				 outputdir);
		postmaster_pid = spawn_process(buf);
		if (postmaster_pid == INVALID_PID)
		{
			fprintf(stderr, _("\n%s: could not spawn postmaster: %s\n"),
					progname, strerror(errno));
			exit_nicely(2);
		}

		/*
B
Bruce Momjian 已提交
2160 2161 2162
		 * Wait till postmaster is able to accept connections (normally only a
		 * second or so, but Cygwin is reportedly *much* slower).  Don't wait
		 * forever, however.
2163 2164 2165 2166
		 */
		for (i = 0; i < 60; i++)
		{
			/* Done if psql succeeds */
2167
			if (system(buf2) == 0)
2168 2169 2170 2171 2172 2173 2174
				break;

			/*
			 * Fail immediately if postmaster has exited
			 */
#ifndef WIN32
			if (kill(postmaster_pid, 0) != 0)
2175 2176 2177
#else
			if (WaitForSingleObject(postmaster_pid, 0) == WAIT_OBJECT_0)
#endif
2178 2179 2180 2181 2182 2183 2184
			{
				fprintf(stderr, _("\n%s: postmaster failed\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);
				exit_nicely(2);
			}

			pg_usleep(1000000L);
		}
2185
		if (i >= 60)
2186
		{
2187 2188 2189
			fprintf(stderr, _("\n%s: postmaster did not respond within 60 seconds\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);

			/*
B
Bruce Momjian 已提交
2190 2191 2192
			 * If we get here, the postmaster is probably wedged somewhere in
			 * startup.  Try to kill it ungracefully rather than leaving a
			 * stuck postmaster that might interfere with subsequent test
2193 2194 2195 2196 2197 2198 2199
			 * attempts.
			 */
#ifndef WIN32
			if (kill(postmaster_pid, SIGKILL) != 0 &&
				errno != ESRCH)
				fprintf(stderr, _("\n%s: could not kill failed postmaster: %s\n"),
						progname, strerror(errno));
2200 2201 2202 2203
#else
			if (TerminateProcess(postmaster_pid, 255) == 0)
				fprintf(stderr, _("\n%s: could not kill failed postmaster: %lu\n"),
						progname, GetLastError());
2204 2205
#endif

2206 2207 2208 2209 2210 2211
			exit_nicely(2);
		}

		postmaster_running = true;

		printf(_("running on port %d with pid %lu\n"),
2212
			   port, (unsigned long) postmaster_pid);
2213 2214 2215 2216 2217
	}
	else
	{
		/*
		 * Using an existing installation, so may need to get rid of
2218
		 * pre-existing database(s) and role(s)
2219
		 */
2220 2221 2222 2223
		for (sl = dblist; sl; sl = sl->next)
			drop_database_if_exists(sl->str);
		for (sl = extraroles; sl; sl = sl->next)
			drop_role_if_exists(sl->str);
2224 2225 2226
	}

	/*
2227
	 * Create the test database(s) and role(s)
2228
	 */
2229 2230 2231 2232
	for (sl = dblist; sl; sl = sl->next)
		create_database(sl->str);
	for (sl = extraroles; sl; sl = sl->next)
		create_role(sl->str, dblist);
2233 2234 2235 2236 2237 2238 2239 2240

	/*
	 * Ready to run the tests
	 */
	header(_("running regression test queries"));

	for (sl = schedulelist; sl != NULL; sl = sl->next)
	{
2241
		run_schedule(sl->str, tfunc);
2242 2243 2244 2245
	}

	for (sl = extra_tests; sl != NULL; sl = sl->next)
	{
2246
		run_single_test(sl->str, tfunc);
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
	}

	/*
	 * Shut down temp installation's postmaster
	 */
	if (temp_install)
	{
		header(_("shutting down postmaster"));
		stop_postmaster();
	}

	fclose(logfile);

	/*
	 * Emit nice-looking summary message
	 */
	if (fail_count == 0 && fail_ignore_count == 0)
		snprintf(buf, sizeof(buf),
				 _(" All %d tests passed. "),
				 success_count);
B
Bruce Momjian 已提交
2267
	else if (fail_count == 0)	/* fail_count=0, fail_ignore_count>0 */
2268 2269 2270 2271 2272
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests passed, %d failed test(s) ignored. "),
				 success_count,
				 success_count + fail_ignore_count,
				 fail_ignore_count);
B
Bruce Momjian 已提交
2273
	else if (fail_ignore_count == 0)	/* fail_count>0 && fail_ignore_count=0 */
2274 2275 2276
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests failed. "),
				 fail_count,
B
Bruce Momjian 已提交
2277 2278 2279
				 success_count + fail_count);
	else
		/* fail_count>0 && fail_ignore_count>0 */
2280 2281
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests failed, %d of these failures ignored. "),
B
Bruce Momjian 已提交
2282 2283
				 fail_count + fail_ignore_count,
				 success_count + fail_count + fail_ignore_count,
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
				 fail_ignore_count);

	putchar('\n');
	for (i = strlen(buf); i > 0; i--)
		putchar('=');
	printf("\n%s\n", buf);
	for (i = strlen(buf); i > 0; i--)
		putchar('=');
	putchar('\n');
	putchar('\n');

	if (file_size(difffilename) > 0)
	{
		printf(_("The differences that caused some tests to fail can be viewed in the\n"
				 "file \"%s\".  A copy of the test summary that you see\n"
				 "above is saved in the file \"%s\".\n\n"),
			   difffilename, logfilename);
	}
	else
	{
		unlink(difffilename);
		unlink(logfilename);
	}

	if (fail_count != 0)
		exit_nicely(1);

	return 0;
}