fts.c 23.3 KB
Newer Older
1 2 3 4 5 6 7 8
/*-------------------------------------------------------------------------
 *
 * fts.c
 *	  Process under QD postmaster polls the segments on a periodic basis
 *    or at the behest of QEs.
 *
 * Maintains an array in shared memory containing the state of each segment.
 *
9 10 11 12 13 14 15
 * Portions Copyright (c) 2005-2010, Greenplum Inc.
 * Portions Copyright (c) 2011, EMC Corp.
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
 *
 *
 * IDENTIFICATION
 *	    src/backend/fts/fts.c
16 17 18 19 20 21 22 23 24 25
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <unistd.h>

#include "access/genam.h"
#include "access/heapam.h"
#include "catalog/gp_segment_config.h"
26
#include "catalog/pg_authid.h"
27 28 29
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "cdb/cdbvars.h"
30 31
#include "libpq-fe.h"
#include "libpq-int.h"
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include "cdb/cdbfts.h"
#include "postmaster/fork_process.h"
#include "postmaster/postmaster.h"
#include "postmaster/fts.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/pmsignal.h"			/* PostmasterIsAlive */
#include "storage/sinvaladt.h"
#include "utils/builtins.h"
#include "utils/faultinjector.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/relcache.h"
47
#include "utils/snapmgr.h"
48

49 50 51 52 53 54

#include "catalog/pg_authid.h"
#include "catalog/pg_database.h"
#include "catalog/pg_tablespace.h"
#include "catalog/catalog.h"

55
#include "catalog/gp_configuration_history.h"
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include "catalog/gp_segment_config.h"

#include "storage/backendid.h"

#include "executor/spi.h"

#include "tcop/tcopprot.h" /* quickdie() */


/*
 * CONSTANTS
 */
/* maximum number of segments */
#define MAX_NUM_OF_SEGMENTS  32768

71
bool am_ftshandler = false;
72 73 74 75
#ifndef USE_SEGWALREP
/* one byte of status for each segment */
static uint8 scan_status[MAX_NUM_OF_SEGMENTS];
#endif
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

#define GpConfigHistoryRelName    "gp_configuration_history"


/*
 * STATIC VARIABLES
 */

static bool am_ftsprobe = false;

static volatile bool shutdown_requested = false;
static volatile bool rescan_requested = false;
static volatile sig_atomic_t got_SIGHUP = false;

static char *probeDatabase = "postgres";

/*
 * FUNCTION PROTOTYPES
 */

#ifdef EXEC_BACKEND
static pid_t ftsprobe_forkexec(void);
#endif
NON_EXEC_STATIC void ftsMain(int argc, char *argv[]);
static void FtsLoop(void);

102
static CdbComponentDatabases *readCdbComponentInfoAndUpdateStatus(MemoryContext);
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 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 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 314 315 316 317 318 319 320 321

/*
 * Main entry point for ftsprobe process.
 *
 * This code is heavily based on pgarch.c, q.v.
 */
int
ftsprobe_start(void)
{
	pid_t		FtsProbePID;

#ifdef EXEC_BACKEND
	switch ((FtsProbePID = ftsprobe_forkexec()))
#else
	switch ((FtsProbePID = fork_process()))
#endif
	{
		case -1:
			ereport(LOG,
					(errmsg("could not fork ftsprobe process: %m")));
			return 0;

#ifndef EXEC_BACKEND
		case 0:
			/* in postmaster child ... */
			/* Close the postmaster's sockets */
			ClosePostmasterPorts(false);

			ftsMain(0, NULL);
			break;
#endif
		default:
			return (int)FtsProbePID;
	}

	
	/* shouldn't get here */
	return 0;
}


/*=========================================================================
 * HELPER FUNCTIONS
 */


#ifdef EXEC_BACKEND
/*
 * ftsprobe_forkexec()
 *
 * Format up the arglist for the ftsprobe process, then fork and exec.
 */
static pid_t
ftsprobe_forkexec(void)
{
	char	   *av[10];
	int			ac = 0;

	av[ac++] = "postgres";
	av[ac++] = "--forkftsprobe";
	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
	av[ac] = NULL;

	Assert(ac < lengthof(av));

	return postmaster_forkexec(ac, av);
}
#endif   /* EXEC_BACKEND */

inline bool
IsFtsShudownRequested(void) {
	return shutdown_requested;
}

static void
RequestShutdown(SIGNAL_ARGS)
{
	shutdown_requested = true;
}

/* SIGHUP: set flag to reload config file */
static void
sigHupHandler(SIGNAL_ARGS)
{
	got_SIGHUP = true;
}

/* SIGINT: set flag to run an fts full-scan */
static void
ReqFtsFullScan(SIGNAL_ARGS)
{
	rescan_requested = true;
}

/*
 * FtsProbeMain
 */
NON_EXEC_STATIC void
ftsMain(int argc, char *argv[])
{
	sigjmp_buf	local_sigjmp_buf;
	char	   *fullpath;

	IsUnderPostmaster = true;
	am_ftsprobe = true;

	/* Stay away from PMChildSlot */
	MyPMChildSlot = -1;

	/* reset MyProcPid */
	MyProcPid = getpid();
	
	/* Lose the postmaster's on-exit routines */
	on_exit_reset();

	/* Identify myself via ps */
	init_ps_display("ftsprobe process", "", "", "");

	SetProcessingMode(InitProcessing);

	/*
	 * reread postgresql.conf if requested
	 */
	pqsignal(SIGHUP, sigHupHandler);

	/*
	 * Presently, SIGINT will lead to autovacuum shutdown, because that's how
	 * we handle ereport(ERROR).  It could be improved however.
	 */
	pqsignal(SIGINT, ReqFtsFullScan);		/* request full-scan */
	pqsignal(SIGTERM, die);
	pqsignal(SIGQUIT, quickdie); /* we don't do any ftsprobe specific cleanup, just use the standard. */
	pqsignal(SIGALRM, handle_sig_alarm);

	pqsignal(SIGPIPE, SIG_IGN);
	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
	/* We don't listen for async notifies */
	pqsignal(SIGUSR2, RequestShutdown);
	pqsignal(SIGFPE, FloatExceptionHandler);
	pqsignal(SIGCHLD, SIG_DFL);

	/*
	 * Copied from bgwriter
	 */
	CurrentResourceOwner = ResourceOwnerCreate(NULL, "FTS Probe");

	/* Early initialization */
	BaseInit();

	/* See InitPostgres()... */
	InitProcess();	
	InitBufferPoolBackend();
	InitXLOGAccess();

	SetProcessingMode(NormalProcessing);

	/*
	 * If an exception is encountered, processing resumes here.
	 *
	 * See notes in postgres.c about the design of this coding.
	 */
	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
	{
		/* Prevents interrupts while cleaning up */
		HOLD_INTERRUPTS();

		/* Report the error to the server log */
		EmitErrorReport();

		/*
		 * We can now go away.	Note that because we'll call InitProcess, a
		 * callback will be registered to do ProcKill, which will clean up
		 * necessary state.
		 */
		proc_exit(0);
	}

	/* We can now handle ereport(ERROR) */
	PG_exception_stack = &local_sigjmp_buf;

	PG_SETMASK(&UnBlockSig);

	/*
	 * Add my PGPROC struct to the ProcArray.
	 *
	 * Once I have done this, I am visible to other backends!
	 */
	InitProcessPhase2();

	/*
	 * Initialize my entry in the shared-invalidation manager's array of
	 * per-backend data.
	 *
	 * Sets up MyBackendId, a unique backend identifier.
	 */
	MyBackendId = InvalidBackendId;

	SharedInvalBackendInit(false);

	if (MyBackendId > MaxBackends || MyBackendId <= 0)
		elog(FATAL, "bad backend id: %d", MyBackendId);

	/*
	 * bufmgr needs another initialization call too
	 */
	InitBufferPoolBackend();

	/* heap access requires the rel-cache */
	RelationCacheInitialize();
	InitCatalogCache();

	/*
	 * It's now possible to do real access to the system catalogs.
	 *
	 * Load relcache entries for the system catalogs.  This must create at
	 * least the minimum set of "nailed-in" cache entries.
	 */
	RelationCacheInitializePhase2();

322 323 324 325 326 327 328 329
	/*
	 * Start a new transaction here before first access to db, and get a
	 * snapshot.  We don't have a use for the snapshot itself, but we're
	 * interested in the secondary effect that it sets RecentGlobalXmin.
	 */
	StartTransactionCommand();
	(void) GetTransactionSnapshot();

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	/*
	 * In order to access the catalog, we need a database, and a
	 * tablespace; our access to the heap is going to be slightly
	 * limited, so we'll just use some defaults.
	 */
	if (!FindMyDatabase(probeDatabase, &MyDatabaseId, &MyDatabaseTableSpace))
		ereport(FATAL,
				(errcode(ERRCODE_UNDEFINED_DATABASE),
				 errmsg("database \"%s\" does not exit", probeDatabase)));

	/* Now we can mark our PGPROC entry with the database ID */
	/* (We assume this is an atomic store so no lock is needed) */
	MyProc->databaseId = MyDatabaseId;

	fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);

	SetDatabasePath(fullpath);

	RelationCacheInitializePhase3();

350 351 352
	/* close the transaction we started above */
	CommitTransactionCommand();

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
	/* shmem: publish probe pid */
	ftsProbeInfo->fts_probePid = MyProcPid;

	/* main loop */
	FtsLoop();

	/* One iteration done, go away */
	proc_exit(0);
}

/*
 * Populate cdb_component_dbs object by reading from catalog.  Use
 * probeContext instead of current memory context because current
 * context will be destroyed by CommitTransactionCommand().
 */
368 369
static
CdbComponentDatabases *readCdbComponentInfoAndUpdateStatus(MemoryContext probeContext)
370 371 372
{
	int i;
	MemoryContext save = MemoryContextSwitchTo(probeContext);
373 374
	/* cdbs is free'd by FtsLoop(). */
	CdbComponentDatabases *cdbs = getCdbComponentInfo(false);
375 376
	MemoryContextSwitchTo(save);

377
	for (i=0; i < cdbs->total_segment_dbs; i++)
378
	{
379
		CdbComponentDatabaseInfo *segInfo = &cdbs->segment_db_info[i];
380 381 382 383 384 385 386 387 388 389
		uint8	segStatus;

		segStatus = 0;

		if (SEGMENT_IS_ALIVE(segInfo))
			segStatus |= FTS_STATUS_ALIVE;

		if (SEGMENT_IS_ACTIVE_PRIMARY(segInfo))
			segStatus |= FTS_STATUS_PRIMARY;

390
		if (segInfo->preferred_role == GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY)
391 392
			segStatus |= FTS_STATUS_DEFINEDPRIMARY;

393
		if (segInfo->mode == GP_SEGMENT_CONFIGURATION_MODE_INSYNC)
394 395
			segStatus |= FTS_STATUS_SYNCHRONIZED;

396
		if (segInfo->mode == GP_SEGMENT_CONFIGURATION_MODE_CHANGETRACKING)
397 398 399 400
			segStatus |= FTS_STATUS_CHANGELOGGING;

		ftsProbeInfo->fts_status[segInfo->dbid] = segStatus;
	}
401 402

	return cdbs;
403 404
}

A
Ashwin Agrawal 已提交
405 406
#ifdef USE_SEGWALREP
static void
407
probeWalRepUpdateConfig(int16 dbid, int16 segindex, bool IsSegmentAlive, bool IsInSync)
A
Ashwin Agrawal 已提交
408
{
409 410
	Assert(IsInSync ? IsSegmentAlive : true);

A
Ashwin Agrawal 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	/*
	 * Insert new tuple into gp_configuration_history catalog.
	 */
	{
		Relation histrel;
		HeapTuple histtuple;
		Datum histvals[Natts_gp_configuration_history];
		bool histnulls[Natts_gp_configuration_history] = { false };
		char desc[SQL_CMD_BUF_SIZE];

		histrel = heap_open(GpConfigHistoryRelationId,
							RowExclusiveLock);

		histvals[Anum_gp_configuration_history_time-1] =
				TimestampTzGetDatum(GetCurrentTimestamp());
		histvals[Anum_gp_configuration_history_dbid-1] =
				Int16GetDatum(dbid);
		snprintf(desc, sizeof(desc),
429 430 431 432 433 434 435
				 "FTS: update status and mode for dbid %d with contentid %d to %c and %c",
				 dbid, segindex,
				 IsSegmentAlive ? GP_SEGMENT_CONFIGURATION_STATUS_UP :
				 GP_SEGMENT_CONFIGURATION_STATUS_DOWN,
				 IsInSync ? GP_SEGMENT_CONFIGURATION_MODE_INSYNC :
				 GP_SEGMENT_CONFIGURATION_MODE_NOTINSYNC
			);
A
Ashwin Agrawal 已提交
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
		histvals[Anum_gp_configuration_history_desc-1] =
				CStringGetTextDatum(desc);
		histtuple = heap_form_tuple(RelationGetDescr(histrel), histvals, histnulls);
		simple_heap_insert(histrel, histtuple);
		CatalogUpdateIndexes(histrel, histtuple);

		heap_close(histrel, RowExclusiveLock);
	}

	/*
	 * Find and update gp_segment_configuration tuple.
	 */
	{
		Relation configrel;

		HeapTuple configtuple;
		HeapTuple newtuple;

		Datum configvals[Natts_gp_segment_configuration];
		bool confignulls[Natts_gp_segment_configuration] = { false };
		bool repls[Natts_gp_segment_configuration] = { false };

		ScanKeyData scankey;
		SysScanDesc sscan;

		configrel = heap_open(GpSegmentConfigRelationId,
							  RowExclusiveLock);

		ScanKeyInit(&scankey,
					Anum_gp_segment_configuration_dbid,
					BTEqualStrategyNumber, F_INT2EQ,
					Int16GetDatum(dbid));
		sscan = systable_beginscan(configrel, GpSegmentConfigDbidIndexId,
								   true, SnapshotNow, 1, &scankey);

		configtuple = systable_getnext(sscan);

		if (!HeapTupleIsValid(configtuple))
		{
			elog(ERROR, "FTS cannot find dbid=%d in %s", dbid,
				 RelationGetRelationName(configrel));
		}

		configvals[Anum_gp_segment_configuration_status-1] =
			CharGetDatum(IsSegmentAlive ? GP_SEGMENT_CONFIGURATION_STATUS_UP :
										GP_SEGMENT_CONFIGURATION_STATUS_DOWN);
		repls[Anum_gp_segment_configuration_status-1] = true;

484 485 486 487 488
		configvals[Anum_gp_segment_configuration_mode-1] =
			CharGetDatum(IsInSync ? GP_SEGMENT_CONFIGURATION_MODE_INSYNC :
						 GP_SEGMENT_CONFIGURATION_MODE_NOTINSYNC);
		repls[Anum_gp_segment_configuration_mode-1] = true;

A
Ashwin Agrawal 已提交
489 490 491 492 493 494 495 496 497 498 499 500 501
		newtuple = heap_modify_tuple(configtuple, RelationGetDescr(configrel),
									 configvals, confignulls, repls);
		simple_heap_update(configrel, &configtuple->t_self, newtuple);
		CatalogUpdateIndexes(configrel, newtuple);

		systable_endscan(sscan);
		pfree(newtuple);

		heap_close(configrel, RowExclusiveLock);
	}
}

static bool
502
probeWalRepPublishUpdate(CdbComponentDatabases *cdbs, probe_context *context)
A
Ashwin Agrawal 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515
{
	bool is_updated = false;

	for (int response_index = 0; response_index < context->count; response_index ++)
	{
		probe_response_per_segment *response = &(context->responses[response_index]);

		Assert(SEGMENT_IS_ACTIVE_PRIMARY(response->segment_db_info));

		if (!FtsIsActive())
			return false;

		CdbComponentDatabaseInfo *primary = response->segment_db_info;
516

517 518 519
		CdbComponentDatabaseInfo *mirror = FtsGetPeerSegment(cdbs,
															 primary->segindex,
															 primary->dbid);
A
Ashwin Agrawal 已提交
520

521 522 523 524 525 526
		/*
		 * Currently, mode of primary and mirror should be same, either both
		 * reflecting in sync or not in sync.
		 */
		Assert(primary->mode == mirror->mode);

A
Ashwin Agrawal 已提交
527 528
		bool IsPrimaryAlive = response->result.isPrimaryAlive;
		bool IsMirrorAlive = response->result.isMirrorAlive;
529 530 531 532
		bool IsInSync = response->result.isInSync;

		/* If are in sync, then both have to be ALIVE */
		Assert(IsInSync ? (IsPrimaryAlive && IsMirrorAlive) : true);
A
Ashwin Agrawal 已提交
533 534 535 536

		bool UpdatePrimary = (IsPrimaryAlive != SEGMENT_IS_ALIVE(primary));
		bool UpdateMirror = (IsMirrorAlive != SEGMENT_IS_ALIVE(mirror));

537 538 539 540
		/*
		 * If probe response state is different from current state in
		 * configuration, update both primary and mirror.
		 */
541 542 543
		if (IsInSync != SEGMENT_IS_IN_SYNC(primary))
			UpdatePrimary = UpdateMirror = true;

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
		/*
		 * ----------------------------
		 * In double fault situations:
		 *     - Primary and Mirror are up but not in SYNC
		 *     - Mirror is down and hence are not in SYNC
		 *
		 * In these situations probe fails, cannot make any change to
		 * configuration and need to leave current primary marked as UP.
		 */
		if (SEGMENT_IS_NOT_INSYNC(primary) && !IsPrimaryAlive)
		{
			elog(WARNING, "FTS double fault detected for primary dbid %d, mirror dbid %d having contentid %d",
				 primary->dbid, mirror->dbid, primary->segindex);
			continue;
		}

A
Ashwin Agrawal 已提交
560 561 562 563 564 565 566 567 568 569 570
		if (UpdatePrimary || UpdateMirror)
		{
			/*
			 * Commit/abort transaction below will destroy
			 * CurrentResourceOwner.  We need it for catalog reads.
			 */
			ResourceOwner save = CurrentResourceOwner;
			StartTransactionCommand();
			GetTransactionSnapshot();

			if (UpdatePrimary)
571 572
				probeWalRepUpdateConfig(primary->dbid, primary->segindex,
										IsPrimaryAlive, IsInSync);
A
Ashwin Agrawal 已提交
573 574

			if (UpdateMirror)
575 576
				probeWalRepUpdateConfig(mirror->dbid, mirror->segindex,
										IsMirrorAlive, IsInSync);
A
Ashwin Agrawal 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

			if (shutdown_requested)
			{
				elog(LOG, "Shutdown in progress, ignoring FTS prober updates.");
				return is_updated;
			}

			is_updated = true;

			CommitTransactionCommand();
			CurrentResourceOwner = save;
		}
	}

	return is_updated;
}

static void
FtsWalRepInitProbeContext(CdbComponentDatabases *cdbs, probe_context *context)
{
597
	context->count = cdbs->total_segments;
A
Ashwin Agrawal 已提交
598 599 600 601 602 603
	context->responses = (probe_response_per_segment *)palloc(context->count * sizeof(probe_response_per_segment));

	int response_index = 0;

	for(int segment_index = 0; segment_index < cdbs->total_segment_dbs; segment_index++)
	{
604
		CdbComponentDatabaseInfo *segment = &(cdbs->segment_db_info[segment_index]);
A
Ashwin Agrawal 已提交
605 606 607 608 609 610 611 612 613 614 615
		probe_response_per_segment *response = &(context->responses[response_index]);

		if (!SEGMENT_IS_ACTIVE_PRIMARY(segment))
			continue;

		/*
		 * We initialize the probe_result.IsPrimaryAlive and
		 * probe_result.IsMirrorAlive to current state, and that will prevent
		 * changing of mirror status if the primary goes down.
		 */
		CdbComponentDatabaseInfo *primary = segment;
616 617
		CdbComponentDatabaseInfo *mirror = FtsGetPeerSegment(cdbs,
															 primary->segindex,
A
Ashwin Agrawal 已提交
618 619
															 primary->dbid);

620 621 622 623
		/* primary in catalog will NEVER be marked down. */
		Assert(FtsIsSegmentAlive(primary));

		/*
624 625 626 627 628
		 * Before we probe, we always DEFAULT the response for primary is
		 * down. This will only be changed to true if primary is alive,
		 * otherwise some error happened during the probe. Similarly, always
		 * DEFAULT the response to not in sync. Only if primary communicates
		 * positively, consider it in sync.
629 630
		 */
		response->result.isPrimaryAlive = false;
A
Ashwin Agrawal 已提交
631
		response->result.isMirrorAlive = SEGMENT_IS_ALIVE(mirror);
632
		response->result.isInSync = false;
A
Ashwin Agrawal 已提交
633 634 635 636 637 638 639 640 641 642

		response->segment_db_info = primary;
		response->isScheduled = false;

		Assert(response_index < context->count);
		response_index ++;
	}
}
#endif

643 644 645
static
void FtsLoop()
{
A
Ashwin Agrawal 已提交
646
	bool	updated_probe_state, processing_fullscan;
647 648
	MemoryContext probeContext = NULL, oldContext = NULL;
	time_t elapsed,	probe_start_time;
649
	CdbComponentDatabases *cdbs = NULL;
650 651 652 653 654 655

	probeContext = AllocSetContextCreate(TopMemoryContext,
										 "FtsProbeMemCtxt",
										 ALLOCSET_DEFAULT_INITSIZE,	/* always have some memory */
										 ALLOCSET_DEFAULT_INITSIZE,
										 ALLOCSET_DEFAULT_MAXSIZE);
656

657 658
	for (;;)
	{
659 660
		bool		has_mirrors;

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
		if (shutdown_requested)
			break;
		/* no need to live on if postmaster has died */
		if (!PostmasterIsAlive(true))
			exit(1);

		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);
		}

		probe_start_time = time(NULL);

		ftsLock();

		/* atomically clear cancel flag and check pause flag */
		bool pauseProbes = ftsProbeInfo->fts_pauseProbes;
		ftsProbeInfo->fts_discardResults = false;

		ftsUnlock();

		if (pauseProbes)
		{
			if (gp_log_fts >= GPVARS_VERBOSITY_VERBOSE)
				elog(LOG, "skipping probe, we're paused.");
			goto prober_sleep;
		}

690
		if (cdbs != NULL)
691
		{
692 693
			freeCdbComponentDatabases(cdbs);
			cdbs = NULL;
694 695 696 697 698 699 700
		}

		if (ftsProbeInfo->fts_probeScanRequested == ftsProbeInfo->fts_statusVersion)
			processing_fullscan = true;
		else
			processing_fullscan = false;

701 702 703
		/* Need a transaction to access the catalogs */
		StartTransactionCommand();

704
		cdbs = readCdbComponentInfoAndUpdateStatus(probeContext);
705

706
		/* Check here gp_segment_configuration if has mirror's */
707 708 709 710 711 712
		has_mirrors = gp_segment_config_has_mirrors();

		/* close the transaction we started above */
		CommitTransactionCommand();

		if (!has_mirrors)
713 714 715 716 717 718 719 720 721 722
		{
			/* The dispatcher could have requested a scan so just ignore it and unblock the dispatcher */
			if (processing_fullscan)
			{
				ftsProbeInfo->fts_statusVersion = ftsProbeInfo->fts_statusVersion + 1;
				rescan_requested = false;
			}
			goto prober_sleep;
		}

723 724
		elog(DEBUG3, "FTS: starting %s scan with %d segments and %d contents",
			 (processing_fullscan ? "full " : ""),
725 726
			 cdbs->total_segment_dbs,
			 cdbs->total_segments);
727 728 729 730 731 732 733

		/*
		 * We probe in a special context, some of the heap access
		 * stuff palloc()s internally
		 */
		oldContext = MemoryContextSwitchTo(probeContext);

A
Ashwin Agrawal 已提交
734 735 736
#ifdef USE_SEGWALREP
		probe_context context;

737
		FtsWalRepInitProbeContext(cdbs, &context);
A
Ashwin Agrawal 已提交
738 739
		FtsWalRepProbeSegments(&context);

740
		updated_probe_state = probeWalRepPublishUpdate(cdbs, &context);
A
Ashwin Agrawal 已提交
741
#else
742
		/* probe segments */
743
		FtsProbeSegments(cdbs, scan_status);
744 745 746 747 748

		/*
		 * Now we've completed the scan, update shared-memory. if we
		 * change anything, we return true.
		 */
749
		updated_probe_state = probePublishUpdate(cdbs, scan_status);
A
Ashwin Agrawal 已提交
750
#endif
751 752 753 754 755

		MemoryContextSwitchTo(oldContext);

		/* free any pallocs we made inside probeSegments() */
		MemoryContextReset(probeContext);
756
		cdbs = NULL;
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

		if (!FtsIsActive())
		{
			if (gp_log_fts >= GPVARS_VERBOSITY_VERBOSE)
				elog(LOG, "FTS: skipping probe, FTS is paused or shutting down.");
			goto prober_sleep;
		}

		/*
		 * If we're not processing a full-scan, but one has been requested; we start over.
		 */
		if (!processing_fullscan &&
			ftsProbeInfo->fts_probeScanRequested == ftsProbeInfo->fts_statusVersion)
			continue;

		/*
		 * bump the version (this also serves as an acknowledgement to
		 * a probe-request).
		 */
A
Ashwin Agrawal 已提交
776
		if (updated_probe_state || processing_fullscan)
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
		{
			ftsProbeInfo->fts_statusVersion = ftsProbeInfo->fts_statusVersion + 1;
			rescan_requested = false;
		}

		/* if no full-scan has been requested, we can sleep. */
		if (ftsProbeInfo->fts_probeScanRequested >= ftsProbeInfo->fts_statusVersion)
		{
			/* we need to do a probe immediately */
			elog(LOG, "FTS: skipping sleep, requested version: %d, current version: %d.",
				 (int)ftsProbeInfo->fts_probeScanRequested, (int)ftsProbeInfo->fts_statusVersion);
			continue;
		}

	prober_sleep:
		{
			/* check if we need to sleep before starting next iteration */
			elapsed = time(NULL) - probe_start_time;
			if (elapsed < gp_fts_probe_interval && !shutdown_requested)
			{
				pg_usleep((gp_fts_probe_interval - elapsed) * USECS_PER_SEC);
798 799

				CHECK_FOR_INTERRUPTS();
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
			}
		}
	} /* end server loop */

	return;
}

/*
 * Check if FTS is active
 */
bool
FtsIsActive(void)
{
	return (!ftsProbeInfo->fts_discardResults && !shutdown_requested);
}

bool
FtsIsSegmentAlive(CdbComponentDatabaseInfo *segInfo)
{
819 820 821 822 823
	if (SEGMENT_IS_ACTIVE_MIRROR(segInfo) && SEGMENT_IS_ALIVE(segInfo))
		return true;

	if (SEGMENT_IS_ACTIVE_PRIMARY(segInfo))
		return true;
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

	return false;
}


/*
 * Dump out the changes to our logfile.
 */
void
FtsDumpChanges(FtsSegmentStatusChange *changes, int changeEntries)
{
	Assert(changes != NULL);
	int i = 0;

	for (i = 0; i < changeEntries; i++)
	{
		bool new_alive, old_alive;
		bool new_pri, old_pri;

		new_alive = (changes[i].newStatus & FTS_STATUS_ALIVE ? true : false);
		old_alive = (changes[i].oldStatus & FTS_STATUS_ALIVE ? true : false);

		new_pri = (changes[i].newStatus & FTS_STATUS_PRIMARY ? true : false);
		old_pri = (changes[i].oldStatus & FTS_STATUS_PRIMARY ? true : false);

		elog(LOG, "FTS: change state for segment (dbid=%d, content=%d) from ('%c','%c') to ('%c','%c')",
			 changes[i].dbid,
			 changes[i].segindex,
852 853 854 855
			 (old_alive ? GP_SEGMENT_CONFIGURATION_STATUS_UP : GP_SEGMENT_CONFIGURATION_STATUS_DOWN),
			 (old_pri ? GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY : GP_SEGMENT_CONFIGURATION_ROLE_MIRROR),
			 (new_alive ? GP_SEGMENT_CONFIGURATION_STATUS_UP : GP_SEGMENT_CONFIGURATION_STATUS_DOWN),
			 (new_pri ? GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY : GP_SEGMENT_CONFIGURATION_ROLE_MIRROR));
856 857 858 859 860 861
	}
}

/*
 * Get peer segment descriptor
 */
862 863
CdbComponentDatabaseInfo *FtsGetPeerSegment(CdbComponentDatabases *cdbs,
											int content, int dbid)
864 865 866
{
	int i;

867
	for (i=0; i < cdbs->total_segment_dbs; i++)
868
	{
869
		CdbComponentDatabaseInfo *segInfo = &cdbs->segment_db_info[i];
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

		if (segInfo->segindex == content && segInfo->dbid != dbid)
		{
			/* found it */
			return segInfo;
		}
	}

	return NULL;
}


/*
 * Notify postmaster to shut down due to inconsistent segment state
 */
void FtsRequestPostmasterShutdown(CdbComponentDatabaseInfo *primary, CdbComponentDatabaseInfo *mirror)
{
	FtsRequestMasterShutdown();

	elog(FATAL, "FTS: detected invalid state for content=%d: "
			    "primary (dbid=%d, mode='%c', status='%c'), "
			    "mirror (dbid=%d, mode='%c', status='%c'), "
			    "shutting down master.",
			    primary->segindex,
			    primary->dbid,
			    primary->mode,
			    primary->status,
			    mirror->dbid,
			    mirror->mode,
			    mirror->status
			    );
}

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
/*
 * Request the fault-prober to suspend probes -- no fault actions will
 * be taken based on in-flight probes until the prober is unpaused.
 */
bool
gpvars_assign_gp_fts_probe_pause(bool newval, bool doit, GucSource source)
{
	if (doit)
	{
		/*
		 * We only want to do fancy stuff on the master (where we have a
		 * prober).
		 */
		if (am_ftsprobe && ftsProbeInfo && Gp_segment == -1)
		{
			/*
			 * fts_pauseProbes is externally set/cleared; fts_cancelProbes is
			 * externally set and cleared by FTS
			 */
			ftsLock();

			ftsProbeInfo->fts_pauseProbes = newval;
			ftsProbeInfo->fts_discardResults = ftsProbeInfo->fts_discardResults || newval;
			ftsUnlock();
		}
		gp_fts_probe_pause = newval;
	}

	return true;
}