1 /*-------------------------------------------------------------------------
4 * Asynchronous notification: NOTIFY, LISTEN, UNLISTEN
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/commands/async.c
12 *-------------------------------------------------------------------------
15 /*-------------------------------------------------------------------------
16 * Async Notification Model as of 9.0:
18 * 1. Multiple backends on same machine. Multiple backends listening on
19 * several channels. (Channels are also called "conditions" in other
22 * 2. There is one central queue in disk-based storage (directory pg_notify/),
23 * with actively-used pages mapped into shared memory by the slru.c module.
24 * All notification messages are placed in the queue and later read out
25 * by listening backends.
27 * There is no central knowledge of which backend listens on which channel;
28 * every backend has its own list of interesting channels.
30 * Although there is only one queue, notifications are treated as being
31 * database-local; this is done by including the sender's database OID
32 * in each notification message. Listening backends ignore messages
33 * that don't match their database OID. This is important because it
34 * ensures senders and receivers have the same database encoding and won't
35 * misinterpret non-ASCII text in the channel name or payload string.
37 * Since notifications are not expected to survive database crashes,
38 * we can simply clean out the pg_notify data at any reboot, and there
39 * is no need for WAL support or fsync'ing.
41 * 3. Every backend that is listening on at least one channel registers by
42 * entering its PID into the array in AsyncQueueControl. It then scans all
43 * incoming notifications in the central queue and first compares the
44 * database OID of the notification with its own database OID and then
45 * compares the notified channel with the list of channels that it listens
46 * to. In case there is a match it delivers the notification event to its
47 * frontend. Non-matching events are simply skipped.
49 * 4. The NOTIFY statement (routine Async_Notify) stores the notification in
50 * a backend-local list which will not be processed until transaction end.
52 * Duplicate notifications from the same transaction are sent out as one
53 * notification only. This is done to save work when for example a trigger
54 * on a 2 million row table fires a notification for each row that has been
55 * changed. If the application needs to receive every single notification
56 * that has been sent, it can easily add some unique string into the extra
59 * When the transaction is ready to commit, PreCommit_Notify() adds the
60 * pending notifications to the head of the queue. The head pointer of the
61 * queue always points to the next free position and a position is just a
62 * page number and the offset in that page. This is done before marking the
63 * transaction as committed in clog. If we run into problems writing the
64 * notifications, we can still call elog(ERROR, ...) and the transaction
67 * Once we have put all of the notifications into the queue, we return to
68 * CommitTransaction() which will then do the actual transaction commit.
70 * After commit we are called another time (AtCommit_Notify()). Here we
71 * make the actual updates to the effective listen state (listenChannels).
73 * Finally, after we are out of the transaction altogether, we check if
74 * we need to signal listening backends. In SignalBackends() we scan the
75 * list of listening backends and send a PROCSIG_NOTIFY_INTERRUPT signal
76 * to every listening backend (we don't know which backend is listening on
77 * which channel so we must signal them all). We can exclude backends that
78 * are already up to date, though. We don't bother with a self-signal
79 * either, but just process the queue directly.
81 * 5. Upon receipt of a PROCSIG_NOTIFY_INTERRUPT signal, the signal handler
82 * can call inbound-notify processing immediately if this backend is idle
83 * (ie, it is waiting for a frontend command and is not within a transaction
84 * block). Otherwise the handler may only set a flag, which will cause the
85 * processing to occur just before we next go idle.
87 * Inbound-notify processing consists of reading all of the notifications
88 * that have arrived since scanning last time. We read every notification
89 * until we reach either a notification from an uncommitted transaction or
90 * the head pointer's position. Then we check if we were the laziest
91 * backend: if our pointer is set to the same position as the global tail
92 * pointer is set, then we move the global tail pointer ahead to where the
93 * second-laziest backend is (in general, we take the MIN of the current
94 * head position and all active backends' new tail pointers). Whenever we
95 * move the global tail pointer we also truncate now-unused pages (i.e.,
96 * delete files in pg_notify/ that are no longer used).
98 * An application that listens on the same channel it notifies will get
99 * NOTIFY messages for its own NOTIFYs. These can be ignored, if not useful,
100 * by comparing be_pid in the NOTIFY message to the application's own backend's
101 * PID. (As of FE/BE protocol 2.0, the backend's PID is provided to the
102 * frontend during startup.) The above design guarantees that notifies from
103 * other backends will never be missed by ignoring self-notifies.
105 * The amount of shared memory used for notify management (NUM_ASYNC_BUFFERS)
106 * can be varied without affecting anything but performance. The maximum
107 * amount of notification data that can be queued at one time is determined
108 * by slru.c's wraparound limit; see QUEUE_MAX_PAGE below.
109 *-------------------------------------------------------------------------
112 #include "postgres.h"
118 #include "access/slru.h"
119 #include "access/transam.h"
120 #include "access/xact.h"
121 #include "catalog/pg_database.h"
122 #include "commands/async.h"
124 #include "libpq/libpq.h"
125 #include "libpq/pqformat.h"
126 #include "miscadmin.h"
127 #include "storage/ipc.h"
128 #include "storage/lmgr.h"
129 #include "storage/procsignal.h"
130 #include "storage/sinval.h"
131 #include "tcop/tcopprot.h"
132 #include "utils/builtins.h"
133 #include "utils/memutils.h"
134 #include "utils/ps_status.h"
138 * Maximum size of a NOTIFY payload, including terminating NULL. This
139 * must be kept small enough so that a notification message fits on one
140 * SLRU page. The magic fudge factor here is noncritical as long as it's
141 * more than AsyncQueueEntryEmptySize --- we make it significantly bigger
142 * than that, so changes in that data structure won't affect user-visible
145 #define NOTIFY_PAYLOAD_MAX_LENGTH (BLCKSZ - NAMEDATALEN - 128)
148 * Struct representing an entry in the global notify queue
150 * This struct declaration has the maximal length, but in a real queue entry
151 * the data area is only big enough for the actual channel and payload strings
152 * (each null-terminated). AsyncQueueEntryEmptySize is the minimum possible
153 * entry size, if both channel and payload strings are empty (but note it
154 * doesn't include alignment padding).
156 * The "length" field should always be rounded up to the next QUEUEALIGN
157 * multiple so that all fields are properly aligned.
159 typedef struct AsyncQueueEntry
161 int length; /* total allocated length of entry */
162 Oid dboid; /* sender's database OID */
163 TransactionId xid; /* sender's XID */
164 int32 srcPid; /* sender's PID */
165 char data[NAMEDATALEN + NOTIFY_PAYLOAD_MAX_LENGTH];
168 /* Currently, no field of AsyncQueueEntry requires more than int alignment */
169 #define QUEUEALIGN(len) INTALIGN(len)
171 #define AsyncQueueEntryEmptySize (offsetof(AsyncQueueEntry, data) + 2)
174 * Struct describing a queue position, and assorted macros for working with it
176 typedef struct QueuePosition
178 int page; /* SLRU page number */
179 int offset; /* byte offset within page */
182 #define QUEUE_POS_PAGE(x) ((x).page)
183 #define QUEUE_POS_OFFSET(x) ((x).offset)
185 #define SET_QUEUE_POS(x,y,z) \
191 #define QUEUE_POS_EQUAL(x,y) \
192 ((x).page == (y).page && (x).offset == (y).offset)
194 /* choose logically smaller QueuePosition */
195 #define QUEUE_POS_MIN(x,y) \
196 (asyncQueuePagePrecedesLogically((x).page, (y).page) ? (x) : \
197 (x).page != (y).page ? (y) : \
198 (x).offset < (y).offset ? (x) : (y))
201 * Struct describing a listening backend's status
203 typedef struct QueueBackendStatus
205 int32 pid; /* either a PID or InvalidPid */
206 QueuePosition pos; /* backend has read queue up to here */
207 } QueueBackendStatus;
209 #define InvalidPid (-1)
212 * Shared memory state for LISTEN/NOTIFY (excluding its SLRU stuff)
214 * The AsyncQueueControl structure is protected by the AsyncQueueLock.
216 * When holding the lock in SHARED mode, backends may only inspect their own
217 * entries as well as the head and tail pointers. Consequently we can allow a
218 * backend to update its own record while holding only SHARED lock (since no
219 * other backend will inspect it).
221 * When holding the lock in EXCLUSIVE mode, backends can inspect the entries
222 * of other backends and also change the head and tail pointers.
224 * In order to avoid deadlocks, whenever we need both locks, we always first
225 * get AsyncQueueLock and then AsyncCtlLock.
227 * Each backend uses the backend[] array entry with index equal to its
228 * BackendId (which can range from 1 to MaxBackends). We rely on this to make
229 * SendProcSignal fast.
231 typedef struct AsyncQueueControl
233 QueuePosition head; /* head points to the next free location */
234 QueuePosition tail; /* the global tail is equivalent to the tail
235 * of the "slowest" backend */
236 TimestampTz lastQueueFillWarn; /* time of last queue-full msg */
237 QueueBackendStatus backend[1]; /* actually of length MaxBackends+1 */
238 /* DO NOT ADD FURTHER STRUCT MEMBERS HERE */
241 static AsyncQueueControl *asyncQueueControl;
243 #define QUEUE_HEAD (asyncQueueControl->head)
244 #define QUEUE_TAIL (asyncQueueControl->tail)
245 #define QUEUE_BACKEND_PID(i) (asyncQueueControl->backend[i].pid)
246 #define QUEUE_BACKEND_POS(i) (asyncQueueControl->backend[i].pos)
249 * The SLRU buffer area through which we access the notification queue
251 static SlruCtlData AsyncCtlData;
253 #define AsyncCtl (&AsyncCtlData)
254 #define QUEUE_PAGESIZE BLCKSZ
255 #define QUEUE_FULL_WARN_INTERVAL 5000 /* warn at most once every 5s */
258 * slru.c currently assumes that all filenames are four characters of hex
259 * digits. That means that we can use segments 0000 through FFFF.
260 * Each segment contains SLRU_PAGES_PER_SEGMENT pages which gives us
261 * the pages from 0 to SLRU_PAGES_PER_SEGMENT * 0x10000 - 1.
263 * It's of course possible to enhance slru.c, but this gives us so much
264 * space already that it doesn't seem worth the trouble.
266 * The most data we can have in the queue at a time is QUEUE_MAX_PAGE/2
267 * pages, because more than that would confuse slru.c into thinking there
268 * was a wraparound condition. With the default BLCKSZ this means there
269 * can be up to 8GB of queued-and-not-read data.
271 * Note: it's possible to redefine QUEUE_MAX_PAGE with a smaller multiple of
272 * SLRU_PAGES_PER_SEGMENT, for easier testing of queue-full behaviour.
274 #define QUEUE_MAX_PAGE (SLRU_PAGES_PER_SEGMENT * 0x10000 - 1)
277 * listenChannels identifies the channels we are actually listening to
278 * (ie, have committed a LISTEN on). It is a simple list of channel names,
279 * allocated in TopMemoryContext.
281 static List *listenChannels = NIL; /* list of C strings */
284 * State for pending LISTEN/UNLISTEN actions consists of an ordered list of
285 * all actions requested in the current transaction. As explained above,
286 * we don't actually change listenChannels until we reach transaction commit.
288 * The list is kept in CurTransactionContext. In subtransactions, each
289 * subtransaction has its own list in its own CurTransactionContext, but
290 * successful subtransactions attach their lists to their parent's list.
291 * Failed subtransactions simply discard their lists.
302 ListenActionKind action;
303 char channel[1]; /* actually, as long as needed */
306 static List *pendingActions = NIL; /* list of ListenAction */
308 static List *upperPendingActions = NIL; /* list of upper-xact lists */
311 * State for outbound notifies consists of a list of all channels+payloads
312 * NOTIFYed in the current transaction. We do not actually perform a NOTIFY
313 * until and unless the transaction commits. pendingNotifies is NIL if no
314 * NOTIFYs have been done in the current transaction.
316 * The list is kept in CurTransactionContext. In subtransactions, each
317 * subtransaction has its own list in its own CurTransactionContext, but
318 * successful subtransactions attach their lists to their parent's list.
319 * Failed subtransactions simply discard their lists.
321 * Note: the action and notify lists do not interact within a transaction.
322 * In particular, if a transaction does NOTIFY and then LISTEN on the same
323 * condition name, it will get a self-notify at commit. This is a bit odd
324 * but is consistent with our historical behavior.
326 typedef struct Notification
328 char *channel; /* channel name */
329 char *payload; /* payload string (can be empty) */
332 static List *pendingNotifies = NIL; /* list of Notifications */
334 static List *upperPendingNotifies = NIL; /* list of upper-xact lists */
337 * State for inbound notifications consists of two flags: one saying whether
338 * the signal handler is currently allowed to call ProcessIncomingNotify
339 * directly, and one saying whether the signal has occurred but the handler
340 * was not allowed to call ProcessIncomingNotify at the time.
342 * NB: the "volatile" on these declarations is critical! If your compiler
343 * does not grok "volatile", you'd be best advised to compile this file
344 * with all optimization turned off.
346 static volatile sig_atomic_t notifyInterruptEnabled = 0;
347 static volatile sig_atomic_t notifyInterruptOccurred = 0;
349 /* True if we've registered an on_shmem_exit cleanup */
350 static bool unlistenExitRegistered = false;
352 /* has this backend sent notifications in the current transaction? */
353 static bool backendHasSentNotifications = false;
355 /* has this backend executed its first LISTEN in the current transaction? */
356 static bool backendHasExecutedInitialListen = false;
359 bool Trace_notify = false;
361 /* local function prototypes */
362 static bool asyncQueuePagePrecedesPhysically(int p, int q);
363 static bool asyncQueuePagePrecedesLogically(int p, int q);
364 static void queue_listen(ListenActionKind action, const char *channel);
365 static void Async_UnlistenOnExit(int code, Datum arg);
366 static void Exec_ListenPreCommit(void);
367 static void Exec_ListenCommit(const char *channel);
368 static void Exec_UnlistenCommit(const char *channel);
369 static void Exec_UnlistenAllCommit(void);
370 static bool IsListeningOn(const char *channel);
371 static void asyncQueueUnregister(void);
372 static bool asyncQueueIsFull(void);
373 static bool asyncQueueAdvance(QueuePosition *position, int entryLength);
374 static void asyncQueueNotificationToEntry(Notification *n, AsyncQueueEntry *qe);
375 static ListCell *asyncQueueAddEntries(ListCell *nextNotify);
376 static void asyncQueueFillWarning(void);
377 static bool SignalBackends(void);
378 static void asyncQueueReadAllNotifications(void);
379 static bool asyncQueueProcessPageEntries(QueuePosition *current,
382 static void asyncQueueAdvanceTail(void);
383 static void ProcessIncomingNotify(void);
384 static void NotifyMyFrontEnd(const char *channel,
387 static bool AsyncExistsPendingNotify(const char *channel, const char *payload);
388 static void ClearPendingActionsAndNotifies(void);
392 * We will work on the page range of 0..QUEUE_MAX_PAGE.
394 * asyncQueuePagePrecedesPhysically just checks numerically without any magic
395 * if one page precedes another one. This is wrong for normal operation but
396 * is helpful when clearing pg_notify/ during startup.
398 * asyncQueuePagePrecedesLogically compares using wraparound logic, as is
399 * required by slru.c.
402 asyncQueuePagePrecedesPhysically(int p, int q)
408 asyncQueuePagePrecedesLogically(int p, int q)
413 * We have to compare modulo (QUEUE_MAX_PAGE+1)/2. Both inputs should be
414 * in the range 0..QUEUE_MAX_PAGE.
416 Assert(p >= 0 && p <= QUEUE_MAX_PAGE);
417 Assert(q >= 0 && q <= QUEUE_MAX_PAGE);
420 if (diff >= ((QUEUE_MAX_PAGE + 1) / 2))
421 diff -= QUEUE_MAX_PAGE + 1;
422 else if (diff < -((QUEUE_MAX_PAGE + 1) / 2))
423 diff += QUEUE_MAX_PAGE + 1;
428 * Report space needed for our shared memory area
435 /* This had better match AsyncShmemInit */
436 size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
437 size = add_size(size, sizeof(AsyncQueueControl));
439 size = add_size(size, SimpleLruShmemSize(NUM_ASYNC_BUFFERS, 0));
445 * Initialize our shared memory area
455 * Create or attach to the AsyncQueueControl structure.
457 * The used entries in the backend[] array run from 1 to MaxBackends.
458 * sizeof(AsyncQueueControl) already includes space for the unused zero'th
459 * entry, but we need to add on space for the used entries.
461 size = mul_size(MaxBackends, sizeof(QueueBackendStatus));
462 size = add_size(size, sizeof(AsyncQueueControl));
464 asyncQueueControl = (AsyncQueueControl *)
465 ShmemInitStruct("Async Queue Control", size, &found);
469 /* First time through, so initialize it */
472 SET_QUEUE_POS(QUEUE_HEAD, 0, 0);
473 SET_QUEUE_POS(QUEUE_TAIL, 0, 0);
474 asyncQueueControl->lastQueueFillWarn = 0;
475 /* zero'th entry won't be used, but let's initialize it anyway */
476 for (i = 0; i <= MaxBackends; i++)
478 QUEUE_BACKEND_PID(i) = InvalidPid;
479 SET_QUEUE_POS(QUEUE_BACKEND_POS(i), 0, 0);
484 * Set up SLRU management of the pg_notify data.
486 AsyncCtl->PagePrecedes = asyncQueuePagePrecedesLogically;
487 SimpleLruInit(AsyncCtl, "Async Ctl", NUM_ASYNC_BUFFERS, 0,
488 AsyncCtlLock, "pg_notify");
489 /* Override default assumption that writes should be fsync'd */
490 AsyncCtl->do_fsync = false;
495 * During start or reboot, clean out the pg_notify directory.
497 * Since we want to remove every file, we temporarily use
498 * asyncQueuePagePrecedesPhysically() and pass INT_MAX as the
499 * comparison value; every file in the directory should therefore
500 * appear to be less than that.
502 AsyncCtl->PagePrecedes = asyncQueuePagePrecedesPhysically;
503 (void) SlruScanDirectory(AsyncCtl, INT_MAX, true);
504 AsyncCtl->PagePrecedes = asyncQueuePagePrecedesLogically;
506 /* Now initialize page zero to empty */
507 LWLockAcquire(AsyncCtlLock, LW_EXCLUSIVE);
508 slotno = SimpleLruZeroPage(AsyncCtl, QUEUE_POS_PAGE(QUEUE_HEAD));
509 /* This write is just to verify that pg_notify/ is writable */
510 SimpleLruWritePage(AsyncCtl, slotno, NULL);
511 LWLockRelease(AsyncCtlLock);
518 * SQL function to send a notification event
521 pg_notify(PG_FUNCTION_ARGS)
529 channel = text_to_cstring(PG_GETARG_TEXT_PP(0));
534 payload = text_to_cstring(PG_GETARG_TEXT_PP(1));
536 /* For NOTIFY as a statement, this is checked in ProcessUtility */
537 PreventCommandDuringRecovery("NOTIFY");
539 Async_Notify(channel, payload);
548 * This is executed by the SQL notify command.
550 * Adds the message to the list of pending notifies.
551 * Actual notification happens during transaction commit.
552 * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
555 Async_Notify(const char *channel, const char *payload)
558 MemoryContext oldcontext;
561 elog(DEBUG1, "Async_Notify(%s)", channel);
563 /* a channel name must be specified */
564 if (!channel || !strlen(channel))
566 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
567 errmsg("channel name cannot be empty")));
569 if (strlen(channel) >= NAMEDATALEN)
571 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
572 errmsg("channel name too long")));
576 if (strlen(payload) >= NOTIFY_PAYLOAD_MAX_LENGTH)
578 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
579 errmsg("payload string too long")));
582 /* no point in making duplicate entries in the list ... */
583 if (AsyncExistsPendingNotify(channel, payload))
587 * The notification list needs to live until end of transaction, so store
588 * it in the transaction context.
590 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
592 n = (Notification *) palloc(sizeof(Notification));
593 n->channel = pstrdup(channel);
595 n->payload = pstrdup(payload);
600 * We want to preserve the order so we need to append every notification.
601 * See comments at AsyncExistsPendingNotify().
603 pendingNotifies = lappend(pendingNotifies, n);
605 MemoryContextSwitchTo(oldcontext);
610 * Common code for listen, unlisten, unlisten all commands.
612 * Adds the request to the list of pending actions.
613 * Actual update of the listenChannels list happens during transaction
617 queue_listen(ListenActionKind action, const char *channel)
619 MemoryContext oldcontext;
620 ListenAction *actrec;
623 * Unlike Async_Notify, we don't try to collapse out duplicates. It would
624 * be too complicated to ensure we get the right interactions of
625 * conflicting LISTEN/UNLISTEN/UNLISTEN_ALL, and it's unlikely that there
626 * would be any performance benefit anyway in sane applications.
628 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
630 /* space for terminating null is included in sizeof(ListenAction) */
631 actrec = (ListenAction *) palloc(sizeof(ListenAction) + strlen(channel));
632 actrec->action = action;
633 strcpy(actrec->channel, channel);
635 pendingActions = lappend(pendingActions, actrec);
637 MemoryContextSwitchTo(oldcontext);
643 * This is executed by the SQL listen command.
646 Async_Listen(const char *channel)
649 elog(DEBUG1, "Async_Listen(%s,%d)", channel, MyProcPid);
651 queue_listen(LISTEN_LISTEN, channel);
657 * This is executed by the SQL unlisten command.
660 Async_Unlisten(const char *channel)
663 elog(DEBUG1, "Async_Unlisten(%s,%d)", channel, MyProcPid);
665 /* If we couldn't possibly be listening, no need to queue anything */
666 if (pendingActions == NIL && !unlistenExitRegistered)
669 queue_listen(LISTEN_UNLISTEN, channel);
675 * This is invoked by UNLISTEN * command, and also at backend exit.
678 Async_UnlistenAll(void)
681 elog(DEBUG1, "Async_UnlistenAll(%d)", MyProcPid);
683 /* If we couldn't possibly be listening, no need to queue anything */
684 if (pendingActions == NIL && !unlistenExitRegistered)
687 queue_listen(LISTEN_UNLISTEN_ALL, "");
691 * SQL function: return a set of the channel names this backend is actively
694 * Note: this coding relies on the fact that the listenChannels list cannot
695 * change within a transaction.
698 pg_listening_channels(PG_FUNCTION_ARGS)
700 FuncCallContext *funcctx;
703 /* stuff done only on the first call of the function */
704 if (SRF_IS_FIRSTCALL())
706 MemoryContext oldcontext;
708 /* create a function context for cross-call persistence */
709 funcctx = SRF_FIRSTCALL_INIT();
711 /* switch to memory context appropriate for multiple function calls */
712 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
714 /* allocate memory for user context */
715 lcp = (ListCell **) palloc(sizeof(ListCell *));
716 *lcp = list_head(listenChannels);
717 funcctx->user_fctx = (void *) lcp;
719 MemoryContextSwitchTo(oldcontext);
722 /* stuff done on every call of the function */
723 funcctx = SRF_PERCALL_SETUP();
724 lcp = (ListCell **) funcctx->user_fctx;
728 char *channel = (char *) lfirst(*lcp);
731 SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(channel));
734 SRF_RETURN_DONE(funcctx);
738 * Async_UnlistenOnExit
740 * This is executed at backend exit if we have done any LISTENs in this
741 * backend. It might not be necessary anymore, if the user UNLISTENed
742 * everything, but we don't try to detect that case.
745 Async_UnlistenOnExit(int code, Datum arg)
747 Exec_UnlistenAllCommit();
753 * This is called at the prepare phase of a two-phase
754 * transaction. Save the state for possible commit later.
757 AtPrepare_Notify(void)
759 /* It's not allowed to have any pending LISTEN/UNLISTEN/NOTIFY actions */
760 if (pendingActions || pendingNotifies)
762 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
763 errmsg("cannot PREPARE a transaction that has executed LISTEN, UNLISTEN or NOTIFY")));
769 * This is called at transaction commit, before actually committing to
772 * If there are pending LISTEN actions, make sure we are listed in the
773 * shared-memory listener array. This must happen before commit to
774 * ensure we don't miss any notifies from transactions that commit
777 * If there are outbound notify requests in the pendingNotifies list,
778 * add them to the global queue. We do that before commit so that
779 * we can still throw error if we run out of queue space.
782 PreCommit_Notify(void)
786 if (pendingActions == NIL && pendingNotifies == NIL)
787 return; /* no relevant statements in this xact */
790 elog(DEBUG1, "PreCommit_Notify");
792 Assert(backendHasExecutedInitialListen == false);
794 /* Preflight for any pending listen/unlisten actions */
795 foreach(p, pendingActions)
797 ListenAction *actrec = (ListenAction *) lfirst(p);
799 switch (actrec->action)
802 Exec_ListenPreCommit();
804 case LISTEN_UNLISTEN:
805 /* there is no Exec_UnlistenPreCommit() */
807 case LISTEN_UNLISTEN_ALL:
808 /* there is no Exec_UnlistenAllPreCommit() */
813 /* Queue any pending notifies */
816 ListCell *nextNotify;
819 * Make sure that we have an XID assigned to the current transaction.
820 * GetCurrentTransactionId is cheap if we already have an XID, but not
821 * so cheap if we don't, and we'd prefer not to do that work while
822 * holding AsyncQueueLock.
824 (void) GetCurrentTransactionId();
827 * Serialize writers by acquiring a special lock that we hold till
828 * after commit. This ensures that queue entries appear in commit
829 * order, and in particular that there are never uncommitted queue
830 * entries ahead of committed ones, so an uncommitted transaction
831 * can't block delivery of deliverable notifications.
833 * We use a heavyweight lock so that it'll automatically be released
834 * after either commit or abort. This also allows deadlocks to be
835 * detected, though really a deadlock shouldn't be possible here.
837 * The lock is on "database 0", which is pretty ugly but it doesn't
838 * seem worth inventing a special locktag category just for this.
839 * (Historical note: before PG 9.0, a similar lock on "database 0" was
840 * used by the flatfiles mechanism.)
842 LockSharedObject(DatabaseRelationId, InvalidOid, 0,
843 AccessExclusiveLock);
845 /* Now push the notifications into the queue */
846 backendHasSentNotifications = true;
848 nextNotify = list_head(pendingNotifies);
849 while (nextNotify != NULL)
852 * Add the pending notifications to the queue. We acquire and
853 * release AsyncQueueLock once per page, which might be overkill
854 * but it does allow readers to get in while we're doing this.
856 * A full queue is very uncommon and should really not happen,
857 * given that we have so much space available in the SLRU pages.
858 * Nevertheless we need to deal with this possibility. Note that
859 * when we get here we are in the process of committing our
860 * transaction, but we have not yet committed to clog, so at this
861 * point in time we can still roll the transaction back.
863 LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
864 asyncQueueFillWarning();
865 if (asyncQueueIsFull())
867 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
868 errmsg("too many notifications in the NOTIFY queue")));
869 nextNotify = asyncQueueAddEntries(nextNotify);
870 LWLockRelease(AsyncQueueLock);
878 * This is called at transaction commit, after committing to clog.
880 * Update listenChannels and clear transaction-local state.
883 AtCommit_Notify(void)
888 * Allow transactions that have not executed LISTEN/UNLISTEN/NOTIFY to
889 * return as soon as possible
891 if (!pendingActions && !pendingNotifies)
895 elog(DEBUG1, "AtCommit_Notify");
897 /* Perform any pending listen/unlisten actions */
898 foreach(p, pendingActions)
900 ListenAction *actrec = (ListenAction *) lfirst(p);
902 switch (actrec->action)
905 Exec_ListenCommit(actrec->channel);
907 case LISTEN_UNLISTEN:
908 Exec_UnlistenCommit(actrec->channel);
910 case LISTEN_UNLISTEN_ALL:
911 Exec_UnlistenAllCommit();
917 * If we did an initial LISTEN, listenChannels now has the entry, so we no
918 * longer need or want the flag to be set.
920 backendHasExecutedInitialListen = false;
923 ClearPendingActionsAndNotifies();
927 * Exec_ListenPreCommit --- subroutine for PreCommit_Notify
929 * This function must make sure we are ready to catch any incoming messages.
932 Exec_ListenPreCommit(void)
935 * Nothing to do if we are already listening to something, nor if we
936 * already ran this routine in this transaction.
938 if (listenChannels != NIL || backendHasExecutedInitialListen)
942 elog(DEBUG1, "Exec_ListenPreCommit(%d)", MyProcPid);
945 * We need this variable to detect an aborted initial LISTEN. In that case
946 * we would set up our pointer but not listen on any channel. This flag
947 * gets cleared in AtCommit_Notify or AtAbort_Notify().
949 backendHasExecutedInitialListen = true;
952 * Before registering, make sure we will unlisten before dying. (Note:
953 * this action does not get undone if we abort later.)
955 if (!unlistenExitRegistered)
957 on_shmem_exit(Async_UnlistenOnExit, 0);
958 unlistenExitRegistered = true;
962 * This is our first LISTEN, so establish our pointer.
964 * We set our pointer to the global tail pointer and then move it forward
965 * over already-committed notifications. This ensures we cannot miss any
966 * not-yet-committed notifications. We might get a few more but that
969 LWLockAcquire(AsyncQueueLock, LW_SHARED);
970 QUEUE_BACKEND_POS(MyBackendId) = QUEUE_TAIL;
971 QUEUE_BACKEND_PID(MyBackendId) = MyProcPid;
972 LWLockRelease(AsyncQueueLock);
975 * Try to move our pointer forward as far as possible. This will skip over
976 * already-committed notifications. Still, we could get notifications that
977 * have already committed before we started to LISTEN.
979 * Note that we are not yet listening on anything, so we won't deliver any
980 * notification to the frontend.
982 * This will also advance the global tail pointer if possible.
984 asyncQueueReadAllNotifications();
988 * Exec_ListenCommit --- subroutine for AtCommit_Notify
990 * Add the channel to the list of channels we are listening on.
993 Exec_ListenCommit(const char *channel)
995 MemoryContext oldcontext;
997 /* Do nothing if we are already listening on this channel */
998 if (IsListeningOn(channel))
1002 * Add the new channel name to listenChannels.
1004 * XXX It is theoretically possible to get an out-of-memory failure here,
1005 * which would be bad because we already committed. For the moment it
1006 * doesn't seem worth trying to guard against that, but maybe improve this
1009 oldcontext = MemoryContextSwitchTo(TopMemoryContext);
1010 listenChannels = lappend(listenChannels, pstrdup(channel));
1011 MemoryContextSwitchTo(oldcontext);
1015 * Exec_UnlistenCommit --- subroutine for AtCommit_Notify
1017 * Remove the specified channel name from listenChannels.
1020 Exec_UnlistenCommit(const char *channel)
1026 elog(DEBUG1, "Exec_UnlistenCommit(%s,%d)", channel, MyProcPid);
1029 foreach(q, listenChannels)
1031 char *lchan = (char *) lfirst(q);
1033 if (strcmp(lchan, channel) == 0)
1035 listenChannels = list_delete_cell(listenChannels, q, prev);
1043 * We do not complain about unlistening something not being listened;
1047 /* If no longer listening to anything, get out of listener array */
1048 if (listenChannels == NIL)
1049 asyncQueueUnregister();
1053 * Exec_UnlistenAllCommit --- subroutine for AtCommit_Notify
1055 * Unlisten on all channels for this backend.
1058 Exec_UnlistenAllCommit(void)
1061 elog(DEBUG1, "Exec_UnlistenAllCommit(%d)", MyProcPid);
1063 list_free_deep(listenChannels);
1064 listenChannels = NIL;
1066 asyncQueueUnregister();
1070 * ProcessCompletedNotifies --- send out signals and self-notifies
1072 * This is called from postgres.c just before going idle at the completion
1073 * of a transaction. If we issued any notifications in the just-completed
1074 * transaction, send signals to other backends to process them, and also
1075 * process the queue ourselves to send messages to our own frontend.
1077 * The reason that this is not done in AtCommit_Notify is that there is
1078 * a nonzero chance of errors here (for example, encoding conversion errors
1079 * while trying to format messages to our frontend). An error during
1080 * AtCommit_Notify would be a PANIC condition. The timing is also arranged
1081 * to ensure that a transaction's self-notifies are delivered to the frontend
1082 * before it gets the terminating ReadyForQuery message.
1084 * Note that we send signals and process the queue even if the transaction
1085 * eventually aborted. This is because we need to clean out whatever got
1086 * added to the queue.
1088 * NOTE: we are outside of any transaction here.
1091 ProcessCompletedNotifies(void)
1095 /* Nothing to do if we didn't send any notifications */
1096 if (!backendHasSentNotifications)
1100 * We reset the flag immediately; otherwise, if any sort of error occurs
1101 * below, we'd be locked up in an infinite loop, because control will come
1102 * right back here after error cleanup.
1104 backendHasSentNotifications = false;
1107 elog(DEBUG1, "ProcessCompletedNotifies");
1110 * We must run asyncQueueReadAllNotifications inside a transaction, else
1111 * bad things happen if it gets an error.
1113 StartTransactionCommand();
1115 /* Send signals to other backends */
1116 signalled = SignalBackends();
1118 if (listenChannels != NIL)
1120 /* Read the queue ourselves, and send relevant stuff to the frontend */
1121 asyncQueueReadAllNotifications();
1123 else if (!signalled)
1126 * If we found no other listening backends, and we aren't listening
1127 * ourselves, then we must execute asyncQueueAdvanceTail to flush the
1128 * queue, because ain't nobody else gonna do it. This prevents queue
1129 * overflow when we're sending useless notifies to nobody. (A new
1130 * listener could have joined since we looked, but if so this is
1133 asyncQueueAdvanceTail();
1136 CommitTransactionCommand();
1138 /* We don't need pq_flush() here since postgres.c will do one shortly */
1142 * Test whether we are actively listening on the given channel name.
1144 * Note: this function is executed for every notification found in the queue.
1145 * Perhaps it is worth further optimization, eg convert the list to a sorted
1146 * array so we can binary-search it. In practice the list is likely to be
1147 * fairly short, though.
1150 IsListeningOn(const char *channel)
1154 foreach(p, listenChannels)
1156 char *lchan = (char *) lfirst(p);
1158 if (strcmp(lchan, channel) == 0)
1165 * Remove our entry from the listeners array when we are no longer listening
1166 * on any channel. NB: must not fail if we're already not listening.
1169 asyncQueueUnregister(void)
1173 Assert(listenChannels == NIL); /* else caller error */
1175 LWLockAcquire(AsyncQueueLock, LW_SHARED);
1176 /* check if entry is valid and oldest ... */
1177 advanceTail = (MyProcPid == QUEUE_BACKEND_PID(MyBackendId)) &&
1178 QUEUE_POS_EQUAL(QUEUE_BACKEND_POS(MyBackendId), QUEUE_TAIL);
1179 /* ... then mark it invalid */
1180 QUEUE_BACKEND_PID(MyBackendId) = InvalidPid;
1181 LWLockRelease(AsyncQueueLock);
1183 /* If we were the laziest backend, try to advance the tail pointer */
1185 asyncQueueAdvanceTail();
1189 * Test whether there is room to insert more notification messages.
1191 * Caller must hold at least shared AsyncQueueLock.
1194 asyncQueueIsFull(void)
1200 * The queue is full if creating a new head page would create a page that
1201 * logically precedes the current global tail pointer, ie, the head
1202 * pointer would wrap around compared to the tail. We cannot create such
1203 * a head page for fear of confusing slru.c. For safety we round the tail
1204 * pointer back to a segment boundary (compare the truncation logic in
1205 * asyncQueueAdvanceTail).
1207 * Note that this test is *not* dependent on how much space there is on
1208 * the current head page. This is necessary because asyncQueueAddEntries
1209 * might try to create the next head page in any case.
1211 nexthead = QUEUE_POS_PAGE(QUEUE_HEAD) + 1;
1212 if (nexthead > QUEUE_MAX_PAGE)
1213 nexthead = 0; /* wrap around */
1214 boundary = QUEUE_POS_PAGE(QUEUE_TAIL);
1215 boundary -= boundary % SLRU_PAGES_PER_SEGMENT;
1216 return asyncQueuePagePrecedesLogically(nexthead, boundary);
1220 * Advance the QueuePosition to the next entry, assuming that the current
1221 * entry is of length entryLength. If we jump to a new page the function
1222 * returns true, else false.
1225 asyncQueueAdvance(QueuePosition *position, int entryLength)
1227 int pageno = QUEUE_POS_PAGE(*position);
1228 int offset = QUEUE_POS_OFFSET(*position);
1229 bool pageJump = false;
1232 * Move to the next writing position: First jump over what we have just
1235 offset += entryLength;
1236 Assert(offset <= QUEUE_PAGESIZE);
1239 * In a second step check if another entry can possibly be written to the
1240 * page. If so, stay here, we have reached the next position. If not, then
1241 * we need to move on to the next page.
1243 if (offset + QUEUEALIGN(AsyncQueueEntryEmptySize) > QUEUE_PAGESIZE)
1246 if (pageno > QUEUE_MAX_PAGE)
1247 pageno = 0; /* wrap around */
1252 SET_QUEUE_POS(*position, pageno, offset);
1257 * Fill the AsyncQueueEntry at *qe with an outbound notification message.
1260 asyncQueueNotificationToEntry(Notification *n, AsyncQueueEntry *qe)
1262 size_t channellen = strlen(n->channel);
1263 size_t payloadlen = strlen(n->payload);
1266 Assert(channellen < NAMEDATALEN);
1267 Assert(payloadlen < NOTIFY_PAYLOAD_MAX_LENGTH);
1269 /* The terminators are already included in AsyncQueueEntryEmptySize */
1270 entryLength = AsyncQueueEntryEmptySize + payloadlen + channellen;
1271 entryLength = QUEUEALIGN(entryLength);
1272 qe->length = entryLength;
1273 qe->dboid = MyDatabaseId;
1274 qe->xid = GetCurrentTransactionId();
1275 qe->srcPid = MyProcPid;
1276 memcpy(qe->data, n->channel, channellen + 1);
1277 memcpy(qe->data + channellen + 1, n->payload, payloadlen + 1);
1281 * Add pending notifications to the queue.
1283 * We go page by page here, i.e. we stop once we have to go to a new page but
1284 * we will be called again and then fill that next page. If an entry does not
1285 * fit into the current page, we write a dummy entry with an InvalidOid as the
1286 * database OID in order to fill the page. So every page is always used up to
1287 * the last byte which simplifies reading the page later.
1289 * We are passed the list cell containing the next notification to write
1290 * and return the first still-unwritten cell back. Eventually we will return
1291 * NULL indicating all is done.
1293 * We are holding AsyncQueueLock already from the caller and grab AsyncCtlLock
1294 * locally in this function.
1297 asyncQueueAddEntries(ListCell *nextNotify)
1304 /* We hold both AsyncQueueLock and AsyncCtlLock during this operation */
1305 LWLockAcquire(AsyncCtlLock, LW_EXCLUSIVE);
1307 /* Fetch the current page */
1308 pageno = QUEUE_POS_PAGE(QUEUE_HEAD);
1309 slotno = SimpleLruReadPage(AsyncCtl, pageno, true, InvalidTransactionId);
1310 /* Note we mark the page dirty before writing in it */
1311 AsyncCtl->shared->page_dirty[slotno] = true;
1313 while (nextNotify != NULL)
1315 Notification *n = (Notification *) lfirst(nextNotify);
1317 /* Construct a valid queue entry in local variable qe */
1318 asyncQueueNotificationToEntry(n, &qe);
1320 offset = QUEUE_POS_OFFSET(QUEUE_HEAD);
1322 /* Check whether the entry really fits on the current page */
1323 if (offset + qe.length <= QUEUE_PAGESIZE)
1325 /* OK, so advance nextNotify past this item */
1326 nextNotify = lnext(nextNotify);
1331 * Write a dummy entry to fill up the page. Actually readers will
1332 * only check dboid and since it won't match any reader's database
1333 * OID, they will ignore this entry and move on.
1335 qe.length = QUEUE_PAGESIZE - offset;
1336 qe.dboid = InvalidOid;
1337 qe.data[0] = '\0'; /* empty channel */
1338 qe.data[1] = '\0'; /* empty payload */
1341 /* Now copy qe into the shared buffer page */
1342 memcpy(AsyncCtl->shared->page_buffer[slotno] + offset,
1346 /* Advance QUEUE_HEAD appropriately, and note if page is full */
1347 if (asyncQueueAdvance(&(QUEUE_HEAD), qe.length))
1350 * Page is full, so we're done here, but first fill the next page
1351 * with zeroes. The reason to do this is to ensure that slru.c's
1352 * idea of the head page is always the same as ours, which avoids
1353 * boundary problems in SimpleLruTruncate. The test in
1354 * asyncQueueIsFull() ensured that there is room to create this
1355 * page without overrunning the queue.
1357 slotno = SimpleLruZeroPage(AsyncCtl, QUEUE_POS_PAGE(QUEUE_HEAD));
1358 /* And exit the loop */
1363 LWLockRelease(AsyncCtlLock);
1369 * Check whether the queue is at least half full, and emit a warning if so.
1371 * This is unlikely given the size of the queue, but possible.
1372 * The warnings show up at most once every QUEUE_FULL_WARN_INTERVAL.
1374 * Caller must hold exclusive AsyncQueueLock.
1377 asyncQueueFillWarning(void)
1379 int headPage = QUEUE_POS_PAGE(QUEUE_HEAD);
1380 int tailPage = QUEUE_POS_PAGE(QUEUE_TAIL);
1385 occupied = headPage - tailPage;
1388 return; /* fast exit for common case */
1392 /* head has wrapped around, tail not yet */
1393 occupied += QUEUE_MAX_PAGE + 1;
1396 fillDegree = (double) occupied / (double) ((QUEUE_MAX_PAGE + 1) / 2);
1398 if (fillDegree < 0.5)
1401 t = GetCurrentTimestamp();
1403 if (TimestampDifferenceExceeds(asyncQueueControl->lastQueueFillWarn,
1404 t, QUEUE_FULL_WARN_INTERVAL))
1406 QueuePosition min = QUEUE_HEAD;
1407 int32 minPid = InvalidPid;
1410 for (i = 1; i <= MaxBackends; i++)
1412 if (QUEUE_BACKEND_PID(i) != InvalidPid)
1414 min = QUEUE_POS_MIN(min, QUEUE_BACKEND_POS(i));
1415 if (QUEUE_POS_EQUAL(min, QUEUE_BACKEND_POS(i)))
1416 minPid = QUEUE_BACKEND_PID(i);
1421 (errmsg("NOTIFY queue is %.0f%% full", fillDegree * 100),
1422 (minPid != InvalidPid ?
1423 errdetail("The server process with PID %d is among those with the oldest transactions.", minPid)
1425 (minPid != InvalidPid ?
1426 errhint("The NOTIFY queue cannot be emptied until that process ends its current transaction.")
1429 asyncQueueControl->lastQueueFillWarn = t;
1434 * Send signals to all listening backends (except our own).
1436 * Returns true if we sent at least one signal.
1438 * Since we need EXCLUSIVE lock anyway we also check the position of the other
1439 * backends and in case one is already up-to-date we don't signal it.
1440 * This can happen if concurrent notifying transactions have sent a signal and
1441 * the signaled backend has read the other notifications and ours in the same
1444 * Since we know the BackendId and the Pid the signalling is quite cheap.
1447 SignalBackends(void)
1449 bool signalled = false;
1457 * Identify all backends that are listening and not already up-to-date. We
1458 * don't want to send signals while holding the AsyncQueueLock, so we just
1459 * build a list of target PIDs.
1461 * XXX in principle these pallocs could fail, which would be bad. Maybe
1462 * preallocate the arrays? But in practice this is only run in trivial
1463 * transactions, so there should surely be space available.
1465 pids = (int32 *) palloc(MaxBackends * sizeof(int32));
1466 ids = (BackendId *) palloc(MaxBackends * sizeof(BackendId));
1469 LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
1470 for (i = 1; i <= MaxBackends; i++)
1472 pid = QUEUE_BACKEND_PID(i);
1473 if (pid != InvalidPid && pid != MyProcPid)
1475 QueuePosition pos = QUEUE_BACKEND_POS(i);
1477 if (!QUEUE_POS_EQUAL(pos, QUEUE_HEAD))
1485 LWLockRelease(AsyncQueueLock);
1487 /* Now send signals */
1488 for (i = 0; i < count; i++)
1493 * Note: assuming things aren't broken, a signal failure here could
1494 * only occur if the target backend exited since we released
1495 * AsyncQueueLock; which is unlikely but certainly possible. So we
1496 * just log a low-level debug message if it happens.
1498 if (SendProcSignal(pid, PROCSIG_NOTIFY_INTERRUPT, ids[i]) < 0)
1499 elog(DEBUG3, "could not signal backend with PID %d: %m", pid);
1513 * This is called at transaction abort.
1515 * Gets rid of pending actions and outbound notifies that we would have
1516 * executed if the transaction got committed.
1519 AtAbort_Notify(void)
1522 * If we LISTEN but then roll back the transaction we have set our pointer
1523 * but have not made any entry in listenChannels. In that case, remove our
1526 if (backendHasExecutedInitialListen)
1529 * Checking listenChannels should be redundant but it can't hurt doing
1530 * it for safety reasons.
1532 if (listenChannels == NIL)
1533 asyncQueueUnregister();
1535 backendHasExecutedInitialListen = false;
1539 ClearPendingActionsAndNotifies();
1543 * AtSubStart_Notify() --- Take care of subtransaction start.
1545 * Push empty state for the new subtransaction.
1548 AtSubStart_Notify(void)
1550 MemoryContext old_cxt;
1552 /* Keep the list-of-lists in TopTransactionContext for simplicity */
1553 old_cxt = MemoryContextSwitchTo(TopTransactionContext);
1555 upperPendingActions = lcons(pendingActions, upperPendingActions);
1557 Assert(list_length(upperPendingActions) ==
1558 GetCurrentTransactionNestLevel() - 1);
1560 pendingActions = NIL;
1562 upperPendingNotifies = lcons(pendingNotifies, upperPendingNotifies);
1564 Assert(list_length(upperPendingNotifies) ==
1565 GetCurrentTransactionNestLevel() - 1);
1567 pendingNotifies = NIL;
1569 MemoryContextSwitchTo(old_cxt);
1573 * AtSubCommit_Notify() --- Take care of subtransaction commit.
1575 * Reassign all items in the pending lists to the parent transaction.
1578 AtSubCommit_Notify(void)
1580 List *parentPendingActions;
1581 List *parentPendingNotifies;
1583 parentPendingActions = (List *) linitial(upperPendingActions);
1584 upperPendingActions = list_delete_first(upperPendingActions);
1586 Assert(list_length(upperPendingActions) ==
1587 GetCurrentTransactionNestLevel() - 2);
1590 * Mustn't try to eliminate duplicates here --- see queue_listen()
1592 pendingActions = list_concat(parentPendingActions, pendingActions);
1594 parentPendingNotifies = (List *) linitial(upperPendingNotifies);
1595 upperPendingNotifies = list_delete_first(upperPendingNotifies);
1597 Assert(list_length(upperPendingNotifies) ==
1598 GetCurrentTransactionNestLevel() - 2);
1601 * We could try to eliminate duplicates here, but it seems not worthwhile.
1603 pendingNotifies = list_concat(parentPendingNotifies, pendingNotifies);
1607 * AtSubAbort_Notify() --- Take care of subtransaction abort.
1610 AtSubAbort_Notify(void)
1612 int my_level = GetCurrentTransactionNestLevel();
1615 * All we have to do is pop the stack --- the actions/notifies made in
1616 * this subxact are no longer interesting, and the space will be freed
1617 * when CurTransactionContext is recycled.
1619 * This routine could be called more than once at a given nesting level if
1620 * there is trouble during subxact abort. Avoid dumping core by using
1621 * GetCurrentTransactionNestLevel as the indicator of how far we need to
1624 while (list_length(upperPendingActions) > my_level - 2)
1626 pendingActions = (List *) linitial(upperPendingActions);
1627 upperPendingActions = list_delete_first(upperPendingActions);
1630 while (list_length(upperPendingNotifies) > my_level - 2)
1632 pendingNotifies = (List *) linitial(upperPendingNotifies);
1633 upperPendingNotifies = list_delete_first(upperPendingNotifies);
1638 * HandleNotifyInterrupt
1640 * This is called when PROCSIG_NOTIFY_INTERRUPT is received.
1642 * If we are idle (notifyInterruptEnabled is set), we can safely invoke
1643 * ProcessIncomingNotify directly. Otherwise, just set a flag
1647 HandleNotifyInterrupt(void)
1650 * Note: this is called by a SIGNAL HANDLER. You must be very wary what
1651 * you do here. Some helpful soul had this routine sprinkled with
1652 * TPRINTFs, which would likely lead to corruption of stdio buffers if
1653 * they were ever turned on.
1656 /* Don't joggle the elbow of proc_exit */
1657 if (proc_exit_inprogress)
1660 if (notifyInterruptEnabled)
1662 bool save_ImmediateInterruptOK = ImmediateInterruptOK;
1665 * We may be called while ImmediateInterruptOK is true; turn it off
1666 * while messing with the NOTIFY state. (We would have to save and
1667 * restore it anyway, because PGSemaphore operations inside
1668 * ProcessIncomingNotify() might reset it.)
1670 ImmediateInterruptOK = false;
1673 * I'm not sure whether some flavors of Unix might allow another
1674 * SIGUSR1 occurrence to recursively interrupt this routine. To cope
1675 * with the possibility, we do the same sort of dance that
1676 * EnableNotifyInterrupt must do --- see that routine for comments.
1678 notifyInterruptEnabled = 0; /* disable any recursive signal */
1679 notifyInterruptOccurred = 1; /* do at least one iteration */
1682 notifyInterruptEnabled = 1;
1683 if (!notifyInterruptOccurred)
1685 notifyInterruptEnabled = 0;
1686 if (notifyInterruptOccurred)
1688 /* Here, it is finally safe to do stuff. */
1690 elog(DEBUG1, "HandleNotifyInterrupt: perform async notify");
1692 ProcessIncomingNotify();
1695 elog(DEBUG1, "HandleNotifyInterrupt: done");
1700 * Restore ImmediateInterruptOK, and check for interrupts if needed.
1702 ImmediateInterruptOK = save_ImmediateInterruptOK;
1703 if (save_ImmediateInterruptOK)
1704 CHECK_FOR_INTERRUPTS();
1709 * In this path it is NOT SAFE to do much of anything, except this:
1711 notifyInterruptOccurred = 1;
1716 * EnableNotifyInterrupt
1718 * This is called by the PostgresMain main loop just before waiting
1719 * for a frontend command. If we are truly idle (ie, *not* inside
1720 * a transaction block), then process any pending inbound notifies,
1721 * and enable the signal handler to process future notifies directly.
1723 * NOTE: the signal handler starts out disabled, and stays so until
1724 * PostgresMain calls this the first time.
1727 EnableNotifyInterrupt(void)
1729 if (IsTransactionOrTransactionBlock())
1730 return; /* not really idle */
1733 * This code is tricky because we are communicating with a signal handler
1734 * that could interrupt us at any point. If we just checked
1735 * notifyInterruptOccurred and then set notifyInterruptEnabled, we could
1736 * fail to respond promptly to a signal that happens in between those two
1737 * steps. (A very small time window, perhaps, but Murphy's Law says you
1738 * can hit it...) Instead, we first set the enable flag, then test the
1739 * occurred flag. If we see an unserviced interrupt has occurred, we
1740 * re-clear the enable flag before going off to do the service work. (That
1741 * prevents re-entrant invocation of ProcessIncomingNotify() if another
1742 * interrupt occurs.) If an interrupt comes in between the setting and
1743 * clearing of notifyInterruptEnabled, then it will have done the service
1744 * work and left notifyInterruptOccurred zero, so we have to check again
1745 * after clearing enable. The whole thing has to be in a loop in case
1746 * another interrupt occurs while we're servicing the first. Once we get
1747 * out of the loop, enable is set and we know there is no unserviced
1750 * NB: an overenthusiastic optimizing compiler could easily break this
1751 * code. Hopefully, they all understand what "volatile" means these days.
1755 notifyInterruptEnabled = 1;
1756 if (!notifyInterruptOccurred)
1758 notifyInterruptEnabled = 0;
1759 if (notifyInterruptOccurred)
1762 elog(DEBUG1, "EnableNotifyInterrupt: perform async notify");
1764 ProcessIncomingNotify();
1767 elog(DEBUG1, "EnableNotifyInterrupt: done");
1773 * DisableNotifyInterrupt
1775 * This is called by the PostgresMain main loop just after receiving
1776 * a frontend command. Signal handler execution of inbound notifies
1777 * is disabled until the next EnableNotifyInterrupt call.
1779 * The PROCSIG_CATCHUP_INTERRUPT signal handler also needs to call this,
1780 * so as to prevent conflicts if one signal interrupts the other. So we
1781 * must return the previous state of the flag.
1784 DisableNotifyInterrupt(void)
1786 bool result = (notifyInterruptEnabled != 0);
1788 notifyInterruptEnabled = 0;
1794 * Read all pending notifications from the queue, and deliver appropriate
1795 * ones to my frontend. Stop when we reach queue head or an uncommitted
1799 asyncQueueReadAllNotifications(void)
1802 QueuePosition oldpos;
1806 /* page_buffer must be adequately aligned, so use a union */
1809 char buf[QUEUE_PAGESIZE];
1810 AsyncQueueEntry align;
1813 /* Fetch current state */
1814 LWLockAcquire(AsyncQueueLock, LW_SHARED);
1815 /* Assert checks that we have a valid state entry */
1816 Assert(MyProcPid == QUEUE_BACKEND_PID(MyBackendId));
1817 pos = oldpos = QUEUE_BACKEND_POS(MyBackendId);
1819 LWLockRelease(AsyncQueueLock);
1821 if (QUEUE_POS_EQUAL(pos, head))
1823 /* Nothing to do, we have read all notifications already. */
1828 * Note that we deliver everything that we see in the queue and that
1829 * matches our _current_ listening state.
1830 * Especially we do not take into account different commit times.
1831 * Consider the following example:
1833 * Backend 1: Backend 2:
1835 * transaction starts
1838 * transaction starts
1844 * It could happen that backend 2 sees the notification from backend 1 in
1845 * the queue. Even though the notifying transaction committed before
1846 * the listening transaction, we still deliver the notification.
1848 * The idea is that an additional notification does not do any harm, we
1849 * just need to make sure that we do not miss a notification.
1851 * It is possible that we fail while trying to send a message to our
1852 * frontend (for example, because of encoding conversion failure).
1853 * If that happens it is critical that we not try to send the same
1854 * message over and over again. Therefore, we place a PG_TRY block
1855 * here that will forcibly advance our backend position before we lose
1856 * control to an error. (We could alternatively retake AsyncQueueLock
1857 * and move the position before handling each individual message, but
1858 * that seems like too much lock traffic.)
1867 int curpage = QUEUE_POS_PAGE(pos);
1868 int curoffset = QUEUE_POS_OFFSET(pos);
1873 * We copy the data from SLRU into a local buffer, so as to avoid
1874 * holding the AsyncCtlLock while we are examining the entries and
1875 * possibly transmitting them to our frontend. Copy only the part
1876 * of the page we will actually inspect.
1878 slotno = SimpleLruReadPage_ReadOnly(AsyncCtl, curpage,
1879 InvalidTransactionId);
1880 if (curpage == QUEUE_POS_PAGE(head))
1882 /* we only want to read as far as head */
1883 copysize = QUEUE_POS_OFFSET(head) - curoffset;
1885 copysize = 0; /* just for safety */
1889 /* fetch all the rest of the page */
1890 copysize = QUEUE_PAGESIZE - curoffset;
1892 memcpy(page_buffer.buf + curoffset,
1893 AsyncCtl->shared->page_buffer[slotno] + curoffset,
1895 /* Release lock that we got from SimpleLruReadPage_ReadOnly() */
1896 LWLockRelease(AsyncCtlLock);
1899 * Process messages up to the stop position, end of page, or an
1900 * uncommitted message.
1902 * Our stop position is what we found to be the head's position
1903 * when we entered this function. It might have changed already.
1904 * But if it has, we will receive (or have already received and
1905 * queued) another signal and come here again.
1907 * We are not holding AsyncQueueLock here! The queue can only
1908 * extend beyond the head pointer (see above) and we leave our
1909 * backend's pointer where it is so nobody will truncate or
1910 * rewrite pages under us. Especially we don't want to hold a lock
1911 * while sending the notifications to the frontend.
1913 reachedStop = asyncQueueProcessPageEntries(&pos, head,
1915 } while (!reachedStop);
1919 /* Update shared state */
1920 LWLockAcquire(AsyncQueueLock, LW_SHARED);
1921 QUEUE_BACKEND_POS(MyBackendId) = pos;
1922 advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
1923 LWLockRelease(AsyncQueueLock);
1925 /* If we were the laziest backend, try to advance the tail pointer */
1927 asyncQueueAdvanceTail();
1933 /* Update shared state */
1934 LWLockAcquire(AsyncQueueLock, LW_SHARED);
1935 QUEUE_BACKEND_POS(MyBackendId) = pos;
1936 advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
1937 LWLockRelease(AsyncQueueLock);
1939 /* If we were the laziest backend, try to advance the tail pointer */
1941 asyncQueueAdvanceTail();
1945 * Fetch notifications from the shared queue, beginning at position current,
1946 * and deliver relevant ones to my frontend.
1948 * The current page must have been fetched into page_buffer from shared
1949 * memory. (We could access the page right in shared memory, but that
1950 * would imply holding the AsyncCtlLock throughout this routine.)
1952 * We stop if we reach the "stop" position, or reach a notification from an
1953 * uncommitted transaction, or reach the end of the page.
1955 * The function returns true once we have reached the stop position or an
1956 * uncommitted notification, and false if we have finished with the page.
1957 * In other words: once it returns true there is no need to look further.
1958 * The QueuePosition *current is advanced past all processed messages.
1961 asyncQueueProcessPageEntries(QueuePosition *current,
1965 bool reachedStop = false;
1966 bool reachedEndOfPage;
1967 AsyncQueueEntry *qe;
1971 QueuePosition thisentry = *current;
1973 if (QUEUE_POS_EQUAL(thisentry, stop))
1976 qe = (AsyncQueueEntry *) (page_buffer + QUEUE_POS_OFFSET(thisentry));
1979 * Advance *current over this message, possibly to the next page. As
1980 * noted in the comments for asyncQueueReadAllNotifications, we must
1981 * do this before possibly failing while processing the message.
1983 reachedEndOfPage = asyncQueueAdvance(current, qe->length);
1985 /* Ignore messages destined for other databases */
1986 if (qe->dboid == MyDatabaseId)
1988 if (TransactionIdDidCommit(qe->xid))
1990 /* qe->data is the null-terminated channel name */
1991 char *channel = qe->data;
1993 if (IsListeningOn(channel))
1995 /* payload follows channel name */
1996 char *payload = qe->data + strlen(channel) + 1;
1998 NotifyMyFrontEnd(channel, payload, qe->srcPid);
2001 else if (TransactionIdDidAbort(qe->xid))
2004 * If the source transaction aborted, we just ignore its
2011 * The transaction has neither committed nor aborted so far,
2012 * so we can't process its message yet. Break out of the
2013 * loop, but first back up *current so we will reprocess the
2014 * message next time. (Note: it is unlikely but not
2015 * impossible for TransactionIdDidCommit to fail, so we can't
2016 * really avoid this advance-then-back-up behavior when
2017 * dealing with an uncommitted message.)
2019 *current = thisentry;
2025 /* Loop back if we're not at end of page */
2026 } while (!reachedEndOfPage);
2028 if (QUEUE_POS_EQUAL(*current, stop))
2035 * Advance the shared queue tail variable to the minimum of all the
2036 * per-backend tail pointers. Truncate pg_notify space if possible.
2039 asyncQueueAdvanceTail(void)
2047 LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
2049 for (i = 1; i <= MaxBackends; i++)
2051 if (QUEUE_BACKEND_PID(i) != InvalidPid)
2052 min = QUEUE_POS_MIN(min, QUEUE_BACKEND_POS(i));
2054 oldtailpage = QUEUE_POS_PAGE(QUEUE_TAIL);
2056 LWLockRelease(AsyncQueueLock);
2059 * We can truncate something if the global tail advanced across an SLRU
2062 * XXX it might be better to truncate only once every several segments, to
2063 * reduce the number of directory scans.
2065 newtailpage = QUEUE_POS_PAGE(min);
2066 boundary = newtailpage - (newtailpage % SLRU_PAGES_PER_SEGMENT);
2067 if (asyncQueuePagePrecedesLogically(oldtailpage, boundary))
2070 * SimpleLruTruncate() will ask for AsyncCtlLock but will also release
2073 SimpleLruTruncate(AsyncCtl, newtailpage);
2078 * ProcessIncomingNotify
2080 * Deal with arriving NOTIFYs from other backends.
2081 * This is called either directly from the PROCSIG_NOTIFY_INTERRUPT
2082 * signal handler, or the next time control reaches the outer idle loop.
2083 * Scan the queue for arriving notifications and report them to my front
2086 * NOTE: since we are outside any transaction, we must create our own.
2089 ProcessIncomingNotify(void)
2091 bool catchup_enabled;
2093 /* We *must* reset the flag */
2094 notifyInterruptOccurred = 0;
2096 /* Do nothing else if we aren't actively listening */
2097 if (listenChannels == NIL)
2100 /* Must prevent catchup interrupt while I am running */
2101 catchup_enabled = DisableCatchupInterrupt();
2104 elog(DEBUG1, "ProcessIncomingNotify");
2106 set_ps_display("notify interrupt", false);
2109 * We must run asyncQueueReadAllNotifications inside a transaction, else
2110 * bad things happen if it gets an error.
2112 StartTransactionCommand();
2114 asyncQueueReadAllNotifications();
2116 CommitTransactionCommand();
2119 * Must flush the notify messages to ensure frontend gets them promptly.
2123 set_ps_display("idle", false);
2126 elog(DEBUG1, "ProcessIncomingNotify: done");
2128 if (catchup_enabled)
2129 EnableCatchupInterrupt();
2133 * Send NOTIFY message to my front end.
2136 NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
2138 if (whereToSendOutput == DestRemote)
2142 pq_beginmessage(&buf, 'A');
2143 pq_sendint(&buf, srcPid, sizeof(int32));
2144 pq_sendstring(&buf, channel);
2145 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2146 pq_sendstring(&buf, payload);
2147 pq_endmessage(&buf);
2150 * NOTE: we do not do pq_flush() here. For a self-notify, it will
2151 * happen at the end of the transaction, and for incoming notifies
2152 * ProcessIncomingNotify will do it after finding all the notifies.
2156 elog(INFO, "NOTIFY for \"%s\" payload \"%s\"", channel, payload);
2159 /* Does pendingNotifies include the given channel/payload? */
2161 AsyncExistsPendingNotify(const char *channel, const char *payload)
2166 if (pendingNotifies == NIL)
2169 if (payload == NULL)
2173 * We need to append new elements to the end of the list in order to keep
2174 * the order. However, on the other hand we'd like to check the list
2175 * backwards in order to make duplicate-elimination a tad faster when the
2176 * same condition is signaled many times in a row. So as a compromise we
2177 * check the tail element first which we can access directly. If this
2178 * doesn't match, we check the whole list.
2180 * As we are not checking our parents' lists, we can still get duplicates
2181 * in combination with subtransactions, like in:
2190 n = (Notification *) llast(pendingNotifies);
2191 if (strcmp(n->channel, channel) == 0 &&
2192 strcmp(n->payload, payload) == 0)
2195 foreach(p, pendingNotifies)
2197 n = (Notification *) lfirst(p);
2199 if (strcmp(n->channel, channel) == 0 &&
2200 strcmp(n->payload, payload) == 0)
2207 /* Clear the pendingActions and pendingNotifies lists. */
2209 ClearPendingActionsAndNotifies(void)
2212 * We used to have to explicitly deallocate the list members and nodes,
2213 * because they were malloc'd. Now, since we know they are palloc'd in
2214 * CurTransactionContext, we need not do that --- they'll go away
2215 * automatically at transaction exit. We need only reset the list head
2218 pendingActions = NIL;
2219 pendingNotifies = NIL;