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

Go to the source code of this file.

Data Structures

struct  BackgroundWorkerSlot
 
struct  BackgroundWorkerArray
 
struct  BackgroundWorkerHandle
 

Typedefs

typedef struct BackgroundWorkerSlot BackgroundWorkerSlot
 
typedef struct BackgroundWorkerArray BackgroundWorkerArray
 

Functions

static bgworker_main_type LookupBackgroundWorkerFunction (const char *libraryname, const char *funcname)
 
Size BackgroundWorkerShmemSize (void)
 
void BackgroundWorkerShmemInit (void)
 
static RegisteredBgWorkerFindRegisteredWorkerBySlotNumber (int slotno)
 
void BackgroundWorkerStateChange (bool allow_new_workers)
 
void ForgetBackgroundWorker (RegisteredBgWorker *rw)
 
void ReportBackgroundWorkerPID (RegisteredBgWorker *rw)
 
void ReportBackgroundWorkerExit (RegisteredBgWorker *rw)
 
void BackgroundWorkerStopNotifications (pid_t pid)
 
void ForgetUnstartedBackgroundWorkers (void)
 
void ResetBackgroundWorkerCrashTimes (void)
 
static bool SanityCheckBackgroundWorker (BackgroundWorker *worker, int elevel)
 
static void bgworker_die (SIGNAL_ARGS)
 
void BackgroundWorkerMain (char *startup_data, size_t startup_data_len)
 
void BackgroundWorkerInitializeConnection (const char *dbname, const char *username, uint32 flags)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid, uint32 flags)
 
void BackgroundWorkerBlockSignals (void)
 
void BackgroundWorkerUnblockSignals (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

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

Typedef Documentation

◆ BackgroundWorkerArray

◆ BackgroundWorkerSlot

Function Documentation

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 920 of file bgworker.c.

921 {
922  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
923 }
sigset_t BlockSig
Definition: pqsignal.c:23

References BlockSig.

◆ BackgroundWorkerInitializeConnection()

void BackgroundWorkerInitializeConnection ( const char *  dbname,
const char *  username,
uint32  flags 
)

Definition at line 852 of file bgworker.c.

853 {
855  bits32 init_flags = 0; /* never honor session_preload_libraries */
856 
857  /* ignore datallowconn? */
858  if (flags & BGWORKER_BYPASS_ALLOWCONN)
859  init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
860  /* ignore rolcanlogin? */
861  if (flags & BGWORKER_BYPASS_ROLELOGINCHECK)
862  init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
863 
864  /* XXX is this the right errcode? */
866  ereport(FATAL,
867  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
868  errmsg("database connection requirement not indicated during registration")));
869 
870  InitPostgres(dbname, InvalidOid, /* database to connect to */
871  username, InvalidOid, /* role to connect as */
872  init_flags,
873  NULL); /* no out_dbname */
874 
875  /* it had better not gotten out of "init" mode yet */
876  if (!IsInitProcessingMode())
877  ereport(ERROR,
878  (errmsg("invalid processing mode in background worker")));
880 }
#define BGWORKER_BYPASS_ROLELOGINCHECK
Definition: bgworker.h:157
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:156
uint32 bits32
Definition: c.h:526
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
static char * username
Definition: initdb.c:153
@ NormalProcessing
Definition: miscadmin.h:449
#define IsInitProcessingMode()
Definition: miscadmin.h:455
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:478
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:477
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:698
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
char * dbname
Definition: streamutil.c:50

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, dbname, ereport, errcode(), errmsg(), ERROR, FATAL, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitPostgres(), InvalidOid, IsInitProcessingMode, MyBgworkerEntry, NormalProcessing, SetProcessingMode, and username.

Referenced by ApplyLauncherMain(), and worker_spi_main().

◆ BackgroundWorkerInitializeConnectionByOid()

void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid,
uint32  flags 
)

Definition at line 886 of file bgworker.c.

887 {
889  bits32 init_flags = 0; /* never honor session_preload_libraries */
890 
891  /* ignore datallowconn? */
892  if (flags & BGWORKER_BYPASS_ALLOWCONN)
893  init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
894  /* ignore rolcanlogin? */
895  if (flags & BGWORKER_BYPASS_ROLELOGINCHECK)
896  init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
897 
898  /* XXX is this the right errcode? */
900  ereport(FATAL,
901  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
902  errmsg("database connection requirement not indicated during registration")));
903 
904  InitPostgres(NULL, dboid, /* database to connect to */
905  NULL, useroid, /* role to connect as */
906  init_flags,
907  NULL); /* no out_dbname */
908 
909  /* it had better not gotten out of "init" mode yet */
910  if (!IsInitProcessingMode())
911  ereport(ERROR,
912  (errmsg("invalid processing mode in background worker")));
914 }

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, ereport, errcode(), errmsg(), ERROR, FATAL, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitPostgres(), IsInitProcessingMode, MyBgworkerEntry, NormalProcessing, and SetProcessingMode.

Referenced by autoprewarm_database_main(), InitializeLogRepWorker(), ParallelWorkerMain(), and worker_spi_main().

◆ BackgroundWorkerMain()

void BackgroundWorkerMain ( char *  startup_data,
size_t  startup_data_len 
)

Definition at line 717 of file bgworker.c.

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

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

◆ BackgroundWorkerShmemInit()

void BackgroundWorkerShmemInit ( void  )

Definition at line 162 of file bgworker.c.

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

References Assert, BackgroundWorkerData, BackgroundWorkerList, BackgroundWorkerShmemSize(), BackgroundWorker::bgw_notify_pid, dlist_iter::cur, dlist_container, dlist_foreach, 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(), BackgroundWorkerArray::slot, BackgroundWorkerSlot::terminate, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

Referenced by CreateOrAttachShmemStructs().

◆ BackgroundWorkerShmemSize()

Size BackgroundWorkerShmemSize ( void  )

Definition at line 146 of file bgworker.c.

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

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

Referenced by BackgroundWorkerShmemInit(), and CalculateShmemSize().

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)

Definition at line 246 of file bgworker.c.

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

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

Referenced by process_pm_pmsignal().

◆ BackgroundWorkerStopNotifications()

void BackgroundWorkerStopNotifications ( pid_t  pid)

Definition at line 514 of file bgworker.c.

515 {
516  dlist_iter iter;
517 
519  {
520  RegisteredBgWorker *rw;
521 
522  rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
523  if (rw->rw_worker.bgw_notify_pid == pid)
524  rw->rw_worker.bgw_notify_pid = 0;
525  }
526 }

References BackgroundWorkerList, BackgroundWorker::bgw_notify_pid, dlist_iter::cur, dlist_container, dlist_foreach, and RegisteredBgWorker::rw_worker.

Referenced by CleanupBackend().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 926 of file bgworker.c.

927 {
928  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
929 }
sigset_t UnBlockSig
Definition: pqsignal.c:22

References UnBlockSig.

Referenced by ApplyLauncherMain(), autoprewarm_database_main(), autoprewarm_main(), BackgroundWorkerMain(), ParallelApplyWorkerMain(), ParallelWorkerMain(), SetupApplyOrSyncWorker(), test_shm_mq_main(), and worker_spi_main().

◆ bgworker_die()

static void bgworker_die ( SIGNAL_ARGS  )
static

Definition at line 703 of file bgworker.c.

704 {
705  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
706 
707  ereport(FATAL,
708  (errcode(ERRCODE_ADMIN_SHUTDOWN),
709  errmsg("terminating background worker \"%s\" due to administrator command",
711 }

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

Referenced by BackgroundWorkerMain().

◆ FindRegisteredWorkerBySlotNumber()

static RegisteredBgWorker* FindRegisteredWorkerBySlotNumber ( int  slotno)
static

Definition at line 221 of file bgworker.c.

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

References BackgroundWorkerList, dlist_iter::cur, dlist_container, dlist_foreach, and RegisteredBgWorker::rw_shmem_slot.

Referenced by BackgroundWorkerStateChange().

◆ ForgetBackgroundWorker()

void ForgetBackgroundWorker ( RegisteredBgWorker rw)

Definition at line 429 of file bgworker.c.

430 {
431  BackgroundWorkerSlot *slot;
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 
451  dlist_delete(&rw->rw_lnode);
452  pfree(rw);
453 }
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405
void pfree(void *pointer)
Definition: mcxt.c:1521

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

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

◆ ForgetUnstartedBackgroundWorkers()

void ForgetUnstartedBackgroundWorkers ( void  )

Definition at line 541 of file bgworker.c.

542 {
543  dlist_mutable_iter iter;
544 
546  {
547  RegisteredBgWorker *rw;
548  BackgroundWorkerSlot *slot;
549 
550  rw = dlist_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 
562  if (notify_pid != 0)
563  kill(notify_pid, SIGUSR1);
564  }
565  }
566 }
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition: bgworker.c:429
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:640
dlist_node * cur
Definition: ilist.h:200

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

Referenced by PostmasterStateMachine().

◆ GetBackgroundWorkerPid()

BgwHandleStatus GetBackgroundWorkerPid ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1157 of file bgworker.c.

1158 {
1159  BackgroundWorkerSlot *slot;
1160  pid_t pid;
1161 
1162  Assert(handle->slot < max_worker_processes);
1163  slot = &BackgroundWorkerData->slot[handle->slot];
1164 
1165  /*
1166  * We could probably arrange to synchronize access to data using memory
1167  * barriers only, but for now, let's just keep it simple and grab the
1168  * lock. It seems unlikely that there will be enough traffic here to
1169  * result in meaningful contention.
1170  */
1171  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1172 
1173  /*
1174  * The generation number can't be concurrently changed while we hold the
1175  * lock. The pid, which is updated by the postmaster, can change at any
1176  * time, but we assume such changes are atomic. So the value we read
1177  * won't be garbage, but it might be out of date by the time the caller
1178  * examines it (but that's unavoidable anyway).
1179  *
1180  * The in_use flag could be in the process of changing from true to false,
1181  * but if it is already false then it can't change further.
1182  */
1183  if (handle->generation != slot->generation || !slot->in_use)
1184  pid = 0;
1185  else
1186  pid = slot->pid;
1187 
1188  /* All done. */
1189  LWLockRelease(BackgroundWorkerLock);
1190 
1191  if (pid == 0)
1192  return BGWH_STOPPED;
1193  else if (pid == InvalidPid)
1194  return BGWH_NOT_YET_STARTED;
1195  *pidp = pid;
1196  return BGWH_STARTED;
1197 }
@ BGWH_STARTED
Definition: bgworker.h:105
@ BGWH_NOT_YET_STARTED
Definition: bgworker.h:106
@ BGWH_STOPPED
Definition: bgworker.h:107
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_SHARED
Definition: lwlock.h:115

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

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

◆ GetBackgroundWorkerTypeByPid()

const char* GetBackgroundWorkerTypeByPid ( pid_t  pid)

Definition at line 1371 of file bgworker.c.

1372 {
1373  int slotno;
1374  bool found = false;
1375  static char result[BGW_MAXLEN];
1376 
1377  LWLockAcquire(BackgroundWorkerLock, LW_SHARED);
1378 
1379  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; slotno++)
1380  {
1382 
1383  if (slot->pid > 0 && slot->pid == pid)
1384  {
1385  strcpy(result, slot->worker.bgw_type);
1386  found = true;
1387  break;
1388  }
1389  }
1390 
1391  LWLockRelease(BackgroundWorkerLock);
1392 
1393  if (!found)
1394  return NULL;
1395 
1396  return result;
1397 }

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

Referenced by pg_stat_get_activity().

◆ LookupBackgroundWorkerFunction()

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

Definition at line 1337 of file bgworker.c.

1338 {
1339  /*
1340  * If the function is to be loaded from postgres itself, search the
1341  * InternalBGWorkers array.
1342  */
1343  if (strcmp(libraryname, "postgres") == 0)
1344  {
1345  int i;
1346 
1347  for (i = 0; i < lengthof(InternalBGWorkers); i++)
1348  {
1349  if (strcmp(InternalBGWorkers[i].fn_name, funcname) == 0)
1350  return InternalBGWorkers[i].fn_addr;
1351  }
1352 
1353  /* We can only reach this by programming error. */
1354  elog(ERROR, "internal function \"%s\" not found", funcname);
1355  }
1356 
1357  /* Otherwise load from external library. */
1358  return (bgworker_main_type)
1359  load_external_function(libraryname, funcname, true, NULL);
1360 }
static const struct @18 InternalBGWorkers[]
const char * fn_name
Definition: bgworker.c:116
bgworker_main_type fn_addr
Definition: bgworker.c:117
#define lengthof(array)
Definition: c.h:793
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:105
#define funcname
Definition: indent_codes.h:69
int i
Definition: isn.c:72

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

Referenced by BackgroundWorkerMain().

◆ RegisterBackgroundWorker()

void RegisterBackgroundWorker ( BackgroundWorker worker)

Definition at line 939 of file bgworker.c.

940 {
941  RegisteredBgWorker *rw;
942  static int numworkers = 0;
943 
944  /*
945  * Static background workers can only be registered in the postmaster
946  * process.
947  */
949  {
950  /*
951  * In EXEC_BACKEND or single-user mode, we process
952  * shared_preload_libraries in backend processes too. We cannot
953  * register static background workers at that stage, but many
954  * libraries' _PG_init() functions don't distinguish whether they're
955  * being loaded in the postmaster or in a backend, they just check
956  * process_shared_preload_libraries_in_progress. It's a bit sloppy,
957  * but for historical reasons we tolerate it. In EXEC_BACKEND mode,
958  * the background workers should already have been registered when the
959  * library was loaded in postmaster.
960  */
962  return;
963  ereport(LOG,
964  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
965  errmsg("background worker \"%s\": must be registered in \"shared_preload_libraries\"",
966  worker->bgw_name)));
967  return;
968  }
969 
970  /*
971  * Cannot register static background workers after calling
972  * BackgroundWorkerShmemInit().
973  */
974  if (BackgroundWorkerData != NULL)
975  elog(ERROR, "cannot register background worker \"%s\" after shmem init",
976  worker->bgw_name);
977 
978  ereport(DEBUG1,
979  (errmsg_internal("registering background worker \"%s\"", worker->bgw_name)));
980 
981  if (!SanityCheckBackgroundWorker(worker, LOG))
982  return;
983 
984  if (worker->bgw_notify_pid != 0)
985  {
986  ereport(LOG,
987  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
988  errmsg("background worker \"%s\": only dynamic background workers can request notification",
989  worker->bgw_name)));
990  return;
991  }
992 
993  /*
994  * Enforce maximum number of workers. Note this is overly restrictive: we
995  * could allow more non-shmem-connected workers, because these don't count
996  * towards the MAX_BACKENDS limit elsewhere. For now, it doesn't seem
997  * important to relax this restriction.
998  */
999  if (++numworkers > max_worker_processes)
1000  {
1001  ereport(LOG,
1002  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
1003  errmsg("too many background workers"),
1004  errdetail_plural("Up to %d background worker can be registered with the current settings.",
1005  "Up to %d background workers can be registered with the current settings.",
1008  errhint("Consider increasing the configuration parameter \"%s\".", "max_worker_processes")));
1009  return;
1010  }
1011 
1012  /*
1013  * Copy the registration data into the registered workers list.
1014  */
1016  sizeof(RegisteredBgWorker),
1018  if (rw == NULL)
1019  {
1020  ereport(LOG,
1021  (errcode(ERRCODE_OUT_OF_MEMORY),
1022  errmsg("out of memory")));
1023  return;
1024  }
1025 
1026  rw->rw_worker = *worker;
1027  rw->rw_pid = 0;
1028  rw->rw_crashed_at = 0;
1029  rw->rw_terminate = false;
1030 
1032 }
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition: bgworker.c:631
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1295
int errhint(const char *fmt,...)
Definition: elog.c:1317
bool IsPostmasterEnvironment
Definition: globals.c:118
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1839

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

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

◆ RegisterDynamicBackgroundWorker()

bool RegisterDynamicBackgroundWorker ( BackgroundWorker worker,
BackgroundWorkerHandle **  handle 
)

Definition at line 1045 of file bgworker.c.

1047 {
1048  int slotno;
1049  bool success = false;
1050  bool parallel;
1051  uint64 generation = 0;
1052 
1053  /*
1054  * We can't register dynamic background workers from the postmaster. If
1055  * this is a standalone backend, we're the only process and can't start
1056  * any more. In a multi-process environment, it might be theoretically
1057  * possible, but we don't currently support it due to locking
1058  * considerations; see comments on the BackgroundWorkerSlot data
1059  * structure.
1060  */
1061  if (!IsUnderPostmaster)
1062  return false;
1063 
1064  if (!SanityCheckBackgroundWorker(worker, ERROR))
1065  return false;
1066 
1067  parallel = (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0;
1068 
1069  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
1070 
1071  /*
1072  * If this is a parallel worker, check whether there are already too many
1073  * parallel workers; if so, don't register another one. Our view of
1074  * parallel_terminate_count may be slightly stale, but that doesn't really
1075  * matter: we would have gotten the same result if we'd arrived here
1076  * slightly earlier anyway. There's no help for it, either, since the
1077  * postmaster must not take locks; a memory barrier wouldn't guarantee
1078  * anything useful.
1079  */
1080  if (parallel && (BackgroundWorkerData->parallel_register_count -
1083  {
1087  LWLockRelease(BackgroundWorkerLock);
1088  return false;
1089  }
1090 
1091  /*
1092  * Look for an unused slot. If we find one, grab it.
1093  */
1094  for (slotno = 0; slotno < BackgroundWorkerData->total_slots; ++slotno)
1095  {
1097 
1098  if (!slot->in_use)
1099  {
1100  memcpy(&slot->worker, worker, sizeof(BackgroundWorker));
1101  slot->pid = InvalidPid; /* indicates not started yet */
1102  slot->generation++;
1103  slot->terminate = false;
1104  generation = slot->generation;
1105  if (parallel)
1107 
1108  /*
1109  * Make sure postmaster doesn't see the slot as in use before it
1110  * sees the new contents.
1111  */
1112  pg_write_barrier();
1113 
1114  slot->in_use = true;
1115  success = true;
1116  break;
1117  }
1118  }
1119 
1120  LWLockRelease(BackgroundWorkerLock);
1121 
1122  /* If we found a slot, tell the postmaster to notice the change. */
1123  if (success)
1125 
1126  /*
1127  * If we found a slot and the user has provided a handle, initialize it.
1128  */
1129  if (success && handle)
1130  {
1131  *handle = palloc(sizeof(BackgroundWorkerHandle));
1132  (*handle)->slot = slotno;
1133  (*handle)->generation = generation;
1134  }
1135 
1136  return success;
1137 }
#define pg_write_barrier()
Definition: atomics.h:157
#define MAX_PARALLEL_WORKER_LIMIT
int max_parallel_workers
Definition: globals.c:144
static bool success
Definition: initdb.c:186
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void * palloc(Size size)
Definition: mcxt.c:1317
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:165
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition: pmsignal.h:40

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

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

◆ ReportBackgroundWorkerExit()

void ReportBackgroundWorkerExit ( RegisteredBgWorker rw)

Definition at line 483 of file bgworker.c.

484 {
485  BackgroundWorkerSlot *slot;
486  int notify_pid;
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 BGW_NEVER_RESTART
Definition: bgworker.h:85

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

Referenced by CleanupBackend().

◆ ReportBackgroundWorkerPID()

◆ ResetBackgroundWorkerCrashTimes()

void ResetBackgroundWorkerCrashTimes ( void  )

Definition at line 579 of file bgworker.c.

580 {
581  dlist_mutable_iter iter;
582 
584  {
585  RegisteredBgWorker *rw;
586 
587  rw = dlist_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  */
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 }

References Assert, BackgroundWorkerList, BackgroundWorker::bgw_flags, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BGWORKER_CLASS_PARALLEL, dlist_mutable_iter::cur, dlist_container, dlist_foreach_modify, ForgetBackgroundWorker(), RegisteredBgWorker::rw_crashed_at, and RegisteredBgWorker::rw_worker.

Referenced by PostmasterStateMachine().

◆ SanityCheckBackgroundWorker()

static bool SanityCheckBackgroundWorker ( BackgroundWorker worker,
int  elevel 
)
static

Definition at line 631 of file bgworker.c.

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

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

Referenced by RegisterBackgroundWorker(), and RegisterDynamicBackgroundWorker().

◆ TerminateBackgroundWorker()

void TerminateBackgroundWorker ( BackgroundWorkerHandle handle)

Definition at line 1296 of file bgworker.c.

1297 {
1298  BackgroundWorkerSlot *slot;
1299  bool signal_postmaster = false;
1300 
1301  Assert(handle->slot < max_worker_processes);
1302  slot = &BackgroundWorkerData->slot[handle->slot];
1303 
1304  /* Set terminate flag in shared memory, unless slot has been reused. */
1305  LWLockAcquire(BackgroundWorkerLock, LW_EXCLUSIVE);
1306  if (handle->generation == slot->generation)
1307  {
1308  slot->terminate = true;
1309  signal_postmaster = true;
1310  }
1311  LWLockRelease(BackgroundWorkerLock);
1312 
1313  /* Make sure the postmaster notices the change to shared memory. */
1314  if (signal_postmaster)
1316 }

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

Referenced by cleanup_background_workers(), and DestroyParallelContext().

◆ WaitForBackgroundWorkerShutdown()

BgwHandleStatus WaitForBackgroundWorkerShutdown ( BackgroundWorkerHandle handle)

Definition at line 1257 of file bgworker.c.

1258 {
1259  BgwHandleStatus status;
1260  int rc;
1261 
1262  for (;;)
1263  {
1264  pid_t pid;
1265 
1267 
1268  status = GetBackgroundWorkerPid(handle, &pid);
1269  if (status == BGWH_STOPPED)
1270  break;
1271 
1272  rc = WaitLatch(MyLatch,
1274  WAIT_EVENT_BGWORKER_SHUTDOWN);
1275 
1276  if (rc & WL_POSTMASTER_DEATH)
1277  {
1278  status = BGWH_POSTMASTER_DIED;
1279  break;
1280  }
1281 
1283  }
1284 
1285  return status;
1286 }
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1157
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_POSTMASTER_DIED
Definition: bgworker.h:108
struct Latch * MyLatch
Definition: globals.c:62
void ResetLatch(Latch *latch)
Definition: latch.c:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_LATCH_SET
Definition: latch.h:127
#define WL_POSTMASTER_DEATH
Definition: latch.h:131
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122

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

Referenced by apw_start_database_worker(), and WaitForParallelWorkersToExit().

◆ WaitForBackgroundWorkerStartup()

BgwHandleStatus WaitForBackgroundWorkerStartup ( BackgroundWorkerHandle handle,
pid_t *  pidp 
)

Definition at line 1212 of file bgworker.c.

1213 {
1214  BgwHandleStatus status;
1215  int rc;
1216 
1217  for (;;)
1218  {
1219  pid_t pid;
1220 
1222 
1223  status = GetBackgroundWorkerPid(handle, &pid);
1224  if (status == BGWH_STARTED)
1225  *pidp = pid;
1226  if (status != BGWH_NOT_YET_STARTED)
1227  break;
1228 
1229  rc = WaitLatch(MyLatch,
1231  WAIT_EVENT_BGWORKER_STARTUP);
1232 
1233  if (rc & WL_POSTMASTER_DEATH)
1234  {
1235  status = BGWH_POSTMASTER_DIED;
1236  break;
1237  }
1238 
1240  }
1241 
1242  return status;
1243 }

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

Referenced by apw_start_leader_worker(), and worker_spi_launch().

Variable Documentation

◆ BackgroundWorkerData

◆ BackgroundWorkerList

◆ fn_addr

Definition at line 117 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 116 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ 

const { ... } InternalBGWorkers[]
Initial value:
=
{
{
"ParallelWorkerMain", ParallelWorkerMain
},
{
"ApplyLauncherMain", ApplyLauncherMain
},
{
"ApplyWorkerMain", ApplyWorkerMain
},
{
"ParallelApplyWorkerMain", ParallelApplyWorkerMain
},
{
"TablesyncWorkerMain", TablesyncWorkerMain
}
}
void ParallelApplyWorkerMain(Datum main_arg)
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:1288
void ApplyWorkerMain(Datum main_arg)
Definition: worker.c:4784
void ApplyLauncherMain(Datum main_arg)
Definition: launcher.c:1128
void TablesyncWorkerMain(Datum main_arg)
Definition: tablesync.c:1719

Referenced by LookupBackgroundWorkerFunction().