PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
async.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * async.c
4  * Asynchronous notification: NOTIFY, LISTEN, UNLISTEN
5  *
6  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/commands/async.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 
15 /*-------------------------------------------------------------------------
16  * Async Notification Model as of 9.0:
17  *
18  * 1. Multiple backends on same machine. Multiple backends listening on
19  * several channels. (Channels are also called "conditions" in other
20  * parts of the code.)
21  *
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.
26  *
27  * There is no central knowledge of which backend listens on which channel;
28  * every backend has its own list of interesting channels.
29  *
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.
36  *
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.
40  *
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.
48  *
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.
51  *
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
57  * payload parameter.
58  *
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
65  * will roll back.
66  *
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.
69  *
70  * After commit we are called another time (AtCommit_Notify()). Here we
71  * make the actual updates to the effective listen state (listenChannels).
72  *
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.
80  *
81  * 5. Upon receipt of a PROCSIG_NOTIFY_INTERRUPT signal, the signal handler
82  * sets the process's latch, which triggers the event to be processed
83  * immediately if this backend is idle (i.e., it is waiting for a frontend
84  * command and is not within a transaction block. C.f.
85  * ProcessClientReadInterrupt()). Otherwise the handler may only set a
86  * flag, which will cause the processing to occur just before we next go
87  * idle.
88  *
89  * Inbound-notify processing consists of reading all of the notifications
90  * that have arrived since scanning last time. We read every notification
91  * until we reach either a notification from an uncommitted transaction or
92  * the head pointer's position. Then we check if we were the laziest
93  * backend: if our pointer is set to the same position as the global tail
94  * pointer is set, then we move the global tail pointer ahead to where the
95  * second-laziest backend is (in general, we take the MIN of the current
96  * head position and all active backends' new tail pointers). Whenever we
97  * move the global tail pointer we also truncate now-unused pages (i.e.,
98  * delete files in pg_notify/ that are no longer used).
99  *
100  * An application that listens on the same channel it notifies will get
101  * NOTIFY messages for its own NOTIFYs. These can be ignored, if not useful,
102  * by comparing be_pid in the NOTIFY message to the application's own backend's
103  * PID. (As of FE/BE protocol 2.0, the backend's PID is provided to the
104  * frontend during startup.) The above design guarantees that notifies from
105  * other backends will never be missed by ignoring self-notifies.
106  *
107  * The amount of shared memory used for notify management (NUM_ASYNC_BUFFERS)
108  * can be varied without affecting anything but performance. The maximum
109  * amount of notification data that can be queued at one time is determined
110  * by slru.c's wraparound limit; see QUEUE_MAX_PAGE below.
111  *-------------------------------------------------------------------------
112  */
113 
114 #include "postgres.h"
115 
116 #include <limits.h>
117 #include <unistd.h>
118 #include <signal.h>
119 
120 #include "access/slru.h"
121 #include "access/transam.h"
122 #include "access/xact.h"
123 #include "catalog/pg_database.h"
124 #include "commands/async.h"
125 #include "funcapi.h"
126 #include "libpq/libpq.h"
127 #include "libpq/pqformat.h"
128 #include "miscadmin.h"
129 #include "storage/ipc.h"
130 #include "storage/lmgr.h"
131 #include "storage/proc.h"
132 #include "storage/procarray.h"
133 #include "storage/procsignal.h"
134 #include "storage/sinval.h"
135 #include "tcop/tcopprot.h"
136 #include "utils/builtins.h"
137 #include "utils/memutils.h"
138 #include "utils/ps_status.h"
139 #include "utils/timestamp.h"
140 
141 
142 /*
143  * Maximum size of a NOTIFY payload, including terminating NULL. This
144  * must be kept small enough so that a notification message fits on one
145  * SLRU page. The magic fudge factor here is noncritical as long as it's
146  * more than AsyncQueueEntryEmptySize --- we make it significantly bigger
147  * than that, so changes in that data structure won't affect user-visible
148  * restrictions.
149  */
150 #define NOTIFY_PAYLOAD_MAX_LENGTH (BLCKSZ - NAMEDATALEN - 128)
151 
152 /*
153  * Struct representing an entry in the global notify queue
154  *
155  * This struct declaration has the maximal length, but in a real queue entry
156  * the data area is only big enough for the actual channel and payload strings
157  * (each null-terminated). AsyncQueueEntryEmptySize is the minimum possible
158  * entry size, if both channel and payload strings are empty (but note it
159  * doesn't include alignment padding).
160  *
161  * The "length" field should always be rounded up to the next QUEUEALIGN
162  * multiple so that all fields are properly aligned.
163  */
164 typedef struct AsyncQueueEntry
165 {
166  int length; /* total allocated length of entry */
167  Oid dboid; /* sender's database OID */
168  TransactionId xid; /* sender's XID */
169  int32 srcPid; /* sender's PID */
172 
173 /* Currently, no field of AsyncQueueEntry requires more than int alignment */
174 #define QUEUEALIGN(len) INTALIGN(len)
175 
176 #define AsyncQueueEntryEmptySize (offsetof(AsyncQueueEntry, data) + 2)
177 
178 /*
179  * Struct describing a queue position, and assorted macros for working with it
180  */
181 typedef struct QueuePosition
182 {
183  int page; /* SLRU page number */
184  int offset; /* byte offset within page */
185 } QueuePosition;
186 
187 #define QUEUE_POS_PAGE(x) ((x).page)
188 #define QUEUE_POS_OFFSET(x) ((x).offset)
189 
190 #define SET_QUEUE_POS(x,y,z) \
191  do { \
192  (x).page = (y); \
193  (x).offset = (z); \
194  } while (0)
195 
196 #define QUEUE_POS_EQUAL(x,y) \
197  ((x).page == (y).page && (x).offset == (y).offset)
198 
199 /* choose logically smaller QueuePosition */
200 #define QUEUE_POS_MIN(x,y) \
201  (asyncQueuePagePrecedes((x).page, (y).page) ? (x) : \
202  (x).page != (y).page ? (y) : \
203  (x).offset < (y).offset ? (x) : (y))
204 
205 /*
206  * Struct describing a listening backend's status
207  */
208 typedef struct QueueBackendStatus
209 {
210  int32 pid; /* either a PID or InvalidPid */
211  QueuePosition pos; /* backend has read queue up to here */
213 
214 /*
215  * Shared memory state for LISTEN/NOTIFY (excluding its SLRU stuff)
216  *
217  * The AsyncQueueControl structure is protected by the AsyncQueueLock.
218  *
219  * When holding the lock in SHARED mode, backends may only inspect their own
220  * entries as well as the head and tail pointers. Consequently we can allow a
221  * backend to update its own record while holding only SHARED lock (since no
222  * other backend will inspect it).
223  *
224  * When holding the lock in EXCLUSIVE mode, backends can inspect the entries
225  * of other backends and also change the head and tail pointers.
226  *
227  * In order to avoid deadlocks, whenever we need both locks, we always first
228  * get AsyncQueueLock and then AsyncCtlLock.
229  *
230  * Each backend uses the backend[] array entry with index equal to its
231  * BackendId (which can range from 1 to MaxBackends). We rely on this to make
232  * SendProcSignal fast.
233  */
234 typedef struct AsyncQueueControl
235 {
236  QueuePosition head; /* head points to the next free location */
237  QueuePosition tail; /* the global tail is equivalent to the tail
238  * of the "slowest" backend */
239  TimestampTz lastQueueFillWarn; /* time of last queue-full msg */
240  QueueBackendStatus backend[FLEXIBLE_ARRAY_MEMBER];
241  /* backend[0] is not used; used entries are from [1] to [MaxBackends] */
243 
245 
246 #define QUEUE_HEAD (asyncQueueControl->head)
247 #define QUEUE_TAIL (asyncQueueControl->tail)
248 #define QUEUE_BACKEND_PID(i) (asyncQueueControl->backend[i].pid)
249 #define QUEUE_BACKEND_POS(i) (asyncQueueControl->backend[i].pos)
250 
251 /*
252  * The SLRU buffer area through which we access the notification queue
253  */
255 
256 #define AsyncCtl (&AsyncCtlData)
257 #define QUEUE_PAGESIZE BLCKSZ
258 #define QUEUE_FULL_WARN_INTERVAL 5000 /* warn at most once every 5s */
259 
260 /*
261  * slru.c currently assumes that all filenames are four characters of hex
262  * digits. That means that we can use segments 0000 through FFFF.
263  * Each segment contains SLRU_PAGES_PER_SEGMENT pages which gives us
264  * the pages from 0 to SLRU_PAGES_PER_SEGMENT * 0x10000 - 1.
265  *
266  * It's of course possible to enhance slru.c, but this gives us so much
267  * space already that it doesn't seem worth the trouble.
268  *
269  * The most data we can have in the queue at a time is QUEUE_MAX_PAGE/2
270  * pages, because more than that would confuse slru.c into thinking there
271  * was a wraparound condition. With the default BLCKSZ this means there
272  * can be up to 8GB of queued-and-not-read data.
273  *
274  * Note: it's possible to redefine QUEUE_MAX_PAGE with a smaller multiple of
275  * SLRU_PAGES_PER_SEGMENT, for easier testing of queue-full behaviour.
276  */
277 #define QUEUE_MAX_PAGE (SLRU_PAGES_PER_SEGMENT * 0x10000 - 1)
278 
279 /*
280  * listenChannels identifies the channels we are actually listening to
281  * (ie, have committed a LISTEN on). It is a simple list of channel names,
282  * allocated in TopMemoryContext.
283  */
284 static List *listenChannels = NIL; /* list of C strings */
285 
286 /*
287  * State for pending LISTEN/UNLISTEN actions consists of an ordered list of
288  * all actions requested in the current transaction. As explained above,
289  * we don't actually change listenChannels until we reach transaction commit.
290  *
291  * The list is kept in CurTransactionContext. In subtransactions, each
292  * subtransaction has its own list in its own CurTransactionContext, but
293  * successful subtransactions attach their lists to their parent's list.
294  * Failed subtransactions simply discard their lists.
295  */
296 typedef enum
297 {
302 
303 typedef struct
304 {
306  char channel[FLEXIBLE_ARRAY_MEMBER]; /* nul-terminated string */
307 } ListenAction;
308 
309 static List *pendingActions = NIL; /* list of ListenAction */
310 
311 static List *upperPendingActions = NIL; /* list of upper-xact lists */
312 
313 /*
314  * State for outbound notifies consists of a list of all channels+payloads
315  * NOTIFYed in the current transaction. We do not actually perform a NOTIFY
316  * until and unless the transaction commits. pendingNotifies is NIL if no
317  * NOTIFYs have been done in the current transaction.
318  *
319  * The list is kept in CurTransactionContext. In subtransactions, each
320  * subtransaction has its own list in its own CurTransactionContext, but
321  * successful subtransactions attach their lists to their parent's list.
322  * Failed subtransactions simply discard their lists.
323  *
324  * Note: the action and notify lists do not interact within a transaction.
325  * In particular, if a transaction does NOTIFY and then LISTEN on the same
326  * condition name, it will get a self-notify at commit. This is a bit odd
327  * but is consistent with our historical behavior.
328  */
329 typedef struct Notification
330 {
331  char *channel; /* channel name */
332  char *payload; /* payload string (can be empty) */
333 } Notification;
334 
335 static List *pendingNotifies = NIL; /* list of Notifications */
336 
337 static List *upperPendingNotifies = NIL; /* list of upper-xact lists */
338 
339 /*
340  * Inbound notifications are initially processed by HandleNotifyInterrupt(),
341  * called from inside a signal handler. That just sets the
342  * notifyInterruptPending flag and sets the process
343  * latch. ProcessNotifyInterrupt() will then be called whenever it's safe to
344  * actually deal with the interrupt.
345  */
346 volatile sig_atomic_t notifyInterruptPending = false;
347 
348 /* True if we've registered an on_shmem_exit cleanup */
349 static bool unlistenExitRegistered = false;
350 
351 /* True if we're currently registered as a listener in asyncQueueControl */
352 static bool amRegisteredListener = false;
353 
354 /* has this backend sent notifications in the current transaction? */
355 static bool backendHasSentNotifications = false;
356 
357 /* GUC parameter */
358 bool Trace_notify = false;
359 
360 /* local function prototypes */
361 static bool asyncQueuePagePrecedes(int p, int q);
362 static void queue_listen(ListenActionKind action, const char *channel);
363 static void Async_UnlistenOnExit(int code, Datum arg);
364 static void Exec_ListenPreCommit(void);
365 static void Exec_ListenCommit(const char *channel);
366 static void Exec_UnlistenCommit(const char *channel);
367 static void Exec_UnlistenAllCommit(void);
368 static bool IsListeningOn(const char *channel);
369 static void asyncQueueUnregister(void);
370 static bool asyncQueueIsFull(void);
371 static bool asyncQueueAdvance(volatile QueuePosition *position, int entryLength);
373 static ListCell *asyncQueueAddEntries(ListCell *nextNotify);
374 static double asyncQueueUsage(void);
375 static void asyncQueueFillWarning(void);
376 static bool SignalBackends(void);
377 static void asyncQueueReadAllNotifications(void);
378 static bool asyncQueueProcessPageEntries(volatile QueuePosition *current,
379  QueuePosition stop,
380  char *page_buffer);
381 static void asyncQueueAdvanceTail(void);
382 static void ProcessIncomingNotify(void);
383 static void NotifyMyFrontEnd(const char *channel,
384  const char *payload,
385  int32 srcPid);
386 static bool AsyncExistsPendingNotify(const char *channel, const char *payload);
387 static void ClearPendingActionsAndNotifies(void);
388 
389 /*
390  * We will work on the page range of 0..QUEUE_MAX_PAGE.
391  */
392 static bool
394 {
395  int diff;
396 
397  /*
398  * We have to compare modulo (QUEUE_MAX_PAGE+1)/2. Both inputs should be
399  * in the range 0..QUEUE_MAX_PAGE.
400  */
401  Assert(p >= 0 && p <= QUEUE_MAX_PAGE);
402  Assert(q >= 0 && q <= QUEUE_MAX_PAGE);
403 
404  diff = p - q;
405  if (diff >= ((QUEUE_MAX_PAGE + 1) / 2))
406  diff -= QUEUE_MAX_PAGE + 1;
407  else if (diff < -((QUEUE_MAX_PAGE + 1) / 2))
408  diff += QUEUE_MAX_PAGE + 1;
409  return diff < 0;
410 }
411 
412 /*
413  * Report space needed for our shared memory area
414  */
415 Size
417 {
418  Size size;
419 
420  /* This had better match AsyncShmemInit */
421  size = mul_size(MaxBackends + 1, sizeof(QueueBackendStatus));
422  size = add_size(size, offsetof(AsyncQueueControl, backend));
423 
425 
426  return size;
427 }
428 
429 /*
430  * Initialize our shared memory area
431  */
432 void
434 {
435  bool found;
436  int slotno;
437  Size size;
438 
439  /*
440  * Create or attach to the AsyncQueueControl structure.
441  *
442  * The used entries in the backend[] array run from 1 to MaxBackends; the
443  * zero'th entry is unused but must be allocated.
444  */
445  size = mul_size(MaxBackends + 1, sizeof(QueueBackendStatus));
446  size = add_size(size, offsetof(AsyncQueueControl, backend));
447 
448  asyncQueueControl = (AsyncQueueControl *)
449  ShmemInitStruct("Async Queue Control", size, &found);
450 
451  if (!found)
452  {
453  /* First time through, so initialize it */
454  int i;
455 
456  SET_QUEUE_POS(QUEUE_HEAD, 0, 0);
457  SET_QUEUE_POS(QUEUE_TAIL, 0, 0);
458  asyncQueueControl->lastQueueFillWarn = 0;
459  /* zero'th entry won't be used, but let's initialize it anyway */
460  for (i = 0; i <= MaxBackends; i++)
461  {
464  }
465  }
466 
467  /*
468  * Set up SLRU management of the pg_notify data.
469  */
470  AsyncCtl->PagePrecedes = asyncQueuePagePrecedes;
471  SimpleLruInit(AsyncCtl, "Async Ctl", NUM_ASYNC_BUFFERS, 0,
472  AsyncCtlLock, "pg_notify");
473  /* Override default assumption that writes should be fsync'd */
474  AsyncCtl->do_fsync = false;
475 
476  if (!found)
477  {
478  /*
479  * During start or reboot, clean out the pg_notify directory.
480  */
482 
483  /* Now initialize page zero to empty */
484  LWLockAcquire(AsyncCtlLock, LW_EXCLUSIVE);
486  /* This write is just to verify that pg_notify/ is writable */
487  SimpleLruWritePage(AsyncCtl, slotno);
488  LWLockRelease(AsyncCtlLock);
489  }
490 }
491 
492 
493 /*
494  * pg_notify -
495  * SQL function to send a notification event
496  */
497 Datum
499 {
500  const char *channel;
501  const char *payload;
502 
503  if (PG_ARGISNULL(0))
504  channel = "";
505  else
506  channel = text_to_cstring(PG_GETARG_TEXT_PP(0));
507 
508  if (PG_ARGISNULL(1))
509  payload = "";
510  else
511  payload = text_to_cstring(PG_GETARG_TEXT_PP(1));
512 
513  /* For NOTIFY as a statement, this is checked in ProcessUtility */
515 
516  Async_Notify(channel, payload);
517 
518  PG_RETURN_VOID();
519 }
520 
521 
522 /*
523  * Async_Notify
524  *
525  * This is executed by the SQL notify command.
526  *
527  * Adds the message to the list of pending notifies.
528  * Actual notification happens during transaction commit.
529  * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
530  */
531 void
532 Async_Notify(const char *channel, const char *payload)
533 {
534  Notification *n;
535  MemoryContext oldcontext;
536 
537  if (Trace_notify)
538  elog(DEBUG1, "Async_Notify(%s)", channel);
539 
540  /* a channel name must be specified */
541  if (!channel || !strlen(channel))
542  ereport(ERROR,
543  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
544  errmsg("channel name cannot be empty")));
545 
546  if (strlen(channel) >= NAMEDATALEN)
547  ereport(ERROR,
548  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
549  errmsg("channel name too long")));
550 
551  if (payload)
552  {
553  if (strlen(payload) >= NOTIFY_PAYLOAD_MAX_LENGTH)
554  ereport(ERROR,
555  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
556  errmsg("payload string too long")));
557  }
558 
559  /* no point in making duplicate entries in the list ... */
560  if (AsyncExistsPendingNotify(channel, payload))
561  return;
562 
563  /*
564  * The notification list needs to live until end of transaction, so store
565  * it in the transaction context.
566  */
568 
569  n = (Notification *) palloc(sizeof(Notification));
570  n->channel = pstrdup(channel);
571  if (payload)
572  n->payload = pstrdup(payload);
573  else
574  n->payload = "";
575 
576  /*
577  * We want to preserve the order so we need to append every notification.
578  * See comments at AsyncExistsPendingNotify().
579  */
580  pendingNotifies = lappend(pendingNotifies, n);
581 
582  MemoryContextSwitchTo(oldcontext);
583 }
584 
585 /*
586  * queue_listen
587  * Common code for listen, unlisten, unlisten all commands.
588  *
589  * Adds the request to the list of pending actions.
590  * Actual update of the listenChannels list happens during transaction
591  * commit.
592  */
593 static void
594 queue_listen(ListenActionKind action, const char *channel)
595 {
596  MemoryContext oldcontext;
597  ListenAction *actrec;
598 
599  /*
600  * Unlike Async_Notify, we don't try to collapse out duplicates. It would
601  * be too complicated to ensure we get the right interactions of
602  * conflicting LISTEN/UNLISTEN/UNLISTEN_ALL, and it's unlikely that there
603  * would be any performance benefit anyway in sane applications.
604  */
606 
607  /* space for terminating null is included in sizeof(ListenAction) */
608  actrec = (ListenAction *) palloc(offsetof(ListenAction, channel) +
609  strlen(channel) + 1);
610  actrec->action = action;
611  strcpy(actrec->channel, channel);
612 
613  pendingActions = lappend(pendingActions, actrec);
614 
615  MemoryContextSwitchTo(oldcontext);
616 }
617 
618 /*
619  * Async_Listen
620  *
621  * This is executed by the SQL listen command.
622  */
623 void
624 Async_Listen(const char *channel)
625 {
626  if (Trace_notify)
627  elog(DEBUG1, "Async_Listen(%s,%d)", channel, MyProcPid);
628 
629  queue_listen(LISTEN_LISTEN, channel);
630 }
631 
632 /*
633  * Async_Unlisten
634  *
635  * This is executed by the SQL unlisten command.
636  */
637 void
638 Async_Unlisten(const char *channel)
639 {
640  if (Trace_notify)
641  elog(DEBUG1, "Async_Unlisten(%s,%d)", channel, MyProcPid);
642 
643  /* If we couldn't possibly be listening, no need to queue anything */
644  if (pendingActions == NIL && !unlistenExitRegistered)
645  return;
646 
647  queue_listen(LISTEN_UNLISTEN, channel);
648 }
649 
650 /*
651  * Async_UnlistenAll
652  *
653  * This is invoked by UNLISTEN * command, and also at backend exit.
654  */
655 void
657 {
658  if (Trace_notify)
659  elog(DEBUG1, "Async_UnlistenAll(%d)", MyProcPid);
660 
661  /* If we couldn't possibly be listening, no need to queue anything */
662  if (pendingActions == NIL && !unlistenExitRegistered)
663  return;
664 
666 }
667 
668 /*
669  * SQL function: return a set of the channel names this backend is actively
670  * listening to.
671  *
672  * Note: this coding relies on the fact that the listenChannels list cannot
673  * change within a transaction.
674  */
675 Datum
677 {
678  FuncCallContext *funcctx;
679  ListCell **lcp;
680 
681  /* stuff done only on the first call of the function */
682  if (SRF_IS_FIRSTCALL())
683  {
684  MemoryContext oldcontext;
685 
686  /* create a function context for cross-call persistence */
687  funcctx = SRF_FIRSTCALL_INIT();
688 
689  /* switch to memory context appropriate for multiple function calls */
690  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
691 
692  /* allocate memory for user context */
693  lcp = (ListCell **) palloc(sizeof(ListCell *));
694  *lcp = list_head(listenChannels);
695  funcctx->user_fctx = (void *) lcp;
696 
697  MemoryContextSwitchTo(oldcontext);
698  }
699 
700  /* stuff done on every call of the function */
701  funcctx = SRF_PERCALL_SETUP();
702  lcp = (ListCell **) funcctx->user_fctx;
703 
704  while (*lcp != NULL)
705  {
706  char *channel = (char *) lfirst(*lcp);
707 
708  *lcp = lnext(*lcp);
709  SRF_RETURN_NEXT(funcctx, CStringGetTextDatum(channel));
710  }
711 
712  SRF_RETURN_DONE(funcctx);
713 }
714 
715 /*
716  * Async_UnlistenOnExit
717  *
718  * This is executed at backend exit if we have done any LISTENs in this
719  * backend. It might not be necessary anymore, if the user UNLISTENed
720  * everything, but we don't try to detect that case.
721  */
722 static void
724 {
727 }
728 
729 /*
730  * AtPrepare_Notify
731  *
732  * This is called at the prepare phase of a two-phase
733  * transaction. Save the state for possible commit later.
734  */
735 void
737 {
738  /* It's not allowed to have any pending LISTEN/UNLISTEN/NOTIFY actions */
739  if (pendingActions || pendingNotifies)
740  ereport(ERROR,
741  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
742  errmsg("cannot PREPARE a transaction that has executed LISTEN, UNLISTEN, or NOTIFY")));
743 }
744 
745 /*
746  * PreCommit_Notify
747  *
748  * This is called at transaction commit, before actually committing to
749  * clog.
750  *
751  * If there are pending LISTEN actions, make sure we are listed in the
752  * shared-memory listener array. This must happen before commit to
753  * ensure we don't miss any notifies from transactions that commit
754  * just after ours.
755  *
756  * If there are outbound notify requests in the pendingNotifies list,
757  * add them to the global queue. We do that before commit so that
758  * we can still throw error if we run out of queue space.
759  */
760 void
762 {
763  ListCell *p;
764 
765  if (pendingActions == NIL && pendingNotifies == NIL)
766  return; /* no relevant statements in this xact */
767 
768  if (Trace_notify)
769  elog(DEBUG1, "PreCommit_Notify");
770 
771  /* Preflight for any pending listen/unlisten actions */
772  foreach(p, pendingActions)
773  {
774  ListenAction *actrec = (ListenAction *) lfirst(p);
775 
776  switch (actrec->action)
777  {
778  case LISTEN_LISTEN:
780  break;
781  case LISTEN_UNLISTEN:
782  /* there is no Exec_UnlistenPreCommit() */
783  break;
784  case LISTEN_UNLISTEN_ALL:
785  /* there is no Exec_UnlistenAllPreCommit() */
786  break;
787  }
788  }
789 
790  /* Queue any pending notifies */
791  if (pendingNotifies)
792  {
793  ListCell *nextNotify;
794 
795  /*
796  * Make sure that we have an XID assigned to the current transaction.
797  * GetCurrentTransactionId is cheap if we already have an XID, but not
798  * so cheap if we don't, and we'd prefer not to do that work while
799  * holding AsyncQueueLock.
800  */
801  (void) GetCurrentTransactionId();
802 
803  /*
804  * Serialize writers by acquiring a special lock that we hold till
805  * after commit. This ensures that queue entries appear in commit
806  * order, and in particular that there are never uncommitted queue
807  * entries ahead of committed ones, so an uncommitted transaction
808  * can't block delivery of deliverable notifications.
809  *
810  * We use a heavyweight lock so that it'll automatically be released
811  * after either commit or abort. This also allows deadlocks to be
812  * detected, though really a deadlock shouldn't be possible here.
813  *
814  * The lock is on "database 0", which is pretty ugly but it doesn't
815  * seem worth inventing a special locktag category just for this.
816  * (Historical note: before PG 9.0, a similar lock on "database 0" was
817  * used by the flatfiles mechanism.)
818  */
821 
822  /* Now push the notifications into the queue */
824 
825  nextNotify = list_head(pendingNotifies);
826  while (nextNotify != NULL)
827  {
828  /*
829  * Add the pending notifications to the queue. We acquire and
830  * release AsyncQueueLock once per page, which might be overkill
831  * but it does allow readers to get in while we're doing this.
832  *
833  * A full queue is very uncommon and should really not happen,
834  * given that we have so much space available in the SLRU pages.
835  * Nevertheless we need to deal with this possibility. Note that
836  * when we get here we are in the process of committing our
837  * transaction, but we have not yet committed to clog, so at this
838  * point in time we can still roll the transaction back.
839  */
840  LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
842  if (asyncQueueIsFull())
843  ereport(ERROR,
844  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
845  errmsg("too many notifications in the NOTIFY queue")));
846  nextNotify = asyncQueueAddEntries(nextNotify);
847  LWLockRelease(AsyncQueueLock);
848  }
849  }
850 }
851 
852 /*
853  * AtCommit_Notify
854  *
855  * This is called at transaction commit, after committing to clog.
856  *
857  * Update listenChannels and clear transaction-local state.
858  */
859 void
861 {
862  ListCell *p;
863 
864  /*
865  * Allow transactions that have not executed LISTEN/UNLISTEN/NOTIFY to
866  * return as soon as possible
867  */
868  if (!pendingActions && !pendingNotifies)
869  return;
870 
871  if (Trace_notify)
872  elog(DEBUG1, "AtCommit_Notify");
873 
874  /* Perform any pending listen/unlisten actions */
875  foreach(p, pendingActions)
876  {
877  ListenAction *actrec = (ListenAction *) lfirst(p);
878 
879  switch (actrec->action)
880  {
881  case LISTEN_LISTEN:
882  Exec_ListenCommit(actrec->channel);
883  break;
884  case LISTEN_UNLISTEN:
885  Exec_UnlistenCommit(actrec->channel);
886  break;
887  case LISTEN_UNLISTEN_ALL:
889  break;
890  }
891  }
892 
893  /* If no longer listening to anything, get out of listener array */
894  if (amRegisteredListener && listenChannels == NIL)
896 
897  /* And clean up */
899 }
900 
901 /*
902  * Exec_ListenPreCommit --- subroutine for PreCommit_Notify
903  *
904  * This function must make sure we are ready to catch any incoming messages.
905  */
906 static void
908 {
909  /*
910  * Nothing to do if we are already listening to something, nor if we
911  * already ran this routine in this transaction.
912  */
914  return;
915 
916  if (Trace_notify)
917  elog(DEBUG1, "Exec_ListenPreCommit(%d)", MyProcPid);
918 
919  /*
920  * Before registering, make sure we will unlisten before dying. (Note:
921  * this action does not get undone if we abort later.)
922  */
924  {
926  unlistenExitRegistered = true;
927  }
928 
929  /*
930  * This is our first LISTEN, so establish our pointer.
931  *
932  * We set our pointer to the global tail pointer and then move it forward
933  * over already-committed notifications. This ensures we cannot miss any
934  * not-yet-committed notifications. We might get a few more but that
935  * doesn't hurt.
936  */
937  LWLockAcquire(AsyncQueueLock, LW_SHARED);
940  LWLockRelease(AsyncQueueLock);
941 
942  /* Now we are listed in the global array, so remember we're listening */
943  amRegisteredListener = true;
944 
945  /*
946  * Try to move our pointer forward as far as possible. This will skip over
947  * already-committed notifications. Still, we could get notifications that
948  * have already committed before we started to LISTEN.
949  *
950  * Note that we are not yet listening on anything, so we won't deliver any
951  * notification to the frontend.
952  *
953  * This will also advance the global tail pointer if possible.
954  */
956 }
957 
958 /*
959  * Exec_ListenCommit --- subroutine for AtCommit_Notify
960  *
961  * Add the channel to the list of channels we are listening on.
962  */
963 static void
964 Exec_ListenCommit(const char *channel)
965 {
966  MemoryContext oldcontext;
967 
968  /* Do nothing if we are already listening on this channel */
969  if (IsListeningOn(channel))
970  return;
971 
972  /*
973  * Add the new channel name to listenChannels.
974  *
975  * XXX It is theoretically possible to get an out-of-memory failure here,
976  * which would be bad because we already committed. For the moment it
977  * doesn't seem worth trying to guard against that, but maybe improve this
978  * later.
979  */
981  listenChannels = lappend(listenChannels, pstrdup(channel));
982  MemoryContextSwitchTo(oldcontext);
983 }
984 
985 /*
986  * Exec_UnlistenCommit --- subroutine for AtCommit_Notify
987  *
988  * Remove the specified channel name from listenChannels.
989  */
990 static void
991 Exec_UnlistenCommit(const char *channel)
992 {
993  ListCell *q;
994  ListCell *prev;
995 
996  if (Trace_notify)
997  elog(DEBUG1, "Exec_UnlistenCommit(%s,%d)", channel, MyProcPid);
998 
999  prev = NULL;
1000  foreach(q, listenChannels)
1001  {
1002  char *lchan = (char *) lfirst(q);
1003 
1004  if (strcmp(lchan, channel) == 0)
1005  {
1006  listenChannels = list_delete_cell(listenChannels, q, prev);
1007  pfree(lchan);
1008  break;
1009  }
1010  prev = q;
1011  }
1012 
1013  /*
1014  * We do not complain about unlistening something not being listened;
1015  * should we?
1016  */
1017 }
1018 
1019 /*
1020  * Exec_UnlistenAllCommit --- subroutine for AtCommit_Notify
1021  *
1022  * Unlisten on all channels for this backend.
1023  */
1024 static void
1026 {
1027  if (Trace_notify)
1028  elog(DEBUG1, "Exec_UnlistenAllCommit(%d)", MyProcPid);
1029 
1030  list_free_deep(listenChannels);
1031  listenChannels = NIL;
1032 }
1033 
1034 /*
1035  * ProcessCompletedNotifies --- send out signals and self-notifies
1036  *
1037  * This is called from postgres.c just before going idle at the completion
1038  * of a transaction. If we issued any notifications in the just-completed
1039  * transaction, send signals to other backends to process them, and also
1040  * process the queue ourselves to send messages to our own frontend.
1041  *
1042  * The reason that this is not done in AtCommit_Notify is that there is
1043  * a nonzero chance of errors here (for example, encoding conversion errors
1044  * while trying to format messages to our frontend). An error during
1045  * AtCommit_Notify would be a PANIC condition. The timing is also arranged
1046  * to ensure that a transaction's self-notifies are delivered to the frontend
1047  * before it gets the terminating ReadyForQuery message.
1048  *
1049  * Note that we send signals and process the queue even if the transaction
1050  * eventually aborted. This is because we need to clean out whatever got
1051  * added to the queue.
1052  *
1053  * NOTE: we are outside of any transaction here.
1054  */
1055 void
1057 {
1058  MemoryContext caller_context;
1059  bool signalled;
1060 
1061  /* Nothing to do if we didn't send any notifications */
1063  return;
1064 
1065  /*
1066  * We reset the flag immediately; otherwise, if any sort of error occurs
1067  * below, we'd be locked up in an infinite loop, because control will come
1068  * right back here after error cleanup.
1069  */
1071 
1072  /*
1073  * We must preserve the caller's memory context (probably MessageContext)
1074  * across the transaction we do here.
1075  */
1076  caller_context = CurrentMemoryContext;
1077 
1078  if (Trace_notify)
1079  elog(DEBUG1, "ProcessCompletedNotifies");
1080 
1081  /*
1082  * We must run asyncQueueReadAllNotifications inside a transaction, else
1083  * bad things happen if it gets an error.
1084  */
1086 
1087  /* Send signals to other backends */
1088  signalled = SignalBackends();
1089 
1090  if (listenChannels != NIL)
1091  {
1092  /* Read the queue ourselves, and send relevant stuff to the frontend */
1094  }
1095  else if (!signalled)
1096  {
1097  /*
1098  * If we found no other listening backends, and we aren't listening
1099  * ourselves, then we must execute asyncQueueAdvanceTail to flush the
1100  * queue, because ain't nobody else gonna do it. This prevents queue
1101  * overflow when we're sending useless notifies to nobody. (A new
1102  * listener could have joined since we looked, but if so this is
1103  * harmless.)
1104  */
1106  }
1107 
1109 
1110  MemoryContextSwitchTo(caller_context);
1111 
1112  /* We don't need pq_flush() here since postgres.c will do one shortly */
1113 }
1114 
1115 /*
1116  * Test whether we are actively listening on the given channel name.
1117  *
1118  * Note: this function is executed for every notification found in the queue.
1119  * Perhaps it is worth further optimization, eg convert the list to a sorted
1120  * array so we can binary-search it. In practice the list is likely to be
1121  * fairly short, though.
1122  */
1123 static bool
1124 IsListeningOn(const char *channel)
1125 {
1126  ListCell *p;
1127 
1128  foreach(p, listenChannels)
1129  {
1130  char *lchan = (char *) lfirst(p);
1131 
1132  if (strcmp(lchan, channel) == 0)
1133  return true;
1134  }
1135  return false;
1136 }
1137 
1138 /*
1139  * Remove our entry from the listeners array when we are no longer listening
1140  * on any channel. NB: must not fail if we're already not listening.
1141  */
1142 static void
1144 {
1145  bool advanceTail;
1146 
1147  Assert(listenChannels == NIL); /* else caller error */
1148 
1149  if (!amRegisteredListener) /* nothing to do */
1150  return;
1151 
1152  LWLockAcquire(AsyncQueueLock, LW_SHARED);
1153  /* check if entry is valid and oldest ... */
1154  advanceTail = (MyProcPid == QUEUE_BACKEND_PID(MyBackendId)) &&
1156  /* ... then mark it invalid */
1158  LWLockRelease(AsyncQueueLock);
1159 
1160  /* mark ourselves as no longer listed in the global array */
1161  amRegisteredListener = false;
1162 
1163  /* If we were the laziest backend, try to advance the tail pointer */
1164  if (advanceTail)
1166 }
1167 
1168 /*
1169  * Test whether there is room to insert more notification messages.
1170  *
1171  * Caller must hold at least shared AsyncQueueLock.
1172  */
1173 static bool
1175 {
1176  int nexthead;
1177  int boundary;
1178 
1179  /*
1180  * The queue is full if creating a new head page would create a page that
1181  * logically precedes the current global tail pointer, ie, the head
1182  * pointer would wrap around compared to the tail. We cannot create such
1183  * a head page for fear of confusing slru.c. For safety we round the tail
1184  * pointer back to a segment boundary (compare the truncation logic in
1185  * asyncQueueAdvanceTail).
1186  *
1187  * Note that this test is *not* dependent on how much space there is on
1188  * the current head page. This is necessary because asyncQueueAddEntries
1189  * might try to create the next head page in any case.
1190  */
1191  nexthead = QUEUE_POS_PAGE(QUEUE_HEAD) + 1;
1192  if (nexthead > QUEUE_MAX_PAGE)
1193  nexthead = 0; /* wrap around */
1194  boundary = QUEUE_POS_PAGE(QUEUE_TAIL);
1195  boundary -= boundary % SLRU_PAGES_PER_SEGMENT;
1196  return asyncQueuePagePrecedes(nexthead, boundary);
1197 }
1198 
1199 /*
1200  * Advance the QueuePosition to the next entry, assuming that the current
1201  * entry is of length entryLength. If we jump to a new page the function
1202  * returns true, else false.
1203  */
1204 static bool
1205 asyncQueueAdvance(volatile QueuePosition *position, int entryLength)
1206 {
1207  int pageno = QUEUE_POS_PAGE(*position);
1208  int offset = QUEUE_POS_OFFSET(*position);
1209  bool pageJump = false;
1210 
1211  /*
1212  * Move to the next writing position: First jump over what we have just
1213  * written or read.
1214  */
1215  offset += entryLength;
1216  Assert(offset <= QUEUE_PAGESIZE);
1217 
1218  /*
1219  * In a second step check if another entry can possibly be written to the
1220  * page. If so, stay here, we have reached the next position. If not, then
1221  * we need to move on to the next page.
1222  */
1224  {
1225  pageno++;
1226  if (pageno > QUEUE_MAX_PAGE)
1227  pageno = 0; /* wrap around */
1228  offset = 0;
1229  pageJump = true;
1230  }
1231 
1232  SET_QUEUE_POS(*position, pageno, offset);
1233  return pageJump;
1234 }
1235 
1236 /*
1237  * Fill the AsyncQueueEntry at *qe with an outbound notification message.
1238  */
1239 static void
1241 {
1242  size_t channellen = strlen(n->channel);
1243  size_t payloadlen = strlen(n->payload);
1244  int entryLength;
1245 
1246  Assert(channellen < NAMEDATALEN);
1247  Assert(payloadlen < NOTIFY_PAYLOAD_MAX_LENGTH);
1248 
1249  /* The terminators are already included in AsyncQueueEntryEmptySize */
1250  entryLength = AsyncQueueEntryEmptySize + payloadlen + channellen;
1251  entryLength = QUEUEALIGN(entryLength);
1252  qe->length = entryLength;
1253  qe->dboid = MyDatabaseId;
1254  qe->xid = GetCurrentTransactionId();
1255  qe->srcPid = MyProcPid;
1256  memcpy(qe->data, n->channel, channellen + 1);
1257  memcpy(qe->data + channellen + 1, n->payload, payloadlen + 1);
1258 }
1259 
1260 /*
1261  * Add pending notifications to the queue.
1262  *
1263  * We go page by page here, i.e. we stop once we have to go to a new page but
1264  * we will be called again and then fill that next page. If an entry does not
1265  * fit into the current page, we write a dummy entry with an InvalidOid as the
1266  * database OID in order to fill the page. So every page is always used up to
1267  * the last byte which simplifies reading the page later.
1268  *
1269  * We are passed the list cell containing the next notification to write
1270  * and return the first still-unwritten cell back. Eventually we will return
1271  * NULL indicating all is done.
1272  *
1273  * We are holding AsyncQueueLock already from the caller and grab AsyncCtlLock
1274  * locally in this function.
1275  */
1276 static ListCell *
1278 {
1279  AsyncQueueEntry qe;
1280  QueuePosition queue_head;
1281  int pageno;
1282  int offset;
1283  int slotno;
1284 
1285  /* We hold both AsyncQueueLock and AsyncCtlLock during this operation */
1286  LWLockAcquire(AsyncCtlLock, LW_EXCLUSIVE);
1287 
1288  /*
1289  * We work with a local copy of QUEUE_HEAD, which we write back to shared
1290  * memory upon exiting. The reason for this is that if we have to advance
1291  * to a new page, SimpleLruZeroPage might fail (out of disk space, for
1292  * instance), and we must not advance QUEUE_HEAD if it does. (Otherwise,
1293  * subsequent insertions would try to put entries into a page that slru.c
1294  * thinks doesn't exist yet.) So, use a local position variable. Note
1295  * that if we do fail, any already-inserted queue entries are forgotten;
1296  * this is okay, since they'd be useless anyway after our transaction
1297  * rolls back.
1298  */
1299  queue_head = QUEUE_HEAD;
1300 
1301  /* Fetch the current page */
1302  pageno = QUEUE_POS_PAGE(queue_head);
1303  slotno = SimpleLruReadPage(AsyncCtl, pageno, true, InvalidTransactionId);
1304  /* Note we mark the page dirty before writing in it */
1305  AsyncCtl->shared->page_dirty[slotno] = true;
1306 
1307  while (nextNotify != NULL)
1308  {
1309  Notification *n = (Notification *) lfirst(nextNotify);
1310 
1311  /* Construct a valid queue entry in local variable qe */
1313 
1314  offset = QUEUE_POS_OFFSET(queue_head);
1315 
1316  /* Check whether the entry really fits on the current page */
1317  if (offset + qe.length <= QUEUE_PAGESIZE)
1318  {
1319  /* OK, so advance nextNotify past this item */
1320  nextNotify = lnext(nextNotify);
1321  }
1322  else
1323  {
1324  /*
1325  * Write a dummy entry to fill up the page. Actually readers will
1326  * only check dboid and since it won't match any reader's database
1327  * OID, they will ignore this entry and move on.
1328  */
1329  qe.length = QUEUE_PAGESIZE - offset;
1330  qe.dboid = InvalidOid;
1331  qe.data[0] = '\0'; /* empty channel */
1332  qe.data[1] = '\0'; /* empty payload */
1333  }
1334 
1335  /* Now copy qe into the shared buffer page */
1336  memcpy(AsyncCtl->shared->page_buffer[slotno] + offset,
1337  &qe,
1338  qe.length);
1339 
1340  /* Advance queue_head appropriately, and detect if page is full */
1341  if (asyncQueueAdvance(&(queue_head), qe.length))
1342  {
1343  /*
1344  * Page is full, so we're done here, but first fill the next page
1345  * with zeroes. The reason to do this is to ensure that slru.c's
1346  * idea of the head page is always the same as ours, which avoids
1347  * boundary problems in SimpleLruTruncate. The test in
1348  * asyncQueueIsFull() ensured that there is room to create this
1349  * page without overrunning the queue.
1350  */
1351  slotno = SimpleLruZeroPage(AsyncCtl, QUEUE_POS_PAGE(queue_head));
1352  /* And exit the loop */
1353  break;
1354  }
1355  }
1356 
1357  /* Success, so update the global QUEUE_HEAD */
1358  QUEUE_HEAD = queue_head;
1359 
1360  LWLockRelease(AsyncCtlLock);
1361 
1362  return nextNotify;
1363 }
1364 
1365 /*
1366  * SQL function to return the fraction of the notification queue currently
1367  * occupied.
1368  */
1369 Datum
1371 {
1372  double usage;
1373 
1374  LWLockAcquire(AsyncQueueLock, LW_SHARED);
1375  usage = asyncQueueUsage();
1376  LWLockRelease(AsyncQueueLock);
1377 
1378  PG_RETURN_FLOAT8(usage);
1379 }
1380 
1381 /*
1382  * Return the fraction of the queue that is currently occupied.
1383  *
1384  * The caller must hold AysncQueueLock in (at least) shared mode.
1385  */
1386 static double
1388 {
1389  int headPage = QUEUE_POS_PAGE(QUEUE_HEAD);
1390  int tailPage = QUEUE_POS_PAGE(QUEUE_TAIL);
1391  int occupied;
1392 
1393  occupied = headPage - tailPage;
1394 
1395  if (occupied == 0)
1396  return (double) 0; /* fast exit for common case */
1397 
1398  if (occupied < 0)
1399  {
1400  /* head has wrapped around, tail not yet */
1401  occupied += QUEUE_MAX_PAGE + 1;
1402  }
1403 
1404  return (double) occupied / (double) ((QUEUE_MAX_PAGE + 1) / 2);
1405 }
1406 
1407 /*
1408  * Check whether the queue is at least half full, and emit a warning if so.
1409  *
1410  * This is unlikely given the size of the queue, but possible.
1411  * The warnings show up at most once every QUEUE_FULL_WARN_INTERVAL.
1412  *
1413  * Caller must hold exclusive AsyncQueueLock.
1414  */
1415 static void
1417 {
1418  double fillDegree;
1419  TimestampTz t;
1420 
1421  fillDegree = asyncQueueUsage();
1422  if (fillDegree < 0.5)
1423  return;
1424 
1425  t = GetCurrentTimestamp();
1426 
1427  if (TimestampDifferenceExceeds(asyncQueueControl->lastQueueFillWarn,
1429  {
1430  QueuePosition min = QUEUE_HEAD;
1431  int32 minPid = InvalidPid;
1432  int i;
1433 
1434  for (i = 1; i <= MaxBackends; i++)
1435  {
1436  if (QUEUE_BACKEND_PID(i) != InvalidPid)
1437  {
1438  min = QUEUE_POS_MIN(min, QUEUE_BACKEND_POS(i));
1439  if (QUEUE_POS_EQUAL(min, QUEUE_BACKEND_POS(i)))
1440  minPid = QUEUE_BACKEND_PID(i);
1441  }
1442  }
1443 
1444  ereport(WARNING,
1445  (errmsg("NOTIFY queue is %.0f%% full", fillDegree * 100),
1446  (minPid != InvalidPid ?
1447  errdetail("The server process with PID %d is among those with the oldest transactions.", minPid)
1448  : 0),
1449  (minPid != InvalidPid ?
1450  errhint("The NOTIFY queue cannot be emptied until that process ends its current transaction.")
1451  : 0)));
1452 
1453  asyncQueueControl->lastQueueFillWarn = t;
1454  }
1455 }
1456 
1457 /*
1458  * Send signals to all listening backends (except our own).
1459  *
1460  * Returns true if we sent at least one signal.
1461  *
1462  * Since we need EXCLUSIVE lock anyway we also check the position of the other
1463  * backends and in case one is already up-to-date we don't signal it.
1464  * This can happen if concurrent notifying transactions have sent a signal and
1465  * the signaled backend has read the other notifications and ours in the same
1466  * step.
1467  *
1468  * Since we know the BackendId and the Pid the signalling is quite cheap.
1469  */
1470 static bool
1472 {
1473  bool signalled = false;
1474  int32 *pids;
1475  BackendId *ids;
1476  int count;
1477  int i;
1478  int32 pid;
1479 
1480  /*
1481  * Identify all backends that are listening and not already up-to-date. We
1482  * don't want to send signals while holding the AsyncQueueLock, so we just
1483  * build a list of target PIDs.
1484  *
1485  * XXX in principle these pallocs could fail, which would be bad. Maybe
1486  * preallocate the arrays? But in practice this is only run in trivial
1487  * transactions, so there should surely be space available.
1488  */
1489  pids = (int32 *) palloc(MaxBackends * sizeof(int32));
1490  ids = (BackendId *) palloc(MaxBackends * sizeof(BackendId));
1491  count = 0;
1492 
1493  LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
1494  for (i = 1; i <= MaxBackends; i++)
1495  {
1496  pid = QUEUE_BACKEND_PID(i);
1497  if (pid != InvalidPid && pid != MyProcPid)
1498  {
1500 
1501  if (!QUEUE_POS_EQUAL(pos, QUEUE_HEAD))
1502  {
1503  pids[count] = pid;
1504  ids[count] = i;
1505  count++;
1506  }
1507  }
1508  }
1509  LWLockRelease(AsyncQueueLock);
1510 
1511  /* Now send signals */
1512  for (i = 0; i < count; i++)
1513  {
1514  pid = pids[i];
1515 
1516  /*
1517  * Note: assuming things aren't broken, a signal failure here could
1518  * only occur if the target backend exited since we released
1519  * AsyncQueueLock; which is unlikely but certainly possible. So we
1520  * just log a low-level debug message if it happens.
1521  */
1522  if (SendProcSignal(pid, PROCSIG_NOTIFY_INTERRUPT, ids[i]) < 0)
1523  elog(DEBUG3, "could not signal backend with PID %d: %m", pid);
1524  else
1525  signalled = true;
1526  }
1527 
1528  pfree(pids);
1529  pfree(ids);
1530 
1531  return signalled;
1532 }
1533 
1534 /*
1535  * AtAbort_Notify
1536  *
1537  * This is called at transaction abort.
1538  *
1539  * Gets rid of pending actions and outbound notifies that we would have
1540  * executed if the transaction got committed.
1541  */
1542 void
1544 {
1545  /*
1546  * If we LISTEN but then roll back the transaction after PreCommit_Notify,
1547  * we have registered as a listener but have not made any entry in
1548  * listenChannels. In that case, deregister again.
1549  */
1550  if (amRegisteredListener && listenChannels == NIL)
1552 
1553  /* And clean up */
1555 }
1556 
1557 /*
1558  * AtSubStart_Notify() --- Take care of subtransaction start.
1559  *
1560  * Push empty state for the new subtransaction.
1561  */
1562 void
1564 {
1565  MemoryContext old_cxt;
1566 
1567  /* Keep the list-of-lists in TopTransactionContext for simplicity */
1569 
1570  upperPendingActions = lcons(pendingActions, upperPendingActions);
1571 
1572  Assert(list_length(upperPendingActions) ==
1574 
1575  pendingActions = NIL;
1576 
1577  upperPendingNotifies = lcons(pendingNotifies, upperPendingNotifies);
1578 
1579  Assert(list_length(upperPendingNotifies) ==
1581 
1582  pendingNotifies = NIL;
1583 
1584  MemoryContextSwitchTo(old_cxt);
1585 }
1586 
1587 /*
1588  * AtSubCommit_Notify() --- Take care of subtransaction commit.
1589  *
1590  * Reassign all items in the pending lists to the parent transaction.
1591  */
1592 void
1594 {
1595  List *parentPendingActions;
1596  List *parentPendingNotifies;
1597 
1598  parentPendingActions = (List *) linitial(upperPendingActions);
1599  upperPendingActions = list_delete_first(upperPendingActions);
1600 
1601  Assert(list_length(upperPendingActions) ==
1603 
1604  /*
1605  * Mustn't try to eliminate duplicates here --- see queue_listen()
1606  */
1607  pendingActions = list_concat(parentPendingActions, pendingActions);
1608 
1609  parentPendingNotifies = (List *) linitial(upperPendingNotifies);
1610  upperPendingNotifies = list_delete_first(upperPendingNotifies);
1611 
1612  Assert(list_length(upperPendingNotifies) ==
1614 
1615  /*
1616  * We could try to eliminate duplicates here, but it seems not worthwhile.
1617  */
1618  pendingNotifies = list_concat(parentPendingNotifies, pendingNotifies);
1619 }
1620 
1621 /*
1622  * AtSubAbort_Notify() --- Take care of subtransaction abort.
1623  */
1624 void
1626 {
1627  int my_level = GetCurrentTransactionNestLevel();
1628 
1629  /*
1630  * All we have to do is pop the stack --- the actions/notifies made in
1631  * this subxact are no longer interesting, and the space will be freed
1632  * when CurTransactionContext is recycled.
1633  *
1634  * This routine could be called more than once at a given nesting level if
1635  * there is trouble during subxact abort. Avoid dumping core by using
1636  * GetCurrentTransactionNestLevel as the indicator of how far we need to
1637  * prune the list.
1638  */
1639  while (list_length(upperPendingActions) > my_level - 2)
1640  {
1641  pendingActions = (List *) linitial(upperPendingActions);
1642  upperPendingActions = list_delete_first(upperPendingActions);
1643  }
1644 
1645  while (list_length(upperPendingNotifies) > my_level - 2)
1646  {
1647  pendingNotifies = (List *) linitial(upperPendingNotifies);
1648  upperPendingNotifies = list_delete_first(upperPendingNotifies);
1649  }
1650 }
1651 
1652 /*
1653  * HandleNotifyInterrupt
1654  *
1655  * Signal handler portion of interrupt handling. Let the backend know
1656  * that there's a pending notify interrupt. If we're currently reading
1657  * from the client, this will interrupt the read and
1658  * ProcessClientReadInterrupt() will call ProcessNotifyInterrupt().
1659  */
1660 void
1662 {
1663  /*
1664  * Note: this is called by a SIGNAL HANDLER. You must be very wary what
1665  * you do here.
1666  */
1667 
1668  /* signal that work needs to be done */
1669  notifyInterruptPending = true;
1670 
1671  /* make sure the event is processed in due course */
1672  SetLatch(MyLatch);
1673 }
1674 
1675 /*
1676  * ProcessNotifyInterrupt
1677  *
1678  * This is called just after waiting for a frontend command. If a
1679  * interrupt arrives (via HandleNotifyInterrupt()) while reading, the
1680  * read will be interrupted via the process's latch, and this routine
1681  * will get called. If we are truly idle (ie, *not* inside a transaction
1682  * block), process the incoming notifies.
1683  */
1684 void
1686 {
1688  return; /* not really idle */
1689 
1690  while (notifyInterruptPending)
1692 }
1693 
1694 
1695 /*
1696  * Read all pending notifications from the queue, and deliver appropriate
1697  * ones to my frontend. Stop when we reach queue head or an uncommitted
1698  * notification.
1699  */
1700 static void
1702 {
1703  volatile QueuePosition pos;
1704  QueuePosition oldpos;
1705  QueuePosition head;
1706  bool advanceTail;
1707 
1708  /* page_buffer must be adequately aligned, so use a union */
1709  union
1710  {
1711  char buf[QUEUE_PAGESIZE];
1712  AsyncQueueEntry align;
1713  } page_buffer;
1714 
1715  /* Fetch current state */
1716  LWLockAcquire(AsyncQueueLock, LW_SHARED);
1717  /* Assert checks that we have a valid state entry */
1719  pos = oldpos = QUEUE_BACKEND_POS(MyBackendId);
1720  head = QUEUE_HEAD;
1721  LWLockRelease(AsyncQueueLock);
1722 
1723  if (QUEUE_POS_EQUAL(pos, head))
1724  {
1725  /* Nothing to do, we have read all notifications already. */
1726  return;
1727  }
1728 
1729  /*----------
1730  * Note that we deliver everything that we see in the queue and that
1731  * matches our _current_ listening state.
1732  * Especially we do not take into account different commit times.
1733  * Consider the following example:
1734  *
1735  * Backend 1: Backend 2:
1736  *
1737  * transaction starts
1738  * NOTIFY foo;
1739  * commit starts
1740  * transaction starts
1741  * LISTEN foo;
1742  * commit starts
1743  * commit to clog
1744  * commit to clog
1745  *
1746  * It could happen that backend 2 sees the notification from backend 1 in
1747  * the queue. Even though the notifying transaction committed before
1748  * the listening transaction, we still deliver the notification.
1749  *
1750  * The idea is that an additional notification does not do any harm, we
1751  * just need to make sure that we do not miss a notification.
1752  *
1753  * It is possible that we fail while trying to send a message to our
1754  * frontend (for example, because of encoding conversion failure).
1755  * If that happens it is critical that we not try to send the same
1756  * message over and over again. Therefore, we place a PG_TRY block
1757  * here that will forcibly advance our backend position before we lose
1758  * control to an error. (We could alternatively retake AsyncQueueLock
1759  * and move the position before handling each individual message, but
1760  * that seems like too much lock traffic.)
1761  *----------
1762  */
1763  PG_TRY();
1764  {
1765  bool reachedStop;
1766 
1767  do
1768  {
1769  int curpage = QUEUE_POS_PAGE(pos);
1770  int curoffset = QUEUE_POS_OFFSET(pos);
1771  int slotno;
1772  int copysize;
1773 
1774  /*
1775  * We copy the data from SLRU into a local buffer, so as to avoid
1776  * holding the AsyncCtlLock while we are examining the entries and
1777  * possibly transmitting them to our frontend. Copy only the part
1778  * of the page we will actually inspect.
1779  */
1780  slotno = SimpleLruReadPage_ReadOnly(AsyncCtl, curpage,
1782  if (curpage == QUEUE_POS_PAGE(head))
1783  {
1784  /* we only want to read as far as head */
1785  copysize = QUEUE_POS_OFFSET(head) - curoffset;
1786  if (copysize < 0)
1787  copysize = 0; /* just for safety */
1788  }
1789  else
1790  {
1791  /* fetch all the rest of the page */
1792  copysize = QUEUE_PAGESIZE - curoffset;
1793  }
1794  memcpy(page_buffer.buf + curoffset,
1795  AsyncCtl->shared->page_buffer[slotno] + curoffset,
1796  copysize);
1797  /* Release lock that we got from SimpleLruReadPage_ReadOnly() */
1798  LWLockRelease(AsyncCtlLock);
1799 
1800  /*
1801  * Process messages up to the stop position, end of page, or an
1802  * uncommitted message.
1803  *
1804  * Our stop position is what we found to be the head's position
1805  * when we entered this function. It might have changed already.
1806  * But if it has, we will receive (or have already received and
1807  * queued) another signal and come here again.
1808  *
1809  * We are not holding AsyncQueueLock here! The queue can only
1810  * extend beyond the head pointer (see above) and we leave our
1811  * backend's pointer where it is so nobody will truncate or
1812  * rewrite pages under us. Especially we don't want to hold a lock
1813  * while sending the notifications to the frontend.
1814  */
1815  reachedStop = asyncQueueProcessPageEntries(&pos, head,
1816  page_buffer.buf);
1817  } while (!reachedStop);
1818  }
1819  PG_CATCH();
1820  {
1821  /* Update shared state */
1822  LWLockAcquire(AsyncQueueLock, LW_SHARED);
1824  advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
1825  LWLockRelease(AsyncQueueLock);
1826 
1827  /* If we were the laziest backend, try to advance the tail pointer */
1828  if (advanceTail)
1830 
1831  PG_RE_THROW();
1832  }
1833  PG_END_TRY();
1834 
1835  /* Update shared state */
1836  LWLockAcquire(AsyncQueueLock, LW_SHARED);
1838  advanceTail = QUEUE_POS_EQUAL(oldpos, QUEUE_TAIL);
1839  LWLockRelease(AsyncQueueLock);
1840 
1841  /* If we were the laziest backend, try to advance the tail pointer */
1842  if (advanceTail)
1844 }
1845 
1846 /*
1847  * Fetch notifications from the shared queue, beginning at position current,
1848  * and deliver relevant ones to my frontend.
1849  *
1850  * The current page must have been fetched into page_buffer from shared
1851  * memory. (We could access the page right in shared memory, but that
1852  * would imply holding the AsyncCtlLock throughout this routine.)
1853  *
1854  * We stop if we reach the "stop" position, or reach a notification from an
1855  * uncommitted transaction, or reach the end of the page.
1856  *
1857  * The function returns true once we have reached the stop position or an
1858  * uncommitted notification, and false if we have finished with the page.
1859  * In other words: once it returns true there is no need to look further.
1860  * The QueuePosition *current is advanced past all processed messages.
1861  */
1862 static bool
1864  QueuePosition stop,
1865  char *page_buffer)
1866 {
1867  bool reachedStop = false;
1868  bool reachedEndOfPage;
1869  AsyncQueueEntry *qe;
1870 
1871  do
1872  {
1873  QueuePosition thisentry = *current;
1874 
1875  if (QUEUE_POS_EQUAL(thisentry, stop))
1876  break;
1877 
1878  qe = (AsyncQueueEntry *) (page_buffer + QUEUE_POS_OFFSET(thisentry));
1879 
1880  /*
1881  * Advance *current over this message, possibly to the next page. As
1882  * noted in the comments for asyncQueueReadAllNotifications, we must
1883  * do this before possibly failing while processing the message.
1884  */
1885  reachedEndOfPage = asyncQueueAdvance(current, qe->length);
1886 
1887  /* Ignore messages destined for other databases */
1888  if (qe->dboid == MyDatabaseId)
1889  {
1890  if (TransactionIdIsInProgress(qe->xid))
1891  {
1892  /*
1893  * The source transaction is still in progress, so we can't
1894  * process this message yet. Break out of the loop, but first
1895  * back up *current so we will reprocess the message next
1896  * time. (Note: it is unlikely but not impossible for
1897  * TransactionIdDidCommit to fail, so we can't really avoid
1898  * this advance-then-back-up behavior when dealing with an
1899  * uncommitted message.)
1900  *
1901  * Note that we must test TransactionIdIsInProgress before we
1902  * test TransactionIdDidCommit, else we might return a message
1903  * from a transaction that is not yet visible to snapshots;
1904  * compare the comments at the head of tqual.c.
1905  */
1906  *current = thisentry;
1907  reachedStop = true;
1908  break;
1909  }
1910  else if (TransactionIdDidCommit(qe->xid))
1911  {
1912  /* qe->data is the null-terminated channel name */
1913  char *channel = qe->data;
1914 
1915  if (IsListeningOn(channel))
1916  {
1917  /* payload follows channel name */
1918  char *payload = qe->data + strlen(channel) + 1;
1919 
1920  NotifyMyFrontEnd(channel, payload, qe->srcPid);
1921  }
1922  }
1923  else
1924  {
1925  /*
1926  * The source transaction aborted or crashed, so we just
1927  * ignore its notifications.
1928  */
1929  }
1930  }
1931 
1932  /* Loop back if we're not at end of page */
1933  } while (!reachedEndOfPage);
1934 
1935  if (QUEUE_POS_EQUAL(*current, stop))
1936  reachedStop = true;
1937 
1938  return reachedStop;
1939 }
1940 
1941 /*
1942  * Advance the shared queue tail variable to the minimum of all the
1943  * per-backend tail pointers. Truncate pg_notify space if possible.
1944  */
1945 static void
1947 {
1948  QueuePosition min;
1949  int i;
1950  int oldtailpage;
1951  int newtailpage;
1952  int boundary;
1953 
1954  LWLockAcquire(AsyncQueueLock, LW_EXCLUSIVE);
1955  min = QUEUE_HEAD;
1956  for (i = 1; i <= MaxBackends; i++)
1957  {
1958  if (QUEUE_BACKEND_PID(i) != InvalidPid)
1959  min = QUEUE_POS_MIN(min, QUEUE_BACKEND_POS(i));
1960  }
1961  oldtailpage = QUEUE_POS_PAGE(QUEUE_TAIL);
1962  QUEUE_TAIL = min;
1963  LWLockRelease(AsyncQueueLock);
1964 
1965  /*
1966  * We can truncate something if the global tail advanced across an SLRU
1967  * segment boundary.
1968  *
1969  * XXX it might be better to truncate only once every several segments, to
1970  * reduce the number of directory scans.
1971  */
1972  newtailpage = QUEUE_POS_PAGE(min);
1973  boundary = newtailpage - (newtailpage % SLRU_PAGES_PER_SEGMENT);
1974  if (asyncQueuePagePrecedes(oldtailpage, boundary))
1975  {
1976  /*
1977  * SimpleLruTruncate() will ask for AsyncCtlLock but will also release
1978  * the lock again.
1979  */
1980  SimpleLruTruncate(AsyncCtl, newtailpage);
1981  }
1982 }
1983 
1984 /*
1985  * ProcessIncomingNotify
1986  *
1987  * Deal with arriving NOTIFYs from other backends as soon as it's safe to
1988  * do so. This used to be called from the PROCSIG_NOTIFY_INTERRUPT
1989  * signal handler, but isn't anymore.
1990  *
1991  * Scan the queue for arriving notifications and report them to my front
1992  * end.
1993  *
1994  * NOTE: since we are outside any transaction, we must create our own.
1995  */
1996 static void
1998 {
1999  /* We *must* reset the flag */
2000  notifyInterruptPending = false;
2001 
2002  /* Do nothing else if we aren't actively listening */
2003  if (listenChannels == NIL)
2004  return;
2005 
2006  if (Trace_notify)
2007  elog(DEBUG1, "ProcessIncomingNotify");
2008 
2009  set_ps_display("notify interrupt", false);
2010 
2011  /*
2012  * We must run asyncQueueReadAllNotifications inside a transaction, else
2013  * bad things happen if it gets an error.
2014  */
2016 
2018 
2020 
2021  /*
2022  * Must flush the notify messages to ensure frontend gets them promptly.
2023  */
2024  pq_flush();
2025 
2026  set_ps_display("idle", false);
2027 
2028  if (Trace_notify)
2029  elog(DEBUG1, "ProcessIncomingNotify: done");
2030 }
2031 
2032 /*
2033  * Send NOTIFY message to my front end.
2034  */
2035 static void
2036 NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
2037 {
2039  {
2041 
2042  pq_beginmessage(&buf, 'A');
2043  pq_sendint(&buf, srcPid, sizeof(int32));
2044  pq_sendstring(&buf, channel);
2046  pq_sendstring(&buf, payload);
2047  pq_endmessage(&buf);
2048 
2049  /*
2050  * NOTE: we do not do pq_flush() here. For a self-notify, it will
2051  * happen at the end of the transaction, and for incoming notifies
2052  * ProcessIncomingNotify will do it after finding all the notifies.
2053  */
2054  }
2055  else
2056  elog(INFO, "NOTIFY for \"%s\" payload \"%s\"", channel, payload);
2057 }
2058 
2059 /* Does pendingNotifies include the given channel/payload? */
2060 static bool
2061 AsyncExistsPendingNotify(const char *channel, const char *payload)
2062 {
2063  ListCell *p;
2064  Notification *n;
2065 
2066  if (pendingNotifies == NIL)
2067  return false;
2068 
2069  if (payload == NULL)
2070  payload = "";
2071 
2072  /*----------
2073  * We need to append new elements to the end of the list in order to keep
2074  * the order. However, on the other hand we'd like to check the list
2075  * backwards in order to make duplicate-elimination a tad faster when the
2076  * same condition is signaled many times in a row. So as a compromise we
2077  * check the tail element first which we can access directly. If this
2078  * doesn't match, we check the whole list.
2079  *
2080  * As we are not checking our parents' lists, we can still get duplicates
2081  * in combination with subtransactions, like in:
2082  *
2083  * begin;
2084  * notify foo '1';
2085  * savepoint foo;
2086  * notify foo '1';
2087  * commit;
2088  *----------
2089  */
2090  n = (Notification *) llast(pendingNotifies);
2091  if (strcmp(n->channel, channel) == 0 &&
2092  strcmp(n->payload, payload) == 0)
2093  return true;
2094 
2095  foreach(p, pendingNotifies)
2096  {
2097  n = (Notification *) lfirst(p);
2098 
2099  if (strcmp(n->channel, channel) == 0 &&
2100  strcmp(n->payload, payload) == 0)
2101  return true;
2102  }
2103 
2104  return false;
2105 }
2106 
2107 /* Clear the pendingActions and pendingNotifies lists. */
2108 static void
2110 {
2111  /*
2112  * We used to have to explicitly deallocate the list members and nodes,
2113  * because they were malloc'd. Now, since we know they are palloc'd in
2114  * CurTransactionContext, we need not do that --- they'll go away
2115  * automatically at transaction exit. We need only reset the list head
2116  * pointers.
2117  */
2118  pendingActions = NIL;
2119  pendingNotifies = NIL;
2120 }
struct QueueBackendStatus QueueBackendStatus
#define NIL
Definition: pg_list.h:69
static void usage(void)
Definition: pg_standby.c:503
#define QUEUE_TAIL
Definition: async.c:247
char data[NAMEDATALEN+NOTIFY_PAYLOAD_MAX_LENGTH]
Definition: async.c:170
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:37
int errhint(const char *fmt,...)
Definition: elog.c:982
static void queue_listen(ListenActionKind action, const char *channel)
Definition: async.c:594
static SlruCtlData AsyncCtlData
Definition: async.c:254
BackendId MyBackendId
Definition: globals.c:71
#define pq_flush()
Definition: libpq.h:39
MemoryContext TopTransactionContext
Definition: mcxt.c:48
#define QUEUE_BACKEND_PID(i)
Definition: async.c:248
int page
Definition: async.c:183
uint32 TransactionId
Definition: c.h:382
bool SlruScanDirCbDeleteAll(SlruCtl ctl, char *filename, int segpage, void *data)
Definition: slru.c:1262
#define DEBUG3
Definition: elog.h:23
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1551
void AsyncShmemInit(void)
Definition: async.c:433
bool TransactionIdIsInProgress(TransactionId xid)
Definition: procarray.c:991
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:285
char * pstrdup(const char *in)
Definition: mcxt.c:1160
#define DatabaseRelationId
Definition: pg_database.h:29
void CommitTransactionCommand(void)
Definition: xact.c:2707
void SimpleLruTruncate(SlruCtl ctl, int cutoffPage)
Definition: slru.c:1141
#define PG_RETURN_FLOAT8(x)
Definition: fmgr.h:310
#define AsyncCtl
Definition: async.c:256
#define llast(l)
Definition: pg_list.h:126
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void Exec_UnlistenAllCommit(void)
Definition: async.c:1025
int offset
Definition: async.c:184
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:299
MemoryContext CurTransactionContext
Definition: mcxt.c:49
static List * listenChannels
Definition: async.c:284
void AtPrepare_Notify(void)
Definition: async.c:736
int errcode(int sqlerrcode)
Definition: elog.c:573
Datum pg_notification_queue_usage(PG_FUNCTION_ARGS)
Definition: async.c:1370
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4282
char * channel
Definition: async.c:331
#define INFO
Definition: elog.h:31
List * list_concat(List *list1, List *list2)
Definition: list.c:321
static double asyncQueueUsage(void)
Definition: async.c:1387
void pq_sendstring(StringInfo buf, const char *str)
Definition: pqformat.c:185
void Async_Listen(const char *channel)
Definition: async.c:624
static void ClearPendingActionsAndNotifies(void)
Definition: async.c:2109
static void asyncQueueNotificationToEntry(Notification *n, AsyncQueueEntry *qe)
Definition: async.c:1240
static bool asyncQueueAdvance(volatile QueuePosition *position, int entryLength)
Definition: async.c:1205
#define QUEUE_HEAD
Definition: async.c:246
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
static void Exec_UnlistenCommit(const char *channel)
Definition: async.c:991
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:104
static void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid)
Definition: async.c:2036
void SimpleLruInit(SlruCtl ctl, const char *name, int nslots, int nlsns, LWLock *ctllock, const char *subdir)
Definition: slru.c:163
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1656
Size SimpleLruShmemSize(int nslots, int nlsns)
Definition: slru.c:143
void list_free_deep(List *list)
Definition: list.c:1147
static bool IsListeningOn(const char *channel)
Definition: async.c:1124
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:289
static bool unlistenExitRegistered
Definition: async.c:349
static bool asyncQueueIsFull(void)
Definition: async.c:1174
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
static void asyncQueueFillWarning(void)
Definition: async.c:1416
signed int int32
Definition: c.h:242
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:270
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1547
QueuePosition pos
Definition: async.c:211
#define NAMEDATALEN
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:291
char * payload
Definition: async.c:332
void PreCommit_Notify(void)
Definition: async.c:761
#define NUM_ASYNC_BUFFERS
Definition: async.h:23
#define QUEUE_POS_OFFSET(x)
Definition: async.c:188
int SendProcSignal(pid_t pid, ProcSignalReason reason, BackendId backendId)
Definition: procsignal.c:187
double TimestampTz
Definition: timestamp.h:51
void pfree(void *pointer)
Definition: mcxt.c:993
#define linitial(l)
Definition: pg_list.h:110
#define AsyncQueueEntryEmptySize
Definition: async.c:176
#define ERROR
Definition: elog.h:41
static List * pendingActions
Definition: async.c:309
void PreventCommandDuringRecovery(const char *cmdname)
Definition: utility.c:265
void ProcessNotifyInterrupt(void)
Definition: async.c:1685
static bool AsyncExistsPendingNotify(const char *channel, const char *payload)
Definition: async.c:2061
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:325
int SimpleLruReadPage(SlruCtl ctl, int pageno, bool write_ok, TransactionId xid)
Definition: slru.c:358
static void Async_UnlistenOnExit(int code, Datum arg)
Definition: async.c:723
void AtSubCommit_Notify(void)
Definition: async.c:1593
static bool backendHasSentNotifications
Definition: async.c:355
int MaxBackends
Definition: globals.c:121
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:414
static char * buf
Definition: pg_test_fsync.c:65
#define QUEUE_PAGESIZE
Definition: async.c:257
#define SET_QUEUE_POS(x, y, z)
Definition: async.c:190
int errdetail(const char *fmt,...)
Definition: elog.c:868
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
#define InvalidTransactionId
Definition: transam.h:31
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
void SimpleLruWritePage(SlruCtl ctl, int slotno)
Definition: slru.c:561
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define NOTIFY_PAYLOAD_MAX_LENGTH
Definition: async.c:150
static bool asyncQueuePagePrecedes(int p, int q)
Definition: async.c:393
static AsyncQueueControl * asyncQueueControl
Definition: async.c:244
static void asyncQueueAdvanceTail(void)
Definition: async.c:1946
static void Exec_ListenCommit(const char *channel)
Definition: async.c:964
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:132
MemoryContext TopMemoryContext
Definition: mcxt.c:43
void SetLatch(volatile Latch *latch)
Definition: unix_latch.c:520
#define QUEUE_FULL_WARN_INTERVAL
Definition: async.c:258
List * lappend(List *list, void *datum)
Definition: list.c:128
struct AsyncQueueControl AsyncQueueControl
#define WARNING
Definition: elog.h:38
struct QueuePosition QueuePosition
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
Size mul_size(Size s1, Size s2)
Definition: shmem.c:448
void AtSubAbort_Notify(void)
Definition: async.c:1625
static List * upperPendingActions
Definition: async.c:311
ListenActionKind
Definition: async.c:296
static void ProcessIncomingNotify(void)
Definition: async.c:1997
uintptr_t Datum
Definition: postgres.h:374
static void asyncQueueUnregister(void)
Definition: async.c:1143
static bool amRegisteredListener
Definition: async.c:352
void AtAbort_Notify(void)
Definition: async.c:1543
Size add_size(Size s1, Size s2)
Definition: shmem.c:431
int BackendId
Definition: backendid.h:21
#define QUEUEALIGN(len)
Definition: async.c:174
Oid MyDatabaseId
Definition: globals.c:73
int SimpleLruReadPage_ReadOnly(SlruCtl ctl, int pageno, TransactionId xid)
Definition: slru.c:450
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:836
QueuePosition head
Definition: async.c:236
#define InvalidOid
Definition: postgres_ext.h:36
static void asyncQueueReadAllNotifications(void)
Definition: async.c:1701
void AtSubStart_Notify(void)
Definition: async.c:1563
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:758
#define PG_RETURN_VOID()
Definition: fmgr.h:293
Datum pg_notify(PG_FUNCTION_ARGS)
Definition: async.c:498
List * lcons(void *datum, List *list)
Definition: list.c:259
#define PG_CATCH()
Definition: elog.h:302
#define PG_ARGISNULL(n)
Definition: fmgr.h:166
static ListCell * asyncQueueAddEntries(ListCell *nextNotify)
Definition: async.c:1277
#define NULL
Definition: c.h:215
#define Assert(condition)
Definition: c.h:656
void ProcessCompletedNotifies(void)
Definition: async.c:1056
#define lfirst(lc)
Definition: pg_list.h:106
bool SlruScanDirectory(SlruCtl ctl, SlruScanCallback callback, void *data)
Definition: slru.c:1285
static void Exec_ListenPreCommit(void)
Definition: async.c:907
QueueBackendStatus backend[FLEXIBLE_ARRAY_MEMBER]
Definition: async.c:240
void StartTransactionCommand(void)
Definition: xact.c:2637
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:109
struct AsyncQueueEntry AsyncQueueEntry
Size AsyncShmemSize(void)
Definition: async.c:416
size_t Size
Definition: c.h:341
void Async_UnlistenAll(void)
Definition: async.c:656
static int list_length(const List *l)
Definition: pg_list.h:89
struct Notification Notification
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:928
#define PG_RE_THROW()
Definition: elog.h:323
bool Trace_notify
Definition: async.c:358
void Async_Notify(const char *channel, const char *payload)
Definition: async.c:532
Datum pg_listening_channels(PG_FUNCTION_ARGS)
Definition: async.c:676
TransactionId xid
Definition: async.c:168
char * text_to_cstring(const text *t)
Definition: varlena.c:173
#define AccessExclusiveLock
Definition: lockdefs.h:46
void AtCommit_Notify(void)
Definition: async.c:860
void * user_fctx
Definition: funcapi.h:90
void HandleNotifyInterrupt(void)
Definition: async.c:1661
void * palloc(Size size)
Definition: mcxt.c:892
int errmsg(const char *fmt,...)
Definition: elog.c:795
void pq_sendint(StringInfo buf, int i, int b)
Definition: pqformat.c:235
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:343
char channel[FLEXIBLE_ARRAY_MEMBER]
Definition: async.c:306
int i
ListenActionKind action
Definition: async.c:305
#define CStringGetTextDatum(s)
Definition: builtins.h:780
int32 srcPid
Definition: async.c:169
void * arg
static List * upperPendingNotifies
Definition: async.c:337
struct Latch * MyLatch
Definition: globals.c:50
volatile sig_atomic_t notifyInterruptPending
Definition: async.c:346
#define PG_FUNCTION_ARGS
Definition: fmgr.h:150
static bool asyncQueueProcessPageEntries(volatile QueuePosition *current, QueuePosition stop, char *page_buffer)
Definition: async.c:1863
#define elog
Definition: elog.h:228
#define SLRU_PAGES_PER_SEGMENT
Definition: slru.h:37
TimestampTz lastQueueFillWarn
Definition: async.c:239
CommandDest whereToSendOutput
Definition: postgres.c:86
#define QUEUE_MAX_PAGE
Definition: async.c:277
#define PG_TRY()
Definition: elog.h:293
QueuePosition tail
Definition: async.c:237
#define QUEUE_BACKEND_POS(i)
Definition: async.c:249
Definition: pg_list.h:45
ProtocolVersion FrontendProtocol
Definition: globals.c:27
int SimpleLruZeroPage(SlruCtl ctl, int pageno)
Definition: slru.c:246
#define PG_END_TRY()
Definition: elog.h:309
#define QUEUE_POS_PAGE(x)
Definition: async.c:187
#define QUEUE_POS_EQUAL(x, y)
Definition: async.c:196
#define offsetof(type, field)
Definition: c.h:536
#define QUEUE_POS_MIN(x, y)
Definition: async.c:200
void Async_Unlisten(const char *channel)
Definition: async.c:638
List * list_delete_first(List *list)
Definition: list.c:666
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:309
static bool SignalBackends(void)
Definition: async.c:1471
#define InvalidPid
Definition: miscadmin.h:31
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:287
static List * pendingNotifies
Definition: async.c:335