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

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 146 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 148 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 145 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 147 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 566 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 567 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 568 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 229 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 559 of file postmaster.c.

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 560 of file postmaster.c.

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 561 of file postmaster.c.

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 558 of file postmaster.c.

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 563 of file postmaster.c.

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

5809 {
5810  Backend *bn;
5811 
5812  /*
5813  * Check that database state allows another connection. Currently the
5814  * only possible failure is CAC_TOOMANY, so we just log an error message
5815  * based on that rather than checking the error code precisely.
5816  */
5818  {
5819  ereport(LOG,
5820  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5821  errmsg("no slot available for new worker process")));
5822  return false;
5823  }
5824 
5825  /*
5826  * Compute the cancel key that will be assigned to this session. We
5827  * probably don't need cancel keys for background workers, but we'd better
5828  * have something random in the field to prevent unfriendly people from
5829  * sending cancels to them.
5830  */
5832  {
5833  ereport(LOG,
5834  (errcode(ERRCODE_INTERNAL_ERROR),
5835  errmsg("could not generate random cancel key")));
5836  return false;
5837  }
5838 
5839  bn = malloc(sizeof(Backend));
5840  if (bn == NULL)
5841  {
5842  ereport(LOG,
5843  (errcode(ERRCODE_OUT_OF_MEMORY),
5844  errmsg("out of memory")));
5845  return false;
5846  }
5847 
5848  bn->cancel_key = MyCancelKey;
5851  bn->dead_end = false;
5852  bn->bgworker_notify = false;
5853 
5854  rw->rw_backend = bn;
5855  rw->rw_child_slot = bn->child_slot;
5856 
5857  return true;
5858 }
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:2445
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5251
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:184
int bkend_type
Definition: postmaster.c:182
bool dead_end
Definition: postmaster.c:183
int32 cancel_key
Definition: postmaster.c:180
int child_slot
Definition: postmaster.c:181

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

4252 {
4253  int status;
4254  int ret;
4255  char remote_host[NI_MAXHOST];
4256  char remote_port[NI_MAXSERV];
4257  StringInfoData ps_data;
4258 
4259  /* Save port etc. for ps status */
4260  MyProcPort = port;
4261 
4262  /* Tell fd.c about the long-lived FD associated with the port */
4264 
4265  /*
4266  * PreAuthDelay is a debugging aid for investigating problems in the
4267  * authentication cycle: it can be set in postgresql.conf to allow time to
4268  * attach to the newly-forked backend with a debugger. (See also
4269  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4270  * is not honored until after authentication.)
4271  */
4272  if (PreAuthDelay > 0)
4273  pg_usleep(PreAuthDelay * 1000000L);
4274 
4275  /* This flag will remain set until InitPostgres finishes authentication */
4276  ClientAuthInProgress = true; /* limit visibility of log messages */
4277 
4278  /* set these to empty in case they are needed before we set them up */
4279  port->remote_host = "";
4280  port->remote_port = "";
4281 
4282  /*
4283  * Initialize libpq and enable reporting of ereport errors to the client.
4284  * Must do this now because authentication uses libpq to send messages.
4285  */
4286  pq_init(); /* initialize libpq to talk to client */
4287  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4288 
4289  /*
4290  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4291  * to collect the startup packet; while SIGQUIT results in _exit(2).
4292  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4293  * cleanly if a buggy client fails to send the packet promptly.
4294  *
4295  * Exiting with _exit(1) is only possible because we have not yet touched
4296  * shared memory; therefore no outside-the-process state needs to get
4297  * cleaned up.
4298  */
4300  /* SIGQUIT handler was already set up by InitPostmasterChild */
4301  InitializeTimeouts(); /* establishes SIGALRM handler */
4302  sigprocmask(SIG_SETMASK, &StartupBlockSig, NULL);
4303 
4304  /*
4305  * Get the remote host name and port for logging and status display.
4306  */
4307  remote_host[0] = '\0';
4308  remote_port[0] = '\0';
4309  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4310  remote_host, sizeof(remote_host),
4311  remote_port, sizeof(remote_port),
4312  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4313  ereport(WARNING,
4314  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4315  gai_strerror(ret))));
4316 
4317  /*
4318  * Save remote_host and remote_port in port structure (after this, they
4319  * will appear in log_line_prefix data for log messages).
4320  */
4321  port->remote_host = strdup(remote_host);
4322  port->remote_port = strdup(remote_port);
4323 
4324  /* And now we can issue the Log_connections message, if wanted */
4325  if (Log_connections)
4326  {
4327  if (remote_port[0])
4328  ereport(LOG,
4329  (errmsg("connection received: host=%s port=%s",
4330  remote_host,
4331  remote_port)));
4332  else
4333  ereport(LOG,
4334  (errmsg("connection received: host=%s",
4335  remote_host)));
4336  }
4337 
4338  /*
4339  * If we did a reverse lookup to name, we might as well save the results
4340  * rather than possibly repeating the lookup during authentication.
4341  *
4342  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4343  * get nothing useful for a client without an rDNS entry. Therefore, we
4344  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4345  * it into remote_hostname if so. (This test is conservative and might
4346  * sometimes classify a hostname as numeric, but an error in that
4347  * direction is safe; it only results in a possible extra lookup.)
4348  */
4349  if (log_hostname &&
4350  ret == 0 &&
4351  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4352  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4353  port->remote_hostname = strdup(remote_host);
4354 
4355  /*
4356  * Ready to begin client interaction. We will give up and _exit(1) after
4357  * a time delay, so that a broken client can't hog a connection
4358  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4359  * against the time limit.
4360  *
4361  * Note: AuthenticationTimeout is applied here while waiting for the
4362  * startup packet, and then again in InitPostgres for the duration of any
4363  * authentication operations. So a hostile client could tie up the
4364  * process for nearly twice AuthenticationTimeout before we kick him off.
4365  *
4366  * Note: because PostgresMain will call InitializeTimeouts again, the
4367  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4368  * since we never use it again after this function.
4369  */
4372 
4373  /*
4374  * Receive the startup packet (which might turn out to be a cancel request
4375  * packet).
4376  */
4377  status = ProcessStartupPacket(port, false, false);
4378 
4379  /*
4380  * Disable the timeout, and prevent SIGTERM again.
4381  */
4383  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
4384 
4385  /*
4386  * As a safety check that nothing in startup has yet performed
4387  * shared-memory modifications that would need to be undone if we had
4388  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4389  * handlers have been registered yet. (This isn't terribly bulletproof,
4390  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4391  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4392  * handlers unfortunately, since pq_init() already registered one.)
4393  */
4395 
4396  /*
4397  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4398  * already did any appropriate error reporting.
4399  */
4400  if (status != STATUS_OK)
4401  proc_exit(0);
4402 
4403  /*
4404  * Now that we have the user and database name, we can set the process
4405  * title for ps. It's good to do this as early as possible in startup.
4406  */
4407  initStringInfo(&ps_data);
4408  if (am_walsender)
4410  appendStringInfo(&ps_data, "%s ", port->user_name);
4411  if (port->database_name[0] != '\0')
4412  appendStringInfo(&ps_data, "%s ", port->database_name);
4413  appendStringInfoString(&ps_data, port->remote_host);
4414  if (port->remote_port[0] != '\0')
4415  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4416 
4417  init_ps_display(ps_data.data);
4418  pfree(ps_data.data);
4419 
4420  set_ps_display("initializing");
4421 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
#define STATUS_OK
Definition: c.h:1182
@ 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:1173
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:1456
@ B_WAL_SENDER
Definition: miscadmin.h:340
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:264
static int port
Definition: pg_regress.c:109
pqsigfunc pqsignal(int signo, pqsigfunc func)
CommandDest whereToSendOutput
Definition: postgres.c:88
int PreAuthDelay
Definition: postmaster.c:235
bool log_hostname
Definition: postmaster.c:238
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5217
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5241
bool Log_connections
Definition: postmaster.c:239
bool ClientAuthInProgress
Definition: postmaster.c:356
int AuthenticationTimeout
Definition: postmaster.c:236
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:1950
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_OK, WARNING, and whereToSendOutput.

Referenced by BackendStartup().

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4431 of file postmaster.c.

4432 {
4433  /*
4434  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4435  * just yet, though, because InitPostgres will need the HBA data.)
4436  */
4438 
4439  PostgresMain(port->database_name, port->user_name);
4440 }
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:4127

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

Referenced by BackendStartup().

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4091 of file postmaster.c.

4092 {
4093  Backend *bn; /* for backend cleanup */
4094  pid_t pid;
4095 
4096  /*
4097  * Create backend data structure. Better before the fork() so we can
4098  * handle failure cleanly.
4099  */
4100  bn = (Backend *) malloc(sizeof(Backend));
4101  if (!bn)
4102  {
4103  ereport(LOG,
4104  (errcode(ERRCODE_OUT_OF_MEMORY),
4105  errmsg("out of memory")));
4106  return STATUS_ERROR;
4107  }
4108 
4109  /*
4110  * Compute the cancel key that will be assigned to this backend. The
4111  * backend will have its own copy in the forked-off process' value of
4112  * MyCancelKey, so that it can transmit the key to the frontend.
4113  */
4115  {
4116  free(bn);
4117  ereport(LOG,
4118  (errcode(ERRCODE_INTERNAL_ERROR),
4119  errmsg("could not generate random cancel key")));
4120  return STATUS_ERROR;
4121  }
4122 
4123  bn->cancel_key = MyCancelKey;
4124 
4125  /* Pass down canAcceptConnections state */
4126  port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL);
4127  bn->dead_end = (port->canAcceptConnections != CAC_OK);
4128 
4129  /*
4130  * Unless it's a dead_end child, assign it a child slot number
4131  */
4132  if (!bn->dead_end)
4134  else
4135  bn->child_slot = 0;
4136 
4137  /* Hasn't asked to be notified about any bgworkers yet */
4138  bn->bgworker_notify = false;
4139 
4140 #ifdef EXEC_BACKEND
4141  pid = backend_forkexec(port);
4142 #else /* !EXEC_BACKEND */
4143  pid = fork_process();
4144  if (pid == 0) /* child */
4145  {
4146  free(bn);
4147 
4148  /* Detangle from postmaster */
4150 
4151  /* Close the postmaster's sockets */
4152  ClosePostmasterPorts(false);
4153 
4154  /* Perform additional initialization and collect startup packet */
4156 
4157  /*
4158  * Create a per-backend PGPROC struct in shared memory. We must do
4159  * this before we can use LWLocks. In the !EXEC_BACKEND case (here)
4160  * this could be delayed a bit further, but EXEC_BACKEND needs to do
4161  * stuff with LWLocks before PostgresMain(), so we do it here as well
4162  * for symmetry.
4163  */
4164  InitProcess();
4165 
4166  /* And run the backend */
4167  BackendRun(port);
4168  }
4169 #endif /* EXEC_BACKEND */
4170 
4171  if (pid < 0)
4172  {
4173  /* in parent, fork failed */
4174  int save_errno = errno;
4175 
4176  if (!bn->dead_end)
4178  free(bn);
4179  errno = save_errno;
4180  ereport(LOG,
4181  (errmsg("could not fork new process for connection: %m")));
4182  report_fork_failure_to_client(port, save_errno);
4183  return STATUS_ERROR;
4184  }
4185 
4186  /* in parent, successful fork */
4187  ereport(DEBUG2,
4188  (errmsg_internal("forked new backend, pid=%d socket=%d",
4189  (int) pid, (int) port->sock)));
4190 
4191  /*
4192  * Everything's been successful, it's safe to add this backend to our list
4193  * of backends.
4194  */
4195  bn->pid = pid;
4196  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4198 
4199 #ifdef EXEC_BACKEND
4200  if (!bn->dead_end)
4201  ShmemBackendArrayAdd(bn);
4202 #endif
4203 
4204  return STATUS_OK;
4205 }
#define STATUS_ERROR
Definition: c.h:1183
#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:145
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4431
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2549
static void BackendInitialize(Port *port)
Definition: postmaster.c:4251
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4216
static dlist_head BackendList
Definition: postmaster.c:188
void InitProcess(void)
Definition: proc.c:297
dlist_node elem
Definition: postmaster.c:185
pid_t pid
Definition: postmaster.c:179

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

5633 {
5634  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
5635 }

References BlockSig.

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5578 of file postmaster.c.

5579 {
5581 
5582  /* XXX is this the right errcode? */
5584  ereport(FATAL,
5585  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5586  errmsg("database connection requirement not indicated during registration")));
5587 
5588  InitPostgres(dbname, InvalidOid, /* database to connect to */
5589  username, InvalidOid, /* role to connect as */
5590  false, /* never honor session_preload_libraries */
5591  (flags & BGWORKER_BYPASS_ALLOWCONN) != 0, /* ignore datallowconn? */
5592  NULL); /* no out_dbname */
5593 
5594  /* it had better not gotten out of "init" mode yet */
5595  if (!IsInitProcessingMode())
5596  ereport(ERROR,
5597  (errmsg("invalid processing mode in background worker")));
5599 }
#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:409
#define IsInitProcessingMode()
Definition: miscadmin.h:415
#define SetProcessingMode(mode)
Definition: miscadmin.h:420
const char * username
Definition: pgbench.c:296
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bool load_session_libraries, bool override_allow_connections, char *out_dbname)
Definition: postinit.c:718
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
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(), and worker_spi_main().

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5605 of file postmaster.c.

5606 {
5608 
5609  /* XXX is this the right errcode? */
5611  ereport(FATAL,
5612  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5613  errmsg("database connection requirement not indicated during registration")));
5614 
5615  InitPostgres(NULL, dboid, /* database to connect to */
5616  NULL, useroid, /* role to connect as */
5617  false, /* never honor session_preload_libraries */
5618  (flags & BGWORKER_BYPASS_ALLOWCONN) != 0, /* ignore datallowconn? */
5619  NULL); /* no out_dbname */
5620 
5621  /* it had better not gotten out of "init" mode yet */
5622  if (!IsInitProcessingMode())
5623  ereport(ERROR,
5624  (errmsg("invalid processing mode in background worker")));
5626 }

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(), InitializeLogRepWorker(), and ParallelWorkerMain().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5638 of file postmaster.c.

5639 {
5640  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5641 }
sigset_t UnBlockSig
Definition: pqsignal.c:22

References UnBlockSig.

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

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5766 of file postmaster.c.

5767 {
5768  switch (pmState)
5769  {
5770  case PM_NO_CHILDREN:
5771  case PM_WAIT_DEAD_END:
5772  case PM_SHUTDOWN_2:
5773  case PM_SHUTDOWN:
5774  case PM_WAIT_BACKENDS:
5775  case PM_STOP_BACKENDS:
5776  break;
5777 
5778  case PM_RUN:
5780  return true;
5781  /* fall through */
5782 
5783  case PM_HOT_STANDBY:
5785  return true;
5786  /* fall through */
5787 
5788  case PM_RECOVERY:
5789  case PM_STARTUP:
5790  case PM_INIT:
5792  return true;
5793  /* fall through */
5794  }
5795 
5796  return false;
5797 }
@ 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 2445 of file postmaster.c.

2446 {
2447  CAC_state result = CAC_OK;
2448 
2449  /*
2450  * Can't start backends when in startup/shutdown/inconsistent recovery
2451  * state. We treat autovac workers the same as user backends for this
2452  * purpose. However, bgworkers are excluded from this test; we expect
2453  * bgworker_should_start_now() decided whether the DB state allows them.
2454  */
2455  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2456  backend_type != BACKEND_TYPE_BGWORKER)
2457  {
2458  if (Shutdown > NoShutdown)
2459  return CAC_SHUTDOWN; /* shutdown is pending */
2460  else if (!FatalError && pmState == PM_STARTUP)
2461  return CAC_STARTUP; /* normal startup */
2462  else if (!FatalError && pmState == PM_RECOVERY)
2463  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2464  * state */
2465  else
2466  return CAC_RECOVERY; /* else must be crash recovery */
2467  }
2468 
2469  /*
2470  * "Smart shutdown" restrictions are applied only to normal connections,
2471  * not to autovac workers or bgworkers.
2472  */
2473  if (!connsAllowed && backend_type == BACKEND_TYPE_NORMAL)
2474  return CAC_SHUTDOWN; /* shutdown is pending */
2475 
2476  /*
2477  * Don't start too many children.
2478  *
2479  * We allow more connections here than we can have backends because some
2480  * might still be authenticating; they might fail auth, or some existing
2481  * backend might exit before the auth cycle is completed. The exact
2482  * MaxBackends limit is enforced when a new backend tries to join the
2483  * shared-inval backend array.
2484  *
2485  * The limit here must match the sizes of the per-child-process arrays;
2486  * see comments for MaxLivePostmasterChildren().
2487  */
2489  result = CAC_TOOMANY;
2490 
2491  return result;
2492 }
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:149
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5568
#define NoShutdown
Definition: postmaster.c:270
static bool FatalError
Definition: postmaster.c:277
static int CountChildren(int target)
Definition: postmaster.c:5261

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

1583 {
1584  char path[MAXPGPATH];
1585  FILE *fp;
1586 
1587  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1588 
1589  fp = AllocateFile(path, PG_BINARY_R);
1590  if (fp == NULL)
1591  {
1592  write_stderr("%s: could not find the database system\n"
1593  "Expected to find it in the directory \"%s\",\n"
1594  "but could not open file \"%s\": %s\n",
1595  progname, DataDir, path, strerror(errno));
1596  ExitPostmaster(2);
1597  }
1598  FreeFile(fp);
1599 }
#define write_stderr(str)
Definition: parallel.c:184
#define PG_BINARY_R
Definition: c.h:1285
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2528
int FreeFile(FILE *file)
Definition: fd.c:2726
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:5021

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

3363 {
3364  dlist_mutable_iter iter;
3365 
3366  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3367 
3368  /*
3369  * If a backend dies in an ugly way then we must signal all other backends
3370  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3371  * assume everything is all right and proceed to remove the backend from
3372  * the active backend list.
3373  */
3374 
3375 #ifdef WIN32
3376 
3377  /*
3378  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3379  * since that sometimes happens under load when the process fails to start
3380  * properly (long before it starts using shared memory). Microsoft reports
3381  * it is related to mutex failure:
3382  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3383  */
3384  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3385  {
3386  LogChildExit(LOG, _("server process"), pid, exitstatus);
3387  exitstatus = 0;
3388  }
3389 #endif
3390 
3391  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3392  {
3393  HandleChildCrash(pid, exitstatus, _("server process"));
3394  return;
3395  }
3396 
3398  {
3399  Backend *bp = dlist_container(Backend, elem, iter.cur);
3400 
3401  if (bp->pid == pid)
3402  {
3403  if (!bp->dead_end)
3404  {
3406  {
3407  /*
3408  * Uh-oh, the child failed to clean itself up. Treat as a
3409  * crash after all.
3410  */
3411  HandleChildCrash(pid, exitstatus, _("server process"));
3412  return;
3413  }
3414 #ifdef EXEC_BACKEND
3415  ShmemBackendArrayRemove(bp);
3416 #endif
3417  }
3418  if (bp->bgworker_notify)
3419  {
3420  /*
3421  * This backend may have been slated to receive SIGUSR1 when
3422  * some background worker started or stopped. Cancel those
3423  * notifications, as we don't want to signal PIDs that are not
3424  * PostgreSQL backends. This gets skipped in the (probably
3425  * very common) case where the backend has never requested any
3426  * such notifications.
3427  */
3429  }
3430  dlist_delete(iter.cur);
3431  free(bp);
3432  break;
3433  }
3434  }
3435 }
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:520
#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:3620
#define EXIT_STATUS_1(st)
Definition: postmaster.c:567
#define EXIT_STATUS_0(st)
Definition: postmaster.c:566
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3445
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 3266 of file postmaster.c.

3268 {
3269  char namebuf[MAXPGPATH];
3270  slist_mutable_iter iter;
3271 
3273  {
3274  RegisteredBgWorker *rw;
3275 
3276  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3277 
3278  if (rw->rw_pid != pid)
3279  continue;
3280 
3281 #ifdef WIN32
3282  /* see CleanupBackend */
3283  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3284  exitstatus = 0;
3285 #endif
3286 
3287  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3288  rw->rw_worker.bgw_type);
3289 
3290 
3291  if (!EXIT_STATUS_0(exitstatus))
3292  {
3293  /* Record timestamp, so we know when to restart the worker. */
3295  }
3296  else
3297  {
3298  /* Zero exit status means terminate */
3299  rw->rw_crashed_at = 0;
3300  rw->rw_terminate = true;
3301  }
3302 
3303  /*
3304  * Additionally, just like a backend, any exit status other than 0 or
3305  * 1 is considered a crash and causes a system-wide restart.
3306  */
3307  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3308  {
3309  HandleChildCrash(pid, exitstatus, namebuf);
3310  return true;
3311  }
3312 
3313  /*
3314  * We must release the postmaster child slot. If the worker failed to
3315  * do so, it did not clean up after itself, requiring a crash-restart
3316  * cycle.
3317  */
3319  {
3320  HandleChildCrash(pid, exitstatus, namebuf);
3321  return true;
3322  }
3323 
3324  /* Get it out of the BackendList and clear out remaining data */
3325  dlist_delete(&rw->rw_backend->elem);
3326 #ifdef EXEC_BACKEND
3327  ShmemBackendArrayRemove(rw->rw_backend);
3328 #endif
3329 
3330  /*
3331  * It's possible that this background worker started some OTHER
3332  * background worker and asked to be notified when that worker started
3333  * or stopped. If so, cancel any notifications destined for the
3334  * now-dead backend.
3335  */
3336  if (rw->rw_backend->bgworker_notify)
3338  free(rw->rw_backend);
3339  rw->rw_backend = NULL;
3340  rw->rw_pid = 0;
3341  rw->rw_child_slot = 0;
3342  ReportBackgroundWorkerExit(&iter); /* report child death */
3343 
3344  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3345  namebuf, pid, exitstatus);
3346 
3347  return true;
3348  }
3349 
3350  return false;
3351 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:486
#define DEBUG1
Definition: elog.h:30
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:1148
#define slist_container(type, membername, ptr)
Definition: ilist.h:1106
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BackgroundWorker rw_worker
slist_node * cur
Definition: ilist.h:274

References _, BackgroundWorkerList, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_type, bkend::bgworker_notify, slist_mutable_iter::cur, DEBUG1, dlist_delete(), bkend::elem, EXIT_STATUS_0, EXIT_STATUS_1, 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 2549 of file postmaster.c.

2550 {
2551  /* Release resources held by the postmaster's WaitEventSet. */
2552  if (pm_wait_set)
2553  {
2555  pm_wait_set = NULL;
2556  }
2557 
2558 #ifndef WIN32
2559 
2560  /*
2561  * Close the write end of postmaster death watch pipe. It's important to
2562  * do this as early as possible, so that if postmaster dies, others won't
2563  * think that it's still running because we're holding the pipe open.
2564  */
2566  ereport(FATAL,
2568  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2570  /* Notify fd.c that we released one pipe FD. */
2572 #endif
2573 
2574  /*
2575  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2576  * so we don't call ReleaseExternalFD() here.
2577  *
2578  * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
2579  * EXEC_BACKEND mode.
2580  */
2581 #ifndef EXEC_BACKEND
2582  for (int i = 0; i < MAXLISTEN; i++)
2583  {
2585  {
2588  }
2589  }
2590 #endif
2591 
2592  /*
2593  * If using syslogger, close the read side of the pipe. We don't bother
2594  * tracking this in fd.c, either.
2595  */
2596  if (!am_syslogger)
2597  {
2598 #ifndef WIN32
2599  if (syslogPipe[0] >= 0)
2600  close(syslogPipe[0]);
2601  syslogPipe[0] = -1;
2602 #else
2603  if (syslogPipe[0])
2604  CloseHandle(syslogPipe[0]);
2605  syslogPipe[0] = 0;
2606 #endif
2607  }
2608 
2609 #ifdef USE_BONJOUR
2610  /* If using Bonjour, close the connection to the mDNS daemon */
2611  if (bonjour_sdref)
2612  close(DNSServiceRefSockFD(bonjour_sdref));
2613 #endif
2614 }
int errcode_for_file_access(void)
Definition: elog.c:881
void ReleaseExternalFD(void)
Definition: fd.c:1191
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:874
#define PGINVALID_SOCKET
Definition: port.h:31
int postmaster_alive_fds[2]
Definition: postmaster.c:575
static WaitEventSet * pm_wait_set
Definition: postmaster.c:383
#define MAXLISTEN
Definition: postmaster.c:229
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:230
#define POSTMASTER_FD_OWN
Definition: postmaster.h:47
void StreamClose(pgsocket sock)
Definition: pqcomm.c:835
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 1480 of file postmaster.c.

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

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

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1696 of file postmaster.c.

1697 {
1698  int nsockets;
1699 
1700  if (pm_wait_set)
1702  pm_wait_set = NULL;
1703 
1704  /* How many server sockets do we need to wait for? */
1705  nsockets = 0;
1706  if (accept_connections)
1707  {
1708  while (nsockets < MAXLISTEN &&
1709  ListenSocket[nsockets] != PGINVALID_SOCKET)
1710  ++nsockets;
1711  }
1712 
1715  NULL);
1716 
1717  if (accept_connections)
1718  {
1719  for (int i = 0; i < nsockets; i++)
1721  NULL, NULL);
1722  }
1723 }
struct Latch * MyLatch
Definition: globals.c:58
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:721
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:920
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:835
#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 2501 of file postmaster.c.

2502 {
2503  Port *port;
2504 
2505  if (!(port = (Port *) calloc(1, sizeof(Port))))
2506  {
2507  ereport(LOG,
2508  (errcode(ERRCODE_OUT_OF_MEMORY),
2509  errmsg("out of memory")));
2510  ExitPostmaster(1);
2511  }
2512 
2513  if (StreamConnection(serverFd, port) != STATUS_OK)
2514  {
2515  if (port->sock != PGINVALID_SOCKET)
2516  StreamClose(port->sock);
2517  ConnFree(port);
2518  return NULL;
2519  }
2520 
2521  return port;
2522 }
#define calloc(a, b)
Definition: header.h:55
static void ConnFree(Port *port)
Definition: postmaster.c:2532
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:701
Definition: libpq-be.h:147

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

2533 {
2534  free(port);
2535 }

References free, and port.

Referenced by ConnCreate(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5261 of file postmaster.c.

5262 {
5263  dlist_iter iter;
5264  int cnt = 0;
5265 
5266  dlist_foreach(iter, &BackendList)
5267  {
5268  Backend *bp = dlist_container(Backend, elem, iter.cur);
5269 
5270  if (bp->dead_end)
5271  continue;
5272 
5273  /*
5274  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5275  * it first and avoid touching shared memory for every child.
5276  */
5277  if (target != BACKEND_TYPE_ALL)
5278  {
5279  /*
5280  * Assign bkend_type for any recently announced WAL Sender
5281  * processes.
5282  */
5283  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5286 
5287  if (!(target & bp->bkend_type))
5288  continue;
5289  }
5290 
5291  cnt++;
5292  }
5293  return cnt;
5294 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:307
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
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 5524 of file postmaster.c.

5525 {
5526  FILE *fp;
5527  int i;
5528 
5529 #define OPTS_FILE "postmaster.opts"
5530 
5531  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5532  {
5533  ereport(LOG,
5535  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5536  return false;
5537  }
5538 
5539  fprintf(fp, "%s", fullprogname);
5540  for (i = 1; i < argc; i++)
5541  fprintf(fp, " \"%s\"", argv[i]);
5542  fputs("\n", fp);
5543 
5544  if (fclose(fp))
5545  {
5546  ereport(LOG,
5548  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5549  return false;
5550  }
5551 
5552  return true;
5553 }
#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 1611 of file postmaster.c.

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

5675 {
5676  pid_t worker_pid;
5677 
5678  Assert(rw->rw_pid == 0);
5679 
5680  /*
5681  * Allocate and assign the Backend element. Note we must do this before
5682  * forking, so that we can handle failures (out of memory or child-process
5683  * slots) cleanly.
5684  *
5685  * Treat failure as though the worker had crashed. That way, the
5686  * postmaster will wait a bit before attempting to start it again; if we
5687  * tried again right away, most likely we'd find ourselves hitting the
5688  * same resource-exhaustion condition.
5689  */
5690  if (!assign_backendlist_entry(rw))
5691  {
5693  return false;
5694  }
5695 
5696  ereport(DEBUG1,
5697  (errmsg_internal("starting background worker process \"%s\"",
5698  rw->rw_worker.bgw_name)));
5699 
5700 #ifdef EXEC_BACKEND
5701  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5702 #else
5703  switch ((worker_pid = fork_process()))
5704 #endif
5705  {
5706  case -1:
5707  /* in postmaster, fork failed ... */
5708  ereport(LOG,
5709  (errmsg("could not fork worker process: %m")));
5710  /* undo what assign_backendlist_entry did */
5712  rw->rw_child_slot = 0;
5713  free(rw->rw_backend);
5714  rw->rw_backend = NULL;
5715  /* mark entry as crashed, so we'll try again later */
5717  break;
5718 
5719 #ifndef EXEC_BACKEND
5720  case 0:
5721  /* in postmaster child ... */
5723 
5724  /* Close the postmaster's sockets */
5725  ClosePostmasterPorts(false);
5726 
5727  /*
5728  * Before blowing away PostmasterContext, save this bgworker's
5729  * data where it can find it.
5730  */
5733  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5734 
5735  /* Release postmaster's working memory context */
5738  PostmasterContext = NULL;
5739 
5741 
5742  exit(1); /* should not get here */
5743  break;
5744 #endif
5745  default:
5746  /* in postmaster, fork successful ... */
5747  rw->rw_pid = worker_pid;
5748  rw->rw_backend->pid = rw->rw_pid;
5750  /* add new worker to lists of backends */
5752 #ifdef EXEC_BACKEND
5753  ShmemBackendArrayAdd(rw->rw_backend);
5754 #endif
5755  return true;
5756  }
5757 
5758  return false;
5759 }
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:467
void StartBackgroundWorker(void)
Definition: bgworker.c:747
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1021
MemoryContext PostmasterContext
Definition: mcxt.c:143
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5808
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 5232 of file postmaster.c.

5233 {
5234 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5021 of file postmaster.c.

5022 {
5023 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5024 
5025  /*
5026  * There is no known cause for a postmaster to become multithreaded after
5027  * startup. Recheck to account for the possibility of unknown causes.
5028  * This message uses LOG level, because an unclean shutdown at this point
5029  * would usually not look much different from a clean shutdown.
5030  */
5031  if (pthread_is_threaded_np() != 0)
5032  ereport(LOG,
5033  (errcode(ERRCODE_INTERNAL_ERROR),
5034  errmsg_internal("postmaster became multithreaded"),
5035  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5036 #endif
5037 
5038  /* should cleanup shared memory and kill all backends */
5039 
5040  /*
5041  * Not sure of the semantics here. When the Postmaster dies, should the
5042  * backends all be killed? probably not.
5043  *
5044  * MUST -- vadim 05-10-1999
5045  */
5046 
5047  proc_exit(status);
5048 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202

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

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1528 of file postmaster.c.

1529 {
1530  DIR *pdir;
1531 
1532  /* Locate the postgres executable itself */
1533  if (find_my_exec(argv0, my_exec_path) < 0)
1534  ereport(FATAL,
1535  (errmsg("%s: could not locate my own executable path", argv0)));
1536 
1537 #ifdef EXEC_BACKEND
1538  /* Locate executable backend before we change working directory */
1539  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1540  postgres_exec_path) < 0)
1541  ereport(FATAL,
1542  (errmsg("%s: could not locate matching postgres executable",
1543  argv0)));
1544 #endif
1545 
1546  /*
1547  * Locate the pkglib directory --- this has to be set early in case we try
1548  * to load any modules from it in response to postgresql.conf entries.
1549  */
1551 
1552  /*
1553  * Verify that there's a readable directory there; otherwise the Postgres
1554  * installation is incomplete or corrupt. (A typical cause of this
1555  * failure is that the postgres executable has been moved or hardlinked to
1556  * some directory that's not a sibling of the installation lib/
1557  * directory.)
1558  */
1559  pdir = AllocateDir(pkglib_path);
1560  if (pdir == NULL)
1561  ereport(ERROR,
1563  errmsg("could not open directory \"%s\": %m",
1564  pkglib_path),
1565  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1566  my_exec_path)));
1567  FreeDir(pdir);
1568 
1569  /*
1570  * XXX is it worth similarly checking the share/ directory? If the lib/
1571  * directory is there, then share/ probably is too.
1572  */
1573 }
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:2906
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2788
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 2942 of file postmaster.c.

2943 {
2944  int save_errno = errno;
2945 
2946  pending_pm_child_exit = true;
2947  SetLatch(MyLatch);
2948 
2949  errno = save_errno;
2950 }
void SetLatch(Latch *latch)
Definition: latch.c:605
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 2666 of file postmaster.c.

2667 {
2668  int save_errno = errno;
2669 
2670  pending_pm_pmsignal = true;
2671  SetLatch(MyLatch);
2672 
2673  errno = save_errno;
2674 }
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 2680 of file postmaster.c.

2681 {
2682  int save_errno = errno;
2683 
2685  SetLatch(MyLatch);
2686 
2687  errno = save_errno;
2688 }
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 2763 of file postmaster.c.

2764 {
2765  int save_errno = errno;
2766 
2767  switch (postgres_signal_arg)
2768  {
2769  case SIGTERM:
2770  /* smart is implied if the other two flags aren't set */
2772  break;
2773  case SIGINT:
2776  break;
2777  case SIGQUIT:
2780  break;
2781  }
2782  SetLatch(MyLatch);
2783 
2784  errno = save_errno;
2785 }
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:169

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

Referenced by PostmasterMain().

◆ HandleChildCrash()

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

Definition at line 3445 of file postmaster.c.

3446 {
3447  dlist_mutable_iter iter;
3448  slist_iter siter;
3449  Backend *bp;
3450  bool take_action;
3451 
3452  /*
3453  * We only log messages and send signals if this is the first process
3454  * crash and we're not doing an immediate shutdown; otherwise, we're only
3455  * here to update postmaster's idea of live processes. If we have already
3456  * signaled children, nonzero exit status is to be expected, so don't
3457  * clutter log.
3458  */
3459  take_action = !FatalError && Shutdown != ImmediateShutdown;
3460 
3461  if (take_action)
3462  {
3463  LogChildExit(LOG, procname, pid, exitstatus);
3464  ereport(LOG,
3465  (errmsg("terminating any other active server processes")));
3467  }
3468 
3469  /* Process background workers. */
3471  {
3472  RegisteredBgWorker *rw;
3473 
3474  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3475  if (rw->rw_pid == 0)
3476  continue; /* not running */
3477  if (rw->rw_pid == pid)
3478  {
3479  /*
3480  * Found entry for freshly-dead worker, so remove it.
3481  */
3483  dlist_delete(&rw->rw_backend->elem);
3484 #ifdef EXEC_BACKEND
3485  ShmemBackendArrayRemove(rw->rw_backend);
3486 #endif
3487  free(rw->rw_backend);
3488  rw->rw_backend = NULL;
3489  rw->rw_pid = 0;
3490  rw->rw_child_slot = 0;
3491  /* don't reset crashed_at */
3492  /* don't report child stop, either */
3493  /* Keep looping so we can signal remaining workers */
3494  }
3495  else
3496  {
3497  /*
3498  * This worker is still alive. Unless we did so already, tell it
3499  * to commit hara-kiri.
3500  */
3501  if (take_action)
3502  sigquit_child(rw->rw_pid);
3503  }
3504  }
3505 
3506  /* Process regular backends */
3508  {
3509  bp = dlist_container(Backend, elem, iter.cur);
3510 
3511  if (bp->pid == pid)
3512  {
3513  /*
3514  * Found entry for freshly-dead backend, so remove it.
3515  */
3516  if (!bp->dead_end)
3517  {
3519 #ifdef EXEC_BACKEND
3520  ShmemBackendArrayRemove(bp);
3521 #endif
3522  }
3523  dlist_delete(iter.cur);
3524  free(bp);
3525  /* Keep looping so we can signal remaining backends */
3526  }
3527  else
3528  {
3529  /*
3530  * This backend is still alive. Unless we did so already, tell it
3531  * to commit hara-kiri.
3532  *
3533  * We could exclude dead_end children here, but at least when
3534  * sending SIGABRT it seems better to include them.
3535  *
3536  * Background workers were already processed above; ignore them
3537  * here.
3538  */
3539  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3540  continue;
3541 
3542  if (take_action)
3543  sigquit_child(bp->pid);
3544  }
3545  }
3546 
3547  /* Take care of the startup process too */
3548  if (pid == StartupPID)
3549  {
3550  StartupPID = 0;
3551  /* Caller adjusts StartupStatus, so don't touch it here */
3552  }
3553  else if (StartupPID != 0 && take_action)
3554  {
3557  }
3558 
3559  /* Take care of the bgwriter too */
3560  if (pid == BgWriterPID)
3561  BgWriterPID = 0;
3562  else if (BgWriterPID != 0 && take_action)
3564 
3565  /* Take care of the checkpointer too */
3566  if (pid == CheckpointerPID)
3567  CheckpointerPID = 0;
3568  else if (CheckpointerPID != 0 && take_action)
3570 
3571  /* Take care of the walwriter too */
3572  if (pid == WalWriterPID)
3573  WalWriterPID = 0;
3574  else if (WalWriterPID != 0 && take_action)
3576 
3577  /* Take care of the walreceiver too */
3578  if (pid == WalReceiverPID)
3579  WalReceiverPID = 0;
3580  else if (WalReceiverPID != 0 && take_action)
3582 
3583  /* Take care of the autovacuum launcher too */
3584  if (pid == AutoVacPID)
3585  AutoVacPID = 0;
3586  else if (AutoVacPID != 0 && take_action)
3588 
3589  /* Take care of the archiver too */
3590  if (pid == PgArchPID)
3591  PgArchPID = 0;
3592  else if (PgArchPID != 0 && take_action)
3594 
3595  /* We do NOT restart the syslogger */
3596 
3597  if (Shutdown != ImmediateShutdown)
3598  FatalError = true;
3599 
3600  /* We now transit into a state of waiting for children to die */
3601  if (pmState == PM_RECOVERY ||
3602  pmState == PM_HOT_STANDBY ||
3603  pmState == PM_RUN ||
3605  pmState == PM_SHUTDOWN)
3607 
3608  /*
3609  * .. and if this doesn't happen quickly enough, now the clock is ticking
3610  * for us to kill them without mercy.
3611  */
3612  if (AbortStartTime == 0)
3613  AbortStartTime = time(NULL);
3614 }
#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:4002
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 6473 of file postmaster.c.

6474 {
6475 #ifndef WIN32
6476 
6477  /*
6478  * Create a pipe. Postmaster holds the write end of the pipe open
6479  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6480  * the read file descriptor to select() to wake up in case postmaster
6481  * dies, or check for postmaster death with a (read() == 0). Children must
6482  * close the write end as soon as possible after forking, because EOF
6483  * won't be signaled in the read end until all processes have closed the
6484  * write fd. That is taken care of in ClosePostmasterPorts().
6485  */
6487  if (pipe(postmaster_alive_fds) < 0)
6488  ereport(FATAL,
6490  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6491 
6492  /* Notify fd.c that we've eaten two FDs for the pipe. */
6495 
6496  /*
6497  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6498  * call.
6499  */
6500  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6501  ereport(FATAL,
6503  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6504 #else
6505 
6506  /*
6507  * On Windows, we use a process handle for the same purpose.
6508  */
6509  if (DuplicateHandle(GetCurrentProcess(),
6510  GetCurrentProcess(),
6511  GetCurrentProcess(),
6512  &PostmasterHandle,
6513  0,
6514  TRUE,
6515  DUPLICATE_SAME_ACCESS) == 0)
6516  ereport(FATAL,
6517  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6518  GetLastError())));
6519 #endif /* WIN32 */
6520 }
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 2623 of file postmaster.c.

2624 {
2625  MyProcPid = getpid();
2628 
2629  /*
2630  * Set a different global seed in every process. We want something
2631  * unpredictable, so if possible, use high-quality random bits for the
2632  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2633  */
2635  {
2636  uint64 rseed;
2637 
2638  /*
2639  * Since PIDs and timestamps tend to change more frequently in their
2640  * least significant bits, shift the timestamp left to allow a larger
2641  * total number of seeds in a given time period. Since that would
2642  * leave only 20 bits of the timestamp that cycle every ~1 second,
2643  * also mix in some higher bits.
2644  */
2645  rseed = ((uint64) MyProcPid) ^
2646  ((uint64) MyStartTimestamp << 12) ^
2647  ((uint64) MyStartTimestamp >> 20);
2648 
2650  }
2651 
2652  /*
2653  * Also make sure that we've set a good seed for random(3). Use of that
2654  * is deprecated in core Postgres, but extensions might use it.
2655  */
2656 #ifndef WIN32
2658 #endif
2659 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1762
#define unlikely(x)
Definition: c.h:300
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 3620 of file postmaster.c.

3621 {
3622  /*
3623  * size of activity_buffer is arbitrary, but set equal to default
3624  * track_activity_query_size
3625  */
3626  char activity_buffer[1024];
3627  const char *activity = NULL;
3628 
3629  if (!EXIT_STATUS_0(exitstatus))
3630  activity = pgstat_get_crashed_backend_activity(pid,
3631  activity_buffer,
3632  sizeof(activity_buffer));
3633 
3634  if (WIFEXITED(exitstatus))
3635  ereport(lev,
3636 
3637  /*------
3638  translator: %s is a noun phrase describing a child process, such as
3639  "server process" */
3640  (errmsg("%s (PID %d) exited with exit code %d",
3641  procname, pid, WEXITSTATUS(exitstatus)),
3642  activity ? errdetail("Failed process was running: %s", activity) : 0));
3643  else if (WIFSIGNALED(exitstatus))
3644  {
3645 #if defined(WIN32)
3646  ereport(lev,
3647 
3648  /*------
3649  translator: %s is a noun phrase describing a child process, such as
3650  "server process" */
3651  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3652  procname, pid, WTERMSIG(exitstatus)),
3653  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3654  activity ? errdetail("Failed process was running: %s", activity) : 0));
3655 #else
3656  ereport(lev,
3657 
3658  /*------
3659  translator: %s is a noun phrase describing a child process, such as
3660  "server process" */
3661  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3662  procname, pid, WTERMSIG(exitstatus),
3663  pg_strsignal(WTERMSIG(exitstatus))),
3664  activity ? errdetail("Failed process was running: %s", activity) : 0));
3665 #endif
3666  }
3667  else
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) exited with unrecognized status %d",
3674  procname, pid, exitstatus),
3675  activity ? errdetail("Failed process was running: %s", activity) : 0));
3676 }
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:152
#define WIFSIGNALED(w)
Definition: win32_port.h:153
#define WTERMSIG(w)
Definition: win32_port.h:155
#define WEXITSTATUS(w)
Definition: win32_port.h:154

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

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

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5568 of file postmaster.c.

5569 {
5570  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5572 }
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 5872 of file postmaster.c.

5873 {
5874 #define MAX_BGWORKERS_TO_LAUNCH 100
5875  int num_launched = 0;
5876  TimestampTz now = 0;
5877  slist_mutable_iter iter;
5878 
5879  /*
5880  * During crash recovery, we have no need to be called until the state
5881  * transition out of recovery.
5882  */
5883  if (FatalError)
5884  {
5885  StartWorkerNeeded = false;
5886  HaveCrashedWorker = false;
5887  return;
5888  }
5889 
5890  /* Don't need to be called again unless we find a reason for it below */
5891  StartWorkerNeeded = false;
5892  HaveCrashedWorker = false;
5893 
5895  {
5896  RegisteredBgWorker *rw;
5897 
5898  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5899 
5900  /* ignore if already running */
5901  if (rw->rw_pid != 0)
5902  continue;
5903 
5904  /* if marked for death, clean up and remove from list */
5905  if (rw->rw_terminate)
5906  {
5907  ForgetBackgroundWorker(&iter);
5908  continue;
5909  }
5910 
5911  /*
5912  * If this worker has crashed previously, maybe it needs to be
5913  * restarted (unless on registration it specified it doesn't want to
5914  * be restarted at all). Check how long ago did a crash last happen.
5915  * If the last crash is too recent, don't start it right away; let it
5916  * be restarted once enough time has passed.
5917  */
5918  if (rw->rw_crashed_at != 0)
5919  {
5921  {
5922  int notify_pid;
5923 
5924  notify_pid = rw->rw_worker.bgw_notify_pid;
5925 
5926  ForgetBackgroundWorker(&iter);
5927 
5928  /* Report worker is gone now. */
5929  if (notify_pid != 0)
5930  kill(notify_pid, SIGUSR1);
5931 
5932  continue;
5933  }
5934 
5935  /* read system time only when needed */
5936  if (now == 0)
5938 
5940  rw->rw_worker.bgw_restart_time * 1000))
5941  {
5942  /* Set flag to remember that we have workers to start later */
5943  HaveCrashedWorker = true;
5944  continue;
5945  }
5946  }
5947 
5949  {
5950  /* reset crash time before trying to start worker */
5951  rw->rw_crashed_at = 0;
5952 
5953  /*
5954  * Try to start the worker.
5955  *
5956  * On failure, give up processing workers for now, but set
5957  * StartWorkerNeeded so we'll come back here on the next iteration
5958  * of ServerLoop to try again. (We don't want to wait, because
5959  * there might be additional ready-to-run workers.) We could set
5960  * HaveCrashedWorker as well, since this worker is now marked
5961  * crashed, but there's no need because the next run of this
5962  * function will do that.
5963  */
5964  if (!do_start_bgworker(rw))
5965  {
5966  StartWorkerNeeded = true;
5967  return;
5968  }
5969 
5970  /*
5971  * If we've launched as many workers as allowed, quit, but have
5972  * ServerLoop call us again to look for additional ready-to-run
5973  * workers. There might not be any, but we'll find out the next
5974  * time we run.
5975  */
5976  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5977  {
5978  StartWorkerNeeded = true;
5979  return;
5980  }
5981  }
5982  }
5983 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1719
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5674
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5766
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
pid_t bgw_notify_pid
Definition: bgworker.h:100
#define kill(pid, sig)
Definition: win32_port.h:485
#define SIGUSR1
Definition: win32_port.h:180

References BackgroundWorkerList, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, bgworker_should_start_now(), slist_mutable_iter::cur, do_start_bgworker(), FatalError, ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, kill, MAX_BGWORKERS_TO_LAUNCH, now(), RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SIGUSR1, slist_container, slist_foreach_modify, StartWorkerNeeded, and TimestampDifferenceExceeds().

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5505 of file postmaster.c.

5506 {
5507  if (WalReceiverPID == 0 &&
5508  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5509  pmState == PM_HOT_STANDBY) &&
5511  {
5513  if (WalReceiverPID != 0)
5514  WalReceiverRequested = false;
5515  /* else leave the flag set, so we'll try again later */
5516  }
5517 }
#define SmartShutdown
Definition: postmaster.c:271
static bool WalReceiverRequested
Definition: postmaster.c:368
#define StartWalReceiver()
Definition: postmaster.c:563

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

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

5992 {
5993  dlist_iter iter;
5994  Backend *bp;
5995 
5996  dlist_foreach(iter, &BackendList)
5997  {
5998  bp = dlist_container(Backend, elem, iter.cur);
5999  if (bp->pid == pid)
6000  {
6001  bp->bgworker_notify = true;
6002  return true;
6003  }
6004  }
6005  return false;
6006 }

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

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

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

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

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

5056 {
5057  pending_pm_pmsignal = false;
5058 
5059  ereport(DEBUG2,
5060  (errmsg_internal("postmaster received pmsignal signal")));
5061 
5062  /*
5063  * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
5064  * unexpected states. If the startup process quickly starts up, completes
5065  * recovery, exits, we might process the death of the startup process
5066  * first. We don't want to go back to recovery in that case.
5067  */
5070  {
5071  /* WAL redo has started. We're out of reinitialization. */
5072  FatalError = false;
5073  AbortStartTime = 0;
5074 
5075  /*
5076  * Start the archiver if we're responsible for (re-)archiving received
5077  * files.
5078  */
5079  Assert(PgArchPID == 0);
5080  if (XLogArchivingAlways())
5082 
5083  /*
5084  * If we aren't planning to enter hot standby mode later, treat
5085  * RECOVERY_STARTED as meaning we're out of startup, and report status
5086  * accordingly.
5087  */
5088  if (!EnableHotStandby)
5089  {
5091 #ifdef USE_SYSTEMD
5092  sd_notify(0, "READY=1");
5093 #endif
5094  }
5095 
5096  pmState = PM_RECOVERY;
5097  }
5098 
5101  {
5102  ereport(LOG,
5103  (errmsg("database system is ready to accept read-only connections")));
5104 
5105  /* Report status */
5107 #ifdef USE_SYSTEMD
5108  sd_notify(0, "READY=1");
5109 #endif
5110 
5112  connsAllowed = true;
5113 
5114  /* Some workers may be scheduled to start now */
5115  StartWorkerNeeded = true;
5116  }
5117 
5118  /* Process background worker state changes. */
5120  {
5121  /* Accept new worker requests only if not stopping. */
5123  StartWorkerNeeded = true;
5124  }
5125 
5128 
5129  /* Tell syslogger to rotate logfile if requested */
5130  if (SysLoggerPID != 0)
5131  {
5132  if (CheckLogrotateSignal())
5133  {
5136  }
5138  {
5140  }
5141  }
5142 
5145  {
5146  /*
5147  * Start one iteration of the autovacuum daemon, even if autovacuuming
5148  * is nominally not enabled. This is so we can have an active defense
5149  * against transaction ID wraparound. We set a flag for the main loop
5150  * to do it rather than trying to do it here --- this is because the
5151  * autovac process itself may send the signal, and we want to handle
5152  * that by launching another iteration as soon as the current one
5153  * completes.
5154  */
5155  start_autovac_launcher = true;
5156  }
5157 
5160  {
5161  /* The autovacuum launcher wants us to start a worker process. */
5163  }
5164 
5166  {
5167  /* Startup Process wants us to start the walreceiver process. */
5168  /* Start immediately if possible, else remember request for later. */
5169  WalReceiverRequested = true;
5171  }
5172 
5173  /*
5174  * Try to advance postmaster's state machine, if a child requests it.
5175  *
5176  * Be careful about the order of this action relative to this function's
5177  * other actions. Generally, this should be after other actions, in case
5178  * they have effects PostmasterStateMachine would need to know about.
5179  * However, we should do it before the CheckPromoteSignal step, which
5180  * cannot have any (immediate) effect on the state machine, but does
5181  * depend on what state we're in now.
5182  */
5184  {
5186  }
5187 
5188  if (StartupPID != 0 &&
5189  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5190  pmState == PM_HOT_STANDBY) &&
5192  {
5193  /*
5194  * Tell startup process to finish recovery.
5195  *
5196  * Leave the promote signal file in place and let the Startup process
5197  * do the unlink.
5198  */
5200  }
5201 }
void BackgroundWorkerStateChange(bool allow_new_workers)
Definition: bgworker.c:248
#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:5505
static bool start_autovac_launcher
Definition: postmaster.c:362
static void StartAutovacuumWorker(void)
Definition: postmaster.c:5414
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 2694 of file postmaster.c.

2695 {
2696  pending_pm_reload_request = false;
2697 
2698  ereport(DEBUG2,
2699  (errmsg_internal("postmaster received reload request signal")));
2700 
2701  if (Shutdown <= SmartShutdown)
2702  {
2703  ereport(LOG,
2704  (errmsg("received SIGHUP, reloading configuration files")));
2707  if (StartupPID != 0)
2709  if (BgWriterPID != 0)
2711  if (CheckpointerPID != 0)
2713  if (WalWriterPID != 0)
2715  if (WalReceiverPID != 0)
2717  if (AutoVacPID != 0)
2719  if (PgArchPID != 0)
2721  if (SysLoggerPID != 0)
2723 
2724  /* Reload authentication config files too */
2725  if (!load_hba())
2726  ereport(LOG,
2727  /* translator: %s is a configuration file */
2728  (errmsg("%s was not reloaded", HbaFileName)));
2729 
2730  if (!load_ident())
2731  ereport(LOG,
2732  (errmsg("%s was not reloaded", IdentFileName)));
2733 
2734 #ifdef USE_SSL
2735  /* Reload SSL configuration as well */
2736  if (EnableSSL)
2737  {
2738  if (secure_initialize(false) == 0)
2739  LoadedSSL = true;
2740  else
2741  ereport(LOG,
2742  (errmsg("SSL configuration was not reloaded")));
2743  }
2744  else
2745  {
2746  secure_destroy();
2747  LoadedSSL = false;
2748  }
2749 #endif
2750 
2751 #ifdef EXEC_BACKEND
2752  /* Update the starting-point file for future children */
2753  write_nondefault_variables(PGC_SIGHUP);
2754 #endif
2755  }
2756 }
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:538

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

2792 {
2793  int mode;
2794 
2795  ereport(DEBUG2,
2796  (errmsg_internal("postmaster received shutdown request signal")));
2797 
2799 
2800  /*
2801  * If more than one shutdown request signal arrived since the last server
2802  * loop, take the one that is the most immediate. That matches the
2803  * priority that would apply if we processed them one by one in any order.
2804  */
2806  {
2810  }
2812  {
2814  mode = FastShutdown;
2815  }
2816  else
2817  mode = SmartShutdown;
2818 
2819  switch (mode)
2820  {
2821  case SmartShutdown:
2822 
2823  /*
2824  * Smart Shutdown:
2825  *
2826  * Wait for children to end their work, then shut down.
2827  */
2828  if (Shutdown >= SmartShutdown)
2829  break;
2831  ereport(LOG,
2832  (errmsg("received smart shutdown request")));
2833 
2834  /* Report status */
2836 #ifdef USE_SYSTEMD
2837  sd_notify(0, "STOPPING=1");
2838 #endif
2839 
2840  /*
2841  * If we reached normal running, we go straight to waiting for
2842  * client backends to exit. If already in PM_STOP_BACKENDS or a
2843  * later state, do not change it.
2844  */
2845  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2846  connsAllowed = false;
2847  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2848  {
2849  /* There should be no clients, so proceed to stop children */
2851  }
2852 
2853  /*
2854  * Now wait for online backup mode to end and backends to exit. If
2855  * that is already the case, PostmasterStateMachine will take the
2856  * next step.
2857  */
2859  break;
2860 
2861  case FastShutdown:
2862 
2863  /*
2864  * Fast Shutdown:
2865  *
2866  * Abort all children with SIGTERM (rollback active transactions
2867  * and exit) and shut down when they are gone.
2868  */
2869  if (Shutdown >= FastShutdown)
2870  break;
2872  ereport(LOG,
2873  (errmsg("received fast shutdown request")));
2874 
2875  /* Report status */
2877 #ifdef USE_SYSTEMD
2878  sd_notify(0, "STOPPING=1");
2879 #endif
2880 
2881  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2882  {
2883  /* Just shut down background processes silently */
2885  }
2886  else if (pmState == PM_RUN ||
2888  {
2889  /* Report that we're about to zap live client sessions */
2890  ereport(LOG,
2891  (errmsg("aborting any active transactions")));
2893  }
2894 
2895  /*
2896  * PostmasterStateMachine will issue any necessary signals, or
2897  * take the next step if no child processes need to be killed.
2898  */
2900  break;
2901 
2902  case ImmediateShutdown:
2903 
2904  /*
2905  * Immediate Shutdown:
2906  *
2907  * abort all children with SIGQUIT, wait for them to exit,
2908  * terminate remaining ones with SIGKILL, then exit without
2909  * attempt to properly shut down the data base system.
2910  */
2911  if (Shutdown >= ImmediateShutdown)
2912  break;
2914  ereport(LOG,
2915  (errmsg("received immediate shutdown request")));
2916 
2917  /* Report status */
2919 #ifdef USE_SYSTEMD
2920  sd_notify(0, "STOPPING=1");
2921 #endif
2922 
2923  /* tell children to shut down ASAP */
2924  /* (note we don't apply send_abort_for_crash here) */
2928 
2929  /* set stopwatch for them to die */
2930  AbortStartTime = time(NULL);
2931 
2932  /*
2933  * Now wait for backends to exit. If there are none,
2934  * PostmasterStateMachine will take the next step.
2935  */
2937  break;
2938  }
2939 }
static PgChecksumMode mode
Definition: pg_checksums.c:56
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
#define FastShutdown
Definition: postmaster.c: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 5217 of file postmaster.c.

5218 {
5219  _exit(1);
5220 }

Referenced by BackendInitialize().

◆ processCancelRequest()

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

Definition at line 2379 of file postmaster.c.

2380 {
2381  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2382  int backendPID;
2383  int32 cancelAuthCode;
2384  Backend *bp;
2385 
2386 #ifndef EXEC_BACKEND
2387  dlist_iter iter;
2388 #else
2389  int i;
2390 #endif
2391 
2392  backendPID = (int) pg_ntoh32(canc->backendPID);
2393  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2394 
2395  /*
2396  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2397  * longer access the postmaster's own backend list, and must rely on the
2398  * duplicate array in shared memory.
2399  */
2400 #ifndef EXEC_BACKEND
2401  dlist_foreach(iter, &BackendList)
2402  {
2403  bp = dlist_container(Backend, elem, iter.cur);
2404 #else
2405  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2406  {
2407  bp = (Backend *) &ShmemBackendArray[i];
2408 #endif
2409  if (bp->pid == backendPID)
2410  {
2411  if (bp->cancel_key == cancelAuthCode)
2412  {
2413  /* Found a match; signal that backend to cancel current op */
2414  ereport(DEBUG2,
2415  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2416  backendPID)));
2417  signal_child(bp->pid, SIGINT);
2418  }
2419  else
2420  /* Right PID, wrong key: no way, Jose */
2421  ereport(LOG,
2422  (errmsg("wrong key in cancel request for process %d",
2423  backendPID)));
2424  return;
2425  }
2426 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2427  }
2428 #else
2429  }
2430 #endif
2431 
2432  /* No matching backend */
2433  ereport(LOG,
2434  (errmsg("PID %d in cancel request did not match any process",
2435  backendPID)));
2436 }
signed int int32
Definition: c.h:483
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
uint32 backendPID
Definition: pqcomm.h:138
uint32 cancelAuthCode
Definition: pqcomm.h:139

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

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