PostgreSQL Source Code git master
Loading...
Searching...
No Matches
bgworker_internals.h File Reference
#include "datatype/timestamp.h"
#include "lib/ilist.h"
#include "postmaster/bgworker.h"
Include dependency graph for bgworker_internals.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  RegisteredBgWorker
 

Macros

#define MAX_PARALLEL_WORKER_LIMIT   1024
 

Typedefs

typedef struct RegisteredBgWorker RegisteredBgWorker
 

Functions

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

Variables

PGDLLIMPORT dlist_head BackgroundWorkerList
 

Macro Definition Documentation

◆ MAX_PARALLEL_WORKER_LIMIT

#define MAX_PARALLEL_WORKER_LIMIT   1024

Definition at line 24 of file bgworker_internals.h.

Typedef Documentation

◆ RegisteredBgWorker

Function Documentation

◆ BackgroundWorkerMain()

pg_noreturn void BackgroundWorkerMain ( const void startup_data,
size_t  startup_data_len 
)
extern

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
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition bgworker.h:60
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 FATAL
Definition elog.h:42
#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
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:201
static int fb(int x)
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.

◆ BackgroundWorkerStateChange()

void BackgroundWorkerStateChange ( bool  allow_new_workers)
extern

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
dlist_head BackgroundWorkerList
Definition bgworker.c:45
static BackgroundWorkerArray * BackgroundWorkerData
Definition bgworker.c:113
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
int errcode(int sqlerrcode)
Definition elog.c:875
#define LOG
Definition elog.h:32
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG1
Definition elog.h:31
#define ereport(elevel,...)
Definition elog.h:152
#define MCXT_ALLOC_ZERO
Definition fe_memutils.h:30
#define MCXT_ALLOC_NO_OOM
Definition fe_memutils.h:29
int max_worker_processes
Definition globals.c:146
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
static char * errmsg
#define MAXPGPATH
bool PostmasterMarkPIDForWorkerNotify(int pid)
uint32 parallel_terminate_count
Definition bgworker.c:103
BackgroundWorkerSlot slot[FLEXIBLE_ARRAY_MEMBER]
Definition bgworker.c:104
BackgroundWorker worker
Definition bgworker.c:85
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
pid_t bgw_notify_pid
Definition bgworker.h:107
BackgroundWorker rw_worker
#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)
extern

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}
#define dlist_foreach(iter, lhead)
Definition ilist.h:623
#define dlist_container(type, membername, ptr)
Definition ilist.h:593
dlist_node * cur
Definition ilist.h:179

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

Referenced by CleanupBackend().

◆ ForgetBackgroundWorker()

void ForgetBackgroundWorker ( RegisteredBgWorker rw)
extern

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  )
extern

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
#define InvalidPid
Definition miscadmin.h:32
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().

◆ ReportBackgroundWorkerExit()

void ReportBackgroundWorkerExit ( RegisteredBgWorker rw)
extern

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  )
extern

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().

Variable Documentation

◆ BackgroundWorkerList