cdb_restore.c 56.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/*-------------------------------------------------------------------------
 *
 * cdb_restore.c
 *	  cdb_restore is a utility for restoring a cdb cluster of postgres databases
 *
 *-------------------------------------------------------------------------
 */

#include "postgres_fe.h"
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <regex.h>
#include <ctype.h>
#include <pthread.h>
#include "getopt_long.h"
#include "pqexpbuffer.h"
#include "libpq-fe.h"
#include "fe-auth.h"
#include "pg_backup.h"
#include "cdb_table.h"
#include "cdb_dump_util.h"
#include "cdb_backup_state.h"
#include "cdb_dump.h"
#include <poll.h>

/* This is necessary on platforms where optreset variable is not available.
 * Look at "man getopt" documentation for details.
 */
#ifndef HAVE_OPTRESET
int			optreset;
#endif

#define DUMP_PREFIX (dump_prefix==NULL?"":dump_prefix)

/* Forward decls */
static void freeThreadParmArray(ThreadParmArray * pParmAr);
static bool createThreadParmArray(int nCount, ThreadParmArray * pParmAr);
static char *addPassThroughParm(char Parm, const char *pszValue, char *pszPassThroughParmString);
static bool fillInputOptions(int argc, char **argv, InputOptions * pInputOpts);
static bool parmValNeedsQuotes(const char *Value);
static void usage(void);
static void *threadProc(void *arg);
static void myHandler(SIGNAL_ARGS);
static void installSignalHandlers(void);
static bool restoreMaster(InputOptions * pInputOpts, PGconn *pConn, SegmentDatabase *sSegDB, SegmentDatabase *tSegDB, ThreadParm * pParm);
47
static void spinOffThreads(PGconn *pConn, InputOptions * pInputOpts, const RestorePairArray * restorePair, ThreadParmArray * pParmAr);
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
static int	reportRestoreResults(const char *pszReportDirectory, const ThreadParm * pMasterParm, const ThreadParmArray * pParmAr);
static int	reportMasterError(InputOptions inputopts, const ThreadParm * pMasterParm, const char *localMsg);
static void updateAppendOnlyStats(PGconn *pConn);
static bool g_b_SendCancelMessage = false;
typedef struct option optType;

static RestoreOptions *opts = NULL;
static bool dataOnly = false;
static bool postdataSchemaRestore = false;
static bool postdataRestore = true;
static bool schemaRestore = true;
static bool dataRestore = true;
static bool schemaOnly = false;
static bool bForcePassword = false;
static bool bIgnoreVersion = false;
static bool bAoStats = true;
static const char *pszAgent = "gp_restore_agent";

static const char *logInfo = "INFO";
static const char *logWarn = "WARN";
static const char *logError = "ERROR";
static const char *logFatal = "FATAL";
const char *progname;
static char * addPassThroughLongParm(const char *Parm, const char *pszValue, char *pszPassThroughParmString);
72 73
PQExpBuffer dir_buf = NULL;
PQExpBuffer dump_prefix_buf = NULL;
74 75 76 77 78

/* NetBackup related variable */
static char *netbackup_service_host = NULL;
static char *netbackup_block_size = NULL;

79 80
static char *change_schema = NULL;

81 82 83 84 85 86 87 88 89 90 91 92 93 94
#ifdef USE_DDBOOST
static int dd_boost_enabled = 0;
#endif

int
main(int argc, char **argv)
{
	PGconn	   *pConn = NULL;
	int			failCount = -1;
	int			i;
	bool		found_master;
	SegmentDatabase *sourceSegDB = NULL;
	SegmentDatabase *targetSegDB = NULL;

95 96 97
	dir_buf = createPQExpBuffer();
	dump_prefix_buf = createPQExpBuffer();

98 99
	progname = get_progname(argv[0]);

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 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 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	/* This struct holds the values of the command line parameters */
	InputOptions inputOpts;

	/*
	 * This struct holds an array of the segment databases from the master mpp
	 * tables
	 */
	RestorePairArray restorePairAr;

	/* This struct holds an array of the thread parameters */
	ThreadParmArray parmAr;
	ThreadParm	masterParm;

	memset(&inputOpts, 0, sizeof(inputOpts));
	memset(&restorePairAr, 0, sizeof(restorePairAr));
	memset(&parmAr, 0, sizeof(parmAr));
	memset(&masterParm, 0, sizeof(masterParm));

#ifdef USE_DDBOOST
	dd_boost_enabled = 0;
#endif
	/* Parse command line for options */
	if (!fillInputOptions(argc, argv, &inputOpts))
	{
		failCount = reportMasterError(inputOpts, &masterParm,
									  get_early_error());
		mpp_err_msg(logInfo, progname, "Reporting Master Error from fillInputOptions.\n");
		goto cleanup;
	}


	mpp_err_msg(logInfo, progname, "Analyzed command line options.\n");

	/* Connect to database on the master */
	mpp_err_msg(logInfo, progname, "Connecting to master segment on host %s port %s database %s.\n",
				StringNotNull(inputOpts.pszPGHost, "localhost"),
				StringNotNull(inputOpts.pszPGPort, "5432"),
				StringNotNull(inputOpts.pszMasterDBName, "?"));

	pConn = GetMasterConnection(progname, inputOpts.pszMasterDBName, inputOpts.pszPGHost,
								inputOpts.pszPGPort, inputOpts.pszUserName,
								bForcePassword, bIgnoreVersion, true);
	if (pConn == NULL)
	{
		masterParm.pOptionsData = &inputOpts;
		failCount = reportMasterError(inputOpts, &masterParm,
									  get_early_error());
		goto cleanup;

	}

	/* Read mpp segment databases configuration from the master */
	mpp_err_msg(logInfo, progname, "Reading Greenplum Database configuration info from master segment database.\n");
	if (!GetRestoreSegmentDatabaseArray(pConn, &restorePairAr, inputOpts.backupLocation, inputOpts.pszRawDumpSet, dataOnly))
		goto cleanup;

	/* find master node */
	targetSegDB = NULL;
	found_master = false;

	for (i = 0; i < restorePairAr.count; i++)
	{
		targetSegDB = &restorePairAr.pData[i].segdb_target;
		sourceSegDB = &restorePairAr.pData[i].segdb_source;

		if (targetSegDB->role == ROLE_MASTER)
		{
			found_master = true;
			break;
		}
	}

	/* Install the SIGINT and SIGTERM handlers */
	installSignalHandlers();


	/* There is no behavior change for full restore with no filter and for incremental restore.
	 * The behavior only changes when postdataSchemaRestore is specified, incase of full restore with table filters,
	 * for all other cases schemaRestore, dataRestore and postdataRestore defaults to true, hence no behavior change.
	 */

	/*
	 * restore master first. However, if we restore only data, or if master
	 * segment is not included in our restore set, skip master
	 */
	if (!dataOnly && found_master && schemaRestore)
	{
		if (!restoreMaster(&inputOpts, pConn, sourceSegDB, targetSegDB, &masterParm))
		{
			failCount = reportMasterError(inputOpts, &masterParm, NULL);
			goto cleanup;
		}

	}

	/* restore segdbs. However, if we restore schema only, skip segdbs */
	if (!schemaOnly && dataRestore)
	{
		if (restorePairAr.count > 0)
		{
			/*
			 * Create the threads to talk to each of the databases being
			 * restored. Wait for them to finish.
			 */
			spinOffThreads(pConn, &inputOpts, &restorePairAr, &parmAr);

			mpp_err_msg(logInfo, progname, "All remote %s programs are finished.\n", pszAgent);
		}

		/*
		 * If any AO table data was restored, update the master AO statistics
		 */
		if (bAoStats)
			updateAppendOnlyStats(pConn);
	}

	/*
	 * restore post-data items last. However, if we restore only data, or if master
	 * segment is not included in our restore set, skip this step
	 */
	if (!dataOnly && found_master && postdataRestore)
	{
		char * newParms;
		int newlen =  strlen(" --post-data-schema-only") + 1;
		if (inputOpts.pszPassThroughParms != NULL)
			newlen += strlen(inputOpts.pszPassThroughParms);
		newParms = malloc(newlen);
		newParms[0] = '\0';
		if (inputOpts.pszPassThroughParms != NULL)
		    strcpy(newParms, inputOpts.pszPassThroughParms);
		strcat(newParms, " --post-data-schema-only");
		inputOpts.pszPassThroughParms = newParms;

		if (!restoreMaster(&inputOpts, pConn, sourceSegDB, targetSegDB, &masterParm))
		{
			failCount = reportMasterError(inputOpts, &masterParm, NULL);
			goto cleanup;
		}

	}

	/* Produce results report */
	failCount = reportRestoreResults(inputOpts.pszReportDirectory, &masterParm, &parmAr);

cleanup:
245
	FreeRestorePairArray(&restorePairAr);
246
	FreeInputOptions(&inputOpts);
247

248 249
	if (opts != NULL)
		free(opts);
250

251 252 253 254 255 256 257 258 259 260 261
	freeThreadParmArray(&parmAr);

	if (masterParm.pszErrorMsg)
		free(masterParm.pszErrorMsg);

	if (masterParm.pszRemoteBackupPath)
		free(masterParm.pszRemoteBackupPath);

	if (pConn != NULL)
		PQfinish(pConn);

262 263 264
	destroyPQExpBuffer(dir_buf);
	destroyPQExpBuffer(dump_prefix_buf);

265
	return failCount;
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
}

static void
usage(void)
{
	printf(("%s restores a Greenplum Database database from an archive created by gp_dump.\n\n"), progname);
	printf(("Usage:\n"));
	printf(("  %s [OPTIONS]\n"), progname);

	printf(("\nGeneral options:\n"));
	printf(("  -d, --dbname=NAME        output database name\n"));
	printf(("  -i, --ignore-version     proceed even when server version mismatches\n"));
	printf(("  -v, --verbose            verbose mode. adds verbose information to the\n"
			"                           per segment status files\n"));
	printf(("  --help                   show this help, then exit\n"));
	printf(("  --version                output version information, then exit\n"));

	printf(("\nOptions controlling the output content:\n"));
	printf(("  -a, --data-only          restore only the data, no schema\n"));
	printf(("  -s, --schema-only        restore only the schema, no data\n"));
	printf(("  -P, --post-data-schema-only    restore only the postdataSchema\n"));

	printf(("\nConnection options:\n"));
	printf(("  -h, --host=HOSTNAME      database server host or socket directory\n"));
	printf(("  -p, --port=PORT          database server port number\n"));
	printf(("  -U, --username=NAME      connect as specified database user\n"));
	printf(("  -W, --password           force password prompt (should happen automatically)\n"));

	printf(("\nGreenplum Database specific options:\n"));
	printf(("  --gp-c                  use gunzip for in-line de-compression\n"));
	printf(("  --gp-d=BACKUPFILEDIR    directory where backup files are located\n"));
	printf(("  --gp-i                  ignore error\n"));
	printf(("  --gp-k=KEY              date time backup key from gp_backup run\n"));
	printf(("  --gp-r=REPORTFILEDIR    directory where report file is placed\n"));
	printf(("  --status=STATUSFILEDIR  directory where status file is placed\n"));
	printf(("  --gp-l=FILELOCATIONS    backup files are on (p)rimaries only (default)\n"));
	printf(("                          or (i)ndividual segdb (must be followed with a list of dbid's\n"));
	printf(("                          where backups are located. For example: --gp-l=i[10,12,15]\n"));
	printf(("  --gp-f=FILE             FILE, present on all machines, with tables to include in restore\n"));
	printf(("  --prefix=PREFIX         PREFIX of the dump files to be restored\n"));
306
	printf(("  --change-schema=SCHEMA  Name of the schema to which files are to be restored\n"));
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
}

bool
fillInputOptions(int argc, char **argv, InputOptions * pInputOpts)
{
	int			c;
	/* Archive	  *AH; */
	/* char    *inputFileSpec; */
	extern int	optind;
	extern char *optarg;
	/* static int	use_setsessauth = 0; */
	static int	disable_triggers = 0;
	bool		bSawCDB_S_Option;
	int			lenCmdLineParms;
	int			i;

	struct option cmdopts[] = {
		/*{"clean", 0, NULL, 'c'}, */
		/* {"create", 0, NULL, 'C'}, */
		{"data-only", 0, NULL, 'a'},
		{"post-data-schema-only", 0, NULL, 'P'},
		{"dbname", 1, NULL, 'd'},
		/*{"file", 1, NULL, 'f'},
		{"format", 1, NULL, 'F'},*/
		//{"function", 1, NULL, 'P'},
		{"host", 1, NULL, 'h'},
		{"ignore-version", 0, NULL, 'i'},
		/* {"index", 1, NULL, 'I'}, */
		/* {"list", 0, NULL, 'l'}, */
		/* {"no-privileges", 0, NULL, 'x'}, */
		{"no-acl", 0, NULL, 'x'},
		/* {"no-owner", 0, NULL, 'O'}, */
		{"no-reconnect", 0, NULL, 'R'},
		{"port", 1, NULL, 'p'},
		/* {"oid-order", 0, NULL, 'o'}, */
		/* {"orig-order", 0, NULL, 'N'}, */
		{"password", 0, NULL, 'W'},
		/* {"rearrange", 0, NULL, 'r'}, */
		{"schema-only", 0, NULL, 's'},
		/* {"superuser", 1, NULL, 'S'}, */
		/* {"table", 1, NULL, 't'}, */
		/* {"trigger", 1, NULL, 'T'}, */
		/* {"use-list", 1, NULL, 'L'}, */
		{"username", 1, NULL, 'U'},
		{"verbose", 0, NULL, 'v'},

		/*
		 * the following options don't have an equivalent short option letter,
		 * but are available as '-X long-name'
		 */
		//{"use-set-session-authorization", no_argument, &use_setsessauth, 1},
		//{"disable-triggers", no_argument, &disable_triggers, 1},

		/*
		 * the following are Greenplum Database specific, and don't have an equivalent short option
		 */
		{"gp-c", no_argument, NULL, 1},
		/* {"gp-cf", required_argument, NULL, 2}, */
		{"gp-d", required_argument, NULL, 3},
		{"gp-i", no_argument, NULL, 4},
		/* {"gp-hdb", required_argument, NULL, 5}, */
		{"gp-k", required_argument, NULL, 6},
		{"gp-r", required_argument, NULL, 7},
		{"gp-s", required_argument, NULL, 8},
		{"gp-l", required_argument, NULL, 9},

#ifdef USE_DDBOOST
                {"ddboost", no_argument, NULL, 10},
#endif

		{"gp-f", required_argument, NULL, 11},
		{"gp-nostats", no_argument, NULL, 12},
		{"prefix", required_argument, NULL, 13},
		{"status", required_argument, NULL, 14},
		{"netbackup-service-host", required_argument, NULL, 15},
		{"netbackup-block-size", required_argument, NULL, 16},
383
		{"change-schema", required_argument, NULL, 17},
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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 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 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 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 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
		{NULL, 0, NULL, 0}
	};

	/* Initialize option fields  */
	memset(pInputOpts, 0, sizeof(InputOptions));

	pInputOpts->actors = SET_NO_MIRRORS;		/* restore primaries only.
												 * mirrors will get sync'ed
												 * automatically */
	pInputOpts->backupLocation = FILE_ON_PRIMARIES;
	pInputOpts->bOnErrorStop = true;
	pInputOpts->pszBackupDirectory = NULL;

	opts = (RestoreOptions *) calloc(1, sizeof(RestoreOptions));
	if (opts == NULL)
	{
		mpp_err_msg_cache(logError, progname, "error allocating memory for RestoreOptions");
		return false;
	}

	opts->format = archUnknown;
	opts->suppressDumpWarnings = false;

	bSawCDB_S_Option = false;

	if (argc == 1)
	{
		usage();
		exit(0);
	}

	if (argc > 1)
	{
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
		{
			usage();
			exit(0);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			puts("gp_restore (Greenplum Database) " GP_VERSION);
			exit(0);
		}
	}

	/*
	 * Record the command line parms as a string for documentation in the
	 * ouput report
	 */
	lenCmdLineParms = 0;
	for (i = 1; i < argc; i++)
	{
		if (i > 1)
			lenCmdLineParms += 1;

		lenCmdLineParms += strlen(argv[i]);
		if (parmValNeedsQuotes(argv[i]))
			lenCmdLineParms += 2;
	}

	pInputOpts->pszCmdLineParms = (char *) malloc(lenCmdLineParms + 1);
	if (pInputOpts->pszCmdLineParms == NULL)
	{
		mpp_err_msg_cache(logError, progname, "error allocating memory for pInputOpts->pszCmdLineParms\n");
		return false;
	}

	memset(pInputOpts->pszCmdLineParms, 0, lenCmdLineParms + 1);
	for (i = 1; i < argc; i++)
	{
		if (i > 1)
			strcat(pInputOpts->pszCmdLineParms, " ");
		if (parmValNeedsQuotes(argv[i]))
		{
			strcat(pInputOpts->pszCmdLineParms, "\"");
			strcat(pInputOpts->pszCmdLineParms, argv[i]);
			strcat(pInputOpts->pszCmdLineParms, "\"");
		}
		else
			strcat(pInputOpts->pszCmdLineParms, argv[i]);
	}

	while ((c = getopt_long(argc, argv, "aPcd:h:ip:RsuU:vwW",
							cmdopts, NULL)) != -1)
	{
		switch (c)
		{
			case 'a':			/* Dump data only */
				opts->dataOnly = 1;
				dataOnly = true;
				pInputOpts->pszPassThroughParms = addPassThroughParm(c, NULL, pInputOpts->pszPassThroughParms);
				break;
			case 'P':			/* postdataSchemaRestore is only specified for full restore with table filters. */
				opts->postdataSchemaRestore = 1;
				postdataSchemaRestore = true;
				break;
/*			case 'c':		*/	/* clean (i.e., drop) schema prior to create */
/*				opts->dropSchema = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm(c, NULL, pInputOpts->pszPassThroughParms);
				break;
*/
/*			case 'C':
				opts->create = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms );
				break;
									   */
			case 'd':
				opts->dbname = strdup(optarg);
				pInputOpts->pszDBName = Safe_strdup(opts->dbname);
				pInputOpts->pszMasterDBName = Safe_strdup(opts->dbname);
				break;
/*			case 'f':			// output file name
				opts->filename = strdup(optarg);
				break;

			case 'F':
				if (strlen(optarg) != 0)
				{
					opts->formatName = strdup(optarg);
					pInputOpts->pszPassThroughParms = addPassThroughParm( c, optarg, pInputOpts->pszPassThroughParms );
				}

				break;
*/
			case 'h':
				if (strlen(optarg) != 0)
				{
					opts->pghost = strdup(optarg);
					pInputOpts->pszPGHost = Safe_strdup(optarg);
				}

				break;
			case 'i':
				/* obsolete option */
				break;

				/* case 'l':		  // * Dump the TOC summary * */
/*				opts->tocSummary = 1; */
/*				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms ); */
/*				break; */

				/* case 'L':		  // * input TOC summary file name * */
/*				opts->tocFile = strdup(optarg); */
/*				break; */

/*			case 'N':
				opts->origOrder = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms );
				break;
			case 'o':
				opts->oidOrder = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms );
				break;
			case 'O':
				opts->noOwner = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms );
				break;
									   */ case 'p':
				if (strlen(optarg) != 0)
				{
					opts->pgport = strdup(optarg);
					pInputOpts->pszPGPort = Safe_strdup(optarg);
				}
				break;
/*			case 'r':
				opts->rearrange = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms );
				break;
									   */ case 'R':
				/* no-op, still accepted for backwards compatibility */
				break;
/*			case 'P':			// Function
				opts->selTypes = 1;
				opts->selFunction = 1;
				opts->functionNames = strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, optarg, pInputOpts->pszPassThroughParms );
				break;
			case 'I':			// Index
				opts->selTypes = 1;
				opts->selIndex = 1;
				opts->indexNames = strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, optarg, pInputOpts->pszPassThroughParms );
				break;
			case 'T':			// Trigger
				opts->selTypes = 1;
				opts->selTrigger = 1;
				opts->triggerNames = strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, optarg, pInputOpts->pszPassThroughParms );
				break;
*/ 
			case 's':		/* dump schema only */
				opts->schemaOnly = 1;
				schemaOnly = true;
				pInputOpts->pszPassThroughParms = addPassThroughParm(c, NULL, pInputOpts->pszPassThroughParms);
				break;
/* 			case 'S':		  //  * Superuser username * */
/*				if (strlen(optarg) != 0) */
/*					opts->superuser = strdup(optarg); */
/*				break; */
/*			case 't':			// Dump data for this table only
				opts->selTypes = 1;
				opts->selTable = 1;
				opts->tableNames = strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, optarg, pInputOpts->pszPassThroughParms );
				break;
*/
			case 'u':
				opts->promptPassword = TRI_YES;
				opts->username = simple_prompt("User name: ", 100, true);
				pInputOpts->pszUserName = Safe_strdup(opts->username);
				break;

			case 'U':
				opts->username = optarg;
				pInputOpts->pszUserName = Safe_strdup(opts->username);
				break;

			case 'v':			/* verbose */
				opts->verbose = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm(c, NULL, pInputOpts->pszPassThroughParms);
				break;

			case 'w':
				opts->promptPassword = TRI_NO;
				break;

			case 'W':
				opts->promptPassword = TRI_YES;
				break;

/*			case 'x':			// skip ACL dump
				opts->aclsSkip = 1;
				pInputOpts->pszPassThroughParms = addPassThroughParm( c, NULL, pInputOpts->pszPassThroughParms );
				break;

			case 'X':
				if (strcmp(optarg, "use-set-session-authorization") == 0)
				 *								  *//* no-op, still allowed
					for compatibility */ ;

				/* else if (strcmp(optarg, "disable-triggers") == 0) */
				/* disable_triggers = 1; */
				/* else */
				/* { */
				/* fprintf(stderr, */
				/* ("%s: invalid -X option -- %s\n"), */
				/* progname , optarg); */

				/*
				 * fprintf(stderr, ("Try \"%s --help\" for more
				 * information.\n"), progname );
				 */
				/* exit(1); */
				/* } */

				/*
				 * pInputOpts->pszPassThroughParms = addPassThroughParm( c,
				 * optarg, pInputOpts->pszPassThroughParms );
				 */
				/* break; */

				/* This covers the long options equivalent to -X xxx. */
			case 0:
				break;

			case 1:
				/* gp-c remote compression program */
				pInputOpts->pszCompressionProgram = "gunzip";	/* Safe_strdup(optarg); */
				break;

			case 2:
				/* gp-cf control file */

				/*
				 * temporary disabled if ( bSawCDB_S_Option ) { Ignore gp_s
				 * option
				 *
				 * mpp_err_msg(logInfo, progname, "ignoring the gp-s
				 * option, since the gp-cf option is set.\n"); }
				 *
				 * if (!FillCDBSet(&pInputOpts->set, optarg)) exit(1);
				 */

				break;

			case 3:
				/* gp-d backup remote directory */
				pInputOpts->pszBackupDirectory = Safe_strdup(optarg);
				break;

			case 4:
				/* gp-e on error stop */
				pInputOpts->bOnErrorStop = false;
				break;

			case 5:
				/* gp-hdb master database name */
				/* pInputOpts->pszMasterDBName = Safe_strdup(optarg); */
				break;

			case 6:
				/* gp-k backup timestamp key */
				pInputOpts->pszKey = Safe_strdup(optarg);
				break;

			case 7:
				/* gp-r report directory */
				pInputOpts->pszReportDirectory = Safe_strdup(optarg);
				break;
			case 8:
				/* gp-s backup set specification */

				/*
				 * temporay disabled bSawCDB_S_Option = true; if (
				 * pInputOpts->set.type == SET_INDIVIDUAL ) { Ignore this, as
				 * we've already encountered an individual spec
				 * mpp_err_msg(logInfo, progname, "ignoring the gp-s
				 * option, since the gp-cf option is set.\n"); } else
				 *
				 *
				 *
				 * { if ( strcasecmp( optarg, "a") == 0 ) pInputOpts->set.type
				 * = SET_ALL; else if ( strcasecmp( optarg, "t") == 0 )
				 * pInputOpts->set.type = SET_SEGDBS_ONLY; else if (
				 * strcasecmp( optarg, "h") == 0 ) pInputOpts->set.type =
				 * SET_MASTER_ONLY; else { mpp_err_msg(logInfo, progname,
				 * "invalid gp-s option %s.  Must be a, t, or h.\n", optarg);
				 * exit(1); } } break;
				 */
			case 9:

				/* gp-l backup file location */
				if (strcasecmp(optarg, "p") == 0)
				{
					pInputOpts->backupLocation = FILE_ON_PRIMARIES;
					pInputOpts->pszRawDumpSet = NULL;
				}
				else if (strncasecmp(optarg, "i", 1) == 0)
				{
					pInputOpts->backupLocation = FILE_ON_INDIVIDUAL;
					pInputOpts->pszRawDumpSet = Safe_strdup(optarg);
				}
				else
				{
					mpp_err_msg_cache(logError, progname, "invalid gp-l option %s.  Must be p (on primary segments), or i[dbid list] for \"individual\".\n", optarg);
					return false;
				}
				break;
#ifdef USE_DDBOOST
			case 10:
				dd_boost_enabled = 1;
				break;
#endif
			case 11:
				pInputOpts->pszPassThroughParms = addPassThroughLongParm("gp-f", optarg, pInputOpts->pszPassThroughParms);
				break;

			case 12:
				bAoStats = false;
				break;
			case 13:
745 746
				appendPQExpBuffer(dump_prefix_buf, "%s", optarg);
				pInputOpts->pszPassThroughParms = addPassThroughLongParm("prefix", dump_prefix_buf->data, pInputOpts->pszPassThroughParms);
747 748
				break;
			case 14:
749 750
				appendPQExpBuffer(dir_buf, "%s", optarg);
				pInputOpts->pszPassThroughParms = addPassThroughLongParm("status", dir_buf->data, pInputOpts->pszPassThroughParms);
751 752 753 754
				break;
			case 15:
				netbackup_service_host = Safe_strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughLongParm("netbackup-service-host", netbackup_service_host, pInputOpts->pszPassThroughParms);
755 756
				if (netbackup_service_host != NULL)
					free(netbackup_service_host);
757 758 759 760
				break;
			case 16:
				netbackup_block_size = Safe_strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughLongParm("netbackup-block-size", netbackup_block_size, pInputOpts->pszPassThroughParms);
761 762
				if (netbackup_block_size != NULL)
					free(netbackup_block_size);
763
				break;
764 765 766
			case 17:
				change_schema = Safe_strdup(optarg);
				pInputOpts->pszPassThroughParms = addPassThroughLongParm("change-schema", change_schema, pInputOpts->pszPassThroughParms);
767
				if (change_schema != NULL)
768 769
					free(change_schema);
				break;
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 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 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
			default:
				mpp_err_msg_cache(logError, progname, "Try \"%s --help\" for more information.\n", progname);
				return false;
		}
	}


	/* If postdataSchemaRestore is specified with -s option then only schema is restored and not postdataSchema.*/
	if (schemaOnly && postdataSchemaRestore && !dataOnly)
	{
		schemaRestore = true;
		postdataRestore = false;
	}

	/* If postdataSchemaRestore is specified without -s and -a option then only postdataSchema is restored. */
	if (postdataSchemaRestore && !schemaOnly && !dataOnly)
	{
		postdataRestore = true;
		schemaRestore = false;
		dataRestore = false;
	}

	
#ifdef USE_DDBOOST
        if (dd_boost_enabled)
	{
                pInputOpts->pszPassThroughParms = addPassThroughLongParm("dd_boost_enabled", NULL, pInputOpts->pszPassThroughParms);
		if (pInputOpts->pszBackupDirectory)
                	pInputOpts->pszPassThroughParms = addPassThroughLongParm("dd_boost_dir", pInputOpts->pszBackupDirectory, pInputOpts->pszPassThroughParms);
		else
			pInputOpts->pszPassThroughParms = addPassThroughLongParm("dd_boost_dir", "db_dumps", pInputOpts->pszPassThroughParms);
	}
#endif

	/*
	 * get PG env variables, override only of no cmd-line value specified
	 */
	if (pInputOpts->pszDBName == NULL)
	{
		if (getenv("PGDATABASE") != NULL)
		{
			pInputOpts->pszDBName = Safe_strdup(getenv("PGDATABASE"));
			pInputOpts->pszMasterDBName = Safe_strdup(getenv("PGDATABASE")); /* TODO: is this variable redundant? */
		}
	}

	if (pInputOpts->pszPGPort == NULL)
	{
		if (getenv("PGPORT") != NULL)
			pInputOpts->pszPGPort = Safe_strdup(getenv("PGPORT"));
	}

	if (pInputOpts->pszPGHost == NULL)
	{
		if (getenv("PGHOST") != NULL)
			pInputOpts->pszPGHost = Safe_strdup(getenv("PGHOST"));
	}


	/*
	 * Check for cmd line parameter errors.
	 */
	if (pInputOpts->pszDBName == NULL)
	{
		mpp_err_msg_cache(logError, progname, "%s command line missing the database parameter (-d)\n", progname);
		return false;
	}

	opts->useDB = 1;

	if (pInputOpts->pszKey == NULL)
	{
		mpp_err_msg_cache(logError, progname, "%s command line missing the date time backup key parameter (--gp-k)\n", progname);
		return false;
	}

	if (pInputOpts->pszMasterDBName == NULL)
	{
		mpp_err_msg_cache(logError, progname, "%s command line missing the master database parameter (--)\n", progname);
		return false;
	}

	if ((dataOnly || schemaOnly) && pInputOpts->backupLocation == FILE_ON_INDIVIDUAL)
	{
		mpp_err_msg_cache(logError, progname, "options \"schema only\" (-s) or \"data only\" (-a) cannot be used together with --gp-s=i\n"
						  "If you want to use --gp-i and dump only data, omit dbid number 1 (master) from the individual dbid list.\n");
		return false;
	}


	if (opts->formatName == NULL)
	{
		opts->formatName = "p";
	}

	opts->disable_triggers = disable_triggers;
	bForcePassword = (opts->promptPassword == TRI_YES);
	/* bIgnoreVersion = (opts->ignoreVersion == 1); */
	if (opts->formatName)
	{

		switch (opts->formatName[0])
		{

			case 'c':
			case 'C':
				opts->format = archCustom;
				break;

			case 'f':
			case 'F':
				opts->format = archFiles;
				break;

			case 't':
			case 'T':
				opts->format = archTar;
				break;

			case 'p':
			case 'P':
				opts->format = archNull;
				break;

			default:
				mpp_err_msg_cache(logError, progname, "unrecognized archive format '%s'; please specify 'p', 't', or 'c'\n",
								  opts->formatName);
				return false;
		}
	}

	return true;

}

/*
 * parmValNeedsQuotes: This function checks to see whether there is any whitespace in the parameter value.
 * This is used for pass thru parameters, top know whether to enclose them in quotes or not.
 */
bool
parmValNeedsQuotes(const char *Value)
{
	static regex_t rFinder;
	static bool bCompiled = false;
	static bool bAlwaysPutQuotes = false;
	bool		bPutQuotes = false;

	if (!bCompiled)
	{
		if (0 != regcomp(&rFinder, "[[:space:]]", REG_EXTENDED | REG_NOSUB))
			bAlwaysPutQuotes = true;

		bCompiled = true;
	}

	if (!bAlwaysPutQuotes)
	{
		if (regexec(&rFinder, Value, 0, NULL, 0) == 0)
			bPutQuotes = true;
	}
	else
		bPutQuotes = true;

	return bPutQuotes;
}

/*
 * addPassThroughParm: this function adds to the string of pass-through parameters.  These get sent to each
 * backend and get passed to the gp_dump program.
 */
char *
addPassThroughParm(char Parm, const char *pszValue, char *pszPassThroughParmString)
{
	char	   *pszRtn;
	bool		bFirstTime = (pszPassThroughParmString == NULL);

	if (pszValue != NULL)
	{
		if (parmValNeedsQuotes(pszValue))
		{
			if (bFirstTime)
				pszRtn = MakeString("-%c \"%s\"", Parm, pszValue);
			else
				pszRtn = MakeString("%s -%c \"%s\"", pszPassThroughParmString, Parm, pszValue);
		}
		else
		{
			if (bFirstTime)
				pszRtn = MakeString("-%c %s", Parm, pszValue);
			else
				pszRtn = MakeString("%s -%c %s", pszPassThroughParmString, Parm, pszValue);
		}
	}
	else
	{
		if (bFirstTime)
			pszRtn = MakeString("-%c", Parm);
		else
			pszRtn = MakeString("%s -%c", pszPassThroughParmString, Parm);
	}

	return pszRtn;
}

/* threadProc: This function is used to connect to one database that needs to be restored,
 * make a gp_restore_launch call to cause the restore process to begin on the instance hosting the
 * database.  Then it waits for notifications from the process.  It receives a notification
 * wnenever the gp_restore_agent process signals with a NOTIFY. This happens when the process starts,
 * and when it finishes.
 */
void *
threadProc(void *arg)
{
	/*
	 * The argument is a pointer to a ThreadParm structure that stays around
	 * for the entire time the program is running. so we need not worry about
	 * making a copy of it.
	 */
	ThreadParm *pParm = (ThreadParm *) arg;

	SegmentDatabase *sSegDB = pParm->pSourceSegDBData;
	SegmentDatabase *tSegDB = pParm->pTargetSegDBData;
	const InputOptions *pInputOpts = pParm->pOptionsData;
	const char *pszKey = pInputOpts->pszKey;
	PGconn	   *pConn;
	char	   *pszPassThroughCredentials;
	char	   *pszPassThroughTargetInfo;
	PQExpBuffer Qry;
998
	PQExpBuffer pqBuffer;
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
	PGresult   *pRes;
	int			sock;
	bool		bSentCancelMessage;
	bool		bIsFinished;
	bool		bIsStarted;
	int			nTries;
	char	   *pszNotifyRelName;
	char	   *pszNotifyRelNameStart;
	char	   *pszNotifyRelNameSucceed;
	char	   *pszNotifyRelNameFail;
	PGnotify   *pNotify;
	int			nNotifies;
	struct pollfd *pollInput;
	int 		pollResult = 0;
	int			pollTimeout;

	/*
	 * Block SIGINT and SIGKILL signals (we can handle them in the main
	 * thread)
	 */
	sigset_t	newset;

	sigemptyset(&newset);
	sigaddset(&newset, SIGINT);
	sigaddset(&newset, SIGKILL);
	pthread_sigmask(SIG_SETMASK, &newset, NULL);

	/* Create a connection for this thread */
	if (strcasecmp(pInputOpts->pszDBName, pInputOpts->pszMasterDBName) != 0)
	{
		if (sSegDB->pszDBName != NULL)
			free(sSegDB->pszDBName);

		sSegDB->pszDBName = Safe_strdup(pInputOpts->pszDBName);
	}

1035
	/* connect to the source segDB to start gp_restore_agent there */
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
	pConn = MakeDBConnection(sSegDB, false);
	if (PQstatus(pConn) == CONNECTION_BAD)
	{
		g_b_SendCancelMessage = true;
		pParm->pszErrorMsg = MakeString("Connection to dbid %d on host %s failed: %s",
										sSegDB->dbid, StringNotNull(sSegDB->pszHost, "localhost"), PQerrorMessage(pConn));
		mpp_err_msg_cache(logError, progname, pParm->pszErrorMsg);
		PQfinish(pConn);
		return NULL;
	}

	/* issue a LISTEN command for 3 different names */
	DoCancelNotifyListen(pConn, true, pszKey, sSegDB->role, sSegDB->dbid, tSegDB->dbid, SUFFIX_START);
	DoCancelNotifyListen(pConn, true, pszKey, sSegDB->role, sSegDB->dbid, tSegDB->dbid, SUFFIX_SUCCEED);
	DoCancelNotifyListen(pConn, true, pszKey, sSegDB->role, sSegDB->dbid, tSegDB->dbid, SUFFIX_FAIL);

	mpp_err_msg(logInfo, progname, "Listening for messages from dbid %d server (source) for dbid %d restore\n", sSegDB->dbid, tSegDB->dbid);

	/* Execute gp_restore_launch  */

	/*
	 * If there is a password associated with this login, we pass it as a
	 * base64 encoded string in the parameter pszPassThroughCredentials
	 */
	pszPassThroughCredentials = NULL;
	if (sSegDB->pszDBPswd != NULL && *sSegDB->pszDBPswd != '\0')
		pszPassThroughCredentials = DataToBase64(sSegDB->pszDBPswd, strlen(sSegDB->pszDBPswd));

	pszPassThroughTargetInfo = MakeString("--target-dbid %d --target-host %s --target-port %d ",
								tSegDB->dbid, tSegDB->pszHost, tSegDB->port);

	Qry = createPQExpBuffer();
	appendPQExpBuffer(Qry, "SELECT * FROM gp_restore_launch('%s', '%s', '%s', '%s', '%s', '%s', %d, %s)",
					  StringNotNull(pInputOpts->pszBackupDirectory, ""),
					  pszKey,
					  StringNotNull(pInputOpts->pszCompressionProgram, ""),
					  StringNotNull(pInputOpts->pszPassThroughParms, ""),
					  StringNotNull(pszPassThroughCredentials, ""),
					  StringNotNull(pszPassThroughTargetInfo, ""),
					  tSegDB->dbid,
					  pInputOpts->bOnErrorStop ? "true" : "false");

	if (pszPassThroughCredentials != NULL)
		free(pszPassThroughCredentials);

	if (pszPassThroughTargetInfo != NULL)
		free(pszPassThroughTargetInfo);

	pRes = PQexec(pConn, Qry->data);
	if (!pRes || PQresultStatus(pRes) != PGRES_TUPLES_OK || PQntuples(pRes) == 0)
	{
		g_b_SendCancelMessage = true;
		pParm->pszErrorMsg = MakeString("could not start Greenplum Database restore: %s", PQerrorMessage(pConn));
		mpp_err_msg_cache(logError, progname, pParm->pszErrorMsg);
		PQfinish(pConn);
		return NULL;
	}

	mpp_err_msg(logInfo, progname, "Successfully launched Greenplum Database restore on dbid %d to restore dbid %d\n", sSegDB->dbid, tSegDB->dbid);

	pParm->pszRemoteBackupPath = strdup(PQgetvalue(pRes, 0, 0));

	PQclear(pRes);
	destroyPQExpBuffer(Qry);

	/* Now wait for notifications from the back end back end */
	sock = PQsocket(pConn);

	bSentCancelMessage = false;
	bIsFinished = false;
	bIsStarted = false;
	nTries = 0;

	pszNotifyRelName = MakeString("N%s_%d_%d_T%d",
						   pszKey, sSegDB->role, sSegDB->dbid, tSegDB->dbid);
	pszNotifyRelNameStart = MakeString("%s_%s", pszNotifyRelName, SUFFIX_START);
	pszNotifyRelNameSucceed = MakeString("%s_%s", pszNotifyRelName, SUFFIX_SUCCEED);
	pszNotifyRelNameFail = MakeString("%s_%s", pszNotifyRelName, SUFFIX_FAIL);

	pollInput = (struct pollfd *)malloc(sizeof(struct pollfd));
	
	while (!bIsFinished)
	{
		/*
		 * Check to see whether another thread has failed and therefore we
		 * should cancel
		 */
		if (g_b_SendCancelMessage && !bSentCancelMessage && bIsStarted)
		{
			mpp_err_msg(logInfo, progname, "noticed that a cancel order is in effect. Informing dbid %d on host %s\n",
				  sSegDB->dbid, StringNotNull(sSegDB->pszHost, "localhost"));

			/*
			 * Either one of the other threads have failed, or a Ctrl C was
			 * received.  So post a cancel message
			 */
			DoCancelNotifyListen(pConn, false, pszKey, sSegDB->role, sSegDB->dbid, tSegDB->dbid, NULL);
			bSentCancelMessage = true;
		}
		
		/* Replacing select() by poll() here to overcome the limitations of 
		select() to handle large socket file descriptor values.
		*/

		pollInput->fd = sock;
		pollInput->events = POLLIN;
		pollInput->revents = 0; 		
		pollTimeout = 2000;
		pollResult = poll(pollInput, 1, pollTimeout);

		if(pollResult < 0) 
		{
			g_b_SendCancelMessage = true;
			pParm->pszErrorMsg = MakeString("poll failed for backup key %s, source dbid %d, target dbid %d failed\n",
										 pszKey, sSegDB->dbid, tSegDB->dbid);
			mpp_err_msg(logError, progname, pParm->pszErrorMsg);
			PQfinish(pConn);
1153 1154 1155 1156 1157
			free(pszNotifyRelName);
			free(pszNotifyRelNameStart);
			free(pszNotifyRelNameSucceed);
			free(pszNotifyRelNameFail);
			free(pollInput);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
			return NULL;
		}

		/* See whether the connection went down */
		if (PQstatus(pConn) == CONNECTION_BAD)
		{
			g_b_SendCancelMessage = true;
			pParm->pszErrorMsg = MakeString("connection went down for backup key %s, source dbid %d, target dbid %d\n",
										 pszKey, sSegDB->dbid, tSegDB->dbid);
			mpp_err_msg(logFatal, progname, pParm->pszErrorMsg);
1168 1169 1170 1171 1172
			free(pszNotifyRelName);
			free(pszNotifyRelNameStart);
			free(pszNotifyRelNameSucceed);
			free(pszNotifyRelNameFail);
			free(pollInput);
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
			PQfinish(pConn);
			return NULL;
		}

		PQconsumeInput(pConn);

		nNotifies = 0;
		while (NULL != (pNotify = PQnotifies(pConn)))
		{
			if (strncasecmp(pszNotifyRelName, pNotify->relname, strlen(pszNotifyRelName)) == 0)
			{
				nNotifies++;
				if (strcasecmp(pszNotifyRelNameStart, pNotify->relname) == 0)
				{
					bIsStarted = true;
					mpp_err_msg(logInfo, progname, "restore started for source dbid %d, target dbid %d on host %s\n",
								sSegDB->dbid, tSegDB->dbid, StringNotNull(sSegDB->pszHost, "localhost"));
				}
				else if (strcasecmp(pszNotifyRelNameSucceed, pNotify->relname) == 0)
				{
					bIsFinished = true;
					pParm->bSuccess = true;
					mpp_err_msg(logInfo, progname, "restore succeeded for source dbid %d, target dbid %d on host %s\n",
								sSegDB->dbid, tSegDB->dbid, StringNotNull(sSegDB->pszHost, "localhost"));
				}
				else if (strcasecmp(pszNotifyRelNameFail, pNotify->relname) == 0)
				{
					g_b_SendCancelMessage = true;
					bIsFinished = true;
					pParm->bSuccess = false;
1203
					pqBuffer = createPQExpBuffer();
1204
					/* Make call to get error message from file on server */
1205 1206 1207
					ReadBackendBackupFileError(pConn, dir_buf->data, pszKey, BFT_RESTORE_STATUS, progname, pqBuffer);
					pParm->pszErrorMsg = MakeString("%s", pqBuffer->data);
					destroyPQExpBuffer(pqBuffer);
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235

					mpp_err_msg(logError, progname, "restore failed for source dbid %d, target dbid %d on host %s\n",
								sSegDB->dbid, tSegDB->dbid, StringNotNull(sSegDB->pszHost, "localhost"));
				}
			}

			PQfreemem(pNotify);
		}

		if (nNotifies == 0)
		{
			if (!bIsStarted)
			{
				nTries++;
				/* increase timeout to 10min for heavily loaded system */
				if (nTries == 300)
				{
					bIsFinished = true;
					pParm->bSuccess = false;
					pParm->pszErrorMsg = MakeString("restore failed to start for source dbid %d, target dbid %d on host %s in the required time interval\n",
													sSegDB->dbid, tSegDB->dbid, StringNotNull(sSegDB->pszHost, "localhost"));
					DoCancelNotifyListen(pConn, false, pszKey, sSegDB->role, sSegDB->dbid, tSegDB->dbid, NULL);
					bSentCancelMessage = true;
				}
			}
		}
	}

1236 1237 1238 1239 1240 1241 1242
	/*
	 * If segment reports success or no errors so far, scan of the restore status file
	 * for ERRORS and report them if found
	 */
	if(pParm->bSuccess || pParm->pszErrorMsg == NULL)
	{
		pqBuffer = createPQExpBuffer();
1243
		int status = ReadBackendBackupFileError(pConn, dir_buf == NULL ? "" : dir_buf->data, pszKey, BFT_RESTORE_STATUS, progname, pqBuffer);
1244 1245
		if (status != 0)
		{
1246
			pParm->pszErrorMsg = MakeString("%s", pqBuffer->data);
1247
		}
1248
		destroyPQExpBuffer(pqBuffer);
1249 1250
	}

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
	if (pszNotifyRelName != NULL)
		free(pszNotifyRelName);
	if (pszNotifyRelNameStart != NULL)
		free(pszNotifyRelNameStart);
	if (pszNotifyRelNameSucceed != NULL)
		free(pszNotifyRelNameSucceed);
	if (pszNotifyRelNameFail != NULL)
		free(pszNotifyRelNameFail);

	PQfinish(pConn);

	return (NULL);
}

/*
 * installSignalHandlers: This function sets both the SIGINT and SIGTERM signal handlers
 * to the routine myHandler.
 */
void
installSignalHandlers(void)
{
	struct sigaction act,
				oact;

	act.sa_handler = myHandler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	act.sa_flags |= SA_RESTART;

	/* Install SIGINT interrupt handler */
	if (sigaction(SIGINT, &act, &oact) < 0)
	{
		mpp_err_msg_cache(logError, progname, "Error trying to set SIGINT interrupt handler\n");
	}

	act.sa_handler = myHandler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	act.sa_flags |= SA_RESTART;

	/* Install SIGTERM interrupt handler */
	if (sigaction(SIGTERM, &act, &oact) < 0)
	{
		mpp_err_msg_cache(logError, progname, "Error trying to set SIGTERM interrupt handler\n");
	}
}

/*
 * myHandler: This function is the signal handler for both SIGINT and SIGTERM signals.
 * It simply sets a global variable, which is checked by each thread to see whether it
 * should cancel the restore running on the remote database.
 */
void
myHandler(SIGNAL_ARGS)
{
	static bool bAlreadyHere = false;

	if (bAlreadyHere)
	{
		return;
	}

	bAlreadyHere = true;

	g_b_SendCancelMessage = true;
}

bool
restoreMaster(InputOptions * pInputOpts,
			  PGconn *pConn,
			  SegmentDatabase *sSegDB,
			  SegmentDatabase *tSegDB,
			  ThreadParm * pParm)
{
	bool		rtn = false;
	bool		bForcePassword = false;
	/*bool		bIgnoreVersion = false;*/

	memset(pParm, 0, sizeof(ThreadParm));

	/* We need to restore the master */
	mpp_err_msg(logInfo, progname, "Starting to restore the master database.\n");

	if (opts != NULL && opts->promptPassword == TRI_YES)
		bForcePassword = true;

	/* Now, spin off a thread to do the restore, and wait for it to finish */
	pParm->thread = 0;
	pParm->pTargetSegDBData = tSegDB;
	pParm->pSourceSegDBData = sSegDB;
	pParm->pOptionsData = pInputOpts;
1342
	pParm->bSuccess = true;
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
	pParm->pszErrorMsg = NULL;
	pParm->pszRemoteBackupPath = NULL;

	mpp_err_msg(logInfo, progname, "Creating thread to restore master database: host %s port %d database %s\n",
				StringNotNull(pParm->pTargetSegDBData->pszHost, "localhost"),
				pParm->pTargetSegDBData->port,
				pParm->pTargetSegDBData->pszDBName
		);

	pthread_create(&pParm->thread,
				   NULL,
				   threadProc,
				   pParm);

	pthread_join(pParm->thread, NULL);
	pParm->thread = (pthread_t) 0;

	if (pParm->bSuccess)
	{
		mpp_err_msg(logInfo, progname, "Successfully restored master database: host %s port %d database %s\n",
				StringNotNull(pParm->pTargetSegDBData->pszHost, "localhost"),
					pParm->pTargetSegDBData->port,
					pParm->pTargetSegDBData->pszDBName
			);
		rtn = true;
	}
	else
	{
		if (pParm->pszErrorMsg != NULL)
			mpp_err_msg(logError, progname, "see error report for details\n");
		else
		{
			mpp_err_msg(logError, progname, "Failed to restore master database: host %s port %d database %s\n",
				StringNotNull(pParm->pTargetSegDBData->pszHost, "localhost"),
						pParm->pTargetSegDBData->port,
						pParm->pTargetSegDBData->pszDBName
				);
		}
	}

	return rtn;
}

/*
 * updateAppendOnlyStats
 *
 * for every append only that exists in the database (whether we just restored
 * it or not) update its statistics on the master - note that this must not be
 * made with utility mode connection, but rather a regular connection.
 */
void
updateAppendOnlyStats(PGconn *pConn)
{
	/* query that gets all ao tables in the database */
	PQExpBuffer get_query = createPQExpBuffer();
	PGresult   *get_res;
	int			get_ntups = 0;

	/* query that updates all ao tables in the database */
	PQExpBuffer update_query = createPQExpBuffer();
	PGresult   *update_res = NULL;
	int			update_ntups = 0;

	/* misc */
	int			i_tablename = 0;
	int			i_schemaname = 0;
	int			i = 0;

	mpp_err_msg(logInfo, progname, "updating Append Only table statistics\n");

	/* Fetch all Append Only tables */
	appendPQExpBuffer(get_query,
					  "SELECT c.relname,n.nspname "
					  "FROM pg_class c, pg_namespace n "
					  "WHERE c.relnamespace=n.oid "
					  "AND (c.relstorage='a' OR c.relstorage='c')");

	get_res = PQexec(pConn, get_query->data);

	if (!get_res || PQresultStatus(get_res) != PGRES_TUPLES_OK)
	{
		const char *err;

		if (get_res)
			err = PQresultErrorMessage(get_res);
		else
			err = PQerrorMessage(pConn);

		mpp_err_msg(logWarn, progname,
					"Failed to get Append Only tables for updating stats. "
					"error was: %s\n", err);

	}
	else
	{
		/* A-OK */
		get_ntups = PQntuples(get_res);
		i_tablename = PQfnumber(get_res, "relname");
		i_schemaname = PQfnumber(get_res, "nspname");

		for (i = 0; i < get_ntups; i++)
		{
			char	   *tablename = PQgetvalue(get_res, i, i_tablename);
			char	   *schemaname = PQgetvalue(get_res, i, i_schemaname);

			resetPQExpBuffer(update_query);
			appendPQExpBuffer(update_query,
							  "SELECT * "
							  "FROM gp_update_ao_master_stats('%s.%s')",
							  schemaname, tablename);

			update_res = PQexec(pConn, update_query->data);

			if (!update_res || PQresultStatus(update_res) != PGRES_TUPLES_OK)
			{
				const char *err;

				if (update_res)
					err = PQresultErrorMessage(update_res);
				else
					err = PQerrorMessage(pConn);

				mpp_err_msg(logWarn, progname,
							"Failed to update Append Only table stats. error "
						"was: %s, query was: %s\n", err, update_query->data);
			}
			else
			{
				/* A-OK */
				update_ntups = PQntuples(update_res);
				if (update_ntups != 1)
					mpp_err_msg(logWarn, progname,
								"Expected 1 tuple, got %d. query was: %s\n",
								update_ntups, update_query->data);
			}
		}
	}

	/* clean up */
	if (update_res)
		PQclear(update_res);

	if (get_res)
		PQclear(get_res);

	destroyPQExpBuffer(get_query);
	destroyPQExpBuffer(update_query);

}

/*
 * spinOffThreads: This function deals with all the threads that drive the backend restores.
 * First, it initializes the ThreadParmArray.  Then it loops and creates each of the threads.
 * It then waits for all threads to finish.
 */
void
spinOffThreads(PGconn *pConn, InputOptions * pInputOpts, const RestorePairArray * restorePairAr, ThreadParmArray * pParmAr)
{
	int			i;

	/*
	 * Create a thread and have it work on executing the dump on the
	 * appropriate segdb.
	 */
	if (!createThreadParmArray(restorePairAr->count, pParmAr))
	{
		mpp_err_msg(logError, progname, "Cannot allocate memory for thread parameters\n");
		exit(-1);
	}

	for (i = 0; i < pParmAr->count; i++)
	{
		ThreadParm *pParm = &pParmAr->pData[i];

		pParm->pSourceSegDBData = &restorePairAr->pData[i].segdb_source;
		pParm->pTargetSegDBData = &restorePairAr->pData[i].segdb_target;
		pParm->pOptionsData = pInputOpts;
1520
		pParm->bSuccess = true;
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624

		/* exclude master node */
		if (pParm->pTargetSegDBData->role == ROLE_MASTER)
			continue;

		mpp_err_msg(logInfo, progname, "Creating thread to restore dbid %d (%s:%d) from backup file on dbid %d (%s:%d)\n",
					pParm->pTargetSegDBData->dbid,
				StringNotNull(pParm->pTargetSegDBData->pszHost, "localhost"),
					pParm->pTargetSegDBData->port,
					pParm->pSourceSegDBData->dbid,
				StringNotNull(pParm->pSourceSegDBData->pszHost, "localhost"),
					pParm->pSourceSegDBData->port);

		pthread_create(&pParm->thread,
					   NULL,
					   threadProc,
					   pParm);
	}

	mpp_err_msg(logInfo, progname, "Waiting for all remote %s programs to finish.\n", pszAgent);

	/* Wait for all threads to complete */
	for (i = 0; i < pParmAr->count; i++)
	{
		ThreadParm *pParm = &pParmAr->pData[i];

		/* exclude master node and not valid node */
		if (pParm->thread == (pthread_t) 0)
			continue;
		pthread_join(pParm->thread, NULL);
		pParm->thread = (pthread_t) 0;
	}
}

/*
 * freeThreadParmArray: This function frees the memory allocated for the pData element of the
 * ThreadParmArray, as well as the strings allocated within each element
 * of the array.  It does not free the pParmAr itself.
 */
void
freeThreadParmArray(ThreadParmArray * pParmAr)
{
	int			i;

	for (i = 0; i < pParmAr->count; i++)
	{
		ThreadParm *p = &pParmAr->pData[i];

		if (p->pszRemoteBackupPath != NULL)
			free(p->pszRemoteBackupPath);

		if (p->pszErrorMsg != NULL)
			free(p->pszErrorMsg);
	}

	if (pParmAr->pData != NULL)
		free(pParmAr->pData);

	pParmAr->count = 0;
	pParmAr->pData = NULL;
}

/*
 * createThreadParmArray: This function initializes the count and pData elements of the ThreadParmArray.
 */
bool
createThreadParmArray(int nCount, ThreadParmArray * pParmAr)
{
	int			i;

	pParmAr->count = nCount;
	pParmAr->pData = (ThreadParm *) malloc(nCount * sizeof(ThreadParm));
	if (pParmAr->pData == NULL)
		return false;

	for (i = 0; i < nCount; i++)
	{
		ThreadParm *p = &pParmAr->pData[i];

		p->thread = 0;
		p->pSourceSegDBData = NULL;
		p->pTargetSegDBData = NULL;
		p->pOptionsData = NULL;
		p->bSuccess = true;
		p->pszErrorMsg = NULL;
		p->pszRemoteBackupPath = NULL;
	}

	return true;
}

/*
 * reportRestoreResults: This function outputs a summary of the restore results to a file or to stdout
 */
int
reportRestoreResults(const char *pszReportDirectory, const ThreadParm * pMasterParm, const ThreadParmArray * pParmAr)
{
	InputOptions *pOptions;
	PQExpBuffer reportBuf = NULL;
	FILE	   *fRptFile = NULL;
	char	   *pszReportPathName = NULL;
	char	   *pszFormat;
	int			i;
	int			failCount;
1625
	int			errorCount;
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
	const ThreadParm *pParm;
	char	   *pszStatus;
	char	   *pszMsg;

	assert(pParmAr != NULL && pMasterParm != NULL);

	if (pParmAr->count == 0 && pMasterParm->pOptionsData == NULL)
	{
		mpp_err_msg(logInfo, progname, "No results to report.");
		return 0;
	}

	pOptions = (pParmAr->count > 0) ? pParmAr->pData[0].pOptionsData : pMasterParm->pOptionsData;
	assert(pOptions != NULL);


	/*
	 * Set the report directory if not set by user (with --gp-r)
	 */
	if (pszReportDirectory == NULL || *pszReportDirectory == '\0')
	{

		if (getenv("MASTER_DATA_DIRECTORY") != NULL)
		{
			/*
			 * report directory not set by user - default to
			 * $MASTER_DATA_DIRECTORY
			 */
1654
			pszReportDirectory = getenv("MASTER_DATA_DIRECTORY");
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
		}
		else
		{
			/* $MASTER_DATA_DIRECTORY not set. Default to current directory */
			pszReportDirectory = "./";
		}
	}

	/* See whether we can create the file in the report directory */
	if (pszReportDirectory[strlen(pszReportDirectory) - 1] != '/')
		pszFormat = "%s/%sgp_restore_%s.rpt";
	else
		pszFormat = "%s%sgp_restore_%s.rpt";

1669 1670 1671 1672 1673 1674 1675
	pszReportPathName = MakeString(pszFormat, pszReportDirectory, dump_prefix_buf == NULL ? "" : dump_prefix_buf->data, pOptions->pszKey);

	if (pszReportPathName == NULL)
	{
		mpp_err_msg(logError, progname, "Cannot allocate memory for report file path\n");
		exit(-1);
	}
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

	fRptFile = fopen(pszReportPathName, "w");
	if (fRptFile == NULL)
		mpp_err_msg(logWarn, progname, "Cannot open report file %s for writing.  Will use stdout instead.\n",
					pszReportPathName);

	/* buffer to store the complete restore report */
	reportBuf = createPQExpBuffer();

	/*
	 * Write to buffer a report showing the timestamp key, what the command
	 * line options were, which segment databases were backed up, to where,
	 * and any errors that occurred.
	 */
	appendPQExpBuffer(reportBuf, "\nGreenplum Database Restore Report\n");
	appendPQExpBuffer(reportBuf, "Timestamp Key: %s\n", pOptions->pszKey);

	appendPQExpBuffer(reportBuf, "gp_restore Command Line: %s\n",
					  StringNotNull(pOptions->pszCmdLineParms, "None"));

	appendPQExpBuffer(reportBuf, "Pass through Command Line Options: %s\n",
					  StringNotNull(pOptions->pszPassThroughParms, "None"));

	appendPQExpBuffer(reportBuf, "Compression Program: %s\n",
					  StringNotNull(pOptions->pszCompressionProgram, "None"));

	appendPQExpBuffer(reportBuf, "\n");
	appendPQExpBuffer(reportBuf, "Individual Results\n");

	failCount = 0;
1706
	errorCount = 0;
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
	for (i = 0; i < pParmAr->count + 1; i++)
	{
		if (i == 0)
		{
			if (pMasterParm->pOptionsData != NULL)
				pParm = pMasterParm;
			else
				continue;
		}
		else
		{
			pParm = &pParmAr->pData[i - 1];
			if (pParm->pTargetSegDBData->role == ROLE_MASTER)
				continue;
		}

1723
		pszMsg = pParm->pszErrorMsg;
1724
		if (!pParm->bSuccess)
1725 1726
		{
			pszStatus = "Failed with error: \n{\n";
1727
			failCount++;
1728 1729 1730 1731 1732 1733 1734 1735
		}
		else if (pParm->bSuccess && pszMsg != NULL)
		{
			pszStatus = "Completed but errors were found: \n{\n";
			errorCount++;
		}
		else
			pszStatus = "Succeeded";
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
		if (pszMsg == NULL)
			pszMsg = "";

		appendPQExpBuffer(reportBuf, "\tRestore of %s on dbid %d (%s:%d) from %s: %s%s%s\n",
						  pParm->pTargetSegDBData->pszDBName,
						  pParm->pTargetSegDBData->dbid,
				StringNotNull(pParm->pTargetSegDBData->pszHost, "localhost"),
						  pParm->pTargetSegDBData->port,
						  StringNotNull(pParm->pszRemoteBackupPath, ""),
						  pszStatus,
						  pszMsg,
						  (strcmp(pszMsg, "") == 0) ? "" : "}"
			);
	}

1751
	if (failCount == 0 && errorCount == 0)
1752
		appendPQExpBuffer(reportBuf, "\n%s  utility finished successfully.\n", progname);
1753
	else if (failCount > 0)
1754
		appendPQExpBuffer(reportBuf, "\n%s  utility finished unsuccessfully with  %d  failures.\n", progname, failCount);
1755 1756
	else
		appendPQExpBuffer(reportBuf, "\n%s  utility finished but errors were found.\n", progname);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773

	/* write report to report file */
	if (fRptFile != NULL)
	{
		mpp_msg(logInfo, progname, "Report results also written to %s.\n", pszReportPathName);
		fprintf(fRptFile, "%s", reportBuf->data);
		fclose(fRptFile);
	}

	/* write report to stdout */
	fprintf(stdout, "%s", reportBuf->data);

	if (pszReportPathName != NULL)
		free(pszReportPathName);

	destroyPQExpBuffer(reportBuf);

1774 1775 1776 1777 1778
	if (failCount > 0)
		return 1;
	else if (errorCount > 0)
		return 2;
	return 0;
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
}

/*
 * the same as reportRestoreResults but only for the master. This is a little ugly
 * since we repeat some of the code but we need a majoy overhaul in dump/restore
 * anyhow - so it will do for now.
 */
int
reportMasterError(InputOptions inputopts, const ThreadParm * pMasterParm, const char *localMsg)
{
	InputOptions *pOptions;
	PQExpBuffer reportBuf = NULL;
	FILE	   *fRptFile = NULL;
	char	   *pszReportPathName = NULL;
	char	   *pszFormat;
	int			failCount;
	const ThreadParm *pParm;
	char	   *pszStatus;
	char	   *pszMsg;
	char	   *pszReportDirectory;

	assert(pMasterParm != NULL);

	if (pMasterParm->pOptionsData == NULL)
	{
		pOptions = &inputopts;
	}
	else
	{
		pOptions = pMasterParm->pOptionsData;
	}

	/* generate a timestamp key if we haven't already */
	if (!pOptions->pszKey)
		pOptions->pszKey = GenerateTimestampKey();

	/*
	 * Set the report directory if not set by user (with --gp-r)
	 */
	pszReportDirectory = pOptions->pszReportDirectory;
	if (pszReportDirectory == NULL || *pszReportDirectory == '\0')
	{

		if (getenv("MASTER_DATA_DIRECTORY") != NULL)
		{
			/*
			 * report directory not set by user - default to
			 * $MASTER_DATA_DIRECTORY
			 */
1828
			pszReportDirectory = getenv("MASTER_DATA_DIRECTORY");
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
		}
		else
		{
			/* $MASTER_DATA_DIRECTORY not set. Default to current directory */
			pszReportDirectory = "./";
		}
	}

	/* See whether we can create the file in the report directory */
	if (pszReportDirectory[strlen(pszReportDirectory) - 1] != '/')
		pszFormat = "%s/gp_restore_%s.rpt";
	else
		pszFormat = "%sgp_restore_%s.rpt";

	pszReportPathName = MakeString(pszFormat, pszReportDirectory, pOptions->pszKey);

1845 1846 1847 1848 1849 1850
	if (pszReportPathName == NULL)
	{
		mpp_err_msg(logError, progname, "Cannot allocate memory for report file path\n");
		exit(-1);
	}

1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
	fRptFile = fopen(pszReportPathName, "w");
	if (fRptFile == NULL)
		mpp_err_msg(logWarn, progname, "Cannot open report file %s for writing.  Will use stdout instead.\n",
					pszReportPathName);

	/* buffer to store the complete restore report */
	reportBuf = createPQExpBuffer();

	/*
	 * Write to buffer a report showing the timestamp key, what the command
	 * line options were, which segment databases were backed up, to where,
	 * and any errors that occurred.
	 */
	appendPQExpBuffer(reportBuf, "\nGreenplum Database Restore Report\n");
	appendPQExpBuffer(reportBuf, "Timestamp Key: %s\n", pOptions->pszKey);

	appendPQExpBuffer(reportBuf, "gp_restore Command Line: %s\n",
					  StringNotNull(pOptions->pszCmdLineParms, "None"));

	appendPQExpBuffer(reportBuf, "Pass through Command Line Options: %s\n",
					  StringNotNull(pOptions->pszPassThroughParms, "None"));

	appendPQExpBuffer(reportBuf, "Compression Program: %s\n",
					  StringNotNull(pOptions->pszCompressionProgram, "None"));

	appendPQExpBuffer(reportBuf, "\n");
	appendPQExpBuffer(reportBuf, "Individual Results\n");


	failCount = 1;

	pParm = pMasterParm;

	pszStatus = "Failed with error: \n{";
	if (localMsg != NULL)
		pszMsg = (char *) localMsg;
	else
		pszMsg = pParm->pszErrorMsg;
	if (pszMsg == NULL)
		pszMsg = "";

	appendPQExpBuffer(reportBuf, "\tRestore of database \"%s\" on Master database: %s%s%s\n",
					  StringNotNull(pOptions->pszDBName, "UNSPECIFIED"),
					  pszStatus,
					  pszMsg,
					  (strcmp(pszMsg, "") == 0) ? "" : "}"
		);

	appendPQExpBuffer(reportBuf, "\n%s  utility finished unsuccessfully with 1 failure.\n", progname);

	/* write report to report file */
	if (fRptFile != NULL)
	{
		mpp_msg(logInfo, progname, "Report results also written to %s.\n", pszReportPathName);
		fprintf(fRptFile, "%s", reportBuf->data);
		fclose(fRptFile);
	}

	/* write report to stdout */
	fprintf(stdout, "%s", reportBuf->data);

	if (pszReportPathName != NULL)
		free(pszReportPathName);

	destroyPQExpBuffer(reportBuf);

	return failCount;
}

/*
 * addPassThroughLongParm: this function adds a long option to the string of pass-through parameters.
 * These get sent to each backend and get passed to the gp_dump_agent program.
 */
static char *
addPassThroughLongParm(const char *Parm, const char *pszValue, char *pszPassThroughParmString)
{
        char       *pszRtn;
        bool            bFirstTime = (pszPassThroughParmString == NULL);

        if (pszValue != NULL)
        {
                if (parmValNeedsQuotes(pszValue))
                {
                        PQExpBuffer valueBuf = createPQExpBuffer();

                        if (bFirstTime)
                                pszRtn = MakeString("--%s \"%s\"", Parm, shellEscape(pszValue, valueBuf));
                        else
                                pszRtn = MakeString("%s --%s \"%s\"", pszPassThroughParmString, Parm, shellEscape(pszValue, valueBuf));

                        destroyPQExpBuffer(valueBuf);
                }
                else
                {
                        if (bFirstTime)
                                pszRtn = MakeString("--%s %s", Parm, pszValue);
                        else
                                pszRtn = MakeString("%s --%s %s", pszPassThroughParmString, Parm, pszValue);
                }
        }
        else
        {
                if (bFirstTime)
                        pszRtn = MakeString("--%s", Parm);
                else
                        pszRtn = MakeString("%s --%s", pszPassThroughParmString, Parm);
        }

        return pszRtn;
}