PostgreSQL Source Code  git master
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/xlog.h"
#include "access/xlogrecovery.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/ip.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/auxprocess.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 "storage/proc.h"
#include "tcop/backend_startup.h"
#include "tcop/tcopprot.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */
 
#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */
 
#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */
 
#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */
 
#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */
 
#define MAXLISTEN   64
 
#define NoShutdown   0
 
#define SmartShutdown   1
 
#define FastShutdown   2
 
#define ImmediateShutdown   3
 
#define SIGKILL_CHILDREN_AFTER_SECS   5
 
#define SignalChildren(sig)   SignalSomeChildren(sig, BACKEND_TYPE_ALL)
 
#define PgArchStartupAllowed()
 
#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
 

Typedefs

typedef struct bkend Backend
 

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

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 (int pid, int exitstatus)
 
static bool CleanupBackgroundWorker (int pid, 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 (int backend_type)
 
static bool RandomCancelKey (int32 *cancel_key)
 
static void signal_child (pid_t pid, int signal)
 
static void sigquit_child (pid_t pid)
 
static bool SignalSomeChildren (int signal, int target)
 
static void TerminateChildren (int signal)
 
static int CountChildren (int target)
 
static bool assign_backendlist_entry (RegisteredBgWorker *rw)
 
static void maybe_start_bgworkers (void)
 
static bool CreateOptsFile (int argc, char *argv[], char *fullprogname)
 
static pid_t StartChildProcess (BackendType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void MaybeStartWalSummarizer (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
static void MaybeStartSlotSyncWorker (void)
 
void PostmasterMain (int argc, char *argv[])
 
static int DetermineSleepTime (void)
 
static void ConfigurePostmasterWaitSet (bool accept_connections)
 
void processCancelRequest (int backendPID, int32 cancelAuthCode)
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
int MaxLivePostmasterChildren (void)
 
void BackgroundWorkerInitializeConnection (const char *dbname, const char *username, uint32 flags)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid, uint32 flags)
 
void BackgroundWorkerBlockSignals (void)
 
void BackgroundWorkerUnblockSignals (void)
 
static bool do_start_bgworker (RegisteredBgWorker *rw)
 
static bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

static dlist_head BackendList = DLIST_STATIC_INIT(BackendList)
 
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 pid_t StartupPID = 0
 
static pid_t BgWriterPID = 0
 
static pid_t CheckpointerPID = 0
 
static pid_t WalWriterPID = 0
 
static pid_t WalReceiverPID = 0
 
static pid_t WalSummarizerPID = 0
 
static pid_t AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t SysLoggerPID = 0
 
static pid_t SlotSyncWorkerPID = 0
 
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

◆ BACKEND_TYPE_ALL

#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */

Definition at line 140 of file postmaster.c.

◆ BACKEND_TYPE_AUTOVAC

#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */

Definition at line 137 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 139 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 136 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 138 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 470 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 471 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 472 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 266 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 267 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 220 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 264 of file postmaster.c.

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
bool PgArchCanRestart(void)
Definition: pgarch.c:191
@ PM_RUN
Definition: postmaster.c:320
@ PM_HOT_STANDBY
Definition: postmaster.c:319
@ PM_RECOVERY
Definition: postmaster.c:318
static PMState pmState
Definition: postmaster.c:331
#define XLogArchivingActive()
Definition: xlog.h:97
#define XLogArchivingAlways()
Definition: xlog.h:100

Definition at line 441 of file postmaster.c.

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 346 of file postmaster.c.

◆ SignalChildren

#define SignalChildren (   sig)    SignalSomeChildren(sig, BACKEND_TYPE_ALL)

Definition at line 422 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 265 of file postmaster.c.

Typedef Documentation

◆ Backend

typedef struct bkend Backend

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 253 of file postmaster.c.

254 {
257  STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
StartupStatusEnum
Definition: postmaster.c:254
@ STARTUP_SIGNALED
Definition: postmaster.c:257
@ STARTUP_CRASHED
Definition: postmaster.c:258
@ STARTUP_NOT_RUNNING
Definition: postmaster.c:255
@ STARTUP_RUNNING
Definition: postmaster.c:256

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 4345 of file postmaster.c.

4346 {
4347  Backend *bn;
4348 
4349  /*
4350  * Check that database state allows another connection. Currently the
4351  * only possible failure is CAC_TOOMANY, so we just log an error message
4352  * based on that rather than checking the error code precisely.
4353  */
4355  {
4356  ereport(LOG,
4357  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
4358  errmsg("no slot available for new background worker process")));
4359  return false;
4360  }
4361 
4362  /*
4363  * Compute the cancel key that will be assigned to this session. We
4364  * probably don't need cancel keys for background workers, but we'd better
4365  * have something random in the field to prevent unfriendly people from
4366  * sending cancels to them.
4367  */
4369  {
4370  ereport(LOG,
4371  (errcode(ERRCODE_INTERNAL_ERROR),
4372  errmsg("could not generate random cancel key")));
4373  return false;
4374  }
4375 
4376  bn = palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM);
4377  if (bn == NULL)
4378  {
4379  ereport(LOG,
4380  (errcode(ERRCODE_OUT_OF_MEMORY),
4381  errmsg("out of memory")));
4382  return false;
4383  }
4384 
4385  bn->cancel_key = MyCancelKey;
4388  bn->dead_end = false;
4389  bn->bgworker_notify = false;
4390 
4391  rw->rw_backend = bn;
4392  rw->rw_child_slot = bn->child_slot;
4393 
4394  return true;
4395 }
@ CAC_OK
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:17
int32 MyCancelKey
Definition: globals.c:50
int MyPMChildSlot
Definition: globals.c:51
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1355
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:247
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:1895
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:139
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:3868
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:175
int bkend_type
Definition: postmaster.c:173
bool dead_end
Definition: postmaster.c:174
int32 cancel_key
Definition: postmaster.c:171
int child_slot
Definition: postmaster.c:172

References AssignPostmasterChildSlot(), BACKEND_TYPE_BGWORKER, bkend::bgworker_notify, bkend::bkend_type, CAC_OK, canAcceptConnections(), bkend::cancel_key, bkend::child_slot, bkend::dead_end, ereport, errcode(), errmsg(), LOG, MCXT_ALLOC_NO_OOM, MyCancelKey, MyPMChildSlot, palloc_extended(), RandomCancelKey(), RegisteredBgWorker::rw_backend, and RegisteredBgWorker::rw_child_slot.

Referenced by do_start_bgworker().

◆ BackendStartup()

static int BackendStartup ( ClientSocket client_sock)
static

Definition at line 3544 of file postmaster.c.

3545 {
3546  Backend *bn; /* for backend cleanup */
3547  pid_t pid;
3548  BackendStartupData startup_data;
3549 
3550  /*
3551  * Create backend data structure. Better before the fork() so we can
3552  * handle failure cleanly.
3553  */
3554  bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM);
3555  if (!bn)
3556  {
3557  ereport(LOG,
3558  (errcode(ERRCODE_OUT_OF_MEMORY),
3559  errmsg("out of memory")));
3560  return STATUS_ERROR;
3561  }
3562 
3563  /*
3564  * Compute the cancel key that will be assigned to this backend. The
3565  * backend will have its own copy in the forked-off process' value of
3566  * MyCancelKey, so that it can transmit the key to the frontend.
3567  */
3569  {
3570  pfree(bn);
3571  ereport(LOG,
3572  (errcode(ERRCODE_INTERNAL_ERROR),
3573  errmsg("could not generate random cancel key")));
3574  return STATUS_ERROR;
3575  }
3576 
3577  /* Pass down canAcceptConnections state */
3579  bn->dead_end = (startup_data.canAcceptConnections != CAC_OK);
3580  bn->cancel_key = MyCancelKey;
3581 
3582  /*
3583  * Unless it's a dead_end child, assign it a child slot number
3584  */
3585  if (!bn->dead_end)
3587  else
3588  bn->child_slot = 0;
3589 
3590  /* Hasn't asked to be notified about any bgworkers yet */
3591  bn->bgworker_notify = false;
3592 
3594  (char *) &startup_data, sizeof(startup_data),
3595  client_sock);
3596  if (pid < 0)
3597  {
3598  /* in parent, fork failed */
3599  int save_errno = errno;
3600 
3601  if (!bn->dead_end)
3603  pfree(bn);
3604  errno = save_errno;
3605  ereport(LOG,
3606  (errmsg("could not fork new process for connection: %m")));
3607  report_fork_failure_to_client(client_sock, save_errno);
3608  return STATUS_ERROR;
3609  }
3610 
3611  /* in parent, successful fork */
3612  ereport(DEBUG2,
3613  (errmsg_internal("forked new backend, pid=%d socket=%d",
3614  (int) pid, (int) client_sock->sock)));
3615 
3616  /*
3617  * Everything's been successful, it's safe to add this backend to our list
3618  * of backends.
3619  */
3620  bn->pid = pid;
3621  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
3623 
3624 #ifdef EXEC_BACKEND
3625  if (!bn->dead_end)
3626  ShmemBackendArrayAdd(bn);
3627 #endif
3628 
3629  return STATUS_OK;
3630 }
#define STATUS_OK
Definition: c.h:1156
#define STATUS_ERROR
Definition: c.h:1157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
#define DEBUG2
Definition: elog.h:29
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
pid_t postmaster_child_launch(BackendType child_type, char *startup_data, size_t startup_data_len, ClientSocket *client_sock)
void pfree(void *pointer)
Definition: mcxt.c:1508
@ B_BACKEND
Definition: miscadmin.h:338
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:284
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:136
static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
Definition: postmaster.c:3641
static dlist_head BackendList
Definition: postmaster.c:179
CAC_state canAcceptConnections
pgsocket sock
Definition: libpq-be.h:224
dlist_node elem
Definition: postmaster.c:176
pid_t pid
Definition: postmaster.c:170

References AssignPostmasterChildSlot(), B_BACKEND, BACKEND_TYPE_NORMAL, BackendList, bkend::bgworker_notify, bkend::bkend_type, CAC_OK, canAcceptConnections(), BackendStartupData::canAcceptConnections, bkend::cancel_key, bkend::child_slot, bkend::dead_end, DEBUG2, dlist_push_head(), bkend::elem, ereport, errcode(), errmsg(), errmsg_internal(), LOG, MCXT_ALLOC_NO_OOM, MyCancelKey, MyPMChildSlot, palloc_extended(), pfree(), bkend::pid, postmaster_child_launch(), RandomCancelKey(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), ClientSocket::sock, STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 4223 of file postmaster.c.

4224 {
4225  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
4226 }
sigset_t BlockSig
Definition: pqsignal.c:23

References BlockSig.

◆ BackgroundWorkerInitializeConnection()

void BackgroundWorkerInitializeConnection ( const char *  dbname,
const char *  username,
uint32  flags 
)

Definition at line 4155 of file postmaster.c.

4156 {
4158  bits32 init_flags = 0; /* never honor session_preload_libraries */
4159 
4160  /* ignore datallowconn? */
4161  if (flags & BGWORKER_BYPASS_ALLOWCONN)
4162  init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
4163  /* ignore rolcanlogin? */
4164  if (flags & BGWORKER_BYPASS_ROLELOGINCHECK)
4165  init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
4166 
4167  /* XXX is this the right errcode? */
4169  ereport(FATAL,
4170  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4171  errmsg("database connection requirement not indicated during registration")));
4172 
4173  InitPostgres(dbname, InvalidOid, /* database to connect to */
4174  username, InvalidOid, /* role to connect as */
4175  init_flags,
4176  NULL); /* no out_dbname */
4177 
4178  /* it had better not gotten out of "init" mode yet */
4179  if (!IsInitProcessingMode())
4180  ereport(ERROR,
4181  (errmsg("invalid processing mode in background worker")));
4183 }
#define BGWORKER_BYPASS_ROLELOGINCHECK
Definition: bgworker.h:157
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:156
uint32 bits32
Definition: c.h:502
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
@ NormalProcessing
Definition: miscadmin.h:449
#define IsInitProcessingMode()
Definition: miscadmin.h:455
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:478
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:477
const char * username
Definition: pgbench.c:296
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:736
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:185
char * dbname
Definition: streamutil.c:52

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, dbname, ereport, errcode(), errmsg(), ERROR, FATAL, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitPostgres(), InvalidOid, IsInitProcessingMode, MyBgworkerEntry, NormalProcessing, SetProcessingMode, and username.

Referenced by ApplyLauncherMain(), and worker_spi_main().

◆ BackgroundWorkerInitializeConnectionByOid()

void BackgroundWorkerInitializeConnectionByOid ( Oid  dboid,
Oid  useroid,
uint32  flags 
)

Definition at line 4189 of file postmaster.c.

4190 {
4192  bits32 init_flags = 0; /* never honor session_preload_libraries */
4193 
4194  /* ignore datallowconn? */
4195  if (flags & BGWORKER_BYPASS_ALLOWCONN)
4196  init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
4197  /* ignore rolcanlogin? */
4198  if (flags & BGWORKER_BYPASS_ROLELOGINCHECK)
4199  init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
4200 
4201  /* XXX is this the right errcode? */
4203  ereport(FATAL,
4204  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4205  errmsg("database connection requirement not indicated during registration")));
4206 
4207  InitPostgres(NULL, dboid, /* database to connect to */
4208  NULL, useroid, /* role to connect as */
4209  init_flags,
4210  NULL); /* no out_dbname */
4211 
4212  /* it had better not gotten out of "init" mode yet */
4213  if (!IsInitProcessingMode())
4214  ereport(ERROR,
4215  (errmsg("invalid processing mode in background worker")));
4217 }

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, ereport, errcode(), errmsg(), ERROR, FATAL, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitPostgres(), IsInitProcessingMode, MyBgworkerEntry, NormalProcessing, and SetProcessingMode.

Referenced by autoprewarm_database_main(), InitializeLogRepWorker(), ParallelWorkerMain(), and worker_spi_main().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 4229 of file postmaster.c.

4230 {
4231  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4232 }
sigset_t UnBlockSig
Definition: pqsignal.c:22

References UnBlockSig.

Referenced by ApplyLauncherMain(), autoprewarm_database_main(), autoprewarm_main(), BackgroundWorkerMain(), ParallelApplyWorkerMain(), ParallelWorkerMain(), SetupApplyOrSyncWorker(), test_shm_mq_main(), and worker_spi_main().

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 4303 of file postmaster.c.

4304 {
4305  switch (pmState)
4306  {
4307  case PM_NO_CHILDREN:
4308  case PM_WAIT_DEAD_END:
4309  case PM_SHUTDOWN_2:
4310  case PM_SHUTDOWN:
4311  case PM_WAIT_BACKENDS:
4312  case PM_STOP_BACKENDS:
4313  break;
4314 
4315  case PM_RUN:
4317  return true;
4318  /* fall through */
4319 
4320  case PM_HOT_STANDBY:
4322  return true;
4323  /* fall through */
4324 
4325  case PM_RECOVERY:
4326  case PM_STARTUP:
4327  case PM_INIT:
4329  return true;
4330  /* fall through */
4331  }
4332 
4333  return false;
4334 }
@ 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:94

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

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 1895 of file postmaster.c.

1896 {
1897  CAC_state result = CAC_OK;
1898 
1899  /*
1900  * Can't start backends when in startup/shutdown/inconsistent recovery
1901  * state. We treat autovac workers the same as user backends for this
1902  * purpose. However, bgworkers are excluded from this test; we expect
1903  * bgworker_should_start_now() decided whether the DB state allows them.
1904  */
1905  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
1906  backend_type != BACKEND_TYPE_BGWORKER)
1907  {
1908  if (Shutdown > NoShutdown)
1909  return CAC_SHUTDOWN; /* shutdown is pending */
1910  else if (!FatalError && pmState == PM_STARTUP)
1911  return CAC_STARTUP; /* normal startup */
1912  else if (!FatalError && pmState == PM_RECOVERY)
1913  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
1914  * state */
1915  else
1916  return CAC_RECOVERY; /* else must be crash recovery */
1917  }
1918 
1919  /*
1920  * "Smart shutdown" restrictions are applied only to normal connections,
1921  * not to autovac workers or bgworkers.
1922  */
1923  if (!connsAllowed && backend_type == BACKEND_TYPE_NORMAL)
1924  return CAC_SHUTDOWN; /* shutdown is pending */
1925 
1926  /*
1927  * Don't start too many children.
1928  *
1929  * We allow more connections here than we can have backends because some
1930  * might still be authenticating; they might fail auth, or some existing
1931  * backend might exit before the auth cycle is completed. The exact
1932  * MaxBackends limit is enforced when a new backend tries to join the
1933  * shared-inval backend array.
1934  *
1935  * The limit here must match the sizes of the per-child-process arrays;
1936  * see comments for MaxLivePostmasterChildren().
1937  */
1939  result = CAC_TOOMANY;
1940 
1941  return result;
1942 }
CAC_state
@ CAC_TOOMANY
@ CAC_RECOVERY
@ CAC_NOTCONSISTENT
@ CAC_STARTUP
@ CAC_SHUTDOWN
static bool connsAllowed
Definition: postmaster.c:339
static int Shutdown
Definition: postmaster.c:269
#define BACKEND_TYPE_ALL
Definition: postmaster.c:140
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:4145
#define NoShutdown
Definition: postmaster.c:264
static bool FatalError
Definition: postmaster.c:271
static int CountChildren(int target)
Definition: postmaster.c:3878

References BACKEND_TYPE_ALL, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, CAC_NOTCONSISTENT, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_TOOMANY, connsAllowed, CountChildren(), FatalError, MaxLivePostmasterChildren(), NoShutdown, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, pmState, and Shutdown.

Referenced by assign_backendlist_entry(), BackendStartup(), and StartAutovacuumWorker().

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1487 of file postmaster.c.

1488 {
1489  char path[MAXPGPATH];
1490  FILE *fp;
1491 
1492  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1493 
1494  fp = AllocateFile(path, PG_BINARY_R);
1495  if (fp == NULL)
1496  {
1497  write_stderr("%s: could not find the database system\n"
1498  "Expected to find it in the directory \"%s\",\n"
1499  "but could not open file \"%s\": %m\n",
1500  progname, DataDir, path);
1501  ExitPostmaster(2);
1502  }
1503  FreeFile(fp);
1504 }
#define write_stderr(str)
Definition: parallel.c:184
#define PG_BINARY_R
Definition: c.h:1262
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2583
int FreeFile(FILE *file)
Definition: fd.c:2781
char * DataDir
Definition: globals.c:68
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:3668

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

Referenced by PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

Definition at line 2790 of file postmaster.c.

2792 {
2793  dlist_mutable_iter iter;
2794 
2795  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
2796 
2797  /*
2798  * If a backend dies in an ugly way then we must signal all other backends
2799  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
2800  * assume everything is all right and proceed to remove the backend from
2801  * the active backend list.
2802  */
2803 
2804 #ifdef WIN32
2805 
2806  /*
2807  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
2808  * since that sometimes happens under load when the process fails to start
2809  * properly (long before it starts using shared memory). Microsoft reports
2810  * it is related to mutex failure:
2811  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
2812  */
2813  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2814  {
2815  LogChildExit(LOG, _("server process"), pid, exitstatus);
2816  exitstatus = 0;
2817  }
2818 #endif
2819 
2820  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2821  {
2822  HandleChildCrash(pid, exitstatus, _("server process"));
2823  return;
2824  }
2825 
2827  {
2828  Backend *bp = dlist_container(Backend, elem, iter.cur);
2829 
2830  if (bp->pid == pid)
2831  {
2832  if (!bp->dead_end)
2833  {
2835  {
2836  /*
2837  * Uh-oh, the child failed to clean itself up. Treat as a
2838  * crash after all.
2839  */
2840  HandleChildCrash(pid, exitstatus, _("server process"));
2841  return;
2842  }
2843 #ifdef EXEC_BACKEND
2844  ShmemBackendArrayRemove(bp);
2845 #endif
2846  }
2847  if (bp->bgworker_notify)
2848  {
2849  /*
2850  * This backend may have been slated to receive SIGUSR1 when
2851  * some background worker started or stopped. Cancel those
2852  * notifications, as we don't want to signal PIDs that are not
2853  * PostgreSQL backends. This gets skipped in the (probably
2854  * very common) case where the backend has never requested any
2855  * such notifications.
2856  */
2858  }
2859  dlist_delete(iter.cur);
2860  pfree(bp);
2861  break;
2862  }
2863  }
2864 }
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:520
#define _(x)
Definition: elog.c:90
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:640
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3061
#define EXIT_STATUS_1(st)
Definition: postmaster.c:471
#define EXIT_STATUS_0(st)
Definition: postmaster.c:470
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:2874
dlist_node * cur
Definition: ilist.h:200

References _, BackendList, BackgroundWorkerStopNotifications(), bkend::bgworker_notify, bkend::child_slot, dlist_mutable_iter::cur, bkend::dead_end, DEBUG2, dlist_container, dlist_delete(), dlist_foreach_modify, EXIT_STATUS_0, EXIT_STATUS_1, HandleChildCrash(), LOG, LogChildExit(), pfree(), bkend::pid, and ReleasePostmasterChildSlot().

Referenced by process_pm_child_exit().

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 2695 of file postmaster.c.

2697 {
2698  char namebuf[MAXPGPATH];
2699  slist_mutable_iter iter;
2700 
2702  {
2703  RegisteredBgWorker *rw;
2704 
2705  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
2706 
2707  if (rw->rw_pid != pid)
2708  continue;
2709 
2710 #ifdef WIN32
2711  /* see CleanupBackend */
2712  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
2713  exitstatus = 0;
2714 #endif
2715 
2716  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
2717  rw->rw_worker.bgw_type);
2718 
2719 
2720  if (!EXIT_STATUS_0(exitstatus))
2721  {
2722  /* Record timestamp, so we know when to restart the worker. */
2724  }
2725  else
2726  {
2727  /* Zero exit status means terminate */
2728  rw->rw_crashed_at = 0;
2729  rw->rw_terminate = true;
2730  }
2731 
2732  /*
2733  * Additionally, just like a backend, any exit status other than 0 or
2734  * 1 is considered a crash and causes a system-wide restart.
2735  */
2736  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2737  {
2738  HandleChildCrash(pid, exitstatus, namebuf);
2739  return true;
2740  }
2741 
2742  /*
2743  * We must release the postmaster child slot. If the worker failed to
2744  * do so, it did not clean up after itself, requiring a crash-restart
2745  * cycle.
2746  */
2748  {
2749  HandleChildCrash(pid, exitstatus, namebuf);
2750  return true;
2751  }
2752 
2753  /* Get it out of the BackendList and clear out remaining data */
2754  dlist_delete(&rw->rw_backend->elem);
2755 #ifdef EXEC_BACKEND
2756  ShmemBackendArrayRemove(rw->rw_backend);
2757 #endif
2758 
2759  /*
2760  * It's possible that this background worker started some OTHER
2761  * background worker and asked to be notified when that worker started
2762  * or stopped. If so, cancel any notifications destined for the
2763  * now-dead backend.
2764  */
2765  if (rw->rw_backend->bgworker_notify)
2767  pfree(rw->rw_backend);
2768  rw->rw_backend = NULL;
2769  rw->rw_pid = 0;
2770  rw->rw_child_slot = 0;
2771  ReportBackgroundWorkerExit(&iter); /* report child death */
2772 
2773  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
2774  namebuf, pid, exitstatus);
2775 
2776  return true;
2777  }
2778 
2779  return false;
2780 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
slist_head BackgroundWorkerList
Definition: bgworker.c:40
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:486
#define DEBUG1
Definition: elog.h:30
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:1148
#define slist_container(type, membername, ptr)
Definition: ilist.h:1106
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BackgroundWorker rw_worker
slist_node * cur
Definition: ilist.h:274

References _, BackgroundWorkerList, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_type, bkend::bgworker_notify, slist_mutable_iter::cur, DEBUG1, dlist_delete(), bkend::elem, EXIT_STATUS_0, EXIT_STATUS_1, GetCurrentTimestamp(), HandleChildCrash(), LOG, LogChildExit(), MAXPGPATH, pfree(), ReleasePostmasterChildSlot(), ReportBackgroundWorkerExit(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, slist_container, slist_foreach_modify, and snprintf.

Referenced by process_pm_child_exit().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 1955 of file postmaster.c.

1956 {
1957  /* Release resources held by the postmaster's WaitEventSet. */
1958  if (pm_wait_set)
1959  {
1961  pm_wait_set = NULL;
1962  }
1963 
1964 #ifndef WIN32
1965 
1966  /*
1967  * Close the write end of postmaster death watch pipe. It's important to
1968  * do this as early as possible, so that if postmaster dies, others won't
1969  * think that it's still running because we're holding the pipe open.
1970  */
1972  ereport(FATAL,
1974  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
1976  /* Notify fd.c that we released one pipe FD. */
1978 #endif
1979 
1980  /*
1981  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
1982  * so we don't call ReleaseExternalFD() here.
1983  *
1984  * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
1985  * EXEC_BACKEND mode.
1986  */
1987 #ifndef EXEC_BACKEND
1988  if (ListenSockets)
1989  {
1990  for (int i = 0; i < NumListenSockets; i++)
1991  {
1992  if (closesocket(ListenSockets[i]) != 0)
1993  elog(LOG, "could not close listen socket: %m");
1994  }
1996  }
1997  NumListenSockets = 0;
1998  ListenSockets = NULL;
1999 #endif
2000 
2001  /*
2002  * If using syslogger, close the read side of the pipe. We don't bother
2003  * tracking this in fd.c, either.
2004  */
2005  if (!am_syslogger)
2006  {
2007 #ifndef WIN32
2008  if (syslogPipe[0] >= 0)
2009  close(syslogPipe[0]);
2010  syslogPipe[0] = -1;
2011 #else
2012  if (syslogPipe[0])
2013  CloseHandle(syslogPipe[0]);
2014  syslogPipe[0] = 0;
2015 #endif
2016  }
2017 
2018 #ifdef USE_BONJOUR
2019  /* If using Bonjour, close the connection to the mDNS daemon */
2020  if (bonjour_sdref)
2021  close(DNSServiceRefSockFD(bonjour_sdref));
2022 #endif
2023 }
int errcode_for_file_access(void)
Definition: elog.c:882
#define elog(elevel,...)
Definition: elog.h:224
void ReleaseExternalFD(void)
Definition: fd.c:1239
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:917
#define closesocket
Definition: port.h:349
static pgsocket * ListenSockets
Definition: postmaster.c:222
static int NumListenSockets
Definition: postmaster.c:221
int postmaster_alive_fds[2]
Definition: postmaster.c:479
static WaitEventSet * pm_wait_set
Definition: postmaster.c:377
#define POSTMASTER_FD_OWN
Definition: postmaster.h:49
int syslogPipe[2]
Definition: syslogger.c:116

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

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

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

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1601 of file postmaster.c.

1602 {
1603  if (pm_wait_set)
1605  pm_wait_set = NULL;
1606 
1608  accept_connections ? (1 + NumListenSockets) : 1);
1610  NULL);
1611 
1612  if (accept_connections)
1613  {
1614  for (int i = 0; i < NumListenSockets; i++)
1616  NULL, NULL);
1617  }
1618 }
struct Latch * MyLatch
Definition: globals.c:60
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: latch.c:751
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:963
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:874
#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 ( int  target)
static

Definition at line 3878 of file postmaster.c.

3879 {
3880  dlist_iter iter;
3881  int cnt = 0;
3882 
3883  dlist_foreach(iter, &BackendList)
3884  {
3885  Backend *bp = dlist_container(Backend, elem, iter.cur);
3886 
3887  if (bp->dead_end)
3888  continue;
3889 
3890  /*
3891  * Since target == BACKEND_TYPE_ALL is the most common case, we test
3892  * it first and avoid touching shared memory for every child.
3893  */
3894  if (target != BACKEND_TYPE_ALL)
3895  {
3896  /*
3897  * Assign bkend_type for any recently announced WAL Sender
3898  * processes.
3899  */
3900  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
3903 
3904  if (!(target & bp->bkend_type))
3905  continue;
3906  }
3907 
3908  cnt++;
3909  }
3910  return cnt;
3911 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:307
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:138
dlist_node * cur
Definition: ilist.h:179

References BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, bkend::bkend_type, bkend::child_slot, dlist_iter::cur, bkend::dead_end, dlist_container, dlist_foreach, and IsPostmasterChildWalSender().

Referenced by canAcceptConnections(), and PostmasterStateMachine().

◆ CreateOptsFile()

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

Definition at line 4101 of file postmaster.c.

4102 {
4103  FILE *fp;
4104  int i;
4105 
4106 #define OPTS_FILE "postmaster.opts"
4107 
4108  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
4109  {
4110  ereport(LOG,
4112  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
4113  return false;
4114  }
4115 
4116  fprintf(fp, "%s", fullprogname);
4117  for (i = 1; i < argc; i++)
4118  fprintf(fp, " \"%s\"", argv[i]);
4119  fputs("\n", fp);
4120 
4121  if (fclose(fp))
4122  {
4123  ereport(LOG,
4125  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
4126  return false;
4127  }
4128 
4129  return true;
4130 }
#define fprintf
Definition: port.h:242
#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 1516 of file postmaster.c.

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

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

Referenced by ServerLoop().

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 4244 of file postmaster.c.

4245 {
4246  pid_t worker_pid;
4247 
4248  Assert(rw->rw_pid == 0);
4249 
4250  /*
4251  * Allocate and assign the Backend element. Note we must do this before
4252  * forking, so that we can handle failures (out of memory or child-process
4253  * slots) cleanly.
4254  *
4255  * Treat failure as though the worker had crashed. That way, the
4256  * postmaster will wait a bit before attempting to start it again; if we
4257  * tried again right away, most likely we'd find ourselves hitting the
4258  * same resource-exhaustion condition.
4259  */
4260  if (!assign_backendlist_entry(rw))
4261  {
4263  return false;
4264  }
4265 
4266  ereport(DEBUG1,
4267  (errmsg_internal("starting background worker process \"%s\"",
4268  rw->rw_worker.bgw_name)));
4269 
4270  worker_pid = postmaster_child_launch(B_BG_WORKER, (char *) &rw->rw_worker, sizeof(BackgroundWorker), NULL);
4271  if (worker_pid == -1)
4272  {
4273  /* in postmaster, fork failed ... */
4274  ereport(LOG,
4275  (errmsg("could not fork background worker process: %m")));
4276  /* undo what assign_backendlist_entry did */
4278  rw->rw_child_slot = 0;
4279  pfree(rw->rw_backend);
4280  rw->rw_backend = NULL;
4281  /* mark entry as crashed, so we'll try again later */
4283  return false;
4284  }
4285 
4286  /* in postmaster, fork successful ... */
4287  rw->rw_pid = worker_pid;
4288  rw->rw_backend->pid = rw->rw_pid;
4290  /* add new worker to lists of backends */
4292 #ifdef EXEC_BACKEND
4293  ShmemBackendArrayAdd(rw->rw_backend);
4294 #endif
4295  return true;
4296 }
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:467
Assert(fmt[strlen(fmt) - 1] !='\n')
@ B_BG_WORKER
Definition: miscadmin.h:341
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:4345
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91

References Assert(), assign_backendlist_entry(), B_BG_WORKER, BackendList, BackgroundWorker::bgw_name, DEBUG1, dlist_push_head(), bkend::elem, ereport, errmsg(), errmsg_internal(), GetCurrentTimestamp(), LOG, pfree(), bkend::pid, postmaster_child_launch(), ReleasePostmasterChildSlot(), ReportBackgroundWorkerPID(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, and RegisteredBgWorker::rw_worker.

Referenced by maybe_start_bgworkers().

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 3860 of file postmaster.c.

3861 {
3862 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 3668 of file postmaster.c.

3669 {
3670 #ifdef HAVE_PTHREAD_IS_THREADED_NP
3671 
3672  /*
3673  * There is no known cause for a postmaster to become multithreaded after
3674  * startup. Recheck to account for the possibility of unknown causes.
3675  * This message uses LOG level, because an unclean shutdown at this point
3676  * would usually not look much different from a clean shutdown.
3677  */
3678  if (pthread_is_threaded_np() != 0)
3679  ereport(LOG,
3680  (errcode(ERRCODE_INTERNAL_ERROR),
3681  errmsg_internal("postmaster became multithreaded"),
3682  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
3683 #endif
3684 
3685  /* should cleanup shared memory and kill all backends */
3686 
3687  /*
3688  * Not sure of the semantics here. When the Postmaster dies, should the
3689  * backends all be killed? probably not.
3690  *
3691  * MUST -- vadim 05-10-1999
3692  */
3693 
3694  proc_exit(status);
3695 }
int errdetail(const char *fmt,...)
Definition: elog.c:1205
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 1433 of file postmaster.c.

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

2344 {
2345  pending_pm_child_exit = true;
2346  SetLatch(MyLatch);
2347 }
void SetLatch(Latch *latch)
Definition: latch.c:632
static volatile sig_atomic_t pending_pm_child_exit
Definition: postmaster.c:370

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

2076 {
2077  pending_pm_pmsignal = true;
2078  SetLatch(MyLatch);
2079 }
static volatile sig_atomic_t pending_pm_pmsignal
Definition: postmaster.c:369

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

2086 {
2088  SetLatch(MyLatch);
2089 }
static volatile sig_atomic_t pending_pm_reload_request
Definition: postmaster.c:371

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

2169 {
2170  switch (postgres_signal_arg)
2171  {
2172  case SIGTERM:
2173  /* smart is implied if the other two flags aren't set */
2175  break;
2176  case SIGINT:
2179  break;
2180  case SIGQUIT:
2183  break;
2184  }
2185  SetLatch(MyLatch);
2186 }
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition: postmaster.c:373
static volatile sig_atomic_t pending_pm_shutdown_request
Definition: postmaster.c:372
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition: postmaster.c:374
#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 2874 of file postmaster.c.

2875 {
2876  dlist_mutable_iter iter;
2877  slist_iter siter;
2878  Backend *bp;
2879  bool take_action;
2880 
2881  /*
2882  * We only log messages and send signals if this is the first process
2883  * crash and we're not doing an immediate shutdown; otherwise, we're only
2884  * here to update postmaster's idea of live processes. If we have already
2885  * signaled children, nonzero exit status is to be expected, so don't
2886  * clutter log.
2887  */
2888  take_action = !FatalError && Shutdown != ImmediateShutdown;
2889 
2890  if (take_action)
2891  {
2892  LogChildExit(LOG, procname, pid, exitstatus);
2893  ereport(LOG,
2894  (errmsg("terminating any other active server processes")));
2896  }
2897 
2898  /* Process background workers. */
2900  {
2901  RegisteredBgWorker *rw;
2902 
2903  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
2904  if (rw->rw_pid == 0)
2905  continue; /* not running */
2906  if (rw->rw_pid == pid)
2907  {
2908  /*
2909  * Found entry for freshly-dead worker, so remove it.
2910  */
2912  dlist_delete(&rw->rw_backend->elem);
2913 #ifdef EXEC_BACKEND
2914  ShmemBackendArrayRemove(rw->rw_backend);
2915 #endif
2916  pfree(rw->rw_backend);
2917  rw->rw_backend = NULL;
2918  rw->rw_pid = 0;
2919  rw->rw_child_slot = 0;
2920  /* don't reset crashed_at */
2921  /* don't report child stop, either */
2922  /* Keep looping so we can signal remaining workers */
2923  }
2924  else
2925  {
2926  /*
2927  * This worker is still alive. Unless we did so already, tell it
2928  * to commit hara-kiri.
2929  */
2930  if (take_action)
2931  sigquit_child(rw->rw_pid);
2932  }
2933  }
2934 
2935  /* Process regular backends */
2937  {
2938  bp = dlist_container(Backend, elem, iter.cur);
2939 
2940  if (bp->pid == pid)
2941  {
2942  /*
2943  * Found entry for freshly-dead backend, so remove it.
2944  */
2945  if (!bp->dead_end)
2946  {
2948 #ifdef EXEC_BACKEND
2949  ShmemBackendArrayRemove(bp);
2950 #endif
2951  }
2952  dlist_delete(iter.cur);
2953  pfree(bp);
2954  /* Keep looping so we can signal remaining backends */
2955  }
2956  else
2957  {
2958  /*
2959  * This backend is still alive. Unless we did so already, tell it
2960  * to commit hara-kiri.
2961  *
2962  * We could exclude dead_end children here, but at least when
2963  * sending SIGABRT it seems better to include them.
2964  *
2965  * Background workers were already processed above; ignore them
2966  * here.
2967  */
2968  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
2969  continue;
2970 
2971  if (take_action)
2972  sigquit_child(bp->pid);
2973  }
2974  }
2975 
2976  /* Take care of the startup process too */
2977  if (pid == StartupPID)
2978  {
2979  StartupPID = 0;
2980  /* Caller adjusts StartupStatus, so don't touch it here */
2981  }
2982  else if (StartupPID != 0 && take_action)
2983  {
2986  }
2987 
2988  /* Take care of the bgwriter too */
2989  if (pid == BgWriterPID)
2990  BgWriterPID = 0;
2991  else if (BgWriterPID != 0 && take_action)
2993 
2994  /* Take care of the checkpointer too */
2995  if (pid == CheckpointerPID)
2996  CheckpointerPID = 0;
2997  else if (CheckpointerPID != 0 && take_action)
2999 
3000  /* Take care of the walwriter too */
3001  if (pid == WalWriterPID)
3002  WalWriterPID = 0;
3003  else if (WalWriterPID != 0 && take_action)
3005 
3006  /* Take care of the walreceiver too */
3007  if (pid == WalReceiverPID)
3008  WalReceiverPID = 0;
3009  else if (WalReceiverPID != 0 && take_action)
3011 
3012  /* Take care of the walsummarizer too */
3013  if (pid == WalSummarizerPID)
3014  WalSummarizerPID = 0;
3015  else if (WalSummarizerPID != 0 && take_action)
3017 
3018  /* Take care of the autovacuum launcher too */
3019  if (pid == AutoVacPID)
3020  AutoVacPID = 0;
3021  else if (AutoVacPID != 0 && take_action)
3023 
3024  /* Take care of the archiver too */
3025  if (pid == PgArchPID)
3026  PgArchPID = 0;
3027  else if (PgArchPID != 0 && take_action)
3029 
3030  /* Take care of the slot sync worker too */
3031  if (pid == SlotSyncWorkerPID)
3032  SlotSyncWorkerPID = 0;
3033  else if (SlotSyncWorkerPID != 0 && take_action)
3035 
3036  /* We do NOT restart the syslogger */
3037 
3038  if (Shutdown != ImmediateShutdown)
3039  FatalError = true;
3040 
3041  /* We now transit into a state of waiting for children to die */
3042  if (pmState == PM_RECOVERY ||
3043  pmState == PM_HOT_STANDBY ||
3044  pmState == PM_RUN ||
3046  pmState == PM_SHUTDOWN)
3048 
3049  /*
3050  * .. and if this doesn't happen quickly enough, now the clock is ticking
3051  * for us to kill them without mercy.
3052  */
3053  if (AbortStartTime == 0)
3054  AbortStartTime = time(NULL);
3055 }
#define slist_foreach(iter, lhead)
Definition: ilist.h:1132
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:218
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
static pid_t WalReceiverPID
Definition: postmaster.c:245
static pid_t PgArchPID
Definition: postmaster.c:248
#define ImmediateShutdown
Definition: postmaster.c:267
static pid_t AutoVacPID
Definition: postmaster.c:247
static pid_t SlotSyncWorkerPID
Definition: postmaster.c:250
static pid_t CheckpointerPID
Definition: postmaster.c:243
static pid_t BgWriterPID
Definition: postmaster.c:242
static pid_t WalWriterPID
Definition: postmaster.c:244
static StartupStatusEnum StartupStatus
Definition: postmaster.c:261
static pid_t WalSummarizerPID
Definition: postmaster.c:246
static void sigquit_child(pid_t pid)
Definition: postmaster.c:3451
static pid_t StartupPID
Definition: postmaster.c:241
slist_node * cur
Definition: ilist.h:259

References AbortStartTime, AutoVacPID, BACKEND_TYPE_BGWORKER, BackendList, BackgroundWorkerList, BgWriterPID, bkend::bkend_type, CheckpointerPID, bkend::child_slot, dlist_mutable_iter::cur, slist_iter::cur, bkend::dead_end, dlist_container, dlist_delete(), dlist_foreach_modify, bkend::elem, ereport, errmsg(), FatalError, ImmediateShutdown, LOG, LogChildExit(), pfree(), PgArchPID, bkend::pid, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_CRASH, pmState, ReleasePostmasterChildSlot(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_pid, SetQuitSignalReason(), Shutdown, sigquit_child(), slist_container, slist_foreach, SlotSyncWorkerPID, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 4703 of file postmaster.c.

4704 {
4705 #ifndef WIN32
4706 
4707  /*
4708  * Create a pipe. Postmaster holds the write end of the pipe open
4709  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
4710  * the read file descriptor to select() to wake up in case postmaster
4711  * dies, or check for postmaster death with a (read() == 0). Children must
4712  * close the write end as soon as possible after forking, because EOF
4713  * won't be signaled in the read end until all processes have closed the
4714  * write fd. That is taken care of in ClosePostmasterPorts().
4715  */
4717  if (pipe(postmaster_alive_fds) < 0)
4718  ereport(FATAL,
4720  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
4721 
4722  /* Notify fd.c that we've eaten two FDs for the pipe. */
4725 
4726  /*
4727  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
4728  * call.
4729  */
4730  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
4731  ereport(FATAL,
4733  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
4734 #else
4735 
4736  /*
4737  * On Windows, we use a process handle for the same purpose.
4738  */
4739  if (DuplicateHandle(GetCurrentProcess(),
4740  GetCurrentProcess(),
4741  GetCurrentProcess(),
4742  &PostmasterHandle,
4743  0,
4744  TRUE,
4745  DUPLICATE_SAME_ACCESS) == 0)
4746  ereport(FATAL,
4747  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
4748  GetLastError())));
4749 #endif /* WIN32 */
4750 }
int errcode_for_socket_access(void)
Definition: elog.c:955
void ReserveExternalFD(void)
Definition: fd.c:1221
pid_t PostmasterPid
Definition: globals.c:103
int MyProcPid
Definition: globals.c:45
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:48

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

2033 {
2034  MyProcPid = getpid();
2037 
2038  /*
2039  * Set a different global seed in every process. We want something
2040  * unpredictable, so if possible, use high-quality random bits for the
2041  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2042  */
2044  {
2045  uint64 rseed;
2046 
2047  /*
2048  * Since PIDs and timestamps tend to change more frequently in their
2049  * least significant bits, shift the timestamp left to allow a larger
2050  * total number of seeds in a given time period. Since that would
2051  * leave only 20 bits of the timestamp that cycle every ~1 second,
2052  * also mix in some higher bits.
2053  */
2054  rseed = ((uint64) MyProcPid) ^
2055  ((uint64) MyStartTimestamp << 12) ^
2056  ((uint64) MyStartTimestamp >> 20);
2057 
2059  }
2060 
2061  /*
2062  * Also make sure that we've set a good seed for random(3). Use of that
2063  * is deprecated in core Postgres, but extensions might use it.
2064  */
2065 #ifndef WIN32
2067 #endif
2068 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1833
#define unlikely(x)
Definition: c.h:298
TimestampTz MyStartTimestamp
Definition: globals.c:47
pg_time_t MyStartTime
Definition: globals.c:46
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().

◆ LogChildExit()

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

Definition at line 3061 of file postmaster.c.

3062 {
3063  /*
3064  * size of activity_buffer is arbitrary, but set equal to default
3065  * track_activity_query_size
3066  */
3067  char activity_buffer[1024];
3068  const char *activity = NULL;
3069 
3070  if (!EXIT_STATUS_0(exitstatus))
3071  activity = pgstat_get_crashed_backend_activity(pid,
3072  activity_buffer,
3073  sizeof(activity_buffer));
3074 
3075  if (WIFEXITED(exitstatus))
3076  ereport(lev,
3077 
3078  /*------
3079  translator: %s is a noun phrase describing a child process, such as
3080  "server process" */
3081  (errmsg("%s (PID %d) exited with exit code %d",
3082  procname, pid, WEXITSTATUS(exitstatus)),
3083  activity ? errdetail("Failed process was running: %s", activity) : 0));
3084  else if (WIFSIGNALED(exitstatus))
3085  {
3086 #if defined(WIN32)
3087  ereport(lev,
3088 
3089  /*------
3090  translator: %s is a noun phrase describing a child process, such as
3091  "server process" */
3092  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3093  procname, pid, WTERMSIG(exitstatus)),
3094  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3095  activity ? errdetail("Failed process was running: %s", activity) : 0));
3096 #else
3097  ereport(lev,
3098 
3099  /*------
3100  translator: %s is a noun phrase describing a child process, such as
3101  "server process" */
3102  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3103  procname, pid, WTERMSIG(exitstatus),
3104  pg_strsignal(WTERMSIG(exitstatus))),
3105  activity ? errdetail("Failed process was running: %s", activity) : 0));
3106 #endif
3107  }
3108  else
3109  ereport(lev,
3110 
3111  /*------
3112  translator: %s is a noun phrase describing a child process, such as
3113  "server process" */
3114  (errmsg("%s (PID %d) exited with unrecognized status %d",
3115  procname, pid, exitstatus),
3116  activity ? errdetail("Failed process was running: %s", activity) : 0));
3117 }
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(), CleanupBackgroundWorker(), HandleChildCrash(), and process_pm_child_exit().

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 4145 of file postmaster.c.

4146 {
4147  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
4149 }
int autovacuum_max_workers
Definition: autovacuum.c:116
int MaxConnections
Definition: globals.c:140
int max_worker_processes
Definition: globals.c:141
int max_wal_senders
Definition: walsender.c:121

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

Referenced by canAcceptConnections(), PMSignalShmemInit(), PMSignalShmemSize(), and processCancelRequest().

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 4409 of file postmaster.c.

4410 {
4411 #define MAX_BGWORKERS_TO_LAUNCH 100
4412  int num_launched = 0;
4413  TimestampTz now = 0;
4414  slist_mutable_iter iter;
4415 
4416  /*
4417  * During crash recovery, we have no need to be called until the state
4418  * transition out of recovery.
4419  */
4420  if (FatalError)
4421  {
4422  StartWorkerNeeded = false;
4423  HaveCrashedWorker = false;
4424  return;
4425  }
4426 
4427  /* Don't need to be called again unless we find a reason for it below */
4428  StartWorkerNeeded = false;
4429  HaveCrashedWorker = false;
4430 
4432  {
4433  RegisteredBgWorker *rw;
4434 
4435  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
4436 
4437  /* ignore if already running */
4438  if (rw->rw_pid != 0)
4439  continue;
4440 
4441  /* if marked for death, clean up and remove from list */
4442  if (rw->rw_terminate)
4443  {
4444  ForgetBackgroundWorker(&iter);
4445  continue;
4446  }
4447 
4448  /*
4449  * If this worker has crashed previously, maybe it needs to be
4450  * restarted (unless on registration it specified it doesn't want to
4451  * be restarted at all). Check how long ago did a crash last happen.
4452  * If the last crash is too recent, don't start it right away; let it
4453  * be restarted once enough time has passed.
4454  */
4455  if (rw->rw_crashed_at != 0)
4456  {
4458  {
4459  int notify_pid;
4460 
4461  notify_pid = rw->rw_worker.bgw_notify_pid;
4462 
4463  ForgetBackgroundWorker(&iter);
4464 
4465  /* Report worker is gone now. */
4466  if (notify_pid != 0)
4467  kill(notify_pid, SIGUSR1);
4468 
4469  continue;
4470  }
4471 
4472  /* read system time only when needed */
4473  if (now == 0)
4475 
4477  rw->rw_worker.bgw_restart_time * 1000))
4478  {
4479  /* Set flag to remember that we have workers to start later */
4480  HaveCrashedWorker = true;
4481  continue;
4482  }
4483  }
4484 
4486  {
4487  /* reset crash time before trying to start worker */
4488  rw->rw_crashed_at = 0;
4489 
4490  /*
4491  * Try to start the worker.
4492  *
4493  * On failure, give up processing workers for now, but set
4494  * StartWorkerNeeded so we'll come back here on the next iteration
4495  * of ServerLoop to try again. (We don't want to wait, because
4496  * there might be additional ready-to-run workers.) We could set
4497  * HaveCrashedWorker as well, since this worker is now marked
4498  * crashed, but there's no need because the next run of this
4499  * function will do that.
4500  */
4501  if (!do_start_bgworker(rw))
4502  {
4503  StartWorkerNeeded = true;
4504  return;
4505  }
4506 
4507  /*
4508  * If we've launched as many workers as allowed, quit, but have
4509  * ServerLoop call us again to look for additional ready-to-run
4510  * workers. There might not be any, but we'll find out the next
4511  * time we run.
4512  */
4513  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
4514  {
4515  StartWorkerNeeded = true;
4516  return;
4517  }
4518  }
4519  }
4520 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1790
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:4244
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:4303
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:485
#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(), slist_mutable_iter::cur, do_start_bgworker(), FatalError, ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, kill, MAX_BGWORKERS_TO_LAUNCH, now(), RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SIGUSR1, slist_container, slist_foreach_modify, StartWorkerNeeded, and TimestampDifferenceExceeds().

Referenced by PostmasterMain(), process_pm_child_exit(), process_pm_pmsignal(), and ServerLoop().

◆ MaybeStartSlotSyncWorker()

static void MaybeStartSlotSyncWorker ( void  )
static

Definition at line 4089 of file postmaster.c.

4090 {
4091  if (SlotSyncWorkerPID == 0 && pmState == PM_HOT_STANDBY &&
4095 }
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:343
#define SmartShutdown
Definition: postmaster.c:265
static pid_t StartChildProcess(BackendType type)
Definition: postmaster.c:3924
bool sync_replication_slots
Definition: slotsync.c:101
bool SlotSyncWorkerCanRestart(void)
Definition: slotsync.c:1358
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:921

References B_SLOTSYNC_WORKER, LOG, PM_HOT_STANDBY, pmState, Shutdown, SlotSyncWorkerCanRestart(), SlotSyncWorkerPID, SmartShutdown, StartChildProcess(), sync_replication_slots, and ValidateSlotSyncParams().

Referenced by process_pm_child_exit(), and ServerLoop().

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 4051 of file postmaster.c.

4052 {
4053  if (WalReceiverPID == 0 &&
4054  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
4055  pmState == PM_HOT_STANDBY) &&
4057  {
4059  if (WalReceiverPID != 0)
4060  WalReceiverRequested = false;
4061  /* else leave the flag set, so we'll try again later */
4062  }
4063 }
@ B_WAL_RECEIVER
Definition: miscadmin.h:359
static bool WalReceiverRequested
Definition: postmaster.c:362

References B_WAL_RECEIVER, PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, pmState, Shutdown, SmartShutdown, StartChildProcess(), WalReceiverPID, and WalReceiverRequested.

Referenced by process_pm_pmsignal(), and ServerLoop().

◆ MaybeStartWalSummarizer()

static void MaybeStartWalSummarizer ( void  )
static

Definition at line 4070 of file postmaster.c.

4071 {
4072  if (summarize_wal && WalSummarizerPID == 0 &&
4073  (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
4076 }
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:360
bool summarize_wal

References B_WAL_SUMMARIZER, PM_HOT_STANDBY, PM_RUN, pmState, Shutdown, SmartShutdown, StartChildProcess(), summarize_wal, and WalSummarizerPID.

Referenced by process_pm_child_exit(), and ServerLoop().

◆ PostmasterMain()

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

Definition at line 489 of file postmaster.c.

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

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert(), autovac_init(), B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, BgWriterPID, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPID, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), DEBUG3, DestNone, 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, InitializeGUCOptions(), InitializeLatchSupport(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), InitProcessLocalLatch(), 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, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworkers(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, name, NIL, NumListenSockets, on_proc_exit(), optarg, opterr, optind, palloc(), 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(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartChildProcess(), STARTUP_RUNNING, StartupPID, StartupStatus, STATUS_OK, success, summarize_wal, SuperuserReservedConnections, SysLogger_Start(), SysLoggerPID, 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 4528 of file postmaster.c.

4529 {
4530  dlist_iter iter;
4531  Backend *bp;
4532 
4533  dlist_foreach(iter, &BackendList)
4534  {
4535  bp = dlist_container(Backend, elem, iter.cur);
4536  if (bp->pid == pid)
4537  {
4538  bp->bgworker_notify = true;
4539  return true;
4540  }
4541  }
4542  return false;
4543 }

References BackendList, bkend::bgworker_notify, dlist_iter::cur, dlist_container, dlist_foreach, and bkend::pid.

Referenced by BackgroundWorkerStateChange().

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3127 of file postmaster.c.

3128 {
3129  /* If we're doing a smart shutdown, try to advance that state. */
3130  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3131  {
3132  if (!connsAllowed)
3133  {
3134  /*
3135  * This state ends when we have no normal client backends running.
3136  * Then we're ready to stop other children.
3137  */
3140  }
3141  }
3142 
3143  /*
3144  * If we're ready to do so, signal child processes to shut down. (This
3145  * isn't a persistent state, but treating it as a distinct pmState allows
3146  * us to share this code across multiple shutdown code paths.)
3147  */
3148  if (pmState == PM_STOP_BACKENDS)
3149  {
3150  /*
3151  * Forget any pending requests for background workers, since we're no
3152  * longer willing to launch any new workers. (If additional requests
3153  * arrive, BackgroundWorkerStateChange will reject them.)
3154  */
3156 
3157  /* Signal all backend children except walsenders */
3158  SignalSomeChildren(SIGTERM,
3160  /* and the autovac launcher too */
3161  if (AutoVacPID != 0)
3162  signal_child(AutoVacPID, SIGTERM);
3163  /* and the bgwriter too */
3164  if (BgWriterPID != 0)
3165  signal_child(BgWriterPID, SIGTERM);
3166  /* and the walwriter too */
3167  if (WalWriterPID != 0)
3168  signal_child(WalWriterPID, SIGTERM);
3169  /* If we're in recovery, also stop startup and walreceiver procs */
3170  if (StartupPID != 0)
3171  signal_child(StartupPID, SIGTERM);
3172  if (WalReceiverPID != 0)
3173  signal_child(WalReceiverPID, SIGTERM);
3174  if (WalSummarizerPID != 0)
3175  signal_child(WalSummarizerPID, SIGTERM);
3176  if (SlotSyncWorkerPID != 0)
3177  signal_child(SlotSyncWorkerPID, SIGTERM);
3178  /* checkpointer, archiver, stats, and syslogger may continue for now */
3179 
3180  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3182  }
3183 
3184  /*
3185  * If we are in a state-machine state that implies waiting for backends to
3186  * exit, see if they're all gone, and change state if so.
3187  */
3188  if (pmState == PM_WAIT_BACKENDS)
3189  {
3190  /*
3191  * PM_WAIT_BACKENDS state ends when we have no regular backends
3192  * (including autovac workers), no bgworkers (including unconnected
3193  * ones), and no walwriter, autovac launcher, bgwriter or slot sync
3194  * worker. If we are doing crash recovery or an immediate shutdown
3195  * then we expect the checkpointer to exit as well, otherwise not. The
3196  * stats and syslogger processes are disregarded since they are not
3197  * connected to shared memory; we also disregard dead_end children
3198  * here. Walsenders and archiver are also disregarded, they will be
3199  * terminated later after writing the checkpoint record.
3200  */
3202  StartupPID == 0 &&
3203  WalReceiverPID == 0 &&
3204  WalSummarizerPID == 0 &&
3205  BgWriterPID == 0 &&
3206  (CheckpointerPID == 0 ||
3208  WalWriterPID == 0 &&
3209  AutoVacPID == 0 &&
3210  SlotSyncWorkerPID == 0)
3211  {
3213  {
3214  /*
3215  * Start waiting for dead_end children to die. This state
3216  * change causes ServerLoop to stop creating new ones.
3217  */
3219 
3220  /*
3221  * We already SIGQUIT'd the archiver and stats processes, if
3222  * any, when we started immediate shutdown or entered
3223  * FatalError state.
3224  */
3225  }
3226  else
3227  {
3228  /*
3229  * If we get here, we are proceeding with normal shutdown. All
3230  * the regular children are gone, and it's time to tell the
3231  * checkpointer to do a shutdown checkpoint.
3232  */
3234  /* Start the checkpointer if not running */
3235  if (CheckpointerPID == 0)
3237  /* And tell it to shut down */
3238  if (CheckpointerPID != 0)
3239  {
3241  pmState = PM_SHUTDOWN;
3242  }
3243  else
3244  {
3245  /*
3246  * If we failed to fork a checkpointer, just shut down.
3247  * Any required cleanup will happen at next restart. We
3248  * set FatalError so that an "abnormal shutdown" message
3249  * gets logged when we exit.
3250  *
3251  * We don't consult send_abort_for_crash here, as it's
3252  * unlikely that dumping cores would illuminate the reason
3253  * for checkpointer fork failure.
3254  */
3255  FatalError = true;
3257 
3258  /* Kill the walsenders and archiver too */
3260  if (PgArchPID != 0)
3262  }
3263  }
3264  }
3265  }
3266 
3267  if (pmState == PM_SHUTDOWN_2)
3268  {
3269  /*
3270  * PM_SHUTDOWN_2 state ends when there's no other children than
3271  * dead_end children left. There shouldn't be any regular backends
3272  * left by now anyway; what we're really waiting for is walsenders and
3273  * archiver.
3274  */
3275  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3276  {
3278  }
3279  }
3280 
3281  if (pmState == PM_WAIT_DEAD_END)
3282  {
3283  /* Don't allow any new socket connection events. */
3285 
3286  /*
3287  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3288  * (ie, no dead_end children remain), and the archiver is gone too.
3289  *
3290  * The reason we wait for those two is to protect them against a new
3291  * postmaster starting conflicting subprocesses; this isn't an
3292  * ironclad protection, but it at least helps in the
3293  * shutdown-and-immediately-restart scenario. Note that they have
3294  * already been sent appropriate shutdown signals, either during a
3295  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3296  * FatalError processing.
3297  */
3298  if (dlist_is_empty(&BackendList) && PgArchPID == 0)
3299  {
3300  /* These other guys should be dead already */
3301  Assert(StartupPID == 0);
3302  Assert(WalReceiverPID == 0);
3303  Assert(WalSummarizerPID == 0);
3304  Assert(BgWriterPID == 0);
3305  Assert(CheckpointerPID == 0);
3306  Assert(WalWriterPID == 0);
3307  Assert(AutoVacPID == 0);
3308  Assert(SlotSyncWorkerPID == 0);
3309  /* syslogger is not considered here */
3311  }
3312  }
3313 
3314  /*
3315  * If we've been told to shut down, we exit as soon as there are no
3316  * remaining children. If there was a crash, cleanup will occur at the
3317  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3318  * crash before exiting, but that seems unwise if we are quitting because
3319  * we got SIGTERM from init --- there may well not be time for recovery
3320  * before init decides to SIGKILL us.)
3321  *
3322  * Note that the syslogger continues to run. It will exit when it sees
3323  * EOF on its input pipe, which happens when there are no more upstream
3324  * processes.
3325  */
3327  {
3328  if (FatalError)
3329  {
3330  ereport(LOG, (errmsg("abnormal database system shutdown")));
3331  ExitPostmaster(1);
3332  }
3333  else
3334  {
3335  /*
3336  * Normal exit from the postmaster is here. We don't need to log
3337  * anything here, since the UnlinkLockFiles proc_exit callback
3338  * will do so, and that should be the last user-visible action.
3339  */
3340  ExitPostmaster(0);
3341  }
3342  }
3343 
3344  /*
3345  * If the startup process failed, or the user does not want an automatic
3346  * restart after backend crashes, wait for all non-syslogger children to
3347  * exit, and then exit postmaster. We don't try to reinitialize when the
3348  * startup process fails, because more than likely it will just fail again
3349  * and we will keep trying forever.
3350  */
3351  if (pmState == PM_NO_CHILDREN)
3352  {
3354  {
3355  ereport(LOG,
3356  (errmsg("shutting down due to startup process failure")));
3357  ExitPostmaster(1);
3358  }
3359  if (!restart_after_crash)
3360  {
3361  ereport(LOG,
3362  (errmsg("shutting down because restart_after_crash is off")));
3363  ExitPostmaster(1);
3364  }
3365  }
3366 
3367  /*
3368  * If we need to recover from a crash, wait for all non-syslogger children
3369  * to exit, then reset shmem and start the startup process.
3370  */
3371  if (FatalError && pmState == PM_NO_CHILDREN)
3372  {
3373  ereport(LOG,
3374  (errmsg("all server processes terminated; reinitializing")));
3375 
3376  /* remove leftover temporary files after a crash */
3379 
3380  /* allow background workers to immediately restart */
3382 
3383  shmem_exit(1);
3384 
3385  /* re-read control file into local memory */
3387 
3388  /* re-create shared memory and semaphores */
3390 
3392  Assert(StartupPID != 0);
3394  pmState = PM_STARTUP;
3395  /* crash recovery started, reset SIGKILL flag */
3396  AbortStartTime = 0;
3397 
3398  /* start accepting server socket connection events again */
3400  }
3401 }
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:585
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:547
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
void shmem_exit(int code)
Definition: ipc.c:228
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3421
bool remove_temp_files_after_crash
Definition: postmaster.c:236
bool restart_after_crash
Definition: postmaster.c:235
#define SignalChildren(sig)
Definition: postmaster.c:422
static bool SignalSomeChildren(int signal, int target)
Definition: postmaster.c:3465
static void ConfigurePostmasterWaitSet(bool accept_connections)
Definition: postmaster.c:1601

References AbortStartTime, Assert(), AutoVacPID, B_CHECKPOINTER, B_STARTUP, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, BgWriterPID, CheckpointerPID, ConfigurePostmasterWaitSet(), connsAllowed, CountChildren(), CreateSharedMemoryAndSemaphores(), dlist_is_empty(), ereport, errmsg(), ExitPostmaster(), FatalError, ForgetUnstartedBackgroundWorkers(), ImmediateShutdown, LocalProcessControlFile(), LOG, NoShutdown, PgArchPID, 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, SignalSomeChildren(), SIGQUIT, SIGUSR2, SlotSyncWorkerPID, StartChildProcess(), STARTUP_CRASHED, STARTUP_RUNNING, StartupPID, StartupStatus, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

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

2354 {
2355  int pid; /* process id of dead child process */
2356  int exitstatus; /* its exit status */
2357 
2358  pending_pm_child_exit = false;
2359 
2360  ereport(DEBUG4,
2361  (errmsg_internal("reaping dead processes")));
2362 
2363  while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2364  {
2365  /*
2366  * Check if this child was a startup process.
2367  */
2368  if (pid == StartupPID)
2369  {
2370  StartupPID = 0;
2371 
2372  /*
2373  * Startup process exited in response to a shutdown request (or it
2374  * completed normally regardless of the shutdown request).
2375  */
2376  if (Shutdown > NoShutdown &&
2377  (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2378  {
2381  /* PostmasterStateMachine logic does the rest */
2382  continue;
2383  }
2384 
2385  if (EXIT_STATUS_3(exitstatus))
2386  {
2387  ereport(LOG,
2388  (errmsg("shutdown at recovery target")));
2391  TerminateChildren(SIGTERM);
2393  /* PostmasterStateMachine logic does the rest */
2394  continue;
2395  }
2396 
2397  /*
2398  * Unexpected exit of startup process (including FATAL exit)
2399  * during PM_STARTUP is treated as catastrophic. There are no
2400  * other processes running yet, so we can just exit.
2401  */
2402  if (pmState == PM_STARTUP &&
2404  !EXIT_STATUS_0(exitstatus))
2405  {
2406  LogChildExit(LOG, _("startup process"),
2407  pid, exitstatus);
2408  ereport(LOG,
2409  (errmsg("aborting startup due to startup process failure")));
2410  ExitPostmaster(1);
2411  }
2412 
2413  /*
2414  * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2415  * the startup process is catastrophic, so kill other children,
2416  * and set StartupStatus so we don't try to reinitialize after
2417  * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
2418  * then we previously sent the startup process a SIGQUIT; so
2419  * that's probably the reason it died, and we do want to try to
2420  * restart in that case.
2421  *
2422  * This stanza also handles the case where we sent a SIGQUIT
2423  * during PM_STARTUP due to some dead_end child crashing: in that
2424  * situation, if the startup process dies on the SIGQUIT, we need
2425  * to transition to PM_WAIT_BACKENDS state which will allow
2426  * PostmasterStateMachine to restart the startup process. (On the
2427  * other hand, the startup process might complete normally, if we
2428  * were too late with the SIGQUIT. In that case we'll fall
2429  * through and commence normal operations.)
2430  */
2431  if (!EXIT_STATUS_0(exitstatus))
2432  {
2434  {
2436  if (pmState == PM_STARTUP)
2438  }
2439  else
2441  HandleChildCrash(pid, exitstatus,
2442  _("startup process"));
2443  continue;
2444  }
2445 
2446  /*
2447  * Startup succeeded, commence normal operations
2448  */
2450  FatalError = false;
2451  AbortStartTime = 0;
2452  ReachedNormalRunning = true;
2453  pmState = PM_RUN;
2454  connsAllowed = true;
2455 
2456  /*
2457  * Crank up the background tasks, if we didn't do that already
2458  * when we entered consistent recovery state. It doesn't matter
2459  * if this fails, we'll just try again later.
2460  */
2461  if (CheckpointerPID == 0)
2463  if (BgWriterPID == 0)
2465  if (WalWriterPID == 0)
2468 
2469  /*
2470  * Likewise, start other special children as needed. In a restart
2471  * situation, some of them may be alive already.
2472  */
2475  if (PgArchStartupAllowed() && PgArchPID == 0)
2478 
2479  /* workers may be scheduled to start now */
2481 
2482  /* at this point we are really open for business */
2483  ereport(LOG,
2484  (errmsg("database system is ready to accept connections")));
2485 
2486  /* Report status */
2488 #ifdef USE_SYSTEMD
2489  sd_notify(0, "READY=1");
2490 #endif
2491 
2492  continue;
2493  }
2494 
2495  /*
2496  * Was it the bgwriter? Normal exit can be ignored; we'll start a new
2497  * one at the next iteration of the postmaster's main loop, if
2498  * necessary. Any other exit condition is treated as a crash.
2499  */
2500  if (pid == BgWriterPID)
2501  {
2502  BgWriterPID = 0;
2503  if (!EXIT_STATUS_0(exitstatus))
2504  HandleChildCrash(pid, exitstatus,
2505  _("background writer process"));
2506  continue;
2507  }
2508 
2509  /*
2510  * Was it the checkpointer?
2511  */
2512  if (pid == CheckpointerPID)
2513  {
2514  CheckpointerPID = 0;
2515  if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
2516  {
2517  /*
2518  * OK, we saw normal exit of the checkpointer after it's been
2519  * told to shut down. We expect that it wrote a shutdown
2520  * checkpoint. (If for some reason it didn't, recovery will
2521  * occur on next postmaster start.)
2522  *
2523  * At this point we should have no normal backend children
2524  * left (else we'd not be in PM_SHUTDOWN state) but we might
2525  * have dead_end children to wait for.
2526  *
2527  * If we have an archiver subprocess, tell it to do a last
2528  * archive cycle and quit. Likewise, if we have walsender
2529  * processes, tell them to send any remaining WAL and quit.
2530  */
2532 
2533  /* Waken archiver for the last time */
2534  if (PgArchPID != 0)
2536 
2537  /*
2538  * Waken walsenders for the last time. No regular backends
2539  * should be around anymore.
2540  */
2542 
2544  }
2545  else
2546  {
2547  /*
2548  * Any unexpected exit of the checkpointer (including FATAL
2549  * exit) is treated as a crash.
2550  */
2551  HandleChildCrash(pid, exitstatus,
2552  _("checkpointer process"));
2553  }
2554 
2555  continue;
2556  }
2557 
2558  /*
2559  * Was it the wal writer? Normal exit can be ignored; we'll start a
2560  * new one at the next iteration of the postmaster's main loop, if
2561  * necessary. Any other exit condition is treated as a crash.
2562  */
2563  if (pid == WalWriterPID)
2564  {
2565  WalWriterPID = 0;
2566  if (!EXIT_STATUS_0(exitstatus))
2567  HandleChildCrash(pid, exitstatus,
2568  _("WAL writer process"));
2569  continue;
2570  }
2571 
2572  /*
2573  * Was it the wal receiver? If exit status is zero (normal) or one
2574  * (FATAL exit), we assume everything is all right just like normal
2575  * backends. (If we need a new wal receiver, we'll start one at the
2576  * next iteration of the postmaster's main loop.)
2577  */
2578  if (pid == WalReceiverPID)
2579  {
2580  WalReceiverPID = 0;
2581  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2582  HandleChildCrash(pid, exitstatus,
2583  _("WAL receiver process"));
2584  continue;
2585  }
2586 
2587  /*
2588  * Was it the wal summarizer? Normal exit can be ignored; we'll start
2589  * a new one at the next iteration of the postmaster's main loop, if
2590  * necessary. Any other exit condition is treated as a crash.
2591  */
2592  if (pid == WalSummarizerPID)
2593  {
2594  WalSummarizerPID = 0;
2595  if (!EXIT_STATUS_0(exitstatus))
2596  HandleChildCrash(pid, exitstatus,
2597  _("WAL summarizer process"));
2598  continue;
2599  }
2600 
2601  /*
2602  * Was it the autovacuum launcher? Normal exit can be ignored; we'll
2603  * start a new one at the next iteration of the postmaster's main
2604  * loop, if necessary. Any other exit condition is treated as a
2605  * crash.
2606  */
2607  if (pid == AutoVacPID)
2608  {
2609  AutoVacPID = 0;
2610  if (!EXIT_STATUS_0(exitstatus))
2611  HandleChildCrash(pid, exitstatus,
2612  _("autovacuum launcher process"));
2613  continue;
2614  }
2615 
2616  /*
2617  * Was it the archiver? If exit status is zero (normal) or one (FATAL
2618  * exit), we assume everything is all right just like normal backends
2619  * and just try to restart a new one so that we immediately retry
2620  * archiving remaining files. (If fail, we'll try again in future
2621  * cycles of the postmaster's main loop.) Unless we were waiting for
2622  * it to shut down; don't restart it in that case, and
2623  * PostmasterStateMachine() will advance to the next shutdown step.
2624  */
2625  if (pid == PgArchPID)
2626  {
2627  PgArchPID = 0;
2628  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2629  HandleChildCrash(pid, exitstatus,
2630  _("archiver process"));
2631  if (PgArchStartupAllowed())
2633  continue;
2634  }
2635 
2636  /* Was it the system logger? If so, try to start a new one */
2637  if (pid == SysLoggerPID)
2638  {
2639  SysLoggerPID = 0;
2640  /* for safety's sake, launch new logger *first* */
2642  if (!EXIT_STATUS_0(exitstatus))
2643  LogChildExit(LOG, _("system logger process"),
2644  pid, exitstatus);
2645  continue;
2646  }
2647 
2648  /*
2649  * Was it the slot sync worker? Normal exit or FATAL exit can be
2650  * ignored (FATAL can be caused by libpqwalreceiver on receiving
2651  * shutdown request by the startup process during promotion); we'll
2652  * start a new one at the next iteration of the postmaster's main
2653  * loop, if necessary. Any other exit condition is treated as a crash.
2654  */
2655  if (pid == SlotSyncWorkerPID)
2656  {
2657  SlotSyncWorkerPID = 0;
2658  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
2659  HandleChildCrash(pid, exitstatus,
2660  _("slot sync worker process"));
2661  continue;
2662  }
2663 
2664  /* Was it one of our background workers? */
2665  if (CleanupBackgroundWorker(pid, exitstatus))
2666  {
2667  /* have it be restarted */
2668  HaveCrashedWorker = true;
2669  continue;
2670  }
2671 
2672  /*
2673  * Else do standard backend child cleanup.
2674  */
2675  CleanupBackend(pid, exitstatus);
2676  } /* loop over pending child-death reports */
2677 
2678  /*
2679  * After cleaning out the SIGCHLD queue, see if we have any state changes
2680  * or actions to make.
2681  */
2683 }
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3170
#define DEBUG4
Definition: elog.h:27
@ B_WAL_WRITER
Definition: miscadmin.h:361
@ B_ARCHIVER
Definition: miscadmin.h:355
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:339
#define PM_STATUS_READY
Definition: pidfile.h:53
static bool CleanupBackgroundWorker(int pid, int exitstatus)
Definition: postmaster.c:2695
static void MaybeStartWalSummarizer(void)
Definition: postmaster.c:4070
static void PostmasterStateMachine(void)
Definition: postmaster.c:3127
static void TerminateChildren(int signal)
Definition: postmaster.c:3509
static void MaybeStartSlotSyncWorker(void)
Definition: postmaster.c:4089
#define PgArchStartupAllowed()
Definition: postmaster.c:441
static bool ReachedNormalRunning
Definition: postmaster.c:348
static void CleanupBackend(int pid, int exitstatus)
Definition: postmaster.c:2790
#define EXIT_STATUS_3(st)
Definition: postmaster.c:472

References _, AbortStartTime, AddToDataDirLockFile(), Assert(), AutoVacPID, AutoVacuumingActive(), B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_BG_WRITER, B_CHECKPOINTER, B_WAL_WRITER, BgWriterPID, CheckpointerPID, CleanupBackend(), CleanupBackgroundWorker(), connsAllowed, DEBUG4, ereport, errmsg(), errmsg_internal(), EXIT_STATUS_0, EXIT_STATUS_1, EXIT_STATUS_3, ExitPostmaster(), FatalError, HandleChildCrash(), HaveCrashedWorker, IsBinaryUpgrade, LOCK_FILE_LINE_PM_STATUS, LOG, LogChildExit(), Max, maybe_start_bgworkers(), MaybeStartSlotSyncWorker(), MaybeStartWalSummarizer(), NoShutdown, pending_pm_child_exit, PgArchPID, PgArchStartupAllowed, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STATUS_READY, PM_WAIT_BACKENDS, pmState, PostmasterStateMachine(), ReachedNormalRunning, Shutdown, signal_child(), SignalChildren, SIGUSR2, SlotSyncWorkerPID, SmartShutdown, StartChildProcess(), STARTUP_CRASHED, STARTUP_NOT_RUNNING, STARTUP_SIGNALED, StartupPID, StartupStatus, SysLogger_Start(), SysLoggerPID, TerminateChildren(), WalReceiverPID, WalSummarizerPID, and WalWriterPID.

Referenced by ServerLoop().

◆ process_pm_pmsignal()

static void process_pm_pmsignal ( void  )
static

Definition at line 3702 of file postmaster.c.

3703 {
3704  pending_pm_pmsignal = false;
3705 
3706  ereport(DEBUG2,
3707  (errmsg_internal("postmaster received pmsignal signal")));
3708 
3709  /*
3710  * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
3711  * unexpected states. If the startup process quickly starts up, completes
3712  * recovery, exits, we might process the death of the startup process
3713  * first. We don't want to go back to recovery in that case.
3714  */
3717  {
3718  /* WAL redo has started. We're out of reinitialization. */
3719  FatalError = false;
3720  AbortStartTime = 0;
3721 
3722  /*
3723  * Start the archiver if we're responsible for (re-)archiving received
3724  * files.
3725  */
3726  Assert(PgArchPID == 0);
3727  if (XLogArchivingAlways())
3729 
3730  /*
3731  * If we aren't planning to enter hot standby mode later, treat
3732  * RECOVERY_STARTED as meaning we're out of startup, and report status
3733  * accordingly.
3734  */
3735  if (!EnableHotStandby)
3736  {
3738 #ifdef USE_SYSTEMD
3739  sd_notify(0, "READY=1");
3740 #endif
3741  }
3742 
3743  pmState = PM_RECOVERY;
3744  }
3745 
3748  {
3749  ereport(LOG,
3750  (errmsg("database system is ready to accept read-only connections")));
3751 
3752  /* Report status */
3754 #ifdef USE_SYSTEMD
3755  sd_notify(0, "READY=1");
3756 #endif
3757 
3759  connsAllowed = true;
3760 
3761  /* Some workers may be scheduled to start now */
3762  StartWorkerNeeded = true;
3763  }
3764 
3765  /* Process background worker state changes. */
3767  {
3768  /* Accept new worker requests only if not stopping. */
3770  StartWorkerNeeded = true;
3771  }
3772 
3775 
3776  /* Tell syslogger to rotate logfile if requested */
3777  if (SysLoggerPID != 0)
3778  {
3779  if (CheckLogrotateSignal())
3780  {
3783  }
3785  {
3787  }
3788  }
3789 
3792  {
3793  /*
3794  * Start one iteration of the autovacuum daemon, even if autovacuuming
3795  * is nominally not enabled. This is so we can have an active defense
3796  * against transaction ID wraparound. We set a flag for the main loop
3797  * to do it rather than trying to do it here --- this is because the
3798  * autovac process itself may send the signal, and we want to handle
3799  * that by launching another iteration as soon as the current one
3800  * completes.
3801  */
3802  start_autovac_launcher = true;
3803  }
3804 
3807  {
3808  /* The autovacuum launcher wants us to start a worker process. */
3810  }
3811 
3813  {
3814  /* Startup Process wants us to start the walreceiver process. */
3815  /* Start immediately if possible, else remember request for later. */
3816  WalReceiverRequested = true;
3818  }
3819 
3820  /*
3821  * Try to advance postmaster's state machine, if a child requests it.
3822  *
3823  * Be careful about the order of this action relative to this function's
3824  * other actions. Generally, this should be after other actions, in case
3825  * they have effects PostmasterStateMachine would need to know about.
3826  * However, we should do it before the CheckPromoteSignal step, which
3827  * cannot have any (immediate) effect on the state machine, but does
3828  * depend on what state we're in now.
3829  */
3831  {
3833  }
3834 
3835  if (StartupPID != 0 &&
3836  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
3837  pmState == PM_HOT_STANDBY) &&
3839  {
3840  /*
3841  * Tell startup process to finish recovery.
3842  *
3843  * Leave the promote signal file in place and let the Startup process
3844  * do the unlink.
3845  */
3847  }
3848 }
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:198
@ 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 MaybeStartWalReceiver(void)
Definition: postmaster.c:4051
static bool start_autovac_launcher
Definition: postmaster.c:356
static void StartAutovacuumWorker(void)
Definition: postmaster.c:3960
bool CheckLogrotateSignal(void)
Definition: syslogger.c:1573
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, HaveCrashedWorker, LOCK_FILE_LINE_PM_STATUS, LOG, maybe_start_bgworkers(), MaybeStartWalReceiver(), NoShutdown, pending_pm_pmsignal, PgArchPID, 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(), StartupPID, StartWorkerNeeded, SysLoggerPID, WalReceiverRequested, and XLogArchivingAlways.

Referenced by ServerLoop().

◆ process_pm_reload_request()

static void process_pm_reload_request ( void  )
static

Definition at line 2095 of file postmaster.c.

2096 {
2097  pending_pm_reload_request = false;
2098 
2099  ereport(DEBUG2,
2100  (errmsg_internal("postmaster received reload request signal")));
2101 
2102  if (Shutdown <= SmartShutdown)
2103  {
2104  ereport(LOG,
2105  (errmsg("received SIGHUP, reloading configuration files")));
2108  if (StartupPID != 0)
2110  if (BgWriterPID != 0)
2112  if (CheckpointerPID != 0)
2114  if (WalWriterPID != 0)
2116  if (WalReceiverPID != 0)
2118  if (WalSummarizerPID != 0)
2120  if (AutoVacPID != 0)
2122  if (PgArchPID != 0)
2124  if (SysLoggerPID != 0)
2126  if (SlotSyncWorkerPID != 0)
2128 
2129  /* Reload authentication config files too */
2130  if (!load_hba())
2131  ereport(LOG,
2132  /* translator: %s is a configuration file */
2133  (errmsg("%s was not reloaded", HbaFileName)));
2134 
2135  if (!load_ident())
2136  ereport(LOG,
2137  (errmsg("%s was not reloaded", IdentFileName)));
2138 
2139 #ifdef USE_SSL
2140  /* Reload SSL configuration as well */
2141  if (EnableSSL)
2142  {
2143  if (secure_initialize(false) == 0)
2144  LoadedSSL = true;
2145  else
2146  ereport(LOG,
2147  (errmsg("SSL configuration was not reloaded")));
2148  }
2149  else
2150  {
2151  secure_destroy();
2152  LoadedSSL = false;
2153  }
2154 #endif
2155 
2156 #ifdef EXEC_BACKEND
2157  /* Update the starting-point file for future children */
2158  write_nondefault_variables(PGC_SIGHUP);
2159 #endif
2160  }
2161 }
void secure_destroy(void)
Definition: be-secure.c:86
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
char * IdentFileName
Definition: guc_tables.c:541

References AutoVacPID, BgWriterPID, CheckpointerPID, DEBUG2, EnableSSL, ereport, errmsg(), errmsg_internal(), HbaFileName, IdentFileName, load_hba(), load_ident(), LoadedSSL, LOG, pending_pm_reload_request, PgArchPID, PGC_SIGHUP, ProcessConfigFile(), secure_destroy(), secure_initialize(), Shutdown, SIGHUP, signal_child(), SignalChildren, SlotSyncWorkerPID, SmartShutdown, StartupPID, SysLoggerPID, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

Referenced by ServerLoop().

◆ process_pm_shutdown_request()

static void process_pm_shutdown_request ( void  )
static

Definition at line 2192 of file postmaster.c.

2193 {
2194  int mode;
2195 
2196  ereport(DEBUG2,
2197  (errmsg_internal("postmaster received shutdown request signal")));
2198 
2200 
2201  /*
2202  * If more than one shutdown request signal arrived since the last server
2203  * loop, take the one that is the most immediate. That matches the
2204  * priority that would apply if we processed them one by one in any order.
2205  */
2207  {
2211  }
2213  {
2215  mode = FastShutdown;
2216  }
2217  else
2218  mode = SmartShutdown;
2219 
2220  switch (mode)
2221  {
2222  case SmartShutdown:
2223 
2224  /*
2225  * Smart Shutdown:
2226  *
2227  * Wait for children to end their work, then shut down.
2228  */
2229  if (Shutdown >= SmartShutdown)
2230  break;
2232  ereport(LOG,
2233  (errmsg("received smart shutdown request")));
2234 
2235  /* Report status */
2237 #ifdef USE_SYSTEMD
2238  sd_notify(0, "STOPPING=1");
2239 #endif
2240 
2241  /*
2242  * If we reached normal running, we go straight to waiting for
2243  * client backends to exit. If already in PM_STOP_BACKENDS or a
2244  * later state, do not change it.
2245  */
2246  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2247  connsAllowed = false;
2248  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2249  {
2250  /* There should be no clients, so proceed to stop children */
2252  }
2253 
2254  /*
2255  * Now wait for online backup mode to end and backends to exit. If
2256  * that is already the case, PostmasterStateMachine will take the
2257  * next step.
2258  */
2260  break;
2261 
2262  case FastShutdown:
2263 
2264  /*
2265  * Fast Shutdown:
2266  *
2267  * Abort all children with SIGTERM (rollback active transactions
2268  * and exit) and shut down when they are gone.
2269  */
2270  if (Shutdown >= FastShutdown)
2271  break;
2273  ereport(LOG,
2274  (errmsg("received fast shutdown request")));
2275 
2276  /* Report status */
2278 #ifdef USE_SYSTEMD
2279  sd_notify(0, "STOPPING=1");
2280 #endif
2281 
2282  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2283  {
2284  /* Just shut down background processes silently */
2286  }
2287  else if (pmState == PM_RUN ||
2289  {
2290  /* Report that we're about to zap live client sessions */
2291  ereport(LOG,
2292  (errmsg("aborting any active transactions")));
2294  }
2295 
2296  /*
2297  * PostmasterStateMachine will issue any necessary signals, or
2298  * take the next step if no child processes need to be killed.
2299  */
2301  break;
2302 
2303  case ImmediateShutdown:
2304 
2305  /*
2306  * Immediate Shutdown:
2307  *
2308  * abort all children with SIGQUIT, wait for them to exit,
2309  * terminate remaining ones with SIGKILL, then exit without
2310  * attempt to properly shut down the data base system.
2311  */
2312  if (Shutdown >= ImmediateShutdown)
2313  break;
2315  ereport(LOG,
2316  (errmsg("received immediate shutdown request")));
2317 
2318  /* Report status */
2320 #ifdef USE_SYSTEMD
2321  sd_notify(0, "STOPPING=1");
2322 #endif
2323 
2324  /* tell children to shut down ASAP */
2325  /* (note we don't apply send_abort_for_crash here) */
2329 
2330  /* set stopwatch for them to die */
2331  AbortStartTime = time(NULL);
2332 
2333  /*
2334  * Now wait for backends to exit. If there are none,
2335  * PostmasterStateMachine will take the next step.
2336  */
2338  break;
2339  }
2340 }
static PgChecksumMode mode
Definition: pg_checksums.c:56
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
#define FastShutdown
Definition: postmaster.c:266

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

◆ processCancelRequest()

void processCancelRequest ( int  backendPID,
int32  cancelAuthCode 
)

Definition at line 1835 of file postmaster.c.

1836 {
1837  Backend *bp;
1838 
1839 #ifndef EXEC_BACKEND
1840  dlist_iter iter;
1841 #else
1842  int i;
1843 #endif
1844 
1845  /*
1846  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
1847  * longer access the postmaster's own backend list, and must rely on the
1848  * duplicate array in shared memory.
1849  */
1850 #ifndef EXEC_BACKEND
1851  dlist_foreach(iter, &BackendList)
1852  {
1853  bp = dlist_container(Backend, elem, iter.cur);
1854 #else
1855  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
1856  {
1857  bp = (Backend *) &ShmemBackendArray[i];
1858 #endif
1859  if (bp->pid == backendPID)
1860  {
1861  if (bp->cancel_key == cancelAuthCode)
1862  {
1863  /* Found a match; signal that backend to cancel current op */
1864  ereport(DEBUG2,
1865  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
1866  backendPID)));
1867  signal_child(bp->pid, SIGINT);
1868  }
1869  else
1870  /* Right PID, wrong key: no way, Jose */
1871  ereport(LOG,
1872  (errmsg("wrong key in cancel request for process %d",
1873  backendPID)));
1874  return;
1875  }
1876 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
1877  }
1878 #else
1879  }
1880 #endif
1881 
1882  /* No matching backend */
1883  ereport(LOG,
1884  (errmsg("PID %d in cancel request did not match any process",
1885  backendPID)));
1886 }

References BackendList, bkend::cancel_key, dlist_iter::cur, DEBUG2, dlist_container, dlist_foreach, ereport, errmsg(), errmsg_internal(), i, LOG, MaxLivePostmasterChildren(), bkend::pid, and signal_child().

Referenced by ProcessStartupPacket().

◆ RandomCancelKey()

static bool RandomCancelKey ( int32 cancel_key)
static

Definition at line 3868 of file postmaster.c.

3869 {
3870  return pg_strong_random(cancel_key, sizeof(int32));
3871 }
signed int int32
Definition: c.h:481
bool pg_strong_random(void *buf, size_t len)

References pg_strong_random().

Referenced by assign_backendlist_entry(), BackendStartup(), and StartAutovacuumWorker().

◆ report_fork_failure_to_client()

static void report_fork_failure_to_client ( ClientSocket client_sock,
int  errnum 
)
static

Definition at line 3641 of file postmaster.c.

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

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

Referenced by BackendStartup().

◆ ServerLoop()

static int ServerLoop ( void  )
static

Definition at line 1624 of file postmaster.c.

1625 {
1626  time_t last_lockfile_recheck_time,
1627  last_touch_time;
1628  WaitEvent events[MAXLISTEN];
1629  int nevents;
1630 
1632  last_lockfile_recheck_time = last_touch_time = time(NULL);
1633 
1634  for (;;)
1635  {
1636  time_t now;
1637 
1638  nevents = WaitEventSetWait(pm_wait_set,
1640  events,
1641  lengthof(events),
1642  0 /* postmaster posts no wait_events */ );
1643 
1644  /*
1645  * Latch set by signal handler, or new connection pending on any of
1646  * our sockets? If the latter, fork a child process to deal with it.
1647  */
1648  for (int i = 0; i < nevents; i++)
1649  {
1650  if (events[i].events & WL_LATCH_SET)
1652 
1653  /*
1654  * The following requests are handled unconditionally, even if we
1655  * didn't see WL_LATCH_SET. This gives high priority to shutdown
1656  * and reload requests where the latch happens to appear later in
1657  * events[] or will be reported by a later call to
1658  * WaitEventSetWait().
1659  */
1666  if (pending_pm_pmsignal)
1668 
1669  if (events[i].events & WL_SOCKET_ACCEPT)
1670  {
1671  ClientSocket s;
1672 
1673  if (AcceptConnection(events[i].fd, &s) == STATUS_OK)
1674  BackendStartup(&s);
1675 
1676  /* We no longer need the open socket in this process */
1677  if (s.sock != PGINVALID_SOCKET)
1678  {
1679  if (closesocket(s.sock) != 0)
1680  elog(LOG, "could not close client socket: %m");
1681  }
1682  }
1683  }
1684 
1685  /* If we have lost the log collector, try to start a new one */
1686  if (SysLoggerPID == 0 && Logging_collector)
1688 
1689  /*
1690  * If no background writer process is running, and we are not in a
1691  * state that prevents it, start one. It doesn't matter if this
1692  * fails, we'll just try again later. Likewise for the checkpointer.
1693  */
1694  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
1696  {
1697  if (CheckpointerPID == 0)
1699  if (BgWriterPID == 0)
1701  }
1702 
1703  /*
1704  * Likewise, if we have lost the walwriter process, try to start a new
1705  * one. But this is needed only in normal operation (else we cannot
1706  * be writing any new WAL).
1707  */
1708  if (WalWriterPID == 0 && pmState == PM_RUN)
1710 
1711  /*
1712  * If we have lost the autovacuum launcher, try to start a new one. We
1713  * don't want autovacuum to run in binary upgrade mode because
1714  * autovacuum might update relfrozenxid for empty tables before the
1715  * physical files are put in place.
1716  */
1717  if (!IsBinaryUpgrade && AutoVacPID == 0 &&
1719  pmState == PM_RUN)
1720  {
1722  if (AutoVacPID != 0)
1723  start_autovac_launcher = false; /* signal processed */
1724  }
1725 
1726  /* If we have lost the archiver, try to start a new one. */
1727  if (PgArchPID == 0 && PgArchStartupAllowed())
1729 
1730  /* If we need to start a slot sync worker, try to do that now */
1732 
1733  /* If we need to signal the autovacuum launcher, do so now */
1735  {
1736  avlauncher_needs_signal = false;
1737  if (AutoVacPID != 0)
1739  }
1740 
1741  /* If we need to start a WAL receiver, try to do that now */
1744 
1745  /* If we need to start a WAL summarizer, try to do that now */
1747 
1748  /* Get other worker processes running, if needed */
1751 
1752 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1753 
1754  /*
1755  * With assertions enabled, check regularly for appearance of
1756  * additional threads. All builds check at start and exit.
1757  */
1758  Assert(pthread_is_threaded_np() == 0);
1759 #endif
1760 
1761  /*
1762  * Lastly, check to see if it's time to do some things that we don't
1763  * want to do every single time through the loop, because they're a
1764  * bit expensive. Note that there's up to a minute of slop in when
1765  * these tasks will be performed, since DetermineSleepTime() will let
1766  * us sleep at most that long; except for SIGKILL timeout which has
1767  * special-case logic there.
1768  */
1769  now = time(NULL);
1770 
1771  /*
1772  * If we already sent SIGQUIT to children and they are slow to shut
1773  * down, it's time to send them SIGKILL (or SIGABRT if requested).
1774  * This doesn't happen normally, but under certain conditions backends
1775  * can get stuck while shutting down. This is a last measure to get
1776  * them unwedged.
1777  *
1778  * Note we also do this during recovery from a process crash.
1779  */
1780  if ((Shutdown >= ImmediateShutdown || FatalError) &&
1781  AbortStartTime != 0 &&
1783  {
1784  /* We were gentle with them before. Not anymore */
1785  ereport(LOG,
1786  /* translator: %s is SIGKILL or SIGABRT */
1787  (errmsg("issuing %s to recalcitrant children",
1788  send_abort_for_kill ? "SIGABRT" : "SIGKILL")));
1790  /* reset flag so we don't SIGKILL again */
1791  AbortStartTime = 0;
1792  }
1793 
1794  /*
1795  * Once a minute, verify that postmaster.pid hasn't been removed or
1796  * overwritten. If it has, we force a shutdown. This avoids having
1797  * postmasters and child processes hanging around after their database
1798  * is gone, and maybe causing problems if a new database cluster is
1799  * created in the same place. It also provides some protection
1800  * against a DBA foolishly removing postmaster.pid and manually
1801  * starting a new postmaster. Data corruption is likely to ensue from
1802  * that anyway, but we can minimize the damage by aborting ASAP.
1803  */
1804  if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
1805  {
1806  if (!RecheckDataDirLockFile())
1807  {
1808  ereport(LOG,
1809  (errmsg("performing immediate shutdown because data directory lock file is invalid")));
1811  }
1812  last_lockfile_recheck_time = now;
1813  }
1814 
1815  /*
1816  * Touch Unix socket and lock files every 58 minutes, to ensure that
1817  * they are not removed by overzealous /tmp-cleaning tasks. We assume
1818  * no one runs cleaners with cutoff times of less than an hour ...
1819  */
1820  if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
1821  {
1822  TouchSocketFiles();
1824  last_touch_time = now;
1825  }
1826  }
1827 }
#define lengthof(array)
Definition: c.h:775
#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:1424
void ResetLatch(Latch *latch)
Definition: latch.c:724
void TouchSocketLockFiles(void)
Definition: miscinit.c:1482
bool RecheckDataDirLockFile(void)
Definition: miscinit.c:1638
static void process_pm_pmsignal(void)
Definition: postmaster.c:3702
static int DetermineSleepTime(void)
Definition: postmaster.c:1516
static void process_pm_child_exit(void)
Definition: postmaster.c:2353
bool send_abort_for_kill
Definition: postmaster.c:238
static int BackendStartup(ClientSocket *client_sock)
Definition: postmaster.c:3544
static void process_pm_shutdown_request(void)
Definition: postmaster.c:2192
static bool avlauncher_needs_signal
Definition: postmaster.c:359
static void process_pm_reload_request(void)
Definition: postmaster.c:2095
int AcceptConnection(pgsocket server_fd, ClientSocket *client_sock)
Definition: pqcomm.c:791
void TouchSocketFiles(void)
Definition: pqcomm.c:827
static int fd(const char *x, int i)
Definition: preproc-init.c:105
bool Logging_collector
Definition: syslogger.c:70
#define SIGABRT
Definition: win32_port.h:171
#define SIGKILL
Definition: win32_port.h:172

References AbortStartTime, AcceptConnection(), Assert(), AutoVacPID, AutoVacuumingActive(), avlauncher_needs_signal, B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_BG_WRITER, B_CHECKPOINTER, B_WAL_WRITER, BackendStartup(), BgWriterPID, CheckpointerPID, closesocket, ConfigurePostmasterWaitSet(), DetermineSleepTime(), elog, ereport, errmsg(), FatalError, fd(), HaveCrashedWorker, i, ImmediateShutdown, IsBinaryUpgrade, kill, lengthof, LOG, Logging_collector, MAXLISTEN, maybe_start_bgworkers(), MaybeStartSlotSyncWorker(), MaybeStartWalReceiver(), MaybeStartWalSummarizer(), MyLatch, MyProcPid, now(), pending_pm_child_exit, pending_pm_pmsignal, pending_pm_reload_request, pending_pm_shutdown_request, PgArchPID, PgArchStartupAllowed, PGINVALID_SOCKET, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, pm_wait_set, pmState, 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, start_autovac_launcher, StartChildProcess(), StartWorkerNeeded, STATUS_OK, SysLogger_Start(), SysLoggerPID, TerminateChildren(), TouchSocketFiles(), TouchSocketLockFiles(), WaitEventSetWait(), WalReceiverRequested, WalWriterPID, WL_LATCH_SET, and WL_SOCKET_ACCEPT.

Referenced by PostmasterMain().

◆ signal_child()

static void signal_child ( pid_t  pid,
int  signal 
)
static

Definition at line 3421 of file postmaster.c.

3422 {
3423  if (kill(pid, signal) < 0)
3424  elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
3425 #ifdef HAVE_SETSID
3426  switch (signal)
3427  {
3428  case SIGINT:
3429  case SIGTERM:
3430  case SIGQUIT:
3431  case SIGKILL:
3432  case SIGABRT:
3433  if (kill(-pid, signal) < 0)
3434  elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
3435  break;
3436  default:
3437  break;
3438  }
3439 #endif
3440 }

References DEBUG3, elog, kill, SIGABRT, SIGKILL, and SIGQUIT.

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

◆ SignalSomeChildren()

static bool SignalSomeChildren ( int  signal,
int  target 
)
static

Definition at line 3465 of file postmaster.c.

3466 {
3467  dlist_iter iter;
3468  bool signaled = false;
3469 
3470  dlist_foreach(iter, &BackendList)
3471  {
3472  Backend *bp = dlist_container(Backend, elem, iter.cur);
3473 
3474  if (bp->dead_end)
3475  continue;
3476 
3477  /*
3478  * Since target == BACKEND_TYPE_ALL is the most common case, we test
3479  * it first and avoid touching shared memory for every child.
3480  */
3481  if (target != BACKEND_TYPE_ALL)
3482  {
3483  /*
3484  * Assign bkend_type for any recently announced WAL Sender
3485  * processes.
3486  */
3487  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
3490 
3491  if (!(target & bp->bkend_type))
3492  continue;
3493  }
3494 
3495  ereport(DEBUG4,
3496  (errmsg_internal("sending signal %d to process %d",
3497  signal, (int) bp->pid)));
3498  signal_child(bp->pid, signal);
3499  signaled = true;
3500  }
3501  return signaled;
3502 }

References BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, bkend::bkend_type, bkend::child_slot, dlist_iter::cur, bkend::dead_end, DEBUG4, dlist_container, dlist_foreach, ereport, errmsg_internal(), IsPostmasterChildWalSender(), bkend::pid, and signal_child().

Referenced by PostmasterStateMachine().

◆ sigquit_child()

static void sigquit_child ( pid_t  pid)
static

Definition at line 3451 of file postmaster.c.

3452 {
3453  ereport(DEBUG2,
3454  (errmsg_internal("sending %s to process %d",
3455  (send_abort_for_crash ? "SIGABRT" : "SIGQUIT"),
3456  (int) pid)));
3458 }
bool send_abort_for_crash
Definition: postmaster.c:237

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

Referenced by HandleChildCrash().

◆ StartAutovacuumWorker()

static void StartAutovacuumWorker ( void  )
static

Definition at line 3960 of file postmaster.c.

3961 {
3962  Backend *bn;
3963 
3964  /*
3965  * If not in condition to run a process, don't try, but handle it like a
3966  * fork failure. This does not normally happen, since the signal is only
3967  * supposed to be sent by autovacuum launcher when it's OK to do it, but
3968  * we have to check to avoid race-condition problems during DB state
3969  * changes.
3970  */
3972  {
3973  /*
3974  * Compute the cancel key that will be assigned to this session. We
3975  * probably don't need cancel keys for autovac workers, but we'd
3976  * better have something random in the field to prevent unfriendly
3977  * people from sending cancels to them.
3978  */
3980  {
3981  ereport(LOG,
3982  (errcode(ERRCODE_INTERNAL_ERROR),
3983  errmsg("could not generate random cancel key")));
3984  return;
3985  }
3986 
3987  bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM);
3988  if (bn)
3989  {
3990  bn->cancel_key = MyCancelKey;
3991 
3992  /* Autovac workers are not dead_end and need a child slot */
3993  bn->dead_end = false;
3995  bn->bgworker_notify = false;
3996 
3998  if (bn->pid > 0)
3999  {
4002 #ifdef EXEC_BACKEND
4003  ShmemBackendArrayAdd(bn);
4004 #endif
4005  /* all OK */
4006  return;
4007  }
4008 
4009  /*
4010  * fork failed, fall through to report -- actual error message was
4011  * logged by StartChildProcess
4012  */
4014  pfree(bn);
4015  }
4016  else
4017  ereport(LOG,
4018  (errcode(ERRCODE_OUT_OF_MEMORY),
4019  errmsg("out of memory")));
4020  }
4021 
4022  /*
4023  * Report the failure to the launcher, if it's running. (If it's not, we
4024  * might not even be connected to shared memory, so don't try to call
4025  * AutoVacWorkerFailed.) Note that we also need to signal it so that it
4026  * responds to the condition, but we don't do that here, instead waiting
4027  * for ServerLoop to do it. This way we avoid a ping-pong signaling in
4028  * quick succession between the autovac launcher and postmaster in case
4029  * things get ugly.
4030  */
4031  if (AutoVacPID != 0)
4032  {
4034  avlauncher_needs_signal = true;
4035  }
4036 }
void AutoVacWorkerFailed(void)
Definition: autovacuum.c:1336
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:340
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:137

References AssignPostmasterChildSlot(), AutoVacPID, AutoVacWorkerFailed(), avlauncher_needs_signal, B_AUTOVAC_WORKER, BACKEND_TYPE_AUTOVAC, BackendList, bkend::bgworker_notify, bkend::bkend_type, CAC_OK, canAcceptConnections(), bkend::cancel_key, bkend::child_slot, bkend::dead_end, dlist_push_head(), bkend::elem, ereport, errcode(), errmsg(), LOG, MCXT_ALLOC_NO_OOM, MyCancelKey, MyPMChildSlot, palloc_extended(), pfree(), bkend::pid, RandomCancelKey(), ReleasePostmasterChildSlot(), and StartChildProcess().

Referenced by process_pm_pmsignal().

◆ StartChildProcess()

static pid_t StartChildProcess ( BackendType  type)
static

Definition at line 3924 of file postmaster.c.

3925 {
3926  pid_t pid;
3927 
3928  pid = postmaster_child_launch(type, NULL, 0, NULL);
3929  if (pid < 0)
3930  {
3931  /* in parent, fork failed */
3932  ereport(LOG,
3933  (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
3934 
3935  /*
3936  * fork failure is fatal during startup, but there's no need to choke
3937  * immediately if starting other child types fails.
3938  */
3939  if (type == B_STARTUP)
3940  ExitPostmaster(1);
3941  return 0;
3942  }
3943 
3944  /*
3945  * in parent, successful fork
3946  */
3947  return pid;
3948 }
const char * PostmasterChildName(BackendType child_type)
const char * type

References B_STARTUP, ereport, errmsg(), ExitPostmaster(), LOG, postmaster_child_launch(), PostmasterChildName(), and type.

Referenced by MaybeStartSlotSyncWorker(), MaybeStartWalReceiver(), MaybeStartWalSummarizer(), PostmasterMain(), PostmasterStateMachine(), process_pm_child_exit(), process_pm_pmsignal(), ServerLoop(), and StartAutovacuumWorker().

◆ TerminateChildren()

static void TerminateChildren ( int  signal)
static

Definition at line 3509 of file postmaster.c.

3510 {
3511  SignalChildren(signal);
3512  if (StartupPID != 0)
3513  {
3514  signal_child(StartupPID, signal);
3515  if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
3517  }
3518  if (BgWriterPID != 0)
3519  signal_child(BgWriterPID, signal);
3520  if (CheckpointerPID != 0)
3521  signal_child(CheckpointerPID, signal);
3522  if (WalWriterPID != 0)
3523  signal_child(WalWriterPID, signal);
3524  if (WalReceiverPID != 0)
3525  signal_child(WalReceiverPID, signal);
3526  if (WalSummarizerPID != 0)
3527  signal_child(WalSummarizerPID, signal);
3528  if (AutoVacPID != 0)
3529  signal_child(AutoVacPID, signal);
3530  if (PgArchPID != 0)
3531  signal_child(PgArchPID, signal);
3532  if (SlotSyncWorkerPID != 0)
3534 }

References AutoVacPID, BgWriterPID, CheckpointerPID, PgArchPID, SIGABRT, SIGKILL, signal_child(), SignalChildren, SIGQUIT, SlotSyncWorkerPID, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

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

1422 {
1423  if (external_pid_file)
1424  unlink(external_pid_file);
1425 }

References external_pid_file.

Referenced by PostmasterMain().

Variable Documentation

◆ AbortStartTime

◆ AuthenticationTimeout

int AuthenticationTimeout = 60

Definition at line 228 of file postmaster.c.

Referenced by BackendInitialize(), and PerformAuthentication().

◆ AutoVacPID

◆ avlauncher_needs_signal

bool avlauncher_needs_signal = false
static

Definition at line 359 of file postmaster.c.

Referenced by ServerLoop(), and StartAutovacuumWorker().

◆ BackendList

◆ BgWriterPID

◆ bonjour_name

char* bonjour_name

Definition at line 234 of file postmaster.c.

Referenced by PostmasterMain().

◆ CheckpointerPID

◆ ClientAuthInProgress

◆ connsAllowed

◆ enable_bonjour

bool enable_bonjour = false

Definition at line 233 of file postmaster.c.

Referenced by PostmasterMain().

◆ EnableSSL

bool EnableSSL = false

◆ FatalError

◆ HaveCrashedWorker

bool HaveCrashedWorker = false
static

◆ ListenAddresses

char* ListenAddresses

Definition at line 196 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 230 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 370 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 373 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 374 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 369 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

◆ PgArchPID

◆ pm_wait_set

WaitEventSet* pm_wait_set
static

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

Referenced by CreateLockFile(), and PostmasterMain().

◆ PreAuthDelay

int PreAuthDelay = 0

Definition at line 227 of file postmaster.c.

Referenced by BackendInitialize().

◆ ReachedNormalRunning

bool ReachedNormalRunning = false
static

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

Referenced by PostmasterStateMachine().

◆ ReservedConnections

int ReservedConnections

Definition at line 217 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ restart_after_crash

bool restart_after_crash = true

Definition at line 235 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ send_abort_for_crash

bool send_abort_for_crash = false

Definition at line 237 of file postmaster.c.

Referenced by sigquit_child().

◆ send_abort_for_kill

bool send_abort_for_kill = false

Definition at line 238 of file postmaster.c.

Referenced by ServerLoop().

◆ Shutdown

◆ SlotSyncWorkerPID

◆ start_autovac_launcher

bool start_autovac_launcher = false
static

Definition at line 356 of file postmaster.c.

Referenced by process_pm_pmsignal(), and ServerLoop().

◆ StartupPID

◆ StartupStatus

◆ StartWorkerNeeded

bool StartWorkerNeeded = true
static

◆ SuperuserReservedConnections

int SuperuserReservedConnections

Definition at line 216 of file postmaster.c.

Referenced by InitPostgres(), and PostmasterMain().

◆ SysLoggerPID

pid_t SysLoggerPID = 0
static

◆ Unix_socket_directories

char* Unix_socket_directories

Definition at line 193 of file postmaster.c.

Referenced by PostmasterMain().

◆ WalReceiverPID

◆ WalReceiverRequested

bool WalReceiverRequested = false
static

Definition at line 362 of file postmaster.c.

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

◆ WalSummarizerPID

◆ WalWriterPID