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/transam.h"
#include "access/xlog.h"
#include "access/xlogrecovery.h"
#include "catalog/pg_control.h"
#include "common/file_perm.h"
#include "common/ip.h"
#include "common/pg_prng.h"
#include "common/string.h"
#include "lib/ilist.h"
#include "libpq/auth.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "nodes/queryjumble.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/fork_process.h"
#include "postmaster/interrupt.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "replication/logicallauncher.h"
#include "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/ps_status.h"
#include "utils/timeout.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 StartupDataBase()   StartChildProcess(StartupProcess)
 
#define StartArchiver()   StartChildProcess(ArchiverProcess)
 
#define StartBackgroundWriter()   StartChildProcess(BgWriterProcess)
 
#define StartCheckpointer()   StartChildProcess(CheckpointerProcess)
 
#define StartWalWriter()   StartChildProcess(WalWriterProcess)
 
#define StartWalReceiver()   StartChildProcess(WalReceiverProcess)
 
#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 PortConnCreate (int serverFd)
 
static void ConnFree (Port *port)
 
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 process_startup_packet_die (SIGNAL_ARGS)
 
static void dummy_handler (SIGNAL_ARGS)
 
static void StartupPacketTimeoutHandler (void)
 
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 BackendInitialize (Port *port)
 
static void BackendRun (Port *port) pg_attribute_noreturn()
 
static void ExitPostmaster (int status) pg_attribute_noreturn()
 
static int ServerLoop (void)
 
static int BackendStartup (Port *port)
 
static int ProcessStartupPacket (Port *port, bool ssl_done, bool gss_done)
 
static void SendNegotiateProtocolVersion (List *unrecognized_protocol_options)
 
static void processCancelRequest (Port *port, void *pkt)
 
static void report_fork_failure_to_client (Port *port, 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 (AuxProcType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
void PostmasterMain (int argc, char *argv[])
 
static int DetermineSleepTime (void)
 
static void ConfigurePostmasterWaitSet (bool accept_connections)
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
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 pgsocket ListenSocket [MAXLISTEN]
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = 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 AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t SysLoggerPID = 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 148 of file postmaster.c.

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 145 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 147 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 144 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 146 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 567 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 568 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 569 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 272 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 273 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 228 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 270 of file postmaster.c.

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
bool PgArchCanRestart(void)
Definition: pgarch.c:192
@ PM_RUN
Definition: postmaster.c:326
@ PM_HOT_STANDBY
Definition: postmaster.c:325
@ PM_RECOVERY
Definition: postmaster.c:324
static PMState pmState
Definition: postmaster.c:337
#define XLogArchivingActive()
Definition: xlog.h:94
#define XLogArchivingAlways()
Definition: xlog.h:97

Definition at line 453 of file postmaster.c.

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 352 of file postmaster.c.

◆ SignalChildren

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

Definition at line 436 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 271 of file postmaster.c.

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 560 of file postmaster.c.

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 561 of file postmaster.c.

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 562 of file postmaster.c.

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 559 of file postmaster.c.

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 564 of file postmaster.c.

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 259 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5830 of file postmaster.c.

5831 {
5832  Backend *bn;
5833 
5834  /*
5835  * Check that database state allows another connection. Currently the
5836  * only possible failure is CAC_TOOMANY, so we just log an error message
5837  * based on that rather than checking the error code precisely.
5838  */
5840  {
5841  ereport(LOG,
5842  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5843  errmsg("no slot available for new worker process")));
5844  return false;
5845  }
5846 
5847  /*
5848  * Compute the cancel key that will be assigned to this session. We
5849  * probably don't need cancel keys for background workers, but we'd better
5850  * have something random in the field to prevent unfriendly people from
5851  * sending cancels to them.
5852  */
5854  {
5855  ereport(LOG,
5856  (errcode(ERRCODE_INTERNAL_ERROR),
5857  errmsg("could not generate random cancel key")));
5858  return false;
5859  }
5860 
5861  bn = malloc(sizeof(Backend));
5862  if (bn == NULL)
5863  {
5864  ereport(LOG,
5865  (errcode(ERRCODE_OUT_OF_MEMORY),
5866  errmsg("out of memory")));
5867  return false;
5868  }
5869 
5870  bn->cancel_key = MyCancelKey;
5873  bn->dead_end = false;
5874  bn->bgworker_notify = false;
5875 
5876  rw->rw_backend = bn;
5877  rw->rw_child_slot = bn->child_slot;
5878 
5879  return true;
5880 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int32 MyCancelKey
Definition: globals.c:48
int MyPMChildSlot
Definition: globals.c:49
#define malloc(a)
Definition: header.h:50
@ CAC_OK
Definition: libpq-be.h:63
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:247
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2470
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:147
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5273
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:183
int bkend_type
Definition: postmaster.c:181
bool dead_end
Definition: postmaster.c:182
int32 cancel_key
Definition: postmaster.c:179
int child_slot
Definition: postmaster.c:180

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, malloc, MyCancelKey, MyPMChildSlot, RandomCancelKey(), RegisteredBgWorker::rw_backend, and RegisteredBgWorker::rw_child_slot.

Referenced by do_start_bgworker().

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4273 of file postmaster.c.

4274 {
4275  int status;
4276  int ret;
4277  char remote_host[NI_MAXHOST];
4278  char remote_port[NI_MAXSERV];
4279  StringInfoData ps_data;
4280 
4281  /* Save port etc. for ps status */
4282  MyProcPort = port;
4283 
4284  /* Tell fd.c about the long-lived FD associated with the port */
4286 
4287  /*
4288  * PreAuthDelay is a debugging aid for investigating problems in the
4289  * authentication cycle: it can be set in postgresql.conf to allow time to
4290  * attach to the newly-forked backend with a debugger. (See also
4291  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4292  * is not honored until after authentication.)
4293  */
4294  if (PreAuthDelay > 0)
4295  pg_usleep(PreAuthDelay * 1000000L);
4296 
4297  /* This flag will remain set until InitPostgres finishes authentication */
4298  ClientAuthInProgress = true; /* limit visibility of log messages */
4299 
4300  /* set these to empty in case they are needed before we set them up */
4301  port->remote_host = "";
4302  port->remote_port = "";
4303 
4304  /*
4305  * Initialize libpq and enable reporting of ereport errors to the client.
4306  * Must do this now because authentication uses libpq to send messages.
4307  */
4308  pq_init(); /* initialize libpq to talk to client */
4309  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4310 
4311  /*
4312  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4313  * to collect the startup packet; while SIGQUIT results in _exit(2).
4314  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4315  * cleanly if a buggy client fails to send the packet promptly.
4316  *
4317  * Exiting with _exit(1) is only possible because we have not yet touched
4318  * shared memory; therefore no outside-the-process state needs to get
4319  * cleaned up.
4320  */
4322  /* SIGQUIT handler was already set up by InitPostmasterChild */
4323  InitializeTimeouts(); /* establishes SIGALRM handler */
4324  sigprocmask(SIG_SETMASK, &StartupBlockSig, NULL);
4325 
4326  /*
4327  * Get the remote host name and port for logging and status display.
4328  */
4329  remote_host[0] = '\0';
4330  remote_port[0] = '\0';
4331  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4332  remote_host, sizeof(remote_host),
4333  remote_port, sizeof(remote_port),
4334  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4335  ereport(WARNING,
4336  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4337  gai_strerror(ret))));
4338 
4339  /*
4340  * Save remote_host and remote_port in port structure (after this, they
4341  * will appear in log_line_prefix data for log messages).
4342  */
4343  port->remote_host = strdup(remote_host);
4344  port->remote_port = strdup(remote_port);
4345 
4346  /* And now we can issue the Log_connections message, if wanted */
4347  if (Log_connections)
4348  {
4349  if (remote_port[0])
4350  ereport(LOG,
4351  (errmsg("connection received: host=%s port=%s",
4352  remote_host,
4353  remote_port)));
4354  else
4355  ereport(LOG,
4356  (errmsg("connection received: host=%s",
4357  remote_host)));
4358  }
4359 
4360  /*
4361  * If we did a reverse lookup to name, we might as well save the results
4362  * rather than possibly repeating the lookup during authentication.
4363  *
4364  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4365  * get nothing useful for a client without an rDNS entry. Therefore, we
4366  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4367  * it into remote_hostname if so. (This test is conservative and might
4368  * sometimes classify a hostname as numeric, but an error in that
4369  * direction is safe; it only results in a possible extra lookup.)
4370  */
4371  if (log_hostname &&
4372  ret == 0 &&
4373  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4374  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4375  port->remote_hostname = strdup(remote_host);
4376 
4377  /*
4378  * Ready to begin client interaction. We will give up and _exit(1) after
4379  * a time delay, so that a broken client can't hog a connection
4380  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4381  * against the time limit.
4382  *
4383  * Note: AuthenticationTimeout is applied here while waiting for the
4384  * startup packet, and then again in InitPostgres for the duration of any
4385  * authentication operations. So a hostile client could tie up the
4386  * process for nearly twice AuthenticationTimeout before we kick him off.
4387  *
4388  * Note: because PostgresMain will call InitializeTimeouts again, the
4389  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4390  * since we never use it again after this function.
4391  */
4394 
4395  /*
4396  * Receive the startup packet (which might turn out to be a cancel request
4397  * packet).
4398  */
4399  status = ProcessStartupPacket(port, false, false);
4400 
4401  /*
4402  * Disable the timeout, and prevent SIGTERM again.
4403  */
4405  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
4406 
4407  /*
4408  * As a safety check that nothing in startup has yet performed
4409  * shared-memory modifications that would need to be undone if we had
4410  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4411  * handlers have been registered yet. (This isn't terribly bulletproof,
4412  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4413  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4414  * handlers unfortunately, since pq_init() already registered one.)
4415  */
4417 
4418  /*
4419  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4420  * already did any appropriate error reporting.
4421  */
4422  if (status != STATUS_OK)
4423  proc_exit(0);
4424 
4425  /*
4426  * Now that we have the user and database name, we can set the process
4427  * title for ps. It's good to do this as early as possible in startup.
4428  */
4429  initStringInfo(&ps_data);
4430  if (am_walsender)
4432  appendStringInfo(&ps_data, "%s ", port->user_name);
4433  if (port->database_name[0] != '\0')
4434  appendStringInfo(&ps_data, "%s ", port->database_name);
4435  appendStringInfoString(&ps_data, port->remote_host);
4436  if (port->remote_port[0] != '\0')
4437  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4438 
4439  init_ps_display(ps_data.data);
4440  pfree(ps_data.data);
4441 
4442  set_ps_display("initializing");
4443 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
#define STATUS_OK
Definition: c.h:1159
@ DestRemote
Definition: dest.h:89
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
#define WARNING
Definition: elog.h:36
void ReserveExternalFD(void)
Definition: fd.c:1127
struct Port * MyProcPort
Definition: globals.c:47
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
void check_on_shmem_exit_lists_are_empty(void)
Definition: ipc.c:428
void proc_exit(int code)
Definition: ipc.c:104
void pfree(void *pointer)
Definition: mcxt.c:1436
@ B_WAL_SENDER
Definition: miscadmin.h:331
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:264
static int port
Definition: pg_regress.c:90
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
pqsigfunc pqsignal(int signo, pqsigfunc func)
CommandDest whereToSendOutput
Definition: postgres.c:84
int PreAuthDelay
Definition: postmaster.c:234
bool log_hostname
Definition: postmaster.c:237
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5239
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5263
bool Log_connections
Definition: postmaster.c:238
bool ClientAuthInProgress
Definition: postmaster.c:356
int AuthenticationTimeout
Definition: postmaster.c:235
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:1948
void pq_init(void)
Definition: pqcomm.c:172
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:242
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
void pg_usleep(long microsec)
Definition: signal.c:53
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:564
void InitializeTimeouts(void)
Definition: timeout.c:474
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:689
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:509
@ STARTUP_PACKET_TIMEOUT
Definition: timeout.h:26
bool am_walsender
Definition: walsender.c:116

References am_walsender, appendStringInfo(), appendStringInfoString(), AuthenticationTimeout, B_WAL_SENDER, BlockSig, check_on_shmem_exit_lists_are_empty(), ClientAuthInProgress, StringInfoData::data, DestRemote, disable_timeout(), enable_timeout_after(), ereport, errmsg(), errmsg_internal(), GetBackendTypeDesc(), init_ps_display(), InitializeTimeouts(), initStringInfo(), LOG, Log_connections, log_hostname, MyProcPort, pfree(), pg_getnameinfo_all(), pg_usleep(), port, pq_init(), pqsignal(), PreAuthDelay, proc_exit(), process_startup_packet_die(), ProcessStartupPacket(), RegisterTimeout(), ReserveExternalFD(), set_ps_display(), STARTUP_PACKET_TIMEOUT, StartupBlockSig, StartupPacketTimeoutHandler(), status(), STATUS_OK, WARNING, and whereToSendOutput.

Referenced by BackendStartup().

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4453 of file postmaster.c.

4454 {
4455  /*
4456  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4457  * just yet, though, because InitPostgres will need the HBA data.)
4458  */
4460 
4461  PostgresMain(port->database_name, port->user_name);
4462 }
MemoryContext TopMemoryContext
Definition: mcxt.c:141
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4065

References MemoryContextSwitchTo(), port, PostgresMain(), and TopMemoryContext.

Referenced by BackendStartup().

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4113 of file postmaster.c.

4114 {
4115  Backend *bn; /* for backend cleanup */
4116  pid_t pid;
4117 
4118  /*
4119  * Create backend data structure. Better before the fork() so we can
4120  * handle failure cleanly.
4121  */
4122  bn = (Backend *) malloc(sizeof(Backend));
4123  if (!bn)
4124  {
4125  ereport(LOG,
4126  (errcode(ERRCODE_OUT_OF_MEMORY),
4127  errmsg("out of memory")));
4128  return STATUS_ERROR;
4129  }
4130 
4131  /*
4132  * Compute the cancel key that will be assigned to this backend. The
4133  * backend will have its own copy in the forked-off process' value of
4134  * MyCancelKey, so that it can transmit the key to the frontend.
4135  */
4137  {
4138  free(bn);
4139  ereport(LOG,
4140  (errcode(ERRCODE_INTERNAL_ERROR),
4141  errmsg("could not generate random cancel key")));
4142  return STATUS_ERROR;
4143  }
4144 
4145  bn->cancel_key = MyCancelKey;
4146 
4147  /* Pass down canAcceptConnections state */
4148  port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL);
4149  bn->dead_end = (port->canAcceptConnections != CAC_OK);
4150 
4151  /*
4152  * Unless it's a dead_end child, assign it a child slot number
4153  */
4154  if (!bn->dead_end)
4156  else
4157  bn->child_slot = 0;
4158 
4159  /* Hasn't asked to be notified about any bgworkers yet */
4160  bn->bgworker_notify = false;
4161 
4162 #ifdef EXEC_BACKEND
4163  pid = backend_forkexec(port);
4164 #else /* !EXEC_BACKEND */
4165  pid = fork_process();
4166  if (pid == 0) /* child */
4167  {
4168  free(bn);
4169 
4170  /* Detangle from postmaster */
4172 
4173  /* Close the postmaster's sockets */
4174  ClosePostmasterPorts(false);
4175 
4176  /* Perform additional initialization and collect startup packet */
4178 
4179  /*
4180  * Create a per-backend PGPROC struct in shared memory. We must do
4181  * this before we can use LWLocks. In the !EXEC_BACKEND case (here)
4182  * this could be delayed a bit further, but EXEC_BACKEND needs to do
4183  * stuff with LWLocks before PostgresMain(), so we do it here as well
4184  * for symmetry.
4185  */
4186  InitProcess();
4187 
4188  /* And run the backend */
4189  BackendRun(port);
4190  }
4191 #endif /* EXEC_BACKEND */
4192 
4193  if (pid < 0)
4194  {
4195  /* in parent, fork failed */
4196  int save_errno = errno;
4197 
4198  if (!bn->dead_end)
4200  free(bn);
4201  errno = save_errno;
4202  ereport(LOG,
4203  (errmsg("could not fork new process for connection: %m")));
4204  report_fork_failure_to_client(port, save_errno);
4205  return STATUS_ERROR;
4206  }
4207 
4208  /* in parent, successful fork */
4209  ereport(DEBUG2,
4210  (errmsg_internal("forked new backend, pid=%d socket=%d",
4211  (int) pid, (int) port->sock)));
4212 
4213  /*
4214  * Everything's been successful, it's safe to add this backend to our list
4215  * of backends.
4216  */
4217  bn->pid = pid;
4218  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4220 
4221 #ifdef EXEC_BACKEND
4222  if (!bn->dead_end)
4223  ShmemBackendArrayAdd(bn);
4224 #endif
4225 
4226  return STATUS_OK;
4227 }
#define STATUS_ERROR
Definition: c.h:1160
#define DEBUG2
Definition: elog.h:29
pid_t fork_process(void)
Definition: fork_process.c:32
#define free(a)
Definition: header.h:65
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
void InitPostmasterChild(void)
Definition: miscinit.c:95
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:284
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:144
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4453
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2574
static void BackendInitialize(Port *port)
Definition: postmaster.c:4273
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4238
static dlist_head BackendList
Definition: postmaster.c:187
void InitProcess(void)
Definition: proc.c:297
dlist_node elem
Definition: postmaster.c:184
pid_t pid
Definition: postmaster.c:178

References AssignPostmasterChildSlot(), BACKEND_TYPE_NORMAL, BackendInitialize(), BackendList, BackendRun(), bkend::bgworker_notify, bkend::bkend_type, CAC_OK, canAcceptConnections(), bkend::cancel_key, bkend::child_slot, ClosePostmasterPorts(), bkend::dead_end, DEBUG2, dlist_push_head(), bkend::elem, ereport, errcode(), errmsg(), errmsg_internal(), fork_process(), free, InitPostmasterChild(), InitProcess(), LOG, malloc, MyCancelKey, MyPMChildSlot, bkend::pid, port, RandomCancelKey(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5654 of file postmaster.c.

5655 {
5656  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
5657 }

References BlockSig.

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5600 of file postmaster.c.

5601 {
5603 
5604  /* XXX is this the right errcode? */
5606  ereport(FATAL,
5607  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5608  errmsg("database connection requirement not indicated during registration")));
5609 
5610  InitPostgres(dbname, InvalidOid, /* database to connect to */
5611  username, InvalidOid, /* role to connect as */
5612  false, /* never honor session_preload_libraries */
5613  (flags & BGWORKER_BYPASS_ALLOWCONN) != 0, /* ignore datallowconn? */
5614  NULL); /* no out_dbname */
5615 
5616  /* it had better not gotten out of "init" mode yet */
5617  if (!IsInitProcessingMode())
5618  ereport(ERROR,
5619  (errmsg("invalid processing mode in background worker")));
5621 }
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:155
#define FATAL
Definition: elog.h:41
#define ERROR
Definition: elog.h:39
@ NormalProcessing
Definition: miscadmin.h:400
#define IsInitProcessingMode()
Definition: miscadmin.h:406
#define SetProcessingMode(mode)
Definition: miscadmin.h:411
const char * username
Definition: pgbench.c:306
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bool load_session_libraries, bool override_allow_connections, char *out_dbname)
Definition: postinit.c:722
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:193
char * dbname
Definition: streamutil.c:51

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

Referenced by ApplyLauncherMain().

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5627 of file postmaster.c.

5628 {
5630 
5631  /* XXX is this the right errcode? */
5633  ereport(FATAL,
5634  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5635  errmsg("database connection requirement not indicated during registration")));
5636 
5637  InitPostgres(NULL, dboid, /* database to connect to */
5638  NULL, useroid, /* role to connect as */
5639  false, /* never honor session_preload_libraries */
5640  (flags & BGWORKER_BYPASS_ALLOWCONN) != 0, /* ignore datallowconn? */
5641  NULL); /* no out_dbname */
5642 
5643  /* it had better not gotten out of "init" mode yet */
5644  if (!IsInitProcessingMode())
5645  ereport(ERROR,
5646  (errmsg("invalid processing mode in background worker")));
5648 }

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

Referenced by autoprewarm_database_main(), InitializeApplyWorker(), and ParallelWorkerMain().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5660 of file postmaster.c.

5661 {
5662  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5663 }
sigset_t UnBlockSig
Definition: pqsignal.c:22

References UnBlockSig.

Referenced by ApplyLauncherMain(), ApplyWorkerMain(), autoprewarm_database_main(), autoprewarm_main(), ParallelApplyWorkerMain(), ParallelWorkerMain(), StartBackgroundWorker(), and test_shm_mq_main().

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5788 of file postmaster.c.

5789 {
5790  switch (pmState)
5791  {
5792  case PM_NO_CHILDREN:
5793  case PM_WAIT_DEAD_END:
5794  case PM_SHUTDOWN_2:
5795  case PM_SHUTDOWN:
5796  case PM_WAIT_BACKENDS:
5797  case PM_STOP_BACKENDS:
5798  break;
5799 
5800  case PM_RUN:
5802  return true;
5803  /* fall through */
5804 
5805  case PM_HOT_STANDBY:
5807  return true;
5808  /* fall through */
5809 
5810  case PM_RECOVERY:
5811  case PM_STARTUP:
5812  case PM_INIT:
5814  return true;
5815  /* fall through */
5816  }
5817 
5818  return false;
5819 }
@ 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 2470 of file postmaster.c.

2471 {
2472  CAC_state result = CAC_OK;
2473 
2474  /*
2475  * Can't start backends when in startup/shutdown/inconsistent recovery
2476  * state. We treat autovac workers the same as user backends for this
2477  * purpose. However, bgworkers are excluded from this test; we expect
2478  * bgworker_should_start_now() decided whether the DB state allows them.
2479  */
2480  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2481  backend_type != BACKEND_TYPE_BGWORKER)
2482  {
2483  if (Shutdown > NoShutdown)
2484  return CAC_SHUTDOWN; /* shutdown is pending */
2485  else if (!FatalError && pmState == PM_STARTUP)
2486  return CAC_STARTUP; /* normal startup */
2487  else if (!FatalError && pmState == PM_RECOVERY)
2488  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2489  * state */
2490  else
2491  return CAC_RECOVERY; /* else must be crash recovery */
2492  }
2493 
2494  /*
2495  * "Smart shutdown" restrictions are applied only to normal connections,
2496  * not to autovac workers or bgworkers.
2497  */
2498  if (!connsAllowed && backend_type == BACKEND_TYPE_NORMAL)
2499  return CAC_SHUTDOWN; /* shutdown is pending */
2500 
2501  /*
2502  * Don't start too many children.
2503  *
2504  * We allow more connections here than we can have backends because some
2505  * might still be authenticating; they might fail auth, or some existing
2506  * backend might exit before the auth cycle is completed. The exact
2507  * MaxBackends limit is enforced when a new backend tries to join the
2508  * shared-inval backend array.
2509  *
2510  * The limit here must match the sizes of the per-child-process arrays;
2511  * see comments for MaxLivePostmasterChildren().
2512  */
2514  result = CAC_TOOMANY;
2515 
2516  return result;
2517 }
CAC_state
Definition: libpq-be.h:62
@ CAC_TOOMANY
Definition: libpq-be.h:68
@ CAC_RECOVERY
Definition: libpq-be.h:66
@ CAC_NOTCONSISTENT
Definition: libpq-be.h:67
@ CAC_STARTUP
Definition: libpq-be.h:64
@ CAC_SHUTDOWN
Definition: libpq-be.h:65
static bool connsAllowed
Definition: postmaster.c:345
static int Shutdown
Definition: postmaster.c:275
#define BACKEND_TYPE_ALL
Definition: postmaster.c:148
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5590
#define NoShutdown
Definition: postmaster.c:270
static bool FatalError
Definition: postmaster.c:277
static int CountChildren(int target)
Definition: postmaster.c:5283

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

1581 {
1582  char path[MAXPGPATH];
1583  FILE *fp;
1584 
1585  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1586 
1587  fp = AllocateFile(path, PG_BINARY_R);
1588  if (fp == NULL)
1589  {
1590  write_stderr("%s: could not find the database system\n"
1591  "Expected to find it in the directory \"%s\",\n"
1592  "but could not open file \"%s\": %s\n",
1593  progname, DataDir, path, strerror(errno));
1594  ExitPostmaster(2);
1595  }
1596  FreeFile(fp);
1597 }
#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:2384
int FreeFile(FILE *file)
Definition: fd.c:2582
char * DataDir
Definition: globals.c:66
const char * progname
Definition: main.c:45
#define MAXPGPATH
#define strerror
Definition: port.h:251
#define snprintf
Definition: port.h:238
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5043

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

Referenced by PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

Definition at line 3383 of file postmaster.c.

3385 {
3386  dlist_mutable_iter iter;
3387 
3388  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3389 
3390  /*
3391  * If a backend dies in an ugly way then we must signal all other backends
3392  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3393  * assume everything is all right and proceed to remove the backend from
3394  * the active backend list.
3395  */
3396 
3397 #ifdef WIN32
3398 
3399  /*
3400  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3401  * since that sometimes happens under load when the process fails to start
3402  * properly (long before it starts using shared memory). Microsoft reports
3403  * it is related to mutex failure:
3404  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3405  */
3406  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3407  {
3408  LogChildExit(LOG, _("server process"), pid, exitstatus);
3409  exitstatus = 0;
3410  }
3411 #endif
3412 
3413  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3414  {
3415  HandleChildCrash(pid, exitstatus, _("server process"));
3416  return;
3417  }
3418 
3420  {
3421  Backend *bp = dlist_container(Backend, elem, iter.cur);
3422 
3423  if (bp->pid == pid)
3424  {
3425  if (!bp->dead_end)
3426  {
3428  {
3429  /*
3430  * Uh-oh, the child failed to clean itself up. Treat as a
3431  * crash after all.
3432  */
3433  HandleChildCrash(pid, exitstatus, _("server process"));
3434  return;
3435  }
3436 #ifdef EXEC_BACKEND
3437  ShmemBackendArrayRemove(bp);
3438 #endif
3439  }
3440  if (bp->bgworker_notify)
3441  {
3442  /*
3443  * This backend may have been slated to receive SIGUSR1 when
3444  * some background worker started or stopped. Cancel those
3445  * notifications, as we don't want to signal PIDs that are not
3446  * PostgreSQL backends. This gets skipped in the (probably
3447  * very common) case where the backend has never requested any
3448  * such notifications.
3449  */
3451  }
3452  dlist_delete(iter.cur);
3453  free(bp);
3454  break;
3455  }
3456  }
3457 }
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:517
#define _(x)
Definition: elog.c:91
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:3642
#define EXIT_STATUS_1(st)
Definition: postmaster.c:568
#define EXIT_STATUS_0(st)
Definition: postmaster.c:567
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3467
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, free, HandleChildCrash(), LOG, LogChildExit(), bkend::pid, and ReleasePostmasterChildSlot().

Referenced by process_pm_child_exit().

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3288 of file postmaster.c.

3290 {
3291  char namebuf[MAXPGPATH];
3292  slist_mutable_iter iter;
3293 
3295  {
3296  RegisteredBgWorker *rw;
3297 
3298  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3299 
3300  if (rw->rw_pid != pid)
3301  continue;
3302 
3303 #ifdef WIN32
3304  /* see CleanupBackend */
3305  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3306  exitstatus = 0;
3307 #endif
3308 
3309  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3310  rw->rw_worker.bgw_type);
3311 
3312 
3313  if (!EXIT_STATUS_0(exitstatus))
3314  {
3315  /* Record timestamp, so we know when to restart the worker. */
3317  }
3318  else
3319  {
3320  /* Zero exit status means terminate */
3321  rw->rw_crashed_at = 0;
3322  rw->rw_terminate = true;
3323  }
3324 
3325  /*
3326  * Additionally, just like a backend, any exit status other than 0 or
3327  * 1 is considered a crash and causes a system-wide restart.
3328  */
3329  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3330  {
3331  HandleChildCrash(pid, exitstatus, namebuf);
3332  return true;
3333  }
3334 
3335  /*
3336  * We must release the postmaster child slot. If the worker failed to
3337  * do so, it did not clean up after itself, requiring a crash-restart
3338  * cycle.
3339  */
3341  {
3342  HandleChildCrash(pid, exitstatus, namebuf);
3343  return true;
3344  }
3345 
3346  /* Get it out of the BackendList and clear out remaining data */
3347  dlist_delete(&rw->rw_backend->elem);
3348 #ifdef EXEC_BACKEND
3349  ShmemBackendArrayRemove(rw->rw_backend);
3350 #endif
3351 
3352  /*
3353  * It's possible that this background worker started some OTHER
3354  * background worker and asked to be notified when that worker started
3355  * or stopped. If so, cancel any notifications destined for the
3356  * now-dead backend.
3357  */
3358  if (rw->rw_backend->bgworker_notify)
3360  free(rw->rw_backend);
3361  rw->rw_backend = NULL;
3362  rw->rw_pid = 0;
3363  rw->rw_child_slot = 0;
3364  ReportBackgroundWorkerExit(&iter); /* report child death */
3365 
3366  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3367  namebuf, pid, exitstatus);
3368 
3369  return true;
3370  }
3371 
3372  return false;
3373 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1582
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:483
#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, free, GetCurrentTimestamp(), HandleChildCrash(), LOG, LogChildExit(), MAXPGPATH, 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 2574 of file postmaster.c.

2575 {
2576  int i;
2577 
2578  /* Release resources held by the postmaster's WaitEventSet. */
2579  if (pm_wait_set)
2580  {
2582  pm_wait_set = NULL;
2583  }
2584 
2585 #ifndef WIN32
2586 
2587  /*
2588  * Close the write end of postmaster death watch pipe. It's important to
2589  * do this as early as possible, so that if postmaster dies, others won't
2590  * think that it's still running because we're holding the pipe open.
2591  */
2593  ereport(FATAL,
2595  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2597  /* Notify fd.c that we released one pipe FD. */
2599 #endif
2600 
2601  /*
2602  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2603  * so we don't call ReleaseExternalFD() here.
2604  */
2605  for (i = 0; i < MAXLISTEN; i++)
2606  {
2608  {
2611  }
2612  }
2613 
2614  /*
2615  * If using syslogger, close the read side of the pipe. We don't bother
2616  * tracking this in fd.c, either.
2617  */
2618  if (!am_syslogger)
2619  {
2620 #ifndef WIN32
2621  if (syslogPipe[0] >= 0)
2622  close(syslogPipe[0]);
2623  syslogPipe[0] = -1;
2624 #else
2625  if (syslogPipe[0])
2626  CloseHandle(syslogPipe[0]);
2627  syslogPipe[0] = 0;
2628 #endif
2629  }
2630 
2631 #ifdef USE_BONJOUR
2632  /* If using Bonjour, close the connection to the mDNS daemon */
2633  if (bonjour_sdref)
2634  close(DNSServiceRefSockFD(bonjour_sdref));
2635 #endif
2636 }
int errcode_for_file_access(void)
Definition: elog.c:881
void ReleaseExternalFD(void)
Definition: fd.c:1145
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:876
#define PGINVALID_SOCKET
Definition: port.h:31
int postmaster_alive_fds[2]
Definition: postmaster.c:576
static WaitEventSet * pm_wait_set
Definition: postmaster.c:383
#define MAXLISTEN
Definition: postmaster.c:228
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:229
#define POSTMASTER_FD_OWN
Definition: postmaster.h:47
void StreamClose(pgsocket sock)
Definition: pqcomm.c:832
int syslogPipe[2]
Definition: syslogger.c:117

References close, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, FreeWaitEventSetAfterFork(), i, ListenSocket, MAXLISTEN, PGINVALID_SOCKET, pm_wait_set, postmaster_alive_fds, POSTMASTER_FD_OWN, ReleaseExternalFD(), StreamClose(), and syslogPipe.

Referenced by BackendStartup(), do_start_bgworker(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1478 of file postmaster.c.

1479 {
1480  int i;
1481 
1482  /*
1483  * First, explicitly close all the socket FDs. We used to just let this
1484  * happen implicitly at postmaster exit, but it's better to close them
1485  * before we remove the postmaster.pid lockfile; otherwise there's a race
1486  * condition if a new postmaster wants to re-use the TCP port number.
1487  */
1488  for (i = 0; i < MAXLISTEN; i++)
1489  {
1491  {
1494  }
1495  }
1496 
1497  /*
1498  * Next, remove any filesystem entries for Unix sockets. To avoid race
1499  * conditions against incoming postmasters, this must happen after closing
1500  * the sockets and before removing lock files.
1501  */
1503 
1504  /*
1505  * We don't do anything about socket lock files here; those will be
1506  * removed in a later on_proc_exit callback.
1507  */
1508 }
void RemoveSocketFiles(void)
Definition: pqcomm.c:865

References i, ListenSocket, MAXLISTEN, PGINVALID_SOCKET, RemoveSocketFiles(), and StreamClose().

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1694 of file postmaster.c.

1695 {
1696  int nsockets;
1697 
1698  if (pm_wait_set)
1700  pm_wait_set = NULL;
1701 
1702  /* How many server sockets do we need to wait for? */
1703  nsockets = 0;
1704  if (accept_connections)
1705  {
1706  while (nsockets < MAXLISTEN &&
1707  ListenSocket[nsockets] != PGINVALID_SOCKET)
1708  ++nsockets;
1709  }
1710 
1713  NULL);
1714 
1715  if (accept_connections)
1716  {
1717  for (int i = 0; i < nsockets; i++)
1719  NULL, NULL);
1720  }
1721 }
struct Latch * MyLatch
Definition: globals.c:58
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:723
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:922
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:837
#define WL_SOCKET_ACCEPT
Definition: latch.h:142
#define WL_LATCH_SET
Definition: latch.h:125
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135

References AddWaitEventToSet(), CreateWaitEventSet(), CurrentMemoryContext, FreeWaitEventSet(), i, ListenSocket, MAXLISTEN, MyLatch, PGINVALID_SOCKET, pm_wait_set, WL_LATCH_SET, and WL_SOCKET_ACCEPT.

Referenced by PostmasterStateMachine(), and ServerLoop().

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2526 of file postmaster.c.

2527 {
2528  Port *port;
2529 
2530  if (!(port = (Port *) calloc(1, sizeof(Port))))
2531  {
2532  ereport(LOG,
2533  (errcode(ERRCODE_OUT_OF_MEMORY),
2534  errmsg("out of memory")));
2535  ExitPostmaster(1);
2536  }
2537 
2538  if (StreamConnection(serverFd, port) != STATUS_OK)
2539  {
2540  if (port->sock != PGINVALID_SOCKET)
2541  StreamClose(port->sock);
2542  ConnFree(port);
2543  return NULL;
2544  }
2545 
2546  return port;
2547 }
#define calloc(a, b)
Definition: header.h:55
static void ConnFree(Port *port)
Definition: postmaster.c:2557
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:698
Definition: libpq-be.h:146

References calloc, ConnFree(), ereport, errcode(), errmsg(), ExitPostmaster(), LOG, PGINVALID_SOCKET, port, STATUS_OK, StreamClose(), and StreamConnection().

Referenced by ServerLoop().

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2557 of file postmaster.c.

2558 {
2559  free(port);
2560 }

References free, and port.

Referenced by ConnCreate(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5283 of file postmaster.c.

5284 {
5285  dlist_iter iter;
5286  int cnt = 0;
5287 
5288  dlist_foreach(iter, &BackendList)
5289  {
5290  Backend *bp = dlist_container(Backend, elem, iter.cur);
5291 
5292  if (bp->dead_end)
5293  continue;
5294 
5295  /*
5296  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5297  * it first and avoid touching shared memory for every child.
5298  */
5299  if (target != BACKEND_TYPE_ALL)
5300  {
5301  /*
5302  * Assign bkend_type for any recently announced WAL Sender
5303  * processes.
5304  */
5305  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5308 
5309  if (!(target & bp->bkend_type))
5310  continue;
5311  }
5312 
5313  cnt++;
5314  }
5315  return cnt;
5316 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:307
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:146
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 5546 of file postmaster.c.

5547 {
5548  FILE *fp;
5549  int i;
5550 
5551 #define OPTS_FILE "postmaster.opts"
5552 
5553  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5554  {
5555  ereport(LOG,
5557  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5558  return false;
5559  }
5560 
5561  fprintf(fp, "%s", fullprogname);
5562  for (i = 1; i < argc; i++)
5563  fprintf(fp, " \"%s\"", argv[i]);
5564  fputs("\n", fp);
5565 
5566  if (fclose(fp))
5567  {
5568  ereport(LOG,
5570  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5571  return false;
5572  }
5573 
5574  return true;
5575 }
#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 1609 of file postmaster.c.

1610 {
1611  TimestampTz next_wakeup = 0;
1612 
1613  /*
1614  * Normal case: either there are no background workers at all, or we're in
1615  * a shutdown sequence (during which we ignore bgworkers altogether).
1616  */
1617  if (Shutdown > NoShutdown ||
1619  {
1620  if (AbortStartTime != 0)
1621  {
1622  int seconds;
1623 
1624  /* time left to abort; clamp to 0 in case it already expired */
1625  seconds = SIGKILL_CHILDREN_AFTER_SECS -
1626  (time(NULL) - AbortStartTime);
1627 
1628  return Max(seconds * 1000, 0);
1629  }
1630  else
1631  return 60 * 1000;
1632  }
1633 
1634  if (StartWorkerNeeded)
1635  return 0;
1636 
1637  if (HaveCrashedWorker)
1638  {
1639  slist_mutable_iter siter;
1640 
1641  /*
1642  * When there are crashed bgworkers, we sleep just long enough that
1643  * they are restarted when they request to be. Scan the list to
1644  * determine the minimum of all wakeup times according to most recent
1645  * crash time and requested restart interval.
1646  */
1648  {
1649  RegisteredBgWorker *rw;
1650  TimestampTz this_wakeup;
1651 
1652  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1653 
1654  if (rw->rw_crashed_at == 0)
1655  continue;
1656 
1658  || rw->rw_terminate)
1659  {
1660  ForgetBackgroundWorker(&siter);
1661  continue;
1662  }
1663 
1664  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1665  1000L * rw->rw_worker.bgw_restart_time);
1666  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1667  next_wakeup = this_wakeup;
1668  }
1669  }
1670 
1671  if (next_wakeup != 0)
1672  {
1673  int ms;
1674 
1675  /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1677  next_wakeup);
1678  return Min(60 * 1000, ms);
1679  }
1680 
1681  return 60 * 1000;
1682 }
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1703
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:429
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Min(x, y)
Definition: c.h:988
#define Max(x, y)
Definition: c.h:982
int64 TimestampTz
Definition: timestamp.h:39
static bool HaveCrashedWorker
Definition: postmaster.c:372
static time_t AbortStartTime
Definition: postmaster.c:349
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:352
static bool StartWorkerNeeded
Definition: postmaster.c:371
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 5696 of file postmaster.c.

5697 {
5698  pid_t worker_pid;
5699 
5700  Assert(rw->rw_pid == 0);
5701 
5702  /*
5703  * Allocate and assign the Backend element. Note we must do this before
5704  * forking, so that we can handle failures (out of memory or child-process
5705  * slots) cleanly.
5706  *
5707  * Treat failure as though the worker had crashed. That way, the
5708  * postmaster will wait a bit before attempting to start it again; if we
5709  * tried again right away, most likely we'd find ourselves hitting the
5710  * same resource-exhaustion condition.
5711  */
5712  if (!assign_backendlist_entry(rw))
5713  {
5715  return false;
5716  }
5717 
5718  ereport(DEBUG1,
5719  (errmsg_internal("starting background worker process \"%s\"",
5720  rw->rw_worker.bgw_name)));
5721 
5722 #ifdef EXEC_BACKEND
5723  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5724 #else
5725  switch ((worker_pid = fork_process()))
5726 #endif
5727  {
5728  case -1:
5729  /* in postmaster, fork failed ... */
5730  ereport(LOG,
5731  (errmsg("could not fork worker process: %m")));
5732  /* undo what assign_backendlist_entry did */
5734  rw->rw_child_slot = 0;
5735  free(rw->rw_backend);
5736  rw->rw_backend = NULL;
5737  /* mark entry as crashed, so we'll try again later */
5739  break;
5740 
5741 #ifndef EXEC_BACKEND
5742  case 0:
5743  /* in postmaster child ... */
5745 
5746  /* Close the postmaster's sockets */
5747  ClosePostmasterPorts(false);
5748 
5749  /*
5750  * Before blowing away PostmasterContext, save this bgworker's
5751  * data where it can find it.
5752  */
5755  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5756 
5757  /* Release postmaster's working memory context */
5760  PostmasterContext = NULL;
5761 
5763 
5764  exit(1); /* should not get here */
5765  break;
5766 #endif
5767  default:
5768  /* in postmaster, fork successful ... */
5769  rw->rw_pid = worker_pid;
5770  rw->rw_backend->pid = rw->rw_pid;
5772  /* add new worker to lists of backends */
5774 #ifdef EXEC_BACKEND
5775  ShmemBackendArrayAdd(rw->rw_backend);
5776 #endif
5777  return true;
5778  }
5779 
5780  return false;
5781 }
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:464
void StartBackgroundWorker(void)
Definition: bgworker.c:744
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1005
MemoryContext PostmasterContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5830
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91

References Assert(), assign_backendlist_entry(), BackendList, BackgroundWorker::bgw_name, ClosePostmasterPorts(), DEBUG1, dlist_push_head(), bkend::elem, ereport, errmsg(), errmsg_internal(), exit(), fork_process(), free, GetCurrentTimestamp(), InitPostmasterChild(), LOG, MemoryContextAlloc(), MemoryContextDelete(), MemoryContextSwitchTo(), MyBgworkerEntry, bkend::pid, PostmasterContext, ReleasePostmasterChildSlot(), ReportBackgroundWorkerPID(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_shmem_slot, RegisteredBgWorker::rw_worker, StartBackgroundWorker(), and TopMemoryContext.

Referenced by maybe_start_bgworkers().

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5254 of file postmaster.c.

5255 {
5256 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5043 of file postmaster.c.

5044 {
5045 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5046 
5047  /*
5048  * There is no known cause for a postmaster to become multithreaded after
5049  * startup. Recheck to account for the possibility of unknown causes.
5050  * This message uses LOG level, because an unclean shutdown at this point
5051  * would usually not look much different from a clean shutdown.
5052  */
5053  if (pthread_is_threaded_np() != 0)
5054  ereport(LOG,
5055  (errcode(ERRCODE_INTERNAL_ERROR),
5056  errmsg_internal("postmaster became multithreaded"),
5057  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5058 #endif
5059 
5060  /* should cleanup shared memory and kill all backends */
5061 
5062  /*
5063  * Not sure of the semantics here. When the Postmaster dies, should the
5064  * backends all be killed? probably not.
5065  *
5066  * MUST -- vadim 05-10-1999
5067  */
5068 
5069  proc_exit(status);
5070 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202

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

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1526 of file postmaster.c.

1527 {
1528  DIR *pdir;
1529 
1530  /* Locate the postgres executable itself */
1531  if (find_my_exec(argv0, my_exec_path) < 0)
1532  ereport(FATAL,
1533  (errmsg("%s: could not locate my own executable path", argv0)));
1534 
1535 #ifdef EXEC_BACKEND
1536  /* Locate executable backend before we change working directory */
1537  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1538  postgres_exec_path) < 0)
1539  ereport(FATAL,
1540  (errmsg("%s: could not locate matching postgres executable",
1541  argv0)));
1542 #endif
1543 
1544  /*
1545  * Locate the pkglib directory --- this has to be set early in case we try
1546  * to load any modules from it in response to postgresql.conf entries.
1547  */
1549 
1550  /*
1551  * Verify that there's a readable directory there; otherwise the Postgres
1552  * installation is incomplete or corrupt. (A typical cause of this
1553  * failure is that the postgres executable has been moved or hardlinked to
1554  * some directory that's not a sibling of the installation lib/
1555  * directory.)
1556  */
1557  pdir = AllocateDir(pkglib_path);
1558  if (pdir == NULL)
1559  ereport(ERROR,
1561  errmsg("could not open directory \"%s\": %m",
1562  pkglib_path),
1563  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1564  my_exec_path)));
1565  FreeDir(pdir);
1566 
1567  /*
1568  * XXX is it worth similarly checking the share/ directory? If the lib/
1569  * directory is there, then share/ probably is too.
1570  */
1571 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:158
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:327
int errhint(const char *fmt,...)
Definition: elog.c:1316
int FreeDir(DIR *dir)
Definition: fd.c:2762
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2644
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
static char * argv0
Definition: pg_ctl.c:92
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879
#define PG_BACKEND_VERSIONSTR
Definition: port.h:143
Definition: dirent.c:26

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

Referenced by PostmasterMain().

◆ handle_pm_child_exit_signal()

static void handle_pm_child_exit_signal ( SIGNAL_ARGS  )
static

Definition at line 2964 of file postmaster.c.

2965 {
2966  int save_errno = errno;
2967 
2968  pending_pm_child_exit = true;
2969  SetLatch(MyLatch);
2970 
2971  errno = save_errno;
2972 }
void SetLatch(Latch *latch)
Definition: latch.c:607
static volatile sig_atomic_t pending_pm_child_exit
Definition: postmaster.c:376

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

2689 {
2690  int save_errno = errno;
2691 
2692  pending_pm_pmsignal = true;
2693  SetLatch(MyLatch);
2694 
2695  errno = save_errno;
2696 }
static volatile sig_atomic_t pending_pm_pmsignal
Definition: postmaster.c:375

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

2703 {
2704  int save_errno = errno;
2705 
2707  SetLatch(MyLatch);
2708 
2709  errno = save_errno;
2710 }
static volatile sig_atomic_t pending_pm_reload_request
Definition: postmaster.c:377

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

2786 {
2787  int save_errno = errno;
2788 
2789  switch (postgres_signal_arg)
2790  {
2791  case SIGTERM:
2792  /* smart is implied if the other two flags aren't set */
2794  break;
2795  case SIGINT:
2798  break;
2799  case SIGQUIT:
2802  break;
2803  }
2804  SetLatch(MyLatch);
2805 
2806  errno = save_errno;
2807 }
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition: postmaster.c:379
static volatile sig_atomic_t pending_pm_shutdown_request
Definition: postmaster.c:378
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition: postmaster.c:380
#define SIGQUIT
Definition: win32_port.h:177

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

3468 {
3469  dlist_mutable_iter iter;
3470  slist_iter siter;
3471  Backend *bp;
3472  bool take_action;
3473 
3474  /*
3475  * We only log messages and send signals if this is the first process
3476  * crash and we're not doing an immediate shutdown; otherwise, we're only
3477  * here to update postmaster's idea of live processes. If we have already
3478  * signaled children, nonzero exit status is to be expected, so don't
3479  * clutter log.
3480  */
3481  take_action = !FatalError && Shutdown != ImmediateShutdown;
3482 
3483  if (take_action)
3484  {
3485  LogChildExit(LOG, procname, pid, exitstatus);
3486  ereport(LOG,
3487  (errmsg("terminating any other active server processes")));
3489  }
3490 
3491  /* Process background workers. */
3493  {
3494  RegisteredBgWorker *rw;
3495 
3496  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3497  if (rw->rw_pid == 0)
3498  continue; /* not running */
3499  if (rw->rw_pid == pid)
3500  {
3501  /*
3502  * Found entry for freshly-dead worker, so remove it.
3503  */
3505  dlist_delete(&rw->rw_backend->elem);
3506 #ifdef EXEC_BACKEND
3507  ShmemBackendArrayRemove(rw->rw_backend);
3508 #endif
3509  free(rw->rw_backend);
3510  rw->rw_backend = NULL;
3511  rw->rw_pid = 0;
3512  rw->rw_child_slot = 0;
3513  /* don't reset crashed_at */
3514  /* don't report child stop, either */
3515  /* Keep looping so we can signal remaining workers */
3516  }
3517  else
3518  {
3519  /*
3520  * This worker is still alive. Unless we did so already, tell it
3521  * to commit hara-kiri.
3522  */
3523  if (take_action)
3524  sigquit_child(rw->rw_pid);
3525  }
3526  }
3527 
3528  /* Process regular backends */
3530  {
3531  bp = dlist_container(Backend, elem, iter.cur);
3532 
3533  if (bp->pid == pid)
3534  {
3535  /*
3536  * Found entry for freshly-dead backend, so remove it.
3537  */
3538  if (!bp->dead_end)
3539  {
3541 #ifdef EXEC_BACKEND
3542  ShmemBackendArrayRemove(bp);
3543 #endif
3544  }
3545  dlist_delete(iter.cur);
3546  free(bp);
3547  /* Keep looping so we can signal remaining backends */
3548  }
3549  else
3550  {
3551  /*
3552  * This backend is still alive. Unless we did so already, tell it
3553  * to commit hara-kiri.
3554  *
3555  * We could exclude dead_end children here, but at least when
3556  * sending SIGABRT it seems better to include them.
3557  *
3558  * Background workers were already processed above; ignore them
3559  * here.
3560  */
3561  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3562  continue;
3563 
3564  if (take_action)
3565  sigquit_child(bp->pid);
3566  }
3567  }
3568 
3569  /* Take care of the startup process too */
3570  if (pid == StartupPID)
3571  {
3572  StartupPID = 0;
3573  /* Caller adjusts StartupStatus, so don't touch it here */
3574  }
3575  else if (StartupPID != 0 && take_action)
3576  {
3579  }
3580 
3581  /* Take care of the bgwriter too */
3582  if (pid == BgWriterPID)
3583  BgWriterPID = 0;
3584  else if (BgWriterPID != 0 && take_action)
3586 
3587  /* Take care of the checkpointer too */
3588  if (pid == CheckpointerPID)
3589  CheckpointerPID = 0;
3590  else if (CheckpointerPID != 0 && take_action)
3592 
3593  /* Take care of the walwriter too */
3594  if (pid == WalWriterPID)
3595  WalWriterPID = 0;
3596  else if (WalWriterPID != 0 && take_action)
3598 
3599  /* Take care of the walreceiver too */
3600  if (pid == WalReceiverPID)
3601  WalReceiverPID = 0;
3602  else if (WalReceiverPID != 0 && take_action)
3604 
3605  /* Take care of the autovacuum launcher too */
3606  if (pid == AutoVacPID)
3607  AutoVacPID = 0;
3608  else if (AutoVacPID != 0 && take_action)
3610 
3611  /* Take care of the archiver too */
3612  if (pid == PgArchPID)
3613  PgArchPID = 0;
3614  else if (PgArchPID != 0 && take_action)
3616 
3617  /* We do NOT restart the syslogger */
3618 
3619  if (Shutdown != ImmediateShutdown)
3620  FatalError = true;
3621 
3622  /* We now transit into a state of waiting for children to die */
3623  if (pmState == PM_RECOVERY ||
3624  pmState == PM_HOT_STANDBY ||
3625  pmState == PM_RUN ||
3627  pmState == PM_SHUTDOWN)
3629 
3630  /*
3631  * .. and if this doesn't happen quickly enough, now the clock is ticking
3632  * for us to kill them without mercy.
3633  */
3634  if (AbortStartTime == 0)
3635  AbortStartTime = time(NULL);
3636 }
#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:253
static pid_t PgArchPID
Definition: postmaster.c:255
#define ImmediateShutdown
Definition: postmaster.c:273
static pid_t AutoVacPID
Definition: postmaster.c:254
static pid_t CheckpointerPID
Definition: postmaster.c:251
static pid_t BgWriterPID
Definition: postmaster.c:250
static pid_t WalWriterPID
Definition: postmaster.c:252
static StartupStatusEnum StartupStatus
Definition: postmaster.c:267
static void sigquit_child(pid_t pid)
Definition: postmaster.c:4024
static pid_t StartupPID
Definition: postmaster.c:249
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, free, ImmediateShutdown, LOG, LogChildExit(), 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, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6499 of file postmaster.c.

6500 {
6501 #ifndef WIN32
6502 
6503  /*
6504  * Create a pipe. Postmaster holds the write end of the pipe open
6505  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6506  * the read file descriptor to select() to wake up in case postmaster
6507  * dies, or check for postmaster death with a (read() == 0). Children must
6508  * close the write end as soon as possible after forking, because EOF
6509  * won't be signaled in the read end until all processes have closed the
6510  * write fd. That is taken care of in ClosePostmasterPorts().
6511  */
6513  if (pipe(postmaster_alive_fds) < 0)
6514  ereport(FATAL,
6516  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6517 
6518  /* Notify fd.c that we've eaten two FDs for the pipe. */
6521 
6522  /*
6523  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6524  * call.
6525  */
6526  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6527  ereport(FATAL,
6529  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6530 #else
6531 
6532  /*
6533  * On Windows, we use a process handle for the same purpose.
6534  */
6535  if (DuplicateHandle(GetCurrentProcess(),
6536  GetCurrentProcess(),
6537  GetCurrentProcess(),
6538  &PostmasterHandle,
6539  0,
6540  TRUE,
6541  DUPLICATE_SAME_ACCESS) == 0)
6542  ereport(FATAL,
6543  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6544  GetLastError())));
6545 #endif /* WIN32 */
6546 }
int errcode_for_socket_access(void)
Definition: elog.c:952
pid_t PostmasterPid
Definition: globals.c:99
int MyProcPid
Definition: globals.c:44
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46

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

2646 {
2647  MyProcPid = getpid();
2650 
2651  /*
2652  * Set a different global seed in every process. We want something
2653  * unpredictable, so if possible, use high-quality random bits for the
2654  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2655  */
2657  {
2658  uint64 rseed;
2659 
2660  /*
2661  * Since PIDs and timestamps tend to change more frequently in their
2662  * least significant bits, shift the timestamp left to allow a larger
2663  * total number of seeds in a given time period. Since that would
2664  * leave only 20 bits of the timestamp that cycle every ~1 second,
2665  * also mix in some higher bits.
2666  */
2667  rseed = ((uint64) MyProcPid) ^
2668  ((uint64) MyStartTimestamp << 12) ^
2669  ((uint64) MyStartTimestamp >> 20);
2670 
2672  }
2673 
2674  /*
2675  * Also make sure that we've set a good seed for random(3). Use of that
2676  * is deprecated in core Postgres, but extensions might use it.
2677  */
2678 #ifndef WIN32
2680 #endif
2681 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1770
#define unlikely(x)
Definition: c.h:295
TimestampTz MyStartTimestamp
Definition: globals.c:46
pg_time_t MyStartTime
Definition: globals.c:45
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:191
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 3642 of file postmaster.c.

3643 {
3644  /*
3645  * size of activity_buffer is arbitrary, but set equal to default
3646  * track_activity_query_size
3647  */
3648  char activity_buffer[1024];
3649  const char *activity = NULL;
3650 
3651  if (!EXIT_STATUS_0(exitstatus))
3652  activity = pgstat_get_crashed_backend_activity(pid,
3653  activity_buffer,
3654  sizeof(activity_buffer));
3655 
3656  if (WIFEXITED(exitstatus))
3657  ereport(lev,
3658 
3659  /*------
3660  translator: %s is a noun phrase describing a child process, such as
3661  "server process" */
3662  (errmsg("%s (PID %d) exited with exit code %d",
3663  procname, pid, WEXITSTATUS(exitstatus)),
3664  activity ? errdetail("Failed process was running: %s", activity) : 0));
3665  else if (WIFSIGNALED(exitstatus))
3666  {
3667 #if defined(WIN32)
3668  ereport(lev,
3669 
3670  /*------
3671  translator: %s is a noun phrase describing a child process, such as
3672  "server process" */
3673  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3674  procname, pid, WTERMSIG(exitstatus)),
3675  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3676  activity ? errdetail("Failed process was running: %s", activity) : 0));
3677 #else
3678  ereport(lev,
3679 
3680  /*------
3681  translator: %s is a noun phrase describing a child process, such as
3682  "server process" */
3683  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3684  procname, pid, WTERMSIG(exitstatus),
3685  pg_strsignal(WTERMSIG(exitstatus))),
3686  activity ? errdetail("Failed process was running: %s", activity) : 0));
3687 #endif
3688  }
3689  else
3690  ereport(lev,
3691 
3692  /*------
3693  translator: %s is a noun phrase describing a child process, such as
3694  "server process" */
3695  (errmsg("%s (PID %d) exited with unrecognized status %d",
3696  procname, pid, exitstatus),
3697  activity ? errdetail("Failed process was running: %s", activity) : 0));
3698 }
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:42
#define WIFEXITED(w)
Definition: win32_port.h:160
#define WIFSIGNALED(w)
Definition: win32_port.h:161
#define WTERMSIG(w)
Definition: win32_port.h:163
#define WEXITSTATUS(w)
Definition: win32_port.h:162

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

5591 {
5592  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5594 }
int autovacuum_max_workers
Definition: autovacuum.c:117
int MaxConnections
Definition: globals.c:137
int max_worker_processes
Definition: globals.c:138
int max_wal_senders
Definition: walsender.c:122

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

5895 {
5896 #define MAX_BGWORKERS_TO_LAUNCH 100
5897  int num_launched = 0;
5898  TimestampTz now = 0;
5899  slist_mutable_iter iter;
5900 
5901  /*
5902  * During crash recovery, we have no need to be called until the state
5903  * transition out of recovery.
5904  */
5905  if (FatalError)
5906  {
5907  StartWorkerNeeded = false;
5908  HaveCrashedWorker = false;
5909  return;
5910  }
5911 
5912  /* Don't need to be called again unless we find a reason for it below */
5913  StartWorkerNeeded = false;
5914  HaveCrashedWorker = false;
5915 
5917  {
5918  RegisteredBgWorker *rw;
5919 
5920  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5921 
5922  /* ignore if already running */
5923  if (rw->rw_pid != 0)
5924  continue;
5925 
5926  /* if marked for death, clean up and remove from list */
5927  if (rw->rw_terminate)
5928  {
5929  ForgetBackgroundWorker(&iter);
5930  continue;
5931  }
5932 
5933  /*
5934  * If this worker has crashed previously, maybe it needs to be
5935  * restarted (unless on registration it specified it doesn't want to
5936  * be restarted at all). Check how long ago did a crash last happen.
5937  * If the last crash is too recent, don't start it right away; let it
5938  * be restarted once enough time has passed.
5939  */
5940  if (rw->rw_crashed_at != 0)
5941  {
5943  {
5944  int notify_pid;
5945 
5946  notify_pid = rw->rw_worker.bgw_notify_pid;
5947 
5948  ForgetBackgroundWorker(&iter);
5949 
5950  /* Report worker is gone now. */
5951  if (notify_pid != 0)
5952  kill(notify_pid, SIGUSR1);
5953 
5954  continue;
5955  }
5956 
5957  /* read system time only when needed */
5958  if (now == 0)
5960 
5962  rw->rw_worker.bgw_restart_time * 1000))
5963  {
5964  /* Set flag to remember that we have workers to start later */
5965  HaveCrashedWorker = true;
5966  continue;
5967  }
5968  }
5969 
5971  {
5972  /* reset crash time before trying to start worker */
5973  rw->rw_crashed_at = 0;
5974 
5975  /*
5976  * Try to start the worker.
5977  *
5978  * On failure, give up processing workers for now, but set
5979  * StartWorkerNeeded so we'll come back here on the next iteration
5980  * of ServerLoop to try again. (We don't want to wait, because
5981  * there might be additional ready-to-run workers.) We could set
5982  * HaveCrashedWorker as well, since this worker is now marked
5983  * crashed, but there's no need because the next run of this
5984  * function will do that.
5985  */
5986  if (!do_start_bgworker(rw))
5987  {
5988  StartWorkerNeeded = true;
5989  return;
5990  }
5991 
5992  /*
5993  * If we've launched as many workers as allowed, quit, but have
5994  * ServerLoop call us again to look for additional ready-to-run
5995  * workers. There might not be any, but we'll find out the next
5996  * time we run.
5997  */
5998  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5999  {
6000  StartWorkerNeeded = true;
6001  return;
6002  }
6003  }
6004  }
6005 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1727
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1546
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5696
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5788
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:489
#define SIGUSR1
Definition: win32_port.h:188

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5527 of file postmaster.c.

5528 {
5529  if (WalReceiverPID == 0 &&
5530  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5531  pmState == PM_HOT_STANDBY) &&
5533  {
5535  if (WalReceiverPID != 0)
5536  WalReceiverRequested = false;
5537  /* else leave the flag set, so we'll try again later */
5538  }
5539 }
#define SmartShutdown
Definition: postmaster.c:271
static bool WalReceiverRequested
Definition: postmaster.c:368
#define StartWalReceiver()
Definition: postmaster.c:564

References PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, pmState, Shutdown, SmartShutdown, StartWalReceiver, WalReceiverPID, and WalReceiverRequested.

Referenced by process_pm_pmsignal(), and ServerLoop().

◆ PostmasterMain()

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

Definition at line 586 of file postmaster.c.

587 {
588  int opt;
589  int status;
590  char *userDoption = NULL;
591  bool listen_addr_saved = false;
592  int i;
593  char *output_config_variable = NULL;
594 
596 
598 
600 
601  /*
602  * Start our win32 signal implementation
603  */
604 #ifdef WIN32
606 #endif
607 
608  /*
609  * We should not be creating any files or directories before we check the
610  * data directory (see checkDataDir()), but just in case set the umask to
611  * the most restrictive (owner-only) permissions.
612  *
613  * checkDataDir() will reset the umask based on the data directory
614  * permissions.
615  */
616  umask(PG_MODE_MASK_OWNER);
617 
618  /*
619  * By default, palloc() requests in the postmaster will be allocated in
620  * the PostmasterContext, which is space that can be recycled by backends.
621  * Allocated data that needs to be available to backends should be
622  * allocated in TopMemoryContext.
623  */
625  "Postmaster",
628 
629  /* Initialize paths to installation files */
630  getInstallationPaths(argv[0]);
631 
632  /*
633  * Set up signal handlers for the postmaster process.
634  *
635  * CAUTION: when changing this list, check for side-effects on the signal
636  * handling setup of child processes. See tcop/postgres.c,
637  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
638  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
639  * postmaster/bgworker.c and postmaster/checkpointer.c.
640  */
641  pqinitmask();
642  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
643 
648  pqsignal(SIGALRM, SIG_IGN); /* ignored */
649  pqsignal(SIGPIPE, SIG_IGN); /* ignored */
651  pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
653 
654  /* This may configure SIGURG, depending on platform. */
657 
658  /*
659  * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
660  * ignore those signals in a postmaster environment, so that there is no
661  * risk of a child process freezing up due to writing to stderr. But for
662  * a standalone backend, their default handling is reasonable. Hence, all
663  * child processes should just allow the inherited settings to stand.
664  */
665 #ifdef SIGTTIN
666  pqsignal(SIGTTIN, SIG_IGN); /* ignored */
667 #endif
668 #ifdef SIGTTOU
669  pqsignal(SIGTTOU, SIG_IGN); /* ignored */
670 #endif
671 
672  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
673 #ifdef SIGXFSZ
674  pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
675 #endif
676 
677  /* Begin accepting signals. */
678  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
679 
680  /*
681  * Options setup
682  */
684 
685  opterr = 1;
686 
687  /*
688  * Parse command-line options. CAUTION: keep this in sync with
689  * tcop/postgres.c (the option sets should not conflict) and with the
690  * common help() function in main/main.c.
691  */
692  while ((opt = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:")) != -1)
693  {
694  switch (opt)
695  {
696  case 'B':
697  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
698  break;
699 
700  case 'b':
701  /* Undocumented flag used for binary upgrades */
702  IsBinaryUpgrade = true;
703  break;
704 
705  case 'C':
706  output_config_variable = strdup(optarg);
707  break;
708 
709  case 'c':
710  case '-':
711  {
712  char *name,
713  *value;
714 
716  if (!value)
717  {
718  if (opt == '-')
719  ereport(ERROR,
720  (errcode(ERRCODE_SYNTAX_ERROR),
721  errmsg("--%s requires a value",
722  optarg)));
723  else
724  ereport(ERROR,
725  (errcode(ERRCODE_SYNTAX_ERROR),
726  errmsg("-c %s requires a value",
727  optarg)));
728  }
729 
731  pfree(name);
732  pfree(value);
733  break;
734  }
735 
736  case 'D':
737  userDoption = strdup(optarg);
738  break;
739 
740  case 'd':
742  break;
743 
744  case 'E':
745  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
746  break;
747 
748  case 'e':
749  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
750  break;
751 
752  case 'F':
753  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
754  break;
755 
756  case 'f':
758  {
759  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
760  progname, optarg);
761  ExitPostmaster(1);
762  }
763  break;
764 
765  case 'h':
766  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
767  break;
768 
769  case 'i':
770  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
771  break;
772 
773  case 'j':
774  /* only used by interactive backend */
775  break;
776 
777  case 'k':
778  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
779  break;
780 
781  case 'l':
782  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
783  break;
784 
785  case 'N':
786  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
787  break;
788 
789  case 'O':
790  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
791  break;
792 
793  case 'P':
794  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
795  break;
796 
797  case 'p':
799  break;
800 
801  case 'r':
802  /* only used by single-user backend */
803  break;
804 
805  case 'S':
807  break;
808 
809  case 's':
810  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
811  break;
812 
813  case 'T':
814 
815  /*
816  * This option used to be defined as sending SIGSTOP after a
817  * backend crash, but sending SIGABRT seems more useful.
818  */
819  SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
820  break;
821 
822  case 't':
823  {
824  const char *tmp = get_stats_option_name(optarg);
825 
826  if (tmp)
827  {
829  }
830  else
831  {
832  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
833  progname, optarg);
834  ExitPostmaster(1);
835  }
836  break;
837  }
838 
839  case 'W':
840  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
841  break;
842 
843  default:
844  write_stderr("Try \"%s --help\" for more information.\n",
845  progname);
846  ExitPostmaster(1);
847  }
848  }
849 
850  /*
851  * Postmaster accepts no non-option switch arguments.
852  */
853  if (optind < argc)
854  {
855  write_stderr("%s: invalid argument: \"%s\"\n",
856  progname, argv[optind]);
857  write_stderr("Try \"%s --help\" for more information.\n",
858  progname);
859  ExitPostmaster(1);
860  }
861 
862  /*
863  * Locate the proper configuration files and data directory, and read
864  * postgresql.conf for the first time.
865  */
867  ExitPostmaster(2);
868 
869  if (output_config_variable != NULL)
870  {
871  /*
872  * If this is a runtime-computed GUC, it hasn't yet been initialized,
873  * and the present value is not useful. However, this is a convenient
874  * place to print the value for most GUCs because it is safe to run
875  * postmaster startup to this point even if the server is already
876  * running. For the handful of runtime-computed GUCs that we cannot
877  * provide meaningful values for yet, we wait until later in
878  * postmaster startup to print the value. We won't be able to use -C
879  * on running servers for those GUCs, but using this option now would
880  * lead to incorrect results for them.
881  */
882  int flags = GetConfigOptionFlags(output_config_variable, true);
883 
884  if ((flags & GUC_RUNTIME_COMPUTED) == 0)
885  {
886  /*
887  * "-C guc" was specified, so print GUC's value and exit. No
888  * extra permission check is needed because the user is reading
889  * inside the data dir.
890  */
891  const char *config_val = GetConfigOption(output_config_variable,
892  false, false);
893 
894  puts(config_val ? config_val : "");
895  ExitPostmaster(0);
896  }
897 
898  /*
899  * A runtime-computed GUC will be printed later on. As we initialize
900  * a server startup sequence, silence any log messages that may show
901  * up in the output generated. FATAL and more severe messages are
902  * useful to show, even if one would only expect at least PANIC. LOG
903  * entries are hidden.
904  */
905  SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
907  }
908 
909  /* Verify that DataDir looks reasonable */
910  checkDataDir();
911 
912  /* Check that pg_control exists */
914 
915  /* And switch working directory into it */
916  ChangeToDataDir();
917 
918  /*
919  * Check for invalid combinations of GUC settings.
920  */
922  {
923  write_stderr("%s: superuser_reserved_connections (%d) plus reserved_connections (%d) must be less than max_connections (%d)\n",
924  progname,
927  ExitPostmaster(1);
928  }
930  ereport(ERROR,
931  (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
933  ereport(ERROR,
934  (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
935 
936  /*
937  * Other one-time internal sanity checks can go here, if they are fast.
938  * (Put any slow processing further down, after postmaster.pid creation.)
939  */
940  if (!CheckDateTokenTables())
941  {
942  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
943  ExitPostmaster(1);
944  }
945 
946  /*
947  * Now that we are done processing the postmaster arguments, reset
948  * getopt(3) library so that it will work correctly in subprocesses.
949  */
950  optind = 1;
951 #ifdef HAVE_INT_OPTRESET
952  optreset = 1; /* some systems need this too */
953 #endif
954 
955  /* For debugging: display postmaster environment */
956  {
957  extern char **environ;
958  char **p;
959 
960  ereport(DEBUG3,
961  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
962  progname)));
963  ereport(DEBUG3,
964  (errmsg_internal("-----------------------------------------")));
965  for (p = environ; *p; ++p)
966  ereport(DEBUG3,
967  (errmsg_internal("\t%s", *p)));
968  ereport(DEBUG3,
969  (errmsg_internal("-----------------------------------------")));
970  }
971 
972  /*
973  * Create lockfile for data directory.
974  *
975  * We want to do this before we try to grab the input sockets, because the
976  * data directory interlock is more reliable than the socket-file
977  * interlock (thanks to whoever decided to put socket files in /tmp :-().
978  * For the same reason, it's best to grab the TCP socket(s) before the
979  * Unix socket(s).
980  *
981  * Also note that this internally sets up the on_proc_exit function that
982  * is responsible for removing both data directory and socket lockfiles;
983  * so it must happen before opening sockets so that at exit, the socket
984  * lockfiles go away after CloseServerPorts runs.
985  */
986  CreateDataDirLockFile(true);
987 
988  /*
989  * Read the control file (for error checking and config info).
990  *
991  * Since we verify the control file's CRC, this has a useful side effect
992  * on machines where we need a run-time test for CRC support instructions.
993  * The postmaster will do the test once at startup, and then its child
994  * processes will inherit the correct function pointer and not need to
995  * repeat the test.
996  */
998 
999  /*
1000  * Register the apply launcher. It's probably a good idea to call this
1001  * before any modules had a chance to take the background worker slots.
1002  */
1004 
1005  /*
1006  * process any libraries that should be preloaded at postmaster start
1007  */
1009 
1010  /*
1011  * Initialize SSL library, if specified.
1012  */
1013 #ifdef USE_SSL
1014  if (EnableSSL)
1015  {
1016  (void) secure_initialize(true);
1017  LoadedSSL = true;
1018  }
1019 #endif
1020 
1021  /*
1022  * Now that loadable modules have had their chance to alter any GUCs,
1023  * calculate MaxBackends.
1024  */
1026 
1027  /*
1028  * Give preloaded libraries a chance to request additional shared memory.
1029  */
1031 
1032  /*
1033  * Now that loadable modules have had their chance to request additional
1034  * shared memory, determine the value of any runtime-computed GUCs that
1035  * depend on the amount of shared memory required.
1036  */
1038 
1039  /*
1040  * Now that modules have been loaded, we can process any custom resource
1041  * managers specified in the wal_consistency_checking GUC.
1042  */
1044 
1045  /*
1046  * If -C was specified with a runtime-computed GUC, we held off printing
1047  * the value earlier, as the GUC was not yet initialized. We handle -C
1048  * for most GUCs before we lock the data directory so that the option may
1049  * be used on a running server. However, a handful of GUCs are runtime-
1050  * computed and do not have meaningful values until after locking the data
1051  * directory, and we cannot safely calculate their values earlier on a
1052  * running server. At this point, such GUCs should be properly
1053  * initialized, and we haven't yet set up shared memory, so this is a good
1054  * time to handle the -C option for these special GUCs.
1055  */
1056  if (output_config_variable != NULL)
1057  {
1058  const char *config_val = GetConfigOption(output_config_variable,
1059  false, false);
1060 
1061  puts(config_val ? config_val : "");
1062  ExitPostmaster(0);
1063  }
1064 
1065  /*
1066  * Set up shared memory and semaphores.
1067  *
1068  * Note: if using SysV shmem and/or semas, each postmaster startup will
1069  * normally choose the same IPC keys. This helps ensure that we will
1070  * clean up dead IPC objects if the postmaster crashes and is restarted.
1071  */
1073 
1074  /*
1075  * Estimate number of openable files. This must happen after setting up
1076  * semaphores, because on some platforms semaphores count as open files.
1077  */
1078  set_max_safe_fds();
1079 
1080  /*
1081  * Set reference point for stack-depth checking.
1082  */
1083  (void) set_stack_base();
1084 
1085  /*
1086  * Initialize pipe (or process handle on Windows) that allows children to
1087  * wake up from sleep on postmaster death.
1088  */
1090 
1091 #ifdef WIN32
1092 
1093  /*
1094  * Initialize I/O completion port used to deliver list of dead children.
1095  */
1096  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1097  if (win32ChildQueue == NULL)
1098  ereport(FATAL,
1099  (errmsg("could not create I/O completion port for child queue")));
1100 #endif
1101 
1102 #ifdef EXEC_BACKEND
1103  /* Write out nondefault GUC settings for child processes to use */
1104  write_nondefault_variables(PGC_POSTMASTER);
1105 
1106  /*
1107  * Clean out the temp directory used to transmit parameters to child
1108  * processes (see internal_forkexec, below). We must do this before
1109  * launching any child processes, else we have a race condition: we could
1110  * remove a parameter file before the child can read it. It should be
1111  * safe to do so now, because we verified earlier that there are no
1112  * conflicting Postgres processes in this data directory.
1113  */
1115 #endif
1116 
1117  /*
1118  * Forcibly remove the files signaling a standby promotion request.
1119  * Otherwise, the existence of those files triggers a promotion too early,
1120  * whether a user wants that or not.
1121  *
1122  * This removal of files is usually unnecessary because they can exist
1123  * only during a few moments during a standby promotion. However there is
1124  * a race condition: if pg_ctl promote is executed and creates the files
1125  * during a promotion, the files can stay around even after the server is
1126  * brought up to be the primary. Then, if a new standby starts by using
1127  * the backup taken from the new primary, the files can exist at server
1128  * startup and must be removed in order to avoid an unexpected promotion.
1129  *
1130  * Note that promotion signal files need to be removed before the startup
1131  * process is invoked. Because, after that, they can be used by
1132  * postmaster's SIGUSR1 signal handler.
1133  */
1135 
1136  /* Do the same for logrotate signal file */
1138 
1139  /* Remove any outdated file holding the current log filenames. */
1140  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1141  ereport(LOG,
1143  errmsg("could not remove file \"%s\": %m",
1145 
1146  /*
1147  * If enabled, start up syslogger collection subprocess
1148  */
1150 
1151  /*
1152  * Reset whereToSendOutput from DestDebug (its starting state) to
1153  * DestNone. This stops ereport from sending log messages to stderr unless
1154  * Log_destination permits. We don't do this until the postmaster is
1155  * fully launched, since startup failures may as well be reported to
1156  * stderr.
1157  *
1158  * If we are in fact disabling logging to stderr, first emit a log message
1159  * saying so, to provide a breadcrumb trail for users who may not remember
1160  * that their logging is configured to go somewhere else.
1161  */
1163  ereport(LOG,
1164  (errmsg("ending log output to stderr"),
1165  errhint("Future log output will go to log destination \"%s\".",
1167 
1169 
1170  /*
1171  * Report server startup in log. While we could emit this much earlier,
1172  * it seems best to do so after starting the log collector, if we intend
1173  * to use one.
1174  */
1175  ereport(LOG,
1176  (errmsg("starting %s", PG_VERSION_STR)));
1177 
1178  /*
1179  * Establish input sockets.
1180  *
1181  * First, mark them all closed, and set up an on_proc_exit function that's
1182  * charged with closing the sockets again at postmaster shutdown.
1183  */
1184  for (i = 0; i < MAXLISTEN; i++)
1186 
1188 
1189  if (ListenAddresses)
1190  {
1191  char *rawstring;
1192  List *elemlist;
1193  ListCell *l;
1194  int success = 0;
1195 
1196  /* Need a modifiable copy of ListenAddresses */
1197  rawstring = pstrdup(ListenAddresses);
1198 
1199  /* Parse string into list of hostnames */
1200  if (!SplitGUCList(rawstring, ',', &elemlist))
1201  {
1202  /* syntax error in list */
1203  ereport(FATAL,
1204  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1205  errmsg("invalid list syntax in parameter \"%s\"",
1206  "listen_addresses")));
1207  }
1208 
1209  foreach(l, elemlist)
1210  {
1211  char *curhost = (char *) lfirst(l);
1212 
1213  if (strcmp(curhost, "*") == 0)
1214  status = StreamServerPort(AF_UNSPEC, NULL,
1215  (unsigned short) PostPortNumber,
1216  NULL,
1218  else
1219  status = StreamServerPort(AF_UNSPEC, curhost,
1220  (unsigned short) PostPortNumber,
1221  NULL,
1223 
1224  if (status == STATUS_OK)
1225  {
1226  success++;
1227  /* record the first successful host addr in lockfile */
1228  if (!listen_addr_saved)
1229  {
1231  listen_addr_saved = true;
1232  }
1233  }
1234  else
1235  ereport(WARNING,
1236  (errmsg("could not create listen socket for \"%s\"",
1237  curhost)));
1238  }
1239 
1240  if (!success && elemlist != NIL)
1241  ereport(FATAL,
1242  (errmsg("could not create any TCP/IP sockets")));
1243 
1244  list_free(elemlist);
1245  pfree(rawstring);
1246  }
1247 
1248 #ifdef USE_BONJOUR
1249  /* Register for Bonjour only if we opened TCP socket(s) */
1251  {
1252  DNSServiceErrorType err;
1253 
1254  /*
1255  * We pass 0 for interface_index, which will result in registering on
1256  * all "applicable" interfaces. It's not entirely clear from the
1257  * DNS-SD docs whether this would be appropriate if we have bound to
1258  * just a subset of the available network interfaces.
1259  */
1260  err = DNSServiceRegister(&bonjour_sdref,
1261  0,
1262  0,
1263  bonjour_name,
1264  "_postgresql._tcp.",
1265  NULL,
1266  NULL,
1268  0,
1269  NULL,
1270  NULL,
1271  NULL);
1272  if (err != kDNSServiceErr_NoError)
1273  ereport(LOG,
1274  (errmsg("DNSServiceRegister() failed: error code %ld",
1275  (long) err)));
1276 
1277  /*
1278  * We don't bother to read the mDNS daemon's reply, and we expect that
1279  * it will automatically terminate our registration when the socket is
1280  * closed at postmaster termination. So there's nothing more to be
1281  * done here. However, the bonjour_sdref is kept around so that
1282  * forked children can close their copies of the socket.
1283  */
1284  }
1285 #endif
1286 
1288  {
1289  char *rawstring;
1290  List *elemlist;
1291  ListCell *l;
1292  int success = 0;
1293 
1294  /* Need a modifiable copy of Unix_socket_directories */
1295  rawstring = pstrdup(Unix_socket_directories);
1296 
1297  /* Parse string into list of directories */
1298  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1299  {
1300  /* syntax error in list */
1301  ereport(FATAL,
1302  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1303  errmsg("invalid list syntax in parameter \"%s\"",
1304  "unix_socket_directories")));
1305  }
1306 
1307  foreach(l, elemlist)
1308  {
1309  char *socketdir = (char *) lfirst(l);
1310 
1311  status = StreamServerPort(AF_UNIX, NULL,
1312  (unsigned short) PostPortNumber,
1313  socketdir,
1315 
1316  if (status == STATUS_OK)
1317  {
1318  success++;
1319  /* record the first successful Unix socket in lockfile */
1320  if (success == 1)
1322  }
1323  else
1324  ereport(WARNING,
1325  (errmsg("could not create Unix-domain socket in directory \"%s\"",
1326  socketdir)));
1327  }
1328 
1329  if (!success && elemlist != NIL)
1330  ereport(FATAL,
1331  (errmsg("could not create any Unix-domain sockets")));
1332 
1333  list_free_deep(elemlist);
1334  pfree(rawstring);
1335  }
1336 
1337  /*
1338  * check that we have some socket to listen on
1339  */
1340  if (ListenSocket[0] == PGINVALID_SOCKET)
1341  ereport(FATAL,
1342  (errmsg("no socket created for listening")));
1343 
1344  /*
1345  * If no valid TCP ports, write an empty line for listen address,
1346  * indicating the Unix socket must be used. Note that this line is not
1347  * added to the lock file until there is a socket backing it.
1348  */
1349  if (!listen_addr_saved)
1351 
1352  /*
1353  * Record postmaster options. We delay this till now to avoid recording
1354  * bogus options (eg, unusable port number).
1355  */
1356  if (!CreateOptsFile(argc, argv, my_exec_path))
1357  ExitPostmaster(1);
1358 
1359  /*
1360  * Write the external PID file if requested
1361  */
1362  if (external_pid_file)
1363  {
1364  FILE *fpidfile = fopen(external_pid_file, "w");
1365 
1366  if (fpidfile)
1367  {
1368  fprintf(fpidfile, "%d\n", MyProcPid);
1369  fclose(fpidfile);
1370 
1371  /* Make PID file world readable */
1372  if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1373  write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1375  }
1376  else
1377  write_stderr("%s: could not write external PID file \"%s\": %s\n",
1379 
1381  }
1382 
1383  /*
1384  * Remove old temporary files. At this point there can be no other
1385  * Postgres processes running in this directory, so this should be safe.
1386  */
1388 
1389  /*
1390  * Initialize the autovacuum subsystem (again, no process start yet)
1391  */
1392  autovac_init();
1393 
1394  /*
1395  * Load configuration files for client authentication.
1396  */
1397  if (!load_hba())
1398  {
1399  /*
1400  * It makes no sense to continue if we fail to load the HBA file,
1401  * since there is no way to connect to the database in this case.
1402  */
1403  ereport(FATAL,
1404  /* translator: %s is a configuration file */
1405  (errmsg("could not load %s", HbaFileName)));
1406  }
1407  if (!load_ident())
1408  {
1409  /*
1410  * We can start up without the IDENT file, although it means that you
1411  * cannot log in using any of the authentication methods that need a
1412  * user name mapping. load_ident() already logged the details of error
1413  * to the log.
1414  */
1415  }
1416 
1417 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1418 
1419  /*
1420  * On macOS, libintl replaces setlocale() with a version that calls
1421  * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1422  * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1423  * the process multithreaded. The postmaster calls sigprocmask() and
1424  * calls fork() without an immediate exec(), both of which have undefined
1425  * behavior in a multithreaded program. A multithreaded postmaster is the
1426  * normal case on Windows, which offers neither fork() nor sigprocmask().
1427  */
1428  if (pthread_is_threaded_np() != 0)
1429  ereport(FATAL,
1430  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1431  errmsg("postmaster became multithreaded during startup"),
1432  errhint("Set the LC_ALL environment variable to a valid locale.")));
1433 #endif
1434 
1435  /*
1436  * Remember postmaster startup time
1437  */
1439 
1440  /*
1441  * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1442  * see what's happening.
1443  */
1445 
1446  /* Start bgwriter and checkpointer so they can help with recovery */
1447  if (CheckpointerPID == 0)
1449  if (BgWriterPID == 0)
1451 
1452  /*
1453  * We're ready to rock and roll...
1454  */
1456  Assert(StartupPID != 0);
1458  pmState = PM_STARTUP;
1459 
1460  /* Some workers may be scheduled to start now */
1462 
1463  status = ServerLoop();
1464 
1465  /*
1466  * ServerLoop probably shouldn't ever return, but if it does, close down.
1467  */
1469 
1470  abort(); /* not reached */
1471 }
void autovac_init(void)
Definition: autovacuum.c:3304
void pqinitmask(void)
Definition: pqsignal.c:41
bool CheckDateTokenTables(void)
Definition: datetime.c:4686
TimestampTz PgStartTime
Definition: timestamp.c:53
int secure_initialize(bool isServerStart)
Definition: be-secure.c:76
@ DestNone
Definition: dest.h:87
int Log_destination
Definition: elog.c:113
char * Log_destination_string
Definition: elog.c:114
#define DEBUG3
Definition: elog.h:28
#define LOG_DESTINATION_STDERR
Definition: elog.h:492
const char * name
Definition: encode.c:571
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:3134
void RemovePgTempFiles(void)
Definition: fd.c:3075
void set_max_safe_fds(void)
Definition: fd.c:950
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
bool IsBinaryUpgrade
Definition: globals.c:114
bool IsPostmasterEnvironment
Definition: globals.c:112
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4176
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1749
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6186
void InitializeGUCOptions(void)
Definition: guc.c:1495
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4200
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4295
#define GUC_RUNTIME_COMPUTED
Definition: guc.h:223
@ 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:529
char * external_pid_file
Definition: guc_tables.c:531
bool load_ident(void)
Definition: hba.c:3043
bool load_hba(void)
Definition: hba.c:2651
static struct @145 value
static bool success
Definition: initdb.c:187
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void InitializeShmemGUCs(void)
Definition: ipci.c:325
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:174
void InitializeLatchSupport(void)
Definition: latch.c:207
void ApplyLauncherRegister(void)
Definition: launcher.c:881
void list_free(List *list)
Definition: list.c:1545
void list_free_deep(List *list)
Definition: list.c:1559
char * pstrdup(const char *in)
Definition: mcxt.c:1624
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
void ChangeToDataDir(void)
Definition: miscinit.c:449
void process_shmem_requests(void)
Definition: miscinit.c:1875
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1515
void InitProcessLocalLatch(void)
Definition: miscinit.c:242
void process_shared_preload_libraries(void)
Definition: miscinit.c:1847
void checkDataDir(void)
Definition: miscinit.c:336
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1459
#define pg_hton16(x)
Definition: pg_bswap.h:120
#define PG_TEMP_FILES_DIR
Definition: pg_checksums.c:62
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
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3592
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3621
static const char * userDoption
Definition: postgres.c:155
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3663
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3411
void InitializeMaxBackends(void)
Definition: postinit.c:563
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2785
static void maybe_start_bgworkers(void)
Definition: postmaster.c:5894
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1478
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:6499
void InitProcessGlobals(void)
Definition: postmaster.c:2645
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2702
static int ServerLoop(void)
Definition: postmaster.c:1727
int PostPortNumber
Definition: postmaster.c:198
static void checkControlFile(void)
Definition: postmaster.c:1580
#define StartupDataBase()
Definition: postmaster.c:559
bool enable_bonjour
Definition: postmaster.c:241
int ReservedConnections
Definition: postmaster.c:225
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
Definition: postmaster.c:2688
char * Unix_socket_directories
Definition: postmaster.c:201
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:5546
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
Definition: postmaster.c:2964
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1526
#define StartCheckpointer()
Definition: postmaster.c:562
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1514
#define StartBackgroundWriter()
Definition: postmaster.c:561
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:5254
bool EnableSSL
Definition: postmaster.c:232
char * ListenAddresses
Definition: postmaster.c:204
int SuperuserReservedConnections
Definition: postmaster.c:224
char * bonjour_name
Definition: postmaster.c:242
static pid_t SysLoggerPID
Definition: postmaster.c:256
int StreamServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
Definition: pqcomm.c:321
char ** environ
void pgwin32_signal_initialize(void)
Definition: signal.c:79
Definition: pg_list.h:54
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1636
int SysLogger_Start(void)
Definition: syslogger.c:567
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:100
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3582
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3703
#define S_IROTH
Definition: win32_port.h:315
#define SIGCHLD
Definition: win32_port.h:186
#define SIGHUP
Definition: win32_port.h:176
#define S_IRGRP
Definition: win32_port.h:303
#define SIGPIPE
Definition: win32_port.h:181
#define S_IRUSR
Definition: win32_port.h:291
#define SIGALRM
Definition: win32_port.h:182
#define SIGUSR2
Definition: win32_port.h:189
#define SIG_IGN
Definition: win32_port.h:173
#define S_IWUSR
Definition: win32_port.h:294
int XLogArchiveMode
Definition: xlog.c:122
int wal_level
Definition: xlog.c:134
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4400
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4463
@ ARCHIVE_MODE_OFF
Definition: xlog.h:60
@ WAL_LEVEL_MINIMAL
Definition: xlog.h:69
void RemovePromoteSignalFiles(void)

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert(), autovac_init(), 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, i, InitializeGUCOptions(), InitializeLatchSupport(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), InitProcessLocalLatch(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenSocket, load_hba(), load_ident(), 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, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGC_S_OVERRIDE, PGC_SUSET, PGINVALID_SOCKET, 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(), StartBackgroundWriter, StartCheckpointer, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror, success, 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 6013 of file postmaster.c.

6014 {
6015  dlist_iter iter;
6016  Backend *bp;
6017 
6018  dlist_foreach(iter, &BackendList)
6019  {
6020  bp = dlist_container(Backend, elem, iter.cur);
6021  if (bp->pid == pid)
6022  {
6023  bp->bgworker_notify = true;
6024  return true;
6025  }
6026  }
6027  return false;
6028 }

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

3709 {
3710  /* If we're doing a smart shutdown, try to advance that state. */
3711  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3712  {
3713  if (!connsAllowed)
3714  {
3715  /*
3716  * This state ends when we have no normal client backends running.
3717  * Then we're ready to stop other children.
3718  */
3721  }
3722  }
3723 
3724  /*
3725  * If we're ready to do so, signal child processes to shut down. (This
3726  * isn't a persistent state, but treating it as a distinct pmState allows
3727  * us to share this code across multiple shutdown code paths.)
3728  */
3729  if (pmState == PM_STOP_BACKENDS)
3730  {
3731  /*
3732  * Forget any pending requests for background workers, since we're no
3733  * longer willing to launch any new workers. (If additional requests
3734  * arrive, BackgroundWorkerStateChange will reject them.)
3735  */
3737 
3738  /* Signal all backend children except walsenders */
3739  SignalSomeChildren(SIGTERM,
3741  /* and the autovac launcher too */
3742  if (AutoVacPID != 0)
3743  signal_child(AutoVacPID, SIGTERM);
3744  /* and the bgwriter too */
3745  if (BgWriterPID != 0)
3746  signal_child(BgWriterPID, SIGTERM);
3747  /* and the walwriter too */
3748  if (WalWriterPID != 0)
3749  signal_child(WalWriterPID, SIGTERM);
3750  /* If we're in recovery, also stop startup and walreceiver procs */
3751  if (StartupPID != 0)
3752  signal_child(StartupPID, SIGTERM);
3753  if (WalReceiverPID != 0)
3754  signal_child(WalReceiverPID, SIGTERM);
3755  /* checkpointer, archiver, stats, and syslogger may continue for now */
3756 
3757  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3759  }
3760 
3761  /*
3762  * If we are in a state-machine state that implies waiting for backends to
3763  * exit, see if they're all gone, and change state if so.
3764  */
3765  if (pmState == PM_WAIT_BACKENDS)
3766  {
3767  /*
3768  * PM_WAIT_BACKENDS state ends when we have no regular backends
3769  * (including autovac workers), no bgworkers (including unconnected
3770  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3771  * doing crash recovery or an immediate shutdown then we expect the
3772  * checkpointer to exit as well, otherwise not. The stats and
3773  * syslogger processes are disregarded since they are not connected to
3774  * shared memory; we also disregard dead_end children here. Walsenders
3775  * and archiver are also disregarded, they will be terminated later
3776  * after writing the checkpoint record.
3777  */
3779  StartupPID == 0 &&
3780  WalReceiverPID == 0 &&
3781  BgWriterPID == 0 &&
3782  (CheckpointerPID == 0 ||
3784  WalWriterPID == 0 &&
3785  AutoVacPID == 0)
3786  {
3788  {
3789  /*
3790  * Start waiting for dead_end children to die. This state
3791  * change causes ServerLoop to stop creating new ones.
3792  */
3794 
3795  /*
3796  * We already SIGQUIT'd the archiver and stats processes, if
3797  * any, when we started immediate shutdown or entered
3798  * FatalError state.
3799  */
3800  }
3801  else
3802  {
3803  /*
3804  * If we get here, we are proceeding with normal shutdown. All
3805  * the regular children are gone, and it's time to tell the
3806  * checkpointer to do a shutdown checkpoint.
3807  */
3809  /* Start the checkpointer if not running */
3810  if (CheckpointerPID == 0)
3812  /* And tell it to shut down */
3813  if (CheckpointerPID != 0)
3814  {
3816  pmState = PM_SHUTDOWN;
3817  }
3818  else
3819  {
3820  /*
3821  * If we failed to fork a checkpointer, just shut down.
3822  * Any required cleanup will happen at next restart. We
3823  * set FatalError so that an "abnormal shutdown" message
3824  * gets logged when we exit.
3825  *
3826  * We don't consult send_abort_for_crash here, as it's
3827  * unlikely that dumping cores would illuminate the reason
3828  * for checkpointer fork failure.
3829  */
3830  FatalError = true;
3832 
3833  /* Kill the walsenders and archiver too */
3835  if (PgArchPID != 0)
3837  }
3838  }
3839  }
3840  }
3841 
3842  if (pmState == PM_SHUTDOWN_2)
3843  {
3844  /*
3845  * PM_SHUTDOWN_2 state ends when there's no other children than
3846  * dead_end children left. There shouldn't be any regular backends
3847  * left by now anyway; what we're really waiting for is walsenders and
3848  * archiver.
3849  */
3850  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3851  {
3853  }
3854  }
3855 
3856  if (pmState == PM_WAIT_DEAD_END)
3857  {
3858  /* Don't allow any new socket connection events. */
3860 
3861  /*
3862  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3863  * (ie, no dead_end children remain), and the archiver is gone too.
3864  *
3865  * The reason we wait for those two is to protect them against a new
3866  * postmaster starting conflicting subprocesses; this isn't an
3867  * ironclad protection, but it at least helps in the
3868  * shutdown-and-immediately-restart scenario. Note that they have
3869  * already been sent appropriate shutdown signals, either during a
3870  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3871  * FatalError processing.
3872  */
3873  if (dlist_is_empty(&BackendList) && PgArchPID == 0)
3874  {
3875  /* These other guys should be dead already */
3876  Assert(StartupPID == 0);
3877  Assert(WalReceiverPID == 0);
3878  Assert(BgWriterPID == 0);
3879  Assert(CheckpointerPID == 0);
3880  Assert(WalWriterPID == 0);
3881  Assert(AutoVacPID == 0);
3882  /* syslogger is not considered here */
3884  }
3885  }
3886 
3887  /*
3888  * If we've been told to shut down, we exit as soon as there are no
3889  * remaining children. If there was a crash, cleanup will occur at the
3890  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3891  * crash before exiting, but that seems unwise if we are quitting because
3892  * we got SIGTERM from init --- there may well not be time for recovery
3893  * before init decides to SIGKILL us.)
3894  *
3895  * Note that the syslogger continues to run. It will exit when it sees
3896  * EOF on its input pipe, which happens when there are no more upstream
3897  * processes.
3898  */
3900  {
3901  if (FatalError)
3902  {
3903  ereport(LOG, (errmsg("abnormal database system shutdown")));
3904  ExitPostmaster(1);
3905  }
3906  else
3907  {
3908  /*
3909  * Normal exit from the postmaster is here. We don't need to log
3910  * anything here, since the UnlinkLockFiles proc_exit callback
3911  * will do so, and that should be the last user-visible action.
3912  */
3913  ExitPostmaster(0);
3914  }
3915  }
3916 
3917  /*
3918  * If the startup process failed, or the user does not want an automatic
3919  * restart after backend crashes, wait for all non-syslogger children to
3920  * exit, and then exit postmaster. We don't try to reinitialize when the
3921  * startup process fails, because more than likely it will just fail again
3922  * and we will keep trying forever.
3923  */
3924  if (pmState == PM_NO_CHILDREN)
3925  {
3927  {
3928  ereport(LOG,
3929  (errmsg("shutting down due to startup process failure")));
3930  ExitPostmaster(1);
3931  }
3932  if (!restart_after_crash)
3933  {
3934  ereport(LOG,
3935  (errmsg("shutting down because restart_after_crash is off")));
3936  ExitPostmaster(1);
3937  }
3938  }
3939 
3940  /*
3941  * If we need to recover from a crash, wait for all non-syslogger children
3942  * to exit, then reset shmem and StartupDataBase.
3943  */
3944  if (FatalError && pmState == PM_NO_CHILDREN)
3945  {
3946  ereport(LOG,
3947  (errmsg("all server processes terminated; reinitializing")));
3948 
3949  /* remove leftover temporary files after a crash */
3952 
3953  /* allow background workers to immediately restart */
3955 
3956  shmem_exit(1);
3957 
3958  /* re-read control file into local memory */
3960 
3961  /* re-create shared memory and semaphores */
3963 
3965  Assert(StartupPID != 0);
3967  pmState = PM_STARTUP;
3968  /* crash recovery started, reset SIGKILL flag */
3969  AbortStartTime = 0;
3970 
3971  /* start accepting server socket connection events again */
3973  }
3974 }
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:582
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:544
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
void shmem_exit(int code)
Definition: ipc.c:224
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3994
bool remove_temp_files_after_crash
Definition: postmaster.c:244
bool restart_after_crash
Definition: postmaster.c:243
#define SignalChildren(sig)
Definition: postmaster.c:436
static bool SignalSomeChildren(int signal, int target)
Definition: postmaster.c:4038
static void ConfigurePostmasterWaitSet(bool accept_connections)
Definition: postmaster.c:1694

References AbortStartTime, Assert(), AutoVacPID, 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, StartCheckpointer, STARTUP_CRASHED, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, WalReceiverPID, 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 2978 of file postmaster.c.

2979 {
2980  int pid; /* process id of dead child process */
2981  int exitstatus; /* its exit status */
2982 
2983  pending_pm_child_exit = false;
2984 
2985  ereport(DEBUG4,
2986  (errmsg_internal("reaping dead processes")));
2987 
2988  while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2989  {
2990  /*
2991  * Check if this child was a startup process.
2992  */
2993  if (pid == StartupPID)
2994  {
2995  StartupPID = 0;
2996 
2997  /*
2998  * Startup process exited in response to a shutdown request (or it
2999  * completed normally regardless of the shutdown request).
3000  */
3001  if (Shutdown > NoShutdown &&
3002  (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
3003  {
3006  /* PostmasterStateMachine logic does the rest */
3007  continue;
3008  }
3009 
3010  if (EXIT_STATUS_3(exitstatus))
3011  {
3012  ereport(LOG,
3013  (errmsg("shutdown at recovery target")));
3016  TerminateChildren(SIGTERM);
3018  /* PostmasterStateMachine logic does the rest */
3019  continue;
3020  }
3021 
3022  /*
3023  * Unexpected exit of startup process (including FATAL exit)
3024  * during PM_STARTUP is treated as catastrophic. There are no
3025  * other processes running yet, so we can just exit.
3026  */
3027  if (pmState == PM_STARTUP &&
3029  !EXIT_STATUS_0(exitstatus))
3030  {
3031  LogChildExit(LOG, _("startup process"),
3032  pid, exitstatus);
3033  ereport(LOG,
3034  (errmsg("aborting startup due to startup process failure")));
3035  ExitPostmaster(1);
3036  }
3037 
3038  /*
3039  * After PM_STARTUP, any unexpected exit (including FATAL exit) of
3040  * the startup process is catastrophic, so kill other children,
3041  * and set StartupStatus so we don't try to reinitialize after
3042  * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
3043  * then we previously sent the startup process a SIGQUIT; so
3044  * that's probably the reason it died, and we do want to try to
3045  * restart in that case.
3046  *
3047  * This stanza also handles the case where we sent a SIGQUIT
3048  * during PM_STARTUP due to some dead_end child crashing: in that
3049  * situation, if the startup process dies on the SIGQUIT, we need
3050  * to transition to PM_WAIT_BACKENDS state which will allow
3051  * PostmasterStateMachine to restart the startup process. (On the
3052  * other hand, the startup process might complete normally, if we
3053  * were too late with the SIGQUIT. In that case we'll fall
3054  * through and commence normal operations.)
3055  */
3056  if (!EXIT_STATUS_0(exitstatus))
3057  {
3059  {
3061  if (pmState == PM_STARTUP)
3063  }
3064  else
3066  HandleChildCrash(pid, exitstatus,
3067  _("startup process"));
3068  continue;
3069  }
3070 
3071  /*
3072  * Startup succeeded, commence normal operations
3073  */
3075  FatalError = false;
3076  AbortStartTime = 0;
3077  ReachedNormalRunning = true;
3078  pmState = PM_RUN;
3079  connsAllowed = true;
3080 
3081  /*
3082  * Crank up the background tasks, if we didn't do that already
3083  * when we entered consistent recovery state. It doesn't matter
3084  * if this fails, we'll just try again later.
3085  */
3086  if (CheckpointerPID == 0)
3088  if (BgWriterPID == 0)
3090  if (WalWriterPID == 0)
3092 
3093  /*
3094  * Likewise, start other special children as needed. In a restart
3095  * situation, some of them may be alive already.
3096  */
3099  if (PgArchStartupAllowed() && PgArchPID == 0)
3101 
3102  /* workers may be scheduled to start now */
3104 
3105  /* at this point we are really open for business */
3106  ereport(LOG,
3107  (errmsg("database system is ready to accept connections")));
3108 
3109  /* Report status */
3111 #ifdef USE_SYSTEMD
3112  sd_notify(0, "READY=1");
3113 #endif
3114 
3115  continue;
3116  }
3117 
3118  /*
3119  * Was it the bgwriter? Normal exit can be ignored; we'll start a new
3120  * one at the next iteration of the postmaster's main loop, if
3121  * necessary. Any other exit condition is treated as a crash.
3122  */
3123  if (pid == BgWriterPID)
3124  {
3125  BgWriterPID = 0;
3126  if (!EXIT_STATUS_0(exitstatus))
3127  HandleChildCrash(pid, exitstatus,
3128  _("background writer process"));
3129  continue;
3130  }
3131 
3132  /*
3133  * Was it the checkpointer?
3134  */
3135  if (pid == CheckpointerPID)
3136  {
3137  CheckpointerPID = 0;
3138  if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
3139  {
3140  /*
3141  * OK, we saw normal exit of the checkpointer after it's been
3142  * told to shut down. We expect that it wrote a shutdown
3143  * checkpoint. (If for some reason it didn't, recovery will
3144  * occur on next postmaster start.)
3145  *
3146  * At this point we should have no normal backend children
3147  * left (else we'd not be in PM_SHUTDOWN state) but we might
3148  * have dead_end children to wait for.
3149  *
3150  * If we have an archiver subprocess, tell it to do a last
3151  * archive cycle and quit. Likewise, if we have walsender
3152  * processes, tell them to send any remaining WAL and quit.
3153  */
3155 
3156  /* Waken archiver for the last time */
3157  if (PgArchPID != 0)
3159 
3160  /*
3161  * Waken walsenders for the last time. No regular backends
3162  * should be around anymore.
3163  */
3165 
3167  }
3168  else
3169  {
3170  /*
3171  * Any unexpected exit of the checkpointer (including FATAL
3172  * exit) is treated as a crash.
3173  */
3174  HandleChildCrash(pid, exitstatus,
3175  _("checkpointer process"));
3176  }
3177 
3178  continue;
3179  }
3180 
3181  /*
3182  * Was it the wal writer? Normal exit can be ignored; we'll start a
3183  * new one at the next iteration of the postmaster's main loop, if
3184  * necessary. Any other exit condition is treated as a crash.
3185  */
3186  if (pid == WalWriterPID)
3187  {
3188  WalWriterPID = 0;
3189  if (!EXIT_STATUS_0(exitstatus))
3190  HandleChildCrash(pid, exitstatus,
3191  _("WAL writer process"));
3192  continue;
3193  }
3194 
3195  /*
3196  * Was it the wal receiver? If exit status is zero (normal) or one
3197  * (FATAL exit), we assume everything is all right just like normal
3198  * backends. (If we need a new wal receiver, we'll start one at the
3199  * next iteration of the postmaster's main loop.)
3200  */
3201  if (pid == WalReceiverPID)
3202  {
3203  WalReceiverPID = 0;
3204  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3205  HandleChildCrash(pid, exitstatus,
3206  _("WAL receiver process"));
3207  continue;
3208  }
3209 
3210  /*
3211  * Was it the autovacuum launcher? Normal exit can be ignored; we'll
3212  * start a new one at the next iteration of the postmaster's main
3213  * loop, if necessary. Any other exit condition is treated as a
3214  * crash.
3215  */
3216  if (pid == AutoVacPID)
3217  {
3218  AutoVacPID = 0;
3219  if (!EXIT_STATUS_0(exitstatus))
3220  HandleChildCrash(pid, exitstatus,
3221  _("autovacuum launcher process"));
3222  continue;
3223  }
3224 
3225  /*
3226  * Was it the archiver? If exit status is zero (normal) or one (FATAL
3227  * exit), we assume everything is all right just like normal backends
3228  * and just try to restart a new one so that we immediately retry
3229  * archiving remaining files. (If fail, we'll try again in future
3230  * cycles of the postmaster's main loop.) Unless we were waiting for
3231  * it to shut down; don't restart it in that case, and
3232  * PostmasterStateMachine() will advance to the next shutdown step.
3233  */
3234  if (pid == PgArchPID)
3235  {
3236  PgArchPID = 0;
3237  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3238  HandleChildCrash(pid, exitstatus,
3239  _("archiver process"));
3240  if (PgArchStartupAllowed())
3242  continue;
3243  }
3244 
3245  /* Was it the system logger? If so, try to start a new one */
3246  if (pid == SysLoggerPID)
3247  {
3248  SysLoggerPID = 0;
3249  /* for safety's sake, launch new logger *first* */
3251  if (!EXIT_STATUS_0(exitstatus))
3252  LogChildExit(LOG, _("system logger process"),
3253  pid, exitstatus);
3254  continue;
3255  }
3256 
3257  /* Was it one of our background workers? */
3258  if (CleanupBackgroundWorker(pid, exitstatus))
3259  {
3260  /* have it be restarted */
3261  HaveCrashedWorker = true;
3262  continue;
3263  }
3264 
3265  /*
3266  * Else do standard backend child cleanup.
3267  */
3268  CleanupBackend(pid, exitstatus);
3269  } /* loop over pending child-death reports */
3270 
3271  /*
3272  * After cleaning out the SIGCHLD queue, see if we have any state changes
3273  * or actions to make.
3274  */
3276 }
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3250
int StartAutoVacLauncher(void)
#define DEBUG4
Definition: elog.h:27
#define PM_STATUS_READY
Definition: pidfile.h:53
static bool CleanupBackgroundWorker(int pid, int exitstatus)
Definition: postmaster.c:3288
#define StartArchiver()
Definition: postmaster.c:560
static void PostmasterStateMachine(void)
Definition: postmaster.c:3708
static void TerminateChildren(int signal)
Definition: postmaster.c:4082
#define PgArchStartupAllowed()
Definition: postmaster.c:453
static bool ReachedNormalRunning
Definition: postmaster.c:354
#define StartWalWriter()
Definition: postmaster.c:563
static void CleanupBackend(int pid, int exitstatus)
Definition: postmaster.c:3383
#define EXIT_STATUS_3(st)
Definition: postmaster.c:569

References _, AbortStartTime, AddToDataDirLockFile(), Assert(), AutoVacPID, AutoVacuumingActive(), 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(), 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, SmartShutdown, StartArchiver, StartAutoVacLauncher(), StartBackgroundWriter, StartCheckpointer, STARTUP_CRASHED, STARTUP_NOT_RUNNING, STARTUP_SIGNALED, StartupPID, StartupStatus, StartWalWriter, SysLogger_Start(), SysLoggerPID, TerminateChildren(), WalReceiverPID, and WalWriterPID.

Referenced by ServerLoop().

◆ process_pm_pmsignal()

static void process_pm_pmsignal ( void  )
static

Definition at line 5077 of file postmaster.c.

5078 {
5079  pending_pm_pmsignal = false;
5080 
5081  ereport(DEBUG2,
5082  (errmsg_internal("postmaster received pmsignal signal")));
5083 
5084  /*
5085  * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
5086  * unexpected states. If the startup process quickly starts up, completes
5087  * recovery, exits, we might process the death of the startup process
5088  * first. We don't want to go back to recovery in that case.
5089  */
5092  {
5093  /* WAL redo has started. We're out of reinitialization. */
5094  FatalError = false;
5095  AbortStartTime = 0;
5096 
5097  /*
5098  * Start the archiver if we're responsible for (re-)archiving received
5099  * files.
5100  */
5101  Assert(PgArchPID == 0);
5102  if (XLogArchivingAlways())
5104 
5105  /*
5106  * If we aren't planning to enter hot standby mode later, treat
5107  * RECOVERY_STARTED as meaning we're out of startup, and report status
5108  * accordingly.
5109  */
5110  if (!EnableHotStandby)
5111  {
5113 #ifdef USE_SYSTEMD
5114  sd_notify(0, "READY=1");
5115 #endif
5116  }
5117 
5118  pmState = PM_RECOVERY;
5119  }
5120 
5123  {
5124  ereport(LOG,
5125  (errmsg("database system is ready to accept read-only connections")));
5126 
5127  /* Report status */
5129 #ifdef USE_SYSTEMD
5130  sd_notify(0, "READY=1");
5131 #endif
5132 
5134  connsAllowed = true;
5135 
5136  /* Some workers may be scheduled to start now */
5137  StartWorkerNeeded = true;
5138  }
5139 
5140  /* Process background worker state changes. */
5142  {
5143  /* Accept new worker requests only if not stopping. */
5145  StartWorkerNeeded = true;
5146  }
5147 
5150 
5151  /* Tell syslogger to rotate logfile if requested */
5152  if (SysLoggerPID != 0)
5153  {
5154  if (CheckLogrotateSignal())
5155  {
5158  }
5160  {
5162  }
5163  }
5164 
5167  {
5168  /*
5169  * Start one iteration of the autovacuum daemon, even if autovacuuming
5170  * is nominally not enabled. This is so we can have an active defense
5171  * against transaction ID wraparound. We set a flag for the main loop
5172  * to do it rather than trying to do it here --- this is because the
5173  * autovac process itself may send the signal, and we want to handle
5174  * that by launching another iteration as soon as the current one
5175  * completes.
5176  */
5177  start_autovac_launcher = true;
5178  }
5179 
5182  {
5183  /* The autovacuum launcher wants us to start a worker process. */
5185  }
5186 
5188  {
5189  /* Startup Process wants us to start the walreceiver process. */
5190  /* Start immediately if possible, else remember request for later. */
5191  WalReceiverRequested = true;
5193  }
5194 
5195  /*
5196  * Try to advance postmaster's state machine, if a child requests it.
5197  *
5198  * Be careful about the order of this action relative to this function's
5199  * other actions. Generally, this should be after other actions, in case
5200  * they have effects PostmasterStateMachine would need to know about.
5201  * However, we should do it before the CheckPromoteSignal step, which
5202  * cannot have any (immediate) effect on the state machine, but does
5203  * depend on what state we're in now.
5204  */
5206  {
5208  }
5209 
5210  if (StartupPID != 0 &&
5211  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5212  pmState == PM_HOT_STANDBY) &&
5214  {
5215  /*
5216  * Tell startup process to finish recovery.
5217  *
5218  * Leave the promote signal file in place and let the Startup process
5219  * do the unlink.
5220  */
5222  }
5223 }
void BackgroundWorkerStateChange(bool allow_new_workers)
Definition: bgworker.c:245
#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:5527
static bool start_autovac_launcher
Definition: postmaster.c:362
static void StartAutovacuumWorker(void)
Definition: postmaster.c:5436
bool CheckLogrotateSignal(void)
Definition: syslogger.c:1622
bool EnableHotStandby
Definition: xlog.c:124
bool CheckPromoteSignal(void)

References AbortStartTime, AddToDataDirLockFile(), Assert(), 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, StartArchiver, StartAutovacuumWorker(), StartupPID, StartWorkerNeeded, SysLoggerPID, WalReceiverRequested, and XLogArchivingAlways.

Referenced by ServerLoop().

◆ process_pm_reload_request()

static void process_pm_reload_request ( void  )
static

Definition at line 2716 of file postmaster.c.

2717 {
2718  pending_pm_reload_request = false;
2719 
2720  ereport(DEBUG2,
2721  (errmsg_internal("postmaster received reload request signal")));
2722 
2723  if (Shutdown <= SmartShutdown)
2724  {
2725  ereport(LOG,
2726  (errmsg("received SIGHUP, reloading configuration files")));
2729  if (StartupPID != 0)
2731  if (BgWriterPID != 0)
2733  if (CheckpointerPID != 0)
2735  if (WalWriterPID != 0)
2737  if (WalReceiverPID != 0)
2739  if (AutoVacPID != 0)
2741  if (PgArchPID != 0)
2743  if (SysLoggerPID != 0)
2745 
2746  /* Reload authentication config files too */
2747  if (!load_hba())
2748  ereport(LOG,
2749  /* translator: %s is a configuration file */
2750  (errmsg("%s was not reloaded", HbaFileName)));
2751 
2752  if (!load_ident())
2753  ereport(LOG,
2754  (errmsg("%s was not reloaded", IdentFileName)));
2755 
2756 #ifdef USE_SSL
2757  /* Reload SSL configuration as well */
2758  if (EnableSSL)
2759  {
2760  if (secure_initialize(false) == 0)
2761  LoadedSSL = true;
2762  else
2763  ereport(LOG,
2764  (errmsg("SSL configuration was not reloaded")));
2765  }
2766  else
2767  {
2768  secure_destroy();
2769  LoadedSSL = false;
2770  }
2771 #endif
2772 
2773 #ifdef EXEC_BACKEND
2774  /* Update the starting-point file for future children */
2775  write_nondefault_variables(PGC_SIGHUP);
2776 #endif
2777  }
2778 }
void secure_destroy(void)
Definition: be-secure.c:89
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
char * IdentFileName
Definition: guc_tables.c:530

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

Referenced by ServerLoop().

◆ process_pm_shutdown_request()

static void process_pm_shutdown_request ( void  )
static

Definition at line 2813 of file postmaster.c.

2814 {
2815  int mode;
2816 
2817  ereport(DEBUG2,
2818  (errmsg_internal("postmaster received shutdown request signal")));
2819 
2821 
2822  /*
2823  * If more than one shutdown request signal arrived since the last server
2824  * loop, take the one that is the most immediate. That matches the
2825  * priority that would apply if we processed them one by one in any order.
2826  */
2828  {
2832  }
2834  {
2836  mode = FastShutdown;
2837  }
2838  else
2839  mode = SmartShutdown;
2840 
2841  switch (mode)
2842  {
2843  case SmartShutdown:
2844 
2845  /*
2846  * Smart Shutdown:
2847  *
2848  * Wait for children to end their work, then shut down.
2849  */
2850  if (Shutdown >= SmartShutdown)
2851  break;
2853  ereport(LOG,
2854  (errmsg("received smart shutdown request")));
2855 
2856  /* Report status */
2858 #ifdef USE_SYSTEMD
2859  sd_notify(0, "STOPPING=1");
2860 #endif
2861 
2862  /*
2863  * If we reached normal running, we go straight to waiting for
2864  * client backends to exit. If already in PM_STOP_BACKENDS or a
2865  * later state, do not change it.
2866  */
2867  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2868  connsAllowed = false;
2869  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2870  {
2871  /* There should be no clients, so proceed to stop children */
2873  }
2874 
2875  /*
2876  * Now wait for online backup mode to end and backends to exit. If
2877  * that is already the case, PostmasterStateMachine will take the
2878  * next step.
2879  */
2881  break;
2882 
2883  case FastShutdown:
2884 
2885  /*
2886  * Fast Shutdown:
2887  *
2888  * Abort all children with SIGTERM (rollback active transactions
2889  * and exit) and shut down when they are gone.
2890  */
2891  if (Shutdown >= FastShutdown)
2892  break;
2894  ereport(LOG,
2895  (errmsg("received fast shutdown request")));
2896 
2897  /* Report status */
2899 #ifdef USE_SYSTEMD
2900  sd_notify(0, "STOPPING=1");
2901 #endif
2902 
2903  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2904  {
2905  /* Just shut down background processes silently */
2907  }
2908  else if (pmState == PM_RUN ||
2910  {
2911  /* Report that we're about to zap live client sessions */
2912  ereport(LOG,
2913  (errmsg("aborting any active transactions")));
2915  }
2916 
2917  /*
2918  * PostmasterStateMachine will issue any necessary signals, or
2919  * take the next step if no child processes need to be killed.
2920  */
2922  break;
2923 
2924  case ImmediateShutdown:
2925 
2926  /*
2927  * Immediate Shutdown:
2928  *
2929  * abort all children with SIGQUIT, wait for them to exit,
2930  * terminate remaining ones with SIGKILL, then exit without
2931  * attempt to properly shut down the data base system.
2932  */
2933  if (Shutdown >= ImmediateShutdown)
2934  break;
2936  ereport(LOG,
2937  (errmsg("received immediate shutdown request")));
2938 
2939  /* Report status */
2941 #ifdef USE_SYSTEMD
2942  sd_notify(0, "STOPPING=1");
2943 #endif
2944 
2945  /* tell children to shut down ASAP */
2946  /* (note we don't apply send_abort_for_crash here) */
2950 
2951  /* set stopwatch for them to die */
2952  AbortStartTime = time(NULL);
2953 
2954  /*
2955  * Now wait for backends to exit. If there are none,
2956  * PostmasterStateMachine will take the next step.
2957  */
2959  break;
2960  }
2961 }
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
#define FastShutdown
Definition: postmaster.c:272

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

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5239 of file postmaster.c.

5240 {
5241  _exit(1);
5242 }

Referenced by BackendInitialize().

◆ processCancelRequest()

static void processCancelRequest ( Port port,
void *  pkt 
)
static

Definition at line 2404 of file postmaster.c.

2405 {
2406  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2407  int backendPID;
2408  int32 cancelAuthCode;
2409  Backend *bp;
2410 
2411 #ifndef EXEC_BACKEND
2412  dlist_iter iter;
2413 #else
2414  int i;
2415 #endif
2416 
2417  backendPID = (int) pg_ntoh32(canc->backendPID);
2418  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2419 
2420  /*
2421  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2422  * longer access the postmaster's own backend list, and must rely on the
2423  * duplicate array in shared memory.
2424  */
2425 #ifndef EXEC_BACKEND
2426  dlist_foreach(iter, &BackendList)
2427  {
2428  bp = dlist_container(Backend, elem, iter.cur);
2429 #else
2430  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2431  {
2432  bp = (Backend *) &ShmemBackendArray[i];
2433 #endif
2434  if (bp->pid == backendPID)
2435  {
2436  if (bp->cancel_key == cancelAuthCode)
2437  {
2438  /* Found a match; signal that backend to cancel current op */
2439  ereport(DEBUG2,
2440  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2441  backendPID)));
2442  signal_child(bp->pid, SIGINT);
2443  }
2444  else
2445  /* Right PID, wrong key: no way, Jose */
2446  ereport(LOG,
2447  (errmsg("wrong key in cancel request for process %d",
2448  backendPID)));
2449  return;
2450  }
2451 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2452  }
2453 #else
2454  }
2455 #endif
2456 
2457  /* No matching backend */
2458  ereport(LOG,
2459  (errmsg("PID %d in cancel request did not match any process",
2460  backendPID)));
2461 }
signed int int32
Definition: c.h:478
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
uint32 backendPID
Definition: pqcomm.h:145
uint32 cancelAuthCode
Definition: pqcomm.h:146

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

Referenced by ProcessStartupPacket().

◆ ProcessStartupPacket()

static int ProcessStartupPacket ( Port port,
bool  ssl_done,
bool  gss_done 
)
static

Definition at line 1948 of file postmaster.c.

1949 {
1950  int32 len;
1951  char *buf;
1952  ProtocolVersion proto;
1953  MemoryContext oldcontext;
1954 
1955  pq_startmsgread();
1956 
1957  /*
1958  * Grab the first byte of the length word separately, so that we can tell
1959  * whether we have no data at all or an incomplete packet. (This might
1960  * sound inefficient, but it's not really, because of buffering in
1961  * pqcomm.c.)
1962  */
1963  if (pq_getbytes((char *) &len, 1) == EOF)
1964  {
1965  /*
1966  * If we get no data at all, don't clutter the log with a complaint;
1967  * such cases often occur for legitimate reasons. An example is that
1968  * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
1969  * client didn't like our response, it'll probably just drop the
1970  * connection. Service-monitoring software also often just opens and
1971  * closes a connection without sending anything. (So do port
1972  * scanners, which may be less benign, but it's not really our job to
1973  * notice those.)
1974  */
1975  return STATUS_ERROR;
1976  }
1977 
1978  if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
1979  {
1980  /* Got a partial length word, so bleat about that */
1981  if (!ssl_done && !gss_done)
1983  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1984  errmsg("incomplete startup packet")));
1985  return STATUS_ERROR;
1986  }
1987 
1988  len = pg_ntoh32(len);
1989  len -= 4;
1990 
1991  if (len < (int32) sizeof(ProtocolVersion) ||
1993  {
1995  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1996  errmsg("invalid length of startup packet")));
1997  return STATUS_ERROR;
1998  }
1999 
2000  /*
2001  * Allocate space to hold the startup packet, plus one extra byte that's
2002  * initialized to be zero. This ensures we will have null termination of
2003  * all strings inside the packet.
2004  */
2005  buf = palloc(len + 1);
2006  buf[len] = '\0';
2007 
2008  if (pq_getbytes(buf, len) == EOF)
2009  {
2011  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2012  errmsg("incomplete startup packet")));
2013  return STATUS_ERROR;
2014  }
2015  pq_endmsgread();
2016 
2017  /*
2018  * The first field is either a protocol version number or a special
2019  * request code.
2020  */
2021  port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
2022 
2023  if (proto == CANCEL_REQUEST_CODE)
2024  {
2025  if (len != sizeof(CancelRequestPacket))
2026  {
2028  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2029  errmsg("invalid length of startup packet")));
2030  return STATUS_ERROR;
2031  }
2033  /* Not really an error, but we don't want to proceed further */
2034  return STATUS_ERROR;
2035  }
2036 
2037  if (proto == NEGOTIATE_SSL_CODE && !ssl_done)
2038  {
2039  char SSLok;
2040 
2041 #ifdef USE_SSL
2042  /* No SSL when disabled or on Unix sockets */
2043  if (!LoadedSSL || port->laddr.addr.ss_family == AF_UNIX)
2044  SSLok = 'N';
2045  else
2046  SSLok = 'S'; /* Support for SSL */
2047 #else
2048  SSLok = 'N'; /* No support for SSL */
2049 #endif
2050 
2051 retry1:
2052  if (send(port->sock, &SSLok, 1, 0) != 1)
2053  {