async.c 15.9 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * async.c--
4
 *	  Asynchronous notification
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
10
 *	  $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.27 1998/01/25 05:12:54 momjian Exp $
11 12 13 14 15
 *
 *-------------------------------------------------------------------------
 */
/* New Async Notification Model:
 * 1. Multiple backends on same machine.  Multiple backends listening on
16
 *	  one relation.
17 18
 *
 * 2. One of the backend does a 'notify <relname>'.  For all backends that
19 20 21 22 23 24 25 26
 *	  are listening to this relation (all notifications take place at the
 *	  end of commit),
 *	  2.a  If the process is the same as the backend process that issued
 *		   notification (we are notifying something that we are listening),
 *		   signal the corresponding frontend over the comm channel using the
 *		   out-of-band channel.
 *	  2.b  For all other listening processes, we send kill(2) to wake up
 *		   the listening backend.
27
 * 3. Upon receiving a kill(2) signal from another backend process notifying
28 29 30 31 32
 *	  that one of the relation that we are listening is being notified,
 *	  we can be in either of two following states:
 *	  3.a  We are sleeping, wake up and signal our frontend.
 *	  3.b  We are in middle of another transaction, wait until the end of
 *		   of the current transaction and signal our frontend.
33 34 35 36 37 38 39 40 41 42 43 44
 * 4. Each frontend receives this notification and prcesses accordingly.
 *
 * -- jw, 12/28/93
 *
 */
/*
 * The following is the old model which does not work.
 */
/*
 * Model is:
 * 1. Multiple backends on same machine.
 *
45 46 47
 * 2. Query on one backend sends stuff over an asynchronous portal by
 *	  appending to a relation, and then doing an async. notification
 *	  (which takes place after commit) to all listeners on this relation.
48
 *
49 50 51
 * 3. Async. notification results in all backends listening on relation
 *	  to be woken up, by a process signal kill(2), with name of relation
 *	  passed in shared memory.
52 53
 *
 * 4. Each backend notifies its respective frontend over the comm
54
 *	  channel using the out-of-band channel.
55 56 57 58 59 60
 *
 * 5. Each frontend receives this notification and processes accordingly.
 *
 * #4,#5 are changing soon with pending rewrite of portal/protocol.
 *
 */
M
-Wall'd  
Marc G. Fournier 已提交
61 62 63 64
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
65
#include <sys/types.h>			/* Needed by in.h on Ultrix */
M
-Wall'd  
Marc G. Fournier 已提交
66
#include <netinet/in.h>
67

M
Marc G. Fournier 已提交
68 69
#include <postgres.h>

B
Bruce Momjian 已提交
70
#include <miscadmin.h>
M
Marc G. Fournier 已提交
71 72 73 74 75 76 77 78
#include <utils/syscache.h>
#include <access/relscan.h>
#include <access/xact.h>
#include <lib/dllist.h>
#include <tcop/dest.h>
#include <catalog/pg_proc.h>
#include <catalog/catname.h>
#include <catalog/pg_listener.h>
79
#include <access/heapam.h>
M
Marc G. Fournier 已提交
80 81 82 83 84
#include <storage/bufmgr.h>
#include <nodes/memnodes.h>
#include <utils/mcxt.h>
#include <commands/async.h>
#include <libpq/libpq.h>
85

M
Marc G. Fournier 已提交
86 87 88
#ifndef HAVE_STRDUP
#  include <port-protos.h>		/* for strdup() */
#endif
89

90 91
#include <storage/lmgr.h>

92 93 94
static int	notifyFrontEndPending = 0;
static int	notifyIssued = 0;
static Dllist *pendingNotifies = NULL;
95 96


97 98 99
static int	AsyncExistsPendingNotify(char *);
static void ClearPendingNotify(void);
static void Async_NotifyFrontEnd(void);
B
Bruce Momjian 已提交
100
void        Async_Unlisten(char *relname, int pid);
101
static void Async_UnlistenOnExit(int code, char *relname);
102

103 104 105 106
/*
 *--------------------------------------------------------------
 * Async_NotifyHandler --
 *
107 108 109 110 111 112 113
 *		This is the signal handler for SIGUSR2.  When the backend
 *		is signaled, the backend can be in two states.
 *		1. If the backend is in the middle of another transaction,
 *		   we set the flag, notifyFrontEndPending, and wait until
 *		   the end of the transaction to notify the front end.
 *		2. If the backend is not in the middle of another transaction,
 *		   we notify the front end immediately.
114
 *
115
 *		-- jw, 12/28/93
116
 * Results:
117
 *		none
118 119
 *
 * Side effects:
120
 *		none
121 122
 */
void
B
Bruce Momjian 已提交
123
Async_NotifyHandler(SIGNAL_ARGS)
124
{
125 126 127 128 129
	extern TransactionState CurrentTransactionState;

	if ((CurrentTransactionState->state == TRANS_DEFAULT) &&
		(CurrentTransactionState->blockState == TRANS_DEFAULT))
	{
130

131
#ifdef ASYNC_DEBUG
132
		elog(DEBUG, "Waking up sleeping backend process");
133
#endif
134
		Async_NotifyFrontEnd();
135

136 137 138
	}
	else
	{
139
#ifdef ASYNC_DEBUG
140 141 142
		elog(DEBUG, "Process is in the middle of another transaction, state = %d, block state = %d",
			 CurrentTransactionState->state,
			 CurrentTransactionState->blockState);
143
#endif
144 145
		notifyFrontEndPending = 1;
	}
146 147 148 149 150 151
}

/*
 *--------------------------------------------------------------
 * Async_Notify --
 *
152 153 154
 *		Adds the relation to the list of pending notifies.
 *		All notification happens at end of commit.
 *		^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
155
 *
156 157 158
 *		All notification of backend processes happens here,
 *		then each backend notifies its corresponding front end at
 *		the end of commit.
159
 *
160 161
 *		This correspond to 'notify <relname>' command
 *		-- jw, 12/28/93
162 163
 *
 * Results:
164
 *		XXX
165 166
 *
 * Side effects:
167
 *		All tuples for relname in pg_listener are updated.
168 169 170 171 172 173
 *
 *--------------------------------------------------------------
 */
void
Async_Notify(char *relname)
{
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188
	HeapTuple	lTuple,
				rTuple;
	Relation	lRel;
	HeapScanDesc sRel;
	TupleDesc	tdesc;
	ScanKeyData key;
	Buffer		b;
	Datum		d,
				value[3];
	bool		isnull;
	char		repl[3],
				nulls[3];

	char	   *notifyName;
189

190
#ifdef ASYNC_DEBUG
191
	elog(DEBUG, "Async_Notify: %s", relname);
192
#endif
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211

	if (!pendingNotifies)
		pendingNotifies = DLNewList();

	/*
	 * Allocate memory from the global malloc pool because it needs to be
	 * referenced also when the transaction is finished.  DZ - 26-08-1996
	 */
	notifyName = strdup(relname);
	DLAddHead(pendingNotifies, DLNewElem(notifyName));

	ScanKeyEntryInitialize(&key, 0,
						   Anum_pg_listener_relname,
						   NameEqualRegProcedure,
						   PointerGetDatum(notifyName));

	lRel = heap_openr(ListenerRelationName);
	tdesc = RelationGetTupleDescriptor(lRel);
	RelationSetLockForWrite(lRel);
212
	sRel = heap_beginscan(lRel, 0, false, 1, &key);
213 214 215 216 217 218 219 220 221

	nulls[0] = nulls[1] = nulls[2] = ' ';
	repl[0] = repl[1] = repl[2] = ' ';
	repl[Anum_pg_listener_notify - 1] = 'r';
	value[0] = value[1] = value[2] = (Datum) 0;
	value[Anum_pg_listener_notify - 1] = Int32GetDatum(1);

	while (HeapTupleIsValid(lTuple = heap_getnext(sRel, 0, &b)))
	{
222 223
		d = heap_getattr(lTuple, b, Anum_pg_listener_notify,
						 tdesc, &isnull);
224 225 226 227 228 229
		if (!DatumGetInt32(d))
		{
			rTuple = heap_modifytuple(lTuple, b, lRel, value, nulls, repl);
			heap_replace(lRel, &lTuple->t_ctid, rTuple);
		}
		ReleaseBuffer(b);
230
	}
231 232 233 234
	heap_endscan(sRel);
	RelationUnsetLockForWrite(lRel);
	heap_close(lRel);
	notifyIssued = 1;
235 236 237 238 239 240
}

/*
 *--------------------------------------------------------------
 * Async_NotifyAtCommit --
 *
241 242 243
 *		Signal our corresponding frontend process on relations that
 *		were notified.	Signal all other backend process that
 *		are listening also.
244
 *
245
 *		-- jw, 12/28/93
246 247
 *
 * Results:
248
 *		XXX
249 250
 *
 * Side effects:
251 252 253
 *		Tuples in pg_listener that has our listenerpid are updated so
 *		that the notification is 0.  We do not want to notify frontend
 *		more than once.
254
 *
255
 *		-- jw, 12/28/93
256 257 258 259 260 261
 *
 *--------------------------------------------------------------
 */
void
Async_NotifyAtCommit()
{
262 263 264 265 266 267 268 269
	HeapTuple	lTuple;
	Relation	lRel;
	HeapScanDesc sRel;
	TupleDesc	tdesc;
	ScanKeyData key;
	Datum		d;
	bool		isnull;
	Buffer		b;
270 271 272 273 274 275 276 277 278 279 280 281 282
	extern TransactionState CurrentTransactionState;

	if (!pendingNotifies)
		pendingNotifies = DLNewList();

	if ((CurrentTransactionState->state == TRANS_DEFAULT) &&
		(CurrentTransactionState->blockState == TRANS_DEFAULT))
	{

		if (notifyIssued)
		{						/* 'notify <relname>' issued by us */
			notifyIssued = 0;
			StartTransactionCommand();
283
#ifdef ASYNC_DEBUG
284
			elog(DEBUG, "Async_NotifyAtCommit.");
285
#endif
286 287 288 289 290 291
			ScanKeyEntryInitialize(&key, 0,
								   Anum_pg_listener_notify,
								   Integer32EqualRegProcedure,
								   Int32GetDatum(1));
			lRel = heap_openr(ListenerRelationName);
			RelationSetLockForWrite(lRel);
292
			sRel = heap_beginscan(lRel, 0, false, 1, &key);
293 294 295 296
			tdesc = RelationGetTupleDescriptor(lRel);

			while (HeapTupleIsValid(lTuple = heap_getnext(sRel, 0, &b)))
			{
297 298
				d = heap_getattr(lTuple, b, Anum_pg_listener_relname,
								 tdesc, &isnull);
299 300 301

				if (AsyncExistsPendingNotify((char *) DatumGetPointer(d)))
				{
302 303
					d = heap_getattr(lTuple, b, Anum_pg_listener_pid,
									 tdesc, &isnull);
304

B
Bruce Momjian 已提交
305
					if (MyProcPid == DatumGetInt32(d))
306
					{
307
#ifdef ASYNC_DEBUG
308
						elog(DEBUG, "Notifying self, setting notifyFronEndPending to 1");
309
#endif
310 311 312 313
						notifyFrontEndPending = 1;
					}
					else
					{
314
#ifdef ASYNC_DEBUG
315
						elog(DEBUG, "Notifying others");
316
#endif
317
#ifdef HAVE_KILL
318 319 320 321 322 323 324 325 326 327 328
						if (kill(DatumGetInt32(d), SIGUSR2) < 0)
						{
							if (errno == ESRCH)
							{
								heap_delete(lRel, &lTuple->t_ctid);
							}
						}
#endif
					}
				}
				ReleaseBuffer(b);
329
			}
330 331 332 333 334 335
			heap_endscan(sRel);
			RelationUnsetLockForWrite(lRel);
			heap_close(lRel);

			CommitTransactionCommand();
			ClearPendingNotify();
336
		}
337

338 339 340 341 342 343
		if (notifyFrontEndPending)
		{						/* we need to notify the frontend of all
								 * pending notifies. */
			notifyFrontEndPending = 1;
			Async_NotifyFrontEnd();
		}
344 345 346 347 348 349 350
	}
}

/*
 *--------------------------------------------------------------
 * Async_NotifyAtAbort --
 *
351 352 353
 *		Gets rid of pending notifies.  List elements are automatically
 *		freed through memory context.
 *
354 355
 *
 * Results:
356
 *		XXX
357 358
 *
 * Side effects:
359
 *		XXX
360 361 362 363 364 365
 *
 *--------------------------------------------------------------
 */
void
Async_NotifyAtAbort()
{
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
	extern TransactionState CurrentTransactionState;

	if (notifyIssued)
	{
		ClearPendingNotify();
	}
	notifyIssued = 0;
	if (pendingNotifies)
		DLFreeList(pendingNotifies);
	pendingNotifies = DLNewList();

	if ((CurrentTransactionState->state == TRANS_DEFAULT) &&
		(CurrentTransactionState->blockState == TRANS_DEFAULT))
	{
		if (notifyFrontEndPending)
		{						/* don't forget to notify front end */
			Async_NotifyFrontEnd();
		}
384 385 386 387 388 389 390
	}
}

/*
 *--------------------------------------------------------------
 * Async_Listen --
 *
391 392
 *		Register a backend (identified by its Unix PID) as listening
 *		on the specified relation.
393
 *
394
 *		This corresponds to the 'listen <relation>' command in SQL
395
 *
396 397
 *		One listener per relation, pg_listener relation is keyed
 *		on (relname,pid) to provide multiple listeners in future.
398 399
 *
 * Results:
400
 *		pg_listeners is updated.
401 402
 *
 * Side effects:
403
 *		XXX
404 405 406 407 408 409
 *
 *--------------------------------------------------------------
 */
void
Async_Listen(char *relname, int pid)
{
410 411 412 413 414 415 416 417 418 419 420 421 422 423
	Datum		values[Natts_pg_listener];
	char		nulls[Natts_pg_listener];
	TupleDesc	tdesc;
	HeapScanDesc s;
	HeapTuple	htup,
				tup;
	Relation	lDesc;
	Buffer		b;
	Datum		d;
	int			i;
	bool		isnull;
	int			alreadyListener = 0;
	char	   *relnamei;
	TupleDesc	tupDesc;
424

425
#ifdef ASYNC_DEBUG
426
	elog(DEBUG, "Async_Listen: %s", relname);
427
#endif
428 429 430 431
	for (i = 0; i < Natts_pg_listener; i++)
	{
		nulls[i] = ' ';
		values[i] = PointerGetDatum(NULL);
432
	}
433 434 435 436 437 438 439 440 441 442 443

	i = 0;
	values[i++] = (Datum) relname;
	values[i++] = (Datum) pid;
	values[i++] = (Datum) 0;	/* no notifies pending */

	lDesc = heap_openr(ListenerRelationName);
	RelationSetLockForWrite(lDesc);

	/* is someone already listening.  One listener per relation */
	tdesc = RelationGetTupleDescriptor(lDesc);
444
	s = heap_beginscan(lDesc, 0, false, 0, (ScanKey) NULL);
445 446
	while (HeapTupleIsValid(htup = heap_getnext(s, 0, &b)))
	{
447 448
		d = heap_getattr(htup, b, Anum_pg_listener_relname, tdesc,
						 &isnull);
449 450 451
		relnamei = DatumGetPointer(d);
		if (!strncmp(relnamei, relname, NAMEDATALEN))
		{
452
			d = heap_getattr(htup, b, Anum_pg_listener_pid, tdesc, &isnull);
453
			pid = DatumGetInt32(d);
B
Bruce Momjian 已提交
454
			if (pid == MyProcPid)
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
			{
				alreadyListener = 1;
			}
		}
		ReleaseBuffer(b);
	}
	heap_endscan(s);

	if (alreadyListener)
	{
		elog(NOTICE, "Async_Listen: We are already listening on %s",
			 relname);
		return;
	}

	tupDesc = lDesc->rd_att;
	tup = heap_formtuple(tupDesc,
						 values,
						 nulls);
	heap_insert(lDesc, tup);

	pfree(tup);

	/*
	 * if (alreadyListener) { elog(NOTICE,"Async_Listen: already one
	 * listener on %s (possibly dead)",relname); }
	 */

	RelationUnsetLockForWrite(lDesc);
	heap_close(lDesc);

	/*
	 * now that we are listening, we should make a note to ourselves to
	 * unlisten prior to dying.
	 */
	relnamei = malloc(NAMEDATALEN);		/* persists to process exit */
491
	StrNCpy(relnamei, relname, NAMEDATALEN);
492
	on_exitpg(Async_UnlistenOnExit, (caddr_t) relnamei);
493 494 495 496 497 498
}

/*
 *--------------------------------------------------------------
 * Async_Unlisten --
 *
499 500 501 502 503
 *		Remove the backend from the list of listening backends
 *		for the specified relation.
 *
 *		This would correspond to the 'unlisten <relation>'
 *		command, but there isn't one yet.
504 505
 *
 * Results:
506
 *		pg_listeners is updated.
507 508
 *
 * Side effects:
509
 *		XXX
510 511 512
 *
 *--------------------------------------------------------------
 */
B
Bruce Momjian 已提交
513
void
514 515
Async_Unlisten(char *relname, int pid)
{
516 517
	Relation	lDesc;
	HeapTuple	lTuple;
518 519 520 521 522 523 524 525 526 527 528 529 530 531

	lTuple = SearchSysCacheTuple(LISTENREL, PointerGetDatum(relname),
								 Int32GetDatum(pid),
								 0, 0);
	lDesc = heap_openr(ListenerRelationName);
	RelationSetLockForWrite(lDesc);

	if (lTuple != NULL)
	{
		heap_delete(lDesc, &lTuple->t_ctid);
	}

	RelationUnsetLockForWrite(lDesc);
	heap_close(lDesc);
532 533
}

534
static void
535
Async_UnlistenOnExit(int code,	/* from exitpg */
536
					 char *relname)
537
{
B
Bruce Momjian 已提交
538
	Async_Unlisten((char *) relname, MyProcPid);
539 540 541 542 543 544
}

/*
 * --------------------------------------------------------------
 * Async_NotifyFrontEnd --
 *
545 546 547
 *		Perform an asynchronous notification to front end over
 *		portal comm channel.  The name of the relation which contains the
 *		data is sent to the front end.
548
 *
549 550
 *		We remove the notification flag from the pg_listener tuple
 *		associated with our process.
551 552
 *
 * Results:
553
 *		XXX
554 555 556
 *
 * Side effects:
 *
557 558 559
 *		We make use of the out-of-band channel to transmit the
 *		notification to the front end.	The actual data transfer takes
 *		place at the front end's request.
560 561 562
 *
 * --------------------------------------------------------------
 */
563
GlobalMemory notifyContext = NULL;
564

565
static void
566 567
Async_NotifyFrontEnd()
{
568
	extern CommandDest whereToSendOutput;
569 570 571 572 573 574 575 576 577 578 579 580
	HeapTuple	lTuple,
				rTuple;
	Relation	lRel;
	HeapScanDesc sRel;
	TupleDesc	tdesc;
	ScanKeyData key[2];
	Datum		d,
				value[3];
	char		repl[3],
				nulls[3];
	Buffer		b;
	bool		isnull;
581 582 583

	notifyFrontEndPending = 0;

584
#ifdef ASYNC_DEBUG
585
	elog(DEBUG, "Async_NotifyFrontEnd: notifying front end.");
586
#endif
587 588 589 590 591 592 593 594 595

	StartTransactionCommand();
	ScanKeyEntryInitialize(&key[0], 0,
						   Anum_pg_listener_notify,
						   Integer32EqualRegProcedure,
						   Int32GetDatum(1));
	ScanKeyEntryInitialize(&key[1], 0,
						   Anum_pg_listener_pid,
						   Integer32EqualRegProcedure,
B
Bruce Momjian 已提交
596
						   Int32GetDatum(MyProcPid));
597 598 599
	lRel = heap_openr(ListenerRelationName);
	RelationSetLockForWrite(lRel);
	tdesc = RelationGetTupleDescriptor(lRel);
600
	sRel = heap_beginscan(lRel, 0, false, 2, key);
601 602 603 604 605 606 607 608 609

	nulls[0] = nulls[1] = nulls[2] = ' ';
	repl[0] = repl[1] = repl[2] = ' ';
	repl[Anum_pg_listener_notify - 1] = 'r';
	value[0] = value[1] = value[2] = (Datum) 0;
	value[Anum_pg_listener_notify - 1] = Int32GetDatum(0);

	while (HeapTupleIsValid(lTuple = heap_getnext(sRel, 0, &b)))
	{
610 611
		d = heap_getattr(lTuple, b, Anum_pg_listener_relname,
						 tdesc, &isnull);
612 613 614 615 616 617 618 619
		rTuple = heap_modifytuple(lTuple, b, lRel, value, nulls, repl);
		heap_replace(lRel, &lTuple->t_ctid, rTuple);

		/* notifying the front end */

		if (whereToSendOutput == Remote)
		{
			pq_putnchar("A", 1);
B
Bruce Momjian 已提交
620
			pq_putint((int32)MyProcPid, sizeof(int32));
621 622 623 624 625 626 627 628
			pq_putstr(DatumGetName(d)->data);
			pq_flush();
		}
		else
		{
			elog(NOTICE, "Async_NotifyFrontEnd: no asynchronous notification to frontend on interactive sessions");
		}
		ReleaseBuffer(b);
629
	}
630
	CommitTransactionCommand();
631 632 633 634 635
}

static int
AsyncExistsPendingNotify(char *relname)
{
636
	Dlelem	   *p;
637 638 639 640 641 642

	for (p = DLGetHead(pendingNotifies);
		 p != NULL;
		 p = DLGetSucc(p))
	{
		/* Use NAMEDATALEN for relname comparison.	  DZ - 26-08-1996 */
643
		if (!strncmp((const char *) DLE_VAL(p), relname, NAMEDATALEN))
644 645 646 647
			return 1;
	}

	return 0;
648 649 650 651 652
}

static void
ClearPendingNotify()
{
653
	Dlelem	   *p;
654

655 656 657
	while ((p = DLRemHead(pendingNotifies)) != NULL)
		free(DLE_VAL(p));
}