1 /*-------------------------------------------------------------------------
4 * Asynchronous notification: NOTIFY, LISTEN, UNLISTEN
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
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 * Like NOTIFY, LISTEN and UNLISTEN just add the desired action to a list
56 * of pending actions. If we reach transaction commit, the changes are
57 * applied to pg_listener just before executing any pending NOTIFYs. This
58 * method is necessary because to avoid race conditions, we must hold lock
59 * on pg_listener from when we insert a new listener tuple until we commit.
60 * To do that and not create undue hazard of deadlock, we don't want to
61 * touch pg_listener until we are otherwise done with the transaction;
62 * in particular it'd be uncool to still be taking user-commanded locks
63 * while holding the pg_listener lock.
65 * Although we grab ExclusiveLock on pg_listener for any operation,
66 * the lock is never held very long, so it shouldn't cause too much of
67 * a performance problem. (Previously we used AccessExclusiveLock, but
68 * there's no real reason to forbid concurrent reads.)
70 * An application that listens on the same relname it notifies will get
71 * NOTIFY messages for its own NOTIFYs. These can be ignored, if not useful,
72 * by comparing be_pid in the NOTIFY message to the application's own backend's
73 * PID. (As of FE/BE protocol 2.0, the backend's PID is provided to the
74 * frontend during startup.) The above design guarantees that notifies from
75 * other backends will never be missed by ignoring self-notifies. Note,
76 * however, that we do *not* guarantee that a separate frontend message will
77 * be sent for every outside NOTIFY. Since there is only room for one
78 * originating PID in pg_listener, outside notifies occurring at about the
79 * same time may be collapsed into a single message bearing the PID of the
80 * first outside backend to perform the NOTIFY.
81 *-------------------------------------------------------------------------
89 #include "access/heapam.h"
90 #include "access/twophase_rmgr.h"
91 #include "access/xact.h"
92 #include "catalog/pg_listener.h"
93 #include "commands/async.h"
94 #include "libpq/libpq.h"
95 #include "libpq/pqformat.h"
96 #include "miscadmin.h"
97 #include "storage/ipc.h"
98 #include "storage/sinval.h"
99 #include "tcop/tcopprot.h"
100 #include "utils/builtins.h"
101 #include "utils/fmgroids.h"
102 #include "utils/memutils.h"
103 #include "utils/ps_status.h"
104 #include "utils/tqual.h"
108 * State for pending LISTEN/UNLISTEN actions consists of an ordered list of
109 * all actions requested in the current transaction. As explained above,
110 * we don't actually modify pg_listener until we reach transaction commit.
112 * The list is kept in CurTransactionContext. In subtransactions, each
113 * subtransaction has its own list in its own CurTransactionContext, but
114 * successful subtransactions attach their lists to their parent's list.
115 * Failed subtransactions simply discard their lists.
126 ListenActionKind action
;
127 char condname
[1]; /* actually, as long as needed */
130 static List
*pendingActions
= NIL
; /* list of ListenAction */
132 static List
*upperPendingActions
= NIL
; /* list of upper-xact lists */
135 * State for outbound notifies consists of a list of all relnames NOTIFYed
136 * in the current transaction. We do not actually perform a NOTIFY until
137 * and unless the transaction commits. pendingNotifies is NIL if no
138 * NOTIFYs have been done in the current transaction.
140 * The list is kept in CurTransactionContext. In subtransactions, each
141 * subtransaction has its own list in its own CurTransactionContext, but
142 * successful subtransactions attach their lists to their parent's list.
143 * Failed subtransactions simply discard their lists.
145 * Note: the action and notify lists do not interact within a transaction.
146 * In particular, if a transaction does NOTIFY and then LISTEN on the same
147 * condition name, it will get a self-notify at commit. This is a bit odd
148 * but is consistent with our historical behavior.
150 static List
*pendingNotifies
= NIL
; /* list of C strings */
152 static List
*upperPendingNotifies
= NIL
; /* list of upper-xact lists */
155 * State for inbound notifies consists of two flags: one saying whether
156 * the signal handler is currently allowed to call ProcessIncomingNotify
157 * directly, and one saying whether the signal has occurred but the handler
158 * was not allowed to call ProcessIncomingNotify at the time.
160 * NB: the "volatile" on these declarations is critical! If your compiler
161 * does not grok "volatile", you'd be best advised to compile this file
162 * with all optimization turned off.
164 static volatile sig_atomic_t notifyInterruptEnabled
= 0;
165 static volatile sig_atomic_t notifyInterruptOccurred
= 0;
167 /* True if we've registered an on_shmem_exit cleanup */
168 static bool unlistenExitRegistered
= false;
170 bool Trace_notify
= false;
173 static void queue_listen(ListenActionKind action
, const char *condname
);
174 static void Async_UnlistenOnExit(int code
, Datum arg
);
175 static void Exec_Listen(Relation lRel
, const char *relname
);
176 static void Exec_Unlisten(Relation lRel
, const char *relname
);
177 static void Exec_UnlistenAll(Relation lRel
);
178 static void Send_Notify(Relation lRel
);
179 static void ProcessIncomingNotify(void);
180 static void NotifyMyFrontEnd(char *relname
, int32 listenerPID
);
181 static bool AsyncExistsPendingNotify(const char *relname
);
182 static void ClearPendingActionsAndNotifies(void);
188 * This is executed by the SQL notify command.
190 * Adds the relation to the list of pending notifies.
191 * Actual notification happens during transaction commit.
192 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
195 Async_Notify(const char *relname
)
198 elog(DEBUG1
, "Async_Notify(%s)", relname
);
200 /* no point in making duplicate entries in the list ... */
201 if (!AsyncExistsPendingNotify(relname
))
204 * The name list needs to live until end of transaction, so store it
205 * in the transaction context.
207 MemoryContext oldcontext
;
209 oldcontext
= MemoryContextSwitchTo(CurTransactionContext
);
212 * Ordering of the list isn't important. We choose to put new
213 * entries on the front, as this might make duplicate-elimination
214 * a tad faster when the same condition is signaled many times in
217 pendingNotifies
= lcons(pstrdup(relname
), pendingNotifies
);
219 MemoryContextSwitchTo(oldcontext
);
225 * Common code for listen, unlisten, unlisten all commands.
227 * Adds the request to the list of pending actions.
228 * Actual update of pg_listener happens during transaction commit.
229 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
232 queue_listen(ListenActionKind action
, const char *condname
)
234 MemoryContext oldcontext
;
235 ListenAction
*actrec
;
238 * Unlike Async_Notify, we don't try to collapse out duplicates.
239 * It would be too complicated to ensure we get the right interactions
240 * of conflicting LISTEN/UNLISTEN/UNLISTEN_ALL, and it's unlikely that
241 * there would be any performance benefit anyway in sane applications.
243 oldcontext
= MemoryContextSwitchTo(CurTransactionContext
);
245 /* space for terminating null is included in sizeof(ListenAction) */
246 actrec
= (ListenAction
*) palloc(sizeof(ListenAction
) + strlen(condname
));
247 actrec
->action
= action
;
248 strcpy(actrec
->condname
, condname
);
250 pendingActions
= lappend(pendingActions
, actrec
);
252 MemoryContextSwitchTo(oldcontext
);
258 * This is executed by the SQL listen command.
261 Async_Listen(const char *relname
)
264 elog(DEBUG1
, "Async_Listen(%s,%d)", relname
, MyProcPid
);
266 queue_listen(LISTEN_LISTEN
, relname
);
272 * This is executed by the SQL unlisten command.
275 Async_Unlisten(const char *relname
)
278 elog(DEBUG1
, "Async_Unlisten(%s,%d)", relname
, MyProcPid
);
280 queue_listen(LISTEN_UNLISTEN
, relname
);
286 * This is invoked by UNLISTEN * command, and also at backend exit.
289 Async_UnlistenAll(void)
292 elog(DEBUG1
, "Async_UnlistenAll(%d)", MyProcPid
);
294 queue_listen(LISTEN_UNLISTEN_ALL
, "");
298 * Async_UnlistenOnExit
300 * Clean up the pg_listener table at backend exit.
302 * This is executed if we have done any LISTENs in this backend.
303 * It might not be necessary anymore, if the user UNLISTENed everything,
304 * but we don't try to detect that case.
307 Async_UnlistenOnExit(int code
, Datum arg
)
310 * We need to start/commit a transaction for the unlisten, but if there is
311 * already an active transaction we had better abort that one first.
312 * Otherwise we'd end up committing changes that probably ought to be
315 AbortOutOfAnyTransaction();
316 /* Now we can do the unlisten */
317 StartTransactionCommand();
319 CommitTransactionCommand();
325 * This is called at the prepare phase of a two-phase
326 * transaction. Save the state for possible commit later.
329 AtPrepare_Notify(void)
333 /* It's not sensible to have any pending LISTEN/UNLISTEN actions */
336 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
337 errmsg("cannot PREPARE a transaction that has executed LISTEN or UNLISTEN")));
339 /* We can deal with pending NOTIFY though */
340 foreach(p
, pendingNotifies
)
342 const char *relname
= (const char *) lfirst(p
);
344 RegisterTwoPhaseRecord(TWOPHASE_RM_NOTIFY_ID
, 0,
345 relname
, strlen(relname
) + 1);
349 * We can clear the state immediately, rather than needing a separate
350 * PostPrepare call, because if the transaction fails we'd just discard
353 ClearPendingActionsAndNotifies();
359 * This is called at transaction commit.
361 * If there are pending LISTEN/UNLISTEN actions, insert or delete
362 * tuples in pg_listener accordingly.
364 * If there are outbound notify requests in the pendingNotifies list,
365 * scan pg_listener for matching tuples, and either signal the other
366 * backend or send a message to our own frontend.
368 * NOTE: we are still inside the current transaction, therefore can
369 * piggyback on its committing of changes.
372 AtCommit_Notify(void)
377 if (pendingActions
== NIL
&& pendingNotifies
== NIL
)
378 return; /* no relevant statements in this xact */
381 * NOTIFY is disabled if not normal processing mode. This test used to be
382 * in xact.c, but it seems cleaner to do it here.
384 if (!IsNormalProcessingMode())
386 ClearPendingActionsAndNotifies();
391 elog(DEBUG1
, "AtCommit_Notify");
393 /* Acquire ExclusiveLock on pg_listener */
394 lRel
= heap_open(ListenerRelationId
, ExclusiveLock
);
396 /* Perform any pending listen/unlisten actions */
397 foreach(p
, pendingActions
)
399 ListenAction
*actrec
= (ListenAction
*) lfirst(p
);
401 switch (actrec
->action
)
404 Exec_Listen(lRel
, actrec
->condname
);
406 case LISTEN_UNLISTEN
:
407 Exec_Unlisten(lRel
, actrec
->condname
);
409 case LISTEN_UNLISTEN_ALL
:
410 Exec_UnlistenAll(lRel
);
414 /* We must CCI after each action in case of conflicting actions */
415 CommandCounterIncrement();
418 /* Perform any pending notifies */
423 * We do NOT release the lock on pg_listener here; we need to hold it
424 * until end of transaction (which is about to happen, anyway) to ensure
425 * that notified backends see our tuple updates when they look. Else they
426 * might disregard the signal, which would make the application programmer
427 * very unhappy. Also, this prevents race conditions when we have just
428 * inserted a listening tuple.
430 heap_close(lRel
, NoLock
);
432 ClearPendingActionsAndNotifies();
435 elog(DEBUG1
, "AtCommit_Notify: done");
439 * Exec_Listen --- subroutine for AtCommit_Notify
441 * Register the current backend as listening on the specified relation.
444 Exec_Listen(Relation lRel
, const char *relname
)
448 Datum values
[Natts_pg_listener
];
449 char nulls
[Natts_pg_listener
];
451 bool alreadyListener
= false;
454 elog(DEBUG1
, "Exec_Listen(%s,%d)", relname
, MyProcPid
);
456 /* Detect whether we are already listening on this relname */
457 scan
= heap_beginscan(lRel
, SnapshotNow
, 0, NULL
);
458 while ((tuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
460 Form_pg_listener listener
= (Form_pg_listener
) GETSTRUCT(tuple
);
462 if (listener
->listenerpid
== MyProcPid
&&
463 strncmp(NameStr(listener
->relname
), relname
, NAMEDATALEN
) == 0)
465 alreadyListener
= true;
466 /* No need to scan the rest of the table */
476 * OK to insert a new tuple
478 memset(nulls
, ' ', sizeof(nulls
));
480 namestrcpy(&condname
, relname
);
481 values
[Anum_pg_listener_relname
- 1] = NameGetDatum(&condname
);
482 values
[Anum_pg_listener_pid
- 1] = Int32GetDatum(MyProcPid
);
483 values
[Anum_pg_listener_notify
- 1] = Int32GetDatum(0); /* no notifies pending */
485 tuple
= heap_formtuple(RelationGetDescr(lRel
), values
, nulls
);
487 simple_heap_insert(lRel
, tuple
);
489 #ifdef NOT_USED /* currently there are no indexes */
490 CatalogUpdateIndexes(lRel
, tuple
);
493 heap_freetuple(tuple
);
496 * now that we are listening, make sure we will unlisten before dying.
498 if (!unlistenExitRegistered
)
500 on_shmem_exit(Async_UnlistenOnExit
, 0);
501 unlistenExitRegistered
= true;
506 * Exec_Unlisten --- subroutine for AtCommit_Notify
508 * Remove the current backend from the list of listening backends
509 * for the specified relation.
512 Exec_Unlisten(Relation lRel
, const char *relname
)
518 elog(DEBUG1
, "Exec_Unlisten(%s,%d)", relname
, MyProcPid
);
520 scan
= heap_beginscan(lRel
, SnapshotNow
, 0, NULL
);
521 while ((tuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
523 Form_pg_listener listener
= (Form_pg_listener
) GETSTRUCT(tuple
);
525 if (listener
->listenerpid
== MyProcPid
&&
526 strncmp(NameStr(listener
->relname
), relname
, NAMEDATALEN
) == 0)
528 /* Found the matching tuple, delete it */
529 simple_heap_delete(lRel
, &tuple
->t_self
);
532 * We assume there can be only one match, so no need to scan the
541 * We do not complain about unlistening something not being listened;
547 * Exec_UnlistenAll --- subroutine for AtCommit_Notify
549 * Update pg_listener to unlisten all relations for this backend.
552 Exec_UnlistenAll(Relation lRel
)
559 elog(DEBUG1
, "Exec_UnlistenAll");
561 /* Find and delete all entries with my listenerPID */
563 Anum_pg_listener_pid
,
564 BTEqualStrategyNumber
, F_INT4EQ
,
565 Int32GetDatum(MyProcPid
));
566 scan
= heap_beginscan(lRel
, SnapshotNow
, 1, key
);
568 while ((lTuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
569 simple_heap_delete(lRel
, &lTuple
->t_self
);
575 * Send_Notify --- subroutine for AtCommit_Notify
577 * Scan pg_listener for tuples matching our pending notifies, and
578 * either signal the other backend or send a message to our own frontend.
581 Send_Notify(Relation lRel
)
583 TupleDesc tdesc
= RelationGetDescr(lRel
);
587 Datum value
[Natts_pg_listener
];
588 char repl
[Natts_pg_listener
],
589 nulls
[Natts_pg_listener
];
591 /* preset data to update notify column to MyProcPid */
592 nulls
[0] = nulls
[1] = nulls
[2] = ' ';
593 repl
[0] = repl
[1] = repl
[2] = ' ';
594 repl
[Anum_pg_listener_notify
- 1] = 'r';
595 value
[0] = value
[1] = value
[2] = (Datum
) 0;
596 value
[Anum_pg_listener_notify
- 1] = Int32GetDatum(MyProcPid
);
598 scan
= heap_beginscan(lRel
, SnapshotNow
, 0, NULL
);
600 while ((lTuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
602 Form_pg_listener listener
= (Form_pg_listener
) GETSTRUCT(lTuple
);
603 char *relname
= NameStr(listener
->relname
);
604 int32 listenerPID
= listener
->listenerpid
;
606 if (!AsyncExistsPendingNotify(relname
))
609 if (listenerPID
== MyProcPid
)
612 * Self-notify: no need to bother with table update. Indeed, we
613 * *must not* clear the notification field in this path, or we
614 * could lose an outside notify, which'd be bad for applications
615 * that ignore self-notify messages.
618 elog(DEBUG1
, "AtCommit_Notify: notifying self");
620 NotifyMyFrontEnd(relname
, listenerPID
);
625 elog(DEBUG1
, "AtCommit_Notify: notifying pid %d",
629 * If someone has already notified this listener, we don't bother
630 * modifying the table, but we do still send a SIGUSR2 signal,
631 * just in case that backend missed the earlier signal for some
632 * reason. It's OK to send the signal first, because the other
633 * guy can't read pg_listener until we unlock it.
635 if (kill(listenerPID
, SIGUSR2
) < 0)
638 * Get rid of pg_listener entry if it refers to a PID that no
639 * longer exists. Presumably, that backend crashed without
640 * deleting its pg_listener entries. This code used to only
641 * delete the entry if errno==ESRCH, but as far as I can see
642 * we should just do it for any failure (certainly at least
645 simple_heap_delete(lRel
, &lTuple
->t_self
);
647 else if (listener
->notification
== 0)
649 /* Rewrite the tuple with my PID in notification column */
650 rTuple
= heap_modifytuple(lTuple
, tdesc
, value
, nulls
, repl
);
651 simple_heap_update(lRel
, &lTuple
->t_self
, rTuple
);
653 #ifdef NOT_USED /* currently there are no indexes */
654 CatalogUpdateIndexes(lRel
, rTuple
);
666 * This is called at transaction abort.
668 * Gets rid of pending actions and outbound notifies that we would have
669 * executed if the transaction got committed.
674 ClearPendingActionsAndNotifies();
678 * AtSubStart_Notify() --- Take care of subtransaction start.
680 * Push empty state for the new subtransaction.
683 AtSubStart_Notify(void)
685 MemoryContext old_cxt
;
687 /* Keep the list-of-lists in TopTransactionContext for simplicity */
688 old_cxt
= MemoryContextSwitchTo(TopTransactionContext
);
690 upperPendingActions
= lcons(pendingActions
, upperPendingActions
);
692 Assert(list_length(upperPendingActions
) ==
693 GetCurrentTransactionNestLevel() - 1);
695 pendingActions
= NIL
;
697 upperPendingNotifies
= lcons(pendingNotifies
, upperPendingNotifies
);
699 Assert(list_length(upperPendingNotifies
) ==
700 GetCurrentTransactionNestLevel() - 1);
702 pendingNotifies
= NIL
;
704 MemoryContextSwitchTo(old_cxt
);
708 * AtSubCommit_Notify() --- Take care of subtransaction commit.
710 * Reassign all items in the pending lists to the parent transaction.
713 AtSubCommit_Notify(void)
715 List
*parentPendingActions
;
716 List
*parentPendingNotifies
;
718 parentPendingActions
= (List
*) linitial(upperPendingActions
);
719 upperPendingActions
= list_delete_first(upperPendingActions
);
721 Assert(list_length(upperPendingActions
) ==
722 GetCurrentTransactionNestLevel() - 2);
725 * Mustn't try to eliminate duplicates here --- see queue_listen()
727 pendingActions
= list_concat(parentPendingActions
, pendingActions
);
729 parentPendingNotifies
= (List
*) linitial(upperPendingNotifies
);
730 upperPendingNotifies
= list_delete_first(upperPendingNotifies
);
732 Assert(list_length(upperPendingNotifies
) ==
733 GetCurrentTransactionNestLevel() - 2);
736 * We could try to eliminate duplicates here, but it seems not worthwhile.
738 pendingNotifies
= list_concat(parentPendingNotifies
, pendingNotifies
);
742 * AtSubAbort_Notify() --- Take care of subtransaction abort.
745 AtSubAbort_Notify(void)
747 int my_level
= GetCurrentTransactionNestLevel();
750 * All we have to do is pop the stack --- the actions/notifies made in this
751 * subxact are no longer interesting, and the space will be freed when
752 * CurTransactionContext is recycled.
754 * This routine could be called more than once at a given nesting level if
755 * there is trouble during subxact abort. Avoid dumping core by using
756 * GetCurrentTransactionNestLevel as the indicator of how far we need to
759 while (list_length(upperPendingActions
) > my_level
- 2)
761 pendingActions
= (List
*) linitial(upperPendingActions
);
762 upperPendingActions
= list_delete_first(upperPendingActions
);
765 while (list_length(upperPendingNotifies
) > my_level
- 2)
767 pendingNotifies
= (List
*) linitial(upperPendingNotifies
);
768 upperPendingNotifies
= list_delete_first(upperPendingNotifies
);
773 * NotifyInterruptHandler
775 * This is the signal handler for SIGUSR2.
777 * If we are idle (notifyInterruptEnabled is set), we can safely invoke
778 * ProcessIncomingNotify directly. Otherwise, just set a flag
782 NotifyInterruptHandler(SIGNAL_ARGS
)
784 int save_errno
= errno
;
787 * Note: this is a SIGNAL HANDLER. You must be very wary what you do
788 * here. Some helpful soul had this routine sprinkled with TPRINTFs, which
789 * would likely lead to corruption of stdio buffers if they were ever
793 /* Don't joggle the elbow of proc_exit */
794 if (proc_exit_inprogress
)
797 if (notifyInterruptEnabled
)
799 bool save_ImmediateInterruptOK
= ImmediateInterruptOK
;
802 * We may be called while ImmediateInterruptOK is true; turn it off
803 * while messing with the NOTIFY state. (We would have to save and
804 * restore it anyway, because PGSemaphore operations inside
805 * ProcessIncomingNotify() might reset it.)
807 ImmediateInterruptOK
= false;
810 * I'm not sure whether some flavors of Unix might allow another
811 * SIGUSR2 occurrence to recursively interrupt this routine. To cope
812 * with the possibility, we do the same sort of dance that
813 * EnableNotifyInterrupt must do --- see that routine for comments.
815 notifyInterruptEnabled
= 0; /* disable any recursive signal */
816 notifyInterruptOccurred
= 1; /* do at least one iteration */
819 notifyInterruptEnabled
= 1;
820 if (!notifyInterruptOccurred
)
822 notifyInterruptEnabled
= 0;
823 if (notifyInterruptOccurred
)
825 /* Here, it is finally safe to do stuff. */
827 elog(DEBUG1
, "NotifyInterruptHandler: perform async notify");
829 ProcessIncomingNotify();
832 elog(DEBUG1
, "NotifyInterruptHandler: done");
837 * Restore ImmediateInterruptOK, and check for interrupts if needed.
839 ImmediateInterruptOK
= save_ImmediateInterruptOK
;
840 if (save_ImmediateInterruptOK
)
841 CHECK_FOR_INTERRUPTS();
846 * In this path it is NOT SAFE to do much of anything, except this:
848 notifyInterruptOccurred
= 1;
855 * EnableNotifyInterrupt
857 * This is called by the PostgresMain main loop just before waiting
858 * for a frontend command. If we are truly idle (ie, *not* inside
859 * a transaction block), then process any pending inbound notifies,
860 * and enable the signal handler to process future notifies directly.
862 * NOTE: the signal handler starts out disabled, and stays so until
863 * PostgresMain calls this the first time.
866 EnableNotifyInterrupt(void)
868 if (IsTransactionOrTransactionBlock())
869 return; /* not really idle */
872 * This code is tricky because we are communicating with a signal handler
873 * that could interrupt us at any point. If we just checked
874 * notifyInterruptOccurred and then set notifyInterruptEnabled, we could
875 * fail to respond promptly to a signal that happens in between those two
876 * steps. (A very small time window, perhaps, but Murphy's Law says you
877 * can hit it...) Instead, we first set the enable flag, then test the
878 * occurred flag. If we see an unserviced interrupt has occurred, we
879 * re-clear the enable flag before going off to do the service work. (That
880 * prevents re-entrant invocation of ProcessIncomingNotify() if another
881 * interrupt occurs.) If an interrupt comes in between the setting and
882 * clearing of notifyInterruptEnabled, then it will have done the service
883 * work and left notifyInterruptOccurred zero, so we have to check again
884 * after clearing enable. The whole thing has to be in a loop in case
885 * another interrupt occurs while we're servicing the first. Once we get
886 * out of the loop, enable is set and we know there is no unserviced
889 * NB: an overenthusiastic optimizing compiler could easily break this
890 * code. Hopefully, they all understand what "volatile" means these days.
894 notifyInterruptEnabled
= 1;
895 if (!notifyInterruptOccurred
)
897 notifyInterruptEnabled
= 0;
898 if (notifyInterruptOccurred
)
901 elog(DEBUG1
, "EnableNotifyInterrupt: perform async notify");
903 ProcessIncomingNotify();
906 elog(DEBUG1
, "EnableNotifyInterrupt: done");
912 * DisableNotifyInterrupt
914 * This is called by the PostgresMain main loop just after receiving
915 * a frontend command. Signal handler execution of inbound notifies
916 * is disabled until the next EnableNotifyInterrupt call.
918 * The SIGUSR1 signal handler also needs to call this, so as to
919 * prevent conflicts if one signal interrupts the other. So we
920 * must return the previous state of the flag.
923 DisableNotifyInterrupt(void)
925 bool result
= (notifyInterruptEnabled
!= 0);
927 notifyInterruptEnabled
= 0;
933 * ProcessIncomingNotify
935 * Deal with arriving NOTIFYs from other backends.
936 * This is called either directly from the SIGUSR2 signal handler,
937 * or the next time control reaches the outer idle loop.
938 * Scan pg_listener for arriving notifies, report them to my front end,
939 * and clear the notification field in pg_listener until next time.
941 * NOTE: since we are outside any transaction, we must create our own.
944 ProcessIncomingNotify(void)
952 Datum value
[Natts_pg_listener
];
953 char repl
[Natts_pg_listener
],
954 nulls
[Natts_pg_listener
];
955 bool catchup_enabled
;
957 /* Must prevent SIGUSR1 interrupt while I am running */
958 catchup_enabled
= DisableCatchupInterrupt();
961 elog(DEBUG1
, "ProcessIncomingNotify");
963 set_ps_display("notify interrupt", false);
965 notifyInterruptOccurred
= 0;
967 StartTransactionCommand();
969 lRel
= heap_open(ListenerRelationId
, ExclusiveLock
);
970 tdesc
= RelationGetDescr(lRel
);
972 /* Scan only entries with my listenerPID */
974 Anum_pg_listener_pid
,
975 BTEqualStrategyNumber
, F_INT4EQ
,
976 Int32GetDatum(MyProcPid
));
977 scan
= heap_beginscan(lRel
, SnapshotNow
, 1, key
);
979 /* Prepare data for rewriting 0 into notification field */
980 nulls
[0] = nulls
[1] = nulls
[2] = ' ';
981 repl
[0] = repl
[1] = repl
[2] = ' ';
982 repl
[Anum_pg_listener_notify
- 1] = 'r';
983 value
[0] = value
[1] = value
[2] = (Datum
) 0;
984 value
[Anum_pg_listener_notify
- 1] = Int32GetDatum(0);
986 while ((lTuple
= heap_getnext(scan
, ForwardScanDirection
)) != NULL
)
988 Form_pg_listener listener
= (Form_pg_listener
) GETSTRUCT(lTuple
);
989 char *relname
= NameStr(listener
->relname
);
990 int32 sourcePID
= listener
->notification
;
994 /* Notify the frontend */
997 elog(DEBUG1
, "ProcessIncomingNotify: received %s from %d",
998 relname
, (int) sourcePID
);
1000 NotifyMyFrontEnd(relname
, sourcePID
);
1003 * Rewrite the tuple with 0 in notification column.
1005 rTuple
= heap_modifytuple(lTuple
, tdesc
, value
, nulls
, repl
);
1006 simple_heap_update(lRel
, &lTuple
->t_self
, rTuple
);
1008 #ifdef NOT_USED /* currently there are no indexes */
1009 CatalogUpdateIndexes(lRel
, rTuple
);
1016 * We do NOT release the lock on pg_listener here; we need to hold it
1017 * until end of transaction (which is about to happen, anyway) to ensure
1018 * that other backends see our tuple updates when they look. Otherwise, a
1019 * transaction started after this one might mistakenly think it doesn't
1020 * need to send this backend a new NOTIFY.
1022 heap_close(lRel
, NoLock
);
1024 CommitTransactionCommand();
1027 * Must flush the notify messages to ensure frontend gets them promptly.
1031 set_ps_display("idle", false);
1034 elog(DEBUG1
, "ProcessIncomingNotify: done");
1036 if (catchup_enabled
)
1037 EnableCatchupInterrupt();
1041 * Send NOTIFY message to my front end.
1044 NotifyMyFrontEnd(char *relname
, int32 listenerPID
)
1046 if (whereToSendOutput
== DestRemote
)
1050 pq_beginmessage(&buf
, 'A');
1051 pq_sendint(&buf
, listenerPID
, sizeof(int32
));
1052 pq_sendstring(&buf
, relname
);
1053 if (PG_PROTOCOL_MAJOR(FrontendProtocol
) >= 3)
1055 /* XXX Add parameter string here later */
1056 pq_sendstring(&buf
, "");
1058 pq_endmessage(&buf
);
1061 * NOTE: we do not do pq_flush() here. For a self-notify, it will
1062 * happen at the end of the transaction, and for incoming notifies
1063 * ProcessIncomingNotify will do it after finding all the notifies.
1067 elog(INFO
, "NOTIFY for %s", relname
);
1070 /* Does pendingNotifies include the given relname? */
1072 AsyncExistsPendingNotify(const char *relname
)
1076 foreach(p
, pendingNotifies
)
1078 const char *prelname
= (const char *) lfirst(p
);
1080 if (strcmp(prelname
, relname
) == 0)
1087 /* Clear the pendingActions and pendingNotifies lists. */
1089 ClearPendingActionsAndNotifies(void)
1092 * We used to have to explicitly deallocate the list members and nodes,
1093 * because they were malloc'd. Now, since we know they are palloc'd in
1094 * CurTransactionContext, we need not do that --- they'll go away
1095 * automatically at transaction exit. We need only reset the list head
1098 pendingActions
= NIL
;
1099 pendingNotifies
= NIL
;
1103 * 2PC processing routine for COMMIT PREPARED case.
1105 * (We don't have to do anything for ROLLBACK PREPARED.)
1108 notify_twophase_postcommit(TransactionId xid
, uint16 info
,
1109 void *recdata
, uint32 len
)
1112 * Set up to issue the NOTIFY at the end of my own current transaction.
1113 * (XXX this has some issues if my own transaction later rolls back, or if
1114 * there is any significant delay before I commit. OK for now because we
1115 * disallow COMMIT PREPARED inside a transaction block.)
1117 Async_Notify((char *) recdata
);