PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/xlog.h"
#include "access/xlogrecovery.h"
#include "common/file_perm.h"
#include "common/pg_prng.h"
#include "lib/ilist.h"
#include "libpq/libpq.h"
#include "libpq/pqsignal.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "postmaster/walsummarizer.h"
#include "replication/logicallauncher.h"
#include "replication/slotsync.h"
#include "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pmsignal.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 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 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_SHUTDOWN ,
  PM_SHUTDOWN_2 , 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 (BackendTypeMask mask, BackendType t)
 
static BackendTypeMask btmask_del (BackendTypeMask mask, BackendType t)
 
static BackendTypeMask btmask_all_except (BackendType t)
 
static BackendTypeMask btmask_all_except2 (BackendType t1, BackendType t2)
 
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 ExitPostmaster (int status) pg_attribute_noreturn()
 
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 void sigquit_child (PMChild *pmchild)
 
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 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 bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

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

Macro Definition Documentation

◆ EXIT_STATUS_0

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

Definition at line 451 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 452 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 453 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 271 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 272 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 225 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 269 of file postmaster.c.

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 351 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 270 of file postmaster.c.

Enumeration Type Documentation

◆ PMState

enum PMState
Enumerator
PM_INIT 
PM_STARTUP 
PM_RECOVERY 
PM_HOT_STANDBY 
PM_RUN 
PM_STOP_BACKENDS 
PM_WAIT_BACKENDS 
PM_SHUTDOWN 
PM_SHUTDOWN_2 
PM_WAIT_DEAD_END 
PM_NO_CHILDREN 

Definition at line 319 of file postmaster.c.

320{
321 PM_INIT, /* postmaster starting */
322 PM_STARTUP, /* waiting for startup subprocess */
323 PM_RECOVERY, /* in archive recovery mode */
324 PM_HOT_STANDBY, /* in hot standby mode */
325 PM_RUN, /* normal "database is alive" state */
326 PM_STOP_BACKENDS, /* need to stop remaining backends */
327 PM_WAIT_BACKENDS, /* waiting for live backends to exit */
328 PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
329 * ckpt */
330 PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
331 * finish */
332 PM_WAIT_DEAD_END, /* waiting for dead-end children to exit */
333 PM_NO_CHILDREN, /* all important children have exited */
334} PMState;
PMState
Definition: postmaster.c:320
@ PM_RUN
Definition: postmaster.c:325
@ PM_HOT_STANDBY
Definition: postmaster.c:324
@ PM_WAIT_DEAD_END
Definition: postmaster.c:332
@ PM_RECOVERY
Definition: postmaster.c:323
@ PM_NO_CHILDREN
Definition: postmaster.c:333
@ PM_WAIT_BACKENDS
Definition: postmaster.c:327
@ PM_SHUTDOWN
Definition: postmaster.c:328
@ PM_STOP_BACKENDS
Definition: postmaster.c:326
@ PM_SHUTDOWN_2
Definition: postmaster.c:330
@ PM_INIT
Definition: postmaster.c:321
@ PM_STARTUP
Definition: postmaster.c:322

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 258 of file postmaster.c.

259{
262 STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
StartupStatusEnum
Definition: postmaster.c:259
@ STARTUP_SIGNALED
Definition: postmaster.c:262
@ STARTUP_CRASHED
Definition: postmaster.c:263
@ STARTUP_NOT_RUNNING
Definition: postmaster.c:260
@ STARTUP_RUNNING
Definition: postmaster.c:261

Function Documentation

◆ BackendStartup()

static int BackendStartup ( ClientSocket client_sock)
static

Definition at line 3341 of file postmaster.c.

3342{
3343 PMChild *bn = NULL;
3344 pid_t pid;
3345 BackendStartupData startup_data;
3346 CAC_state cac;
3347
3348 /*
3349 * Allocate and assign the child slot. Note we must do this before
3350 * forking, so that we can handle failures (out of memory or child-process
3351 * slots) cleanly.
3352 */
3354 if (cac == CAC_OK)
3355 {
3356 /* Can change later to B_WAL_SENDER */
3358 if (!bn)
3359 {
3360 /*
3361 * Too many regular child processes; launch a dead-end child
3362 * process instead.
3363 */
3364 cac = CAC_TOOMANY;
3365 }
3366 }
3367 if (!bn)
3368 {
3369 bn = AllocDeadEndChild();
3370 if (!bn)
3371 {
3372 ereport(LOG,
3373 (errcode(ERRCODE_OUT_OF_MEMORY),
3374 errmsg("out of memory")));
3375 return STATUS_ERROR;
3376 }
3377 }
3378
3379 /* Pass down canAcceptConnections state */
3380 startup_data.canAcceptConnections = cac;
3381 bn->rw = NULL;
3382
3383 /* Hasn't asked to be notified about any bgworkers yet */
3384 bn->bgworker_notify = false;
3385
3387 (char *) &startup_data, sizeof(startup_data),
3388 client_sock);
3389 if (pid < 0)
3390 {
3391 /* in parent, fork failed */
3392 int save_errno = errno;
3393
3394 (void) ReleasePostmasterChildSlot(bn);
3395 errno = save_errno;
3396 ereport(LOG,
3397 (errmsg("could not fork new process for connection: %m")));
3398 report_fork_failure_to_client(client_sock, save_errno);
3399 return STATUS_ERROR;
3400 }
3401
3402 /* in parent, successful fork */
3404 (errmsg_internal("forked new %s, pid=%d socket=%d",
3406 (int) pid, (int) client_sock->sock)));
3407
3408 /*
3409 * Everything's been successful, it's safe to add this backend to our list
3410 * of backends.
3411 */
3412 bn->pid = pid;
3413 return STATUS_OK;
3414}
CAC_state
@ CAC_TOOMANY
@ CAC_OK
#define STATUS_OK
Definition: c.h:1123
#define STATUS_ERROR
Definition: c.h:1124
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define DEBUG2
Definition: elog.h:29
#define ereport(elevel,...)
Definition: elog.h:149
pid_t postmaster_child_launch(BackendType child_type, int child_slot, char *startup_data, size_t startup_data_len, ClientSocket *client_sock)
@ B_BACKEND
Definition: miscadmin.h:341
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:263
PMChild * AssignPostmasterChildSlot(BackendType btype)
Definition: pmchild.c:161
bool ReleasePostmasterChildSlot(PMChild *pmchild)
Definition: pmchild.c:235
PMChild * AllocDeadEndChild(void)
Definition: pmchild.c:207
static CAC_state canAcceptConnections(BackendType backend_type)
Definition: postmaster.c:1782
static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
Definition: postmaster.c:3425
CAC_state canAcceptConnections
pgsocket sock
Definition: libpq-be.h:244
struct RegisteredBgWorker * rw
Definition: postmaster.h:45
bool bgworker_notify
Definition: postmaster.h:46
BackendType bkend_type
Definition: postmaster.h:44
pid_t pid
Definition: postmaster.h:42
int child_slot
Definition: postmaster.h:43

References AllocDeadEndChild(), AssignPostmasterChildSlot(), B_BACKEND, PMChild::bgworker_notify, PMChild::bkend_type, CAC_OK, CAC_TOOMANY, canAcceptConnections(), BackendStartupData::canAcceptConnections, PMChild::child_slot, DEBUG2, ereport, errcode(), errmsg(), errmsg_internal(), GetBackendTypeDesc(), LOG, PMChild::pid, postmaster_child_launch(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), PMChild::rw, ClientSocket::sock, 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 3915 of file postmaster.c.

3916{
3917 switch (pmState)
3918 {
3919 case PM_NO_CHILDREN:
3920 case PM_WAIT_DEAD_END:
3921 case PM_SHUTDOWN_2:
3922 case PM_SHUTDOWN:
3923 case PM_WAIT_BACKENDS:
3924 case PM_STOP_BACKENDS:
3925 break;
3926
3927 case PM_RUN:
3929 return true;
3930 /* fall through */
3931
3932 case PM_HOT_STANDBY:
3934 return true;
3935 /* fall through */
3936
3937 case PM_RECOVERY:
3938 case PM_STARTUP:
3939 case PM_INIT:
3941 return true;
3942 /* fall through */
3943 }
3944
3945 return false;
3946}
@ BgWorkerStart_RecoveryFinished
Definition: bgworker.h:81
@ BgWorkerStart_ConsistentState
Definition: bgworker.h:80
@ BgWorkerStart_PostmasterStart
Definition: bgworker.h:79
static time_t start_time
Definition: pg_ctl.c:95
static PMState pmState
Definition: postmaster.c:336

References BgWorkerStart_ConsistentState, BgWorkerStart_PostmasterStart, BgWorkerStart_RecoveryFinished, PM_HOT_STANDBY, PM_INIT, PM_NO_CHILDREN, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, pmState, and start_time.

Referenced by maybe_start_bgworkers().

◆ btmask()

static BackendTypeMask btmask ( BackendType  t)
inlinestatic

Definition at line 145 of file postmaster.c.

146{
147 BackendTypeMask mask = {.mask = 1 << t};
148
149 return mask;
150}

References BackendTypeMask::mask.

Referenced by PostmasterStateMachine(), and process_pm_child_exit().

◆ btmask_add()

static BackendTypeMask btmask_add ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 153 of file postmaster.c.

154{
155 mask.mask |= 1 << t;
156 return mask;
157}

References BackendTypeMask::mask.

Referenced by PostmasterStateMachine().

◆ btmask_all_except()

static BackendTypeMask btmask_all_except ( BackendType  t)
inlinestatic

Definition at line 167 of file postmaster.c.

168{
170
171 mask = btmask_del(mask, t);
172 return mask;
173}
static const BackendTypeMask BTYPE_MASK_ALL
Definition: postmaster.c:141
static BackendTypeMask btmask_del(BackendTypeMask mask, BackendType t)
Definition: postmaster.c:160

References btmask_del(), and BTYPE_MASK_ALL.

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

◆ btmask_all_except2()

static BackendTypeMask btmask_all_except2 ( BackendType  t1,
BackendType  t2 
)
inlinestatic

Definition at line 176 of file postmaster.c.

177{
179
180 mask = btmask_del(mask, t1);
181 mask = btmask_del(mask, t2);
182 return mask;
183}

References btmask_del(), and BTYPE_MASK_ALL.

Referenced by PostmasterStateMachine().

◆ btmask_contains()

static bool btmask_contains ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 186 of file postmaster.c.

187{
188 return (mask.mask & (1 << t)) != 0;
189}

References BackendTypeMask::mask.

Referenced by CountChildren(), and SignalChildren().

◆ btmask_del()

static BackendTypeMask btmask_del ( BackendTypeMask  mask,
BackendType  t 
)
inlinestatic

Definition at line 160 of file postmaster.c.

161{
162 mask.mask &= ~(1 << t);
163 return mask;
164}

References BackendTypeMask::mask.

Referenced by btmask_all_except(), and btmask_all_except2().

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( BackendType  backend_type)
static

Definition at line 1782 of file postmaster.c.

1783{
1784 CAC_state result = CAC_OK;
1785
1786 Assert(backend_type == B_BACKEND || backend_type == B_AUTOVAC_WORKER);
1787
1788 /*
1789 * Can't start backends when in startup/shutdown/inconsistent recovery
1790 * state. We treat autovac workers the same as user backends for this
1791 * purpose.
1792 */
1793 if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
1794 {
1795 if (Shutdown > NoShutdown)
1796 return CAC_SHUTDOWN; /* shutdown is pending */
1797 else if (!FatalError && pmState == PM_STARTUP)
1798 return CAC_STARTUP; /* normal startup */
1799 else if (!FatalError && pmState == PM_RECOVERY)
1800 return CAC_NOTCONSISTENT; /* not yet at consistent recovery
1801 * state */
1802 else
1803 return CAC_RECOVERY; /* else must be crash recovery */
1804 }
1805
1806 /*
1807 * "Smart shutdown" restrictions are applied only to normal connections,
1808 * not to autovac workers.
1809 */
1810 if (!connsAllowed && backend_type == B_BACKEND)
1811 return CAC_SHUTDOWN; /* shutdown is pending */
1812
1813 return result;
1814}
@ CAC_RECOVERY
@ CAC_NOTCONSISTENT
@ CAC_STARTUP
@ CAC_SHUTDOWN
#define Assert(condition)
Definition: c.h:812
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:344
static bool connsAllowed
Definition: postmaster.c:344
static int Shutdown
Definition: postmaster.c:274
#define NoShutdown
Definition: postmaster.c:269
static bool FatalError
Definition: postmaster.c:276

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

Referenced by BackendStartup(), and StartAutovacuumWorker().

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1486 of file postmaster.c.

1487{
1488 char path[MAXPGPATH];
1489 FILE *fp;
1490
1491 snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1492
1493 fp = AllocateFile(path, PG_BINARY_R);
1494 if (fp == NULL)
1495 {
1496 write_stderr("%s: could not find the database system\n"
1497 "Expected to find it in the directory \"%s\",\n"
1498 "but could not open file \"%s\": %m\n",
1499 progname, DataDir, path);
1500 ExitPostmaster(2);
1501 }
1502 FreeFile(fp);
1503}
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1229
int FreeFile(FILE *file)
Definition: fd.c:2803
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2605
char * DataDir
Definition: globals.c:70
const char * progname
Definition: main.c:44
#define MAXPGPATH
#define snprintf
Definition: port.h:238
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:3452

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

Referenced by PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( PMChild bp,
int  exitstatus 
)
static

Definition at line 2542 of file postmaster.c.

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

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

Referenced by process_pm_child_exit().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1827 of file postmaster.c.

1828{
1829 /* Release resources held by the postmaster's WaitEventSet. */
1830 if (pm_wait_set)
1831 {
1833 pm_wait_set = NULL;
1834 }
1835
1836#ifndef WIN32
1837
1838 /*
1839 * Close the write end of postmaster death watch pipe. It's important to
1840 * do this as early as possible, so that if postmaster dies, others won't
1841 * think that it's still running because we're holding the pipe open.
1842 */
1844 ereport(FATAL,
1846 errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1848 /* Notify fd.c that we released one pipe FD. */
1850#endif
1851
1852 /*
1853 * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1854 * so we don't call ReleaseExternalFD() here.
1855 *
1856 * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1857 * EXEC_BACKEND mode.
1858 */
1859#ifndef EXEC_BACKEND
1860 if (ListenSockets)
1861 {
1862 for (int i = 0; i < NumListenSockets; i++)
1863 {
1864 if (closesocket(ListenSockets[i]) != 0)
1865 elog(LOG, "could not close listen socket: %m");
1866 }
1868 }
1869 NumListenSockets = 0;
1870 ListenSockets = NULL;
1871#endif
1872
1873 /*
1874 * If using syslogger, close the read side of the pipe. We don't bother
1875 * tracking this in fd.c, either.
1876 */
1877 if (!am_syslogger)
1878 {
1879#ifndef WIN32
1880 if (syslogPipe[0] >= 0)
1881 close(syslogPipe[0]);
1882 syslogPipe[0] = -1;
1883#else
1884 if (syslogPipe[0])
1885 CloseHandle(syslogPipe[0]);
1886 syslogPipe[0] = 0;
1887#endif
1888 }
1889
1890#ifdef USE_BONJOUR
1891 /* If using Bonjour, close the connection to the mDNS daemon */
1892 if (bonjour_sdref)
1893 close(DNSServiceRefSockFD(bonjour_sdref));
1894#endif
1895}
int errcode_for_file_access(void)
Definition: elog.c:876
#define FATAL
Definition: elog.h:41
#define elog(elevel,...)
Definition: elog.h:225
void ReleaseExternalFD(void)
Definition: fd.c:1238
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:72
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:911
void pfree(void *pointer)
Definition: mcxt.c:1521
#define closesocket
Definition: port.h:349
static pgsocket * ListenSockets
Definition: postmaster.c:227
static int NumListenSockets
Definition: postmaster.c:226
int postmaster_alive_fds[2]
Definition: postmaster.c:460
static WaitEventSet * pm_wait_set
Definition: postmaster.c:382
#define POSTMASTER_FD_OWN
Definition: postmaster.h:85
int syslogPipe[2]
Definition: syslogger.c:114

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

Referenced by postmaster_child_launch().

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1386 of file postmaster.c.

1387{
1388 int i;
1389
1390 /*
1391 * First, explicitly close all the socket FDs. We used to just let this
1392 * happen implicitly at postmaster exit, but it's better to close them
1393 * before we remove the postmaster.pid lockfile; otherwise there's a race
1394 * condition if a new postmaster wants to re-use the TCP port number.
1395 */
1396 for (i = 0; i < NumListenSockets; i++)
1397 {
1398 if (closesocket(ListenSockets[i]) != 0)
1399 elog(LOG, "could not close listen socket: %m");
1400 }
1401 NumListenSockets = 0;
1402
1403 /*
1404 * Next, remove any filesystem entries for Unix sockets. To avoid race
1405 * conditions against incoming postmasters, this must happen after closing
1406 * the sockets and before removing lock files.
1407 */
1409
1410 /*
1411 * We don't do anything about socket lock files here; those will be
1412 * removed in a later on_proc_exit callback.
1413 */
1414}
void RemoveSocketFiles(void)
Definition: pqcomm.c:848

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

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1600 of file postmaster.c.

1601{
1602 if (pm_wait_set)
1604 pm_wait_set = NULL;
1605
1607 accept_connections ? (1 + NumListenSockets) : 1);
1609 NULL);
1610
1611 if (accept_connections)
1612 {
1613 for (int i = 0; i < NumListenSockets; i++)
1615 NULL, NULL);
1616 }
1617}
struct Latch * MyLatch
Definition: globals.c:62
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:957
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:868
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: latch.c:751
#define WL_SOCKET_ACCEPT
Definition: latch.h:144
#define WL_LATCH_SET
Definition: latch.h:127
#define PGINVALID_SOCKET
Definition: port.h:31

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

Referenced by PostmasterStateMachine(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( BackendTypeMask  targetMask)
static

Definition at line 3647 of file postmaster.c.

3648{
3649 dlist_iter iter;
3650 int cnt = 0;
3651
3653 {
3654 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3655
3656 /*
3657 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3658 * if any B_BACKEND backends have recently announced that they are
3659 * actually WAL senders.
3660 */
3661 if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3662 bp->bkend_type == B_BACKEND)
3663 {
3666 }
3667
3668 if (!btmask_contains(targetMask, bp->bkend_type))
3669 continue;
3670
3672 (errmsg_internal("%s process %d is still running",
3673 GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
3674
3675 cnt++;
3676 }
3677 return cnt;
3678}
#define DEBUG4
Definition: elog.h:27
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
@ B_WAL_SENDER
Definition: miscadmin.h:346
dlist_head ActiveChildList
Definition: pmchild.c:60
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:271
static bool btmask_contains(BackendTypeMask mask, BackendType t)
Definition: postmaster.c:186
dlist_node * cur
Definition: ilist.h:179

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

Referenced by PostmasterStateMachine().

◆ CreateOptsFile()

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

Definition at line 3812 of file postmaster.c.

3813{
3814 FILE *fp;
3815 int i;
3816
3817#define OPTS_FILE "postmaster.opts"
3818
3819 if ((fp = fopen(OPTS_FILE, "w")) == NULL)
3820 {
3821 ereport(LOG,
3823 errmsg("could not create file \"%s\": %m", OPTS_FILE)));
3824 return false;
3825 }
3826
3827 fprintf(fp, "%s", fullprogname);
3828 for (i = 1; i < argc; i++)
3829 fprintf(fp, " \"%s\"", argv[i]);
3830 fputs("\n", fp);
3831
3832 if (fclose(fp))
3833 {
3834 ereport(LOG,
3836 errmsg("could not write file \"%s\": %m", OPTS_FILE)));
3837 return false;
3838 }
3839
3840 return true;
3841}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
#define OPTS_FILE

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

Referenced by PostmasterMain().

◆ DetermineSleepTime()

static int DetermineSleepTime ( void  )
static

Definition at line 1515 of file postmaster.c.

1516{
1517 TimestampTz next_wakeup = 0;
1518
1519 /*
1520 * Normal case: either there are no background workers at all, or we're in
1521 * a shutdown sequence (during which we ignore bgworkers altogether).
1522 */
1523 if (Shutdown > NoShutdown ||
1525 {
1526 if (AbortStartTime != 0)
1527 {
1528 int seconds;
1529
1530 /* time left to abort; clamp to 0 in case it already expired */
1531 seconds = SIGKILL_CHILDREN_AFTER_SECS -
1532 (time(NULL) - AbortStartTime);
1533
1534 return Max(seconds * 1000, 0);
1535 }
1536 else
1537 return 60 * 1000;
1538 }
1539
1541 return 0;
1542
1544 {
1545 dlist_mutable_iter iter;
1546
1547 /*
1548 * When there are crashed bgworkers, we sleep just long enough that
1549 * they are restarted when they request to be. Scan the list to
1550 * determine the minimum of all wakeup times according to most recent
1551 * crash time and requested restart interval.
1552 */
1554 {
1556 TimestampTz this_wakeup;
1557
1558 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
1559
1560 if (rw->rw_crashed_at == 0)
1561 continue;
1562
1564 || rw->rw_terminate)
1565 {
1567 continue;
1568 }
1569
1571 1000L * rw->rw_worker.bgw_restart_time);
1572 if (next_wakeup == 0 || this_wakeup < next_wakeup)
1573 next_wakeup = this_wakeup;
1574 }
1575 }
1576
1577 if (next_wakeup != 0)
1578 {
1579 int ms;
1580
1581 /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1583 next_wakeup);
1584 return Min(60 * 1000, ms);
1585 }
1586
1587 return 60 * 1000;
1588}
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1756
dlist_head BackgroundWorkerList
Definition: bgworker.c:40
void ForgetBackgroundWorker(RegisteredBgWorker *rw)
Definition: bgworker.c:429
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Min(x, y)
Definition: c.h:958
#define Max(x, y)
Definition: c.h:952
int64 TimestampTz
Definition: timestamp.h:39
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:640
static time_t AbortStartTime
Definition: postmaster.c:348
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:351
static bool StartWorkerNeeded
Definition: postmaster.c:370
int bgw_restart_time
Definition: bgworker.h:95
dlist_node * cur
Definition: ilist.h:200
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85

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

Referenced by ServerLoop().

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 3639 of file postmaster.c.

3640{
3641}

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 3452 of file postmaster.c.

3453{
3454#ifdef HAVE_PTHREAD_IS_THREADED_NP
3455
3456 /*
3457 * There is no known cause for a postmaster to become multithreaded after
3458 * startup. Recheck to account for the possibility of unknown causes.
3459 * This message uses LOG level, because an unclean shutdown at this point
3460 * would usually not look much different from a clean shutdown.
3461 */
3462 if (pthread_is_threaded_np() != 0)
3463 ereport(LOG,
3464 (errcode(ERRCODE_INTERNAL_ERROR),
3465 errmsg_internal("postmaster became multithreaded"),
3466 errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
3467#endif
3468
3469 /* should cleanup shared memory and kill all backends */
3470
3471 /*
3472 * Not sure of the semantics here. When the Postmaster dies, should the
3473 * backends all be killed? probably not.
3474 *
3475 * MUST -- vadim 05-10-1999
3476 */
3477
3478 proc_exit(status);
3479}
int errdetail(const char *fmt,...)
Definition: elog.c:1203
void proc_exit(int code)
Definition: ipc.c:104

References ereport, errcode(), errdetail(), errmsg_internal(), LOG, and proc_exit().

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1432 of file postmaster.c.

1433{
1434 DIR *pdir;
1435
1436 /* Locate the postgres executable itself */
1438 ereport(FATAL,
1439 (errmsg("%s: could not locate my own executable path", argv0)));
1440
1441#ifdef EXEC_BACKEND
1442 /* Locate executable backend before we change working directory */
1444 postgres_exec_path) < 0)
1445 ereport(FATAL,
1446 (errmsg("%s: could not locate matching postgres executable",
1447 argv0)));
1448#endif
1449
1450 /*
1451 * Locate the pkglib directory --- this has to be set early in case we try
1452 * to load any modules from it in response to postgresql.conf entries.
1453 */
1455
1456 /*
1457 * Verify that there's a readable directory there; otherwise the Postgres
1458 * installation is incomplete or corrupt. (A typical cause of this
1459 * failure is that the postgres executable has been moved or hardlinked to
1460 * some directory that's not a sibling of the installation lib/
1461 * directory.)
1462 */
1463 pdir = AllocateDir(pkglib_path);
1464 if (pdir == NULL)
1465 ereport(ERROR,
1467 errmsg("could not open directory \"%s\": %m",
1468 pkglib_path),
1469 errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1470 my_exec_path)));
1471 FreeDir(pdir);
1472
1473 /*
1474 * It's not worth checking the share/ directory. If the lib/ directory is
1475 * there, then share/ probably is too.
1476 */
1477}
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:310
int errhint(const char *fmt,...)
Definition: elog.c:1317
#define ERROR
Definition: elog.h:39
int FreeDir(DIR *dir)
Definition: fd.c:2983
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2865
char pkglib_path[MAXPGPATH]
Definition: globals.c:81
char my_exec_path[MAXPGPATH]
Definition: globals.c:80
static char * argv0
Definition: pg_ctl.c:93
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879
#define PG_BACKEND_VERSIONSTR
Definition: port.h:143
Definition: dirent.c:26

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

Referenced by PostmasterMain().

◆ handle_pm_child_exit_signal()

static void handle_pm_child_exit_signal ( SIGNAL_ARGS  )
static

Definition at line 2194 of file postmaster.c.

2195{
2196 pending_pm_child_exit = true;
2198}
void SetLatch(Latch *latch)
Definition: latch.c:632
static volatile sig_atomic_t pending_pm_child_exit
Definition: postmaster.c:375

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

1947{
1948 pending_pm_pmsignal = true;
1950}
static volatile sig_atomic_t pending_pm_pmsignal
Definition: postmaster.c:374

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

1957{
1960}
static volatile sig_atomic_t pending_pm_reload_request
Definition: postmaster.c:376

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

2020{
2021 switch (postgres_signal_arg)
2022 {
2023 case SIGTERM:
2024 /* smart is implied if the other two flags aren't set */
2026 break;
2027 case SIGINT:
2030 break;
2031 case SIGQUIT:
2034 break;
2035 }
2037}
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition: postmaster.c:378
static volatile sig_atomic_t pending_pm_shutdown_request
Definition: postmaster.c:377
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition: postmaster.c:379
#define SIGQUIT
Definition: win32_port.h:169

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

Referenced by PostmasterMain().

◆ HandleChildCrash()

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

Definition at line 2672 of file postmaster.c.

2673{
2674 bool take_action;
2675
2676 /*
2677 * We only log messages and send signals if this is the first process
2678 * crash and we're not doing an immediate shutdown; otherwise, we're only
2679 * here to update postmaster's idea of live processes. If we have already
2680 * signaled children, nonzero exit status is to be expected, so don't
2681 * clutter log.
2682 */
2683 take_action = !FatalError && Shutdown != ImmediateShutdown;
2684
2685 if (take_action)
2686 {
2687 LogChildExit(LOG, procname, pid, exitstatus);
2688 ereport(LOG,
2689 (errmsg("terminating any other active server processes")));
2691 }
2692
2693 /*
2694 * Signal all other child processes to exit. The crashed process has
2695 * already been removed from ActiveChildList.
2696 */
2697 if (take_action)
2698 {
2699 dlist_iter iter;
2700
2702 {
2703 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
2704
2705 /* We do NOT restart the syslogger */
2706 if (bp == SysLoggerPMChild)
2707 continue;
2708
2709 if (bp == StartupPMChild)
2711
2712 /*
2713 * This backend is still alive. Unless we did so already, tell it
2714 * to commit hara-kiri.
2715 *
2716 * We could exclude dead-end children here, but at least when
2717 * sending SIGABRT it seems better to include them.
2718 */
2719 sigquit_child(bp);
2720 }
2721 }
2722
2724 FatalError = true;
2725
2726 /* We now transit into a state of waiting for children to die */
2727 if (pmState == PM_RECOVERY ||
2729 pmState == PM_RUN ||
2733
2734 /*
2735 * .. and if this doesn't happen quickly enough, now the clock is ticking
2736 * for us to kill them without mercy.
2737 */
2738 if (AbortStartTime == 0)
2739 AbortStartTime = time(NULL);
2740}
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:202
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
#define ImmediateShutdown
Definition: postmaster.c:272
static PMChild * StartupPMChild
Definition: postmaster.c:246
static PMChild * SysLoggerPMChild
Definition: postmaster.c:254
static StartupStatusEnum StartupStatus
Definition: postmaster.c:266
static void sigquit_child(PMChild *pmchild)
Definition: postmaster.c:3271

References AbortStartTime, ActiveChildList, dlist_iter::cur, dlist_container, dlist_foreach, ereport, errmsg(), FatalError, ImmediateShutdown, LOG, LogChildExit(), PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_CRASH, pmState, SetQuitSignalReason(), Shutdown, sigquit_child(), STARTUP_SIGNALED, StartupPMChild, StartupStatus, and SysLoggerPMChild.

Referenced by CleanupBackend(), and process_pm_child_exit().

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 4214 of file postmaster.c.

4215{
4216#ifndef WIN32
4217
4218 /*
4219 * Create a pipe. Postmaster holds the write end of the pipe open
4220 * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
4221 * the read file descriptor to select() to wake up in case postmaster
4222 * dies, or check for postmaster death with a (read() == 0). Children must
4223 * close the write end as soon as possible after forking, because EOF
4224 * won't be signaled in the read end until all processes have closed the
4225 * write fd. That is taken care of in ClosePostmasterPorts().
4226 */
4228 if (pipe(postmaster_alive_fds) < 0)
4229 ereport(FATAL,
4231 errmsg_internal("could not create pipe to monitor postmaster death: %m")));
4232
4233 /* Notify fd.c that we've eaten two FDs for the pipe. */
4236
4237 /*
4238 * Set O_NONBLOCK to allow testing for the fd's presence with a read()
4239 * call.
4240 */
4241 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
4242 ereport(FATAL,
4244 errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
4245#else
4246
4247 /*
4248 * On Windows, we use a process handle for the same purpose.
4249 */
4250 if (DuplicateHandle(GetCurrentProcess(),
4251 GetCurrentProcess(),
4252 GetCurrentProcess(),
4253 &PostmasterHandle,
4254 0,
4255 TRUE,
4256 DUPLICATE_SAME_ACCESS) == 0)
4257 ereport(FATAL,
4258 (errmsg_internal("could not duplicate postmaster handle: error code %lu",
4259 GetLastError())));
4260#endif /* WIN32 */
4261}
int errcode_for_socket_access(void)
Definition: elog.c:953
void ReserveExternalFD(void)
Definition: fd.c:1220
pid_t PostmasterPid
Definition: globals.c:105
int MyProcPid
Definition: globals.c:46
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:84

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

Referenced by PostmasterMain().

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 1904 of file postmaster.c.

1905{
1908
1909 /*
1910 * Set a different global seed in every process. We want something
1911 * unpredictable, so if possible, use high-quality random bits for the
1912 * seed. Otherwise, fall back to a seed based on timestamp and PID.
1913 */
1915 {
1916 uint64 rseed;
1917
1918 /*
1919 * Since PIDs and timestamps tend to change more frequently in their
1920 * least significant bits, shift the timestamp left to allow a larger
1921 * total number of seeds in a given time period. Since that would
1922 * leave only 20 bits of the timestamp that cycle every ~1 second,
1923 * also mix in some higher bits.
1924 */
1925 rseed = ((uint64) MyProcPid) ^
1926 ((uint64) MyStartTimestamp << 12) ^
1927 ((uint64) MyStartTimestamp >> 20);
1928
1930 }
1931
1932 /*
1933 * Also make sure that we've set a good seed for random(3). Use of that
1934 * is deprecated in core Postgres, but extensions might use it.
1935 */
1936#ifndef WIN32
1938#endif
1939}
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1823
uint64_t uint64
Definition: c.h:486
#define unlikely(x)
Definition: c.h:330
TimestampTz MyStartTimestamp
Definition: globals.c:48
pg_time_t MyStartTime
Definition: globals.c:47
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:227
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define pg_prng_strong_seed(state)
Definition: pg_prng.h:46

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

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

◆ LaunchMissingBackgroundProcesses()

static void LaunchMissingBackgroundProcesses ( void  )
static

Definition at line 3118 of file postmaster.c.

3119{
3120 /* Syslogger is active in all states */
3121 if (SysLoggerPMChild == NULL && Logging_collector)
3123
3124 /*
3125 * The checkpointer and the background writer are active from the start,
3126 * until shutdown is initiated.
3127 *
3128 * (If the checkpointer is not running when we enter the PM_SHUTDOWN
3129 * state, it is launched one more time to perform the shutdown checkpoint.
3130 * That's done in PostmasterStateMachine(), not here.)
3131 */
3132 if (pmState == PM_RUN || pmState == PM_RECOVERY ||
3134 {
3135 if (CheckpointerPMChild == NULL)
3137 if (BgWriterPMChild == NULL)
3139 }
3140
3141 /*
3142 * WAL writer is needed only in normal operation (else we cannot be
3143 * writing any new WAL).
3144 */
3145 if (WalWriterPMChild == NULL && pmState == PM_RUN)
3147
3148 /*
3149 * We don't want autovacuum to run in binary upgrade mode because
3150 * autovacuum might update relfrozenxid for empty tables before the
3151 * physical files are put in place.
3152 */
3153 if (!IsBinaryUpgrade && AutoVacLauncherPMChild == NULL &&
3155 pmState == PM_RUN)
3156 {
3158 if (AutoVacLauncherPMChild != NULL)
3159 start_autovac_launcher = false; /* signal processed */
3160 }
3161
3162 /*
3163 * If WAL archiving is enabled always, we are allowed to start archiver
3164 * even during recovery.
3165 */
3166 if (PgArchPMChild == NULL &&
3167 ((XLogArchivingActive() && pmState == PM_RUN) ||
3171
3172 /*
3173 * If we need to start a slot sync worker, try to do that now
3174 *
3175 * We allow to start the slot sync worker when we are on a hot standby,
3176 * fast or immediate shutdown is not in progress, slot sync parameters are
3177 * configured correctly, and it is the first time of worker's launch, or
3178 * enough time has passed since the worker was launched last.
3179 */
3180 if (SlotSyncWorkerPMChild == NULL && pmState == PM_HOT_STANDBY &&
3184
3185 /*
3186 * If we need to start a WAL receiver, try to do that now
3187 *
3188 * Note: if a walreceiver process is already running, it might seem that
3189 * we should clear WalReceiverRequested. However, there's a race
3190 * condition if the walreceiver terminates and the startup process
3191 * immediately requests a new one: it's quite possible to get the signal
3192 * for the request before reaping the dead walreceiver process. Better to
3193 * risk launching an extra walreceiver than to miss launching one we need.
3194 * (The walreceiver code has logic to recognize that it should go away if
3195 * not needed.)
3196 */
3198 {
3199 if (WalReceiverPMChild == NULL &&
3201 pmState == PM_HOT_STANDBY) &&
3203 {
3205 if (WalReceiverPMChild != 0)
3206 WalReceiverRequested = false;
3207 /* else leave the flag set, so we'll try again later */
3208 }
3209 }
3210
3211 /* If we need to start a WAL summarizer, try to do that now */
3212 if (summarize_wal && WalSummarizerPMChild == NULL &&
3213 (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
3216
3217 /* Get other worker processes running, if needed */
3220}
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3195
bool IsBinaryUpgrade
Definition: globals.c:120
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:365
@ B_WAL_WRITER
Definition: miscadmin.h:366
@ B_WAL_RECEIVER
Definition: miscadmin.h:364
@ B_CHECKPOINTER
Definition: miscadmin.h:362
@ B_BG_WRITER
Definition: miscadmin.h:361
@ B_ARCHIVER
Definition: miscadmin.h:360
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:343
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:347
bool PgArchCanRestart(void)
Definition: pgarch.c:195
#define SmartShutdown
Definition: postmaster.c:270
static PMChild * PgArchPMChild
Definition: postmaster.c:253
static void maybe_start_bgworkers(void)
Definition: postmaster.c:3960
static void StartSysLogger(void)
Definition: postmaster.c:3737
static PMChild * AutoVacLauncherPMChild
Definition: postmaster.c:252
static PMChild * BgWriterPMChild
Definition: postmaster.c:247
static PMChild * StartChildProcess(BackendType type)
Definition: postmaster.c:3691
static bool start_autovac_launcher
Definition: postmaster.c:361
static PMChild * WalReceiverPMChild
Definition: postmaster.c:250
static PMChild * WalWriterPMChild
Definition: postmaster.c:249
static PMChild * WalSummarizerPMChild
Definition: postmaster.c:251
static bool WalReceiverRequested
Definition: postmaster.c:367
static PMChild * CheckpointerPMChild
Definition: postmaster.c:248
static PMChild * SlotSyncWorkerPMChild
Definition: postmaster.c:255
bool sync_replication_slots
Definition: slotsync.c:107
bool SlotSyncWorkerCanRestart(void)
Definition: slotsync.c:1629
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1037
bool Logging_collector
Definition: syslogger.c:70
bool summarize_wal
#define XLogArchivingActive()
Definition: xlog.h:99
#define XLogArchivingAlways()
Definition: xlog.h:102

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

Referenced by ServerLoop().

◆ LogChildExit()

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

Definition at line 2746 of file postmaster.c.

2747{
2748 /*
2749 * size of activity_buffer is arbitrary, but set equal to default
2750 * track_activity_query_size
2751 */
2752 char activity_buffer[1024];
2753 const char *activity = NULL;
2754
2755 if (!EXIT_STATUS_0(exitstatus))
2757 activity_buffer,
2758 sizeof(activity_buffer));
2759
2760 if (WIFEXITED(exitstatus))
2761 ereport(lev,
2762
2763 /*------
2764 translator: %s is a noun phrase describing a child process, such as
2765 "server process" */
2766 (errmsg("%s (PID %d) exited with exit code %d",
2767 procname, pid, WEXITSTATUS(exitstatus)),
2768 activity ? errdetail("Failed process was running: %s", activity) : 0));
2769 else if (WIFSIGNALED(exitstatus))
2770 {
2771#if defined(WIN32)
2772 ereport(lev,
2773
2774 /*------
2775 translator: %s is a noun phrase describing a child process, such as
2776 "server process" */
2777 (errmsg("%s (PID %d) was terminated by exception 0x%X",
2778 procname, pid, WTERMSIG(exitstatus)),
2779 errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
2780 activity ? errdetail("Failed process was running: %s", activity) : 0));
2781#else
2782 ereport(lev,
2783
2784 /*------
2785 translator: %s is a noun phrase describing a child process, such as
2786 "server process" */
2787 (errmsg("%s (PID %d) was terminated by signal %d: %s",
2788 procname, pid, WTERMSIG(exitstatus),
2789 pg_strsignal(WTERMSIG(exitstatus))),
2790 activity ? errdetail("Failed process was running: %s", activity) : 0));
2791#endif
2792 }
2793 else
2794 ereport(lev,
2795
2796 /*------
2797 translator: %s is a noun phrase describing a child process, such as
2798 "server process" */
2799 (errmsg("%s (PID %d) exited with unrecognized status %d",
2800 procname, pid, exitstatus),
2801 activity ? errdetail("Failed process was running: %s", activity) : 0));
2802}
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:39
#define WIFEXITED(w)
Definition: win32_port.h:152
#define WIFSIGNALED(w)
Definition: win32_port.h:153
#define WTERMSIG(w)
Definition: win32_port.h:155
#define WEXITSTATUS(w)
Definition: win32_port.h:154

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

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

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 3960 of file postmaster.c.

3961{
3962#define MAX_BGWORKERS_TO_LAUNCH 100
3963 int num_launched = 0;
3964 TimestampTz now = 0;
3965 dlist_mutable_iter iter;
3966
3967 /*
3968 * During crash recovery, we have no need to be called until the state
3969 * transition out of recovery.
3970 */
3971 if (FatalError)
3972 {
3973 StartWorkerNeeded = false;
3974 HaveCrashedWorker = false;
3975 return;
3976 }
3977
3978 /* Don't need to be called again unless we find a reason for it below */
3979 StartWorkerNeeded = false;
3980 HaveCrashedWorker = false;
3981
3983 {
3985
3986 rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3987
3988 /* ignore if already running */
3989 if (rw->rw_pid != 0)
3990 continue;
3991
3992 /* if marked for death, clean up and remove from list */
3993 if (rw->rw_terminate)
3994 {
3996 continue;
3997 }
3998
3999 /*
4000 * If this worker has crashed previously, maybe it needs to be
4001 * restarted (unless on registration it specified it doesn't want to
4002 * be restarted at all). Check how long ago did a crash last happen.
4003 * If the last crash is too recent, don't start it right away; let it
4004 * be restarted once enough time has passed.
4005 */
4006 if (rw->rw_crashed_at != 0)
4007 {
4009 {
4010 int notify_pid;
4011
4012 notify_pid = rw->rw_worker.bgw_notify_pid;
4013
4015
4016 /* Report worker is gone now. */
4017 if (notify_pid != 0)
4018 kill(notify_pid, SIGUSR1);
4019
4020 continue;
4021 }
4022
4023 /* read system time only when needed */
4024 if (now == 0)
4026
4028 rw->rw_worker.bgw_restart_time * 1000))
4029 {
4030 /* Set flag to remember that we have workers to start later */
4031 HaveCrashedWorker = true;
4032 continue;
4033 }
4034 }
4035
4037 {
4038 /* reset crash time before trying to start worker */
4039 rw->rw_crashed_at = 0;
4040
4041 /*
4042 * Try to start the worker.
4043 *
4044 * On failure, give up processing workers for now, but set
4045 * StartWorkerNeeded so we'll come back here on the next iteration
4046 * of ServerLoop to try again. (We don't want to wait, because
4047 * there might be additional ready-to-run workers.) We could set
4048 * HaveCrashedWorker as well, since this worker is now marked
4049 * crashed, but there's no need because the next run of this
4050 * function will do that.
4051 */
4052 if (!StartBackgroundWorker(rw))
4053 {
4054 StartWorkerNeeded = true;
4055 return;
4056 }
4057
4058 /*
4059 * If we've launched as many workers as allowed, quit, but have
4060 * ServerLoop call us again to look for additional ready-to-run
4061 * workers. There might not be any, but we'll find out the next
4062 * time we run.
4063 */
4064 if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
4065 {
4066 StartWorkerNeeded = true;
4067 return;
4068 }
4069 }
4070 }
4071}
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1780
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1608
static bool StartBackgroundWorker(RegisteredBgWorker *rw)
Definition: postmaster.c:3854
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:3915
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
pid_t bgw_notify_pid
Definition: bgworker.h:100
#define kill(pid, sig)
Definition: win32_port.h:503
#define SIGUSR1
Definition: win32_port.h:180

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

Referenced by LaunchMissingBackgroundProcesses(), and PostmasterMain().

◆ PostmasterMain()

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

Definition at line 470 of file postmaster.c.

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

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, appendStringInfo(), appendStringInfoString(), ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, BgWriterPMChild, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPMChild, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), StringInfoData::data, DEBUG3, DestNone, DISPATCH_POSTMASTER, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, err(), errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), HbaFileName, InitializeFastPathLocks(), InitializeGUCOptions(), InitializeLatchSupport(), InitializeMaxBackends(), InitializeShmemGUCs(), 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(), MemoryContextSwitchTo(), message_level_is_interesting(), my_exec_path, MyProcPid, name, NIL, NumListenSockets, on_proc_exit(), optarg, opterr, optind, palloc(), parse_dispatch_option(), ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGC_S_OVERRIDE, PGC_SUSET, PgStartTime, pgwin32_signal_initialize(), PM_STARTUP, PM_STATUS_STARTING, pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), process_shared_preload_libraries(), process_shmem_requests(), progname, pstrdup(), RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedConnections, S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartChildProcess(), StartSysLogger(), STARTUP_RUNNING, StartupPMChild, StartupStatus, STATUS_OK, success, summarize_wal, SuperuserReservedConnections, TopMemoryContext, UnBlockSig, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 4079 of file postmaster.c.

4080{
4081 dlist_iter iter;
4082 PMChild *bp;
4083
4085 {
4086 bp = dlist_container(PMChild, elem, iter.cur);
4087 if (bp->pid == pid)
4088 {
4089 bp->bgworker_notify = true;
4090 return true;
4091 }
4092 }
4093 return false;
4094}

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

Referenced by BackgroundWorkerStateChange().

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 2812 of file postmaster.c.

2813{
2814 /* If we're doing a smart shutdown, try to advance that state. */
2815 if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2816 {
2817 if (!connsAllowed)
2818 {
2819 /*
2820 * This state ends when we have no normal client backends running.
2821 * Then we're ready to stop other children.
2822 */
2823 if (CountChildren(btmask(B_BACKEND)) == 0)
2825 }
2826 }
2827
2828 /*
2829 * In the PM_WAIT_BACKENDS state, wait for all the regular backends and
2830 * procesess like autovacuum and background workers that are comparable to
2831 * backends to exit.
2832 *
2833 * PM_STOP_BACKENDS is a transient state that means the same as
2834 * PM_WAIT_BACKENDS, but we signal the processes first, before waiting for
2835 * them. Treating it as a distinct pmState allows us to share this code
2836 * across multiple shutdown code paths.
2837 */
2839 {
2840 BackendTypeMask targetMask = BTYPE_MASK_NONE;
2841
2842 /*
2843 * PM_WAIT_BACKENDS state ends when we have no regular backends, no
2844 * autovac launcher or workers, and no bgworkers (including
2845 * unconnected ones). No walwriter, bgwriter, slot sync worker, or
2846 * WAL summarizer either.
2847 */
2848 targetMask = btmask_add(targetMask, B_BACKEND);
2849 targetMask = btmask_add(targetMask, B_AUTOVAC_LAUNCHER);
2850 targetMask = btmask_add(targetMask, B_AUTOVAC_WORKER);
2851 targetMask = btmask_add(targetMask, B_BG_WORKER);
2852
2853 targetMask = btmask_add(targetMask, B_WAL_WRITER);
2854 targetMask = btmask_add(targetMask, B_BG_WRITER);
2855 targetMask = btmask_add(targetMask, B_SLOTSYNC_WORKER);
2856 targetMask = btmask_add(targetMask, B_WAL_SUMMARIZER);
2857
2858 /* If we're in recovery, also stop startup and walreceiver procs */
2859 targetMask = btmask_add(targetMask, B_STARTUP);
2860 targetMask = btmask_add(targetMask, B_WAL_RECEIVER);
2861
2862 /*
2863 * If we are doing crash recovery or an immediate shutdown then we
2864 * expect the checkpointer to exit as well, otherwise not.
2865 */
2867 targetMask = btmask_add(targetMask, B_CHECKPOINTER);
2868
2869 /*
2870 * Walsenders and archiver will continue running; they will be
2871 * terminated later after writing the checkpoint record. We also let
2872 * dead-end children to keep running for now. The syslogger process
2873 * exits last.
2874 *
2875 * This assertion checks that we have covered all backend types,
2876 * either by including them in targetMask, or by noting here that they
2877 * are allowed to continue running.
2878 */
2879#ifdef USE_ASSERT_CHECKING
2880 {
2881 BackendTypeMask remainMask = BTYPE_MASK_NONE;
2882
2883 remainMask = btmask_add(remainMask, B_WAL_SENDER);
2884 remainMask = btmask_add(remainMask, B_ARCHIVER);
2885 remainMask = btmask_add(remainMask, B_DEAD_END_BACKEND);
2886 remainMask = btmask_add(remainMask, B_LOGGER);
2887
2888 /* checkpointer may or may not be in targetMask already */
2889 remainMask = btmask_add(remainMask, B_CHECKPOINTER);
2890
2891 /* these are not real postmaster children */
2892 remainMask = btmask_add(remainMask, B_INVALID);
2893 remainMask = btmask_add(remainMask, B_STANDALONE_BACKEND);
2894
2895 /* All types should be included in targetMask or remainMask */
2896 Assert((remainMask.mask | targetMask.mask) == BTYPE_MASK_ALL.mask);
2897 }
2898#endif
2899
2900 /* If we had not yet signaled the processes to exit, do so now */
2902 {
2903 /*
2904 * Forget any pending requests for background workers, since we're
2905 * no longer willing to launch any new workers. (If additional
2906 * requests arrive, BackgroundWorkerStateChange will reject them.)
2907 */
2909
2910 SignalChildren(SIGTERM, targetMask);
2911
2913 }
2914
2915 /* Are any of the target processes still running? */
2916 if (CountChildren(targetMask) == 0)
2917 {
2919 {
2920 /*
2921 * Stop any dead-end children and stop creating new ones.
2922 */
2926
2927 /*
2928 * We already SIGQUIT'd walsenders and the archiver, if any,
2929 * when we started immediate shutdown or entered FatalError
2930 * state.
2931 */
2932 }
2933 else
2934 {
2935 /*
2936 * If we get here, we are proceeding with normal shutdown. All
2937 * the regular children are gone, and it's time to tell the
2938 * checkpointer to do a shutdown checkpoint.
2939 */
2941 /* Start the checkpointer if not running */
2942 if (CheckpointerPMChild == NULL)
2944 /* And tell it to shut down */
2945 if (CheckpointerPMChild != NULL)
2946 {
2949 }
2950 else
2951 {
2952 /*
2953 * If we failed to fork a checkpointer, just shut down.
2954 * Any required cleanup will happen at next restart. We
2955 * set FatalError so that an "abnormal shutdown" message
2956 * gets logged when we exit.
2957 *
2958 * We don't consult send_abort_for_crash here, as it's
2959 * unlikely that dumping cores would illuminate the reason
2960 * for checkpointer fork failure.
2961 */
2962 FatalError = true;
2965
2966 /* Kill the walsenders and archiver too */
2968 }
2969 }
2970 }
2971 }
2972
2973 if (pmState == PM_SHUTDOWN_2)
2974 {
2975 /*
2976 * PM_SHUTDOWN_2 state ends when there's no other children than
2977 * dead-end children left. There shouldn't be any regular backends
2978 * left by now anyway; what we're really waiting for is walsenders and
2979 * archiver.
2980 */
2982 {
2986 }
2987 }
2988
2990 {
2991 /*
2992 * PM_WAIT_DEAD_END state ends when all other children are gone except
2993 * for the logger. During normal shutdown, all that remains are
2994 * dead-end backends, but in FatalError processing we jump straight
2995 * here with more processes remaining. Note that they have already
2996 * been sent appropriate shutdown signals, either during a normal
2997 * state transition leading up to PM_WAIT_DEAD_END, or during
2998 * FatalError processing.
2999 *
3000 * The reason we wait is to protect against a new postmaster starting
3001 * conflicting subprocesses; this isn't an ironclad protection, but it
3002 * at least helps in the shutdown-and-immediately-restart scenario.
3003 */
3005 {
3006 /* These other guys should be dead already */
3007 Assert(StartupPMChild == NULL);
3008 Assert(WalReceiverPMChild == NULL);
3010 Assert(BgWriterPMChild == NULL);
3011 Assert(CheckpointerPMChild == NULL);
3012 Assert(WalWriterPMChild == NULL);
3015 /* syslogger is not considered here */
3017 }
3018 }
3019
3020 /*
3021 * If we've been told to shut down, we exit as soon as there are no
3022 * remaining children. If there was a crash, cleanup will occur at the
3023 * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3024 * crash before exiting, but that seems unwise if we are quitting because
3025 * we got SIGTERM from init --- there may well not be time for recovery
3026 * before init decides to SIGKILL us.)
3027 *
3028 * Note that the syslogger continues to run. It will exit when it sees
3029 * EOF on its input pipe, which happens when there are no more upstream
3030 * processes.
3031 */
3033 {
3034 if (FatalError)
3035 {
3036 ereport(LOG, (errmsg("abnormal database system shutdown")));
3037 ExitPostmaster(1);
3038 }
3039 else
3040 {
3041 /*
3042 * Normal exit from the postmaster is here. We don't need to log
3043 * anything here, since the UnlinkLockFiles proc_exit callback
3044 * will do so, and that should be the last user-visible action.
3045 */
3046 ExitPostmaster(0);
3047 }
3048 }
3049
3050 /*
3051 * If the startup process failed, or the user does not want an automatic
3052 * restart after backend crashes, wait for all non-syslogger children to
3053 * exit, and then exit postmaster. We don't try to reinitialize when the
3054 * startup process fails, because more than likely it will just fail again
3055 * and we will keep trying forever.
3056 */
3057 if (pmState == PM_NO_CHILDREN)
3058 {
3060 {
3061 ereport(LOG,
3062 (errmsg("shutting down due to startup process failure")));
3063 ExitPostmaster(1);
3064 }
3066 {
3067 ereport(LOG,
3068 (errmsg("shutting down because \"restart_after_crash\" is off")));
3069 ExitPostmaster(1);
3070 }
3071 }
3072
3073 /*
3074 * If we need to recover from a crash, wait for all non-syslogger children
3075 * to exit, then reset shmem and start the startup process.
3076 */
3078 {
3079 ereport(LOG,
3080 (errmsg("all server processes terminated; reinitializing")));
3081
3082 /* remove leftover temporary files after a crash */
3085
3086 /* allow background workers to immediately restart */
3088
3089 shmem_exit(1);
3090
3091 /* re-read control file into local memory */
3093
3094 /* re-create shared memory and semaphores */
3096
3098 Assert(StartupPMChild != NULL);
3101 /* crash recovery started, reset SIGKILL flag */
3102 AbortStartTime = 0;
3103
3104 /* start accepting server socket connection events again */
3106 }
3107}
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:579
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:541
void shmem_exit(int code)
Definition: ipc.c:228
@ B_LOGGER
Definition: miscadmin.h:372
@ B_INVALID
Definition: miscadmin.h:338
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:349
@ B_DEAD_END_BACKEND
Definition: miscadmin.h:342
static int CountChildren(BackendTypeMask targetMask)
Definition: postmaster.c:3647
static BackendTypeMask btmask_all_except2(BackendType t1, BackendType t2)
Definition: postmaster.c:176
static BackendTypeMask btmask_all_except(BackendType t)
Definition: postmaster.c:167
static const BackendTypeMask BTYPE_MASK_NONE
Definition: postmaster.c:142
bool remove_temp_files_after_crash
Definition: postmaster.c:241
bool restart_after_crash
Definition: postmaster.c:240
static void signal_child(PMChild *pmchild, int signal)
Definition: postmaster.c:3239
static bool SignalChildren(int signal, BackendTypeMask targetMask)
Definition: postmaster.c:3284
static BackendTypeMask btmask_add(BackendTypeMask mask, BackendType t)
Definition: postmaster.c:153
static BackendTypeMask btmask(BackendType t)
Definition: postmaster.c:145
static void ConfigurePostmasterWaitSet(bool accept_connections)
Definition: postmaster.c:1600

References AbortStartTime, Assert, AutoVacLauncherPMChild, B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_DEAD_END_BACKEND, B_INVALID, B_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(), btmask_all_except2(), BTYPE_MASK_ALL, BTYPE_MASK_NONE, CheckpointerPMChild, ConfigurePostmasterWaitSet(), connsAllowed, CountChildren(), CreateSharedMemoryAndSemaphores(), ereport, errmsg(), ExitPostmaster(), FatalError, ForgetUnstartedBackgroundWorkers(), ImmediateShutdown, LocalProcessControlFile(), LOG, BackendTypeMask::mask, NoShutdown, PM_HOT_STANDBY, PM_NO_CHILDREN, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, pmState, remove_temp_files_after_crash, RemovePgTempFiles(), ResetBackgroundWorkerCrashTimes(), restart_after_crash, shmem_exit(), Shutdown, signal_child(), SignalChildren(), SIGQUIT, SIGUSR2, SlotSyncWorkerPMChild, StartChildProcess(), STARTUP_CRASHED, STARTUP_RUNNING, StartupPMChild, StartupStatus, 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 2204 of file postmaster.c.

2205{
2206 int pid; /* process id of dead child process */
2207 int exitstatus; /* its exit status */
2208
2209 pending_pm_child_exit = false;
2210
2212 (errmsg_internal("reaping dead processes")));
2213
2214 while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2215 {
2216 PMChild *pmchild;
2217
2218 /*
2219 * Check if this child was a startup process.
2220 */
2221 if (StartupPMChild && pid == StartupPMChild->pid)
2222 {
2224 StartupPMChild = NULL;
2225
2226 /*
2227 * Startup process exited in response to a shutdown request (or it
2228 * completed normally regardless of the shutdown request).
2229 */
2230 if (Shutdown > NoShutdown &&
2231 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2232 {
2235 /* PostmasterStateMachine logic does the rest */
2236 continue;
2237 }
2238
2239 if (EXIT_STATUS_3(exitstatus))
2240 {
2241 ereport(LOG,
2242 (errmsg("shutdown at recovery target")));
2245 TerminateChildren(SIGTERM);
2247 /* PostmasterStateMachine logic does the rest */
2248 continue;
2249 }
2250
2251 /*
2252 * Unexpected exit of startup process (including FATAL exit)
2253 * during PM_STARTUP is treated as catastrophic. There are no
2254 * other processes running yet, so we can just exit.
2255 */
2256 if (pmState == PM_STARTUP &&
2258 !EXIT_STATUS_0(exitstatus))
2259 {
2260 LogChildExit(LOG, _("startup process"),
2261 pid, exitstatus);
2262 ereport(LOG,
2263 (errmsg("aborting startup due to startup process failure")));
2264 ExitPostmaster(1);
2265 }
2266
2267 /*
2268 * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2269 * the startup process is catastrophic, so kill other children,
2270 * and set StartupStatus so we don't try to reinitialize after
2271 * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
2272 * then we previously sent the startup process a SIGQUIT; so
2273 * that's probably the reason it died, and we do want to try to
2274 * restart in that case.
2275 *
2276 * This stanza also handles the case where we sent a SIGQUIT
2277 * during PM_STARTUP due to some dead-end child crashing: in that
2278 * situation, if the startup process dies on the SIGQUIT, we need
2279 * to transition to PM_WAIT_BACKENDS state which will allow
2280 * PostmasterStateMachine to restart the startup process. (On the
2281 * other hand, the startup process might complete normally, if we
2282 * were too late with the SIGQUIT. In that case we'll fall
2283 * through and commence normal operations.)
2284 */
2285 if (!EXIT_STATUS_0(exitstatus))
2286 {
2288 {
2290 if (pmState == PM_STARTUP)
2292 }
2293 else
2295 HandleChildCrash(pid, exitstatus,
2296 _("startup process"));
2297 continue;
2298 }
2299
2300 /*
2301 * Startup succeeded, commence normal operations
2302 */
2304 FatalError = false;
2305 AbortStartTime = 0;
2306 ReachedNormalRunning = true;
2307 pmState = PM_RUN;
2308 connsAllowed = true;
2309
2310 /*
2311 * At the next iteration of the postmaster's main loop, we will
2312 * crank up the background tasks like the autovacuum launcher and
2313 * background workers that were not started earlier already.
2314 */
2315 StartWorkerNeeded = true;
2316
2317 /* at this point we are really open for business */
2318 ereport(LOG,
2319 (errmsg("database system is ready to accept connections")));
2320
2321 /* Report status */
2323#ifdef USE_SYSTEMD
2324 sd_notify(0, "READY=1");
2325#endif
2326
2327 continue;
2328 }
2329
2330 /*
2331 * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2332 * one at the next iteration of the postmaster's main loop, if
2333 * necessary. Any other exit condition is treated as a crash.
2334 */
2335 if (BgWriterPMChild && pid == BgWriterPMChild->pid)
2336 {
2338 BgWriterPMChild = NULL;
2339 if (!EXIT_STATUS_0(exitstatus))
2340 HandleChildCrash(pid, exitstatus,
2341 _("background writer process"));
2342 continue;
2343 }
2344
2345 /*
2346 * Was it the checkpointer?
2347 */
2349 {
2351 CheckpointerPMChild = NULL;
2352 if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2353 {
2354 /*
2355 * OK, we saw normal exit of the checkpointer after it's been
2356 * told to shut down. We expect that it wrote a shutdown
2357 * checkpoint. (If for some reason it didn't, recovery will
2358 * occur on next postmaster start.)
2359 *
2360 * At this point we should have no normal backend children
2361 * left (else we'd not be in PM_SHUTDOWN state) but we might
2362 * have dead-end children to wait for.
2363 *
2364 * If we have an archiver subprocess, tell it to do a last
2365 * archive cycle and quit. Likewise, if we have walsender
2366 * processes, tell them to send any remaining WAL and quit.
2367 */
2369
2370 /* Waken archiver for the last time */
2371 if (PgArchPMChild != NULL)
2373
2374 /*
2375 * Waken walsenders for the last time. No regular backends
2376 * should be around anymore.
2377 */
2379
2381 }
2382 else
2383 {
2384 /*
2385 * Any unexpected exit of the checkpointer (including FATAL
2386 * exit) is treated as a crash.
2387 */
2388 HandleChildCrash(pid, exitstatus,
2389 _("checkpointer process"));
2390 }
2391
2392 continue;
2393 }
2394
2395 /*
2396 * Was it the wal writer? Normal exit can be ignored; we'll start a
2397 * new one at the next iteration of the postmaster's main loop, if
2398 * necessary. Any other exit condition is treated as a crash.
2399 */
2400 if (WalWriterPMChild && pid == WalWriterPMChild->pid)
2401 {
2403 WalWriterPMChild = NULL;
2404 if (!EXIT_STATUS_0(exitstatus))
2405 HandleChildCrash(pid, exitstatus,
2406 _("WAL writer process"));
2407 continue;
2408 }
2409
2410 /*
2411 * Was it the wal receiver? If exit status is zero (normal) or one
2412 * (FATAL exit), we assume everything is all right just like normal
2413 * backends. (If we need a new wal receiver, we'll start one at the
2414 * next iteration of the postmaster's main loop.)
2415 */
2417 {
2419 WalReceiverPMChild = NULL;
2420 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2421 HandleChildCrash(pid, exitstatus,
2422 _("WAL receiver process"));
2423 continue;
2424 }
2425
2426 /*
2427 * Was it the wal summarizer? Normal exit can be ignored; we'll start
2428 * a new one at the next iteration of the postmaster's main loop, if
2429 * necessary. Any other exit condition is treated as a crash.
2430 */
2432 {
2434 WalSummarizerPMChild = NULL;
2435 if (!EXIT_STATUS_0(exitstatus))
2436 HandleChildCrash(pid, exitstatus,
2437 _("WAL summarizer process"));
2438 continue;
2439 }
2440
2441 /*
2442 * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2443 * start a new one at the next iteration of the postmaster's main
2444 * loop, if necessary. Any other exit condition is treated as a
2445 * crash.
2446 */
2448 {
2451 if (!EXIT_STATUS_0(exitstatus))
2452 HandleChildCrash(pid, exitstatus,
2453 _("autovacuum launcher process"));
2454 continue;
2455 }
2456
2457 /*
2458 * Was it the archiver? If exit status is zero (normal) or one (FATAL
2459 * exit), we assume everything is all right just like normal backends
2460 * and just try to start a new one on the next cycle of the
2461 * postmaster's main loop, to retry archiving remaining files.
2462 */
2463 if (PgArchPMChild && pid == PgArchPMChild->pid)
2464 {
2466 PgArchPMChild = NULL;
2467 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2468 HandleChildCrash(pid, exitstatus,
2469 _("archiver process"));
2470 continue;
2471 }
2472
2473 /* Was it the system logger? If so, try to start a new one */
2474 if (SysLoggerPMChild && pid == SysLoggerPMChild->pid)
2475 {
2477 SysLoggerPMChild = NULL;
2478
2479 /* for safety's sake, launch new logger *first* */
2482
2483 if (!EXIT_STATUS_0(exitstatus))
2484 LogChildExit(LOG, _("system logger process"),
2485 pid, exitstatus);
2486 continue;
2487 }
2488
2489 /*
2490 * Was it the slot sync worker? Normal exit or FATAL exit can be
2491 * ignored (FATAL can be caused by libpqwalreceiver on receiving
2492 * shutdown request by the startup process during promotion); we'll
2493 * start a new one at the next iteration of the postmaster's main
2494 * loop, if necessary. Any other exit condition is treated as a crash.
2495 */
2497 {
2499 SlotSyncWorkerPMChild = NULL;
2500 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2501 HandleChildCrash(pid, exitstatus,
2502 _("slot sync worker process"));
2503 continue;
2504 }
2505
2506 /*
2507 * Was it a backend or a background worker?
2508 */
2509 pmchild = FindPostmasterChildByPid(pid);
2510 if (pmchild)
2511 {
2512 CleanupBackend(pmchild, exitstatus);
2513 }
2514
2515 /*
2516 * We don't know anything about this child process. That's highly
2517 * unexpected, as we do track all the child processes that we fork.
2518 */
2519 else
2520 {
2521 if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2522 HandleChildCrash(pid, exitstatus, _("untracked child process"));
2523 else
2524 LogChildExit(LOG, _("untracked child process"), pid, exitstatus);
2525 }
2526 } /* loop over pending child-death reports */
2527
2528 /*
2529 * After cleaning out the SIGCHLD queue, see if we have any state changes
2530 * or actions to make.
2531 */
2533}
#define PM_STATUS_READY
Definition: pidfile.h:53
PMChild * FindPostmasterChildByPid(int pid)
Definition: pmchild.c:273
static void PostmasterStateMachine(void)
Definition: postmaster.c:2812
static void TerminateChildren(int signal)
Definition: postmaster.c:3322
static bool ReachedNormalRunning
Definition: postmaster.c:353
static void CleanupBackend(PMChild *bp, int exitstatus)
Definition: postmaster.c:2542
#define EXIT_STATUS_3(st)
Definition: postmaster.c:453

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

Referenced by ServerLoop().

◆ process_pm_pmsignal()

static void process_pm_pmsignal ( void  )
static

Definition at line 3486 of file postmaster.c.

3487{
3488 pending_pm_pmsignal = false;
3489
3491 (errmsg_internal("postmaster received pmsignal signal")));
3492
3493 /*
3494 * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
3495 * unexpected states. If the startup process quickly starts up, completes
3496 * recovery, exits, we might process the death of the startup process
3497 * first. We don't want to go back to recovery in that case.
3498 */
3501 {
3502 /* WAL redo has started. We're out of reinitialization. */
3503 FatalError = false;
3504 AbortStartTime = 0;
3505
3506 /*
3507 * Start the archiver if we're responsible for (re-)archiving received
3508 * files.
3509 */
3510 Assert(PgArchPMChild == NULL);
3511 if (XLogArchivingAlways())
3513
3514 /*
3515 * If we aren't planning to enter hot standby mode later, treat
3516 * RECOVERY_STARTED as meaning we're out of startup, and report status
3517 * accordingly.
3518 */
3519 if (!EnableHotStandby)
3520 {
3522#ifdef USE_SYSTEMD
3523 sd_notify(0, "READY=1");
3524#endif
3525 }
3526
3528 }
3529
3532 {
3533 ereport(LOG,
3534 (errmsg("database system is ready to accept read-only connections")));
3535
3536 /* Report status */
3538#ifdef USE_SYSTEMD
3539 sd_notify(0, "READY=1");
3540#endif
3541
3543 connsAllowed = true;
3544
3545 /* Some workers may be scheduled to start now */
3546 StartWorkerNeeded = true;
3547 }
3548
3549 /* Process background worker state changes. */
3551 {
3552 /* Accept new worker requests only if not stopping. */
3554 StartWorkerNeeded = true;
3555 }
3556
3557 /* Tell syslogger to rotate logfile if requested */
3558 if (SysLoggerPMChild != NULL)
3559 {
3561 {
3564 }
3566 {
3568 }
3569 }
3570
3573 {
3574 /*
3575 * Start one iteration of the autovacuum daemon, even if autovacuuming
3576 * is nominally not enabled. This is so we can have an active defense
3577 * against transaction ID wraparound. We set a flag for the main loop
3578 * to do it rather than trying to do it here --- this is because the
3579 * autovac process itself may send the signal, and we want to handle
3580 * that by launching another iteration as soon as the current one
3581 * completes.
3582 */
3584 }
3585
3588 {
3589 /* The autovacuum launcher wants us to start a worker process. */
3591 }
3592
3594 {
3595 /* Startup Process wants us to start the walreceiver process. */
3596 WalReceiverRequested = true;
3597 }
3598
3599 /*
3600 * Try to advance postmaster's state machine, if a child requests it.
3601 *
3602 * Be careful about the order of this action relative to this function's
3603 * other actions. Generally, this should be after other actions, in case
3604 * they have effects PostmasterStateMachine would need to know about.
3605 * However, we should do it before the CheckPromoteSignal step, which
3606 * cannot have any (immediate) effect on the state machine, but does
3607 * depend on what state we're in now.
3608 */
3610 {
3612 }
3613
3614 if (StartupPMChild != NULL &&
3616 pmState == PM_HOT_STANDBY) &&
3618 {
3619 /*
3620 * Tell startup process to finish recovery.
3621 *
3622 * Leave the promote signal file in place and let the Startup process
3623 * do the unlink.
3624 */
3626 }
3627}
void BackgroundWorkerStateChange(bool allow_new_workers)
Definition: bgworker.c:246
#define PM_STATUS_STANDBY
Definition: pidfile.h:54
bool CheckPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:182
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition: pmsignal.h:39
@ PMSIGNAL_RECOVERY_STARTED
Definition: pmsignal.h:35
@ PMSIGNAL_START_WALRECEIVER
Definition: pmsignal.h:41
@ PMSIGNAL_START_AUTOVAC_LAUNCHER
Definition: pmsignal.h:38
@ PMSIGNAL_BEGIN_HOT_STANDBY
Definition: pmsignal.h:36
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition: pmsignal.h:40
@ PMSIGNAL_ROTATE_LOGFILE
Definition: pmsignal.h:37
@ PMSIGNAL_ADVANCE_STATE_MACHINE
Definition: pmsignal.h:42
static void StartAutovacuumWorker(void)
Definition: postmaster.c:3762
bool CheckLogrotateSignal(void)
Definition: syslogger.c:1572
bool EnableHotStandby
Definition: xlog.c:121
bool CheckPromoteSignal(void)

References AbortStartTime, AddToDataDirLockFile(), Assert, B_ARCHIVER, BackgroundWorkerStateChange(), CheckLogrotateSignal(), CheckPostmasterSignal(), CheckPromoteSignal(), connsAllowed, DEBUG2, EnableHotStandby, ereport, errmsg(), errmsg_internal(), FatalError, 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, PMSIGNAL_ADVANCE_STATE_MACHINE, PMSIGNAL_BACKGROUND_WORKER_CHANGE, PMSIGNAL_BEGIN_HOT_STANDBY, PMSIGNAL_RECOVERY_STARTED, PMSIGNAL_ROTATE_LOGFILE, PMSIGNAL_START_AUTOVAC_LAUNCHER, PMSIGNAL_START_AUTOVAC_WORKER, PMSIGNAL_START_WALRECEIVER, pmState, PostmasterStateMachine(), RemoveLogrotateSignalFiles(), Shutdown, signal_child(), SIGUSR1, SIGUSR2, SmartShutdown, start_autovac_launcher, StartAutovacuumWorker(), StartChildProcess(), StartupPMChild, StartWorkerNeeded, SysLoggerPMChild, WalReceiverRequested, and XLogArchivingAlways.

Referenced by ServerLoop().

◆ process_pm_reload_request()

static void process_pm_reload_request ( void  )
static

Definition at line 1966 of file postmaster.c.

1967{
1969
1971 (errmsg_internal("postmaster received reload request signal")));
1972
1973 if (Shutdown <= SmartShutdown)
1974 {
1975 ereport(LOG,
1976 (errmsg("received SIGHUP, reloading configuration files")));
1979
1980 /* Reload authentication config files too */
1981 if (!load_hba())
1982 ereport(LOG,
1983 /* translator: %s is a configuration file */
1984 (errmsg("%s was not reloaded", HbaFileName)));
1985
1986 if (!load_ident())
1987 ereport(LOG,
1988 (errmsg("%s was not reloaded", IdentFileName)));
1989
1990#ifdef USE_SSL
1991 /* Reload SSL configuration as well */
1992 if (EnableSSL)
1993 {
1994 if (secure_initialize(false) == 0)
1995 LoadedSSL = true;
1996 else
1997 ereport(LOG,
1998 (errmsg("SSL configuration was not reloaded")));
1999 }
2000 else
2001 {
2003 LoadedSSL = false;
2004 }
2005#endif
2006
2007#ifdef EXEC_BACKEND
2008 /* Update the starting-point file for future children */
2009 write_nondefault_variables(PGC_SIGHUP);
2010#endif
2011 }
2012}
void secure_destroy(void)
Definition: be-secure.c:88
void ProcessConfigFile(GucContext context)
Definition: guc-file.l:120
@ PGC_SIGHUP
Definition: guc.h:71
char * IdentFileName
Definition: guc_tables.c:540

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

Referenced by ServerLoop().

◆ process_pm_shutdown_request()

static void process_pm_shutdown_request ( void  )
static

Definition at line 2043 of file postmaster.c.

2044{
2045 int mode;
2046
2048 (errmsg_internal("postmaster received shutdown request signal")));
2049
2051
2052 /*
2053 * If more than one shutdown request signal arrived since the last server
2054 * loop, take the one that is the most immediate. That matches the
2055 * priority that would apply if we processed them one by one in any order.
2056 */
2058 {
2062 }
2064 {
2067 }
2068 else
2070
2071 switch (mode)
2072 {
2073 case SmartShutdown:
2074
2075 /*
2076 * Smart Shutdown:
2077 *
2078 * Wait for children to end their work, then shut down.
2079 */
2080 if (Shutdown >= SmartShutdown)
2081 break;
2083 ereport(LOG,
2084 (errmsg("received smart shutdown request")));
2085
2086 /* Report status */
2088#ifdef USE_SYSTEMD
2089 sd_notify(0, "STOPPING=1");
2090#endif
2091
2092 /*
2093 * If we reached normal running, we go straight to waiting for
2094 * client backends to exit. If already in PM_STOP_BACKENDS or a
2095 * later state, do not change it.
2096 */
2097 if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2098 connsAllowed = false;
2099 else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2100 {
2101 /* There should be no clients, so proceed to stop children */
2103 }
2104
2105 /*
2106 * Now wait for online backup mode to end and backends to exit. If
2107 * that is already the case, PostmasterStateMachine will take the
2108 * next step.
2109 */
2111 break;
2112
2113 case FastShutdown:
2114
2115 /*
2116 * Fast Shutdown:
2117 *
2118 * Abort all children with SIGTERM (rollback active transactions
2119 * and exit) and shut down when they are gone.
2120 */
2121 if (Shutdown >= FastShutdown)
2122 break;
2124 ereport(LOG,
2125 (errmsg("received fast shutdown request")));
2126
2127 /* Report status */
2129#ifdef USE_SYSTEMD
2130 sd_notify(0, "STOPPING=1");
2131#endif
2132
2134 {
2135 /* Just shut down background processes silently */
2137 }
2138 else if (pmState == PM_RUN ||
2140 {
2141 /* Report that we're about to zap live client sessions */
2142 ereport(LOG,
2143 (errmsg("aborting any active transactions")));
2145 }
2146
2147 /*
2148 * PostmasterStateMachine will issue any necessary signals, or
2149 * take the next step if no child processes need to be killed.
2150 */
2152 break;
2153
2154 case ImmediateShutdown:
2155
2156 /*
2157 * Immediate Shutdown:
2158 *
2159 * abort all children with SIGQUIT, wait for them to exit,
2160 * terminate remaining ones with SIGKILL, then exit without
2161 * attempt to properly shut down the data base system.
2162 */
2164 break;
2166 ereport(LOG,
2167 (errmsg("received immediate shutdown request")));
2168
2169 /* Report status */
2171#ifdef USE_SYSTEMD
2172 sd_notify(0, "STOPPING=1");
2173#endif
2174
2175 /* tell children to shut down ASAP */
2176 /* (note we don't apply send_abort_for_crash here) */
2180
2181 /* set stopwatch for them to die */
2182 AbortStartTime = time(NULL);
2183
2184 /*
2185 * Now wait for backends to exit. If there are none,
2186 * PostmasterStateMachine will take the next step.
2187 */
2189 break;
2190 }
2191}
static PgChecksumMode mode
Definition: pg_checksums.c:55
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
#define FastShutdown
Definition: postmaster.c:271

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

Referenced by ServerLoop().

◆ report_fork_failure_to_client()

static void report_fork_failure_to_client ( ClientSocket client_sock,
int  errnum 
)
static

Definition at line 3425 of file postmaster.c.

3426{
3427 char buffer[1000];
3428 int rc;
3429
3430 /* Format the error message packet (always V2 protocol) */
3431 snprintf(buffer, sizeof(buffer), "E%s%s\n",
3432 _("could not fork new process for connection: "),
3433 strerror(errnum));
3434
3435 /* Set port to non-blocking. Don't do send() if this fails */
3436 if (!pg_set_noblock(client_sock->sock))
3437 return;
3438
3439 /* We'll retry after EINTR, but ignore all other failures */
3440 do
3441 {
3442 rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
3443 } while (rc < 0 && errno == EINTR);
3444}
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define strerror
Definition: port.h:251
#define EINTR
Definition: win32_port.h:374
#define send(s, buf, len, flags)
Definition: win32_port.h:515

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

Referenced by BackendStartup().

◆ ServerLoop()

static int ServerLoop ( void  )
static

Definition at line 1623 of file postmaster.c.

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

References AbortStartTime, AcceptConnection(), Assert, AutoVacLauncherPMChild, avlauncher_needs_signal, BackendStartup(), closesocket, ConfigurePostmasterWaitSet(), DetermineSleepTime(), elog, ereport, errmsg(), FatalError, fd(), i, ImmediateShutdown, kill, LaunchMissingBackgroundProcesses(), lengthof, LOG, MAXLISTEN, MyLatch, MyProcPid, now(), pending_pm_child_exit, pending_pm_pmsignal, pending_pm_reload_request, pending_pm_shutdown_request, PGINVALID_SOCKET, PMChild::pid, 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, 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 3239 of file postmaster.c.

3240{
3241 pid_t pid = pmchild->pid;
3242
3243 if (kill(pid, signal) < 0)
3244 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3245#ifdef HAVE_SETSID
3246 switch (signal)
3247 {
3248 case SIGINT:
3249 case SIGTERM:
3250 case SIGQUIT:
3251 case SIGKILL:
3252 case SIGABRT:
3253 if (kill(-pid, signal) < 0)
3254 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3255 break;
3256 default:
3257 break;
3258 }
3259#endif
3260}

References DEBUG3, elog, kill, PMChild::pid, SIGABRT, SIGKILL, and SIGQUIT.

Referenced by PostmasterStateMachine(), process_pm_child_exit(), process_pm_pmsignal(), SignalChildren(), and sigquit_child().

◆ SignalChildren()

static bool SignalChildren ( int  signal,
BackendTypeMask  targetMask 
)
static

Definition at line 3284 of file postmaster.c.

3285{
3286 dlist_iter iter;
3287 bool signaled = false;
3288
3290 {
3291 PMChild *bp = dlist_container(PMChild, elem, iter.cur);
3292
3293 /*
3294 * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
3295 * if any B_BACKEND backends have recently announced that they are
3296 * actually WAL senders.
3297 */
3298 if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
3299 bp->bkend_type == B_BACKEND)
3300 {
3303 }
3304
3305 if (!btmask_contains(targetMask, bp->bkend_type))
3306 continue;
3307
3309 (errmsg_internal("sending signal %d to %s process %d",
3310 signal, GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
3311 signal_child(bp, signal);
3312 signaled = true;
3313 }
3314 return signaled;
3315}

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

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

◆ sigquit_child()

static void sigquit_child ( PMChild pmchild)
static

Definition at line 3271 of file postmaster.c.

3272{
3274 (errmsg_internal("sending %s to process %d",
3275 (send_abort_for_crash ? "SIGABRT" : "SIGQUIT"),
3276 (int) pmchild->pid)));
3278}
bool send_abort_for_crash
Definition: postmaster.c:242

References DEBUG2, ereport, errmsg_internal(), PMChild::pid, send_abort_for_crash, SIGABRT, signal_child(), and SIGQUIT.

Referenced by HandleChildCrash().

◆ StartAutovacuumWorker()

static void StartAutovacuumWorker ( void  )
static

Definition at line 3762 of file postmaster.c.

3763{
3764 PMChild *bn;
3765
3766 /*
3767 * If not in condition to run a process, don't try, but handle it like a
3768 * fork failure. This does not normally happen, since the signal is only
3769 * supposed to be sent by autovacuum launcher when it's OK to do it, but
3770 * we have to check to avoid race-condition problems during DB state
3771 * changes.
3772 */
3774 {
3776 if (bn)
3777 {
3778 bn->bgworker_notify = false;
3779 bn->rw = NULL;
3780 return;
3781 }
3782 else
3783 {
3784 /*
3785 * fork failed, fall through to report -- actual error message was
3786 * logged by StartChildProcess
3787 */
3788 }
3789 }
3790
3791 /*
3792 * Report the failure to the launcher, if it's running. (If it's not, we
3793 * might not even be connected to shared memory, so don't try to call
3794 * AutoVacWorkerFailed.) Note that we also need to signal it so that it
3795 * responds to the condition, but we don't do that here, instead waiting
3796 * for ServerLoop to do it. This way we avoid a ping-pong signaling in
3797 * quick succession between the autovac launcher and postmaster in case
3798 * things get ugly.
3799 */
3800 if (AutoVacLauncherPMChild != NULL)
3801 {
3804 }
3805}
void AutoVacWorkerFailed(void)
Definition: autovacuum.c:1339

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

Referenced by process_pm_pmsignal().

◆ StartBackgroundWorker()

static bool StartBackgroundWorker ( RegisteredBgWorker rw)
static

Definition at line 3854 of file postmaster.c.

3855{
3856 PMChild *bn;
3857 pid_t worker_pid;
3858
3859 Assert(rw->rw_pid == 0);
3860
3861 /*
3862 * Allocate and assign the child slot. Note we must do this before
3863 * forking, so that we can handle failures (out of memory or child-process
3864 * slots) cleanly.
3865 *
3866 * Treat failure as though the worker had crashed. That way, the
3867 * postmaster will wait a bit before attempting to start it again; if we
3868 * tried again right away, most likely we'd find ourselves hitting the
3869 * same resource-exhaustion condition.
3870 */
3872 if (bn == NULL)
3873 {
3874 ereport(LOG,
3875 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
3876 errmsg("no slot available for new background worker process")));
3878 return false;
3879 }
3880 bn->rw = rw;
3881 bn->bkend_type = B_BG_WORKER;
3882 bn->bgworker_notify = false;
3883
3885 (errmsg_internal("starting background worker process \"%s\"",
3886 rw->rw_worker.bgw_name)));
3887
3889 (char *) &rw->rw_worker, sizeof(BackgroundWorker), NULL);
3890 if (worker_pid == -1)
3891 {
3892 /* in postmaster, fork failed ... */
3893 ereport(LOG,
3894 (errmsg("could not fork background worker process: %m")));
3895 /* undo what AssignPostmasterChildSlot did */
3897
3898 /* mark entry as crashed, so we'll try again later */
3900 return false;
3901 }
3902
3903 /* in postmaster, fork successful ... */
3904 rw->rw_pid = worker_pid;
3905 bn->pid = rw->rw_pid;
3907 return true;
3908}
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91

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

Referenced by maybe_start_bgworkers().

◆ StartChildProcess()

static PMChild * StartChildProcess ( BackendType  type)
static

Definition at line 3691 of file postmaster.c.

3692{
3693 PMChild *pmchild;
3694 pid_t pid;
3695
3697 if (!pmchild)
3698 {
3699 if (type == B_AUTOVAC_WORKER)
3700 ereport(LOG,
3701 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
3702 errmsg("no slot available for new autovacuum worker process")));
3703 else
3704 {
3705 /* shouldn't happen because we allocate enough slots */
3706 elog(LOG, "no postmaster child slot available for aux process");
3707 }
3708 return NULL;
3709 }
3710
3711 pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
3712 if (pid < 0)
3713 {
3714 /* in parent, fork failed */
3716 ereport(LOG,
3717 (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
3718
3719 /*
3720 * fork failure is fatal during startup, but there's no need to choke
3721 * immediately if starting other child types fails.
3722 */
3723 if (type == B_STARTUP)
3724 ExitPostmaster(1);
3725 return NULL;
3726 }
3727
3728 /* in parent, successful fork */
3729 pmchild->pid = pid;
3730 return pmchild;
3731}
const char * PostmasterChildName(BackendType child_type)
const char * type

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

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

◆ StartSysLogger()

void StartSysLogger ( void  )
static

Definition at line 3737 of file postmaster.c.

3738{
3739 Assert(SysLoggerPMChild == NULL);
3740
3742 if (!SysLoggerPMChild)
3743 elog(PANIC, "no postmaster child slot available for syslogger");
3745 if (SysLoggerPMChild->pid == 0)
3746 {
3748 SysLoggerPMChild = NULL;
3749 }
3750}
#define PANIC
Definition: elog.h:42
int SysLogger_Start(int child_slot)
Definition: syslogger.c:593

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

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

◆ StaticAssertDecl()

StaticAssertDecl ( )

◆ TerminateChildren()

static void TerminateChildren ( int  signal)
static

Definition at line 3322 of file postmaster.c.

3323{
3325 if (StartupPMChild != NULL)
3326 {
3327 if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
3329 }
3330}

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

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

◆ unlink_external_pid_file()

static void unlink_external_pid_file ( int  status,
Datum  arg 
)
static

Definition at line 1420 of file postmaster.c.

1421{
1423 unlink(external_pid_file);
1424}

References external_pid_file.

Referenced by PostmasterMain().

Variable Documentation

◆ AbortStartTime

◆ AuthenticationTimeout

int AuthenticationTimeout = 60

Definition at line 233 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ AutoVacLauncherPMChild

PMChild * AutoVacLauncherPMChild = NULL
static

◆ avlauncher_needs_signal

bool avlauncher_needs_signal = false
static

Definition at line 364 of file postmaster.c.

Referenced by ServerLoop(), and StartAutovacuumWorker().

◆ BgWriterPMChild

PMChild * BgWriterPMChild = NULL
static

◆ bonjour_name

char* bonjour_name

Definition at line 239 of file postmaster.c.

Referenced by PostmasterMain().

◆ BTYPE_MASK_ALL

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

Definition at line 141 of file postmaster.c.

Referenced by btmask_all_except(), btmask_all_except2(), and PostmasterStateMachine().

◆ BTYPE_MASK_NONE

const BackendTypeMask BTYPE_MASK_NONE = {0}
static

Definition at line 142 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ CheckpointerPMChild

PMChild * CheckpointerPMChild = NULL
static

◆ ClientAuthInProgress

◆ connsAllowed

◆ enable_bonjour

bool enable_bonjour = false

Definition at line 238 of file postmaster.c.

Referenced by PostmasterMain().

◆ EnableSSL

bool EnableSSL = false

◆ FatalError

◆ HaveCrashedWorker

bool HaveCrashedWorker = false
static

◆ ListenAddresses

char* ListenAddresses

Definition at line 201 of file postmaster.c.

Referenced by PostmasterMain().

◆ ListenSockets

pgsocket* ListenSockets = NULL
static

◆ Log_connections

bool Log_connections = false

◆ log_hostname

bool log_hostname

Definition at line 235 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 375 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 378 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 379 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 374 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 382 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 195 of file postmaster.c.

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

int PreAuthDelay = 0

Definition at line 232 of file postmaster.c.

Referenced by BackendInitialize().

◆ ReachedNormalRunning

bool ReachedNormalRunning = false
static

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

Referenced by PostmasterStateMachine().

◆ ReservedConnections

int ReservedConnections

Definition at line 222 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

bool restart_after_crash = true

Definition at line 240 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

bool send_abort_for_crash = false

Definition at line 242 of file postmaster.c.

Referenced by sigquit_child().

◆ send_abort_for_kill

bool send_abort_for_kill = false

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

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ StartupPMChild

◆ StartupStatus

◆ StartWorkerNeeded

◆ SuperuserReservedConnections

int SuperuserReservedConnections

Definition at line 221 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ SysLoggerPMChild

PMChild * SysLoggerPMChild = NULL
static

◆ Unix_socket_directories

char* Unix_socket_directories

Definition at line 198 of file postmaster.c.

Referenced by PostmasterMain().

◆ WalReceiverPMChild

PMChild * WalReceiverPMChild = NULL
static

◆ WalReceiverRequested

bool WalReceiverRequested = false
static

Definition at line 367 of file postmaster.c.

Referenced by LaunchMissingBackgroundProcesses(), and process_pm_pmsignal().

◆ WalSummarizerPMChild

PMChild * WalSummarizerPMChild = NULL
static

◆ WalWriterPMChild

PMChild * WalWriterPMChild = NULL
static