PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 "pgstat.h"
#include "port/pg_bswap.h"
#include "port/pg_getopt_ctx.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 "storage/shmem_internal.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_start_io_workers (void)
 
static TimestampTz maybe_start_io_workers_scheduled_at (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 charpmstate_name (PMState state)
 
static const charpm_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
 
charUnix_socket_directories
 
charListenAddresses
 
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
 
charbonjour_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 TimestampTz io_worker_launch_next_time = 0
 
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, \
)
#define lengthof(array)
Definition c.h:873
BackendType
Definition miscadmin.h:350
static BackendTypeMask btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
Definition postmaster.c:158
static int fb(int x)

Definition at line 165 of file postmaster.c.

167 {__VA_ARGS__})), \
169 )

◆ btmask_all_except

#define btmask_all_except (   ...)
Value:
)
static BackendTypeMask btmask_all_except_n(int nargs, BackendType *t)
Definition postmaster.c:179

Definition at line 188 of file postmaster.c.

190 {__VA_ARGS__})), \
192 )

◆ EXIT_STATUS_0

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

Definition at line 478 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 479 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 480 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 286 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 287 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 234 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 285 of file postmaster.c.

Enumeration Type Documentation

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 273 of file postmaster.c.

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

Function Documentation

◆ BackendStartup()

static int BackendStartup ( ClientSocket client_sock)
static

Definition at line 3576 of file postmaster.c.

3577{
3578 PMChild *bn = NULL;
3579 pid_t pid;
3581 CAC_state cac;
3582
3583 /*
3584 * Capture time that Postmaster got a socket from accept (for logging
3585 * connection establishment and setup total duration).
3586 */
3588
3589 /*
3590 * Allocate and assign the child slot. Note we must do this before
3591 * forking, so that we can handle failures (out of memory or child-process
3592 * slots) cleanly.
3593 */
3595 if (cac == CAC_OK)
3596 {
3597 /* Can change later to B_WAL_SENDER */
3599 if (!bn)
3600 {
3601 /*
3602 * Too many regular child processes; launch a dead-end child
3603 * process instead.
3604 */
3605 cac = CAC_TOOMANY;
3606 }
3607 }
3608 if (!bn)
3609 {
3611 if (!bn)
3612 {
3613 ereport(LOG,
3615 errmsg("out of memory")));
3616 return STATUS_ERROR;
3617 }
3618 }
3619
3620 /* Pass down canAcceptConnections state */
3621 startup_data.canAcceptConnections = cac;
3622 bn->rw = NULL;
3623
3624 /* Hasn't asked to be notified about any bgworkers yet */
3625 bn->bgworker_notify = false;
3626
3627 pid = postmaster_child_launch(bn->bkend_type, bn->child_slot,
3628 &startup_data, sizeof(startup_data),
3629 client_sock);
3630 if (pid < 0)
3631 {
3632 /* in parent, fork failed */
3633 int save_errno = errno;
3634
3636 errno = save_errno;
3637 ereport(LOG,
3638 (errmsg("could not fork new process for connection: %m")));
3640 return STATUS_ERROR;
3641 }
3642
3643 /* in parent, successful fork */
3645 (errmsg_internal("forked new %s, pid=%d socket=%d",
3646 GetBackendTypeDesc(bn->bkend_type),
3647 (int) pid, (int) client_sock->sock)));
3648
3649 /*
3650 * Everything's been successful, it's safe to add this backend to our list
3651 * of backends.
3652 */
3653 bn->pid = pid;
3654 return STATUS_OK;
3655}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
CAC_state
@ CAC_TOOMANY
@ CAC_OK
#define STATUS_OK
Definition c.h:1258
#define STATUS_ERROR
Definition c.h:1259
int errcode(int sqlerrcode)
Definition elog.c:875
#define LOG
Definition elog.h:32
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG2
Definition elog.h:30
#define ereport(elevel,...)
Definition elog.h:152
pid_t postmaster_child_launch(BackendType child_type, int child_slot, void *startup_data, size_t startup_data_len, const ClientSocket *client_sock)
@ B_BACKEND
Definition miscadmin.h:354
const char * GetBackendTypeDesc(BackendType backendType)
Definition miscinit.c:264
static char * errmsg
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)
static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
TimestampTz socket_created

References AllocDeadEndChild(), AssignPostmasterChildSlot(), B_BACKEND, CAC_OK, CAC_TOOMANY, canAcceptConnections(), DEBUG2, ereport, errcode(), errmsg, errmsg_internal(), fb(), GetBackendTypeDesc(), GetCurrentTimestamp(), LOG, postmaster_child_launch(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), 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 4234 of file postmaster.c.

4235{
4236 switch (pmState)
4237 {
4238 case PM_NO_CHILDREN:
4240 case PM_WAIT_DEAD_END:
4243 case PM_WAIT_IO_WORKERS:
4244 case PM_WAIT_BACKENDS:
4245 case PM_STOP_BACKENDS:
4246 break;
4247
4248 case PM_RUN:
4250 return true;
4252
4253 case PM_HOT_STANDBY:
4255 return true;
4257
4258 case PM_RECOVERY:
4259 case PM_STARTUP:
4260 case PM_INIT:
4262 return true;
4263 }
4264
4265 return false;
4266}
@ BgWorkerStart_RecoveryFinished
Definition bgworker.h:88
@ BgWorkerStart_ConsistentState
Definition bgworker.h:87
@ BgWorkerStart_PostmasterStart
Definition bgworker.h:86
#define pg_fallthrough
Definition c.h:161
static time_t start_time
Definition pg_ctl.c:96
static PMState pmState
Definition postmaster.c:355

References BgWorkerStart_ConsistentState, BgWorkerStart_PostmasterStart, BgWorkerStart_RecoveryFinished, pg_fallthrough, 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 150 of file postmaster.c.

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

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

159{
160 for (int i = 0; i < nargs; i++)
161 mask.mask |= 1 << t[i];
162 return mask;
163}
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 179 of file postmaster.c.

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

References btmask_del(), BTYPE_MASK_ALL, and i.

◆ btmask_contains()

static bool btmask_contains ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 195 of file postmaster.c.

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

References BackendTypeMask::mask.

Referenced by CountChildren(), and SignalChildren().

◆ btmask_del()

static BackendTypeMask btmask_del ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 172 of file postmaster.c.

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

References BackendTypeMask::mask.

Referenced by btmask_all_except_n().

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( BackendType  backend_type)
static

Definition at line 1837 of file postmaster.c.

1838{
1840
1842
1843 /*
1844 * Can't start backends when in startup/shutdown/inconsistent recovery
1845 * state. We treat autovac workers the same as user backends for this
1846 * purpose.
1847 */
1848 if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
1849 {
1850 if (Shutdown > NoShutdown)
1851 return CAC_SHUTDOWN; /* shutdown is pending */
1852 else if (!FatalError && pmState == PM_STARTUP)
1853 return CAC_STARTUP; /* normal startup */
1854 else if (!FatalError && pmState == PM_RECOVERY)
1855 return CAC_NOTHOTSTANDBY; /* not yet ready for hot standby */
1856 else
1857 return CAC_RECOVERY; /* else must be crash recovery */
1858 }
1859
1860 /*
1861 * "Smart shutdown" restrictions are applied only to normal connections,
1862 * not to autovac workers.
1863 */
1865 return CAC_SHUTDOWN; /* shutdown is pending */
1866
1867 return result;
1868}
@ CAC_RECOVERY
@ CAC_NOTHOTSTANDBY
@ CAC_STARTUP
@ CAC_SHUTDOWN
#define Assert(condition)
Definition c.h:943
uint32 result
@ B_AUTOVAC_WORKER
Definition miscadmin.h:357
static bool connsAllowed
Definition postmaster.c:363
static int Shutdown
Definition postmaster.c:289
#define NoShutdown
Definition postmaster.c:284
static bool FatalError
Definition postmaster.c:291

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

Referenced by BackendStartup(), and StartAutovacuumWorker().

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1530 of file postmaster.c.

1531{
1532 char path[MAXPGPATH];
1533 FILE *fp;
1534
1535 snprintf(path, sizeof(path), "%s/%s", DataDir, XLOG_CONTROL_FILE);
1536
1537 fp = AllocateFile(path, PG_BINARY_R);
1538 if (fp == NULL)
1539 {
1540 write_stderr("%s: could not find the database system\n"
1541 "Expected to find it in the directory \"%s\",\n"
1542 "but could not open file \"%s\": %m\n",
1543 progname, DataDir, path);
1544 ExitPostmaster(2);
1545 }
1546 FreeFile(fp);
1547}
#define write_stderr(str)
Definition parallel.c:186
#define PG_BINARY_R
Definition c.h:1376
int FreeFile(FILE *file)
Definition fd.c:2827
FILE * AllocateFile(const char *name, const char *mode)
Definition fd.c:2628
char * DataDir
Definition globals.c:73
const char * progname
Definition main.c:44
#define MAXPGPATH
#define snprintf
Definition port.h:260
static pg_noreturn void ExitPostmaster(int status)
#define XLOG_CONTROL_FILE

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

Referenced by digestControlFile(), and PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( PMChild bp,
int  exitstatus 
)
static

Definition at line 2588 of file postmaster.c.

2590{
2591 char namebuf[MAXPGPATH];
2592 const char *procname;
2593 bool crashed = false;
2594 bool logged = false;
2595 pid_t bp_pid;
2596 bool bp_bgworker_notify;
2599
2600 /* Construct a process name for the log message */
2601 if (bp->bkend_type == B_BG_WORKER)
2602 {
2603 snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
2604 bp->rw->rw_worker.bgw_type);
2605 procname = namebuf;
2606 }
2607 else
2608 procname = _(GetBackendTypeDesc(bp->bkend_type));
2609
2610 /*
2611 * If a backend dies in an ugly way then we must signal all other backends
2612 * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2613 * assume everything is all right and proceed to remove the backend from
2614 * the active child list.
2615 */
2617 crashed = true;
2618
2619#ifdef WIN32
2620
2621 /*
2622 * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2623 * since that sometimes happens under load when the process fails to start
2624 * properly (long before it starts using shared memory). Microsoft reports
2625 * it is related to mutex failure:
2626 * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2627 */
2629 {
2630 LogChildExit(LOG, procname, bp->pid, exitstatus);
2631 logged = true;
2632 crashed = false;
2633 }
2634#endif
2635
2636 /*
2637 * Release the PMChild entry.
2638 *
2639 * If the process attached to shared memory, this also checks that it
2640 * detached cleanly.
2641 */
2642 bp_pid = bp->pid;
2643 bp_bgworker_notify = bp->bgworker_notify;
2644 bp_bkend_type = bp->bkend_type;
2645 rw = bp->rw;
2647 {
2648 /*
2649 * Uh-oh, the child failed to clean itself up. Treat as a crash after
2650 * all.
2651 */
2652 crashed = true;
2653 }
2654 bp = NULL;
2655
2656 /*
2657 * In a crash case, exit immediately without resetting background worker
2658 * state. However, if restart_after_crash is enabled, the background
2659 * worker state (e.g., rw_pid) still needs be reset so the worker can
2660 * restart after crash recovery. This reset is handled in
2661 * ResetBackgroundWorkerCrashTimes(), not here.
2662 */
2663 if (crashed)
2664 {
2666 return;
2667 }
2668
2669 /*
2670 * This backend may have been slated to receive SIGUSR1 when some
2671 * background worker started or stopped. Cancel those notifications, as
2672 * we don't want to signal PIDs that are not PostgreSQL backends. This
2673 * gets skipped in the (probably very common) case where the backend has
2674 * never requested any such notifications.
2675 */
2678
2679 /*
2680 * If it was an autovacuum worker, wake up the launcher so that it can
2681 * immediately launch a new worker or rebalance to cost limit setting of
2682 * the remaining workers.
2683 */
2686
2687 /*
2688 * If it was a background worker, also update its RegisteredBgWorker
2689 * entry.
2690 */
2692 {
2694 {
2695 /* Record timestamp, so we know when to restart the worker. */
2697 }
2698 else
2699 {
2700 /* Zero exit status means terminate */
2701 rw->rw_crashed_at = 0;
2702 rw->rw_terminate = true;
2703 }
2704
2705 rw->rw_pid = 0;
2706 ReportBackgroundWorkerExit(rw); /* report child death */
2707
2708 if (!logged)
2709 {
2711 procname, bp_pid, exitstatus);
2712 logged = true;
2713 }
2714
2715 /* have it be restarted */
2716 HaveCrashedWorker = true;
2717 }
2718
2719 if (!logged)
2720 LogChildExit(DEBUG2, procname, bp_pid, exitstatus);
2721}
void ReportBackgroundWorkerExit(RegisteredBgWorker *rw)
Definition bgworker.c:509
void BackgroundWorkerStopNotifications(pid_t pid)
Definition bgworker.c:540
#define _(x)
Definition elog.c:96
#define DEBUG1
Definition elog.h:31
@ B_BG_WORKER
Definition miscadmin.h:358
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
#define EXIT_STATUS_1(st)
Definition postmaster.c:479
#define EXIT_STATUS_0(st)
Definition postmaster.c:478
static bool HaveCrashedWorker
Definition postmaster.c:390
static PMChild * AutoVacLauncherPMChild
Definition postmaster.c:267
static void signal_child(PMChild *pmchild, int signal)
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
#define SIGUSR2
Definition win32_port.h:171

References _, AutoVacLauncherPMChild, B_AUTOVAC_WORKER, B_BG_WORKER, BackgroundWorkerStopNotifications(), DEBUG1, DEBUG2, EXIT_STATUS_0, EXIT_STATUS_1, fb(), GetBackendTypeDesc(), GetCurrentTimestamp(), HandleChildCrash(), HaveCrashedWorker, LOG, LogChildExit(), MAXPGPATH, ReleasePostmasterChildSlot(), ReportBackgroundWorkerExit(), RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, signal_child(), SIGUSR2, and snprintf.

Referenced by process_pm_child_exit().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1881 of file postmaster.c.

1882{
1883 /* Release resources held by the postmaster's WaitEventSet. */
1884 if (pm_wait_set)
1885 {
1887 pm_wait_set = NULL;
1888 }
1889
1890#ifndef WIN32
1891
1892 /*
1893 * Close the write end of postmaster death watch pipe. It's important to
1894 * do this as early as possible, so that if postmaster dies, others won't
1895 * think that it's still running because we're holding the pipe open.
1896 */
1898 ereport(FATAL,
1900 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1902 /* Notify fd.c that we released one pipe FD. */
1904#endif
1905
1906 /*
1907 * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1908 * so we don't call ReleaseExternalFD() here.
1909 *
1910 * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1911 * EXEC_BACKEND mode.
1912 */
1913#ifndef EXEC_BACKEND
1914 if (ListenSockets)
1915 {
1916 for (int i = 0; i < NumListenSockets; i++)
1917 {
1918 if (closesocket(ListenSockets[i]) != 0)
1919 elog(LOG, "could not close listen socket: %m");
1920 }
1922 }
1923 NumListenSockets = 0;
1925#endif
1926
1927 /*
1928 * If using syslogger, close the read side of the pipe. We don't bother
1929 * tracking this in fd.c, either.
1930 */
1931 if (!am_syslogger)
1932 {
1933#ifndef WIN32
1934 if (syslogPipe[0] >= 0)
1935 close(syslogPipe[0]);
1936 syslogPipe[0] = -1;
1937#else
1938 if (syslogPipe[0])
1940 syslogPipe[0] = 0;
1941#endif
1942 }
1943
1944#ifdef USE_BONJOUR
1945 /* If using Bonjour, close the connection to the mDNS daemon */
1946 if (bonjour_sdref)
1948#endif
1949}
int errcode_for_file_access(void)
Definition elog.c:898
#define FATAL
Definition elog.h:42
#define elog(elevel,...)
Definition elog.h:228
void ReleaseExternalFD(void)
Definition fd.c:1225
#define close(a)
Definition win32.h:12
void pfree(void *pointer)
Definition mcxt.c:1616
#define closesocket
Definition port.h:397
static pgsocket * ListenSockets
Definition postmaster.c:236
static int NumListenSockets
Definition postmaster.c:235
int postmaster_alive_fds[2]
Definition postmaster.c:487
static WaitEventSet * pm_wait_set
Definition postmaster.c:401
#define POSTMASTER_FD_OWN
Definition postmaster.h:84
int syslogPipe[2]
Definition syslogger.c:115
void FreeWaitEventSetAfterFork(WaitEventSet *set)

References close, closesocket, elog, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, fb(), 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 1430 of file postmaster.c.

1431{
1432 int i;
1433
1434 /*
1435 * First, explicitly close all the socket FDs. We used to just let this
1436 * happen implicitly at postmaster exit, but it's better to close them
1437 * before we remove the postmaster.pid lockfile; otherwise there's a race
1438 * condition if a new postmaster wants to re-use the TCP port number.
1439 */
1440 for (i = 0; i < NumListenSockets; i++)
1441 {
1442 if (closesocket(ListenSockets[i]) != 0)
1443 elog(LOG, "could not close listen socket: %m");
1444 }
1445 NumListenSockets = 0;
1446
1447 /*
1448 * Next, remove any filesystem entries for Unix sockets. To avoid race
1449 * conditions against incoming postmasters, this must happen after closing
1450 * the sockets and before removing lock files.
1451 */
1453
1454 /*
1455 * We don't do anything about socket lock files here; those will be
1456 * removed in a later on_proc_exit callback.
1457 */
1458}
void RemoveSocketFiles(void)
Definition pqcomm.c:849

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

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1655 of file postmaster.c.

1656{
1657 if (pm_wait_set)
1659 pm_wait_set = NULL;
1660
1664 NULL);
1665
1667 {
1668 for (int i = 0; i < NumListenSockets; i++)
1670 NULL, NULL);
1671 }
1672}
struct Latch * MyLatch
Definition globals.c:65
#define PGINVALID_SOCKET
Definition port.h:31
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
void FreeWaitEventSet(WaitEventSet *set)
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
#define WL_SOCKET_ACCEPT
#define WL_LATCH_SET

References AddWaitEventToSet(), CreateWaitEventSet(), fb(), 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 3966 of file postmaster.c.

3967{
3968 dlist_iter iter;
3969 int cnt = 0;
3970
3972 {
3973 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3974
3975 /*
3976 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3977 * if any B_BACKEND backends have recently announced that they are
3978 * actually WAL senders.
3979 */
3981 bp->bkend_type == B_BACKEND)
3982 {
3983 if (IsPostmasterChildWalSender(bp->child_slot))
3984 bp->bkend_type = B_WAL_SENDER;
3985 }
3986
3987 if (!btmask_contains(targetMask, bp->bkend_type))
3988 continue;
3989
3991 (errmsg_internal("%s process %d is still running",
3992 GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
3993
3994 cnt++;
3995 }
3996 return cnt;
3997}
#define DEBUG4
Definition elog.h:28
#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:359
dlist_head ActiveChildList
Definition pmchild.c:60
bool IsPostmasterChildWalSender(int slot)
Definition pmsignal.c:270
static bool btmask_contains(BackendTypeMask mask, BackendType t)
Definition postmaster.c:195
dlist_node * cur
Definition ilist.h:179

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

Referenced by PostmasterStateMachine().

◆ CreateOptsFile()

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

Definition at line 4131 of file postmaster.c.

4132{
4133 FILE *fp;
4134 int i;
4135
4136#define OPTS_FILE "postmaster.opts"
4137
4138 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4139 {
4140 ereport(LOG,
4142 errmsg("could not create file \"%s\": %m", OPTS_FILE)));
4143 return false;
4144 }
4145
4146 fprintf(fp, "%s", fullprogname);
4147 for (i = 1; i < argc; i++)
4148 fprintf(fp, " \"%s\"", argv[i]);
4149 fputs("\n", fp);
4150
4151 if (fclose(fp))
4152 {
4153 ereport(LOG,
4155 errmsg("could not write file \"%s\": %m", OPTS_FILE)));
4156 return false;
4157 }
4158
4159 return true;
4160}
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
#define OPTS_FILE

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

Referenced by PostmasterMain().

◆ DetermineSleepTime()

static int DetermineSleepTime ( void  )
static

Definition at line 1559 of file postmaster.c.

1560{
1562
1563 /*
1564 * If in ImmediateShutdown with a SIGKILL timeout, ignore everything else
1565 * and wait for that.
1566 *
1567 * XXX Shouldn't this also test FatalError?
1568 */
1570 {
1571 if (AbortStartTime != 0)
1572 {
1573 time_t curtime = time(NULL);
1574 int seconds;
1575
1576 /*
1577 * time left to abort; clamp to 0 if it already expired, or if
1578 * time goes backwards
1579 */
1580 if (curtime < AbortStartTime ||
1582 seconds = 0;
1583 else
1586
1587 return seconds * 1000;
1588 }
1589 }
1590
1591 /* Time of next maybe_start_io_workers() call, or 0 for none. */
1593
1594 /* Ignore bgworkers during shutdown. */
1596 return 0;
1597
1599 {
1600 dlist_mutable_iter iter;
1601
1602 /*
1603 * When there are crashed bgworkers, we sleep just long enough that
1604 * they are restarted when they request to be. Scan the list to
1605 * determine the minimum of all wakeup times according to most recent
1606 * crash time and requested restart interval.
1607 */
1609 {
1612
1613 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
1614
1615 if (rw->rw_crashed_at == 0)
1616 continue;
1617
1619 || rw->rw_terminate)
1620 {
1622 continue;
1623 }
1624
1626 1000L * rw->rw_worker.bgw_restart_time);
1627 if (next_wakeup == 0 || this_wakeup < next_wakeup)
1629 }
1630 }
1631
1632 if (next_wakeup != 0)
1633 {
1634 int ms;
1635
1636 /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1638 next_wakeup);
1639 return Min(60 * 1000, ms);
1640 }
1641
1642 return 60 * 1000;
1643}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.c:1751
dlist_head BackgroundWorkerList
Definition bgworker.c:45
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition bgworker.c:455
#define BGW_NEVER_RESTART
Definition bgworker.h:92
#define Min(x, y)
Definition c.h:1091
int64 TimestampTz
Definition timestamp.h:39
#define dlist_foreach_modify(iter, lhead)
Definition ilist.h:640
static TimestampTz maybe_start_io_workers_scheduled_at(void)
#define ImmediateShutdown
Definition postmaster.c:287
static time_t AbortStartTime
Definition postmaster.c:367
#define SIGKILL_CHILDREN_AFTER_SECS
Definition postmaster.c:370
static bool StartWorkerNeeded
Definition postmaster.c:389
BackgroundWorker rw_worker
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, fb(), ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, ImmediateShutdown, maybe_start_io_workers_scheduled_at(), 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 3958 of file postmaster.c.

3959{
3960}

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 3693 of file postmaster.c.

3694{
3695#ifdef HAVE_PTHREAD_IS_THREADED_NP
3696
3697 /*
3698 * There is no known cause for a postmaster to become multithreaded after
3699 * startup. However, we might reach here via an error exit before
3700 * reaching the test in PostmasterMain, so provide the same hint as there.
3701 * This message uses LOG level, because an unclean shutdown at this point
3702 * would usually not look much different from a clean shutdown.
3703 */
3704 if (pthread_is_threaded_np() != 0)
3705 ereport(LOG,
3707 errmsg("postmaster became multithreaded"),
3708 errhint("Set the LC_ALL environment variable to a valid locale.")));
3709#endif
3710
3711 /* should cleanup shared memory and kill all backends */
3712
3713 /*
3714 * Not sure of the semantics here. When the Postmaster dies, should the
3715 * backends all be killed? probably not.
3716 *
3717 * MUST -- vadim 05-10-1999
3718 */
3719
3720 proc_exit(status);
3721}
int errhint(const char *fmt,...) pg_attribute_printf(1
void proc_exit(int code)
Definition ipc.c:105

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

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char argv0)
static

Definition at line 1476 of file postmaster.c.

1477{
1478 DIR *pdir;
1479
1480 /* Locate the postgres executable itself */
1482 ereport(FATAL,
1483 (errmsg("%s: could not locate my own executable path", argv0)));
1484
1485#ifdef EXEC_BACKEND
1486 /* Locate executable backend before we change working directory */
1488 postgres_exec_path) < 0)
1489 ereport(FATAL,
1490 (errmsg("%s: could not locate matching postgres executable",
1491 argv0)));
1492#endif
1493
1494 /*
1495 * Locate the pkglib directory --- this has to be set early in case we try
1496 * to load any modules from it in response to postgresql.conf entries.
1497 */
1499
1500 /*
1501 * Verify that there's a readable directory there; otherwise the Postgres
1502 * installation is incomplete or corrupt. (A typical cause of this
1503 * failure is that the postgres executable has been moved or hardlinked to
1504 * some directory that's not a sibling of the installation lib/
1505 * directory.)
1506 */
1508 if (pdir == NULL)
1509 ereport(ERROR,
1511 errmsg("could not open directory \"%s\": %m",
1512 pkglib_path),
1513 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1514 my_exec_path)));
1515 FreeDir(pdir);
1516
1517 /*
1518 * It's not worth checking the share/ directory. If the lib/ directory is
1519 * there, then share/ probably is too.
1520 */
1521}
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:40
int FreeDir(DIR *dir)
Definition fd.c:3009
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
char pkglib_path[MAXPGPATH]
Definition globals.c:84
char my_exec_path[MAXPGPATH]
Definition globals.c:83
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, fb(), 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 2251 of file postmaster.c.

2252{
2253 pending_pm_child_exit = true;
2255}
void SetLatch(Latch *latch)
Definition latch.c:290
static volatile sig_atomic_t pending_pm_child_exit
Definition postmaster.c:394

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

2004{
2005 pending_pm_pmsignal = true;
2007}
static volatile sig_atomic_t pending_pm_pmsignal
Definition postmaster.c:393

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

2014{
2017}
static volatile sig_atomic_t pending_pm_reload_request
Definition postmaster.c:395

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

2077{
2078 switch (postgres_signal_arg)
2079 {
2080 case SIGTERM:
2081 /* smart is implied if the other two flags aren't set */
2083 break;
2084 case SIGINT:
2087 break;
2088 case SIGQUIT:
2091 break;
2092 }
2094}
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition postmaster.c:397
static volatile sig_atomic_t pending_pm_shutdown_request
Definition postmaster.c:396
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition postmaster.c:398
#define SIGQUIT
Definition win32_port.h:159

References fb(), 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 2818 of file postmaster.c.

2819{
2820 /*
2821 * We only log messages and send signals if this is the first process
2822 * crash and we're not doing an immediate shutdown; otherwise, we're only
2823 * here to update postmaster's idea of live processes. If we have already
2824 * signaled children, nonzero exit status is to be expected, so don't
2825 * clutter log.
2826 */
2828 return;
2829
2830 LogChildExit(LOG, procname, pid, exitstatus);
2831 ereport(LOG,
2832 (errmsg("terminating any other active server processes")));
2833
2834 /*
2835 * Switch into error state. The crashed process has already been removed
2836 * from ActiveChildList.
2837 */
2839}
@ PMQUIT_FOR_CRASH
Definition pmsignal.h:56
static void HandleFatalError(QuitSignalReason reason, bool consider_sigabrt)

References ereport, errmsg, FatalError, fb(), 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 2732 of file postmaster.c.

2733{
2734 int sigtosend;
2735
2738
2739 SetQuitSignalReason(reason);
2740
2743 else
2745
2746 /*
2747 * Signal all other child processes to exit.
2748 *
2749 * We could exclude dead-end children here, but at least when sending
2750 * SIGABRT it seems better to include them.
2751 */
2753
2754 FatalError = true;
2755
2756 /*
2757 * Choose the appropriate new state to react to the fatal error. Unless we
2758 * were already in the process of shutting down, we go through
2759 * PM_WAIT_BACKENDS. For errors during the shutdown sequence, we directly
2760 * switch to PM_WAIT_DEAD_END.
2761 */
2762 switch (pmState)
2763 {
2764 case PM_INIT:
2765 /* shouldn't have any children */
2766 Assert(false);
2767 break;
2768
2769 /* wait for children to die */
2770 case PM_STARTUP:
2771 case PM_RECOVERY:
2772 case PM_HOT_STANDBY:
2773 case PM_RUN:
2774 case PM_STOP_BACKENDS:
2776 break;
2777
2778 case PM_WAIT_BACKENDS:
2779 /* there might be more backends to wait for */
2780 break;
2781
2785 case PM_WAIT_IO_WORKERS:
2786
2787 /*
2788 * NB: Similar code exists in PostmasterStateMachine()'s handling
2789 * of FatalError in PM_STOP_BACKENDS/PM_WAIT_BACKENDS states.
2790 */
2793 break;
2794
2795 case PM_WAIT_DEAD_END:
2796 case PM_NO_CHILDREN:
2797 break;
2798 }
2799
2800 /*
2801 * .. and if this doesn't happen quickly enough, now the clock is ticking
2802 * for us to kill them without mercy.
2803 */
2804 if (AbortStartTime == 0)
2805 AbortStartTime = time(NULL);
2806}
void SetQuitSignalReason(QuitSignalReason reason)
Definition pmsignal.c:201
static void TerminateChildren(int signal)
static void UpdatePMState(PMState newState)
bool send_abort_for_crash
Definition postmaster.c:257
static void ConfigurePostmasterWaitSet(bool accept_connections)
#define SIGABRT
Definition win32_port.h:161

References AbortStartTime, Assert, ConfigurePostmasterWaitSet(), FatalError, fb(), 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 4695 of file postmaster.c.

4696{
4697#ifndef WIN32
4698
4699 /*
4700 * Create a pipe. Postmaster holds the write end of the pipe open
4701 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
4702 * the read file descriptor to select() to wake up in case postmaster
4703 * dies, or check for postmaster death with a (read() == 0). Children must
4704 * close the write end as soon as possible after forking, because EOF
4705 * won't be signaled in the read end until all processes have closed the
4706 * write fd. That is taken care of in ClosePostmasterPorts().
4707 */
4709 if (pipe(postmaster_alive_fds) < 0)
4710 ereport(FATAL,
4712 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
4713
4714 /* Notify fd.c that we've eaten two FDs for the pipe. */
4717
4718 /*
4719 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
4720 * call.
4721 */
4723 ereport(FATAL,
4725 errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
4726#else
4727
4728 /*
4729 * On Windows, we use a process handle for the same purpose.
4730 */
4735 0,
4736 TRUE,
4738 ereport(FATAL,
4739 (errmsg_internal("could not duplicate postmaster handle: error code %lu",
4740 GetLastError())));
4741#endif /* WIN32 */
4742}
int errcode_for_socket_access(void)
Definition elog.c:977
void ReserveExternalFD(void)
Definition fd.c:1207
pid_t PostmasterPid
Definition globals.c:108
int MyProcPid
Definition globals.c:49
#define POSTMASTER_FD_WATCH
Definition postmaster.h:83

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

Referenced by PostmasterMain().

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 1958 of file postmaster.c.

1959{
1962
1963 /* initialize timing infrastructure (required for INSTR_* calls) */
1965
1966 /*
1967 * Set a different global seed in every process. We want something
1968 * unpredictable, so if possible, use high-quality random bits for the
1969 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1970 */
1972 {
1973 uint64 rseed;
1974
1975 /*
1976 * Since PIDs and timestamps tend to change more frequently in their
1977 * least significant bits, shift the timestamp left to allow a larger
1978 * total number of seeds in a given time period. Since that would
1979 * leave only 20 bits of the timestamp that cycle every ~1 second,
1980 * also mix in some higher bits.
1981 */
1982 rseed = ((uint64) MyProcPid) ^
1983 ((uint64) MyStartTimestamp << 12) ^
1984 ((uint64) MyStartTimestamp >> 20);
1985
1987 }
1988
1989 /*
1990 * Also make sure that we've set a good seed for random(3). Use of that
1991 * is deprecated in core Postgres, but extensions might use it.
1992 */
1993#ifndef WIN32
1995#endif
1996}
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition timestamp.c:1836
uint64_t uint64
Definition c.h:625
#define unlikely(x)
Definition c.h:438
TimestampTz MyStartTimestamp
Definition globals.c:51
pg_time_t MyStartTime
Definition globals.c:50
void pg_initialize_timing(void)
Definition instr_time.c:82
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 fb(), GetCurrentTimestamp(), MyProcPid, MyStartTime, MyStartTimestamp, pg_global_prng_state, pg_initialize_timing(), 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 3325 of file postmaster.c.

3326{
3327 /* Syslogger is active in all states */
3330
3331 /*
3332 * The number of configured workers might have changed, or a prior start
3333 * of a worker might have failed. Check if we need to start/stop any
3334 * workers.
3335 *
3336 * A config file change will always lead to this function being called, so
3337 * we always will process the config change in a timely manner.
3338 */
3340
3341 /*
3342 * The checkpointer and the background writer are active from the start,
3343 * until shutdown is initiated.
3344 *
3345 * (If the checkpointer is not running when we enter the
3346 * PM_WAIT_XLOG_SHUTDOWN state, it is launched one more time to perform
3347 * the shutdown checkpoint. That's done in PostmasterStateMachine(), not
3348 * here.)
3349 */
3350 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
3352 {
3355 if (BgWriterPMChild == NULL)
3357 }
3358
3359 /*
3360 * WAL writer is needed only in normal operation (else we cannot be
3361 * writing any new WAL).
3362 */
3363 if (WalWriterPMChild == NULL && pmState == PM_RUN)
3365
3366 /*
3367 * We don't want autovacuum to run in binary upgrade mode because
3368 * autovacuum might update relfrozenxid for empty tables before the
3369 * physical files are put in place.
3370 */
3373 pmState == PM_RUN)
3374 {
3377 start_autovac_launcher = false; /* signal processed */
3378 }
3379
3380 /*
3381 * If WAL archiving is enabled always, we are allowed to start archiver
3382 * even during recovery.
3383 */
3384 if (PgArchPMChild == NULL &&
3385 ((XLogArchivingActive() && pmState == PM_RUN) ||
3389
3390 /*
3391 * If we need to start a slot sync worker, try to do that now
3392 *
3393 * We allow to start the slot sync worker when we are on a hot standby,
3394 * fast or immediate shutdown is not in progress, slot sync parameters are
3395 * configured correctly, and it is the first time of worker's launch, or
3396 * enough time has passed since the worker was launched last.
3397 */
3402
3403 /*
3404 * If we need to start a WAL receiver, try to do that now
3405 *
3406 * Note: if a walreceiver process is already running, it might seem that
3407 * we should clear WalReceiverRequested. However, there's a race
3408 * condition if the walreceiver terminates and the startup process
3409 * immediately requests a new one: it's quite possible to get the signal
3410 * for the request before reaping the dead walreceiver process. Better to
3411 * risk launching an extra walreceiver than to miss launching one we need.
3412 * (The walreceiver code has logic to recognize that it should go away if
3413 * not needed.)
3414 */
3416 {
3417 if (WalReceiverPMChild == NULL &&
3419 pmState == PM_HOT_STANDBY) &&
3421 {
3423 if (WalReceiverPMChild != NULL)
3424 WalReceiverRequested = false;
3425 /* else leave the flag set, so we'll try again later */
3426 }
3427 }
3428
3429 /* If we need to start a WAL summarizer, try to do that now */
3431 (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
3434
3435 /* Get other worker processes running, if needed */
3438}
bool AutoVacuumingActive(void)
bool IsBinaryUpgrade
Definition globals.c:123
@ B_WAL_SUMMARIZER
Definition miscadmin.h:379
@ B_WAL_WRITER
Definition miscadmin.h:380
@ B_WAL_RECEIVER
Definition miscadmin.h:378
@ B_CHECKPOINTER
Definition miscadmin.h:375
@ B_BG_WRITER
Definition miscadmin.h:374
@ B_ARCHIVER
Definition miscadmin.h:373
@ B_AUTOVAC_LAUNCHER
Definition miscadmin.h:356
@ B_SLOTSYNC_WORKER
Definition miscadmin.h:360
bool PgArchCanRestart(void)
Definition pgarch.c:196
#define SmartShutdown
Definition postmaster.c:285
static PMChild * PgArchPMChild
Definition postmaster.c:268
static void maybe_start_bgworkers(void)
static void StartSysLogger(void)
static PMChild * BgWriterPMChild
Definition postmaster.c:262
static PMChild * StartChildProcess(BackendType type)
static bool start_autovac_launcher
Definition postmaster.c:380
static PMChild * WalReceiverPMChild
Definition postmaster.c:265
static PMChild * WalWriterPMChild
Definition postmaster.c:264
static PMChild * WalSummarizerPMChild
Definition postmaster.c:266
static PMChild * SysLoggerPMChild
Definition postmaster.c:269
static bool WalReceiverRequested
Definition postmaster.c:386
static PMChild * CheckpointerPMChild
Definition postmaster.c:263
static PMChild * SlotSyncWorkerPMChild
Definition postmaster.c:270
static void maybe_start_io_workers(void)
bool sync_replication_slots
Definition slotsync.c:132
bool SlotSyncWorkerCanRestart(void)
Definition slotsync.c:1884
bool ValidateSlotSyncParams(int elevel)
Definition slotsync.c:1178
bool Logging_collector
Definition syslogger.c:71
bool summarize_wal
#define XLogArchivingActive()
Definition xlog.h:102
#define XLogArchivingAlways()
Definition xlog.h:105

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, fb(), HaveCrashedWorker, IsBinaryUpgrade, LOG, Logging_collector, maybe_start_bgworkers(), maybe_start_io_workers(), 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 2845 of file postmaster.c.

2846{
2847 /*
2848 * size of activity_buffer is arbitrary, but set equal to default
2849 * track_activity_query_size
2850 */
2851 char activity_buffer[1024];
2852 const char *activity = NULL;
2853
2857 sizeof(activity_buffer));
2858
2859 if (WIFEXITED(exitstatus))
2860 ereport(lev,
2861
2862 /*------
2863 translator: %s is a noun phrase describing a child process, such as
2864 "server process" */
2865 (errmsg("%s (PID %d) exited with exit code %d",
2866 procname, pid, WEXITSTATUS(exitstatus)),
2867 activity ? errdetail("Failed process was running: %s", activity) : 0));
2868 else if (WIFSIGNALED(exitstatus))
2869 {
2870#if defined(WIN32)
2871 ereport(lev,
2872
2873 /*------
2874 translator: %s is a noun phrase describing a child process, such as
2875 "server process" */
2876 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2877 procname, pid, WTERMSIG(exitstatus)),
2878 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2879 activity ? errdetail("Failed process was running: %s", activity) : 0));
2880#else
2881 ereport(lev,
2882
2883 /*------
2884 translator: %s is a noun phrase describing a child process, such as
2885 "server process" */
2886 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2887 procname, pid, WTERMSIG(exitstatus),
2889 activity ? errdetail("Failed process was running: %s", activity) : 0));
2890#endif
2891 }
2892 else
2893 ereport(lev,
2894
2895 /*------
2896 translator: %s is a noun phrase describing a child process, such as
2897 "server process" */
2898 (errmsg("%s (PID %d) exited with unrecognized status %d",
2899 procname, pid, exitstatus),
2900 activity ? errdetail("Failed process was running: %s", activity) : 0));
2901}
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
int errdetail(const char *fmt,...) pg_attribute_printf(1
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, fb(), pg_strsignal(), pgstat_get_crashed_backend_activity(), WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

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

◆ maybe_reap_io_worker()

static bool maybe_reap_io_worker ( int  pid)
static

Definition at line 4394 of file postmaster.c.

4395{
4396 for (int i = 0; i < MAX_IO_WORKERS; ++i)
4397 {
4398 if (io_worker_children[i] &&
4399 io_worker_children[i]->pid == pid)
4400 {
4402
4405 return true;
4406 }
4407 }
4408 return false;
4409}
static PMChild * io_worker_children[MAX_IO_WORKERS]
Definition postmaster.c:415
static int io_worker_count
Definition postmaster.c:414
#define MAX_IO_WORKERS
Definition proc.h:526

References fb(), 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 4280 of file postmaster.c.

4281{
4282#define MAX_BGWORKERS_TO_LAUNCH 100
4283 int num_launched = 0;
4284 TimestampTz now = 0;
4285 dlist_mutable_iter iter;
4286
4287 /*
4288 * During crash recovery, we have no need to be called until the state
4289 * transition out of recovery.
4290 */
4291 if (FatalError)
4292 {
4293 StartWorkerNeeded = false;
4294 HaveCrashedWorker = false;
4295 return;
4296 }
4297
4298 /* Don't need to be called again unless we find a reason for it below */
4299 StartWorkerNeeded = false;
4300 HaveCrashedWorker = false;
4301
4303 {
4305
4306 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
4307
4308 /* ignore if already running */
4309 if (rw->rw_pid != 0)
4310 continue;
4311
4312 /* if marked for death, clean up and remove from list */
4313 if (rw->rw_terminate)
4314 {
4316 continue;
4317 }
4318
4319 /*
4320 * If this worker has crashed previously, maybe it needs to be
4321 * restarted (unless on registration it specified it doesn't want to
4322 * be restarted at all). Check how long ago did a crash last happen.
4323 * If the last crash is too recent, don't start it right away; let it
4324 * be restarted once enough time has passed.
4325 */
4326 if (rw->rw_crashed_at != 0)
4327 {
4329 {
4330 int notify_pid;
4331
4333
4335
4336 /* Report worker is gone now. */
4337 if (notify_pid != 0)
4339
4340 continue;
4341 }
4342
4343 /* read system time only when needed */
4344 if (now == 0)
4346
4348 rw->rw_worker.bgw_restart_time * 1000))
4349 {
4350 /* Set flag to remember that we have workers to start later */
4351 HaveCrashedWorker = true;
4352 continue;
4353 }
4354 }
4355
4357 {
4358 /* reset crash time before trying to start worker */
4359 rw->rw_crashed_at = 0;
4360
4361 /*
4362 * Try to start the worker.
4363 *
4364 * On failure, give up processing workers for now, but set
4365 * StartWorkerNeeded so we'll come back here on the next iteration
4366 * of ServerLoop to try again. (We don't want to wait, because
4367 * there might be additional ready-to-run workers.) We could set
4368 * HaveCrashedWorker as well, since this worker is now marked
4369 * crashed, but there's no need because the next run of this
4370 * function will do that.
4371 */
4372 if (!StartBackgroundWorker(rw))
4373 {
4374 StartWorkerNeeded = true;
4375 return;
4376 }
4377
4378 /*
4379 * If we've launched as many workers as allowed, quit, but have
4380 * ServerLoop call us again to look for additional ready-to-run
4381 * workers. There might not be any, but we'll find out the next
4382 * time we run.
4383 */
4385 {
4386 StartWorkerNeeded = true;
4387 return;
4388 }
4389 }
4390 }
4391}
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1775
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1603
static bool StartBackgroundWorker(RegisteredBgWorker *rw)
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
BgWorkerStartTime bgw_start_time
Definition bgworker.h:101
pid_t bgw_notify_pid
Definition bgworker.h:107
#define kill(pid, sig)
Definition win32_port.h:490
#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, fb(), 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().

◆ maybe_start_io_workers()

static void maybe_start_io_workers ( void  )
static

Definition at line 4473 of file postmaster.c.

4474{
4476
4478 {
4480 PMChild *child;
4481 int i;
4482
4484
4485 /* Still waiting for the scheduled time? */
4486 if (scheduled_at > now)
4487 break;
4488
4489 /*
4490 * Compute next launch time relative to the previous value, so that
4491 * time spent on the postmaster's other duties don't result in an
4492 * inaccurate launch interval.
4493 */
4497
4498 /*
4499 * If that's already in the past, the interval is either impossibly
4500 * short or we received no requests for new workers for a period.
4501 * Compute a new future time relative to now instead.
4502 */
4506
4507 /*
4508 * Check if a grow signal has been received, but the grow request has
4509 * been canceled since then because work ran out. We've still
4510 * advanced the next launch time, to suppress repeat signals from
4511 * workers until then.
4512 */
4514 {
4516 break;
4517 }
4518
4519 /* find unused entry in io_worker_children array */
4520 for (i = 0; i < MAX_IO_WORKERS; ++i)
4521 {
4522 if (io_worker_children[i] == NULL)
4523 break;
4524 }
4525 if (i == MAX_IO_WORKERS)
4526 elog(ERROR, "could not find a free IO worker slot");
4527
4528 /* Try to launch one. */
4530 if (child != NULL)
4531 {
4532 io_worker_children[i] = child;
4534 }
4535 else
4536 {
4537 /*
4538 * Fork failure: we'll try again after the launch interval
4539 * expires, or be called again without delay if we don't yet have
4540 * io_min_workers. Don't loop here though, the postmaster has
4541 * other duties.
4542 */
4543 break;
4544 }
4545 }
4546
4547 /*
4548 * Workers decide when to shut down by themselves, according to the
4549 * io_max_workers and io_worker_idle_timeout GUCs.
4550 */
4551}
int io_worker_launch_interval
bool pgaio_worker_pm_test_grow(void)
int io_min_workers
void pgaio_worker_pm_clear_grow_signal_sent(void)
@ B_IO_WORKER
Definition miscadmin.h:376
static TimestampTz io_worker_launch_next_time
Definition postmaster.c:413

References Assert, B_IO_WORKER, elog, ERROR, fb(), GetCurrentTimestamp(), i, io_min_workers, io_worker_children, io_worker_count, io_worker_launch_interval, io_worker_launch_next_time, MAX_IO_WORKERS, maybe_start_io_workers_scheduled_at(), now(), pgaio_worker_pm_clear_grow_signal_sent(), pgaio_worker_pm_test_grow(), PM_WAIT_IO_WORKERS, pmState, StartChildProcess(), and TimestampTzPlusMilliseconds.

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

◆ maybe_start_io_workers_scheduled_at()

static TimestampTz maybe_start_io_workers_scheduled_at ( void  )
static

Definition at line 4420 of file postmaster.c.

4421{
4422 if (!pgaio_workers_enabled())
4423 return 0;
4424
4425 /*
4426 * If we're in final shutting down state, then we're just waiting for all
4427 * processes to exit.
4428 */
4430 return 0;
4431
4432 /* Don't start new workers during an immediate shutdown either. */
4434 return 0;
4435
4436 /*
4437 * Don't start new workers if we're in the shutdown phase of a crash
4438 * restart. But we *do* need to start if we're already starting up again.
4439 */
4441 return 0;
4442
4443 /*
4444 * Don't start a worker if we're at or above the maximum. (Excess workers
4445 * exit when the GUC is lowered, but the count can be temporarily too high
4446 * until they are reaped.)
4447 */
4449 return 0;
4450
4451 /* If we're under the minimum, start a worker as soon as possible. */
4453 return TIMESTAMP_MINUS_INFINITY; /* start worker ASAP */
4454
4455 /* Only proceed if a "grow" signal has been received from a worker. */
4457 return 0;
4458
4459 /*
4460 * maybe_start_io_workers() should start a new I/O worker after this time,
4461 * or as soon as possible if is already in the past.
4462 */
4464}
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
bool pgaio_worker_pm_test_grow_signal_sent(void)
int io_max_workers
bool pgaio_workers_enabled(void)

References FatalError, ImmediateShutdown, io_max_workers, io_min_workers, io_worker_count, io_worker_launch_next_time, pgaio_worker_pm_test_grow_signal_sent(), pgaio_workers_enabled(), PM_STOP_BACKENDS, PM_WAIT_IO_WORKERS, pmState, Shutdown, and TIMESTAMP_MINUS_INFINITY.

Referenced by DetermineSleepTime(), and maybe_start_io_workers().

◆ pm_signame()

static const char * pm_signame ( int  signal)
static

Definition at line 3448 of file postmaster.c.

3449{
3450#define PM_TOSTR_CASE(sym) case sym: return #sym
3451 switch (signal)
3452 {
3462 default:
3463 /* all signals sent by postmaster should be listed here */
3464 Assert(false);
3465 return "(unknown)";
3466 }
3467#undef PM_TOSTR_CASE
3468
3469 return ""; /* silence compiler */
3470}
#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, fb(), 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 497 of file postmaster.c.

498{
500 int opt;
501 int status;
502 char *userDoption = NULL;
503 bool listen_addr_saved = false;
505
507
509
511
512 /*
513 * Start our win32 signal implementation
514 */
515#ifdef WIN32
517#endif
518
519 /*
520 * We should not be creating any files or directories before we check the
521 * data directory (see checkDataDir()), but just in case set the umask to
522 * the most restrictive (owner-only) permissions.
523 *
524 * checkDataDir() will reset the umask based on the data directory
525 * permissions.
526 */
528
529 /*
530 * By default, palloc() requests in the postmaster will be allocated in
531 * the PostmasterContext, which is space that can be recycled by backends.
532 * Allocated data that needs to be available to backends should be
533 * allocated in TopMemoryContext.
534 */
536 "Postmaster",
539
540 /* Initialize paths to installation files */
541 getInstallationPaths(argv[0]);
542
543 /*
544 * Set up signal handlers for the postmaster process.
545 *
546 * CAUTION: when changing this list, check for side-effects on the signal
547 * handling setup of child processes. See tcop/postgres.c,
548 * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
549 * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
550 * postmaster/bgworker.c and postmaster/checkpointer.c.
551 */
552 pqinitmask();
554
559 pqsignal(SIGALRM, PG_SIG_IGN); /* ignored */
560 pqsignal(SIGPIPE, PG_SIG_IGN); /* ignored */
562 pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
564
565 /* This may configure SIGURG, depending on platform. */
568
569 /*
570 * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
571 * ignore those signals in a postmaster environment, so that there is no
572 * risk of a child process freezing up due to writing to stderr. But for
573 * a standalone backend, their default handling is reasonable. Hence, all
574 * child processes should just allow the inherited settings to stand.
575 */
576#ifdef SIGTTIN
577 pqsignal(SIGTTIN, PG_SIG_IGN); /* ignored */
578#endif
579#ifdef SIGTTOU
580 pqsignal(SIGTTOU, PG_SIG_IGN); /* ignored */
581#endif
582
583 /* ignore SIGXFSZ, so that ulimit violations work like disk full */
584#ifdef SIGXFSZ
585 pqsignal(SIGXFSZ, PG_SIG_IGN); /* ignored */
586#endif
587
588 /* Begin accepting signals. */
590
591 /*
592 * Options setup
593 */
595
596 /*
597 * Parse command-line options. CAUTION: keep this in sync with
598 * tcop/postgres.c (the option sets should not conflict) and with the
599 * common help() function in main/main.c.
600 */
601 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:");
602 optctx.opterr = 1;
603 while ((opt = pg_getopt_next(&optctx)) != -1)
604 {
605 switch (opt)
606 {
607 case 'B':
608 SetConfigOption("shared_buffers", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
609 break;
610
611 case 'b':
612 /* Undocumented flag used for binary upgrades */
613 IsBinaryUpgrade = true;
614 break;
615
616 case 'C':
618 break;
619
620 case '-':
621
622 /*
623 * Error if the user misplaced a special must-be-first option
624 * for dispatching to a subprogram. parse_dispatch_option()
625 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
626 * error for anything else.
627 */
631 errmsg("--%s must be first argument", optctx.optarg)));
632
634 case 'c':
635 {
636 char *name,
637 *value;
638
639 ParseLongOption(optctx.optarg, &name, &value);
640 if (!value)
641 {
642 if (opt == '-')
645 errmsg("--%s requires a value",
646 optctx.optarg)));
647 else
650 errmsg("-c %s requires a value",
651 optctx.optarg)));
652 }
653
655 pfree(name);
656 pfree(value);
657 break;
658 }
659
660 case 'D':
661 userDoption = strdup(optctx.optarg);
662 break;
663
664 case 'd':
666 break;
667
668 case 'E':
669 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
670 break;
671
672 case 'e':
673 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
674 break;
675
676 case 'F':
677 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
678 break;
679
680 case 'f':
682 {
683 write_stderr("%s: invalid argument for option -f: \"%s\"\n",
684 progname, optctx.optarg);
686 }
687 break;
688
689 case 'h':
690 SetConfigOption("listen_addresses", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
691 break;
692
693 case 'i':
694 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
695 break;
696
697 case 'j':
698 /* only used by interactive backend */
699 break;
700
701 case 'k':
702 SetConfigOption("unix_socket_directories", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
703 break;
704
705 case 'l':
707 break;
708
709 case 'N':
710 SetConfigOption("max_connections", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
711 break;
712
713 case 'O':
714 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
715 break;
716
717 case 'P':
718 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
719 break;
720
721 case 'p':
723 break;
724
725 case 'r':
726 /* only used by single-user backend */
727 break;
728
729 case 'S':
730 SetConfigOption("work_mem", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
731 break;
732
733 case 's':
734 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
735 break;
736
737 case 'T':
738
739 /*
740 * This option used to be defined as sending SIGSTOP after a
741 * backend crash, but sending SIGABRT seems more useful.
742 */
743 SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
744 break;
745
746 case 't':
747 {
748 const char *tmp = get_stats_option_name(optctx.optarg);
749
750 if (tmp)
751 {
753 }
754 else
755 {
756 write_stderr("%s: invalid argument for option -t: \"%s\"\n",
757 progname, optctx.optarg);
759 }
760 break;
761 }
762
763 case 'W':
764 SetConfigOption("post_auth_delay", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
765 break;
766
767 default:
768 write_stderr("Try \"%s --help\" for more information.\n",
769 progname);
771 }
772 }
773
774 /*
775 * Postmaster accepts no non-option switch arguments.
776 */
777 if (optctx.optind < argc)
778 {
779 write_stderr("%s: invalid argument: \"%s\"\n",
780 progname, argv[optctx.optind]);
781 write_stderr("Try \"%s --help\" for more information.\n",
782 progname);
784 }
785
786 /*
787 * Locate the proper configuration files and data directory, and read
788 * postgresql.conf for the first time.
789 */
792
794 {
795 /*
796 * If this is a runtime-computed GUC, it hasn't yet been initialized,
797 * and the present value is not useful. However, this is a convenient
798 * place to print the value for most GUCs because it is safe to run
799 * postmaster startup to this point even if the server is already
800 * running. For the handful of runtime-computed GUCs that we cannot
801 * provide meaningful values for yet, we wait until later in
802 * postmaster startup to print the value. We won't be able to use -C
803 * on running servers for those GUCs, but using this option now would
804 * lead to incorrect results for them.
805 */
807
808 if ((flags & GUC_RUNTIME_COMPUTED) == 0)
809 {
810 /*
811 * "-C guc" was specified, so print GUC's value and exit. No
812 * extra permission check is needed because the user is reading
813 * inside the data dir.
814 */
816 false, false);
817
818 puts(config_val ? config_val : "");
820 }
821
822 /*
823 * A runtime-computed GUC will be printed later on. As we initialize
824 * a server startup sequence, silence any log messages that may show
825 * up in the output generated. FATAL and more severe messages are
826 * useful to show, even if one would only expect at least PANIC. LOG
827 * entries are hidden.
828 */
829 SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
831 }
832
833 /* Verify that DataDir looks reasonable */
834 checkDataDir();
835
836 /* Check that pg_control exists */
838
839 /* And switch working directory into it */
841
842 /*
843 * Check for invalid combinations of GUC settings.
844 */
846 {
847 write_stderr("%s: \"superuser_reserved_connections\" (%d) plus \"reserved_connections\" (%d) must be less than \"max_connections\" (%d)\n",
848 progname,
852 }
855 (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
858 (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
861 (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
864 (errmsg("replication slot synchronization (\"sync_replication_slots\" = on) requires \"wal_level\" to be \"replica\" or \"logical\"")));
865
866 /*
867 * Other one-time internal sanity checks can go here, if they are fast.
868 * (Put any slow processing further down, after postmaster.pid creation.)
869 */
871 {
872 write_stderr("%s: invalid datetoken tables, please fix\n", progname);
874 }
875
876 /* For debugging: display postmaster environment */
878 {
879#if !defined(WIN32)
880 extern char **environ;
881#endif
882 char **p;
884
886
887 appendStringInfoString(&si, "initial environment dump:");
888 for (p = environ; *p; ++p)
889 appendStringInfo(&si, "\n%s", *p);
890
891 ereport(DEBUG3, errmsg_internal("%s", si.data));
892 pfree(si.data);
893 }
894
895 /*
896 * Create lockfile for data directory.
897 *
898 * We want to do this before we try to grab the input sockets, because the
899 * data directory interlock is more reliable than the socket-file
900 * interlock (thanks to whoever decided to put socket files in /tmp :-().
901 * For the same reason, it's best to grab the TCP socket(s) before the
902 * Unix socket(s).
903 *
904 * Also note that this internally sets up the on_proc_exit function that
905 * is responsible for removing both data directory and socket lockfiles;
906 * so it must happen before opening sockets so that at exit, the socket
907 * lockfiles go away after CloseServerPorts runs.
908 */
910
911 /*
912 * Read the control file (for error checking and config info).
913 *
914 * Since we verify the control file's CRC, this has a useful side effect
915 * on machines where we need a run-time test for CRC support instructions.
916 * The postmaster will do the test once at startup, and then its child
917 * processes will inherit the correct function pointer and not need to
918 * repeat the test.
919 */
921
922 /*
923 * Register the apply launcher. It's probably a good idea to call this
924 * before any modules had a chance to take the background worker slots.
925 */
927
928 /*
929 * Register the shared memory needs of all core subsystems.
930 */
932
933 /*
934 * process any libraries that should be preloaded at postmaster start
935 */
937
938 /*
939 * Initialize SSL library, if specified.
940 */
941#ifdef USE_SSL
942 if (EnableSSL)
943 {
944 (void) secure_initialize(true);
945 LoadedSSL = true;
946 }
947#endif
948
949 /*
950 * Now that loadable modules have had their chance to alter any GUCs,
951 * calculate MaxBackends and initialize the machinery to track child
952 * processes.
953 */
956
957 /*
958 * Calculate the size of the PGPROC fast-path lock arrays.
959 */
961
962 /*
963 * Also call any legacy shmem request hooks that might've been installed
964 * by preloaded libraries.
965 *
966 * Note: this must be done before ShmemCallRequestCallbacks(), because the
967 * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
968 * turn affects the size of the LWLock array calculated in lwlock.c.
969 */
971
972 /*
973 * Ask all subsystems, including preloaded libraries, to register their
974 * shared memory needs.
975 */
977
978 /*
979 * Now that loadable modules have had their chance to request additional
980 * shared memory, determine the value of any runtime-computed GUCs that
981 * depend on the amount of shared memory required.
982 */
984
985 /*
986 * Now that modules have been loaded, we can process any custom resource
987 * managers specified in the wal_consistency_checking GUC.
988 */
990
991 /*
992 * If -C was specified with a runtime-computed GUC, we held off printing
993 * the value earlier, as the GUC was not yet initialized. We handle -C
994 * for most GUCs before we lock the data directory so that the option may
995 * be used on a running server. However, a handful of GUCs are runtime-
996 * computed and do not have meaningful values until after locking the data
997 * directory, and we cannot safely calculate their values earlier on a
998 * running server. At this point, such GUCs should be properly
999 * initialized, and we haven't yet set up shared memory, so this is a good
1000 * time to handle the -C option for these special GUCs.
1001 */
1003 {
1005 false, false);
1006
1007 puts(config_val ? config_val : "");
1008 ExitPostmaster(0);
1009 }
1010
1011 /*
1012 * Set up shared memory and semaphores.
1013 *
1014 * Note: if using SysV shmem and/or semas, each postmaster startup will
1015 * normally choose the same IPC keys. This helps ensure that we will
1016 * clean up dead IPC objects if the postmaster crashes and is restarted.
1017 */
1019
1020 /*
1021 * Estimate number of openable files. This must happen after setting up
1022 * semaphores, because on some platforms semaphores count as open files.
1023 */
1025
1026 /*
1027 * Initialize pipe (or process handle on Windows) that allows children to
1028 * wake up from sleep on postmaster death.
1029 */
1031
1032#ifdef WIN32
1033
1034 /*
1035 * Initialize I/O completion port used to deliver list of dead children.
1036 */
1038 if (win32ChildQueue == NULL)
1039 ereport(FATAL,
1040 (errmsg("could not create I/O completion port for child queue")));
1041#endif
1042
1043#ifdef EXEC_BACKEND
1044 /* Write out nondefault GUC settings for child processes to use */
1046
1047 /*
1048 * Clean out the temp directory used to transmit parameters to child
1049 * processes (see internal_forkexec). We must do this before launching
1050 * any child processes, else we have a race condition: we could remove a
1051 * parameter file before the child can read it. It should be safe to do
1052 * so now, because we verified earlier that there are no conflicting
1053 * Postgres processes in this data directory.
1054 */
1056#endif
1057
1058 /*
1059 * Forcibly remove the files signaling a standby promotion request.
1060 * Otherwise, the existence of those files triggers a promotion too early,
1061 * whether a user wants that or not.
1062 *
1063 * This removal of files is usually unnecessary because they can exist
1064 * only during a few moments during a standby promotion. However there is
1065 * a race condition: if pg_ctl promote is executed and creates the files
1066 * during a promotion, the files can stay around even after the server is
1067 * brought up to be the primary. Then, if a new standby starts by using
1068 * the backup taken from the new primary, the files can exist at server
1069 * startup and must be removed in order to avoid an unexpected promotion.
1070 *
1071 * Note that promotion signal files need to be removed before the startup
1072 * process is invoked. Because, after that, they can be used by
1073 * postmaster's SIGUSR1 signal handler.
1074 */
1076
1077 /* Do the same for logrotate signal file */
1079
1080 /* Remove any outdated file holding the current log filenames. */
1082 ereport(LOG,
1084 errmsg("could not remove file \"%s\": %m",
1086
1087 /*
1088 * If enabled, start up syslogger collection subprocess
1089 */
1092
1093 /*
1094 * Reset whereToSendOutput from DestDebug (its starting state) to
1095 * DestNone. This stops ereport from sending log messages to stderr unless
1096 * Log_destination permits. We don't do this until the postmaster is
1097 * fully launched, since startup failures may as well be reported to
1098 * stderr.
1099 *
1100 * If we are in fact disabling logging to stderr, first emit a log message
1101 * saying so, to provide a breadcrumb trail for users who may not remember
1102 * that their logging is configured to go somewhere else.
1103 */
1105 ereport(LOG,
1106 (errmsg("ending log output to stderr"),
1107 errhint("Future log output will go to log destination \"%s\".",
1109
1111
1112 /*
1113 * Report server startup in log. While we could emit this much earlier,
1114 * it seems best to do so after starting the log collector, if we intend
1115 * to use one.
1116 */
1117 ereport(LOG,
1118 (errmsg("starting %s", PG_VERSION_STR)));
1119
1120 /*
1121 * Establish input sockets.
1122 *
1123 * First set up an on_proc_exit function that's charged with closing the
1124 * sockets again at postmaster shutdown.
1125 */
1128
1129 if (ListenAddresses)
1130 {
1131 char *rawstring;
1132 List *elemlist;
1133 ListCell *l;
1134 int success = 0;
1135
1136 /* Need a modifiable copy of ListenAddresses */
1138
1139 /* Parse string into list of hostnames */
1140 if (!SplitGUCList(rawstring, ',', &elemlist))
1141 {
1142 /* syntax error in list */
1143 ereport(FATAL,
1145 errmsg("invalid list syntax in parameter \"%s\"",
1146 "listen_addresses")));
1147 }
1148
1149 foreach(l, elemlist)
1150 {
1151 char *curhost = (char *) lfirst(l);
1152
1153 if (strcmp(curhost, "*") == 0)
1155 (unsigned short) PostPortNumber,
1156 NULL,
1159 MAXLISTEN);
1160 else
1162 (unsigned short) PostPortNumber,
1163 NULL,
1166 MAXLISTEN);
1167
1168 if (status == STATUS_OK)
1169 {
1170 success++;
1171 /* record the first successful host addr in lockfile */
1172 if (!listen_addr_saved)
1173 {
1175 listen_addr_saved = true;
1176 }
1177 }
1178 else
1180 (errmsg("could not create listen socket for \"%s\"",
1181 curhost)));
1182 }
1183
1184 if (!success && elemlist != NIL)
1185 ereport(FATAL,
1186 (errmsg("could not create any TCP/IP sockets")));
1187
1190 }
1191
1192#ifdef USE_BONJOUR
1193 /* Register for Bonjour only if we opened TCP socket(s) */
1195 {
1197
1198 /*
1199 * We pass 0 for interface_index, which will result in registering on
1200 * all "applicable" interfaces. It's not entirely clear from the
1201 * DNS-SD docs whether this would be appropriate if we have bound to
1202 * just a subset of the available network interfaces.
1203 */
1205 0,
1206 0,
1208 "_postgresql._tcp.",
1209 NULL,
1210 NULL,
1212 0,
1213 NULL,
1214 NULL,
1215 NULL);
1217 ereport(LOG,
1218 (errmsg("DNSServiceRegister() failed: error code %ld",
1219 (long) err)));
1220
1221 /*
1222 * We don't bother to read the mDNS daemon's reply, and we expect that
1223 * it will automatically terminate our registration when the socket is
1224 * closed at postmaster termination. So there's nothing more to be
1225 * done here. However, the bonjour_sdref is kept around so that
1226 * forked children can close their copies of the socket.
1227 */
1228 }
1229#endif
1230
1232 {
1233 char *rawstring;
1234 List *elemlist;
1235 ListCell *l;
1236 int success = 0;
1237
1238 /* Need a modifiable copy of Unix_socket_directories */
1240
1241 /* Parse string into list of directories */
1243 {
1244 /* syntax error in list */
1245 ereport(FATAL,
1247 errmsg("invalid list syntax in parameter \"%s\"",
1248 "unix_socket_directories")));
1249 }
1250
1251 foreach(l, elemlist)
1252 {
1253 char *socketdir = (char *) lfirst(l);
1254
1255 status = ListenServerPort(AF_UNIX, NULL,
1256 (unsigned short) PostPortNumber,
1257 socketdir,
1260 MAXLISTEN);
1261
1262 if (status == STATUS_OK)
1263 {
1264 success++;
1265 /* record the first successful Unix socket in lockfile */
1266 if (success == 1)
1268 }
1269 else
1271 (errmsg("could not create Unix-domain socket in directory \"%s\"",
1272 socketdir)));
1273 }
1274
1275 if (!success && elemlist != NIL)
1276 ereport(FATAL,
1277 (errmsg("could not create any Unix-domain sockets")));
1278
1281 }
1282
1283 /*
1284 * check that we have some socket to listen on
1285 */
1286 if (NumListenSockets == 0)
1287 ereport(FATAL,
1288 (errmsg("no socket created for listening")));
1289
1290 /*
1291 * If no valid TCP ports, write an empty line for listen address,
1292 * indicating the Unix socket must be used. Note that this line is not
1293 * added to the lock file until there is a socket backing it.
1294 */
1295 if (!listen_addr_saved)
1297
1298 /*
1299 * Record postmaster options. We delay this till now to avoid recording
1300 * bogus options (eg, unusable port number).
1301 */
1302 if (!CreateOptsFile(argc, argv, my_exec_path))
1303 ExitPostmaster(1);
1304
1305 /*
1306 * Write the external PID file if requested
1307 */
1309 {
1311
1312 if (fpidfile)
1313 {
1314 fprintf(fpidfile, "%d\n", MyProcPid);
1316
1317 /* Make PID file world readable */
1319 write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
1321 }
1322 else
1323 write_stderr("%s: could not write external PID file \"%s\": %m\n",
1325
1327 }
1328
1329 /*
1330 * Remove old temporary files. At this point there can be no other
1331 * Postgres processes running in this directory, so this should be safe.
1332 */
1334
1335 /*
1336 * Initialize the autovacuum subsystem (again, no process start yet)
1337 */
1338 autovac_init();
1339
1340 /*
1341 * Load configuration files for client authentication.
1342 */
1343 if (!load_hba())
1344 {
1345 /*
1346 * It makes no sense to continue if we fail to load the HBA file,
1347 * since there is no way to connect to the database in this case.
1348 */
1349 ereport(FATAL,
1350 /* translator: %s is a configuration file */
1351 (errmsg("could not load %s", HbaFileName)));
1352 }
1353 if (!load_ident())
1354 {
1355 /*
1356 * We can start up without the IDENT file, although it means that you
1357 * cannot log in using any of the authentication methods that need a
1358 * user name mapping. load_ident() already logged the details of error
1359 * to the log.
1360 */
1361 }
1362
1363#ifdef HAVE_PTHREAD_IS_THREADED_NP
1364
1365 /*
1366 * On macOS, libintl replaces setlocale() with a version that calls
1367 * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1368 * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1369 * the process multithreaded. The postmaster calls sigprocmask() and
1370 * calls fork() without an immediate exec(), both of which have undefined
1371 * behavior in a multithreaded program. A multithreaded postmaster is the
1372 * normal case on Windows, which offers neither fork() nor sigprocmask().
1373 * Currently, macOS is the only platform having pthread_is_threaded_np(),
1374 * so we need not worry whether this HINT is appropriate elsewhere.
1375 */
1376 if (pthread_is_threaded_np() != 0)
1377 ereport(FATAL,
1379 errmsg("postmaster became multithreaded during startup"),
1380 errhint("Set the LC_ALL environment variable to a valid locale.")));
1381#endif
1382
1383 /*
1384 * Remember postmaster startup time
1385 */
1387
1388 /*
1389 * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1390 * see what's happening.
1391 */
1393
1395
1396 /* Make sure we can perform I/O while starting up. */
1398
1399 /* Start bgwriter and checkpointer so they can help with recovery */
1402 if (BgWriterPMChild == NULL)
1404
1405 /*
1406 * We're ready to rock and roll...
1407 */
1411
1412 /* Some workers may be scheduled to start now */
1414
1415 status = ServerLoop();
1416
1417 /*
1418 * ServerLoop probably shouldn't ever return, but if it does, close down.
1419 */
1420 ExitPostmaster(status != STATUS_OK);
1421
1422 abort(); /* not reached */
1423}
void autovac_init(void)
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:4934
TimestampTz PgStartTime
Definition timestamp.c:45
int secure_initialize(bool isServerStart)
Definition be-secure.c:79
@ DestNone
Definition dest.h:87
int Log_destination
Definition elog.c:116
bool message_level_is_interesting(int elevel)
Definition elog.c:285
char * Log_destination_string
Definition elog.c:117
#define DEBUG3
Definition elog.h:29
#define WARNING
Definition elog.h:37
#define LOG_DESTINATION_STDERR
Definition elog.h:487
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:3383
void RemovePgTempFiles(void)
Definition fd.c:3323
void set_max_safe_fds(void)
Definition fd.c:1045
#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:145
bool IsPostmasterEnvironment
Definition globals.c:121
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition guc.c:4257
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition guc.c:1656
void ParseLongOption(const char *string, char **name, char **value)
Definition guc.c:6243
void InitializeGUCOptions(void)
Definition guc.c:1408
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition guc.c:4354
#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:584
char * external_pid_file
Definition guc_tables.c:587
bool load_ident(void)
Definition hba.c:2846
bool load_hba(void)
Definition hba.c:2452
static struct @177 value
static bool success
Definition initdb.c:188
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:316
void RegisterBuiltinShmemCallbacks(void)
Definition ipci.c:168
void InitializeShmemGUCs(void)
Definition ipci.c:189
void CreateSharedMemoryAndSemaphores(void)
Definition ipci.c:120
void ApplyLauncherRegister(void)
Definition launcher.c:1010
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:1781
MemoryContext TopMemoryContext
Definition mcxt.c:166
void * palloc(Size size)
Definition mcxt.c:1387
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:377
void ChangeToDataDir(void)
Definition miscinit.c:410
void process_shmem_requests(void)
Definition miscinit.c:1881
void AddToDataDirLockFile(int target_line, const char *str)
Definition miscinit.c:1521
void InitProcessLocalLatch(void)
Definition miscinit.c:236
void process_shared_preload_libraries(void)
Definition miscinit.c:1853
void checkDataDir(void)
Definition miscinit.c:297
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1465
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#define pg_hton16(x)
Definition pg_bswap.h:120
int pg_getopt_next(pg_getopt_ctx *ctx)
void pg_getopt_start(pg_getopt_ctx *ctx, int nargc, char *const *nargv, const char *ostr)
#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:547
#define PG_SIG_IGN
Definition port.h:551
int pgsocket
Definition port.h:29
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition postgres.c:3760
CommandDest whereToSendOutput
Definition postgres.c:97
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3792
const char * get_stats_option_name(const char *arg)
Definition postgres.c:3834
static const char * userDoption
Definition postgres.c:167
void InitializeMaxBackends(void)
Definition postinit.c:559
void InitializeFastPathLocks(void)
Definition postinit.c:584
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
static void CloseServerPorts(int status, Datum arg)
static void InitPostmasterDeathWatchHandle(void)
void InitProcessGlobals(void)
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
static int ServerLoop(void)
int PostPortNumber
Definition postmaster.c:204
static void checkControlFile(void)
bool enable_bonjour
Definition postmaster.c:246
int ReservedConnections
Definition postmaster.c:231
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
static PMChild * StartupPMChild
Definition postmaster.c:261
char * Unix_socket_directories
Definition postmaster.c:207
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
static void getInstallationPaths(const char *argv0)
static void unlink_external_pid_file(int status, Datum arg)
static StartupStatusEnum StartupStatus
Definition postmaster.c:281
#define MAXLISTEN
Definition postmaster.c:234
static void dummy_handler(SIGNAL_ARGS)
bool EnableSSL
Definition postmaster.c:239
char * ListenAddresses
Definition postmaster.c:210
int SuperuserReservedConnections
Definition postmaster.c:230
char * bonjour_name
Definition postmaster.c:247
@ 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:419
char ** environ
void ShmemCallRequestCallbacks(void)
Definition shmem.c:979
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:2950
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition varlena.c:3060
const char * name
void InitializeWaitEventSupport(void)
int max_wal_senders
Definition walsender.c:141
#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:126
int wal_level
Definition xlog.c:138
void InitializeWalConsistencyChecking(void)
Definition xlog.c:5194
void LocalProcessControlFile(bool reset)
Definition xlog.c:5275
@ ARCHIVE_MODE_OFF
Definition xlog.h:67
@ WAL_LEVEL_MINIMAL
Definition xlog.h:76
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(), 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, fb(), fprintf, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), 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_start_bgworkers(), maybe_start_io_workers(), MemoryContextSwitchTo(), message_level_is_interesting(), my_exec_path, MyProcPid, name, NIL, NumListenSockets, on_proc_exit(), palloc(), parse_dispatch_option(), ParseLongOption(), pfree(), pg_fallthrough, pg_getopt_next(), pg_getopt_start(), pg_hton16, PG_MODE_MASK_OWNER, PG_SIG_IGN, 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(), RegisterBuiltinShmemCallbacks(), 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(), ShmemCallRequestCallbacks(), 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_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4560 of file postmaster.c.

4561{
4562 dlist_iter iter;
4563 PMChild *bp;
4564
4566 {
4567 bp = dlist_container(PMChild, elem, iter.cur);
4568 if (bp->pid == pid)
4569 {
4570 bp->bgworker_notify = true;
4571 return true;
4572 }
4573 }
4574 return false;
4575}

References ActiveChildList, dlist_iter::cur, dlist_container, dlist_foreach, and fb().

Referenced by BackgroundWorkerStateChange().

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 2911 of file postmaster.c.

2912{
2913 /* If we're doing a smart shutdown, try to advance that state. */
2914 if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2915 {
2916 if (!connsAllowed)
2917 {
2918 /*
2919 * This state ends when we have no normal client backends running.
2920 * Then we're ready to stop other children.
2921 */
2922 if (CountChildren(btmask(B_BACKEND)) == 0)
2924 }
2925 }
2926
2927 /*
2928 * In the PM_WAIT_BACKENDS state, wait for all the regular backends and
2929 * processes like autovacuum and background workers that are comparable to
2930 * backends to exit.
2931 *
2932 * PM_STOP_BACKENDS is a transient state that means the same as
2933 * PM_WAIT_BACKENDS, but we signal the processes first, before waiting for
2934 * them. Treating it as a distinct pmState allows us to share this code
2935 * across multiple shutdown code paths.
2936 */
2938 {
2940
2941 /*
2942 * PM_WAIT_BACKENDS state ends when we have no regular backends, no
2943 * autovac launcher or workers, and no bgworkers (including
2944 * unconnected ones).
2945 */
2947 B_BACKEND,
2950 B_BG_WORKER);
2951
2952 /*
2953 * No walwriter, bgwriter, slot sync worker, or WAL summarizer either.
2954 */
2960
2961 /* If we're in recovery, also stop startup and walreceiver procs */
2963 B_STARTUP,
2965
2966 /*
2967 * If we are doing crash recovery or an immediate shutdown then we
2968 * expect archiver, checkpointer, io workers and walsender to exit as
2969 * well, otherwise not.
2970 */
2974 B_ARCHIVER,
2976 B_WAL_SENDER);
2977
2978 /*
2979 * Normally archiver, checkpointer, IO workers and walsenders will
2980 * continue running; they will be terminated later after writing the
2981 * checkpoint record. We also let dead-end children to keep running
2982 * for now. The syslogger process exits last.
2983 *
2984 * This assertion checks that we have covered all backend types,
2985 * either by including them in targetMask, or by noting here that they
2986 * are allowed to continue running.
2987 */
2988#ifdef USE_ASSERT_CHECKING
2989 {
2991
2994 B_LOGGER);
2995
2996 /*
2997 * Archiver, checkpointer, IO workers, and walsender may or may
2998 * not be in targetMask already.
2999 */
3001 B_ARCHIVER,
3004 B_WAL_SENDER);
3005
3006 /* these are not real postmaster children */
3008 B_INVALID,
3010
3011 /* also add data checksums processes */
3015
3016 /* All types should be included in targetMask or remainMask */
3018 }
3019#endif
3020
3021 /* If we had not yet signaled the processes to exit, do so now */
3023 {
3024 /*
3025 * Forget any pending requests for background workers, since we're
3026 * no longer willing to launch any new workers. (If additional
3027 * requests arrive, BackgroundWorkerStateChange will reject them.)
3028 */
3030
3032
3034 }
3035
3036 /* Are any of the target processes still running? */
3037 if (CountChildren(targetMask) == 0)
3038 {
3040 {
3041 /*
3042 * Stop any dead-end children and stop creating new ones.
3043 *
3044 * NB: Similar code exists in HandleFatalError(), when the
3045 * error happens in pmState > PM_WAIT_BACKENDS.
3046 */
3050
3051 /*
3052 * We already SIGQUIT'd auxiliary processes (other than
3053 * logger), if any, when we started immediate shutdown or
3054 * entered FatalError state.
3055 */
3056 }
3057 else
3058 {
3059 /*
3060 * If we get here, we are proceeding with normal shutdown. All
3061 * the regular children are gone, and it's time to tell the
3062 * checkpointer to do a shutdown checkpoint.
3063 */
3065 /* Start the checkpointer if not running */
3068 /* And tell it to write the shutdown checkpoint */
3070 {
3073 }
3074 else
3075 {
3076 /*
3077 * If we failed to fork a checkpointer, just shut down.
3078 * Any required cleanup will happen at next restart. We
3079 * set FatalError so that an "abnormal shutdown" message
3080 * gets logged when we exit.
3081 *
3082 * We don't consult send_abort_for_crash here, as it's
3083 * unlikely that dumping cores would illuminate the reason
3084 * for checkpointer fork failure.
3085 *
3086 * XXX: It may be worth to introduce a different PMQUIT
3087 * value that signals that the cluster is in a bad state,
3088 * without a process having crashed. But right now this
3089 * path is very unlikely to be reached, so it isn't
3090 * obviously worthwhile adding a distinct error message in
3091 * quickdie().
3092 */
3094 }
3095 }
3096 }
3097 }
3098
3099 /*
3100 * The state transition from PM_WAIT_XLOG_SHUTDOWN to
3101 * PM_WAIT_XLOG_ARCHIVAL is in process_pm_pmsignal(), in response to
3102 * PMSIGNAL_XLOG_IS_SHUTDOWN.
3103 */
3104
3106 {
3107 /*
3108 * PM_WAIT_XLOG_ARCHIVAL state ends when there are no children other
3109 * than checkpointer, io workers and dead-end children left. There
3110 * shouldn't be any regular backends left by now anyway; what we're
3111 * really waiting for is for walsenders and archiver to exit.
3112 */
3115 {
3118 }
3119 }
3120
3122 {
3123 /*
3124 * PM_WAIT_IO_WORKERS state ends when there's only checkpointer and
3125 * dead-end children left.
3126 */
3127 if (io_worker_count == 0)
3128 {
3130
3131 /*
3132 * Now that the processes mentioned above are gone, tell
3133 * checkpointer to shut down too. That allows checkpointer to
3134 * perform some last bits of cleanup without other processes
3135 * interfering.
3136 */
3139 }
3140 }
3141
3142 /*
3143 * The state transition from PM_WAIT_CHECKPOINTER to PM_WAIT_DEAD_END is
3144 * in process_pm_child_exit().
3145 */
3146
3148 {
3149 /*
3150 * PM_WAIT_DEAD_END state ends when all other children are gone except
3151 * for the logger. During normal shutdown, all that remains are
3152 * dead-end backends, but in FatalError processing we jump straight
3153 * here with more processes remaining. Note that they have already
3154 * been sent appropriate shutdown signals, either during a normal
3155 * state transition leading up to PM_WAIT_DEAD_END, or during
3156 * FatalError processing.
3157 *
3158 * The reason we wait is to protect against a new postmaster starting
3159 * conflicting subprocesses; this isn't an ironclad protection, but it
3160 * at least helps in the shutdown-and-immediately-restart scenario.
3161 */
3163 {
3164 /* These other guys should be dead already */
3173 /* syslogger is not considered here */
3175 }
3176 }
3177
3178 /*
3179 * If we've been told to shut down, we exit as soon as there are no
3180 * remaining children. If there was a crash, cleanup will occur at the
3181 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3182 * crash before exiting, but that seems unwise if we are quitting because
3183 * we got SIGTERM from init --- there may well not be time for recovery
3184 * before init decides to SIGKILL us.)
3185 *
3186 * Note that the syslogger continues to run. It will exit when it sees
3187 * EOF on its input pipe, which happens when there are no more upstream
3188 * processes.
3189 */
3191 {
3192 if (FatalError)
3193 {
3194 ereport(LOG, (errmsg("abnormal database system shutdown")));
3195 ExitPostmaster(1);
3196 }
3197 else
3198 {
3199 /*
3200 * Normal exit from the postmaster is here. We don't need to log
3201 * anything here, since the UnlinkLockFiles proc_exit callback
3202 * will do so, and that should be the last user-visible action.
3203 */
3204 ExitPostmaster(0);
3205 }
3206 }
3207
3208 /*
3209 * If the startup process failed, or the user does not want an automatic
3210 * restart after backend crashes, wait for all non-syslogger children to
3211 * exit, and then exit postmaster. We don't try to reinitialize when the
3212 * startup process fails, because more than likely it will just fail again
3213 * and we will keep trying forever.
3214 */
3215 if (pmState == PM_NO_CHILDREN)
3216 {
3218 {
3219 ereport(LOG,
3220 (errmsg("shutting down due to startup process failure")));
3221 ExitPostmaster(1);
3222 }
3224 {
3225 ereport(LOG,
3226 (errmsg("shutting down because \"restart_after_crash\" is off")));
3227 ExitPostmaster(1);
3228 }
3229 }
3230
3231 /*
3232 * If we need to recover from a crash, wait for all non-syslogger children
3233 * to exit, then reset shmem and start the startup process.
3234 */
3236 {
3237 ereport(LOG,
3238 (errmsg("all server processes terminated; reinitializing")));
3239
3240 /* remove leftover temporary files after a crash */
3243
3244 /* allow background workers to immediately restart */
3246
3247 shmem_exit(1);
3248
3249 /* re-read control file into local memory */
3251
3252 /*
3253 * Re-initialize shared memory and semaphores. Note: We don't call
3254 * RegisterBuiltinShmemCallbacks(), we keep the old registrations. In
3255 * order to re-register structs in extensions, we'd need to reload
3256 * shared preload libraries, and we don't want to do that.
3257 */
3261
3263
3264 /* Make sure we can perform I/O while starting up. */
3266
3270 /* crash recovery started, reset SIGKILL flag */
3271 AbortStartTime = 0;
3272
3273 /* start accepting server socket connection events again */
3275 }
3276}
void ResetBackgroundWorkerCrashTimes(void)
Definition bgworker.c:605
void ForgetUnstartedBackgroundWorkers(void)
Definition bgworker.c:567
void shmem_exit(int code)
Definition ipc.c:229
@ B_DATACHECKSUMSWORKER_WORKER
Definition miscadmin.h:383
@ B_LOGGER
Definition miscadmin.h:389
@ B_DATACHECKSUMSWORKER_LAUNCHER
Definition miscadmin.h:382
@ B_INVALID
Definition miscadmin.h:351
@ B_STANDALONE_BACKEND
Definition miscadmin.h:362
@ B_DEAD_END_BACKEND
Definition miscadmin.h:355
static int CountChildren(BackendTypeMask targetMask)
static const BackendTypeMask BTYPE_MASK_NONE
Definition postmaster.c:147
#define btmask_all_except(...)
Definition postmaster.c:188
#define btmask_add(mask,...)
Definition postmaster.c:165
bool remove_temp_files_after_crash
Definition postmaster.c:249
bool restart_after_crash
Definition postmaster.c:248
static bool SignalChildren(int signal, BackendTypeMask targetMask)
static BackendTypeMask btmask(BackendType t)
Definition postmaster.c:150
void ResetShmemAllocator(void)
Definition shmem.c:743

References AbortStartTime, Assert, AutoVacLauncherPMChild, B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_DATACHECKSUMSWORKER_LAUNCHER, B_DATACHECKSUMSWORKER_WORKER, 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, fb(), ForgetUnstartedBackgroundWorkers(), HandleFatalError(), ImmediateShutdown, io_worker_count, LocalProcessControlFile(), LOG, BackendTypeMask::mask, maybe_start_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(), ResetShmemAllocator(), restart_after_crash, shmem_exit(), ShmemCallRequestCallbacks(), 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 2261 of file postmaster.c.

2262{
2263 int pid; /* process id of dead child process */
2264 int exitstatus; /* its exit status */
2265
2266 pending_pm_child_exit = false;
2267
2269 (errmsg_internal("reaping dead processes")));
2270
2271 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2272 {
2274
2275 /*
2276 * Check if this child was a startup process.
2277 */
2278 if (StartupPMChild && pid == StartupPMChild->pid)
2279 {
2282
2283 /*
2284 * Startup process exited in response to a shutdown request (or it
2285 * completed normally regardless of the shutdown request).
2286 */
2287 if (Shutdown > NoShutdown &&
2289 {
2292 /* PostmasterStateMachine logic does the rest */
2293 continue;
2294 }
2295
2297 {
2298 ereport(LOG,
2299 (errmsg("shutdown at recovery target")));
2304 /* PostmasterStateMachine logic does the rest */
2305 continue;
2306 }
2307
2308 /*
2309 * Any unexpected exit (including FATAL exit) of the startup
2310 * process is catastrophic, so kill other children, and set
2311 * StartupStatus so we don't try to reinitialize after they're
2312 * gone. Exception: if StartupStatus is STARTUP_SIGNALED, then we
2313 * previously sent the startup process a SIGQUIT; so that's
2314 * probably the reason it died, and we do want to try to restart
2315 * in that case.
2316 *
2317 * This stanza also handles the case where we sent a SIGQUIT
2318 * during PM_STARTUP due to some dead-end child crashing: in that
2319 * situation, if the startup process dies on the SIGQUIT, we need
2320 * to transition to PM_WAIT_BACKENDS state which will allow
2321 * PostmasterStateMachine to restart the startup process. (On the
2322 * other hand, the startup process might complete normally, if we
2323 * were too late with the SIGQUIT. In that case we'll fall
2324 * through and commence normal operations.)
2325 */
2327 {
2329 {
2331 if (pmState == PM_STARTUP)
2333 }
2334 else
2337 _("startup process"));
2338 continue;
2339 }
2340
2341 /*
2342 * Startup succeeded, commence normal operations
2343 */
2345 FatalError = false;
2346 AbortStartTime = 0;
2347 ReachedNormalRunning = true;
2349 connsAllowed = true;
2350
2351 /*
2352 * At the next iteration of the postmaster's main loop, we will
2353 * crank up the background tasks like the autovacuum launcher and
2354 * background workers that were not started earlier already.
2355 */
2356 StartWorkerNeeded = true;
2357
2358 /* at this point we are really open for business */
2359 ereport(LOG,
2360 (errmsg("database system is ready to accept connections")));
2361
2362 /* Report status */
2364#ifdef USE_SYSTEMD
2365 sd_notify(0, "READY=1");
2366#endif
2367
2368 continue;
2369 }
2370
2371 /*
2372 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2373 * one at the next iteration of the postmaster's main loop, if
2374 * necessary. Any other exit condition is treated as a crash.
2375 */
2376 if (BgWriterPMChild && pid == BgWriterPMChild->pid)
2377 {
2382 _("background writer process"));
2383 continue;
2384 }
2385
2386 /*
2387 * Was it the checkpointer?
2388 */
2390 {
2394 {
2395 /*
2396 * OK, we saw normal exit of the checkpointer after it's been
2397 * told to shut down. We know checkpointer wrote a shutdown
2398 * checkpoint, otherwise we'd still be in
2399 * PM_WAIT_XLOG_SHUTDOWN state.
2400 *
2401 * At this point only dead-end children and logger should be
2402 * left.
2403 */
2407 }
2408 else
2409 {
2410 /*
2411 * Any unexpected exit of the checkpointer (including FATAL
2412 * exit) is treated as a crash.
2413 */
2415 _("checkpointer process"));
2416 }
2417
2418 continue;
2419 }
2420
2421 /*
2422 * Was it the wal writer? Normal exit can be ignored; we'll start a
2423 * new one at the next iteration of the postmaster's main loop, if
2424 * necessary. Any other exit condition is treated as a crash.
2425 */
2426 if (WalWriterPMChild && pid == WalWriterPMChild->pid)
2427 {
2432 _("WAL writer process"));
2433 continue;
2434 }
2435
2436 /*
2437 * Was it the wal receiver? If exit status is zero (normal) or one
2438 * (FATAL exit), we assume everything is all right just like normal
2439 * backends. (If we need a new wal receiver, we'll start one at the
2440 * next iteration of the postmaster's main loop.)
2441 */
2443 {
2448 _("WAL receiver process"));
2449 continue;
2450 }
2451
2452 /*
2453 * Was it the wal summarizer? Normal exit can be ignored; we'll start
2454 * a new one at the next iteration of the postmaster's main loop, if
2455 * necessary. Any other exit condition is treated as a crash.
2456 */
2458 {
2463 _("WAL summarizer process"));
2464 continue;
2465 }
2466
2467 /*
2468 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2469 * start a new one at the next iteration of the postmaster's main
2470 * loop, if necessary. Any other exit condition is treated as a
2471 * crash.
2472 */
2474 {
2479 _("autovacuum launcher process"));
2480 continue;
2481 }
2482
2483 /*
2484 * Was it the archiver? If exit status is zero (normal) or one (FATAL
2485 * exit), we assume everything is all right just like normal backends
2486 * and just try to start a new one on the next cycle of the
2487 * postmaster's main loop, to retry archiving remaining files.
2488 */
2489 if (PgArchPMChild && pid == PgArchPMChild->pid)
2490 {
2495 _("archiver process"));
2496 continue;
2497 }
2498
2499 /* Was it the system logger? If so, try to start a new one */
2500 if (SysLoggerPMChild && pid == SysLoggerPMChild->pid)
2501 {
2504
2505 /* for safety's sake, launch new logger *first* */
2508
2510 LogChildExit(LOG, _("system logger process"),
2511 pid, exitstatus);
2512 continue;
2513 }
2514
2515 /*
2516 * Was it the slot sync worker? Normal exit or FATAL exit can be
2517 * ignored (FATAL can be caused by libpqwalreceiver on receiving
2518 * shutdown request by the startup process during promotion); we'll
2519 * start a new one at the next iteration of the postmaster's main
2520 * loop, if necessary. Any other exit condition is treated as a crash.
2521 */
2523 {
2528 _("slot sync worker process"));
2529 continue;
2530 }
2531
2532 /* Was it an IO worker? */
2533 if (maybe_reap_io_worker(pid))
2534 {
2536 HandleChildCrash(pid, exitstatus, _("io worker"));
2537
2538 /*
2539 * A worker that exited with an error might have brought the pool
2540 * size below io_min_workers, or allowed the queue to grow to the
2541 * point where another worker called for growth.
2542 *
2543 * In the common case that a worker timed out due to idleness, no
2544 * replacement needs to be started. maybe_start_io_workers() will
2545 * figure that out.
2546 */
2548
2549 continue;
2550 }
2551
2552 /*
2553 * Was it a backend or a background worker?
2554 */
2556 if (pmchild)
2557 {
2559 }
2560
2561 /*
2562 * We don't know anything about this child process. That's highly
2563 * unexpected, as we do track all the child processes that we fork.
2564 */
2565 else
2566 {
2568 HandleChildCrash(pid, exitstatus, _("untracked child process"));
2569 else
2570 LogChildExit(LOG, _("untracked child process"), pid, exitstatus);
2571 }
2572 } /* loop over pending child-death reports */
2573
2574 /*
2575 * After cleaning out the SIGCHLD queue, see if we have any state changes
2576 * or actions to make.
2577 */
2579}
#define Max(x, y)
Definition c.h:1085
#define PM_STATUS_READY
Definition pidfile.h:53
PMChild * FindPostmasterChildByPid(int pid)
Definition pmchild.c:290
static void PostmasterStateMachine(void)
static bool maybe_reap_io_worker(int pid)
static bool ReachedNormalRunning
Definition postmaster.c:372
static void CleanupBackend(PMChild *bp, int exitstatus)
#define EXIT_STATUS_3(st)
Definition postmaster.c:480
pid_t pid
Definition postmaster.h:42

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, FatalError, fb(), FindPostmasterChildByPid(), HandleChildCrash(), LOCK_FILE_LINE_PM_STATUS, LOG, LogChildExit(), Logging_collector, Max, maybe_reap_io_worker(), maybe_start_io_workers(), 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 3728 of file postmaster.c.

3729{
3730 bool request_state_update = false;
3731
3732 pending_pm_pmsignal = false;
3733
3735 (errmsg_internal("postmaster received pmsignal signal")));
3736
3737 /*
3738 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
3739 * unexpected states. If the startup process quickly starts up, completes
3740 * recovery, exits, we might process the death of the startup process
3741 * first. We don't want to go back to recovery in that case.
3742 */
3745 {
3746 /* WAL redo has started. We're out of reinitialization. */
3747 FatalError = false;
3748 AbortStartTime = 0;
3749 reachedConsistency = false;
3750
3751 /*
3752 * Start the archiver if we're responsible for (re-)archiving received
3753 * files.
3754 */
3756 if (XLogArchivingAlways())
3758
3759 /*
3760 * If we aren't planning to enter hot standby mode later, treat
3761 * RECOVERY_STARTED as meaning we're out of startup, and report status
3762 * accordingly.
3763 */
3764 if (!EnableHotStandby)
3765 {
3767#ifdef USE_SYSTEMD
3768 sd_notify(0, "READY=1");
3769#endif
3770 }
3771
3773 }
3774
3777 {
3778 reachedConsistency = true;
3779 }
3780
3783 {
3784 ereport(LOG,
3785 (errmsg("database system is ready to accept read-only connections")));
3786
3787 /* Report status */
3789#ifdef USE_SYSTEMD
3790 sd_notify(0, "READY=1");
3791#endif
3792
3794 connsAllowed = true;
3795
3796 /* Some workers may be scheduled to start now */
3797 StartWorkerNeeded = true;
3798 }
3799
3800 /* Process IO worker start requests. */
3802 {
3803 /*
3804 * No local flag, as the state is exposed through pgaio_worker_*()
3805 * functions. This signal is received on potentially actionable level
3806 * changes, so that maybe_start_io_workers() will run.
3807 */
3808 }
3809
3810 /* Process background worker state changes. */
3812 {
3813 /* Accept new worker requests only if not stopping. */
3815 StartWorkerNeeded = true;
3816 }
3817
3818 /* Tell syslogger to rotate logfile if requested */
3819 if (SysLoggerPMChild != NULL)
3820 {
3822 {
3825 }
3827 {
3829 }
3830 }
3831
3834 {
3835 /*
3836 * Start one iteration of the autovacuum daemon, even if autovacuuming
3837 * is nominally not enabled. This is so we can have an active defense
3838 * against transaction ID wraparound. We set a flag for the main loop
3839 * to do it rather than trying to do it here --- this is because the
3840 * autovac process itself may send the signal, and we want to handle
3841 * that by launching another iteration as soon as the current one
3842 * completes.
3843 */
3845 }
3846
3849 {
3850 /* The autovacuum launcher wants us to start a worker process. */
3852 }
3853
3855 {
3856 /* Startup Process wants us to start the walreceiver process. */
3857 WalReceiverRequested = true;
3858 }
3859
3861 {
3862 /* Checkpointer completed the shutdown checkpoint */
3864 {
3865 /*
3866 * If we have an archiver subprocess, tell it to do a last archive
3867 * cycle and quit. Likewise, if we have walsender processes, tell
3868 * them to send any remaining WAL and quit.
3869 */
3871
3872 /* Waken archiver for the last time */
3873 if (PgArchPMChild != NULL)
3875
3876 /*
3877 * Waken walsenders for the last time. No regular backends should
3878 * be around anymore.
3879 */
3881
3883 }
3884 else if (!FatalError && Shutdown != ImmediateShutdown)
3885 {
3886 /*
3887 * Checkpointer only ought to perform the shutdown checkpoint
3888 * during shutdown. If somehow checkpointer did so in another
3889 * situation, we have no choice but to crash-restart.
3890 *
3891 * It's possible however that we get PMSIGNAL_XLOG_IS_SHUTDOWN
3892 * outside of PM_WAIT_XLOG_SHUTDOWN if an orderly shutdown was
3893 * "interrupted" by a crash or an immediate shutdown.
3894 */
3895 ereport(LOG,
3896 (errmsg("WAL was shut down unexpectedly")));
3897
3898 /*
3899 * Doesn't seem likely to help to take send_abort_for_crash into
3900 * account here.
3901 */
3903 }
3904
3905 /*
3906 * Need to run PostmasterStateMachine() to check if we already can go
3907 * to the next state.
3908 */
3909 request_state_update = true;
3910 }
3911
3912 /*
3913 * Try to advance postmaster's state machine, if a child requests it.
3914 */
3916 {
3917 request_state_update = true;
3918 }
3919
3920 /*
3921 * Be careful about the order of this action relative to this function's
3922 * other actions. Generally, this should be after other actions, in case
3923 * they have effects PostmasterStateMachine would need to know about.
3924 * However, we should do it before the CheckPromoteSignal step, which
3925 * cannot have any (immediate) effect on the state machine, but does
3926 * depend on what state we're in now.
3927 */
3929 {
3931 }
3932
3933 if (StartupPMChild != NULL &&
3935 pmState == PM_HOT_STANDBY) &&
3937 {
3938 /*
3939 * Tell startup process to finish recovery.
3940 *
3941 * Leave the promote signal file in place and let the Startup process
3942 * do the unlink.
3943 */
3945 }
3946}
void BackgroundWorkerStateChange(bool allow_new_workers)
Definition bgworker.c:272
#define PM_STATUS_STANDBY
Definition pidfile.h:54
bool CheckPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:181
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition pmsignal.h:40
@ PMSIGNAL_RECOVERY_STARTED
Definition pmsignal.h:35
@ PMSIGNAL_START_WALRECEIVER
Definition pmsignal.h:43
@ PMSIGNAL_START_AUTOVAC_LAUNCHER
Definition pmsignal.h:39
@ PMSIGNAL_BEGIN_HOT_STANDBY
Definition pmsignal.h:37
@ PMSIGNAL_RECOVERY_CONSISTENT
Definition pmsignal.h:36
@ PMSIGNAL_IO_WORKER_GROW
Definition pmsignal.h:41
@ PMSIGNAL_XLOG_IS_SHUTDOWN
Definition pmsignal.h:45
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition pmsignal.h:42
@ PMSIGNAL_ROTATE_LOGFILE
Definition pmsignal.h:38
@ PMSIGNAL_ADVANCE_STATE_MACHINE
Definition pmsignal.h:44
static void StartAutovacuumWorker(void)
bool CheckLogrotateSignal(void)
Definition syslogger.c:1574
bool EnableHotStandby
Definition xlog.c:128
bool reachedConsistency
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, fb(), 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_IO_WORKER_GROW, 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 2023 of file postmaster.c.

2024{
2026
2028 (errmsg_internal("postmaster received reload request signal")));
2029
2030 if (Shutdown <= SmartShutdown)
2031 {
2032 ereport(LOG,
2033 (errmsg("received SIGHUP, reloading configuration files")));
2036
2037 /* Reload authentication config files too */
2038 if (!load_hba())
2039 ereport(LOG,
2040 /* translator: %s is a configuration file */
2041 (errmsg("%s was not reloaded", HbaFileName)));
2042
2043 if (!load_ident())
2044 ereport(LOG,
2045 (errmsg("%s was not reloaded", IdentFileName)));
2046
2047#ifdef USE_SSL
2048 /* Reload SSL configuration as well */
2049 if (EnableSSL)
2050 {
2051 if (secure_initialize(false) == 0)
2052 LoadedSSL = true;
2053 else
2054 ereport(LOG,
2055 (errmsg("SSL configuration was not reloaded")));
2056 }
2057 else
2058 {
2060 LoadedSSL = false;
2061 }
2062#endif
2063
2064#ifdef EXEC_BACKEND
2065 /* Update the starting-point file for future children */
2067#endif
2068 }
2069}
void secure_destroy(void)
Definition be-secure.c:92
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
@ PGC_SIGHUP
Definition guc.h:75
char * IdentFileName
Definition guc_tables.c:585

References B_DEAD_END_BACKEND, btmask_all_except, DEBUG2, EnableSSL, ereport, errmsg, errmsg_internal(), fb(), 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 2100 of file postmaster.c.

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

References AbortStartTime, AddToDataDirLockFile(), connsAllowed, DEBUG2, ereport, errmsg, errmsg_internal(), FastShutdown, fb(), 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 3666 of file postmaster.c.

3667{
3668 char buffer[1000];
3669 int rc;
3670
3671 /* Format the error message packet (always V2 protocol) */
3672 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3673 _("could not fork new process for connection: "),
3674 strerror(errnum));
3675
3676 /* Set port to non-blocking. Don't do send() if this fails */
3677 if (!pg_set_noblock(client_sock->sock))
3678 return;
3679
3680 /* We'll retry after EINTR, but ignore all other failures */
3681 do
3682 {
3683 rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
3684 } while (rc < 0 && errno == EINTR);
3685}
bool pg_set_noblock(pgsocket sock)
Definition noblock.c:25
#define strerror
Definition port.h:273
#define EINTR
Definition win32_port.h:361
#define send(s, buf, len, flags)
Definition win32_port.h:502

References _, EINTR, fb(), pg_set_noblock(), send, snprintf, and strerror.

Referenced by BackendStartup().

◆ ServerLoop()

static int ServerLoop ( void  )
static

Definition at line 1678 of file postmaster.c.

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

3490{
3491 pid_t pid = pmchild->pid;
3492
3494 (errmsg_internal("sending signal %d/%s to %s process with pid %d",
3496 GetBackendTypeDesc(pmchild->bkend_type),
3497 (int) pmchild->pid)));
3498
3499 if (kill(pid, signal) < 0)
3500 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3501#ifdef HAVE_SETSID
3502 switch (signal)
3503 {
3504 case SIGINT:
3505 case SIGTERM:
3506 case SIGQUIT:
3507 case SIGKILL:
3508 case SIGABRT:
3509 if (kill(-pid, signal) < 0)
3510 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3511 break;
3512 default:
3513 break;
3514 }
3515#endif
3516}
static const char * pm_signame(int signal)

References DEBUG3, elog, ereport, errmsg_internal(), fb(), GetBackendTypeDesc(), kill, pm_signame(), SIGABRT, SIGKILL, and SIGQUIT.

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

◆ SignalChildren()

static bool SignalChildren ( int  signal,
BackendTypeMask  targetMask 
)
static

Definition at line 3522 of file postmaster.c.

3523{
3524 dlist_iter iter;
3525 bool signaled = false;
3526
3528 {
3529 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3530
3531 /*
3532 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3533 * if any B_BACKEND backends have recently announced that they are
3534 * actually WAL senders.
3535 */
3537 bp->bkend_type == B_BACKEND)
3538 {
3539 if (IsPostmasterChildWalSender(bp->child_slot))
3540 bp->bkend_type = B_WAL_SENDER;
3541 }
3542
3543 if (!btmask_contains(targetMask, bp->bkend_type))
3544 continue;
3545
3547 signaled = true;
3548 }
3549 return signaled;
3550}

References ActiveChildList, B_BACKEND, B_WAL_SENDER, btmask_contains(), dlist_iter::cur, dlist_container, dlist_foreach, fb(), 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 4081 of file postmaster.c.

4082{
4083 PMChild *bn;
4084
4085 /*
4086 * If not in condition to run a process, don't try, but handle it like a
4087 * fork failure. This does not normally happen, since the signal is only
4088 * supposed to be sent by autovacuum launcher when it's OK to do it, but
4089 * we have to check to avoid race-condition problems during DB state
4090 * changes.
4091 */
4093 {
4095 if (bn)
4096 {
4097 bn->bgworker_notify = false;
4098 bn->rw = NULL;
4099 return;
4100 }
4101 else
4102 {
4103 /*
4104 * fork failed, fall through to report -- actual error message was
4105 * logged by StartChildProcess
4106 */
4107 }
4108 }
4109
4110 /*
4111 * Report the failure to the launcher, if it's running. (If it's not, we
4112 * might not even be connected to shared memory, so don't try to call
4113 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4114 * responds to the condition, but we don't do that here, instead waiting
4115 * for ServerLoop to do it. This way we avoid a ping-pong signaling in
4116 * quick succession between the autovac launcher and postmaster in case
4117 * things get ugly.
4118 */
4120 {
4123 }
4124}
void AutoVacWorkerFailed(void)

References AutoVacLauncherPMChild, AutoVacWorkerFailed(), avlauncher_needs_signal, B_AUTOVAC_WORKER, CAC_OK, canAcceptConnections(), fb(), and StartChildProcess().

Referenced by process_pm_pmsignal().

◆ StartBackgroundWorker()

static bool StartBackgroundWorker ( RegisteredBgWorker rw)
static

Definition at line 4173 of file postmaster.c.

4174{
4175 PMChild *bn;
4176 pid_t worker_pid;
4177
4178 Assert(rw->rw_pid == 0);
4179
4180 /*
4181 * Allocate and assign the child slot. Note we must do this before
4182 * forking, so that we can handle failures (out of memory or child-process
4183 * slots) cleanly.
4184 *
4185 * Treat failure as though the worker had crashed. That way, the
4186 * postmaster will wait a bit before attempting to start it again; if we
4187 * tried again right away, most likely we'd find ourselves hitting the
4188 * same resource-exhaustion condition.
4189 */
4191 if (bn == NULL)
4192 {
4193 ereport(LOG,
4195 errmsg("no slot available for new background worker process")));
4197 return false;
4198 }
4199 bn->rw = rw;
4200 bn->bkend_type = B_BG_WORKER;
4201 bn->bgworker_notify = false;
4202
4204 (errmsg_internal("starting background worker process \"%s\"",
4205 rw->rw_worker.bgw_name)));
4206
4207 worker_pid = postmaster_child_launch(B_BG_WORKER, bn->child_slot,
4208 &rw->rw_worker, sizeof(BackgroundWorker), NULL);
4209 if (worker_pid == -1)
4210 {
4211 /* in postmaster, fork failed ... */
4212 ereport(LOG,
4213 (errmsg("could not fork background worker process: %m")));
4214 /* undo what AssignPostmasterChildSlot did */
4216
4217 /* mark entry as crashed, so we'll try again later */
4219 return false;
4220 }
4221
4222 /* in postmaster, fork successful ... */
4223 rw->rw_pid = worker_pid;
4224 bn->pid = rw->rw_pid;
4226 return true;
4227}
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition bgworker.c:487
char bgw_name[BGW_MAXLEN]
Definition bgworker.h:98

References Assert, AssignPostmasterChildSlot(), B_BG_WORKER, BackgroundWorker::bgw_name, DEBUG1, ereport, errcode(), errmsg, errmsg_internal(), fb(), GetCurrentTimestamp(), LOG, postmaster_child_launch(), ReleasePostmasterChildSlot(), ReportBackgroundWorkerPID(), 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 4010 of file postmaster.c.

4011{
4013 pid_t pid;
4014
4016 if (!pmchild)
4017 {
4018 if (type == B_AUTOVAC_WORKER)
4019 ereport(LOG,
4021 errmsg("no slot available for new autovacuum worker process")));
4022 else
4023 {
4024 /* shouldn't happen because we allocate enough slots */
4025 elog(LOG, "no postmaster child slot available for aux process");
4026 }
4027 return NULL;
4028 }
4029
4030 pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
4031 if (pid < 0)
4032 {
4033 /* in parent, fork failed */
4035 ereport(LOG,
4036 (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
4037
4038 /*
4039 * fork failure is fatal during startup, but there's no need to choke
4040 * immediately if starting other child types fails.
4041 */
4042 if (type == B_STARTUP)
4043 ExitPostmaster(1);
4044 return NULL;
4045 }
4046
4047 /* in parent, successful fork */
4048 pmchild->pid = pid;
4049 return pmchild;
4050}
const char * PostmasterChildName(BackendType child_type)
const char * type

References AssignPostmasterChildSlot(), B_AUTOVAC_WORKER, B_STARTUP, elog, ereport, errcode(), errmsg, ExitPostmaster(), fb(), LOG, postmaster_child_launch(), PostmasterChildName(), ReleasePostmasterChildSlot(), and type.

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

◆ StartSysLogger()

void StartSysLogger ( void  )
static

Definition at line 4056 of file postmaster.c.

4057{
4059
4061 if (!SysLoggerPMChild)
4062 elog(PANIC, "no postmaster child slot available for syslogger");
4064 if (SysLoggerPMChild->pid == 0)
4065 {
4068 }
4069}
#define PANIC
Definition elog.h:44
int child_slot
Definition postmaster.h:43
int SysLogger_Start(int child_slot)
Definition syslogger.c:593

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

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

◆ StaticAssertDecl()

StaticAssertDecl ( )

◆ TerminateChildren()

◆ unlink_external_pid_file()

static void unlink_external_pid_file ( int  status,
Datum  arg 
)
static

Definition at line 1464 of file postmaster.c.

1465{
1468}

References external_pid_file, and fb().

Referenced by PostmasterMain().

◆ UpdatePMState()

static void UpdatePMState ( PMState  newState)
static

Definition at line 3309 of file postmaster.c.

3310{
3311 elog(DEBUG1, "updating PMState from %s to %s",
3313 pmState = newState;
3314}
static const char * pmstate_name(PMState state)

References DEBUG1, elog, fb(), 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 242 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ AutoVacLauncherPMChild

◆ avlauncher_needs_signal

bool avlauncher_needs_signal = false
static

Definition at line 383 of file postmaster.c.

Referenced by ServerLoop(), and StartAutovacuumWorker().

◆ BgWriterPMChild

PMChild * BgWriterPMChild = NULL
static

◆ bonjour_name

char* bonjour_name

Definition at line 247 of file postmaster.c.

Referenced by PostmasterMain().

◆ BTYPE_MASK_ALL

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

Definition at line 146 of file postmaster.c.

146{(1 << BACKEND_NUM_TYPES) - 1};
#define BACKEND_NUM_TYPES
Definition miscadmin.h:392

Referenced by btmask_all_except_n(), and PostmasterStateMachine().

◆ BTYPE_MASK_NONE

const BackendTypeMask BTYPE_MASK_NONE = {0}
static

Definition at line 147 of file postmaster.c.

147{0};

Referenced by PostmasterStateMachine().

◆ CheckpointerPMChild

PMChild * CheckpointerPMChild = NULL
static

◆ ClientAuthInProgress

◆ connsAllowed

◆ enable_bonjour

bool enable_bonjour = false

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

Referenced by maybe_reap_io_worker(), and maybe_start_io_workers().

◆ io_worker_count

int io_worker_count = 0
static

◆ io_worker_launch_next_time

TimestampTz io_worker_launch_next_time = 0
static

Definition at line 413 of file postmaster.c.

Referenced by maybe_start_io_workers(), and maybe_start_io_workers_scheduled_at().

◆ ListenAddresses

char* ListenAddresses

Definition at line 210 of file postmaster.c.

Referenced by PostmasterMain().

◆ ListenSockets

◆ log_hostname

bool log_hostname

Definition at line 244 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 394 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 397 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 398 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 393 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 401 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 204 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

int PreAuthDelay = 0

Definition at line 241 of file postmaster.c.

Referenced by BackendInitialize().

◆ ReachedNormalRunning

bool ReachedNormalRunning = false
static

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

Referenced by PostmasterStateMachine().

◆ ReservedConnections

int ReservedConnections

Definition at line 231 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

bool restart_after_crash = true

Definition at line 248 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

bool send_abort_for_crash = false

Definition at line 257 of file postmaster.c.

Referenced by HandleFatalError().

◆ send_abort_for_kill

bool send_abort_for_kill = false

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

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ StartupPMChild

PMChild* StartupPMChild = NULL
static

◆ StartupStatus

◆ StartWorkerNeeded

◆ SuperuserReservedConnections

int SuperuserReservedConnections

Definition at line 230 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ SysLoggerPMChild

PMChild * SysLoggerPMChild = NULL
static

◆ Unix_socket_directories

char* Unix_socket_directories

Definition at line 207 of file postmaster.c.

Referenced by PostmasterMain().

◆ WalReceiverPMChild

PMChild * WalReceiverPMChild = NULL
static

◆ WalReceiverRequested

bool WalReceiverRequested = false
static

Definition at line 386 of file postmaster.c.

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ WalSummarizerPMChild

PMChild * WalSummarizerPMChild = NULL
static

◆ WalWriterPMChild

PMChild * WalWriterPMChild = NULL
static