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/interrupt.h"
#include "postmaster/postmaster.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "storage/dsm.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/pg_shmem.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/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 StartBackgroundWorker (void)
 
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

◆ BackgroundWorkerShmemInit()

void BackgroundWorkerShmemInit ( void  )

Definition at line 158 of file bgworker.c.

References Assert, 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 CreateSharedMemoryAndSemaphores().

159 {
160  bool found;
161 
162  BackgroundWorkerData = ShmemInitStruct("Background Worker Data",
164  &found);
165  if (!IsUnderPostmaster)
166  {
167  slist_iter siter;
168  int slotno = 0;
169 
173 
174  /*
175  * Copy contents of worker list into shared memory. Record the shared
176  * memory slot assigned to each worker. This ensures a 1-to-1
177  * correspondence between the postmaster's private list and the array
178  * in shared memory.
179  */
181  {
183  RegisteredBgWorker *rw;
184 
185  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
186  Assert(slotno < max_worker_processes);
187  slot->in_use = true;
188  slot->terminate = false;
189  slot->pid = InvalidPid;
190  slot->generation = 0;
191  rw->rw_shmem_slot = slotno;
192  rw->rw_worker.bgw_notify_pid = 0; /* might be reinit after crash */
193  memcpy(&slot->worker, &rw->rw_worker, sizeof(BackgroundWorker));
194  ++slotno;
195  }
196 
197  /*
198  * Mark any remaining slots as not in use.
199  */
200  while (slotno < max_worker_processes)
201  {
203 
204  slot->in_use = false;
205  ++slotno;
206  }
207  }
208  else
209  Assert(found);
210 }
slist_node * cur
Definition: ilist.h:226
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
Size BackgroundWorkerShmemSize(void)
Definition: bgworker.c:142
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
slist_head BackgroundWorkerList
Definition: bgworker.c:42
uint32 parallel_register_count
Definition: bgworker.c:99
bool IsUnderPostmaster
Definition: globals.c:112
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define Assert(condition)
Definition: c.h:804
BackgroundWorker worker
Definition: bgworker.c:82
#define slist_foreach(iter, lhead)
Definition: ilist.h:719
uint32 parallel_terminate_count
Definition: bgworker.c:100
pid_t bgw_notify_pid
Definition: bgworker.h:100
int max_worker_processes
Definition: globals.c:137
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
#define InvalidPid
Definition: miscadmin.h:32

◆ BackgroundWorkerShmemSize()

Size BackgroundWorkerShmemSize ( void  )

Definition at line 142 of file bgworker.c.

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

Referenced by BackgroundWorkerShmemInit(), and CalculateShmemSize().

143 {
144  Size size;
145 
146  /* Array of workers is variably sized. */
147  size = offsetof(BackgroundWorkerArray, slot);
149  sizeof(BackgroundWorkerSlot)));
150 
151  return size;
152 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
size_t Size
Definition: c.h:540
int max_worker_processes
Definition: globals.c:137
#define offsetof(type, field)
Definition: c.h:727

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)

Definition at line 242 of file bgworker.c.

References ascii_safe_strlcpy(), 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, malloc, max_worker_processes, BackgroundWorkerArray::parallel_terminate_count, pg_memory_barrier, pg_read_barrier, BackgroundWorkerSlot::pid, 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 sigusr1_handler().

243 {
244  int slotno;
245 
246  /*
247  * The total number of slots stored in shared memory should match our
248  * notion of max_worker_processes. If it does not, something is very
249  * wrong. Further down, we always refer to this value as
250  * max_worker_processes, in case shared memory gets corrupted while we're
251  * looping.
252  */
254  {
255  ereport(LOG,
256  (errmsg("inconsistent background worker state (max_worker_processes=%d, total_slots=%d)",
259  return;
260  }
261 
262  /*
263  * Iterate through slots, looking for newly-registered workers or workers
264  * who must die.
265  */
266  for (slotno = 0; slotno < max_worker_processes; ++slotno)
267  {
269  RegisteredBgWorker *rw;
270 
271  if (!slot->in_use)
272  continue;
273 
274  /*
275  * Make sure we don't see the in_use flag before the updated slot
276  * contents.
277  */
278  pg_read_barrier();
279 
280  /* See whether we already know about this worker. */
282  if (rw != NULL)
283  {
284  /*
285  * In general, the worker data can't change after it's initially
286  * registered. However, someone can set the terminate flag.
287  */
288  if (slot->terminate && !rw->rw_terminate)
289  {
290  rw->rw_terminate = true;
291  if (rw->rw_pid != 0)
292  kill(rw->rw_pid, SIGTERM);
293  else
294  {
295  /* Report never-started, now-terminated worker as dead. */
297  }
298  }
299  continue;
300  }
301 
302  /*
303  * If we aren't allowing new workers, then immediately mark it for
304  * termination; the next stanza will take care of cleaning it up.
305  * Doing this ensures that any process waiting for the worker will get
306  * awoken, even though the worker will never be allowed to run.
307  */
308  if (!allow_new_workers)
309  slot->terminate = true;
310 
311  /*
312  * If the worker is marked for termination, we don't need to add it to
313  * the registered workers list; we can just free the slot. However, if
314  * bgw_notify_pid is set, the process that registered the worker may
315  * need to know that we've processed the terminate request, so be sure
316  * to signal it.
317  */
318  if (slot->terminate)
319  {
320  int notify_pid;
321 
322  /*
323  * We need a memory barrier here to make sure that the load of
324  * bgw_notify_pid and the update of parallel_terminate_count
325  * complete before the store to in_use.
326  */
327  notify_pid = slot->worker.bgw_notify_pid;
328  if ((slot->worker.bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
330  slot->pid = 0;
331 
333  slot->in_use = false;
334 
335  if (notify_pid != 0)
336  kill(notify_pid, SIGUSR1);
337 
338  continue;
339  }
340 
341  /*
342  * Copy the registration data into the registered workers list.
343  */
344  rw = malloc(sizeof(RegisteredBgWorker));
345  if (rw == NULL)
346  {
347  ereport(LOG,
348  (errcode(ERRCODE_OUT_OF_MEMORY),
349  errmsg("out of memory")));
350  return;
351  }
352 
353  /*
354  * Copy strings in a paranoid way. If shared memory is corrupted, the
355  * source data might not even be NUL-terminated.
356  */
358  slot->worker.bgw_name, BGW_MAXLEN);
360  slot->worker.bgw_type, BGW_MAXLEN);
365 
366  /*
367  * Copy various fixed-size fields.
368  *
369  * flags, start_time, and restart_time are examined by the postmaster,
370  * but nothing too bad will happen if they are corrupted. The
371  * remaining fields will only be examined by the child process. It
372  * might crash, but we won't.
373  */
374  rw->rw_worker.bgw_flags = slot->worker.bgw_flags;
378  memcpy(rw->rw_worker.bgw_extra, slot->worker.bgw_extra, BGW_EXTRALEN);
379 
380  /*
381  * Copy the PID to be notified about state changes, but only if the
382  * postmaster knows about a backend with that PID. It isn't an error
383  * if the postmaster doesn't know about the PID, because the backend
384  * that requested the worker could have died (or been killed) just
385  * after doing so. Nonetheless, at least until we get some experience
386  * with how this plays out in the wild, log a message at a relative
387  * high debug level.
388  */
391  {
392  elog(DEBUG1, "worker notification PID %ld is not valid",
393  (long) rw->rw_worker.bgw_notify_pid);
394  rw->rw_worker.bgw_notify_pid = 0;
395  }
396 
397  /* Initialize postmaster bookkeeping. */
398  rw->rw_backend = NULL;
399  rw->rw_pid = 0;
400  rw->rw_child_slot = 0;
401  rw->rw_crashed_at = 0;
402  rw->rw_shmem_slot = slotno;
403  rw->rw_terminate = false;
404 
405  /* Log it! */
406  ereport(DEBUG1,
407  (errmsg_internal("registering background worker \"%s\"",
408  rw->rw_worker.bgw_name)));
409 
411  }
412 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:99
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
#define SIGUSR1
Definition: win32_port.h:171
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:593
int bgw_restart_time
Definition: bgworker.h:95
int errcode(int sqlerrcode)
Definition: elog.c:698
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
#define kill(pid, sig)
Definition: win32_port.h:454
void ascii_safe_strlcpy(char *dest, const char *src, size_t destsiz)
Definition: ascii.c:173
#define LOG
Definition: elog.h:26
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:97
#define malloc(a)
Definition: header.h:50
Datum bgw_main_arg
Definition: bgworker.h:98
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
bool PostmasterMarkPIDForWorkerNotify(int pid)
Definition: postmaster.c:6135
slist_head BackgroundWorkerList
Definition: bgworker.c:42
static RegisteredBgWorker * FindRegisteredWorkerBySlotNumber(int slotno)
Definition: bgworker.c:217
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define pg_memory_barrier()
Definition: atomics.h:145
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
BackgroundWorker worker
Definition: bgworker.c:82
#define pg_read_barrier()
Definition: atomics.h:158
#define BGW_MAXLEN
Definition: bgworker.h:86
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
int errmsg(const char *fmt,...)
Definition: elog.c:909
uint32 parallel_terminate_count
Definition: bgworker.c:100
pid_t bgw_notify_pid
Definition: bgworker.h:100
#define elog(elevel,...)
Definition: elog.h:232
int max_worker_processes
Definition: globals.c:137
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:96
#define BGW_EXTRALEN
Definition: bgworker.h:87

◆ BackgroundWorkerStopNotifications()

void BackgroundWorkerStopNotifications ( pid_t  pid)

Definition at line 514 of file bgworker.c.

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

Referenced by CleanupBackend(), and CleanupBackgroundWorker().

515 {
516  slist_iter siter;
517 
519  {
520  RegisteredBgWorker *rw;
521 
522  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
523  if (rw->rw_worker.bgw_notify_pid == pid)
524  rw->rw_worker.bgw_notify_pid = 0;
525  }
526 }
slist_node * cur
Definition: ilist.h:226
slist_head BackgroundWorkerList
Definition: bgworker.c:42
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define slist_foreach(iter, lhead)
Definition: ilist.h:719
pid_t bgw_notify_pid
Definition: bgworker.h:100
BackgroundWorker rw_worker

◆ bgworker_die()

static void bgworker_die ( SIGNAL_ARGS  )
static

Definition at line 724 of file bgworker.c.

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

Referenced by StartBackgroundWorker().

725 {
727 
728  ereport(FATAL,
729  (errcode(ERRCODE_ADMIN_SHUTDOWN),
730  errmsg("terminating background worker \"%s\" due to administrator command",
732 }
int errcode(int sqlerrcode)
Definition: elog.c:698
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define FATAL
Definition: elog.h:49
sigset_t BlockSig
Definition: pqsignal.c:22
#define ereport(elevel,...)
Definition: elog.h:157
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ FindRegisteredWorkerBySlotNumber()

static RegisteredBgWorker* FindRegisteredWorkerBySlotNumber ( int  slotno)
static

Definition at line 217 of file bgworker.c.

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

Referenced by BackgroundWorkerStateChange().

218 {
219  slist_iter siter;
220 
222  {
223  RegisteredBgWorker *rw;
224 
225  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
226  if (rw->rw_shmem_slot == slotno)
227  return rw;
228  }
229 
230  return NULL;
231 }
slist_node * cur
Definition: ilist.h:226
slist_head BackgroundWorkerList
Definition: bgworker.c:42
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define slist_foreach(iter, lhead)
Definition: ilist.h:719

◆ ForgetBackgroundWorker()

void ForgetBackgroundWorker ( slist_mutable_iter cur)

Definition at line 426 of file bgworker.c.

References Assert, BackgroundWorker::bgw_flags, BackgroundWorker::bgw_name, BGWORKER_CLASS_PARALLEL, slist_mutable_iter::cur, DEBUG1, ereport, errmsg_internal(), free, BackgroundWorkerSlot::in_use, max_worker_processes, BackgroundWorkerArray::parallel_terminate_count, 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().

427 {
428  RegisteredBgWorker *rw;
429  BackgroundWorkerSlot *slot;
430 
431  rw = slist_container(RegisteredBgWorker, rw_lnode, cur->cur);
432 
435  Assert(slot->in_use);
436 
437  /*
438  * We need a memory barrier here to make sure that the update of
439  * parallel_terminate_count completes before the store to in_use.
440  */
443 
445  slot->in_use = false;
446 
447  ereport(DEBUG1,
448  (errmsg_internal("unregistering background worker \"%s\"",
449  rw->rw_worker.bgw_name)));
450 
452  free(rw);
453 }
#define DEBUG1
Definition: elog.h:25
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
slist_node * cur
Definition: ilist.h:241
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define ereport(elevel,...)
Definition: elog.h:157
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define pg_memory_barrier()
Definition: atomics.h:145
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
#define Assert(condition)
Definition: c.h:804
uint32 parallel_terminate_count
Definition: bgworker.c:100
int max_worker_processes
Definition: globals.c:137
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:671
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ ForgetUnstartedBackgroundWorkers()

void ForgetUnstartedBackgroundWorkers ( void  )

Definition at line 541 of file bgworker.c.

References Assert, 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().

542 {
543  slist_mutable_iter iter;
544 
546  {
547  RegisteredBgWorker *rw;
548  BackgroundWorkerSlot *slot;
549 
550  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
553 
554  /* If it's not yet started, and there's someone waiting ... */
555  if (slot->pid == InvalidPid &&
556  rw->rw_worker.bgw_notify_pid != 0)
557  {
558  /* ... then zap it, and notify the waiter */
559  int notify_pid = rw->rw_worker.bgw_notify_pid;
560 
561  ForgetBackgroundWorker(&iter);
562  if (notify_pid != 0)
563  kill(notify_pid, SIGUSR1);
564  }
565  }
566 }
#define SIGUSR1
Definition: win32_port.h:171
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
slist_node * cur
Definition: ilist.h:241
#define kill(pid, sig)
Definition: win32_port.h:454
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:735
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:426
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define Assert(condition)
Definition: c.h:804
pid_t bgw_notify_pid
Definition: bgworker.h:100
int max_worker_processes
Definition: globals.c:137
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
#define InvalidPid
Definition: miscadmin.h:32

◆ GetBackgroundWorkerPid()

BgwHandleStatus GetBackgroundWorkerPid ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1068 of file bgworker.c.

References Assert, 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().

1069 {
1070  BackgroundWorkerSlot *slot;
1071  pid_t pid;
1072 
1073  Assert(handle->slot < max_worker_processes);
1074  slot = &BackgroundWorkerData->slot[handle->slot];
1075 
1076  /*
1077  * We could probably arrange to synchronize access to data using memory
1078  * barriers only, but for now, let's just keep it simple and grab the
1079  * lock. It seems unlikely that there will be enough traffic here to
1080  * result in meaningful contention.
1081  */
1082  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1083 
1084  /*
1085  * The generation number can't be concurrently changed while we hold the
1086  * lock. The pid, which is updated by the postmaster, can change at any
1087  * time, but we assume such changes are atomic. So the value we read
1088  * won't be garbage, but it might be out of date by the time the caller
1089  * examines it (but that's unavoidable anyway).
1090  *
1091  * The in_use flag could be in the process of changing from true to false,
1092  * but if it is already false then it can't change further.
1093  */
1094  if (handle->generation != slot->generation || !slot->in_use)
1095  pid = 0;
1096  else
1097  pid = slot->pid;
1098 
1099  /* All done. */
1100  LWLockRelease(BackgroundWorkerLock);
1101 
1102  if (pid == 0)
1103  return BGWH_STOPPED;
1104  else if (pid == InvalidPid)
1105  return BGWH_NOT_YET_STARTED;
1106  *pidp = pid;
1107  return BGWH_STARTED;
1108 }
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int max_worker_processes
Definition: globals.c:137
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
#define InvalidPid
Definition: miscadmin.h:32

◆ GetBackgroundWorkerTypeByPid()

const char* GetBackgroundWorkerTypeByPid ( pid_t  pid)

Definition at line 1282 of file bgworker.c.

References 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().

1283 {
1284  int slotno;
1285  bool found = false;
1286  static char result[BGW_MAXLEN];
1287 
1288  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1289 
1290  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; slotno++)
1291  {
1293 
1294  if (slot->pid > 0 && slot->pid == pid)
1295  {
1296  strcpy(result, slot->worker.bgw_type);
1297  found = true;
1298  break;
1299  }
1300  }
1301 
1302  LWLockRelease(BackgroundWorkerLock);
1303 
1304  if (!found)
1305  return NULL;
1306 
1307  return result;
1308 }
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
BackgroundWorker worker
Definition: bgworker.c:82
#define BGW_MAXLEN
Definition: bgworker.h:86
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ LookupBackgroundWorkerFunction()

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

Definition at line 1248 of file bgworker.c.

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

Referenced by StartBackgroundWorker().

1249 {
1250  /*
1251  * If the function is to be loaded from postgres itself, search the
1252  * InternalBGWorkers array.
1253  */
1254  if (strcmp(libraryname, "postgres") == 0)
1255  {
1256  int i;
1257 
1258  for (i = 0; i < lengthof(InternalBGWorkers); i++)
1259  {
1260  if (strcmp(InternalBGWorkers[i].fn_name, funcname) == 0)
1261  return InternalBGWorkers[i].fn_addr;
1262  }
1263 
1264  /* We can only reach this by programming error. */
1265  elog(ERROR, "internal function \"%s\" not found", funcname);
1266  }
1267 
1268  /* Otherwise load from external library. */
1269  return (bgworker_main_type)
1270  load_external_function(libraryname, funcname, true, NULL);
1271 }
#define lengthof(array)
Definition: c.h:734
const char * fn_name
Definition: bgworker.c:118
#define ERROR
Definition: elog.h:46
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:107
static const struct @15 InternalBGWorkers[]
bgworker_main_type fn_addr
Definition: bgworker.c:119
#define elog(elevel,...)
Definition: elog.h:232
int i
void(* bgworker_main_type)(Datum main_arg)
Definition: bgworker.h:72

◆ RegisterBackgroundWorker()

void RegisterBackgroundWorker ( BackgroundWorker worker)

Definition at line 872 of file bgworker.c.

References BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, DEBUG1, ereport, errcode(), errdetail_plural(), errhint(), errmsg(), errmsg_internal(), IsUnderPostmaster, LOG, malloc, max_worker_processes, 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(), slist_push_head(), and BackgroundWorkerSlot::worker.

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

873 {
874  RegisteredBgWorker *rw;
875  static int numworkers = 0;
876 
877  if (!IsUnderPostmaster)
878  ereport(DEBUG1,
879  (errmsg_internal("registering background worker \"%s\"", worker->bgw_name)));
880 
882  strcmp(worker->bgw_library_name, "postgres") != 0)
883  {
884  if (!IsUnderPostmaster)
885  ereport(LOG,
886  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
887  errmsg("background worker \"%s\": must be registered in shared_preload_libraries",
888  worker->bgw_name)));
889  return;
890  }
891 
892  if (!SanityCheckBackgroundWorker(worker, LOG))
893  return;
894 
895  if (worker->bgw_notify_pid != 0)
896  {
897  ereport(LOG,
898  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
899  errmsg("background worker \"%s\": only dynamic background workers can request notification",
900  worker->bgw_name)));
901  return;
902  }
903 
904  /*
905  * Enforce maximum number of workers. Note this is overly restrictive: we
906  * could allow more non-shmem-connected workers, because these don't count
907  * towards the MAX_BACKENDS limit elsewhere. For now, it doesn't seem
908  * important to relax this restriction.
909  */
910  if (++numworkers > max_worker_processes)
911  {
912  ereport(LOG,
913  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
914  errmsg("too many background workers"),
915  errdetail_plural("Up to %d background worker can be registered with the current settings.",
916  "Up to %d background workers can be registered with the current settings.",
919  errhint("Consider increasing the configuration parameter \"max_worker_processes\".")));
920  return;
921  }
922 
923  /*
924  * Copy the registration data into the registered workers list.
925  */
926  rw = malloc(sizeof(RegisteredBgWorker));
927  if (rw == NULL)
928  {
929  ereport(LOG,
930  (errcode(ERRCODE_OUT_OF_MEMORY),
931  errmsg("out of memory")));
932  return;
933  }
934 
935  rw->rw_worker = *worker;
936  rw->rw_backend = NULL;
937  rw->rw_pid = 0;
938  rw->rw_child_slot = 0;
939  rw->rw_crashed_at = 0;
940  rw->rw_terminate = false;
941 
943 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1156
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1615
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:593
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG
Definition: elog.h:26
#define malloc(a)
Definition: header.h:50
slist_head BackgroundWorkerList
Definition: bgworker.c:42
bool IsUnderPostmaster
Definition: globals.c:112
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition: bgworker.c:652
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1134
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t bgw_notify_pid
Definition: bgworker.h:100
int max_worker_processes
Definition: globals.c:137
BackgroundWorker rw_worker
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:96

◆ RegisterDynamicBackgroundWorker()

bool RegisterDynamicBackgroundWorker ( BackgroundWorker worker,
BackgroundWorkerHandle **  handle 
)

Definition at line 956 of file bgworker.c.

References Assert, 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().

958 {
959  int slotno;
960  bool success = false;
961  bool parallel;
962  uint64 generation = 0;
963 
964  /*
965  * We can't register dynamic background workers from the postmaster. If
966  * this is a standalone backend, we're the only process and can't start
967  * any more. In a multi-process environment, it might be theoretically
968  * possible, but we don't currently support it due to locking
969  * considerations; see comments on the BackgroundWorkerSlot data
970  * structure.
971  */
972  if (!IsUnderPostmaster)
973  return false;
974 
975  if (!SanityCheckBackgroundWorker(worker, ERROR))
976  return false;
977 
978  parallel = (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0;
979 
980  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
981 
982  /*
983  * If this is a parallel worker, check whether there are already too many
984  * parallel workers; if so, don't register another one. Our view of
985  * parallel_terminate_count may be slightly stale, but that doesn't really
986  * matter: we would have gotten the same result if we'd arrived here
987  * slightly earlier anyway. There's no help for it, either, since the
988  * postmaster must not take locks; a memory barrier wouldn't guarantee
989  * anything useful.
990  */
994  {
998  LWLockRelease(BackgroundWorkerLock);
999  return false;
1000  }
1001 
1002  /*
1003  * Look for an unused slot. If we find one, grab it.
1004  */
1005  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; ++slotno)
1006  {
1008 
1009  if (!slot->in_use)
1010  {
1011  memcpy(&slot->worker, worker, sizeof(BackgroundWorker));
1012  slot->pid = InvalidPid; /* indicates not started yet */
1013  slot->generation++;
1014  slot->terminate = false;
1015  generation = slot->generation;
1016  if (parallel)
1018 
1019  /*
1020  * Make sure postmaster doesn't see the slot as in use before it
1021  * sees the new contents.
1022  */
1023  pg_write_barrier();
1024 
1025  slot->in_use = true;
1026  success = true;
1027  break;
1028  }
1029  }
1030 
1031  LWLockRelease(BackgroundWorkerLock);
1032 
1033  /* If we found a slot, tell the postmaster to notice the change. */
1034  if (success)
1036 
1037  /*
1038  * If we found a slot and the user has provided a handle, initialize it.
1039  */
1040  if (success && handle)
1041  {
1042  *handle = palloc(sizeof(BackgroundWorkerHandle));
1043  (*handle)->slot = slotno;
1044  (*handle)->generation = generation;
1045  }
1046 
1047  return success;
1048 }
int max_parallel_workers
Definition: globals.c:138
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define ERROR
Definition: elog.h:46
uint32 parallel_register_count
Definition: bgworker.c:99
bool IsUnderPostmaster
Definition: globals.c:112
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition: bgworker.c:652
#define Assert(condition)
Definition: c.h:804
BackgroundWorker worker
Definition: bgworker.c:82
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void * palloc(Size size)
Definition: mcxt.c:1062
uint32 parallel_terminate_count
Definition: bgworker.c:100
#define pg_write_barrier()
Definition: atomics.h:159
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:153
#define MAX_PARALLEL_WORKER_LIMIT
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
static bool success
Definition: initdb.c:165
#define InvalidPid
Definition: miscadmin.h:32

◆ ReportBackgroundWorkerExit()

void ReportBackgroundWorkerExit ( slist_mutable_iter cur)

Definition at line 480 of file bgworker.c.

References Assert, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, slist_mutable_iter::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().

481 {
482  RegisteredBgWorker *rw;
483  BackgroundWorkerSlot *slot;
484  int notify_pid;
485 
486  rw = slist_container(RegisteredBgWorker, rw_lnode, cur->cur);
487 
490  slot->pid = rw->rw_pid;
491  notify_pid = rw->rw_worker.bgw_notify_pid;
492 
493  /*
494  * If this worker is slated for deregistration, do that before notifying
495  * the process which started it. Otherwise, if that process tries to
496  * reuse the slot immediately, it might not be available yet. In theory
497  * that could happen anyway if the process checks slot->pid at just the
498  * wrong moment, but this makes the window narrower.
499  */
500  if (rw->rw_terminate ||
503 
504  if (notify_pid != 0)
505  kill(notify_pid, SIGUSR1);
506 }
#define SIGUSR1
Definition: win32_port.h:171
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:95
#define kill(pid, sig)
Definition: win32_port.h:454
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:426
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define Assert(condition)
Definition: c.h:804
pid_t bgw_notify_pid
Definition: bgworker.h:100
int max_worker_processes
Definition: globals.c:137
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ ReportBackgroundWorkerPID()

void ReportBackgroundWorkerPID ( RegisteredBgWorker rw)

Definition at line 461 of file bgworker.c.

References Assert, BackgroundWorker::bgw_notify_pid, kill, max_worker_processes, BackgroundWorkerSlot::pid, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, SIGUSR1, and BackgroundWorkerArray::slot.

Referenced by BackgroundWorkerStateChange(), and do_start_bgworker().

462 {
463  BackgroundWorkerSlot *slot;
464 
467  slot->pid = rw->rw_pid;
468 
469  if (rw->rw_worker.bgw_notify_pid != 0)
471 }
#define SIGUSR1
Definition: win32_port.h:171
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
#define kill(pid, sig)
Definition: win32_port.h:454
#define Assert(condition)
Definition: c.h:804
pid_t bgw_notify_pid
Definition: bgworker.h:100
int max_worker_processes
Definition: globals.c:137
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ ResetBackgroundWorkerCrashTimes()

void ResetBackgroundWorkerCrashTimes ( void  )

Definition at line 579 of file bgworker.c.

References Assert, BackgroundWorker::bgw_flags, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BGWORKER_CLASS_PARALLEL, slist_mutable_iter::cur, ForgetBackgroundWorker(), BackgroundWorkerSlot::in_use, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_worker, slist_container, slist_foreach_modify, BackgroundWorkerArray::slot, and BackgroundWorkerSlot::worker.

Referenced by PostmasterStateMachine().

580 {
581  slist_mutable_iter iter;
582 
584  {
585  RegisteredBgWorker *rw;
586 
587  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
588 
590  {
591  /*
592  * Workers marked BGW_NEVER_RESTART shouldn't get relaunched after
593  * the crash, so forget about them. (If we wait until after the
594  * crash to forget about them, and they are parallel workers,
595  * parallel_terminate_count will get incremented after we've
596  * already zeroed parallel_register_count, which would be bad.)
597  */
598  ForgetBackgroundWorker(&iter);
599  }
600  else
601  {
602  /*
603  * The accounting which we do via parallel_register_count and
604  * parallel_terminate_count would get messed up if a worker marked
605  * parallel could survive a crash and restart cycle. All such
606  * workers should be marked BGW_NEVER_RESTART, and thus control
607  * should never reach this branch.
608  */
610 
611  /*
612  * Allow this worker to be restarted immediately after we finish
613  * resetting.
614  */
615  rw->rw_crashed_at = 0;
616 
617  /*
618  * If there was anyone waiting for it, they're history.
619  */
620  rw->rw_worker.bgw_notify_pid = 0;
621  }
622  }
623 }
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:95
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:735
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:426
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
#define Assert(condition)
Definition: c.h:804
pid_t bgw_notify_pid
Definition: bgworker.h:100
BackgroundWorker rw_worker

◆ SanityCheckBackgroundWorker()

static bool SanityCheckBackgroundWorker ( BackgroundWorker worker,
int  elevel 
)
static

Definition at line 652 of file bgworker.c.

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().

653 {
654  /* sanity check for flags */
655 
656  /*
657  * We used to support workers not connected to shared memory, but don't
658  * anymore. Thus this is a required flag now. We're not removing the flag
659  * for compatibility reasons and because the flag still provides some
660  * signal when reading code.
661  */
662  if (!(worker->bgw_flags & BGWORKER_SHMEM_ACCESS))
663  {
664  ereport(elevel,
665  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
666  errmsg("background worker \"%s\": background worker without shared memory access are not supported",
667  worker->bgw_name)));
668  return false;
669  }
670 
672  {
674  {
675  ereport(elevel,
676  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
677  errmsg("background worker \"%s\": cannot request database access if starting at postmaster start",
678  worker->bgw_name)));
679  return false;
680  }
681 
682  /* XXX other checks? */
683  }
684 
685  if ((worker->bgw_restart_time < 0 &&
686  worker->bgw_restart_time != BGW_NEVER_RESTART) ||
687  (worker->bgw_restart_time > USECS_PER_DAY / 1000))
688  {
689  ereport(elevel,
690  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
691  errmsg("background worker \"%s\": invalid restart interval",
692  worker->bgw_name)));
693  return false;
694  }
695 
696  /*
697  * Parallel workers may not be configured for restart, because the
698  * parallel_register_count/parallel_terminate_count accounting can't
699  * handle parallel workers lasting through a crash-and-restart cycle.
700  */
701  if (worker->bgw_restart_time != BGW_NEVER_RESTART &&
702  (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
703  {
704  ereport(elevel,
705  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
706  errmsg("background worker \"%s\": parallel workers may not be configured for restart",
707  worker->bgw_name)));
708  return false;
709  }
710 
711  /*
712  * If bgw_type is not filled in, use bgw_name.
713  */
714  if (strcmp(worker->bgw_type, "") == 0)
715  strcpy(worker->bgw_type, worker->bgw_name);
716 
717  return true;
718 }
int bgw_restart_time
Definition: bgworker.h:95
int errcode(int sqlerrcode)
Definition: elog.c:698
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:68
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:53
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define USECS_PER_DAY
Definition: timestamp.h:91
static int elevel
Definition: vacuumlazy.c:401
#define ereport(elevel,...)
Definition: elog.h:157
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ StartBackgroundWorker()

void StartBackgroundWorker ( void  )

Definition at line 741 of file bgworker.c.

References 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, IsBackgroundWorker, LookupBackgroundWorkerFunction(), MyBackendType, MyBgworkerEntry, PG_exception_stack, pg_usleep(), PostAuthDelay, pqsignal(), proc_exit(), procsignal_sigusr1_handler(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), and BackgroundWorkerSlot::worker.

Referenced by BackendRun(), and do_start_bgworker().

742 {
743  sigjmp_buf local_sigjmp_buf;
745  bgworker_main_type entrypt;
746 
747  if (worker == NULL)
748  elog(FATAL, "unable to find bgworker entry");
749 
750  IsBackgroundWorker = true;
751 
753  init_ps_display(worker->bgw_name);
754 
756 
757  /* Apply PostAuthDelay */
758  if (PostAuthDelay > 0)
759  pg_usleep(PostAuthDelay * 1000000L);
760 
761  /*
762  * Set up signal handlers.
763  */
765  {
766  /*
767  * SIGINT is used to signal canceling the current action
768  */
772 
773  /* XXX Any other handlers needed here? */
774  }
775  else
776  {
777  pqsignal(SIGINT, SIG_IGN);
779  pqsignal(SIGFPE, SIG_IGN);
780  }
781  pqsignal(SIGTERM, bgworker_die);
782  /* SIGQUIT handler was already set up by InitPostmasterChild */
784 
785  InitializeTimeouts(); /* establishes SIGALRM handler */
786 
790 
791  /*
792  * If an exception is encountered, processing resumes here.
793  *
794  * We just need to clean up, report the error, and go away.
795  */
796  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
797  {
798  /* Since not using PG_TRY, must reset error stack by hand */
799  error_context_stack = NULL;
800 
801  /* Prevent interrupts while cleaning up */
802  HOLD_INTERRUPTS();
803 
804  /*
805  * sigsetjmp will have blocked all signals, but we may need to accept
806  * signals while communicating with our parallel leader. Once we've
807  * done HOLD_INTERRUPTS() it should be safe to unblock signals.
808  */
810 
811  /* Report the error to the parallel leader and the server log */
812  EmitErrorReport();
813 
814  /*
815  * Do we need more cleanup here? For shmem-connected bgworkers, we
816  * will call InitProcess below, which will install ProcKill as exit
817  * callback. That will take care of releasing locks, etc.
818  */
819 
820  /* and go away */
821  proc_exit(1);
822  }
823 
824  /* We can now handle ereport(ERROR) */
825  PG_exception_stack = &local_sigjmp_buf;
826 
827  /*
828  * Create a per-backend PGPROC struct in shared memory, except in the
829  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must
830  * do this before we can use LWLocks (and in the EXEC_BACKEND case we
831  * already had to do some stuff with LWLocks).
832  */
833 #ifndef EXEC_BACKEND
834  InitProcess();
835 #endif
836 
837  /*
838  * Early initialization.
839  */
840  BaseInit();
841 
842  /*
843  * Look up the entry point function, loading its library if necessary.
844  */
846  worker->bgw_function_name);
847 
848  /*
849  * Note that in normal processes, we would call InitPostgres here. For a
850  * worker, however, we don't know what database to connect to, yet; so we
851  * need to wait until the user code does it via
852  * BackgroundWorkerInitializeConnection().
853  */
854 
855  /*
856  * Now invoke the user-defined worker code
857  */
858  entrypt(worker->bgw_main_arg);
859 
860  /* ... and if it returns, we're done */
861  proc_exit(0);
862 }
void InitializeTimeouts(void)
Definition: timeout.c:435
#define SIGUSR1
Definition: win32_port.h:171
BackendType MyBackendType
Definition: miscinit.c:62
#define SIGCHLD
Definition: win32_port.h:169
void proc_exit(int code)
Definition: ipc.c:104
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
void BaseInit(void)
Definition: postinit.c:511
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:97
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2949
bool IsBackgroundWorker
Definition: globals.c:114
ErrorContextCallback * error_context_stack
Definition: elog.c:93
void pg_usleep(long microsec)
Definition: signal.c:53
Datum bgw_main_arg
Definition: bgworker.h:98
#define FATAL
Definition: elog.h:49
void InitProcess(void)
Definition: proc.c:303
#define SIGHUP
Definition: win32_port.h:159
static bgworker_main_type LookupBackgroundWorkerFunction(const char *libraryname, const char *funcname)
Definition: bgworker.c:1248
#define SIG_IGN
Definition: win32_port.h:156
int PostAuthDelay
Definition: postgres.c:103
void EmitErrorReport(void)
Definition: elog.c:1509
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define SIG_DFL
Definition: win32_port.h:154
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define elog(elevel,...)
Definition: elog.h:232
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2970
static void bgworker_die(SIGNAL_ARGS)
Definition: bgworker.c:724
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:96
void(* bgworker_main_type)(Datum main_arg)
Definition: bgworker.h:72
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5781

◆ TerminateBackgroundWorker()

void TerminateBackgroundWorker ( BackgroundWorkerHandle handle)

Definition at line 1207 of file bgworker.c.

References Assert, 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().

1208 {
1209  BackgroundWorkerSlot *slot;
1210  bool signal_postmaster = false;
1211 
1212  Assert(handle->slot < max_worker_processes);
1213  slot = &BackgroundWorkerData->slot[handle->slot];
1214 
1215  /* Set terminate flag in shared memory, unless slot has been reused. */
1216  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
1217  if (handle->generation == slot->generation)
1218  {
1219  slot->terminate = true;
1220  signal_postmaster = true;
1221  }
1222  LWLockRelease(BackgroundWorkerLock);
1223 
1224  /* Make sure the postmaster notices the change to shared memory. */
1225  if (signal_postmaster)
1227 }
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int max_worker_processes
Definition: globals.c:137
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:153
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ WaitForBackgroundWorkerShutdown()

BgwHandleStatus WaitForBackgroundWorkerShutdown ( BackgroundWorkerHandle handle)

Definition at line 1168 of file bgworker.c.

References BGWH_POSTMASTER_DIED, BGWH_STOPPED, CHECK_FOR_INTERRUPTS, GetBackgroundWorkerPid(), MyLatch, BackgroundWorkerSlot::pid, ResetLatch(), status(), WAIT_EVENT_BGWORKER_SHUTDOWN, WaitLatch(), WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by apw_start_database_worker(), and WaitForParallelWorkersToExit().

1169 {
1171  int rc;
1172 
1173  for (;;)
1174  {
1175  pid_t pid;
1176 
1178 
1179  status = GetBackgroundWorkerPid(handle, &pid);
1180  if (status == BGWH_STOPPED)
1181  break;
1182 
1183  rc = WaitLatch(MyLatch,
1186 
1187  if (rc & WL_POSTMASTER_DEATH)
1188  {
1189  status = BGWH_POSTMASTER_DIED;
1190  break;
1191  }
1192 
1194  }
1195 
1196  return status;
1197 }
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
BgwHandleStatus
Definition: bgworker.h:103
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:125
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1068

◆ WaitForBackgroundWorkerStartup()

BgwHandleStatus WaitForBackgroundWorkerStartup ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1123 of file bgworker.c.

References BGWH_NOT_YET_STARTED, BGWH_POSTMASTER_DIED, BGWH_STARTED, CHECK_FOR_INTERRUPTS, GetBackgroundWorkerPid(), MyLatch, BackgroundWorkerSlot::pid, ResetLatch(), status(), WAIT_EVENT_BGWORKER_STARTUP, WaitLatch(), WL_LATCH_SET, and WL_POSTMASTER_DEATH.

Referenced by apw_start_leader_worker(), and worker_spi_launch().

1124 {
1126  int rc;
1127 
1128  for (;;)
1129  {
1130  pid_t pid;
1131 
1133 
1134  status = GetBackgroundWorkerPid(handle, &pid);
1135  if (status == BGWH_STARTED)
1136  *pidp = pid;
1137  if (status != BGWH_NOT_YET_STARTED)
1138  break;
1139 
1140  rc = WaitLatch(MyLatch,
1143 
1144  if (rc & WL_POSTMASTER_DEATH)
1145  {
1146  status = BGWH_POSTMASTER_DIED;
1147  break;
1148  }
1149 
1151  }
1152 
1153  return status;
1154 }
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
BgwHandleStatus
Definition: bgworker.h:103
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:125
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1068

Variable Documentation

◆ BackgroundWorkerData

BackgroundWorkerArray* BackgroundWorkerData
static

Definition at line 110 of file bgworker.c.

◆ BackgroundWorkerList

slist_head BackgroundWorkerList = SLIST_STATIC_INIT(BackgroundWorkerList)

◆ fn_addr

Definition at line 119 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 118 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ InternalBGWorkers

const { ... } InternalBGWorkers[]
Initial value:
=
{
{
"ParallelWorkerMain", ParallelWorkerMain
},
{
"ApplyLauncherMain", ApplyLauncherMain
},
{
"ApplyWorkerMain", ApplyWorkerMain
}
}
void ApplyLauncherMain(Datum main_arg)
Definition: launcher.c:802
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:1251
void ApplyWorkerMain(Datum main_arg)
Definition: worker.c:3329

Referenced by LookupBackgroundWorkerFunction().