PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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/procarray.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 "utils/wait_event.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)
 
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 charGetBackgroundWorkerTypeByPid (pid_t pid)
 
void TerminateBackgroundWorkersForDatabase (Oid databaseId)
 

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

930{
932}
sigset_t BlockSig
Definition pqsignal.c:23
static int fb(int x)

References BlockSig, and fb().

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 861 of file bgworker.c.

862{
864 bits32 init_flags = 0; /* never honor session_preload_libraries */
865
866 /* ignore datallowconn and ACL_CONNECT? */
867 if (flags & BGWORKER_BYPASS_ALLOWCONN)
869 /* ignore rolcanlogin? */
872
873 /* XXX is this the right errcode? */
877 errmsg("database connection requirement not indicated during registration")));
878
879 InitPostgres(dbname, InvalidOid, /* database to connect to */
880 username, InvalidOid, /* role to connect as */
882 NULL); /* no out_dbname */
883
884 /* it had better not gotten out of "init" mode yet */
887 (errmsg("invalid processing mode in background worker")));
889}
#define BGWORKER_BYPASS_ROLELOGINCHECK
Definition bgworker.h:167
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition bgworker.h:166
uint32 bits32
Definition c.h:627
int errcode(int sqlerrcode)
Definition elog.c:874
#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
static char * errmsg
#define InvalidOid
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:719
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, fb(), 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 895 of file bgworker.c.

896{
898 bits32 init_flags = 0; /* never honor session_preload_libraries */
899
900 /* ignore datallowconn and ACL_CONNECT? */
901 if (flags & BGWORKER_BYPASS_ALLOWCONN)
903 /* ignore rolcanlogin? */
906
907 /* XXX is this the right errcode? */
911 errmsg("database connection requirement not indicated during registration")));
912
913 InitPostgres(NULL, dboid, /* database to connect to */
914 NULL, useroid, /* role to connect as */
916 NULL); /* no out_dbname */
917
918 /* it had better not gotten out of "init" mode yet */
921 (errmsg("invalid processing mode in background worker")));
923}

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, ereport, errcode(), errmsg, ERROR, FATAL, fb(), 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 727 of file bgworker.c.

728{
730 BackgroundWorker *worker;
732
733 if (startup_data == NULL)
734 elog(FATAL, "unable to find bgworker entry");
737 memcpy(worker, startup_data, sizeof(BackgroundWorker));
738
739 /*
740 * Now that we're done reading the startup data, release postmaster's
741 * working memory context.
742 */
744 {
747 }
748
749 MyBgworkerEntry = worker;
750 init_ps_display(worker->bgw_name);
751
753
754 /* Apply PostAuthDelay */
755 if (PostAuthDelay > 0)
756 pg_usleep(PostAuthDelay * 1000000L);
757
758 /*
759 * Set up signal handlers.
760 */
762 {
763 /*
764 * SIGINT is used to signal canceling the current action
765 */
769
770 /* XXX Any other handlers needed here? */
771 }
772 else
773 {
777 }
779 /* SIGQUIT handler was already set up by InitPostmasterChild */
781
782 InitializeTimeouts(); /* establishes SIGALRM handler */
783
787
788 /*
789 * If an exception is encountered, processing resumes here.
790 *
791 * We just need to clean up, report the error, and go away.
792 */
793 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
794 {
795 /* Since not using PG_TRY, must reset error stack by hand */
797
798 /* Prevent interrupts while cleaning up */
800
801 /*
802 * sigsetjmp will have blocked all signals, but we may need to accept
803 * signals while communicating with our parallel leader. Once we've
804 * done HOLD_INTERRUPTS() it should be safe to unblock signals.
805 */
807
808 /* Report the error to the parallel leader and the server log */
810
811 /*
812 * Do we need more cleanup here? For shmem-connected bgworkers, we
813 * will call InitProcess below, which will install ProcKill as exit
814 * callback. That will take care of releasing locks, etc.
815 */
816
817 /* and go away */
818 proc_exit(1);
819 }
820
821 /* We can now handle ereport(ERROR) */
823
824 /*
825 * Create a per-backend PGPROC struct in shared memory. We must do this
826 * before we can use LWLocks or access any shared memory.
827 */
828 InitProcess();
829
830 /*
831 * Early initialization.
832 */
833 BaseInit();
834
835 /*
836 * Look up the entry point function, loading its library if necessary.
837 */
839 worker->bgw_function_name);
840
841 /*
842 * Note that in normal processes, we would call InitPostgres here. For a
843 * worker, however, we don't know what database to connect to, yet; so we
844 * need to wait until the user code does it via
845 * BackgroundWorkerInitializeConnection().
846 */
847
848 /*
849 * Now invoke the user-defined worker code
850 */
851 entrypt(worker->bgw_main_arg);
852
853 /* ... and if it returns, we're done */
854 proc_exit(0);
855}
void BackgroundWorkerUnblockSignals(void)
Definition bgworker.c:935
static bgworker_main_type LookupBackgroundWorkerFunction(const char *libraryname, const char *funcname)
Definition bgworker.c:1346
void(* bgworker_main_type)(Datum main_arg)
Definition bgworker.h:79
#define Assert(condition)
Definition c.h:945
void EmitErrorReport(void)
Definition elog.c:1882
ErrorContextCallback * error_context_stack
Definition elog.c:99
sigjmp_buf * PG_exception_stack
Definition elog.c:101
#define elog(elevel,...)
Definition elog.h:226
void proc_exit(int code)
Definition ipc.c:105
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition mcxt.c:1232
MemoryContext TopMemoryContext
Definition mcxt.c:166
MemoryContext PostmasterContext
Definition mcxt.c:168
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
@ InitProcessing
Definition miscadmin.h:471
#define GetProcessingMode()
Definition miscadmin.h:481
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
#define die(msg)
#define pqsignal
Definition port.h:547
int PostAuthDelay
Definition postgres.c:102
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3059
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3042
void BaseInit(void)
Definition postinit.c:616
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:680
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:381
char bgw_function_name[BGW_MAXLEN]
Definition bgworker.h:104
char bgw_name[BGW_MAXLEN]
Definition bgworker.h:98
char bgw_library_name[MAXPGPATH]
Definition bgworker.h:103
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, BackgroundWorkerUnblockSignals(), BaseInit(), BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_main_arg, BackgroundWorker::bgw_name, BGWORKER_BACKEND_DATABASE_CONNECTION, die, elog, EmitErrorReport(), error_context_stack, FATAL, fb(), FloatExceptionHandler(), GetProcessingMode, HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitProcess(), InitProcessing, LookupBackgroundWorkerFunction(), MemoryContextAlloc(), MemoryContextDelete(), 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 174 of file bgworker.c.

175{
176 bool found;
177
178 BackgroundWorkerData = ShmemInitStruct("Background Worker Data",
180 &found);
182 {
183 dlist_iter iter;
184 int slotno = 0;
185
189
190 /*
191 * Copy contents of worker list into shared memory. Record the shared
192 * memory slot assigned to each worker. This ensures a 1-to-1
193 * correspondence between the postmaster's private list and the array
194 * in shared memory.
195 */
197 {
200
201 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
203 slot->in_use = true;
204 slot->terminate = false;
205 slot->pid = InvalidPid;
206 slot->generation = 0;
207 rw->rw_shmem_slot = slotno;
208 rw->rw_worker.bgw_notify_pid = 0; /* might be reinit after crash */
209 memcpy(&slot->worker, &rw->rw_worker, sizeof(BackgroundWorker));
210 ++slotno;
211 }
212
213 /*
214 * Mark any remaining slots as not in use.
215 */
217 {
219
220 slot->in_use = false;
221 ++slotno;
222 }
223 }
224 else
225 Assert(found);
226}
dlist_head BackgroundWorkerList
Definition bgworker.c:42
static BackgroundWorkerArray * BackgroundWorkerData
Definition bgworker.c:110
Size BackgroundWorkerShmemSize(void)
Definition bgworker.c:158
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:380
uint32 parallel_terminate_count
Definition bgworker.c:100
uint32 parallel_register_count
Definition bgworker.c:99
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition bgworker.c:101
BackgroundWorker worker
Definition bgworker.c:82
pid_t bgw_notify_pid
Definition bgworker.h:107
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, fb(), 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 158 of file bgworker.c.

159{
160 Size size;
161
162 /* Array of workers is variably sized. */
163 size = offsetof(BackgroundWorkerArray, slot);
165 sizeof(BackgroundWorkerSlot)));
166
167 return size;
168}
size_t Size
Definition c.h:691
Size add_size(Size s1, Size s2)
Definition shmem.c:455
Size mul_size(Size s1, Size s2)
Definition shmem.c:470

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

Referenced by BackgroundWorkerShmemInit(), and CalculateShmemSize().

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)

Definition at line 258 of file bgworker.c.

259{
260 int slotno;
261
262 /*
263 * The total number of slots stored in shared memory should match our
264 * notion of max_worker_processes. If it does not, something is very
265 * wrong. Further down, we always refer to this value as
266 * max_worker_processes, in case shared memory gets corrupted while we're
267 * looping.
268 */
270 {
271 ereport(LOG,
272 (errmsg("inconsistent background worker state (\"max_worker_processes\"=%d, total slots=%d)",
275 return;
276 }
277
278 /*
279 * Iterate through slots, looking for newly-registered workers or workers
280 * who must die.
281 */
283 {
286
287 if (!slot->in_use)
288 continue;
289
290 /*
291 * Make sure we don't see the in_use flag before the updated slot
292 * contents.
293 */
295
296 /* See whether we already know about this worker. */
298 if (rw != NULL)
299 {
300 /*
301 * In general, the worker data can't change after it's initially
302 * registered. However, someone can set the terminate flag.
303 */
304 if (slot->terminate && !rw->rw_terminate)
305 {
306 rw->rw_terminate = true;
307 if (rw->rw_pid != 0)
308 kill(rw->rw_pid, SIGTERM);
309 else
310 {
311 /* Report never-started, now-terminated worker as dead. */
313 }
314 }
315 continue;
316 }
317
318 /*
319 * If we aren't allowing new workers, then immediately mark it for
320 * termination; the next stanza will take care of cleaning it up.
321 * Doing this ensures that any process waiting for the worker will get
322 * awoken, even though the worker will never be allowed to run.
323 */
325 slot->terminate = true;
326
327 /*
328 * If the worker is marked for termination, we don't need to add it to
329 * the registered workers list; we can just free the slot. However, if
330 * bgw_notify_pid is set, the process that registered the worker may
331 * need to know that we've processed the terminate request, so be sure
332 * to signal it.
333 */
334 if (slot->terminate)
335 {
336 int notify_pid;
337
338 /*
339 * We need a memory barrier here to make sure that the load of
340 * bgw_notify_pid and the update of parallel_terminate_count
341 * complete before the store to in_use.
342 */
344 if ((slot->worker.bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
346 slot->pid = 0;
347
349 slot->in_use = false;
350
351 if (notify_pid != 0)
353
354 continue;
355 }
356
357 /*
358 * Copy the registration data into the registered workers list.
359 */
361 sizeof(RegisteredBgWorker),
363 if (rw == NULL)
364 {
365 ereport(LOG,
367 errmsg("out of memory")));
368 return;
369 }
370
371 /*
372 * Copy strings in a paranoid way. If shared memory is corrupted, the
373 * source data might not even be NUL-terminated.
374 */
376 slot->worker.bgw_name, BGW_MAXLEN);
378 slot->worker.bgw_type, BGW_MAXLEN);
383
384 /*
385 * Copy various fixed-size fields.
386 *
387 * flags, start_time, and restart_time are examined by the postmaster,
388 * but nothing too bad will happen if they are corrupted. The
389 * remaining fields will only be examined by the child process. It
390 * might crash, but we won't.
391 */
397
398 /*
399 * Copy the PID to be notified about state changes, but only if the
400 * postmaster knows about a backend with that PID. It isn't an error
401 * if the postmaster doesn't know about the PID, because the backend
402 * that requested the worker could have died (or been killed) just
403 * after doing so. Nonetheless, at least until we get some experience
404 * with how this plays out in the wild, log a message at a relative
405 * high debug level.
406 */
409 {
410 elog(DEBUG1, "worker notification PID %d is not valid",
411 (int) rw->rw_worker.bgw_notify_pid);
413 }
414
415 /* Initialize postmaster bookkeeping. */
416 rw->rw_pid = 0;
417 rw->rw_crashed_at = 0;
418 rw->rw_shmem_slot = slotno;
419 rw->rw_terminate = false;
420
421 /* Log it! */
423 (errmsg_internal("registering background worker \"%s\"",
424 rw->rw_worker.bgw_name)));
425
427 }
428}
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:473
static RegisteredBgWorker * FindRegisteredWorkerBySlotNumber(int slotno)
Definition bgworker.c:233
#define BGW_EXTRALEN
Definition bgworker.h:94
#define BGWORKER_CLASS_PARALLEL
Definition bgworker.h:75
#define BGW_MAXLEN
Definition bgworker.h:93
#define LOG
Definition elog.h:31
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#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:1289
#define MAXPGPATH
bool PostmasterMarkPIDForWorkerNotify(int pid)
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
BgWorkerStartTime bgw_start_time
Definition bgworker.h:101
char bgw_extra[BGW_EXTRALEN]
Definition bgworker.h:106
#define kill(pid, sig)
Definition win32_port.h:490

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(), fb(), 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 526 of file bgworker.c.

527{
528 dlist_iter iter;
529
531 {
533
534 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
535 if (rw->rw_worker.bgw_notify_pid == pid)
537 }
538}

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

Referenced by CleanupBackend().

◆ BackgroundWorkerUnblockSignals()

◆ FindRegisteredWorkerBySlotNumber()

static RegisteredBgWorker * FindRegisteredWorkerBySlotNumber ( int  slotno)
static

Definition at line 233 of file bgworker.c.

234{
235 dlist_iter iter;
236
238 {
240
241 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
242 if (rw->rw_shmem_slot == slotno)
243 return rw;
244 }
245
246 return NULL;
247}

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

Referenced by BackgroundWorkerStateChange().

◆ ForgetBackgroundWorker()

void ForgetBackgroundWorker ( RegisteredBgWorker rw)

Definition at line 441 of file bgworker.c.

442{
444
447 Assert(slot->in_use);
448
449 /*
450 * We need a memory barrier here to make sure that the update of
451 * parallel_terminate_count completes before the store to in_use.
452 */
455
457 slot->in_use = false;
458
460 (errmsg_internal("unregistering background worker \"%s\"",
461 rw->rw_worker.bgw_name)));
462
464 pfree(rw);
465}
static void dlist_delete(dlist_node *node)
Definition ilist.h:405
void pfree(void *pointer)
Definition mcxt.c:1616

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

554{
556
558 {
561
562 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
565
566 /* If it's not yet started, and there's someone waiting ... */
567 if (slot->pid == InvalidPid &&
568 rw->rw_worker.bgw_notify_pid != 0)
569 {
570 /* ... then zap it, and notify the waiter */
572
574 if (notify_pid != 0)
576 }
577 }
578}
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition bgworker.c:441
#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, fb(), 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 1166 of file bgworker.c.

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

References Assert, BackgroundWorkerData, BGWH_NOT_YET_STARTED, BGWH_STARTED, BGWH_STOPPED, fb(), 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 1380 of file bgworker.c.

1381{
1382 int slotno;
1383 bool found = false;
1384 static char result[BGW_MAXLEN];
1385
1387
1389 {
1391
1392 if (slot->pid > 0 && slot->pid == pid)
1393 {
1394 strcpy(result, slot->worker.bgw_type);
1395 found = true;
1396 break;
1397 }
1398 }
1399
1401
1402 if (!found)
1403 return NULL;
1404
1405 return result;
1406}

References BackgroundWorkerData, BGW_MAXLEN, BackgroundWorker::bgw_type, fb(), 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 1346 of file bgworker.c.

1347{
1348 /*
1349 * If the function is to be loaded from postgres itself, search the
1350 * InternalBGWorkers array.
1351 */
1352 if (strcmp(libraryname, "postgres") == 0)
1353 {
1354 int i;
1355
1356 for (i = 0; i < lengthof(InternalBGWorkers); i++)
1357 {
1359 return InternalBGWorkers[i].fn_addr;
1360 }
1361
1362 /* We can only reach this by programming error. */
1363 elog(ERROR, "internal function \"%s\" not found", funcname);
1364 }
1365
1366 /* Otherwise load from external library. */
1367 return (bgworker_main_type)
1369}
static const struct @18 InternalBGWorkers[]
const char * fn_name
Definition bgworker.c:118
bgworker_main_type fn_addr
Definition bgworker.c:119
#define lengthof(array)
Definition c.h:875
void * load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition dfmgr.c:95
#define funcname
int i
Definition isn.c:77

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

Referenced by BackgroundWorkerMain().

◆ RegisterBackgroundWorker()

void RegisterBackgroundWorker ( BackgroundWorker worker)

Definition at line 948 of file bgworker.c.

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

References BackgroundWorkerData, BackgroundWorkerList, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, DEBUG1, dlist_push_head(), elog, ereport, errcode(), errdetail_plural(), errhint(), errmsg, errmsg_internal(), ERROR, fb(), 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 1054 of file bgworker.c.

1056{
1057 int slotno;
1058 bool success = false;
1059 bool parallel;
1060 uint64 generation = 0;
1061
1062 /*
1063 * We can't register dynamic background workers from the postmaster. If
1064 * this is a standalone backend, we're the only process and can't start
1065 * any more. In a multi-process environment, it might be theoretically
1066 * possible, but we don't currently support it due to locking
1067 * considerations; see comments on the BackgroundWorkerSlot data
1068 * structure.
1069 */
1070 if (!IsUnderPostmaster)
1071 return false;
1072
1073 if (!SanityCheckBackgroundWorker(worker, ERROR))
1074 return false;
1075
1076 parallel = (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0;
1077
1079
1080 /*
1081 * If this is a parallel worker, check whether there are already too many
1082 * parallel workers; if so, don't register another one. Our view of
1083 * parallel_terminate_count may be slightly stale, but that doesn't really
1084 * matter: we would have gotten the same result if we'd arrived here
1085 * slightly earlier anyway. There's no help for it, either, since the
1086 * postmaster must not take locks; a memory barrier wouldn't guarantee
1087 * anything useful.
1088 */
1092 {
1097 return false;
1098 }
1099
1100 /*
1101 * Look for an unused slot. If we find one, grab it.
1102 */
1104 {
1106
1107 if (!slot->in_use)
1108 {
1109 memcpy(&slot->worker, worker, sizeof(BackgroundWorker));
1110 slot->pid = InvalidPid; /* indicates not started yet */
1111 slot->generation++;
1112 slot->terminate = false;
1113 generation = slot->generation;
1114 if (parallel)
1116
1117 /*
1118 * Make sure postmaster doesn't see the slot as in use before it
1119 * sees the new contents.
1120 */
1122
1123 slot->in_use = true;
1124 success = true;
1125 break;
1126 }
1127 }
1128
1130
1131 /* If we found a slot, tell the postmaster to notice the change. */
1132 if (success)
1134
1135 /*
1136 * If we found a slot and the user has provided a handle, initialize it.
1137 */
1138 if (success && handle)
1139 {
1141 (*handle)->slot = slotno;
1142 (*handle)->generation = generation;
1143 }
1144
1145 return success;
1146}
#define pg_write_barrier()
Definition atomics.h:155
#define MAX_PARALLEL_WORKER_LIMIT
uint64_t uint64
Definition c.h:619
#define palloc_object(type)
Definition fe_memutils.h:74
int max_parallel_workers
Definition globals.c:145
static bool success
Definition initdb.c:188
@ LW_EXCLUSIVE
Definition lwlock.h:104
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, fb(), BackgroundWorkerSlot::generation, BackgroundWorkerSlot::in_use, InvalidPid, IsUnderPostmaster, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAX_PARALLEL_WORKER_LIMIT, max_parallel_workers, palloc_object, 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 495 of file bgworker.c.

496{
498 int notify_pid;
499
502 slot->pid = rw->rw_pid;
504
505 /*
506 * If this worker is slated for deregistration, do that before notifying
507 * the process which started it. Otherwise, if that process tries to
508 * reuse the slot immediately, it might not be available yet. In theory
509 * that could happen anyway if the process checks slot->pid at just the
510 * wrong moment, but this makes the window narrower.
511 */
512 if (rw->rw_terminate ||
515
516 if (notify_pid != 0)
518}
#define BGW_NEVER_RESTART
Definition bgworker.h:92

References Assert, BackgroundWorkerData, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, fb(), 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 591 of file bgworker.c.

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

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

645{
646 /* sanity check for flags */
647
648 /*
649 * We used to support workers not connected to shared memory, but don't
650 * anymore. Thus this is a required flag now. We're not removing the flag
651 * for compatibility reasons and because the flag still provides some
652 * signal when reading code.
653 */
654 if (!(worker->bgw_flags & BGWORKER_SHMEM_ACCESS))
655 {
656 ereport(elevel,
658 errmsg("background worker \"%s\": background workers without shared memory access are not supported",
659 worker->bgw_name)));
660 return false;
661 }
662
664 {
666 {
667 ereport(elevel,
669 errmsg("background worker \"%s\": cannot request database access if starting at postmaster start",
670 worker->bgw_name)));
671 return false;
672 }
673
674 /* XXX other checks? */
675 }
676
677 /* Interruptible workers require a database connection */
678 if ((worker->bgw_flags & BGWORKER_INTERRUPTIBLE) &&
680 {
681 ereport(elevel,
683 errmsg("background worker \"%s\": cannot make background workers interruptible without database access",
684 worker->bgw_name)));
685 return false;
686 }
687
688 if ((worker->bgw_restart_time < 0 &&
690 (worker->bgw_restart_time > USECS_PER_DAY / 1000))
691 {
692 ereport(elevel,
694 errmsg("background worker \"%s\": invalid restart interval",
695 worker->bgw_name)));
696 return false;
697 }
698
699 /*
700 * Parallel workers may not be configured for restart, because the
701 * parallel_register_count/parallel_terminate_count accounting can't
702 * handle parallel workers lasting through a crash-and-restart cycle.
703 */
704 if (worker->bgw_restart_time != BGW_NEVER_RESTART &&
705 (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
706 {
707 ereport(elevel,
709 errmsg("background worker \"%s\": parallel workers may not be configured for restart",
710 worker->bgw_name)));
711 return false;
712 }
713
714 /*
715 * If bgw_type is not filled in, use bgw_name.
716 */
717 if (strcmp(worker->bgw_type, "") == 0)
718 strcpy(worker->bgw_type, worker->bgw_name);
719
720 return true;
721}
#define BGWORKER_INTERRUPTIBLE
Definition bgworker.h:67
@ BgWorkerStart_PostmasterStart
Definition bgworker.h:86
#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_INTERRUPTIBLE, BGWORKER_SHMEM_ACCESS, BgWorkerStart_PostmasterStart, ereport, errcode(), errmsg, fb(), and USECS_PER_DAY.

Referenced by RegisterBackgroundWorker(), and RegisterDynamicBackgroundWorker().

◆ TerminateBackgroundWorker()

void TerminateBackgroundWorker ( BackgroundWorkerHandle handle)

Definition at line 1305 of file bgworker.c.

1306{
1308 bool signal_postmaster = false;
1309
1310 Assert(handle->slot < max_worker_processes);
1311 slot = &BackgroundWorkerData->slot[handle->slot];
1312
1313 /* Set terminate flag in shared memory, unless slot has been reused. */
1315 if (handle->generation == slot->generation)
1316 {
1317 slot->terminate = true;
1318 signal_postmaster = true;
1319 }
1321
1322 /* Make sure the postmaster notices the change to shared memory. */
1325}

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

◆ TerminateBackgroundWorkersForDatabase()

void TerminateBackgroundWorkersForDatabase ( Oid  databaseId)

Definition at line 1413 of file bgworker.c.

1414{
1415 bool signal_postmaster = false;
1416
1417 elog(DEBUG1, "attempting worker termination for database %u",
1418 databaseId);
1419
1421
1422 /*
1423 * Iterate through slots, looking for workers connected to the given
1424 * database.
1425 */
1427 {
1429
1430 if (slot->in_use &&
1432 {
1433 PGPROC *proc = BackendPidGetProc(slot->pid);
1434
1435 if (proc && proc->databaseId == databaseId)
1436 {
1437 slot->terminate = true;
1438 signal_postmaster = true;
1439
1440 elog(DEBUG1, "termination requested for worker (PID %d) on database %u",
1441 (int) slot->pid, databaseId);
1442 }
1443 }
1444 }
1445
1447
1448 /* Make sure the postmaster notices the change to shared memory. */
1451}
PGPROC * BackendPidGetProc(int pid)
Definition procarray.c:3156
Definition proc.h:178
Oid databaseId
Definition proc.h:200

References BackendPidGetProc(), BackgroundWorkerData, BackgroundWorker::bgw_flags, BGWORKER_INTERRUPTIBLE, PGPROC::databaseId, DEBUG1, elog, fb(), BackgroundWorkerSlot::in_use, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), BackgroundWorkerSlot::pid, PMSIGNAL_BACKGROUND_WORKER_CHANGE, SendPostmasterSignal(), BackgroundWorkerArray::slot, BackgroundWorkerSlot::terminate, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

Referenced by CountOtherDBBackends().

◆ WaitForBackgroundWorkerShutdown()

BgwHandleStatus WaitForBackgroundWorkerShutdown ( BackgroundWorkerHandle handle)

Definition at line 1266 of file bgworker.c.

1267{
1268 BgwHandleStatus status;
1269 int rc;
1270
1271 for (;;)
1272 {
1273 pid_t pid;
1274
1276
1277 status = GetBackgroundWorkerPid(handle, &pid);
1278 if (status == BGWH_STOPPED)
1279 break;
1280
1281 rc = WaitLatch(MyLatch,
1284
1285 if (rc & WL_POSTMASTER_DEATH)
1286 {
1287 status = BGWH_POSTMASTER_DIED;
1288 break;
1289 }
1290
1292 }
1293
1294 return status;
1295}
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition bgworker.c:1166
BgwHandleStatus
Definition bgworker.h:111
@ BGWH_POSTMASTER_DIED
Definition bgworker.h:115
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
#define WL_POSTMASTER_DEATH

References BGWH_POSTMASTER_DIED, BGWH_STOPPED, CHECK_FOR_INTERRUPTS, fb(), 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 1221 of file bgworker.c.

1222{
1223 BgwHandleStatus status;
1224 int rc;
1225
1226 for (;;)
1227 {
1228 pid_t pid;
1229
1231
1232 status = GetBackgroundWorkerPid(handle, &pid);
1233 if (status == BGWH_STARTED)
1234 *pidp = pid;
1235 if (status != BGWH_NOT_YET_STARTED)
1236 break;
1237
1238 rc = WaitLatch(MyLatch,
1241
1242 if (rc & WL_POSTMASTER_DEATH)
1243 {
1244 status = BGWH_POSTMASTER_DIED;
1245 break;
1246 }
1247
1249 }
1250
1251 return status;
1252}

References BGWH_NOT_YET_STARTED, BGWH_POSTMASTER_DIED, BGWH_STARTED, CHECK_FOR_INTERRUPTS, fb(), 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 119 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 118 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ [struct]

const struct { ... } InternalBGWorkers[]
Initial value:
=
{
{
.fn_name = "ApplyLauncherMain",
.fn_addr = ApplyLauncherMain
},
{
.fn_name = "ApplyWorkerMain",
.fn_addr = ApplyWorkerMain
},
{
.fn_name = "ParallelApplyWorkerMain",
},
{
.fn_name = "ParallelWorkerMain",
.fn_addr = ParallelWorkerMain
},
{
.fn_name = "SequenceSyncWorkerMain",
},
{
.fn_name = "TableSyncWorkerMain",
},
}
void ParallelApplyWorkerMain(Datum main_arg)
void ParallelWorkerMain(Datum main_arg)
Definition parallel.c:1301
void ApplyWorkerMain(Datum main_arg)
Definition worker.c:5986
void ApplyLauncherMain(Datum main_arg)
Definition launcher.c:1205
void SequenceSyncWorkerMain(Datum main_arg)
void TableSyncWorkerMain(Datum main_arg)
Definition tablesync.c:1577

Referenced by LookupBackgroundWorkerFunction().