faultinjector.c 28.9 KB
Newer Older
1
/*-------------------------------------------------------------------------
2
 *
3
 * faultinjector.c
J
Jimmy Yih 已提交
4
 *	  GP Fault Injectors are used for Greenplum internal testing only.
5
 * 
J
Jimmy Yih 已提交
6 7 8 9 10
 * Fault injectors are used for fine control during testing. They allow a
 * developer to create deterministic tests for scenarios that are hard to
 * reproduce. This is done by programming actions at certain key areas to
 * suspend, skip, or even panic the process. Fault injectors are set in shared
 * memory so they are accessible to all segment processes.
11 12 13 14 15 16 17
 *
 * Portions Copyright (c) 2009-2010 Greenplum Inc
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
 *
 *
 * IDENTIFICATION
 *	    src/backend/utils/misc/faultinjector.c
18
 *
19
 *-------------------------------------------------------------------------
20 21 22 23 24
 */

#include "postgres.h"

#include <signal.h>
25 26 27
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
28 29
#include "access/xact.h"
#include "cdb/cdbutil.h"
30 31
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
32
#include "postmaster/autovacuum.h"
33
#include "postmaster/bgwriter.h"
34 35 36 37 38 39
#include "storage/spin.h"
#include "storage/shmem.h"
#include "utils/faultinjector.h"
#include "utils/hsearch.h"
#include "miscadmin.h"

40 41 42 43 44
/*
 * internal include
 */
#include "faultinjector_warnings.h"

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#ifdef FAULT_INJECTOR

/*
 * gettext() can't be used in a static initializer... This breaks nls builds.
 * So, to work around this issue, I've made _() be a no-op.
 */
#undef _
#define _(x) x

typedef struct FaultInjectorShmem_s {
	slock_t		lock;
	
	int			faultInjectorSlots;	
		/* number of fault injection set */
	
	HTAB		*hash;
} FaultInjectorShmem_s;

63 64
bool am_faulthandler = false;

65 66 67 68 69 70
static	FaultInjectorShmem_s *faultInjectorShmem = NULL;

static void FiLockAcquire(void);
static void FiLockRelease(void);

static FaultInjectorEntry_s* FaultInjector_LookupHashEntry(
71
								const char* faultName);
72 73

static FaultInjectorEntry_s* FaultInjector_InsertHashEntry(
74
								const char* faultName,
75 76 77 78 79
								bool	*exists);

static int FaultInjector_NewHashEntry(
								FaultInjectorEntry_s	*entry);

80
static int FaultInjector_MarkEntryAsResume(
81 82 83
								FaultInjectorEntry_s	*entry);

static bool FaultInjector_RemoveHashEntry(
84
								const char* faultName);
85

86 87
static int FaultInjector_SetFaultInjection(FaultInjectorEntry_s *entry);

88 89 90 91
static FaultInjectorType_e FaultInjectorTypeStringToEnum(const char *faultType);

static DDLStatement_e FaultInjectorDDLStringToEnum(const char *ddlString);

92
/* Arrays to map between enum values and strings */
93 94
const char*
FaultInjectorTypeEnumToString[] = {
95 96 97
#define FI_TYPE(id, str) str,
#include "utils/faultinjector_lists.h"
#undef FI_TYPE
98 99 100 101
};

const char*
FaultInjectorDDLEnumToString[] = {
102 103 104
#define FI_DDL_STATEMENT(id, str) str,
#include "utils/faultinjector_lists.h"
#undef FI_DDL_STATEMENT
105 106 107 108
};

const char*
FaultInjectorStateEnumToString[] = {
109 110 111
#define FI_STATE(id, str) str,
#include "utils/faultinjector_lists.h"
#undef FI_STATE
112 113
};

114 115
static FaultInjectorType_e
FaultInjectorTypeStringToEnum(const char* faultTypeString)
116 117 118 119
{
	FaultInjectorType_e	faultTypeEnum = FaultInjectorTypeMax;
	int	ii;
	
120 121 122 123
	for (ii=FaultInjectorTypeNotSpecified+1; ii < FaultInjectorTypeMax; ii++)
	{
		if (strcmp(FaultInjectorTypeEnumToString[ii], faultTypeString) == 0)
		{
124 125 126 127 128 129 130
			faultTypeEnum = ii;
			break;
		}
	}
	return faultTypeEnum;
}

131 132
static DDLStatement_e
FaultInjectorDDLStringToEnum(const char* ddlString)
133 134 135 136
{
	DDLStatement_e	ddlEnum = DDLMax;
	int	ii;
	
137 138 139 140
	for (ii=DDLNotSpecified; ii < DDLMax; ii++)
	{
		if (strcmp(FaultInjectorDDLEnumToString[ii], ddlString) == 0)
		{
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
			ddlEnum = ii;
			break;
		}
	}
	return ddlEnum;
}

static void
FiLockAcquire(void)
{	
	SpinLockAcquire(&faultInjectorShmem->lock);
}

static void
FiLockRelease(void)
{	
	SpinLockRelease(&faultInjectorShmem->lock);
}

160 161 162 163 164 165 166

void InjectFaultInit(void)
{
	warnings_init();
}


167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
/****************************************************************
 * FAULT INJECTOR routines
 ****************************************************************/
Size
FaultInjector_ShmemSize(void)
{
	Size	size;
	
	size = hash_estimate_size(
							  (Size)FAULTINJECTOR_MAX_SLOTS, 
							  sizeof(FaultInjectorEntry_s));
	
	size = add_size(size, sizeof(FaultInjectorShmem_s));
	
	return size;	
}

/*
 * Hash table contains fault injection that are set on the system waiting to be injected.
 * FaultInjector identifier is the key in the hash table.
 * Hash table in shared memory is initialized only on primary and mirror segment. 
 * It is not initialized on master host.
 */
void
FaultInjector_ShmemInit(void)
{
	HASHCTL	hash_ctl;
	bool	foundPtr;
	
	faultInjectorShmem = (FaultInjectorShmem_s *) ShmemInitStruct("fault injector",
																  sizeof(FaultInjectorShmem_s),
																  &foundPtr);
	
	if (faultInjectorShmem == NULL) {
		ereport(ERROR,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 (errmsg("not enough shared memory for fault injector"))));
	}	
	
	if (! foundPtr) 
	{
		MemSet(faultInjectorShmem, 0, sizeof(FaultInjectorShmem_s));
	}	
	
	SpinLockInit(&faultInjectorShmem->lock);
	
	faultInjectorShmem->faultInjectorSlots = 0;
	
	MemSet(&hash_ctl, 0, sizeof(hash_ctl));
216
	hash_ctl.keysize = FAULT_NAME_MAX_LENGTH;
217
	hash_ctl.entrysize = sizeof(FaultInjectorEntry_s);
218
	hash_ctl.hash = string_hash;
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	
	faultInjectorShmem->hash = ShmemInitHash("fault injector hash",
								   FAULTINJECTOR_MAX_SLOTS,
								   FAULTINJECTOR_MAX_SLOTS,
								   &hash_ctl,
								   HASH_ELEM | HASH_FUNCTION);
	
	if (faultInjectorShmem->hash == NULL) {
		ereport(ERROR, 
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 (errmsg("not enough shared memory for fault injector"))));
	}
	
	return;						  
}

FaultInjectorType_e
FaultInjector_InjectFaultIfSet(
237 238 239 240 241 242
							   const char*				 faultName,
							   DDLStatement_e			 ddlStatement,
							   const char*				 databaseName,
							   const char*				 tableName)
{

243 244 245 246 247 248
	FaultInjectorEntry_s   *entryShared, localEntry,
						   *entryLocal = &localEntry;
	char					databaseNameLocal[NAMEDATALEN];
	char					tableNameLocal[NAMEDATALEN];
	int						ii = 0;
	int cnt = 3600;
249
	FaultInjectorType_e retvalue = FaultInjectorTypeNotSpecified;
250

251 252 253 254 255 256 257 258 259
	if (strlen(faultName) >= sizeof(localEntry.faultName))
		elog(ERROR, "fault name too long: '%s'", faultName);
	if (strcmp(faultName, FaultInjectorNameAll) == 0)
		elog(ERROR, "invalid fault name '%s'", faultName);
	if (strlen(databaseName) >= NAMEDATALEN)
		elog(ERROR, "database name too long:'%s'", databaseName);
	if (strlen(tableName) >= NAMEDATALEN)
		elog(ERROR, "table name too long: '%s'", tableName);

260 261 262 263 264 265 266
	/*
	 * Auto-vacuum worker and launcher process, may run at unpredictable times
	 * while running tests. So, skip setting any faults for auto-vacuum
	 * launcher or worker. If anytime in future need to test these processes
	 * using fault injector framework, this restriction needs to be lifted and
	 * some other mechanism needs to be placed to avoid flaky failures.
	 */
267
	if (IsAutoVacuumLauncherProcess() ||
268 269 270
		(IsAutoVacuumWorkerProcess() &&
		 !(0 == strcmp("vacuum_update_dat_frozen_xid", faultName) ||
			 0 == strcmp("auto_vac_worker_before_do_autovacuum", faultName))))
271 272
		return FaultInjectorTypeNotSpecified;

273 274 275 276 277 278 279 280 281 282 283 284 285
	/*
	 * Return immediately if no fault has been injected ever.  It is
	 * important to not touch the spinlock, especially if this is the
	 * postmaster process.  If one of the backend processes dies while
	 * holding the spin lock, and postmaster comes here before resetting
	 * the shared memory, it waits without holder process and eventually
	 * goes into PANIC.  Also this saves a few cycles to acquire the spin
	 * lock and look into the shared hash table.
	 *
	 * Although this is a race condition without lock, a false negative is
	 * ok given this framework is purely for dev/testing.
	 */
	if (faultInjectorShmem->faultInjectorSlots == 0)
286
		return FaultInjectorTypeNotSpecified;
287

288 289
	snprintf(databaseNameLocal, sizeof(databaseNameLocal), "%s", databaseName);
	snprintf(tableNameLocal, sizeof(tableNameLocal), "%s", tableName);
290 291 292

	FiLockAcquire();

293
	entryShared = FaultInjector_LookupHashEntry(faultName);
294

295 296 297 298 299
	do
	{
		if (entryShared == NULL)
			/* fault injection is not set */
			break;
300

301 302 303
		if (entryShared->ddlStatement != ddlStatement)
			/* fault injection is not set for the specified DDL */
			break;
304

305 306 307
		if (strcmp(entryShared->databaseName, databaseNameLocal) != 0)
			/* fault injection is not set for the specified database name */
			break;
308
	
309 310 311
		if (strcmp(entryShared->tableName, tableNameLocal) != 0)
			/* fault injection is not set for the specified table name */
			break;
312

313 314 315 316 317 318
		if (entryShared->faultInjectorState == FaultInjectorStateCompleted ||
			entryShared->faultInjectorState == FaultInjectorStateFailed) {
			/* fault injection was already executed */
			break;
		}

319 320 321
		entryShared->numTimesTriggered++;

		if (entryShared->numTimesTriggered < entryShared->startOccurrence)
322
		{
323
			break;
324 325
		}

326
		/* Update the injection fault entry in hash table */
327
		entryShared->faultInjectorState = FaultInjectorStateTriggered;
328 329 330 331 332 333

		/* Mark fault injector to completed */
		if (entryShared->endOccurrence != INFINITE_END_OCCURRENCE &&
			entryShared->numTimesTriggered >= entryShared->endOccurrence)
			entryShared->faultInjectorState = FaultInjectorStateCompleted;

334 335 336 337 338 339 340 341
		memcpy(entryLocal, entryShared, sizeof(FaultInjectorEntry_s));
		retvalue = entryLocal->faultInjectorType;
	} while (0);

	FiLockRelease();

	if (retvalue == FaultInjectorTypeNotSpecified)
		return FaultInjectorTypeNotSpecified;
342 343 344 345 346 347

	/* Inject fault */
	switch (entryLocal->faultInjectorType) {
		case FaultInjectorTypeNotSpecified:
			
			break;
348

349
		case FaultInjectorTypeSleep:
350 351 352
			ereport(LOG,
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
353
							entryLocal->faultName,
354 355
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));	
			
356
			pg_usleep(entryLocal->extraArg * 1000000L);
357
			break;
358

359 360
		case FaultInjectorTypeFatal:
			ereport(FATAL, 
361 362
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
363
							entryLocal->faultName,
364
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));
365
			break;
366

367
		case FaultInjectorTypePanic:
368 369 370 371 372
			/*
			 * Avoid core file generation for this PANIC. It helps to avoid
			 * filling up disks during tests and also saves time.
			 */
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
373
			;struct rlimit lim;
374 375 376 377 378 379 380
			getrlimit(RLIMIT_CORE, &lim);
			lim.rlim_cur = 0;
			if (setrlimit(RLIMIT_CORE, &lim) != 0)
				elog(NOTICE,
					 "setrlimit failed for RLIMIT_CORE soft limit to zero. errno: %d (%m).",
					 errno);
#endif
381
			ereport(PANIC, 
382 383
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
384
							entryLocal->faultName,
385 386 387
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));	

			break;
388

389 390
		case FaultInjectorTypeError:
			ereport(ERROR, 
391 392
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
393
							entryLocal->faultName,
394 395
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));	
			break;
396

397 398
		case FaultInjectorTypeInfiniteLoop:
			ereport(LOG, 
399 400
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
401
							entryLocal->faultName,
402 403
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));

404 405 406
			for (ii=0;
				 ii < cnt && FaultInjector_LookupHashEntry(entryLocal->faultName);
				 ii++)
407 408
			{
				pg_usleep(1000000L); // sleep for 1 sec (1 sec * 3600 = 1 hour)
409
				CHECK_FOR_INTERRUPTS();
410 411 412 413 414 415 416 417
			}
			break;
			
		case FaultInjectorTypeSuspend:
		{
			FaultInjectorEntry_s	*entry;
			
			ereport(LOG, 
418 419
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
420
							entryLocal->faultName,
421 422
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));	
			
423
			while ((entry = FaultInjector_LookupHashEntry(entryLocal->faultName)) != NULL &&
424 425 426 427 428 429 430 431
				   entry->faultInjectorType != FaultInjectorTypeResume)
			{
				pg_usleep(1000000L);  // 1 sec
			}

			if (entry != NULL)
			{
				ereport(LOG, 
432 433
						(errcode(ERRCODE_FAULT_INJECT),
						 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
434
							entryLocal->faultName,
435 436 437 438 439
							FaultInjectorTypeEnumToString[entry->faultInjectorType])));	
			}
			else
			{
				ereport(LOG, 
440 441
						(errcode(ERRCODE_FAULT_INJECT),
						 errmsg("fault 'NULL', fault name:'%s'  ",
442
								entryLocal->faultName)));
443 444 445 446 447 448 449 450 451 452 453

				/*
				 * Since the entry is gone already, we should NOT update
				 * the entry below.  (There could be other places in this
				 * function that are under the same situation, but I'm too
				 * tired to look for them...)
				 */
				return entryLocal->faultInjectorType;
			}
			break;
		}
454

455 456
		case FaultInjectorTypeSkip:
			ereport(LOG, 
457 458
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
459
							entryLocal->faultName,
460 461 462 463 464 465 466 467
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));							
			break;

		case FaultInjectorTypeResume:
			break;
			
		case FaultInjectorTypeSegv:
		{
R
Richard Guo 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481
			/*
			 * Avoid core file generation for this PANIC. It helps to avoid
			 * filling up disks during tests and also saves time.
			 */
#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_CORE)
			struct rlimit lim;
			getrlimit(RLIMIT_CORE, &lim);
			lim.rlim_cur = 0;
			if (setrlimit(RLIMIT_CORE, &lim) != 0)
				elog(NOTICE,
					 "setrlimit failed for RLIMIT_CORE soft limit to zero. errno: %d (%m).",
					 errno);
#endif

482
			*(volatile int *) 0 = 1234;
483 484 485 486 487 488 489 490 491 492 493
			break;
		}
		
		case FaultInjectorTypeInterrupt:
		{
			/*
			 * The place where this type of fault is injected must have
			 * has HOLD_INTERRUPTS() .. RESUME_INTERRUPTS() around it, otherwise
			 * the interrupt could be handled inside the fault injector itself
			 */
			ereport(LOG,
494 495
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
496
							entryLocal->faultName,
497 498 499 500 501 502 503
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));

			InterruptPending = true;
			QueryCancelPending = true;
			break;
		}

504 505 506
		case FaultInjectorTypeFinishPending:
		{
			ereport(LOG,
507 508
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
509
							entryLocal->faultName,
510 511 512 513 514
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));
			QueryFinishPending = true;
			break;
		}

515 516 517
		default:
			
			ereport(LOG, 
518 519
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("unexpected error, fault triggered, fault name:'%s' fault type:'%s' ",
520
							entryLocal->faultName,
521 522 523 524 525 526 527 528 529 530 531 532 533 534
							FaultInjectorTypeEnumToString[entryLocal->faultInjectorType])));	
			
			Assert(0);
			break;
	}
		
	return (entryLocal->faultInjectorType);
}

/*
 * lookup if fault injection is set
 */
static FaultInjectorEntry_s*
FaultInjector_LookupHashEntry(
535
							  const char* faultName)
536 537 538 539 540 541
{
	FaultInjectorEntry_s	*entry;
	
	Assert(faultInjectorShmem->hash != NULL);
	entry = (FaultInjectorEntry_s *) hash_search(
												  faultInjectorShmem->hash, 
542
												  (void *) faultName, // key
543 544 545 546 547
												  HASH_FIND, 
												  NULL);
	
	if (entry == NULL) {
		ereport(DEBUG5,
548 549
				(errmsg("FaultInjector_LookupHashEntry() could not find fault injection hash entry:'%s' ",
						faultName)));
550 551 552 553 554 555 556 557 558 559
	} 
	
	return entry;
}

/*
 * insert fault injection in hash table 
 */ 
static FaultInjectorEntry_s*
FaultInjector_InsertHashEntry(
560
							const char* faultName,
561 562 563 564 565 566 567 568 569
							bool	*exists)
{
	
	bool					foundPtr;
	FaultInjectorEntry_s	*entry;

	Assert(faultInjectorShmem->hash != NULL);
	entry = (FaultInjectorEntry_s *) hash_search(
												  faultInjectorShmem->hash, 
570 571
												  (void *) faultName, // key
												  HASH_ENTER_NULL,
572
												  &foundPtr);
573

574 575 576 577 578
	if (entry == NULL) {
		*exists = FALSE;
		return entry;
	} 
	
579 580
	elog(DEBUG1, "FaultInjector_InsertHashEntry() entry_key:%s",
		 entry->faultName);
581 582 583 584 585 586
	
	if (foundPtr) {
		*exists = TRUE;
	} else {
		*exists = FALSE;
	}
587

588 589 590 591 592 593 594 595
	return entry;
}

/*
 * 
 */
static bool
FaultInjector_RemoveHashEntry(
596
							  const char* faultName)
597 598 599 600 601 602 603 604
{	
	
	FaultInjectorEntry_s	*entry;
	bool					isRemoved = FALSE;
	
	Assert(faultInjectorShmem->hash != NULL);
	entry = (FaultInjectorEntry_s *) hash_search(
												  faultInjectorShmem->hash, 
605
												  (void *) faultName, // key
606 607 608 609 610 611 612
												  HASH_REMOVE, 
												  NULL);
	
	if (entry) 
	{
		ereport(LOG, 
				(errmsg("fault removed, fault name:'%s' fault type:'%s' ",
613
						entry->faultName,
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
						FaultInjectorTypeEnumToString[entry->faultInjectorType])));							
		
		isRemoved = TRUE;
	}
	
	return isRemoved;			
}

/*
 *
 */
static int 
FaultInjector_NewHashEntry(
						   FaultInjectorEntry_s	*entry)
{
	
	FaultInjectorEntry_s	*entryLocal=NULL;
	bool					exists;
	int						status = STATUS_OK;

	FiLockAcquire();

	if ((faultInjectorShmem->faultInjectorSlots + 1) >= FAULTINJECTOR_MAX_SLOTS) {
		FiLockRelease();
		status = STATUS_ERROR;
		ereport(WARNING,
640 641 642 643
				(errmsg("cannot insert fault injection, no slots available"),
				 errdetail("Fault name:'%s' fault type:'%s'",
						   entry->faultName,
						   FaultInjectorTypeEnumToString[entry->faultInjectorType])));
644 645 646 647 648 649
		snprintf(entry->bufOutput, sizeof(entry->bufOutput), 
				 "could not insert fault injection, max slots:'%d' reached",
				 FAULTINJECTOR_MAX_SLOTS);
		
		goto exit;
	}
650

651
	entryLocal = FaultInjector_InsertHashEntry(entry->faultName, &exists);
652 653 654 655 656
		
	if (entryLocal == NULL) {
		FiLockRelease();
		status = STATUS_ERROR;
		ereport(WARNING,
657 658 659 660
				(errmsg("cannot insert fault injection entry into table, no memory"),
				 errdetail("Fault name:'%s' fault type:'%s'",
						   entry->faultName,
						   FaultInjectorTypeEnumToString[entry->faultInjectorType])));
661 662 663 664 665 666 667 668 669 670
		snprintf(entry->bufOutput, sizeof(entry->bufOutput), 
				 "could not insert fault injection, no memory");
		
		goto exit;
	}
		
	if (exists) {
		FiLockRelease();
		status = STATUS_ERROR;
		ereport(WARNING,
671 672 673 674
				(errmsg("cannot insert fault injection entry into table, entry already exists"),
				 errdetail("Fault name:'%s' fault type:'%s' ",
						   entry->faultName,
						   FaultInjectorTypeEnumToString[entry->faultInjectorType])));
675 676 677 678 679 680 681
		snprintf(entry->bufOutput, sizeof(entry->bufOutput), 
				 "could not insert fault injection, entry already exists");
		
		goto exit;
	}
		
	entryLocal->faultInjectorType = entry->faultInjectorType;
682 683
	strlcpy(entryLocal->faultName, entry->faultName, sizeof(entryLocal->faultName));

684
	entryLocal->extraArg = entry->extraArg;
685 686
	entryLocal->ddlStatement = entry->ddlStatement;
	
687 688
	entryLocal->startOccurrence = entry->startOccurrence;
	entryLocal->endOccurrence = entry->endOccurrence;
689 690

	entryLocal->numTimesTriggered = 0;
691 692 693 694 695 696 697 698 699
	strcpy(entryLocal->databaseName, entry->databaseName);
	strcpy(entryLocal->tableName, entry->tableName);
		
	entryLocal->faultInjectorState = FaultInjectorStateWaiting;

	faultInjectorShmem->faultInjectorSlots++;
		
	FiLockRelease();
	
700
	elog(DEBUG1, "FaultInjector_NewHashEntry(): '%s'", entry->faultName);
701 702 703 704 705 706 707 708 709 710
	
exit:
		
	return status;			
}

/*
 * update hash entry with state 
 */		
static int 
711
FaultInjector_MarkEntryAsResume(
712 713 714 715 716 717
							FaultInjectorEntry_s	*entry)
{
	
	FaultInjectorEntry_s	*entryLocal;
	int						status = STATUS_OK;

718 719
	Assert(entry->faultInjectorType == FaultInjectorTypeResume);

720 721
	FiLockAcquire();

722
	entryLocal = FaultInjector_LookupHashEntry(entry->faultName);
723
	
724 725
	if (entryLocal == NULL)
	{
726 727 728
		FiLockRelease();
		status = STATUS_ERROR;
		ereport(WARNING,
729 730 731 732
				(errmsg("cannot update fault injection hash entry with fault injection status, no entry found"),
				 errdetail("Fault name:'%s' fault type:'%s'",
						   entry->faultName,
						   FaultInjectorTypeEnumToString[entry->faultInjectorType])));
733 734
		goto exit;
	}
735 736

	if (entryLocal->faultInjectorType != FaultInjectorTypeSuspend)
737 738
	{
		FiLockRelease();
739 740 741
		ereport(ERROR, 
				(errcode(ERRCODE_FAULT_INJECT),
				 errmsg("only suspend fault can be resumed")));	
742
	}
743 744

	entryLocal->faultInjectorType = FaultInjectorTypeResume;
745 746 747 748
	
	FiLockRelease();
	
	ereport(DEBUG1,
749
			(errmsg("LOG(fault injector): update fault injection hash entry identifier:'%s' state:'%s'",
750
					entry->faultName,
751
					FaultInjectorStateEnumToString[entryLocal->faultInjectorState])));
752 753 754 755 756 757 758
	
exit:	
	
	return status;			
}

/*
759
 * Inject fault according to its type.
760
 */
761
static int
762 763 764 765 766 767 768 769 770 771 772 773
FaultInjector_SetFaultInjection(
						   FaultInjectorEntry_s	*entry)
{
	int		status = STATUS_OK;
	bool	isRemoved = FALSE;
	
	switch (entry->faultInjectorType) {
		case FaultInjectorTypeReset:
		{
			HASH_SEQ_STATUS			hash_status;
			FaultInjectorEntry_s	*entryLocal;
			
774
			if (strcmp(entry->faultName, FaultInjectorNameAll) == 0)
775 776 777 778 779 780
			{
				hash_seq_init(&hash_status, faultInjectorShmem->hash);
				
				FiLockAcquire();
				
				while ((entryLocal = (FaultInjectorEntry_s *) hash_seq_search(&hash_status)) != NULL) {
781
					isRemoved = FaultInjector_RemoveHashEntry(entryLocal->faultName);
782 783 784 785 786 787 788 789 790 791
					if (isRemoved == TRUE) {
						faultInjectorShmem->faultInjectorSlots--;
					}					
				}
				FiLockRelease();
				Assert(faultInjectorShmem->faultInjectorSlots == 0);
			}
			else
			{
				FiLockAcquire();
792
				isRemoved = FaultInjector_RemoveHashEntry(entry->faultName);
793 794 795 796 797 798
				if (isRemoved == TRUE) {
					faultInjectorShmem->faultInjectorSlots--;
				}
				FiLockRelease();
			}
				
799
			if (isRemoved == FALSE)
800
				ereport(DEBUG1,
801
						(errmsg("LOG(fault injector): could not remove fault injection from hash identifier:'%s'",
802
								entry->faultName)));
803 804 805
			
			break;
		}
806 807 808 809

		case FaultInjectorTypeWaitUntilTriggered:
		{
			FaultInjectorEntry_s	*entryLocal;
810
			int retry_count = 3000; /* 10 minutes */
811 812

			while ((entryLocal = FaultInjector_LookupHashEntry(entry->faultName)) != NULL &&
813 814
				   entryLocal->faultInjectorState != FaultInjectorStateCompleted &&
				   entryLocal->numTimesTriggered - entryLocal->startOccurrence < entry->extraArg - 1)
815
			{
816
				pg_usleep(200000);  /* 0.2 sec */
817 818 819 820 821 822 823 824
				retry_count--;
				if (!retry_count)
				{
					ereport(ERROR,
							(errcode(ERRCODE_FAULT_INJECT),
							 errmsg("fault not triggered, fault name:'%s' fault type:'%s' ",
									entryLocal->faultName,
									FaultInjectorTypeEnumToString[entry->faultInjectorType]),
825
							 errdetail("Timed-out as 10 minutes max wait happens until triggered.")));
826
				}
827 828 829 830 831 832 833
			}

			if (entryLocal != NULL)
			{
				ereport(LOG,
						(errcode(ERRCODE_FAULT_INJECT),
						 errmsg("fault triggered %d times, fault name:'%s' fault type:'%s' ",
834
							entryLocal->numTimesTriggered,
835 836 837 838 839 840
							entryLocal->faultName,
							FaultInjectorTypeEnumToString[entry->faultInjectorType])));
				status = STATUS_OK;
			}
			else
			{
841
				ereport(ERROR,
842
						(errcode(ERRCODE_FAULT_INJECT),
843
						 errmsg("fault not set, fault name:'%s'  ",
844
								entry->faultName)));
845 846 847 848
			}
			break;
		}

849 850 851
		case FaultInjectorTypeStatus:
		{	
			FaultInjectorEntry_s	*entryLocal;
852
			int                     length;
853 854 855

			if (faultInjectorShmem->hash == NULL)
			{
856 857
				status = STATUS_ERROR;
				break;
858 859 860
			}
			length = snprintf(entry->bufOutput, sizeof(entry->bufOutput), "Success: ");

861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
			entryLocal = FaultInjector_LookupHashEntry(entry->faultName);
			if (entryLocal)
			{
				length = snprintf(
					(entry->bufOutput + length),
					sizeof(entry->bufOutput) - length,
					"fault name:'%s' "
					"fault type:'%s' "
					"ddl statement:'%s' "
					"database name:'%s' "
					"table name:'%s' "
					"start occurrence:'%d' "
					"end occurrence:'%d' "
					"extra arg:'%d' "
					"fault injection state:'%s'  "
					"num times hit:'%d' \n",
					entryLocal->faultName,
					FaultInjectorTypeEnumToString[entryLocal->faultInjectorType],
					FaultInjectorDDLEnumToString[entryLocal->ddlStatement],
					entryLocal->databaseName,
					entryLocal->tableName,
					entryLocal->startOccurrence,
					entryLocal->endOccurrence,
					entryLocal->extraArg,
					FaultInjectorStateEnumToString[entryLocal->faultInjectorState],
					entryLocal->numTimesTriggered);
887
			}
888 889 890 891 892
			else
			{
				length = snprintf(entry->bufOutput, sizeof(entry->bufOutput),
								  "Failure: fault name:'%s' not set",
								  entry->faultName);
893
			}
894 895
			elog(LOG, "%s", entry->bufOutput);
			if (length > sizeof(entry->bufOutput))
896
				elog(LOG, "fault status truncated from %d to %zu characters",
897
					 length, sizeof(entry->bufOutput));
898 899 900
			break;
		}
		case FaultInjectorTypeResume:
901
		{
902
			ereport(LOG, 
903 904
					(errcode(ERRCODE_FAULT_INJECT),
					 errmsg("fault triggered, fault name:'%s' fault type:'%s' ",
905
							entry->faultName,
906 907
							FaultInjectorTypeEnumToString[entry->faultInjectorType])));	
			
908
			FaultInjector_MarkEntryAsResume(entry);
909 910
			
			break;
911
		}
912 913 914 915 916 917 918 919
		default: 
			
			status = FaultInjector_NewHashEntry(entry);
			break;
	}
	return status;
}

920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
void
HandleFaultMessage(const char* msg)
{
	char name[NAMEDATALEN];
	char type[NAMEDATALEN];
	char ddl[NAMEDATALEN];
	char db[NAMEDATALEN];
	char table[NAMEDATALEN];
	int start;
	int end;
	int extra;
	char *result;
	int len;

	if (sscanf(msg, "faultname=%s type=%s ddl=%s db=%s table=%s "
			   "start=%d end=%d extra=%d",
			   name, type, ddl, db, table, &start, &end, &extra) != 8)
		elog(ERROR, "invalid fault message: %s", msg);
	/* The value '#' means not specified. */
	if (ddl[0] == '#')
		ddl[0] = '\0';
	if (db[0] == '#')
		db[0] = '\0';
	if (table[0] == '#')
		table[0] = '\0';

	result = InjectFault(name, type, ddl, db, table, start, end, extra);
	len = strlen(result);

	StringInfoData buf;
	pq_beginmessage(&buf, 'T');
	pq_sendint(&buf, Natts_fault_message_response, 2);

	pq_sendstring(&buf, "status");
	pq_sendint(&buf, 0, 4);		/* table oid */
	pq_sendint(&buf, Anum_fault_message_response_status, 2);		/* attnum */
	pq_sendint(&buf, TEXTOID, 4);		/* type oid */
	pq_sendint(&buf, -1, 2);	/* typlen */
	pq_sendint(&buf, -1, 4);		/* typmod */
	pq_sendint(&buf, 0, 2);		/* format code */
	pq_endmessage(&buf);

	/* Send a DataRow message */
	pq_beginmessage(&buf, 'D');
	pq_sendint(&buf, Natts_fault_message_response, 2);		/* # of columns */

	pq_sendint(&buf, len, 4);
	pq_sendbytes(&buf, result, len);
	pq_endmessage(&buf);
	EndCommand(GPCONN_TYPE_FAULT, DestRemote);
	pq_flush();
}

char *
InjectFault(char *faultName, char *type, char *ddlStatement, char *databaseName,
			char *tableName, int startOccurrence, int endOccurrence, int extraArg)
{
	StringInfo buf = makeStringInfo();
978
	FaultInjectorEntry_s faultEntry;
979

980 981 982
	elog(DEBUG1, "injecting fault: name %s, type %s, DDL %s, db %s, table %s, startOccurrence %d, endOccurrence %d, extraArg %d",
		 faultName, type, ddlStatement, databaseName, tableName,
		 startOccurrence, endOccurrence, extraArg );
983

984 985 986 987 988 989 990 991 992 993
	faultEntry.faultInjectorType = FaultInjectorTypeStringToEnum(type);
	faultEntry.ddlStatement = FaultInjectorDDLStringToEnum(ddlStatement);
	faultEntry.extraArg = extraArg;
	faultEntry.startOccurrence = startOccurrence;
	faultEntry.endOccurrence = endOccurrence;

	/*
	 * Validations:
	 *
	 */
994 995 996 997 998 999 1000
	if (strlcpy(faultEntry.faultName, faultName, sizeof(faultEntry.faultName)) >=
		sizeof(faultEntry.faultName))
		ereport(ERROR,
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("fault name too long: '%s'", faultName),
				 errdetail("Fault name should be no more than %d characters.",
						   FAULT_NAME_MAX_LENGTH-1)));
1001

1002 1003
	if (faultEntry.faultInjectorType == FaultInjectorTypeMax)
		ereport(ERROR,
1004
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
1005
				 errmsg("could not recognize fault type '%s'", type)));
1006

1007 1008 1009 1010 1011 1012 1013
	/* Special fault name "all" is only used to reset all faults */
	if (faultEntry.faultInjectorType != FaultInjectorTypeReset &&
		strcmp(faultEntry.faultName, FaultInjectorNameAll) == 0)
		ereport(ERROR,
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("invalid fault name '%s'", faultName)));

1014
	if (faultEntry.faultInjectorType == FaultInjectorTypeSleep)
1015
	{
1016 1017
		if (extraArg < 0 || extraArg > 7200)
			ereport(ERROR,
1018 1019 1020 1021
					(errcode(ERRCODE_PROTOCOL_VIOLATION),
					 errmsg("invalid sleep time, allowed range [0, 7200 sec]")));
	}

1022 1023
	if (faultEntry.ddlStatement == DDLMax)
		ereport(ERROR,
1024 1025 1026
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("could not recognize DDL statement")));

1027 1028 1029 1030 1031 1032 1033 1034
	if (strlcpy(faultEntry.databaseName, databaseName,
				sizeof(faultEntry.databaseName)) >=
		sizeof(faultEntry.databaseName))
		ereport(ERROR,
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("database name too long: '%s'", databaseName),
				 errdetail("Database name should be no more than %d characters.",
						   NAMEDATALEN-1)));
1035

1036 1037 1038 1039 1040 1041 1042
	if (strlcpy(faultEntry.tableName, tableName, sizeof(faultEntry.tableName)) >=
		sizeof(faultEntry.tableName))
		ereport(ERROR,
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("table name too long: '%s'", tableName),
				 errdetail("Table name should be no more than %d characters.",
						   NAMEDATALEN-1)));
1043 1044

	if (startOccurrence < 1 || startOccurrence > 1000)
1045
		ereport(ERROR,
1046 1047 1048 1049 1050
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("invalid start occurrence number, allowed range [1, 1000]")));


	if (endOccurrence != INFINITE_END_OCCURRENCE && endOccurrence < startOccurrence)
1051
		ereport(ERROR,
1052 1053 1054
				(errcode(ERRCODE_PROTOCOL_VIOLATION),
				 errmsg("invalid end occurrence number, allowed range [startOccurrence, ] or -1")));

1055 1056 1057 1058 1059 1060 1061

	/*
	 * Warnings:
	 *
	 */
	emit_warnings(faultEntry);

1062

1063
	if (FaultInjector_SetFaultInjection(&faultEntry) == STATUS_OK)
1064
	{
1065 1066
		if (faultEntry.faultInjectorType == FaultInjectorTypeStatus)
			appendStringInfo(buf, "%s", faultEntry.bufOutput);
1067
		else
1068
		{
1069
			appendStringInfo(buf, "Success:");
1070 1071
			elog(LOG, "injected fault '%s' type '%s'", faultName, type);
		}
1072 1073
	}
	else
1074
		appendStringInfo(buf, "Failure: %s", faultEntry.bufOutput);
1075 1076 1077

	return buf->data;
}
1078
#endif