PostgreSQL Source Code  git master
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/transam.h"
#include "access/xlog.h"
#include "access/xlogrecovery.h"
#include "catalog/pg_control.h"
#include "common/file_perm.h"
#include "common/ip.h"
#include "common/pg_prng.h"
#include "common/string.h"
#include "lib/ilist.h"
#include "libpq/auth.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "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/queryjumble.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 reset_shared (void)
 
static void SIGHUP_handler (SIGNAL_ARGS)
 
static void pmdie (SIGNAL_ARGS)
 
static void reaper (SIGNAL_ARGS)
 
static void sigusr1_handler (SIGNAL_ARGS)
 
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 int initMasks (fd_set *rmask)
 
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 bool SignalSomeChildren (int signal, int targets)
 
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 void DetermineSleepTime (struct timeval *timeout)
 
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
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int ReservedBackends
 
static pgsocket ListenSocket [MAXLISTEN]
 
static bool Reinit = true
 
static int SendStop = false
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
bool remove_temp_files_after_crash = true
 
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 volatile sig_atomic_t start_autovac_launcher = false
 
static volatile bool avlauncher_needs_signal = false
 
static volatile sig_atomic_t WalReceiverRequested = false
 
static volatile bool StartWorkerNeeded = true
 
static volatile bool HaveCrashedWorker = false
 
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 152 of file postmaster.c.

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 149 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 151 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 148 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 150 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 555 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 556 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 557 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 274 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 275 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 222 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 272 of file postmaster.c.

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
bool PgArchCanRestart(void)
Definition: pgarch.c:189
@ PM_RUN
Definition: postmaster.c:328
@ PM_HOT_STANDBY
Definition: postmaster.c:327
@ PM_RECOVERY
Definition: postmaster.c:326
static PMState pmState
Definition: postmaster.c:339
#define XLogArchivingActive()
Definition: xlog.h:94
#define XLogArchivingAlways()
Definition: xlog.h:97

Definition at line 441 of file postmaster.c.

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 354 of file postmaster.c.

◆ SignalChildren

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

Definition at line 424 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 273 of file postmaster.c.

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 548 of file postmaster.c.

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 549 of file postmaster.c.

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 550 of file postmaster.c.

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 547 of file postmaster.c.

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 552 of file postmaster.c.

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 261 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5882 of file postmaster.c.

5883 {
5884  Backend *bn;
5885 
5886  /*
5887  * Check that database state allows another connection. Currently the
5888  * only possible failure is CAC_TOOMANY, so we just log an error message
5889  * based on that rather than checking the error code precisely.
5890  */
5892  {
5893  ereport(LOG,
5894  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5895  errmsg("no slot available for new worker process")));
5896  return false;
5897  }
5898 
5899  /*
5900  * Compute the cancel key that will be assigned to this session. We
5901  * probably don't need cancel keys for background workers, but we'd better
5902  * have something random in the field to prevent unfriendly people from
5903  * sending cancels to them.
5904  */
5906  {
5907  ereport(LOG,
5908  (errcode(ERRCODE_INTERNAL_ERROR),
5909  errmsg("could not generate random cancel key")));
5910  return false;
5911  }
5912 
5913  bn = malloc(sizeof(Backend));
5914  if (bn == NULL)
5915  {
5916  ereport(LOG,
5917  (errcode(ERRCODE_OUT_OF_MEMORY),
5918  errmsg("out of memory")));
5919  return false;
5920  }
5921 
5922  bn->cancel_key = MyCancelKey;
5925  bn->dead_end = false;
5926  bn->bgworker_notify = false;
5927 
5928  rw->rw_backend = bn;
5929  rw->rw_child_slot = bn->child_slot;
5930 
5931  return true;
5932 }
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define LOG
Definition: elog.h:25
#define ereport(elevel,...)
Definition: elog.h:143
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:73
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:219
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2519
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:151
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5333
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:187
int bkend_type
Definition: postmaster.c:185
bool dead_end
Definition: postmaster.c:186
int32 cancel_key
Definition: postmaster.c:183
int child_slot
Definition: postmaster.c:184

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

4316 {
4317  int status;
4318  int ret;
4319  char remote_host[NI_MAXHOST];
4320  char remote_port[NI_MAXSERV];
4321  StringInfoData ps_data;
4322 
4323  /* Save port etc. for ps status */
4324  MyProcPort = port;
4325 
4326  /* Tell fd.c about the long-lived FD associated with the port */
4328 
4329  /*
4330  * PreAuthDelay is a debugging aid for investigating problems in the
4331  * authentication cycle: it can be set in postgresql.conf to allow time to
4332  * attach to the newly-forked backend with a debugger. (See also
4333  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4334  * is not honored until after authentication.)
4335  */
4336  if (PreAuthDelay > 0)
4337  pg_usleep(PreAuthDelay * 1000000L);
4338 
4339  /* This flag will remain set until InitPostgres finishes authentication */
4340  ClientAuthInProgress = true; /* limit visibility of log messages */
4341 
4342  /* set these to empty in case they are needed before we set them up */
4343  port->remote_host = "";
4344  port->remote_port = "";
4345 
4346  /*
4347  * Initialize libpq and enable reporting of ereport errors to the client.
4348  * Must do this now because authentication uses libpq to send messages.
4349  */
4350  pq_init(); /* initialize libpq to talk to client */
4351  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4352 
4353  /*
4354  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4355  * to collect the startup packet; while SIGQUIT results in _exit(2).
4356  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4357  * cleanly if a buggy client fails to send the packet promptly.
4358  *
4359  * Exiting with _exit(1) is only possible because we have not yet touched
4360  * shared memory; therefore no outside-the-process state needs to get
4361  * cleaned up.
4362  */
4364  /* SIGQUIT handler was already set up by InitPostmasterChild */
4365  InitializeTimeouts(); /* establishes SIGALRM handler */
4367 
4368  /*
4369  * Get the remote host name and port for logging and status display.
4370  */
4371  remote_host[0] = '\0';
4372  remote_port[0] = '\0';
4373  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4374  remote_host, sizeof(remote_host),
4375  remote_port, sizeof(remote_port),
4376  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4377  ereport(WARNING,
4378  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4379  gai_strerror(ret))));
4380 
4381  /*
4382  * Save remote_host and remote_port in port structure (after this, they
4383  * will appear in log_line_prefix data for log messages).
4384  */
4385  port->remote_host = strdup(remote_host);
4386  port->remote_port = strdup(remote_port);
4387 
4388  /* And now we can issue the Log_connections message, if wanted */
4389  if (Log_connections)
4390  {
4391  if (remote_port[0])
4392  ereport(LOG,
4393  (errmsg("connection received: host=%s port=%s",
4394  remote_host,
4395  remote_port)));
4396  else
4397  ereport(LOG,
4398  (errmsg("connection received: host=%s",
4399  remote_host)));
4400  }
4401 
4402  /*
4403  * If we did a reverse lookup to name, we might as well save the results
4404  * rather than possibly repeating the lookup during authentication.
4405  *
4406  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4407  * get nothing useful for a client without an rDNS entry. Therefore, we
4408  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4409  * it into remote_hostname if so. (This test is conservative and might
4410  * sometimes classify a hostname as numeric, but an error in that
4411  * direction is safe; it only results in a possible extra lookup.)
4412  */
4413  if (log_hostname &&
4414  ret == 0 &&
4415  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4416  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4417  port->remote_hostname = strdup(remote_host);
4418 
4419  /*
4420  * Ready to begin client interaction. We will give up and _exit(1) after
4421  * a time delay, so that a broken client can't hog a connection
4422  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4423  * against the time limit.
4424  *
4425  * Note: AuthenticationTimeout is applied here while waiting for the
4426  * startup packet, and then again in InitPostgres for the duration of any
4427  * authentication operations. So a hostile client could tie up the
4428  * process for nearly twice AuthenticationTimeout before we kick him off.
4429  *
4430  * Note: because PostgresMain will call InitializeTimeouts again, the
4431  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4432  * since we never use it again after this function.
4433  */
4436 
4437  /*
4438  * Receive the startup packet (which might turn out to be a cancel request
4439  * packet).
4440  */
4441  status = ProcessStartupPacket(port, false, false);
4442 
4443  /*
4444  * Disable the timeout, and prevent SIGTERM again.
4445  */
4447  PG_SETMASK(&BlockSig);
4448 
4449  /*
4450  * As a safety check that nothing in startup has yet performed
4451  * shared-memory modifications that would need to be undone if we had
4452  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4453  * handlers have been registered yet. (This isn't terribly bulletproof,
4454  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4455  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4456  * handlers unfortunately, since pq_init() already registered one.)
4457  */
4459 
4460  /*
4461  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4462  * already did any appropriate error reporting.
4463  */
4464  if (status != STATUS_OK)
4465  proc_exit(0);
4466 
4467  /*
4468  * Now that we have the user and database name, we can set the process
4469  * title for ps. It's good to do this as early as possible in startup.
4470  */
4471  initStringInfo(&ps_data);
4472  if (am_walsender)
4474  appendStringInfo(&ps_data, "%s ", port->user_name);
4475  if (!am_walsender)
4476  appendStringInfo(&ps_data, "%s ", port->database_name);
4477  appendStringInfo(&ps_data, "%s", port->remote_host);
4478  if (port->remote_port[0] != '\0')
4479  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4480 
4481  init_ps_display(ps_data.data);
4482  pfree(ps_data.data);
4483 
4484  set_ps_display("initializing");
4485 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
#define STATUS_OK
Definition: c.h:1178
@ DestRemote
Definition: dest.h:91
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define WARNING
Definition: elog.h:30
void ReserveExternalFD(void)
Definition: fd.c:1149
#define gai_strerror
Definition: getaddrinfo.h:146
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define NI_MAXSERV
Definition: getaddrinfo.h:91
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
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:122
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:1175
@ B_WAL_SENDER
Definition: miscadmin.h:335
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:249
static int port
Definition: pg_regress.c:92
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
CommandDest whereToSendOutput
Definition: postgres.c:92
int PreAuthDelay
Definition: postmaster.c:238
bool log_hostname
Definition: postmaster.c:241
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5299
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5323
bool Log_connections
Definition: postmaster.c:242
bool ClientAuthInProgress
Definition: postmaster.c:358
int AuthenticationTimeout
Definition: postmaster.c:239
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:2000
void pq_init(void)
Definition: pqcomm.c:176
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void set_ps_display(const char *activity)
Definition: ps_status.c:349
void pg_usleep(long microsec)
Definition: signal.c:53
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
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(), 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(), gai_strerror, GetBackendTypeDesc(), init_ps_display(), InitializeTimeouts(), initStringInfo(), LOG, Log_connections, log_hostname, MyProcPort, NI_MAXHOST, NI_MAXSERV, NI_NUMERICHOST, NI_NUMERICSERV, pfree(), pg_getnameinfo_all(), PG_SETMASK, pg_usleep(), port, pq_init(), pqsignal(), PreAuthDelay, proc_exit(), process_startup_packet_die(), ProcessStartupPacket(), RegisterTimeout(), ReserveExternalFD(), set_ps_display(), STARTUP_PACKET_TIMEOUT, StartupBlockSig, StartupPacketTimeoutHandler(), status(), STATUS_OK, WARNING, and whereToSendOutput.

Referenced by BackendStartup().

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4495 of file postmaster.c.

4496 {
4497  /*
4498  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4499  * just yet, though, because InitPostgres will need the HBA data.)
4500  */
4502 
4503  PostgresMain(port->database_name, port->user_name);
4504 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4048

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

Referenced by BackendStartup().

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4155 of file postmaster.c.

4156 {
4157  Backend *bn; /* for backend cleanup */
4158  pid_t pid;
4159 
4160  /*
4161  * Create backend data structure. Better before the fork() so we can
4162  * handle failure cleanly.
4163  */
4164  bn = (Backend *) malloc(sizeof(Backend));
4165  if (!bn)
4166  {
4167  ereport(LOG,
4168  (errcode(ERRCODE_OUT_OF_MEMORY),
4169  errmsg("out of memory")));
4170  return STATUS_ERROR;
4171  }
4172 
4173  /*
4174  * Compute the cancel key that will be assigned to this backend. The
4175  * backend will have its own copy in the forked-off process' value of
4176  * MyCancelKey, so that it can transmit the key to the frontend.
4177  */
4179  {
4180  free(bn);
4181  ereport(LOG,
4182  (errcode(ERRCODE_INTERNAL_ERROR),
4183  errmsg("could not generate random cancel key")));
4184  return STATUS_ERROR;
4185  }
4186 
4187  bn->cancel_key = MyCancelKey;
4188 
4189  /* Pass down canAcceptConnections state */
4190  port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL);
4191  bn->dead_end = (port->canAcceptConnections != CAC_OK);
4192 
4193  /*
4194  * Unless it's a dead_end child, assign it a child slot number
4195  */
4196  if (!bn->dead_end)
4198  else
4199  bn->child_slot = 0;
4200 
4201  /* Hasn't asked to be notified about any bgworkers yet */
4202  bn->bgworker_notify = false;
4203 
4204 #ifdef EXEC_BACKEND
4205  pid = backend_forkexec(port);
4206 #else /* !EXEC_BACKEND */
4207  pid = fork_process();
4208  if (pid == 0) /* child */
4209  {
4210  free(bn);
4211 
4212  /* Detangle from postmaster */
4214 
4215  /* Close the postmaster's sockets */
4216  ClosePostmasterPorts(false);
4217 
4218  /* Perform additional initialization and collect startup packet */
4220 
4221  /*
4222  * Create a per-backend PGPROC struct in shared memory. We must do
4223  * this before we can use LWLocks. In the !EXEC_BACKEND case (here)
4224  * this could be delayed a bit further, but EXEC_BACKEND needs to do
4225  * stuff with LWLocks before PostgresMain(), so we do it here as well
4226  * for symmetry.
4227  */
4228  InitProcess();
4229 
4230  /* And run the backend */
4231  BackendRun(port);
4232  }
4233 #endif /* EXEC_BACKEND */
4234 
4235  if (pid < 0)
4236  {
4237  /* in parent, fork failed */
4238  int save_errno = errno;
4239 
4240  if (!bn->dead_end)
4242  free(bn);
4243  errno = save_errno;
4244  ereport(LOG,
4245  (errmsg("could not fork new process for connection: %m")));
4246  report_fork_failure_to_client(port, save_errno);
4247  return STATUS_ERROR;
4248  }
4249 
4250  /* in parent, successful fork */
4251  ereport(DEBUG2,
4252  (errmsg_internal("forked new backend, pid=%d socket=%d",
4253  (int) pid, (int) port->sock)));
4254 
4255  /*
4256  * Everything's been successful, it's safe to add this backend to our list
4257  * of backends.
4258  */
4259  bn->pid = pid;
4260  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4262 
4263 #ifdef EXEC_BACKEND
4264  if (!bn->dead_end)
4265  ShmemBackendArrayAdd(bn);
4266 #endif
4267 
4268  return STATUS_OK;
4269 }
#define STATUS_ERROR
Definition: c.h:1179
#define DEBUG2
Definition: elog.h:23
pid_t fork_process(void)
Definition: fork_process.c:29
#define free(a)
Definition: header.h:65
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
void InitPostmasterChild(void)
Definition: miscinit.c:95
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:148
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4495
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2623
static void BackendInitialize(Port *port)
Definition: postmaster.c:4315
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4280
static dlist_head BackendList
Definition: postmaster.c:191
void InitProcess(void)
Definition: proc.c:301
dlist_node elem
Definition: postmaster.c:188
pid_t pid
Definition: postmaster.c:182

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

5707 {
5708  PG_SETMASK(&BlockSig);
5709 }

References BlockSig, and PG_SETMASK.

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5660 of file postmaster.c.

5661 {
5663 
5664  /* XXX is this the right errcode? */
5666  ereport(FATAL,
5667  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5668  errmsg("database connection requirement not indicated during registration")));
5669 
5671 
5672  /* it had better not gotten out of "init" mode yet */
5673  if (!IsInitProcessingMode())
5674  ereport(ERROR,
5675  (errmsg("invalid processing mode in background worker")));
5677 }
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:155
#define FATAL
Definition: elog.h:35
#define ERROR
Definition: elog.h:33
@ NormalProcessing
Definition: miscadmin.h:401
#define IsInitProcessingMode()
Definition: miscadmin.h:407
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
const char * username
Definition: pgbench.c:309
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:646
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:197
char * dbname
Definition: streamutil.c:51

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

Referenced by ApplyLauncherMain().

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5683 of file postmaster.c.

5684 {
5686 
5687  /* XXX is this the right errcode? */
5689  ereport(FATAL,
5690  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5691  errmsg("database connection requirement not indicated during registration")));
5692 
5693  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5694 
5695  /* it had better not gotten out of "init" mode yet */
5696  if (!IsInitProcessingMode())
5697  ereport(ERROR,
5698  (errmsg("invalid processing mode in background worker")));
5700 }

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

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

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5840 of file postmaster.c.

5841 {
5842  switch (pmState)
5843  {
5844  case PM_NO_CHILDREN:
5845  case PM_WAIT_DEAD_END:
5846  case PM_SHUTDOWN_2:
5847  case PM_SHUTDOWN:
5848  case PM_WAIT_BACKENDS:
5849  case PM_STOP_BACKENDS:
5850  break;
5851 
5852  case PM_RUN:
5854  return true;
5855  /* fall through */
5856 
5857  case PM_HOT_STANDBY:
5859  return true;
5860  /* fall through */
5861 
5862  case PM_RECOVERY:
5863  case PM_STARTUP:
5864  case PM_INIT:
5866  return true;
5867  /* fall through */
5868  }
5869 
5870  return false;
5871 }
@ 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:99

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

2520 {
2521  CAC_state result = CAC_OK;
2522 
2523  /*
2524  * Can't start backends when in startup/shutdown/inconsistent recovery
2525  * state. We treat autovac workers the same as user backends for this
2526  * purpose. However, bgworkers are excluded from this test; we expect
2527  * bgworker_should_start_now() decided whether the DB state allows them.
2528  */
2529  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2530  backend_type != BACKEND_TYPE_BGWORKER)
2531  {
2532  if (Shutdown > NoShutdown)
2533  return CAC_SHUTDOWN; /* shutdown is pending */
2534  else if (!FatalError && pmState == PM_STARTUP)
2535  return CAC_STARTUP; /* normal startup */
2536  else if (!FatalError && pmState == PM_RECOVERY)
2537  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2538  * state */
2539  else
2540  return CAC_RECOVERY; /* else must be crash recovery */
2541  }
2542 
2543  /*
2544  * "Smart shutdown" restrictions are applied only to normal connections,
2545  * not to autovac workers or bgworkers.
2546  */
2547  if (!connsAllowed && backend_type == BACKEND_TYPE_NORMAL)
2548  return CAC_SHUTDOWN; /* shutdown is pending */
2549 
2550  /*
2551  * Don't start too many children.
2552  *
2553  * We allow more connections here than we can have backends because some
2554  * might still be authenticating; they might fail auth, or some existing
2555  * backend might exit before the auth cycle is completed. The exact
2556  * MaxBackends limit is enforced when a new backend tries to join the
2557  * shared-inval backend array.
2558  *
2559  * The limit here must match the sizes of the per-child-process arrays;
2560  * see comments for MaxLivePostmasterChildren().
2561  */
2563  result = CAC_TOOMANY;
2564 
2565  return result;
2566 }
CAC_state
Definition: libpq-be.h:72
@ CAC_TOOMANY
Definition: libpq-be.h:78
@ CAC_RECOVERY
Definition: libpq-be.h:76
@ CAC_NOTCONSISTENT
Definition: libpq-be.h:77
@ CAC_STARTUP
Definition: libpq-be.h:74
@ CAC_SHUTDOWN
Definition: libpq-be.h:75
static bool connsAllowed
Definition: postmaster.c:347
static int Shutdown
Definition: postmaster.c:277
#define BACKEND_TYPE_ALL
Definition: postmaster.c:152
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5650
#define NoShutdown
Definition: postmaster.c:272
static bool FatalError
Definition: postmaster.c:279
static int CountChildren(int target)
Definition: postmaster.c:5343

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

1595 {
1596  char path[MAXPGPATH];
1597  FILE *fp;
1598 
1599  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1600 
1601  fp = AllocateFile(path, PG_BINARY_R);
1602  if (fp == NULL)
1603  {
1604  write_stderr("%s: could not find the database system\n"
1605  "Expected to find it in the directory \"%s\",\n"
1606  "but could not open file \"%s\": %s\n",
1607  progname, DataDir, path, strerror(errno));
1608  ExitPostmaster(2);
1609  }
1610  FreeFile(fp);
1611 }
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1281
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2398
int FreeFile(FILE *file)
Definition: fd.c:2597
char * DataDir
Definition: globals.c:66
const char * progname
Definition: main.c:50
#define MAXPGPATH
#define strerror
Definition: port.h:238
#define snprintf
Definition: port.h:225
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5093

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

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

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3298 of file postmaster.c.

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

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

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2623 of file postmaster.c.

2624 {
2625  int i;
2626 
2627 #ifndef WIN32
2628 
2629  /*
2630  * Close the write end of postmaster death watch pipe. It's important to
2631  * do this as early as possible, so that if postmaster dies, others won't
2632  * think that it's still running because we're holding the pipe open.
2633  */
2635  ereport(FATAL,
2637  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2639  /* Notify fd.c that we released one pipe FD. */
2641 #endif
2642 
2643  /*
2644  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2645  * so we don't call ReleaseExternalFD() here.
2646  */
2647  for (i = 0; i < MAXLISTEN; i++)
2648  {
2650  {
2653  }
2654  }
2655 
2656  /*
2657  * If using syslogger, close the read side of the pipe. We don't bother
2658  * tracking this in fd.c, either.
2659  */
2660  if (!am_syslogger)
2661  {
2662 #ifndef WIN32
2663  if (syslogPipe[0] >= 0)
2664  close(syslogPipe[0]);
2665  syslogPipe[0] = -1;
2666 #else
2667  if (syslogPipe[0])
2668  CloseHandle(syslogPipe[0]);
2669  syslogPipe[0] = 0;
2670 #endif
2671  }
2672 
2673 #ifdef USE_BONJOUR
2674  /* If using Bonjour, close the connection to the mDNS daemon */
2675  if (bonjour_sdref)
2676  close(DNSServiceRefSockFD(bonjour_sdref));
2677 #endif
2678 }
int errcode_for_file_access(void)
Definition: elog.c:716
void ReleaseExternalFD(void)
Definition: fd.c:1167
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
#define PGINVALID_SOCKET
Definition: port.h:31
int postmaster_alive_fds[2]
Definition: postmaster.c:564
#define MAXLISTEN
Definition: postmaster.c:222
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:223
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
void StreamClose(pgsocket sock)
Definition: pqcomm.c:850
int syslogPipe[2]
Definition: syslogger.c:117

References close, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, i, ListenSocket, MAXLISTEN, PGINVALID_SOCKET, 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 1492 of file postmaster.c.

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

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

Referenced by PostmasterMain().

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2575 of file postmaster.c.

2576 {
2577  Port *port;
2578 
2579  if (!(port = (Port *) calloc(1, sizeof(Port))))
2580  {
2581  ereport(LOG,
2582  (errcode(ERRCODE_OUT_OF_MEMORY),
2583  errmsg("out of memory")));
2584  ExitPostmaster(1);
2585  }
2586 
2587  if (StreamConnection(serverFd, port) != STATUS_OK)
2588  {
2589  if (port->sock != PGINVALID_SOCKET)
2590  StreamClose(port->sock);
2591  ConnFree(port);
2592  return NULL;
2593  }
2594 
2595  return port;
2596 }
#define calloc(a, b)
Definition: header.h:55
static void ConnFree(Port *port)
Definition: postmaster.c:2606
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:716
Definition: libpq-be.h:125

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

2607 {
2608  free(conn);
2609 }
PGconn * conn
Definition: streamutil.c:54

References conn, and free.

Referenced by ConnCreate(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5343 of file postmaster.c.

5344 {
5345  dlist_iter iter;
5346  int cnt = 0;
5347 
5348  dlist_foreach(iter, &BackendList)
5349  {
5350  Backend *bp = dlist_container(Backend, elem, iter.cur);
5351 
5352  if (bp->dead_end)
5353  continue;
5354 
5355  /*
5356  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5357  * it first and avoid touching shared memory for every child.
5358  */
5359  if (target != BACKEND_TYPE_ALL)
5360  {
5361  /*
5362  * Assign bkend_type for any recently announced WAL Sender
5363  * processes.
5364  */
5365  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5368 
5369  if (!(target & bp->bkend_type))
5370  continue;
5371  }
5372 
5373  cnt++;
5374  }
5375  return cnt;
5376 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:275
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:150
dlist_node * cur
Definition: ilist.h:161

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

5607 {
5608  FILE *fp;
5609  int i;
5610 
5611 #define OPTS_FILE "postmaster.opts"
5612 
5613  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5614  {
5615  ereport(LOG,
5617  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5618  return false;
5619  }
5620 
5621  fprintf(fp, "%s", fullprogname);
5622  for (i = 1; i < argc; i++)
5623  fprintf(fp, " \"%s\"", argv[i]);
5624  fputs("\n", fp);
5625 
5626  if (fclose(fp))
5627  {
5628  ereport(LOG,
5630  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5631  return false;
5632  }
5633 
5634  return true;
5635 }
#define fprintf
Definition: port.h:229
#define OPTS_FILE

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

Referenced by PostmasterMain().

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1623 of file postmaster.c.

1624 {
1625  TimestampTz next_wakeup = 0;
1626 
1627  /*
1628  * Normal case: either there are no background workers at all, or we're in
1629  * a shutdown sequence (during which we ignore bgworkers altogether).
1630  */
1631  if (Shutdown > NoShutdown ||
1633  {
1634  if (AbortStartTime != 0)
1635  {
1636  /* time left to abort; clamp to 0 in case it already expired */
1637  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1638  (time(NULL) - AbortStartTime);
1639  timeout->tv_sec = Max(timeout->tv_sec, 0);
1640  timeout->tv_usec = 0;
1641  }
1642  else
1643  {
1644  timeout->tv_sec = 60;
1645  timeout->tv_usec = 0;
1646  }
1647  return;
1648  }
1649 
1650  if (StartWorkerNeeded)
1651  {
1652  timeout->tv_sec = 0;
1653  timeout->tv_usec = 0;
1654  return;
1655  }
1656 
1657  if (HaveCrashedWorker)
1658  {
1659  slist_mutable_iter siter;
1660 
1661  /*
1662  * When there are crashed bgworkers, we sleep just long enough that
1663  * they are restarted when they request to be. Scan the list to
1664  * determine the minimum of all wakeup times according to most recent
1665  * crash time and requested restart interval.
1666  */
1668  {
1669  RegisteredBgWorker *rw;
1670  TimestampTz this_wakeup;
1671 
1672  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1673 
1674  if (rw->rw_crashed_at == 0)
1675  continue;
1676 
1678  || rw->rw_terminate)
1679  {
1680  ForgetBackgroundWorker(&siter);
1681  continue;
1682  }
1683 
1684  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1685  1000L * rw->rw_worker.bgw_restart_time);
1686  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1687  next_wakeup = this_wakeup;
1688  }
1689  }
1690 
1691  if (next_wakeup != 0)
1692  {
1693  long secs;
1694  int microsecs;
1695 
1697  &secs, &microsecs);
1698  timeout->tv_sec = secs;
1699  timeout->tv_usec = microsecs;
1700 
1701  /* Ensure we don't exceed one minute */
1702  if (timeout->tv_sec > 60)
1703  {
1704  timeout->tv_sec = 60;
1705  timeout->tv_usec = 0;
1706  }
1707  }
1708  else
1709  {
1710  timeout->tv_sec = 60;
1711  timeout->tv_usec = 0;
1712  }
1713 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1650
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:426
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Max(x, y)
Definition: c.h:991
int64 TimestampTz
Definition: timestamp.h:39
static time_t AbortStartTime
Definition: postmaster.c:351
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:354
static volatile bool HaveCrashedWorker
Definition: postmaster.c:374
static volatile bool StartWorkerNeeded
Definition: postmaster.c:373
int bgw_restart_time
Definition: bgworker.h:95
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56

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

Referenced by ServerLoop().

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5748 of file postmaster.c.

5749 {
5750  pid_t worker_pid;
5751 
5752  Assert(rw->rw_pid == 0);
5753 
5754  /*
5755  * Allocate and assign the Backend element. Note we must do this before
5756  * forking, so that we can handle failures (out of memory or child-process
5757  * slots) cleanly.
5758  *
5759  * Treat failure as though the worker had crashed. That way, the
5760  * postmaster will wait a bit before attempting to start it again; if we
5761  * tried again right away, most likely we'd find ourselves hitting the
5762  * same resource-exhaustion condition.
5763  */
5764  if (!assign_backendlist_entry(rw))
5765  {
5767  return false;
5768  }
5769 
5770  ereport(DEBUG1,
5771  (errmsg_internal("starting background worker process \"%s\"",
5772  rw->rw_worker.bgw_name)));
5773 
5774 #ifdef EXEC_BACKEND
5775  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5776 #else
5777  switch ((worker_pid = fork_process()))
5778 #endif
5779  {
5780  case -1:
5781  /* in postmaster, fork failed ... */
5782  ereport(LOG,
5783  (errmsg("could not fork worker process: %m")));
5784  /* undo what assign_backendlist_entry did */
5786  rw->rw_child_slot = 0;
5787  free(rw->rw_backend);
5788  rw->rw_backend = NULL;
5789  /* mark entry as crashed, so we'll try again later */
5791  break;
5792 
5793 #ifndef EXEC_BACKEND
5794  case 0:
5795  /* in postmaster child ... */
5797 
5798  /* Close the postmaster's sockets */
5799  ClosePostmasterPorts(false);
5800 
5801  /*
5802  * Before blowing away PostmasterContext, save this bgworker's
5803  * data where it can find it.
5804  */
5807  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5808 
5809  /* Release postmaster's working memory context */
5812  PostmasterContext = NULL;
5813 
5815 
5816  exit(1); /* should not get here */
5817  break;
5818 #endif
5819  default:
5820  /* in postmaster, fork successful ... */
5821  rw->rw_pid = worker_pid;
5822  rw->rw_backend->pid = rw->rw_pid;
5824  /* add new worker to lists of backends */
5826 #ifdef EXEC_BACKEND
5827  ShmemBackendArrayAdd(rw->rw_backend);
5828 #endif
5829  return true;
5830  }
5831 
5832  return false;
5833 }
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
void StartBackgroundWorker(void)
Definition: bgworker.c:741
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
MemoryContext PostmasterContext
Definition: mcxt.c:50
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5882
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 5314 of file postmaster.c.

5315 {
5316 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5093 of file postmaster.c.

5094 {
5095 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5096 
5097  /*
5098  * There is no known cause for a postmaster to become multithreaded after
5099  * startup. Recheck to account for the possibility of unknown causes.
5100  * This message uses LOG level, because an unclean shutdown at this point
5101  * would usually not look much different from a clean shutdown.
5102  */
5103  if (pthread_is_threaded_np() != 0)
5104  ereport(LOG,
5105  (errcode(ERRCODE_INTERNAL_ERROR),
5106  errmsg_internal("postmaster became multithreaded"),
5107  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5108 #endif
5109 
5110  /* should cleanup shared memory and kill all backends */
5111 
5112  /*
5113  * Not sure of the semantics here. When the Postmaster dies, should the
5114  * backends all be killed? probably not.
5115  *
5116  * MUST -- vadim 05-10-1999
5117  */
5118 
5119  proc_exit(status);
5120 }
int errdetail(const char *fmt,...)
Definition: elog.c:1037

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

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1540 of file postmaster.c.

1541 {
1542  DIR *pdir;
1543 
1544  /* Locate the postgres executable itself */
1545  if (find_my_exec(argv0, my_exec_path) < 0)
1546  ereport(FATAL,
1547  (errmsg("%s: could not locate my own executable path", argv0)));
1548 
1549 #ifdef EXEC_BACKEND
1550  /* Locate executable backend before we change working directory */
1551  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1552  postgres_exec_path) < 0)
1553  ereport(FATAL,
1554  (errmsg("%s: could not locate matching postgres executable",
1555  argv0)));
1556 #endif
1557 
1558  /*
1559  * Locate the pkglib directory --- this has to be set early in case we try
1560  * to load any modules from it in response to postgresql.conf entries.
1561  */
1563 
1564  /*
1565  * Verify that there's a readable directory there; otherwise the Postgres
1566  * installation is incomplete or corrupt. (A typical cause of this
1567  * failure is that the postgres executable has been moved or hardlinked to
1568  * some directory that's not a sibling of the installation lib/
1569  * directory.)
1570  */
1571  pdir = AllocateDir(pkglib_path);
1572  if (pdir == NULL)
1573  ereport(ERROR,
1575  errmsg("could not open directory \"%s\": %m",
1576  pkglib_path),
1577  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1578  my_exec_path)));
1579  FreeDir(pdir);
1580 
1581  /*
1582  * XXX is it worth similarly checking the share/ directory? If the lib/
1583  * directory is there, then share/ probably is too.
1584  */
1585 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:140
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:335
int errhint(const char *fmt,...)
Definition: elog.c:1151
int FreeDir(DIR *dir)
Definition: fd.c:2777
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2659
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
static char * argv0
Definition: pg_ctl.c:97
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879
#define PG_BACKEND_VERSIONSTR
Definition: port.h:139
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().

◆ HandleChildCrash()

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

Definition at line 3477 of file postmaster.c.

3478 {
3479  dlist_mutable_iter iter;
3480  slist_iter siter;
3481  Backend *bp;
3482  bool take_action;
3483 
3484  /*
3485  * We only log messages and send signals if this is the first process
3486  * crash and we're not doing an immediate shutdown; otherwise, we're only
3487  * here to update postmaster's idea of live processes. If we have already
3488  * signaled children, nonzero exit status is to be expected, so don't
3489  * clutter log.
3490  */
3491  take_action = !FatalError && Shutdown != ImmediateShutdown;
3492 
3493  if (take_action)
3494  {
3495  LogChildExit(LOG, procname, pid, exitstatus);
3496  ereport(LOG,
3497  (errmsg("terminating any other active server processes")));
3499  }
3500 
3501  /* Process background workers. */
3503  {
3504  RegisteredBgWorker *rw;
3505 
3506  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3507  if (rw->rw_pid == 0)
3508  continue; /* not running */
3509  if (rw->rw_pid == pid)
3510  {
3511  /*
3512  * Found entry for freshly-dead worker, so remove it.
3513  */
3515  dlist_delete(&rw->rw_backend->elem);
3516 #ifdef EXEC_BACKEND
3517  ShmemBackendArrayRemove(rw->rw_backend);
3518 #endif
3519  free(rw->rw_backend);
3520  rw->rw_backend = NULL;
3521  rw->rw_pid = 0;
3522  rw->rw_child_slot = 0;
3523  /* don't reset crashed_at */
3524  /* don't report child stop, either */
3525  /* Keep looping so we can signal remaining workers */
3526  }
3527  else
3528  {
3529  /*
3530  * This worker is still alive. Unless we did so already, tell it
3531  * to commit hara-kiri.
3532  *
3533  * SIGQUIT is the special signal that says exit without proc_exit
3534  * and let the user know what's going on. But if SendStop is set
3535  * (-T on command line), then we send SIGSTOP instead, so that we
3536  * can get core dumps from all backends by hand.
3537  */
3538  if (take_action)
3539  {
3540  ereport(DEBUG2,
3541  (errmsg_internal("sending %s to process %d",
3542  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3543  (int) rw->rw_pid)));
3545  }
3546  }
3547  }
3548 
3549  /* Process regular backends */
3551  {
3552  bp = dlist_container(Backend, elem, iter.cur);
3553 
3554  if (bp->pid == pid)
3555  {
3556  /*
3557  * Found entry for freshly-dead backend, so remove it.
3558  */
3559  if (!bp->dead_end)
3560  {
3562 #ifdef EXEC_BACKEND
3563  ShmemBackendArrayRemove(bp);
3564 #endif
3565  }
3566  dlist_delete(iter.cur);
3567  free(bp);
3568  /* Keep looping so we can signal remaining backends */
3569  }
3570  else
3571  {
3572  /*
3573  * This backend is still alive. Unless we did so already, tell it
3574  * to commit hara-kiri.
3575  *
3576  * SIGQUIT is the special signal that says exit without proc_exit
3577  * and let the user know what's going on. But if SendStop is set
3578  * (-T on command line), then we send SIGSTOP instead, so that we
3579  * can get core dumps from all backends by hand.
3580  *
3581  * We could exclude dead_end children here, but at least in the
3582  * SIGSTOP case it seems better to include them.
3583  *
3584  * Background workers were already processed above; ignore them
3585  * here.
3586  */
3587  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3588  continue;
3589 
3590  if (take_action)
3591  {
3592  ereport(DEBUG2,
3593  (errmsg_internal("sending %s to process %d",
3594  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3595  (int) bp->pid)));
3596  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3597  }
3598  }
3599  }
3600 
3601  /* Take care of the startup process too */
3602  if (pid == StartupPID)
3603  {
3604  StartupPID = 0;
3605  /* Caller adjusts StartupStatus, so don't touch it here */
3606  }
3607  else if (StartupPID != 0 && take_action)
3608  {
3609  ereport(DEBUG2,
3610  (errmsg_internal("sending %s to process %d",
3611  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3612  (int) StartupPID)));
3615  }
3616 
3617  /* Take care of the bgwriter too */
3618  if (pid == BgWriterPID)
3619  BgWriterPID = 0;
3620  else if (BgWriterPID != 0 && take_action)
3621  {
3622  ereport(DEBUG2,
3623  (errmsg_internal("sending %s to process %d",
3624  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3625  (int) BgWriterPID)));
3627  }
3628 
3629  /* Take care of the checkpointer too */
3630  if (pid == CheckpointerPID)
3631  CheckpointerPID = 0;
3632  else if (CheckpointerPID != 0 && take_action)
3633  {
3634  ereport(DEBUG2,
3635  (errmsg_internal("sending %s to process %d",
3636  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3637  (int) CheckpointerPID)));
3639  }
3640 
3641  /* Take care of the walwriter too */
3642  if (pid == WalWriterPID)
3643  WalWriterPID = 0;
3644  else if (WalWriterPID != 0 && take_action)
3645  {
3646  ereport(DEBUG2,
3647  (errmsg_internal("sending %s to process %d",
3648  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3649  (int) WalWriterPID)));
3651  }
3652 
3653  /* Take care of the walreceiver too */
3654  if (pid == WalReceiverPID)
3655  WalReceiverPID = 0;
3656  else if (WalReceiverPID != 0 && take_action)
3657  {
3658  ereport(DEBUG2,
3659  (errmsg_internal("sending %s to process %d",
3660  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3661  (int) WalReceiverPID)));
3663  }
3664 
3665  /* Take care of the autovacuum launcher too */
3666  if (pid == AutoVacPID)
3667  AutoVacPID = 0;
3668  else if (AutoVacPID != 0 && take_action)
3669  {
3670  ereport(DEBUG2,
3671  (errmsg_internal("sending %s to process %d",
3672  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3673  (int) AutoVacPID)));
3675  }
3676 
3677  /* Take care of the archiver too */
3678  if (pid == PgArchPID)
3679  PgArchPID = 0;
3680  else if (PgArchPID != 0 && take_action)
3681  {
3682  ereport(DEBUG2,
3683  (errmsg_internal("sending %s to process %d",
3684  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3685  (int) PgArchPID)));
3687  }
3688 
3689  /* We do NOT restart the syslogger */
3690 
3691  if (Shutdown != ImmediateShutdown)
3692  FatalError = true;
3693 
3694  /* We now transit into a state of waiting for children to die */
3695  if (pmState == PM_RECOVERY ||
3696  pmState == PM_HOT_STANDBY ||
3697  pmState == PM_RUN ||
3699  pmState == PM_SHUTDOWN)
3701 
3702  /*
3703  * .. and if this doesn't happen quickly enough, now the clock is ticking
3704  * for us to kill them without mercy.
3705  */
3706  if (AbortStartTime == 0)
3707  AbortStartTime = time(NULL);
3708 }
#define slist_foreach(iter, lhead)
Definition: ilist.h:719
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:190
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
static pid_t WalReceiverPID
Definition: postmaster.c:255
static pid_t PgArchPID
Definition: postmaster.c:257
#define ImmediateShutdown
Definition: postmaster.c:275
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4054
static pid_t AutoVacPID
Definition: postmaster.c:256
static int SendStop
Definition: postmaster.c:233
static pid_t CheckpointerPID
Definition: postmaster.c:253
static pid_t BgWriterPID
Definition: postmaster.c:252
static pid_t WalWriterPID
Definition: postmaster.c:254
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
static pid_t StartupPID
Definition: postmaster.c:251
slist_node * cur
Definition: ilist.h:226
#define SIGSTOP
Definition: win32_port.h:174
#define SIGQUIT
Definition: win32_port.h:168

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, DEBUG2, dlist_container, dlist_delete(), dlist_foreach_modify, bkend::elem, ereport, errmsg(), errmsg_internal(), 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, SendStop, SetQuitSignalReason(), Shutdown, signal_child(), SIGQUIT, SIGSTOP, slist_container, slist_foreach, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1958 of file postmaster.c.

1959 {
1960  int maxsock = -1;
1961  int i;
1962 
1963  FD_ZERO(rmask);
1964 
1965  for (i = 0; i < MAXLISTEN; i++)
1966  {
1967  int fd = ListenSocket[i];
1968 
1969  if (fd == PGINVALID_SOCKET)
1970  break;
1971  FD_SET(fd, rmask);
1972 
1973  if (fd > maxsock)
1974  maxsock = fd;
1975  }
1976 
1977  return maxsock + 1;
1978 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105

References fd(), i, ListenSocket, MAXLISTEN, and PGINVALID_SOCKET.

Referenced by ServerLoop().

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6541 of file postmaster.c.

6542 {
6543 #ifndef WIN32
6544 
6545  /*
6546  * Create a pipe. Postmaster holds the write end of the pipe open
6547  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6548  * the read file descriptor to select() to wake up in case postmaster
6549  * dies, or check for postmaster death with a (read() == 0). Children must
6550  * close the write end as soon as possible after forking, because EOF
6551  * won't be signaled in the read end until all processes have closed the
6552  * write fd. That is taken care of in ClosePostmasterPorts().
6553  */
6555  if (pipe(postmaster_alive_fds) < 0)
6556  ereport(FATAL,
6558  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6559 
6560  /* Notify fd.c that we've eaten two FDs for the pipe. */
6563 
6564  /*
6565  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6566  * call.
6567  */
6568  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6569  ereport(FATAL,
6571  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6572 #else
6573 
6574  /*
6575  * On Windows, we use a process handle for the same purpose.
6576  */
6577  if (DuplicateHandle(GetCurrentProcess(),
6578  GetCurrentProcess(),
6579  GetCurrentProcess(),
6580  &PostmasterHandle,
6581  0,
6582  TRUE,
6583  DUPLICATE_SAME_ACCESS) == 0)
6584  ereport(FATAL,
6585  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6586  GetLastError())));
6587 #endif /* WIN32 */
6588 }
int errcode_for_socket_access(void)
Definition: elog.c:787
pid_t PostmasterPid
Definition: globals.c:99
int MyProcPid
Definition: globals.c:44
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:43

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

2688 {
2689  MyProcPid = getpid();
2692 
2693  /*
2694  * Set a different global seed in every process. We want something
2695  * unpredictable, so if possible, use high-quality random bits for the
2696  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2697  */
2699  {
2700  uint64 rseed;
2701 
2702  /*
2703  * Since PIDs and timestamps tend to change more frequently in their
2704  * least significant bits, shift the timestamp left to allow a larger
2705  * total number of seeds in a given time period. Since that would
2706  * leave only 20 bits of the timestamp that cycle every ~1 second,
2707  * also mix in some higher bits.
2708  */
2709  rseed = ((uint64) MyProcPid) ^
2710  ((uint64) MyStartTimestamp << 12) ^
2711  ((uint64) MyStartTimestamp >> 20);
2712 
2714  }
2715 
2716  /*
2717  * Also make sure that we've set a good seed for random(3). Use of that
2718  * is deprecated in core Postgres, but extensions might use it.
2719  */
2720 #ifndef WIN32
2722 #endif
2723 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1748
#define unlikely(x)
Definition: c.h:284
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:185
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:83
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:28
#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 3714 of file postmaster.c.

3715 {
3716  /*
3717  * size of activity_buffer is arbitrary, but set equal to default
3718  * track_activity_query_size
3719  */
3720  char activity_buffer[1024];
3721  const char *activity = NULL;
3722 
3723  if (!EXIT_STATUS_0(exitstatus))
3724  activity = pgstat_get_crashed_backend_activity(pid,
3725  activity_buffer,
3726  sizeof(activity_buffer));
3727 
3728  if (WIFEXITED(exitstatus))
3729  ereport(lev,
3730 
3731  /*------
3732  translator: %s is a noun phrase describing a child process, such as
3733  "server process" */
3734  (errmsg("%s (PID %d) exited with exit code %d",
3735  procname, pid, WEXITSTATUS(exitstatus)),
3736  activity ? errdetail("Failed process was running: %s", activity) : 0));
3737  else if (WIFSIGNALED(exitstatus))
3738  {
3739 #if defined(WIN32)
3740  ereport(lev,
3741 
3742  /*------
3743  translator: %s is a noun phrase describing a child process, such as
3744  "server process" */
3745  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3746  procname, pid, WTERMSIG(exitstatus)),
3747  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3748  activity ? errdetail("Failed process was running: %s", activity) : 0));
3749 #else
3750  ereport(lev,
3751 
3752  /*------
3753  translator: %s is a noun phrase describing a child process, such as
3754  "server process" */
3755  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3756  procname, pid, WTERMSIG(exitstatus),
3757  pg_strsignal(WTERMSIG(exitstatus))),
3758  activity ? errdetail("Failed process was running: %s", activity) : 0));
3759 #endif
3760  }
3761  else
3762  ereport(lev,
3763 
3764  /*------
3765  translator: %s is a noun phrase describing a child process, such as
3766  "server process" */
3767  (errmsg("%s (PID %d) exited with unrecognized status %d",
3768  procname, pid, exitstatus),
3769  activity ? errdetail("Failed process was running: %s", activity) : 0));
3770 }
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:151
#define WIFSIGNALED(w)
Definition: win32_port.h:152
#define WTERMSIG(w)
Definition: win32_port.h:154
#define WEXITSTATUS(w)
Definition: win32_port.h:153

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

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5650 of file postmaster.c.

5651 {
5652  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5654 }
int autovacuum_max_workers
Definition: autovacuum.c:116
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 5946 of file postmaster.c.

5947 {
5948 #define MAX_BGWORKERS_TO_LAUNCH 100
5949  int num_launched = 0;
5950  TimestampTz now = 0;
5951  slist_mutable_iter iter;
5952 
5953  /*
5954  * During crash recovery, we have no need to be called until the state
5955  * transition out of recovery.
5956  */
5957  if (FatalError)
5958  {
5959  StartWorkerNeeded = false;
5960  HaveCrashedWorker = false;
5961  return;
5962  }
5963 
5964  /* Don't need to be called again unless we find a reason for it below */
5965  StartWorkerNeeded = false;
5966  HaveCrashedWorker = false;
5967 
5969  {
5970  RegisteredBgWorker *rw;
5971 
5972  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5973 
5974  /* ignore if already running */
5975  if (rw->rw_pid != 0)
5976  continue;
5977 
5978  /* if marked for death, clean up and remove from list */
5979  if (rw->rw_terminate)
5980  {
5981  ForgetBackgroundWorker(&iter);
5982  continue;
5983  }
5984 
5985  /*
5986  * If this worker has crashed previously, maybe it needs to be
5987  * restarted (unless on registration it specified it doesn't want to
5988  * be restarted at all). Check how long ago did a crash last happen.
5989  * If the last crash is too recent, don't start it right away; let it
5990  * be restarted once enough time has passed.
5991  */
5992  if (rw->rw_crashed_at != 0)
5993  {
5995  {
5996  int notify_pid;
5997 
5998  notify_pid = rw->rw_worker.bgw_notify_pid;
5999 
6000  ForgetBackgroundWorker(&iter);
6001 
6002  /* Report worker is gone now. */
6003  if (notify_pid != 0)
6004  kill(notify_pid, SIGUSR1);
6005 
6006  continue;
6007  }
6008 
6009  /* read system time only when needed */
6010  if (now == 0)
6012 
6014  rw->rw_worker.bgw_restart_time * 1000))
6015  {
6016  /* Set flag to remember that we have workers to start later */
6017  HaveCrashedWorker = true;
6018  continue;
6019  }
6020  }
6021 
6023  {
6024  /* reset crash time before trying to start worker */
6025  rw->rw_crashed_at = 0;
6026 
6027  /*
6028  * Try to start the worker.
6029  *
6030  * On failure, give up processing workers for now, but set
6031  * StartWorkerNeeded so we'll come back here on the next iteration
6032  * of ServerLoop to try again. (We don't want to wait, because
6033  * there might be additional ready-to-run workers.) We could set
6034  * HaveCrashedWorker as well, since this worker is now marked
6035  * crashed, but there's no need because the next run of this
6036  * function will do that.
6037  */
6038  if (!do_start_bgworker(rw))
6039  {
6040  StartWorkerNeeded = true;
6041  return;
6042  }
6043 
6044  /*
6045  * If we've launched as many workers as allowed, quit, but have
6046  * ServerLoop call us again to look for additional ready-to-run
6047  * workers. There might not be any, but we'll find out the next
6048  * time we run.
6049  */
6050  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
6051  {
6052  StartWorkerNeeded = true;
6053  return;
6054  }
6055  }
6056  }
6057 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1705
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5748
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5840
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:464
#define SIGUSR1
Definition: win32_port.h:179

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(), reaper(), ServerLoop(), and sigusr1_handler().

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5587 of file postmaster.c.

5588 {
5589  if (WalReceiverPID == 0 &&
5590  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5591  pmState == PM_HOT_STANDBY) &&
5593  {
5595  if (WalReceiverPID != 0)
5596  WalReceiverRequested = false;
5597  /* else leave the flag set, so we'll try again later */
5598  }
5599 }
#define SmartShutdown
Definition: postmaster.c:273
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:370
#define StartWalReceiver()
Definition: postmaster.c:552

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

Referenced by ServerLoop(), and sigusr1_handler().

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2827 of file postmaster.c.

2828 {
2829  int save_errno = errno;
2830 
2831  /*
2832  * We rely on the signal mechanism to have blocked all signals ... except
2833  * on Windows, which lacks sigaction(), so we have to do it manually.
2834  */
2835 #ifdef WIN32
2836  PG_SETMASK(&BlockSig);
2837 #endif
2838 
2839  ereport(DEBUG2,
2840  (errmsg_internal("postmaster received signal %d",
2841  postgres_signal_arg)));
2842 
2843  switch (postgres_signal_arg)
2844  {
2845  case SIGTERM:
2846 
2847  /*
2848  * Smart Shutdown:
2849  *
2850  * Wait for children to end their work, then shut down.
2851  */
2852  if (Shutdown >= SmartShutdown)
2853  break;
2855  ereport(LOG,
2856  (errmsg("received smart shutdown request")));
2857 
2858  /* Report status */
2860 #ifdef USE_SYSTEMD
2861  sd_notify(0, "STOPPING=1");
2862 #endif
2863 
2864  /*
2865  * If we reached normal running, we go straight to waiting for
2866  * client backends to exit. If already in PM_STOP_BACKENDS or a
2867  * later state, do not change it.
2868  */
2869  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2870  connsAllowed = false;
2871  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2872  {
2873  /* There should be no clients, so proceed to stop children */
2875  }
2876 
2877  /*
2878  * Now wait for online backup mode to end and backends to exit. If
2879  * that is already the case, PostmasterStateMachine will take the
2880  * next step.
2881  */
2883  break;
2884 
2885  case SIGINT:
2886 
2887  /*
2888  * Fast Shutdown:
2889  *
2890  * Abort all children with SIGTERM (rollback active transactions
2891  * and exit) and shut down when they are gone.
2892  */
2893  if (Shutdown >= FastShutdown)
2894  break;
2896  ereport(LOG,
2897  (errmsg("received fast shutdown request")));
2898 
2899  /* Report status */
2901 #ifdef USE_SYSTEMD
2902  sd_notify(0, "STOPPING=1");
2903 #endif
2904 
2905  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2906  {
2907  /* Just shut down background processes silently */
2909  }
2910  else if (pmState == PM_RUN ||
2912  {
2913  /* Report that we're about to zap live client sessions */
2914  ereport(LOG,
2915  (errmsg("aborting any active transactions")));
2917  }
2918 
2919  /*
2920  * PostmasterStateMachine will issue any necessary signals, or
2921  * take the next step if no child processes need to be killed.
2922  */
2924  break;
2925 
2926  case SIGQUIT:
2927 
2928  /*
2929  * Immediate Shutdown:
2930  *
2931  * abort all children with SIGQUIT, wait for them to exit,
2932  * terminate remaining ones with SIGKILL, then exit without
2933  * attempt to properly shut down the data base system.
2934  */
2935  if (Shutdown >= ImmediateShutdown)
2936  break;
2938  ereport(LOG,
2939  (errmsg("received immediate shutdown request")));
2940 
2941  /* Report status */
2943 #ifdef USE_SYSTEMD
2944  sd_notify(0, "STOPPING=1");
2945 #endif
2946 
2947  /* tell children to shut down ASAP */
2951 
2952  /* set stopwatch for them to die */
2953  AbortStartTime = time(NULL);
2954 
2955  /*
2956  * Now wait for backends to exit. If there are none,
2957  * PostmasterStateMachine will take the next step.
2958  */
2960  break;
2961  }
2962 
2963 #ifdef WIN32
2965 #endif
2966 
2967  errno = save_errno;
2968 }
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1350
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
static void PostmasterStateMachine(void)
Definition: postmaster.c:3779
static void TerminateChildren(int signal)
Definition: postmaster.c:4124
#define FastShutdown
Definition: postmaster.c:274

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

Referenced by PostmasterMain().

◆ PostmasterMain()

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

Definition at line 574 of file postmaster.c.

575 {
576  int opt;
577  int status;
578  char *userDoption = NULL;
579  bool listen_addr_saved = false;
580  int i;
581  char *output_config_variable = NULL;
582 
584 
586 
588 
589  /*
590  * Start our win32 signal implementation
591  */
592 #ifdef WIN32
594 #endif
595 
596  /*
597  * We should not be creating any files or directories before we check the
598  * data directory (see checkDataDir()), but just in case set the umask to
599  * the most restrictive (owner-only) permissions.
600  *
601  * checkDataDir() will reset the umask based on the data directory
602  * permissions.
603  */
604  umask(PG_MODE_MASK_OWNER);
605 
606  /*
607  * By default, palloc() requests in the postmaster will be allocated in
608  * the PostmasterContext, which is space that can be recycled by backends.
609  * Allocated data that needs to be available to backends should be
610  * allocated in TopMemoryContext.
611  */
613  "Postmaster",
616 
617  /* Initialize paths to installation files */
618  getInstallationPaths(argv[0]);
619 
620  /*
621  * Set up signal handlers for the postmaster process.
622  *
623  * In the postmaster, we use pqsignal_pm() rather than pqsignal() (which
624  * is used by all child processes and client processes). That has a
625  * couple of special behaviors:
626  *
627  * 1. Except on Windows, we tell sigaction() to block all signals for the
628  * duration of the signal handler. This is faster than our old approach
629  * of blocking/unblocking explicitly in the signal handler, and it should
630  * also prevent excessive stack consumption if signals arrive quickly.
631  *
632  * 2. We do not set the SA_RESTART flag. This is because signals will be
633  * blocked at all times except when ServerLoop is waiting for something to
634  * happen, and during that window, we want signals to exit the select(2)
635  * wait so that ServerLoop can respond if anything interesting happened.
636  * On some platforms, signals marked SA_RESTART would not cause the
637  * select() wait to end.
638  *
639  * Child processes will generally want SA_RESTART, so pqsignal() sets that
640  * flag. We expect children to set up their own handlers before
641  * unblocking signals.
642  *
643  * CAUTION: when changing this list, check for side-effects on the signal
644  * handling setup of child processes. See tcop/postgres.c,
645  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
646  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
647  * postmaster/bgworker.c and postmaster/checkpointer.c.
648  */
649  pqinitmask();
651 
652  pqsignal_pm(SIGHUP, SIGHUP_handler); /* reread config file and have
653  * children do same */
654  pqsignal_pm(SIGINT, pmdie); /* send SIGTERM and shut down */
655  pqsignal_pm(SIGQUIT, pmdie); /* send SIGQUIT and die */
656  pqsignal_pm(SIGTERM, pmdie); /* wait for children and shut down */
657  pqsignal_pm(SIGALRM, SIG_IGN); /* ignored */
658  pqsignal_pm(SIGPIPE, SIG_IGN); /* ignored */
659  pqsignal_pm(SIGUSR1, sigusr1_handler); /* message from child process */
660  pqsignal_pm(SIGUSR2, dummy_handler); /* unused, reserve for children */
661  pqsignal_pm(SIGCHLD, reaper); /* handle child termination */
662 
663 #ifdef SIGURG
664 
665  /*
666  * Ignore SIGURG for now. Child processes may change this (see
667  * InitializeLatchSupport), but they will not receive any such signals
668  * until they wait on a latch.
669  */
670  pqsignal_pm(SIGURG, SIG_IGN); /* ignored */
671 #endif
672 
673  /*
674  * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
675  * ignore those signals in a postmaster environment, so that there is no
676  * risk of a child process freezing up due to writing to stderr. But for
677  * a standalone backend, their default handling is reasonable. Hence, all
678  * child processes should just allow the inherited settings to stand.
679  */
680 #ifdef SIGTTIN
681  pqsignal_pm(SIGTTIN, SIG_IGN); /* ignored */
682 #endif
683 #ifdef SIGTTOU
684  pqsignal_pm(SIGTTOU, SIG_IGN); /* ignored */
685 #endif
686 
687  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
688 #ifdef SIGXFSZ
689  pqsignal_pm(SIGXFSZ, SIG_IGN); /* ignored */
690 #endif
691 
692  /*
693  * Options setup
694  */
696 
697  opterr = 1;
698 
699  /*
700  * Parse command-line options. CAUTION: keep this in sync with
701  * tcop/postgres.c (the option sets should not conflict) and with the
702  * common help() function in main/main.c.
703  */
704  while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:W:-:")) != -1)
705  {
706  switch (opt)
707  {
708  case 'B':
709  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
710  break;
711 
712  case 'b':
713  /* Undocumented flag used for binary upgrades */
714  IsBinaryUpgrade = true;
715  break;
716 
717  case 'C':
718  output_config_variable = strdup(optarg);
719  break;
720 
721  case 'D':
722  userDoption = strdup(optarg);
723  break;
724 
725  case 'd':
727  break;
728 
729  case 'E':
730  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
731  break;
732 
733  case 'e':
734  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
735  break;
736 
737  case 'F':
738  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
739  break;
740 
741  case 'f':
743  {
744  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
745  progname, optarg);
746  ExitPostmaster(1);
747  }
748  break;
749 
750  case 'h':
751  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
752  break;
753 
754  case 'i':
755  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
756  break;
757 
758  case 'j':
759  /* only used by interactive backend */
760  break;
761 
762  case 'k':
763  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
764  break;
765 
766  case 'l':
767  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
768  break;
769 
770  case 'N':
771  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
772  break;
773 
774  case 'n':
775  /* Don't reinit shared mem after abnormal exit */
776  Reinit = false;
777  break;
778 
779  case 'O':
780  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
781  break;
782 
783  case 'P':
784  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
785  break;
786 
787  case 'p':
789  break;
790 
791  case 'r':
792  /* only used by single-user backend */
793  break;
794 
795  case 'S':
797  break;
798 
799  case 's':
800  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
801  break;
802 
803  case 'T':
804 
805  /*
806  * In the event that some backend dumps core, send SIGSTOP,
807  * rather than SIGQUIT, to all its peers. This lets the wily
808  * post_hacker collect core dumps from everyone.
809  */
810  SendStop = true;
811  break;
812 
813  case 't':
814  {
815  const char *tmp = get_stats_option_name(optarg);
816 
817  if (tmp)
818  {
820  }
821  else
822  {
823  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
824  progname, optarg);
825  ExitPostmaster(1);
826  }
827  break;
828  }
829 
830  case 'W':
831  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
832  break;
833 
834  case 'c':
835  case '-':
836  {
837  char *name,
838  *value;
839 
841  if (!value)
842  {
843  if (opt == '-')
844  ereport(ERROR,
845  (errcode(ERRCODE_SYNTAX_ERROR),
846  errmsg("--%s requires a value",
847  optarg)));
848  else
849  ereport(ERROR,
850  (errcode(ERRCODE_SYNTAX_ERROR),
851  errmsg("-c %s requires a value",
852  optarg)));
853  }
854 
856  free(name);
857  free(value);
858  break;
859  }
860 
861  default:
862  write_stderr("Try \"%s --help\" for more information.\n",
863  progname);
864  ExitPostmaster(1);
865  }
866  }
867 
868  /*
869  * Postmaster accepts no non-option switch arguments.
870  */
871  if (optind < argc)
872  {
873  write_stderr("%s: invalid argument: \"%s\"\n",
874  progname, argv[optind]);
875  write_stderr("Try \"%s --help\" for more information.\n",
876  progname);
877  ExitPostmaster(1);
878  }
879 
880  /*
881  * Locate the proper configuration files and data directory, and read
882  * postgresql.conf for the first time.
883  */
885  ExitPostmaster(2);
886 
887  if (output_config_variable != NULL)
888  {
889  /*
890  * If this is a runtime-computed GUC, it hasn't yet been initialized,
891  * and the present value is not useful. However, this is a convenient
892  * place to print the value for most GUCs because it is safe to run
893  * postmaster startup to this point even if the server is already
894  * running. For the handful of runtime-computed GUCs that we cannot
895  * provide meaningful values for yet, we wait until later in
896  * postmaster startup to print the value. We won't be able to use -C
897  * on running servers for those GUCs, but using this option now would
898  * lead to incorrect results for them.
899  */
900  int flags = GetConfigOptionFlags(output_config_variable, true);
901 
902  if ((flags & GUC_RUNTIME_COMPUTED) == 0)
903  {
904  /*
905  * "-C guc" was specified, so print GUC's value and exit. No
906  * extra permission check is needed because the user is reading
907  * inside the data dir.
908  */
909  const char *config_val = GetConfigOption(output_config_variable,
910  false, false);
911 
912  puts(config_val ? config_val : "");
913  ExitPostmaster(0);
914  }
915 
916  /*
917  * A runtime-computed GUC will be printed later on. As we initialize
918  * a server startup sequence, silence any log messages that may show
919  * up in the output generated. FATAL and more severe messages are
920  * useful to show, even if one would only expect at least PANIC. LOG
921  * entries are hidden.
922  */
923  SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
925  }
926 
927  /* Verify that DataDir looks reasonable */
928  checkDataDir();
929 
930  /* Check that pg_control exists */
932 
933  /* And switch working directory into it */
934  ChangeToDataDir();
935 
936  /*
937  * Check for invalid combinations of GUC settings.
938  */
940  {
941  write_stderr("%s: superuser_reserved_connections (%d) must be less than max_connections (%d)\n",
942  progname,
944  ExitPostmaster(1);
945  }
947  ereport(ERROR,
948  (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
950  ereport(ERROR,
951  (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
952 
953  /*
954  * Other one-time internal sanity checks can go here, if they are fast.
955  * (Put any slow processing further down, after postmaster.pid creation.)
956  */
957  if (!CheckDateTokenTables())
958  {
959  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
960  ExitPostmaster(1);
961  }
962 
963  /*
964  * Now that we are done processing the postmaster arguments, reset
965  * getopt(3) library so that it will work correctly in subprocesses.
966  */
967  optind = 1;
968 #ifdef HAVE_INT_OPTRESET
969  optreset = 1; /* some systems need this too */
970 #endif
971 
972  /* For debugging: display postmaster environment */
973  {
974  extern char **environ;
975  char **p;
976 
977  ereport(DEBUG3,
978  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
979  progname)));
980  ereport(DEBUG3,
981  (errmsg_internal("-----------------------------------------")));
982  for (p = environ; *p; ++p)
983  ereport(DEBUG3,
984  (errmsg_internal("\t%s", *p)));
985  ereport(DEBUG3,
986  (errmsg_internal("-----------------------------------------")));
987  }
988 
989  /*
990  * Create lockfile for data directory.
991  *
992  * We want to do this before we try to grab the input sockets, because the
993  * data directory interlock is more reliable than the socket-file
994  * interlock (thanks to whoever decided to put socket files in /tmp :-().
995  * For the same reason, it's best to grab the TCP socket(s) before the
996  * Unix socket(s).
997  *
998  * Also note that this internally sets up the on_proc_exit function that
999  * is responsible for removing both data directory and socket lockfiles;
1000  * so it must happen before opening sockets so that at exit, the socket
1001  * lockfiles go away after CloseServerPorts runs.
1002  */
1003  CreateDataDirLockFile(true);
1004 
1005  /*
1006  * Read the control file (for error checking and config info).
1007  *
1008  * Since we verify the control file's CRC, this has a useful side effect
1009  * on machines where we need a run-time test for CRC support instructions.
1010  * The postmaster will do the test once at startup, and then its child
1011  * processes will inherit the correct function pointer and not need to
1012  * repeat the test.
1013  */
1014  LocalProcessControlFile(false);
1015 
1016  /*
1017  * Register the apply launcher. It's probably a good idea to call this
1018  * before any modules had a chance to take the background worker slots.
1019  */
1021 
1022  /*
1023  * process any libraries that should be preloaded at postmaster start
1024  */
1026 
1027  /*
1028  * Initialize SSL library, if specified.
1029  */
1030 #ifdef USE_SSL
1031  if (EnableSSL)
1032  {
1033  (void) secure_initialize(true);
1034  LoadedSSL = true;
1035  }
1036 #endif
1037 
1038  /*
1039  * Now that loadable modules have had their chance to alter any GUCs,
1040  * calculate MaxBackends.
1041  */
1043 
1044  /*
1045  * Give preloaded libraries a chance to request additional shared memory.
1046  */
1048 
1049  /*
1050  * Now that loadable modules have had their chance to request additional
1051  * shared memory, determine the value of any runtime-computed GUCs that
1052  * depend on the amount of shared memory required.
1053  */
1055 
1056  /*
1057  * Now that modules have been loaded, we can process any custom resource
1058  * managers specified in the wal_consistency_checking GUC.
1059  */
1061 
1062  /*
1063  * If -C was specified with a runtime-computed GUC, we held off printing
1064  * the value earlier, as the GUC was not yet initialized. We handle -C
1065  * for most GUCs before we lock the data directory so that the option may
1066  * be used on a running server. However, a handful of GUCs are runtime-
1067  * computed and do not have meaningful values until after locking the data
1068  * directory, and we cannot safely calculate their values earlier on a
1069  * running server. At this point, such GUCs should be properly
1070  * initialized, and we haven't yet set up shared memory, so this is a good
1071  * time to handle the -C option for these special GUCs.
1072  */
1073  if (output_config_variable != NULL)
1074  {
1075  const char *config_val = GetConfigOption(output_config_variable,
1076  false, false);
1077 
1078  puts(config_val ? config_val : "");
1079  ExitPostmaster(0);
1080  }
1081 
1082  /*
1083  * Set up shared memory and semaphores.
1084  */
1085  reset_shared();
1086 
1087  /*
1088  * Estimate number of openable files. This must happen after setting up
1089  * semaphores, because on some platforms semaphores count as open files.
1090  */
1091  set_max_safe_fds();
1092 
1093  /*
1094  * Set reference point for stack-depth checking.
1095  */
1096  (void) set_stack_base();
1097 
1098  /*
1099  * Initialize pipe (or process handle on Windows) that allows children to
1100  * wake up from sleep on postmaster death.
1101  */
1103 
1104 #ifdef WIN32
1105 
1106  /*
1107  * Initialize I/O completion port used to deliver list of dead children.
1108  */
1109  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1110  if (win32ChildQueue == NULL)
1111  ereport(FATAL,
1112  (errmsg("could not create I/O completion port for child queue")));
1113 #endif
1114 
1115 #ifdef EXEC_BACKEND
1116  /* Write out nondefault GUC settings for child processes to use */
1117  write_nondefault_variables(PGC_POSTMASTER);
1118 
1119  /*
1120  * Clean out the temp directory used to transmit parameters to child
1121  * processes (see internal_forkexec, below). We must do this before
1122  * launching any child processes, else we have a race condition: we could
1123  * remove a parameter file before the child can read it. It should be
1124  * safe to do so now, because we verified earlier that there are no
1125  * conflicting Postgres processes in this data directory.
1126  */
1128 #endif
1129 
1130  /*
1131  * Forcibly remove the files signaling a standby promotion request.
1132  * Otherwise, the existence of those files triggers a promotion too early,
1133  * whether a user wants that or not.
1134  *
1135  * This removal of files is usually unnecessary because they can exist
1136  * only during a few moments during a standby promotion. However there is
1137  * a race condition: if pg_ctl promote is executed and creates the files
1138  * during a promotion, the files can stay around even after the server is
1139  * brought up to be the primary. Then, if a new standby starts by using
1140  * the backup taken from the new primary, the files can exist at server
1141  * startup and must be removed in order to avoid an unexpected promotion.
1142  *
1143  * Note that promotion signal files need to be removed before the startup
1144  * process is invoked. Because, after that, they can be used by
1145  * postmaster's SIGUSR1 signal handler.
1146  */
1148 
1149  /* Do the same for logrotate signal file */
1151 
1152  /* Remove any outdated file holding the current log filenames. */
1153  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1154  ereport(LOG,
1156  errmsg("could not remove file \"%s\": %m",
1158 
1159  /*
1160  * If enabled, start up syslogger collection subprocess
1161  */
1163 
1164  /*
1165  * Reset whereToSendOutput from DestDebug (its starting state) to
1166  * DestNone. This stops ereport from sending log messages to stderr unless
1167  * Log_destination permits. We don't do this until the postmaster is
1168  * fully launched, since startup failures may as well be reported to
1169  * stderr.
1170  *
1171  * If we are in fact disabling logging to stderr, first emit a log message
1172  * saying so, to provide a breadcrumb trail for users who may not remember
1173  * that their logging is configured to go somewhere else.
1174  */
1176  ereport(LOG,
1177  (errmsg("ending log output to stderr"),
1178  errhint("Future log output will go to log destination \"%s\".",
1180 
1182 
1183  /*
1184  * Report server startup in log. While we could emit this much earlier,
1185  * it seems best to do so after starting the log collector, if we intend
1186  * to use one.
1187  */
1188  ereport(LOG,
1189  (errmsg("starting %s", PG_VERSION_STR)));
1190 
1191  /*
1192  * Establish input sockets.
1193  *
1194  * First, mark them all closed, and set up an on_proc_exit function that's
1195  * charged with closing the sockets again at postmaster shutdown.
1196  */
1197  for (i = 0; i < MAXLISTEN; i++)
1199 
1201 
1202  if (ListenAddresses)
1203  {
1204  char *rawstring;
1205  List *elemlist;
1206  ListCell *l;
1207  int success = 0;
1208 
1209  /* Need a modifiable copy of ListenAddresses */
1210  rawstring = pstrdup(ListenAddresses);
1211 
1212  /* Parse string into list of hostnames */
1213  if (!SplitGUCList(rawstring, ',', &elemlist))
1214  {
1215  /* syntax error in list */
1216  ereport(FATAL,
1217  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1218  errmsg("invalid list syntax in parameter \"%s\"",
1219  "listen_addresses")));
1220  }
1221 
1222  foreach(l, elemlist)
1223  {
1224  char *curhost = (char *) lfirst(l);
1225 
1226  if (strcmp(curhost, "*") == 0)
1227  status = StreamServerPort(AF_UNSPEC, NULL,
1228  (unsigned short) PostPortNumber,
1229  NULL,
1231  else
1232  status = StreamServerPort(AF_UNSPEC, curhost,
1233  (unsigned short) PostPortNumber,
1234  NULL,
1236 
1237  if (status == STATUS_OK)
1238  {
1239  success++;
1240  /* record the first successful host addr in lockfile */
1241  if (!listen_addr_saved)
1242  {
1244  listen_addr_saved = true;
1245  }
1246  }
1247  else
1248  ereport(WARNING,
1249  (errmsg("could not create listen socket for \"%s\"",
1250  curhost)));
1251  }
1252 
1253  if (!success && elemlist != NIL)
1254  ereport(FATAL,
1255  (errmsg("could not create any TCP/IP sockets")));
1256 
1257  list_free(elemlist);
1258  pfree(rawstring);
1259  }
1260 
1261 #ifdef USE_BONJOUR
1262  /* Register for Bonjour only if we opened TCP socket(s) */
1264  {
1265  DNSServiceErrorType err;
1266 
1267  /*
1268  * We pass 0 for interface_index, which will result in registering on
1269  * all "applicable" interfaces. It's not entirely clear from the
1270  * DNS-SD docs whether this would be appropriate if we have bound to
1271  * just a subset of the available network interfaces.
1272  */
1273  err = DNSServiceRegister(&bonjour_sdref,
1274  0,
1275  0,
1276  bonjour_name,
1277  "_postgresql._tcp.",
1278  NULL,
1279  NULL,
1281  0,
1282  NULL,
1283  NULL,
1284  NULL);
1285  if (err != kDNSServiceErr_NoError)
1286  ereport(LOG,
1287  (errmsg("DNSServiceRegister() failed: error code %ld",
1288  (long) err)));
1289 
1290  /*
1291  * We don't bother to read the mDNS daemon's reply, and we expect that
1292  * it will automatically terminate our registration when the socket is
1293  * closed at postmaster termination. So there's nothing more to be
1294  * done here. However, the bonjour_sdref is kept around so that
1295  * forked children can close their copies of the socket.
1296  */
1297  }
1298 #endif
1299 
1300 #ifdef HAVE_UNIX_SOCKETS
1302  {
1303  char *rawstring;
1304  List *elemlist;
1305  ListCell *l;
1306  int success = 0;
1307 
1308  /* Need a modifiable copy of Unix_socket_directories */
1309  rawstring = pstrdup(Unix_socket_directories);
1310 
1311  /* Parse string into list of directories */
1312  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1313  {
1314  /* syntax error in list */
1315  ereport(FATAL,
1316  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1317  errmsg("invalid list syntax in parameter \"%s\"",
1318  "unix_socket_directories")));
1319  }
1320 
1321  foreach(l, elemlist)
1322  {
1323  char *socketdir = (char *) lfirst(l);
1324 
1325  status = StreamServerPort(AF_UNIX, NULL,
1326  (unsigned short) PostPortNumber,
1327  socketdir,
1329 
1330  if (status == STATUS_OK)
1331  {
1332  success++;
1333  /* record the first successful Unix socket in lockfile */
1334  if (success == 1)
1336  }
1337  else
1338  ereport(WARNING,
1339  (errmsg("could not create Unix-domain socket in directory \"%s\"",
1340  socketdir)));
1341  }
1342 
1343  if (!success && elemlist != NIL)
1344  ereport(FATAL,
1345  (errmsg("could not create any Unix-domain sockets")));
1346 
1347  list_free_deep(elemlist);
1348  pfree(rawstring);
1349  }
1350 #endif
1351 
1352  /*
1353  * check that we have some socket to listen on
1354  */
1355  if (ListenSocket[0] == PGINVALID_SOCKET)
1356  ereport(FATAL,
1357  (errmsg("no socket created for listening")));
1358 
1359  /*
1360  * If no valid TCP ports, write an empty line for listen address,
1361  * indicating the Unix socket must be used. Note that this line is not
1362  * added to the lock file until there is a socket backing it.
1363  */
1364  if (!listen_addr_saved)
1366 
1367  /*
1368  * Record postmaster options. We delay this till now to avoid recording
1369  * bogus options (eg, unusable port number).
1370  */
1371  if (!CreateOptsFile(argc, argv, my_exec_path))
1372  ExitPostmaster(1);
1373 
1374  /*
1375  * Write the external PID file if requested
1376  */
1377  if (external_pid_file)
1378  {
1379  FILE *fpidfile = fopen(external_pid_file, "w");
1380 
1381  if (fpidfile)
1382  {
1383  fprintf(fpidfile, "%d\n", MyProcPid);
1384  fclose(fpidfile);
1385 
1386  /* Make PID file world readable */
1387  if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1388  write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1390  }
1391  else
1392  write_stderr("%s: could not write external PID file \"%s\": %s\n",
1394 
1396  }
1397 
1398  /*
1399  * Remove old temporary files. At this point there can be no other
1400  * Postgres processes running in this directory, so this should be safe.
1401  */
1403 
1404  /*
1405  * Initialize the autovacuum subsystem (again, no process start yet)
1406  */
1407  autovac_init();
1408 
1409  /*
1410  * Load configuration files for client authentication.
1411  */
1412  if (!load_hba())
1413  {
1414  /*
1415  * It makes no sense to continue if we fail to load the HBA file,
1416  * since there is no way to connect to the database in this case.
1417  */
1418  ereport(FATAL,
1419  (errmsg("could not load pg_hba.conf")));
1420  }
1421  if (!load_ident())
1422  {
1423  /*
1424  * We can start up without the IDENT file, although it means that you
1425  * cannot log in using any of the authentication methods that need a
1426  * user name mapping. load_ident() already logged the details of error
1427  * to the log.
1428  */
1429  }
1430 
1431 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1432 
1433  /*
1434  * On macOS, libintl replaces setlocale() with a version that calls
1435  * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1436  * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1437  * the process multithreaded. The postmaster calls sigprocmask() and
1438  * calls fork() without an immediate exec(), both of which have undefined
1439  * behavior in a multithreaded program. A multithreaded postmaster is the
1440  * normal case on Windows, which offers neither fork() nor sigprocmask().
1441  */
1442  if (pthread_is_threaded_np() != 0)
1443  ereport(FATAL,
1444  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1445  errmsg("postmaster became multithreaded during startup"),
1446  errhint("Set the LC_ALL environment variable to a valid locale.")));
1447 #endif
1448 
1449  /*
1450  * Remember postmaster startup time
1451  */
1453 
1454  /*
1455  * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1456  * see what's happening.
1457  */
1459 
1460  /* Start bgwriter and checkpointer so they can help with recovery */
1461  if (CheckpointerPID == 0)
1463  if (BgWriterPID == 0)
1465 
1466  /*
1467  * We're ready to rock and roll...
1468  */
1470  Assert(StartupPID != 0);
1472  pmState = PM_STARTUP;
1473 
1474  /* Some workers may be scheduled to start now */
1476 
1477  status = ServerLoop();
1478 
1479  /*
1480  * ServerLoop probably shouldn't ever return, but if it does, close down.
1481  */
1483 
1484  abort(); /* not reached */
1485 }
void autovac_init(void)
Definition: autovacuum.c:3289
void pqinitmask(void)
Definition: pqsignal.c:41
pqsigfunc pqsignal_pm(int signo, pqsigfunc func)
Definition: pqsignal.c:120
bool CheckDateTokenTables(void)
Definition: datetime.c:4727
TimestampTz PgStartTime
Definition: timestamp.c:53
int secure_initialize(bool isServerStart)
Definition: be-secure.c:78
@ DestNone
Definition: dest.h:89
int Log_destination
Definition: elog.c:111
char * Log_destination_string
Definition: elog.c:112
#define DEBUG3
Definition: elog.h:22
#define LOG_DESTINATION_STDERR
Definition: elog.h:421
const char * name
Definition: encode.c:561
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3149
void RemovePgTempFiles(void)
Definition: fd.c:3090
void set_max_safe_fds(void)
Definition: fd.c:965
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
bool IsBinaryUpgrade
Definition: globals.c:114
bool IsPostmasterEnvironment
Definition: globals.c:112
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8373
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:6096
void InitializeWalConsistencyChecking(void)
Definition: guc.c:5888
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:11333
void InitializeGUCOptions(void)
Definition: guc.c:5835
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:8397
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:8492
char * external_pid_file
Definition: guc.c:657
#define GUC_RUNTIME_COMPUTED
Definition: guc.h:239
@ PGC_S_OVERRIDE
Definition: guc.h:120
@ PGC_S_ARGV
Definition: guc.h:114
@ PGC_SUSET
Definition: guc.h:75
@ PGC_POSTMASTER
Definition: guc.h:71
bool load_ident(void)
Definition: hba.c:2586
bool load_hba(void)
Definition: hba.c:2207
static struct @151 value
static bool success
Definition: initdb.c:169
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void InitializeShmemGUCs(void)
Definition: ipci.c:324
void ApplyLauncherRegister(void)
Definition: launcher.c:706
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:1305
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
void ChangeToDataDir(void)
Definition: miscinit.c:431
void process_shmem_requests(void)
Definition: miscinit.c:1710
void process_shared_preload_libraries(void)
Definition: miscinit.c:1682
void checkDataDir(void)
Definition: miscinit.c:318
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1294
#define pg_hton16(x)
Definition: pg_bswap.h:120
#define PG_TEMP_FILES_DIR
Definition: pg_checksums.c:62
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT int opterr
Definition: getopt.c:49
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define lfirst(lc)
Definition: pg_list.h:170
#define NIL
Definition: pg_list.h:66
#define PM_STATUS_STARTING
Definition: pidfile.h:51
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: pidfile.h:42
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: pidfile.h:41
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3598
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3627
static const char * userDoption
Definition: postgres.c:170
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3669
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3440
void InitializeMaxBackends(void)
Definition: postinit.c:551
static void maybe_start_bgworkers(void)
Definition: postmaster.c:5946
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1492
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:6541
static void pmdie(SIGNAL_ARGS)
Definition: postmaster.c:2827
void InitProcessGlobals(void)
Definition: postmaster.c:2687
static void reset_shared(void)
Definition: postmaster.c:2730
static int ServerLoop(void)
Definition: postmaster.c:1721
int PostPortNumber
Definition: postmaster.c:202
static void checkControlFile(void)
Definition: postmaster.c:1594
#define StartupDataBase()
Definition: postmaster.c:547
bool enable_bonjour
Definition: postmaster.c:245
char * Unix_socket_directories
Definition: postmaster.c:205
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:5606
static void sigusr1_handler(SIGNAL_ARGS)
Definition: postmaster.c:5126
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1540
static bool Reinit
Definition: postmaster.c:232
#define StartCheckpointer()
Definition: postmaster.c:550
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1528
#define StartBackgroundWriter()
Definition: postmaster.c:549
static void reaper(SIGNAL_ARGS)
Definition: postmaster.c:2974
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:5314
bool EnableSSL
Definition: postmaster.c:236
char * ListenAddresses
Definition: postmaster.c:208
char * bonjour_name
Definition: postmaster.c:246
static void SIGHUP_handler(SIGNAL_ARGS)
Definition: postmaster.c:2747
int ReservedBackends
Definition: postmaster.c:219
static pid_t SysLoggerPID
Definition: postmaster.c:258
int StreamServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
Definition: pqcomm.c:318
char ** environ
void pgwin32_signal_initialize(void)
Definition: signal.c:79
Definition: pg_list.h:52
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:3842
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3963
#define S_IROTH
Definition: win32_port.h:312
#define SIGCHLD
Definition: win32_port.h:177
#define SIGHUP
Definition: win32_port.h:167
#define S_IRGRP
Definition: win32_port.h:300
#define SIGPIPE
Definition: win32_port.h:172
#define S_IRUSR
Definition: win32_port.h:288
#define SIGALRM
Definition: win32_port.h:173
#define SIGUSR2
Definition: win32_port.h:180
#define SIG_IGN
Definition: win32_port.h:164
#define S_IWUSR
Definition: win32_port.h:291
int XLogArchiveMode
Definition: xlog.c:120
int wal_level
Definition: xlog.c:132
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4323
@ 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(), DEBUG3, DestNone, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, free, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, i, InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), 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_SETMASK, 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, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal_pm(), process_shared_preload_libraries(), process_shmem_requests(), progname, pstrdup(), reaper(), Reinit, RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedBackends, reset_shared(), S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), SendStop, ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGHUP_handler(), SIGPIPE, SIGQUIT, SIGUSR1, sigusr1_handler(), SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartBackgroundWriter, StartCheckpointer, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror, success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, 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 6065 of file postmaster.c.

6066 {
6067  dlist_iter iter;
6068  Backend *bp;
6069 
6070  dlist_foreach(iter, &BackendList)
6071  {
6072  bp = dlist_container(Backend, elem, iter.cur);
6073  if (bp->pid == pid)
6074  {
6075  bp->bgworker_notify = true;
6076  return true;
6077  }
6078  }
6079  return false;
6080 }

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

3780 {
3781  /* If we're doing a smart shutdown, try to advance that state. */
3782  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3783  {
3784  if (!connsAllowed)
3785  {
3786  /*
3787  * This state ends when we have no normal client backends running.
3788  * Then we're ready to stop other children.
3789  */
3792  }
3793  }
3794 
3795  /*
3796  * If we're ready to do so, signal child processes to shut down. (This
3797  * isn't a persistent state, but treating it as a distinct pmState allows
3798  * us to share this code across multiple shutdown code paths.)
3799  */
3800  if (pmState == PM_STOP_BACKENDS)
3801  {
3802  /*
3803  * Forget any pending requests for background workers, since we're no
3804  * longer willing to launch any new workers. (If additional requests
3805  * arrive, BackgroundWorkerStateChange will reject them.)
3806  */
3808 
3809  /* Signal all backend children except walsenders */
3810  SignalSomeChildren(SIGTERM,
3812  /* and the autovac launcher too */
3813  if (AutoVacPID != 0)
3814  signal_child(AutoVacPID, SIGTERM);
3815  /* and the bgwriter too */
3816  if (BgWriterPID != 0)
3817  signal_child(BgWriterPID, SIGTERM);
3818  /* and the walwriter too */
3819  if (WalWriterPID != 0)
3820  signal_child(WalWriterPID, SIGTERM);
3821  /* If we're in recovery, also stop startup and walreceiver procs */
3822  if (StartupPID != 0)
3823  signal_child(StartupPID, SIGTERM);
3824  if (WalReceiverPID != 0)
3825  signal_child(WalReceiverPID, SIGTERM);
3826  /* checkpointer, archiver, stats, and syslogger may continue for now */
3827 
3828  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3830  }
3831 
3832  /*
3833  * If we are in a state-machine state that implies waiting for backends to
3834  * exit, see if they're all gone, and change state if so.
3835  */
3836  if (pmState == PM_WAIT_BACKENDS)
3837  {
3838  /*
3839  * PM_WAIT_BACKENDS state ends when we have no regular backends
3840  * (including autovac workers), no bgworkers (including unconnected
3841  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3842  * doing crash recovery or an immediate shutdown then we expect the
3843  * checkpointer to exit as well, otherwise not. The stats and
3844  * syslogger processes are disregarded since they are not connected to
3845  * shared memory; we also disregard dead_end children here. Walsenders
3846  * and archiver are also disregarded, they will be terminated later
3847  * after writing the checkpoint record.
3848  */
3850  StartupPID == 0 &&
3851  WalReceiverPID == 0 &&
3852  BgWriterPID == 0 &&
3853  (CheckpointerPID == 0 ||
3855  WalWriterPID == 0 &&
3856  AutoVacPID == 0)
3857  {
3859  {
3860  /*
3861  * Start waiting for dead_end children to die. This state
3862  * change causes ServerLoop to stop creating new ones.
3863  */
3865 
3866  /*
3867  * We already SIGQUIT'd the archiver and stats processes, if
3868  * any, when we started immediate shutdown or entered
3869  * FatalError state.
3870  */
3871  }
3872  else
3873  {
3874  /*
3875  * If we get here, we are proceeding with normal shutdown. All
3876  * the regular children are gone, and it's time to tell the
3877  * checkpointer to do a shutdown checkpoint.
3878  */
3880  /* Start the checkpointer if not running */
3881  if (CheckpointerPID == 0)
3883  /* And tell it to shut down */
3884  if (CheckpointerPID != 0)
3885  {
3887  pmState = PM_SHUTDOWN;
3888  }
3889  else
3890  {
3891  /*
3892  * If we failed to fork a checkpointer, just shut down.
3893  * Any required cleanup will happen at next restart. We
3894  * set FatalError so that an "abnormal shutdown" message
3895  * gets logged when we exit.
3896  */
3897  FatalError = true;
3899 
3900  /* Kill the walsenders and archiver too */
3902  if (PgArchPID != 0)
3904  }
3905  }
3906  }
3907  }
3908 
3909  if (pmState == PM_SHUTDOWN_2)
3910  {
3911  /*
3912  * PM_SHUTDOWN_2 state ends when there's no other children than
3913  * dead_end children left. There shouldn't be any regular backends
3914  * left by now anyway; what we're really waiting for is walsenders and
3915  * archiver.
3916  */
3917  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3918  {
3920  }
3921  }
3922 
3923  if (pmState == PM_WAIT_DEAD_END)
3924  {
3925  /*
3926  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3927  * (ie, no dead_end children remain), and the archiver is gone too.
3928  *
3929  * The reason we wait for those two is to protect them against a new
3930  * postmaster starting conflicting subprocesses; this isn't an
3931  * ironclad protection, but it at least helps in the
3932  * shutdown-and-immediately-restart scenario. Note that they have
3933  * already been sent appropriate shutdown signals, either during a
3934  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3935  * FatalError processing.
3936  */
3937  if (dlist_is_empty(&BackendList) && PgArchPID == 0)
3938  {
3939  /* These other guys should be dead already */
3940  Assert(StartupPID == 0);
3941  Assert(WalReceiverPID == 0);
3942  Assert(BgWriterPID == 0);
3943  Assert(CheckpointerPID == 0);
3944  Assert(WalWriterPID == 0);
3945  Assert(AutoVacPID == 0);
3946  /* syslogger is not considered here */
3948  }
3949  }
3950 
3951  /*
3952  * If we've been told to shut down, we exit as soon as there are no
3953  * remaining children. If there was a crash, cleanup will occur at the
3954  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3955  * crash before exiting, but that seems unwise if we are quitting because
3956  * we got SIGTERM from init --- there may well not be time for recovery
3957  * before init decides to SIGKILL us.)
3958  *
3959  * Note that the syslogger continues to run. It will exit when it sees
3960  * EOF on its input pipe, which happens when there are no more upstream
3961  * processes.
3962  */
3964  {
3965  if (FatalError)
3966  {
3967  ereport(LOG, (errmsg("abnormal database system shutdown")));
3968  ExitPostmaster(1);
3969  }
3970  else
3971  {
3972  /*
3973  * Normal exit from the postmaster is here. We don't need to log
3974  * anything here, since the UnlinkLockFiles proc_exit callback
3975  * will do so, and that should be the last user-visible action.
3976  */
3977  ExitPostmaster(0);
3978  }
3979  }
3980 
3981  /*
3982  * If the startup process failed, or the user does not want an automatic
3983  * restart after backend crashes, wait for all non-syslogger children to
3984  * exit, and then exit postmaster. We don't try to reinitialize when the
3985  * startup process fails, because more than likely it will just fail again
3986  * and we will keep trying forever.
3987  */
3988  if (pmState == PM_NO_CHILDREN)
3989  {
3991  {
3992  ereport(LOG,
3993  (errmsg("shutting down due to startup process failure")));
3994  ExitPostmaster(1);
3995  }
3996  if (!restart_after_crash)
3997  {
3998  ereport(LOG,
3999  (errmsg("shutting down because restart_after_crash is off")));
4000  ExitPostmaster(1);
4001  }
4002  }
4003 
4004  /*
4005  * If we need to recover from a crash, wait for all non-syslogger children
4006  * to exit, then reset shmem and StartupDataBase.
4007  */
4008  if (FatalError && pmState == PM_NO_CHILDREN)
4009  {
4010  ereport(LOG,
4011  (errmsg("all server processes terminated; reinitializing")));
4012 
4013  /* remove leftover temporary files after a crash */
4016 
4017  /* allow background workers to immediately restart */
4019 
4020  shmem_exit(1);
4021 
4022  /* re-read control file into local memory */
4024 
4025  reset_shared();
4026 
4028  Assert(StartupPID != 0);
4030  pmState = PM_STARTUP;
4031  /* crash recovery started, reset SIGKILL flag */
4032  AbortStartTime = 0;
4033  }
4034 }
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:579
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:541
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
void shmem_exit(int code)
Definition: ipc.c:224
bool remove_temp_files_after_crash
Definition: postmaster.c:248
bool restart_after_crash
Definition: postmaster.c:247
#define SignalChildren(sig)
Definition: postmaster.c:424
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4080

References AbortStartTime, Assert(), AutoVacPID, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, BgWriterPID, CheckpointerPID, connsAllowed, CountChildren(), 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(), reset_shared(), 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 pmdie(), reaper(), and sigusr1_handler().

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5299 of file postmaster.c.

5300 {
5301  _exit(1);
5302 }

Referenced by BackendInitialize().

◆ processCancelRequest()

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

Definition at line 2453 of file postmaster.c.

2454 {
2455  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2456  int backendPID;
2457  int32 cancelAuthCode;
2458  Backend *bp;
2459 
2460 #ifndef EXEC_BACKEND
2461  dlist_iter iter;
2462 #else
2463  int i;
2464 #endif
2465 
2466  backendPID = (int) pg_ntoh32(canc->backendPID);
2467  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2468 
2469  /*
2470  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2471  * longer access the postmaster's own backend list, and must rely on the
2472  * duplicate array in shared memory.
2473  */
2474 #ifndef EXEC_BACKEND
2475  dlist_foreach(iter, &BackendList)
2476  {
2477  bp = dlist_container(Backend, elem, iter.cur);
2478 #else
2479  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2480  {
2481  bp = (Backend *) &ShmemBackendArray[i];
2482 #endif
2483  if (bp->pid == backendPID)
2484  {
2485  if (bp->cancel_key == cancelAuthCode)
2486  {
2487  /* Found a match; signal that backend to cancel current op */
2488  ereport(DEBUG2,
2489  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2490  backendPID)));
2491  signal_child(bp->pid, SIGINT);
2492  }
2493  else
2494  /* Right PID, wrong key: no way, Jose */
2495  ereport(LOG,
2496  (errmsg("wrong key in cancel request for process %d",
2497  backendPID)));
2498  return;
2499  }
2500 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2501  }
2502 #else
2503  }
2504 #endif
2505 
2506  /* No matching backend */
2507  ereport(LOG,
2508  (errmsg("PID %d in cancel request did not match any process",
2509  backendPID)));
2510 }
signed int int32
Definition: c.h:440
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
uint32 backendPID
Definition: pqcomm.h:182
uint32 cancelAuthCode
Definition: pqcomm.h:183

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

2001 {
2002  int32 len;
2003  char *buf;
2004  ProtocolVersion proto;
2005  MemoryContext oldcontext;
2006 
2007  pq_startmsgread();
2008 
2009  /*
2010  * Grab the first byte of the length word separately, so that we can tell
2011  * whether we have no data at all or an incomplete packet. (This might
2012  * sound inefficient, but it's not really, because of buffering in
2013  * pqcomm.c.)
2014  */
2015  if (pq_getbytes((char *) &len, 1) == EOF)
2016  {
2017  /*
2018  * If we get no data at all, don't clutter the log with a complaint;
2019  * such cases often occur for legitimate reasons. An example is that
2020  * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
2021  * client didn't like our response, it'll probably just drop the
2022  * connection. Service-monitoring software also often just opens and
2023  * closes a connection without sending anything. (So do port
2024  * scanners, which may be less benign, but it's not really our job to
2025  * notice those.)
2026  */
2027  return STATUS_ERROR;
2028  }
2029 
2030  if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
2031  {
2032  /* Got a partial length word, so bleat about that */
2033  if (!ssl_done && !gss_done)
2035  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2036  errmsg("incomplete startup packet")));
2037  return STATUS_ERROR;
2038  }
2039 
2040  len = pg_ntoh32(len);
2041  len -= 4;
2042 
2043  if (len < (int32) sizeof(ProtocolVersion) ||
2045  {
2047  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2048  errmsg("invalid length of startup packet")));
2049  return STATUS_ERROR;
2050  }
2051 
2052  /*
2053  * Allocate space to hold the startup packet, plus one extra byte that's
2054  * initialized to be zero. This ensures we will have null termination of
2055  * all strings inside the packet.
2056  */
2057  buf = palloc(len + 1);
2058  buf[len] = '\0';
2059 
2060  if (pq_getbytes(buf, len) == EOF)
2061  {
2063  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2064  errmsg("incomplete startup packet")));
2065  return STATUS_ERROR;
2066  }
2067  pq_endmsgread();
2068 
2069  /*
2070  * The first field is either a protocol version number or a special
2071  * request code.
2072  */
2073  port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
2074 
2075  if (proto == CANCEL_REQUEST_CODE)
2076  {
2078  /* Not really an error, but we don't want to proceed further */
2079  return STATUS_ERROR;
2080  }
2081 
2082  if (proto == NEGOTIATE_SSL_CODE && !ssl_done)
2083  {
2084  char SSLok;
2085 
2086 #ifdef USE_SSL
2087  /* No SSL when disabled or on Unix sockets */
2088  if (!LoadedSSL || port->laddr.addr.ss_family == AF_UNIX)
2089  SSLok = 'N';
2090  else
2091  SSLok = 'S'; /* Support for SSL */
2092 #else
2093  SSLok = 'N'; /* No support for SSL */
2094 #endif
2095 
2096 retry1:
2097  if (send(port->sock, &SSLok, 1, 0) != 1)
2098  {
2099  if (errno == EINTR)
2100  goto retry1; /* if interrupted, just retry */
2103  errmsg("failed to send SSL negotiation response: %m")));
2104  return STATUS_ERROR; /* close the connection */
2105  }
2106 
2107 #ifdef USE_SSL
2108  if (SSLok == 'S' && secure_open_server(port) == -1)
2109  return STATUS_ERROR;
2110 #endif
2111 
2112  /*
2113  * At this point we should have no data already buffered. If we do,
2114  * it was received before we performed the SSL handshake, so it wasn't
2115  * encrypted and indeed may have been injected by a man-in-the-middle.
2116  * We report this case to the client.
2117  */
2118  if (pq_buffer_has_data())
2119  ereport(FATAL,
2120  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2121  errmsg("received unencrypted data after SSL request"),
2122  errdetail("This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.")));
2123 
2124  /*
2125  * regular startup packet, cancel, etc packet should follow, but not
2126  * another SSL negotiation request, and a GSS request should only
2127  * follow if SSL was rejected (client may negotiate in either order)
2128  */
2129  return ProcessStartupPacket(port, true, SSLok == 'S');
2130  }
2131  else if (proto == NEGOTIATE_GSS_CODE && !gss_done)
2132  {
2133  char GSSok = 'N';
2134 
2135 #ifdef ENABLE_GSS
2136  /* No GSSAPI encryption when on Unix socket */
2137  if (port->laddr.addr.ss_family != AF_UNIX)
2138  GSSok = 'G';
2139 #endif
2140 
2141  while (send(port->sock, &GSSok, 1, 0) != 1)
2142  {
2143  if (errno == EINTR)
2144  continue;
2147  errmsg("failed to send GSSAPI negotiation response: %m")));
2148  return STATUS_ERROR; /* close the connection */
2149  }
2150 
2151 #ifdef ENABLE_GSS
2152  if (GSSok == 'G' && secure_open_gssapi(port) == -1)
2153  return STATUS_ERROR;
2154 #endif
2155 
2156  /*
2157  * At this point we should have no data already buffered. If we do,
2158  * it was received before we performed the GSS handshake, so it wasn't
2159  * encrypted and indeed may have been injected by a man-in-the-middle.
2160  * We report this case to the client.
2161  */
2162  if (pq_buffer_has_data())
2163  ereport(FATAL,
2164  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2165  errmsg("received unencrypted data after GSSAPI encryption request"),
2166  errdetail("This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.")));
2167 
2168  /*
2169  * regular startup packet, cancel, etc packet should follow, but not
2170  * another GSS negotiation request, and an SSL request should only
2171  * follow if GSS was rejected (client may negotiate in either order)
2172  */
2173  return ProcessStartupPacket(port, GSSok == 'G', true);
2174  }
2175 
2176  /* Could add additional special packet types here */
2177 
2178  /*
2179  * Set FrontendProtocol now so that ereport() knows what format to send if
2180  * we fail during startup.
2181  */
2182  FrontendProtocol = proto;
2183 
2184  /* Check that the major protocol version is in range. */
2187  ereport(FATAL,
2188  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2189  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
2190  PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
2194 
2195  /*
2196  * Now fetch parameters out of startup packet and save them into the Port
2197  * structure. All data structures attached to the Port struct must be
2198  * allocated in TopMemoryContext so that they will remain available in a
2199  * running backend (even after PostmasterContext is destroyed). We need
2200  * not worry about leaking this storage on failure, since we aren't in the
2201  * postmaster process anymore.
2202  */
2204 
2205  /* Handle protocol version 3 startup packet */
2206  {
2207  int32 offset = sizeof(ProtocolVersion);
2208  List *unrecognized_protocol_options = NIL;
2209 
2210  /*
2211  * Scan packet body for name/option pairs. We can assume any string
2212  * beginning within the packet body is null-terminated, thanks to
2213  * zeroing extra byte above.
2214  */
2215  port->guc_options = NIL;
2216 
2217  while (offset < len)
2218  {
2219  char *nameptr = buf + offset;
2220  int32 valoffset;
2221  char *valptr;
2222 
2223  if (*nameptr == '\0')
2224  break; /* found packet terminator */
2225  valoffset = offset + strlen(nameptr) + 1;
2226  if (valoffset >= len)
2227  break; /* missing value, will complain below */
2228  valptr = buf + valoffset;
2229 
2230  if (strcmp(nameptr, "database") == 0)
2231  port->database_name = pstrdup(valptr);
2232  else if (strcmp(nameptr, "user") == 0)
2233  port->user_name = pstrdup(valptr);
2234  else if (strcmp(nameptr, "options") == 0)
2235  port->cmdline_options = pstrdup(valptr);
2236  else if (strcmp(nameptr, "replication") == 0)
2237  {
2238  /*
2239  * Due to backward compatibility concerns the replication
2240  * parameter is a hybrid beast which allows the value to be
2241  * either boolean or the string 'database'. The latter
2242  * connects to a specific database which is e.g. required for
2243  * logical decoding while.
2244  */
2245  if (strcmp(valptr, "database") == 0)
2246  {
2247  am_walsender = true;
2248  am_db_walsender = true;
2249  }
2250  else if (!parse_bool(valptr, &am_walsender))
2251  ereport(FATAL,
2252  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2253  errmsg("invalid value for parameter \"%s\": \"%s\"",
2254  "replication",
2255  valptr),
2256  errhint("Valid values are: \"false\", 0, \"true\", 1, \"database\".")));
2257  }
2258  else if (strncmp(nameptr, "_pq_.", 5) == 0)
2259  {
2260  /*
2261  * Any option beginning with _pq_. is reserved for use as a
2262  * protocol-level option, but at present no such options are
2263  * defined.
2264  */
2265  unrecognized_protocol_options =
2266  lappend(unrecognized_protocol_options, pstrdup(nameptr));
2267  }
2268  else
2269  {
2270  /* Assume it's a generic GUC option */
2271  port->guc_options = lappend(port->guc_options,
2272  pstrdup(nameptr));
2273  port->guc_options = lappend(port->guc_options,
2274  pstrdup(valptr));
2275 
2276  /*
2277  * Copy application_name to port if we come across it. This
2278  * is done so we can log the application_name in the
2279  * connection authorization message. Note that the GUC would
2280  * be used but we haven't gone through GUC setup yet.
2281  */
2282  if (strcmp(nameptr, "application_name") == 0)
2283  {
2284  char *tmp_app_name = pstrdup(valptr);
2285 
2286  pg_clean_ascii(tmp_app_name);
2287 
2288  port->application_name = tmp_app_name;
2289  }
2290  }
2291  offset = valoffset + strlen(valptr) + 1;
2292  }
2293 
2294  /*
2295  * If we didn't find a packet terminator exactly at the end of the
2296  * given packet length, complain.
2297  */
2298  if (offset != len - 1)
2299  ereport(FATAL,
2300  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2301  errmsg("invalid startup packet layout: expected terminator as last byte")));
2302 
2303  /*
2304  * If the client requested a newer protocol version or if the client
2305  * requested any protocol options we didn't recognize, let them know
2306  * the newest minor protocol version we do support and the names of
2307  * any unrecognized options.
2308  */
2310  unrecognized_protocol_options != NIL)
2311  SendNegotiateProtocolVersion(unrecognized_protocol_options);
2312  }
2313 
2314  /* Check a user name was given. */
2315  if (port->user_name == NULL || port->user_name[0] == '\0')
2316  ereport(FATAL,
2317  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
2318  errmsg("no PostgreSQL user name specified in startup packet")));
2319 
2320  /* The database defaults to the user name. */
2321  if (port->database_name == NULL || port->database_name[0] == '\0')
2322  port->database_name = pstrdup(port->user_name);
2323 
2324  if (Db_user_namespace)
2325  {
2326  /*
2327  * If user@, it is a global user, remove '@'. We only want to do this
2328  * if there is an '@' at the end and no earlier in the user string or
2329  * they may fake as a local user of another database attaching to this
2330  * database.
2331  */
2332  if (strchr(port->user_name, '@') ==
2333  port->user_name + strlen(port->user_name) - 1)
2334  *strchr(port->user_name, '@') = '\0';
2335  else
2336  {
2337  /* Append '@' and dbname */
2338  port->user_name = psprintf("%s@%s", port->user_name, port->database_name);
2339  }
2340  }
2341 
2342  /*
2343  * Truncate given database and user names to length of a Postgres name.
2344  * This avoids lookup failures when overlength names are given.
2345  */
2346  if (strlen(port->database_name) >= NAMEDATALEN)
2347  port->database_name[NAMEDATALEN - 1] = '\0';
2348  if (strlen(port->user_name) >= NAMEDATALEN)
2349  port->user_name[NAMEDATALEN - 1] = '\0';
2350 
2351  if (am_walsender)
2353  else
2355 
2356  /*
2357  * Normal walsender backends, e.g. for streaming replication, are not
2358  * connected to a particular database. But walsenders used for logical
2359  * replication need to connect to a specific database. We allow streaming
2360  * replication commands to be issued even if connected to a database as it
2361  * can make sense to first make a basebackup and then stream changes
2362  * starting from that.
2363  */
2364  if (am_walsender && !am_db_walsender)
2365  port->database_name[0] = '\0';
2366 
2367  /*
2368  * Done putting stuff in TopMemoryContext.
2369  */
2370  MemoryContextSwitchTo(oldcontext);
2371 
2372  /*
2373  * If we're going to reject the connection due to database state, say so
2374  * now instead of wasting cycles on an authentication exchange. (This also
2375  * allows a pg_ping utility to be written.)
2376  */
2377  switch (port->canAcceptConnections)
2378  {
2379  case CAC_STARTUP:
2380  ereport(FATAL,
2382  errmsg("the database system is starting up")));
2383  break;
2384  case CAC_NOTCONSISTENT:
2385  if (EnableHotStandby)
2386  ereport(FATAL,
2388  errmsg("the database system is not yet accepting connections"),
2389  errdetail("Consistent recovery state has not been yet reached.")));
2390  else
2391  ereport(FATAL,
2393  errmsg("the database system is not accepting connections"),
2394  errdetail("Hot standby mode is disabled.")));
2395  break;
2396  case CAC_SHUTDOWN:
2397  ereport(FATAL,
2399  errmsg("the database system is shutting down")));
2400  break;
2401  case CAC_RECOVERY:
2402  ereport(FATAL,
2404  errmsg("the database system is in recovery mode")));
2405  break;
2406  case CAC_TOOMANY:
2407  ereport(FATAL,
2408  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
2409  errmsg("sorry, too many clients already")));
2410  break;
2411  case CAC_OK:
2412  break;
2413  }
2414 
2415  return STATUS_OK;
2416 }
ssize_t secure_open_gssapi(Port *port)
int secure_open_server(Port *port)
Definition: be-secure.c:115
bool parse_bool(const char *value, bool *result)
Definition: bool.c:30
#define COMMERROR
Definition: elog.h:27
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:96
ProtocolVersion FrontendProtocol
Definition: globals.c:28
List * lappend(List *list, void *datum)
Definition: list.c:338
void * palloc(Size size)
Definition: mcxt.c:1068
@ B_BACKEND
Definition: miscadmin.h:329
BackendType MyBackendType
Definition: miscinit.c:63
#define NAMEDATALEN
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
bool Db_user_namespace
Definition: postmaster.c:243
static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options)
Definition: postmaster.c:2432
static void processCancelRequest(Port *port, void *pkt)
Definition: postmaster.c:2453
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1088
void pq_endmsgread(void)
Definition: pqcomm.c:1188
bool pq_buffer_has_data(void)
Definition: pqcomm.c:1151
void pq_startmsgread(void)
Definition: pqcomm.c:1164
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:113
#define PG_PROTOCOL_EARLIEST
Definition: pqcomm.h:122
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:176
#define MAX_STARTUP_PACKET_LENGTH
Definition: pqcomm.h:146
#define PG_PROTOCOL_LATEST
Definition: pqcomm.h:123
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:192
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:191
uint32 ProtocolVersion
Definition: pqcomm.h:125
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:114
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void pg_clean_ascii(char *str)
Definition: string.c:82
bool am_db_walsender
Definition: walsender.c:119
#define EINTR
Definition: win32_port.h:351
#define send(s, buf, len, flags)
Definition: win32_port.h:476
bool EnableHotStandby
Definition: xlog.c:122

References am_db_walsender, am_walsender, B_BACKEND, B_WAL_SENDER, buf, CAC_NOTCONSISTENT, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_TOOMANY, CANCEL_REQUEST_CODE, COMMERROR, Db_user_namespace, EINTR, EnableHotStandby, ereport, errcode(), ERRCODE_CANNOT_CONNECT_NOW, errcode_for_socket_access(), errdetail(), errhint(), errmsg(), FATAL, FrontendProtocol, lappend(), len, MAX_STARTUP_PACKET_LENGTH, MemoryContextSwitchTo(), MyBackendType, NAMEDATALEN, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, NIL, palloc(), parse_bool(), pg_clean_ascii(), pg_ntoh32, PG_PROTOCOL_EARLIEST, PG_PROTOCOL_LATEST, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, port, pq_buffer_has_data(), pq_endmsgread(), pq_getbytes(), pq_startmsgread(), processCancelRequest(), psprintf(), pstrdup(), secure_open_gssapi(), secure_open_server(), send, SendNegotiateProtocolVersion(), STATUS_ERROR, STATUS_OK, and TopMemoryContext.

Referenced by BackendInitialize().

◆ RandomCancelKey()

static bool RandomCancelKey ( int32 cancel_key)
static

Definition at line 5333 of file postmaster.c.

5334 {
5335  return pg_strong_random(cancel_key, sizeof(int32));
5336 }
bool pg_strong_random(void *buf, size_t len)

References pg_strong_random().

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

◆ reaper()

static void reaper ( SIGNAL_ARGS  )
static

Definition at line 2974 of file postmaster.c.

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