PostgreSQL Source Code git master
Loading...
Searching...
No Matches
bgworker.c File Reference
#include "postgres.h"
#include "access/parallel.h"
#include "commands/repack.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/datachecksum_state.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 "storage/subsystems.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 void BackgroundWorkerShmemRequest (void *arg)
 
static void BackgroundWorkerShmemInit (void *arg)
 
static bgworker_main_type LookupBackgroundWorkerFunction (const char *libraryname, const char *funcname)
 
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
 
const ShmemCallbacks BackgroundWorkerShmemCallbacks
 
struct { 
 
   const char *   fn_name 
 
   bgworker_main_type   fn_addr 
 
InternalBGWorkers [] 
 

Typedef Documentation

◆ BackgroundWorkerArray

◆ BackgroundWorkerSlot

Function Documentation

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 943 of file bgworker.c.

944{
946}
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 875 of file bgworker.c.

876{
878 uint32 init_flags = 0; /* never honor session_preload_libraries */
879
880 /* ignore datallowconn and ACL_CONNECT? */
881 if (flags & BGWORKER_BYPASS_ALLOWCONN)
883 /* ignore rolcanlogin? */
886
887 /* XXX is this the right errcode? */
891 errmsg("database connection requirement not indicated during registration")));
892
893 InitPostgres(dbname, InvalidOid, /* database to connect to */
894 username, InvalidOid, /* role to connect as */
896 NULL); /* no out_dbname */
897
898 /* it had better not gotten out of "init" mode yet */
901 (errmsg("invalid processing mode in background worker")));
903}
#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_t uint32
Definition c.h:624
int errcode(int sqlerrcode)
Definition elog.c:875
#define FATAL
Definition elog.h:42
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
static char * username
Definition initdb.c:153
@ NormalProcessing
Definition miscadmin.h:490
#define IsInitProcessingMode()
Definition miscadmin.h:496
#define SetProcessingMode(mode)
Definition miscadmin.h:501
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition miscadmin.h:519
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition miscadmin.h:518
static char * errmsg
#define InvalidOid
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:719
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:201
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 909 of file bgworker.c.

910{
912 uint32 init_flags = 0; /* never honor session_preload_libraries */
913
914 /* ignore datallowconn and ACL_CONNECT? */
915 if (flags & BGWORKER_BYPASS_ALLOWCONN)
917 /* ignore rolcanlogin? */
920
921 /* XXX is this the right errcode? */
925 errmsg("database connection requirement not indicated during registration")));
926
927 InitPostgres(NULL, dboid, /* database to connect to */
928 NULL, useroid, /* role to connect as */
930 NULL); /* no out_dbname */
931
932 /* it had better not gotten out of "init" mode yet */
935 (errmsg("invalid processing mode in background worker")));
937}

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(), DataChecksumsWorkerLauncherMain(), DataChecksumsWorkerMain(), InitializeLogRepWorker(), ParallelWorkerMain(), RepackWorkerMain(), and worker_spi_main().

◆ BackgroundWorkerMain()

void BackgroundWorkerMain ( const void startup_data,
size_t  startup_data_len 
)

Definition at line 741 of file bgworker.c.

742{
744 BackgroundWorker *worker;
746
747 if (startup_data == NULL)
748 elog(FATAL, "unable to find bgworker entry");
751 memcpy(worker, startup_data, sizeof(BackgroundWorker));
752
753 /*
754 * Now that we're done reading the startup data, release postmaster's
755 * working memory context.
756 */
758 {
761 }
762
763 MyBgworkerEntry = worker;
764 init_ps_display(worker->bgw_name);
765
767
768 /* Apply PostAuthDelay */
769 if (PostAuthDelay > 0)
770 pg_usleep(PostAuthDelay * 1000000L);
771
772 /*
773 * Set up signal handlers.
774 */
776 {
777 /*
778 * SIGINT is used to signal canceling the current action
779 */
783
784 /* XXX Any other handlers needed here? */
785 }
786 else
787 {
791 }
793 /* SIGQUIT handler was already set up by InitPostmasterChild */
795
796 InitializeTimeouts(); /* establishes SIGALRM handler */
797
801
802 /*
803 * If an exception is encountered, processing resumes here.
804 *
805 * We just need to clean up, report the error, and go away.
806 */
807 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
808 {
809 /* Since not using PG_TRY, must reset error stack by hand */
811
812 /* Prevent interrupts while cleaning up */
814
815 /*
816 * sigsetjmp will have blocked all signals, but we may need to accept
817 * signals while communicating with our parallel leader. Once we've
818 * done HOLD_INTERRUPTS() it should be safe to unblock signals.
819 */
821
822 /* Report the error to the parallel leader and the server log */
824
825 /*
826 * Do we need more cleanup here? For shmem-connected bgworkers, we
827 * will call InitProcess below, which will install ProcKill as exit
828 * callback. That will take care of releasing locks, etc.
829 */
830
831 /* and go away */
832 proc_exit(1);
833 }
834
835 /* We can now handle ereport(ERROR) */
837
838 /*
839 * Create a per-backend PGPROC struct in shared memory. We must do this
840 * before we can use LWLocks or access any shared memory.
841 */
842 InitProcess();
843
844 /*
845 * Early initialization.
846 */
847 BaseInit();
848
849 /*
850 * Look up the entry point function, loading its library if necessary.
851 */
853 worker->bgw_function_name);
854
855 /*
856 * Note that in normal processes, we would call InitPostgres here. For a
857 * worker, however, we don't know what database to connect to, yet; so we
858 * need to wait until the user code does it via
859 * BackgroundWorkerInitializeConnection().
860 */
861
862 /*
863 * Now invoke the user-defined worker code
864 */
865 entrypt(worker->bgw_main_arg);
866
867 /* ... and if it returns, we're done */
868 proc_exit(0);
869}
void BackgroundWorkerUnblockSignals(void)
Definition bgworker.c:949
static bgworker_main_type LookupBackgroundWorkerFunction(const char *libraryname, const char *funcname)
Definition bgworker.c:1360
void(* bgworker_main_type)(Datum main_arg)
Definition bgworker.h:79
#define Assert(condition)
Definition c.h:943
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void EmitErrorReport(void)
Definition elog.c:1883
ErrorContextCallback * error_context_stack
Definition elog.c:100
sigjmp_buf * PG_exception_stack
Definition elog.c:102
#define elog(elevel,...)
Definition elog.h:228
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:489
#define GetProcessingMode()
Definition miscadmin.h:499
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
#define die(msg)
#define pqsignal
Definition port.h:547
#define PG_SIG_IGN
Definition port.h:551
#define PG_SIG_DFL
Definition port.h:550
int PostAuthDelay
Definition postgres.c:105
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3081
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3064
void BaseInit(void)
Definition postinit.c:616
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:688
void init_ps_display(const char *fixed_part)
Definition ps_status.c:286
void pg_usleep(long microsec)
Definition signal.c:53
void InitProcess(void)
Definition proc.c:392
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(), memcpy(), MemoryContextAlloc(), MemoryContextDelete(), MyBgworkerEntry, PG_exception_stack, PG_SIG_DFL, PG_SIG_IGN, pg_usleep(), PostAuthDelay, PostmasterContext, pqsignal, proc_exit(), procsignal_sigusr1_handler(), SIGCHLD, SIGHUP, SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), and TopMemoryContext.

◆ BackgroundWorkerShmemInit()

static void BackgroundWorkerShmemInit ( void arg)
static

Definition at line 198 of file bgworker.c.

199{
200 dlist_iter iter;
201 int slotno = 0;
202
206
207 /*
208 * Copy contents of worker list into shared memory. Record the shared
209 * memory slot assigned to each worker. This ensures a 1-to-1
210 * correspondence between the postmaster's private list and the array in
211 * shared memory.
212 */
214 {
217
218 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
220 slot->in_use = true;
221 slot->terminate = false;
222 slot->pid = InvalidPid;
223 slot->generation = 0;
224 rw->rw_shmem_slot = slotno;
225 rw->rw_worker.bgw_notify_pid = 0; /* might be reinit after crash */
226 memcpy(&slot->worker, &rw->rw_worker, sizeof(BackgroundWorker));
227 ++slotno;
228 }
229
230 /*
231 * Mark any remaining slots as not in use.
232 */
234 {
236
237 slot->in_use = false;
238 ++slotno;
239 }
240}
dlist_head BackgroundWorkerList
Definition bgworker.c:45
static BackgroundWorkerArray * BackgroundWorkerData
Definition bgworker.c:113
int max_worker_processes
Definition globals.c:146
#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
uint32 parallel_terminate_count
Definition bgworker.c:103
uint32 parallel_register_count
Definition bgworker.c:102
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition bgworker.c:104
BackgroundWorker worker
Definition bgworker.c:85
pid_t bgw_notify_pid
Definition bgworker.h:107
BackgroundWorker rw_worker
dlist_node * cur
Definition ilist.h:179

References Assert, BackgroundWorkerData, BackgroundWorkerList, BackgroundWorker::bgw_notify_pid, dlist_iter::cur, dlist_container, dlist_foreach, fb(), BackgroundWorkerSlot::generation, BackgroundWorkerSlot::in_use, InvalidPid, max_worker_processes, memcpy(), BackgroundWorkerArray::parallel_register_count, BackgroundWorkerArray::parallel_terminate_count, BackgroundWorkerSlot::pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, BackgroundWorkerArray::slot, BackgroundWorkerSlot::terminate, BackgroundWorkerArray::total_slots, and BackgroundWorkerSlot::worker.

◆ BackgroundWorkerShmemRequest()

static void BackgroundWorkerShmemRequest ( void arg)
static

Definition at line 180 of file bgworker.c.

181{
182 Size size;
183
184 /* Array of workers is variably sized. */
185 size = offsetof(BackgroundWorkerArray, slot);
187 sizeof(BackgroundWorkerSlot)));
188 ShmemRequestStruct(.name = "Background Worker Data",
189 .size = size,
190 .ptr = (void **) &BackgroundWorkerData,
191 );
192}
size_t Size
Definition c.h:689
Size add_size(Size s1, Size s2)
Definition shmem.c:1048
Size mul_size(Size s1, Size s2)
Definition shmem.c:1063
#define ShmemRequestStruct(...)
Definition shmem.h:176
const char * name

References add_size(), BackgroundWorkerData, fb(), max_worker_processes, mul_size(), name, and ShmemRequestStruct.

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)

Definition at line 272 of file bgworker.c.

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

541{
542 dlist_iter iter;
543
545 {
547
548 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
549 if (rw->rw_worker.bgw_notify_pid == pid)
551 }
552}

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

248{
249 dlist_iter iter;
250
252 {
254
255 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
256 if (rw->rw_shmem_slot == slotno)
257 return rw;
258 }
259
260 return NULL;
261}

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

456{
458
461 Assert(slot->in_use);
462
463 /*
464 * We need a memory barrier here to make sure that the update of
465 * parallel_terminate_count completes before the store to in_use.
466 */
469
471 slot->in_use = false;
472
474 (errmsg_internal("unregistering background worker \"%s\"",
475 rw->rw_worker.bgw_name)));
476
478 pfree(rw);
479}
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 567 of file bgworker.c.

568{
570
572 {
575
576 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
579
580 /* If it's not yet started, and there's someone waiting ... */
581 if (slot->pid == InvalidPid &&
582 rw->rw_worker.bgw_notify_pid != 0)
583 {
584 /* ... then zap it, and notify the waiter */
586
588 if (notify_pid != 0)
590 }
591 }
592}
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition bgworker.c:455
#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 1180 of file bgworker.c.

1181{
1183 pid_t pid;
1184
1185 Assert(handle->slot < max_worker_processes);
1186 slot = &BackgroundWorkerData->slot[handle->slot];
1187
1188 /*
1189 * We could probably arrange to synchronize access to data using memory
1190 * barriers only, but for now, let's just keep it simple and grab the
1191 * lock. It seems unlikely that there will be enough traffic here to
1192 * result in meaningful contention.
1193 */
1195
1196 /*
1197 * The generation number can't be concurrently changed while we hold the
1198 * lock. The pid, which is updated by the postmaster, can change at any
1199 * time, but we assume such changes are atomic. So the value we read
1200 * won't be garbage, but it might be out of date by the time the caller
1201 * examines it (but that's unavoidable anyway).
1202 *
1203 * The in_use flag could be in the process of changing from true to false,
1204 * but if it is already false then it can't change further.
1205 */
1206 if (handle->generation != slot->generation || !slot->in_use)
1207 pid = 0;
1208 else
1209 pid = slot->pid;
1210
1211 /* All done. */
1213
1214 if (pid == 0)
1215 return BGWH_STOPPED;
1216 else if (pid == InvalidPid)
1217 return BGWH_NOT_YET_STARTED;
1218 *pidp = pid;
1219 return BGWH_STARTED;
1220}
@ 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:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ 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 1394 of file bgworker.c.

1395{
1396 int slotno;
1397 bool found = false;
1398 static char result[BGW_MAXLEN];
1399
1401
1403 {
1405
1406 if (slot->pid > 0 && slot->pid == pid)
1407 {
1408 strcpy(result, slot->worker.bgw_type);
1409 found = true;
1410 break;
1411 }
1412 }
1413
1415
1416 if (!found)
1417 return NULL;
1418
1419 return result;
1420}
uint32 result

References BackgroundWorkerData, BGW_MAXLEN, BackgroundWorker::bgw_type, fb(), LW_SHARED, LWLockAcquire(), LWLockRelease(), BackgroundWorkerSlot::pid, result, 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 1360 of file bgworker.c.

1361{
1362 /*
1363 * If the function is to be loaded from postgres itself, search the
1364 * InternalBGWorkers array.
1365 */
1366 if (strcmp(libraryname, "postgres") == 0)
1367 {
1368 int i;
1369
1370 for (i = 0; i < lengthof(InternalBGWorkers); i++)
1371 {
1373 return InternalBGWorkers[i].fn_addr;
1374 }
1375
1376 /* We can only reach this by programming error. */
1377 elog(ERROR, "internal function \"%s\" not found", funcname);
1378 }
1379
1380 /* Otherwise load from external library. */
1381 return (bgworker_main_type)
1383}
static const struct @18 InternalBGWorkers[]
const char * fn_name
Definition bgworker.c:129
bgworker_main_type fn_addr
Definition bgworker.c:130
#define lengthof(array)
Definition c.h:873
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 962 of file bgworker.c.

963{
965 static int numworkers = 0;
966
967 /*
968 * Static background workers can only be registered in the postmaster
969 * process.
970 */
972 {
973 /*
974 * In EXEC_BACKEND or single-user mode, we process
975 * shared_preload_libraries in backend processes too. We cannot
976 * register static background workers at that stage, but many
977 * libraries' _PG_init() functions don't distinguish whether they're
978 * being loaded in the postmaster or in a backend, they just check
979 * process_shared_preload_libraries_in_progress. It's a bit sloppy,
980 * but for historical reasons we tolerate it. In EXEC_BACKEND mode,
981 * the background workers should already have been registered when the
982 * library was loaded in postmaster.
983 */
985 return;
986 ereport(LOG,
988 errmsg("background worker \"%s\": must be registered in \"shared_preload_libraries\"",
989 worker->bgw_name)));
990 return;
991 }
992
993 /*
994 * Cannot register static background workers after calling
995 * BackgroundWorkerShmemInit().
996 */
998 elog(ERROR, "cannot register background worker \"%s\" after shmem init",
999 worker->bgw_name);
1000
1002 (errmsg_internal("registering background worker \"%s\"", worker->bgw_name)));
1003
1004 if (!SanityCheckBackgroundWorker(worker, LOG))
1005 return;
1006
1007 if (worker->bgw_notify_pid != 0)
1008 {
1009 ereport(LOG,
1011 errmsg("background worker \"%s\": only dynamic background workers can request notification",
1012 worker->bgw_name)));
1013 return;
1014 }
1015
1016 /*
1017 * Enforce maximum number of workers. Note this is overly restrictive: we
1018 * could allow more non-shmem-connected workers, because these don't count
1019 * towards the MAX_BACKENDS limit elsewhere. For now, it doesn't seem
1020 * important to relax this restriction.
1021 */
1023 {
1024 ereport(LOG,
1026 errmsg("too many background workers"),
1027 errdetail_plural("Up to %d background worker can be registered with the current settings.",
1028 "Up to %d background workers can be registered with the current settings.",
1031 errhint("Consider increasing the configuration parameter \"%s\".", "max_worker_processes")));
1032 return;
1033 }
1034
1035 /*
1036 * Copy the registration data into the registered workers list.
1037 */
1039 sizeof(RegisteredBgWorker),
1041 if (rw == NULL)
1042 {
1043 ereport(LOG,
1045 errmsg("out of memory")));
1046 return;
1047 }
1048
1049 rw->rw_worker = *worker;
1050 rw->rw_pid = 0;
1051 rw->rw_crashed_at = 0;
1052 rw->rw_terminate = false;
1053
1055}
static bool SanityCheckBackgroundWorker(BackgroundWorker *worker, int elevel)
Definition bgworker.c:658
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 IsUnderPostmaster
Definition globals.c:122
bool IsPostmasterEnvironment
Definition globals.c:121
bool process_shared_preload_libraries_in_progress
Definition miscinit.c:1788

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(), apw_start_leader_worker(), and pgsa_start_worker().

◆ RegisterDynamicBackgroundWorker()

bool RegisterDynamicBackgroundWorker ( BackgroundWorker worker,
BackgroundWorkerHandle **  handle 
)

Definition at line 1068 of file bgworker.c.

1070{
1071 int slotno;
1072 bool success = false;
1073 bool parallel;
1074 uint64 generation = 0;
1075
1076 /*
1077 * We can't register dynamic background workers from the postmaster. If
1078 * this is a standalone backend, we're the only process and can't start
1079 * any more. In a multi-process environment, it might be theoretically
1080 * possible, but we don't currently support it due to locking
1081 * considerations; see comments on the BackgroundWorkerSlot data
1082 * structure.
1083 */
1084 if (!IsUnderPostmaster)
1085 return false;
1086
1087 if (!SanityCheckBackgroundWorker(worker, ERROR))
1088 return false;
1089
1090 parallel = (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0;
1091
1093
1094 /*
1095 * If this is a parallel worker, check whether there are already too many
1096 * parallel workers; if so, don't register another one. Our view of
1097 * parallel_terminate_count may be slightly stale, but that doesn't really
1098 * matter: we would have gotten the same result if we'd arrived here
1099 * slightly earlier anyway. There's no help for it, either, since the
1100 * postmaster must not take locks; a memory barrier wouldn't guarantee
1101 * anything useful.
1102 */
1106 {
1111 return false;
1112 }
1113
1114 /*
1115 * Look for an unused slot. If we find one, grab it.
1116 */
1118 {
1120
1121 if (!slot->in_use)
1122 {
1123 memcpy(&slot->worker, worker, sizeof(BackgroundWorker));
1124 slot->pid = InvalidPid; /* indicates not started yet */
1125 slot->generation++;
1126 slot->terminate = false;
1127 generation = slot->generation;
1128 if (parallel)
1130
1131 /*
1132 * Make sure postmaster doesn't see the slot as in use before it
1133 * sees the new contents.
1134 */
1136
1137 slot->in_use = true;
1138 success = true;
1139 break;
1140 }
1141 }
1142
1144
1145 /* If we found a slot, tell the postmaster to notice the change. */
1146 if (success)
1148
1149 /*
1150 * If we found a slot and the user has provided a handle, initialize it.
1151 */
1152 if (success && handle)
1153 {
1155 (*handle)->slot = slotno;
1156 (*handle)->generation = generation;
1157 }
1158
1159 return success;
1160}
#define pg_write_barrier()
Definition atomics.h:155
#define MAX_PARALLEL_WORKER_LIMIT
uint64_t uint64
Definition c.h:625
#define palloc_object(type)
Definition fe_memutils.h:74
int max_parallel_workers
Definition globals.c:147
static bool success
Definition initdb.c:188
@ LW_EXCLUSIVE
Definition lwlock.h:104
void SendPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:164
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition pmsignal.h:42

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, memcpy(), 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(), pgsa_start_worker(), ProcessDatabase(), setup_background_workers(), start_repack_decoding_worker(), StartDataChecksumsWorkerLauncher(), and worker_spi_launch().

◆ ReportBackgroundWorkerExit()

void ReportBackgroundWorkerExit ( RegisteredBgWorker rw)

Definition at line 509 of file bgworker.c.

510{
512 int notify_pid;
513
516 slot->pid = rw->rw_pid;
518
519 /*
520 * If this worker is slated for deregistration, do that before notifying
521 * the process which started it. Otherwise, if that process tries to
522 * reuse the slot immediately, it might not be available yet. In theory
523 * that could happen anyway if the process checks slot->pid at just the
524 * wrong moment, but this makes the window narrower.
525 */
526 if (rw->rw_terminate ||
529
530 if (notify_pid != 0)
532}
#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 605 of file bgworker.c.

606{
608
610 {
612
613 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
614
616 {
617 /*
618 * Workers marked BGW_NEVER_RESTART shouldn't get relaunched after
619 * the crash, so forget about them. (If we wait until after the
620 * crash to forget about them, and they are parallel workers,
621 * parallel_terminate_count will get incremented after we've
622 * already zeroed parallel_register_count, which would be bad.)
623 */
625 }
626 else
627 {
628 /*
629 * The accounting which we do via parallel_register_count and
630 * parallel_terminate_count would get messed up if a worker marked
631 * parallel could survive a crash and restart cycle. All such
632 * workers should be marked BGW_NEVER_RESTART, and thus control
633 * should never reach this branch.
634 */
636
637 /*
638 * Allow this worker to be restarted immediately after we finish
639 * resetting.
640 */
641 rw->rw_crashed_at = 0;
642 rw->rw_pid = 0;
643
644 /*
645 * If there was anyone waiting for it, they're history.
646 */
648 }
649 }
650}

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

659{
660 /* sanity check for flags */
661
662 /*
663 * We used to support workers not connected to shared memory, but don't
664 * anymore. Thus this is a required flag now. We're not removing the flag
665 * for compatibility reasons and because the flag still provides some
666 * signal when reading code.
667 */
668 if (!(worker->bgw_flags & BGWORKER_SHMEM_ACCESS))
669 {
670 ereport(elevel,
672 errmsg("background worker \"%s\": background workers without shared memory access are not supported",
673 worker->bgw_name)));
674 return false;
675 }
676
678 {
680 {
681 ereport(elevel,
683 errmsg("background worker \"%s\": cannot request database access if starting at postmaster start",
684 worker->bgw_name)));
685 return false;
686 }
687
688 /* XXX other checks? */
689 }
690
691 /* Interruptible workers require a database connection */
692 if ((worker->bgw_flags & BGWORKER_INTERRUPTIBLE) &&
694 {
695 ereport(elevel,
697 errmsg("background worker \"%s\": cannot make background workers interruptible without database access",
698 worker->bgw_name)));
699 return false;
700 }
701
702 if ((worker->bgw_restart_time < 0 &&
704 (worker->bgw_restart_time > USECS_PER_DAY / 1000))
705 {
706 ereport(elevel,
708 errmsg("background worker \"%s\": invalid restart interval",
709 worker->bgw_name)));
710 return false;
711 }
712
713 /*
714 * Parallel workers may not be configured for restart, because the
715 * parallel_register_count/parallel_terminate_count accounting can't
716 * handle parallel workers lasting through a crash-and-restart cycle.
717 */
718 if (worker->bgw_restart_time != BGW_NEVER_RESTART &&
719 (worker->bgw_flags & BGWORKER_CLASS_PARALLEL) != 0)
720 {
721 ereport(elevel,
723 errmsg("background worker \"%s\": parallel workers may not be configured for restart",
724 worker->bgw_name)));
725 return false;
726 }
727
728 /*
729 * If bgw_type is not filled in, use bgw_name.
730 */
731 if (strcmp(worker->bgw_type, "") == 0)
732 strcpy(worker->bgw_type, worker->bgw_name);
733
734 return true;
735}
#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 1319 of file bgworker.c.

1320{
1322 bool signal_postmaster = false;
1323
1324 Assert(handle->slot < max_worker_processes);
1325 slot = &BackgroundWorkerData->slot[handle->slot];
1326
1327 /* Set terminate flag in shared memory, unless slot has been reused. */
1329 if (handle->generation == slot->generation)
1330 {
1331 slot->terminate = true;
1332 signal_postmaster = true;
1333 }
1335
1336 /* Make sure the postmaster notices the change to shared memory. */
1339}

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(), DestroyParallelContext(), and stop_repack_decoding_worker().

◆ TerminateBackgroundWorkersForDatabase()

void TerminateBackgroundWorkersForDatabase ( Oid  databaseId)

Definition at line 1427 of file bgworker.c.

1428{
1429 bool signal_postmaster = false;
1430
1431 elog(DEBUG1, "attempting worker termination for database %u",
1432 databaseId);
1433
1435
1436 /*
1437 * Iterate through slots, looking for workers connected to the given
1438 * database.
1439 */
1441 {
1443
1444 if (slot->in_use &&
1446 {
1447 PGPROC *proc = BackendPidGetProc(slot->pid);
1448
1449 if (proc && proc->databaseId == databaseId)
1450 {
1451 slot->terminate = true;
1452 signal_postmaster = true;
1453
1454 elog(DEBUG1, "termination requested for worker (PID %d) on database %u",
1455 (int) slot->pid, databaseId);
1456 }
1457 }
1458 }
1459
1461
1462 /* Make sure the postmaster notices the change to shared memory. */
1465}
PGPROC * BackendPidGetProc(int pid)
Definition procarray.c:3169
Definition proc.h:179
Oid databaseId
Definition proc.h:201

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

1281{
1282 BgwHandleStatus status;
1283 int rc;
1284
1285 for (;;)
1286 {
1287 pid_t pid;
1288
1290
1291 status = GetBackgroundWorkerPid(handle, &pid);
1292 if (status == BGWH_STOPPED)
1293 break;
1294
1295 rc = WaitLatch(MyLatch,
1298
1299 if (rc & WL_POSTMASTER_DEATH)
1300 {
1301 status = BGWH_POSTMASTER_DIED;
1302 break;
1303 }
1304
1306 }
1307
1308 return status;
1309}
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition bgworker.c:1180
BgwHandleStatus
Definition bgworker.h:111
@ BGWH_POSTMASTER_DIED
Definition bgworker.h:115
struct Latch * MyLatch
Definition globals.c:65
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:125
#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(), ProcessDatabase(), stop_repack_decoding_worker(), and WaitForParallelWorkersToExit().

◆ WaitForBackgroundWorkerStartup()

BgwHandleStatus WaitForBackgroundWorkerStartup ( BackgroundWorkerHandle handle,
pid_t pidp 
)

Definition at line 1235 of file bgworker.c.

1236{
1237 BgwHandleStatus status;
1238 int rc;
1239
1240 for (;;)
1241 {
1242 pid_t pid;
1243
1245
1246 status = GetBackgroundWorkerPid(handle, &pid);
1247 if (status == BGWH_STARTED)
1248 *pidp = pid;
1249 if (status != BGWH_NOT_YET_STARTED)
1250 break;
1251
1252 rc = WaitLatch(MyLatch,
1255
1256 if (rc & WL_POSTMASTER_DEATH)
1257 {
1258 status = BGWH_POSTMASTER_DIED;
1259 break;
1260 }
1261
1263 }
1264
1265 return status;
1266}

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(), pgsa_start_worker(), ProcessDatabase(), and worker_spi_launch().

Variable Documentation

◆ BackgroundWorkerData

◆ BackgroundWorkerList

◆ BackgroundWorkerShmemCallbacks

const ShmemCallbacks BackgroundWorkerShmemCallbacks
Initial value:
= {
}
static void BackgroundWorkerShmemRequest(void *arg)
Definition bgworker.c:180
static void BackgroundWorkerShmemInit(void *arg)
Definition bgworker.c:198

Definition at line 118 of file bgworker.c.

118 {
119 .request_fn = BackgroundWorkerShmemRequest,
120 .init_fn = BackgroundWorkerShmemInit,
121};

◆ fn_addr

Definition at line 130 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ fn_name

const char* fn_name

Definition at line 129 of file bgworker.c.

Referenced by LookupBackgroundWorkerFunction().

◆ [struct]

const struct { ... } InternalBGWorkers[]