pg_regress.c 76.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-2014, PostgreSQL Global Development Group
12 13
 * Portions Copyright (c) 1994, Regents of the University of California
 *
14
 * src/test/regress/pg_regress.c
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>

27 28 29 30
#ifdef __linux__
#include <mntent.h>
#endif

31 32 33
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
34 35
#endif

36 37
#include "getopt_long.h"
#include "pg_config_paths.h"
38 39 40 41

/* for resultmap we need a list of pairs of strings */
typedef struct _resultmap
{
B
Bruce Momjian 已提交
42
	char	   *test;
43
	char	   *type;
B
Bruce Momjian 已提交
44
	char	   *resultfile;
45
	struct _resultmap *next;
B
Bruce Momjian 已提交
46
} _resultmap;
47 48

/*
49 50 51 52 53
 * 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.
54 55 56 57
 *
 * 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.
58
 */
59 60 61 62 63 64
char	   *bindir = PGBINDIR;
char	   *libdir = LIBDIR;
char	   *datadir = PGSHAREDIR;
char	   *host_platform = HOST_TUPLE;

#ifndef WIN32_ONLY_COMPILER
65
static char *makeprog = MAKEPROG;
66
#endif
B
Bruce Momjian 已提交
67

68
#ifndef WIN32					/* not used in WIN32 case */
69
static char *shellprog = SHELLPROG;
70
#endif
71

72 73 74
static char gpdiffprog[MAXPGPATH];
static char gpstringsubsprog[MAXPGPATH];

75 76
/*
 * On Windows we use -w in diff switches to avoid problems with inconsistent
B
Bruce Momjian 已提交
77
 * newline representation.  The actual result files will generally have
78 79 80
 * Windows-style newlines, but the comparison files might or might not.
 */
#ifndef WIN32
81 82 83
/* GPDB:  Add stuff to ignore all the extra NOTICE messages we give */
const char *basic_diff_opts = "-I HINT: -I CONTEXT: -I GP_IGNORE:";
const char *pretty_diff_opts = "-I HINT: -I CONTEXT: -I GP_IGNORE: -U3";
84 85 86 87
#else
const char *basic_diff_opts = "-w";
const char *pretty_diff_opts = "-w -C3";
#endif
88 89

/* options settable from command line */
90 91 92 93
_stringlist *dblist = NULL;
bool		debug = false;
char	   *inputdir = ".";
char	   *outputdir = ".";
94
char	   *prehook = "";
95
char	   *psqldir = PGBINDIR;
96
char	   *launcher = NULL;
97
bool 		optimizer_enabled = false;
98
bool 		resgroup_enabled = false;
99
static _stringlist *loadlanguage = NULL;
100
static _stringlist *loadextension = NULL;
B
Bruce Momjian 已提交
101
static int	max_connections = 0;
102 103
static char *encoding = NULL;
static _stringlist *schedulelist = NULL;
104
static _stringlist *exclude_tests = NULL;
105 106
static _stringlist *extra_tests = NULL;
static char *temp_install = NULL;
107
static char *temp_config = NULL;
108 109
static char *top_builddir = NULL;
static bool nolocale = false;
110
static bool use_existing = false;
111
static char *hostname = NULL;
B
Bruce Momjian 已提交
112
static int	port = -1;
113
static bool port_specified_by_user = false;
114
static char *dlpath = PKGLIBDIR;
115
static char *user = NULL;
116
static _stringlist *extraroles = NULL;
117
static _stringlist *extra_install = NULL;
118
static char *initfile = NULL;
119
static char *aodir = NULL;
120
static char *resgroupdir = NULL;
121
static bool ignore_plans = false;
122 123 124 125 126 127 128 129 130 131 132 133

/* 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 已提交
134 135 136
static int	success_count = 0;
static int	fail_count = 0;
static int	fail_ignore_count = 0;
137

138 139 140 141 142 143 144 145 146
static bool directory_exists(const char *dir);
static void make_directory(const char *dir);

static void create_database(const char *dbname);
static void drop_database_if_exists(const char *dbname);

static int
run_diff(const char *cmd, const char *filename);

147 148
static bool should_exclude_test(char *test);

149 150 151 152
static void
header(const char *fmt,...)
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
153
__attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
154 155 156 157
static void
status(const char *fmt,...)
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
158
__attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
159
static void
B
Bruce Momjian 已提交
160
psql_command(const char *database, const char *query,...)
161 162
/* This extension allows gcc to check the format string for consistency with
   the supplied arguments. */
163
__attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
164

165 166 167
#ifdef WIN32
typedef BOOL (WINAPI * __CreateRestrictedToken) (HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD, PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);

168 169
/* Windows API define missing from some versions of MingW headers */
#ifndef  DISABLE_MAX_PRIVILEGE
170 171
#define DISABLE_MAX_PRIVILEGE	0x1
#endif
172
#endif
173

174 175
static bool detectCgroupMountPoint(char *cgdir, int len);

176
/*
177
 * allow core files if possible.
178
 */
179
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
180
static void
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
unlimit_core_size(void)
{
	struct rlimit lim;

	getrlimit(RLIMIT_CORE, &lim);
	if (lim.rlim_max == 0)
	{
		fprintf(stderr,
				_("%s: could not set core size: disallowed by hard limit\n"),
				progname);
		return;
	}
	else if (lim.rlim_max == RLIM_INFINITY || lim.rlim_cur < lim.rlim_max)
	{
		lim.rlim_cur = lim.rlim_max;
		setrlimit(RLIMIT_CORE, &lim);
	}
}
#endif


/*
 * Add an item at the end of a stringlist.
 */
void
B
Bruce Momjian 已提交
206
add_stringlist_item(_stringlist **listhead, const char *str)
207 208 209 210 211 212 213 214 215 216 217
{
	_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 已提交
218
			 /* skip */ ;
219 220 221 222
		oldentry->next = newentry;
	}
}

223 224 225 226
/*
 * Free a stringlist.
 */
static void
B
Bruce Momjian 已提交
227
free_stringlist(_stringlist **listhead)
228 229 230 231 232 233 234 235 236 237 238 239 240 241
{
	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 已提交
242
split_to_stringlist(const char *s, const char *delim, _stringlist **listhead)
243 244 245 246 247 248 249 250 251 252 253 254
{
	char	   *sc = strdup(s);
	char	   *token = strtok(sc, delim);

	while (token)
	{
		add_stringlist_item(listhead, token);
		token = strtok(NULL, delim);
	}
	free(sc);
}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
/*
 * 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 已提交
314
		char		buf[MAXPGPATH * 2];
315
		int			r;
316

317 318 319 320
		/* On Windows, system() seems not to force fflush, so... */
		fflush(stdout);
		fflush(stderr);

321
		snprintf(buf, sizeof(buf),
322
				 "\"%s/pg_ctl\" stop -D \"%s/data\" -s -m fast",
323
				 bindir, temp_install);
324 325 326 327 328
		r = system(buf);
		if (r != 0)
		{
			fprintf(stderr, _("\n%s: could not stop postmaster: exit code was %d\n"),
					progname, r);
329
			_exit(2);			/* not exit(), that could be recursive */
330 331
		}

332 333 334 335 336 337 338 339
		postmaster_running = false;
	}
}

/*
 * Always exit through here, not through plain exit(), to ensure we make
 * an effort to shut down a temp postmaster
 */
340
void
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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
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;
}

420
/*
R
Robert Haas 已提交
421
 * Replace all occurrences of a string in a string with a different string.
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
 * NOTE: Assumes there is enough room in the target buffer!
 */
void
replace_string(char *string, char *replace, char *replacement)
{
	char	   *ptr;

	while ((ptr = strstr(string, replace)) != NULL)
	{
		char	   *dup = strdup(string);

		strlcpy(string, dup, ptr - string + 1);
		strcat(string, replacement);
		strcat(string, dup + (ptr - string) + strlen(replace));
		free(dup);
	}
}

440 441 442 443 444
typedef struct replacements
{
	char *abs_srcdir;
	char *abs_builddir;
	char *testtablespace;
445
	char *dlpath;
446 447 448
	char *dlsuffix;
	char *bindir;
	char *orientation;
449
	char *cgroup_mnt_point;
450 451
} replacements;

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
/* Internal helper function to detect cgroup mount point at runtime.*/
static bool
detectCgroupMountPoint(char *cgdir, int len)
{
#ifdef __linux__
	struct mntent *me;
	FILE *fp;
	bool ret = false;

	fp = setmntent("/proc/self/mounts", "r");
	if (fp == NULL)
		return ret;

	while ((me = getmntent(fp)))
	{
		char *p;

		if (strcmp(me->mnt_type, "cgroup"))
			continue;

		strncpy(cgdir, me->mnt_dir, len);

		p = strrchr(cgdir, '/');
		if (p != NULL)
		{
			*p = 0;
			ret = true;
		}
		break;
	}

	endmntent(fp);
	return ret;
#else
	return false;
#endif
}

490 491 492
static void
convert_line(char *line, replacements *repls)
{
493
	replace_string(line, "@cgroup_mnt_point@", repls->cgroup_mnt_point);
494 495 496
	replace_string(line, "@abs_srcdir@", repls->abs_srcdir);
	replace_string(line, "@abs_builddir@", repls->abs_builddir);
	replace_string(line, "@testtablespace@", repls->testtablespace);
497
	replace_string(line, "@libdir@", repls->dlpath);
498 499 500
	replace_string(line, "@DLSUFFIX@", repls->dlsuffix);
	replace_string(line, "@bindir@", repls->bindir);
	if (repls->orientation)
501
	{
502
		replace_string(line, "@orientation@", repls->orientation);
503 504 505 506 507
		if (strcmp(repls->orientation, "row") == 0)
			replace_string(line, "@aoseg@", "aoseg");
		else
			replace_string(line, "@aoseg@", "aocsseg");
	}
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
}

/*
 * Generate two files for each UAO test case, one for row and the
 * other for column orientation.
 */
static int
generate_uao_sourcefiles(char *src_dir, char *dest_dir, char *suffix, replacements *repls)
{
	struct stat st;
	int			ret;
	char	  **name;
	char	  **names;
	int			count = 0;

	/*
	 * Return silently if src_dir or dest_dir is not a directory, in
	 * the same spirit as in convert_sourcefiles_in().
	 */
	ret = stat(src_dir, &st);
	if (ret != 0 || !S_ISDIR(st.st_mode))
		return 0;

	ret = stat(dest_dir, &st);
	if (ret != 0 || !S_ISDIR(st.st_mode))
		return 0;

	names = pgfnames(src_dir);
	if (!names)
		/* Error logged in pgfnames */
		exit_nicely(2);

	/* finally loop on each file and generate the files */
	for (name = names; *name; name++)
	{
		char		srcfile[MAXPGPATH];
		char		destfile_row[MAXPGPATH];
		char		destfile_col[MAXPGPATH];
		char		prefix[MAXPGPATH];
		FILE	   *infile,
				   *outfile_row,
				   *outfile_col;
		char		line[1024];
		char		line_row[1024];
		bool		has_tokens = false;

		/* 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.  Optimizer specific
		 * answer filenames must end with "optimizer".
		 */
		snprintf(srcfile, MAXPGPATH, "%s/%s", src_dir, *name);
		if (strlen(*name) > 17 &&
			strcmp(*name + strlen(*name) - 17, "_optimizer.source") == 0)
		{
			snprintf(prefix, strlen(*name) - 16, "%s", *name);
			snprintf(destfile_row, MAXPGPATH, "%s/%s_row_optimizer.%s",
					 dest_dir, prefix, suffix);
			snprintf(destfile_col, MAXPGPATH, "%s/%s_column_optimizer.%s",
					 dest_dir, prefix, suffix);
		}
		else
		{
			snprintf(prefix, strlen(*name) - 6, "%s", *name);
			snprintf(destfile_row, MAXPGPATH, "%s/%s_row.%s",
					 dest_dir, prefix, suffix);
			snprintf(destfile_col, MAXPGPATH, "%s/%s_column.%s",
					 dest_dir, prefix, suffix);
		}

		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_row = fopen(destfile_row, "w");
		if (!outfile_row)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
					progname, destfile_row, strerror(errno));
			exit_nicely(2);
		}
		outfile_col = fopen(destfile_col, "w");
		if (!outfile_col)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
					progname, destfile_col, strerror(errno));
			exit_nicely(2);
		}

		while (fgets(line, sizeof(line), infile))
		{
			strncpy(line_row, line, sizeof(line));
			repls->orientation = "row";
			convert_line(line_row, repls);
			repls->orientation = "column";
			convert_line(line, repls);
			fputs(line, outfile_col);
			fputs(line_row, outfile_row);
			/*
			 * Remember if there are any more tokens that we didn't recognize.
			 * They need to be handled by the gpstringsubs.pl script
			 */
			if (!has_tokens && strchr(line, '@') != NULL)
				has_tokens = true;
		}

		fclose(infile);
		fclose(outfile_row);
		fclose(outfile_col);
		if (has_tokens)
		{
			char		cmd[MAXPGPATH * 3];
			snprintf(cmd, sizeof(cmd),
631
					 "%s %s", gpstringsubsprog, destfile_row);
632 633 634 635 636 637
			if (run_diff(cmd, destfile_row) != 0)
			{
				fprintf(stderr, _("%s: could not convert %s\n"),
						progname, destfile_row);
			}
			snprintf(cmd, sizeof(cmd),
638
					 "%s %s", gpstringsubsprog, destfile_col);
639 640 641 642 643 644 645 646 647 648 649 650
			if (run_diff(cmd, destfile_col) != 0)
			{
				fprintf(stderr, _("%s: could not convert %s\n"),
						progname, destfile_col);
			}
		}
	}

	pgfnames_cleanup(names);
	return count;
}

651 652 653 654 655 656
/*
 * 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.
 */
657
static int
658
convert_sourcefiles_in(char *source_subdir, char *dest_dir, char *dest_subdir, char *suffix)
659 660 661
{
	char		testtablespace[MAXPGPATH];
	char		indir[MAXPGPATH];
662
	char		cgroup_mnt_point[MAXPGPATH];
663
	replacements repls;
664
	struct stat st;
665
	int			ret;
666 667 668
	char	  **name;
	char	  **names;
	int			count = 0;
B
Bruce Momjian 已提交
669

670
	snprintf(indir, MAXPGPATH, "%s/%s", inputdir, source_subdir);
671 672 673 674 675 676

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

683 684 685
	names = pgfnames(indir);
	if (!names)
		/* Error logged in pgfnames */
686
		exit(2);
687 688

	/* also create the output directory if not present */
689 690
	if (!directory_exists(dest_subdir))
		make_directory(dest_subdir);
691

692
	snprintf(testtablespace, MAXPGPATH, "%s/testtablespace", outputdir);
693 694

#ifdef WIN32
695

696 697
	/*
	 * On Windows only, clean out the test tablespace dir, or create it if it
698 699 700
	 * 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.)
701 702 703 704 705 706
	 *
	 * 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.
	 */
	if (directory_exists(testtablespace))
S
Stephen Frost 已提交
707 708 709 710 711 712
		if (!rmtree(testtablespace, true))
		{
			fprintf(stderr, _("\n%s: could not remove test tablespace \"%s\": %s\n"),
					progname, testtablespace, strerror(errno));
			exit(2);
		}
713 714 715
	make_directory(testtablespace);
#endif

716 717 718 719 720
	memset(cgroup_mnt_point, 0, sizeof(cgroup_mnt_point));
	if (!detectCgroupMountPoint(cgroup_mnt_point,
								sizeof(cgroup_mnt_point) - 1))
		strcpy(cgroup_mnt_point, "/sys/fs/cgroup");

721
	memset(&repls, 0, sizeof(repls));
722 723
	repls.abs_srcdir = inputdir;
	repls.abs_builddir = outputdir;
724
	repls.testtablespace = testtablespace;
725
	repls.dlpath = dlpath;
726 727
	repls.dlsuffix = DLSUFFIX;
	repls.bindir = bindir;
728
	repls.cgroup_mnt_point = cgroup_mnt_point;
729

730 731 732 733 734 735 736 737 738 739 740
	/* finally loop on each file and do the replacement */
	for (name = names; *name; name++)
	{
		char		srcfile[MAXPGPATH];
		char		destfile[MAXPGPATH];
		char		prefix[MAXPGPATH];
		FILE	   *infile,
				   *outfile;
		char		line[1024];
		bool		has_tokens = false;

741
		if (aodir && strncmp(*name, aodir, strlen(aodir)) == 0 &&
742
			(strlen(*name) < 8 || strcmp(*name + strlen(*name) - 7, ".source") != 0))
743 744
		{
			snprintf(srcfile, MAXPGPATH, "%s/%s",  indir, *name);
745
			snprintf(destfile, MAXPGPATH, "%s/%s", dest_subdir, *name);
746 747 748 749
			count += generate_uao_sourcefiles(srcfile, destfile, suffix, &repls);
			continue;
		}

750 751 752
		if (resgroupdir && strncmp(*name, resgroupdir, strlen(resgroupdir)) == 0 &&
			(strlen(*name) < 8 || strcmp(*name + strlen(*name) - 7, ".source") != 0))
		{
753 754
			snprintf(srcfile, MAXPGPATH, "%s/%s", source_subdir, *name);
			snprintf(destfile, MAXPGPATH, "%s/%s", dest_subdir, *name);
755 756 757 758
			count += convert_sourcefiles_in(srcfile, dest_dir, destfile, suffix);
			continue;
		}

759 760 761 762 763 764 765 766 767 768 769
		/* 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);
770
		snprintf(destfile, MAXPGPATH, "%s/%s/%s.%s", dest_dir, dest_subdir,
771
				 prefix, suffix);
772 773 774 775 776 777

		infile = fopen(srcfile, "r");
		if (!infile)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
					progname, srcfile, strerror(errno));
778
			exit(2);
779 780 781 782 783 784
		}
		outfile = fopen(destfile, "w");
		if (!outfile)
		{
			fprintf(stderr, _("%s: could not open file \"%s\" for writing: %s\n"),
					progname, destfile, strerror(errno));
785
			exit(2);
786 787 788
		}
		while (fgets(line, sizeof(line), infile))
		{
789
			convert_line(line, &repls);
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
			fputs(line, outfile);

			/*
			 * Remember if there are any more tokens that we didn't recognize.
			 * They need to be handled by the gpstringsubs.pl script
			 */
			if (!has_tokens && strchr(line, '@') != NULL)
				has_tokens = true;
		}
		fclose(infile);
		fclose(outfile);

		if (has_tokens)
		{
			char		cmd[MAXPGPATH * 3];
			snprintf(cmd, sizeof(cmd),
806
					 "%s %s", gpstringsubsprog, destfile);
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
			if (run_diff(cmd, destfile) != 0)
			{
				fprintf(stderr, _("%s: could not convert %s\n"),
						progname, destfile);
			}
		}

	}

	/*
	 * If we didn't process any files, complain because it probably means
	 * somebody neglected to pass the needed --inputdir argument.
	 */
	if (count <= 0)
	{
		fprintf(stderr, _("%s: no *.source files found in \"%s\"\n"),
				progname, indir);
824
		exit(2);
825 826 827
	}

	pgfnames_cleanup(names);
828 829

	return count;
830 831
}

832
/* Create the .sql, .out and .yml files from the .source files, if any */
833 834 835
static void
convert_sourcefiles(void)
{
836
	convert_sourcefiles_in("input", outputdir, "sql", "sql");
837
	convert_sourcefiles_in("output", outputdir, "expected", "out");
838 839

	convert_sourcefiles_in("yml_in", inputdir, "yml", "yml");
840 841
}

842 843 844 845
/*
 * Scan resultmap file to find which platform-specific expected files to use.
 *
 * The format of each line of the file is
B
Bruce Momjian 已提交
846
 *		   testname/hostplatformpattern=substitutefile
847 848 849 850
 * 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 已提交
851
 * matched against is the config.guess output.  (In the shell-script version,
852 853 854 855 856 857
 * 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 已提交
858 859
	char		buf[MAXPGPATH];
	FILE	   *f;
860 861 862

	/* scan the file ... */
	snprintf(buf, sizeof(buf), "%s/resultmap", inputdir);
B
Bruce Momjian 已提交
863
	f = fopen(buf, "r");
864 865 866 867 868 869 870
	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));
871
		exit(2);
872
	}
873 874

	while (fgets(buf, sizeof(buf), f))
875
	{
B
Bruce Momjian 已提交
876
		char	   *platform;
877
		char	   *file_type;
B
Bruce Momjian 已提交
878 879
		char	   *expected;
		int			i;
880 881 882

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

		/* parse out the line fields */
887 888 889 890 891
		file_type = strchr(buf, ':');
		if (!file_type)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
892
			exit(2);
893 894 895 896
		}
		*file_type++ = '\0';

		platform = strchr(file_type, ':');
897 898 899 900
		if (!platform)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
901
			exit(2);
902 903 904 905 906 907 908
		}
		*platform++ = '\0';
		expected = strchr(platform, '=');
		if (!expected)
		{
			fprintf(stderr, _("incorrectly formatted resultmap entry: %s\n"),
					buf);
909
			exit(2);
910 911 912 913
		}
		*expected++ = '\0';

		/*
B
Bruce Momjian 已提交
914 915 916 917
		 * 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.
918 919 920 921 922 923
		 */
		if (string_matches_pattern(host_platform, platform))
		{
			_resultmap *entry = malloc(sizeof(_resultmap));

			entry->test = strdup(buf);
924
			entry->type = strdup(file_type);
925 926 927 928 929 930 931 932
			entry->resultfile = strdup(expected);
			entry->next = resultmap;
			resultmap = entry;
		}
	}
	fclose(f);
}

933 934 935 936 937
/*
 * Check in resultmap if we should be looking at a different file
 */
static
const char *
938
get_expectfile(const char *testname, const char *file, const char *default_expectfile)
939
{
940
	char		expectpath[MAXPGPATH];
941
	char	   *file_type;
942 943
	char	   *file_name;
	char		base_file[MAXPGPATH];
944
	_resultmap *rm;
945
	char		buf[MAXPGPATH];
946 947 948 949 950 951 952 953 954 955

	/*
	 * 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++;

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
	/*
	 * Also determine the base file name from the result full path.
	 */
	if (!(file_name = strrchr(file, '/')))
		return NULL;

	file_name ++;

	if (file_type < file_name)
		return NULL;
	strlcpy(base_file, file_name, (file_type) - file_name);

	/*
	 * Find the directory the default expected file is in. That is, everything
	 * up to the last slash.
	 */
	{
		char	   *p = strrchr(default_expectfile, '/');

		if (!p)
			return NULL;

		strlcpy(expectpath, default_expectfile, p - default_expectfile + 1);
	}

981 982 983 984
	for (rm = resultmap; rm != NULL; rm = rm->next)
	{
		if (strcmp(testname, rm->test) == 0 && strcmp(file_type, rm->type) == 0)
		{
985 986
			snprintf(buf, sizeof(buf), "%s/%s", expectpath, rm->resultfile);
			return strdup(buf);
987 988 989
		}
	}

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
	/* Use ORCA or resgroup expected outputs, if available */
	if  (optimizer_enabled && resgroup_enabled)
	{
		snprintf(buf, sizeof(buf), "%s/%s_optimizer_resgroup.%s", expectpath, base_file, file_type);
		if (file_exists(buf))
			return strdup(buf);
	}
	if  (optimizer_enabled)
	{
		snprintf(buf, sizeof(buf), "%s/%s_optimizer.%s", expectpath, base_file, file_type);
		if (file_exists(buf))
			return strdup(buf);
	}
	if  (resgroup_enabled)
	{
		snprintf(buf, sizeof(buf), "%s/%s_resgroup.%s", expectpath, base_file, file_type);
		if (file_exists(buf))
			return strdup(buf);
	}

1010 1011 1012
	return NULL;
}

1013 1014 1015 1016 1017 1018
/*
 * Handy subroutine for setting an environment variable "var" to "val"
 */
static void
doputenv(const char *var, const char *val)
{
P
Peter Eisentraut 已提交
1019
	char	   *s;
1020

T
Tom Lane 已提交
1021
	s = psprintf("%s=%s", var, val);
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
	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 已提交
1032 1033
	char	   *oldval = getenv(pathname);
	char	   *newval;
1034 1035 1036 1037

	if (!oldval || !oldval[0])
	{
		/* no previous value */
T
Tom Lane 已提交
1038
		newval = psprintf("%s=%s", pathname, addval);
1039 1040
	}
	else
T
Tom Lane 已提交
1041
		newval = psprintf("%s=%s%c%s", pathname, addval, separator, oldval);
P
Peter Eisentraut 已提交
1042

1043 1044 1045 1046 1047 1048 1049 1050 1051
	putenv(newval);
}

/*
 * Prepare environment variables for running regression tests
 */
static void
initialize_environment(void)
{
1052 1053
	putenv("PGAPPNAME=pg_regress");

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	if (nolocale)
	{
		/*
		 * Clear out any non-C locale settings
		 */
		unsetenv("LC_COLLATE");
		unsetenv("LC_CTYPE");
		unsetenv("LC_MONETARY");
		unsetenv("LC_NUMERIC");
		unsetenv("LC_TIME");
		unsetenv("LANG");
		/* On Windows the default locale cannot be English, so force it */
#if defined(WIN32) || defined(__CYGWIN__)
		putenv("LANG=en");
#endif
	}

1071
	/*
1072 1073 1074 1075
	 * Set translation-related settings to English; otherwise psql will
	 * produce translated messages and produce diffs.  (XXX If we ever support
	 * translation of pg_regress, this needs to be moved elsewhere, where psql
	 * is actually called.)
1076 1077
	 */
	unsetenv("LANGUAGE");
1078 1079
	unsetenv("LC_ALL");
	putenv("LC_MESSAGES=C");
1080 1081

	/*
1082
	 * Set encoding as requested
1083
	 */
1084
	if (encoding)
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
		doputenv("PGCLIENTENCODING", encoding);
	else
		unsetenv("PGCLIENTENCODING");

	/*
	 * Set timezone and datestyle for datetime-related tests
	 */
	putenv("PGTZ=PST8PDT");
	putenv("PGDATESTYLE=Postgres, MDY");

1095 1096 1097 1098 1099 1100 1101 1102
	/*
	 * 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.
	 */
	{
		const char *my_pgoptions = "-c intervalstyle=postgres_verbose";
		const char *old_pgoptions = getenv("PGOPTIONS");
1103
		char	   *new_pgoptions;
1104 1105 1106

		if (!old_pgoptions)
			old_pgoptions = "";
T
Tom Lane 已提交
1107 1108
		new_pgoptions = psprintf("PGOPTIONS=%s %s",
								 old_pgoptions, my_pgoptions);
1109 1110 1111
		putenv(new_pgoptions);
	}

1112 1113 1114
	if (temp_install)
	{
		/*
B
Bruce Momjian 已提交
1115 1116 1117 1118 1119 1120
		 * 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.
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
		 */
		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 已提交
1136
			char		s[16];
1137

B
Bruce Momjian 已提交
1138 1139
			sprintf(s, "%d", port);
			doputenv("PGPORT", s);
1140 1141
		}

1142 1143
		/*
		 * GNU make stores some flags in the MAKEFLAGS environment variable to
B
Bruce Momjian 已提交
1144
		 * pass arguments to its own children.  If we are invoked by make,
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
		 * that causes the make invoked by us to think its part of the make
		 * task invoking us, and so it tries to communicate with the toplevel
		 * make.  Which fails.
		 *
		 * Unset the variable to protect against such problems.  We also reset
		 * MAKELEVEL to be certain the child doesn't notice the make above us.
		 */
		unsetenv("MAKEFLAGS");
		unsetenv("MAKELEVEL");

1155 1156 1157
		/*
		 * Adjust path variables to point into the temp-install tree
		 */
T
Tom Lane 已提交
1158
		bindir = psprintf("%s/install/%s", temp_install, bindir);
1159

T
Tom Lane 已提交
1160
		libdir = psprintf("%s/install/%s", temp_install, libdir);
1161

T
Tom Lane 已提交
1162
		datadir = psprintf("%s/install/%s", temp_install, datadir);
1163

1164 1165 1166
		/* psql will be installed into temp-install bindir */
		psqldir = bindir;

1167 1168 1169 1170
		/*
		 * Set up shared library paths to include the temp install.
		 *
		 * LD_LIBRARY_PATH covers many platforms.  DYLD_LIBRARY_PATH works on
B
Bruce Momjian 已提交
1171
		 * Darwin, and maybe other Mach-based systems.  LIBPATH is for AIX.
1172
		 * Windows needs shared libraries in PATH (only those linked into
B
Bruce Momjian 已提交
1173 1174
		 * executables, not dlopen'ed ones). Feel free to account for others
		 * as well.
1175 1176 1177
		 */
		add_to_path("LD_LIBRARY_PATH", ':', libdir);
		add_to_path("DYLD_LIBRARY_PATH", ':', libdir);
1178
		add_to_path("LIBPATH", ':', libdir);
1179
#if defined(WIN32)
1180
		add_to_path("PATH", ';', libdir);
1181 1182
#elif defined(__CYGWIN__)
		add_to_path("PATH", ':', libdir);
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
#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 已提交
1201
			char		s[16];
1202

B
Bruce Momjian 已提交
1203 1204
			sprintf(s, "%d", port);
			doputenv("PGPORT", s);
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
		}
		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"));
	}

1229
	convert_sourcefiles();
1230 1231 1232 1233 1234 1235 1236 1237 1238
	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 已提交
1239
psql_command(const char *database, const char *query,...)
1240
{
B
Bruce Momjian 已提交
1241 1242 1243 1244 1245 1246
	char		query_formatted[1024];
	char		query_escaped[2048];
	char		psql_cmd[MAXPGPATH + 2048];
	va_list		args;
	char	   *s;
	char	   *d;
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264

	/* 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),
1265
			 "\"%s%spsql\" -X -c \"%s\" \"%s\"",
1266 1267 1268 1269
			 psqldir ? psqldir : "",
			 psqldir ? "/" : "",
			 query_escaped,
			 database);
1270 1271 1272 1273 1274

	if (system(psql_cmd) != 0)
	{
		/* psql probably already reported the error */
		fprintf(stderr, _("command failed: %s\n"), psql_cmd);
1275
		exit(2);
1276 1277 1278 1279 1280 1281
	}
}

/*
 * Spawn a process to execute the given shell command; don't wait for it
 *
1282
 * Returns the process ID (or HANDLE) so we can wait for it later
1283
 */
1284
PID_TYPE
1285 1286 1287
spawn_process(const char *cmdline)
{
#ifndef WIN32
B
Bruce Momjian 已提交
1288
	pid_t		pid;
1289 1290

	/*
B
Bruce Momjian 已提交
1291
	 * Must flush I/O buffers before fork.  Ideally we'd use fflush(NULL) here
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
	 * ... 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));
1304
		exit(2);
1305 1306 1307
	}
	if (pid == 0)
	{
1308 1309 1310
		/*
		 * In child
		 *
B
Bruce Momjian 已提交
1311
		 * Instead of using system(), exec the shell directly, and tell it to
B
Bruce Momjian 已提交
1312
		 * "exec" the command too.  This saves two useless processes per
B
Bruce Momjian 已提交
1313
		 * parallel test case.
1314
		 */
P
Peter Eisentraut 已提交
1315
		char	   *cmdline2;
1316

T
Tom Lane 已提交
1317
		cmdline2 = psprintf("exec %s", cmdline);
1318
		execl(shellprog, shellprog, "-c", cmdline2, (char *) NULL);
1319 1320
		fprintf(stderr, _("%s: could not exec \"%s\": %s\n"),
				progname, shellprog, strerror(errno));
1321
		_exit(1);				/* not exit() here... */
1322 1323 1324 1325
	}
	/* in parent */
	return pid;
#else
B
Bruce Momjian 已提交
1326
	char	   *cmdline2;
1327
	BOOL		b;
1328 1329
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
1330 1331 1332 1333 1334 1335
	HANDLE		origToken;
	HANDLE		restrictedToken;
	SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY};
	SID_AND_ATTRIBUTES dropSids[2];
	__CreateRestrictedToken _CreateRestrictedToken = NULL;
	HANDLE		Advapi32Handle;
1336 1337 1338 1339

	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);

1340 1341 1342 1343 1344
	Advapi32Handle = LoadLibrary("ADVAPI32.DLL");
	if (Advapi32Handle != NULL)
	{
		_CreateRestrictedToken = (__CreateRestrictedToken) GetProcAddress(Advapi32Handle, "CreateRestrictedToken");
	}
1345

1346
	if (_CreateRestrictedToken == NULL)
1347
	{
1348 1349 1350 1351
		if (Advapi32Handle != NULL)
			FreeLibrary(Advapi32Handle);
		fprintf(stderr, _("%s: cannot create restricted tokens on this platform\n"),
				progname);
1352
		exit(2);
1353 1354
	}

1355 1356 1357
	/* Open the current token to use as base for the restricted one */
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &origToken))
	{
1358
		fprintf(stderr, _("could not open process token: error code %lu\n"),
1359
				GetLastError());
1360
		exit(2);
1361
	}
1362

1363 1364 1365 1366 1367 1368 1369
	/* Allocate list of SIDs to remove */
	ZeroMemory(&dropSids, sizeof(dropSids));
	if (!AllocateAndInitializeSid(&NtAuthority, 2,
								  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))
	{
1370
		fprintf(stderr, _("could not allocate SIDs: error code %lu\n"), GetLastError());
1371
		exit(2);
1372
	}
1373

1374 1375 1376 1377 1378 1379 1380
	b = _CreateRestrictedToken(origToken,
							   DISABLE_MAX_PRIVILEGE,
							   sizeof(dropSids) / sizeof(dropSids[0]),
							   dropSids,
							   0, NULL,
							   0, NULL,
							   &restrictedToken);
1381

1382 1383 1384 1385 1386 1387 1388
	FreeSid(dropSids[1].Sid);
	FreeSid(dropSids[0].Sid);
	CloseHandle(origToken);
	FreeLibrary(Advapi32Handle);

	if (!b)
	{
1389
		fprintf(stderr, _("could not create restricted token: error code %lu\n"),
1390
				GetLastError());
1391
		exit(2);
1392
	}
1393

1394
	cmdline2 = psprintf("cmd /c \"%s\"", cmdline);
1395

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
#ifndef __CYGWIN__
	AddUserToTokenDacl(restrictedToken);
#endif

	if (!CreateProcessAsUser(restrictedToken,
							 NULL,
							 cmdline2,
							 NULL,
							 NULL,
							 TRUE,
							 CREATE_SUSPENDED,
							 NULL,
							 NULL,
							 &si,
							 &pi))
1411
	{
1412
		fprintf(stderr, _("could not start process for \"%s\": error code %lu\n"),
1413
				cmdline2, GetLastError());
1414
		exit(2);
1415 1416
	}

1417 1418
	free(cmdline2);

1419
	ResumeThread(pi.hThread);
1420 1421 1422
	CloseHandle(pi.hThread);
	return pi.hProcess;
#endif
1423 1424 1425 1426 1427 1428 1429 1430
}

/*
 * Count bytes in file
 */
static long
file_size(const char *file)
{
B
Bruce Momjian 已提交
1431 1432
	long		r;
	FILE	   *f = fopen(file, "r");
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

	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 已提交
1452 1453 1454
	int			c;
	int			l = 0;
	FILE	   *f = fopen(file, "r");
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470

	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;
}

1471
bool
1472 1473
file_exists(const char *file)
{
B
Bruce Momjian 已提交
1474
	FILE	   *f = fopen(file, "r");
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488

	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;
1489
	if (S_ISDIR(st.st_mode))
1490 1491 1492 1493 1494 1495 1496 1497
		return true;
	return false;
}

/* Create a directory */
static void
make_directory(const char *dir)
{
1498
	if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) < 0)
1499 1500 1501
	{
		fprintf(stderr, _("%s: could not create directory \"%s\": %s\n"),
				progname, dir, strerror(errno));
1502
		exit(2);
1503 1504 1505
	}
}

1506 1507 1508 1509 1510 1511 1512 1513
/*
 * In: filename.ext, Return: filename_i.ext, where 0 < i <= 9
 */
static char *
get_alternative_expectfile(const char *expectfile, int i)
{
	char	   *last_dot;
	int			ssize = strlen(expectfile) + 2 + 1;
S
Stephen Frost 已提交
1514 1515
	char	   *tmp;
	char	   *s;
B
Bruce Momjian 已提交
1516

B
Bruce Momjian 已提交
1517
	if (!(tmp = (char *) malloc(ssize)))
S
Stephen Frost 已提交
1518
		return NULL;
P
Peter Eisentraut 已提交
1519

B
Bruce Momjian 已提交
1520
	if (!(s = (char *) malloc(ssize)))
S
Stephen Frost 已提交
1521 1522 1523 1524
	{
		free(tmp);
		return NULL;
	}
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539

	strcpy(tmp, expectfile);
	last_dot = strrchr(tmp, '.');
	if (!last_dot)
	{
		free(tmp);
		free(s);
		return NULL;
	}
	*last_dot = '\0';
	snprintf(s, ssize, "%s_%d.%s", tmp, i, last_dot + 1);
	free(tmp);
	return s;
}

1540
/*
1541
 * Run a "diff" command and also check that it didn't crash
1542
 */
1543 1544
static int
run_diff(const char *cmd, const char *filename)
1545
{
B
Bruce Momjian 已提交
1546
	int			r;
1547 1548 1549 1550 1551

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

1556
	/*
B
Bruce Momjian 已提交
1557 1558
	 * On WIN32, if the 'diff' command cannot be found, system() returns 1,
	 * but produces nothing to stdout, so we check for that here.
1559 1560 1561 1562
	 */
	if (WEXITSTATUS(r) == 1 && file_size(filename) <= 0)
	{
		fprintf(stderr, _("diff command not found: %s\n"), cmd);
1563
		exit(2);
1564
	}
1565 1566
#else
	UnusedArg(filename);
1567
#endif
B
Bruce Momjian 已提交
1568

1569
	return WEXITSTATUS(r);
1570 1571
}

1572 1573 1574 1575 1576 1577 1578
/*
 * 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
1579
results_differ(const char *testname, const char *resultsfile, const char *default_expectfile)
1580
{
B
Bruce Momjian 已提交
1581 1582 1583 1584
	char		expectfile[MAXPGPATH];
	char		diff[MAXPGPATH];
	char		cmd[MAXPGPATH * 3];
	char		best_expect_file[MAXPGPATH];
1585 1586
    char        diff_opts[MAXPGPATH];
    char        m_pretty_diff_opts[MAXPGPATH];
B
Bruce Momjian 已提交
1587 1588 1589 1590
	FILE	   *difffile;
	int			best_line_count;
	int			i;
	int			l;
1591
	const char *platform_expectfile;
1592
	const char *ignore_plans_opts;
B
Bruce Momjian 已提交
1593

1594 1595 1596 1597
	/*
	 * We can pass either the resultsfile or the expectfile, they should have
	 * the same type (filename.type) anyway.
	 */
1598
	platform_expectfile = get_expectfile(testname, resultsfile, default_expectfile);
1599 1600

	if (platform_expectfile)
1601 1602 1603
		strlcpy(expectfile, platform_expectfile, sizeof(expectfile));
	else
		strlcpy(expectfile, default_expectfile, sizeof(expectfile));
1604

1605 1606 1607 1608 1609
	if (ignore_plans)
		ignore_plans_opts = " -gpd_ignore_plans";
	else
		ignore_plans_opts = "";

1610 1611 1612 1613 1614 1615 1616
	/* Name to use for temporary diff file */
	snprintf(diff, sizeof(diff), "%s.diff", resultsfile);
    
	/* Add init file arguments if provided via commandline */
	if (initfile)
	{
	  snprintf(diff_opts, sizeof(diff_opts),
1617
			   "%s%s --gpd_init %s", basic_diff_opts, ignore_plans_opts, initfile);
1618

1619
	  snprintf(m_pretty_diff_opts, sizeof(m_pretty_diff_opts),
1620
			   "%s%s --gpd_init %s", pretty_diff_opts, ignore_plans_opts, initfile);
1621 1622 1623 1624
	}
	else
	{
		snprintf(diff_opts, sizeof(diff_opts),
1625
			   "%s%s", basic_diff_opts, ignore_plans_opts);
1626

1627
		snprintf(m_pretty_diff_opts, sizeof(m_pretty_diff_opts),
1628
				 "%s%s", pretty_diff_opts, ignore_plans_opts);
1629
	}
1630 1631 1632

	/* OK, run the diff */
	snprintf(cmd, sizeof(cmd),
1633
			 "%s %s \"%s\" \"%s\" > \"%s\"",
1634
			 gpdiffprog, diff_opts, expectfile, resultsfile, diff);
1635 1636

	/* Is the diff file empty? */
1637
	if (run_diff(cmd, diff) == 0)
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
	{
		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++)
	{
1649 1650 1651
		char	   *alt_expectfile;

		alt_expectfile = get_alternative_expectfile(expectfile, i);
S
Stephen Frost 已提交
1652 1653 1654 1655 1656 1657 1658
		if (!alt_expectfile)
		{
			fprintf(stderr, _("Unable to check secondary comparison files: %s\n"),
					strerror(errno));
			exit(2);
		}

1659
		if (!file_exists(alt_expectfile))
S
Stephen Frost 已提交
1660 1661
		{
			free(alt_expectfile);
1662
			continue;
S
Stephen Frost 已提交
1663
		}
1664 1665

		snprintf(cmd, sizeof(cmd),
1666
				 "%s %s \"%s\" \"%s\" > \"%s\"",
1667
				 gpdiffprog, diff_opts, alt_expectfile, resultsfile, diff);
1668

1669
		if (run_diff(cmd, diff) == 0)
1670 1671
		{
			unlink(diff);
S
Stephen Frost 已提交
1672
			free(alt_expectfile);
1673 1674 1675 1676 1677 1678 1679 1680
			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;
1681
			strlcpy(best_expect_file, alt_expectfile, sizeof(best_expect_file));
1682
		}
1683
		free(alt_expectfile);
1684 1685
	}

B
Bruce Momjian 已提交
1686 1687 1688
	/*
	 * fall back on the canonical results file if we haven't tried it yet and
	 * haven't found a complete match yet.
1689 1690 1691 1692 1693 1694 1695
	 *
	 * In GPDB, platform_expectfile is used for determining ORCA/planner/resgroup
	 * expect files, wheras in upstream that is not the case and it is based on
	 * the underlying platform. Thus, it is unnecessary and confusing to compare
	 * against default answer file even when platform_expect file exists. It gets
	 * confusing because the below block chooses the best expect file based on
	 * the number of lines in diff file.
A
 
Andrew Dunstan 已提交
1696 1697
	 */

1698
#if 0
1699
	if (platform_expectfile)
A
 
Andrew Dunstan 已提交
1700 1701
	{
		snprintf(cmd, sizeof(cmd),
1702
				 "%s %s \"%s\" \"%s\" > \"%s\"",
1703
				 gpdiffprog, diff_opts, default_expectfile, resultsfile, diff);
A
 
Andrew Dunstan 已提交
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716

		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;
1717
			strlcpy(best_expect_file, default_expectfile, sizeof(best_expect_file));
A
 
Andrew Dunstan 已提交
1718 1719
		}
	}
1720
#endif
1721
	/*
B
Bruce Momjian 已提交
1722 1723
	 * Use the best comparison file to generate the "pretty" diff, which we
	 * append to the diffs summary file.
1724 1725
	 */
	snprintf(cmd, sizeof(cmd),
1726
			 "%s %s \"%s\" \"%s\" >> \"%s\"",
1727
			 gpdiffprog, m_pretty_diff_opts, best_expect_file, resultsfile, difffilename);
1728
	run_diff(cmd, difffilename);
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743

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

	unlink(diff);
	return true;
}

/*
1744 1745
 * Wait for specified subprocesses to finish, and return their exit
 * statuses into statuses[]
1746
 *
1747
 * If names isn't NULL, print each subprocess's name as it finishes
1748 1749
 *
 * Note: it's OK to scribble on the pids array, but not on the names array
1750 1751
 */
static void
1752
wait_for_tests(PID_TYPE *pids, int *statuses, char **names, struct timeval *end_times, int num_tests)
1753
{
B
Bruce Momjian 已提交
1754 1755
	int			tests_left;
	int			i;
1756

1757
#ifdef WIN32
B
Bruce Momjian 已提交
1758
	PID_TYPE   *active_pids = malloc(num_tests * sizeof(PID_TYPE));
1759 1760 1761 1762

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

1763 1764 1765
	tests_left = num_tests;
	while (tests_left > 0)
	{
B
Bruce Momjian 已提交
1766
		PID_TYPE	p;
1767 1768

#ifndef WIN32
1769 1770 1771
		int			exit_status;

		p = wait(&exit_status);
1772 1773 1774 1775 1776

		if (p == INVALID_PID)
		{
			fprintf(stderr, _("failed to wait for subprocesses: %s\n"),
					strerror(errno));
1777
			exit(2);
1778 1779
		}
#else
1780
		DWORD		exit_status;
B
Bruce Momjian 已提交
1781
		int			r;
1782

1783 1784
		r = WaitForMultipleObjects(tests_left, active_pids, FALSE, INFINITE);
		if (r < WAIT_OBJECT_0 || r >= WAIT_OBJECT_0 + tests_left)
1785
		{
1786
			fprintf(stderr, _("failed to wait for subprocesses: error code %lu\n"),
1787
					GetLastError());
1788
			exit(2);
1789
		}
1790 1791 1792
		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 已提交
1793
#endif   /* WIN32 */
1794

B
Bruce Momjian 已提交
1795
		for (i = 0; i < num_tests; i++)
1796 1797 1798
		{
			if (p == pids[i])
			{
1799
#ifdef WIN32
1800
				GetExitCodeProcess(pids[i], &exit_status);
1801 1802 1803
				CloseHandle(pids[i]);
#endif
				pids[i] = INVALID_PID;
1804
				statuses[i] = (int) exit_status;
1805 1806
				if (names)
					status(" %s", names[i]);
1807 1808
				if (end_times)
					gettimeofday(&end_times[i], NULL);
1809
				tests_left--;
1810
				break;
1811 1812 1813 1814
			}
		}
	}

1815 1816
#ifdef WIN32
	free(active_pids);
1817 1818 1819
#endif
}

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
/*
 * 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);
}

1849 1850 1851 1852
/*
 * Run all the tests specified in one schedule file
 */
static void
1853
run_schedule(const char *schedule, test_function tfunc)
1854 1855
{
#define MAX_PARALLEL_TESTS 100
B
Bruce Momjian 已提交
1856
	char	   *tests[MAX_PARALLEL_TESTS];
1857 1858 1859
	_stringlist *resultfiles[MAX_PARALLEL_TESTS];
	_stringlist *expectfiles[MAX_PARALLEL_TESTS];
	_stringlist *tags[MAX_PARALLEL_TESTS];
B
Bruce Momjian 已提交
1860
	PID_TYPE	pids[MAX_PARALLEL_TESTS];
1861 1862
	int			statuses[MAX_PARALLEL_TESTS];
	struct timeval end_times[MAX_PARALLEL_TESTS];
1863
	_stringlist *ignorelist = NULL;
B
Bruce Momjian 已提交
1864 1865 1866
	char		scbuf[1024];
	FILE	   *scf;
	int			line_num = 0;
1867

1868 1869 1870 1871 1872
	memset(resultfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
	memset(expectfiles, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
	memset(tags, 0, sizeof(_stringlist *) * MAX_PARALLEL_TESTS);
	memset(end_times, 0, sizeof(struct timeval) * MAX_PARALLEL_TESTS);

1873 1874 1875 1876 1877
	scf = fopen(schedule, "r");
	if (!scf)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, schedule, strerror(errno));
1878
		exit(2);
1879 1880
	}

1881
	while (fgets(scbuf, sizeof(scbuf), scf))
1882
	{
B
Bruce Momjian 已提交
1883 1884 1885 1886 1887
		char	   *test = NULL;
		char	   *c;
		int			num_tests;
		bool		inword;
		int			i;
1888
		struct timeval start_time;
1889 1890 1891

		line_num++;

1892 1893 1894 1895 1896 1897 1898 1899 1900
		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]);
		}

1901 1902
		/* strip trailing whitespace, especially the newline */
		i = strlen(scbuf);
B
Bruce Momjian 已提交
1903
		while (i > 0 && isspace((unsigned char) scbuf[i - 1]))
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
			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 已提交
1916

1917 1918
			/*
			 * Note: ignore: lines do not run the test, they just say that
B
Bruce Momjian 已提交
1919 1920
			 * 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.
1921 1922 1923 1924 1925 1926 1927
			 */
			continue;
		}
		else
		{
			fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
					schedule, line_num, scbuf);
1928
			exit(2);
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
		}

		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);
1947
					exit(2);
1948
				}
1949 1950 1951 1952

				if (num_tests - 1 >= 0 && should_exclude_test(tests[num_tests - 1]))
					num_tests--;

1953 1954 1955 1956 1957 1958
				tests[num_tests] = c;
				num_tests++;
				inword = true;
			}
		}

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
		/* The last test in the line needs to be checked for exclusion */
		if (num_tests - 1 >= 0 && should_exclude_test(tests[num_tests - 1]))
		{
			num_tests--;

			/* All tests in this line are to be excluded, so go to the next line */
			if (num_tests == 0)
				continue;
		}

1969 1970 1971 1972
		if (num_tests == 0)
		{
			fprintf(stderr, _("syntax error in schedule file \"%s\" line %d: %s\n"),
					schedule, line_num, scbuf);
1973
			exit(2);
1974 1975
		}

1976
		gettimeofday(&start_time, NULL);
1977 1978
		if (num_tests == 1)
		{
1979
			status(_("test %-24s ... "), tests[0]);
1980 1981
			pids[0] = (tfunc) (tests[0], &resultfiles[0], &expectfiles[0], &tags[0]);
			wait_for_tests(pids, statuses, NULL, end_times, 1);
1982 1983 1984 1985
			/* status line is finished below */
		}
		else if (max_connections > 0 && max_connections < num_tests)
		{
B
Bruce Momjian 已提交
1986
			int			oldest = 0;
1987 1988 1989 1990 1991 1992 1993

			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)
				{
1994 1995
					wait_for_tests(pids + oldest, statuses + oldest,
								   tests + oldest, end_times + oldest, i - oldest);
1996 1997
					oldest = i;
				}
1998
				pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
1999
			}
2000 2001
			wait_for_tests(pids + oldest, statuses + oldest,
						   tests + oldest, end_times + oldest, i - oldest);
2002 2003 2004 2005 2006 2007 2008
			status_end();
		}
		else
		{
			status(_("parallel group (%d tests): "), num_tests);
			for (i = 0; i < num_tests; i++)
			{
2009
				pids[i] = (tfunc) (tests[i], &resultfiles[i], &expectfiles[i], &tags[i]);
2010
			}
2011
			wait_for_tests(pids, statuses, tests, end_times, num_tests);
2012 2013 2014 2015 2016 2017
			status_end();
		}

		/* Check results for all tests */
		for (i = 0; i < num_tests; i++)
		{
2018 2019 2020 2021 2022 2023 2024
			_stringlist *rl,
					   *el,
					   *tl;
			bool		differ = false;
			double		diff_secs = 0, diff_elapse = 0;
			struct timeval diff_start_time, diff_end_time;

2025
			if (num_tests > 1)
2026
				status(_("     %-24s ... "), tests[i]);
2027

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
			diff_secs = end_times[i].tv_usec - start_time.tv_usec;
			diff_secs /= 1000000;
			diff_secs += end_times[i].tv_sec - start_time.tv_sec;
			/*
			 * Advance over all three lists simultaneously.
			 *
			 * 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.
			 */

			gettimeofday(&diff_start_time, NULL);
			for (rl = resultfiles[i], el = expectfiles[i], tl = tags[i];
				 rl != NULL;	/* rl and el have the same length */
				 rl = rl->next, el = el->next)
			{
				bool		newdiff;

				if (tl)
2047
					tl = tl->next;		/* tl has the same length as rl and el
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
										 * if it exists */

				newdiff = results_differ(tests[i], rl->str, el->str);
				if (newdiff && tl)
				{
					printf("%s ", tl->str);
				}
				differ |= newdiff;
			}
			gettimeofday(&diff_end_time, NULL);

			diff_elapse = diff_end_time.tv_usec - diff_start_time.tv_usec;
			diff_elapse /= 1000000;
			diff_elapse += diff_end_time.tv_sec - diff_start_time.tv_sec;

			if (differ)
2064
			{
B
Bruce Momjian 已提交
2065
				bool		ignore = false;
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
				_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"));
2084
    				status(_(" (%.2f sec)  (diff:%.2f sec)"), diff_secs, diff_elapse);
2085 2086 2087 2088 2089 2090
					fail_count++;
				}
			}
			else
			{
				status(_("ok"));
2091
				status(_(" (%.2f sec)  (diff:%.2f sec)"), diff_secs, diff_elapse);
2092 2093 2094
				success_count++;
			}

2095 2096 2097
			if (statuses[i] != 0)
				log_child_failure(statuses[i]);

2098 2099 2100 2101
			status_end();
		}
	}

2102 2103
	free_stringlist(&ignorelist);

2104 2105 2106 2107 2108 2109 2110
	fclose(scf);
}

/*
 * Run a single test
 */
static void
2111
run_single_test(const char *test, test_function tfunc)
2112
{
B
Bruce Momjian 已提交
2113
	PID_TYPE	pid;
2114 2115 2116 2117 2118 2119 2120 2121
	int			exit_status;
	_stringlist *resultfiles = NULL;
	_stringlist *expectfiles = NULL;
	_stringlist *tags = NULL;
	_stringlist *rl,
			   *el,
			   *tl;
	bool		differ = false;
2122

2123
	status(_("test %-24s ... "), test);
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
	pid = (tfunc) (test, &resultfiles, &expectfiles, &tags);
	wait_for_tests(&pid, &exit_status, NULL, NULL, 1);

	/*
	 * Advance over all three lists simultaneously.
	 *
	 * 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.
	 */
	for (rl = resultfiles, el = expectfiles, tl = tags;
		 rl != NULL;			/* rl and el have the same length */
		 rl = rl->next, el = el->next)
	{
		bool		newdiff;

		if (tl)
2141
			tl = tl->next;		/* tl has the same length as rl and el if it
2142 2143 2144 2145 2146 2147 2148 2149 2150
								 * exists */

		newdiff = results_differ(test, rl->str, el->str);
		if (newdiff && tl)
		{
			printf("%s ", tl->str);
		}
		differ |= newdiff;
	}
2151

2152
	if (differ)
2153 2154 2155 2156 2157 2158 2159 2160 2161
	{
		status(_("FAILED"));
		fail_count++;
	}
	else
	{
		status(_("ok"));
		success_count++;
	}
2162 2163 2164 2165

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

2166 2167 2168
	status_end();
}

2169 2170
/*
 * Find the other binaries that we need. Currently, gpdiff.pl and
2171
 * gpstringsubs.pl.
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
 */
static void
find_helper_programs(const char *argv0)
{
	if (find_other_exec(argv0, "gpdiff.pl", NULL, gpdiffprog) != 0)
	{
		char		full_path[MAXPGPATH];

		if (find_my_exec(argv0, full_path) < 0)
			strlcpy(full_path, progname, sizeof(full_path));

		fprintf(stderr,
				_("The program \"gpdiff.pl\" is needed by %s "
				  "but was not found in the same directory as \"%s\".\n"),
				progname, full_path);
		exit(1);
	}
	if (find_other_exec(argv0, "gpstringsubs.pl", NULL, gpstringsubsprog) != 0)
	{
		char		full_path[MAXPGPATH];

		if (find_my_exec(argv0, full_path) < 0)
			strlcpy(full_path, progname, sizeof(full_path));

		fprintf(stderr,
				_("The program \"gpstringsubs.pl\" is needed by %s "
				  "but was not found in the same directory as \"%s\".\n"),
				progname, full_path);
		exit(1);
	}
}
2203 2204 2205 2206 2207 2208
/*
 * Create the summary-output files (making them empty if already existing)
 */
static void
open_result_files(void)
{
B
Bruce Momjian 已提交
2209 2210
	char		file[MAXPGPATH];
	FILE	   *difffile;
2211 2212 2213 2214 2215 2216 2217 2218 2219

	/* 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));
2220
		exit(2);
2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
	}

	/* 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));
2231
		exit(2);
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
	}
	/* 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);
}

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
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;

	/*
	 * We use template0 so that any installation-local cruft in template1 will
	 * not mess up the tests.
	 */
	header(_("creating database \"%s\""), dbname);
2259
	if (encoding)
2260 2261
		psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0 ENCODING='%s'", dbname, encoding);
	else
2262 2263
		psql_command("postgres", "CREATE DATABASE \"%s\" TEMPLATE=template0%s", dbname,
					 (nolocale) ? " LC_COLLATE='C' LC_CTYPE='C'" : "");
2264 2265 2266 2267 2268 2269 2270 2271 2272
	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);

	/*
B
Bruce Momjian 已提交
2273
	 * Install any requested procedural languages.  We use CREATE OR REPLACE
2274
	 * so that this will work whether or not the language is preinstalled.
2275 2276 2277 2278
	 */
	for (sl = loadlanguage; sl != NULL; sl = sl->next)
	{
		header(_("installing %s"), sl->str);
2279
		psql_command(dbname, "CREATE OR REPLACE LANGUAGE \"%s\"", sl->str);
2280
	}
2281 2282

	/*
2283 2284
	 * Install any requested extensions.  We use CREATE IF NOT EXISTS so that
	 * this will work whether or not the extension is preinstalled.
2285 2286 2287 2288 2289 2290
	 */
	for (sl = loadextension; sl != NULL; sl = sl->next)
	{
		header(_("installing %s"), sl->str);
		psql_command(dbname, "CREATE EXTENSION IF NOT EXISTS \"%s\"", sl->str);
	}
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
}

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 已提交
2301
create_role(const char *rolename, const _stringlist *granted_dbs)
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
{
	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\"",
					 granted_dbs->str, rolename);
	}
}

static char *
trim_white_space(char *str)
{
	char *end;
	while (isspace((unsigned char)*str))
	{
		str++;
	}

	if (*str == 0)
	{
		return str;
	}

	end = str + strlen(str) - 1;
	while (end > str && isspace((unsigned char)*end))
	{
		end--;
	}

	*(end+1) = 0;
	return str;
}

2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
/*
 * Should the test be excluded from running
 */
static bool
should_exclude_test(char *test)
{
	_stringlist *sl;
	for (sl = exclude_tests; sl != NULL; sl = sl->next)
	{
		if (strcmp(test, sl->str) == 0)
			return true;
	}

	return false;
}

2352
/*
J
Jesse Zhang 已提交
2353
 * @brief Check whether a feature (e.g. optimizer) is on or off.
2354
 * If the input feature is optimizer, then set the global
2355
 * variable "optimizer_enabled" accordingly.
2356
 *
J
Jesse Zhang 已提交
2357
 * @param feature_name Name of the feature to be checked (e.g. optimizer)
2358
 * @param feature_value Expected value when the feature is enabled (i.e., on or group)
2359 2360 2361
 * @param on_msg Message to be printed when the feature is enabled
 * @param off_msg Message to be printed when the feature is disabled
 * @return true if the feature is enabled; false otherwise
2362
 */
2363
static bool
2364 2365
check_feature_status(const char *feature_name, const char *feature_value,
					 const char *on_msg, const char *off_msg)
2366 2367 2368 2369
{
	char psql_cmd[MAXPGPATH];
	char statusfilename[MAXPGPATH];
	char line[1024];
2370
	bool isEnabled = false;
2371
	int len;
2372

2373
	header(_("checking %s status"), feature_name);
2374

2375
	snprintf(statusfilename, sizeof(statusfilename), "%s/%s_status.out", outputdir, feature_name);
2376

2377
	len = snprintf(psql_cmd, sizeof(psql_cmd),
2378
			"\"%s%spsql\" -X -t -c \"show %s;\" -o \"%s\" -d \"postgres\"",
2379 2380 2381 2382
			psqldir ? psqldir : "",
			psqldir ? "/" : "",
			feature_name,
			statusfilename);
2383

2384 2385 2386
	if (len >= sizeof(psql_cmd))
		exit_nicely(2);

2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
	if (system(psql_cmd) != 0)
		exit_nicely(2);

	FILE *statusfile = fopen(statusfilename, "r");
	if (!statusfile)
	{
		fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
				progname, statusfilename, strerror(errno));
		exit_nicely(2);
	}

	while (fgets(line, sizeof(line), statusfile))
	{
		char *trimmed = trim_white_space(line);
2401
		if (strcmp(trimmed, feature_value) == 0)
2402
		{
2403
			status(_("%s"), on_msg);
2404
			isEnabled = true;
2405 2406 2407
			break;
		}
	}
2408 2409 2410
	if (!isEnabled)
		status(_("%s"), off_msg);

2411 2412
	status_end();
	fclose(statusfile);
2413
	unlink(statusfilename);
2414
	return isEnabled;
2415 2416
}

2417 2418 2419 2420 2421
static void
help(void)
{
	printf(_("PostgreSQL regression test driver\n"));
	printf(_("\n"));
2422
	printf(_("Usage:\n  %s [OPTION]... [EXTRA-TEST]...\n"), progname);
2423 2424
	printf(_("\n"));
	printf(_("Options:\n"));
2425
	printf(_("  --create-role=ROLE        create the specified role before testing\n"));
2426 2427
	printf(_("  --dbname=DB               use database DB (default \"regression\")\n"));
	printf(_("  --debug                   turn on debug mode in programs that are run\n"));
2428 2429
	printf(_("  --dlpath=DIR              look for dynamic libraries in DIR\n"));
	printf(_("  --encoding=ENCODING       use ENCODING as the encoding\n"));
2430
	printf(_("  --inputdir=DIR            take input files from DIR (default \".\")\n"));
2431 2432
	printf(_("  --launcher=CMD            use CMD as launcher of psql\n"));
	printf(_("  --load-extension=EXT      load the named extension before running the\n"));
2433
	printf(_("                            tests; can appear multiple times\n"));
2434
	printf(_("  --load-language=LANG      load the named language before running the\n"));
2435
	printf(_("                            tests; can appear multiple times\n"));
2436
	printf(_("  --max-connections=N       maximum number of concurrent connections\n"));
2437
	printf(_("                            (default is 0, meaning unlimited)\n"));
2438
	printf(_("  --outputdir=DIR           place output files in DIR (default \".\")\n"));
2439
	printf(_("  --prehook=NAME            pre-hook name (default \"\")\n"));
2440
	printf(_("  --schedule=FILE           use test ordering schedule from FILE\n"));
2441
	printf(_("                            (can be used multiple times to concatenate)\n"));
2442
	printf(_("  --temp-install=DIR        create a temporary installation in DIR\n"));
2443
	printf(_("  --use-existing            use an existing installation\n"));
R
Richard Guo 已提交
2444 2445
	/* Please put GPDB speicifc options at the end. */
	printf(_("  --exclude-tests=TEST      command or space delimited tests to exclude from running\n"));
2446
    printf(_(" --init-file=GPD_INIT_FILE  init file to be used for gpdiff\n"));
2447 2448
	printf(_("  --ao-dir=DIR              directory name prefix containing generic\n"));
	printf(_("                            UAO row and column tests\n"));
2449
	printf(_("  --resgroup-dir=DIR        directory name prefix containing resgroup tests\n"));
2450
	printf(_("  --ignore-plans            ignore any explain plan diffs\n"));
2451 2452
	printf(_("\n"));
	printf(_("Options for \"temp-install\" mode:\n"));
2453
	printf(_("  --extra-install=DIR       additional directory to install (e.g., contrib)\n"));
2454
	printf(_("  --no-locale               use C locale\n"));
2455
	printf(_("  --port=PORT               start postmaster on PORT\n"));
2456 2457
	printf(_("  --temp-config=FILE        append contents of FILE to temporary config\n"));
	printf(_("  --top-builddir=DIR        (relative) path to top level build directory\n"));
2458 2459 2460 2461 2462
	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"));
2463
	printf(_("  --psqldir=DIR             use psql in DIR (default: configured bindir)\n"));
2464 2465 2466 2467
	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"));
2468
	printf(_("Report bugs to <bugs@greenplum.org>.\n"));
2469 2470 2471
}

int
2472
regression_main(int argc, char *argv[], init_function ifunc, test_function tfunc)
2473 2474 2475 2476 2477 2478 2479 2480 2481
{
	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},
2482
		{"encoding", required_argument, NULL, 6},
2483 2484 2485 2486 2487 2488 2489 2490
		{"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},
2491
		{"psqldir", required_argument, NULL, 16},
2492
		{"dlpath", required_argument, NULL, 17},
2493
		{"create-role", required_argument, NULL, 18},
2494
		{"temp-config", required_argument, NULL, 19},
2495
		{"use-existing", no_argument, NULL, 20},
2496
		{"launcher", required_argument, NULL, 21},
2497
		{"load-extension", required_argument, NULL, 22},
2498
		{"extra-install", required_argument, NULL, 23},
2499 2500 2501 2502
        {"init-file", required_argument, NULL, 25},
        {"ao-dir", required_argument, NULL, 26},
        {"resgroup-dir", required_argument, NULL, 27},
        {"exclude-tests", required_argument, NULL, 28},
2503
		{"ignore-plans", no_argument, NULL, 29},
2504
		{"prehook", required_argument, NULL, 30},
2505 2506 2507
		{NULL, 0, NULL, 0}
	};

2508 2509 2510 2511 2512 2513 2514
	_stringlist *sl;
	int			c;
	int			i;
	int			option_index;
	char		buf[MAXPGPATH * 4];
	char		buf2[MAXPGPATH * 4];

2515
	progname = get_progname(argv[0]);
2516
	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_regress"));
2517

2518 2519
	atexit(stop_postmaster);

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

2525 2526 2527 2528
	/*
	 * We call the initialization function here because that way we can set
	 * default parameters and let them be overwritten by the commandline.
	 */
2529
	ifunc(argc, argv);
2530

2531 2532 2533
	if (getenv("PG_REGRESS_DIFF_OPTS"))
		pretty_diff_opts = getenv("PG_REGRESS_DIFF_OPTS");

2534 2535 2536 2537 2538 2539
	while ((c = getopt_long(argc, argv, "hV", long_options, &option_index)) != -1)
	{
		switch (c)
		{
			case 'h':
				help();
2540
				exit(0);
2541
			case 'V':
2542
				puts("pg_regress (PostgreSQL) " PG_VERSION);
2543
				exit(0);
2544
			case 1:
2545 2546 2547 2548 2549 2550 2551

				/*
				 * If a default database was specified, we need to remove it
				 * before we add the specified one.
				 */
				free_stringlist(&dblist);
				split_to_stringlist(strdup(optarg), ", ", &dblist);
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
				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:
2575
				temp_install = make_absolute_path(optarg);
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
				break;
			case 10:
				nolocale = true;
				break;
			case 11:
				top_builddir = strdup(optarg);
				break;
			case 13:
				hostname = strdup(optarg);
				break;
			case 14:
				port = atoi(optarg);
2588
				port_specified_by_user = true;
2589 2590 2591 2592
				break;
			case 15:
				user = strdup(optarg);
				break;
2593 2594 2595 2596 2597
			case 16:
				/* "--psqldir=" should mean to use PATH */
				if (strlen(optarg))
					psqldir = strdup(optarg);
				break;
2598
			case 17:
2599
				dlpath = strdup(optarg);
2600 2601 2602 2603
				break;
			case 18:
				split_to_stringlist(strdup(optarg), ", ", &extraroles);
				break;
2604 2605 2606
			case 19:
				temp_config = strdup(optarg);
				break;
2607 2608 2609
			case 20:
				use_existing = true;
				break;
2610 2611 2612
			case 21:
				launcher = strdup(optarg);
				break;
2613 2614 2615
			case 22:
				add_stringlist_item(&loadextension, optarg);
				break;
2616 2617 2618
			case 23:
				add_stringlist_item(&extra_install, optarg);
				break;
2619
            case 25:
2620
                initfile = strdup(optarg);
2621
                break;
2622
            case 26:
2623
                aodir = strdup(optarg);
2624
                break;
2625
            case 27:
2626
                resgroupdir = strdup(optarg);
2627
                break;
2628
            case 28:
2629
                split_to_stringlist(strdup(optarg), ", ", &exclude_tests);
2630
                break;
2631 2632 2633
			case 29:
				ignore_plans = true;
				break;
2634 2635 2636
			case 30:
				prehook = strdup(optarg);
				break;
2637 2638 2639 2640
			default:
				/* getopt_long already emitted a complaint */
				fprintf(stderr, _("\nTry \"%s -h\" for more information.\n"),
						progname);
2641
				exit(2);
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
		}
	}

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

2654
	if (temp_install && !port_specified_by_user)
2655

2656
		/*
2657 2658 2659
		 * To reduce chances of interference with parallel installations, use
		 * a port number starting in the private range (49152-65535)
		 * calculated from the version number.
2660 2661
		 */
		port = 0xC000 | (PG_VERSION_NUM & 0x3FFF);
2662

2663 2664 2665
	inputdir = make_absolute_path(inputdir);
	outputdir = make_absolute_path(outputdir);
	dlpath = make_absolute_path(dlpath);
2666 2667 2668 2669

	/*
	 * Initialization
	 */
2670
	find_helper_programs(argv[0]);
2671 2672
	open_result_files();

2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
	if (prehook[0])
	{
		char	   *fullname = malloc(strlen(inputdir) +
									  strlen("/sql/hooks/") +
									  strlen(prehook) +
									  strlen(".sql") +
									  1 /* '\0' */);
		sprintf(fullname, "%s/sql/hooks/%s.sql", inputdir, prehook);
		prehook = fullname;

		if (!file_exists(prehook))
		{
			convert_sourcefiles_in("input/hooks", outputdir, "sql/hooks", "sql");

			if (!file_exists(prehook))
			{
				fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
						progname, prehook, strerror(errno));
				exit(2);
			}
		}
	}

2696 2697
	initialize_environment();

2698 2699 2700 2701
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
	unlimit_core_size();
#endif

2702 2703
	if (temp_install)
	{
2704
		FILE	   *pg_conf;
2705
		_stringlist *sl;
2706

2707 2708 2709 2710 2711 2712
		/*
		 * Prepare the temp installation
		 */
		if (!top_builddir)
		{
			fprintf(stderr, _("--top-builddir must be specified when using --temp-install\n"));
2713
			exit(2);
2714 2715 2716 2717 2718
		}

		if (directory_exists(temp_install))
		{
			header(_("removing existing temp installation"));
S
Stephen Frost 已提交
2719 2720 2721 2722 2723
			if (!rmtree(temp_install, true))
			{
				fprintf(stderr, _("\n%s: could not remove temp installation \"%s\": %s\n"), progname, temp_install, strerror(errno));
				exit(2);
			}
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
		}

		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" */
2737
#ifndef WIN32_ONLY_COMPILER
2738
		snprintf(buf, sizeof(buf),
2739
				 "\"%s\" -C \"%s\" DESTDIR=\"%s/install\" install > \"%s/log/install.log\" 2>&1",
2740
				 makeprog, top_builddir, temp_install, outputdir);
2741 2742
#else
		snprintf(buf, sizeof(buf),
2743
				 "perl \"%s/src/tools/msvc/install.pl\" \"%s/install\" >\"%s/log/install.log\" 2>&1",
2744 2745
				 top_builddir, temp_install, outputdir);
#endif
2746 2747
		if (system(buf))
		{
2748
			fprintf(stderr, _("\n%s: installation failed\nExamine %s/log/install.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2749
			exit(2);
2750 2751
		}

2752 2753 2754 2755
		for (sl = extra_install; sl != NULL; sl = sl->next)
		{
#ifndef WIN32_ONLY_COMPILER
			snprintf(buf, sizeof(buf),
2756
					 "\"%s\" -C \"%s/%s\" DESTDIR=\"%s/install\" install >> \"%s/log/install.log\" 2>&1",
B
Bruce Momjian 已提交
2757
				   makeprog, top_builddir, sl->str, temp_install, outputdir);
2758
#else
2759
			fprintf(stderr, _("\n%s: --extra-install option not supported on this platform\n"), progname);
2760
			exit(2);
2761 2762 2763 2764 2765
#endif

			if (system(buf))
			{
				fprintf(stderr, _("\n%s: installation failed\nExamine %s/log/install.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2766
				exit(2);
2767 2768 2769
			}
		}

2770 2771 2772
		/* initdb */
		header(_("initializing database system"));
		snprintf(buf, sizeof(buf),
2773
				 "\"%s/initdb\" -D \"%s/data\" -L \"%s\" --noclean --nosync%s%s > \"%s/log/initdb.log\" 2>&1",
2774
				 bindir, temp_install, datadir,
2775 2776
				 debug ? " --debug" : "",
				 nolocale ? " --no-locale" : "",
2777 2778 2779
				 outputdir);
		if (system(buf))
		{
2780
			fprintf(stderr, _("\n%s: initdb failed\nExamine %s/log/initdb.log for the reason.\nCommand was: %s\n"), progname, outputdir, buf);
2781
			exit(2);
2782 2783
		}

2784
		/*
2785 2786 2787
		 * Adjust the default postgresql.conf as needed for regression
		 * testing. The user can specify a file to be appended; in any case we
		 * set max_prepared_transactions to enable testing of prepared xacts.
2788
		 * (Note: to reduce the probability of unexpected shmmax failures,
2789 2790
		 * don't set max_prepared_transactions any higher than actually needed
		 * by the prepared_xacts regression test.)
2791 2792 2793 2794 2795 2796
		 */
		snprintf(buf, sizeof(buf), "%s/data/postgresql.conf", temp_install);
		pg_conf = fopen(buf, "a");
		if (pg_conf == NULL)
		{
			fprintf(stderr, _("\n%s: could not open \"%s\" for adding extra config: %s\n"), progname, buf, strerror(errno));
2797
			exit(2);
2798 2799 2800 2801
		}
		fputs("\n# Configuration added by pg_regress\n\n", pg_conf);
		fputs("max_prepared_transactions = 2\n", pg_conf);

2802 2803
		if (temp_config != NULL)
		{
B
Bruce Momjian 已提交
2804 2805
			FILE	   *extra_conf;
			char		line_buf[1024];
2806

B
Bruce Momjian 已提交
2807
			extra_conf = fopen(temp_config, "r");
2808 2809
			if (extra_conf == NULL)
			{
2810
				fprintf(stderr, _("\n%s: could not open \"%s\" to read extra config: %s\n"), progname, temp_config, strerror(errno));
2811
				exit(2);
2812
			}
B
Bruce Momjian 已提交
2813
			while (fgets(line_buf, sizeof(line_buf), extra_conf) != NULL)
2814 2815 2816 2817
				fputs(line_buf, pg_conf);
			fclose(extra_conf);
		}

2818 2819
		fclose(pg_conf);

2820 2821 2822 2823
		/*
		 * Check if there is a postmaster running already.
		 */
		snprintf(buf2, sizeof(buf2),
2824
				 "\"%s/psql\" -X postgres <%s 2>%s",
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
				 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"));
2839
					exit(2);
2840 2841
				}

2842
				fprintf(stderr, _("port %d apparently in use, trying %d\n"), port, port + 1);
2843 2844 2845 2846 2847 2848 2849 2850
				port++;
				sprintf(s, "%d", port);
				doputenv("PGPORT", s);
			}
			else
				break;
		}

2851 2852 2853 2854 2855
		/*
		 * Start the temp postmaster
		 */
		header(_("starting postmaster"));
		snprintf(buf, sizeof(buf),
2856
				 "\"%s/postgres\" -D \"%s/data\" -F%s -c \"listen_addresses=%s\" > \"%s/log/postmaster.log\" 2>&1",
2857
				 bindir, temp_install,
2858
				 debug ? " -d 5" : "",
2859 2860 2861 2862 2863 2864 2865
				 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));
2866
			exit(2);
2867 2868 2869
		}

		/*
B
Bruce Momjian 已提交
2870 2871 2872
		 * 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.
2873 2874 2875 2876
		 */
		for (i = 0; i < 60; i++)
		{
			/* Done if psql succeeds */
2877
			if (system(buf2) == 0)
2878 2879 2880 2881 2882 2883 2884
				break;

			/*
			 * Fail immediately if postmaster has exited
			 */
#ifndef WIN32
			if (kill(postmaster_pid, 0) != 0)
2885 2886 2887
#else
			if (WaitForSingleObject(postmaster_pid, 0) == WAIT_OBJECT_0)
#endif
2888 2889
			{
				fprintf(stderr, _("\n%s: postmaster failed\nExamine %s/log/postmaster.log for the reason\n"), progname, outputdir);
2890
				exit(2);
2891 2892 2893 2894
			}

			pg_usleep(1000000L);
		}
2895
		if (i >= 60)
2896
		{
2897 2898 2899
			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 已提交
2900 2901 2902
			 * 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
2903 2904 2905 2906 2907 2908 2909
			 * 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));
2910 2911
#else
			if (TerminateProcess(postmaster_pid, 255) == 0)
2912
				fprintf(stderr, _("\n%s: could not kill failed postmaster: error code %lu\n"),
2913
						progname, GetLastError());
2914 2915
#endif

2916
			exit(2);
2917 2918 2919 2920
		}

		postmaster_running = true;

2921 2922 2923 2924 2925 2926
#ifdef WIN64
/* need a series of two casts to convert HANDLE without compiler warning */
#define ULONGPID(x) (unsigned long) (unsigned long long) (x)
#else
#define ULONGPID(x) (unsigned long) (x)
#endif
P
Peter Eisentraut 已提交
2927
		printf(_("running on port %d with PID %lu\n"),
2928
			   port, ULONGPID(postmaster_pid));
2929 2930 2931 2932 2933
	}
	else
	{
		/*
		 * Using an existing installation, so may need to get rid of
2934
		 * pre-existing database(s) and role(s)
2935
		 */
2936 2937 2938 2939 2940 2941 2942
		if (!use_existing)
		{
			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);
		}
2943 2944 2945
	}

	/*
2946
	 * Create the test database(s) and role(s)
2947
	 */
2948 2949 2950 2951 2952 2953 2954
	if (!use_existing)
	{
		for (sl = dblist; sl; sl = sl->next)
			create_database(sl->str);
		for (sl = extraroles; sl; sl = sl->next)
			create_role(sl->str, dblist);
	}
2955 2956

	/*
2957
	 * Find out if optimizer is on or off
2958
	 */
2959
	optimizer_enabled = check_feature_status("optimizer", "on",
2960 2961 2962
			"Optimizer enabled. Using optimizer answer files whenever possible",
			"Optimizer disabled. Using planner answer files");

2963 2964 2965 2966 2967 2968 2969
	/*
	 * Find out if gp_resource_manager is group or not
	 */
	resgroup_enabled = check_feature_status("gp_resource_manager", "group",
			"Resource group enabled. Using resource group answer files whenever possible",
			"Resource group disabled. Using default answer files");

2970 2971 2972 2973 2974 2975 2976
	/*
	 * Ready to run the tests
	 */
	header(_("running regression test queries"));

	for (sl = schedulelist; sl != NULL; sl = sl->next)
	{
2977
		run_schedule(sl->str, tfunc);
2978 2979 2980 2981
	}

	for (sl = extra_tests; sl != NULL; sl = sl->next)
	{
2982
		run_single_test(sl->str, tfunc);
2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
	}

	/*
	 * 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 已提交
3003
	else if (fail_count == 0)	/* fail_count=0, fail_ignore_count>0 */
3004 3005 3006 3007 3008
		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 已提交
3009
	else if (fail_ignore_count == 0)	/* fail_count>0 && fail_ignore_count=0 */
3010 3011 3012
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests failed. "),
				 fail_count,
B
Bruce Momjian 已提交
3013 3014 3015
				 success_count + fail_count);
	else
		/* fail_count>0 && fail_ignore_count>0 */
3016 3017
		snprintf(buf, sizeof(buf),
				 _(" %d of %d tests failed, %d of these failures ignored. "),
B
Bruce Momjian 已提交
3018 3019
				 fail_count + fail_ignore_count,
				 success_count + fail_count + fail_ignore_count,
3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
				 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)
3045
		exit(1);
3046 3047 3048

	return 0;
}