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 (void)
 
void ForgetBackgroundWorker (slist_mutable_iter *cur)
 
void ReportBackgroundWorkerPID (RegisteredBgWorker *rw)
 
void ReportBackgroundWorkerExit (slist_mutable_iter *cur)
 
void BackgroundWorkerStopNotifications (pid_t pid)
 
void ResetBackgroundWorkerCrashTimes (void)
 
static bool SanityCheckBackgroundWorker (BackgroundWorker *worker, int elevel)
 
static void bgworker_die (SIGNAL_ARGS)
 
static void bgworker_sigusr1_handler (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:392
slist_head BackgroundWorkerList
Definition: bgworker.c:42
uint32 parallel_register_count
Definition: bgworker.c:99
bool IsUnderPostmaster
Definition: globals.c:109
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define Assert(condition)
Definition: c.h:800
BackgroundWorker worker
Definition: bgworker.c:82
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
uint32 parallel_terminate_count
Definition: bgworker.c:100
pid_t bgw_notify_pid
Definition: bgworker.h:99
int max_worker_processes
Definition: globals.c:134
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 CreateSharedMemoryAndSemaphores().

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:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:528
int max_worker_processes
Definition: globals.c:134
#define offsetof(type, field)
Definition: c.h:723

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( void  )

Definition at line 240 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(), 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().

241 {
242  int slotno;
243 
244  /*
245  * The total number of slots stored in shared memory should match our
246  * notion of max_worker_processes. If it does not, something is very
247  * wrong. Further down, we always refer to this value as
248  * max_worker_processes, in case shared memory gets corrupted while we're
249  * looping.
250  */
252  {
253  elog(LOG,
254  "inconsistent background worker state (max_worker_processes=%d, total_slots=%d",
257  return;
258  }
259 
260  /*
261  * Iterate through slots, looking for newly-registered workers or workers
262  * who must die.
263  */
264  for (slotno = 0; slotno < max_worker_processes; ++slotno)
265  {
267  RegisteredBgWorker *rw;
268 
269  if (!slot->in_use)
270  continue;
271 
272  /*
273  * Make sure we don't see the in_use flag before the updated slot
274  * contents.
275  */
276  pg_read_barrier();
277 
278  /* See whether we already know about this worker. */
280  if (rw != NULL)
281  {
282  /*
283  * In general, the worker data can't change after it's initially
284  * registered. However, someone can set the terminate flag.
285  */
286  if (slot->terminate && !rw->rw_terminate)
287  {
288  rw->rw_terminate = true;
289  if (rw->rw_pid != 0)
290  kill(rw->rw_pid, SIGTERM);
291  else
292  {
293  /* Report never-started, now-terminated worker as dead. */
295  }
296  }
297  continue;
298  }
299 
300  /*
301  * If the worker is marked for termination, we don't need to add it to
302  * the registered workers list; we can just free the slot. However, if
303  * bgw_notify_pid is set, the process that registered the worker may
304  * need to know that we've processed the terminate request, so be sure
305  * to signal it.
306  */
307  if (slot->terminate)
308  {
309  int notify_pid;
310 
311  /*
312  * We need a memory barrier here to make sure that the load of
313  * bgw_notify_pid and the update of parallel_terminate_count
314  * complete before the store to in_use.
315  */
316  notify_pid = slot->worker.bgw_notify_pid;
317  if ((slot->worker.bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
320  slot->pid = 0;
321  slot->in_use = false;
322  if (notify_pid != 0)
323  kill(notify_pid, SIGUSR1);
324 
325  continue;
326  }
327 
328  /*
329  * Copy the registration data into the registered workers list.
330  */
331  rw = malloc(sizeof(RegisteredBgWorker));
332  if (rw == NULL)
333  {
334  ereport(LOG,
335  (errcode(ERRCODE_OUT_OF_MEMORY),
336  errmsg("out of memory")));
337  return;
338  }
339 
340  /*
341  * Copy strings in a paranoid way. If shared memory is corrupted, the
342  * source data might not even be NUL-terminated.
343  */
345  slot->worker.bgw_name, BGW_MAXLEN);
347  slot->worker.bgw_type, BGW_MAXLEN);
352 
353  /*
354  * Copy various fixed-size fields.
355  *
356  * flags, start_time, and restart_time are examined by the postmaster,
357  * but nothing too bad will happen if they are corrupted. The
358  * remaining fields will only be examined by the child process. It
359  * might crash, but we won't.
360  */
361  rw->rw_worker.bgw_flags = slot->worker.bgw_flags;
365  memcpy(rw->rw_worker.bgw_extra, slot->worker.bgw_extra, BGW_EXTRALEN);
366 
367  /*
368  * Copy the PID to be notified about state changes, but only if the
369  * postmaster knows about a backend with that PID. It isn't an error
370  * if the postmaster doesn't know about the PID, because the backend
371  * that requested the worker could have died (or been killed) just
372  * after doing so. Nonetheless, at least until we get some experience
373  * with how this plays out in the wild, log a message at a relative
374  * high debug level.
375  */
378  {
379  elog(DEBUG1, "worker notification PID %lu is not valid",
380  (long) rw->rw_worker.bgw_notify_pid);
381  rw->rw_worker.bgw_notify_pid = 0;
382  }
383 
384  /* Initialize postmaster bookkeeping. */
385  rw->rw_backend = NULL;
386  rw->rw_pid = 0;
387  rw->rw_child_slot = 0;
388  rw->rw_crashed_at = 0;
389  rw->rw_shmem_slot = slotno;
390  rw->rw_terminate = false;
391 
392  /* Log it! */
393  ereport(DEBUG1,
394  (errmsg("registering background worker \"%s\"",
395  rw->rw_worker.bgw_name)));
396 
398  }
399 }
char bgw_extra[BGW_EXTRALEN]
Definition: bgworker.h:98
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:574
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:691
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
#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:96
#define malloc(a)
Definition: header.h:50
Datum bgw_main_arg
Definition: bgworker.h:97
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:439
bool PostmasterMarkPIDForWorkerNotify(int pid)
Definition: postmaster.c:6089
slist_head BackgroundWorkerList
Definition: bgworker.c:42
static RegisteredBgWorker * FindRegisteredWorkerBySlotNumber(int slotno)
Definition: bgworker.c:217
#define ereport(elevel,...)
Definition: elog.h:155
#define pg_memory_barrier()
Definition: atomics.h:145
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
BackgroundWorker worker
Definition: bgworker.c:82
#define pg_read_barrier()
Definition: atomics.h:158
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:902
uint32 parallel_terminate_count
Definition: bgworker.c:100
pid_t bgw_notify_pid
Definition: bgworker.h:99
#define elog(elevel,...)
Definition: elog.h:228
int max_worker_processes
Definition: globals.c:134
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
#define BGW_EXTRALEN
Definition: bgworker.h:86

◆ BackgroundWorkerStopNotifications()

void BackgroundWorkerStopNotifications ( pid_t  pid)

Definition at line 492 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().

493 {
494  slist_iter siter;
495 
497  {
498  RegisteredBgWorker *rw;
499 
500  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
501  if (rw->rw_worker.bgw_notify_pid == pid)
502  rw->rw_worker.bgw_notify_pid = 0;
503  }
504 }
slist_node * cur
Definition: ilist.h:226
slist_head BackgroundWorkerList
Definition: bgworker.c:42
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
pid_t bgw_notify_pid
Definition: bgworker.h:99
BackgroundWorker rw_worker

◆ bgworker_die()

static void bgworker_die ( SIGNAL_ARGS  )
static

Definition at line 647 of file bgworker.c.

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

Referenced by StartBackgroundWorker().

648 {
650 
651  ereport(FATAL,
652  (errcode(ERRCODE_ADMIN_SHUTDOWN),
653  errmsg("terminating background worker \"%s\" due to administrator command",
655 }
int errcode(int sqlerrcode)
Definition: elog.c:691
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define FATAL
Definition: elog.h:52
sigset_t BlockSig
Definition: pqsignal.c:22
#define ereport(elevel,...)
Definition: elog.h:155
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:902

◆ bgworker_sigusr1_handler()

static void bgworker_sigusr1_handler ( SIGNAL_ARGS  )
static

Definition at line 664 of file bgworker.c.

References latch_sigusr1_handler().

Referenced by StartBackgroundWorker().

665 {
666  int save_errno = errno;
667 
669 
670  errno = save_errno;
671 }
void latch_sigusr1_handler(void)
Definition: latch.c:1944

◆ 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:674
#define slist_foreach(iter, lhead)
Definition: ilist.h:700

◆ ForgetBackgroundWorker()

void ForgetBackgroundWorker ( slist_mutable_iter cur)

Definition at line 411 of file bgworker.c.

References Assert, BackgroundWorker::bgw_flags, BackgroundWorker::bgw_name, BGWORKER_CLASS_PARALLEL, slist_mutable_iter::cur, DEBUG1, ereport, errmsg(), free, BackgroundWorkerSlot::in_use, max_worker_processes, BackgroundWorkerArray::parallel_terminate_count, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, slist_container, slist_delete_current(), and BackgroundWorkerArray::slot.

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

412 {
413  RegisteredBgWorker *rw;
414  BackgroundWorkerSlot *slot;
415 
416  rw = slist_container(RegisteredBgWorker, rw_lnode, cur->cur);
417 
422 
423  slot->in_use = false;
424 
425  ereport(DEBUG1,
426  (errmsg("unregistering background worker \"%s\"",
427  rw->rw_worker.bgw_name)));
428 
430  free(rw);
431 }
#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:67
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define ereport(elevel,...)
Definition: elog.h:155
#define free(a)
Definition: header.h:65
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:800
int errmsg(const char *fmt,...)
Definition: elog.c:902
uint32 parallel_terminate_count
Definition: bgworker.c:100
int max_worker_processes
Definition: globals.c:134
static void slist_delete_current(slist_mutable_iter *iter)
Definition: ilist.h:652
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ GetBackgroundWorkerPid()

BgwHandleStatus GetBackgroundWorkerPid ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1030 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().

1031 {
1032  BackgroundWorkerSlot *slot;
1033  pid_t pid;
1034 
1035  Assert(handle->slot < max_worker_processes);
1036  slot = &BackgroundWorkerData->slot[handle->slot];
1037 
1038  /*
1039  * We could probably arrange to synchronize access to data using memory
1040  * barriers only, but for now, let's just keep it simple and grab the
1041  * lock. It seems unlikely that there will be enough traffic here to
1042  * result in meaningful contention.
1043  */
1044  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1045 
1046  /*
1047  * The generation number can't be concurrently changed while we hold the
1048  * lock. The pid, which is updated by the postmaster, can change at any
1049  * time, but we assume such changes are atomic. So the value we read
1050  * won't be garbage, but it might be out of date by the time the caller
1051  * examines it (but that's unavoidable anyway).
1052  *
1053  * The in_use flag could be in the process of changing from true to false,
1054  * but if it is already false then it can't change further.
1055  */
1056  if (handle->generation != slot->generation || !slot->in_use)
1057  pid = 0;
1058  else
1059  pid = slot->pid;
1060 
1061  /* All done. */
1062  LWLockRelease(BackgroundWorkerLock);
1063 
1064  if (pid == 0)
1065  return BGWH_STOPPED;
1066  else if (pid == InvalidPid)
1067  return BGWH_NOT_YET_STARTED;
1068  *pidp = pid;
1069  return BGWH_STARTED;
1070 }
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
#define Assert(condition)
Definition: c.h:800
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
int max_worker_processes
Definition: globals.c:134
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 1238 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().

1239 {
1240  int slotno;
1241  bool found = false;
1242  static char result[BGW_MAXLEN];
1243 
1244  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1245 
1246  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; slotno++)
1247  {
1249 
1250  if (slot->pid > 0 && slot->pid == pid)
1251  {
1252  strcpy(result, slot->worker.bgw_type);
1253  found = true;
1254  break;
1255  }
1256  }
1257 
1258  LWLockRelease(BackgroundWorkerLock);
1259 
1260  if (!found)
1261  return NULL;
1262 
1263  return result;
1264 }
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
BackgroundWorker worker
Definition: bgworker.c:82
#define BGW_MAXLEN
Definition: bgworker.h:85
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
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 1204 of file bgworker.c.

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

Referenced by StartBackgroundWorker().

1205 {
1206  /*
1207  * If the function is to be loaded from postgres itself, search the
1208  * InternalBGWorkers array.
1209  */
1210  if (strcmp(libraryname, "postgres") == 0)
1211  {
1212  int i;
1213 
1214  for (i = 0; i < lengthof(InternalBGWorkers); i++)
1215  {
1216  if (strcmp(InternalBGWorkers[i].fn_name, funcname) == 0)
1217  return InternalBGWorkers[i].fn_addr;
1218  }
1219 
1220  /* We can only reach this by programming error. */
1221  elog(ERROR, "internal function \"%s\" not found", funcname);
1222  }
1223 
1224  /* Otherwise load from external library. */
1225  return (bgworker_main_type)
1226  load_external_function(libraryname, funcname, true, NULL);
1227 }
static const struct @21 InternalBGWorkers[]
#define lengthof(array)
Definition: c.h:730
const char * fn_name
Definition: bgworker.c:118
#define ERROR
Definition: elog.h:43
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:107
bgworker_main_type fn_addr
Definition: bgworker.c:119
#define elog(elevel,...)
Definition: elog.h:228
int i
void(* bgworker_main_type)(Datum main_arg)
Definition: bgworker.h:71

◆ RegisterBackgroundWorker()

void RegisterBackgroundWorker ( BackgroundWorker worker)

Definition at line 834 of file bgworker.c.

References BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, DEBUG1, ereport, errcode(), errdetail_plural(), errhint(), errmsg(), 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().

835 {
836  RegisteredBgWorker *rw;
837  static int numworkers = 0;
838 
839  if (!IsUnderPostmaster)
840  ereport(DEBUG1,
841  (errmsg("registering background worker \"%s\"", worker->bgw_name)));
842 
844  strcmp(worker->bgw_library_name, "postgres") != 0)
845  {
846  if (!IsUnderPostmaster)
847  ereport(LOG,
848  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
849  errmsg("background worker \"%s\": must be registered in shared_preload_libraries",
850  worker->bgw_name)));
851  return;
852  }
853 
854  if (!SanityCheckBackgroundWorker(worker, LOG))
855  return;
856 
857  if (worker->bgw_notify_pid != 0)
858  {
859  ereport(LOG,
860  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
861  errmsg("background worker \"%s\": only dynamic background workers can request notification",
862  worker->bgw_name)));
863  return;
864  }
865 
866  /*
867  * Enforce maximum number of workers. Note this is overly restrictive: we
868  * could allow more non-shmem-connected workers, because these don't count
869  * towards the MAX_BACKENDS limit elsewhere. For now, it doesn't seem
870  * important to relax this restriction.
871  */
872  if (++numworkers > max_worker_processes)
873  {
874  ereport(LOG,
875  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
876  errmsg("too many background workers"),
877  errdetail_plural("Up to %d background worker can be registered with the current settings.",
878  "Up to %d background workers can be registered with the current settings.",
881  errhint("Consider increasing the configuration parameter \"max_worker_processes\".")));
882  return;
883  }
884 
885  /*
886  * Copy the registration data into the registered workers list.
887  */
888  rw = malloc(sizeof(RegisteredBgWorker));
889  if (rw == NULL)
890  {
891  ereport(LOG,
892  (errcode(ERRCODE_OUT_OF_MEMORY),
893  errmsg("out of memory")));
894  return;
895  }
896 
897  rw->rw_worker = *worker;
898  rw->rw_backend = NULL;
899  rw->rw_pid = 0;
900  rw->rw_child_slot = 0;
901  rw->rw_crashed_at = 0;
902  rw->rw_terminate = false;
903 
905 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1149
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1596
static void slist_push_head(slist_head *head, slist_node *node)
Definition: ilist.h:574
int errcode(int sqlerrcode)
Definition: elog.c:691
#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:109
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition: bgworker.c:582
#define ereport(elevel,...)
Definition: elog.h:155
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1127
int errmsg(const char *fmt,...)
Definition: elog.c:902
pid_t bgw_notify_pid
Definition: bgworker.h:99
int max_worker_processes
Definition: globals.c:134
BackgroundWorker rw_worker
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95

◆ RegisterDynamicBackgroundWorker()

bool RegisterDynamicBackgroundWorker ( BackgroundWorker worker,
BackgroundWorkerHandle **  handle 
)

Definition at line 918 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().

920 {
921  int slotno;
922  bool success = false;
923  bool parallel;
924  uint64 generation = 0;
925 
926  /*
927  * We can't register dynamic background workers from the postmaster. If
928  * this is a standalone backend, we're the only process and can't start
929  * any more. In a multi-process environment, it might be theoretically
930  * possible, but we don't currently support it due to locking
931  * considerations; see comments on the BackgroundWorkerSlot data
932  * structure.
933  */
934  if (!IsUnderPostmaster)
935  return false;
936 
937  if (!SanityCheckBackgroundWorker(worker, ERROR))
938  return false;
939 
940  parallel = (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0;
941 
942  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
943 
944  /*
945  * If this is a parallel worker, check whether there are already too many
946  * parallel workers; if so, don't register another one. Our view of
947  * parallel_terminate_count may be slightly stale, but that doesn't really
948  * matter: we would have gotten the same result if we'd arrived here
949  * slightly earlier anyway. There's no help for it, either, since the
950  * postmaster must not take locks; a memory barrier wouldn't guarantee
951  * anything useful.
952  */
956  {
960  LWLockRelease(BackgroundWorkerLock);
961  return false;
962  }
963 
964  /*
965  * Look for an unused slot. If we find one, grab it.
966  */
967  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; ++slotno)
968  {
970 
971  if (!slot->in_use)
972  {
973  memcpy(&slot->worker, worker, sizeof(BackgroundWorker));
974  slot->pid = InvalidPid; /* indicates not started yet */
975  slot->generation++;
976  slot->terminate = false;
977  generation = slot->generation;
978  if (parallel)
980 
981  /*
982  * Make sure postmaster doesn't see the slot as in use before it
983  * sees the new contents.
984  */
986 
987  slot->in_use = true;
988  success = true;
989  break;
990  }
991  }
992 
993  LWLockRelease(BackgroundWorkerLock);
994 
995  /* If we found a slot, tell the postmaster to notice the change. */
996  if (success)
998 
999  /*
1000  * If we found a slot and the user has provided a handle, initialize it.
1001  */
1002  if (success && handle)
1003  {
1004  *handle = palloc(sizeof(BackgroundWorkerHandle));
1005  (*handle)->slot = slotno;
1006  (*handle)->generation = generation;
1007  }
1008 
1009  return success;
1010 }
int max_parallel_workers
Definition: globals.c:135
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
#define ERROR
Definition: elog.h:43
uint32 parallel_register_count
Definition: bgworker.c:99
bool IsUnderPostmaster
Definition: globals.c:109
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition: bgworker.c:582
#define Assert(condition)
Definition: c.h:800
BackgroundWorker worker
Definition: bgworker.c:82
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
void * palloc(Size size)
Definition: mcxt.c:950
uint32 parallel_terminate_count
Definition: bgworker.c:100
#define pg_write_barrier()
Definition: atomics.h:159
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:146
#define MAX_PARALLEL_WORKER_LIMIT
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101
static bool success
Definition: initdb.c:162
#define InvalidPid
Definition: miscadmin.h:32

◆ ReportBackgroundWorkerExit()

void ReportBackgroundWorkerExit ( slist_mutable_iter cur)

Definition at line 458 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().

459 {
460  RegisteredBgWorker *rw;
461  BackgroundWorkerSlot *slot;
462  int notify_pid;
463 
464  rw = slist_container(RegisteredBgWorker, rw_lnode, cur->cur);
465 
468  slot->pid = rw->rw_pid;
469  notify_pid = rw->rw_worker.bgw_notify_pid;
470 
471  /*
472  * If this worker is slated for deregistration, do that before notifying
473  * the process which started it. Otherwise, if that process tries to
474  * reuse the slot immediately, it might not be available yet. In theory
475  * that could happen anyway if the process checks slot->pid at just the
476  * wrong moment, but this makes the window narrower.
477  */
478  if (rw->rw_terminate ||
481 
482  if (notify_pid != 0)
483  kill(notify_pid, SIGUSR1);
484 }
#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:94
#define kill(pid, sig)
Definition: win32_port.h:454
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:411
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define Assert(condition)
Definition: c.h:800
pid_t bgw_notify_pid
Definition: bgworker.h:99
int max_worker_processes
Definition: globals.c:134
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ ReportBackgroundWorkerPID()

void ReportBackgroundWorkerPID ( RegisteredBgWorker rw)

Definition at line 439 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().

440 {
441  BackgroundWorkerSlot *slot;
442 
445  slot->pid = rw->rw_pid;
446 
447  if (rw->rw_worker.bgw_notify_pid != 0)
449 }
#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:800
pid_t bgw_notify_pid
Definition: bgworker.h:99
int max_worker_processes
Definition: globals.c:134
BackgroundWorker rw_worker
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ ResetBackgroundWorkerCrashTimes()

void ResetBackgroundWorkerCrashTimes ( void  )

Definition at line 514 of file bgworker.c.

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

515 {
516  slist_mutable_iter iter;
517 
519  {
520  RegisteredBgWorker *rw;
521 
522  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
523 
525  {
526  /*
527  * Workers marked BGW_NEVER_RESTART shouldn't get relaunched after
528  * the crash, so forget about them. (If we wait until after the
529  * crash to forget about them, and they are parallel workers,
530  * parallel_terminate_count will get incremented after we've
531  * already zeroed parallel_register_count, which would be bad.)
532  */
533  ForgetBackgroundWorker(&iter);
534  }
535  else
536  {
537  /*
538  * The accounting which we do via parallel_register_count and
539  * parallel_terminate_count would get messed up if a worker marked
540  * parallel could survive a crash and restart cycle. All such
541  * workers should be marked BGW_NEVER_RESTART, and thus control
542  * should never reach this branch.
543  */
545 
546  /*
547  * Allow this worker to be restarted immediately after we finish
548  * resetting.
549  */
550  rw->rw_crashed_at = 0;
551  }
552  }
553 }
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:94
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:411
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define Assert(condition)
Definition: c.h:800
BackgroundWorker rw_worker

◆ SanityCheckBackgroundWorker()

static bool SanityCheckBackgroundWorker ( BackgroundWorker worker,
int  elevel 
)
static

Definition at line 582 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().

583 {
584  /* sanity check for flags */
586  {
587  if (!(worker->bgw_flags & BGWORKER_SHMEM_ACCESS))
588  {
589  ereport(elevel,
590  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
591  errmsg("background worker \"%s\": must attach to shared memory in order to request a database connection",
592  worker->bgw_name)));
593  return false;
594  }
595 
597  {
598  ereport(elevel,
599  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
600  errmsg("background worker \"%s\": cannot request database access if starting at postmaster start",
601  worker->bgw_name)));
602  return false;
603  }
604 
605  /* XXX other checks? */
606  }
607 
608  if ((worker->bgw_restart_time < 0 &&
609  worker->bgw_restart_time != BGW_NEVER_RESTART) ||
610  (worker->bgw_restart_time > USECS_PER_DAY / 1000))
611  {
612  ereport(elevel,
613  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
614  errmsg("background worker \"%s\": invalid restart interval",
615  worker->bgw_name)));
616  return false;
617  }
618 
619  /*
620  * Parallel workers may not be configured for restart, because the
621  * parallel_register_count/parallel_terminate_count accounting can't
622  * handle parallel workers lasting through a crash-and-restart cycle.
623  */
624  if (worker->bgw_restart_time != BGW_NEVER_RESTART &&
625  (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
626  {
627  ereport(elevel,
628  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
629  errmsg("background worker \"%s\": parallel workers may not be configured for restart",
630  worker->bgw_name)));
631  return false;
632  }
633 
634  /*
635  * If bgw_type is not filled in, use bgw_name.
636  */
637  if (strcmp(worker->bgw_type, "") == 0)
638  strcpy(worker->bgw_type, worker->bgw_name);
639 
640  return true;
641 }
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:691
#define BGWORKER_CLASS_PARALLEL
Definition: bgworker.h:67
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define USECS_PER_DAY
Definition: timestamp.h:91
static int elevel
Definition: vacuumlazy.c:333
#define ereport(elevel,...)
Definition: elog.h:155
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:902

◆ StartBackgroundWorker()

void StartBackgroundWorker ( void  )

Definition at line 680 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(), BGWORKER_SHMEM_ACCESS, bgworker_sigusr1_handler(), dsm_detach_all(), elog, EmitErrorReport(), error_context_stack, FATAL, FloatExceptionHandler(), HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitProcess(), InitProcessing, IsBackgroundWorker, LookupBackgroundWorkerFunction(), MyBackendType, MyBgworkerEntry, PG_exception_stack, pg_usleep(), PGSharedMemoryDetach(), 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().

681 {
682  sigjmp_buf local_sigjmp_buf;
684  bgworker_main_type entrypt;
685 
686  if (worker == NULL)
687  elog(FATAL, "unable to find bgworker entry");
688 
689  IsBackgroundWorker = true;
690 
692  init_ps_display(worker->bgw_name);
693 
694  /*
695  * If we're not supposed to have shared memory access, then detach from
696  * shared memory. If we didn't request shared memory access, the
697  * postmaster won't force a cluster-wide restart if we exit unexpectedly,
698  * so we'd better make sure that we don't mess anything up that would
699  * require that sort of cleanup.
700  */
701  if ((worker->bgw_flags & BGWORKER_SHMEM_ACCESS) == 0)
702  {
703  dsm_detach_all();
705  }
706 
708 
709  /* Apply PostAuthDelay */
710  if (PostAuthDelay > 0)
711  pg_usleep(PostAuthDelay * 1000000L);
712 
713  /*
714  * Set up signal handlers.
715  */
717  {
718  /*
719  * SIGINT is used to signal canceling the current action
720  */
724 
725  /* XXX Any other handlers needed here? */
726  }
727  else
728  {
729  pqsignal(SIGINT, SIG_IGN);
731  pqsignal(SIGFPE, SIG_IGN);
732  }
733  pqsignal(SIGTERM, bgworker_die);
734  /* SIGQUIT handler was already set up by InitPostmasterChild */
736 
737  InitializeTimeouts(); /* establishes SIGALRM handler */
738 
742 
743  /*
744  * If an exception is encountered, processing resumes here.
745  *
746  * We just need to clean up, report the error, and go away.
747  */
748  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
749  {
750  /* Since not using PG_TRY, must reset error stack by hand */
751  error_context_stack = NULL;
752 
753  /* Prevent interrupts while cleaning up */
754  HOLD_INTERRUPTS();
755 
756  /*
757  * sigsetjmp will have blocked all signals, but we may need to accept
758  * signals while communicating with our parallel leader. Once we've
759  * done HOLD_INTERRUPTS() it should be safe to unblock signals.
760  */
762 
763  /* Report the error to the parallel leader and the server log */
764  EmitErrorReport();
765 
766  /*
767  * Do we need more cleanup here? For shmem-connected bgworkers, we
768  * will call InitProcess below, which will install ProcKill as exit
769  * callback. That will take care of releasing locks, etc.
770  */
771 
772  /* and go away */
773  proc_exit(1);
774  }
775 
776  /* We can now handle ereport(ERROR) */
777  PG_exception_stack = &local_sigjmp_buf;
778 
779  /*
780  * If the background worker request shared memory access, set that up now;
781  * else, detach all shared memory segments.
782  */
783  if (worker->bgw_flags & BGWORKER_SHMEM_ACCESS)
784  {
785  /*
786  * Early initialization. Some of this could be useful even for
787  * background workers that aren't using shared memory, but they can
788  * call the individual startup routines for those subsystems if
789  * needed.
790  */
791  BaseInit();
792 
793  /*
794  * Create a per-backend PGPROC struct in shared memory, except in the
795  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must
796  * do this before we can use LWLocks (and in the EXEC_BACKEND case we
797  * already had to do some stuff with LWLocks).
798  */
799 #ifndef EXEC_BACKEND
800  InitProcess();
801 #endif
802  }
803 
804  /*
805  * Look up the entry point function, loading its library if necessary.
806  */
808  worker->bgw_function_name);
809 
810  /*
811  * Note that in normal processes, we would call InitPostgres here. For a
812  * worker, however, we don't know what database to connect to, yet; so we
813  * need to wait until the user code does it via
814  * BackgroundWorkerInitializeConnection().
815  */
816 
817  /*
818  * Now invoke the user-defined worker code
819  */
820  entrypt(worker->bgw_main_arg);
821 
822  /* ... and if it returns, we're done */
823  proc_exit(0);
824 }
void InitializeTimeouts(void)
Definition: timeout.c:346
static void bgworker_sigusr1_handler(SIGNAL_ARGS)
Definition: bgworker.c:664
#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:399
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
void BaseInit(void)
Definition: postinit.c:547
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
void PGSharedMemoryDetach(void)
Definition: sysv_shmem.c:909
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2857
bool IsBackgroundWorker
Definition: globals.c:111
ErrorContextCallback * error_context_stack
Definition: elog.c:92
void pg_usleep(long microsec)
Definition: signal.c:53
Datum bgw_main_arg
Definition: bgworker.h:97
#define FATAL
Definition: elog.h:52
void InitProcess(void)
Definition: proc.c:301
#define SIGHUP
Definition: win32_port.h:159
static bgworker_main_type LookupBackgroundWorkerFunction(const char *libraryname, const char *funcname)
Definition: bgworker.c:1204
#define SIG_IGN
Definition: win32_port.h:156
int PostAuthDelay
Definition: postgres.c:102
void EmitErrorReport(void)
Definition: elog.c:1501
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:90
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
void dsm_detach_all(void)
Definition: dsm.c:741
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:228
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2878
static void bgworker_die(SIGNAL_ARGS)
Definition: bgworker.c:647
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
void(* bgworker_main_type)(Datum main_arg)
Definition: bgworker.h:71
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5735

◆ TerminateBackgroundWorker()

void TerminateBackgroundWorker ( BackgroundWorkerHandle handle)

Definition at line 1163 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().

1164 {
1165  BackgroundWorkerSlot *slot;
1166  bool signal_postmaster = false;
1167 
1168  Assert(handle->slot < max_worker_processes);
1169  slot = &BackgroundWorkerData->slot[handle->slot];
1170 
1171  /* Set terminate flag in shared memory, unless slot has been reused. */
1172  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
1173  if (handle->generation == slot->generation)
1174  {
1175  slot->terminate = true;
1176  signal_postmaster = true;
1177  }
1178  LWLockRelease(BackgroundWorkerLock);
1179 
1180  /* Make sure the postmaster notices the change to shared memory. */
1181  if (signal_postmaster)
1183 }
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:110
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
#define Assert(condition)
Definition: c.h:800
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
int max_worker_processes
Definition: globals.c:134
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:146
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition: bgworker.c:101

◆ WaitForBackgroundWorkerShutdown()

BgwHandleStatus WaitForBackgroundWorkerShutdown ( BackgroundWorkerHandle handle)

Definition at line 1124 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().

1125 {
1127  int rc;
1128 
1129  for (;;)
1130  {
1131  pid_t pid;
1132 
1134 
1135  status = GetBackgroundWorkerPid(handle, &pid);
1136  if (status == BGWH_STOPPED)
1137  break;
1138 
1139  rc = WaitLatch(MyLatch,
1142 
1143  if (rc & WL_POSTMASTER_DEATH)
1144  {
1145  status = BGWH_POSTMASTER_DIED;
1146  break;
1147  }
1148 
1150  }
1151 
1152  return status;
1153 }
void ResetLatch(Latch *latch)
Definition: latch.c:588
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
BgwHandleStatus
Definition: bgworker.h:102
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:124
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1030

◆ WaitForBackgroundWorkerStartup()

BgwHandleStatus WaitForBackgroundWorkerStartup ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1082 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().

1083 {
1085  int rc;
1086 
1087  for (;;)
1088  {
1089  pid_t pid;
1090 
1092 
1093  status = GetBackgroundWorkerPid(handle, &pid);
1094  if (status == BGWH_STARTED)
1095  *pidp = pid;
1096  if (status != BGWH_NOT_YET_STARTED)
1097  break;
1098 
1099  rc = WaitLatch(MyLatch,
1102 
1103  if (rc & WL_POSTMASTER_DEATH)
1104  {
1105  status = BGWH_POSTMASTER_DIED;
1106  break;
1107  }
1108 
1110  }
1111 
1112  return status;
1113 }
void ResetLatch(Latch *latch)
Definition: latch.c:588
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
BgwHandleStatus
Definition: bgworker.h:102
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:124
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1030

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:950
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:1239
void ApplyWorkerMain(Datum main_arg)
Definition: worker.c:2926

Referenced by LookupBackgroundWorkerFunction().