PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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/xlog_internal.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:791
BackendType
Definition: miscadmin.h:338
static BackendTypeMask btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
Definition: postmaster.c:157

Definition at line 164 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:178

Definition at line 187 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 474 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 475 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 476 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 285 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 286 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 233 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 283 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 368 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 284 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 334 of file postmaster.c.

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 272 of file postmaster.c.

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

Function Documentation

◆ BackendStartup()

static int BackendStartup ( ClientSocket client_sock)
static

Definition at line 3547 of file postmaster.c.

3548{
3549 PMChild *bn = NULL;
3550 pid_t pid;
3551 BackendStartupData startup_data;
3552 CAC_state cac;
3553
3554 /*
3555 * Capture time that Postmaster got a socket from accept (for logging
3556 * connection establishment and setup total duration).
3557 */
3558 startup_data.socket_created = GetCurrentTimestamp();
3559
3560 /*
3561 * Allocate and assign the child slot. Note we must do this before
3562 * forking, so that we can handle failures (out of memory or child-process
3563 * slots) cleanly.
3564 */
3566 if (cac == CAC_OK)
3567 {
3568 /* Can change later to B_WAL_SENDER */
3570 if (!bn)
3571 {
3572 /*
3573 * Too many regular child processes; launch a dead-end child
3574 * process instead.
3575 */
3576 cac = CAC_TOOMANY;
3577 }
3578 }
3579 if (!bn)
3580 {
3581 bn = AllocDeadEndChild();
3582 if (!bn)
3583 {
3584 ereport(LOG,
3585 (errcode(ERRCODE_OUT_OF_MEMORY),
3586 errmsg("out of memory")));
3587 return STATUS_ERROR;
3588 }
3589 }
3590
3591 /* Pass down canAcceptConnections state */
3592 startup_data.canAcceptConnections = cac;
3593 bn->rw = NULL;
3594
3595 /* Hasn't asked to be notified about any bgworkers yet */
3596 bn->bgworker_notify = false;
3597
3599 &startup_data, sizeof(startup_data),
3600 client_sock);
3601 if (pid < 0)
3602 {
3603 /* in parent, fork failed */
3604 int save_errno = errno;
3605
3606 (void) ReleasePostmasterChildSlot(bn);
3607 errno = save_errno;
3608 ereport(LOG,
3609 (errmsg("could not fork new process for connection: %m")));
3610 report_fork_failure_to_client(client_sock, save_errno);
3611 return STATUS_ERROR;
3612 }
3613
3614 /* in parent, successful fork */
3616 (errmsg_internal("forked new %s, pid=%d socket=%d",
3618 (int) pid, (int) client_sock->sock)));
3619
3620 /*
3621 * Everything's been successful, it's safe to add this backend to our list
3622 * of backends.
3623 */
3624 bn->pid = pid;
3625 return STATUS_OK;
3626}
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
CAC_state
@ CAC_TOOMANY
@ CAC_OK
#define STATUS_OK
Definition: c.h:1172
#define STATUS_ERROR
Definition: c.h:1173
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1170
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define LOG
Definition: elog.h:31
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:150
pid_t postmaster_child_launch(BackendType child_type, int child_slot, void *startup_data, size_t startup_data_len, ClientSocket *client_sock)
@ B_BACKEND
Definition: miscadmin.h:342
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:263
PMChild * AssignPostmasterChildSlot(BackendType btype)
Definition: pmchild.c:178
bool ReleasePostmasterChildSlot(PMChild *pmchild)
Definition: pmchild.c:252
PMChild * AllocDeadEndChild(void)
Definition: pmchild.c:224
static CAC_state canAcceptConnections(BackendType backend_type)
Definition: postmaster.c:1822
static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
Definition: postmaster.c:3637
CAC_state canAcceptConnections
TimestampTz socket_created
pgsocket sock
Definition: libpq-be.h:250
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 4195 of file postmaster.c.

4196{
4197 switch (pmState)
4198 {
4199 case PM_NO_CHILDREN:
4201 case PM_WAIT_DEAD_END:
4204 case PM_WAIT_IO_WORKERS:
4205 case PM_WAIT_BACKENDS:
4206 case PM_STOP_BACKENDS:
4207 break;
4208
4209 case PM_RUN:
4211 return true;
4212 /* fall through */
4213
4214 case PM_HOT_STANDBY:
4216 return true;
4217 /* fall through */
4218
4219 case PM_RECOVERY:
4220 case PM_STARTUP:
4221 case PM_INIT:
4223 return true;
4224 /* fall through */
4225 }
4226
4227 return false;
4228}
@ 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:96
static PMState pmState
Definition: postmaster.c:353

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 149 of file postmaster.c.

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

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 157 of file postmaster.c.

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

References i, and BackendTypeMask::mask.

◆ btmask_all_except_n()

static BackendTypeMask btmask_all_except_n ( int  nargs,
BackendType t 
)
inlinestatic

Definition at line 178 of file postmaster.c.

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

References btmask_del(), BTYPE_MASK_ALL, and i.

◆ btmask_contains()

static bool btmask_contains ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 194 of file postmaster.c.

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

References BackendTypeMask::mask.

Referenced by CountChildren(), and SignalChildren().

◆ btmask_del()

static BackendTypeMask btmask_del ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 171 of file postmaster.c.

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

References BackendTypeMask::mask.

Referenced by btmask_all_except_n().

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( BackendType  backend_type)
static

Definition at line 1822 of file postmaster.c.

1823{
1824 CAC_state result = CAC_OK;
1825
1826 Assert(backend_type == B_BACKEND || backend_type == B_AUTOVAC_WORKER);
1827
1828 /*
1829 * Can't start backends when in startup/shutdown/inconsistent recovery
1830 * state. We treat autovac workers the same as user backends for this
1831 * purpose.
1832 */
1833 if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
1834 {
1835 if (Shutdown > NoShutdown)
1836 return CAC_SHUTDOWN; /* shutdown is pending */
1837 else if (!FatalError && pmState == PM_STARTUP)
1838 return CAC_STARTUP; /* normal startup */
1839 else if (!FatalError && pmState == PM_RECOVERY)
1840 return CAC_NOTHOTSTANDBY; /* not yet ready for hot standby */
1841 else
1842 return CAC_RECOVERY; /* else must be crash recovery */
1843 }
1844
1845 /*
1846 * "Smart shutdown" restrictions are applied only to normal connections,
1847 * not to autovac workers.
1848 */
1849 if (!connsAllowed && backend_type == B_BACKEND)
1850 return CAC_SHUTDOWN; /* shutdown is pending */
1851
1852 return result;
1853}
@ CAC_RECOVERY
@ CAC_NOTHOTSTANDBY
@ CAC_STARTUP
@ CAC_SHUTDOWN
Assert(PointerIsAligned(start, uint64))
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:345
static bool connsAllowed
Definition: postmaster.c:361
static int Shutdown
Definition: postmaster.c:288
#define NoShutdown
Definition: postmaster.c:283
static bool FatalError
Definition: postmaster.c:290

References Assert(), B_AUTOVAC_WORKER, B_BACKEND, CAC_NOTHOTSTANDBY, 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 1518 of file postmaster.c.

1519{
1520 char path[MAXPGPATH];
1521 FILE *fp;
1522
1523 snprintf(path, sizeof(path), "%s/%s", DataDir, XLOG_CONTROL_FILE);
1524
1525 fp = AllocateFile(path, PG_BINARY_R);
1526 if (fp == NULL)
1527 {
1528 write_stderr("%s: could not find the database system\n"
1529 "Expected to find it in the directory \"%s\",\n"
1530 "but could not open file \"%s\": %m\n",
1531 progname, DataDir, path);
1532 ExitPostmaster(2);
1533 }
1534 FreeFile(fp);
1535}
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1278
int FreeFile(FILE *file)
Definition: fd.c:2840
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2641
char * DataDir
Definition: globals.c:71
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:3664
#define XLOG_CONTROL_FILE

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

Referenced by PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( PMChild bp,
int  exitstatus 
)
static

Definition at line 2576 of file postmaster.c.

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

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

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 1418 of file postmaster.c.

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

1641{
1642 if (pm_wait_set)
1644 pm_wait_set = NULL;
1645
1647 accept_connections ? (1 + NumListenSockets) : 1);
1649 NULL);
1650
1651 if (accept_connections)
1652 {
1653 for (int i = 0; i < NumListenSockets; i++)
1655 NULL, NULL);
1656 }
1657}
struct Latch * MyLatch
Definition: globals.c:63
#define PGINVALID_SOCKET
Definition: port.h:31
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: waiteventset.c:570
void FreeWaitEventSet(WaitEventSet *set)
Definition: waiteventset.c:481
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: waiteventset.c:364
#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 3927 of file postmaster.c.

3928{
3929 dlist_iter iter;
3930 int cnt = 0;
3931
3933 {
3934 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3935
3936 /*
3937 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3938 * if any B_BACKEND backends have recently announced that they are
3939 * actually WAL senders.
3940 */
3941 if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3942 bp->bkend_type == B_BACKEND)
3943 {
3946 }
3947
3948 if (!btmask_contains(targetMask, bp->bkend_type))
3949 continue;
3950
3952 (errmsg_internal("%s process %d is still running",
3953 GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
3954
3955 cnt++;
3956 }
3957 return cnt;
3958}
#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:347
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:194
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 4092 of file postmaster.c.

4093{
4094 FILE *fp;
4095 int i;
4096
4097#define OPTS_FILE "postmaster.opts"
4098
4099 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4100 {
4101 ereport(LOG,
4103 errmsg("could not create file \"%s\": %m", OPTS_FILE)));
4104 return false;
4105 }
4106
4107 fprintf(fp, "%s", fullprogname);
4108 for (i = 1; i < argc; i++)
4109 fprintf(fp, " \"%s\"", argv[i]);
4110 fputs("\n", fp);
4111
4112 if (fclose(fp))
4113 {
4114 ereport(LOG,
4116 errmsg("could not write file \"%s\": %m", OPTS_FILE)));
4117 return false;
4118 }
4119
4120 return true;
4121}
#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 1547 of file postmaster.c.

1548{
1549 TimestampTz next_wakeup = 0;
1550
1551 /*
1552 * Normal case: either there are no background workers at all, or we're in
1553 * a shutdown sequence (during which we ignore bgworkers altogether).
1554 */
1555 if (Shutdown > NoShutdown ||
1557 {
1558 if (AbortStartTime != 0)
1559 {
1560 time_t curtime = time(NULL);
1561 int seconds;
1562
1563 /*
1564 * time left to abort; clamp to 0 if it already expired, or if
1565 * time goes backwards
1566 */
1567 if (curtime < AbortStartTime ||
1569 seconds = 0;
1570 else
1571 seconds = SIGKILL_CHILDREN_AFTER_SECS -
1572 (curtime - AbortStartTime);
1573
1574 return seconds * 1000;
1575 }
1576 else
1577 return 60 * 1000;
1578 }
1579
1581 return 0;
1582
1584 {
1585 dlist_mutable_iter iter;
1586
1587 /*
1588 * When there are crashed bgworkers, we sleep just long enough that
1589 * they are restarted when they request to be. Scan the list to
1590 * determine the minimum of all wakeup times according to most recent
1591 * crash time and requested restart interval.
1592 */
1594 {
1596 TimestampTz this_wakeup;
1597
1598 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
1599
1600 if (rw->rw_crashed_at == 0)
1601 continue;
1602
1604 || rw->rw_terminate)
1605 {
1607 continue;
1608 }
1609
1611 1000L * rw->rw_worker.bgw_restart_time);
1612 if (next_wakeup == 0 || this_wakeup < next_wakeup)
1613 next_wakeup = this_wakeup;
1614 }
1615 }
1616
1617 if (next_wakeup != 0)
1618 {
1619 int ms;
1620
1621 /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1623 next_wakeup);
1624 return Min(60 * 1000, ms);
1625 }
1626
1627 return 60 * 1000;
1628}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1757
dlist_head BackgroundWorkerList
Definition: bgworker.c:40
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition: bgworker.c:432
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Min(x, y)
Definition: c.h:1007
int64 TimestampTz
Definition: timestamp.h:39
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:640
static time_t AbortStartTime
Definition: postmaster.c:365
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:368
static bool StartWorkerNeeded
Definition: postmaster.c:387
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, 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 3919 of file postmaster.c.

3920{
3921}

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 3664 of file postmaster.c.

3665{
3666#ifdef HAVE_PTHREAD_IS_THREADED_NP
3667
3668 /*
3669 * There is no known cause for a postmaster to become multithreaded after
3670 * startup. However, we might reach here via an error exit before
3671 * reaching the test in PostmasterMain, so provide the same hint as there.
3672 * This message uses LOG level, because an unclean shutdown at this point
3673 * would usually not look much different from a clean shutdown.
3674 */
3675 if (pthread_is_threaded_np() != 0)
3676 ereport(LOG,
3677 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3678 errmsg("postmaster became multithreaded"),
3679 errhint("Set the LC_ALL environment variable to a valid locale.")));
3680#endif
3681
3682 /* should cleanup shared memory and kill all backends */
3683
3684 /*
3685 * Not sure of the semantics here. When the Postmaster dies, should the
3686 * backends all be killed? probably not.
3687 *
3688 * MUST -- vadim 05-10-1999
3689 */
3690
3691 proc_exit(status);
3692}
int errhint(const char *fmt,...)
Definition: elog.c:1330
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 1464 of file postmaster.c.

1465{
1466 DIR *pdir;
1467
1468 /* Locate the postgres executable itself */
1470 ereport(FATAL,
1471 (errmsg("%s: could not locate my own executable path", argv0)));
1472
1473#ifdef EXEC_BACKEND
1474 /* Locate executable backend before we change working directory */
1476 postgres_exec_path) < 0)
1477 ereport(FATAL,
1478 (errmsg("%s: could not locate matching postgres executable",
1479 argv0)));
1480#endif
1481
1482 /*
1483 * Locate the pkglib directory --- this has to be set early in case we try
1484 * to load any modules from it in response to postgresql.conf entries.
1485 */
1487
1488 /*
1489 * Verify that there's a readable directory there; otherwise the Postgres
1490 * installation is incomplete or corrupt. (A typical cause of this
1491 * failure is that the postgres executable has been moved or hardlinked to
1492 * some directory that's not a sibling of the installation lib/
1493 * directory.)
1494 */
1495 pdir = AllocateDir(pkglib_path);
1496 if (pdir == NULL)
1497 ereport(ERROR,
1499 errmsg("could not open directory \"%s\": %m",
1500 pkglib_path),
1501 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1502 my_exec_path)));
1503 FreeDir(pdir);
1504
1505 /*
1506 * It's not worth checking the share/ directory. If the lib/ directory is
1507 * there, then share/ probably is too.
1508 */
1509}
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:161
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:311
#define ERROR
Definition: elog.h:39
int FreeDir(DIR *dir)
Definition: fd.c:3022
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2904
char pkglib_path[MAXPGPATH]
Definition: globals.c:82
char my_exec_path[MAXPGPATH]
Definition: globals.c:81
static char * argv0
Definition: pg_ctl.c:94
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 2233 of file postmaster.c.

2234{
2235 pending_pm_child_exit = true;
2237}
void SetLatch(Latch *latch)
Definition: latch.c:290
static volatile sig_atomic_t pending_pm_child_exit
Definition: postmaster.c:392

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 1985 of file postmaster.c.

1986{
1987 pending_pm_pmsignal = true;
1989}
static volatile sig_atomic_t pending_pm_pmsignal
Definition: postmaster.c:391

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 1995 of file postmaster.c.

1996{
1999}
static volatile sig_atomic_t pending_pm_reload_request
Definition: postmaster.c:393

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 2058 of file postmaster.c.

2059{
2060 switch (postgres_signal_arg)
2061 {
2062 case SIGTERM:
2063 /* smart is implied if the other two flags aren't set */
2065 break;
2066 case SIGINT:
2069 break;
2070 case SIGQUIT:
2073 break;
2074 }
2076}
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition: postmaster.c:395
static volatile sig_atomic_t pending_pm_shutdown_request
Definition: postmaster.c:394
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition: postmaster.c:396
#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 2801 of file postmaster.c.

2802{
2803 /*
2804 * We only log messages and send signals if this is the first process
2805 * crash and we're not doing an immediate shutdown; otherwise, we're only
2806 * here to update postmaster's idea of live processes. If we have already
2807 * signaled children, nonzero exit status is to be expected, so don't
2808 * clutter log.
2809 */
2811 return;
2812
2813 LogChildExit(LOG, procname, pid, exitstatus);
2814 ereport(LOG,
2815 (errmsg("terminating any other active server processes")));
2816
2817 /*
2818 * Switch into error state. The crashed process has already been removed
2819 * from ActiveChildList.
2820 */
2822}
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:55
#define ImmediateShutdown
Definition: postmaster.c:286
static void HandleFatalError(QuitSignalReason reason, bool consider_sigabrt)
Definition: postmaster.c:2712

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 2712 of file postmaster.c.

2713{
2714 int sigtosend;
2715
2718
2719 SetQuitSignalReason(reason);
2720
2721 if (consider_sigabrt && send_abort_for_crash)
2722 sigtosend = SIGABRT;
2723 else
2724 sigtosend = SIGQUIT;
2725
2726 /*
2727 * Signal all other child processes to exit.
2728 *
2729 * We could exclude dead-end children here, but at least when sending
2730 * SIGABRT it seems better to include them.
2731 */
2732 TerminateChildren(sigtosend);
2733
2734 FatalError = true;
2735
2736 /*
2737 * Choose the appropriate new state to react to the fatal error. Unless we
2738 * were already in the process of shutting down, we go through
2739 * PM_WAIT_BACKENDS. For errors during the shutdown sequence, we directly
2740 * switch to PM_WAIT_DEAD_END.
2741 */
2742 switch (pmState)
2743 {
2744 case PM_INIT:
2745 /* shouldn't have any children */
2746 Assert(false);
2747 break;
2748 case PM_STARTUP:
2749 /* should have been handled in process_pm_child_exit */
2750 Assert(false);
2751 break;
2752
2753 /* wait for children to die */
2754 case PM_RECOVERY:
2755 case PM_HOT_STANDBY:
2756 case PM_RUN:
2757 case PM_STOP_BACKENDS:
2759 break;
2760
2761 case PM_WAIT_BACKENDS:
2762 /* there might be more backends to wait for */
2763 break;
2764
2768 case PM_WAIT_IO_WORKERS:
2769
2770 /*
2771 * NB: Similar code exists in PostmasterStateMachine()'s handling
2772 * of FatalError in PM_STOP_BACKENDS/PM_WAIT_BACKENDS states.
2773 */
2776 break;
2777
2778 case PM_WAIT_DEAD_END:
2779 case PM_NO_CHILDREN:
2780 break;
2781 }
2782
2783 /*
2784 * .. and if this doesn't happen quickly enough, now the clock is ticking
2785 * for us to kill them without mercy.
2786 */
2787 if (AbortStartTime == 0)
2788 AbortStartTime = time(NULL);
2789}
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:202
static void TerminateChildren(int signal)
Definition: postmaster.c:3528
static void UpdatePMState(PMState newState)
Definition: postmaster.c:3280
bool send_abort_for_crash
Definition: postmaster.c:256
static void ConfigurePostmasterWaitSet(bool accept_connections)
Definition: postmaster.c:1640
#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 4589 of file postmaster.c.

4590{
4591#ifndef WIN32
4592
4593 /*
4594 * Create a pipe. Postmaster holds the write end of the pipe open
4595 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
4596 * the read file descriptor to select() to wake up in case postmaster
4597 * dies, or check for postmaster death with a (read() == 0). Children must
4598 * close the write end as soon as possible after forking, because EOF
4599 * won't be signaled in the read end until all processes have closed the
4600 * write fd. That is taken care of in ClosePostmasterPorts().
4601 */
4603 if (pipe(postmaster_alive_fds) < 0)
4604 ereport(FATAL,
4606 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
4607
4608 /* Notify fd.c that we've eaten two FDs for the pipe. */
4611
4612 /*
4613 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
4614 * call.
4615 */
4616 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
4617 ereport(FATAL,
4619 errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
4620#else
4621
4622 /*
4623 * On Windows, we use a process handle for the same purpose.
4624 */
4625 if (DuplicateHandle(GetCurrentProcess(),
4626 GetCurrentProcess(),
4627 GetCurrentProcess(),
4628 &PostmasterHandle,
4629 0,
4630 TRUE,
4631 DUPLICATE_SAME_ACCESS) == 0)
4632 ereport(FATAL,
4633 (errmsg_internal("could not duplicate postmaster handle: error code %lu",
4634 GetLastError())));
4635#endif /* WIN32 */
4636}
int errcode_for_socket_access(void)
Definition: elog.c:963
void ReserveExternalFD(void)
Definition: fd.c:1220
pid_t PostmasterPid
Definition: globals.c:106
int MyProcPid
Definition: globals.c:47
#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 1943 of file postmaster.c.

1944{
1947
1948 /*
1949 * Set a different global seed in every process. We want something
1950 * unpredictable, so if possible, use high-quality random bits for the
1951 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1952 */
1954 {
1955 uint64 rseed;
1956
1957 /*
1958 * Since PIDs and timestamps tend to change more frequently in their
1959 * least significant bits, shift the timestamp left to allow a larger
1960 * total number of seeds in a given time period. Since that would
1961 * leave only 20 bits of the timestamp that cycle every ~1 second,
1962 * also mix in some higher bits.
1963 */
1964 rseed = ((uint64) MyProcPid) ^
1965 ((uint64) MyStartTimestamp << 12) ^
1966 ((uint64) MyStartTimestamp >> 20);
1967
1969 }
1970
1971 /*
1972 * Also make sure that we've set a good seed for random(3). Use of that
1973 * is deprecated in core Postgres, but extensions might use it.
1974 */
1975#ifndef WIN32
1977#endif
1978}
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1842
uint64_t uint64
Definition: c.h:543
#define unlikely(x)
Definition: c.h:406
TimestampTz MyStartTimestamp
Definition: globals.c:49
pg_time_t MyStartTime
Definition: globals.c:48
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 3296 of file postmaster.c.

3297{
3298 /* Syslogger is active in all states */
3299 if (SysLoggerPMChild == NULL && Logging_collector)
3301
3302 /*
3303 * The number of configured workers might have changed, or a prior start
3304 * of a worker might have failed. Check if we need to start/stop any
3305 * workers.
3306 *
3307 * A config file change will always lead to this function being called, so
3308 * we always will process the config change in a timely manner.
3309 */
3311
3312 /*
3313 * The checkpointer and the background writer are active from the start,
3314 * until shutdown is initiated.
3315 *
3316 * (If the checkpointer is not running when we enter the
3317 * PM_WAIT_XLOG_SHUTDOWN state, it is launched one more time to perform
3318 * the shutdown checkpoint. That's done in PostmasterStateMachine(), not
3319 * here.)
3320 */
3321 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
3323 {
3324 if (CheckpointerPMChild == NULL)
3326 if (BgWriterPMChild == NULL)
3328 }
3329
3330 /*
3331 * WAL writer is needed only in normal operation (else we cannot be
3332 * writing any new WAL).
3333 */
3334 if (WalWriterPMChild == NULL && pmState == PM_RUN)
3336
3337 /*
3338 * We don't want autovacuum to run in binary upgrade mode because
3339 * autovacuum might update relfrozenxid for empty tables before the
3340 * physical files are put in place.
3341 */
3342 if (!IsBinaryUpgrade && AutoVacLauncherPMChild == NULL &&
3344 pmState == PM_RUN)
3345 {
3347 if (AutoVacLauncherPMChild != NULL)
3348 start_autovac_launcher = false; /* signal processed */
3349 }
3350
3351 /*
3352 * If WAL archiving is enabled always, we are allowed to start archiver
3353 * even during recovery.
3354 */
3355 if (PgArchPMChild == NULL &&
3356 ((XLogArchivingActive() && pmState == PM_RUN) ||
3360
3361 /*
3362 * If we need to start a slot sync worker, try to do that now
3363 *
3364 * We allow to start the slot sync worker when we are on a hot standby,
3365 * fast or immediate shutdown is not in progress, slot sync parameters are
3366 * configured correctly, and it is the first time of worker's launch, or
3367 * enough time has passed since the worker was launched last.
3368 */
3369 if (SlotSyncWorkerPMChild == NULL && pmState == PM_HOT_STANDBY &&
3373
3374 /*
3375 * If we need to start a WAL receiver, try to do that now
3376 *
3377 * Note: if a walreceiver process is already running, it might seem that
3378 * we should clear WalReceiverRequested. However, there's a race
3379 * condition if the walreceiver terminates and the startup process
3380 * immediately requests a new one: it's quite possible to get the signal
3381 * for the request before reaping the dead walreceiver process. Better to
3382 * risk launching an extra walreceiver than to miss launching one we need.
3383 * (The walreceiver code has logic to recognize that it should go away if
3384 * not needed.)
3385 */
3387 {
3388 if (WalReceiverPMChild == NULL &&
3390 pmState == PM_HOT_STANDBY) &&
3392 {
3394 if (WalReceiverPMChild != 0)
3395 WalReceiverRequested = false;
3396 /* else leave the flag set, so we'll try again later */
3397 }
3398 }
3399
3400 /* If we need to start a WAL summarizer, try to do that now */
3401 if (summarize_wal && WalSummarizerPMChild == NULL &&
3402 (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
3405
3406 /* Get other worker processes running, if needed */
3409}
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3314
bool IsBinaryUpgrade
Definition: globals.c:121
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:367
@ B_WAL_WRITER
Definition: miscadmin.h:368
@ B_WAL_RECEIVER
Definition: miscadmin.h:366
@ B_CHECKPOINTER
Definition: miscadmin.h:363
@ B_BG_WRITER
Definition: miscadmin.h:362
@ B_ARCHIVER
Definition: miscadmin.h:361
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:344
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:348
bool PgArchCanRestart(void)
Definition: pgarch.c:196
#define SmartShutdown
Definition: postmaster.c:284
static PMChild * PgArchPMChild
Definition: postmaster.c:267
static void maybe_start_bgworkers(void)
Definition: postmaster.c:4242
static void StartSysLogger(void)
Definition: postmaster.c:4017
static PMChild * AutoVacLauncherPMChild
Definition: postmaster.c:266
static PMChild * BgWriterPMChild
Definition: postmaster.c:261
static PMChild * StartChildProcess(BackendType type)
Definition: postmaster.c:3971
static bool start_autovac_launcher
Definition: postmaster.c:378
static PMChild * WalReceiverPMChild
Definition: postmaster.c:264
static PMChild * WalWriterPMChild
Definition: postmaster.c:263
static PMChild * WalSummarizerPMChild
Definition: postmaster.c:265
static void maybe_adjust_io_workers(void)
Definition: postmaster.c:4381
static PMChild * SysLoggerPMChild
Definition: postmaster.c:268
static bool WalReceiverRequested
Definition: postmaster.c:384
static PMChild * CheckpointerPMChild
Definition: postmaster.c:262
static PMChild * SlotSyncWorkerPMChild
Definition: postmaster.c:269
bool sync_replication_slots
Definition: slotsync.c:106
bool SlotSyncWorkerCanRestart(void)
Definition: slotsync.c:1649
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1057
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 2828 of file postmaster.c.

2829{
2830 /*
2831 * size of activity_buffer is arbitrary, but set equal to default
2832 * track_activity_query_size
2833 */
2834 char activity_buffer[1024];
2835 const char *activity = NULL;
2836
2837 if (!EXIT_STATUS_0(exitstatus))
2839 activity_buffer,
2840 sizeof(activity_buffer));
2841
2842 if (WIFEXITED(exitstatus))
2843 ereport(lev,
2844
2845 /*------
2846 translator: %s is a noun phrase describing a child process, such as
2847 "server process" */
2848 (errmsg("%s (PID %d) exited with exit code %d",
2849 procname, pid, WEXITSTATUS(exitstatus)),
2850 activity ? errdetail("Failed process was running: %s", activity) : 0));
2851 else if (WIFSIGNALED(exitstatus))
2852 {
2853#if defined(WIN32)
2854 ereport(lev,
2855
2856 /*------
2857 translator: %s is a noun phrase describing a child process, such as
2858 "server process" */
2859 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2860 procname, pid, WTERMSIG(exitstatus)),
2861 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2862 activity ? errdetail("Failed process was running: %s", activity) : 0));
2863#else
2864 ereport(lev,
2865
2866 /*------
2867 translator: %s is a noun phrase describing a child process, such as
2868 "server process" */
2869 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2870 procname, pid, WTERMSIG(exitstatus),
2871 pg_strsignal(WTERMSIG(exitstatus))),
2872 activity ? errdetail("Failed process was running: %s", activity) : 0));
2873#endif
2874 }
2875 else
2876 ereport(lev,
2877
2878 /*------
2879 translator: %s is a noun phrase describing a child process, such as
2880 "server process" */
2881 (errmsg("%s (PID %d) exited with unrecognized status %d",
2882 procname, pid, exitstatus),
2883 activity ? errdetail("Failed process was running: %s", activity) : 0));
2884}
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
int errdetail(const char *fmt,...)
Definition: elog.c:1216
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 4381 of file postmaster.c.

4382{
4383 if (!pgaio_workers_enabled())
4384 return;
4385
4386 /*
4387 * If we're in final shutting down state, then we're just waiting for all
4388 * processes to exit.
4389 */
4391 return;
4392
4393 /* Don't start new workers during an immediate shutdown either. */
4395 return;
4396
4397 /*
4398 * Don't start new workers if we're in the shutdown phase of a crash
4399 * restart. But we *do* need to start if we're already starting up again.
4400 */
4402 return;
4403
4405
4406 /* Not enough running? */
4407 while (io_worker_count < io_workers)
4408 {
4409 PMChild *child;
4410 int i;
4411
4412 /* find unused entry in io_worker_children array */
4413 for (i = 0; i < MAX_IO_WORKERS; ++i)
4414 {
4415 if (io_worker_children[i] == NULL)
4416 break;
4417 }
4418 if (i == MAX_IO_WORKERS)
4419 elog(ERROR, "could not find a free IO worker slot");
4420
4421 /* Try to launch one. */
4423 if (child != NULL)
4424 {
4425 io_worker_children[i] = child;
4427 }
4428 else
4429 break; /* try again next time */
4430 }
4431
4432 /* Too many running? */
4434 {
4435 /* ask the IO worker in the highest slot to exit */
4436 for (int i = MAX_IO_WORKERS - 1; i >= 0; --i)
4437 {
4438 if (io_worker_children[i] != NULL)
4439 {
4441 break;
4442 }
4443 }
4444 }
4445}
bool pgaio_workers_enabled(void)
int io_workers
Definition: method_worker.c:94
@ B_IO_WORKER
Definition: miscadmin.h:364
static PMChild * io_worker_children[MAX_IO_WORKERS]
Definition: postmaster.c:412
static int io_worker_count
Definition: postmaster.c:411
#define MAX_IO_WORKERS
Definition: proc.h:462
#define kill(pid, sig)
Definition: win32_port.h:493
#define SIGUSR2
Definition: win32_port.h:171

References Assert(), B_IO_WORKER, elog, ERROR, FatalError, i, 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 4356 of file postmaster.c.

4357{
4358 for (int i = 0; i < MAX_IO_WORKERS; ++i)
4359 {
4360 if (io_worker_children[i] &&
4361 io_worker_children[i]->pid == pid)
4362 {
4364
4366 io_worker_children[i] = NULL;
4367 return true;
4368 }
4369 }
4370 return false;
4371}

References i, 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 4242 of file postmaster.c.

4243{
4244#define MAX_BGWORKERS_TO_LAUNCH 100
4245 int num_launched = 0;
4246 TimestampTz now = 0;
4247 dlist_mutable_iter iter;
4248
4249 /*
4250 * During crash recovery, we have no need to be called until the state
4251 * transition out of recovery.
4252 */
4253 if (FatalError)
4254 {
4255 StartWorkerNeeded = false;
4256 HaveCrashedWorker = false;
4257 return;
4258 }
4259
4260 /* Don't need to be called again unless we find a reason for it below */
4261 StartWorkerNeeded = false;
4262 HaveCrashedWorker = false;
4263
4265 {
4267
4268 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
4269
4270 /* ignore if already running */
4271 if (rw->rw_pid != 0)
4272 continue;
4273
4274 /* if marked for death, clean up and remove from list */
4275 if (rw->rw_terminate)
4276 {
4278 continue;
4279 }
4280
4281 /*
4282 * If this worker has crashed previously, maybe it needs to be
4283 * restarted (unless on registration it specified it doesn't want to
4284 * be restarted at all). Check how long ago did a crash last happen.
4285 * If the last crash is too recent, don't start it right away; let it
4286 * be restarted once enough time has passed.
4287 */
4288 if (rw->rw_crashed_at != 0)
4289 {
4291 {
4292 int notify_pid;
4293
4294 notify_pid = rw->rw_worker.bgw_notify_pid;
4295
4297
4298 /* Report worker is gone now. */
4299 if (notify_pid != 0)
4300 kill(notify_pid, SIGUSR1);
4301
4302 continue;
4303 }
4304
4305 /* read system time only when needed */
4306 if (now == 0)
4308
4310 rw->rw_worker.bgw_restart_time * 1000))
4311 {
4312 /* Set flag to remember that we have workers to start later */
4313 HaveCrashedWorker = true;
4314 continue;
4315 }
4316 }
4317
4319 {
4320 /* reset crash time before trying to start worker */
4321 rw->rw_crashed_at = 0;
4322
4323 /*
4324 * Try to start the worker.
4325 *
4326 * On failure, give up processing workers for now, but set
4327 * StartWorkerNeeded so we'll come back here on the next iteration
4328 * of ServerLoop to try again. (We don't want to wait, because
4329 * there might be additional ready-to-run workers.) We could set
4330 * HaveCrashedWorker as well, since this worker is now marked
4331 * crashed, but there's no need because the next run of this
4332 * function will do that.
4333 */
4334 if (!StartBackgroundWorker(rw))
4335 {
4336 StartWorkerNeeded = true;
4337 return;
4338 }
4339
4340 /*
4341 * If we've launched as many workers as allowed, quit, but have
4342 * ServerLoop call us again to look for additional ready-to-run
4343 * workers. There might not be any, but we'll find out the next
4344 * time we run.
4345 */
4346 if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
4347 {
4348 StartWorkerNeeded = true;
4349 return;
4350 }
4351 }
4352 }
4353}
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1781
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
static bool StartBackgroundWorker(RegisteredBgWorker *rw)
Definition: postmaster.c:4134
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:4195
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 3419 of file postmaster.c.

3420{
3421#define PM_TOSTR_CASE(sym) case sym: return #sym
3422 switch (signal)
3423 {
3427 PM_TOSTR_CASE(SIGINT);
3430 PM_TOSTR_CASE(SIGTERM);
3433 default:
3434 /* all signals sent by postmaster should be listed here */
3435 Assert(false);
3436 return "(unknown)";
3437 }
3438#undef PM_TOSTR_CASE
3439
3440 return ""; /* silence compiler */
3441}
#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 493 of file postmaster.c.

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

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4454 of file postmaster.c.

4455{
4456 dlist_iter iter;
4457 PMChild *bp;
4458
4460 {
4461 bp = dlist_container(PMChild, elem, iter.cur);
4462 if (bp->pid == pid)
4463 {
4464 bp->bgworker_notify = true;
4465 return true;
4466 }
4467 }
4468 return false;
4469}

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 2894 of file postmaster.c.

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

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 2243 of file postmaster.c.

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

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 3699 of file postmaster.c.

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

2006{
2008
2010 (errmsg_internal("postmaster received reload request signal")));
2011
2012 if (Shutdown <= SmartShutdown)
2013 {
2014 ereport(LOG,
2015 (errmsg("received SIGHUP, reloading configuration files")));
2018
2019 /* Reload authentication config files too */
2020 if (!load_hba())
2021 ereport(LOG,
2022 /* translator: %s is a configuration file */
2023 (errmsg("%s was not reloaded", HbaFileName)));
2024
2025 if (!load_ident())
2026 ereport(LOG,
2027 (errmsg("%s was not reloaded", IdentFileName)));
2028
2029#ifdef USE_SSL
2030 /* Reload SSL configuration as well */
2031 if (EnableSSL)
2032 {
2033 if (secure_initialize(false) == 0)
2034 LoadedSSL = true;
2035 else
2036 ereport(LOG,
2037 (errmsg("SSL configuration was not reloaded")));
2038 }
2039 else
2040 {
2042 LoadedSSL = false;
2043 }
2044#endif
2045
2046#ifdef EXEC_BACKEND
2047 /* Update the starting-point file for future children */
2048 write_nondefault_variables(PGC_SIGHUP);
2049#endif
2050 }
2051}
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:558

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 2082 of file postmaster.c.

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

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 3637 of file postmaster.c.

3638{
3639 char buffer[1000];
3640 int rc;
3641
3642 /* Format the error message packet (always V2 protocol) */
3643 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3644 _("could not fork new process for connection: "),
3645 strerror(errnum));
3646
3647 /* Set port to non-blocking. Don't do send() if this fails */
3648 if (!pg_set_noblock(client_sock->sock))
3649 return;
3650
3651 /* We'll retry after EINTR, but ignore all other failures */
3652 do
3653 {
3654 rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
3655 } while (rc < 0 && errno == EINTR);
3656}
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 1663 of file postmaster.c.

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

3461{
3462 pid_t pid = pmchild->pid;
3463
3465 (errmsg_internal("sending signal %d/%s to %s process with pid %d",
3466 signal, pm_signame(signal),
3468 (int) pmchild->pid)));
3469
3470 if (kill(pid, signal) < 0)
3471 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3472#ifdef HAVE_SETSID
3473 switch (signal)
3474 {
3475 case SIGINT:
3476 case SIGTERM:
3477 case SIGQUIT:
3478 case SIGKILL:
3479 case SIGABRT:
3480 if (kill(-pid, signal) < 0)
3481 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3482 break;
3483 default:
3484 break;
3485 }
3486#endif
3487}
static const char * pm_signame(int signal)
Definition: postmaster.c:3419

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 3493 of file postmaster.c.

3494{
3495 dlist_iter iter;
3496 bool signaled = false;
3497
3499 {
3500 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3501
3502 /*
3503 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3504 * if any B_BACKEND backends have recently announced that they are
3505 * actually WAL senders.
3506 */
3507 if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3508 bp->bkend_type == B_BACKEND)
3509 {
3512 }
3513
3514 if (!btmask_contains(targetMask, bp->bkend_type))
3515 continue;
3516
3517 signal_child(bp, signal);
3518 signaled = true;
3519 }
3520 return signaled;
3521}

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 4042 of file postmaster.c.

4043{
4044 PMChild *bn;
4045
4046 /*
4047 * If not in condition to run a process, don't try, but handle it like a
4048 * fork failure. This does not normally happen, since the signal is only
4049 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4050 * we have to check to avoid race-condition problems during DB state
4051 * changes.
4052 */
4054 {
4056 if (bn)
4057 {
4058 bn->bgworker_notify = false;
4059 bn->rw = NULL;
4060 return;
4061 }
4062 else
4063 {
4064 /*
4065 * fork failed, fall through to report -- actual error message was
4066 * logged by StartChildProcess
4067 */
4068 }
4069 }
4070
4071 /*
4072 * Report the failure to the launcher, if it's running. (If it's not, we
4073 * might not even be connected to shared memory, so don't try to call
4074 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4075 * responds to the condition, but we don't do that here, instead waiting
4076 * for ServerLoop to do it. This way we avoid a ping-pong signaling in
4077 * quick succession between the autovac launcher and postmaster in case
4078 * things get ugly.
4079 */
4080 if (AutoVacLauncherPMChild != NULL)
4081 {
4084 }
4085}
void AutoVacWorkerFailed(void)
Definition: autovacuum.c:1368

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 4134 of file postmaster.c.

4135{
4136 PMChild *bn;
4137 pid_t worker_pid;
4138
4139 Assert(rw->rw_pid == 0);
4140
4141 /*
4142 * Allocate and assign the child slot. Note we must do this before
4143 * forking, so that we can handle failures (out of memory or child-process
4144 * slots) cleanly.
4145 *
4146 * Treat failure as though the worker had crashed. That way, the
4147 * postmaster will wait a bit before attempting to start it again; if we
4148 * tried again right away, most likely we'd find ourselves hitting the
4149 * same resource-exhaustion condition.
4150 */
4152 if (bn == NULL)
4153 {
4154 ereport(LOG,
4155 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
4156 errmsg("no slot available for new background worker process")));
4158 return false;
4159 }
4160 bn->rw = rw;
4161 bn->bkend_type = B_BG_WORKER;
4162 bn->bgworker_notify = false;
4163
4165 (errmsg_internal("starting background worker process \"%s\"",
4166 rw->rw_worker.bgw_name)));
4167
4169 &rw->rw_worker, sizeof(BackgroundWorker), NULL);
4170 if (worker_pid == -1)
4171 {
4172 /* in postmaster, fork failed ... */
4173 ereport(LOG,
4174 (errmsg("could not fork background worker process: %m")));
4175 /* undo what AssignPostmasterChildSlot did */
4177
4178 /* mark entry as crashed, so we'll try again later */
4180 return false;
4181 }
4182
4183 /* in postmaster, fork successful ... */
4184 rw->rw_pid = worker_pid;
4185 bn->pid = rw->rw_pid;
4187 return true;
4188}
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:464
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 3971 of file postmaster.c.

3972{
3973 PMChild *pmchild;
3974 pid_t pid;
3975
3977 if (!pmchild)
3978 {
3979 if (type == B_AUTOVAC_WORKER)
3980 ereport(LOG,
3981 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
3982 errmsg("no slot available for new autovacuum worker process")));
3983 else
3984 {
3985 /* shouldn't happen because we allocate enough slots */
3986 elog(LOG, "no postmaster child slot available for aux process");
3987 }
3988 return NULL;
3989 }
3990
3991 pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
3992 if (pid < 0)
3993 {
3994 /* in parent, fork failed */
3996 ereport(LOG,
3997 (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
3998
3999 /*
4000 * fork failure is fatal during startup, but there's no need to choke
4001 * immediately if starting other child types fails.
4002 */
4003 if (type == B_STARTUP)
4004 ExitPostmaster(1);
4005 return NULL;
4006 }
4007
4008 /* in parent, successful fork */
4009 pmchild->pid = pid;
4010 return pmchild;
4011}
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 4017 of file postmaster.c.

4018{
4019 Assert(SysLoggerPMChild == NULL);
4020
4022 if (!SysLoggerPMChild)
4023 elog(PANIC, "no postmaster child slot available for syslogger");
4025 if (SysLoggerPMChild->pid == 0)
4026 {
4028 SysLoggerPMChild = NULL;
4029 }
4030}
#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 3528 of file postmaster.c.

3529{
3531 if (StartupPMChild != NULL)
3532 {
3533 if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
3535 }
3536}

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 1452 of file postmaster.c.

1453{
1455 unlink(external_pid_file);
1456}

References external_pid_file.

Referenced by PostmasterMain().

◆ UpdatePMState()

static void UpdatePMState ( PMState  newState)
static

Definition at line 3280 of file postmaster.c.

3281{
3282 elog(DEBUG1, "updating PMState from %s to %s",
3283 pmstate_name(pmState), pmstate_name(newState));
3284 pmState = newState;
3285}
static const char * pmstate_name(PMState state)
Definition: postmaster.c:3250

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 241 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 381 of file postmaster.c.

Referenced by ServerLoop(), and StartAutovacuumWorker().

◆ BgWriterPMChild

PMChild * BgWriterPMChild = NULL
static

◆ bonjour_name

char* bonjour_name

Definition at line 246 of file postmaster.c.

Referenced by PostmasterMain().

◆ BTYPE_MASK_ALL

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

Definition at line 145 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 146 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ CheckpointerPMChild

PMChild * CheckpointerPMChild = NULL
static

◆ ClientAuthInProgress

◆ connsAllowed

◆ enable_bonjour

bool enable_bonjour = false

Definition at line 245 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 412 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 209 of file postmaster.c.

Referenced by PostmasterMain().

◆ ListenSockets

pgsocket* ListenSockets = NULL
static

◆ log_hostname

bool log_hostname

Definition at line 243 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 392 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 395 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 396 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 391 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 399 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 203 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

int PreAuthDelay = 0

Definition at line 240 of file postmaster.c.

Referenced by BackendInitialize().

◆ ReachedNormalRunning

bool ReachedNormalRunning = false
static

Definition at line 370 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 248 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ ReservedConnections

int ReservedConnections

Definition at line 230 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

bool restart_after_crash = true

Definition at line 247 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

bool send_abort_for_crash = false

Definition at line 256 of file postmaster.c.

Referenced by HandleFatalError().

◆ send_abort_for_kill

bool send_abort_for_kill = false

Definition at line 257 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 378 of file postmaster.c.

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ StartupPMChild

PMChild* StartupPMChild = NULL
static

◆ StartupStatus

◆ StartWorkerNeeded

◆ SuperuserReservedConnections

int SuperuserReservedConnections

Definition at line 229 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ SysLoggerPMChild

PMChild * SysLoggerPMChild = NULL
static

◆ Unix_socket_directories

char* Unix_socket_directories

Definition at line 206 of file postmaster.c.

Referenced by PostmasterMain().

◆ WalReceiverPMChild

PMChild * WalReceiverPMChild = NULL
static

◆ WalReceiverRequested

bool WalReceiverRequested = false
static

Definition at line 384 of file postmaster.c.

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ WalSummarizerPMChild

PMChild * WalSummarizerPMChild = NULL
static

◆ WalWriterPMChild

PMChild * WalWriterPMChild = NULL
static