cdbtm.c 93.1 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * cdbtm.c
 *	  Provides routines for performing distributed transaction
 *
6 7 8 9 10 11
 * Portions Copyright (c) 2005-2009, Greenplum inc
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
 *
 *
 * IDENTIFICATION
 *	    src/backend/cdb/cdbtm.c
12 13 14 15 16 17
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <time.h>
18
#include <sys/types.h>
19 20
#include <unistd.h>

H
Heikki Linnakangas 已提交
21
#include "catalog/pg_authid.h"
22 23 24 25 26 27
#include "cdb/cdbtm.h"
#include "libpq/libpq-be.h"
#include "miscadmin.h"
#include "storage/shmem.h"
#include "storage/ipc.h"
#include "cdb/cdbdisp.h"
28 29
#include "cdb/cdbdisp_query.h"
#include "cdb/cdbdisp_dtx.h"
30
#include "cdb/cdbdispatchresult.h"
31 32 33 34 35
#include "cdb/cdbdtxcontextinfo.h"

#include "cdb/cdbvars.h"
#include "access/transam.h"
#include "access/xact.h"
36 37
#include "libpq-fe.h"
#include "libpq-int.h"
38 39 40 41 42
#include "cdb/cdbfts.h"
#include "lib/stringinfo.h"
#include "access/twophase.h"
#include "access/distributedlog.h"
#include "postmaster/postmaster.h"
43
#include "storage/procarray.h"
44 45 46 47

#include "cdb/cdbllize.h"
#include "utils/faultinjector.h"
#include "utils/fmgroids.h"
48
#include "utils/sharedsnapshot.h"
49
#include "utils/snapmgr.h"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

extern bool Test_print_direct_dispatch_info;

#define DTM_DEBUG3 (Debug_print_full_dtm ? LOG : DEBUG3)
#define DTM_DEBUG5 (Debug_print_full_dtm ? LOG : DEBUG5)

/*
 * Directory where Utility Mode DTM REDO file reside within PGDATA
 */
#define UTILITYMODEDTMREDO_DIR "pg_utilitymodedtmredo"

/*
 * File name for Utility Mode DTM REDO
 */
#define UTILITYMODEDTMREDO_FILE "savedtmredo.file"

static LWLockId shmControlLock;
G
Gang Xiong 已提交
67
static slock_t *shmControlSeqnoLock;
68
static volatile bool *shmTmRecoverred;
G
Gang Xiong 已提交
69
volatile DistributedTransactionTimeStamp *shmDistribTimeStamp;
70
static volatile DistributedTransactionId *shmGIDSeq = NULL;
71

A
Ashwin Agrawal 已提交
72
volatile bool *shmDtmStarted;
G
Gang Xiong 已提交
73
uint32 *shmNextSnapshotId;
74

G
Gang Xiong 已提交
75 76 77
/* transactions need recover */
TMGXACT_LOG *shmCommittedGxactArray;
volatile int *shmNumCommittedGxacts;
78 79 80 81 82 83 84 85 86

/**
 * This pointer into shared memory is on the QD, and represents the current open transaction.
 */
static TMGXACT *currentGxact;

static int	max_tm_gxacts = 100;

static int	redoFileFD = -1;
A
Ashwin Agrawal 已提交
87
static int	redoFileOffset;
88 89 90 91

typedef struct InDoubtDtx
{
	char		gid[TMGIDSIZE];
A
Ashwin Agrawal 已提交
92
} InDoubtDtx;
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120


/* here are some flag options relationed to the txnOptions field of
 * PQsendGpQuery
 */

/* bit 1 is for statement wants DTX transaction
 *
 * bits 2-3 for iso level  00 read-committed
 *						   01 read-uncommitted
 *						   10 repeatable-read
 *						   11 serializable
 * bit 4 is for read-only
 */
#define GP_OPT_NEED_TWO_PHASE                           0x0001

#define GP_OPT_READ_COMMITTED    						0x0002
#define GP_OPT_READ_UNCOMMITTED  						0x0004
#define GP_OPT_REPEATABLE_READ   						0x0006
#define GP_OPT_SERIALIZABLE 	  						0x0008

#define GP_OPT_READ_ONLY         						0x0010

#define GP_OPT_EXPLICT_BEGIN      						0x0020

/*=========================================================================
 * FUNCTIONS PROTOTYPES
 */
G
Gang Xiong 已提交
121 122 123
static DistributedTransactionId generateGID(void);
static void clearAndResetGxact(void);
static void resetCurrentGxact(void);
124 125 126 127 128 129 130 131 132
static void recoverTM(void);
static bool recoverInDoubtTransactions(void);
static HTAB *gatherRMInDoubtTransactions(void);
static void abortRMInDoubtTransactions(HTAB *htab);

/* static void resolveInDoubtDtx(void); */
static void dumpRMOnlyDtx(HTAB *htab, StringInfoData *buff);

static bool doDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, int flags,
A
Ashwin Agrawal 已提交
133 134 135
							 char *gid, DistributedTransactionId gxid,
							 bool *badGangs, bool raiseError, CdbDispatchDirectDesc *direct,
							 char *serializedDtxContextInfo, int serializedDtxContextInfoLen);
136 137
static void doPrepareTransaction(void);
static void doInsertForgetCommitted(void);
G
Gang Xiong 已提交
138
static void clearTransactionState(void);
139 140
static void doNotifyingCommitPrepared(void);
static void doNotifyingAbort(void);
141
static void retryAbortPrepared(void);
142 143 144 145 146
static bool doNotifyCommittedInDoubt(char *gid);
static void doAbortInDoubt(char *gid);
static void doQEDistributedExplicitBegin(int txnOptions);

static bool isDtxQueryDispatcher(void);
A
Ashwin Agrawal 已提交
147
static void UtilityModeSaveRedo(bool committed, TMGXACT_LOG *gxact_log);
148 149 150 151 152
static void ReplayRedoFromUtilityMode(void);
static void RemoveRedoUtilityModeFile(void);
static void performDtxProtocolCommitPrepared(const char *gid, bool raiseErrorIfNotFound);
static void performDtxProtocolAbortPrepared(const char *gid, bool raiseErrorIfNotFound);

G
Gang Xiong 已提交
153
extern void resetSessionForPrimaryGangLoss(bool resetSession);
154 155 156 157 158 159 160 161 162 163 164
extern void CheckForResetSession(void);

/**
 * All assignments of the global DistributedTransactionContext should go through this function
 *   (so we can add logging here to see all assignments)
 *
 * @param context the new value for DistributedTransactionContext
 */
static void
setDistributedTransactionContext(DtxContext context)
{
A
Ashwin Agrawal 已提交
165 166 167 168
	/*
	 * elog(INFO, "Setting DistributedTransactionContext to '%s'",
	 * DtxContextToString(context));
	 */
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
	DistributedTransactionContext = context;
}

static void
requireDistributedTransactionContext(DtxContext requiredCurrentContext)
{
	if (DistributedTransactionContext != requiredCurrentContext)
	{
		elog(FATAL, "Expected segment distributed transaction context to be '%s', found '%s'",
			 DtxContextToString(requiredCurrentContext),
			 DtxContextToString(DistributedTransactionContext));
	}
}

static void
setGxactState(TMGXACT *transaction, DtxState state)
{
	Assert(transaction != NULL);
A
Ashwin Agrawal 已提交
187 188 189 190 191

	/*
	 * elog(INFO, "Setting transaction state to '%s'",
	 * DtxStateToString(state));
	 */
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
	transaction->state = state;
}

/**
 * All assignments of currentGxact->state should go through this function
 *   (so we can add logging here to see all assignments)
 *
 * This should only be called when currentGxact is non-NULL
 *
 * @param state the new value for currentGxact->state
 */
static void
setCurrentGxactState(DtxState state)
{
	setGxactState(currentGxact, state);
}

/**
 * Does DistributedTransactionContext indicate that this is acting as a QD?
 */
static bool
isQDContext(void)
{
A
Ashwin Agrawal 已提交
215
	switch (DistributedTransactionContext)
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
	{
		case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
		case DTX_CONTEXT_QD_RETRY_PHASE_2:
			return true;
		default:
			return false;
	}
}

/**
 * Does DistributedTransactionContext indicate that this is acting as a QE?
 */
static bool
isQEContext()
{
A
Ashwin Agrawal 已提交
231
	switch (DistributedTransactionContext)
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
	{
		case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
		case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
		case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
		case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
		case DTX_CONTEXT_QE_READER:
			return true;
		default:
			return false;
	}
}

/*=========================================================================
 * VISIBLE FUNCTIONS
 */

DistributedTransactionTimeStamp
getDtxStartTime(void)
{
	if (shmDistribTimeStamp != NULL)
		return *shmDistribTimeStamp;
	else
		return 0;
}

DistributedTransactionId
getDistributedTransactionId(void)
{
A
Ashwin Agrawal 已提交
260
	if (isQDContext())
261 262 263 264 265
	{
		return currentGxact == NULL
			? InvalidDistributedTransactionId
			: currentGxact->gxid;
	}
A
Ashwin Agrawal 已提交
266
	else if (isQEContext())
267 268 269 270 271 272 273 274 275 276 277 278
	{
		return QEDtxContextInfo.distributedXid;
	}
	else
	{
		return InvalidDistributedTransactionId;
	}
}

bool
getDistributedTransactionIdentifier(char *id)
{
A
Ashwin Agrawal 已提交
279
	if (isQDContext())
280 281 282 283
	{
		if (currentGxact != NULL)
		{
			/*
A
Ashwin Agrawal 已提交
284 285
			 * The length check here requires the identifer have a trailing
			 * NUL character.
286 287 288
			 */
			if (strlen(currentGxact->gid) >= TMGIDSIZE)
				elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
289
					 (int) strlen(currentGxact->gid));
290 291 292 293
			memcpy(id, currentGxact->gid, TMGIDSIZE);
			return true;
		}
	}
A
Ashwin Agrawal 已提交
294
	else if (isQEContext())
295 296 297 298 299
	{
		if (QEDtxContextInfo.distributedXid != InvalidDistributedTransactionId)
		{
			if (strlen(QEDtxContextInfo.distributedId) >= TMGIDSIZE)
				elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
300
					 (int) strlen(QEDtxContextInfo.distributedId));
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
			memcpy(id, QEDtxContextInfo.distributedId, TMGIDSIZE);
			return true;
		}
	}

	MemSet(id, 0, TMGIDSIZE);
	return false;
}

bool
isPreparedDtxTransaction(void)
{
	if (Gp_role != GP_ROLE_DISPATCH ||
		DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE ||
		currentGxact == NULL)
		return false;

	return (currentGxact->state == DTX_STATE_PREPARED);
}

void
getDtxLogInfo(TMGXACT_LOG *gxact_log)
{
	if (currentGxact == NULL)
	{
		elog(FATAL, "getDtxLogInfo found current distributed transaction is NULL");
	}

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
331
			 (int) strlen(currentGxact->gid));
332 333 334 335 336 337 338 339 340
	memcpy(gxact_log->gid, currentGxact->gid, TMGIDSIZE);
	gxact_log->gxid = currentGxact->gxid;
}

bool
notifyCommittedDtxTransactionIsNeeded(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
A
Ashwin Agrawal 已提交
341
		elog(DTM_DEBUG5, "notifyCommittedDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
342 343 344 345 346 347
			 DtxContextToString(DistributedTransactionContext));
		return false;
	}

	if (currentGxact == NULL)
	{
A
Ashwin Agrawal 已提交
348
		elog(DTM_DEBUG5, "notifyCommittedDtxTransaction nothing to do (currentGxact == NULL)");
349 350 351 352 353 354
		return false;
	}

	return true;
}

G
Gang Xiong 已提交
355 356 357 358 359 360 361 362
bool
includeInCheckpointIsNeeded(TMGXACT *gxact)
{
	volatile DtxState state = gxact->state;
	return ((state >= DTX_STATE_INSERTED_COMMITTED &&
			 state < DTX_STATE_INSERTED_FORGET_COMMITTED) ||
			state == DTX_STATE_RETRY_COMMIT_PREPARED);
}
363 364 365 366 367 368 369
/*
 * Notify commited a global transaction, called by user commit
 * or by CommitTransaction
 */
void
notifyCommittedDtxTransaction(void)
{
A
Ashwin Agrawal 已提交
370
	Assert(DistributedTransactionContext == DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE);
371

A
Ashwin Agrawal 已提交
372
	Assert(currentGxact != NULL);
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

	doNotifyingCommitPrepared();
}

static inline void
copyDirectDispatchFromTransaction(CdbDispatchDirectDesc *dOut)
{
	if (currentGxact->directTransaction)
	{
		dOut->directed_dispatch = true;
		dOut->count = 1;
		dOut->content[0] = currentGxact->directTransactionContentId;
	}
	else
	{
		dOut->directed_dispatch = false;
	}
}

static bool
GetRootNodeIsDirectDispatch(PlannedStmt *stmt)
{
A
Ashwin Agrawal 已提交
395
	if (stmt == NULL)
396 397
		return false;

A
Ashwin Agrawal 已提交
398
	if (stmt->planTree == NULL)
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
		return false;

	return stmt->planTree->directDispatch.isDirectDispatch;
}

/**
 * note that the ability to look at the root node of a plan in order to determine
 *    direct dispatch overall depends on the way we assign direct dispatch.  Parent slices are
 *    never more directed than child slices.  This could be fixed with an iteration over all slices and
 *    combine from every slice.
 *
 * return true IFF the directDispatch data stored in n should be applied to the transaction
 */
static bool
GetPlannedStmtDirectDispatch_AndUsingNodeIsSufficient(PlannedStmt *stmt)
{
A
Ashwin Agrawal 已提交
415
	if (!GetRootNodeIsDirectDispatch(stmt))
416 417 418
		return false;

	/*
A
Ashwin Agrawal 已提交
419 420 421 422
	 * now look at number initplans .. we do something simple.  ANY initPlans
	 * means we don't do directDispatch at the dtm level.  It's technically
	 * possible that the initPlan and the node share the same direct dispatch
	 * set but we don't bother right now.
423
	 */
A
Ashwin Agrawal 已提交
424
	if (stmt->nInitPlans > 0)
425 426 427 428 429 430 431 432 433 434 435
		return false;

	return true;
}

/*
 * @param needsTwoPhaseCommit if true then marks the current Distributed Transaction as needing to use the
 *       2 phase commit protocol.
 */
void
dtmPreCommand(const char *debugCaller, const char *debugDetail, PlannedStmt *stmt,
A
Ashwin Agrawal 已提交
436
			  bool needsTwoPhaseCommit, bool wantSnapshot, bool inCursor)
437
{
A
Ashwin Agrawal 已提交
438 439 440
	bool		needsPromotionFromDirectDispatch = false;
	const bool	rootNodeIsDirectDispatch = GetRootNodeIsDirectDispatch(stmt);
	const bool	nodeSaysDirectDispatch = GetPlannedStmtDirectDispatch_AndUsingNodeIsSufficient(stmt);
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

	Assert(debugCaller != NULL);
	Assert(debugDetail != NULL);

	/**
	 * update the information about what segments are participating in the transaction
	 */
	if (currentGxact == NULL)
	{
		/* no open transaction so don't do anything */
	}
	else if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
	{
		/* Can we direct this transaction to a single content-id ? */
		if (nodeSaysDirectDispatch)
		{
			currentGxact->directTransaction = true;
			currentGxact->directTransactionContentId = linitial_int(stmt->planTree->directDispatch.contentIds);

			elog(DTM_DEBUG5,
				 "dtmPreCommand going distributed (to content %d) for gid = %s (%s, detail = '%s')",
				 currentGxact->directTransactionContentId, currentGxact->gid, debugCaller, debugDetail);
		}
		else
		{
			currentGxact->directTransaction = false;

A
Ashwin Agrawal 已提交
468
			if (rootNodeIsDirectDispatch)
469
			{
A
Ashwin Agrawal 已提交
470 471 472 473
				/*
				 * implicit write on the root, but some initPlan was to all
				 * contents...so send explicit start
				 */
474 475 476 477 478 479 480 481 482 483
				needsPromotionFromDirectDispatch = true;
			}

			elog(DTM_DEBUG5,
				 "dtmPreCommand going distributed (all gangs) for gid = %s (%s, detail = '%s')",
				 currentGxact->gid, debugCaller, debugDetail);
		}
	}
	else if (currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED)
	{
A
Ashwin Agrawal 已提交
484 485
		bool		wasDirected = currentGxact->directTransaction;
		int			wasPromotedFromDirectDispatchContentId = wasDirected ? currentGxact->directTransactionContentId : -1;
486 487

		/* Can we still direct this transaction to a single content-id ? */
A
Ashwin Agrawal 已提交
488
		if (currentGxact->directTransaction)
489
		{
A
Ashwin Agrawal 已提交
490 491
			currentGxact->directTransaction = false;
			/* turn off, but may be restored below */
492 493 494

			if (nodeSaysDirectDispatch)
			{
A
Ashwin Agrawal 已提交
495 496 497
				int			contentId = linitial_int(stmt->planTree->directDispatch.contentIds);

				if (contentId == currentGxact->directTransactionContentId)
498
				{
A
Ashwin Agrawal 已提交
499 500 501 502
					/*
					 * it was the same content!  Stay in a single direct
					 * transaction
					 */
503 504 505 506 507
					currentGxact->directTransaction = true;
				}
			}
		}

A
Ashwin Agrawal 已提交
508
		if (currentGxact->directTransaction)
509 510 511 512 513
		{
			/** was not actually promoted */
			wasPromotedFromDirectDispatchContentId = -1;
		}

A
Ashwin Agrawal 已提交
514
		if (wasPromotedFromDirectDispatchContentId != -1)
515 516 517 518 519 520 521
			needsPromotionFromDirectDispatch = true;

		elog(DTM_DEBUG5,
			 "dtmPreCommand gid = %s is already distributed (%s, detail = '%s'), (was %s : now %s)",
			 currentGxact->gid, debugCaller, debugDetail,
			 wasDirected ? "directed" : "all gangs",
			 currentGxact->directTransaction ? "directed" : "all gangs"
A
Ashwin Agrawal 已提交
522
			);
523 524 525 526 527
	}

	/**
	 * If two-phase commit then begin transaction.
	 */
A
Ashwin Agrawal 已提交
528
	if (needsTwoPhaseCommit)
529 530 531 532 533 534 535
	{
		if (currentGxact == NULL)
		{
			elog(ERROR, "DTM transaction is not active (%s, detail = '%s')", debugCaller, debugDetail);
		}
		else if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		{
A
Ashwin Agrawal 已提交
536
			setCurrentGxactState(DTX_STATE_ACTIVE_DISTRIBUTED);
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
		}
		else if (currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED)
		{
			/* already distributed, no need to change */
		}
		else
		{
			elog(ERROR, "DTM transaction is not active (state = %s, %s, detail = '%s')",
				 DtxStateToString(currentGxact->state), debugCaller, debugDetail);
		}
	}

	/**
	 * If promotion from direct-dispatch to whole-cluster dispatch was done then tell about it.
	 *
	 * FUTURE: note that this is only needed if the query we are going to run would not itself
	 *   do this (that is, if the query we are going to run is a read-only one)
	 */
A
Ashwin Agrawal 已提交
555 556 557
	if (currentGxact &&
		currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED &&
		needsPromotionFromDirectDispatch)
558 559
	{
		CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
A
Ashwin Agrawal 已提交
560 561 562 563
		char	   *serializedDtxContextInfo;
		int			serializedDtxContextInfoLen;
		bool		badGangs,
					succeeded;
564 565

		serializedDtxContextInfo = qdSerializeDtxContextInfo(&serializedDtxContextInfoLen, wantSnapshot, inCursor,
A
Ashwin Agrawal 已提交
566
															 mppTxnOptions(true), "promoteTransactionIn_dtmPreCommand");
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

		succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_STAY_AT_OR_BECOME_IMPLIED_WRITER, /* flags */ 0,
												 currentGxact->gid, currentGxact->gxid,
												 &badGangs, /* raiseError */ false, &direct,
												 serializedDtxContextInfo, serializedDtxContextInfoLen);

		/* send a DTM command to others to tell them about the transaction */
		if (!succeeded)
		{
			ereport(ERROR, (errmsg("Global transaction upgrade from single segment to entire cluster failed for gid = \"%s\" due to error",
								   currentGxact->gid)));
		}
	}
}


/*
 * Routine to dispatch internal sub-transaction calls from UDFs to segments.
 * The calls are BeginInternalSubTransaction, ReleaseCurrentSubTransaction and
A
Ashwin Agrawal 已提交
586
 * RollbackAndReleaseCurrentSubTransaction.
587 588 589 590 591
 */
bool
doDispatchSubtransactionInternalCmd(DtxProtocolCommand cmdType)
{
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
A
Ashwin Agrawal 已提交
592 593 594 595
	char	   *serializedDtxContextInfo = NULL;
	int			serializedDtxContextInfoLen = 0;
	bool		badGangs,
				succeeded = false;
596

G
Gang Xiong 已提交
597 598 599
	if (cmdType == DTX_PROTOCOL_COMMAND_SUBTRANSACTION_BEGIN_INTERNAL &&
		currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		setCurrentGxactState(DTX_STATE_ACTIVE_DISTRIBUTED);
A
Ashwin Agrawal 已提交
600

601
	serializedDtxContextInfo = qdSerializeDtxContextInfo(
A
Ashwin Agrawal 已提交
602 603 604 605 606
														 &serializedDtxContextInfoLen,
														 false /* wantSnapshot */ ,
														 false /* inCursor */ ,
														 mppTxnOptions(true),
														 "doDispatchSubtransactionInternalCmd");
607 608

	succeeded = doDispatchDtxProtocolCommand(
A
Ashwin Agrawal 已提交
609 610 611 612
											 cmdType, /* flags */ 0,
											 currentGxact->gid, currentGxact->gxid,
											 &badGangs, /* raiseError */ true, &direct,
											 serializedDtxContextInfo, serializedDtxContextInfoLen);
613 614 615 616

	/* send a DTM command to others to tell them about the transaction */
	if (!succeeded)
	{
A
Ashwin Agrawal 已提交
617 618 619 620
		ereport(ERROR,
				(errmsg(
						"dispatching subtransaction internal command failed for gid = \"%s\" due to error",
						currentGxact->gid)));
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
	}

	return succeeded;
}

/*
 * The executor can avoid starting a distributed transaction if it knows that
 * the current dtx is clean and we aren't in a user-started global transaction.
 */
bool
isCurrentDtxTwoPhase(void)
{
	if (currentGxact == NULL)
	{
		return false;
	}
	else
	{
		return currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED;
	}
}

DtxState
getCurrentDtxState(void)
{
	if (currentGxact != NULL)
		return currentGxact->state;

	return DTX_STATE_NONE;
}

static void
doPrepareTransaction(void)
{
A
Ashwin Agrawal 已提交
655 656
	bool		succeeded;
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
657 658 659 660

	CHECK_FOR_INTERRUPTS();

	elog(DTM_DEBUG5, "doPrepareTransaction entering in state = %s",
A
Ashwin Agrawal 已提交
661
		 DtxStateToString(currentGxact->state));
662

A
Ashwin Agrawal 已提交
663 664 665 666
	/*
	 * Don't allow a cancel while we're dispatching our prepare (we wrap our
	 * state change as well; for good measure.
	 */
667 668 669 670 671
	HOLD_INTERRUPTS();

	copyDirectDispatchFromTransaction(&direct);

	Assert(currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED);
A
Ashwin Agrawal 已提交
672
	setCurrentGxactState(DTX_STATE_PREPARING);
673 674 675 676 677

	elog(DTM_DEBUG5, "doPrepareTransaction moved to state = %s", DtxStateToString(currentGxact->state));

	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_PREPARE, /* flags */ 0,
											 currentGxact->gid, currentGxact->gxid,
678
											 &currentGxact->badPrepareGangs, /* raiseError */ true, &direct, NULL, 0);
679

A
Ashwin Agrawal 已提交
680 681 682 683
	/*
	 * Now we've cleaned up our dispatched statement, cancels are allowed
	 * again.
	 */
684 685 686 687 688 689 690 691 692 693 694 695 696
	RESUME_INTERRUPTS();

	if (!succeeded)
	{
		elog(DTM_DEBUG5, "doPrepareTransaction error finds badPrimaryGangs = %s",
			 (currentGxact->badPrepareGangs ? "true" : "false"));
		elog(ERROR, "The distributed transaction 'Prepare' broadcast failed to one or more segments for gid = %s.",
			 currentGxact->gid);
	}
	elog(DTM_DEBUG5, "The distributed transaction 'Prepare' broadcast succeeded to the segments for gid = %s.",
		 currentGxact->gid);

	Assert(currentGxact->state == DTX_STATE_PREPARING);
A
Ashwin Agrawal 已提交
697
	setCurrentGxactState(DTX_STATE_PREPARED);
698

699
	SIMPLE_FAULT_INJECTOR(DtmBroadcastPrepare);
700 701 702 703 704 705 706 707 708 709 710 711 712 713

	elog(DTM_DEBUG5, "doPrepareTransaction leaving in state = %s", DtxStateToString(currentGxact->state));
}

/*
 * Insert FORGET COMMITTED into the xlog.
 */
static void
doInsertForgetCommitted(void)
{
	TMGXACT_LOG gxact_log;

	elog(DTM_DEBUG5, "doInsertForgetCommitted entering in state = %s", DtxStateToString(currentGxact->state));

A
Ashwin Agrawal 已提交
714
	setCurrentGxactState(DTX_STATE_INSERTING_FORGET_COMMITTED);
715 716 717

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
718
			 (int) strlen(currentGxact->gid));
719 720 721 722 723
	memcpy(&gxact_log.gid, currentGxact->gid, TMGIDSIZE);
	gxact_log.gxid = currentGxact->gxid;

	RecordDistributedForgetCommitted(&gxact_log);

A
Ashwin Agrawal 已提交
724
	setCurrentGxactState(DTX_STATE_INSERTED_FORGET_COMMITTED);
G
Gang Xiong 已提交
725
}
726

G
Gang Xiong 已提交
727 728 729
static void
clearTransactionState(void)
{
730
	/*
A
Ashwin Agrawal 已提交
731 732 733 734
	 * These two actions must be performed for a distributed transaction under
	 * the same locking of ProceArrayLock so the visibility of the transaction
	 * changes for local master readers (e.g. those using  SnapshotNow for
	 * reading) the same as for distributed transactions.
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
	 *
	 *
	 * In upstream Postgres, proc->xid is cleared in ProcArrayEndTransaction.
	 * But there would have a small window in Greenplum that allows inconsistency
	 * between ProcArrayEndTransaction and notifying prepared commit to segments.
	 * In between, the master has new tuple visible while the segments are seeing
	 * old tuples.
	 *
	 * For example, session 1 runs:
	 *    RENAME from a_new to a;
	 * session 2 runs:
	 *    DROP TABLE a;
	 *
	 * When session 1 goes to just before notifyCommittedDtxTransaction, the new
	 * coming session 2 can see a new tuple for renamed table "a" in pg_class,
	 * and can drop it in master. However, dispatching DROP to segments, at this
	 * point of time segments still have old tuple for "a_new" visible in
	 * pg_class and DROP process just fails to drop "a". Then DTX is notified
	 * later and committed in the segments, the new tuple for "a" is visible
	 * now, but nobody wants to DROP it anymore, so the master has no tuple for
	 * "a" while the segments have it.
	 *
	 * To fix this, transactions require two-phase commit should defer clear 
	 * proc->xid here with ProcArryLock held.
759
	 */
G
Gang Xiong 已提交
760
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
761
	ClearTransactionFromPgProc_UnderLock(MyProc, true);
G
Gang Xiong 已提交
762
	ProcArrayEndGxact();
763
	LWLockRelease(ProcArrayLock);
764 765 766 767 768
}

static void
doNotifyingCommitPrepared(void)
{
A
Ashwin Agrawal 已提交
769 770 771
	bool		succeeded;
	bool		badGangs;
	int			retry = 0;
A
Ashwin Agrawal 已提交
772
	volatile int savedInterruptHoldoffCount;
773

A
Ashwin Agrawal 已提交
774
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
775 776 777 778 779 780

	elog(DTM_DEBUG5, "doNotifyingCommitPrepared entering in state = %s", DtxStateToString(currentGxact->state));

	copyDirectDispatchFromTransaction(&direct);

	Assert(currentGxact->state == DTX_STATE_FORCED_COMMITTED);
A
Ashwin Agrawal 已提交
781
	setCurrentGxactState(DTX_STATE_NOTIFYING_COMMIT_PREPARED);
782 783 784

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
785
			 (int) strlen(currentGxact->gid));
786

787
	SIMPLE_FAULT_INJECTOR(DtmBroadcastCommitPrepared);
A
Ashwin Agrawal 已提交
788
	savedInterruptHoldoffCount = InterruptHoldoffCount;
789

790 791 792 793 794 795 796 797 798
	PG_TRY();
	{
		succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_COMMIT_PREPARED, /* flags */ 0,
												 currentGxact->gid, currentGxact->gxid,
												 &badGangs, /* raiseError */ false,
												 &direct, NULL, 0);
	}
	PG_CATCH();
	{
A
Ashwin Agrawal 已提交
799 800 801 802
		/*
		 * restore the previous value, which is reset to 0 in errfinish.
		 */
		InterruptHoldoffCount = savedInterruptHoldoffCount;
803 804 805 806
		succeeded = false;
	}
	PG_END_TRY();

807 808
	if (!succeeded)
	{
809 810 811
		Assert(currentGxact->state == DTX_STATE_NOTIFYING_COMMIT_PREPARED);
		elog(DTM_DEBUG5, "marking retry needed for distributed transaction"
			 " 'Commit Prepared' broadcast to the segments for gid = %s.",
812
			 currentGxact->gid);
813 814 815 816 817 818 819 820 821
		setCurrentGxactState(DTX_STATE_RETRY_COMMIT_PREPARED);
		setDistributedTransactionContext(DTX_CONTEXT_QD_RETRY_PHASE_2);
	}

	while (!succeeded && dtx_phase2_retry_count > retry++)
	{
		elog(WARNING, "the distributed transaction 'Commit Prepared' broadcast "
			 "failed to one or more segments for gid = %s.  Retrying ... try %d",
			 currentGxact->gid, retry);
822 823

		/*
A
Ashwin Agrawal 已提交
824 825
		 * We must succeed in delivering the commit to all segment instances,
		 * or any failed segment instances must be marked INVALID.
826 827
		 */
		elog(NOTICE, "Releasing segworker group to retry broadcast.");
828
		DisconnectAndDestroyAllGangs(true);
829 830

		/*
A
Ashwin Agrawal 已提交
831 832
		 * This call will at a minimum change the session id so we will not
		 * have SharedSnapshotAdd colissions.
833 834
		 */
		CheckForResetSession();
A
Ashwin Agrawal 已提交
835
		savedInterruptHoldoffCount = InterruptHoldoffCount;
836

837 838 839
		PG_TRY();
		{
			succeeded = doDispatchDtxProtocolCommand(
A
Ashwin Agrawal 已提交
840 841 842 843
													 DTX_PROTOCOL_COMMAND_RETRY_COMMIT_PREPARED, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
844 845 846
		}
		PG_CATCH();
		{
A
Ashwin Agrawal 已提交
847 848 849 850
			/*
			 * restore the previous value, which is reset to 0 in errfinish.
			 */
			InterruptHoldoffCount = savedInterruptHoldoffCount;
851 852 853
			succeeded = false;
		}
		PG_END_TRY();
854 855
	}

856 857
	if (!succeeded)
		elog(PANIC, "unable to complete 'Commit Prepared' broadcast for gid = %s",
A
Ashwin Agrawal 已提交
858
			 currentGxact->gid);
859 860 861
	elog(DTM_DEBUG5, "the distributed transaction 'Commit Prepared' broadcast "
		 "succeeded to all the segments for gid = %s.", currentGxact->gid);

862
	doInsertForgetCommitted();
G
Gang Xiong 已提交
863 864 865

	clearTransactionState();
	resetCurrentGxact();
866 867
}

868 869 870
static void
retryAbortPrepared(void)
{
A
Ashwin Agrawal 已提交
871 872 873
	int			retry = 0;
	bool		succeeded = false;
	bool		badGangs = false;
A
Ashwin Agrawal 已提交
874
	volatile int savedInterruptHoldoffCount;
875 876 877 878 879 880

	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;

	while (!succeeded && dtx_phase2_retry_count > retry++)
	{
		/*
A
Ashwin Agrawal 已提交
881 882 883
		 * By deallocating the gang, we will force a new gang to connect to
		 * all the segment instances.  And, we will abort the transactions in
		 * the segments. What's left are possibily prepared transactions.
884
		 */
885 886
		if (retry > 1)
			elog(NOTICE, "Releasing segworker groups to retry broadcast.");
887 888 889
		DisconnectAndDestroyAllGangs(true);

		/*
A
Ashwin Agrawal 已提交
890 891
		 * This call will at a minimum change the session id so we will not
		 * have SharedSnapshotAdd colissions.
892 893 894
		 */
		CheckForResetSession();

A
Ashwin Agrawal 已提交
895 896
		savedInterruptHoldoffCount = InterruptHoldoffCount;

897 898 899
		PG_TRY();
		{
			succeeded = doDispatchDtxProtocolCommand(
A
Ashwin Agrawal 已提交
900 901 902 903
													 DTX_PROTOCOL_COMMAND_RETRY_ABORT_PREPARED, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
904 905 906 907 908 909 910
			if (!succeeded)
				elog(WARNING, "the distributed transaction 'Abort' broadcast "
					 "failed to one or more segments for gid = %s.  "
					 "Retrying ... try %d", currentGxact->gid, retry);
		}
		PG_CATCH();
		{
A
Ashwin Agrawal 已提交
911 912 913 914
			/*
			 * restore the previous value, which is reset to 0 in errfinish.
			 */
			InterruptHoldoffCount = savedInterruptHoldoffCount;
915 916 917 918 919 920 921 922 923 924 925 926 927
			succeeded = false;
		}
		PG_END_TRY();
	}

	if (!succeeded)
		elog(PANIC, "unable to complete 'Abort' broadcast for gid = %s",
			 currentGxact->gid);
	elog(DTM_DEBUG5, "The distributed transaction 'Abort' broadcast succeeded to "
		 "all the segments for gid = %s.", currentGxact->gid);
}


928 929 930
static void
doNotifyingAbort(void)
{
A
Ashwin Agrawal 已提交
931 932
	bool		succeeded;
	bool		badGangs;
A
Ashwin Agrawal 已提交
933
	volatile int savedInterruptHoldoffCount;
934

A
Ashwin Agrawal 已提交
935
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
936 937 938 939

	elog(DTM_DEBUG5, "doNotifyingAborted entering in state = %s", DtxStateToString(currentGxact->state));

	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
A
Ashwin Agrawal 已提交
940 941
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
942 943 944 945 946

	copyDirectDispatchFromTransaction(&direct);

	if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED)
	{
947
		if (GangsExist())
948 949 950 951 952 953 954 955 956 957 958
		{
			succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_ABORT_NO_PREPARED, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
			if (!succeeded)
			{
				elog(WARNING, "The distributed transaction 'Abort' broadcast failed to one or more segments for gid = %s.",
					 currentGxact->gid);

				/*
A
Ashwin Agrawal 已提交
959 960
				 * Reset the dispatch logic and disconnect from any segment
				 * that didn't respond to our abort.
961 962
				 */
				elog(NOTICE, "Releasing segworker groups to finish aborting the transaction.");
963
				DisconnectAndDestroyAllGangs(true);
964 965

				/*
A
Ashwin Agrawal 已提交
966 967
				 * This call will at a minimum change the session id so we
				 * will not have SharedSnapshotAdd colissions.
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
				 */
				CheckForResetSession();
			}
			else
			{
				elog(DTM_DEBUG5,
					 "The distributed transaction 'Abort' broadcast succeeded to all the segments for gid = %s.",
					 currentGxact->gid);
			}
		}
		else
		{
			elog(DTM_DEBUG5,
				 "The distributed transaction 'Abort' broadcast was omitted (segworker group already dead) gid = %s.",
				 currentGxact->gid);
		}
	}
	else
	{
		DtxProtocolCommand dtxProtocolCommand;
A
Ashwin Agrawal 已提交
988 989
		char	   *abortString;
		int			retry = 0;
990 991

		Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
A
Ashwin Agrawal 已提交
992
			   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
993 994 995 996 997 998 999 1000 1001 1002 1003 1004

		if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED)
		{
			dtxProtocolCommand = DTX_PROTOCOL_COMMAND_ABORT_SOME_PREPARED;
			abortString = "Abort [Prepared]";
		}
		else
		{
			dtxProtocolCommand = DTX_PROTOCOL_COMMAND_ABORT_PREPARED;
			abortString = "Abort Prepared";
		}

A
Ashwin Agrawal 已提交
1005 1006
		savedInterruptHoldoffCount = InterruptHoldoffCount;

1007
		PG_TRY();
1008
		{
1009 1010 1011 1012 1013 1014 1015
			succeeded = doDispatchDtxProtocolCommand(dtxProtocolCommand, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
		}
		PG_CATCH();
		{
A
Ashwin Agrawal 已提交
1016 1017 1018 1019
			/*
			 * restore the previous value, which is reset to 0 in errfinish.
			 */
			InterruptHoldoffCount = savedInterruptHoldoffCount;
1020 1021 1022
			succeeded = false;
		}
		PG_END_TRY();
1023

1024 1025 1026 1027 1028
		if (!succeeded)
		{
			elog(WARNING, "the distributed transaction '%s' broadcast failed"
				 " to one or more segments for gid = %s.  Retrying ... try %d",
				 abortString, currentGxact->gid, retry);
1029

A
Ashwin Agrawal 已提交
1030
			setCurrentGxactState(DTX_STATE_RETRY_ABORT_PREPARED);
1031
			setDistributedTransactionContext(DTX_CONTEXT_QD_RETRY_PHASE_2);
1032
		}
1033
		retryAbortPrepared();
1034 1035
	}

1036
	SIMPLE_FAULT_INJECTOR(DtmBroadcastAbortPrepared);
1037 1038

	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
A
Ashwin Agrawal 已提交
1039 1040
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED ||
1041
		   currentGxact->state == DTX_STATE_RETRY_ABORT_PREPARED);
G
Gang Xiong 已提交
1042
	elog(DTM_DEBUG5, "doNotifyingAbort called resetCurrentGxact");
1043 1044 1045 1046 1047
}

static bool
doNotifyCommittedInDoubt(char *gid)
{
A
Ashwin Agrawal 已提交
1048 1049
	bool		succeeded;
	bool		badGangs;
1050

A
Ashwin Agrawal 已提交
1051
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072

	/* UNDONE: Pass real gxid instead of InvalidDistributedTransactionId. */
	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_RECOVERY_COMMIT_PREPARED, /* flags */ 0,
											 gid, InvalidDistributedTransactionId,
											 &badGangs, /* raiseError */ false,
											 &direct, NULL, 0);
	if (!succeeded)
	{
		elog(FATAL, "Crash recovery broadcast of the distributed transaction 'Commit Prepared' broadcast failed to one or more segments for gid = %s.", gid);
	}
	else
	{
		elog(LOG, "Crash recovery broadcast of the distributed transaction 'Commit Prepared' broadcast succeeded for gid = %s.", gid);
	}

	return succeeded;
}

static void
doAbortInDoubt(char *gid)
{
A
Ashwin Agrawal 已提交
1073 1074
	bool		succeeded;
	bool		badGangs;
1075

A
Ashwin Agrawal 已提交
1076
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
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

	/* UNDONE: Pass real gxid instead of InvalidDistributedTransactionId. */
	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_RECOVERY_ABORT_PREPARED, /* flags */ 0,
											 gid, InvalidDistributedTransactionId,
											 &badGangs, /* raiseError */ false,
											 &direct, NULL, 0);
	if (!succeeded)
	{
		elog(FATAL, "Crash recovery retry of the distributed transaction 'Abort Prepared' broadcast failed to one or more segments for gid = %s.  System will retry again later", gid);
	}
	else
	{
		elog(LOG, "Crash recovery broadcast of the distributed transaction 'Abort Prepared' broadcast succeeded for gid = %s", gid);
	}
}

/*
 * prepare a global transaction, called by user commit
 * or by CommitTransaction
 */
void
prepareDtxTransaction(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
A
Ashwin Agrawal 已提交
1102
		elog(DTM_DEBUG5, "prepareDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
			 DtxContextToString(DistributedTransactionContext));
		return;
	}

	if (currentGxact == NULL)
	{
		return;
	}

	if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
	{
		/*
		 * This transaction did not go distributed.
		 */
G
Gang Xiong 已提交
1117
		clearAndResetGxact();
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
		elog(DTM_DEBUG5, "prepareDtxTransaction ignoring not distributed gid = %s", currentGxact->gid);
		return;
	}

	elog(DTM_DEBUG5,
		 "prepareDtxTransaction called with state = %s",
		 DtxStateToString(currentGxact->state));

	Assert(currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED);

	/*
	 * Broadcast PREPARE TRANSACTION to segments.
	 */
	doPrepareTransaction();
}

/*
 * rollback a global transaction, called by user rollback
 * or by AbortTransaction during Postgres automatic rollback
 */
void
rollbackDtxTransaction(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
A
Ashwin Agrawal 已提交
1143
		elog(DTM_DEBUG5, "rollbackDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
1144 1145 1146 1147 1148
			 DtxContextToString(DistributedTransactionContext));
		return;
	}
	if (currentGxact == NULL)
	{
A
Ashwin Agrawal 已提交
1149
		elog(DTM_DEBUG5, "rollbackDtxTransaction nothing to do (currentGxact == NULL)");
1150 1151 1152 1153 1154 1155 1156 1157
		return;
	}

	elog(DTM_DEBUG5, "rollbackDtxTransaction called with state = %s, gid = %s",
		 DtxStateToString(currentGxact->state), currentGxact->gid);

	switch (currentGxact->state)
	{
A
Ashwin Agrawal 已提交
1158
		case DTX_STATE_ACTIVE_NOT_DISTRIBUTED:
1159 1160

			/*
A
Ashwin Agrawal 已提交
1161
			 * Let go of these...
1162
			 */
G
Gang Xiong 已提交
1163
			clearAndResetGxact();
1164 1165
			return;

A
Ashwin Agrawal 已提交
1166 1167 1168
		case DTX_STATE_ACTIVE_DISTRIBUTED:
			setCurrentGxactState(DTX_STATE_NOTIFYING_ABORT_NO_PREPARED);
			break;
1169

A
Ashwin Agrawal 已提交
1170 1171 1172 1173
		case DTX_STATE_PREPARING:
			if (currentGxact->badPrepareGangs)
			{
				setCurrentGxactState(DTX_STATE_RETRY_ABORT_PREPARED);
1174

A
Ashwin Agrawal 已提交
1175 1176 1177 1178 1179
				/*
				 * DisconnectAndDestroyAllGangs and ResetSession happens
				 * inside retryAbortPrepared.
				 */
				retryAbortPrepared();
G
Gang Xiong 已提交
1180
				clearAndResetGxact();
A
Ashwin Agrawal 已提交
1181 1182 1183 1184
				return;
			}
			setCurrentGxactState(DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED);
			break;
1185

A
Ashwin Agrawal 已提交
1186 1187 1188
		case DTX_STATE_PREPARED:
			setCurrentGxactState(DTX_STATE_NOTIFYING_ABORT_PREPARED);
			break;
1189

A
Ashwin Agrawal 已提交
1190
		case DTX_STATE_NOTIFYING_ABORT_NO_PREPARED:
1191

A
Ashwin Agrawal 已提交
1192 1193 1194 1195 1196 1197 1198
			/*
			 * By deallocating the gang, we will force a new gang to connect
			 * to all the segment instances.  And, we will abort the
			 * transactions in the segments.
			 */
			elog(NOTICE, "Releasing segworker groups to finish aborting the transaction.");
			DisconnectAndDestroyAllGangs(true);
1199

A
Ashwin Agrawal 已提交
1200 1201 1202 1203 1204 1205
			/*
			 * This call will at a minimum change the session id so we will
			 * not have SharedSnapshotAdd colissions.
			 */
			CheckForResetSession();

G
Gang Xiong 已提交
1206
			clearAndResetGxact();
A
Ashwin Agrawal 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
			return;

		case DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED:
		case DTX_STATE_NOTIFYING_ABORT_PREPARED:
			elog(FATAL, "Unable to complete the 'Abort Prepared' broadcast for gid '%s'",
				 currentGxact->gid);
			break;

		case DTX_STATE_FORCED_COMMITTED:
		case DTX_STATE_NOTIFYING_COMMIT_PREPARED:
		case DTX_STATE_INSERTING_COMMITTED:
		case DTX_STATE_INSERTED_COMMITTED:
		case DTX_STATE_INSERTING_FORGET_COMMITTED:
		case DTX_STATE_INSERTED_FORGET_COMMITTED:
		case DTX_STATE_RETRY_COMMIT_PREPARED:
		case DTX_STATE_RETRY_ABORT_PREPARED:
			elog(DTM_DEBUG5, "rollbackDtxTransaction dtx state \"%s\" not expected here",
				 DtxStateToString(currentGxact->state));
G
Gang Xiong 已提交
1225
			clearAndResetGxact();
A
Ashwin Agrawal 已提交
1226 1227 1228 1229 1230 1231
			return;

		default:
			elog(PANIC, "Unrecognized dtx state: %d",
				 (int) currentGxact->state);
			break;
1232 1233 1234 1235
	}


	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
A
Ashwin Agrawal 已提交
1236 1237
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
1238 1239 1240 1241 1242

	/*
	 * if the process is in the middle of blowing up... then we don't do
	 * anything here.  we can resolve any in-doubt transactions later.
	 *
A
Ashwin Agrawal 已提交
1243
	 * We can't dispatch -- but we *do* need to free up shared-memory entries.
1244 1245 1246 1247 1248 1249 1250 1251
	 */
	if (proc_exit_inprogress)
	{
		/*
		 * Unable to complete distributed abort broadcast with possible
		 * prepared transactions...
		 */
		if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
A
Ashwin Agrawal 已提交
1252
			currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED)
1253 1254 1255 1256 1257 1258
		{
			elog(FATAL, "Unable to complete the 'Abort Prepared' broadcast for gid '%s'",
				 currentGxact->gid);
		}

		Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED);
A
Ashwin Agrawal 已提交
1259

1260
		/*
A
Ashwin Agrawal 已提交
1261 1262 1263
		 * By deallocating the gang, we will force a new gang to connect to
		 * all the segment instances.  And, we will abort the transactions in
		 * the segments.
1264
		 */
1265
		DisconnectAndDestroyAllGangs(true);
1266 1267

		/*
A
Ashwin Agrawal 已提交
1268 1269
		 * This call will at a minimum change the session id so we will not
		 * have SharedSnapshotAdd colissions.
1270 1271 1272
		 */
		CheckForResetSession();

G
Gang Xiong 已提交
1273
		clearAndResetGxact();
1274 1275 1276 1277
		return;
	}

	doNotifyingAbort();
G
Gang Xiong 已提交
1278
	clearAndResetGxact();
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295

	return;
}

/*
 * Error handling in initTM() is our caller.
 *
 * recoverTM() may throw errors.
 */
static void
initTM_recover_as_needed(void)
{
	Assert(shmTmRecoverred != NULL);

	/* Need to recover ? */
	if (!*shmTmRecoverred)
	{
G
Gang Xiong 已提交
1296
		LWLockAcquire(shmControlLock, LW_EXCLUSIVE);
1297 1298 1299 1300 1301

		/* Still need to recover? */
		if (!*shmTmRecoverred)
		{
			volatile int savedInterruptHoldoffCount = InterruptHoldoffCount;
A
Ashwin Agrawal 已提交
1302

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
			/*
			 * We have to catch errors here, otherwise the silly TmLock will
			 * stay in the backend process until this process goes away.
			 */
			PG_TRY();
			{
				recoverTM();
				*shmTmRecoverred = true;
			}
			PG_CATCH();
			{
				/*
				 * We can't simply use HOLD_INTERRUPTS as in LWLockRelease,
				 * because at this point we don't know if other LWLocks have
A
Ashwin Agrawal 已提交
1317 1318 1319 1320
				 * been acquired by myself.  Also, we don't know if
				 * releaseTmLock actually releases the lock, depending on
				 * ControlLockCount. Instead, restore the previous value,
				 * which is reset to 0 in errfinish.
1321 1322
				 */
				InterruptHoldoffCount = savedInterruptHoldoffCount;
G
Gang Xiong 已提交
1323
				LWLockRelease(shmControlLock);
1324 1325 1326 1327 1328 1329 1330

				/* Assuming we have a catcher above... */
				PG_RE_THROW();
			}
			PG_END_TRY();
		}

G
Gang Xiong 已提交
1331
		LWLockRelease(shmControlLock);
1332 1333 1334 1335 1336 1337
	}
}

static char *
getSuperuser(Oid *userOid)
{
A
Ashwin Agrawal 已提交
1338 1339 1340
	char	   *suser = NULL;
	Relation	auth_rel;
	HeapTuple	auth_tup;
1341 1342
	HeapScanDesc auth_scan;
	ScanKeyData key[2];
A
Ashwin Agrawal 已提交
1343
	bool		isNull;
1344 1345

	ScanKeyInit(&key[0],
A
Ashwin Agrawal 已提交
1346 1347 1348
				Anum_pg_authid_rolsuper,
				BTEqualStrategyNumber, F_BOOLEQ,
				BoolGetDatum(true));
1349 1350

	ScanKeyInit(&key[1],
A
Ashwin Agrawal 已提交
1351 1352 1353
				Anum_pg_authid_rolcanlogin,
				BTEqualStrategyNumber, F_BOOLEQ,
				BoolGetDatum(true));
1354 1355 1356 1357 1358

	auth_rel = heap_open(AuthIdRelationId, AccessShareLock);
	auth_scan = heap_beginscan(auth_rel, SnapshotNow, 2, key);

	while (HeapTupleIsValid(auth_tup = heap_getnext(auth_scan,
A
Ashwin Agrawal 已提交
1359
													ForwardScanDirection)))
1360
	{
A
Ashwin Agrawal 已提交
1361 1362
		Datum		attrName;
		Datum		attrNameOid;
1363 1364 1365 1366 1367 1368 1369 1370

		(void) heap_getattr(auth_tup, Anum_pg_authid_rolvaliduntil,
							auth_rel->rd_att, &isNull);
		/* we actually want it to be NULL, that means always valid */
		if (!isNull)
			continue;

		attrName = heap_getattr(auth_tup, Anum_pg_authid_rolname,
A
Ashwin Agrawal 已提交
1371
								auth_rel->rd_att, &isNull);
1372 1373 1374 1375 1376 1377

		Assert(!isNull);

		suser = pstrdup(DatumGetCString(attrName));

		attrNameOid = heap_getattr(auth_tup, ObjectIdAttributeNumber,
A
Ashwin Agrawal 已提交
1378
								   auth_rel->rd_att, &isNull);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
		Assert(!isNull);
		*userOid = DatumGetObjectId(attrNameOid);

		break;
	}

	heap_endscan(auth_scan);
	heap_close(auth_rel, AccessShareLock);

	return suser;
}

static char *
ChangeToSuperuser()
{
A
Ashwin Agrawal 已提交
1394 1395 1396
	char	   *olduser = NULL;
	char	   *newuser;
	Oid			userOid = InvalidOid;
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
	MemoryContext oldcontext;

	if (!IsAuthenticatedUserSuperUser())
	{
		oldcontext = MemoryContextSwitchTo(TopMemoryContext);
		newuser = getSuperuser(&userOid);
		MemoryContextSwitchTo(oldcontext);

		olduser = MyProcPort->user_name;
		SetSessionUserId(userOid, true);
		MyProcPort->user_name = newuser;
	}

	return olduser;
}

static void
RestoreToUser(char *olduser)
{
	MemoryContext oldcontext;

	if (!IsAuthenticatedUserSuperUser())
	{
		oldcontext = MemoryContextSwitchTo(TopMemoryContext);
		pfree(MyProcPort->user_name);
		MemoryContextSwitchTo(oldcontext);

		MyProcPort->user_name = olduser;
		SetSessionUserId(GetAuthenticatedUserId(), false);
	}
}

/*
 * Initialize TM, called by cdb_setup() for each QD process.
 *
 * First call to this function will trigger tm recovery.
 *
 * MPP-9894: in 4.0, if we've been started with enough segments to
 * run, but without having them in the right "roles" (see
 * gp_segment_configuration), we need to prober to convert them -- our
 * first attempt to dispatch will fail, we've got to catch that! The
 * retry should be fine, if not we're in serious "FATAL" trouble.
 */
void
initTM(void)
{
A
Ashwin Agrawal 已提交
1443 1444 1445 1446
	char	   *olduser = NULL;
	MemoryContext oldcontext;
	bool		succeeded,
				first;
1447 1448 1449 1450 1451 1452 1453

	Assert(shmTmRecoverred != NULL);

	/* Need to recover ? */
	if (!*shmTmRecoverred)
	{
		/*
A
Ashwin Agrawal 已提交
1454 1455 1456 1457
		 * DTM initialization should be done in the context of the superuser,
		 * and not the user who initiated this backend (MPP-13866). Following
		 * code changes the context to superuser and and then restores it
		 * back.
1458 1459
		 */
		olduser = ChangeToSuperuser();
1460 1461

		SIMPLE_FAULT_INJECTOR(DtmInit);
1462 1463 1464 1465 1466 1467 1468 1469

		oldcontext = CurrentMemoryContext;
		succeeded = false;
		first = true;
		while (true)
		{
			/*
			 * MPP-9894: during startup, we don't have a top-level
A
Ashwin Agrawal 已提交
1470 1471
			 * PG_TRY/PG_CATCH block yet, the dispatcher may throw errors: we
			 * need to catch them.
1472 1473 1474 1475
			 */
			PG_TRY();
			{
				/*
A
Ashwin Agrawal 已提交
1476 1477
				 * FtsNotifyProber could throw ERROR, so we should catch it if
				 * it happens.
1478 1479
				 */
				if (!first)
G
Gang Xiong 已提交
1480
					FtsNotifyProber();
1481 1482 1483 1484 1485 1486 1487 1488 1489

				initTM_recover_as_needed();
				succeeded = true;
			}
			PG_CATCH();
			{
				MemoryContextSwitchTo(oldcontext);

				elog(LOG, "DTM initialization, caught exception: "
A
Ashwin Agrawal 已提交
1490
					 "looking for failed segments.");
1491 1492

				/* Log the error. */
1493
				elog_demote(LOG);
1494
				EmitErrorReport();
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
				FlushErrorState();

				/*
				 * Keep going outside of PG_TRY block even if we want to
				 * retry; don't jumping out of this block without PG_END_TRY.
				 */
			}
			PG_END_TRY();

			if (!succeeded)
			{
				if (first)
				{
					first = false;
					continue;
				}
				else
				{
					elog(LOG, "DTM initialization, failed on retry.");
					elog(FATAL, "DTM initialization: failure during startup "
A
Ashwin Agrawal 已提交
1515
						 "recovery, retry failed, check segment status");
1516 1517 1518
				}
			}

1519
			Assert(!LWLockHeldByMe(shmControlLock));
A
Ashwin Agrawal 已提交
1520

1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
			/*
			 * We are done with the recovery.
			 */
			break;
		}

		RestoreToUser(olduser);

		freeGangsForPortal(NULL);
	}
}

/* get tm share memory size */
int
tmShmemSize(void)
{
	if ((Gp_role != GP_ROLE_DISPATCH) && (Gp_role != GP_ROLE_UTILITY))
		return 0;

	return
G
Gang Xiong 已提交
1541
		MAXALIGN(TMCONTROLBLOCK_BYTES(max_tm_gxacts));
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
}


/*
 * tmShmemInit - should be called only once from postmaster and inherit by all
 * postgres processes
 */
void
tmShmemInit(void)
{
	bool		found;
	TmControlBlock *shared;

	/*
A
Ashwin Agrawal 已提交
1556 1557 1558 1559
	 * max_prepared_xacts is a guc which is postmaster-startup setable -- it
	 * can only be updated by restarting the system. Global transactions will
	 * all use two-phase commit, so the number of global transactions is bound
	 * to the number of prepared.
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
	 */
	max_tm_gxacts = max_prepared_xacts;

	if ((Gp_role != GP_ROLE_DISPATCH) && (Gp_role != GP_ROLE_UTILITY))
		return;

	shared = (TmControlBlock *) ShmemInitStruct("Transaction manager", tmShmemSize(), &found);
	if (!shared)
		elog(FATAL, "could not initialize transaction manager share memory");

	shmControlLock = shared->ControlLock;
G
Gang Xiong 已提交
1571
	shmControlSeqnoLock = &shared->ControlSeqnoLock;
1572 1573 1574 1575 1576 1577 1578
	shmTmRecoverred = &shared->recoverred;
	shmDistribTimeStamp = &shared->distribTimeStamp;
	shmGIDSeq = &shared->seqno;
	/* Only initialize this if we are the creator of the shared memory */
	if (!found)
	{
		time_t		t = time(NULL);
A
Ashwin Agrawal 已提交
1579

1580 1581 1582 1583 1584
		if (t == (time_t) -1)
		{
			elog(PANIC, "cannot generate global transaction id");
		}

A
Ashwin Agrawal 已提交
1585 1586
		*shmDistribTimeStamp = (DistributedTransactionTimeStamp) t;
		elog(DEBUG1, "DTM start timestamp %u", *shmDistribTimeStamp);
1587 1588 1589 1590 1591

		*shmGIDSeq = FirstDistributedTransactionId;
	}
	shmDtmStarted = &shared->DtmStarted;
	shmNextSnapshotId = &shared->NextSnapshotId;
G
Gang Xiong 已提交
1592 1593
	shmNumCommittedGxacts = &shared->num_committed_xacts;
	shmCommittedGxactArray = &shared->committed_gxact_array[0];
1594 1595 1596 1597 1598 1599 1600

	if (!IsUnderPostmaster)
		/* Initialize locks and shared memory area */
	{
		shared->ControlLock = LWLockAssign();
		shmControlLock = shared->ControlLock;

G
Gang Xiong 已提交
1601 1602 1603 1604 1605
		SpinLockInit(shmControlSeqnoLock);
		*shmNextSnapshotId = 0;
		*shmDtmStarted = false;
		*shmTmRecoverred = false;
		*shmNumCommittedGxacts = 0;
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
	}
}

/* mppTxnOptions:
 * Generates an int containing the appropriate flags to direct the remote
 * segdb QE process to perform any needed transaction commands before or
 * after the statement.
 */
int
mppTxnOptions(bool needTwoPhase)
{
A
Ashwin Agrawal 已提交
1617
	int			options = 0;
1618 1619 1620 1621 1622 1623 1624 1625 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

	elog(DTM_DEBUG5,
		 "mppTxnOptions DefaultXactIsoLevel = %s, DefaultXactReadOnly = %s, XactIsoLevel = %s, XactReadOnly = %s.",
		 IsoLevelAsUpperString(DefaultXactIsoLevel), (DefaultXactReadOnly ? "true" : "false"),
		 IsoLevelAsUpperString(XactIsoLevel), (XactReadOnly ? "true" : "false"));

	if (needTwoPhase)
		options |= GP_OPT_NEED_TWO_PHASE;

	if (XactIsoLevel == XACT_READ_COMMITTED)
		options |= GP_OPT_READ_COMMITTED;
	else if (XactIsoLevel == XACT_REPEATABLE_READ)
		options |= GP_OPT_REPEATABLE_READ;
	else if (XactIsoLevel == XACT_SERIALIZABLE)
		options |= GP_OPT_SERIALIZABLE;

	if (XactReadOnly)
		options |= GP_OPT_READ_ONLY;

	if (currentGxact != NULL && currentGxact->explicitBeginRemembered)
		options |= GP_OPT_EXPLICT_BEGIN;

	elog(DTM_DEBUG5,
		 "mppTxnOptions txnOptions = 0x%x, needTwoPhase = %s, explicitBegin = %s, isoLevel = %s, readOnly = %s.",
		 options,
		 (isMppTxOptions_NeedTwoPhase(options) ? "true" : "false"), (isMppTxOptions_ExplicitBegin(options) ? "true" : "false"),
		 IsoLevelAsUpperString(mppTxOptions_IsoLevel(options)), (isMppTxOptions_ReadOnly(options) ? "true" : "false"));

	return options;

}

int
mppTxOptions_IsoLevel(int txnOptions)
{
1653
	if ((txnOptions & GP_OPT_SERIALIZABLE) == GP_OPT_SERIALIZABLE)
1654
		return XACT_SERIALIZABLE;
1655
	else if ((txnOptions & GP_OPT_REPEATABLE_READ) == GP_OPT_REPEATABLE_READ)
1656
		return XACT_REPEATABLE_READ;
1657 1658
	else if ((txnOptions & GP_OPT_READ_COMMITTED) == GP_OPT_READ_COMMITTED)
		return XACT_READ_COMMITTED;
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 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 1706 1707
	else
		return XACT_READ_UNCOMMITTED;
}

bool
isMppTxOptions_ReadOnly(int txnOptions)
{
	return ((txnOptions & GP_OPT_READ_ONLY) != 0);
}



/* unpackMppTxnOptions:
 * Unpack an int containing the appropriate flags to direct the remote
 * segdb QE process to perform any needed transaction commands before or
 * after the statement.
 */
void
unpackMppTxnOptions(int txnOptions, int *isoLevel, bool *readOnly)
{
	*isoLevel = mppTxOptions_IsoLevel(txnOptions);

	*readOnly = isMppTxOptions_ReadOnly(txnOptions);
}

/* isMppTxOptions_StatementWantsDtxTransaction:
 * Return the NeedTwoPhase flag.
 */
bool
isMppTxOptions_NeedTwoPhase(int txnOptions)
{
	return ((txnOptions & GP_OPT_NEED_TWO_PHASE) != 0);
}

/* isMppTxOptions_ExplicitBegin:
 * Return the ExplicitBegin flag.
 */
bool
isMppTxOptions_ExplicitBegin(int txnOptions)
{
	return ((txnOptions & GP_OPT_EXPLICT_BEGIN) != 0);
}

/*
 * Redo transaction commit log record.
 */
void
redoDtxCheckPoint(TMGXACT_CHECKPOINT *gxact_checkpoint)
{
A
Ashwin Agrawal 已提交
1708
	int			committedCount;
1709

A
Ashwin Agrawal 已提交
1710
	int			i;
1711 1712

	/*
A
Ashwin Agrawal 已提交
1713 1714
	 * For checkpoint same as REDO, lets add entries to file in utility and
	 * in-memory if Dispatch.
1715 1716 1717
	 */

	committedCount = gxact_checkpoint->committedCount;
1718
	elog(DTM_DEBUG5, "redoDtxCheckPoint has committedCount = %d", committedCount);
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729

	for (i = 0; i < committedCount; i++)
	{
		redoDistributedCommitRecord(&gxact_checkpoint->committedGxactArray[i]);
	}
}

static void
GetRedoFileName(char *path)
{
	snprintf(path, MAXPGPATH,
A
Ashwin Agrawal 已提交
1730 1731
			 "%s/" UTILITYMODEDTMREDO_DIR "/" UTILITYMODEDTMREDO_FILE, DataDir);
	elog(DTM_DEBUG3, "Returning save DTM redo file path = %s", path);
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
}

void
UtilityModeFindOrCreateDtmRedoFile(void)
{
	char		path[MAXPGPATH];

	if (Gp_role != GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "Not in Utility Mode (role = %s) -- skipping finding or creating DTM redo file",
			 role_to_string(Gp_role));
		return;
	}
	GetRedoFileName(path);

	redoFileFD = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
	if (redoFileFD < 0)
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create save DTM redo file \"%s\"",
						path)));
	}

	redoFileOffset = lseek(redoFileFD, 0, SEEK_END);
	elog(DTM_DEBUG3, "Succesfully opened DTM redo file %s (end offset %d)",
		 path, redoFileOffset);
}

/*
 *
 */
static void
A
Ashwin Agrawal 已提交
1765
UtilityModeSaveRedo(bool committed, TMGXACT_LOG *gxact_log)
1766 1767
{
	TMGXACT_UTILITY_MODE_REDO utilityModeRedo;
A
Ashwin Agrawal 已提交
1768
	int			write_len;
1769 1770 1771 1772 1773

	utilityModeRedo.committed = committed;
	memcpy(&utilityModeRedo.gxact_log, gxact_log, sizeof(TMGXACT_LOG));

	elog(DTM_DEBUG5, "Writing {committed = %s, gid = %s, gxid = %u} to DTM redo file",
A
Ashwin Agrawal 已提交
1774 1775 1776
		 (utilityModeRedo.committed ? "true" : "false"),
		 utilityModeRedo.gxact_log.gid,
		 utilityModeRedo.gxact_log.gxid);
1777 1778 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

	write_len = write(redoFileFD, &utilityModeRedo, sizeof(TMGXACT_UTILITY_MODE_REDO));
	if (write_len != sizeof(TMGXACT_UTILITY_MODE_REDO))
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not write save DTM redo file : %m")));
	}

}

void
UtilityModeCloseDtmRedoFile(void)
{
	if (Gp_role != GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "Not in Utility Mode (role = %s)-- skipping closing DTM redo file",
			 role_to_string(Gp_role));
		return;
	}
	elog(DTM_DEBUG3, "Closing DTM redo file");
	close(redoFileFD);
}

static void
ReplayRedoFromUtilityMode(void)
{
	TMGXACT_UTILITY_MODE_REDO utilityModeRedo;

	int			fd;
	int			read_len;
A
Ashwin Agrawal 已提交
1808
	int			errno;
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
	char		path[MAXPGPATH];
	int			entries;

	entries = 0;

	GetRedoFileName(path);

	fd = open(path, O_RDONLY, 0);
	if (fd < 0)
	{
		/* UNDONE: Distinquish "not found" from other errors. */
		elog(DTM_DEBUG3, "Could not open DTM redo file %s for reading",
A
Ashwin Agrawal 已提交
1821
			 path);
1822 1823 1824 1825 1826 1827
		return;
	}

	elog(DTM_DEBUG3, "Succesfully opened DTM redo file %s for reading",
		 path);

A
Ashwin Agrawal 已提交
1828
	while (true)
1829 1830 1831 1832 1833 1834 1835 1836
	{
		errno = 0;
		read_len = read(fd, &utilityModeRedo, sizeof(TMGXACT_UTILITY_MODE_REDO));

		if (read_len == 0)
			break;
		else if (read_len != sizeof(TMGXACT_UTILITY_MODE_REDO) && errno == 0)
			elog(ERROR, "Bad redo length (expected %d and found %d)",
A
Ashwin Agrawal 已提交
1837
				 (int) sizeof(TMGXACT_UTILITY_MODE_REDO), read_len);
1838 1839 1840 1841 1842 1843 1844 1845 1846
		else if (errno != 0)
		{
			close(fd);
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("error reading DTM redo file: %m")));
		}

		elog(DTM_DEBUG5, "Read {committed = %s, gid = %s, gxid = %u} from DTM redo file",
A
Ashwin Agrawal 已提交
1847 1848 1849
			 (utilityModeRedo.committed ? "true" : "false"),
			 utilityModeRedo.gxact_log.gid,
			 utilityModeRedo.gxact_log.gxid);
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
		if (utilityModeRedo.committed)
		{
			redoDistributedCommitRecord(&utilityModeRedo.gxact_log);
		}
		else
		{
			redoDistributedForgetCommitRecord(&utilityModeRedo.gxact_log);
		}

		entries++;
	}

	elog(DTM_DEBUG5, "Processed %d entries from DTM redo file",
		 entries);
	close(fd);

}

static void
RemoveRedoUtilityModeFile(void)
{
	char		path[MAXPGPATH];
A
Ashwin Agrawal 已提交
1872
	bool		removed;
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883

	GetRedoFileName(path);
	removed = (unlink(path) == 0);
	elog(DTM_DEBUG5, "Removed DTM redo file %s (%s)",
		 path, (removed ? "true" : "false"));
}

/*
 * Redo transaction commit log record.
 */
void
A
Ashwin Agrawal 已提交
1884
redoDistributedCommitRecord(TMGXACT_LOG *gxact_log)
1885 1886 1887 1888 1889
{

	int			i;

	/*
A
Ashwin Agrawal 已提交
1890 1891
	 * The length check here requires the identifer have a trailing NUL
	 * character.
1892 1893 1894
	 */
	if (strlen(gxact_log->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
1895
			 (int) strlen(gxact_log->gid));
1896 1897 1898 1899 1900 1901 1902 1903

	if (Gp_role == GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "DB in Utility mode.  Save DTM distributed commit until later.");
		UtilityModeSaveRedo(true, gxact_log);
		return;
	}

G
Gang Xiong 已提交
1904
	for (i = 0; i < *shmNumCommittedGxacts; i++)
1905
	{
G
Gang Xiong 已提交
1906 1907
		if (strcmp(gxact_log->gid, shmCommittedGxactArray[i].gid) == 0)
			return;
1908
	}
G
Gang Xiong 已提交
1909 1910

	if (i == *shmNumCommittedGxacts)
1911 1912 1913 1914
	{
		/*
		 * Transaction not found, this is the first log of this transaction.
		 */
G
Gang Xiong 已提交
1915
		if (*shmNumCommittedGxacts >= max_tm_gxacts)
1916 1917 1918 1919 1920 1921 1922
		{
			ereport(FATAL,
					(errmsg("the limit of %d distributed transactions has been reached.",
							max_tm_gxacts),
					 errdetail("The global user configuration (GUC) server parameter max_prepared_transactions controls this limit.")));
		}

G
Gang Xiong 已提交
1923 1924 1925
		shmCommittedGxactArray[(*shmNumCommittedGxacts)++] = *gxact_log;
		elog((Debug_print_full_dtm ? LOG : DEBUG5),
				"Crash recovery redo added committed distributed transaction gid = %s", gxact_log->gid);
1926 1927 1928 1929 1930 1931 1932
	}
}

/*
 * Redo transaction forget commit log record.
 */
void
A
Ashwin Agrawal 已提交
1933
redoDistributedForgetCommitRecord(TMGXACT_LOG *gxact_log)
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
{
	int			i;

	if (Gp_role == GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "DB in Utility mode.  Save DTM disributed forget until later.");
		UtilityModeSaveRedo(false, gxact_log);
		return;
	}

G
Gang Xiong 已提交
1944
	for (i = 0; i < *shmNumCommittedGxacts; i++)
1945
	{
G
Gang Xiong 已提交
1946
		if (strcmp(gxact_log->gid, shmCommittedGxactArray[i].gid) == 0)
1947 1948 1949 1950
		{
			/* found an active global transaction */
			elog((Debug_print_full_dtm ? INFO : DEBUG5),
				 "Crash recovery redo removed committed distributed transaction gid = %s for forget",
G
Gang Xiong 已提交
1951 1952 1953 1954 1955 1956 1957
				 gxact_log->gid);

			/* there's no concurrent access to shmCommittedGxactArray during recovery */
			(*shmNumCommittedGxacts)--;
			if (i != *shmNumCommittedGxacts)
				shmCommittedGxactArray[i] = shmCommittedGxactArray[*shmNumCommittedGxacts];

1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
			return;
		}
	}

	elog((Debug_print_full_dtm ? WARNING : DEBUG5),
		 "Crash recovery redo did not find committed distributed transaction gid = %s for forget",
		 gxact_log->gid);

}

static void
A
Ashwin Agrawal 已提交
1969
descGxactLog(StringInfo buf, TMGXACT_LOG *gxact_log)
1970 1971 1972 1973 1974 1975 1976 1977 1978
{
	appendStringInfo(buf, " gid = %s, gxid = %u",
					 gxact_log->gid, gxact_log->gxid);
}

/*
 * Describe redo transaction commit log record.
 */
void
A
Ashwin Agrawal 已提交
1979
descDistributedCommitRecord(StringInfo buf, TMGXACT_LOG *gxact_log)
1980 1981 1982 1983 1984 1985 1986 1987
{
	descGxactLog(buf, gxact_log);
}

/*
 * Describe redo transaction forget commit log record.
 */
void
A
Ashwin Agrawal 已提交
1988
descDistributedForgetCommitRecord(StringInfo buf, TMGXACT_LOG *gxact_log)
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
{
	descGxactLog(buf, gxact_log);
}


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

static bool
doDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, int flags,
A
Ashwin Agrawal 已提交
2000
							 char *gid, DistributedTransactionId gxid,
2001 2002
							 bool *badGangs, bool raiseError,
							 CdbDispatchDirectDesc *direct,
2003 2004
							 char *serializedDtxContextInfo,
							 int serializedDtxContextInfoLen)
2005
{
A
Ashwin Agrawal 已提交
2006 2007 2008
	int			i,
				resultCount,
				numOfFailed = 0;
2009

A
Ashwin Agrawal 已提交
2010
	char	   *dtxProtocolCommandStr = 0;
2011

2012
	struct pg_result **results = NULL;
2013 2014 2015

	dtxProtocolCommandStr = DtxProtocolCommandToString(dtxProtocolCommand);

A
Ashwin Agrawal 已提交
2016
	if (Test_print_direct_dispatch_info)
2017
	{
A
Ashwin Agrawal 已提交
2018
		if (direct->directed_dispatch)
2019
			elog(INFO, "Distributed transaction command '%s' to SINGLE content", dtxProtocolCommandStr);
A
Ashwin Agrawal 已提交
2020 2021
		else
			elog(INFO, "Distributed transaction command '%s' to ALL contents", dtxProtocolCommandStr);
2022 2023 2024 2025
	}
	elog(DTM_DEBUG5,
		 "dispatchDtxProtocolCommand: %d ('%s'), direct content #: %d",
		 dtxProtocolCommand, dtxProtocolCommandStr,
A
Ashwin Agrawal 已提交
2026
		 direct->directed_dispatch ? direct->content[0] : -1);
2027

2028
	ErrorData *qeError;
2029
	results = CdbDispatchDtxProtocolCommand(dtxProtocolCommand, flags,
A
Ashwin Agrawal 已提交
2030 2031
											dtxProtocolCommandStr,
											gid, gxid,
2032
											&qeError, &resultCount, badGangs, direct,
A
Ashwin Agrawal 已提交
2033
											serializedDtxContextInfo, serializedDtxContextInfoLen);
2034

2035
	if (qeError)
2036
	{
2037 2038 2039 2040 2041 2042 2043 2044
		if (!raiseError)
		{
			ereport(LOG,
					(errmsg("DTM error (gathered results from cmd '%s')", dtxProtocolCommandStr),
					 errdetail("QE reported error: %s", qeError->message)));
		}
		else
			ReThrowError(qeError);
2045 2046 2047 2048 2049
		return false;
	}

	if (results == NULL)
	{
A
Ashwin Agrawal 已提交
2050 2051
		numOfFailed++;			/* If we got no results, we need to treat it
								 * as an error! */
2052
	}
2053

2054 2055
	for (i = 0; i < resultCount; i++)
	{
A
Ashwin Agrawal 已提交
2056 2057
		char	   *cmdStatus;
		ExecStatusType resultStatus;
2058

A
Ashwin Agrawal 已提交
2059 2060 2061 2062
		/*
		 * note: PQresultStatus() is smart enough to deal with results[i] ==
		 * NULL
		 */
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
		resultStatus = PQresultStatus(results[i]);
		if (resultStatus != PGRES_COMMAND_OK &&
			resultStatus != PGRES_TUPLES_OK)
		{
			numOfFailed++;
		}
		else
		{
			/*
			 * success ? If an error happened during a transaction which
			 * hasn't already been caught when we try a prepare we'll get a
			 * rollback from our prepare ON ONE SEGMENT: so we go look at the
			 * status, otherwise we could issue a COMMIT when we don't want
			 * to!
			 */
			cmdStatus = PQcmdStatus(results[i]);

			elog(DEBUG3, "DTM: status message cmd '%s' [%d] result '%s'", dtxProtocolCommandStr, i, cmdStatus);
			if (strncmp(cmdStatus, dtxProtocolCommandStr, strlen(cmdStatus)) != 0)
			{
				/* failed */
				numOfFailed++;
			}
		}
	}

2089 2090
	for (i = 0; i < resultCount; i++)
		PQclear(results[i]);
2091 2092 2093

	if (results)
		free(results);
2094 2095 2096 2097 2098 2099

	return (numOfFailed == 0);
}


bool
2100
dispatchDtxCommand(const char *cmd)
2101
{
A
Ashwin Agrawal 已提交
2102 2103
	int			i,
				numOfFailed = 0;
2104

2105
	CdbPgResults cdb_pgresults = {NULL, 0};
2106 2107 2108

	elog(DTM_DEBUG5, "dispatchDtxCommand: '%s'", cmd);

2109
	CdbDispatchCommand(cmd, DF_NONE, &cdb_pgresults);
2110

2111
	if (cdb_pgresults.numResults == 0)
2112
	{
A
Ashwin Agrawal 已提交
2113 2114
		return false;			/* If we got no results, we need to treat it
								 * as an error! */
2115 2116
	}

2117
	for (i = 0; i < cdb_pgresults.numResults; i++)
2118
	{
A
Ashwin Agrawal 已提交
2119 2120
		char	   *cmdStatus;
		ExecStatusType resultStatus;
2121

A
Ashwin Agrawal 已提交
2122 2123 2124 2125
		/*
		 * note: PQresultStatus() is smart enough to deal with results[i] ==
		 * NULL
		 */
2126
		resultStatus = PQresultStatus(cdb_pgresults.pg_results[i]);
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
		if (resultStatus != PGRES_COMMAND_OK &&
			resultStatus != PGRES_TUPLES_OK)
		{
			numOfFailed++;
		}
		else
		{
			/*
			 * success ? If an error happened during a transaction which
			 * hasn't already been caught when we try a prepare we'll get a
			 * rollback from our prepare ON ONE SEGMENT: so we go look at the
			 * status, otherwise we could issue a COMMIT when we don't want
			 * to!
			 */
2141
			cmdStatus = PQcmdStatus(cdb_pgresults.pg_results[i]);
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151

			elog(DEBUG3, "DTM: status message cmd '%s' [%d] result '%s'", cmd, i, cmdStatus);
			if (strncmp(cmdStatus, cmd, strlen(cmdStatus)) != 0)
			{
				/* failed */
				numOfFailed++;
			}
		}
	}

2152
	cdbdisp_clearCdbPgResults(&cdb_pgresults);
2153 2154 2155 2156 2157

	return (numOfFailed == 0);
}

/* initialize a global transaction context */
G
Gang Xiong 已提交
2158
void
A
Ashwin Agrawal 已提交
2159
initGxact(TMGXACT *gxact)
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
{
	MemSet(gxact->gid, 0, TMGIDSIZE);
	gxact->gxid = InvalidDistributedTransactionId;
	setGxactState(gxact, DTX_STATE_NONE);

	/*
	 * Memory only fields.
	 */

	gxact->sessionId = gp_session_id;

	gxact->explicitBeginRemembered = false;

2173
	gxact->xminDistributedSnapshot = InvalidDistributedTransactionId;
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195

	gxact->badPrepareGangs = false;

	gxact->directTransaction = false;
	gxact->directTransactionContentId = 0;
}

bool
getNextDistributedXactStatus(TMGALLXACTSTATUS *allDistributedXactStatus, TMGXACTSTATUS **distributedXactStatus)
{
	if (allDistributedXactStatus->next >= allDistributedXactStatus->count)
	{
		return false;
	}

	*distributedXactStatus = &allDistributedXactStatus->statusArray[allDistributedXactStatus->next];
	allDistributedXactStatus->next++;

	return true;
}

void
G
Gang Xiong 已提交
2196
setCurrentGxact(void)
2197
{
G
Gang Xiong 已提交
2198 2199
	DistributedTransactionId gxid = generateGID();
	Assert(gxid != InvalidDistributedTransactionId);
2200

G
Gang Xiong 已提交
2201
	currentGxact = &MyProc->gxact;
2202

G
Gang Xiong 已提交
2203 2204 2205 2206 2207
	Assert(*shmDistribTimeStamp != 0);
	sprintf(currentGxact->gid, "%u-%.10u", *shmDistribTimeStamp, gxid);
	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
				(int) strlen(currentGxact->gid));
2208 2209

	/*
A
Ashwin Agrawal 已提交
2210 2211
	 * Until we get our first distributed snapshot, we use our distributed
	 * transaction identifier for the minimum.
2212
	 */
G
Gang Xiong 已提交
2213
	currentGxact->xminDistributedSnapshot = gxid;
2214

G
Gang Xiong 已提交
2215
	setCurrentGxactState(DTX_STATE_ACTIVE_NOT_DISTRIBUTED);
2216

G
Gang Xiong 已提交
2217
	currentGxact->gxid = gxid;
2218 2219 2220
}

static void
G
Gang Xiong 已提交
2221
resetCurrentGxact(void)
2222
{
G
Gang Xiong 已提交
2223 2224
	Assert (currentGxact != NULL);
	Assert (currentGxact->gxid == InvalidDistributedTransactionId);
2225 2226 2227 2228
	currentGxact = NULL;
}

static void
G
Gang Xiong 已提交
2229
clearAndResetGxact(void)
2230
{
G
Gang Xiong 已提交
2231
	Assert(currentGxact != NULL);
2232

G
Gang Xiong 已提交
2233 2234 2235
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
	ProcArrayEndGxact();
	LWLockRelease(ProcArrayLock);
2236

G
Gang Xiong 已提交
2237
	resetCurrentGxact();
2238 2239 2240
}

/*
G
Gang Xiong 已提交
2241
 * serializes commits with checkpoint info using PGPROC->inCommit
2242 2243 2244 2245 2246 2247 2248
 * Change state to DTX_STATE_INSERTING_COMMITTED.
 */
void
insertingDistributedCommitted(void)
{
	elog(DTM_DEBUG5,
		 "insertingDistributedCommitted entering in state = %s",
A
Ashwin Agrawal 已提交
2249
		 DtxStateToString(currentGxact->state));
2250 2251

	Assert(currentGxact->state == DTX_STATE_PREPARED);
A
Ashwin Agrawal 已提交
2252
	setCurrentGxactState(DTX_STATE_INSERTING_COMMITTED);
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
}

/*
 * Change state to DTX_STATE_INSERTED_COMMITTED.
 */
void
insertedDistributedCommitted(void)
{
	elog(DTM_DEBUG5,
		 "insertedDistributedCommitted entering in state = %s for gid = %s",
A
Ashwin Agrawal 已提交
2263
		 DtxStateToString(currentGxact->state), currentGxact->gid);
2264 2265

	Assert(currentGxact->state == DTX_STATE_INSERTING_COMMITTED);
A
Ashwin Agrawal 已提交
2266
	setCurrentGxactState(DTX_STATE_INSERTED_COMMITTED);
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
}


/*
 * Change state to DTX_STATE_FORCED_COMMITTED.
 */
void
forcedDistributedCommitted(XLogRecPtr *recptr)
{
	elog(DTM_DEBUG5,
		 "forcedDistributedCommitted entering in state = %s for gid = %s (xlog record %X/%X)",
2278
		 DtxStateToString(currentGxact->state), currentGxact->gid, recptr->xlogid, recptr->xrecoff);
2279 2280

	Assert(currentGxact->state == DTX_STATE_INSERTED_COMMITTED);
A
Ashwin Agrawal 已提交
2281
	setCurrentGxactState(DTX_STATE_FORCED_COMMITTED);
2282 2283
}

G
Gang Xiong 已提交
2284 2285 2286
/* generate global transaction id */
static DistributedTransactionId
generateGID(void)
2287
{
G
Gang Xiong 已提交
2288
	DistributedTransactionId gxid;
2289

G
Gang Xiong 已提交
2290
	SpinLockAcquire(shmControlSeqnoLock);
2291 2292 2293 2294

	/* tm lock acquired by caller */
	if (*shmGIDSeq >= LastDistributedTransactionId)
	{
G
Gang Xiong 已提交
2295
		SpinLockRelease(shmControlSeqnoLock);
2296
		ereport(FATAL,
A
Ashwin Agrawal 已提交
2297
				(errmsg("reached limit of %u global transactions per start", LastDistributedTransactionId)));
2298
	}
G
Gang Xiong 已提交
2299
	gxid = ++(*shmGIDSeq);
2300

G
Gang Xiong 已提交
2301 2302
	SpinLockRelease(shmControlSeqnoLock);
	return gxid;
2303 2304
}

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
/*
 * Return the highest global transaction id that has been generated.
 */
DistributedTransactionId
getMaxDistributedXid(void)
{
	if (!shmGIDSeq)
		return 0;

	return *shmGIDSeq;
}

2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
/*
 * recoverTM:
 * perform TM recovery, this connects to all QE and resolve all in-doubt txn.
 *
 * This gets called when there is not any other DTM activity going on.
 *
 * First, we'll replay the dtm log and get our shmem as up to date as possible
 * in order to help resolve in-doubt transactions.	Then we'll go through and
 * try and resolve in-doubt transactions based on information in the DTM log.
 * The remaining in-doubt transactions that remain (ones the DTM doesn't know
 * about) are all ABORTed.
 *
 * If we're in read-only mode; we need to get started, but we can't run the
 * full recovery. So we go get the highest distributed-xid, but don't run
 * the recovery.
 */
static void
recoverTM(void)
{
2336
	bool		dtmRecoveryDeferred;
2337 2338 2339 2340

	elog(DTM_DEBUG3, "Starting to Recover DTM...");

	/*
A
Ashwin Agrawal 已提交
2341 2342 2343
	 * do not do recovery if read only mode is set. in this case, there may be
	 * in-doubt transaction in down segdb , which will not be resolved at this
	 * time.
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
	 */
	if (isFtsReadOnlySet())
	{
		elog(DTM_DEBUG3, "FTS is Read Only.  Defer DTM recovery till later.");
		if (currentGxact != NULL)
		{
			elog(DTM_DEBUG5,
				 "recoverTM setting currentGxact to NULL for gid = %s (index = %d)",
				 currentGxact->gid, currentGxact->debugIndex);
		}
		currentGxact = NULL;

2356
		dtmRecoveryDeferred = true;
2357 2358
	}
	else
2359
		dtmRecoveryDeferred = false;
2360 2361 2362 2363 2364 2365 2366

	if (Gp_role == GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "DB in Utility mode.  Defer DTM recovery till later.");
		return;
	}

2367
	if (!dtmRecoveryDeferred)
2368 2369 2370 2371 2372
	{
		/*
		 * Attempt to recover all in-doubt transactions.
		 *
		 * first resolve all in-doubt transactions from the DTM's perspective
A
Ashwin Agrawal 已提交
2373 2374
		 * and then resolve any remaining in-doubt transactions that the RMs
		 * have.
2375 2376 2377 2378 2379 2380 2381 2382
		 */
		recoverInDoubtTransactions();
	}
	else
		elog(LOG, "DTM starting in readonly-mode: deferring recovery");

	/* finished recovery successfully. */

2383
	*shmGIDSeq = 1;
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395

	*shmDtmStarted = true;
	elog(LOG, "DTM Started");
}

/* recoverInDoubtTransactions:
 * Go through all in-doubt transactions that the DTM knows about and
 * resolve them.
 */
static bool
recoverInDoubtTransactions(void)
{
A
Ashwin Agrawal 已提交
2396 2397
	int			i;
	HTAB	   *htab;
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409

	elog(DTM_DEBUG3, "recover in-doubt distributed transactions");

	ReplayRedoFromUtilityMode();

	/*
	 * For each committed transaction found in the redo pass that was not
	 * matched by a forget committed record, change its state indicating
	 * committed notification needed.  Attempt a notification.
	 */
	elog(DTM_DEBUG5,
		 "Going to retry commit notification for distributed transactions (count = %d)",
G
Gang Xiong 已提交
2410
		 *shmNumCommittedGxacts);
2411

G
Gang Xiong 已提交
2412
	for (i = 0; i < *shmNumCommittedGxacts; i++)
2413
	{
G
Gang Xiong 已提交
2414
		TMGXACT_LOG    *gxact_log = &shmCommittedGxactArray[i];
2415

G
Gang Xiong 已提交
2416
		Assert(gxact_log->gxid != InvalidDistributedTransactionId);
2417 2418 2419

		elog(DTM_DEBUG5,
			 "Recovering committed distributed transaction gid = %s",
G
Gang Xiong 已提交
2420
			 gxact_log->gid);
2421

G
Gang Xiong 已提交
2422
		doNotifyCommittedInDoubt(gxact_log->gid);
2423

G
Gang Xiong 已提交
2424
		RecordDistributedForgetCommitted(gxact_log);
2425 2426
	}

G
Gang Xiong 已提交
2427
	*shmNumCommittedGxacts = 0;
2428
	/*
A
Ashwin Agrawal 已提交
2429 2430
	 * UNDONE: Thus, any in-doubt transctions found will be for aborted
	 * transactions. UNDONE: Gather in-boubt transactions and issue aborts.
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
	 */
	htab = gatherRMInDoubtTransactions();

	/*
	 * go through and resolve any remaining in-doubt transactions that the
	 * RM's have AFTER recoverDTMInDoubtTransactions.  ALL of these in doubt
	 * transactions will be ABORT'd.  The fact that the DTM doesn't know about
	 * them means that something bad happened before everybody voted to
	 * COMMIT.
	 */
	abortRMInDoubtTransactions(htab);

	/* get rid of the hashtable */
	hash_destroy(htab);

	/* yes... we are paranoid and will double check */
	htab = gatherRMInDoubtTransactions();

	/*
	 * Hmm.  we still have some remaining indoubt transactions.  For now we
	 * dont have an automated way to clean this mess up.  So we'll have to
	 * rely on smart Admins to do the job manually.  We'll error out of here
	 * and try and provide as much info as possible.
	 *
	 * TODO: We really want to be able to say this particular segdb has these
	 * remaining in-doubt transactions.
	 */
	if (htab != NULL)
	{
		StringInfoData indoubtBuff;

		initStringInfo(&indoubtBuff);

		dumpRMOnlyDtx(htab, &indoubtBuff);

		ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
						errmsg("DTM Log recovery failed.  There are still unresolved "
							   "in-doubt transactions on some of the segment databaes "
							   "that were not able to be resolved for an unknown reason. "),
						errdetail("Here is a list of in-doubt transactions in the system: %s",
								  indoubtBuff.data),
						errhint("Try restarting the Greenplum Database array.  If the problem persists "
								" an Administrator will need to resolve these transactions "
								" manually.")));

	}

	RemoveRedoUtilityModeFile();

	return true;
}

/*
 * gatherRMInDoubtTransactions:
 * Builds a hashtable of all of the in-doubt transactions that exist on the
 * segment databases.  The hashtable basically just serves as a single list
 * without duplicates of all the in-doubt transactions.  It does not keep track
 * of which seg db's have which transactions in-doubt.  It currently doesn't
 * need to due to the way we handle this information later.
 */
static HTAB *
gatherRMInDoubtTransactions(void)
{
2494
	CdbPgResults cdb_pgresults = {NULL, 0};
2495
	const char *cmdbuf = "select gid from pg_prepared_xacts";
2496
	PGresult   *rs;
2497 2498 2499 2500 2501

	InDoubtDtx *lastDtx = NULL;

	HASHCTL		hctl;
	HTAB	   *htab = NULL;
2502
	int			i;
2503 2504 2505 2506 2507
	int			j,
				rows;
	bool		found;

	/* call to all QE to get in-doubt transactions */
2508
	CdbDispatchCommand(cmdbuf, DF_NONE, &cdb_pgresults);
2509 2510

	/* If any result set is nonempty, there are in-doubt transactions. */
2511
	for (i = 0; i < cdb_pgresults.numResults; i++)
2512
	{
A
Ashwin Agrawal 已提交
2513
		rs = cdb_pgresults.pg_results[i];
2514
		rows = PQntuples(rs);
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527

		for (j = 0; j < rows; j++)
		{
			char	   *gid;

			/*
			 * we dont setup our hashtable until we know we have at least one
			 * in doubt transaction
			 */
			if (htab == NULL)
			{

				/* setup a hash table */
A
Ashwin Agrawal 已提交
2528
				hctl.keysize = TMGIDSIZE;	/* GID */
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
				hctl.entrysize = sizeof(InDoubtDtx);

				htab = hash_create("InDoubtDtxHash", 10, &hctl, HASH_ELEM);

				if (htab == NULL)
				{
					ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY),
									errmsg("DTM could not allocate hash table for InDoubtDtxList.")));
				}
			}

2540
			gid = PQgetvalue(rs, j, 0);
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

			/* Now we can add entry to hash table */
			lastDtx = (InDoubtDtx *) hash_search(htab, gid, HASH_ENTER, &found);

			/*
			 * only need to bother doing work if there isn't already an entry
			 * for our GID
			 */
			if (!found)
			{
				elog(DEBUG3, "Found in-doubt transaction with GID: %s on remote RM", gid);

				strcpy(lastDtx->gid, gid);
			}

		}
	}

2559
	cdbdisp_clearCdbPgResults(&cdb_pgresults);
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634

	return htab;
}

/*
 * abortRMInDoubtTransactions:
 * Goes through all the InDoubtDtx's in the provided htab and ABORTs them
 * across all of the QEs by sending a ROLLBACK PREPARED.
 *
 */
static void
abortRMInDoubtTransactions(HTAB *htab)
{
	HASH_SEQ_STATUS status;
	InDoubtDtx *entry = NULL;

	if (htab == NULL)
		return;

	/*
	 * now we have a nice hashtable full of in-doubt dtx's that we need to
	 * resolve.  so we'll use a nice big hammer to get this job done.  instead
	 * of keeping track of which QEs have a prepared txn to be aborted and
	 * which ones don't.  we just issue a ROLLBACK to all of them and ignore
	 * any pesky errors.  This is certainly not an elegant solution but is OK
	 * for now.
	 */
	hash_seq_init(&status, htab);


	while ((entry = (InDoubtDtx *) hash_seq_search(&status)) != NULL)
	{
		elog(DTM_DEBUG3, "Aborting in-doubt transaction with gid = %s", entry->gid);

		doAbortInDoubt(entry->gid);

	}
}

static void
dumpRMOnlyDtx(HTAB *htab, StringInfoData *buff)
{
	HASH_SEQ_STATUS status;
	InDoubtDtx *entry = NULL;

	if (htab == NULL)
		return;

	hash_seq_init(&status, htab);

	appendStringInfo(buff, "List of In-doubt transactions remaining across the segdbs: (");

	while ((entry = (InDoubtDtx *) hash_seq_search(&status)) != NULL)
	{
		appendStringInfo(buff, "\"%s\" , ", entry->gid);
	}

	appendStringInfo(buff, ")");

}


/*
 * When called, a SET command is dispatched and the writer gang
 * writes the shared snapshot. This function actually does nothing
 * useful besides making sure that a writer gang is alive and has
 * set the shared snapshot so that the readers could access it.
 *
 * At this point this function is added as a helper for cursor
 * query execution since in MPP cursor queries don't use writer
 * gangs. However, it could be used for other purposes as well.
 *
 * See declaration of assign_gp_write_shared_snapshot(...) for more
 * information.
 */
A
Ashwin Agrawal 已提交
2635 2636
void
verify_shared_snapshot_ready(void)
2637 2638 2639
{
	if (Gp_role == GP_ROLE_DISPATCH)
	{
2640
		CdbDispatchCommand("set gp_write_shared_snapshot=true",
A
Ashwin Agrawal 已提交
2641 2642 2643 2644
						   DF_CANCEL_ON_ERROR |
						   DF_WITH_SNAPSHOT |
						   DF_NEED_TWO_PHASE,
						   NULL);
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663

		dumpSharedLocalSnapshot_forCursor();

		/*
		 * To keep our readers in sync (since they will be dispatched
		 * separately) we need to rewind the segmate synchronizer.
		 */
		DtxContextInfo_RewindSegmateSync();
	}
}

/*
 * Force the writer QE to write the shared snapshot. Will get called
 * after a "set gp_write_shared_snapshot=<true/false>" is executed
 * in dispatch mode.
 *
 * See verify_shared_snapshot_ready(...) for additional information.
 */
bool
A
Ashwin Agrawal 已提交
2664
assign_gp_write_shared_snapshot(bool newval, bool doit, GucSource source __attribute__((unused)))
2665 2666 2667 2668 2669 2670
{

#if FALSE
	elog(DEBUG1, "SET gp_write_shared_snapshot: %s, doit=%s",
		 (newval ? "true" : "false"), (doit ? "true" : "false"));
#endif
A
Ashwin Agrawal 已提交
2671

2672
	/*
A
Ashwin Agrawal 已提交
2673 2674
	 * Make sure newval is "true". if it's "false" this could be a part of a
	 * ROLLBACK so we don't want to set the snapshot then.
2675 2676 2677 2678 2679
	 */
	if (doit && newval)
	{
		if (Gp_role == GP_ROLE_EXECUTE)
		{
2680
			PushActiveSnapshot(GetTransactionSnapshot());
2681 2682 2683 2684 2685

			if (Gp_is_writer)
			{
				dumpSharedLocalSnapshot_forCursor();
			}
2686 2687

			PopActiveSnapshot();
2688 2689 2690 2691 2692 2693 2694 2695 2696
		}
	}

	return true;
}

static void
doQEDistributedExplicitBegin(int txnOptions)
{
A
Ashwin Agrawal 已提交
2697 2698
	int			ExplicitIsoLevel;
	bool		ExplicitReadOnly;
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708

	/*
	 * Start a command.
	 */
	StartTransactionCommand();

	/* Here is the explicit BEGIN. */
	BeginTransactionBlock();

	unpackMppTxnOptions(txnOptions,
A
Ashwin Agrawal 已提交
2709
						&ExplicitIsoLevel, &ExplicitReadOnly);
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727

	XactIsoLevel = ExplicitIsoLevel;
	XactReadOnly = ExplicitReadOnly;

	elog(DTM_DEBUG5, "doQEDistributedExplicitBegin setting XactIsoLevel = %s and XactReadOnly = %s",
		 IsoLevelAsUpperString(XactIsoLevel), (XactReadOnly ? "true" : "false"));

	/*
	 * Finish the BEGIN command.  It will leave the explict transaction
	 * in-progress.
	 */
	CommitTransactionCommand();

}

static bool
isDtxQueryDispatcher(void)
{
A
Ashwin Agrawal 已提交
2728 2729
	bool		isDtmStarted;
	bool		isSharedLocalSnapshotSlotPresent;
2730 2731 2732 2733

	isDtmStarted = (shmDtmStarted != NULL && *shmDtmStarted);
	isSharedLocalSnapshotSlotPresent = (SharedLocalSnapshotSlot != NULL);

A
Ashwin Agrawal 已提交
2734 2735 2736
	return (Gp_role == GP_ROLE_DISPATCH &&
			isDtmStarted &&
			isSharedLocalSnapshotSlotPresent);
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752
}

/*
 * Called prior to handling a requested that comes to the QD, or a utility request to a QE.
 *
 * Sets up the distributed transaction context value and does some basic error checking.
 *
 * Essentially:
 *     if the DistributedTransactionContext is already QD_DISTRIBUTED_CAPABLE then leave it
 *     else if the DistributedTransactionContext is already QE_TWO_PHASE_EXPLICIT_WRITER then leave it
 *     else it MUST be a LOCAL_ONLY, and is converted to QD_DISTRIBUTED_CAPABLE if this process is acting
 *          as a QE.
 */
void
setupRegularDtxContext(void)
{
A
Ashwin Agrawal 已提交
2753
	switch (DistributedTransactionContext)
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
	{
		case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
			/* Continue in this context.  Do not touch QEDtxContextInfo, etc. */
			break;

		case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
			/* Allow this for copy...???  Do not touch QEDtxContextInfo, etc. */
			break;

		default:
			if (DistributedTransactionContext != DTX_CONTEXT_LOCAL_ONLY)
			{
A
Ashwin Agrawal 已提交
2766 2767 2768 2769 2770 2771 2772 2773 2774
				/*
				 * we must be one of:
				 *
				 * DTX_CONTEXT_QD_RETRY_PHASE_2,
				 * DTX_CONTEXT_QE_ENTRY_DB_SINGLETON,
				 * DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT,
				 * DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER,
				 * DTX_CONTEXT_QE_READER, DTX_CONTEXT_QE_PREPARED
				 */
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805

				elog(ERROR, "setupRegularDtxContext finds unexpected DistributedTransactionContext = '%s'",
					 DtxContextToString(DistributedTransactionContext));
			}

			/* DistributedTransactionContext is DTX_CONTEXT_LOCAL_ONLY */

			Assert(QEDtxContextInfo.distributedXid == InvalidDistributedTransactionId);

			/*
			 * Determine if we are strictly local or a distributed capable QD.
			 */
			Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);

			if (isDtxQueryDispatcher())
			{
				setDistributedTransactionContext(DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE);
			}
			break;
	}

	elog(DTM_DEBUG5, "setupRegularDtxContext leaving with DistributedTransactionContext = '%s'.",
		 DtxContextToString(DistributedTransactionContext));
}

/**
 * Called on the QE when a query to process has been received.
 *
 * This will set up all distributed transaction information and set the state appropriately.
 */
void
A
Ashwin Agrawal 已提交
2806
setupQEDtxContext(DtxContextInfo *dtxContextInfo)
2807 2808
{
	DistributedSnapshot *distributedSnapshot;
A
Ashwin Agrawal 已提交
2809 2810 2811 2812 2813 2814 2815 2816
	int			txnOptions;
	bool		needTwoPhase;
	bool		explicitBegin;
	bool		haveDistributedSnapshot;
	bool		isEntryDbSingleton = false;
	bool		isReaderQE = false;
	bool		isWriterQE = false;
	bool		isSharedLocalSnapshotSlotPresent;
2817

A
Ashwin Agrawal 已提交
2818
	Assert(dtxContextInfo != NULL);
2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829

	/*
	 * DTX Context Info (even when empty) only comes in QE requests.
	 */
	distributedSnapshot = &dtxContextInfo->distributedSnapshot;
	txnOptions = dtxContextInfo->distributedTxnOptions;

	needTwoPhase = isMppTxOptions_NeedTwoPhase(txnOptions);
	explicitBegin = isMppTxOptions_ExplicitBegin(txnOptions);

	haveDistributedSnapshot =
A
Ashwin Agrawal 已提交
2830
		(dtxContextInfo->distributedXid != InvalidDistributedTransactionId);
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
	isSharedLocalSnapshotSlotPresent = (SharedLocalSnapshotSlot != NULL);

	if (DEBUG5 >= log_min_messages || Debug_print_full_dtm)
	{
		elog(DTM_DEBUG5,
			 "setupQEDtxContext inputs (part 1): Gp_role = %s, Gp_is_writer = %s, "
			 "txnOptions = 0x%x, needTwoPhase = %s, explicitBegin = %s, isoLevel = %s, readOnly = %s, haveDistributedSnapshot = %s.",
			 role_to_string(Gp_role), (Gp_is_writer ? "true" : "false"), txnOptions,
			 (needTwoPhase ? "true" : "false"), (explicitBegin ? "true" : "false"),
			 IsoLevelAsUpperString(mppTxOptions_IsoLevel(txnOptions)), (isMppTxOptions_ReadOnly(txnOptions) ? "true" : "false"),
			 (haveDistributedSnapshot ? "true" : "false"));
A
Ashwin Agrawal 已提交
2842
		elog(DTM_DEBUG5,
2843 2844
			 "setupQEDtxContext inputs (part 2): distributedXid = %u, isSharedLocalSnapshotSlotPresent = %s.",
			 dtxContextInfo->distributedXid,
A
Ashwin Agrawal 已提交
2845
			 (isSharedLocalSnapshotSlotPresent ? "true" : "false"));
2846 2847 2848 2849 2850 2851 2852

		if (haveDistributedSnapshot)
		{
			elog(DTM_DEBUG5,
				 "setupQEDtxContext inputs (part 2a): distributedXid = %u, "
				 "distributedSnapshotData (xmin = %u, xmax = %u, xcnt = %u), distributedCommandId = %d",
				 dtxContextInfo->distributedXid,
2853 2854
				 distributedSnapshot->xmin, distributedSnapshot->xmax,
				 distributedSnapshot->count,
2855 2856 2857 2858
				 dtxContextInfo->curcid);
		}
		if (isSharedLocalSnapshotSlotPresent)
		{
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
			if (DTM_DEBUG5 >= log_min_messages)
			{
				LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_SHARED);
				elog(DTM_DEBUG5,
					 "setupQEDtxContext inputs (part 2b):  shared local snapshot xid = %u "
					 "(xmin: %u xmax: %u xcnt: %u) curcid: %d, QDxid = %u/%u, QDcid = %u",
					 SharedLocalSnapshotSlot->xid,
					 SharedLocalSnapshotSlot->snapshot.xmin,
					 SharedLocalSnapshotSlot->snapshot.xmax,
					 SharedLocalSnapshotSlot->snapshot.xcnt,
					 SharedLocalSnapshotSlot->snapshot.curcid,
					 SharedLocalSnapshotSlot->QDxid,
					 SharedLocalSnapshotSlot->segmateSync,
					 SharedLocalSnapshotSlot->QDcid);
				LWLockRelease(SharedLocalSnapshotSlot->slotLock);
			}
2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888
		}
	}

	switch (Gp_role)
	{
		case GP_ROLE_EXECUTE:
			if (Gp_segment == -1 && !Gp_is_writer)
			{
				isEntryDbSingleton = true;
			}
			else
			{
				/*
				 * NOTE: this is a bit hackish. It appears as though
A
Ashwin Agrawal 已提交
2889 2890
				 * StartTransaction() gets called during connection setup
				 * before we even have time to setup our shared snapshot slot.
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915
				 */
				if (SharedLocalSnapshotSlot == NULL)
				{
					if (explicitBegin || haveDistributedSnapshot)
					{
						elog(ERROR, "setupQEDtxContext not expecting distributed begin or snapshot when no Snapshot slot exists");
					}
				}
				else
				{
					if (Gp_is_writer)
					{
						isWriterQE = true;
					}
					else
					{
						isReaderQE = true;
					}
				}
			}
			break;

		default:
			Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);
			elog(DTM_DEBUG5,
A
Ashwin Agrawal 已提交
2916
				 "setupQEDtxContext leaving context = 'Local Only' for Gp_role = %s", role_to_string(Gp_role));
2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
			return;
	}

	elog(DTM_DEBUG5,
		 "setupQEDtxContext intermediate result: isEntryDbSingleton = %s, isWriterQE = %s, isReaderQE = %s.",
		 (isEntryDbSingleton ? "true" : "false"),
		 (isWriterQE ? "true" : "false"), (isReaderQE ? "true" : "false"));

	/*
	 * Copy to our QE global variable.
	 */
	DtxContextInfo_Copy(&QEDtxContextInfo, dtxContextInfo);

	switch (DistributedTransactionContext)
	{
		case DTX_CONTEXT_LOCAL_ONLY:
			if (isEntryDbSingleton && haveDistributedSnapshot)
			{
				/*
				 * Later, in GetSnapshotData, we will adopt the QD's
				 * transaction and snapshot information.
				 */

A
Ashwin Agrawal 已提交
2940
				setDistributedTransactionContext(DTX_CONTEXT_QE_ENTRY_DB_SINGLETON);
2941 2942 2943 2944 2945 2946 2947 2948
			}
			else if (isReaderQE && haveDistributedSnapshot)
			{
				/*
				 * Later, in GetSnapshotData, we will adopt the QE Writer's
				 * transaction and snapshot information.
				 */

A
Ashwin Agrawal 已提交
2949
				setDistributedTransactionContext(DTX_CONTEXT_QE_READER);
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
			}
			else if (isWriterQE && (explicitBegin || needTwoPhase))
			{
				if (!haveDistributedSnapshot)
				{
					elog(DTM_DEBUG5,
						 "setupQEDtxContext Segment Writer is involved in a distributed transaction without a distributed snapshot...");
				}

				if (IsTransactionOrTransactionBlock())
				{
					elog(ERROR, "Starting an explicit distributed transaction in segment -- cannot already be in a transaction");
				}

				if (explicitBegin)
				{
					/*
A
Ashwin Agrawal 已提交
2967 2968
					 * We set the DistributedTransactionContext BEFORE we
					 * create the transactions to influence the behavior of
2969 2970
					 * StartTransaction.
					 */
A
Ashwin Agrawal 已提交
2971
					setDistributedTransactionContext(DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER);
2972 2973 2974 2975 2976 2977

					doQEDistributedExplicitBegin(txnOptions);
				}
				else
				{
					Assert(needTwoPhase);
A
Ashwin Agrawal 已提交
2978
					setDistributedTransactionContext(DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER);
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990
				}
			}
			else if (haveDistributedSnapshot)
			{
				if (IsTransactionOrTransactionBlock())
				{
					elog(ERROR,
						 "Going to start a local implicit transaction in segment using a distribute "
						 "snapshot -- cannot already be in a transaction");
				}

				/*
A
Ashwin Agrawal 已提交
2991 2992 2993
				 * Before executing the query, postgres.c make a standard call
				 * to StartTransactionCommand which will begin a local
				 * transaction with StartTransaction.  This is fine.
2994
				 *
A
Ashwin Agrawal 已提交
2995 2996 2997
				 * However, when the snapshot is created later, the state
				 * below will tell GetSnapshotData to make the local snapshot
				 * from the distributed snapshot.
2998
				 */
A
Ashwin Agrawal 已提交
2999
				setDistributedTransactionContext(DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT);
3000 3001 3002
			}
			else
			{
A
Ashwin Agrawal 已提交
3003
				Assert(!haveDistributedSnapshot);
3004 3005

				/*
A
Ashwin Agrawal 已提交
3006 3007
				 * A local implicit transaction without reference to a
				 * distributed snapshot.  Stay in NONE state.
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
				 */
				Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);
			}
			break;

		case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
/*
		elog(NOTICE, "We should have left this transition state '%s' at the end of the previous command...",
			 DtxContextToString(DistributedTransactionContext));
*/
A
Ashwin Agrawal 已提交
3018
			Assert(IsTransactionOrTransactionBlock());
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031

			if (explicitBegin)
			{
				elog(ERROR, "Cannot have an explicit BEGIN statement...");
			}
			break;

		case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
			elog(ERROR, "We should have left this transition state '%s' at the end of the previous command",
				 DtxContextToString(DistributedTransactionContext));
			break;

		case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
A
Ashwin Agrawal 已提交
3032
			Assert(IsTransactionOrTransactionBlock());
3033 3034 3035 3036
			break;

		case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
		case DTX_CONTEXT_QE_READER:
A
Ashwin Agrawal 已提交
3037

3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061
			/*
			 * We are playing games with the xact.c code, so we shouldn't test
			 * with the IsTransactionOrTransactionBlock() routine.
			 */
			break;

		case DTX_CONTEXT_QE_PREPARED:
		case DTX_CONTEXT_QE_FINISH_PREPARED:
			elog(ERROR, "We should not be trying to execute a query in state '%s'",
				 DtxContextToString(DistributedTransactionContext));
			break;

		default:
			elog(PANIC, "Unexpected segment distribute transaction context value: %d",
				 (int) DistributedTransactionContext);
			break;
	}

	elog(DTM_DEBUG5, "setupQEDtxContext final result: DistributedTransactionContext = '%s'.",
		 DtxContextToString(DistributedTransactionContext));

	if (haveDistributedSnapshot)
	{
		elog((Debug_print_snapshot_dtm ? LOG : DEBUG5), "[Distributed Snapshot #%u] *Set QE* currcid = %d (gxid = %u, '%s')",
3062
			 dtxContextInfo->distributedSnapshot.distribSnapshotId,
3063 3064 3065 3066 3067 3068 3069 3070
			 dtxContextInfo->curcid,
			 getDistributedTransactionId(),
			 DtxContextToString(DistributedTransactionContext));
	}

}

void
A
Ashwin Agrawal 已提交
3071
finishDistributedTransactionContext(char *debugCaller, bool aborted)
3072 3073 3074 3075
{
	DistributedTransactionId gxid;

	/*
A
Ashwin Agrawal 已提交
3076 3077
	 * We let the 2 retry states go up to PostgresMain.c, otherwise everything
	 * MUST be complete.
3078 3079
	 */
	if (currentGxact != NULL &&
A
Ashwin Agrawal 已提交
3080 3081
		(currentGxact->state != DTX_STATE_RETRY_COMMIT_PREPARED &&
		 currentGxact->state != DTX_STATE_RETRY_ABORT_PREPARED))
3082 3083
	{
		elog(FATAL, "Expected currentGxact to be NULL at this point.  Found gid =%s, gxid = %u (state = %s, caller = %s)",
A
Ashwin Agrawal 已提交
3084
			 currentGxact->gid, currentGxact->gxid, DtxStateToString(currentGxact->state), debugCaller);
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094
	}

	gxid = getDistributedTransactionId();
	elog(DTM_DEBUG5,
		 "finishDistributedTransactionContext called to change DistributedTransactionContext from %s to %s (caller = %s, gxid = %u)",
		 DtxContextToString(DistributedTransactionContext),
		 DtxContextToString(DTX_CONTEXT_LOCAL_ONLY),
		 debugCaller,
		 gxid);

A
Ashwin Agrawal 已提交
3095
	setDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138

	DtxContextInfo_Reset(&QEDtxContextInfo);

}

static void
rememberDtxExplicitBegin(void)
{
	if (currentGxact == NULL)
	{
		return;
	}

	if (!currentGxact->explicitBeginRemembered)
	{
		elog(DTM_DEBUG5, "rememberDtxExplicitBegin explicit BEGIN for gid = %s",
			 currentGxact->gid);
		currentGxact->explicitBeginRemembered = true;
	}
	else
	{
		elog(DTM_DEBUG5, "rememberDtxExplicitBegin already an explicit BEGIN for gid = %s",
			 currentGxact->gid);
	}
}

/*
 * This is mostly here because
 * cdbcopy doesn't use cdbdisp's services.
 */
void
sendDtxExplicitBegin(void)
{
	char		cmdbuf[100];

	if (currentGxact == NULL)
	{
		return;
	}

	rememberDtxExplicitBegin();

	dtmPreCommand("sendDtxExplicitBegin", "(none)", NULL,
A
Ashwin Agrawal 已提交
3139
				   /* is two-phase */ true, /* withSnapshot */ true, /* inCursor */ false);
3140 3141

	/*
A
Ashwin Agrawal 已提交
3142 3143
	 * Be explicit about both the isolation level and the access mode since in
	 * MPP our QEs are in a another process.
3144 3145 3146 3147 3148 3149
	 */
	sprintf(cmdbuf, "BEGIN ISOLATION LEVEL %s, READ %s",
			IsoLevelAsUpperString(XactIsoLevel),
			(XactReadOnly ? "ONLY" : "WRITE"));

	/*
A
Ashwin Agrawal 已提交
3150 3151
	 * dispatch a DTX command, in the event of an error, this call will either
	 * exit via elog()/ereport() or return false
3152
	 */
3153
	if (!dispatchDtxCommand(cmdbuf))
3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168
	{
		ereport(ERROR, (errmsg("Global transaction BEGIN failed for gid = \"%s\" due to error",
							   currentGxact->gid)));
	}
}

/**
 * On the QD, run the Prepare operation.
 */
static void
performDtxProtocolPrepare(const char *gid)
{
	StartTransactionCommand();

	elog(DTM_DEBUG5, "performDtxProtocolCommand going to call PrepareTransactionBlock for distributed transaction (id = '%s')", gid);
A
Ashwin Agrawal 已提交
3169
	if (!PrepareTransactionBlock((char *) gid))
3170 3171 3172 3173 3174 3175
	{
		elog(ERROR, "Prepare of distributed transaction %s failed", gid);
		return;
	}

	/*
A
Ashwin Agrawal 已提交
3176 3177
	 * Calling CommitTransactionCommand will cause the actual COMMIT/PREPARE
	 * work to be performed.
3178 3179 3180 3181 3182
	 */
	CommitTransactionCommand();

	elog(DTM_DEBUG5, "Prepare of distributed transaction succeeded (id = '%s')", gid);

A
Ashwin Agrawal 已提交
3183
	setDistributedTransactionContext(DTX_CONTEXT_QE_PREPARED);
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
}

/**
 * On the QD, run the Commit Prepared operation.
 */
static void
performDtxProtocolCommitPrepared(const char *gid, bool raiseErrorIfNotFound)
{
	elog(DTM_DEBUG5,
		 "performDtxProtocolCommitPrepared going to call FinishPreparedTransaction for distributed transaction %s", gid);

	StartTransactionCommand();

	/*
	 * Since this call may fail, lets setup a handler.
	 */
	PG_TRY();
	{
A
Ashwin Agrawal 已提交
3202
		FinishPreparedTransaction((char *) gid, /* isCommit */ true, raiseErrorIfNotFound);
3203 3204 3205 3206 3207 3208 3209 3210 3211
	}
	PG_CATCH();
	{
		finishDistributedTransactionContext("performDtxProtocolCommitPrepared -- Commit Prepared (error case)", false);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/*
A
Ashwin Agrawal 已提交
3212 3213
	 * Calling CommitTransactionCommand will cause the actual COMMIT/PREPARE
	 * work to be performed.
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
	 */
	CommitTransactionCommand();

	finishDistributedTransactionContext("performDtxProtocolCommitPrepared -- Commit Prepared", false);
}

/**
 * On the QD, run the Abort Prepared operation.
 */
static void
performDtxProtocolAbortPrepared(const char *gid, bool raiseErrorIfNotFound)
{
	elog(DTM_DEBUG5, "performDtxProtocolAbortPrepared going to call FinishPreparedTransaction for distributed transaction %s", gid);

	StartTransactionCommand();

	/*
	 * Since this call may fail, lets setup a handler.
	 */
	PG_TRY();
	{
A
Ashwin Agrawal 已提交
3235
		FinishPreparedTransaction((char *) gid, /* isCommit */ false, raiseErrorIfNotFound);
3236 3237 3238 3239 3240 3241 3242 3243 3244
	}
	PG_CATCH();
	{
		finishDistributedTransactionContext("performDtxProtocolAbortPrepared -- Commit Prepared (error case)", true);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/*
A
Ashwin Agrawal 已提交
3245 3246
	 * Calling CommitTransactionCommand will cause the actual COMMIT/PREPARE
	 * work to be performed.
3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
	 */
	CommitTransactionCommand();

	finishDistributedTransactionContext("performDtxProtocolAbortPrepared -- Commit Prepared", true);
}

/**
 * On the QE, handle a DtxProtocolCommand
 */
void
performDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand,
A
Ashwin Agrawal 已提交
3258 3259
						  int flags __attribute__((unused)),
						  const char *loggingStr __attribute__((unused)), const char *gid,
3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
						  DistributedTransactionId gxid __attribute__((unused)),
						  DtxContextInfo *contextInfo)
{
	elog(DTM_DEBUG5,
		 "performDtxProtocolCommand called with DTX protocol = %s, segment distribute transaction context: '%s'",
		 DtxProtocolCommandToString(dtxProtocolCommand), DtxContextToString(DistributedTransactionContext));

	switch (dtxProtocolCommand)
	{
		case DTX_PROTOCOL_COMMAND_STAY_AT_OR_BECOME_IMPLIED_WRITER:
A
Ashwin Agrawal 已提交
3270
			switch (DistributedTransactionContext)
3271
			{
A
Ashwin Agrawal 已提交
3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291
				case DTX_CONTEXT_LOCAL_ONLY:
					/** convert to implicit_writer! */
					setupQEDtxContext(contextInfo);
					StartTransactionCommand();
					break;
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
					/** already the state we like */
					break;
				default:
					if (isQEContext() || isQDContext())
					{
						elog(FATAL, "Unexpected segment distributed transaction context: '%s'",
							 DtxContextToString(DistributedTransactionContext));
					}
					else
					{
						elog(PANIC, "Unexpected segment distributed transaction context value: %d",
							 (int) DistributedTransactionContext);
					}
					break;
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
			}
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_NO_PREPARED:
			elog(DTM_DEBUG5,
				 "performDtxProtocolCommand going to call AbortOutOfAnyTransaction for distributed transaction %s", gid);
			AbortOutOfAnyTransaction();
			break;

		case DTX_PROTOCOL_COMMAND_PREPARE:
A
Ashwin Agrawal 已提交
3302

3303
			/*
A
Ashwin Agrawal 已提交
3304 3305
			 * The QD has directed us to read-only commit or prepare an
			 * implicit or explicit distributed transaction.
3306 3307 3308 3309
			 */
			switch (DistributedTransactionContext)
			{
				case DTX_CONTEXT_LOCAL_ONLY:
A
Ashwin Agrawal 已提交
3310

3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
					/*
					 * Spontaneously aborted while we were back at the QD?
					 */
					elog(ERROR, "Distributed transaction %s not found", gid);
					break;

				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
					performDtxProtocolPrepare(gid);
					break;

				case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
				case DTX_CONTEXT_QD_RETRY_PHASE_2:
				case DTX_CONTEXT_QE_PREPARED:
				case DTX_CONTEXT_QE_FINISH_PREPARED:
				case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
				case DTX_CONTEXT_QE_READER:
					elog(FATAL, "Unexpected segment distribute transaction context: '%s'",
						 DtxContextToString(DistributedTransactionContext));

				default:
					elog(PANIC, "Unexpected segment distribute transaction context value: %d",
						 (int) DistributedTransactionContext);
					break;
			}
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_SOME_PREPARED:
			switch (DistributedTransactionContext)
			{
				case DTX_CONTEXT_LOCAL_ONLY:
A
Ashwin Agrawal 已提交
3342

3343 3344
					/*
					 * Spontaneously aborted while we were back at the QD?
3345 3346 3347 3348
					 *
					 * It's normal if the transaction doesn't exist. The QD will
					 * call abort on us, even if we didn't finish the prepare yet,
					 * if some other QE reported failure already.
3349
					 */
3350 3351
					elog(DTM_DEBUG3, "Distributed transaction %s not found during abort", gid);
					AbortOutOfAnyTransaction();
3352 3353 3354 3355 3356 3357 3358 3359
					break;

				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
					AbortOutOfAnyTransaction();
					break;

				case DTX_CONTEXT_QE_PREPARED:
A
Ashwin Agrawal 已提交
3360
					setDistributedTransactionContext(DTX_CONTEXT_QE_FINISH_PREPARED);
3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378
					performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ true);
					break;

				case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
				case DTX_CONTEXT_QD_RETRY_PHASE_2:
				case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
				case DTX_CONTEXT_QE_READER:
					elog(PANIC, "Unexpected segment distribute transaction context: '%s'",
						 DtxContextToString(DistributedTransactionContext));

				default:
					elog(PANIC, "Unexpected segment distribute transaction context value: %d",
						 (int) DistributedTransactionContext);
					break;
			}
			break;

		case DTX_PROTOCOL_COMMAND_COMMIT_PREPARED:
A
Ashwin Agrawal 已提交
3379 3380
			requireDistributedTransactionContext(DTX_CONTEXT_QE_PREPARED);
			setDistributedTransactionContext(DTX_CONTEXT_QE_FINISH_PREPARED);
3381 3382 3383 3384
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ true);
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_PREPARED:
A
Ashwin Agrawal 已提交
3385 3386
			requireDistributedTransactionContext(DTX_CONTEXT_QE_PREPARED);
			setDistributedTransactionContext(DTX_CONTEXT_QE_FINISH_PREPARED);
3387 3388 3389 3390
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ true);
			break;

		case DTX_PROTOCOL_COMMAND_RETRY_COMMIT_PREPARED:
A
Ashwin Agrawal 已提交
3391
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3392 3393 3394 3395
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RETRY_ABORT_PREPARED:
A
Ashwin Agrawal 已提交
3396
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3397 3398 3399 3400
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RECOVERY_COMMIT_PREPARED:
A
Ashwin Agrawal 已提交
3401
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3402 3403 3404 3405
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RECOVERY_ABORT_PREPARED:
A
Ashwin Agrawal 已提交
3406
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3407 3408 3409 3410
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_BEGIN_INTERNAL:
A
Ashwin Agrawal 已提交
3411
			switch (DistributedTransactionContext)
3412 3413
			{
				case DTX_CONTEXT_LOCAL_ONLY:
A
Ashwin Agrawal 已提交
3414

3415
					/*
A
Ashwin Agrawal 已提交
3416 3417
					 * QE is not aware of DTX yet. A typical case is SELECT
					 * foo(), where foo() opens internal subtransaction
3418 3419 3420 3421 3422
					 */
					setupQEDtxContext(contextInfo);
					StartTransactionCommand();
					break;
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
A
Ashwin Agrawal 已提交
3423 3424 3425 3426 3427

					/*
					 * We already marked this QE to be writer, and transaction
					 * is open.
					 */
3428 3429 3430 3431 3432
				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_READER:
					break;
				default:
					/* Lets flag this situation out, with explicit crash */
A
Ashwin Agrawal 已提交
3433 3434 3435
					Assert(false);
					elog(DTM_DEBUG5,
						 " SUBTRANSACTION_BEGIN_INTERNAL distributed transaction context invalid: %d",
3436 3437 3438 3439 3440
						 (int) DistributedTransactionContext);
					break;
			}

			BeginInternalSubTransaction(NULL);
A
Ashwin Agrawal 已提交
3441
			Assert(contextInfo->nestingLevel + 1 == GetCurrentTransactionNestLevel());
3442 3443 3444 3445 3446 3447
			break;

		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_RELEASE_INTERNAL:
			Assert(contextInfo->nestingLevel == GetCurrentTransactionNestLevel());
			ReleaseCurrentSubTransaction();
			break;
A
Ashwin Agrawal 已提交
3448

3449
		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_ROLLBACK_INTERNAL:
A
Ashwin Agrawal 已提交
3450 3451 3452 3453

			/*
			 * Rollback performs work on master and then dispatches, hence has
			 * nestingLevel its expecting post operation
3454 3455 3456
			 */
			if ((contextInfo->nestingLevel + 1) > GetCurrentTransactionNestLevel())
			{
A
Ashwin Agrawal 已提交
3457 3458 3459
				ereport(ERROR,
						(errmsg("transaction %s at level %d already processed (current level %d)",
								gid, contextInfo->nestingLevel, GetCurrentTransactionNestLevel())));
3460
			}
A
Ashwin Agrawal 已提交
3461

3462
			unsigned int i = GetCurrentTransactionNestLevel() - contextInfo->nestingLevel;
A
Ashwin Agrawal 已提交
3463

3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
			while (i > 0)
			{
				RollbackAndReleaseCurrentSubTransaction();
				i--;
			}

			Assert(contextInfo->nestingLevel == GetCurrentTransactionNestLevel());
			break;

		default:
			elog(ERROR, "Unrecognized dtx protocol command: %d",
				 (int) dtxProtocolCommand);
			break;
	}
	elog(DTM_DEBUG5, "performDtxProtocolCommand successful return for distributed transaction %s", gid);
}