1 /*-------------------------------------------------------------------------
4 * Asynchronous notification: NOTIFY, LISTEN, UNLISTEN
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/commands/async.c,v 1.98 2003/08/04 02:39:58 momjian Exp $
12 *-------------------------------------------------------------------------
15 /*-------------------------------------------------------------------------
16 * New Async Notification Model:
17 * 1. Multiple backends on same machine. Multiple backends listening on
18 * one relation. (Note: "listening on a relation" is not really the
19 * right way to think about it, since the notify names need not have
20 * anything to do with the names of relations actually in the database.
21 * But this terminology is all over the code and docs, and I don't feel
22 * like trying to replace it.)
24 * 2. There is a tuple in relation "pg_listener" for each active LISTEN,
25 * ie, each relname/listenerPID pair. The "notification" field of the
26 * tuple is zero when no NOTIFY is pending for that listener, or the PID
27 * of the originating backend when a cross-backend NOTIFY is pending.
28 * (We skip writing to pg_listener when doing a self-NOTIFY, so the
29 * notification field should never be equal to the listenerPID field.)
31 * 3. The NOTIFY statement itself (routine Async_Notify) just adds the target
32 * relname to a list of outstanding NOTIFY requests. Actual processing
33 * happens if and only if we reach transaction commit. At that time (in
34 * routine AtCommit_Notify) we scan pg_listener for matching relnames.
35 * If the listenerPID in a matching tuple is ours, we just send a notify
36 * message to our own front end. If it is not ours, and "notification"
37 * is not already nonzero, we set notification to our own PID and send a
38 * SIGUSR2 signal to the receiving process (indicated by listenerPID).
39 * BTW: if the signal operation fails, we presume that the listener backend
40 * crashed without removing this tuple, and remove the tuple for it.
42 * 4. Upon receipt of a SIGUSR2 signal, the signal handler can call inbound-
43 * notify processing immediately if this backend is idle (ie, it is
44 * waiting for a frontend command and is not within a transaction block).
45 * Otherwise the handler may only set a flag, which will cause the
46 * processing to occur just before we next go idle.
48 * 5. Inbound-notify processing consists of scanning pg_listener for tuples
49 * matching our own listenerPID and having nonzero notification fields.
50 * For each such tuple, we send a message to our frontend and clear the
51 * notification field. BTW: this routine has to start/commit its own
52 * transaction, since by assumption it is only called from outside any
55 * Although we grab AccessExclusiveLock on pg_listener for any operation,
56 * the lock is never held very long, so it shouldn't cause too much of
57 * a performance problem.
59 * An application that listens on the same relname it notifies will get
60 * NOTIFY messages for its own NOTIFYs. These can be ignored, if not useful,
61 * by comparing be_pid in the NOTIFY message to the application's own backend's
62 * PID. (As of FE/BE protocol 2.0, the backend's PID is provided to the
63 * frontend during startup.) The above design guarantees that notifies from
64 * other backends will never be missed by ignoring self-notifies. Note,
65 * however, that we do *not* guarantee that a separate frontend message will
66 * be sent for every outside NOTIFY. Since there is only room for one
67 * originating PID in pg_listener, outside notifies occurring at about the
68 * same time may be collapsed into a single message bearing the PID of the
69 * first outside backend to perform the NOTIFY.
70 *-------------------------------------------------------------------------
78 #include <netinet/in.h>
80 #include "access/heapam.h"
81 #include "catalog/catname.h"
82 #include "catalog/pg_listener.h"
83 #include "commands/async.h"
84 #include "libpq/libpq.h"
85 #include "libpq/pqformat.h"
86 #include "miscadmin.h"
87 #include "storage/ipc.h"
88 #include "tcop/tcopprot.h"
89 #include "utils/fmgroids.h"
90 #include "utils/ps_status.h"
91 #include "utils/syscache.h"
94 /* stuff that we really ought not be touching directly :-( */
95 extern TransactionState CurrentTransactionState;
99 * State for outbound notifies consists of a list of all relnames NOTIFYed
100 * in the current transaction. We do not actually perform a NOTIFY until
101 * and unless the transaction commits. pendingNotifies is NIL if no
102 * NOTIFYs have been done in the current transaction. The List nodes and
103 * referenced strings are all palloc'd in TopTransactionContext.
105 static List *pendingNotifies = NIL;
108 * State for inbound notifies consists of two flags: one saying whether
109 * the signal handler is currently allowed to call ProcessIncomingNotify
110 * directly, and one saying whether the signal has occurred but the handler
111 * was not allowed to call ProcessIncomingNotify at the time.
113 * NB: the "volatile" on these declarations is critical! If your compiler
114 * does not grok "volatile", you'd be best advised to compile this file
115 * with all optimization turned off.
117 static volatile int notifyInterruptEnabled = 0;
118 static volatile int notifyInterruptOccurred = 0;
120 /* True if we've registered an on_shmem_exit cleanup */
121 static bool unlistenExitRegistered = false;
123 bool Trace_notify = false;
126 static void Async_UnlistenAll(void);
127 static void Async_UnlistenOnExit(void);
128 static void ProcessIncomingNotify(void);
129 static void NotifyMyFrontEnd(char *relname, int32 listenerPID);
130 static bool AsyncExistsPendingNotify(const char *relname);
131 static void ClearPendingNotifies(void);
135 *--------------------------------------------------------------
138 * This is executed by the SQL notify command.
140 * Adds the relation to the list of pending notifies.
141 * Actual notification happens during transaction commit.
142 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
147 *--------------------------------------------------------------
150 Async_Notify(char *relname)
153 elog(DEBUG1, "Async_Notify(%s)", relname);
155 /* no point in making duplicate entries in the list ... */
156 if (!AsyncExistsPendingNotify(relname))
159 * The name list needs to live until end of transaction, so store
160 * it in the top transaction context.
162 MemoryContext oldcontext;
164 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
166 pendingNotifies = lcons(pstrdup(relname), pendingNotifies);
168 MemoryContextSwitchTo(oldcontext);
173 *--------------------------------------------------------------
176 * This is executed by the SQL listen command.
178 * Register a backend (identified by its Unix PID) as listening
179 * on the specified relation.
185 * pg_listener is updated.
187 *--------------------------------------------------------------
190 Async_Listen(char *relname, int pid)
195 Datum values[Natts_pg_listener];
196 char nulls[Natts_pg_listener];
198 bool alreadyListener = false;
201 elog(DEBUG1, "Async_Listen(%s,%d)", relname, pid);
203 lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
205 /* Detect whether we are already listening on this relname */
206 scan = heap_beginscan(lRel, SnapshotNow, 0, (ScanKey) NULL);
207 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
209 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(tuple);
211 if (listener->listenerpid == pid &&
212 strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0)
214 alreadyListener = true;
215 /* No need to scan the rest of the table */
223 heap_close(lRel, AccessExclusiveLock);
225 (errmsg("already listening on \"%s\"", relname)));
230 * OK to insert a new tuple
233 for (i = 0; i < Natts_pg_listener; i++)
236 values[i] = PointerGetDatum(NULL);
240 values[i++] = (Datum) relname;
241 values[i++] = (Datum) pid;
242 values[i++] = (Datum) 0; /* no notifies pending */
244 tuple = heap_formtuple(RelationGetDescr(lRel), values, nulls);
245 simple_heap_insert(lRel, tuple);
247 #ifdef NOT_USED /* currently there are no indexes */
248 CatalogUpdateIndexes(lRel, tuple);
251 heap_freetuple(tuple);
253 heap_close(lRel, AccessExclusiveLock);
256 * now that we are listening, make sure we will unlisten before dying.
258 if (!unlistenExitRegistered)
260 on_shmem_exit(Async_UnlistenOnExit, 0);
261 unlistenExitRegistered = true;
266 *--------------------------------------------------------------
269 * This is executed by the SQL unlisten command.
271 * Remove the backend from the list of listening backends
272 * for the specified relation.
278 * pg_listener is updated.
280 *--------------------------------------------------------------
283 Async_Unlisten(char *relname, int pid)
289 /* Handle specially the `unlisten "*"' command */
290 if ((!relname) || (*relname == '\0') || (strcmp(relname, "*") == 0))
297 elog(DEBUG1, "Async_Unlisten(%s,%d)", relname, pid);
299 lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
301 scan = heap_beginscan(lRel, SnapshotNow, 0, (ScanKey) NULL);
302 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
304 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(tuple);
306 if (listener->listenerpid == pid &&
307 strncmp(NameStr(listener->relname), relname, NAMEDATALEN) == 0)
309 /* Found the matching tuple, delete it */
310 simple_heap_delete(lRel, &tuple->t_self);
313 * We assume there can be only one match, so no need to scan
314 * the rest of the table
321 heap_close(lRel, AccessExclusiveLock);
324 * We do not complain about unlistening something not being listened;
330 *--------------------------------------------------------------
333 * Unlisten all relations for this backend.
335 * This is invoked by UNLISTEN "*" command, and also at backend exit.
341 * pg_listener is updated.
343 *--------------------------------------------------------------
346 Async_UnlistenAll(void)
355 elog(DEBUG1, "Async_UnlistenAll");
357 lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
358 tdesc = RelationGetDescr(lRel);
360 /* Find and delete all entries with my listenerPID */
361 ScanKeyEntryInitialize(&key[0], 0,
362 Anum_pg_listener_pid,
364 Int32GetDatum(MyProcPid));
365 scan = heap_beginscan(lRel, SnapshotNow, 1, key);
367 while ((lTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
368 simple_heap_delete(lRel, &lTuple->t_self);
371 heap_close(lRel, AccessExclusiveLock);
375 *--------------------------------------------------------------
376 * Async_UnlistenOnExit
378 * Clean up the pg_listener table at backend exit.
380 * This is executed if we have done any LISTENs in this backend.
381 * It might not be necessary anymore, if the user UNLISTENed everything,
382 * but we don't try to detect that case.
388 * pg_listener is updated if necessary.
390 *--------------------------------------------------------------
393 Async_UnlistenOnExit(void)
396 * We need to start/commit a transaction for the unlisten, but if
397 * there is already an active transaction we had better abort that one
398 * first. Otherwise we'd end up committing changes that probably
399 * ought to be discarded.
401 AbortOutOfAnyTransaction();
402 /* Now we can do the unlisten */
403 StartTransactionCommand();
405 CommitTransactionCommand();
409 *--------------------------------------------------------------
412 * This is called at transaction commit.
414 * If there are outbound notify requests in the pendingNotifies list,
415 * scan pg_listener for matching tuples, and either signal the other
416 * backend or send a message to our own frontend.
418 * NOTE: we are still inside the current transaction, therefore can
419 * piggyback on its committing of changes.
425 * Tuples in pg_listener that have matching relnames and other peoples'
426 * listenerPIDs are updated with a nonzero notification field.
428 *--------------------------------------------------------------
431 AtCommit_Notify(void)
438 Datum value[Natts_pg_listener];
439 char repl[Natts_pg_listener],
440 nulls[Natts_pg_listener];
442 if (pendingNotifies == NIL)
443 return; /* no NOTIFY statements in this
447 * NOTIFY is disabled if not normal processing mode. This test used to
448 * be in xact.c, but it seems cleaner to do it here.
450 if (!IsNormalProcessingMode())
452 ClearPendingNotifies();
457 elog(DEBUG1, "AtCommit_Notify");
459 /* preset data to update notify column to MyProcPid */
460 nulls[0] = nulls[1] = nulls[2] = ' ';
461 repl[0] = repl[1] = repl[2] = ' ';
462 repl[Anum_pg_listener_notify - 1] = 'r';
463 value[0] = value[1] = value[2] = (Datum) 0;
464 value[Anum_pg_listener_notify - 1] = Int32GetDatum(MyProcPid);
466 lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
467 tdesc = RelationGetDescr(lRel);
468 scan = heap_beginscan(lRel, SnapshotNow, 0, (ScanKey) NULL);
470 while ((lTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
472 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(lTuple);
473 char *relname = NameStr(listener->relname);
474 int32 listenerPID = listener->listenerpid;
476 if (!AsyncExistsPendingNotify(relname))
479 if (listenerPID == MyProcPid)
482 * Self-notify: no need to bother with table update. Indeed,
483 * we *must not* clear the notification field in this path, or
484 * we could lose an outside notify, which'd be bad for
485 * applications that ignore self-notify messages.
489 elog(DEBUG1, "AtCommit_Notify: notifying self");
491 NotifyMyFrontEnd(relname, listenerPID);
496 elog(DEBUG1, "AtCommit_Notify: notifying pid %d",
500 * If someone has already notified this listener, we don't
501 * bother modifying the table, but we do still send a SIGUSR2
502 * signal, just in case that backend missed the earlier signal
503 * for some reason. It's OK to send the signal first, because
504 * the other guy can't read pg_listener until we unlock it.
506 if (kill(listenerPID, SIGUSR2) < 0)
509 * Get rid of pg_listener entry if it refers to a PID that
510 * no longer exists. Presumably, that backend crashed
511 * without deleting its pg_listener entries. This code
512 * used to only delete the entry if errno==ESRCH, but as
513 * far as I can see we should just do it for any failure
514 * (certainly at least for EPERM too...)
516 simple_heap_delete(lRel, &lTuple->t_self);
518 else if (listener->notification == 0)
520 rTuple = heap_modifytuple(lTuple, lRel,
522 simple_heap_update(lRel, &lTuple->t_self, rTuple);
524 #ifdef NOT_USED /* currently there are no indexes */
525 CatalogUpdateIndexes(lRel, rTuple);
534 * We do NOT release the lock on pg_listener here; we need to hold it
535 * until end of transaction (which is about to happen, anyway) to
536 * ensure that notified backends see our tuple updates when they look.
537 * Else they might disregard the signal, which would make the
538 * application programmer very unhappy.
540 heap_close(lRel, NoLock);
542 ClearPendingNotifies();
545 elog(DEBUG1, "AtCommit_Notify: done");
549 *--------------------------------------------------------------
552 * This is called at transaction abort.
554 * Gets rid of pending outbound notifies that we would have executed
555 * if the transaction got committed.
560 *--------------------------------------------------------------
565 ClearPendingNotifies();
569 *--------------------------------------------------------------
570 * Async_NotifyHandler
572 * This is the signal handler for SIGUSR2.
574 * If we are idle (notifyInterruptEnabled is set), we can safely invoke
575 * ProcessIncomingNotify directly. Otherwise, just set a flag
583 *--------------------------------------------------------------
586 Async_NotifyHandler(SIGNAL_ARGS)
588 int save_errno = errno;
591 * Note: this is a SIGNAL HANDLER. You must be very wary what you do
592 * here. Some helpful soul had this routine sprinkled with TPRINTFs,
593 * which would likely lead to corruption of stdio buffers if they were
597 /* Don't joggle the elbow of proc_exit */
598 if (proc_exit_inprogress)
601 if (notifyInterruptEnabled)
603 bool save_ImmediateInterruptOK = ImmediateInterruptOK;
606 * We may be called while ImmediateInterruptOK is true; turn it
607 * off while messing with the NOTIFY state. (We would have to
608 * save and restore it anyway, because PGSemaphore operations
609 * inside ProcessIncomingNotify() might reset it.)
611 ImmediateInterruptOK = false;
614 * I'm not sure whether some flavors of Unix might allow another
615 * SIGUSR2 occurrence to recursively interrupt this routine. To
616 * cope with the possibility, we do the same sort of dance that
617 * EnableNotifyInterrupt must do --- see that routine for
620 notifyInterruptEnabled = 0; /* disable any recursive signal */
621 notifyInterruptOccurred = 1; /* do at least one iteration */
624 notifyInterruptEnabled = 1;
625 if (!notifyInterruptOccurred)
627 notifyInterruptEnabled = 0;
628 if (notifyInterruptOccurred)
630 /* Here, it is finally safe to do stuff. */
632 elog(DEBUG1, "Async_NotifyHandler: perform async notify");
634 ProcessIncomingNotify();
637 elog(DEBUG1, "Async_NotifyHandler: done");
642 * Restore ImmediateInterruptOK, and check for interrupts if
645 ImmediateInterruptOK = save_ImmediateInterruptOK;
646 if (save_ImmediateInterruptOK)
647 CHECK_FOR_INTERRUPTS();
652 * In this path it is NOT SAFE to do much of anything, except
655 notifyInterruptOccurred = 1;
662 * --------------------------------------------------------------
663 * EnableNotifyInterrupt
665 * This is called by the PostgresMain main loop just before waiting
666 * for a frontend command. If we are truly idle (ie, *not* inside
667 * a transaction block), then process any pending inbound notifies,
668 * and enable the signal handler to process future notifies directly.
670 * NOTE: the signal handler starts out disabled, and stays so until
671 * PostgresMain calls this the first time.
672 * --------------------------------------------------------------
675 EnableNotifyInterrupt(void)
677 if (CurrentTransactionState->blockState != TRANS_DEFAULT)
678 return; /* not really idle */
681 * This code is tricky because we are communicating with a signal
682 * handler that could interrupt us at any point. If we just checked
683 * notifyInterruptOccurred and then set notifyInterruptEnabled, we
684 * could fail to respond promptly to a signal that happens in between
685 * those two steps. (A very small time window, perhaps, but Murphy's
686 * Law says you can hit it...) Instead, we first set the enable flag,
687 * then test the occurred flag. If we see an unserviced interrupt has
688 * occurred, we re-clear the enable flag before going off to do the
689 * service work. (That prevents re-entrant invocation of
690 * ProcessIncomingNotify() if another interrupt occurs.) If an
691 * interrupt comes in between the setting and clearing of
692 * notifyInterruptEnabled, then it will have done the service work and
693 * left notifyInterruptOccurred zero, so we have to check again after
694 * clearing enable. The whole thing has to be in a loop in case
695 * another interrupt occurs while we're servicing the first. Once we
696 * get out of the loop, enable is set and we know there is no
697 * unserviced interrupt.
699 * NB: an overenthusiastic optimizing compiler could easily break this
700 * code. Hopefully, they all understand what "volatile" means these
705 notifyInterruptEnabled = 1;
706 if (!notifyInterruptOccurred)
708 notifyInterruptEnabled = 0;
709 if (notifyInterruptOccurred)
712 elog(DEBUG1, "EnableNotifyInterrupt: perform async notify");
714 ProcessIncomingNotify();
717 elog(DEBUG1, "EnableNotifyInterrupt: done");
723 * --------------------------------------------------------------
724 * DisableNotifyInterrupt
726 * This is called by the PostgresMain main loop just after receiving
727 * a frontend command. Signal handler execution of inbound notifies
728 * is disabled until the next EnableNotifyInterrupt call.
729 * --------------------------------------------------------------
732 DisableNotifyInterrupt(void)
734 notifyInterruptEnabled = 0;
738 * --------------------------------------------------------------
739 * ProcessIncomingNotify
741 * Deal with arriving NOTIFYs from other backends.
742 * This is called either directly from the SIGUSR2 signal handler,
743 * or the next time control reaches the outer idle loop.
744 * Scan pg_listener for arriving notifies, report them to my front end,
745 * and clear the notification field in pg_listener until next time.
747 * NOTE: since we are outside any transaction, we must create our own.
752 * --------------------------------------------------------------
755 ProcessIncomingNotify(void)
763 Datum value[Natts_pg_listener];
764 char repl[Natts_pg_listener],
765 nulls[Natts_pg_listener];
768 elog(DEBUG1, "ProcessIncomingNotify");
770 set_ps_display("async_notify");
772 notifyInterruptOccurred = 0;
774 StartTransactionCommand();
776 lRel = heap_openr(ListenerRelationName, AccessExclusiveLock);
777 tdesc = RelationGetDescr(lRel);
779 /* Scan only entries with my listenerPID */
780 ScanKeyEntryInitialize(&key[0], 0,
781 Anum_pg_listener_pid,
783 Int32GetDatum(MyProcPid));
784 scan = heap_beginscan(lRel, SnapshotNow, 1, key);
786 /* Prepare data for rewriting 0 into notification field */
787 nulls[0] = nulls[1] = nulls[2] = ' ';
788 repl[0] = repl[1] = repl[2] = ' ';
789 repl[Anum_pg_listener_notify - 1] = 'r';
790 value[0] = value[1] = value[2] = (Datum) 0;
791 value[Anum_pg_listener_notify - 1] = Int32GetDatum(0);
793 while ((lTuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
795 Form_pg_listener listener = (Form_pg_listener) GETSTRUCT(lTuple);
796 char *relname = NameStr(listener->relname);
797 int32 sourcePID = listener->notification;
801 /* Notify the frontend */
804 elog(DEBUG1, "ProcessIncomingNotify: received %s from %d",
805 relname, (int) sourcePID);
807 NotifyMyFrontEnd(relname, sourcePID);
808 /* Rewrite the tuple with 0 in notification column */
809 rTuple = heap_modifytuple(lTuple, lRel, value, nulls, repl);
810 simple_heap_update(lRel, &lTuple->t_self, rTuple);
812 #ifdef NOT_USED /* currently there are no indexes */
813 CatalogUpdateIndexes(lRel, rTuple);
820 * We do NOT release the lock on pg_listener here; we need to hold it
821 * until end of transaction (which is about to happen, anyway) to
822 * ensure that other backends see our tuple updates when they look.
823 * Otherwise, a transaction started after this one might mistakenly
824 * think it doesn't need to send this backend a new NOTIFY.
826 heap_close(lRel, NoLock);
828 CommitTransactionCommand();
831 * Must flush the notify messages to ensure frontend gets them
836 set_ps_display("idle");
839 elog(DEBUG1, "ProcessIncomingNotify: done");
843 * Send NOTIFY message to my front end.
846 NotifyMyFrontEnd(char *relname, int32 listenerPID)
848 if (whereToSendOutput == Remote)
852 pq_beginmessage(&buf, 'A');
853 pq_sendint(&buf, listenerPID, sizeof(int32));
854 pq_sendstring(&buf, relname);
855 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
857 /* XXX Add parameter string here later */
858 pq_sendstring(&buf, "");
863 * NOTE: we do not do pq_flush() here. For a self-notify, it will
864 * happen at the end of the transaction, and for incoming notifies
865 * ProcessIncomingNotify will do it after finding all the
870 elog(INFO, "NOTIFY for %s", relname);
873 /* Does pendingNotifies include the given relname? */
875 AsyncExistsPendingNotify(const char *relname)
879 foreach(p, pendingNotifies)
881 /* Use NAMEDATALEN for relname comparison. DZ - 26-08-1996 */
882 if (strncmp((const char *) lfirst(p), relname, NAMEDATALEN) == 0)
889 /* Clear the pendingNotifies list. */
891 ClearPendingNotifies(void)
894 * We used to have to explicitly deallocate the list members and
895 * nodes, because they were malloc'd. Now, since we know they are
896 * palloc'd in TopTransactionContext, we need not do that --- they'll
897 * go away automatically at transaction exit. We need only reset the
900 pendingNotifies = NIL;