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

Go to the source code of this file.

Data Structures

struct  BackgroundWorkerSlot
 
struct  BackgroundWorkerArray
 
struct  BackgroundWorkerHandle
 

Typedefs

typedef struct BackgroundWorkerSlot BackgroundWorkerSlot
 
typedef struct BackgroundWorkerArray BackgroundWorkerArray
 

Functions

static bgworker_main_type LookupBackgroundWorkerFunction (const char *libraryname, const char *funcname)
 
Size BackgroundWorkerShmemSize (void)
 
void BackgroundWorkerShmemInit (void)
 
static RegisteredBgWorkerFindRegisteredWorkerBySlotNumber (int slotno)
 
void BackgroundWorkerStateChange (bool allow_new_workers)
 
void ForgetBackgroundWorker (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 (const void *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 924 of file bgworker.c.

925{
926 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
927}
sigset_t BlockSig
Definition: pqsignal.c:23

References BlockSig.

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 856 of file bgworker.c.

857{
859 bits32 init_flags = 0; /* never honor session_preload_libraries */
860
861 /* ignore datallowconn and ACL_CONNECT? */
862 if (flags & BGWORKER_BYPASS_ALLOWCONN)
863 init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
864 /* ignore rolcanlogin? */
866 init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
867
868 /* XXX is this the right errcode? */
871 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
872 errmsg("database connection requirement not indicated during registration")));
873
874 InitPostgres(dbname, InvalidOid, /* database to connect to */
875 username, InvalidOid, /* role to connect as */
876 init_flags,
877 NULL); /* no out_dbname */
878
879 /* it had better not gotten out of "init" mode yet */
882 (errmsg("invalid processing mode in background worker")));
884}
#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:551
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
static char * username
Definition: initdb.c:153
@ NormalProcessing
Definition: miscadmin.h:472
#define IsInitProcessingMode()
Definition: miscadmin.h:478
#define SetProcessingMode(mode)
Definition: miscadmin.h:483
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:501
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:500
#define InvalidOid
Definition: postgres_ext.h:37
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:707
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:200
char * dbname
Definition: streamutil.c:49

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 890 of file bgworker.c.

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

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 ( const void *  startup_data,
size_t  startup_data_len 
)

Definition at line 721 of file bgworker.c.

722{
723 sigjmp_buf local_sigjmp_buf;
724 BackgroundWorker *worker;
725 bgworker_main_type entrypt;
726
727 if (startup_data == NULL)
728 elog(FATAL, "unable to find bgworker entry");
729 Assert(startup_data_len == sizeof(BackgroundWorker));
731 memcpy(worker, startup_data, sizeof(BackgroundWorker));
732
733 /*
734 * Now that we're done reading the startup data, release postmaster's
735 * working memory context.
736 */
738 {
740 PostmasterContext = NULL;
741 }
742
743 MyBgworkerEntry = worker;
745 init_ps_display(worker->bgw_name);
746
748
749 /* Apply PostAuthDelay */
750 if (PostAuthDelay > 0)
751 pg_usleep(PostAuthDelay * 1000000L);
752
753 /*
754 * Set up signal handlers.
755 */
757 {
758 /*
759 * SIGINT is used to signal canceling the current action
760 */
764
765 /* XXX Any other handlers needed here? */
766 }
767 else
768 {
769 pqsignal(SIGINT, SIG_IGN);
770 pqsignal(SIGUSR1, SIG_IGN);
771 pqsignal(SIGFPE, SIG_IGN);
772 }
773 pqsignal(SIGTERM, bgworker_die);
774 /* SIGQUIT handler was already set up by InitPostmasterChild */
775 pqsignal(SIGHUP, SIG_IGN);
776
777 InitializeTimeouts(); /* establishes SIGALRM handler */
778
779 pqsignal(SIGPIPE, SIG_IGN);
780 pqsignal(SIGUSR2, SIG_IGN);
781 pqsignal(SIGCHLD, SIG_DFL);
782
783 /*
784 * If an exception is encountered, processing resumes here.
785 *
786 * We just need to clean up, report the error, and go away.
787 */
788 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
789 {
790 /* Since not using PG_TRY, must reset error stack by hand */
791 error_context_stack = NULL;
792
793 /* Prevent interrupts while cleaning up */
795
796 /*
797 * sigsetjmp will have blocked all signals, but we may need to accept
798 * signals while communicating with our parallel leader. Once we've
799 * done HOLD_INTERRUPTS() it should be safe to unblock signals.
800 */
802
803 /* Report the error to the parallel leader and the server log */
805
806 /*
807 * Do we need more cleanup here? For shmem-connected bgworkers, we
808 * will call InitProcess below, which will install ProcKill as exit
809 * callback. That will take care of releasing locks, etc.
810 */
811
812 /* and go away */
813 proc_exit(1);
814 }
815
816 /* We can now handle ereport(ERROR) */
817 PG_exception_stack = &local_sigjmp_buf;
818
819 /*
820 * Create a per-backend PGPROC struct in shared memory. We must do this
821 * before we can use LWLocks or access any shared memory.
822 */
823 InitProcess();
824
825 /*
826 * Early initialization.
827 */
828 BaseInit();
829
830 /*
831 * Look up the entry point function, loading its library if necessary.
832 */
834 worker->bgw_function_name);
835
836 /*
837 * Note that in normal processes, we would call InitPostgres here. For a
838 * worker, however, we don't know what database to connect to, yet; so we
839 * need to wait until the user code does it via
840 * BackgroundWorkerInitializeConnection().
841 */
842
843 /*
844 * Now invoke the user-defined worker code
845 */
846 entrypt(worker->bgw_main_arg);
847
848 /* ... and if it returns, we're done */
849 proc_exit(0);
850}
void BackgroundWorkerUnblockSignals(void)
Definition: bgworker.c:930
static bgworker_main_type LookupBackgroundWorkerFunction(const char *libraryname, const char *funcname)
Definition: bgworker.c:1341
static void bgworker_die(SIGNAL_ARGS)
Definition: bgworker.c:707
void(* bgworker_main_type)(Datum main_arg)
Definition: bgworker.h:72
void EmitErrorReport(void)
Definition: elog.c:1704
ErrorContextCallback * error_context_stack
Definition: elog.c:95
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
#define elog(elevel,...)
Definition: elog.h:226
Assert(PointerIsAligned(start, uint64))
void proc_exit(int code)
Definition: ipc.c:104
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1229
MemoryContext TopMemoryContext
Definition: mcxt.c:166
MemoryContext PostmasterContext
Definition: mcxt.c:168
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:469
@ InitProcessing
Definition: miscadmin.h:471
#define GetProcessingMode()
Definition: miscadmin.h:481
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:134
@ B_BG_WORKER
Definition: miscadmin.h:346
BackendType MyBackendType
Definition: miscinit.c:64
#define pqsignal
Definition: port.h:531
int PostAuthDelay
Definition: postgres.c:100
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3089
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3072
void BaseInit(void)
Definition: postinit.c:607
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:674
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:285
void pg_usleep(long microsec)
Definition: signal.c:53
void InitProcess(void)
Definition: proc.c:391
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:168
#define SIGHUP
Definition: win32_port.h:158
#define SIGPIPE
Definition: win32_port.h:163
#define SIGUSR1
Definition: win32_port.h:170
#define SIGUSR2
Definition: win32_port.h:171

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(), SIGCHLD, SIGHUP, SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), and TopMemoryContext.

◆ BackgroundWorkerShmemInit()

void BackgroundWorkerShmemInit ( void  )

Definition at line 165 of file bgworker.c.

166{
167 bool found;
168
169 BackgroundWorkerData = ShmemInitStruct("Background Worker Data",
171 &found);
173 {
174 dlist_iter iter;
175 int slotno = 0;
176
180
181 /*
182 * Copy contents of worker list into shared memory. Record the shared
183 * memory slot assigned to each worker. This ensures a 1-to-1
184 * correspondence between the postmaster's private list and the array
185 * in shared memory.
186 */
188 {
191
192 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
194 slot->in_use = true;
195 slot->terminate = false;
196 slot->pid = InvalidPid;
197 slot->generation = 0;
198 rw->rw_shmem_slot = slotno;
199 rw->rw_worker.bgw_notify_pid = 0; /* might be reinit after crash */
200 memcpy(&slot->worker, &rw->rw_worker, sizeof(BackgroundWorker));
201 ++slotno;
202 }
203
204 /*
205 * Mark any remaining slots as not in use.
206 */
207 while (slotno < max_worker_processes)
208 {
210
211 slot->in_use = false;
212 ++slotno;
213 }
214 }
215 else
216 Assert(found);
217}
dlist_head BackgroundWorkerList
Definition: bgworker.c:40
static BackgroundWorkerArray * BackgroundWorkerData
Definition: bgworker.c:108
Size BackgroundWorkerShmemSize(void)
Definition: bgworker.c:149
bool IsUnderPostmaster
Definition: globals.c:120
int max_worker_processes
Definition: globals.c:144
#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 149 of file bgworker.c.

150{
151 Size size;
152
153 /* Array of workers is variably sized. */
154 size = offsetof(BackgroundWorkerArray, slot);
156 sizeof(BackgroundWorkerSlot)));
157
158 return size;
159}
size_t Size
Definition: c.h:614
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510

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

Referenced by BackgroundWorkerShmemInit(), and CalculateShmemSize().

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)

Definition at line 249 of file bgworker.c.

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

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 517 of file bgworker.c.

518{
519 dlist_iter iter;
520
522 {
524
525 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
526 if (rw->rw_worker.bgw_notify_pid == pid)
528 }
529}

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

Referenced by CleanupBackend().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_die()

static void bgworker_die ( SIGNAL_ARGS  )
static

Definition at line 707 of file bgworker.c.

708{
709 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
710
712 (errcode(ERRCODE_ADMIN_SHUTDOWN),
713 errmsg("terminating background worker \"%s\" due to administrator command",
715}

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

Referenced by BackgroundWorkerMain().

◆ FindRegisteredWorkerBySlotNumber()

static RegisteredBgWorker * FindRegisteredWorkerBySlotNumber ( int  slotno)
static

Definition at line 224 of file bgworker.c.

225{
226 dlist_iter iter;
227
229 {
231
232 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
233 if (rw->rw_shmem_slot == slotno)
234 return rw;
235 }
236
237 return NULL;
238}

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 432 of file bgworker.c.

433{
435
438 Assert(slot->in_use);
439
440 /*
441 * We need a memory barrier here to make sure that the update of
442 * parallel_terminate_count completes before the store to in_use.
443 */
446
448 slot->in_use = false;
449
451 (errmsg_internal("unregistering background worker \"%s\"",
452 rw->rw_worker.bgw_name)));
453
455 pfree(rw);
456}
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405
void pfree(void *pointer)
Definition: mcxt.c:1594

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 544 of file bgworker.c.

545{
547
549 {
552
553 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
556
557 /* If it's not yet started, and there's someone waiting ... */
558 if (slot->pid == InvalidPid &&
559 rw->rw_worker.bgw_notify_pid != 0)
560 {
561 /* ... then zap it, and notify the waiter */
562 int notify_pid = rw->rw_worker.bgw_notify_pid;
563
565 if (notify_pid != 0)
566 kill(notify_pid, SIGUSR1);
567 }
568 }
569}
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition: bgworker.c:432
#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 1161 of file bgworker.c.

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

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 1375 of file bgworker.c.

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

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 1341 of file bgworker.c.

1342{
1343 /*
1344 * If the function is to be loaded from postgres itself, search the
1345 * InternalBGWorkers array.
1346 */
1347 if (strcmp(libraryname, "postgres") == 0)
1348 {
1349 int i;
1350
1351 for (i = 0; i < lengthof(InternalBGWorkers); i++)
1352 {
1353 if (strcmp(InternalBGWorkers[i].fn_name, funcname) == 0)
1354 return InternalBGWorkers[i].fn_addr;
1355 }
1356
1357 /* We can only reach this by programming error. */
1358 elog(ERROR, "internal function \"%s\" not found", funcname);
1359 }
1360
1361 /* Otherwise load from external library. */
1362 return (bgworker_main_type)
1363 load_external_function(libraryname, funcname, true, NULL);
1364}
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:791
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:95
#define funcname
Definition: indent_codes.h:69
int i
Definition: isn.c:77

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 943 of file bgworker.c.

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

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 1049 of file bgworker.c.

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

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 486 of file bgworker.c.

487{
489 int notify_pid;
490
493 slot->pid = rw->rw_pid;
494 notify_pid = rw->rw_worker.bgw_notify_pid;
495
496 /*
497 * If this worker is slated for deregistration, do that before notifying
498 * the process which started it. Otherwise, if that process tries to
499 * reuse the slot immediately, it might not be available yet. In theory
500 * that could happen anyway if the process checks slot->pid at just the
501 * wrong moment, but this makes the window narrower.
502 */
503 if (rw->rw_terminate ||
506
507 if (notify_pid != 0)
508 kill(notify_pid, SIGUSR1);
509}
#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 582 of file bgworker.c.

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

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, RegisteredBgWorker::rw_pid, and RegisteredBgWorker::rw_worker.

Referenced by PostmasterStateMachine().

◆ SanityCheckBackgroundWorker()

static bool SanityCheckBackgroundWorker ( BackgroundWorker worker,
int  elevel 
)
static

Definition at line 635 of file bgworker.c.

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

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

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 1261 of file bgworker.c.

1262{
1263 BgwHandleStatus status;
1264 int rc;
1265
1266 for (;;)
1267 {
1268 pid_t pid;
1269
1271
1272 status = GetBackgroundWorkerPid(handle, &pid);
1273 if (status == BGWH_STOPPED)
1274 break;
1275
1276 rc = WaitLatch(MyLatch,
1278 WAIT_EVENT_BGWORKER_SHUTDOWN);
1279
1280 if (rc & WL_POSTMASTER_DEATH)
1281 {
1282 status = BGWH_POSTMASTER_DIED;
1283 break;
1284 }
1285
1287 }
1288
1289 return status;
1290}
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1161
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_POSTMASTER_DIED
Definition: bgworker.h:108
struct Latch * MyLatch
Definition: globals.c:63
void ResetLatch(Latch *latch)
Definition: latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:172
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
#define WL_LATCH_SET
Definition: waiteventset.h:34
#define WL_POSTMASTER_DEATH
Definition: waiteventset.h:38

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 1216 of file bgworker.c.

1217{
1218 BgwHandleStatus status;
1219 int rc;
1220
1221 for (;;)
1222 {
1223 pid_t pid;
1224
1226
1227 status = GetBackgroundWorkerPid(handle, &pid);
1228 if (status == BGWH_STARTED)
1229 *pidp = pid;
1230 if (status != BGWH_NOT_YET_STARTED)
1231 break;
1232
1233 rc = WaitLatch(MyLatch,
1235 WAIT_EVENT_BGWORKER_STARTUP);
1236
1237 if (rc & WL_POSTMASTER_DEATH)
1238 {
1239 status = BGWH_POSTMASTER_DIED;
1240 break;
1241 }
1242
1244 }
1245
1246 return status;
1247}

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 struct { ... } InternalBGWorkers[]
Initial value:
=
{
{
"ParallelWorkerMain", ParallelWorkerMain
},
{
"ApplyLauncherMain", ApplyLauncherMain
},
{
"ApplyWorkerMain", ApplyWorkerMain
},
{
"ParallelApplyWorkerMain", ParallelApplyWorkerMain
},
{
"TableSyncWorkerMain", TableSyncWorkerMain
},
{
"SequenceSyncWorkerMain", SequenceSyncWorkerMain
}
}
void ParallelApplyWorkerMain(Datum main_arg)
void ParallelWorkerMain(Datum main_arg)
Definition: parallel.c:1292
void ApplyWorkerMain(Datum main_arg)
Definition: worker.c:5922
void ApplyLauncherMain(Datum main_arg)
Definition: launcher.c:1204
void SequenceSyncWorkerMain(Datum main_arg)
Definition: sequencesync.c:736
void TableSyncWorkerMain(Datum main_arg)
Definition: tablesync.c:1578

Referenced by LookupBackgroundWorkerFunction().