PostgreSQL Source Code git master
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/xlog.h"
#include "access/xlogrecovery.h"
#include "common/file_perm.h"
#include "common/pg_prng.h"
#include "lib/ilist.h"
#include "libpq/libpq.h"
#include "libpq/pqsignal.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "postmaster/walsummarizer.h"
#include "replication/logicallauncher.h"
#include "replication/slotsync.h"
#include "replication/walsender.h"
#include "storage/aio_subsys.h"
#include "storage/fd.h"
#include "storage/io_worker.h"
#include "storage/ipc.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/backend_startup.h"
#include "tcop/tcopprot.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  BackendTypeMask
 

Macros

#define btmask_add(mask, ...)
 
#define btmask_all_except(...)
 
#define MAXLISTEN   64
 
#define NoShutdown   0
 
#define SmartShutdown   1
 
#define FastShutdown   2
 
#define ImmediateShutdown   3
 
#define SIGKILL_CHILDREN_AFTER_SECS   5
 
#define EXIT_STATUS_0(st)   ((st) == 0)
 
#define EXIT_STATUS_1(st)   (WIFEXITED(st) && WEXITSTATUS(st) == 1)
 
#define EXIT_STATUS_3(st)   (WIFEXITED(st) && WEXITSTATUS(st) == 3)
 
#define PM_TOSTR_CASE(sym)   case sym: return #sym
 
#define PM_TOSTR_CASE(sym)   case sym: return #sym
 
#define OPTS_FILE   "postmaster.opts"
 
#define MAX_BGWORKERS_TO_LAUNCH   100
 

Enumerations

enum  StartupStatusEnum { STARTUP_NOT_RUNNING , STARTUP_RUNNING , STARTUP_SIGNALED , STARTUP_CRASHED }
 
enum  PMState {
  PM_INIT , PM_STARTUP , PM_RECOVERY , PM_HOT_STANDBY ,
  PM_RUN , PM_STOP_BACKENDS , PM_WAIT_BACKENDS , PM_WAIT_XLOG_SHUTDOWN ,
  PM_WAIT_XLOG_ARCHIVAL , PM_WAIT_IO_WORKERS , PM_WAIT_CHECKPOINTER , PM_WAIT_DEAD_END ,
  PM_NO_CHILDREN
}
 

Functions

 StaticAssertDecl (BACKEND_NUM_TYPES< 32, "too many backend types for uint32")
 
static BackendTypeMask btmask (BackendType t)
 
static BackendTypeMask btmask_add_n (BackendTypeMask mask, int nargs, BackendType *t)
 
static BackendTypeMask btmask_del (BackendTypeMask mask, BackendType t)
 
static BackendTypeMask btmask_all_except_n (int nargs, BackendType *t)
 
static bool btmask_contains (BackendTypeMask mask, BackendType t)
 
static void CloseServerPorts (int status, Datum arg)
 
static void unlink_external_pid_file (int status, Datum arg)
 
static void getInstallationPaths (const char *argv0)
 
static void checkControlFile (void)
 
static void handle_pm_pmsignal_signal (SIGNAL_ARGS)
 
static void handle_pm_child_exit_signal (SIGNAL_ARGS)
 
static void handle_pm_reload_request_signal (SIGNAL_ARGS)
 
static void handle_pm_shutdown_request_signal (SIGNAL_ARGS)
 
static void process_pm_pmsignal (void)
 
static void process_pm_child_exit (void)
 
static void process_pm_reload_request (void)
 
static void process_pm_shutdown_request (void)
 
static void dummy_handler (SIGNAL_ARGS)
 
static void CleanupBackend (PMChild *bp, int exitstatus)
 
static void HandleChildCrash (int pid, int exitstatus, const char *procname)
 
static void LogChildExit (int lev, const char *procname, int pid, int exitstatus)
 
static void PostmasterStateMachine (void)
 
static void UpdatePMState (PMState newState)
 
static pg_noreturn void ExitPostmaster (int status)
 
static int ServerLoop (void)
 
static int BackendStartup (ClientSocket *client_sock)
 
static void report_fork_failure_to_client (ClientSocket *client_sock, int errnum)
 
static CAC_state canAcceptConnections (BackendType backend_type)
 
static void signal_child (PMChild *pmchild, int signal)
 
static bool SignalChildren (int signal, BackendTypeMask targetMask)
 
static void TerminateChildren (int signal)
 
static int CountChildren (BackendTypeMask targetMask)
 
static void LaunchMissingBackgroundProcesses (void)
 
static void maybe_start_bgworkers (void)
 
static bool maybe_reap_io_worker (int pid)
 
static void maybe_adjust_io_workers (void)
 
static bool CreateOptsFile (int argc, char *argv[], char *fullprogname)
 
static PMChildStartChildProcess (BackendType type)
 
static void StartSysLogger (void)
 
static void StartAutovacuumWorker (void)
 
static bool StartBackgroundWorker (RegisteredBgWorker *rw)
 
static void InitPostmasterDeathWatchHandle (void)
 
void PostmasterMain (int argc, char *argv[])
 
static int DetermineSleepTime (void)
 
static void ConfigurePostmasterWaitSet (bool accept_connections)
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
static void HandleFatalError (QuitSignalReason reason, bool consider_sigabrt)
 
static const char * pmstate_name (PMState state)
 
static const char * pm_signame (int signal)
 
static bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

static const BackendTypeMask BTYPE_MASK_ALL = {(1 << BACKEND_NUM_TYPES) - 1}
 
static const BackendTypeMask BTYPE_MASK_NONE = {0}
 
BackgroundWorkerMyBgworkerEntry = NULL
 
int PostPortNumber = DEF_PGPORT
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int SuperuserReservedConnections
 
int ReservedConnections
 
static int NumListenSockets = 0
 
static pgsocketListenSockets = NULL
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
bool remove_temp_files_after_crash = true
 
bool send_abort_for_crash = false
 
bool send_abort_for_kill = false
 
static PMChildStartupPMChild = NULL
 
static PMChildBgWriterPMChild = NULL
 
static PMChildCheckpointerPMChild = NULL
 
static PMChildWalWriterPMChild = NULL
 
static PMChildWalReceiverPMChild = NULL
 
static PMChildWalSummarizerPMChild = NULL
 
static PMChildAutoVacLauncherPMChild = NULL
 
static PMChildPgArchPMChild = NULL
 
static PMChildSysLoggerPMChild = NULL
 
static PMChildSlotSyncWorkerPMChild = NULL
 
static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING
 
static int Shutdown = NoShutdown
 
static bool FatalError = false
 
static PMState pmState = PM_INIT
 
static bool connsAllowed = true
 
static time_t AbortStartTime = 0
 
static bool ReachedNormalRunning = false
 
bool ClientAuthInProgress = false
 
bool redirection_done = false
 
static bool start_autovac_launcher = false
 
static bool avlauncher_needs_signal = false
 
static bool WalReceiverRequested = false
 
static bool StartWorkerNeeded = true
 
static bool HaveCrashedWorker = false
 
static volatile sig_atomic_t pending_pm_pmsignal
 
static volatile sig_atomic_t pending_pm_child_exit
 
static volatile sig_atomic_t pending_pm_reload_request
 
static volatile sig_atomic_t pending_pm_shutdown_request
 
static volatile sig_atomic_t pending_pm_fast_shutdown_request
 
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
 
static WaitEventSetpm_wait_set
 
static int io_worker_count = 0
 
static PMChildio_worker_children [MAX_IO_WORKERS]
 
int postmaster_alive_fds [2] = {-1, -1}
 

Macro Definition Documentation

◆ btmask_add

#define btmask_add (   mask,
  ... 
)
Value:
btmask_add_n(mask, \
lengthof(((BackendType[]){__VA_ARGS__})), \
(BackendType[]){__VA_ARGS__} \
)
#define lengthof(array)
Definition: c.h:759
BackendType
Definition: miscadmin.h:337
static BackendTypeMask btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
Definition: postmaster.c:156

Definition at line 163 of file postmaster.c.

◆ btmask_all_except

#define btmask_all_except (   ...)
Value:
lengthof(((BackendType[]){__VA_ARGS__})), \
(BackendType[]){__VA_ARGS__} \
)
static BackendTypeMask btmask_all_except_n(int nargs, BackendType *t)
Definition: postmaster.c:177

Definition at line 186 of file postmaster.c.

◆ EXIT_STATUS_0

#define EXIT_STATUS_0 (   st)    ((st) == 0)

Definition at line 473 of file postmaster.c.

◆ EXIT_STATUS_1

#define EXIT_STATUS_1 (   st)    (WIFEXITED(st) && WEXITSTATUS(st) == 1)

Definition at line 474 of file postmaster.c.

◆ EXIT_STATUS_3

#define EXIT_STATUS_3 (   st)    (WIFEXITED(st) && WEXITSTATUS(st) == 3)

Definition at line 475 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 284 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 285 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 232 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 282 of file postmaster.c.

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

◆ PM_TOSTR_CASE [1/2]

#define PM_TOSTR_CASE (   sym)    case sym: return #sym

◆ PM_TOSTR_CASE [2/2]

#define PM_TOSTR_CASE (   sym)    case sym: return #sym

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 367 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 283 of file postmaster.c.

Enumeration Type Documentation

◆ PMState

enum PMState
Enumerator
PM_INIT 
PM_STARTUP 
PM_RECOVERY 
PM_HOT_STANDBY 
PM_RUN 
PM_STOP_BACKENDS 
PM_WAIT_BACKENDS 
PM_WAIT_XLOG_SHUTDOWN 
PM_WAIT_XLOG_ARCHIVAL 
PM_WAIT_IO_WORKERS 
PM_WAIT_CHECKPOINTER 
PM_WAIT_DEAD_END 
PM_NO_CHILDREN 

Definition at line 333 of file postmaster.c.

334{
335 PM_INIT, /* postmaster starting */
336 PM_STARTUP, /* waiting for startup subprocess */
337 PM_RECOVERY, /* in archive recovery mode */
338 PM_HOT_STANDBY, /* in hot standby mode */
339 PM_RUN, /* normal "database is alive" state */
340 PM_STOP_BACKENDS, /* need to stop remaining backends */
341 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
342 PM_WAIT_XLOG_SHUTDOWN, /* waiting for checkpointer to do shutdown
343 * ckpt */
344 PM_WAIT_XLOG_ARCHIVAL, /* waiting for archiver and walsenders to
345 * finish */
346 PM_WAIT_IO_WORKERS, /* waiting for io workers to exit */
347 PM_WAIT_CHECKPOINTER, /* waiting for checkpointer to shut down */
348 PM_WAIT_DEAD_END, /* waiting for dead-end children to exit */
349 PM_NO_CHILDREN, /* all important children have exited */
350} PMState;
PMState
Definition: postmaster.c:334
@ PM_WAIT_XLOG_ARCHIVAL
Definition: postmaster.c:344
@ PM_RUN
Definition: postmaster.c:339
@ PM_HOT_STANDBY
Definition: postmaster.c:338
@ PM_WAIT_DEAD_END
Definition: postmaster.c:348
@ PM_RECOVERY
Definition: postmaster.c:337
@ PM_NO_CHILDREN
Definition: postmaster.c:349
@ PM_WAIT_CHECKPOINTER
Definition: postmaster.c:347
@ PM_WAIT_BACKENDS
Definition: postmaster.c:341
@ PM_WAIT_IO_WORKERS
Definition: postmaster.c:346
@ PM_STOP_BACKENDS
Definition: postmaster.c:340
@ PM_INIT
Definition: postmaster.c:335
@ PM_WAIT_XLOG_SHUTDOWN
Definition: postmaster.c:342
@ PM_STARTUP
Definition: postmaster.c:336

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 271 of file postmaster.c.

272{
275 STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
StartupStatusEnum
Definition: postmaster.c:272
@ STARTUP_SIGNALED
Definition: postmaster.c:275
@ STARTUP_CRASHED
Definition: postmaster.c:276
@ STARTUP_NOT_RUNNING
Definition: postmaster.c:273
@ STARTUP_RUNNING
Definition: postmaster.c:274

Function Documentation

◆ BackendStartup()

static int BackendStartup ( ClientSocket client_sock)
static

Definition at line 3529 of file postmaster.c.

3530{
3531 PMChild *bn = NULL;
3532 pid_t pid;
3533 BackendStartupData startup_data;
3534 CAC_state cac;
3535
3536 /*
3537 * Capture time that Postmaster got a socket from accept (for logging
3538 * connection establishment and setup total duration).
3539 */
3540 startup_data.socket_created = GetCurrentTimestamp();
3541
3542 /*
3543 * Allocate and assign the child slot. Note we must do this before
3544 * forking, so that we can handle failures (out of memory or child-process
3545 * slots) cleanly.
3546 */
3548 if (cac == CAC_OK)
3549 {
3550 /* Can change later to B_WAL_SENDER */
3552 if (!bn)
3553 {
3554 /*
3555 * Too many regular child processes; launch a dead-end child
3556 * process instead.
3557 */
3558 cac = CAC_TOOMANY;
3559 }
3560 }
3561 if (!bn)
3562 {
3563 bn = AllocDeadEndChild();
3564 if (!bn)
3565 {
3566 ereport(LOG,
3567 (errcode(ERRCODE_OUT_OF_MEMORY),
3568 errmsg("out of memory")));
3569 return STATUS_ERROR;
3570 }
3571 }
3572
3573 /* Pass down canAcceptConnections state */
3574 startup_data.canAcceptConnections = cac;
3575 bn->rw = NULL;
3576
3577 /* Hasn't asked to be notified about any bgworkers yet */
3578 bn->bgworker_notify = false;
3579
3581 &startup_data, sizeof(startup_data),
3582 client_sock);
3583 if (pid < 0)
3584 {
3585 /* in parent, fork failed */
3586 int save_errno = errno;
3587
3588 (void) ReleasePostmasterChildSlot(bn);
3589 errno = save_errno;
3590 ereport(LOG,
3591 (errmsg("could not fork new process for connection: %m")));
3592 report_fork_failure_to_client(client_sock, save_errno);
3593 return STATUS_ERROR;
3594 }
3595
3596 /* in parent, successful fork */
3598 (errmsg_internal("forked new %s, pid=%d socket=%d",
3600 (int) pid, (int) client_sock->sock)));
3601
3602 /*
3603 * Everything's been successful, it's safe to add this backend to our list
3604 * of backends.
3605 */
3606 bn->pid = pid;
3607 return STATUS_OK;
3608}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
CAC_state
@ CAC_TOOMANY
@ CAC_OK
#define STATUS_OK
Definition: c.h:1140
#define STATUS_ERROR
Definition: c.h:1141
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:149
pid_t postmaster_child_launch(BackendType child_type, int child_slot, const void *startup_data, size_t startup_data_len, ClientSocket *client_sock)
@ B_BACKEND
Definition: miscadmin.h:341
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:263
PMChild * AssignPostmasterChildSlot(BackendType btype)
Definition: pmchild.c:162
bool ReleasePostmasterChildSlot(PMChild *pmchild)
Definition: pmchild.c:236
PMChild * AllocDeadEndChild(void)
Definition: pmchild.c:208
static CAC_state canAcceptConnections(BackendType backend_type)
Definition: postmaster.c:1810
static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
Definition: postmaster.c:3619
CAC_state canAcceptConnections
TimestampTz socket_created
pgsocket sock
Definition: libpq-be.h:253
struct RegisteredBgWorker * rw
Definition: postmaster.h:45
bool bgworker_notify
Definition: postmaster.h:46
BackendType bkend_type
Definition: postmaster.h:44
pid_t pid
Definition: postmaster.h:42
int child_slot
Definition: postmaster.h:43

References AllocDeadEndChild(), AssignPostmasterChildSlot(), B_BACKEND, PMChild::bgworker_notify, PMChild::bkend_type, CAC_OK, CAC_TOOMANY, canAcceptConnections(), BackendStartupData::canAcceptConnections, PMChild::child_slot, DEBUG2, ereport, errcode(), errmsg(), errmsg_internal(), GetBackendTypeDesc(), GetCurrentTimestamp(), LOG, PMChild::pid, postmaster_child_launch(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), PMChild::rw, ClientSocket::sock, BackendStartupData::socket_created, STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 4170 of file postmaster.c.

4171{
4172 switch (pmState)
4173 {
4174 case PM_NO_CHILDREN:
4176 case PM_WAIT_DEAD_END:
4179 case PM_WAIT_IO_WORKERS:
4180 case PM_WAIT_BACKENDS:
4181 case PM_STOP_BACKENDS:
4182 break;
4183
4184 case PM_RUN:
4186 return true;
4187 /* fall through */
4188
4189 case PM_HOT_STANDBY:
4191 return true;
4192 /* fall through */
4193
4194 case PM_RECOVERY:
4195 case PM_STARTUP:
4196 case PM_INIT:
4198 return true;
4199 /* fall through */
4200 }
4201
4202 return false;
4203}
@ BgWorkerStart_RecoveryFinished
Definition: bgworker.h:81
@ BgWorkerStart_ConsistentState
Definition: bgworker.h:80
@ BgWorkerStart_PostmasterStart
Definition: bgworker.h:79
static time_t start_time
Definition: pg_ctl.c:95
static PMState pmState
Definition: postmaster.c:352

References BgWorkerStart_ConsistentState, BgWorkerStart_PostmasterStart, BgWorkerStart_RecoveryFinished, PM_HOT_STANDBY, PM_INIT, PM_NO_CHILDREN, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_CHECKPOINTER, PM_WAIT_DEAD_END, PM_WAIT_IO_WORKERS, PM_WAIT_XLOG_ARCHIVAL, PM_WAIT_XLOG_SHUTDOWN, pmState, and start_time.

Referenced by maybe_start_bgworkers().

◆ btmask()

static BackendTypeMask btmask ( BackendType  t)
inlinestatic

Definition at line 148 of file postmaster.c.

149{
150 BackendTypeMask mask = {.mask = 1 << t};
151
152 return mask;
153}

References BackendTypeMask::mask.

Referenced by PostmasterStateMachine(), and process_pm_pmsignal().

◆ btmask_add_n()

static BackendTypeMask btmask_add_n ( BackendTypeMask  mask,
int  nargs,
BackendType t 
)
inlinestatic

Definition at line 156 of file postmaster.c.

157{
158 for (int i = 0; i < nargs; i++)
159 mask.mask |= 1 << t[i];
160 return mask;
161}
int i
Definition: isn.c:74

References i, and BackendTypeMask::mask.

◆ btmask_all_except_n()

static BackendTypeMask btmask_all_except_n ( int  nargs,
BackendType t 
)
inlinestatic

Definition at line 177 of file postmaster.c.

178{
180
181 for (int i = 0; i < nargs; i++)
182 mask = btmask_del(mask, t[i]);
183 return mask;
184}
static const BackendTypeMask BTYPE_MASK_ALL
Definition: postmaster.c:144
static BackendTypeMask btmask_del(BackendTypeMask mask, BackendType t)
Definition: postmaster.c:170

References btmask_del(), BTYPE_MASK_ALL, and i.

◆ btmask_contains()

static bool btmask_contains ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 193 of file postmaster.c.

194{
195 return (mask.mask & (1 << t)) != 0;
196}

References BackendTypeMask::mask.

Referenced by CountChildren(), and SignalChildren().

◆ btmask_del()

static BackendTypeMask btmask_del ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 170 of file postmaster.c.

171{
172 mask.mask &= ~(1 << t);
173 return mask;
174}

References BackendTypeMask::mask.

Referenced by btmask_all_except_n().

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( BackendType  backend_type)
static

Definition at line 1810 of file postmaster.c.

1811{
1812 CAC_state result = CAC_OK;
1813
1814 Assert(backend_type == B_BACKEND || backend_type == B_AUTOVAC_WORKER);
1815
1816 /*
1817 * Can't start backends when in startup/shutdown/inconsistent recovery
1818 * state. We treat autovac workers the same as user backends for this
1819 * purpose.
1820 */
1821 if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
1822 {
1823 if (Shutdown > NoShutdown)
1824 return CAC_SHUTDOWN; /* shutdown is pending */
1825 else if (!FatalError && pmState == PM_STARTUP)
1826 return CAC_STARTUP; /* normal startup */
1827 else if (!FatalError && pmState == PM_RECOVERY)
1828 return CAC_NOTCONSISTENT; /* not yet at consistent recovery
1829 * state */
1830 else
1831 return CAC_RECOVERY; /* else must be crash recovery */
1832 }
1833
1834 /*
1835 * "Smart shutdown" restrictions are applied only to normal connections,
1836 * not to autovac workers.
1837 */
1838 if (!connsAllowed && backend_type == B_BACKEND)
1839 return CAC_SHUTDOWN; /* shutdown is pending */
1840
1841 return result;
1842}
@ CAC_RECOVERY
@ CAC_NOTCONSISTENT
@ CAC_STARTUP
@ CAC_SHUTDOWN
Assert(PointerIsAligned(start, uint64))
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:344
static bool connsAllowed
Definition: postmaster.c:360
static int Shutdown
Definition: postmaster.c:287
#define NoShutdown
Definition: postmaster.c:282
static bool FatalError
Definition: postmaster.c:289

References Assert(), B_AUTOVAC_WORKER, B_BACKEND, CAC_NOTCONSISTENT, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, connsAllowed, FatalError, NoShutdown, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, pmState, and Shutdown.

Referenced by BackendStartup(), and StartAutovacuumWorker().

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1514 of file postmaster.c.

1515{
1516 char path[MAXPGPATH];
1517 FILE *fp;
1518
1519 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1520
1521 fp = AllocateFile(path, PG_BINARY_R);
1522 if (fp == NULL)
1523 {
1524 write_stderr("%s: could not find the database system\n"
1525 "Expected to find it in the directory \"%s\",\n"
1526 "but could not open file \"%s\": %m\n",
1527 progname, DataDir, path);
1528 ExitPostmaster(2);
1529 }
1530 FreeFile(fp);
1531}
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1246
int FreeFile(FILE *file)
Definition: fd.c:2803
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2605
char * DataDir
Definition: globals.c:70
const char * progname
Definition: main.c:44
#define MAXPGPATH
#define snprintf
Definition: port.h:239
static pg_noreturn void ExitPostmaster(int status)
Definition: postmaster.c:3646

References AllocateFile(), DataDir, ExitPostmaster(), FreeFile(), MAXPGPATH, PG_BINARY_R, progname, snprintf, and write_stderr.

Referenced by PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( PMChild bp,
int  exitstatus 
)
static

Definition at line 2565 of file postmaster.c.

2567{
2568 char namebuf[MAXPGPATH];
2569 const char *procname;
2570 bool crashed = false;
2571 bool logged = false;
2572 pid_t bp_pid;
2573 bool bp_bgworker_notify;
2574 BackendType bp_bkend_type;
2576
2577 /* Construct a process name for the log message */
2578 if (bp->bkend_type == B_BG_WORKER)
2579 {
2580 snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
2581 bp->rw->rw_worker.bgw_type);
2582 procname = namebuf;
2583 }
2584 else
2585 procname = _(GetBackendTypeDesc(bp->bkend_type));
2586
2587 /*
2588 * If a backend dies in an ugly way then we must signal all other backends
2589 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2590 * assume everything is all right and proceed to remove the backend from
2591 * the active child list.
2592 */
2593 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2594 crashed = true;
2595
2596#ifdef WIN32
2597
2598 /*
2599 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2600 * since that sometimes happens under load when the process fails to start
2601 * properly (long before it starts using shared memory). Microsoft reports
2602 * it is related to mutex failure:
2603 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2604 */
2605 if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2606 {
2607 LogChildExit(LOG, procname, bp->pid, exitstatus);
2608 logged = true;
2609 crashed = false;
2610 }
2611#endif
2612
2613 /*
2614 * Release the PMChild entry.
2615 *
2616 * If the process attached to shared memory, this also checks that it
2617 * detached cleanly.
2618 */
2619 bp_pid = bp->pid;
2620 bp_bgworker_notify = bp->bgworker_notify;
2621 bp_bkend_type = bp->bkend_type;
2622 rw = bp->rw;
2624 {
2625 /*
2626 * Uh-oh, the child failed to clean itself up. Treat as a crash after
2627 * all.
2628 */
2629 crashed = true;
2630 }
2631 bp = NULL;
2632
2633 if (crashed)
2634 {
2635 HandleChildCrash(bp_pid, exitstatus, procname);
2636 return;
2637 }
2638
2639 /*
2640 * This backend may have been slated to receive SIGUSR1 when some
2641 * background worker started or stopped. Cancel those notifications, as
2642 * we don't want to signal PIDs that are not PostgreSQL backends. This
2643 * gets skipped in the (probably very common) case where the backend has
2644 * never requested any such notifications.
2645 */
2646 if (bp_bgworker_notify)
2648
2649 /*
2650 * If it was a background worker, also update its RegisteredBgWorker
2651 * entry.
2652 */
2653 if (bp_bkend_type == B_BG_WORKER)
2654 {
2655 if (!EXIT_STATUS_0(exitstatus))
2656 {
2657 /* Record timestamp, so we know when to restart the worker. */
2659 }
2660 else
2661 {
2662 /* Zero exit status means terminate */
2663 rw->rw_crashed_at = 0;
2664 rw->rw_terminate = true;
2665 }
2666
2667 rw->rw_pid = 0;
2668 ReportBackgroundWorkerExit(rw); /* report child death */
2669
2670 if (!logged)
2671 {
2672 LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
2673 procname, bp_pid, exitstatus);
2674 logged = true;
2675 }
2676
2677 /* have it be restarted */
2678 HaveCrashedWorker = true;
2679 }
2680
2681 if (!logged)
2682 LogChildExit(DEBUG2, procname, bp_pid, exitstatus);
2683}
void ReportBackgroundWorkerExit(RegisteredBgWorker *rw)
Definition: bgworker.c:483
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:514
#define _(x)
Definition: elog.c:90
#define DEBUG1
Definition: elog.h:30
@ B_BG_WORKER
Definition: miscadmin.h:345
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:2810
#define EXIT_STATUS_1(st)
Definition: postmaster.c:474
#define EXIT_STATUS_0(st)
Definition: postmaster.c:473
static bool HaveCrashedWorker
Definition: postmaster.c:387
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:2783
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BackgroundWorker rw_worker

References _, B_BG_WORKER, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_type, PMChild::bgworker_notify, PMChild::bkend_type, DEBUG1, DEBUG2, EXIT_STATUS_0, EXIT_STATUS_1, GetBackendTypeDesc(), GetCurrentTimestamp(), HandleChildCrash(), HaveCrashedWorker, LOG, LogChildExit(), MAXPGPATH, PMChild::pid, ReleasePostmasterChildSlot(), ReportBackgroundWorkerExit(), PMChild::rw, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, and snprintf.

Referenced by process_pm_child_exit().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1855 of file postmaster.c.

1856{
1857 /* Release resources held by the postmaster's WaitEventSet. */
1858 if (pm_wait_set)
1859 {
1861 pm_wait_set = NULL;
1862 }
1863
1864#ifndef WIN32
1865
1866 /*
1867 * Close the write end of postmaster death watch pipe. It's important to
1868 * do this as early as possible, so that if postmaster dies, others won't
1869 * think that it's still running because we're holding the pipe open.
1870 */
1872 ereport(FATAL,
1874 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1876 /* Notify fd.c that we released one pipe FD. */
1878#endif
1879
1880 /*
1881 * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1882 * so we don't call ReleaseExternalFD() here.
1883 *
1884 * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1885 * EXEC_BACKEND mode.
1886 */
1887#ifndef EXEC_BACKEND
1888 if (ListenSockets)
1889 {
1890 for (int i = 0; i < NumListenSockets; i++)
1891 {
1892 if (closesocket(ListenSockets[i]) != 0)
1893 elog(LOG, "could not close listen socket: %m");
1894 }
1896 }
1897 NumListenSockets = 0;
1898 ListenSockets = NULL;
1899#endif
1900
1901 /*
1902 * If using syslogger, close the read side of the pipe. We don't bother
1903 * tracking this in fd.c, either.
1904 */
1905 if (!am_syslogger)
1906 {
1907#ifndef WIN32
1908 if (syslogPipe[0] >= 0)
1909 close(syslogPipe[0]);
1910 syslogPipe[0] = -1;
1911#else
1912 if (syslogPipe[0])
1913 CloseHandle(syslogPipe[0]);
1914 syslogPipe[0] = 0;
1915#endif
1916 }
1917
1918#ifdef USE_BONJOUR
1919 /* If using Bonjour, close the connection to the mDNS daemon */
1920 if (bonjour_sdref)
1921 close(DNSServiceRefSockFD(bonjour_sdref));
1922#endif
1923}
int errcode_for_file_access(void)
Definition: elog.c:876
#define FATAL
Definition: elog.h:41
#define elog(elevel,...)
Definition: elog.h:225
void ReleaseExternalFD(void)
Definition: fd.c:1238
#define close(a)
Definition: win32.h:12
void pfree(void *pointer)
Definition: mcxt.c:1524
#define closesocket
Definition: port.h:377
static pgsocket * ListenSockets
Definition: postmaster.c:234
static int NumListenSockets
Definition: postmaster.c:233
int postmaster_alive_fds[2]
Definition: postmaster.c:482
static WaitEventSet * pm_wait_set
Definition: postmaster.c:398
#define POSTMASTER_FD_OWN
Definition: postmaster.h:84
int syslogPipe[2]
Definition: syslogger.c:114
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: waiteventset.c:523

References close, closesocket, elog, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, FreeWaitEventSetAfterFork(), i, ListenSockets, LOG, NumListenSockets, pfree(), pm_wait_set, postmaster_alive_fds, POSTMASTER_FD_OWN, ReleaseExternalFD(), and syslogPipe.

Referenced by postmaster_child_launch().

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1414 of file postmaster.c.

1415{
1416 int i;
1417
1418 /*
1419 * First, explicitly close all the socket FDs. We used to just let this
1420 * happen implicitly at postmaster exit, but it's better to close them
1421 * before we remove the postmaster.pid lockfile; otherwise there's a race
1422 * condition if a new postmaster wants to re-use the TCP port number.
1423 */
1424 for (i = 0; i < NumListenSockets; i++)
1425 {
1426 if (closesocket(ListenSockets[i]) != 0)
1427 elog(LOG, "could not close listen socket: %m");
1428 }
1429 NumListenSockets = 0;
1430
1431 /*
1432 * Next, remove any filesystem entries for Unix sockets. To avoid race
1433 * conditions against incoming postmasters, this must happen after closing
1434 * the sockets and before removing lock files.
1435 */
1437
1438 /*
1439 * We don't do anything about socket lock files here; those will be
1440 * removed in a later on_proc_exit callback.
1441 */
1442}
void RemoveSocketFiles(void)
Definition: pqcomm.c:848

References closesocket, elog, i, ListenSockets, LOG, NumListenSockets, and RemoveSocketFiles().

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1628 of file postmaster.c.

1629{
1630 if (pm_wait_set)
1632 pm_wait_set = NULL;
1633
1635 accept_connections ? (1 + NumListenSockets) : 1);
1637 NULL);
1638
1639 if (accept_connections)
1640 {
1641 for (int i = 0; i < NumListenSockets; i++)
1643 NULL, NULL);
1644 }
1645}
struct Latch * MyLatch
Definition: globals.c:62
#define PGINVALID_SOCKET
Definition: port.h:31
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: waiteventset.c:569
void FreeWaitEventSet(WaitEventSet *set)
Definition: waiteventset.c:480
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: waiteventset.c:363
#define WL_SOCKET_ACCEPT
Definition: waiteventset.h:51
#define WL_LATCH_SET
Definition: waiteventset.h:34

References AddWaitEventToSet(), CreateWaitEventSet(), FreeWaitEventSet(), i, ListenSockets, MyLatch, NumListenSockets, PGINVALID_SOCKET, pm_wait_set, WL_LATCH_SET, and WL_SOCKET_ACCEPT.

Referenced by HandleFatalError(), PostmasterStateMachine(), process_pm_child_exit(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( BackendTypeMask  targetMask)
static

Definition at line 3902 of file postmaster.c.

3903{
3904 dlist_iter iter;
3905 int cnt = 0;
3906
3908 {
3909 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3910
3911 /*
3912 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3913 * if any B_BACKEND backends have recently announced that they are
3914 * actually WAL senders.
3915 */
3916 if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3917 bp->bkend_type == B_BACKEND)
3918 {
3921 }
3922
3923 if (!btmask_contains(targetMask, bp->bkend_type))
3924 continue;
3925
3927 (errmsg_internal("%s process %d is still running",
3928 GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
3929
3930 cnt++;
3931 }
3932 return cnt;
3933}
#define DEBUG4
Definition: elog.h:27
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
@ B_WAL_SENDER
Definition: miscadmin.h:346
dlist_head ActiveChildList
Definition: pmchild.c:60
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:271
static bool btmask_contains(BackendTypeMask mask, BackendType t)
Definition: postmaster.c:193
dlist_node * cur
Definition: ilist.h:179

References ActiveChildList, B_BACKEND, B_WAL_SENDER, PMChild::bkend_type, btmask_contains(), PMChild::child_slot, dlist_iter::cur, DEBUG4, dlist_container, dlist_foreach, ereport, errmsg_internal(), GetBackendTypeDesc(), IsPostmasterChildWalSender(), and PMChild::pid.

Referenced by PostmasterStateMachine().

◆ CreateOptsFile()

static bool CreateOptsFile ( int  argc,
char *  argv[],
char *  fullprogname 
)
static

Definition at line 4067 of file postmaster.c.

4068{
4069 FILE *fp;
4070 int i;
4071
4072#define OPTS_FILE "postmaster.opts"
4073
4074 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4075 {
4076 ereport(LOG,
4078 errmsg("could not create file \"%s\": %m", OPTS_FILE)));
4079 return false;
4080 }
4081
4082 fprintf(fp, "%s", fullprogname);
4083 for (i = 1; i < argc; i++)
4084 fprintf(fp, " \"%s\"", argv[i]);
4085 fputs("\n", fp);
4086
4087 if (fclose(fp))
4088 {
4089 ereport(LOG,
4091 errmsg("could not write file \"%s\": %m", OPTS_FILE)));
4092 return false;
4093 }
4094
4095 return true;
4096}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
#define OPTS_FILE

References ereport, errcode_for_file_access(), errmsg(), fprintf, i, LOG, and OPTS_FILE.

Referenced by PostmasterMain().

◆ DetermineSleepTime()

static int DetermineSleepTime ( void  )
static

Definition at line 1543 of file postmaster.c.

1544{
1545 TimestampTz next_wakeup = 0;
1546
1547 /*
1548 * Normal case: either there are no background workers at all, or we're in
1549 * a shutdown sequence (during which we ignore bgworkers altogether).
1550 */
1551 if (Shutdown > NoShutdown ||
1553 {
1554 if (AbortStartTime != 0)
1555 {
1556 int seconds;
1557
1558 /* time left to abort; clamp to 0 in case it already expired */
1559 seconds = SIGKILL_CHILDREN_AFTER_SECS -
1560 (time(NULL) - AbortStartTime);
1561
1562 return Max(seconds * 1000, 0);
1563 }
1564 else
1565 return 60 * 1000;
1566 }
1567
1569 return 0;
1570
1572 {
1573 dlist_mutable_iter iter;
1574
1575 /*
1576 * When there are crashed bgworkers, we sleep just long enough that
1577 * they are restarted when they request to be. Scan the list to
1578 * determine the minimum of all wakeup times according to most recent
1579 * crash time and requested restart interval.
1580 */
1582 {
1584 TimestampTz this_wakeup;
1585
1586 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
1587
1588 if (rw->rw_crashed_at == 0)
1589 continue;
1590
1592 || rw->rw_terminate)
1593 {
1595 continue;
1596 }
1597
1599 1000L * rw->rw_worker.bgw_restart_time);
1600 if (next_wakeup == 0 || this_wakeup < next_wakeup)
1601 next_wakeup = this_wakeup;
1602 }
1603 }
1604
1605 if (next_wakeup != 0)
1606 {
1607 int ms;
1608
1609 /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1611 next_wakeup);
1612 return Min(60 * 1000, ms);
1613 }
1614
1615 return 60 * 1000;
1616}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1756
dlist_head BackgroundWorkerList
Definition: bgworker.c:40
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition: bgworker.c:429
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Min(x, y)
Definition: c.h:975
#define Max(x, y)
Definition: c.h:969
int64 TimestampTz
Definition: timestamp.h:39
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:640
static time_t AbortStartTime
Definition: postmaster.c:364
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:367
static bool StartWorkerNeeded
Definition: postmaster.c:386
int bgw_restart_time
Definition: bgworker.h:95
dlist_node * cur
Definition: ilist.h:200
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85

References AbortStartTime, BackgroundWorkerList, BGW_NEVER_RESTART, BackgroundWorker::bgw_restart_time, dlist_mutable_iter::cur, dlist_container, dlist_foreach_modify, ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, Max, Min, NoShutdown, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, Shutdown, SIGKILL_CHILDREN_AFTER_SECS, StartWorkerNeeded, TimestampDifferenceMilliseconds(), and TimestampTzPlusMilliseconds.

Referenced by ServerLoop().

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 3894 of file postmaster.c.

3895{
3896}

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 3646 of file postmaster.c.

3647{
3648#ifdef HAVE_PTHREAD_IS_THREADED_NP
3649
3650 /*
3651 * There is no known cause for a postmaster to become multithreaded after
3652 * startup. However, we might reach here via an error exit before
3653 * reaching the test in PostmasterMain, so provide the same hint as there.
3654 * This message uses LOG level, because an unclean shutdown at this point
3655 * would usually not look much different from a clean shutdown.
3656 */
3657 if (pthread_is_threaded_np() != 0)
3658 ereport(LOG,
3659 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3660 errmsg("postmaster became multithreaded"),
3661 errhint("Set the LC_ALL environment variable to a valid locale.")));
3662#endif
3663
3664 /* should cleanup shared memory and kill all backends */
3665
3666 /*
3667 * Not sure of the semantics here. When the Postmaster dies, should the
3668 * backends all be killed? probably not.
3669 *
3670 * MUST -- vadim 05-10-1999
3671 */
3672
3673 proc_exit(status);
3674}
int errhint(const char *fmt,...)
Definition: elog.c:1317
void proc_exit(int code)
Definition: ipc.c:104

References ereport, errcode(), errhint(), errmsg(), LOG, and proc_exit().

Referenced by checkControlFile(), PostmasterMain(), PostmasterStateMachine(), process_pm_child_exit(), and StartChildProcess().

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1460 of file postmaster.c.

1461{
1462 DIR *pdir;
1463
1464 /* Locate the postgres executable itself */
1466 ereport(FATAL,
1467 (errmsg("%s: could not locate my own executable path", argv0)));
1468
1469#ifdef EXEC_BACKEND
1470 /* Locate executable backend before we change working directory */
1472 postgres_exec_path) < 0)
1473 ereport(FATAL,
1474 (errmsg("%s: could not locate matching postgres executable",
1475 argv0)));
1476#endif
1477
1478 /*
1479 * Locate the pkglib directory --- this has to be set early in case we try
1480 * to load any modules from it in response to postgresql.conf entries.
1481 */
1483
1484 /*
1485 * Verify that there's a readable directory there; otherwise the Postgres
1486 * installation is incomplete or corrupt. (A typical cause of this
1487 * failure is that the postgres executable has been moved or hardlinked to
1488 * some directory that's not a sibling of the installation lib/
1489 * directory.)
1490 */
1491 pdir = AllocateDir(pkglib_path);
1492 if (pdir == NULL)
1493 ereport(ERROR,
1495 errmsg("could not open directory \"%s\": %m",
1496 pkglib_path),
1497 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1498 my_exec_path)));
1499 FreeDir(pdir);
1500
1501 /*
1502 * It's not worth checking the share/ directory. If the lib/ directory is
1503 * there, then share/ probably is too.
1504 */
1505}
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:310
#define ERROR
Definition: elog.h:39
int FreeDir(DIR *dir)
Definition: fd.c:2983
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2865
char pkglib_path[MAXPGPATH]
Definition: globals.c:81
char my_exec_path[MAXPGPATH]
Definition: globals.c:80
static char * argv0
Definition: pg_ctl.c:93
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:956
#define PG_BACKEND_VERSIONSTR
Definition: port.h:144
Definition: dirent.c:26

References AllocateDir(), argv0, ereport, errcode_for_file_access(), errhint(), errmsg(), ERROR, FATAL, find_my_exec(), find_other_exec(), FreeDir(), get_pkglib_path(), my_exec_path, PG_BACKEND_VERSIONSTR, and pkglib_path.

Referenced by PostmasterMain().

◆ handle_pm_child_exit_signal()

static void handle_pm_child_exit_signal ( SIGNAL_ARGS  )
static

Definition at line 2222 of file postmaster.c.

2223{
2224 pending_pm_child_exit = true;
2226}
void SetLatch(Latch *latch)
Definition: latch.c:288
static volatile sig_atomic_t pending_pm_child_exit
Definition: postmaster.c:391

References MyLatch, pending_pm_child_exit, and SetLatch().

Referenced by PostmasterMain().

◆ handle_pm_pmsignal_signal()

static void handle_pm_pmsignal_signal ( SIGNAL_ARGS  )
static

Definition at line 1974 of file postmaster.c.

1975{
1976 pending_pm_pmsignal = true;
1978}
static volatile sig_atomic_t pending_pm_pmsignal
Definition: postmaster.c:390

References MyLatch, pending_pm_pmsignal, and SetLatch().

Referenced by PostmasterMain().

◆ handle_pm_reload_request_signal()

static void handle_pm_reload_request_signal ( SIGNAL_ARGS  )
static

Definition at line 1984 of file postmaster.c.

1985{
1988}
static volatile sig_atomic_t pending_pm_reload_request
Definition: postmaster.c:392

References MyLatch, pending_pm_reload_request, and SetLatch().

Referenced by PostmasterMain().

◆ handle_pm_shutdown_request_signal()

static void handle_pm_shutdown_request_signal ( SIGNAL_ARGS  )
static

Definition at line 2047 of file postmaster.c.

2048{
2049 switch (postgres_signal_arg)
2050 {
2051 case SIGTERM:
2052 /* smart is implied if the other two flags aren't set */
2054 break;
2055 case SIGINT:
2058 break;
2059 case SIGQUIT:
2062 break;
2063 }
2065}
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition: postmaster.c:394
static volatile sig_atomic_t pending_pm_shutdown_request
Definition: postmaster.c:393
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition: postmaster.c:395
#define SIGQUIT
Definition: win32_port.h:159

References MyLatch, pending_pm_fast_shutdown_request, pending_pm_immediate_shutdown_request, pending_pm_shutdown_request, SetLatch(), and SIGQUIT.

Referenced by PostmasterMain().

◆ HandleChildCrash()

static void HandleChildCrash ( int  pid,
int  exitstatus,
const char *  procname 
)
static

Definition at line 2783 of file postmaster.c.

2784{
2785 /*
2786 * We only log messages and send signals if this is the first process
2787 * crash and we're not doing an immediate shutdown; otherwise, we're only
2788 * here to update postmaster's idea of live processes. If we have already
2789 * signaled children, nonzero exit status is to be expected, so don't
2790 * clutter log.
2791 */
2793 return;
2794
2795 LogChildExit(LOG, procname, pid, exitstatus);
2796 ereport(LOG,
2797 (errmsg("terminating any other active server processes")));
2798
2799 /*
2800 * Switch into error state. The crashed process has already been removed
2801 * from ActiveChildList.
2802 */
2804}
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:54
#define ImmediateShutdown
Definition: postmaster.c:285
static void HandleFatalError(QuitSignalReason reason, bool consider_sigabrt)
Definition: postmaster.c:2694

References ereport, errmsg(), FatalError, HandleFatalError(), ImmediateShutdown, LOG, LogChildExit(), PMQUIT_FOR_CRASH, and Shutdown.

Referenced by CleanupBackend(), and process_pm_child_exit().

◆ HandleFatalError()

static void HandleFatalError ( QuitSignalReason  reason,
bool  consider_sigabrt 
)
static

Definition at line 2694 of file postmaster.c.

2695{
2696 int sigtosend;
2697
2700
2701 SetQuitSignalReason(reason);
2702
2703 if (consider_sigabrt && send_abort_for_crash)
2704 sigtosend = SIGABRT;
2705 else
2706 sigtosend = SIGQUIT;
2707
2708 /*
2709 * Signal all other child processes to exit.
2710 *
2711 * We could exclude dead-end children here, but at least when sending
2712 * SIGABRT it seems better to include them.
2713 */
2714 TerminateChildren(sigtosend);
2715
2716 FatalError = true;
2717
2718 /*
2719 * Choose the appropriate new state to react to the fatal error. Unless we
2720 * were already in the process of shutting down, we go through
2721 * PM_WAIT_BACKEND. For errors during the shutdown sequence, we directly
2722 * switch to PM_WAIT_DEAD_END.
2723 */
2724 switch (pmState)
2725 {
2726 case PM_INIT:
2727 /* shouldn't have any children */
2728 Assert(false);
2729 break;
2730 case PM_STARTUP:
2731 /* should have been handled in process_pm_child_exit */
2732 Assert(false);
2733 break;
2734
2735 /* wait for children to die */
2736 case PM_RECOVERY:
2737 case PM_HOT_STANDBY:
2738 case PM_RUN:
2739 case PM_STOP_BACKENDS:
2741 break;
2742
2743 case PM_WAIT_BACKENDS:
2744 /* there might be more backends to wait for */
2745 break;
2746
2750 case PM_WAIT_IO_WORKERS:
2751
2752 /*
2753 * NB: Similar code exists in PostmasterStateMachine()'s handling
2754 * of FatalError in PM_STOP_BACKENDS/PM_WAIT_BACKENDS states.
2755 */
2758 break;
2759
2760 case PM_WAIT_DEAD_END:
2761 case PM_NO_CHILDREN:
2762 break;
2763 }
2764
2765 /*
2766 * .. and if this doesn't happen quickly enough, now the clock is ticking
2767 * for us to kill them without mercy.
2768 */
2769 if (AbortStartTime == 0)
2770 AbortStartTime = time(NULL);
2771}
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:202
static void TerminateChildren(int signal)
Definition: postmaster.c:3510
static void UpdatePMState(PMState newState)
Definition: postmaster.c:3262
bool send_abort_for_crash
Definition: postmaster.c:255
static void ConfigurePostmasterWaitSet(bool accept_connections)
Definition: postmaster.c:1628
#define SIGABRT
Definition: win32_port.h:161

References AbortStartTime, Assert(), ConfigurePostmasterWaitSet(), FatalError, ImmediateShutdown, PM_HOT_STANDBY, PM_INIT, PM_NO_CHILDREN, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_CHECKPOINTER, PM_WAIT_DEAD_END, PM_WAIT_IO_WORKERS, PM_WAIT_XLOG_ARCHIVAL, PM_WAIT_XLOG_SHUTDOWN, pmState, send_abort_for_crash, SetQuitSignalReason(), Shutdown, SIGABRT, SIGQUIT, TerminateChildren(), and UpdatePMState().

Referenced by HandleChildCrash(), PostmasterStateMachine(), and process_pm_pmsignal().

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 4564 of file postmaster.c.

4565{
4566#ifndef WIN32
4567
4568 /*
4569 * Create a pipe. Postmaster holds the write end of the pipe open
4570 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
4571 * the read file descriptor to select() to wake up in case postmaster
4572 * dies, or check for postmaster death with a (read() == 0). Children must
4573 * close the write end as soon as possible after forking, because EOF
4574 * won't be signaled in the read end until all processes have closed the
4575 * write fd. That is taken care of in ClosePostmasterPorts().
4576 */
4578 if (pipe(postmaster_alive_fds) < 0)
4579 ereport(FATAL,
4581 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
4582
4583 /* Notify fd.c that we've eaten two FDs for the pipe. */
4586
4587 /*
4588 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
4589 * call.
4590 */
4591 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
4592 ereport(FATAL,
4594 errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
4595#else
4596
4597 /*
4598 * On Windows, we use a process handle for the same purpose.
4599 */
4600 if (DuplicateHandle(GetCurrentProcess(),
4601 GetCurrentProcess(),
4602 GetCurrentProcess(),
4603 &PostmasterHandle,
4604 0,
4605 TRUE,
4606 DUPLICATE_SAME_ACCESS) == 0)
4607 ereport(FATAL,
4608 (errmsg_internal("could not duplicate postmaster handle: error code %lu",
4609 GetLastError())));
4610#endif /* WIN32 */
4611}
int errcode_for_socket_access(void)
Definition: elog.c:953
void ReserveExternalFD(void)
Definition: fd.c:1220
pid_t PostmasterPid
Definition: globals.c:105
int MyProcPid
Definition: globals.c:46
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:83

References Assert(), ereport, errcode_for_file_access(), errcode_for_socket_access(), errmsg_internal(), FATAL, MyProcPid, postmaster_alive_fds, POSTMASTER_FD_WATCH, PostmasterPid, and ReserveExternalFD().

Referenced by PostmasterMain().

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 1932 of file postmaster.c.

1933{
1936
1937 /*
1938 * Set a different global seed in every process. We want something
1939 * unpredictable, so if possible, use high-quality random bits for the
1940 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1941 */
1943 {
1944 uint64 rseed;
1945
1946 /*
1947 * Since PIDs and timestamps tend to change more frequently in their
1948 * least significant bits, shift the timestamp left to allow a larger
1949 * total number of seeds in a given time period. Since that would
1950 * leave only 20 bits of the timestamp that cycle every ~1 second,
1951 * also mix in some higher bits.
1952 */
1953 rseed = ((uint64) MyProcPid) ^
1954 ((uint64) MyStartTimestamp << 12) ^
1955 ((uint64) MyStartTimestamp >> 20);
1956
1958 }
1959
1960 /*
1961 * Also make sure that we've set a good seed for random(3). Use of that
1962 * is deprecated in core Postgres, but extensions might use it.
1963 */
1964#ifndef WIN32
1966#endif
1967}
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1841
uint64_t uint64
Definition: c.h:503
#define unlikely(x)
Definition: c.h:347
TimestampTz MyStartTimestamp
Definition: globals.c:48
pg_time_t MyStartTime
Definition: globals.c:47
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:227
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define pg_prng_strong_seed(state)
Definition: pg_prng.h:46

References GetCurrentTimestamp(), MyProcPid, MyStartTime, MyStartTimestamp, pg_global_prng_state, pg_prng_seed(), pg_prng_strong_seed, pg_prng_uint32(), timestamptz_to_time_t(), and unlikely.

Referenced by InitPostmasterChild(), InitStandaloneProcess(), and PostmasterMain().

◆ LaunchMissingBackgroundProcesses()

static void LaunchMissingBackgroundProcesses ( void  )
static

Definition at line 3278 of file postmaster.c.

3279{
3280 /* Syslogger is active in all states */
3281 if (SysLoggerPMChild == NULL && Logging_collector)
3283
3284 /*
3285 * The number of configured workers might have changed, or a prior start
3286 * of a worker might have failed. Check if we need to start/stop any
3287 * workers.
3288 *
3289 * A config file change will always lead to this function being called, so
3290 * we always will process the config change in a timely manner.
3291 */
3293
3294 /*
3295 * The checkpointer and the background writer are active from the start,
3296 * until shutdown is initiated.
3297 *
3298 * (If the checkpointer is not running when we enter the
3299 * PM_WAIT_XLOG_SHUTDOWN state, it is launched one more time to perform
3300 * the shutdown checkpoint. That's done in PostmasterStateMachine(), not
3301 * here.)
3302 */
3303 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
3305 {
3306 if (CheckpointerPMChild == NULL)
3308 if (BgWriterPMChild == NULL)
3310 }
3311
3312 /*
3313 * WAL writer is needed only in normal operation (else we cannot be
3314 * writing any new WAL).
3315 */
3316 if (WalWriterPMChild == NULL && pmState == PM_RUN)
3318
3319 /*
3320 * We don't want autovacuum to run in binary upgrade mode because
3321 * autovacuum might update relfrozenxid for empty tables before the
3322 * physical files are put in place.
3323 */
3324 if (!IsBinaryUpgrade && AutoVacLauncherPMChild == NULL &&
3326 pmState == PM_RUN)
3327 {
3329 if (AutoVacLauncherPMChild != NULL)
3330 start_autovac_launcher = false; /* signal processed */
3331 }
3332
3333 /*
3334 * If WAL archiving is enabled always, we are allowed to start archiver
3335 * even during recovery.
3336 */
3337 if (PgArchPMChild == NULL &&
3338 ((XLogArchivingActive() && pmState == PM_RUN) ||
3342
3343 /*
3344 * If we need to start a slot sync worker, try to do that now
3345 *
3346 * We allow to start the slot sync worker when we are on a hot standby,
3347 * fast or immediate shutdown is not in progress, slot sync parameters are
3348 * configured correctly, and it is the first time of worker's launch, or
3349 * enough time has passed since the worker was launched last.
3350 */
3351 if (SlotSyncWorkerPMChild == NULL && pmState == PM_HOT_STANDBY &&
3355
3356 /*
3357 * If we need to start a WAL receiver, try to do that now
3358 *
3359 * Note: if a walreceiver process is already running, it might seem that
3360 * we should clear WalReceiverRequested. However, there's a race
3361 * condition if the walreceiver terminates and the startup process
3362 * immediately requests a new one: it's quite possible to get the signal
3363 * for the request before reaping the dead walreceiver process. Better to
3364 * risk launching an extra walreceiver than to miss launching one we need.
3365 * (The walreceiver code has logic to recognize that it should go away if
3366 * not needed.)
3367 */
3369 {
3370 if (WalReceiverPMChild == NULL &&
3372 pmState == PM_HOT_STANDBY) &&
3374 {
3376 if (WalReceiverPMChild != 0)
3377 WalReceiverRequested = false;
3378 /* else leave the flag set, so we'll try again later */
3379 }
3380 }
3381
3382 /* If we need to start a WAL summarizer, try to do that now */
3383 if (summarize_wal && WalSummarizerPMChild == NULL &&
3384 (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
3387
3388 /* Get other worker processes running, if needed */
3391}
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3248
bool IsBinaryUpgrade
Definition: globals.c:120
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:366
@ B_WAL_WRITER
Definition: miscadmin.h:367
@ B_WAL_RECEIVER
Definition: miscadmin.h:365
@ B_CHECKPOINTER
Definition: miscadmin.h:362
@ B_BG_WRITER
Definition: miscadmin.h:361
@ B_ARCHIVER
Definition: miscadmin.h:360
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:343
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:347
bool PgArchCanRestart(void)
Definition: pgarch.c:196
#define SmartShutdown
Definition: postmaster.c:283
static PMChild * PgArchPMChild
Definition: postmaster.c:266
static void maybe_start_bgworkers(void)
Definition: postmaster.c:4217
static void StartSysLogger(void)
Definition: postmaster.c:3992
static PMChild * AutoVacLauncherPMChild
Definition: postmaster.c:265
static PMChild * BgWriterPMChild
Definition: postmaster.c:260
static PMChild * StartChildProcess(BackendType type)
Definition: postmaster.c:3946
static bool start_autovac_launcher
Definition: postmaster.c:377
static PMChild * WalReceiverPMChild
Definition: postmaster.c:263
static PMChild * WalWriterPMChild
Definition: postmaster.c:262
static PMChild * WalSummarizerPMChild
Definition: postmaster.c:264
static void maybe_adjust_io_workers(void)
Definition: postmaster.c:4356
static PMChild * SysLoggerPMChild
Definition: postmaster.c:267
static bool WalReceiverRequested
Definition: postmaster.c:383
static PMChild * CheckpointerPMChild
Definition: postmaster.c:261
static PMChild * SlotSyncWorkerPMChild
Definition: postmaster.c:268
bool sync_replication_slots
Definition: slotsync.c:107
bool SlotSyncWorkerCanRestart(void)
Definition: slotsync.c:1627
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1037
bool Logging_collector
Definition: syslogger.c:70
bool summarize_wal
#define XLogArchivingActive()
Definition: xlog.h:99
#define XLogArchivingAlways()
Definition: xlog.h:102

References AutoVacLauncherPMChild, AutoVacuumingActive(), B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_BG_WRITER, B_CHECKPOINTER, B_SLOTSYNC_WORKER, B_WAL_RECEIVER, B_WAL_SUMMARIZER, B_WAL_WRITER, BgWriterPMChild, CheckpointerPMChild, HaveCrashedWorker, IsBinaryUpgrade, LOG, Logging_collector, maybe_adjust_io_workers(), maybe_start_bgworkers(), PgArchCanRestart(), PgArchPMChild, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, pmState, Shutdown, SlotSyncWorkerCanRestart(), SlotSyncWorkerPMChild, SmartShutdown, start_autovac_launcher, StartChildProcess(), StartSysLogger(), StartWorkerNeeded, summarize_wal, sync_replication_slots, SysLoggerPMChild, ValidateSlotSyncParams(), WalReceiverPMChild, WalReceiverRequested, WalSummarizerPMChild, WalWriterPMChild, XLogArchivingActive, and XLogArchivingAlways.

Referenced by ServerLoop().

◆ LogChildExit()

static void LogChildExit ( int  lev,
const char *  procname,
int  pid,
int  exitstatus 
)
static

Definition at line 2810 of file postmaster.c.

2811{
2812 /*
2813 * size of activity_buffer is arbitrary, but set equal to default
2814 * track_activity_query_size
2815 */
2816 char activity_buffer[1024];
2817 const char *activity = NULL;
2818
2819 if (!EXIT_STATUS_0(exitstatus))
2821 activity_buffer,
2822 sizeof(activity_buffer));
2823
2824 if (WIFEXITED(exitstatus))
2825 ereport(lev,
2826
2827 /*------
2828 translator: %s is a noun phrase describing a child process, such as
2829 "server process" */
2830 (errmsg("%s (PID %d) exited with exit code %d",
2831 procname, pid, WEXITSTATUS(exitstatus)),
2832 activity ? errdetail("Failed process was running: %s", activity) : 0));
2833 else if (WIFSIGNALED(exitstatus))
2834 {
2835#if defined(WIN32)
2836 ereport(lev,
2837
2838 /*------
2839 translator: %s is a noun phrase describing a child process, such as
2840 "server process" */
2841 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2842 procname, pid, WTERMSIG(exitstatus)),
2843 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2844 activity ? errdetail("Failed process was running: %s", activity) : 0));
2845#else
2846 ereport(lev,
2847
2848 /*------
2849 translator: %s is a noun phrase describing a child process, such as
2850 "server process" */
2851 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2852 procname, pid, WTERMSIG(exitstatus),
2853 pg_strsignal(WTERMSIG(exitstatus))),
2854 activity ? errdetail("Failed process was running: %s", activity) : 0));
2855#endif
2856 }
2857 else
2858 ereport(lev,
2859
2860 /*------
2861 translator: %s is a noun phrase describing a child process, such as
2862 "server process" */
2863 (errmsg("%s (PID %d) exited with unrecognized status %d",
2864 procname, pid, exitstatus),
2865 activity ? errdetail("Failed process was running: %s", activity) : 0));
2866}
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
int errdetail(const char *fmt,...)
Definition: elog.c:1203
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:39
#define WIFEXITED(w)
Definition: win32_port.h:150
#define WIFSIGNALED(w)
Definition: win32_port.h:151
#define WTERMSIG(w)
Definition: win32_port.h:153
#define WEXITSTATUS(w)
Definition: win32_port.h:152

References ereport, errdetail(), errhint(), errmsg(), EXIT_STATUS_0, pg_strsignal(), pgstat_get_crashed_backend_activity(), WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by CleanupBackend(), HandleChildCrash(), and process_pm_child_exit().

◆ maybe_adjust_io_workers()

static void maybe_adjust_io_workers ( void  )
static

Definition at line 4356 of file postmaster.c.

4357{
4358 if (!pgaio_workers_enabled())
4359 return;
4360
4361 /*
4362 * If we're in final shutting down state, then we're just waiting for all
4363 * processes to exit.
4364 */
4366 return;
4367
4368 /* Don't start new workers during an immediate shutdown either. */
4370 return;
4371
4372 /*
4373 * Don't start new workers if we're in the shutdown phase of a crash
4374 * restart. But we *do* need to start if we're already starting up again.
4375 */
4377 return;
4378
4380
4381 /* Not enough running? */
4382 while (io_worker_count < io_workers)
4383 {
4384 PMChild *child;
4385 int id;
4386
4387 /* find unused entry in io_worker_children array */
4388 for (id = 0; id < MAX_IO_WORKERS; ++id)
4389 {
4390 if (io_worker_children[id] == NULL)
4391 break;
4392 }
4393 if (id == MAX_IO_WORKERS)
4394 elog(ERROR, "could not find a free IO worker ID");
4395
4396 /* Try to launch one. */
4398 if (child != NULL)
4399 {
4400 io_worker_children[id] = child;
4402 }
4403 else
4404 break; /* XXX try again soon? */
4405 }
4406
4407 /* Too many running? */
4409 {
4410 /* ask the IO worker in the highest slot to exit */
4411 for (int id = MAX_IO_WORKERS - 1; id >= 0; --id)
4412 {
4413 if (io_worker_children[id] != NULL)
4414 {
4415 kill(io_worker_children[id]->pid, SIGUSR2);
4416 break;
4417 }
4418 }
4419 }
4420}
bool pgaio_workers_enabled(void)
int io_workers
Definition: method_worker.c:92
@ B_IO_WORKER
Definition: miscadmin.h:363
static PMChild * io_worker_children[MAX_IO_WORKERS]
Definition: postmaster.c:411
static int io_worker_count
Definition: postmaster.c:410
#define MAX_IO_WORKERS
Definition: proc.h:446
#define kill(pid, sig)
Definition: win32_port.h:493
#define SIGUSR2
Definition: win32_port.h:171

References Assert(), B_IO_WORKER, elog, ERROR, FatalError, ImmediateShutdown, io_worker_children, io_worker_count, io_workers, kill, MAX_IO_WORKERS, pgaio_workers_enabled(), PM_STOP_BACKENDS, PM_WAIT_IO_WORKERS, pmState, Shutdown, SIGUSR2, and StartChildProcess().

Referenced by LaunchMissingBackgroundProcesses(), PostmasterMain(), PostmasterStateMachine(), and process_pm_child_exit().

◆ maybe_reap_io_worker()

static bool maybe_reap_io_worker ( int  pid)
static

Definition at line 4331 of file postmaster.c.

4332{
4333 for (int id = 0; id < MAX_IO_WORKERS; ++id)
4334 {
4335 if (io_worker_children[id] &&
4336 io_worker_children[id]->pid == pid)
4337 {
4339
4341 io_worker_children[id] = NULL;
4342 return true;
4343 }
4344 }
4345 return false;
4346}

References io_worker_children, io_worker_count, MAX_IO_WORKERS, and ReleasePostmasterChildSlot().

Referenced by process_pm_child_exit().

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 4217 of file postmaster.c.

4218{
4219#define MAX_BGWORKERS_TO_LAUNCH 100
4220 int num_launched = 0;
4221 TimestampTz now = 0;
4222 dlist_mutable_iter iter;
4223
4224 /*
4225 * During crash recovery, we have no need to be called until the state
4226 * transition out of recovery.
4227 */
4228 if (FatalError)
4229 {
4230 StartWorkerNeeded = false;
4231 HaveCrashedWorker = false;
4232 return;
4233 }
4234
4235 /* Don't need to be called again unless we find a reason for it below */
4236 StartWorkerNeeded = false;
4237 HaveCrashedWorker = false;
4238
4240 {
4242
4243 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
4244
4245 /* ignore if already running */
4246 if (rw->rw_pid != 0)
4247 continue;
4248
4249 /* if marked for death, clean up and remove from list */
4250 if (rw->rw_terminate)
4251 {
4253 continue;
4254 }
4255
4256 /*
4257 * If this worker has crashed previously, maybe it needs to be
4258 * restarted (unless on registration it specified it doesn't want to
4259 * be restarted at all). Check how long ago did a crash last happen.
4260 * If the last crash is too recent, don't start it right away; let it
4261 * be restarted once enough time has passed.
4262 */
4263 if (rw->rw_crashed_at != 0)
4264 {
4266 {
4267 int notify_pid;
4268
4269 notify_pid = rw->rw_worker.bgw_notify_pid;
4270
4272
4273 /* Report worker is gone now. */
4274 if (notify_pid != 0)
4275 kill(notify_pid, SIGUSR1);
4276
4277 continue;
4278 }
4279
4280 /* read system time only when needed */
4281 if (now == 0)
4283
4285 rw->rw_worker.bgw_restart_time * 1000))
4286 {
4287 /* Set flag to remember that we have workers to start later */
4288 HaveCrashedWorker = true;
4289 continue;
4290 }
4291 }
4292
4294 {
4295 /* reset crash time before trying to start worker */
4296 rw->rw_crashed_at = 0;
4297
4298 /*
4299 * Try to start the worker.
4300 *
4301 * On failure, give up processing workers for now, but set
4302 * StartWorkerNeeded so we'll come back here on the next iteration
4303 * of ServerLoop to try again. (We don't want to wait, because
4304 * there might be additional ready-to-run workers.) We could set
4305 * HaveCrashedWorker as well, since this worker is now marked
4306 * crashed, but there's no need because the next run of this
4307 * function will do that.
4308 */
4309 if (!StartBackgroundWorker(rw))
4310 {
4311 StartWorkerNeeded = true;
4312 return;
4313 }
4314
4315 /*
4316 * If we've launched as many workers as allowed, quit, but have
4317 * ServerLoop call us again to look for additional ready-to-run
4318 * workers. There might not be any, but we'll find out the next
4319 * time we run.
4320 */
4321 if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
4322 {
4323 StartWorkerNeeded = true;
4324 return;
4325 }
4326 }
4327 }
4328}
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1780
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1608
static bool StartBackgroundWorker(RegisteredBgWorker *rw)
Definition: postmaster.c:4109
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:4170
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
pid_t bgw_notify_pid
Definition: bgworker.h:100
#define SIGUSR1
Definition: win32_port.h:170

References BackgroundWorkerList, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, bgworker_should_start_now(), dlist_mutable_iter::cur, dlist_container, dlist_foreach_modify, FatalError, ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, kill, MAX_BGWORKERS_TO_LAUNCH, now(), RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SIGUSR1, StartBackgroundWorker(), StartWorkerNeeded, and TimestampDifferenceExceeds().

Referenced by LaunchMissingBackgroundProcesses(), and PostmasterMain().

◆ pm_signame()

static const char * pm_signame ( int  signal)
static

Definition at line 3401 of file postmaster.c.

3402{
3403#define PM_TOSTR_CASE(sym) case sym: return #sym
3404 switch (signal)
3405 {
3409 PM_TOSTR_CASE(SIGINT);
3412 PM_TOSTR_CASE(SIGTERM);
3415 default:
3416 /* all signals sent by postmaster should be listed here */
3417 Assert(false);
3418 return "(unknown)";
3419 }
3420#undef PM_TOSTR_CASE
3421
3422 return ""; /* silence compiler */
3423}
#define PM_TOSTR_CASE(sym)
#define SIGCHLD
Definition: win32_port.h:168
#define SIGHUP
Definition: win32_port.h:158
#define SIGKILL
Definition: win32_port.h:162

References Assert(), PM_TOSTR_CASE, SIGABRT, SIGCHLD, SIGHUP, SIGKILL, SIGQUIT, SIGUSR1, and SIGUSR2.

Referenced by signal_child().

◆ pmstate_name()

static const char * pmstate_name ( PMState  state)
static

◆ PostmasterMain()

void PostmasterMain ( int  argc,
char *  argv[] 
)

Definition at line 492 of file postmaster.c.

493{
494 int opt;
495 int status;
496 char *userDoption = NULL;
497 bool listen_addr_saved = false;
498 char *output_config_variable = NULL;
499
501
503
505
506 /*
507 * Start our win32 signal implementation
508 */
509#ifdef WIN32
511#endif
512
513 /*
514 * We should not be creating any files or directories before we check the
515 * data directory (see checkDataDir()), but just in case set the umask to
516 * the most restrictive (owner-only) permissions.
517 *
518 * checkDataDir() will reset the umask based on the data directory
519 * permissions.
520 */
521 umask(PG_MODE_MASK_OWNER);
522
523 /*
524 * By default, palloc() requests in the postmaster will be allocated in
525 * the PostmasterContext, which is space that can be recycled by backends.
526 * Allocated data that needs to be available to backends should be
527 * allocated in TopMemoryContext.
528 */
530 "Postmaster",
533
534 /* Initialize paths to installation files */
535 getInstallationPaths(argv[0]);
536
537 /*
538 * Set up signal handlers for the postmaster process.
539 *
540 * CAUTION: when changing this list, check for side-effects on the signal
541 * handling setup of child processes. See tcop/postgres.c,
542 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
543 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
544 * postmaster/bgworker.c and postmaster/checkpointer.c.
545 */
546 pqinitmask();
547 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
548
553 pqsignal(SIGALRM, SIG_IGN); /* ignored */
554 pqsignal(SIGPIPE, SIG_IGN); /* ignored */
556 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
558
559 /* This may configure SIGURG, depending on platform. */
562
563 /*
564 * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
565 * ignore those signals in a postmaster environment, so that there is no
566 * risk of a child process freezing up due to writing to stderr. But for
567 * a standalone backend, their default handling is reasonable. Hence, all
568 * child processes should just allow the inherited settings to stand.
569 */
570#ifdef SIGTTIN
571 pqsignal(SIGTTIN, SIG_IGN); /* ignored */
572#endif
573#ifdef SIGTTOU
574 pqsignal(SIGTTOU, SIG_IGN); /* ignored */
575#endif
576
577 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
578#ifdef SIGXFSZ
579 pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
580#endif
581
582 /* Begin accepting signals. */
583 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
584
585 /*
586 * Options setup
587 */
589
590 opterr = 1;
591
592 /*
593 * Parse command-line options. CAUTION: keep this in sync with
594 * tcop/postgres.c (the option sets should not conflict) and with the
595 * common help() function in main/main.c.
596 */
597 while ((opt = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:")) != -1)
598 {
599 switch (opt)
600 {
601 case 'B':
602 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
603 break;
604
605 case 'b':
606 /* Undocumented flag used for binary upgrades */
607 IsBinaryUpgrade = true;
608 break;
609
610 case 'C':
611 output_config_variable = strdup(optarg);
612 break;
613
614 case '-':
615
616 /*
617 * Error if the user misplaced a special must-be-first option
618 * for dispatching to a subprogram. parse_dispatch_option()
619 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
620 * error for anything else.
621 */
624 (errcode(ERRCODE_SYNTAX_ERROR),
625 errmsg("--%s must be first argument", optarg)));
626
627 /* FALLTHROUGH */
628 case 'c':
629 {
630 char *name,
631 *value;
632
634 if (!value)
635 {
636 if (opt == '-')
638 (errcode(ERRCODE_SYNTAX_ERROR),
639 errmsg("--%s requires a value",
640 optarg)));
641 else
643 (errcode(ERRCODE_SYNTAX_ERROR),
644 errmsg("-c %s requires a value",
645 optarg)));
646 }
647
649 pfree(name);
650 pfree(value);
651 break;
652 }
653
654 case 'D':
655 userDoption = strdup(optarg);
656 break;
657
658 case 'd':
660 break;
661
662 case 'E':
663 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
664 break;
665
666 case 'e':
667 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
668 break;
669
670 case 'F':
671 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
672 break;
673
674 case 'f':
676 {
677 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
680 }
681 break;
682
683 case 'h':
684 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
685 break;
686
687 case 'i':
688 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
689 break;
690
691 case 'j':
692 /* only used by interactive backend */
693 break;
694
695 case 'k':
696 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
697 break;
698
699 case 'l':
701 break;
702
703 case 'N':
704 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
705 break;
706
707 case 'O':
708 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
709 break;
710
711 case 'P':
712 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
713 break;
714
715 case 'p':
717 break;
718
719 case 'r':
720 /* only used by single-user backend */
721 break;
722
723 case 'S':
725 break;
726
727 case 's':
728 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
729 break;
730
731 case 'T':
732
733 /*
734 * This option used to be defined as sending SIGSTOP after a
735 * backend crash, but sending SIGABRT seems more useful.
736 */
737 SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
738 break;
739
740 case 't':
741 {
742 const char *tmp = get_stats_option_name(optarg);
743
744 if (tmp)
745 {
747 }
748 else
749 {
750 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
753 }
754 break;
755 }
756
757 case 'W':
758 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
759 break;
760
761 default:
762 write_stderr("Try \"%s --help\" for more information.\n",
763 progname);
765 }
766 }
767
768 /*
769 * Postmaster accepts no non-option switch arguments.
770 */
771 if (optind < argc)
772 {
773 write_stderr("%s: invalid argument: \"%s\"\n",
774 progname, argv[optind]);
775 write_stderr("Try \"%s --help\" for more information.\n",
776 progname);
778 }
779
780 /*
781 * Locate the proper configuration files and data directory, and read
782 * postgresql.conf for the first time.
783 */
786
787 if (output_config_variable != NULL)
788 {
789 /*
790 * If this is a runtime-computed GUC, it hasn't yet been initialized,
791 * and the present value is not useful. However, this is a convenient
792 * place to print the value for most GUCs because it is safe to run
793 * postmaster startup to this point even if the server is already
794 * running. For the handful of runtime-computed GUCs that we cannot
795 * provide meaningful values for yet, we wait until later in
796 * postmaster startup to print the value. We won't be able to use -C
797 * on running servers for those GUCs, but using this option now would
798 * lead to incorrect results for them.
799 */
800 int flags = GetConfigOptionFlags(output_config_variable, true);
801
802 if ((flags & GUC_RUNTIME_COMPUTED) == 0)
803 {
804 /*
805 * "-C guc" was specified, so print GUC's value and exit. No
806 * extra permission check is needed because the user is reading
807 * inside the data dir.
808 */
809 const char *config_val = GetConfigOption(output_config_variable,
810 false, false);
811
812 puts(config_val ? config_val : "");
814 }
815
816 /*
817 * A runtime-computed GUC will be printed later on. As we initialize
818 * a server startup sequence, silence any log messages that may show
819 * up in the output generated. FATAL and more severe messages are
820 * useful to show, even if one would only expect at least PANIC. LOG
821 * entries are hidden.
822 */
823 SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
825 }
826
827 /* Verify that DataDir looks reasonable */
828 checkDataDir();
829
830 /* Check that pg_control exists */
832
833 /* And switch working directory into it */
835
836 /*
837 * Check for invalid combinations of GUC settings.
838 */
840 {
841 write_stderr("%s: \"superuser_reserved_connections\" (%d) plus \"reserved_connections\" (%d) must be less than \"max_connections\" (%d)\n",
842 progname,
846 }
849 (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
852 (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
855 (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
856
857 /*
858 * Other one-time internal sanity checks can go here, if they are fast.
859 * (Put any slow processing further down, after postmaster.pid creation.)
860 */
862 {
863 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
865 }
866
867 /*
868 * Now that we are done processing the postmaster arguments, reset
869 * getopt(3) library so that it will work correctly in subprocesses.
870 */
871 optind = 1;
872#ifdef HAVE_INT_OPTRESET
873 optreset = 1; /* some systems need this too */
874#endif
875
876 /* For debugging: display postmaster environment */
878 {
879#if !defined(WIN32) || defined(_MSC_VER)
880 extern char **environ;
881#endif
882 char **p;
884
885 initStringInfo(&si);
886
887 appendStringInfoString(&si, "initial environment dump:");
888 for (p = environ; *p; ++p)
889 appendStringInfo(&si, "\n%s", *p);
890
892 pfree(si.data);
893 }
894
895 /*
896 * Create lockfile for data directory.
897 *
898 * We want to do this before we try to grab the input sockets, because the
899 * data directory interlock is more reliable than the socket-file
900 * interlock (thanks to whoever decided to put socket files in /tmp :-().
901 * For the same reason, it's best to grab the TCP socket(s) before the
902 * Unix socket(s).
903 *
904 * Also note that this internally sets up the on_proc_exit function that
905 * is responsible for removing both data directory and socket lockfiles;
906 * so it must happen before opening sockets so that at exit, the socket
907 * lockfiles go away after CloseServerPorts runs.
908 */
910
911 /*
912 * Read the control file (for error checking and config info).
913 *
914 * Since we verify the control file's CRC, this has a useful side effect
915 * on machines where we need a run-time test for CRC support instructions.
916 * The postmaster will do the test once at startup, and then its child
917 * processes will inherit the correct function pointer and not need to
918 * repeat the test.
919 */
921
922 /*
923 * Register the apply launcher. It's probably a good idea to call this
924 * before any modules had a chance to take the background worker slots.
925 */
927
928 /*
929 * process any libraries that should be preloaded at postmaster start
930 */
932
933 /*
934 * Initialize SSL library, if specified.
935 */
936#ifdef USE_SSL
937 if (EnableSSL)
938 {
939 (void) secure_initialize(true);
940 LoadedSSL = true;
941 }
942#endif
943
944 /*
945 * Now that loadable modules have had their chance to alter any GUCs,
946 * calculate MaxBackends and initialize the machinery to track child
947 * processes.
948 */
951
952 /*
953 * Calculate the size of the PGPROC fast-path lock arrays.
954 */
956
957 /*
958 * Give preloaded libraries a chance to request additional shared memory.
959 */
961
962 /*
963 * Now that loadable modules have had their chance to request additional
964 * shared memory, determine the value of any runtime-computed GUCs that
965 * depend on the amount of shared memory required.
966 */
968
969 /*
970 * Now that modules have been loaded, we can process any custom resource
971 * managers specified in the wal_consistency_checking GUC.
972 */
974
975 /*
976 * If -C was specified with a runtime-computed GUC, we held off printing
977 * the value earlier, as the GUC was not yet initialized. We handle -C
978 * for most GUCs before we lock the data directory so that the option may
979 * be used on a running server. However, a handful of GUCs are runtime-
980 * computed and do not have meaningful values until after locking the data
981 * directory, and we cannot safely calculate their values earlier on a
982 * running server. At this point, such GUCs should be properly
983 * initialized, and we haven't yet set up shared memory, so this is a good
984 * time to handle the -C option for these special GUCs.
985 */
986 if (output_config_variable != NULL)
987 {
988 const char *config_val = GetConfigOption(output_config_variable,
989 false, false);
990
991 puts(config_val ? config_val : "");
993 }
994
995 /*
996 * Set up shared memory and semaphores.
997 *
998 * Note: if using SysV shmem and/or semas, each postmaster startup will
999 * normally choose the same IPC keys. This helps ensure that we will
1000 * clean up dead IPC objects if the postmaster crashes and is restarted.
1001 */
1003
1004 /*
1005 * Estimate number of openable files. This must happen after setting up
1006 * semaphores, because on some platforms semaphores count as open files.
1007 */
1009
1010 /*
1011 * Initialize pipe (or process handle on Windows) that allows children to
1012 * wake up from sleep on postmaster death.
1013 */
1015
1016#ifdef WIN32
1017
1018 /*
1019 * Initialize I/O completion port used to deliver list of dead children.
1020 */
1021 win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1022 if (win32ChildQueue == NULL)
1023 ereport(FATAL,
1024 (errmsg("could not create I/O completion port for child queue")));
1025#endif
1026
1027#ifdef EXEC_BACKEND
1028 /* Write out nondefault GUC settings for child processes to use */
1029 write_nondefault_variables(PGC_POSTMASTER);
1030
1031 /*
1032 * Clean out the temp directory used to transmit parameters to child
1033 * processes (see internal_forkexec). We must do this before launching
1034 * any child processes, else we have a race condition: we could remove a
1035 * parameter file before the child can read it. It should be safe to do
1036 * so now, because we verified earlier that there are no conflicting
1037 * Postgres processes in this data directory.
1038 */
1040#endif
1041
1042 /*
1043 * Forcibly remove the files signaling a standby promotion request.
1044 * Otherwise, the existence of those files triggers a promotion too early,
1045 * whether a user wants that or not.
1046 *
1047 * This removal of files is usually unnecessary because they can exist
1048 * only during a few moments during a standby promotion. However there is
1049 * a race condition: if pg_ctl promote is executed and creates the files
1050 * during a promotion, the files can stay around even after the server is
1051 * brought up to be the primary. Then, if a new standby starts by using
1052 * the backup taken from the new primary, the files can exist at server
1053 * startup and must be removed in order to avoid an unexpected promotion.
1054 *
1055 * Note that promotion signal files need to be removed before the startup
1056 * process is invoked. Because, after that, they can be used by
1057 * postmaster's SIGUSR1 signal handler.
1058 */
1060
1061 /* Do the same for logrotate signal file */
1063
1064 /* Remove any outdated file holding the current log filenames. */
1065 if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1066 ereport(LOG,
1068 errmsg("could not remove file \"%s\": %m",
1070
1071 /*
1072 * If enabled, start up syslogger collection subprocess
1073 */
1076
1077 /*
1078 * Reset whereToSendOutput from DestDebug (its starting state) to
1079 * DestNone. This stops ereport from sending log messages to stderr unless
1080 * Log_destination permits. We don't do this until the postmaster is
1081 * fully launched, since startup failures may as well be reported to
1082 * stderr.
1083 *
1084 * If we are in fact disabling logging to stderr, first emit a log message
1085 * saying so, to provide a breadcrumb trail for users who may not remember
1086 * that their logging is configured to go somewhere else.
1087 */
1089 ereport(LOG,
1090 (errmsg("ending log output to stderr"),
1091 errhint("Future log output will go to log destination \"%s\".",
1093
1095
1096 /*
1097 * Report server startup in log. While we could emit this much earlier,
1098 * it seems best to do so after starting the log collector, if we intend
1099 * to use one.
1100 */
1101 ereport(LOG,
1102 (errmsg("starting %s", PG_VERSION_STR)));
1103
1104 /*
1105 * Establish input sockets.
1106 *
1107 * First set up an on_proc_exit function that's charged with closing the
1108 * sockets again at postmaster shutdown.
1109 */
1112
1113 if (ListenAddresses)
1114 {
1115 char *rawstring;
1116 List *elemlist;
1117 ListCell *l;
1118 int success = 0;
1119
1120 /* Need a modifiable copy of ListenAddresses */
1121 rawstring = pstrdup(ListenAddresses);
1122
1123 /* Parse string into list of hostnames */
1124 if (!SplitGUCList(rawstring, ',', &elemlist))
1125 {
1126 /* syntax error in list */
1127 ereport(FATAL,
1128 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1129 errmsg("invalid list syntax in parameter \"%s\"",
1130 "listen_addresses")));
1131 }
1132
1133 foreach(l, elemlist)
1134 {
1135 char *curhost = (char *) lfirst(l);
1136
1137 if (strcmp(curhost, "*") == 0)
1138 status = ListenServerPort(AF_UNSPEC, NULL,
1139 (unsigned short) PostPortNumber,
1140 NULL,
1143 MAXLISTEN);
1144 else
1145 status = ListenServerPort(AF_UNSPEC, curhost,
1146 (unsigned short) PostPortNumber,
1147 NULL,
1150 MAXLISTEN);
1151
1152 if (status == STATUS_OK)
1153 {
1154 success++;
1155 /* record the first successful host addr in lockfile */
1156 if (!listen_addr_saved)
1157 {
1159 listen_addr_saved = true;
1160 }
1161 }
1162 else
1164 (errmsg("could not create listen socket for \"%s\"",
1165 curhost)));
1166 }
1167
1168 if (!success && elemlist != NIL)
1169 ereport(FATAL,
1170 (errmsg("could not create any TCP/IP sockets")));
1171
1172 list_free(elemlist);
1173 pfree(rawstring);
1174 }
1175
1176#ifdef USE_BONJOUR
1177 /* Register for Bonjour only if we opened TCP socket(s) */
1179 {
1180 DNSServiceErrorType err;
1181
1182 /*
1183 * We pass 0 for interface_index, which will result in registering on
1184 * all "applicable" interfaces. It's not entirely clear from the
1185 * DNS-SD docs whether this would be appropriate if we have bound to
1186 * just a subset of the available network interfaces.
1187 */
1188 err = DNSServiceRegister(&bonjour_sdref,
1189 0,
1190 0,
1192 "_postgresql._tcp.",
1193 NULL,
1194 NULL,
1196 0,
1197 NULL,
1198 NULL,
1199 NULL);
1200 if (err != kDNSServiceErr_NoError)
1201 ereport(LOG,
1202 (errmsg("DNSServiceRegister() failed: error code %ld",
1203 (long) err)));
1204
1205 /*
1206 * We don't bother to read the mDNS daemon's reply, and we expect that
1207 * it will automatically terminate our registration when the socket is
1208 * closed at postmaster termination. So there's nothing more to be
1209 * done here. However, the bonjour_sdref is kept around so that
1210 * forked children can close their copies of the socket.
1211 */
1212 }
1213#endif
1214
1216 {
1217 char *rawstring;
1218 List *elemlist;
1219 ListCell *l;
1220 int success = 0;
1221
1222 /* Need a modifiable copy of Unix_socket_directories */
1223 rawstring = pstrdup(Unix_socket_directories);
1224
1225 /* Parse string into list of directories */
1226 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1227 {
1228 /* syntax error in list */
1229 ereport(FATAL,
1230 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1231 errmsg("invalid list syntax in parameter \"%s\"",
1232 "unix_socket_directories")));
1233 }
1234
1235 foreach(l, elemlist)
1236 {
1237 char *socketdir = (char *) lfirst(l);
1238
1239 status = ListenServerPort(AF_UNIX, NULL,
1240 (unsigned short) PostPortNumber,
1241 socketdir,
1244 MAXLISTEN);
1245
1246 if (status == STATUS_OK)
1247 {
1248 success++;
1249 /* record the first successful Unix socket in lockfile */
1250 if (success == 1)
1252 }
1253 else
1255 (errmsg("could not create Unix-domain socket in directory \"%s\"",
1256 socketdir)));
1257 }
1258
1259 if (!success && elemlist != NIL)
1260 ereport(FATAL,
1261 (errmsg("could not create any Unix-domain sockets")));
1262
1263 list_free_deep(elemlist);
1264 pfree(rawstring);
1265 }
1266
1267 /*
1268 * check that we have some socket to listen on
1269 */
1270 if (NumListenSockets == 0)
1271 ereport(FATAL,
1272 (errmsg("no socket created for listening")));
1273
1274 /*
1275 * If no valid TCP ports, write an empty line for listen address,
1276 * indicating the Unix socket must be used. Note that this line is not
1277 * added to the lock file until there is a socket backing it.
1278 */
1279 if (!listen_addr_saved)
1281
1282 /*
1283 * Record postmaster options. We delay this till now to avoid recording
1284 * bogus options (eg, unusable port number).
1285 */
1286 if (!CreateOptsFile(argc, argv, my_exec_path))
1287 ExitPostmaster(1);
1288
1289 /*
1290 * Write the external PID file if requested
1291 */
1293 {
1294 FILE *fpidfile = fopen(external_pid_file, "w");
1295
1296 if (fpidfile)
1297 {
1298 fprintf(fpidfile, "%d\n", MyProcPid);
1299 fclose(fpidfile);
1300
1301 /* Make PID file world readable */
1302 if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1303 write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
1305 }
1306 else
1307 write_stderr("%s: could not write external PID file \"%s\": %m\n",
1309
1311 }
1312
1313 /*
1314 * Remove old temporary files. At this point there can be no other
1315 * Postgres processes running in this directory, so this should be safe.
1316 */
1318
1319 /*
1320 * Initialize the autovacuum subsystem (again, no process start yet)
1321 */
1322 autovac_init();
1323
1324 /*
1325 * Load configuration files for client authentication.
1326 */
1327 if (!load_hba())
1328 {
1329 /*
1330 * It makes no sense to continue if we fail to load the HBA file,
1331 * since there is no way to connect to the database in this case.
1332 */
1333 ereport(FATAL,
1334 /* translator: %s is a configuration file */
1335 (errmsg("could not load %s", HbaFileName)));
1336 }
1337 if (!load_ident())
1338 {
1339 /*
1340 * We can start up without the IDENT file, although it means that you
1341 * cannot log in using any of the authentication methods that need a
1342 * user name mapping. load_ident() already logged the details of error
1343 * to the log.
1344 */
1345 }
1346
1347#ifdef HAVE_PTHREAD_IS_THREADED_NP
1348
1349 /*
1350 * On macOS, libintl replaces setlocale() with a version that calls
1351 * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1352 * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1353 * the process multithreaded. The postmaster calls sigprocmask() and
1354 * calls fork() without an immediate exec(), both of which have undefined
1355 * behavior in a multithreaded program. A multithreaded postmaster is the
1356 * normal case on Windows, which offers neither fork() nor sigprocmask().
1357 * Currently, macOS is the only platform having pthread_is_threaded_np(),
1358 * so we need not worry whether this HINT is appropriate elsewhere.
1359 */
1360 if (pthread_is_threaded_np() != 0)
1361 ereport(FATAL,
1362 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1363 errmsg("postmaster became multithreaded during startup"),
1364 errhint("Set the LC_ALL environment variable to a valid locale.")));
1365#endif
1366
1367 /*
1368 * Remember postmaster startup time
1369 */
1371
1372 /*
1373 * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1374 * see what's happening.
1375 */
1377
1379
1380 /* Make sure we can perform I/O while starting up. */
1382
1383 /* Start bgwriter and checkpointer so they can help with recovery */
1384 if (CheckpointerPMChild == NULL)
1386 if (BgWriterPMChild == NULL)
1388
1389 /*
1390 * We're ready to rock and roll...
1391 */
1393 Assert(StartupPMChild != NULL);
1395
1396 /* Some workers may be scheduled to start now */
1398
1399 status = ServerLoop();
1400
1401 /*
1402 * ServerLoop probably shouldn't ever return, but if it does, close down.
1403 */
1404 ExitPostmaster(status != STATUS_OK);
1405
1406 abort(); /* not reached */
1407}
void autovac_init(void)
Definition: autovacuum.c:3302
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:23
bool CheckDateTokenTables(void)
Definition: datetime.c:4927
TimestampTz PgStartTime
Definition: timestamp.c:53
int secure_initialize(bool isServerStart)
Definition: be-secure.c:75
@ DestNone
Definition: dest.h:87
int Log_destination
Definition: elog.c:110
bool message_level_is_interesting(int elevel)
Definition: elog.c:272
char * Log_destination_string
Definition: elog.c:111
#define DEBUG3
Definition: elog.h:28
#define WARNING
Definition: elog.h:36
#define LOG_DESTINATION_STDERR
Definition: elog.h:484
void err(int eval, const char *fmt,...)
Definition: err.c:43
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3356
void RemovePgTempFiles(void)
Definition: fd.c:3296
void set_max_safe_fds(void)
Definition: fd.c:1043
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
#define PG_TEMP_FILES_DIR
Definition: file_utils.h:62
int MaxConnections
Definition: globals.c:142
bool IsPostmasterEnvironment
Definition: globals.c:118
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4355
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1784
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6362
void InitializeGUCOptions(void)
Definition: guc.c:1530
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4452
#define GUC_RUNTIME_COMPUTED
Definition: guc.h:229
@ PGC_S_OVERRIDE
Definition: guc.h:123
@ PGC_S_ARGV
Definition: guc.h:117
@ PGC_SUSET
Definition: guc.h:78
@ PGC_POSTMASTER
Definition: guc.h:74
char * HbaFileName
Definition: guc_tables.c:544
char * external_pid_file
Definition: guc_tables.c:546
bool load_ident(void)
Definition: hba.c:3021
bool load_hba(void)
Definition: hba.c:2645
static struct @165 value
static bool success
Definition: initdb.c:186
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void InitializeShmemGUCs(void)
Definition: ipci.c:355
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:200
void ApplyLauncherRegister(void)
Definition: launcher.c:915
void list_free(List *list)
Definition: list.c:1546
void list_free_deep(List *list)
Definition: list.c:1560
DispatchOption parse_dispatch_option(const char *name)
Definition: main.c:243
char * pstrdup(const char *in)
Definition: mcxt.c:1699
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * palloc(Size size)
Definition: mcxt.c:1317
MemoryContext PostmasterContext
Definition: mcxt.c:151
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
@ B_STARTUP
Definition: miscadmin.h:364
void ChangeToDataDir(void)
Definition: miscinit.c:460
void process_shmem_requests(void)
Definition: miscinit.c:1930
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1570
void InitProcessLocalLatch(void)
Definition: miscinit.c:235
void process_shared_preload_libraries(void)
Definition: miscinit.c:1902
void checkDataDir(void)
Definition: miscinit.c:347
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1514
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
#define pg_hton16(x)
Definition: pg_bswap.h:120
PGDLLIMPORT int optind
Definition: getopt.c:51
PGDLLIMPORT int opterr
Definition: getopt.c:50
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
PGDLLIMPORT char * optarg
Definition: getopt.c:53
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define PM_STATUS_STARTING
Definition: pidfile.h:51
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: pidfile.h:42
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: pidfile.h:41
void InitPostmasterChildSlots(void)
Definition: pmchild.c:86
#define pqsignal
Definition: port.h:521
int pgsocket
Definition: port.h:29
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3651
CommandDest whereToSendOutput
Definition: postgres.c:91
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3680
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3722
static const char * userDoption
Definition: postgres.c:153
void InitializeMaxBackends(void)
Definition: postinit.c:555
void InitializeFastPathLocks(void)
Definition: postinit.c:587
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2047
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1414
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:4564
void InitProcessGlobals(void)
Definition: postmaster.c:1932
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:1984
static int ServerLoop(void)
Definition: postmaster.c:1651
int PostPortNumber
Definition: postmaster.c:202
static void checkControlFile(void)
Definition: postmaster.c:1514
bool enable_bonjour
Definition: postmaster.c:244
int ReservedConnections
Definition: postmaster.c:229
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
Definition: postmaster.c:1974
static PMChild * StartupPMChild
Definition: postmaster.c:259
char * Unix_socket_directories
Definition: postmaster.c:205
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:4067
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
Definition: postmaster.c:2222
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1460
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1448
static StartupStatusEnum StartupStatus
Definition: postmaster.c:279
#define MAXLISTEN
Definition: postmaster.c:232
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:3894
bool EnableSSL
Definition: postmaster.c:237
char * ListenAddresses
Definition: postmaster.c:208
int SuperuserReservedConnections
Definition: postmaster.c:228
char * bonjour_name
Definition: postmaster.c:245
@ DISPATCH_POSTMASTER
Definition: postmaster.h:139
PGDLLIMPORT bool LoadedSSL
int ListenServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSockets[], int *NumListenSockets, int MaxListen)
Definition: pqcomm.c:418
char ** environ
void pgwin32_signal_initialize(void)
Definition: signal.c:79
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
Definition: pg_list.h:54
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1588
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:102
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3652
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3773
const char * name
void InitializeWaitEventSupport(void)
Definition: waiteventset.c:240
int max_wal_senders
Definition: walsender.c:122
#define S_IROTH
Definition: win32_port.h:303
#define S_IRGRP
Definition: win32_port.h:291
#define SIGPIPE
Definition: win32_port.h:163
#define S_IRUSR
Definition: win32_port.h:279
#define SIGALRM
Definition: win32_port.h:164
#define S_IWUSR
Definition: win32_port.h:282
int XLogArchiveMode
Definition: xlog.c:119
int wal_level
Definition: xlog.c:131
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4830
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4892
@ ARCHIVE_MODE_OFF
Definition: xlog.h:65
@ WAL_LEVEL_MINIMAL
Definition: xlog.h:74
void RemovePromoteSignalFiles(void)

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, appendStringInfo(), appendStringInfoString(), ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert(), autovac_init(), B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, BgWriterPMChild, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPMChild, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), StringInfoData::data, DEBUG3, DestNone, DISPATCH_POSTMASTER, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, err(), errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), HbaFileName, InitializeFastPathLocks(), InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWaitEventSupport(), InitializeWalConsistencyChecking(), InitPostmasterChildSlots(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), InitProcessLocalLatch(), initStringInfo(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenServerPort(), ListenSockets, load_hba(), load_ident(), LoadedSSL, LocalProcessControlFile(), LOCK_FILE_LINE_LISTEN_ADDR, LOCK_FILE_LINE_PM_STATUS, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, LOG_METAINFO_DATAFILE, Logging_collector, max_wal_senders, MaxConnections, MAXLISTEN, maybe_adjust_io_workers(), maybe_start_bgworkers(), MemoryContextSwitchTo(), message_level_is_interesting(), my_exec_path, MyProcPid, name, NIL, NumListenSockets, on_proc_exit(), optarg, opterr, optind, palloc(), parse_dispatch_option(), ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGC_S_OVERRIDE, PGC_SUSET, PgStartTime, pgwin32_signal_initialize(), PM_STARTUP, PM_STATUS_STARTING, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal, process_shared_preload_libraries(), process_shmem_requests(), progname, pstrdup(), RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedConnections, S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), SetConfigOption(), SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartChildProcess(), StartSysLogger(), STARTUP_RUNNING, StartupPMChild, StartupStatus, STATUS_OK, success, summarize_wal, SuperuserReservedConnections, TopMemoryContext, UnBlockSig, Unix_socket_directories, unlink_external_pid_file(), UpdatePMState(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4429 of file postmaster.c.

4430{
4431 dlist_iter iter;
4432 PMChild *bp;
4433
4435 {
4436 bp = dlist_container(PMChild, elem, iter.cur);
4437 if (bp->pid == pid)
4438 {
4439 bp->bgworker_notify = true;
4440 return true;
4441 }
4442 }
4443 return false;
4444}

References ActiveChildList, PMChild::bgworker_notify, dlist_iter::cur, dlist_container, dlist_foreach, and PMChild::pid.

Referenced by BackgroundWorkerStateChange().

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 2876 of file postmaster.c.

2877{
2878 /* If we're doing a smart shutdown, try to advance that state. */
2879 if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2880 {
2881 if (!connsAllowed)
2882 {
2883 /*
2884 * This state ends when we have no normal client backends running.
2885 * Then we're ready to stop other children.
2886 */
2887 if (CountChildren(btmask(B_BACKEND)) == 0)
2889 }
2890 }
2891
2892 /*
2893 * In the PM_WAIT_BACKENDS state, wait for all the regular backends and
2894 * processes like autovacuum and background workers that are comparable to
2895 * backends to exit.
2896 *
2897 * PM_STOP_BACKENDS is a transient state that means the same as
2898 * PM_WAIT_BACKENDS, but we signal the processes first, before waiting for
2899 * them. Treating it as a distinct pmState allows us to share this code
2900 * across multiple shutdown code paths.
2901 */
2903 {
2904 BackendTypeMask targetMask = BTYPE_MASK_NONE;
2905
2906 /*
2907 * PM_WAIT_BACKENDS state ends when we have no regular backends, no
2908 * autovac launcher or workers, and no bgworkers (including
2909 * unconnected ones).
2910 */
2911 targetMask = btmask_add(targetMask,
2912 B_BACKEND,
2915 B_BG_WORKER);
2916
2917 /*
2918 * No walwriter, bgwriter, slot sync worker, or WAL summarizer either.
2919 */
2920 targetMask = btmask_add(targetMask,
2925
2926 /* If we're in recovery, also stop startup and walreceiver procs */
2927 targetMask = btmask_add(targetMask,
2928 B_STARTUP,
2930
2931 /*
2932 * If we are doing crash recovery or an immediate shutdown then we
2933 * expect archiver, checkpointer, io workers and walsender to exit as
2934 * well, otherwise not.
2935 */
2937 targetMask = btmask_add(targetMask,
2939 B_ARCHIVER,
2941 B_WAL_SENDER);
2942
2943 /*
2944 * Normally archiver, checkpointer, IO workers and walsenders will
2945 * continue running; they will be terminated later after writing the
2946 * checkpoint record. We also let dead-end children to keep running
2947 * for now. The syslogger process exits last.
2948 *
2949 * This assertion checks that we have covered all backend types,
2950 * either by including them in targetMask, or by noting here that they
2951 * are allowed to continue running.
2952 */
2953#ifdef USE_ASSERT_CHECKING
2954 {
2955 BackendTypeMask remainMask = BTYPE_MASK_NONE;
2956
2957 remainMask = btmask_add(remainMask,
2959 B_LOGGER);
2960
2961 /*
2962 * Archiver, checkpointer, IO workers, and walsender may or may
2963 * not be in targetMask already.
2964 */
2965 remainMask = btmask_add(remainMask,
2966 B_ARCHIVER,
2969 B_WAL_SENDER);
2970
2971 /* these are not real postmaster children */
2972 remainMask = btmask_add(remainMask,
2973 B_INVALID,
2975
2976 /* All types should be included in targetMask or remainMask */
2977 Assert((remainMask.mask | targetMask.mask) == BTYPE_MASK_ALL.mask);
2978 }
2979#endif
2980
2981 /* If we had not yet signaled the processes to exit, do so now */
2983 {
2984 /*
2985 * Forget any pending requests for background workers, since we're
2986 * no longer willing to launch any new workers. (If additional
2987 * requests arrive, BackgroundWorkerStateChange will reject them.)
2988 */
2990
2991 SignalChildren(SIGTERM, targetMask);
2992
2994 }
2995
2996 /* Are any of the target processes still running? */
2997 if (CountChildren(targetMask) == 0)
2998 {
3000 {
3001 /*
3002 * Stop any dead-end children and stop creating new ones.
3003 *
3004 * NB: Similar code exists in HandleFatalErrors(), when the
3005 * error happens in pmState > PM_WAIT_BACKENDS.
3006 */
3010
3011 /*
3012 * We already SIGQUIT'd auxiliary processes (other than
3013 * logger), if any, when we started immediate shutdown or
3014 * entered FatalError state.
3015 */
3016 }
3017 else
3018 {
3019 /*
3020 * If we get here, we are proceeding with normal shutdown. All
3021 * the regular children are gone, and it's time to tell the
3022 * checkpointer to do a shutdown checkpoint.
3023 */
3025 /* Start the checkpointer if not running */
3026 if (CheckpointerPMChild == NULL)
3028 /* And tell it to write the shutdown checkpoint */
3029 if (CheckpointerPMChild != NULL)
3030 {
3033 }
3034 else
3035 {
3036 /*
3037 * If we failed to fork a checkpointer, just shut down.
3038 * Any required cleanup will happen at next restart. We
3039 * set FatalError so that an "abnormal shutdown" message
3040 * gets logged when we exit.
3041 *
3042 * We don't consult send_abort_for_crash here, as it's
3043 * unlikely that dumping cores would illuminate the reason
3044 * for checkpointer fork failure.
3045 *
3046 * XXX: It may be worth to introduce a different PMQUIT
3047 * value that signals that the cluster is in a bad state,
3048 * without a process having crashed. But right now this
3049 * path is very unlikely to be reached, so it isn't
3050 * obviously worthwhile adding a distinct error message in
3051 * quickdie().
3052 */
3054 }
3055 }
3056 }
3057 }
3058
3059 /*
3060 * The state transition from PM_WAIT_XLOG_SHUTDOWN to
3061 * PM_WAIT_XLOG_ARCHIVAL is in process_pm_pmsignal(), in response to
3062 * PMSIGNAL_XLOG_IS_SHUTDOWN.
3063 */
3064
3066 {
3067 /*
3068 * PM_WAIT_XLOG_ARCHIVAL state ends when there are no children other
3069 * than checkpointer, io workers and dead-end children left. There
3070 * shouldn't be any regular backends left by now anyway; what we're
3071 * really waiting for is for walsenders and archiver to exit.
3072 */
3075 {
3078 }
3079 }
3080
3082 {
3083 /*
3084 * PM_WAIT_IO_WORKERS state ends when there's only checkpointer and
3085 * dead_end children left.
3086 */
3087 if (io_worker_count == 0)
3088 {
3090
3091 /*
3092 * Now that the processes mentioned above are gone, tell
3093 * checkpointer to shut down too. That allows checkpointer to
3094 * perform some last bits of cleanup without other processes
3095 * interfering.
3096 */
3097 if (CheckpointerPMChild != NULL)
3099 }
3100 }
3101
3102 /*
3103 * The state transition from PM_WAIT_CHECKPOINTER to PM_WAIT_DEAD_END is
3104 * in process_pm_child_exit().
3105 */
3106
3108 {
3109 /*
3110 * PM_WAIT_DEAD_END state ends when all other children are gone except
3111 * for the logger. During normal shutdown, all that remains are
3112 * dead-end backends, but in FatalError processing we jump straight
3113 * here with more processes remaining. Note that they have already
3114 * been sent appropriate shutdown signals, either during a normal
3115 * state transition leading up to PM_WAIT_DEAD_END, or during
3116 * FatalError processing.
3117 *
3118 * The reason we wait is to protect against a new postmaster starting
3119 * conflicting subprocesses; this isn't an ironclad protection, but it
3120 * at least helps in the shutdown-and-immediately-restart scenario.
3121 */
3123 {
3124 /* These other guys should be dead already */
3125 Assert(StartupPMChild == NULL);
3126 Assert(WalReceiverPMChild == NULL);
3128 Assert(BgWriterPMChild == NULL);
3129 Assert(CheckpointerPMChild == NULL);
3130 Assert(WalWriterPMChild == NULL);
3133 /* syslogger is not considered here */
3135 }
3136 }
3137
3138 /*
3139 * If we've been told to shut down, we exit as soon as there are no
3140 * remaining children. If there was a crash, cleanup will occur at the
3141 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3142 * crash before exiting, but that seems unwise if we are quitting because
3143 * we got SIGTERM from init --- there may well not be time for recovery
3144 * before init decides to SIGKILL us.)
3145 *
3146 * Note that the syslogger continues to run. It will exit when it sees
3147 * EOF on its input pipe, which happens when there are no more upstream
3148 * processes.
3149 */
3151 {
3152 if (FatalError)
3153 {
3154 ereport(LOG, (errmsg("abnormal database system shutdown")));
3155 ExitPostmaster(1);
3156 }
3157 else
3158 {
3159 /*
3160 * Normal exit from the postmaster is here. We don't need to log
3161 * anything here, since the UnlinkLockFiles proc_exit callback
3162 * will do so, and that should be the last user-visible action.
3163 */
3164 ExitPostmaster(0);
3165 }
3166 }
3167
3168 /*
3169 * If the startup process failed, or the user does not want an automatic
3170 * restart after backend crashes, wait for all non-syslogger children to
3171 * exit, and then exit postmaster. We don't try to reinitialize when the
3172 * startup process fails, because more than likely it will just fail again
3173 * and we will keep trying forever.
3174 */
3175 if (pmState == PM_NO_CHILDREN)
3176 {
3178 {
3179 ereport(LOG,
3180 (errmsg("shutting down due to startup process failure")));
3181 ExitPostmaster(1);
3182 }
3184 {
3185 ereport(LOG,
3186 (errmsg("shutting down because \"restart_after_crash\" is off")));
3187 ExitPostmaster(1);
3188 }
3189 }
3190
3191 /*
3192 * If we need to recover from a crash, wait for all non-syslogger children
3193 * to exit, then reset shmem and start the startup process.
3194 */
3196 {
3197 ereport(LOG,
3198 (errmsg("all server processes terminated; reinitializing")));
3199
3200 /* remove leftover temporary files after a crash */
3203
3204 /* allow background workers to immediately restart */
3206
3207 shmem_exit(1);
3208
3209 /* re-read control file into local memory */
3211
3212 /* re-create shared memory and semaphores */
3214
3216
3217 /* Make sure we can perform I/O while starting up. */
3219
3221 Assert(StartupPMChild != NULL);
3223 /* crash recovery started, reset SIGKILL flag */
3224 AbortStartTime = 0;
3225
3226 /* start accepting server socket connection events again */
3228 }
3229}
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:579
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:541
void shmem_exit(int code)
Definition: ipc.c:228
@ B_LOGGER
Definition: miscadmin.h:373
@ B_INVALID
Definition: miscadmin.h:338
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:349
@ B_DEAD_END_BACKEND
Definition: miscadmin.h:342
static int CountChildren(BackendTypeMask targetMask)
Definition: postmaster.c:3902
static const BackendTypeMask BTYPE_MASK_NONE
Definition: postmaster.c:145
#define btmask_all_except(...)
Definition: postmaster.c:186
#define btmask_add(mask,...)
Definition: postmaster.c:163
bool remove_temp_files_after_crash
Definition: postmaster.c:247
bool restart_after_crash
Definition: postmaster.c:246
static void signal_child(PMChild *pmchild, int signal)
Definition: postmaster.c:3442
static bool SignalChildren(int signal, BackendTypeMask targetMask)
Definition: postmaster.c:3475
static BackendTypeMask btmask(BackendType t)
Definition: postmaster.c:148

References AbortStartTime, Assert(), AutoVacLauncherPMChild, B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_DEAD_END_BACKEND, B_INVALID, B_IO_WORKER, B_LOGGER, B_SLOTSYNC_WORKER, B_STANDALONE_BACKEND, B_STARTUP, B_WAL_RECEIVER, B_WAL_SENDER, B_WAL_SUMMARIZER, B_WAL_WRITER, BgWriterPMChild, btmask(), btmask_add, btmask_all_except, BTYPE_MASK_ALL, BTYPE_MASK_NONE, CheckpointerPMChild, ConfigurePostmasterWaitSet(), connsAllowed, CountChildren(), CreateSharedMemoryAndSemaphores(), ereport, errmsg(), ExitPostmaster(), FatalError, ForgetUnstartedBackgroundWorkers(), HandleFatalError(), ImmediateShutdown, io_worker_count, LocalProcessControlFile(), LOG, BackendTypeMask::mask, maybe_adjust_io_workers(), NoShutdown, PM_HOT_STANDBY, PM_NO_CHILDREN, PM_RUN, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_CHECKPOINTER, PM_WAIT_DEAD_END, PM_WAIT_IO_WORKERS, PM_WAIT_XLOG_ARCHIVAL, PM_WAIT_XLOG_SHUTDOWN, PMQUIT_FOR_CRASH, pmState, remove_temp_files_after_crash, RemovePgTempFiles(), ResetBackgroundWorkerCrashTimes(), restart_after_crash, shmem_exit(), Shutdown, signal_child(), SignalChildren(), SIGQUIT, SIGUSR2, SlotSyncWorkerPMChild, StartChildProcess(), STARTUP_CRASHED, STARTUP_RUNNING, StartupPMChild, StartupStatus, UpdatePMState(), WalReceiverPMChild, WalSummarizerPMChild, and WalWriterPMChild.

Referenced by process_pm_child_exit(), process_pm_pmsignal(), and process_pm_shutdown_request().

◆ process_pm_child_exit()

static void process_pm_child_exit ( void  )
static

Definition at line 2232 of file postmaster.c.

2233{
2234 int pid; /* process id of dead child process */
2235 int exitstatus; /* its exit status */
2236
2237 pending_pm_child_exit = false;
2238
2240 (errmsg_internal("reaping dead processes")));
2241
2242 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2243 {
2244 PMChild *pmchild;
2245
2246 /*
2247 * Check if this child was a startup process.
2248 */
2249 if (StartupPMChild && pid == StartupPMChild->pid)
2250 {
2252 StartupPMChild = NULL;
2253
2254 /*
2255 * Startup process exited in response to a shutdown request (or it
2256 * completed normally regardless of the shutdown request).
2257 */
2258 if (Shutdown > NoShutdown &&
2259 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2260 {
2263 /* PostmasterStateMachine logic does the rest */
2264 continue;
2265 }
2266
2267 if (EXIT_STATUS_3(exitstatus))
2268 {
2269 ereport(LOG,
2270 (errmsg("shutdown at recovery target")));
2273 TerminateChildren(SIGTERM);
2275 /* PostmasterStateMachine logic does the rest */
2276 continue;
2277 }
2278
2279 /*
2280 * Unexpected exit of startup process (including FATAL exit)
2281 * during PM_STARTUP is treated as catastrophic. There are no
2282 * other processes running yet, so we can just exit.
2283 */
2284 if (pmState == PM_STARTUP &&
2286 !EXIT_STATUS_0(exitstatus))
2287 {
2288 LogChildExit(LOG, _("startup process"),
2289 pid, exitstatus);
2290 ereport(LOG,
2291 (errmsg("aborting startup due to startup process failure")));
2292 ExitPostmaster(1);
2293 }
2294
2295 /*
2296 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2297 * the startup process is catastrophic, so kill other children,
2298 * and set StartupStatus so we don't try to reinitialize after
2299 * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
2300 * then we previously sent the startup process a SIGQUIT; so
2301 * that's probably the reason it died, and we do want to try to
2302 * restart in that case.
2303 *
2304 * This stanza also handles the case where we sent a SIGQUIT
2305 * during PM_STARTUP due to some dead-end child crashing: in that
2306 * situation, if the startup process dies on the SIGQUIT, we need
2307 * to transition to PM_WAIT_BACKENDS state which will allow
2308 * PostmasterStateMachine to restart the startup process. (On the
2309 * other hand, the startup process might complete normally, if we
2310 * were too late with the SIGQUIT. In that case we'll fall
2311 * through and commence normal operations.)
2312 */
2313 if (!EXIT_STATUS_0(exitstatus))
2314 {
2316 {
2318 if (pmState == PM_STARTUP)
2320 }
2321 else
2323 HandleChildCrash(pid, exitstatus,
2324 _("startup process"));
2325 continue;
2326 }
2327
2328 /*
2329 * Startup succeeded, commence normal operations
2330 */
2332 FatalError = false;
2333 AbortStartTime = 0;
2334 ReachedNormalRunning = true;
2336 connsAllowed = true;
2337
2338 /*
2339 * At the next iteration of the postmaster's main loop, we will
2340 * crank up the background tasks like the autovacuum launcher and
2341 * background workers that were not started earlier already.
2342 */
2343 StartWorkerNeeded = true;
2344
2345 /* at this point we are really open for business */
2346 ereport(LOG,
2347 (errmsg("database system is ready to accept connections")));
2348
2349 /* Report status */
2351#ifdef USE_SYSTEMD
2352 sd_notify(0, "READY=1");
2353#endif
2354
2355 continue;
2356 }
2357
2358 /*
2359 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2360 * one at the next iteration of the postmaster's main loop, if
2361 * necessary. Any other exit condition is treated as a crash.
2362 */
2363 if (BgWriterPMChild && pid == BgWriterPMChild->pid)
2364 {
2366 BgWriterPMChild = NULL;
2367 if (!EXIT_STATUS_0(exitstatus))
2368 HandleChildCrash(pid, exitstatus,
2369 _("background writer process"));
2370 continue;
2371 }
2372
2373 /*
2374 * Was it the checkpointer?
2375 */
2377 {
2379 CheckpointerPMChild = NULL;
2380 if (EXIT_STATUS_0(exitstatus) && pmState == PM_WAIT_CHECKPOINTER)
2381 {
2382 /*
2383 * OK, we saw normal exit of the checkpointer after it's been
2384 * told to shut down. We know checkpointer wrote a shutdown
2385 * checkpoint, otherwise we'd still be in
2386 * PM_WAIT_XLOG_SHUTDOWN state.
2387 *
2388 * At this point only dead-end children and logger should be
2389 * left.
2390 */
2394 }
2395 else
2396 {
2397 /*
2398 * Any unexpected exit of the checkpointer (including FATAL
2399 * exit) is treated as a crash.
2400 */
2401 HandleChildCrash(pid, exitstatus,
2402 _("checkpointer process"));
2403 }
2404
2405 continue;
2406 }
2407
2408 /*
2409 * Was it the wal writer? Normal exit can be ignored; we'll start a
2410 * new one at the next iteration of the postmaster's main loop, if
2411 * necessary. Any other exit condition is treated as a crash.
2412 */
2413 if (WalWriterPMChild && pid == WalWriterPMChild->pid)
2414 {
2416 WalWriterPMChild = NULL;
2417 if (!EXIT_STATUS_0(exitstatus))
2418 HandleChildCrash(pid, exitstatus,
2419 _("WAL writer process"));
2420 continue;
2421 }
2422
2423 /*
2424 * Was it the wal receiver? If exit status is zero (normal) or one
2425 * (FATAL exit), we assume everything is all right just like normal
2426 * backends. (If we need a new wal receiver, we'll start one at the
2427 * next iteration of the postmaster's main loop.)
2428 */
2430 {
2432 WalReceiverPMChild = NULL;
2433 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2434 HandleChildCrash(pid, exitstatus,
2435 _("WAL receiver process"));
2436 continue;
2437 }
2438
2439 /*
2440 * Was it the wal summarizer? Normal exit can be ignored; we'll start
2441 * a new one at the next iteration of the postmaster's main loop, if
2442 * necessary. Any other exit condition is treated as a crash.
2443 */
2445 {
2447 WalSummarizerPMChild = NULL;
2448 if (!EXIT_STATUS_0(exitstatus))
2449 HandleChildCrash(pid, exitstatus,
2450 _("WAL summarizer process"));
2451 continue;
2452 }
2453
2454 /*
2455 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2456 * start a new one at the next iteration of the postmaster's main
2457 * loop, if necessary. Any other exit condition is treated as a
2458 * crash.
2459 */
2461 {
2464 if (!EXIT_STATUS_0(exitstatus))
2465 HandleChildCrash(pid, exitstatus,
2466 _("autovacuum launcher process"));
2467 continue;
2468 }
2469
2470 /*
2471 * Was it the archiver? If exit status is zero (normal) or one (FATAL
2472 * exit), we assume everything is all right just like normal backends
2473 * and just try to start a new one on the next cycle of the
2474 * postmaster's main loop, to retry archiving remaining files.
2475 */
2476 if (PgArchPMChild && pid == PgArchPMChild->pid)
2477 {
2479 PgArchPMChild = NULL;
2480 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2481 HandleChildCrash(pid, exitstatus,
2482 _("archiver process"));
2483 continue;
2484 }
2485
2486 /* Was it the system logger? If so, try to start a new one */
2487 if (SysLoggerPMChild && pid == SysLoggerPMChild->pid)
2488 {
2490 SysLoggerPMChild = NULL;
2491
2492 /* for safety's sake, launch new logger *first* */
2495
2496 if (!EXIT_STATUS_0(exitstatus))
2497 LogChildExit(LOG, _("system logger process"),
2498 pid, exitstatus);
2499 continue;
2500 }
2501
2502 /*
2503 * Was it the slot sync worker? Normal exit or FATAL exit can be
2504 * ignored (FATAL can be caused by libpqwalreceiver on receiving
2505 * shutdown request by the startup process during promotion); we'll
2506 * start a new one at the next iteration of the postmaster's main
2507 * loop, if necessary. Any other exit condition is treated as a crash.
2508 */
2510 {
2512 SlotSyncWorkerPMChild = NULL;
2513 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2514 HandleChildCrash(pid, exitstatus,
2515 _("slot sync worker process"));
2516 continue;
2517 }
2518
2519 /* Was it an IO worker? */
2520 if (maybe_reap_io_worker(pid))
2521 {
2522 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2523 HandleChildCrash(pid, exitstatus, _("io worker"));
2524
2526 continue;
2527 }
2528
2529 /*
2530 * Was it a backend or a background worker?
2531 */
2532 pmchild = FindPostmasterChildByPid(pid);
2533 if (pmchild)
2534 {
2535 CleanupBackend(pmchild, exitstatus);
2536 }
2537
2538 /*
2539 * We don't know anything about this child process. That's highly
2540 * unexpected, as we do track all the child processes that we fork.
2541 */
2542 else
2543 {
2544 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2545 HandleChildCrash(pid, exitstatus, _("untracked child process"));
2546 else
2547 LogChildExit(LOG, _("untracked child process"), pid, exitstatus);
2548 }
2549 } /* loop over pending child-death reports */
2550
2551 /*
2552 * After cleaning out the SIGCHLD queue, see if we have any state changes
2553 * or actions to make.
2554 */
2556}
#define PM_STATUS_READY
Definition: pidfile.h:53
PMChild * FindPostmasterChildByPid(int pid)
Definition: pmchild.c:274
static void PostmasterStateMachine(void)
Definition: postmaster.c:2876
static bool maybe_reap_io_worker(int pid)
Definition: postmaster.c:4331
static bool ReachedNormalRunning
Definition: postmaster.c:369
static void CleanupBackend(PMChild *bp, int exitstatus)
Definition: postmaster.c:2565
#define EXIT_STATUS_3(st)
Definition: postmaster.c:475

References _, AbortStartTime, AddToDataDirLockFile(), AutoVacLauncherPMChild, B_LOGGER, BgWriterPMChild, btmask_all_except, CheckpointerPMChild, CleanupBackend(), ConfigurePostmasterWaitSet(), connsAllowed, DEBUG4, ereport, errmsg(), errmsg_internal(), EXIT_STATUS_0, EXIT_STATUS_1, EXIT_STATUS_3, ExitPostmaster(), FatalError, FindPostmasterChildByPid(), HandleChildCrash(), LOCK_FILE_LINE_PM_STATUS, LOG, LogChildExit(), Logging_collector, Max, maybe_adjust_io_workers(), maybe_reap_io_worker(), NoShutdown, pending_pm_child_exit, PgArchPMChild, PMChild::pid, PM_RUN, PM_STARTUP, PM_STATUS_READY, PM_WAIT_BACKENDS, PM_WAIT_CHECKPOINTER, PM_WAIT_DEAD_END, pmState, PostmasterStateMachine(), ReachedNormalRunning, ReleasePostmasterChildSlot(), Shutdown, SignalChildren(), SlotSyncWorkerPMChild, SmartShutdown, StartSysLogger(), STARTUP_CRASHED, STARTUP_NOT_RUNNING, STARTUP_SIGNALED, StartupPMChild, StartupStatus, StartWorkerNeeded, SysLoggerPMChild, TerminateChildren(), UpdatePMState(), WalReceiverPMChild, WalSummarizerPMChild, and WalWriterPMChild.

Referenced by ServerLoop().

◆ process_pm_pmsignal()

static void process_pm_pmsignal ( void  )
static

Definition at line 3681 of file postmaster.c.

3682{
3683 bool request_state_update = false;
3684
3685 pending_pm_pmsignal = false;
3686
3688 (errmsg_internal("postmaster received pmsignal signal")));
3689
3690 /*
3691 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
3692 * unexpected states. If the startup process quickly starts up, completes
3693 * recovery, exits, we might process the death of the startup process
3694 * first. We don't want to go back to recovery in that case.
3695 */
3698 {
3699 /* WAL redo has started. We're out of reinitialization. */
3700 FatalError = false;
3701 AbortStartTime = 0;
3702
3703 /*
3704 * Start the archiver if we're responsible for (re-)archiving received
3705 * files.
3706 */
3707 Assert(PgArchPMChild == NULL);
3708 if (XLogArchivingAlways())
3710
3711 /*
3712 * If we aren't planning to enter hot standby mode later, treat
3713 * RECOVERY_STARTED as meaning we're out of startup, and report status
3714 * accordingly.
3715 */
3716 if (!EnableHotStandby)
3717 {
3719#ifdef USE_SYSTEMD
3720 sd_notify(0, "READY=1");
3721#endif
3722 }
3723
3725 }
3726
3729 {
3730 ereport(LOG,
3731 (errmsg("database system is ready to accept read-only connections")));
3732
3733 /* Report status */
3735#ifdef USE_SYSTEMD
3736 sd_notify(0, "READY=1");
3737#endif
3738
3740 connsAllowed = true;
3741
3742 /* Some workers may be scheduled to start now */
3743 StartWorkerNeeded = true;
3744 }
3745
3746 /* Process background worker state changes. */
3748 {
3749 /* Accept new worker requests only if not stopping. */
3751 StartWorkerNeeded = true;
3752 }
3753
3754 /* Tell syslogger to rotate logfile if requested */
3755 if (SysLoggerPMChild != NULL)
3756 {
3758 {
3761 }
3763 {
3765 }
3766 }
3767
3770 {
3771 /*
3772 * Start one iteration of the autovacuum daemon, even if autovacuuming
3773 * is nominally not enabled. This is so we can have an active defense
3774 * against transaction ID wraparound. We set a flag for the main loop
3775 * to do it rather than trying to do it here --- this is because the
3776 * autovac process itself may send the signal, and we want to handle
3777 * that by launching another iteration as soon as the current one
3778 * completes.
3779 */
3781 }
3782
3785 {
3786 /* The autovacuum launcher wants us to start a worker process. */
3788 }
3789
3791 {
3792 /* Startup Process wants us to start the walreceiver process. */
3793 WalReceiverRequested = true;
3794 }
3795
3797 {
3798 /* Checkpointer completed the shutdown checkpoint */
3800 {
3801 /*
3802 * If we have an archiver subprocess, tell it to do a last archive
3803 * cycle and quit. Likewise, if we have walsender processes, tell
3804 * them to send any remaining WAL and quit.
3805 */
3807
3808 /* Waken archiver for the last time */
3809 if (PgArchPMChild != NULL)
3811
3812 /*
3813 * Waken walsenders for the last time. No regular backends should
3814 * be around anymore.
3815 */
3817
3819 }
3820 else if (!FatalError && Shutdown != ImmediateShutdown)
3821 {
3822 /*
3823 * Checkpointer only ought to perform the shutdown checkpoint
3824 * during shutdown. If somehow checkpointer did so in another
3825 * situation, we have no choice but to crash-restart.
3826 *
3827 * It's possible however that we get PMSIGNAL_XLOG_IS_SHUTDOWN
3828 * outside of PM_WAIT_XLOG_SHUTDOWN if an orderly shutdown was
3829 * "interrupted" by a crash or an immediate shutdown.
3830 */
3831 ereport(LOG,
3832 (errmsg("WAL was shut down unexpectedly")));
3833
3834 /*
3835 * Doesn't seem likely to help to take send_abort_for_crash into
3836 * account here.
3837 */
3839 }
3840
3841 /*
3842 * Need to run PostmasterStateMachine() to check if we already can go
3843 * to the next state.
3844 */
3845 request_state_update = true;
3846 }
3847
3848 /*
3849 * Try to advance postmaster's state machine, if a child requests it.
3850 */
3852 {
3853 request_state_update = true;
3854 }
3855
3856 /*
3857 * Be careful about the order of this action relative to this function's
3858 * other actions. Generally, this should be after other actions, in case
3859 * they have effects PostmasterStateMachine would need to know about.
3860 * However, we should do it before the CheckPromoteSignal step, which
3861 * cannot have any (immediate) effect on the state machine, but does
3862 * depend on what state we're in now.
3863 */
3864 if (request_state_update)
3865 {
3867 }
3868
3869 if (StartupPMChild != NULL &&
3871 pmState == PM_HOT_STANDBY) &&
3873 {
3874 /*
3875 * Tell startup process to finish recovery.
3876 *
3877 * Leave the promote signal file in place and let the Startup process
3878 * do the unlink.
3879 */
3881 }
3882}
void BackgroundWorkerStateChange(bool allow_new_workers)
Definition: bgworker.c:246
#define PM_STATUS_STANDBY
Definition: pidfile.h:54
bool CheckPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:182
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition: pmsignal.h:39
@ PMSIGNAL_RECOVERY_STARTED
Definition: pmsignal.h:35
@ PMSIGNAL_START_WALRECEIVER
Definition: pmsignal.h:41
@ PMSIGNAL_START_AUTOVAC_LAUNCHER
Definition: pmsignal.h:38
@ PMSIGNAL_BEGIN_HOT_STANDBY
Definition: pmsignal.h:36
@ PMSIGNAL_XLOG_IS_SHUTDOWN
Definition: pmsignal.h:43
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition: pmsignal.h:40
@ PMSIGNAL_ROTATE_LOGFILE
Definition: pmsignal.h:37
@ PMSIGNAL_ADVANCE_STATE_MACHINE
Definition: pmsignal.h:42
static void StartAutovacuumWorker(void)
Definition: postmaster.c:4017
bool CheckLogrotateSignal(void)
Definition: syslogger.c:1574
bool EnableHotStandby
Definition: xlog.c:121
bool CheckPromoteSignal(void)

References AbortStartTime, AddToDataDirLockFile(), Assert(), B_ARCHIVER, B_WAL_SENDER, BackgroundWorkerStateChange(), btmask(), CheckLogrotateSignal(), CheckPostmasterSignal(), CheckPromoteSignal(), connsAllowed, DEBUG2, EnableHotStandby, ereport, errmsg(), errmsg_internal(), FatalError, HandleFatalError(), ImmediateShutdown, LOCK_FILE_LINE_PM_STATUS, LOG, NoShutdown, pending_pm_pmsignal, PgArchPMChild, PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, PM_STATUS_READY, PM_STATUS_STANDBY, PM_STOP_BACKENDS, PM_WAIT_XLOG_ARCHIVAL, PM_WAIT_XLOG_SHUTDOWN, PMQUIT_FOR_CRASH, PMSIGNAL_ADVANCE_STATE_MACHINE, PMSIGNAL_BACKGROUND_WORKER_CHANGE, PMSIGNAL_BEGIN_HOT_STANDBY, PMSIGNAL_RECOVERY_STARTED, PMSIGNAL_ROTATE_LOGFILE, PMSIGNAL_START_AUTOVAC_LAUNCHER, PMSIGNAL_START_AUTOVAC_WORKER, PMSIGNAL_START_WALRECEIVER, PMSIGNAL_XLOG_IS_SHUTDOWN, pmState, PostmasterStateMachine(), RemoveLogrotateSignalFiles(), Shutdown, signal_child(), SignalChildren(), SIGUSR1, SIGUSR2, SmartShutdown, start_autovac_launcher, StartAutovacuumWorker(), StartChildProcess(), StartupPMChild, StartWorkerNeeded, SysLoggerPMChild, UpdatePMState(), WalReceiverRequested, and XLogArchivingAlways.

Referenced by ServerLoop().

◆ process_pm_reload_request()

static void process_pm_reload_request ( void  )
static

Definition at line 1994 of file postmaster.c.

1995{
1997
1999 (errmsg_internal("postmaster received reload request signal")));
2000
2001 if (Shutdown <= SmartShutdown)
2002 {
2003 ereport(LOG,
2004 (errmsg("received SIGHUP, reloading configuration files")));
2007
2008 /* Reload authentication config files too */
2009 if (!load_hba())
2010 ereport(LOG,
2011 /* translator: %s is a configuration file */
2012 (errmsg("%s was not reloaded", HbaFileName)));
2013
2014 if (!load_ident())
2015 ereport(LOG,
2016 (errmsg("%s was not reloaded", IdentFileName)));
2017
2018#ifdef USE_SSL
2019 /* Reload SSL configuration as well */
2020 if (EnableSSL)
2021 {
2022 if (secure_initialize(false) == 0)
2023 LoadedSSL = true;
2024 else
2025 ereport(LOG,
2026 (errmsg("SSL configuration was not reloaded")));
2027 }
2028 else
2029 {
2031 LoadedSSL = false;
2032 }
2033#endif
2034
2035#ifdef EXEC_BACKEND
2036 /* Update the starting-point file for future children */
2037 write_nondefault_variables(PGC_SIGHUP);
2038#endif
2039 }
2040}
void secure_destroy(void)
Definition: be-secure.c:88
void ProcessConfigFile(GucContext context)
Definition: guc-file.l:120
@ PGC_SIGHUP
Definition: guc.h:75
char * IdentFileName
Definition: guc_tables.c:545

References B_DEAD_END_BACKEND, btmask_all_except, DEBUG2, EnableSSL, ereport, errmsg(), errmsg_internal(), HbaFileName, IdentFileName, load_hba(), load_ident(), LoadedSSL, LOG, pending_pm_reload_request, PGC_SIGHUP, ProcessConfigFile(), secure_destroy(), secure_initialize(), Shutdown, SIGHUP, SignalChildren(), and SmartShutdown.

Referenced by ServerLoop().

◆ process_pm_shutdown_request()

static void process_pm_shutdown_request ( void  )
static

Definition at line 2071 of file postmaster.c.

2072{
2073 int mode;
2074
2076 (errmsg_internal("postmaster received shutdown request signal")));
2077
2079
2080 /*
2081 * If more than one shutdown request signal arrived since the last server
2082 * loop, take the one that is the most immediate. That matches the
2083 * priority that would apply if we processed them one by one in any order.
2084 */
2086 {
2090 }
2092 {
2095 }
2096 else
2098
2099 switch (mode)
2100 {
2101 case SmartShutdown:
2102
2103 /*
2104 * Smart Shutdown:
2105 *
2106 * Wait for children to end their work, then shut down.
2107 */
2108 if (Shutdown >= SmartShutdown)
2109 break;
2111 ereport(LOG,
2112 (errmsg("received smart shutdown request")));
2113
2114 /* Report status */
2116#ifdef USE_SYSTEMD
2117 sd_notify(0, "STOPPING=1");
2118#endif
2119
2120 /*
2121 * If we reached normal running, we go straight to waiting for
2122 * client backends to exit. If already in PM_STOP_BACKENDS or a
2123 * later state, do not change it.
2124 */
2125 if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2126 connsAllowed = false;
2127 else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2128 {
2129 /* There should be no clients, so proceed to stop children */
2131 }
2132
2133 /*
2134 * Now wait for online backup mode to end and backends to exit. If
2135 * that is already the case, PostmasterStateMachine will take the
2136 * next step.
2137 */
2139 break;
2140
2141 case FastShutdown:
2142
2143 /*
2144 * Fast Shutdown:
2145 *
2146 * Abort all children with SIGTERM (rollback active transactions
2147 * and exit) and shut down when they are gone.
2148 */
2149 if (Shutdown >= FastShutdown)
2150 break;
2152 ereport(LOG,
2153 (errmsg("received fast shutdown request")));
2154
2155 /* Report status */
2157#ifdef USE_SYSTEMD
2158 sd_notify(0, "STOPPING=1");
2159#endif
2160
2162 {
2163 /* Just shut down background processes silently */
2165 }
2166 else if (pmState == PM_RUN ||
2168 {
2169 /* Report that we're about to zap live client sessions */
2170 ereport(LOG,
2171 (errmsg("aborting any active transactions")));
2173 }
2174
2175 /*
2176 * PostmasterStateMachine will issue any necessary signals, or
2177 * take the next step if no child processes need to be killed.
2178 */
2180 break;
2181
2182 case ImmediateShutdown:
2183
2184 /*
2185 * Immediate Shutdown:
2186 *
2187 * abort all children with SIGQUIT, wait for them to exit,
2188 * terminate remaining ones with SIGKILL, then exit without
2189 * attempt to properly shut down the data base system.
2190 */
2192 break;
2194 ereport(LOG,
2195 (errmsg("received immediate shutdown request")));
2196
2197 /* Report status */
2199#ifdef USE_SYSTEMD
2200 sd_notify(0, "STOPPING=1");
2201#endif
2202
2203 /* tell children to shut down ASAP */
2204 /* (note we don't apply send_abort_for_crash here) */
2208
2209 /* set stopwatch for them to die */
2210 AbortStartTime = time(NULL);
2211
2212 /*
2213 * Now wait for backends to exit. If there are none,
2214 * PostmasterStateMachine will take the next step.
2215 */
2217 break;
2218 }
2219}
static PgChecksumMode mode
Definition: pg_checksums.c:55
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:55
#define FastShutdown
Definition: postmaster.c:284

References AbortStartTime, AddToDataDirLockFile(), connsAllowed, DEBUG2, ereport, errmsg(), errmsg_internal(), FastShutdown, ImmediateShutdown, LOCK_FILE_LINE_PM_STATUS, LOG, mode, pending_pm_fast_shutdown_request, pending_pm_immediate_shutdown_request, pending_pm_shutdown_request, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_STATUS_STOPPING, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_STOP, pmState, PostmasterStateMachine(), SetQuitSignalReason(), Shutdown, SIGQUIT, SmartShutdown, TerminateChildren(), and UpdatePMState().

Referenced by ServerLoop().

◆ report_fork_failure_to_client()

static void report_fork_failure_to_client ( ClientSocket client_sock,
int  errnum 
)
static

Definition at line 3619 of file postmaster.c.

3620{
3621 char buffer[1000];
3622 int rc;
3623
3624 /* Format the error message packet (always V2 protocol) */
3625 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3626 _("could not fork new process for connection: "),
3627 strerror(errnum));
3628
3629 /* Set port to non-blocking. Don't do send() if this fails */
3630 if (!pg_set_noblock(client_sock->sock))
3631 return;
3632
3633 /* We'll retry after EINTR, but ignore all other failures */
3634 do
3635 {
3636 rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
3637 } while (rc < 0 && errno == EINTR);
3638}
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define strerror
Definition: port.h:252
#define EINTR
Definition: win32_port.h:364
#define send(s, buf, len, flags)
Definition: win32_port.h:505

References _, EINTR, pg_set_noblock(), send, snprintf, ClientSocket::sock, and strerror.

Referenced by BackendStartup().

◆ ServerLoop()

static int ServerLoop ( void  )
static

Definition at line 1651 of file postmaster.c.

1652{
1653 time_t last_lockfile_recheck_time,
1654 last_touch_time;
1655 WaitEvent events[MAXLISTEN];
1656 int nevents;
1657
1659 last_lockfile_recheck_time = last_touch_time = time(NULL);
1660
1661 for (;;)
1662 {
1663 time_t now;
1664
1665 nevents = WaitEventSetWait(pm_wait_set,
1667 events,
1668 lengthof(events),
1669 0 /* postmaster posts no wait_events */ );
1670
1671 /*
1672 * Latch set by signal handler, or new connection pending on any of
1673 * our sockets? If the latter, fork a child process to deal with it.
1674 */
1675 for (int i = 0; i < nevents; i++)
1676 {
1677 if (events[i].events & WL_LATCH_SET)
1679
1680 /*
1681 * The following requests are handled unconditionally, even if we
1682 * didn't see WL_LATCH_SET. This gives high priority to shutdown
1683 * and reload requests where the latch happens to appear later in
1684 * events[] or will be reported by a later call to
1685 * WaitEventSetWait().
1686 */
1695
1696 if (events[i].events & WL_SOCKET_ACCEPT)
1697 {
1698 ClientSocket s;
1699
1700 if (AcceptConnection(events[i].fd, &s) == STATUS_OK)
1701 BackendStartup(&s);
1702
1703 /* We no longer need the open socket in this process */
1704 if (s.sock != PGINVALID_SOCKET)
1705 {
1706 if (closesocket(s.sock) != 0)
1707 elog(LOG, "could not close client socket: %m");
1708 }
1709 }
1710 }
1711
1712 /*
1713 * If we need to launch any background processes after changing state
1714 * or because some exited, do so now.
1715 */
1717
1718 /* If we need to signal the autovacuum launcher, do so now */
1720 {
1722 if (AutoVacLauncherPMChild != NULL)
1724 }
1725
1726#ifdef HAVE_PTHREAD_IS_THREADED_NP
1727
1728 /*
1729 * With assertions enabled, check regularly for appearance of
1730 * additional threads. All builds check at start and exit.
1731 */
1732 Assert(pthread_is_threaded_np() == 0);
1733#endif
1734
1735 /*
1736 * Lastly, check to see if it's time to do some things that we don't
1737 * want to do every single time through the loop, because they're a
1738 * bit expensive. Note that there's up to a minute of slop in when
1739 * these tasks will be performed, since DetermineSleepTime() will let
1740 * us sleep at most that long; except for SIGKILL timeout which has
1741 * special-case logic there.
1742 */
1743 now = time(NULL);
1744
1745 /*
1746 * If we already sent SIGQUIT to children and they are slow to shut
1747 * down, it's time to send them SIGKILL (or SIGABRT if requested).
1748 * This doesn't happen normally, but under certain conditions backends
1749 * can get stuck while shutting down. This is a last measure to get
1750 * them unwedged.
1751 *
1752 * Note we also do this during recovery from a process crash.
1753 */
1755 AbortStartTime != 0 &&
1757 {
1758 /* We were gentle with them before. Not anymore */
1759 ereport(LOG,
1760 /* translator: %s is SIGKILL or SIGABRT */
1761 (errmsg("issuing %s to recalcitrant children",
1762 send_abort_for_kill ? "SIGABRT" : "SIGKILL")));
1764 /* reset flag so we don't SIGKILL again */
1765 AbortStartTime = 0;
1766 }
1767
1768 /*
1769 * Once a minute, verify that postmaster.pid hasn't been removed or
1770 * overwritten. If it has, we force a shutdown. This avoids having
1771 * postmasters and child processes hanging around after their database
1772 * is gone, and maybe causing problems if a new database cluster is
1773 * created in the same place. It also provides some protection
1774 * against a DBA foolishly removing postmaster.pid and manually
1775 * starting a new postmaster. Data corruption is likely to ensue from
1776 * that anyway, but we can minimize the damage by aborting ASAP.
1777 */
1778 if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
1779 {
1781 {
1782 ereport(LOG,
1783 (errmsg("performing immediate shutdown because data directory lock file is invalid")));
1785 }
1786 last_lockfile_recheck_time = now;
1787 }
1788
1789 /*
1790 * Touch Unix socket and lock files every 58 minutes, to ensure that
1791 * they are not removed by overzealous /tmp-cleaning tasks. We assume
1792 * no one runs cleaners with cutoff times of less than an hour ...
1793 */
1794 if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1795 {
1798 last_touch_time = now;
1799 }
1800 }
1801}
#define SECS_PER_MINUTE
Definition: timestamp.h:128
void ResetLatch(Latch *latch)
Definition: latch.c:372
void TouchSocketLockFiles(void)
Definition: miscinit.c:1541
bool RecheckDataDirLockFile(void)
Definition: miscinit.c:1697
static void process_pm_pmsignal(void)
Definition: postmaster.c:3681
static int DetermineSleepTime(void)
Definition: postmaster.c:1543
static void process_pm_child_exit(void)
Definition: postmaster.c:2232
bool send_abort_for_kill
Definition: postmaster.c:256
static void LaunchMissingBackgroundProcesses(void)
Definition: postmaster.c:3278
static int BackendStartup(ClientSocket *client_sock)
Definition: postmaster.c:3529
static void process_pm_shutdown_request(void)
Definition: postmaster.c:2071
static bool avlauncher_needs_signal
Definition: postmaster.c:380
static void process_pm_reload_request(void)
Definition: postmaster.c:1994
int AcceptConnection(pgsocket server_fd, ClientSocket *client_sock)
Definition: pqcomm.c:794
void TouchSocketFiles(void)
Definition: pqcomm.c:830
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)

References AbortStartTime, AcceptConnection(), Assert(), AutoVacLauncherPMChild, avlauncher_needs_signal, BackendStartup(), closesocket, ConfigurePostmasterWaitSet(), DetermineSleepTime(), elog, ereport, errmsg(), FatalError, fd(), i, ImmediateShutdown, kill, LaunchMissingBackgroundProcesses(), lengthof, LOG, MAXLISTEN, MyLatch, MyProcPid, now(), pending_pm_child_exit, pending_pm_pmsignal, pending_pm_reload_request, pending_pm_shutdown_request, PGINVALID_SOCKET, pm_wait_set, process_pm_child_exit(), process_pm_pmsignal(), process_pm_reload_request(), process_pm_shutdown_request(), RecheckDataDirLockFile(), ResetLatch(), SECS_PER_MINUTE, send_abort_for_kill, Shutdown, SIGABRT, SIGKILL, SIGKILL_CHILDREN_AFTER_SECS, signal_child(), SIGQUIT, SIGUSR2, ClientSocket::sock, STATUS_OK, TerminateChildren(), TouchSocketFiles(), TouchSocketLockFiles(), WaitEventSetWait(), WL_LATCH_SET, and WL_SOCKET_ACCEPT.

Referenced by PostmasterMain().

◆ signal_child()

static void signal_child ( PMChild pmchild,
int  signal 
)
static

Definition at line 3442 of file postmaster.c.

3443{
3444 pid_t pid = pmchild->pid;
3445
3447 (errmsg_internal("sending signal %d/%s to %s process with pid %d",
3448 signal, pm_signame(signal),
3450 (int) pmchild->pid)));
3451
3452 if (kill(pid, signal) < 0)
3453 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3454#ifdef HAVE_SETSID
3455 switch (signal)
3456 {
3457 case SIGINT:
3458 case SIGTERM:
3459 case SIGQUIT:
3460 case SIGKILL:
3461 case SIGABRT:
3462 if (kill(-pid, signal) < 0)
3463 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3464 break;
3465 default:
3466 break;
3467 }
3468#endif
3469}
static const char * pm_signame(int signal)
Definition: postmaster.c:3401

References PMChild::bkend_type, DEBUG3, elog, ereport, errmsg_internal(), GetBackendTypeDesc(), kill, PMChild::pid, pm_signame(), SIGABRT, SIGKILL, and SIGQUIT.

Referenced by PostmasterStateMachine(), process_pm_pmsignal(), ServerLoop(), and SignalChildren().

◆ SignalChildren()

static bool SignalChildren ( int  signal,
BackendTypeMask  targetMask 
)
static

Definition at line 3475 of file postmaster.c.

3476{
3477 dlist_iter iter;
3478 bool signaled = false;
3479
3481 {
3482 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3483
3484 /*
3485 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3486 * if any B_BACKEND backends have recently announced that they are
3487 * actually WAL senders.
3488 */
3489 if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3490 bp->bkend_type == B_BACKEND)
3491 {
3494 }
3495
3496 if (!btmask_contains(targetMask, bp->bkend_type))
3497 continue;
3498
3499 signal_child(bp, signal);
3500 signaled = true;
3501 }
3502 return signaled;
3503}

References ActiveChildList, B_BACKEND, B_WAL_SENDER, PMChild::bkend_type, btmask_contains(), PMChild::child_slot, dlist_iter::cur, dlist_container, dlist_foreach, IsPostmasterChildWalSender(), and signal_child().

Referenced by PostmasterStateMachine(), process_pm_child_exit(), process_pm_pmsignal(), process_pm_reload_request(), and TerminateChildren().

◆ StartAutovacuumWorker()

static void StartAutovacuumWorker ( void  )
static

Definition at line 4017 of file postmaster.c.

4018{
4019 PMChild *bn;
4020
4021 /*
4022 * If not in condition to run a process, don't try, but handle it like a
4023 * fork failure. This does not normally happen, since the signal is only
4024 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4025 * we have to check to avoid race-condition problems during DB state
4026 * changes.
4027 */
4029 {
4031 if (bn)
4032 {
4033 bn->bgworker_notify = false;
4034 bn->rw = NULL;
4035 return;
4036 }
4037 else
4038 {
4039 /*
4040 * fork failed, fall through to report -- actual error message was
4041 * logged by StartChildProcess
4042 */
4043 }
4044 }
4045
4046 /*
4047 * Report the failure to the launcher, if it's running. (If it's not, we
4048 * might not even be connected to shared memory, so don't try to call
4049 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4050 * responds to the condition, but we don't do that here, instead waiting
4051 * for ServerLoop to do it. This way we avoid a ping-pong signaling in
4052 * quick succession between the autovac launcher and postmaster in case
4053 * things get ugly.
4054 */
4055 if (AutoVacLauncherPMChild != NULL)
4056 {
4059 }
4060}
void AutoVacWorkerFailed(void)
Definition: autovacuum.c:1354

References AutoVacLauncherPMChild, AutoVacWorkerFailed(), avlauncher_needs_signal, B_AUTOVAC_WORKER, PMChild::bgworker_notify, CAC_OK, canAcceptConnections(), PMChild::rw, and StartChildProcess().

Referenced by process_pm_pmsignal().

◆ StartBackgroundWorker()

static bool StartBackgroundWorker ( RegisteredBgWorker rw)
static

Definition at line 4109 of file postmaster.c.

4110{
4111 PMChild *bn;
4112 pid_t worker_pid;
4113
4114 Assert(rw->rw_pid == 0);
4115
4116 /*
4117 * Allocate and assign the child slot. Note we must do this before
4118 * forking, so that we can handle failures (out of memory or child-process
4119 * slots) cleanly.
4120 *
4121 * Treat failure as though the worker had crashed. That way, the
4122 * postmaster will wait a bit before attempting to start it again; if we
4123 * tried again right away, most likely we'd find ourselves hitting the
4124 * same resource-exhaustion condition.
4125 */
4127 if (bn == NULL)
4128 {
4129 ereport(LOG,
4130 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
4131 errmsg("no slot available for new background worker process")));
4133 return false;
4134 }
4135 bn->rw = rw;
4136 bn->bkend_type = B_BG_WORKER;
4137 bn->bgworker_notify = false;
4138
4140 (errmsg_internal("starting background worker process \"%s\"",
4141 rw->rw_worker.bgw_name)));
4142
4144 &rw->rw_worker, sizeof(BackgroundWorker), NULL);
4145 if (worker_pid == -1)
4146 {
4147 /* in postmaster, fork failed ... */
4148 ereport(LOG,
4149 (errmsg("could not fork background worker process: %m")));
4150 /* undo what AssignPostmasterChildSlot did */
4152
4153 /* mark entry as crashed, so we'll try again later */
4155 return false;
4156 }
4157
4158 /* in postmaster, fork successful ... */
4159 rw->rw_pid = worker_pid;
4160 bn->pid = rw->rw_pid;
4162 return true;
4163}
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91

References Assert(), AssignPostmasterChildSlot(), B_BG_WORKER, BackgroundWorker::bgw_name, PMChild::bgworker_notify, PMChild::bkend_type, PMChild::child_slot, DEBUG1, ereport, errcode(), errmsg(), errmsg_internal(), GetCurrentTimestamp(), LOG, PMChild::pid, postmaster_child_launch(), ReleasePostmasterChildSlot(), ReportBackgroundWorkerPID(), PMChild::rw, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, and RegisteredBgWorker::rw_worker.

Referenced by maybe_start_bgworkers().

◆ StartChildProcess()

static PMChild * StartChildProcess ( BackendType  type)
static

Definition at line 3946 of file postmaster.c.

3947{
3948 PMChild *pmchild;
3949 pid_t pid;
3950
3952 if (!pmchild)
3953 {
3954 if (type == B_AUTOVAC_WORKER)
3955 ereport(LOG,
3956 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
3957 errmsg("no slot available for new autovacuum worker process")));
3958 else
3959 {
3960 /* shouldn't happen because we allocate enough slots */
3961 elog(LOG, "no postmaster child slot available for aux process");
3962 }
3963 return NULL;
3964 }
3965
3966 pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
3967 if (pid < 0)
3968 {
3969 /* in parent, fork failed */
3971 ereport(LOG,
3972 (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
3973
3974 /*
3975 * fork failure is fatal during startup, but there's no need to choke
3976 * immediately if starting other child types fails.
3977 */
3978 if (type == B_STARTUP)
3979 ExitPostmaster(1);
3980 return NULL;
3981 }
3982
3983 /* in parent, successful fork */
3984 pmchild->pid = pid;
3985 return pmchild;
3986}
const char * PostmasterChildName(BackendType child_type)
const char * type

References AssignPostmasterChildSlot(), B_AUTOVAC_WORKER, B_STARTUP, PMChild::child_slot, elog, ereport, errcode(), errmsg(), ExitPostmaster(), LOG, PMChild::pid, postmaster_child_launch(), PostmasterChildName(), ReleasePostmasterChildSlot(), and type.

Referenced by LaunchMissingBackgroundProcesses(), maybe_adjust_io_workers(), PostmasterMain(), PostmasterStateMachine(), process_pm_pmsignal(), and StartAutovacuumWorker().

◆ StartSysLogger()

void StartSysLogger ( void  )
static

Definition at line 3992 of file postmaster.c.

3993{
3994 Assert(SysLoggerPMChild == NULL);
3995
3997 if (!SysLoggerPMChild)
3998 elog(PANIC, "no postmaster child slot available for syslogger");
4000 if (SysLoggerPMChild->pid == 0)
4001 {
4003 SysLoggerPMChild = NULL;
4004 }
4005}
#define PANIC
Definition: elog.h:42
int SysLogger_Start(int child_slot)
Definition: syslogger.c:593

References Assert(), AssignPostmasterChildSlot(), B_LOGGER, PMChild::child_slot, elog, PANIC, PMChild::pid, ReleasePostmasterChildSlot(), SysLogger_Start(), and SysLoggerPMChild.

Referenced by LaunchMissingBackgroundProcesses(), PostmasterMain(), and process_pm_child_exit().

◆ StaticAssertDecl()

StaticAssertDecl ( )

◆ TerminateChildren()

static void TerminateChildren ( int  signal)
static

Definition at line 3510 of file postmaster.c.

3511{
3513 if (StartupPMChild != NULL)
3514 {
3515 if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
3517 }
3518}

References B_LOGGER, btmask_all_except, SIGABRT, SIGKILL, SignalChildren(), SIGQUIT, STARTUP_SIGNALED, StartupPMChild, and StartupStatus.

Referenced by HandleFatalError(), process_pm_child_exit(), process_pm_shutdown_request(), and ServerLoop().

◆ unlink_external_pid_file()

static void unlink_external_pid_file ( int  status,
Datum  arg 
)
static

Definition at line 1448 of file postmaster.c.

1449{
1451 unlink(external_pid_file);
1452}

References external_pid_file.

Referenced by PostmasterMain().

◆ UpdatePMState()

static void UpdatePMState ( PMState  newState)
static

Definition at line 3262 of file postmaster.c.

3263{
3264 elog(DEBUG1, "updating PMState from %s to %s",
3265 pmstate_name(pmState), pmstate_name(newState));
3266 pmState = newState;
3267}
static const char * pmstate_name(PMState state)
Definition: postmaster.c:3232

References DEBUG1, elog, pmState, and pmstate_name().

Referenced by HandleFatalError(), PostmasterMain(), PostmasterStateMachine(), process_pm_child_exit(), process_pm_pmsignal(), and process_pm_shutdown_request().

Variable Documentation

◆ AbortStartTime

◆ AuthenticationTimeout

int AuthenticationTimeout = 60

Definition at line 240 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ AutoVacLauncherPMChild

PMChild * AutoVacLauncherPMChild = NULL
static

◆ avlauncher_needs_signal

bool avlauncher_needs_signal = false
static

Definition at line 380 of file postmaster.c.

Referenced by ServerLoop(), and StartAutovacuumWorker().

◆ BgWriterPMChild

PMChild * BgWriterPMChild = NULL
static

◆ bonjour_name

char* bonjour_name

Definition at line 245 of file postmaster.c.

Referenced by PostmasterMain().

◆ BTYPE_MASK_ALL

const BackendTypeMask BTYPE_MASK_ALL = {(1 << BACKEND_NUM_TYPES) - 1}
static

Definition at line 144 of file postmaster.c.

Referenced by btmask_all_except_n(), and PostmasterStateMachine().

◆ BTYPE_MASK_NONE

const BackendTypeMask BTYPE_MASK_NONE = {0}
static

Definition at line 145 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ CheckpointerPMChild

PMChild * CheckpointerPMChild = NULL
static

◆ ClientAuthInProgress

◆ connsAllowed

◆ enable_bonjour

bool enable_bonjour = false

Definition at line 244 of file postmaster.c.

Referenced by PostmasterMain().

◆ EnableSSL

bool EnableSSL = false

◆ FatalError

◆ HaveCrashedWorker

bool HaveCrashedWorker = false
static

◆ io_worker_children

PMChild* io_worker_children[MAX_IO_WORKERS]
static

Definition at line 411 of file postmaster.c.

Referenced by maybe_adjust_io_workers(), and maybe_reap_io_worker().

◆ io_worker_count

int io_worker_count = 0
static

◆ ListenAddresses

char* ListenAddresses

Definition at line 208 of file postmaster.c.

Referenced by PostmasterMain().

◆ ListenSockets

pgsocket* ListenSockets = NULL
static

◆ log_hostname

bool log_hostname

Definition at line 242 of file postmaster.c.

Referenced by BackendInitialize().

◆ MyBgworkerEntry

◆ NumListenSockets

int NumListenSockets = 0
static

◆ pending_pm_child_exit

volatile sig_atomic_t pending_pm_child_exit
static

Definition at line 391 of file postmaster.c.

Referenced by handle_pm_child_exit_signal(), process_pm_child_exit(), and ServerLoop().

◆ pending_pm_fast_shutdown_request

volatile sig_atomic_t pending_pm_fast_shutdown_request
static

Definition at line 394 of file postmaster.c.

Referenced by handle_pm_shutdown_request_signal(), and process_pm_shutdown_request().

◆ pending_pm_immediate_shutdown_request

volatile sig_atomic_t pending_pm_immediate_shutdown_request
static

Definition at line 395 of file postmaster.c.

Referenced by handle_pm_shutdown_request_signal(), and process_pm_shutdown_request().

◆ pending_pm_pmsignal

volatile sig_atomic_t pending_pm_pmsignal
static

Definition at line 390 of file postmaster.c.

Referenced by handle_pm_pmsignal_signal(), process_pm_pmsignal(), and ServerLoop().

◆ pending_pm_reload_request

volatile sig_atomic_t pending_pm_reload_request
static

◆ pending_pm_shutdown_request

volatile sig_atomic_t pending_pm_shutdown_request
static

◆ PgArchPMChild

PMChild * PgArchPMChild = NULL
static

◆ pm_wait_set

WaitEventSet* pm_wait_set
static

Definition at line 398 of file postmaster.c.

Referenced by ClosePostmasterPorts(), ConfigurePostmasterWaitSet(), and ServerLoop().

◆ pmState

◆ postmaster_alive_fds

int postmaster_alive_fds[2] = {-1, -1}

◆ PostPortNumber

int PostPortNumber = DEF_PGPORT

Definition at line 202 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

int PreAuthDelay = 0

Definition at line 239 of file postmaster.c.

Referenced by BackendInitialize().

◆ ReachedNormalRunning

bool ReachedNormalRunning = false
static

Definition at line 369 of file postmaster.c.

Referenced by process_pm_child_exit().

◆ redirection_done

bool redirection_done = false

◆ remove_temp_files_after_crash

bool remove_temp_files_after_crash = true

Definition at line 247 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ ReservedConnections

int ReservedConnections

Definition at line 229 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

bool restart_after_crash = true

Definition at line 246 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

bool send_abort_for_crash = false

Definition at line 255 of file postmaster.c.

Referenced by HandleFatalError().

◆ send_abort_for_kill

bool send_abort_for_kill = false

Definition at line 256 of file postmaster.c.

Referenced by ServerLoop().

◆ Shutdown

◆ SlotSyncWorkerPMChild

PMChild * SlotSyncWorkerPMChild = NULL
static

◆ start_autovac_launcher

bool start_autovac_launcher = false
static

Definition at line 377 of file postmaster.c.

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ StartupPMChild

PMChild* StartupPMChild = NULL
static

◆ StartupStatus

◆ StartWorkerNeeded

◆ SuperuserReservedConnections

int SuperuserReservedConnections

Definition at line 228 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ SysLoggerPMChild

PMChild * SysLoggerPMChild = NULL
static

◆ Unix_socket_directories

char* Unix_socket_directories

Definition at line 205 of file postmaster.c.

Referenced by PostmasterMain().

◆ WalReceiverPMChild

PMChild * WalReceiverPMChild = NULL
static

◆ WalReceiverRequested

bool WalReceiverRequested = false
static

Definition at line 383 of file postmaster.c.

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ WalSummarizerPMChild

PMChild * WalSummarizerPMChild = NULL
static

◆ WalWriterPMChild

PMChild * WalWriterPMChild = NULL
static