PostgreSQL Source Code  git master
bgworker.c File Reference
#include "postgres.h"
#include "access/parallel.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/postmaster.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem.h"
#include "tcop/tcopprot.h"
#include "utils/ascii.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/timeout.h"
Include dependency graph for bgworker.c:

Go to the source code of this file.

Data Structures

struct  BackgroundWorkerSlot
 
struct  BackgroundWorkerArray
 
struct  BackgroundWorkerHandle
 

Typedefs

typedef struct BackgroundWorkerSlot BackgroundWorkerSlot
 
typedef struct BackgroundWorkerArray BackgroundWorkerArray
 

Functions

static bgworker_main_type LookupBackgroundWorkerFunction (const char *libraryname, const char *funcname)
 
Size BackgroundWorkerShmemSize (void)
 
void BackgroundWorkerShmemInit (void)
 
static RegisteredBgWorkerFindRegisteredWorkerBySlotNumber (int slotno)
 
void BackgroundWorkerStateChange (bool allow_new_workers)
 
void ForgetBackgroundWorker (slist_mutable_iter *cur)
 
void ReportBackgroundWorkerPID (RegisteredBgWorker *rw)
 
void ReportBackgroundWorkerExit (slist_mutable_iter *cur)
 
void BackgroundWorkerStopNotifications (pid_t pid)
 
void ForgetUnstartedBackgroundWorkers (void)
 
void ResetBackgroundWorkerCrashTimes (void)
 
static bool SanityCheckBackgroundWorker (BackgroundWorker *worker, int elevel)
 
static void bgworker_die (SIGNAL_ARGS)
 
void BackgroundWorkerMain (char *startup_data, size_t startup_data_len)
 
void RegisterBackgroundWorker (BackgroundWorker *worker)
 
bool RegisterDynamicBackgroundWorker (BackgroundWorker *worker, BackgroundWorkerHandle **handle)
 
BgwHandleStatus GetBackgroundWorkerPid (BackgroundWorkerHandle *handle, pid_t *pidp)
 
BgwHandleStatus WaitForBackgroundWorkerStartup (BackgroundWorkerHandle *handle, pid_t *pidp)
 
BgwHandleStatus WaitForBackgroundWorkerShutdown (BackgroundWorkerHandle *handle)
 
void TerminateBackgroundWorker (BackgroundWorkerHandle *handle)
 
const char * GetBackgroundWorkerTypeByPid (pid_t pid)
 

Variables

slist_head BackgroundWorkerList = SLIST_STATIC_INIT(BackgroundWorkerList)
 
static BackgroundWorkerArrayBackgroundWorkerData
 
struct {
   const char *   fn_name
 
   bgworker_main_type   fn_addr
 
InternalBGWorkers []
 

Typedef Documentation

◆ BackgroundWorkerArray

◆ BackgroundWorkerSlot

Function Documentation

◆ BackgroundWorkerMain()

void BackgroundWorkerMain ( char *  startup_data,
size_t  startup_data_len 
)

Definition at line 723 of file bgworker.c.

724 {
725  sigjmp_buf local_sigjmp_buf;
726  BackgroundWorker *worker;
727  bgworker_main_type entrypt;
728 
729  if (startup_data == NULL)
730  elog(FATAL, "unable to find bgworker entry");
731  Assert(startup_data_len == sizeof(BackgroundWorker));
733  memcpy(worker, startup_data, sizeof(BackgroundWorker));
734 
735  /*
736  * Now that we're done reading the startup data, release postmaster's
737  * working memory context.
738  */
739  if (PostmasterContext)
740  {
742  PostmasterContext = NULL;
743  }
744 
745  MyBgworkerEntry = worker;
747  init_ps_display(worker->bgw_name);
748 
750 
751  /* Apply PostAuthDelay */
752  if (PostAuthDelay > 0)
753  pg_usleep(PostAuthDelay * 1000000L);
754 
755  /*
756  * Set up signal handlers.
757  */
759  {
760  /*
761  * SIGINT is used to signal canceling the current action
762  */
766 
767  /* XXX Any other handlers needed here? */
768  }
769  else
770  {
771  pqsignal(SIGINT, SIG_IGN);
773  pqsignal(SIGFPE, SIG_IGN);
774  }
775  pqsignal(SIGTERM, bgworker_die);
776  /* SIGQUIT handler was already set up by InitPostmasterChild */
778 
779  InitializeTimeouts(); /* establishes SIGALRM handler */
780 
784 
785  /*
786  * If an exception is encountered, processing resumes here.
787  *
788  * We just need to clean up, report the error, and go away.
789  */
790  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
791  {
792  /* Since not using PG_TRY, must reset error stack by hand */
793  error_context_stack = NULL;
794 
795  /* Prevent interrupts while cleaning up */
796  HOLD_INTERRUPTS();
797 
798  /*
799  * sigsetjmp will have blocked all signals, but we may need to accept
800  * signals while communicating with our parallel leader. Once we've
801  * done HOLD_INTERRUPTS() it should be safe to unblock signals.
802  */
804 
805  /* Report the error to the parallel leader and the server log */
806  EmitErrorReport();
807 
808  /*
809  * Do we need more cleanup here? For shmem-connected bgworkers, we
810  * will call InitProcess below, which will install ProcKill as exit
811  * callback. That will take care of releasing locks, etc.
812  */
813 
814  /* and go away */
815  proc_exit(1);
816  }
817 
818  /* We can now handle ereport(ERROR) */
819  PG_exception_stack = &local_sigjmp_buf;
820 
821  /*
822  * Create a per-backend PGPROC struct in shared memory. We must do this
823  * before we can use LWLocks or access any shared memory.
824  */
825  InitProcess();
826 
827  /*
828  * Early initialization.
829  */
830  BaseInit();
831 
832  /*
833  * Look up the entry point function, loading its library if necessary.
834  */
836  worker->bgw_function_name);
837 
838  /*
839  * Note that in normal processes, we would call InitPostgres here. For a
840  * worker, however, we don't know what database to connect to, yet; so we
841  * need to wait until the user code does it via
842  * BackgroundWorkerInitializeConnection().
843  */
844 
845  /*
846  * Now invoke the user-defined worker code
847  */
848  entrypt(worker->bgw_main_arg);
849 
850  /* ... and if it returns, we're done */
851  proc_exit(0);
852 }
static bgworker_main_type LookupBackgroundWorkerFunction(const char *libraryname, const char *funcname)
Definition: bgworker.c:1262
static void bgworker_die(SIGNAL_ARGS)
Definition: bgworker.c:709
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
void(* bgworker_main_type)(Datum main_arg)
Definition: bgworker.h:72
#define Assert(condition)
Definition: c.h:858
void EmitErrorReport(void)
Definition: elog.c:1670
ErrorContextCallback * error_context_stack
Definition: elog.c:94
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
#define FATAL
Definition: elog.h:41
#define elog(elevel,...)
Definition: elog.h:224
void proc_exit(int code)
Definition: ipc.c:104
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1180
MemoryContext PostmasterContext
Definition: mcxt.c:151
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
@ InitProcessing
Definition: miscadmin.h:448
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
@ B_BG_WORKER
Definition: miscadmin.h:341
BackendType MyBackendType
Definition: miscinit.c:63
pqsigfunc pqsignal(int signo, pqsigfunc func)
int PostAuthDelay
Definition: postgres.c:101
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3019
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3002
void BaseInit(void)
Definition: postinit.c:645
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:4229
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:185
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:635
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:267
void pg_usleep(long microsec)
Definition: signal.c:53
void InitProcess(void)
Definition: proc.c:296
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:97
Datum bgw_main_arg
Definition: bgworker.h:98
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
char bgw_library_name[MAXPGPATH]
Definition: bgworker.h:96
void InitializeTimeouts(void)
Definition: timeout.c:470
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define SIGPIPE
Definition: win32_port.h:173
#define SIGUSR1
Definition: win32_port.h:180
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165

References Assert, B_BG_WORKER, BackgroundWorkerUnblockSignals(), BaseInit(), BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_main_arg, BackgroundWorker::bgw_name, BGWORKER_BACKEND_DATABASE_CONNECTION, bgworker_die(), elog, EmitErrorReport(), error_context_stack, FATAL, FloatExceptionHandler(), HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitProcess(), InitProcessing, LookupBackgroundWorkerFunction(), MemoryContextAlloc(), MemoryContextDelete(), MyBackendType, MyBgworkerEntry, PG_exception_stack, pg_usleep(), PostAuthDelay, PostmasterContext, pqsignal(), proc_exit(), procsignal_sigusr1_handler(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), and TopMemoryContext.

◆ BackgroundWorkerShmemInit()

void BackgroundWorkerShmemInit ( void  )

Definition at line 162 of file bgworker.c.

163 {
164  bool found;
165 
166  BackgroundWorkerData = ShmemInitStruct("Background Worker Data",
168  &found);
169  if (!IsUnderPostmaster)
170  {
171  slist_iter siter;
172  int slotno = 0;
173 
177 
178  /*
179  * Copy contents of worker list into shared memory. Record the shared
180  * memory slot assigned to each worker. This ensures a 1-to-1
181  * correspondence between the postmaster's private list and the array
182  * in shared memory.
183  */
185  {
187  RegisteredBgWorker *rw;
188 
189  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
190  Assert(slotno < max_worker_processes);
191  slot->in_use = true;
192  slot->terminate = false;
193  slot->pid = InvalidPid;
194  slot->generation = 0;
195  rw->rw_shmem_slot = slotno;
196  rw->rw_worker.bgw_notify_pid = 0; /* might be reinit after crash */
197  memcpy(&slot->worker, &rw->rw_worker, sizeof(BackgroundWorker));
198  ++slotno;
199  }
200 
201  /*
202  * Mark any remaining slots as not in use.
203  */
204  while (slotno < max_worker_processes)
205  {
207 
208  slot->in_use = false;
209  ++slotno;
210  }
211  }
212  else
213  Assert(found);
214 }
slist_head BackgroundWorkerList
Definition: bgworker.c:40
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:108
Size BackgroundWorkerShmemSize(void)
Definition: bgworker.c:146
bool IsUnderPostmaster
Definition: globals.c:117
int max_worker_processes
Definition: globals.c:141
#define slist_container(type, membername, ptr)
Definition: ilist.h:1106
#define slist_foreach(iter, lhead)
Definition: ilist.h:1132
#define InvalidPid
Definition: miscadmin.h:32
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
uint32 parallel_terminate_count
Definition: bgworker.c:98
uint32 parallel_register_count
Definition: bgworker.c:97
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:99
BackgroundWorker worker
Definition: bgworker.c:80
pid_t bgw_notify_pid
Definition: bgworker.h:100
BackgroundWorker rw_worker
slist_node * cur
Definition: ilist.h:259

References Assert, BackgroundWorkerData, BackgroundWorkerList, BackgroundWorkerShmemSize(), BackgroundWorker::bgw_notify_pid, slist_iter::cur, BackgroundWorkerSlot::generation, BackgroundWorkerSlot::in_use, InvalidPid, IsUnderPostmaster, max_worker_processes, BackgroundWorkerArray::parallel_register_count, BackgroundWorkerArray::parallel_terminate_count, BackgroundWorkerSlot::pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, ShmemInitStruct(), slist_container, slist_foreach, BackgroundWorkerArray::slot, BackgroundWorkerSlot::terminate, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

Referenced by CreateOrAttachShmemStructs().

◆ BackgroundWorkerShmemSize()

Size BackgroundWorkerShmemSize ( void  )

Definition at line 146 of file bgworker.c.

147 {
148  Size size;
149 
150  /* Array of workers is variably sized. */
151  size = offsetof(BackgroundWorkerArray, slot);
153  sizeof(BackgroundWorkerSlot)));
154 
155  return size;
156 }
size_t Size
Definition: c.h:605
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

References add_size(), max_worker_processes, mul_size(), and size.

Referenced by BackgroundWorkerShmemInit(), and CalculateShmemSize().

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)

Definition at line 246 of file bgworker.c.

247 {
248  int slotno;
249 
250  /*
251  * The total number of slots stored in shared memory should match our
252  * notion of max_worker_processes. If it does not, something is very
253  * wrong. Further down, we always refer to this value as
254  * max_worker_processes, in case shared memory gets corrupted while we're
255  * looping.
256  */
258  {
259  ereport(LOG,
260  (errmsg("inconsistent background worker state (max_worker_processes=%d, total_slots=%d)",
263  return;
264  }
265 
266  /*
267  * Iterate through slots, looking for newly-registered workers or workers
268  * who must die.
269  */
270  for (slotno = 0; slotno < max_worker_processes; ++slotno)
271  {
273  RegisteredBgWorker *rw;
274 
275  if (!slot->in_use)
276  continue;
277 
278  /*
279  * Make sure we don't see the in_use flag before the updated slot
280  * contents.
281  */
282  pg_read_barrier();
283 
284  /* See whether we already know about this worker. */
286  if (rw != NULL)
287  {
288  /*
289  * In general, the worker data can't change after it's initially
290  * registered. However, someone can set the terminate flag.
291  */
292  if (slot->terminate && !rw->rw_terminate)
293  {
294  rw->rw_terminate = true;
295  if (rw->rw_pid != 0)
296  kill(rw->rw_pid, SIGTERM);
297  else
298  {
299  /* Report never-started, now-terminated worker as dead. */
301  }
302  }
303  continue;
304  }
305 
306  /*
307  * If we aren't allowing new workers, then immediately mark it for
308  * termination; the next stanza will take care of cleaning it up.
309  * Doing this ensures that any process waiting for the worker will get
310  * awoken, even though the worker will never be allowed to run.
311  */
312  if (!allow_new_workers)
313  slot->terminate = true;
314 
315  /*
316  * If the worker is marked for termination, we don't need to add it to
317  * the registered workers list; we can just free the slot. However, if
318  * bgw_notify_pid is set, the process that registered the worker may
319  * need to know that we've processed the terminate request, so be sure
320  * to signal it.
321  */
322  if (slot->terminate)
323  {
324  int notify_pid;
325 
326  /*
327  * We need a memory barrier here to make sure that the load of
328  * bgw_notify_pid and the update of parallel_terminate_count
329  * complete before the store to in_use.
330  */
331  notify_pid = slot->worker.bgw_notify_pid;
332  if ((slot->worker.bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
334  slot->pid = 0;
335 
337  slot->in_use = false;
338 
339  if (notify_pid != 0)
340  kill(notify_pid, SIGUSR1);
341 
342  continue;
343  }
344 
345  /*
346  * Copy the registration data into the registered workers list.
347  */
349  sizeof(RegisteredBgWorker),
351  if (rw == NULL)
352  {
353  ereport(LOG,
354  (errcode(ERRCODE_OUT_OF_MEMORY),
355  errmsg("out of memory")));
356  return;
357  }
358 
359  /*
360  * Copy strings in a paranoid way. If shared memory is corrupted, the
361  * source data might not even be NUL-terminated.
362  */
364  slot->worker.bgw_name, BGW_MAXLEN);
366  slot->worker.bgw_type, BGW_MAXLEN);
371 
372  /*
373  * Copy various fixed-size fields.
374  *
375  * flags, start_time, and restart_time are examined by the postmaster,
376  * but nothing too bad will happen if they are corrupted. The
377  * remaining fields will only be examined by the child process. It
378  * might crash, but we won't.
379  */
380  rw->rw_worker.bgw_flags = slot->worker.bgw_flags;
384  memcpy(rw->rw_worker.bgw_extra, slot->worker.bgw_extra, BGW_EXTRALEN);
385 
386  /*
387  * Copy the PID to be notified about state changes, but only if the
388  * postmaster knows about a backend with that PID. It isn't an error
389  * if the postmaster doesn't know about the PID, because the backend
390  * that requested the worker could have died (or been killed) just
391  * after doing so. Nonetheless, at least until we get some experience
392  * with how this plays out in the wild, log a message at a relative
393  * high debug level.
394  */
397  {
398  elog(DEBUG1, "worker notification PID %d is not valid",
399  (int) rw->rw_worker.bgw_notify_pid);
400  rw->rw_worker.bgw_notify_pid = 0;
401  }
402 
403  /* Initialize postmaster bookkeeping. */
404  rw->rw_backend = NULL;
405  rw->rw_pid = 0;
406  rw->rw_child_slot = 0;
407  rw->rw_crashed_at = 0;
408  rw->rw_shmem_slot = slotno;
409  rw->rw_terminate = false;
410 
411  /* Log it! */
412  ereport(DEBUG1,
413  (errmsg_internal("registering background worker \"%s\"",
414  rw->rw_worker.bgw_name)));
415 
417  }
418 }
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:174
#define pg_memory_barrier()
Definition: atomics.h:138
#define pg_read_barrier()
Definition: atomics.h:151
static RegisteredBgWorker * FindRegisteredWorkerBySlotNumber(int slotno)
Definition: bgworker.c:221
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:467
#define BGW_EXTRALEN
Definition: bgworker.h:87
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
#define BGW_MAXLEN
Definition: bgworker.h:86
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode(int sqlerrcode)
Definition: elog.c:857
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define DEBUG1
Definition: elog.h:30
#define ereport(elevel,...)
Definition: elog.h:149
#define MCXT_ALLOC_ZERO
Definition: fe_memutils.h:18
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:17
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:1006
void * MemoryContextAllocExtended(MemoryContext context, Size size, int flags)
Definition: mcxt.c:1237
#define MAXPGPATH
bool PostmasterMarkPIDForWorkerNotify(int pid)
Definition: postmaster.c:4528
int bgw_restart_time
Definition: bgworker.h:95
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:99
struct bkend * rw_backend
#define kill(pid, sig)
Definition: win32_port.h:485

References ascii_safe_strlcpy(), BackgroundWorkerData, BackgroundWorkerList, BackgroundWorker::bgw_extra, BGW_EXTRALEN, BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_main_arg, BGW_MAXLEN, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, BGWORKER_CLASS_PARALLEL, DEBUG1, elog, ereport, errcode(), errmsg(), errmsg_internal(), FindRegisteredWorkerBySlotNumber(), BackgroundWorkerSlot::in_use, kill, LOG, max_worker_processes, MAXPGPATH, MCXT_ALLOC_NO_OOM, MCXT_ALLOC_ZERO, MemoryContextAllocExtended(), BackgroundWorkerArray::parallel_terminate_count, pg_memory_barrier, pg_read_barrier, BackgroundWorkerSlot::pid, PostmasterContext, PostmasterMarkPIDForWorkerNotify(), ReportBackgroundWorkerPID(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_lnode, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SIGUSR1, slist_push_head(), BackgroundWorkerArray::slot, BackgroundWorkerSlot::terminate, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

Referenced by process_pm_pmsignal().

◆ BackgroundWorkerStopNotifications()

void BackgroundWorkerStopNotifications ( pid_t  pid)

Definition at line 520 of file bgworker.c.

521 {
522  slist_iter siter;
523 
525  {
526  RegisteredBgWorker *rw;
527 
528  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
529  if (rw->rw_worker.bgw_notify_pid == pid)
530  rw->rw_worker.bgw_notify_pid = 0;
531  }
532 }

References BackgroundWorkerList, BackgroundWorker::bgw_notify_pid, slist_iter::cur, RegisteredBgWorker::rw_worker, slist_container, and slist_foreach.

Referenced by CleanupBackend(), and CleanupBackgroundWorker().

◆ bgworker_die()

static void bgworker_die ( SIGNAL_ARGS  )
static

Definition at line 709 of file bgworker.c.

710 {
711  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
712 
713  ereport(FATAL,
714  (errcode(ERRCODE_ADMIN_SHUTDOWN),
715  errmsg("terminating background worker \"%s\" due to administrator command",
717 }
sigset_t BlockSig
Definition: pqsignal.c:23

References BackgroundWorker::bgw_type, BlockSig, ereport, errcode(), errmsg(), FATAL, and MyBgworkerEntry.

Referenced by BackgroundWorkerMain().

◆ FindRegisteredWorkerBySlotNumber()

static RegisteredBgWorker* FindRegisteredWorkerBySlotNumber ( int  slotno)
static

Definition at line 221 of file bgworker.c.

222 {
223  slist_iter siter;
224 
226  {
227  RegisteredBgWorker *rw;
228 
229  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
230  if (rw->rw_shmem_slot == slotno)
231  return rw;
232  }
233 
234  return NULL;
235 }

References BackgroundWorkerList, slist_iter::cur, RegisteredBgWorker::rw_shmem_slot, slist_container, and slist_foreach.

Referenced by BackgroundWorkerStateChange().

◆ ForgetBackgroundWorker()

void ForgetBackgroundWorker ( slist_mutable_iter cur)

Definition at line 432 of file bgworker.c.

433 {
434  RegisteredBgWorker *rw;
435  BackgroundWorkerSlot *slot;
436 
437  rw = slist_container(RegisteredBgWorker, rw_lnode, cur->cur);
438 
441  Assert(slot->in_use);
442 
443  /*
444  * We need a memory barrier here to make sure that the update of
445  * parallel_terminate_count completes before the store to in_use.
446  */
449 
451  slot->in_use = false;
452 
453  ereport(DEBUG1,
454  (errmsg_internal("unregistering background worker \"%s\"",
455  rw->rw_worker.bgw_name)));
456 
458  pfree(rw);
459 }
struct cursor * cur
Definition: ecpg.c:28
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:1084
void pfree(void *pointer)
Definition: mcxt.c:1520

References Assert, BackgroundWorkerData, BackgroundWorker::bgw_flags, BackgroundWorker::bgw_name, BGWORKER_CLASS_PARALLEL, cur, DEBUG1, ereport, errmsg_internal(), BackgroundWorkerSlot::in_use, max_worker_processes, BackgroundWorkerArray::parallel_terminate_count, pfree(), pg_memory_barrier, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, slist_container, slist_delete_current(), and BackgroundWorkerArray::slot.

Referenced by DetermineSleepTime(), ForgetUnstartedBackgroundWorkers(), maybe_start_bgworkers(), ReportBackgroundWorkerExit(), and ResetBackgroundWorkerCrashTimes().

◆ ForgetUnstartedBackgroundWorkers()

void ForgetUnstartedBackgroundWorkers ( void  )

Definition at line 547 of file bgworker.c.

548 {
549  slist_mutable_iter iter;
550 
552  {
553  RegisteredBgWorker *rw;
554  BackgroundWorkerSlot *slot;
555 
556  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
559 
560  /* If it's not yet started, and there's someone waiting ... */
561  if (slot->pid == InvalidPid &&
562  rw->rw_worker.bgw_notify_pid != 0)
563  {
564  /* ... then zap it, and notify the waiter */
565  int notify_pid = rw->rw_worker.bgw_notify_pid;
566 
567  ForgetBackgroundWorker(&iter);
568  if (notify_pid != 0)
569  kill(notify_pid, SIGUSR1);
570  }
571  }
572 }
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:432
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:1148
slist_node * cur
Definition: ilist.h:274

References Assert, BackgroundWorkerData, BackgroundWorkerList, BackgroundWorker::bgw_notify_pid, slist_mutable_iter::cur, ForgetBackgroundWorker(), InvalidPid, kill, max_worker_processes, BackgroundWorkerSlot::pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, SIGUSR1, slist_container, slist_foreach_modify, and BackgroundWorkerArray::slot.

Referenced by PostmasterStateMachine().

◆ GetBackgroundWorkerPid()

BgwHandleStatus GetBackgroundWorkerPid ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1082 of file bgworker.c.

1083 {
1084  BackgroundWorkerSlot *slot;
1085  pid_t pid;
1086 
1087  Assert(handle->slot < max_worker_processes);
1088  slot = &BackgroundWorkerData->slot[handle->slot];
1089 
1090  /*
1091  * We could probably arrange to synchronize access to data using memory
1092  * barriers only, but for now, let's just keep it simple and grab the
1093  * lock. It seems unlikely that there will be enough traffic here to
1094  * result in meaningful contention.
1095  */
1096  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1097 
1098  /*
1099  * The generation number can't be concurrently changed while we hold the
1100  * lock. The pid, which is updated by the postmaster, can change at any
1101  * time, but we assume such changes are atomic. So the value we read
1102  * won't be garbage, but it might be out of date by the time the caller
1103  * examines it (but that's unavoidable anyway).
1104  *
1105  * The in_use flag could be in the process of changing from true to false,
1106  * but if it is already false then it can't change further.
1107  */
1108  if (handle->generation != slot->generation || !slot->in_use)
1109  pid = 0;
1110  else
1111  pid = slot->pid;
1112 
1113  /* All done. */
1114  LWLockRelease(BackgroundWorkerLock);
1115 
1116  if (pid == 0)
1117  return BGWH_STOPPED;
1118  else if (pid == InvalidPid)
1119  return BGWH_NOT_YET_STARTED;
1120  *pidp = pid;
1121  return BGWH_STARTED;
1122 }
@ BGWH_STARTED
Definition: bgworker.h:105
@ BGWH_NOT_YET_STARTED
Definition: bgworker.h:106
@ BGWH_STOPPED
Definition: bgworker.h:107
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
@ LW_SHARED
Definition: lwlock.h:115

References Assert, BackgroundWorkerData, BGWH_NOT_YET_STARTED, BGWH_STARTED, BGWH_STOPPED, BackgroundWorkerSlot::generation, BackgroundWorkerHandle::generation, BackgroundWorkerSlot::in_use, InvalidPid, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_worker_processes, BackgroundWorkerSlot::pid, BackgroundWorkerArray::slot, and BackgroundWorkerHandle::slot.

Referenced by check_worker_status(), shm_mq_counterparty_gone(), shm_mq_wait_internal(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), and WaitForReplicationWorkerAttach().

◆ GetBackgroundWorkerTypeByPid()

const char* GetBackgroundWorkerTypeByPid ( pid_t  pid)

Definition at line 1296 of file bgworker.c.

1297 {
1298  int slotno;
1299  bool found = false;
1300  static char result[BGW_MAXLEN];
1301 
1302  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1303 
1304  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; slotno++)
1305  {
1307 
1308  if (slot->pid > 0 && slot->pid == pid)
1309  {
1310  strcpy(result, slot->worker.bgw_type);
1311  found = true;
1312  break;
1313  }
1314  }
1315 
1316  LWLockRelease(BackgroundWorkerLock);
1317 
1318  if (!found)
1319  return NULL;
1320 
1321  return result;
1322 }

References BackgroundWorkerData, BGW_MAXLEN, BackgroundWorker::bgw_type, LW_SHARED, LWLockAcquire(), LWLockRelease(), BackgroundWorkerSlot::pid, BackgroundWorkerArray::slot, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

Referenced by pg_stat_get_activity().

◆ LookupBackgroundWorkerFunction()

static bgworker_main_type LookupBackgroundWorkerFunction ( const char *  libraryname,
const char *  funcname 
)
static

Definition at line 1262 of file bgworker.c.

1263 {
1264  /*
1265  * If the function is to be loaded from postgres itself, search the
1266  * InternalBGWorkers array.
1267  */
1268  if (strcmp(libraryname, "postgres") == 0)
1269  {
1270  int i;
1271 
1272  for (i = 0; i < lengthof(InternalBGWorkers); i++)
1273  {
1274  if (strcmp(InternalBGWorkers[i].fn_name, funcname) == 0)
1275  return InternalBGWorkers[i].fn_addr;
1276  }
1277 
1278  /* We can only reach this by programming error. */
1279  elog(ERROR, "internal function \"%s\" not found", funcname);
1280  }
1281 
1282  /* Otherwise load from external library. */
1283  return (bgworker_main_type)
1284  load_external_function(libraryname, funcname, true, NULL);
1285 }
static const struct @18 InternalBGWorkers[]
const char * fn_name
Definition: bgworker.c:116
bgworker_main_type fn_addr
Definition: bgworker.c:117
#define lengthof(array)
Definition: c.h:788
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:105
#define ERROR
Definition: elog.h:39
#define funcname
Definition: indent_codes.h:69
int i
Definition: isn.c:73

References elog, ERROR, fn_addr, fn_name, funcname, i, InternalBGWorkers, lengthof, and load_external_function().

Referenced by BackgroundWorkerMain().

◆ RegisterBackgroundWorker()

void RegisterBackgroundWorker ( BackgroundWorker worker)

Definition at line 862 of file bgworker.c.

863 {
864  RegisteredBgWorker *rw;
865  static int numworkers = 0;
866 
867  /*
868  * Static background workers can only be registered in the postmaster
869  * process.
870  */
872  {
873  /*
874  * In EXEC_BACKEND or single-user mode, we process
875  * shared_preload_libraries in backend processes too. We cannot
876  * register static background workers at that stage, but many
877  * libraries' _PG_init() functions don't distinguish whether they're
878  * being loaded in the postmaster or in a backend, they just check
879  * process_shared_preload_libraries_in_progress. It's a bit sloppy,
880  * but for historical reasons we tolerate it. In EXEC_BACKEND mode,
881  * the background workers should already have been registered when the
882  * library was loaded in postmaster.
883  */
885  return;
886  ereport(LOG,
887  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
888  errmsg("background worker \"%s\": must be registered in \"shared_preload_libraries\"",
889  worker->bgw_name)));
890  return;
891  }
892 
893  /*
894  * Cannot register static background workers after calling
895  * BackgroundWorkerShmemInit().
896  */
897  if (BackgroundWorkerData != NULL)
898  elog(ERROR, "cannot register background worker \"%s\" after shmem init",
899  worker->bgw_name);
900 
901  ereport(DEBUG1,
902  (errmsg_internal("registering background worker \"%s\"", worker->bgw_name)));
903 
904  if (!SanityCheckBackgroundWorker(worker, LOG))
905  return;
906 
907  if (worker->bgw_notify_pid != 0)
908  {
909  ereport(LOG,
910  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
911  errmsg("background worker \"%s\": only dynamic background workers can request notification",
912  worker->bgw_name)));
913  return;
914  }
915 
916  /*
917  * Enforce maximum number of workers. Note this is overly restrictive: we
918  * could allow more non-shmem-connected workers, because these don't count
919  * towards the MAX_BACKENDS limit elsewhere. For now, it doesn't seem
920  * important to relax this restriction.
921  */
922  if (++numworkers > max_worker_processes)
923  {
924  ereport(LOG,
925  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
926  errmsg("too many background workers"),
927  errdetail_plural("Up to %d background worker can be registered with the current settings.",
928  "Up to %d background workers can be registered with the current settings.",
931  errhint("Consider increasing the configuration parameter \"max_worker_processes\".")));
932  return;
933  }
934 
935  /*
936  * Copy the registration data into the registered workers list.
937  */
939  sizeof(RegisteredBgWorker),
941  if (rw == NULL)
942  {
943  ereport(LOG,
944  (errcode(ERRCODE_OUT_OF_MEMORY),
945  errmsg("out of memory")));
946  return;
947  }
948 
949  rw->rw_worker = *worker;
950  rw->rw_backend = NULL;
951  rw->rw_pid = 0;
952  rw->rw_child_slot = 0;
953  rw->rw_crashed_at = 0;
954  rw->rw_terminate = false;
955 
957 }
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition: bgworker.c:637
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1295
int errhint(const char *fmt,...)
Definition: elog.c:1317
bool IsPostmasterEnvironment
Definition: globals.c:116
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1778

References BackgroundWorkerData, BackgroundWorkerList, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, DEBUG1, elog, ereport, errcode(), errdetail_plural(), errhint(), errmsg(), errmsg_internal(), ERROR, IsPostmasterEnvironment, IsUnderPostmaster, LOG, max_worker_processes, MCXT_ALLOC_NO_OOM, MemoryContextAllocExtended(), PostmasterContext, process_shared_preload_libraries_in_progress, RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_lnode, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SanityCheckBackgroundWorker(), and slist_push_head().

Referenced by _PG_init(), ApplyLauncherRegister(), and apw_start_leader_worker().

◆ RegisterDynamicBackgroundWorker()

bool RegisterDynamicBackgroundWorker ( BackgroundWorker worker,
BackgroundWorkerHandle **  handle 
)

Definition at line 970 of file bgworker.c.

972 {
973  int slotno;
974  bool success = false;
975  bool parallel;
976  uint64 generation = 0;
977 
978  /*
979  * We can't register dynamic background workers from the postmaster. If
980  * this is a standalone backend, we're the only process and can't start
981  * any more. In a multi-process environment, it might be theoretically
982  * possible, but we don't currently support it due to locking
983  * considerations; see comments on the BackgroundWorkerSlot data
984  * structure.
985  */
986  if (!IsUnderPostmaster)
987  return false;
988 
989  if (!SanityCheckBackgroundWorker(worker, ERROR))
990  return false;
991 
992  parallel = (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0;
993 
994  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
995 
996  /*
997  * If this is a parallel worker, check whether there are already too many
998  * parallel workers; if so, don't register another one. Our view of
999  * parallel_terminate_count may be slightly stale, but that doesn't really
1000  * matter: we would have gotten the same result if we'd arrived here
1001  * slightly earlier anyway. There's no help for it, either, since the
1002  * postmaster must not take locks; a memory barrier wouldn't guarantee
1003  * anything useful.
1004  */
1005  if (parallel && (BackgroundWorkerData->parallel_register_count -
1008  {
1012  LWLockRelease(BackgroundWorkerLock);
1013  return false;
1014  }
1015 
1016  /*
1017  * Look for an unused slot. If we find one, grab it.
1018  */
1019  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; ++slotno)
1020  {
1022 
1023  if (!slot->in_use)
1024  {
1025  memcpy(&slot->worker, worker, sizeof(BackgroundWorker));
1026  slot->pid = InvalidPid; /* indicates not started yet */
1027  slot->generation++;
1028  slot->terminate = false;
1029  generation = slot->generation;
1030  if (parallel)
1032 
1033  /*
1034  * Make sure postmaster doesn't see the slot as in use before it
1035  * sees the new contents.
1036  */
1037  pg_write_barrier();
1038 
1039  slot->in_use = true;
1040  success = true;
1041  break;
1042  }
1043  }
1044 
1045  LWLockRelease(BackgroundWorkerLock);
1046 
1047  /* If we found a slot, tell the postmaster to notice the change. */
1048  if (success)
1050 
1051  /*
1052  * If we found a slot and the user has provided a handle, initialize it.
1053  */
1054  if (success && handle)
1055  {
1056  *handle = palloc(sizeof(BackgroundWorkerHandle));
1057  (*handle)->slot = slotno;
1058  (*handle)->generation = generation;
1059  }
1060 
1061  return success;
1062 }
#define pg_write_barrier()
Definition: atomics.h:152
#define MAX_PARALLEL_WORKER_LIMIT
int max_parallel_workers
Definition: globals.c:142
static bool success
Definition: initdb.c:186
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void * palloc(Size size)
Definition: mcxt.c:1316
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:181
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition: pmsignal.h:40

References Assert, BackgroundWorkerData, BackgroundWorker::bgw_flags, BGWORKER_CLASS_PARALLEL, ERROR, BackgroundWorkerSlot::generation, BackgroundWorkerSlot::in_use, InvalidPid, IsUnderPostmaster, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAX_PARALLEL_WORKER_LIMIT, max_parallel_workers, palloc(), BackgroundWorkerArray::parallel_register_count, BackgroundWorkerArray::parallel_terminate_count, pg_write_barrier, BackgroundWorkerSlot::pid, PMSIGNAL_BACKGROUND_WORKER_CHANGE, SanityCheckBackgroundWorker(), SendPostmasterSignal(), BackgroundWorkerArray::slot, success, BackgroundWorkerSlot::terminate, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

Referenced by apw_start_database_worker(), apw_start_leader_worker(), LaunchParallelWorkers(), logicalrep_worker_launch(), setup_background_workers(), and worker_spi_launch().

◆ ReportBackgroundWorkerExit()

void ReportBackgroundWorkerExit ( slist_mutable_iter cur)

Definition at line 486 of file bgworker.c.

487 {
488  RegisteredBgWorker *rw;
489  BackgroundWorkerSlot *slot;
490  int notify_pid;
491 
492  rw = slist_container(RegisteredBgWorker, rw_lnode, cur->cur);
493 
496  slot->pid = rw->rw_pid;
497  notify_pid = rw->rw_worker.bgw_notify_pid;
498 
499  /*
500  * If this worker is slated for deregistration, do that before notifying
501  * the process which started it. Otherwise, if that process tries to
502  * reuse the slot immediately, it might not be available yet. In theory
503  * that could happen anyway if the process checks slot->pid at just the
504  * wrong moment, but this makes the window narrower.
505  */
506  if (rw->rw_terminate ||
509 
510  if (notify_pid != 0)
511  kill(notify_pid, SIGUSR1);
512 }
#define BGW_NEVER_RESTART
Definition: bgworker.h:85

References Assert, BackgroundWorkerData, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, cur, ForgetBackgroundWorker(), kill, max_worker_processes, BackgroundWorkerSlot::pid, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SIGUSR1, slist_container, and BackgroundWorkerArray::slot.

Referenced by CleanupBackgroundWorker().

◆ ReportBackgroundWorkerPID()

◆ ResetBackgroundWorkerCrashTimes()

void ResetBackgroundWorkerCrashTimes ( void  )

Definition at line 585 of file bgworker.c.

586 {
587  slist_mutable_iter iter;
588 
590  {
591  RegisteredBgWorker *rw;
592 
593  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
594 
596  {
597  /*
598  * Workers marked BGW_NEVER_RESTART shouldn't get relaunched after
599  * the crash, so forget about them. (If we wait until after the
600  * crash to forget about them, and they are parallel workers,
601  * parallel_terminate_count will get incremented after we've
602  * already zeroed parallel_register_count, which would be bad.)
603  */
604  ForgetBackgroundWorker(&iter);
605  }
606  else
607  {
608  /*
609  * The accounting which we do via parallel_register_count and
610  * parallel_terminate_count would get messed up if a worker marked
611  * parallel could survive a crash and restart cycle. All such
612  * workers should be marked BGW_NEVER_RESTART, and thus control
613  * should never reach this branch.
614  */
616 
617  /*
618  * Allow this worker to be restarted immediately after we finish
619  * resetting.
620  */
621  rw->rw_crashed_at = 0;
622 
623  /*
624  * If there was anyone waiting for it, they're history.
625  */
626  rw->rw_worker.bgw_notify_pid = 0;
627  }
628  }
629 }

References Assert, BackgroundWorkerList, BackgroundWorker::bgw_flags, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BGWORKER_CLASS_PARALLEL, slist_mutable_iter::cur, ForgetBackgroundWorker(), RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_worker, slist_container, and slist_foreach_modify.

Referenced by PostmasterStateMachine().

◆ SanityCheckBackgroundWorker()

static bool SanityCheckBackgroundWorker ( BackgroundWorker worker,
int  elevel 
)
static

Definition at line 637 of file bgworker.c.

638 {
639  /* sanity check for flags */
640 
641  /*
642  * We used to support workers not connected to shared memory, but don't
643  * anymore. Thus this is a required flag now. We're not removing the flag
644  * for compatibility reasons and because the flag still provides some
645  * signal when reading code.
646  */
647  if (!(worker->bgw_flags & BGWORKER_SHMEM_ACCESS))
648  {
649  ereport(elevel,
650  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
651  errmsg("background worker \"%s\": background workers without shared memory access are not supported",
652  worker->bgw_name)));
653  return false;
654  }
655 
657  {
659  {
660  ereport(elevel,
661  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
662  errmsg("background worker \"%s\": cannot request database access if starting at postmaster start",
663  worker->bgw_name)));
664  return false;
665  }
666 
667  /* XXX other checks? */
668  }
669 
670  if ((worker->bgw_restart_time < 0 &&
671  worker->bgw_restart_time != BGW_NEVER_RESTART) ||
672  (worker->bgw_restart_time > USECS_PER_DAY / 1000))
673  {
674  ereport(elevel,
675  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
676  errmsg("background worker \"%s\": invalid restart interval",
677  worker->bgw_name)));
678  return false;
679  }
680 
681  /*
682  * Parallel workers may not be configured for restart, because the
683  * parallel_register_count/parallel_terminate_count accounting can't
684  * handle parallel workers lasting through a crash-and-restart cycle.
685  */
686  if (worker->bgw_restart_time != BGW_NEVER_RESTART &&
687  (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
688  {
689  ereport(elevel,
690  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
691  errmsg("background worker \"%s\": parallel workers may not be configured for restart",
692  worker->bgw_name)));
693  return false;
694  }
695 
696  /*
697  * If bgw_type is not filled in, use bgw_name.
698  */
699  if (strcmp(worker->bgw_type, "") == 0)
700  strcpy(worker->bgw_type, worker->bgw_name);
701 
702  return true;
703 }
@ BgWorkerStart_PostmasterStart
Definition: bgworker.h:79
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:53
#define USECS_PER_DAY
Definition: timestamp.h:131

References BackgroundWorker::bgw_flags, BackgroundWorker::bgw_name, BGW_NEVER_RESTART, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_CLASS_PARALLEL, BGWORKER_SHMEM_ACCESS, BgWorkerStart_PostmasterStart, ereport, errcode(), errmsg(), and USECS_PER_DAY.

Referenced by RegisterBackgroundWorker(), and RegisterDynamicBackgroundWorker().

◆ TerminateBackgroundWorker()

void TerminateBackgroundWorker ( BackgroundWorkerHandle handle)

Definition at line 1221 of file bgworker.c.

1222 {
1223  BackgroundWorkerSlot *slot;
1224  bool signal_postmaster = false;
1225 
1226  Assert(handle->slot < max_worker_processes);
1227  slot = &BackgroundWorkerData->slot[handle->slot];
1228 
1229  /* Set terminate flag in shared memory, unless slot has been reused. */
1230  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
1231  if (handle->generation == slot->generation)
1232  {
1233  slot->terminate = true;
1234  signal_postmaster = true;
1235  }
1236  LWLockRelease(BackgroundWorkerLock);
1237 
1238  /* Make sure the postmaster notices the change to shared memory. */
1239  if (signal_postmaster)
1241 }

References Assert, BackgroundWorkerData, BackgroundWorkerSlot::generation, BackgroundWorkerHandle::generation, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_worker_processes, PMSIGNAL_BACKGROUND_WORKER_CHANGE, SendPostmasterSignal(), BackgroundWorkerArray::slot, BackgroundWorkerHandle::slot, and BackgroundWorkerSlot::terminate.

Referenced by cleanup_background_workers(), and DestroyParallelContext().

◆ WaitForBackgroundWorkerShutdown()

BgwHandleStatus WaitForBackgroundWorkerShutdown ( BackgroundWorkerHandle handle)

Definition at line 1182 of file bgworker.c.

1183 {
1184  BgwHandleStatus status;
1185  int rc;
1186 
1187  for (;;)
1188  {
1189  pid_t pid;
1190 
1192 
1193  status = GetBackgroundWorkerPid(handle, &pid);
1194  if (status == BGWH_STOPPED)
1195  break;
1196 
1197  rc = WaitLatch(MyLatch,
1199  WAIT_EVENT_BGWORKER_SHUTDOWN);
1200 
1201  if (rc & WL_POSTMASTER_DEATH)
1202  {
1203  status = BGWH_POSTMASTER_DIED;
1204  break;
1205  }
1206 
1208  }
1209 
1210  return status;
1211 }
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1082
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_POSTMASTER_DIED
Definition: bgworker.h:108
struct Latch * MyLatch
Definition: globals.c:60
void ResetLatch(Latch *latch)
Definition: latch.c:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_LATCH_SET
Definition: latch.h:127
#define WL_POSTMASTER_DEATH
Definition: latch.h:131
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122

References BGWH_POSTMASTER_DIED, BGWH_STOPPED, CHECK_FOR_INTERRUPTS, GetBackgroundWorkerPid(), MyLatch, ResetLatch(), WaitLatch(), WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by apw_start_database_worker(), and WaitForParallelWorkersToExit().

◆ WaitForBackgroundWorkerStartup()

BgwHandleStatus WaitForBackgroundWorkerStartup ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1137 of file bgworker.c.

1138 {
1139  BgwHandleStatus status;
1140  int rc;
1141 
1142  for (;;)
1143  {
1144  pid_t pid;
1145 
1147 
1148  status = GetBackgroundWorkerPid(handle, &pid);
1149  if (status == BGWH_STARTED)
1150  *pidp = pid;
1151  if (status != BGWH_NOT_YET_STARTED)
1152  break;
1153 
1154  rc = WaitLatch(MyLatch,
1156  WAIT_EVENT_BGWORKER_STARTUP);
1157 
1158  if (rc & WL_POSTMASTER_DEATH)
1159  {
1160  status = BGWH_POSTMASTER_DIED;
1161  break;
1162  }
1163 
1165  }
1166 
1167  return status;
1168 }

References BGWH_NOT_YET_STARTED, BGWH_POSTMASTER_DIED, BGWH_STARTED, CHECK_FOR_INTERRUPTS, GetBackgroundWorkerPid(), MyLatch, ResetLatch(), WaitLatch(), WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by apw_start_leader_worker(), and worker_spi_launch().

Variable Documentation

◆ BackgroundWorkerData

◆ BackgroundWorkerList

◆ fn_addr

Definition at line 117 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 116 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ 

const { ... } InternalBGWorkers[]
Initial value:
=
{
{
"ParallelWorkerMain", ParallelWorkerMain
},
{
"ApplyLauncherMain", ApplyLauncherMain
},
{
"ApplyWorkerMain", ApplyWorkerMain
},
{
"ParallelApplyWorkerMain", ParallelApplyWorkerMain
},
{
"TablesyncWorkerMain", TablesyncWorkerMain
}
}
void ParallelApplyWorkerMain(Datum main_arg)
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:1271
void ApplyWorkerMain(Datum main_arg)
Definition: worker.c:4685
void ApplyLauncherMain(Datum main_arg)
Definition: launcher.c:1122
void TablesyncWorkerMain(Datum main_arg)
Definition: tablesync.c:1711

Referenced by LookupBackgroundWorkerFunction().