PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
launcher.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * launcher.c
3  * PostgreSQL logical replication worker launcher process
4  *
5  * Copyright (c) 2016-2017, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/backend/replication/logical/launcher.c
9  *
10  * NOTES
11  * This module contains the logical replication worker launcher which
12  * uses the background worker infrastructure to start the logical
13  * replication workers for every enabled subscription.
14  *
15  *-------------------------------------------------------------------------
16  */
17 
18 #include "postgres.h"
19 
20 #include "funcapi.h"
21 #include "miscadmin.h"
22 #include "pgstat.h"
23 
24 #include "access/heapam.h"
25 #include "access/htup.h"
26 #include "access/htup_details.h"
27 #include "access/xact.h"
28 
31 
32 #include "libpq/pqsignal.h"
33 
34 #include "postmaster/bgworker.h"
36 #include "postmaster/postmaster.h"
37 
40 #include "replication/slot.h"
43 
44 #include "storage/ipc.h"
45 #include "storage/proc.h"
46 #include "storage/procarray.h"
47 #include "storage/procsignal.h"
48 
49 #include "tcop/tcopprot.h"
50 
51 #include "utils/memutils.h"
52 #include "utils/pg_lsn.h"
53 #include "utils/ps_status.h"
54 #include "utils/timeout.h"
55 #include "utils/snapmgr.h"
56 
57 /* max sleep time between cycles (3min) */
58 #define DEFAULT_NAPTIME_PER_CYCLE 180000L
59 
62 
64 
65 typedef struct LogicalRepCtxStruct
66 {
67  /* Supervisor process. */
68  pid_t launcher_pid;
69 
70  /* Background workers. */
71  LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER];
73 
75 
76 static void ApplyLauncherWakeup(void);
77 static void logicalrep_launcher_onexit(int code, Datum arg);
78 static void logicalrep_worker_onexit(int code, Datum arg);
79 static void logicalrep_worker_detach(void);
80 static void logicalrep_worker_cleanup(LogicalRepWorker *worker);
81 
82 /* Flags set by signal handlers */
83 volatile sig_atomic_t got_SIGHUP = false;
84 volatile sig_atomic_t got_SIGTERM = false;
85 
86 static bool on_commit_launcher_wakeup = false;
87 
89 
90 
91 /*
92  * Load the list of subscriptions.
93  *
94  * Only the fields interesting for worker start/stop functions are filled for
95  * each subscription.
96  */
97 static List *
99 {
100  List *res = NIL;
101  Relation rel;
102  HeapScanDesc scan;
103  HeapTuple tup;
104  MemoryContext resultcxt;
105 
106  /* This is the context that we will allocate our output data in */
107  resultcxt = CurrentMemoryContext;
108 
109  /*
110  * Start a transaction so we can access pg_database, and get a snapshot.
111  * We don't have a use for the snapshot itself, but we're interested in
112  * the secondary effect that it sets RecentGlobalXmin. (This is critical
113  * for anything that reads heap pages, because HOT may decide to prune
114  * them even if the process doesn't attempt to modify any tuples.)
115  */
117  (void) GetTransactionSnapshot();
118 
120  scan = heap_beginscan_catalog(rel, 0, NULL);
121 
123  {
125  Subscription *sub;
126  MemoryContext oldcxt;
127 
128  /*
129  * Allocate our results in the caller's context, not the
130  * transaction's. We do this inside the loop, and restore the original
131  * context at the end, so that leaky things like heap_getnext() are
132  * not called in a potentially long-lived context.
133  */
134  oldcxt = MemoryContextSwitchTo(resultcxt);
135 
136  sub = (Subscription *) palloc0(sizeof(Subscription));
137  sub->oid = HeapTupleGetOid(tup);
138  sub->dbid = subform->subdbid;
139  sub->owner = subform->subowner;
140  sub->enabled = subform->subenabled;
141  sub->name = pstrdup(NameStr(subform->subname));
142  /* We don't fill fields we are not interested in. */
143 
144  res = lappend(res, sub);
145  MemoryContextSwitchTo(oldcxt);
146  }
147 
148  heap_endscan(scan);
150 
152 
153  return res;
154 }
155 
156 /*
157  * Wait for a background worker to start up and attach to the shmem context.
158  *
159  * This is only needed for cleaning up the shared memory in case the worker
160  * fails to attach.
161  */
162 static void
164  BackgroundWorkerHandle *handle)
165 {
167  int rc;
168  uint16 generation;
169 
170  /* Remember generation for future identification. */
171  generation = worker->generation;
172 
173  for (;;)
174  {
175  pid_t pid;
176 
178 
179  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
180 
181  /* Worker either died or has started; no need to do anything. */
182  if (!worker->in_use || worker->proc)
183  {
184  LWLockRelease(LogicalRepWorkerLock);
185  return;
186  }
187 
188  LWLockRelease(LogicalRepWorkerLock);
189 
190  /* Check if worker has died before attaching, and clean up after it. */
191  status = GetBackgroundWorkerPid(handle, &pid);
192 
193  if (status == BGWH_STOPPED)
194  {
195  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
196  /* Ensure that this was indeed the worker we waited for. */
197  if (generation == worker->generation)
199  LWLockRelease(LogicalRepWorkerLock);
200  return;
201  }
202 
203  /*
204  * We need timeout because we generally don't get notified via latch
205  * about the worker attach.
206  */
207  rc = WaitLatch(MyLatch,
210 
211  if (rc & WL_POSTMASTER_DEATH)
212  proc_exit(1);
213 
215  }
216 
217  return;
218 }
219 
220 /*
221  * Walks the workers array and searches for one that matches given
222  * subscription id and relid.
223  */
225 logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
226 {
227  int i;
228  LogicalRepWorker *res = NULL;
229 
230  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
231 
232  /* Search for attached worker for a given subscription id. */
233  for (i = 0; i < max_logical_replication_workers; i++)
234  {
235  LogicalRepWorker *w = &LogicalRepCtx->workers[i];
236 
237  if (w->in_use && w->subid == subid && w->relid == relid &&
238  (!only_running || w->proc))
239  {
240  res = w;
241  break;
242  }
243  }
244 
245  return res;
246 }
247 
248 /*
249  * Start new apply background worker.
250  */
251 void
252 logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid,
253  Oid relid)
254 {
255  BackgroundWorker bgw;
256  BackgroundWorkerHandle *bgw_handle;
257  int i;
258  int slot = 0;
259  LogicalRepWorker *worker = NULL;
260  int nsyncworkers;
262 
263  ereport(DEBUG1,
264  (errmsg("starting logical replication worker for subscription \"%s\"",
265  subname)));
266 
267  /* Report this after the initial starting message for consistency. */
268  if (max_replication_slots == 0)
269  ereport(ERROR,
270  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
271  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
272 
273  /*
274  * We need to do the modification of the shared memory under lock so that
275  * we have consistent view.
276  */
277  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
278 
279 retry:
280  /* Find unused worker slot. */
281  for (i = 0; i < max_logical_replication_workers; i++)
282  {
283  LogicalRepWorker *w = &LogicalRepCtx->workers[i];
284 
285  if (!w->in_use)
286  {
287  worker = w;
288  slot = i;
289  break;
290  }
291  }
292 
293  nsyncworkers = logicalrep_sync_worker_count(subid);
294 
295  now = GetCurrentTimestamp();
296 
297  /*
298  * If we didn't find a free slot, try to do garbage collection. The
299  * reason we do this is because if some worker failed to start up and its
300  * parent has crashed while waiting, the in_use state was never cleared.
301  */
302  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
303  {
304  bool did_cleanup = false;
305 
306  for (i = 0; i < max_logical_replication_workers; i++)
307  {
308  LogicalRepWorker *w = &LogicalRepCtx->workers[i];
309 
310  /*
311  * If the worker was marked in use but didn't manage to attach in
312  * time, clean it up.
313  */
314  if (w->in_use && !w->proc &&
317  {
318  elog(WARNING,
319  "logical replication worker for subscription %u took too long to start; canceled",
320  w->subid);
321 
323  did_cleanup = true;
324  }
325  }
326 
327  if (did_cleanup)
328  goto retry;
329  }
330 
331  /*
332  * If we reached the sync worker limit per subscription, just exit
333  * silently as we might get here because of an otherwise harmless race
334  * condition.
335  */
336  if (nsyncworkers >= max_sync_workers_per_subscription)
337  {
338  LWLockRelease(LogicalRepWorkerLock);
339  return;
340  }
341 
342  /*
343  * However if there are no more free worker slots, inform user about it
344  * before exiting.
345  */
346  if (worker == NULL)
347  {
348  LWLockRelease(LogicalRepWorkerLock);
350  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
351  errmsg("out of logical replication worker slots"),
352  errhint("You might need to increase max_logical_replication_workers.")));
353  return;
354  }
355 
356  /* Prepare the worker slot. */
357  worker->launch_time = now;
358  worker->in_use = true;
359  worker->generation++;
360  worker->proc = NULL;
361  worker->dbid = dbid;
362  worker->userid = userid;
363  worker->subid = subid;
364  worker->relid = relid;
365  worker->relstate = SUBREL_STATE_UNKNOWN;
367  worker->last_lsn = InvalidXLogRecPtr;
370  worker->reply_lsn = InvalidXLogRecPtr;
371  TIMESTAMP_NOBEGIN(worker->reply_time);
372 
373  LWLockRelease(LogicalRepWorkerLock);
374 
375  /* Register the new dynamic worker. */
376  memset(&bgw, 0, sizeof(bgw));
380  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
381  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
382  if (OidIsValid(relid))
384  "logical replication worker for subscription %u sync %u", subid, relid);
385  else
387  "logical replication worker for subscription %u", subid);
388 
391  bgw.bgw_main_arg = Int32GetDatum(slot);
392 
393  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
394  {
396  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
397  errmsg("out of background worker slots"),
398  errhint("You might need to increase max_worker_processes.")));
399  return;
400  }
401 
402  /* Now wait until it attaches. */
403  WaitForReplicationWorkerAttach(worker, bgw_handle);
404 }
405 
406 /*
407  * Stop the logical replication worker and wait until it detaches from the
408  * slot.
409  */
410 void
412 {
413  LogicalRepWorker *worker;
414  uint16 generation;
415 
416  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
417 
418  worker = logicalrep_worker_find(subid, relid, false);
419 
420  /* No worker, nothing to do. */
421  if (!worker)
422  {
423  LWLockRelease(LogicalRepWorkerLock);
424  return;
425  }
426 
427  /*
428  * Remember which generation was our worker so we can check if what we see
429  * is still the same one.
430  */
431  generation = worker->generation;
432 
433  /*
434  * If we found worker but it does not have proc set it is starting up,
435  * wait for it to finish and then kill it.
436  */
437  while (worker->in_use && !worker->proc)
438  {
439  int rc;
440 
441  LWLockRelease(LogicalRepWorkerLock);
442 
444 
445  /* Wait for signal. */
446  rc = WaitLatch(&MyProc->procLatch,
449 
450  /* emergency bailout if postmaster has died */
451  if (rc & WL_POSTMASTER_DEATH)
452  proc_exit(1);
453 
455 
456  /* Check worker status. */
457  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
458 
459  /*
460  * Check whether the worker slot is no longer used, which would mean
461  * that the worker has exited, or whether the worker generation is
462  * different, meaning that a different worker has taken the slot.
463  */
464  if (!worker->in_use || worker->generation != generation)
465  {
466  LWLockRelease(LogicalRepWorkerLock);
467  return;
468  }
469 
470  /* Worker has assigned proc, so it has started. */
471  if (worker->proc)
472  break;
473  }
474 
475  /* Now terminate the worker ... */
476  kill(worker->proc->pid, SIGTERM);
477  LWLockRelease(LogicalRepWorkerLock);
478 
479  /* ... and wait for it to die. */
480  for (;;)
481  {
482  int rc;
483 
484  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
485  if (!worker->proc || worker->generation != generation)
486  {
487  LWLockRelease(LogicalRepWorkerLock);
488  break;
489  }
490  LWLockRelease(LogicalRepWorkerLock);
491 
493 
494  /* Wait for more work. */
495  rc = WaitLatch(&MyProc->procLatch,
498 
499  /* emergency bailout if postmaster has died */
500  if (rc & WL_POSTMASTER_DEATH)
501  proc_exit(1);
502 
504  }
505 }
506 
507 /*
508  * Wake up (using latch) the logical replication worker.
509  */
510 void
512 {
513  LogicalRepWorker *worker;
514 
515  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
516  worker = logicalrep_worker_find(subid, relid, true);
517  LWLockRelease(LogicalRepWorkerLock);
518 
519  if (worker)
521 }
522 
523 /*
524  * Wake up (using latch) the logical replication worker.
525  */
526 void
528 {
529  SetLatch(&worker->proc->procLatch);
530 }
531 
532 /*
533  * Attach to a slot.
534  */
535 void
537 {
538  /* Block concurrent access. */
539  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
540 
541  Assert(slot >= 0 && slot < max_logical_replication_workers);
542  MyLogicalRepWorker = &LogicalRepCtx->workers[slot];
543 
544  if (!MyLogicalRepWorker->in_use)
545  {
546  LWLockRelease(LogicalRepWorkerLock);
547  ereport(ERROR,
548  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
549  errmsg("logical replication worker slot %d is empty, cannot attach",
550  slot)));
551  }
552 
553  if (MyLogicalRepWorker->proc)
554  {
555  LWLockRelease(LogicalRepWorkerLock);
556  ereport(ERROR,
557  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
558  errmsg("logical replication worker slot %d is already used by "
559  "another worker, cannot attach", slot)));
560  }
561 
562  MyLogicalRepWorker->proc = MyProc;
564 
565  LWLockRelease(LogicalRepWorkerLock);
566 }
567 
568 /*
569  * Detach the worker (cleans up the worker info).
570  */
571 static void
573 {
574  /* Block concurrent access. */
575  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
576 
577  logicalrep_worker_cleanup(MyLogicalRepWorker);
578 
579  LWLockRelease(LogicalRepWorkerLock);
580 }
581 
582 /*
583  * Clean up worker info.
584  */
585 static void
587 {
588  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
589 
590  worker->in_use = false;
591  worker->proc = NULL;
592  worker->dbid = InvalidOid;
593  worker->userid = InvalidOid;
594  worker->subid = InvalidOid;
595  worker->relid = InvalidOid;
596 }
597 
598 /*
599  * Cleanup function for logical replication launcher.
600  *
601  * Called on logical replication launcher exit.
602  */
603 static void
605 {
606  LogicalRepCtx->launcher_pid = 0;
607 }
608 
609 /*
610  * Cleanup function.
611  *
612  * Called on logical replication worker exit.
613  */
614 static void
616 {
618 }
619 
620 /* SIGTERM: set flag to exit at next convenient time */
621 void
623 {
624  int save_errno = errno;
625 
626  got_SIGTERM = true;
627 
628  /* Waken anything waiting on the process latch */
629  SetLatch(MyLatch);
630 
631  errno = save_errno;
632 }
633 
634 /* SIGHUP: set flag to reload configuration at next convenient time */
635 void
637 {
638  int save_errno = errno;
639 
640  got_SIGHUP = true;
641 
642  /* Waken anything waiting on the process latch */
643  SetLatch(MyLatch);
644 
645  errno = save_errno;
646 }
647 
648 /*
649  * Count the number of registered (not necessarily running) sync workers
650  * for a subscription.
651  */
652 int
654 {
655  int i;
656  int res = 0;
657 
658  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
659 
660  /* Search for attached worker for a given subscription id. */
661  for (i = 0; i < max_logical_replication_workers; i++)
662  {
663  LogicalRepWorker *w = &LogicalRepCtx->workers[i];
664 
665  if (w->subid == subid && OidIsValid(w->relid))
666  res++;
667  }
668 
669  return res;
670 }
671 
672 /*
673  * ApplyLauncherShmemSize
674  * Compute space needed for replication launcher shared memory
675  */
676 Size
678 {
679  Size size;
680 
681  /*
682  * Need the fixed struct and the array of LogicalRepWorker.
683  */
684  size = sizeof(LogicalRepCtxStruct);
685  size = MAXALIGN(size);
687  sizeof(LogicalRepWorker)));
688  return size;
689 }
690 
691 /*
692  * ApplyLauncherRegister
693  * Register a background worker running the logical replication launcher.
694  */
695 void
697 {
698  BackgroundWorker bgw;
699 
701  return;
702 
703  memset(&bgw, 0, sizeof(bgw));
707  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
708  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
710  "logical replication launcher");
711  bgw.bgw_restart_time = 5;
712  bgw.bgw_notify_pid = 0;
713  bgw.bgw_main_arg = (Datum) 0;
714 
716 }
717 
718 /*
719  * ApplyLauncherShmemInit
720  * Allocate and initialize replication launcher shared memory
721  */
722 void
724 {
725  bool found;
726 
727  LogicalRepCtx = (LogicalRepCtxStruct *)
728  ShmemInitStruct("Logical Replication Launcher Data",
730  &found);
731 
732  if (!found)
733  {
734  int slot;
735 
736  memset(LogicalRepCtx, 0, ApplyLauncherShmemSize());
737 
738  /* Initialize memory and spin locks for each worker slot. */
739  for (slot = 0; slot < max_logical_replication_workers; slot++)
740  {
741  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
742 
743  memset(worker, 0, sizeof(LogicalRepWorker));
744  SpinLockInit(&worker->relmutex);
745  }
746  }
747 }
748 
749 /*
750  * Wakeup the launcher on commit if requested.
751  */
752 void
754 {
755  if (isCommit && on_commit_launcher_wakeup)
757 
759 }
760 
761 /*
762  * Request wakeup of the launcher on commit of the transaction.
763  *
764  * This is used to send launcher signal to stop sleeping and process the
765  * subscriptions when current transaction commits. Should be used when new
766  * tuple was added to the pg_subscription catalog.
767 */
768 void
770 {
773 }
774 
775 static void
777 {
778  if (LogicalRepCtx->launcher_pid != 0)
779  kill(LogicalRepCtx->launcher_pid, SIGUSR1);
780 }
781 
782 /*
783  * Main loop for the apply launcher process.
784  */
785 void
787 {
788  TimestampTz last_start_time = 0;
789 
790  ereport(DEBUG1,
791  (errmsg("logical replication launcher started")));
792 
794 
795  /* Establish signal handlers. */
799 
800  /* Make it easy to identify our processes. */
801  SetConfigOption("application_name", MyBgworkerEntry->bgw_name,
803 
804  LogicalRepCtx->launcher_pid = MyProcPid;
805 
806  /*
807  * Establish connection to nailed catalogs (we only ever access
808  * pg_subscription).
809  */
811 
812  /* Enter main loop */
813  while (!got_SIGTERM)
814  {
815  int rc;
816  List *sublist;
817  ListCell *lc;
818  MemoryContext subctx;
819  MemoryContext oldctx;
821  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
822 
823  now = GetCurrentTimestamp();
824 
825  /* Limit the start retry to once a wal_retrieve_retry_interval */
826  if (TimestampDifferenceExceeds(last_start_time, now,
828  {
829  /* Use temporary context for the database list and worker info. */
831  "Logical Replication Launcher sublist",
835  oldctx = MemoryContextSwitchTo(subctx);
836 
837  /* search for subscriptions to start or stop. */
838  sublist = get_subscription_list();
839 
840  /* Start the missing workers for enabled subscriptions. */
841  foreach(lc, sublist)
842  {
843  Subscription *sub = (Subscription *) lfirst(lc);
844  LogicalRepWorker *w;
845 
846  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
847  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
848  LWLockRelease(LogicalRepWorkerLock);
849 
850  if (sub->enabled && w == NULL)
851  {
852  last_start_time = now;
853  wait_time = wal_retrieve_retry_interval;
854 
855  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
856  sub->owner, InvalidOid);
857  }
858  }
859 
860  /* Switch back to original memory context. */
861  MemoryContextSwitchTo(oldctx);
862  /* Clean the temporary memory. */
863  MemoryContextDelete(subctx);
864  }
865  else
866  {
867  /*
868  * The wait in previous cycle was interrupted in less than
869  * wal_retrieve_retry_interval since last worker was started, this
870  * usually means crash of the worker, so we should retry in
871  * wal_retrieve_retry_interval again.
872  */
873  wait_time = wal_retrieve_retry_interval;
874  }
875 
876  /* Wait for more work. */
877  rc = WaitLatch(&MyProc->procLatch,
879  wait_time,
881 
882  /* emergency bailout if postmaster has died */
883  if (rc & WL_POSTMASTER_DEATH)
884  proc_exit(1);
885 
886  if (got_SIGHUP)
887  {
888  got_SIGHUP = false;
890  }
891 
893  }
894 
895  LogicalRepCtx->launcher_pid = 0;
896 
897  /* ... and if it returns, we're done */
898  ereport(DEBUG1,
899  (errmsg("logical replication launcher shutting down")));
900 
901  proc_exit(0);
902 }
903 
904 /*
905  * Returns state of the subscriptions.
906  */
907 Datum
909 {
910 #define PG_STAT_GET_SUBSCRIPTION_COLS 8
911  Oid subid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
912  int i;
913  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
914  TupleDesc tupdesc;
915  Tuplestorestate *tupstore;
916  MemoryContext per_query_ctx;
917  MemoryContext oldcontext;
918 
919  /* check to see if caller supports us returning a tuplestore */
920  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
921  ereport(ERROR,
922  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
923  errmsg("set-valued function called in context that cannot accept a set")));
924  if (!(rsinfo->allowedModes & SFRM_Materialize))
925  ereport(ERROR,
926  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
927  errmsg("materialize mode required, but it is not " \
928  "allowed in this context")));
929 
930  /* Build a tuple descriptor for our result type */
931  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
932  elog(ERROR, "return type must be a row type");
933 
934  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
935  oldcontext = MemoryContextSwitchTo(per_query_ctx);
936 
937  tupstore = tuplestore_begin_heap(true, false, work_mem);
938  rsinfo->returnMode = SFRM_Materialize;
939  rsinfo->setResult = tupstore;
940  rsinfo->setDesc = tupdesc;
941 
942  MemoryContextSwitchTo(oldcontext);
943 
944  /* Make sure we get consistent view of the workers. */
945  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
946 
947  for (i = 0; i <= max_logical_replication_workers; i++)
948  {
949  /* for each row */
951  bool nulls[PG_STAT_GET_SUBSCRIPTION_COLS];
952  int worker_pid;
953  LogicalRepWorker worker;
954 
955  memcpy(&worker, &LogicalRepCtx->workers[i],
956  sizeof(LogicalRepWorker));
957  if (!worker.proc || !IsBackendPid(worker.proc->pid))
958  continue;
959 
960  if (OidIsValid(subid) && worker.subid != subid)
961  continue;
962 
963  worker_pid = worker.proc->pid;
964 
965  MemSet(values, 0, sizeof(values));
966  MemSet(nulls, 0, sizeof(nulls));
967 
968  values[0] = ObjectIdGetDatum(worker.subid);
969  if (OidIsValid(worker.relid))
970  values[1] = ObjectIdGetDatum(worker.relid);
971  else
972  nulls[1] = true;
973  values[2] = Int32GetDatum(worker_pid);
974  if (XLogRecPtrIsInvalid(worker.last_lsn))
975  nulls[3] = true;
976  else
977  values[3] = LSNGetDatum(worker.last_lsn);
978  if (worker.last_send_time == 0)
979  nulls[4] = true;
980  else
981  values[4] = TimestampTzGetDatum(worker.last_send_time);
982  if (worker.last_recv_time == 0)
983  nulls[5] = true;
984  else
985  values[5] = TimestampTzGetDatum(worker.last_recv_time);
986  if (XLogRecPtrIsInvalid(worker.reply_lsn))
987  nulls[6] = true;
988  else
989  values[6] = LSNGetDatum(worker.reply_lsn);
990  if (worker.reply_time == 0)
991  nulls[7] = true;
992  else
993  values[7] = TimestampTzGetDatum(worker.reply_time);
994 
995  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
996 
997  /*
998  * If only a single subscription was requested, and we found it,
999  * break.
1000  */
1001  if (OidIsValid(subid))
1002  break;
1003  }
1004 
1005  LWLockRelease(LogicalRepWorkerLock);
1006 
1007  /* clean up and return the tuplestore */
1008  tuplestore_donestoring(tupstore);
1009 
1010  return (Datum) 0;
1011 }
void AtEOXact_ApplyLauncher(bool isCommit)
Definition: launcher.c:753
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:83
#define NIL
Definition: pg_list.h:69
void logicalrep_worker_sighup(SIGNAL_ARGS)
Definition: launcher.c:636
#define SIGUSR1
Definition: win32.h:202
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:849
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1849
#define DEBUG1
Definition: elog.h:25
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
int MyProcPid
Definition: globals.c:38
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
void ApplyLauncherMain(Datum main_arg)
Definition: launcher.c:786
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
void logicalrep_worker_wakeup(Oid subid, Oid relid)
Definition: launcher.c:511
PGPROC * MyProc
Definition: proc.c:67
int64 TimestampTz
Definition: timestamp.h:39
char * pstrdup(const char *in)
Definition: mcxt.c:1077
void CommitTransactionCommand(void)
Definition: xact.c:2749
#define SpinLockInit(lock)
Definition: spin.h:60
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
TimestampTz last_send_time
XLogRecPtr last_lsn
int bgw_restart_time
Definition: bgworker.h:93
void proc_exit(int code)
Definition: ipc.c:99
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
#define MemSet(start, val, len)
Definition: c.h:857
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:189
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define heap_close(r, l)
Definition: heapam.h:97
FormData_pg_subscription * Form_pg_subscription
void ResetLatch(volatile Latch *latch)
Definition: latch.c:498
unsigned int Oid
Definition: postgres_ext.h:31
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:95
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:162
int wal_receiver_timeout
Definition: walreceiver.c:75
Latch procLatch
Definition: proc.h:103
XLogRecPtr relstate_lsn
static void logicalrep_worker_detach(void)
Definition: launcher.c:572
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:527
Datum bgw_main_arg
Definition: bgworker.h:96
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
unsigned short uint16
Definition: c.h:267
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
int max_sync_workers_per_subscription
Definition: launcher.c:61
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
XLogRecPtr reply_lsn
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:586
#define SUBREL_STATE_UNKNOWN
#define SubscriptionRelationId
void logicalrep_worker_attach(int slot)
Definition: launcher.c:536
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6672
#define PG_GETARG_OID(n)
Definition: fmgr.h:240
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:411
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:677
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
static void logicalrep_launcher_onexit(int code, Datum arg)
Definition: launcher.c:604
#define TIMESTAMP_NOBEGIN(j)
Definition: timestamp.h:112
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
BgwHandleStatus
Definition: bgworker.h:101
static bool on_commit_launcher_wakeup
Definition: launcher.c:86
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
List * lappend(List *list, void *datum)
Definition: list.c:128
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define WARNING
Definition: elog.h:40
int wal_retrieve_retry_interval
Definition: xlog.c:107
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:615
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:878
#define DEFAULT_NAPTIME_PER_CYCLE
Definition: launcher.c:58
uintptr_t Datum
Definition: postgres.h:372
void ApplyLauncherRegister(void)
Definition: launcher.c:696
#define PG_STAT_GET_SUBSCRIPTION_COLS
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
void logicalrep_worker_sigterm(SIGNAL_ARGS)
Definition: launcher.c:622
int work_mem
Definition: globals.c:112
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:653
#define SIGHUP
Definition: win32.h:188
#define InvalidOid
Definition: postgres_ext.h:36
int allowedModes
Definition: execnodes.h:268
TimestampTz launch_time
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
static List * get_subscription_list(void)
Definition: launcher.c:98
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
int max_replication_slots
Definition: slot.c:99
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
TimestampTz last_recv_time
#define PG_ARGISNULL(n)
Definition: fmgr.h:174
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define SIGNAL_ARGS
Definition: c.h:1079
#define NULL
Definition: c.h:229
volatile sig_atomic_t got_SIGTERM
Definition: launcher.c:84
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:252
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:225
void StartTransactionCommand(void)
Definition: xact.c:2679
int max_logical_replication_workers
Definition: launcher.c:60
#define BGW_MAXLEN
Definition: bgworker.h:85
size_t Size
Definition: c.h:356
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:92
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:933
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
#define MAXALIGN(LEN)
Definition: c.h:588
void ApplyLauncherShmemInit(void)
Definition: launcher.c:723
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, BackgroundWorkerHandle *handle)
Definition: launcher.c:163
struct LogicalRepCtxStruct LogicalRepCtxStruct
Tuplestorestate * setResult
Definition: execnodes.h:273
static Datum values[MAXATTR]
Definition: bootstrap.c:163
ExprContext * econtext
Definition: execnodes.h:266
#define Int32GetDatum(X)
Definition: postgres.h:485
TupleDesc setDesc
Definition: execnodes.h:274
int errmsg(const char *fmt,...)
Definition: elog.c:797
pid_t bgw_notify_pid
Definition: bgworker.h:98
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:163
int i
#define NameStr(name)
Definition: c.h:499
bool IsBackendPid(int pid)
Definition: procarray.c:2437
void * arg
struct Latch * MyLatch
Definition: globals.c:51
#define PG_FUNCTION_ARGS
Definition: fmgr.h:158
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:164
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
Datum pg_stat_get_subscription(PG_FUNCTION_ARGS)
Definition: launcher.c:908
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
static void ApplyLauncherWakeup(void)
Definition: launcher.c:776
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:769
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:94
Definition: pg_list.h:45
int pid
Definition: proc.h:108
#define WL_LATCH_SET
Definition: latch.h:124
void BackgroundWorkerInitializeConnection(char *dbname, char *username)
Definition: postmaster.c:5470
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1041
TimestampTz reply_time
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5522