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 "bootstrap/bootstrap.h"
#include "catalog/pg_control.h"
#include "common/file_perm.h"
#include "common/ip.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 "miscadmin.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/fork_process.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "replication/logicallauncher.h"
#include "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/ps_status.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */
 
#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */
 
#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */
 
#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */
 
#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */
 
#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)
 
#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 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_WAIT_BACKUP, PM_WAIT_READONLY, 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 startup_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 char ExtraOptions [MAXPGPATH]
 
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
 
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 PgStatPID = 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 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 */

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 146 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 147 of file postmaster.c.

Referenced by CountChildren(), and SignalSomeChildren().

◆ BACKEND_TYPE_WORKER

#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)

Definition at line 151 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ EXIT_STATUS_0

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

Definition at line 548 of file postmaster.c.

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

◆ EXIT_STATUS_1

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

Definition at line 549 of file postmaster.c.

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

◆ EXIT_STATUS_3

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

Definition at line 550 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 274 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 275 of file postmaster.c.

Referenced by HandleChildCrash(), pmdie(), PostmasterStateMachine(), and ServerLoop().

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

Referenced by maybe_start_bgworkers().

◆ MAXLISTEN

#define MAXLISTEN   64

◆ NoShutdown

#define NoShutdown   0

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

Referenced by CreateOptsFile().

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
#define XLogArchivingAlways()
Definition: xlog.h:183
static PMState pmState
Definition: postmaster.c:341
#define XLogArchivingActive()
Definition: xlog.h:180

Definition at line 435 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 348 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 418 of file postmaster.c.

Referenced by PostmasterStateMachine(), reaper(), SIGHUP_handler(), and TerminateChildren().

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 273 of file postmaster.c.

Referenced by pmdie(), reaper(), and SIGHUP_handler().

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 542 of file postmaster.c.

Referenced by reaper(), ServerLoop(), and sigusr1_handler().

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 543 of file postmaster.c.

Referenced by PostmasterStateMachine(), reaper(), ServerLoop(), and sigusr1_handler().

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 541 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 545 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 544 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

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_WAIT_BACKUP 
PM_WAIT_READONLY 
PM_WAIT_BACKENDS 
PM_SHUTDOWN 
PM_SHUTDOWN_2 
PM_WAIT_DEAD_END 
PM_NO_CHILDREN 

Definition at line 323 of file postmaster.c.

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

◆ 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:261

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5935 of file postmaster.c.

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

5936 {
5937  Backend *bn;
5938 
5939  /*
5940  * Check that database state allows another connection. Currently the
5941  * only possible failure is CAC_TOOMANY, so we just log an error message
5942  * based on that rather than checking the error code precisely.
5943  */
5945  {
5946  ereport(LOG,
5947  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5948  errmsg("no slot available for new worker process")));
5949  return false;
5950  }
5951 
5952  /*
5953  * Compute the cancel key that will be assigned to this session. We
5954  * probably don't need cancel keys for background workers, but we'd better
5955  * have something random in the field to prevent unfriendly people from
5956  * sending cancels to them.
5957  */
5959  {
5960  ereport(LOG,
5961  (errcode(ERRCODE_INTERNAL_ERROR),
5962  errmsg("could not generate random cancel key")));
5963  return false;
5964  }
5965 
5966  bn = malloc(sizeof(Backend));
5967  if (bn == NULL)
5968  {
5969  ereport(LOG,
5970  (errcode(ERRCODE_OUT_OF_MEMORY),
5971  errmsg("out of memory")));
5972  return false;
5973  }
5974 
5975  bn->cancel_key = MyCancelKey;
5978  bn->dead_end = false;
5979  bn->bgworker_notify = false;
5980 
5981  rw->rw_backend = bn;
5982  rw->rw_child_slot = bn->child_slot;
5983 
5984  return true;
5985 }
struct bkend * rw_backend
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2434
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:182
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:184
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:44
int32 cancel_key
Definition: postmaster.c:172
bool dead_end
Definition: postmaster.c:181
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5391
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
#define ereport(elevel,...)
Definition: elog.h:144
int MyPMChildSlot
Definition: globals.c:45
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4297 of file postmaster.c.

References SockAddr::addr, am_walsender, appendStringInfo(), AuthenticationTimeout, B_WAL_SENDER, BlockSig, ClientAuthInProgress, StringInfoData::data, Port::database_name, 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(), ProcessStartupPacket(), Port::raddr, RegisterTimeout(), Port::remote_host, Port::remote_hostname, Port::remote_port, ReserveExternalFD(), SockAddr::salen, set_ps_display(), SIGQUIT, startup_die(), STARTUP_PACKET_TIMEOUT, StartupBlockSig, StartupPacketTimeoutHandler(), status(), STATUS_OK, Port::user_name, WARNING, and whereToSendOutput.

Referenced by BackendRun(), and BackendStartup().

4298 {
4299  int status;
4300  int ret;
4301  char remote_host[NI_MAXHOST];
4302  char remote_port[NI_MAXSERV];
4303  StringInfoData ps_data;
4304 
4305  /* Save port etc. for ps status */
4306  MyProcPort = port;
4307 
4308  /* Tell fd.c about the long-lived FD associated with the port */
4310 
4311  /*
4312  * PreAuthDelay is a debugging aid for investigating problems in the
4313  * authentication cycle: it can be set in postgresql.conf to allow time to
4314  * attach to the newly-forked backend with a debugger. (See also
4315  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4316  * is not honored until after authentication.)
4317  */
4318  if (PreAuthDelay > 0)
4319  pg_usleep(PreAuthDelay * 1000000L);
4320 
4321  /* This flag will remain set until InitPostgres finishes authentication */
4322  ClientAuthInProgress = true; /* limit visibility of log messages */
4323 
4324  /* set these to empty in case they are needed before we set them up */
4325  port->remote_host = "";
4326  port->remote_port = "";
4327 
4328  /*
4329  * Initialize libpq and enable reporting of ereport errors to the client.
4330  * Must do this now because authentication uses libpq to send messages.
4331  */
4332  pq_init(); /* initialize libpq to talk to client */
4333  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4334 
4335  /*
4336  * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
4337  * timeout while trying to collect the startup packet. Otherwise the
4338  * postmaster cannot shutdown the database FAST or IMMED cleanly if a
4339  * buggy client fails to send the packet promptly. XXX it follows that
4340  * the remainder of this function must tolerate losing control at any
4341  * instant. Likewise, any pg_on_exit_callback registered before or during
4342  * this function must be prepared to execute at any instant between here
4343  * and the end of this function. Furthermore, affected callbacks execute
4344  * partially or not at all when a second exit-inducing signal arrives
4345  * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to
4346  * that mechanic, callbacks need not anticipate more than one call.) This
4347  * is fragile; it ought to instead follow the norm of handling interrupts
4348  * at selected, safe opportunities.
4349  */
4350  pqsignal(SIGTERM, startup_die);
4352  InitializeTimeouts(); /* establishes SIGALRM handler */
4354 
4355  /*
4356  * Get the remote host name and port for logging and status display.
4357  */
4358  remote_host[0] = '\0';
4359  remote_port[0] = '\0';
4360  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4361  remote_host, sizeof(remote_host),
4362  remote_port, sizeof(remote_port),
4363  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4364  ereport(WARNING,
4365  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4366  gai_strerror(ret))));
4367 
4368  /*
4369  * Save remote_host and remote_port in port structure (after this, they
4370  * will appear in log_line_prefix data for log messages).
4371  */
4372  port->remote_host = strdup(remote_host);
4373  port->remote_port = strdup(remote_port);
4374 
4375  /* And now we can issue the Log_connections message, if wanted */
4376  if (Log_connections)
4377  {
4378  if (remote_port[0])
4379  ereport(LOG,
4380  (errmsg("connection received: host=%s port=%s",
4381  remote_host,
4382  remote_port)));
4383  else
4384  ereport(LOG,
4385  (errmsg("connection received: host=%s",
4386  remote_host)));
4387  }
4388 
4389  /*
4390  * If we did a reverse lookup to name, we might as well save the results
4391  * rather than possibly repeating the lookup during authentication.
4392  *
4393  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4394  * get nothing useful for a client without an rDNS entry. Therefore, we
4395  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4396  * it into remote_hostname if so. (This test is conservative and might
4397  * sometimes classify a hostname as numeric, but an error in that
4398  * direction is safe; it only results in a possible extra lookup.)
4399  */
4400  if (log_hostname &&
4401  ret == 0 &&
4402  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4403  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4404  port->remote_hostname = strdup(remote_host);
4405 
4406  /*
4407  * Ready to begin client interaction. We will give up and exit(1) after a
4408  * time delay, so that a broken client can't hog a connection
4409  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4410  * against the time limit.
4411  *
4412  * Note: AuthenticationTimeout is applied here while waiting for the
4413  * startup packet, and then again in InitPostgres for the duration of any
4414  * authentication operations. So a hostile client could tie up the
4415  * process for nearly twice AuthenticationTimeout before we kick him off.
4416  *
4417  * Note: because PostgresMain will call InitializeTimeouts again, the
4418  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4419  * since we never use it again after this function.
4420  */
4423 
4424  /*
4425  * Receive the startup packet (which might turn out to be a cancel request
4426  * packet).
4427  */
4428  status = ProcessStartupPacket(port, false, false);
4429 
4430  /*
4431  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4432  * already did any appropriate error reporting.
4433  */
4434  if (status != STATUS_OK)
4435  proc_exit(0);
4436 
4437  /*
4438  * Now that we have the user and database name, we can set the process
4439  * title for ps. It's good to do this as early as possible in startup.
4440  */
4441  initStringInfo(&ps_data);
4442  if (am_walsender)
4444  appendStringInfo(&ps_data, "%s ", port->user_name);
4445  if (!am_walsender)
4446  appendStringInfo(&ps_data, "%s ", port->database_name);
4447  appendStringInfo(&ps_data, "%s", port->remote_host);
4448  if (port->remote_port[0] != '\0')
4449  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4450 
4451  init_ps_display(ps_data.data);
4452  pfree(ps_data.data);
4453 
4454  set_ps_display("initializing");
4455 
4456  /*
4457  * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4458  */
4460  PG_SETMASK(&BlockSig);
4461 }
void InitializeTimeouts(void)
Definition: timeout.c:346
#define SIGQUIT
Definition: win32_port.h:154
static void startup_die(SIGNAL_ARGS)
Definition: postmaster.c:5357
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
struct Port * MyProcPort
Definition: globals.c:43
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:202
struct sockaddr_storage addr
Definition: pqcomm.h:64
void proc_exit(int code)
Definition: ipc.c:104
char * remote_port
Definition: libpq-be.h:132
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:242
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define gai_strerror
Definition: getaddrinfo.h:146
int AuthenticationTimeout
Definition: postmaster.c:239
void set_ps_display(const char *activity)
Definition: ps_status.c:349
char * remote_hostname
Definition: libpq-be.h:128
bool ClientAuthInProgress
Definition: postmaster.c:352
SockAddr raddr
Definition: libpq-be.h:126
bool am_walsender
Definition: walsender.c:115
void pg_usleep(long microsec)
Definition: signal.c:53
void pq_init(void)
Definition: pqcomm.c:192
void pfree(void *pointer)
Definition: mcxt.c:1056
#define NI_MAXHOST
Definition: getaddrinfo.h:88
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void ReserveExternalFD(void)
Definition: fd.c:1080
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:141
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define STATUS_OK
Definition: c.h:1133
bool log_hostname
Definition: postmaster.c:241
static int port
Definition: pg_regress.c:90
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define WARNING
Definition: elog.h:40
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:1925
sigset_t BlockSig
Definition: pqsignal.c:22
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
#define ereport(elevel,...)
Definition: elog.h:144
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:380
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:435
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
sigset_t StartupBlockSig
Definition: pqsignal.c:22
int PreAuthDelay
Definition: postmaster.c:238
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:824
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5381
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:532
CommandDest whereToSendOutput
Definition: postgres.c:91
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
char * database_name
Definition: libpq-be.h:140

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4472 of file postmaster.c.

References AllocateFile(), Assert, AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), av, BackendInitialize(), BlockSig, calloc, checkDataDir(), ClosePostmasterPorts(), CreateSharedMemoryAndSemaphores(), Port::database_name, DEBUG3, DestNone, elog, EnableSSL, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ExtraOptions, FATAL, fork_process(), FreeFile(), Port::gss, i, InitAuxiliaryProcess(), InitializeGUCOptions(), InitPostmasterChild(), InitProcess(), InitShmemAccess(), IsBackgroundWorker, IsPostmasterEnvironment, lengthof, LocalProcessControlFile(), LOG, MakePGDirectory(), malloc, MAXPGPATH, MemoryContextAlloc(), MemoryContextSwitchTo(), MyProcPid, PG_BINARY_W, PG_SETMASK, pg_split_opts(), PG_TEMP_FILE_PREFIX, PG_TEMP_FILES_DIR, PgArchiverMain(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), PgstatCollectorMain(), pgwin32_ReserveSharedMemoryRegion(), pgwin32_signal_initialize(), bkend::pid, port, PostgresMain(), pqinitmask(), process_shared_preload_libraries(), progname, secure_initialize(), snprintf, sprintf, StartBackgroundWorker(), SysLoggerMain(), TopMemoryContext, UsedShmemSegAddr, Port::user_name, and whereToSendOutput.

Referenced by BackendStartup().

4473 {
4474  char **av;
4475  int maxac;
4476  int ac;
4477  int i;
4478 
4479  /*
4480  * Now, build the argv vector that will be given to PostgresMain.
4481  *
4482  * The maximum possible number of commandline arguments that could come
4483  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4484  * pg_split_opts().
4485  */
4486  maxac = 2; /* for fixed args supplied below */
4487  maxac += (strlen(ExtraOptions) + 1) / 2;
4488 
4489  av = (char **) MemoryContextAlloc(TopMemoryContext,
4490  maxac * sizeof(char *));
4491  ac = 0;
4492 
4493  av[ac++] = "postgres";
4494 
4495  /*
4496  * Pass any backend switches specified with -o on the postmaster's own
4497  * command line. We assume these are secure.
4498  */
4499  pg_split_opts(av, &ac, ExtraOptions);
4500 
4501  av[ac] = NULL;
4502 
4503  Assert(ac < maxac);
4504 
4505  /*
4506  * Debug: print arguments being passed to backend
4507  */
4508  ereport(DEBUG3,
4509  (errmsg_internal("%s child[%d]: starting with (",
4510  progname, (int) getpid())));
4511  for (i = 0; i < ac; ++i)
4512  ereport(DEBUG3,
4513  (errmsg_internal("\t%s", av[i])));
4514  ereport(DEBUG3,
4515  (errmsg_internal(")")));
4516 
4517  /*
4518  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4519  * just yet, though, because InitPostgres will need the HBA data.)
4520  */
4522 
4523  PostgresMain(ac, av, port->database_name, port->user_name);
4524 }
#define DEBUG3
Definition: elog.h:23
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
const char * progname
Definition: pg_standby.c:36
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3777
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:467
char * user_name
Definition: libpq-be.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
struct @17::@18 av[32]
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:223
#define Assert(condition)
Definition: c.h:738
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
int i
char * database_name
Definition: libpq-be.h:140

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4147 of file postmaster.c.

References AssignPostmasterChildSlot(), BACKEND_TYPE_NORMAL, BackendInitialize(), BackendRun(), bkend::bgworker_notify, bkend::bkend_type, CAC_OK, CAC_WAITBACKUP, Port::canAcceptConnections, 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(), LOG, malloc, MyCancelKey, MyPMChildSlot, bkend::pid, RandomCancelKey(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), Port::sock, STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

4148 {
4149  Backend *bn; /* for backend cleanup */
4150  pid_t pid;
4151 
4152  /*
4153  * Create backend data structure. Better before the fork() so we can
4154  * handle failure cleanly.
4155  */
4156  bn = (Backend *) malloc(sizeof(Backend));
4157  if (!bn)
4158  {
4159  ereport(LOG,
4160  (errcode(ERRCODE_OUT_OF_MEMORY),
4161  errmsg("out of memory")));
4162  return STATUS_ERROR;
4163  }
4164 
4165  /*
4166  * Compute the cancel key that will be assigned to this backend. The
4167  * backend will have its own copy in the forked-off process' value of
4168  * MyCancelKey, so that it can transmit the key to the frontend.
4169  */
4171  {
4172  free(bn);
4173  ereport(LOG,
4174  (errcode(ERRCODE_INTERNAL_ERROR),
4175  errmsg("could not generate random cancel key")));
4176  return STATUS_ERROR;
4177  }
4178 
4179  bn->cancel_key = MyCancelKey;
4180 
4181  /* Pass down canAcceptConnections state */
4183  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4185 
4186  /*
4187  * Unless it's a dead_end child, assign it a child slot number
4188  */
4189  if (!bn->dead_end)
4191  else
4192  bn->child_slot = 0;
4193 
4194  /* Hasn't asked to be notified about any bgworkers yet */
4195  bn->bgworker_notify = false;
4196 
4197 #ifdef EXEC_BACKEND
4198  pid = backend_forkexec(port);
4199 #else /* !EXEC_BACKEND */
4200  pid = fork_process();
4201  if (pid == 0) /* child */
4202  {
4203  free(bn);
4204 
4205  /* Detangle from postmaster */
4207 
4208  /* Close the postmaster's sockets */
4209  ClosePostmasterPorts(false);
4210 
4211  /* Perform additional initialization and collect startup packet */
4212  BackendInitialize(port);
4213 
4214  /* And run the backend */
4215  BackendRun(port);
4216  }
4217 #endif /* EXEC_BACKEND */
4218 
4219  if (pid < 0)
4220  {
4221  /* in parent, fork failed */
4222  int save_errno = errno;
4223 
4224  if (!bn->dead_end)
4226  free(bn);
4227  errno = save_errno;
4228  ereport(LOG,
4229  (errmsg("could not fork new process for connection: %m")));
4230  report_fork_failure_to_client(port, save_errno);
4231  return STATUS_ERROR;
4232  }
4233 
4234  /* in parent, successful fork */
4235  ereport(DEBUG2,
4236  (errmsg_internal("forked new backend, pid=%d socket=%d",
4237  (int) pid, (int) port->sock)));
4238 
4239  /*
4240  * Everything's been successful, it's safe to add this backend to our list
4241  * of backends.
4242  */
4243  bn->pid = pid;
4244  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4246 
4247 #ifdef EXEC_BACKEND
4248  if (!bn->dead_end)
4249  ShmemBackendArrayAdd(bn);
4250 #endif
4251 
4252  return STATUS_OK;
4253 }
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2434
CAC_state canAcceptConnections
Definition: libpq-be.h:133
void InitPostmasterChild(void)
Definition: miscinit.c:91
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4472
pid_t fork_process(void)
Definition: fork_process.c:32
int errcode(int sqlerrcode)
Definition: elog.c:610
#define STATUS_ERROR
Definition: c.h:1134
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2559
pgsocket sock
Definition: libpq-be.h:122
bool bgworker_notify
Definition: postmaster.c:182
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:184
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:44
static dlist_head BackendList
Definition: postmaster.c:186
#define DEBUG2
Definition: elog.h:24
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4264
int32 cancel_key
Definition: postmaster.c:172
bool dead_end
Definition: postmaster.c:181
#define STATUS_OK
Definition: c.h:1133
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5391
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
#define ereport(elevel,...)
Definition: elog.h:144
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
pid_t pid
Definition: postmaster.c:171
int MyPMChildSlot
Definition: globals.c:45
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void BackendInitialize(Port *port)
Definition: postmaster.c:4297

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5757 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5758 {
5759  PG_SETMASK(&BlockSig);
5760 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t BlockSig
Definition: pqsignal.c:22

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5711 of file postmaster.c.

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

Referenced by ApplyLauncherMain(), and initialize_worker_spi().

5712 {
5714 
5715  /* XXX is this the right errcode? */
5717  ereport(FATAL,
5718  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5719  errmsg("database connection requirement not indicated during registration")));
5720 
5722 
5723  /* it had better not gotten out of "init" mode yet */
5724  if (!IsInitProcessingMode())
5725  ereport(ERROR,
5726  (errmsg("invalid processing mode in background worker")));
5728 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define SetProcessingMode(mode)
Definition: miscadmin.h:398
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
static char * username
Definition: initdb.c:133
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:50
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define IsInitProcessingMode()
Definition: miscadmin.h:393

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5734 of file postmaster.c.

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

5735 {
5737 
5738  /* XXX is this the right errcode? */
5740  ereport(FATAL,
5741  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5742  errmsg("database connection requirement not indicated during registration")));
5743 
5744  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5745 
5746  /* it had better not gotten out of "init" mode yet */
5747  if (!IsInitProcessingMode())
5748  ereport(ERROR,
5749  (errmsg("invalid processing mode in background worker")));
5751 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define SetProcessingMode(mode)
Definition: miscadmin.h:398
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define IsInitProcessingMode()
Definition: miscadmin.h:393

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5763 of file postmaster.c.

References Assert, av, lengthof, MAXPGPATH, PG_SETMASK, snprintf, and UnBlockSig.

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

5764 {
5766 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t UnBlockSig
Definition: pqsignal.c:22

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5891 of file postmaster.c.

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_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_DEAD_END, PM_WAIT_READONLY, and pmState.

Referenced by maybe_start_bgworkers().

5892 {
5893  switch (pmState)
5894  {
5895  case PM_NO_CHILDREN:
5896  case PM_WAIT_DEAD_END:
5897  case PM_SHUTDOWN_2:
5898  case PM_SHUTDOWN:
5899  case PM_WAIT_BACKENDS:
5900  case PM_WAIT_READONLY:
5901  case PM_WAIT_BACKUP:
5902  break;
5903 
5904  case PM_RUN:
5906  return true;
5907  /* fall through */
5908 
5909  case PM_HOT_STANDBY:
5911  return true;
5912  /* fall through */
5913 
5914  case PM_RECOVERY:
5915  case PM_STARTUP:
5916  case PM_INIT:
5918  return true;
5919  /* fall through */
5920 
5921  }
5922 
5923  return false;
5924 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:341

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 2434 of file postmaster.c.

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

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

2435 {
2436  CAC_state result = CAC_OK;
2437 
2438  /*
2439  * Can't start backends when in startup/shutdown/inconsistent recovery
2440  * state. We treat autovac workers the same as user backends for this
2441  * purpose. However, bgworkers are excluded from this test; we expect
2442  * bgworker_should_start_now() decided whether the DB state allows them.
2443  *
2444  * In state PM_WAIT_BACKUP only superusers can connect (this must be
2445  * allowed so that a superuser can end online backup mode); we return
2446  * CAC_WAITBACKUP code to indicate that this must be checked later. Note
2447  * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
2448  * have checked for too many children.
2449  */
2450  if (pmState != PM_RUN &&
2451  backend_type != BACKEND_TYPE_BGWORKER)
2452  {
2453  if (pmState == PM_WAIT_BACKUP)
2454  result = CAC_WAITBACKUP; /* allow superusers only */
2455  else if (Shutdown > NoShutdown)
2456  return CAC_SHUTDOWN; /* shutdown is pending */
2457  else if (!FatalError &&
2458  (pmState == PM_STARTUP ||
2459  pmState == PM_RECOVERY))
2460  return CAC_STARTUP; /* normal startup */
2461  else if (!FatalError &&
2463  result = CAC_OK; /* connection OK during hot standby */
2464  else
2465  return CAC_RECOVERY; /* else must be crash recovery */
2466  }
2467 
2468  /*
2469  * Don't start too many children.
2470  *
2471  * We allow more connections here than we can have backends because some
2472  * might still be authenticating; they might fail auth, or some existing
2473  * backend might exit before the auth cycle is completed. The exact
2474  * MaxBackends limit is enforced when a new backend tries to join the
2475  * shared-inval backend array.
2476  *
2477  * The limit here must match the sizes of the per-child-process arrays;
2478  * see comments for MaxLivePostmasterChildren().
2479  */
2481  result = CAC_TOOMANY;
2482 
2483  return result;
2484 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
static bool FatalError
Definition: postmaster.c:279
static int Shutdown
Definition: postmaster.c:277
static int CountChildren(int target)
Definition: postmaster.c:5401
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static PMState pmState
Definition: postmaster.c:341
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5701
#define NoShutdown
Definition: postmaster.c:272
CAC_state
Definition: libpq-be.h:71

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1516 of file postmaster.c.

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

Referenced by PostmasterMain().

1517 {
1518  char path[MAXPGPATH];
1519  FILE *fp;
1520 
1521  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1522 
1523  fp = AllocateFile(path, PG_BINARY_R);
1524  if (fp == NULL)
1525  {
1526  write_stderr("%s: could not find the database system\n"
1527  "Expected to find it in the directory \"%s\",\n"
1528  "but could not open file \"%s\": %s\n",
1529  progname, DataDir, path, strerror(errno));
1530  ExitPostmaster(2);
1531  }
1532  FreeFile(fp);
1533 }
#define write_stderr(str)
Definition: parallel.c:186
const char * progname
Definition: pg_standby.c:36
#define PG_BINARY_R
Definition: c.h:1235
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5139
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2320
#define strerror
Definition: port.h:206
int FreeFile(FILE *file)
Definition: fd.c:2519
char * DataDir
Definition: globals.c:62
#define snprintf
Definition: port.h:193

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

Definition at line 3389 of file postmaster.c.

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

Referenced by reaper().

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3289 of file postmaster.c.

References _, BackgroundWorkerList, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_flags, BackgroundWorker::bgw_type, bkend::bgworker_notify, BGWORKER_SHMEM_ACCESS, 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().

3291 {
3292  char namebuf[MAXPGPATH];
3293  slist_mutable_iter iter;
3294 
3296  {
3297  RegisteredBgWorker *rw;
3298 
3299  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3300 
3301  if (rw->rw_pid != pid)
3302  continue;
3303 
3304 #ifdef WIN32
3305  /* see CleanupBackend */
3306  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3307  exitstatus = 0;
3308 #endif
3309 
3310  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3311  rw->rw_worker.bgw_type);
3312 
3313 
3314  if (!EXIT_STATUS_0(exitstatus))
3315  {
3316  /* Record timestamp, so we know when to restart the worker. */
3318  }
3319  else
3320  {
3321  /* Zero exit status means terminate */
3322  rw->rw_crashed_at = 0;
3323  rw->rw_terminate = true;
3324  }
3325 
3326  /*
3327  * Additionally, for shared-memory-connected workers, just like a
3328  * backend, any exit status other than 0 or 1 is considered a crash
3329  * and causes a system-wide restart.
3330  */
3331  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3332  {
3333  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3334  {
3335  HandleChildCrash(pid, exitstatus, namebuf);
3336  return true;
3337  }
3338  }
3339 
3340  /*
3341  * We must release the postmaster child slot whether this worker is
3342  * connected to shared memory or not, but we only treat it as a crash
3343  * if it is in fact connected.
3344  */
3347  {
3348  HandleChildCrash(pid, exitstatus, namebuf);
3349  return true;
3350  }
3351 
3352  /* Get it out of the BackendList and clear out remaining data */
3353  dlist_delete(&rw->rw_backend->elem);
3354 #ifdef EXEC_BACKEND
3355  ShmemBackendArrayRemove(rw->rw_backend);
3356 #endif
3357 
3358  /*
3359  * It's possible that this background worker started some OTHER
3360  * background worker and asked to be notified when that worker started
3361  * or stopped. If so, cancel any notifications destined for the
3362  * now-dead backend.
3363  */
3364  if (rw->rw_backend->bgworker_notify)
3366  free(rw->rw_backend);
3367  rw->rw_backend = NULL;
3368  rw->rw_pid = 0;
3369  rw->rw_child_slot = 0;
3370  ReportBackgroundWorkerExit(&iter); /* report child death */
3371 
3372  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3373  namebuf, pid, exitstatus);
3374 
3375  return true;
3376  }
3377 
3378  return false;
3379 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
slist_node * cur
Definition: ilist.h:241
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:458
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:492
bool bgworker_notify
Definition: postmaster.c:182
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
#define EXIT_STATUS_1(st)
Definition: postmaster.c:549
#define MAXPGPATH
slist_head BackgroundWorkerList
Definition: bgworker.c:42
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define free(a)
Definition: header.h:65
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3473
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3729
BackgroundWorker rw_worker
#define snprintf
Definition: port.h:193
#define _(x)
Definition: elog.c:88
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2559 of file postmaster.c.

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 BackendRun(), BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

2560 {
2561  int i;
2562 
2563 #ifndef WIN32
2564 
2565  /*
2566  * Close the write end of postmaster death watch pipe. It's important to
2567  * do this as early as possible, so that if postmaster dies, others won't
2568  * think that it's still running because we're holding the pipe open.
2569  */
2571  ereport(FATAL,
2573  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2575  /* Notify fd.c that we released one pipe FD. */
2577 #endif
2578 
2579  /*
2580  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2581  * so we don't call ReleaseExternalFD() here.
2582  */
2583  for (i = 0; i < MAXLISTEN; i++)
2584  {
2585  if (ListenSocket[i] != PGINVALID_SOCKET)
2586  {
2589  }
2590  }
2591 
2592  /*
2593  * If using syslogger, close the read side of the pipe. We don't bother
2594  * tracking this in fd.c, either.
2595  */
2596  if (!am_syslogger)
2597  {
2598 #ifndef WIN32
2599  if (syslogPipe[0] >= 0)
2600  close(syslogPipe[0]);
2601  syslogPipe[0] = -1;
2602 #else
2603  if (syslogPipe[0])
2604  CloseHandle(syslogPipe[0]);
2605  syslogPipe[0] = 0;
2606 #endif
2607  }
2608 
2609 #ifdef USE_BONJOUR
2610  /* If using Bonjour, close the connection to the mDNS daemon */
2611  if (bonjour_sdref)
2612  close(DNSServiceRefSockFD(bonjour_sdref));
2613 #endif
2614 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:843
#define FATAL
Definition: elog.h:52
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:633
int postmaster_alive_fds[2]
Definition: postmaster.c:557
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
void ReleaseExternalFD(void)
Definition: fd.c:1098
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:217
int syslogPipe[2]
Definition: syslogger.c:113

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1415 of file postmaster.c.

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

Referenced by PostmasterMain().

1416 {
1417  int i;
1418 
1419  /*
1420  * First, explicitly close all the socket FDs. We used to just let this
1421  * happen implicitly at postmaster exit, but it's better to close them
1422  * before we remove the postmaster.pid lockfile; otherwise there's a race
1423  * condition if a new postmaster wants to re-use the TCP port number.
1424  */
1425  for (i = 0; i < MAXLISTEN; i++)
1426  {
1427  if (ListenSocket[i] != PGINVALID_SOCKET)
1428  {
1431  }
1432  }
1433 
1434  /*
1435  * Next, remove any filesystem entries for Unix sockets. To avoid race
1436  * conditions against incoming postmasters, this must happen after closing
1437  * the sockets and before removing lock files.
1438  */
1440 
1441  /*
1442  * We don't do anything about socket lock files here; those will be
1443  * removed in a later on_proc_exit callback.
1444  */
1445 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:843
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
int i
void RemoveSocketFiles(void)
Definition: pqcomm.c:876
#define MAXLISTEN
Definition: postmaster.c:217

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2493 of file postmaster.c.

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

Referenced by ServerLoop().

2494 {
2495  Port *port;
2496 
2497  if (!(port = (Port *) calloc(1, sizeof(Port))))
2498  {
2499  ereport(LOG,
2500  (errcode(ERRCODE_OUT_OF_MEMORY),
2501  errmsg("out of memory")));
2502  ExitPostmaster(1);
2503  }
2504 
2505  if (StreamConnection(serverFd, port) != STATUS_OK)
2506  {
2507  if (port->sock != PGINVALID_SOCKET)
2508  StreamClose(port->sock);
2509  ConnFree(port);
2510  return NULL;
2511  }
2512 
2513  /*
2514  * Allocate GSSAPI specific state struct
2515  */
2516 #ifndef EXEC_BACKEND
2517 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2518  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2519  if (!port->gss)
2520  {
2521  ereport(LOG,
2522  (errcode(ERRCODE_OUT_OF_MEMORY),
2523  errmsg("out of memory")));
2524  ExitPostmaster(1);
2525  }
2526 #endif
2527 #endif
2528 
2529  return port;
2530 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:843
static void ConnFree(Port *port)
Definition: postmaster.c:2537
int errcode(int sqlerrcode)
Definition: elog.c:610
Definition: libpq-be.h:120
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:714
pgsocket sock
Definition: libpq-be.h:122
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5139
#define STATUS_OK
Definition: c.h:1133
static int port
Definition: pg_regress.c:90
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:144
void * gss
Definition: libpq-be.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2537 of file postmaster.c.

References free, Port::gss, and secure_close().

Referenced by ConnCreate(), and ServerLoop().

2538 {
2539 #ifdef USE_SSL
2540  secure_close(conn);
2541 #endif
2542  if (conn->gss)
2543  free(conn->gss);
2544  free(conn);
2545 }
PGconn * conn
Definition: streamutil.c:54
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:133

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5401 of file postmaster.c.

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

Referenced by canAcceptConnections(), and PostmasterStateMachine().

5402 {
5403  dlist_iter iter;
5404  int cnt = 0;
5405 
5406  dlist_foreach(iter, &BackendList)
5407  {
5408  Backend *bp = dlist_container(Backend, elem, iter.cur);
5409 
5410  if (bp->dead_end)
5411  continue;
5412 
5413  /*
5414  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5415  * it first and avoid touching shared memory for every child.
5416  */
5417  if (target != BACKEND_TYPE_ALL)
5418  {
5419  /*
5420  * Assign bkend_type for any recently announced WAL Sender
5421  * processes.
5422  */
5423  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5426 
5427  if (!(target & bp->bkend_type))
5428  continue;
5429  }
5430 
5431  cnt++;
5432  }
5433  return cnt;
5434 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:186
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
bool dead_end
Definition: postmaster.c:181
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:240

◆ CreateOptsFile()

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

Definition at line 5661 of file postmaster.c.

References elog, fprintf, i, LOG, and OPTS_FILE.

Referenced by PostmasterMain().

5662 {
5663  FILE *fp;
5664  int i;
5665 
5666 #define OPTS_FILE "postmaster.opts"
5667 
5668  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5669  {
5670  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5671  return false;
5672  }
5673 
5674  fprintf(fp, "%s", fullprogname);
5675  for (i = 1; i < argc; i++)
5676  fprintf(fp, " \"%s\"", argv[i]);
5677  fputs("\n", fp);
5678 
5679  if (fclose(fp))
5680  {
5681  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5682  return false;
5683  }
5684 
5685  return true;
5686 }
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:197
#define elog(elevel,...)
Definition: elog.h:214
int i
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1545 of file postmaster.c.

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

1546 {
1547  TimestampTz next_wakeup = 0;
1548 
1549  /*
1550  * Normal case: either there are no background workers at all, or we're in
1551  * a shutdown sequence (during which we ignore bgworkers altogether).
1552  */
1553  if (Shutdown > NoShutdown ||
1555  {
1556  if (AbortStartTime != 0)
1557  {
1558  /* time left to abort; clamp to 0 in case it already expired */
1559  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1560  (time(NULL) - AbortStartTime);
1561  timeout->tv_sec = Max(timeout->tv_sec, 0);
1562  timeout->tv_usec = 0;
1563  }
1564  else
1565  {
1566  timeout->tv_sec = 60;
1567  timeout->tv_usec = 0;
1568  }
1569  return;
1570  }
1571 
1572  if (StartWorkerNeeded)
1573  {
1574  timeout->tv_sec = 0;
1575  timeout->tv_usec = 0;
1576  return;
1577  }
1578 
1579  if (HaveCrashedWorker)
1580  {
1581  slist_mutable_iter siter;
1582 
1583  /*
1584  * When there are crashed bgworkers, we sleep just long enough that
1585  * they are restarted when they request to be. Scan the list to
1586  * determine the minimum of all wakeup times according to most recent
1587  * crash time and requested restart interval.
1588  */
1590  {
1591  RegisteredBgWorker *rw;
1592  TimestampTz this_wakeup;
1593 
1594  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1595 
1596  if (rw->rw_crashed_at == 0)
1597  continue;
1598 
1600  || rw->rw_terminate)
1601  {
1602  ForgetBackgroundWorker(&siter);
1603  continue;
1604  }
1605 
1606  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1607  1000L * rw->rw_worker.bgw_restart_time);
1608  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1609  next_wakeup = this_wakeup;
1610  }
1611  }
1612 
1613  if (next_wakeup != 0)
1614  {
1615  long secs;
1616  int microsecs;
1617 
1619  &secs, &microsecs);
1620  timeout->tv_sec = secs;
1621  timeout->tv_usec = microsecs;
1622 
1623  /* Ensure we don't exceed one minute */
1624  if (timeout->tv_sec > 60)
1625  {
1626  timeout->tv_sec = 60;
1627  timeout->tv_usec = 0;
1628  }
1629  }
1630  else
1631  {
1632  timeout->tv_sec = 60;
1633  timeout->tv_usec = 0;
1634  }
1635 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:367
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int64 TimestampTz
Definition: timestamp.h:39
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:94
static volatile bool HaveCrashedWorker
Definition: postmaster.c:368
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
static int Shutdown
Definition: postmaster.c:277
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:411
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:348
#define Max(x, y)
Definition: c.h:914
#define NoShutdown
Definition: postmaster.c:272
BackgroundWorker rw_worker
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1648
static time_t AbortStartTime
Definition: postmaster.c:345

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5799 of file postmaster.c.

References Assert, assign_backendlist_entry(), BackgroundWorker::bgw_name, ClosePostmasterPorts(), DEBUG1, dlist_push_head(), bkend::elem, ereport, errmsg(), fork_process(), free, GetCurrentTimestamp(), InitPostmasterChild(), LOG, MemoryContextAlloc(), MemoryContextDelete(), MemoryContextSwitchTo(), 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().

5800 {
5801  pid_t worker_pid;
5802 
5803  Assert(rw->rw_pid == 0);
5804 
5805  /*
5806  * Allocate and assign the Backend element. Note we must do this before
5807  * forking, so that we can handle failures (out of memory or child-process
5808  * slots) cleanly.
5809  *
5810  * Treat failure as though the worker had crashed. That way, the
5811  * postmaster will wait a bit before attempting to start it again; if we
5812  * tried again right away, most likely we'd find ourselves hitting the
5813  * same resource-exhaustion condition.
5814  */
5815  if (!assign_backendlist_entry(rw))
5816  {
5818  return false;
5819  }
5820 
5821  ereport(DEBUG1,
5822  (errmsg("starting background worker process \"%s\"",
5823  rw->rw_worker.bgw_name)));
5824 
5825 #ifdef EXEC_BACKEND
5826  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5827 #else
5828  switch ((worker_pid = fork_process()))
5829 #endif
5830  {
5831  case -1:
5832  /* in postmaster, fork failed ... */
5833  ereport(LOG,
5834  (errmsg("could not fork worker process: %m")));
5835  /* undo what assign_backendlist_entry did */
5837  rw->rw_child_slot = 0;
5838  free(rw->rw_backend);
5839  rw->rw_backend = NULL;
5840  /* mark entry as crashed, so we'll try again later */
5842  break;
5843 
5844 #ifndef EXEC_BACKEND
5845  case 0:
5846  /* in postmaster child ... */
5848 
5849  /* Close the postmaster's sockets */
5850  ClosePostmasterPorts(false);
5851 
5852  /*
5853  * Before blowing away PostmasterContext, save this bgworker's
5854  * data where it can find it.
5855  */
5858  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5859 
5860  /* Release postmaster's working memory context */
5863  PostmasterContext = NULL;
5864 
5866 
5867  exit(1); /* should not get here */
5868  break;
5869 #endif
5870  default:
5871  /* in postmaster, fork successful ... */
5872  rw->rw_pid = worker_pid;
5873  rw->rw_backend->pid = rw->rw_pid;
5875  /* add new worker to lists of backends */
5877 #ifdef EXEC_BACKEND
5878  ShmemBackendArrayAdd(rw->rw_backend);
5879 #endif
5880  return true;
5881  }
5882 
5883  return false;
5884 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:91
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
pid_t fork_process(void)
Definition: fork_process.c:32
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2559
void StartBackgroundWorker(void)
Definition: bgworker.c:680
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:439
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5935
static dlist_head BackendList
Definition: postmaster.c:186
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define ereport(elevel,...)
Definition: elog.h:144
#define free(a)
Definition: header.h:65
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:738
pid_t pid
Definition: postmaster.c:171
int errmsg(const char *fmt,...)
Definition: elog.c:824
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:46

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5372 of file postmaster.c.

Referenced by PostmasterMain().

5373 {
5374 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5139 of file postmaster.c.

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

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

5140 {
5141 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5142 
5143  /*
5144  * There is no known cause for a postmaster to become multithreaded after
5145  * startup. Recheck to account for the possibility of unknown causes.
5146  * This message uses LOG level, because an unclean shutdown at this point
5147  * would usually not look much different from a clean shutdown.
5148  */
5149  if (pthread_is_threaded_np() != 0)
5150  ereport(LOG,
5151  (errcode(ERRCODE_INTERNAL_ERROR),
5152  errmsg_internal("postmaster became multithreaded"),
5153  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5154 #endif
5155 
5156  /* should cleanup shared memory and kill all backends */
5157 
5158  /*
5159  * Not sure of the semantics here. When the Postmaster dies, should the
5160  * backends all be killed? probably not.
5161  *
5162  * MUST -- vadim 05-10-1999
5163  */
5164 
5165  proc_exit(status);
5166 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1463 of file postmaster.c.

References AllocateDir(), elog, 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().

1464 {
1465  DIR *pdir;
1466 
1467  /* Locate the postgres executable itself */
1468  if (find_my_exec(argv0, my_exec_path) < 0)
1469  elog(FATAL, "%s: could not locate my own executable path", argv0);
1470 
1471 #ifdef EXEC_BACKEND
1472  /* Locate executable backend before we change working directory */
1473  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1474  postgres_exec_path) < 0)
1475  ereport(FATAL,
1476  (errmsg("%s: could not locate matching postgres executable",
1477  argv0)));
1478 #endif
1479 
1480  /*
1481  * Locate the pkglib directory --- this has to be set early in case we try
1482  * to load any modules from it in response to postgresql.conf entries.
1483  */
1485 
1486  /*
1487  * Verify that there's a readable directory there; otherwise the Postgres
1488  * installation is incomplete or corrupt. (A typical cause of this
1489  * failure is that the postgres executable has been moved or hardlinked to
1490  * some directory that's not a sibling of the installation lib/
1491  * directory.)
1492  */
1493  pdir = AllocateDir(pkglib_path);
1494  if (pdir == NULL)
1495  ereport(ERROR,
1497  errmsg("could not open directory \"%s\": %m",
1498  pkglib_path),
1499  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1500  my_exec_path)));
1501  FreeDir(pdir);
1502 
1503  /*
1504  * XXX is it worth similarly checking the share/ directory? If the lib/
1505  * directory is there, then share/ probably is too.
1506  */
1507 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:323
static char * argv0
Definition: pg_ctl.c:97
int errhint(const char *fmt,...)
Definition: elog.c:1071
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
int errcode_for_file_access(void)
Definition: elog.c:633
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2581
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
#define PG_BACKEND_VERSIONSTR
Definition: port.h:112
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
char pkglib_path[MAXPGPATH]
Definition: globals.c:73
int FreeDir(DIR *dir)
Definition: fd.c:2699

◆ HandleChildCrash()

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

Definition at line 3473 of file postmaster.c.

References AbortStartTime, allow_immediate_pgstat_restart(), AutoVacPID, BACKEND_TYPE_BGWORKER, 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, PgStatPID, bkend::pid, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_READONLY, pmState, ReleasePostmasterChildSlot(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_pid, SendStop, Shutdown, signal_child(), SIGQUIT, SIGSTOP, slist_container, slist_foreach, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

3474 {
3475  dlist_mutable_iter iter;
3476  slist_iter siter;
3477  Backend *bp;
3478  bool take_action;
3479 
3480  /*
3481  * We only log messages and send signals if this is the first process
3482  * crash and we're not doing an immediate shutdown; otherwise, we're only
3483  * here to update postmaster's idea of live processes. If we have already
3484  * signaled children, nonzero exit status is to be expected, so don't
3485  * clutter log.
3486  */
3487  take_action = !FatalError && Shutdown != ImmediateShutdown;
3488 
3489  if (take_action)
3490  {
3491  LogChildExit(LOG, procname, pid, exitstatus);
3492  ereport(LOG,
3493  (errmsg("terminating any other active server processes")));
3494  }
3495 
3496  /* Process background workers. */
3498  {
3499  RegisteredBgWorker *rw;
3500 
3501  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3502  if (rw->rw_pid == 0)
3503  continue; /* not running */
3504  if (rw->rw_pid == pid)
3505  {
3506  /*
3507  * Found entry for freshly-dead worker, so remove it.
3508  */
3510  dlist_delete(&rw->rw_backend->elem);
3511 #ifdef EXEC_BACKEND
3512  ShmemBackendArrayRemove(rw->rw_backend);
3513 #endif
3514  free(rw->rw_backend);
3515  rw->rw_backend = NULL;
3516  rw->rw_pid = 0;
3517  rw->rw_child_slot = 0;
3518  /* don't reset crashed_at */
3519  /* don't report child stop, either */
3520  /* Keep looping so we can signal remaining workers */
3521  }
3522  else
3523  {
3524  /*
3525  * This worker is still alive. Unless we did so already, tell it
3526  * to commit hara-kiri.
3527  *
3528  * SIGQUIT is the special signal that says exit without proc_exit
3529  * and let the user know what's going on. But if SendStop is set
3530  * (-s on command line), then we send SIGSTOP instead, so that we
3531  * can get core dumps from all backends by hand.
3532  */
3533  if (take_action)
3534  {
3535  ereport(DEBUG2,
3536  (errmsg_internal("sending %s to process %d",
3537  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3538  (int) rw->rw_pid)));
3540  }
3541  }
3542  }
3543 
3544  /* Process regular backends */
3546  {
3547  bp = dlist_container(Backend, elem, iter.cur);
3548 
3549  if (bp->pid == pid)
3550  {
3551  /*
3552  * Found entry for freshly-dead backend, so remove it.
3553  */
3554  if (!bp->dead_end)
3555  {
3557 #ifdef EXEC_BACKEND
3558  ShmemBackendArrayRemove(bp);
3559 #endif
3560  }
3561  dlist_delete(iter.cur);
3562  free(bp);
3563  /* Keep looping so we can signal remaining backends */
3564  }
3565  else
3566  {
3567  /*
3568  * This backend is still alive. Unless we did so already, tell it
3569  * to commit hara-kiri.
3570  *
3571  * SIGQUIT is the special signal that says exit without proc_exit
3572  * and let the user know what's going on. But if SendStop is set
3573  * (-s on command line), then we send SIGSTOP instead, so that we
3574  * can get core dumps from all backends by hand.
3575  *
3576  * We could exclude dead_end children here, but at least in the
3577  * SIGSTOP case it seems better to include them.
3578  *
3579  * Background workers were already processed above; ignore them
3580  * here.
3581  */
3582  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3583  continue;
3584 
3585  if (take_action)
3586  {
3587  ereport(DEBUG2,
3588  (errmsg_internal("sending %s to process %d",
3589  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3590  (int) bp->pid)));
3591  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3592  }
3593  }
3594  }
3595 
3596  /* Take care of the startup process too */
3597  if (pid == StartupPID)
3598  {
3599  StartupPID = 0;
3600  /* Caller adjusts StartupStatus, so don't touch it here */
3601  }
3602  else if (StartupPID != 0 && take_action)
3603  {
3604  ereport(DEBUG2,
3605  (errmsg_internal("sending %s to process %d",
3606  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3607  (int) StartupPID)));
3610  }
3611 
3612  /* Take care of the bgwriter too */
3613  if (pid == BgWriterPID)
3614  BgWriterPID = 0;
3615  else if (BgWriterPID != 0 && take_action)
3616  {
3617  ereport(DEBUG2,
3618  (errmsg_internal("sending %s to process %d",
3619  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3620  (int) BgWriterPID)));
3622  }
3623 
3624  /* Take care of the checkpointer too */
3625  if (pid == CheckpointerPID)
3626  CheckpointerPID = 0;
3627  else if (CheckpointerPID != 0 && take_action)
3628  {
3629  ereport(DEBUG2,
3630  (errmsg_internal("sending %s to process %d",
3631  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3632  (int) CheckpointerPID)));
3634  }
3635 
3636  /* Take care of the walwriter too */
3637  if (pid == WalWriterPID)
3638  WalWriterPID = 0;
3639  else if (WalWriterPID != 0 && take_action)
3640  {
3641  ereport(DEBUG2,
3642  (errmsg_internal("sending %s to process %d",
3643  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3644  (int) WalWriterPID)));
3646  }
3647 
3648  /* Take care of the walreceiver too */
3649  if (pid == WalReceiverPID)
3650  WalReceiverPID = 0;
3651  else if (WalReceiverPID != 0 && take_action)
3652  {
3653  ereport(DEBUG2,
3654  (errmsg_internal("sending %s to process %d",
3655  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3656  (int) WalReceiverPID)));
3658  }
3659 
3660  /* Take care of the autovacuum launcher too */
3661  if (pid == AutoVacPID)
3662  AutoVacPID = 0;
3663  else if (AutoVacPID != 0 && take_action)
3664  {
3665  ereport(DEBUG2,
3666  (errmsg_internal("sending %s to process %d",
3667  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3668  (int) AutoVacPID)));
3670  }
3671 
3672  /*
3673  * Force a power-cycle of the pgarch process too. (This isn't absolutely
3674  * necessary, but it seems like a good idea for robustness, and it
3675  * simplifies the state-machine logic in the case where a shutdown request
3676  * arrives during crash processing.)
3677  */
3678  if (PgArchPID != 0 && take_action)
3679  {
3680  ereport(DEBUG2,
3681  (errmsg_internal("sending %s to process %d",
3682  "SIGQUIT",
3683  (int) PgArchPID)));
3685  }
3686 
3687  /*
3688  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3689  * necessary, but it seems like a good idea for robustness, and it
3690  * simplifies the state-machine logic in the case where a shutdown request
3691  * arrives during crash processing.)
3692  */
3693  if (PgStatPID != 0 && take_action)
3694  {
3695  ereport(DEBUG2,
3696  (errmsg_internal("sending %s to process %d",
3697  "SIGQUIT",
3698  (int) PgStatPID)));
3701  }
3702 
3703  /* We do NOT restart the syslogger */
3704 
3705  if (Shutdown != ImmediateShutdown)
3706  FatalError = true;
3707 
3708  /* We now transit into a state of waiting for children to die */
3709  if (pmState == PM_RECOVERY ||
3710  pmState == PM_HOT_STANDBY ||
3711  pmState == PM_RUN ||
3712  pmState == PM_WAIT_BACKUP ||
3714  pmState == PM_SHUTDOWN)
3716 
3717  /*
3718  * .. and if this doesn't happen quickly enough, now the clock is ticking
3719  * for us to kill them without mercy.
3720  */
3721  if (AbortStartTime == 0)
3722  AbortStartTime = time(NULL);
3723 }
struct bkend * rw_backend
#define SIGQUIT
Definition: win32_port.h:154
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static pid_t PgStatPID
Definition: postmaster.c:257
slist_node * cur
Definition: ilist.h:226
static pid_t CheckpointerPID
Definition: postmaster.c:252
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool FatalError
Definition: postmaster.c:279
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
#define SIGSTOP
Definition: win32_port.h:160
static int Shutdown
Definition: postmaster.c:277
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static pid_t BgWriterPID
Definition: postmaster.c:251
static pid_t StartupPID
Definition: postmaster.c:250
static dlist_head BackendList
Definition: postmaster.c:186
slist_head BackgroundWorkerList
Definition: bgworker.c:42
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:181
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4044
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
static PMState pmState
Definition: postmaster.c:341
#define ImmediateShutdown
Definition: postmaster.c:275
#define ereport(elevel,...)
Definition: elog.h:144
#define free(a)
Definition: header.h:65
static pid_t WalWriterPID
Definition: postmaster.c:253
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
pid_t pid
Definition: postmaster.c:171
static pid_t AutoVacPID
Definition: postmaster.c:255
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3729
static int SendStop
Definition: postmaster.c:233
static time_t AbortStartTime
Definition: postmaster.c:345
void allow_immediate_pgstat_restart(void)
Definition: pgstat.c:817
static pid_t PgArchPID
Definition: postmaster.c:256

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1883 of file postmaster.c.

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

Referenced by ServerLoop().

1884 {
1885  int maxsock = -1;
1886  int i;
1887 
1888  FD_ZERO(rmask);
1889 
1890  for (i = 0; i < MAXLISTEN; i++)
1891  {
1892  int fd = ListenSocket[i];
1893 
1894  if (fd == PGINVALID_SOCKET)
1895  break;
1896  FD_SET(fd, rmask);
1897 
1898  if (fd > maxsock)
1899  maxsock = fd;
1900  }
1901 
1902  return maxsock + 1;
1903 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
int i
#define MAXLISTEN
Definition: postmaster.c:217

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6602 of file postmaster.c.

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

6603 {
6604 #ifndef WIN32
6605 
6606  /*
6607  * Create a pipe. Postmaster holds the write end of the pipe open
6608  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6609  * the read file descriptor to select() to wake up in case postmaster
6610  * dies, or check for postmaster death with a (read() == 0). Children must
6611  * close the write end as soon as possible after forking, because EOF
6612  * won't be signaled in the read end until all processes have closed the
6613  * write fd. That is taken care of in ClosePostmasterPorts().
6614  */
6616  if (pipe(postmaster_alive_fds) < 0)
6617  ereport(FATAL,
6619  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6620 
6621  /* Notify fd.c that we've eaten two FDs for the pipe. */
6624 
6625  /*
6626  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6627  * call.
6628  */
6629  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6630  ereport(FATAL,
6632  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6633 #else
6634 
6635  /*
6636  * On Windows, we use a process handle for the same purpose.
6637  */
6638  if (DuplicateHandle(GetCurrentProcess(),
6639  GetCurrentProcess(),
6640  GetCurrentProcess(),
6641  &PostmasterHandle,
6642  0,
6643  TRUE,
6644  DUPLICATE_SAME_ACCESS) == 0)
6645  ereport(FATAL,
6646  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6647  GetLastError())));
6648 #endif /* WIN32 */
6649 }
int MyProcPid
Definition: globals.c:40
#define FATAL
Definition: elog.h:52
void ReserveExternalFD(void)
Definition: fd.c:1080
int errcode_for_file_access(void)
Definition: elog.c:633
int errcode_for_socket_access(void)
Definition: elog.c:704
pid_t PostmasterPid
Definition: globals.c:95
int postmaster_alive_fds[2]
Definition: postmaster.c:557
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
#define Assert(condition)
Definition: c.h:738
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2623 of file postmaster.c.

References GetCurrentTimestamp(), MyProcPid, MyStartTime, MyStartTimestamp, pg_strong_random(), srandom(), and timestamptz_to_time_t().

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

2624 {
2625  unsigned int rseed;
2626 
2627  MyProcPid = getpid();
2630 
2631  /*
2632  * Set a different seed for random() in every process. We want something
2633  * unpredictable, so if possible, use high-quality random bits for the
2634  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2635  */
2636  if (!pg_strong_random(&rseed, sizeof(rseed)))
2637  {
2638  /*
2639  * Since PIDs and timestamps tend to change more frequently in their
2640  * least significant bits, shift the timestamp left to allow a larger
2641  * total number of seeds in a given time period. Since that would
2642  * leave only 20 bits of the timestamp that cycle every ~1 second,
2643  * also mix in some higher bits.
2644  */
2645  rseed = ((uint64) MyProcPid) ^
2646  ((uint64) MyStartTimestamp << 12) ^
2647  ((uint64) MyStartTimestamp >> 20);
2648  }
2649  srandom(rseed);
2650 }
int MyProcPid
Definition: globals.c:40
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
pg_time_t MyStartTime
Definition: globals.c:41
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1716
TimestampTz MyStartTimestamp
Definition: globals.c:42
bool pg_strong_random(void *buf, size_t len)
void srandom(unsigned int seed)
Definition: srandom.c:22

◆ LogChildExit()

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

Definition at line 3729 of file postmaster.c.

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

3730 {
3731  /*
3732  * size of activity_buffer is arbitrary, but set equal to default
3733  * track_activity_query_size
3734  */
3735  char activity_buffer[1024];
3736  const char *activity = NULL;
3737 
3738  if (!EXIT_STATUS_0(exitstatus))
3739  activity = pgstat_get_crashed_backend_activity(pid,
3740  activity_buffer,
3741  sizeof(activity_buffer));
3742 
3743  if (WIFEXITED(exitstatus))
3744  ereport(lev,
3745 
3746  /*------
3747  translator: %s is a noun phrase describing a child process, such as
3748  "server process" */
3749  (errmsg("%s (PID %d) exited with exit code %d",
3750  procname, pid, WEXITSTATUS(exitstatus)),
3751  activity ? errdetail("Failed process was running: %s", activity) : 0));
3752  else if (WIFSIGNALED(exitstatus))
3753  {
3754 #if defined(WIN32)
3755  ereport(lev,
3756 
3757  /*------
3758  translator: %s is a noun phrase describing a child process, such as
3759  "server process" */
3760  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3761  procname, pid, WTERMSIG(exitstatus)),
3762  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3763  activity ? errdetail("Failed process was running: %s", activity) : 0));
3764 #else
3765  ereport(lev,
3766 
3767  /*------
3768  translator: %s is a noun phrase describing a child process, such as
3769  "server process" */
3770  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3771  procname, pid, WTERMSIG(exitstatus),
3772  pg_strsignal(WTERMSIG(exitstatus))),
3773  activity ? errdetail("Failed process was running: %s", activity) : 0));
3774 #endif
3775  }
3776  else
3777  ereport(lev,
3778 
3779  /*------
3780  translator: %s is a noun phrase describing a child process, such as
3781  "server process" */
3782  (errmsg("%s (PID %d) exited with unrecognized status %d",
3783  procname, pid, exitstatus),
3784  activity ? errdetail("Failed process was running: %s", activity) : 0));
3785 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define WTERMSIG(w)
Definition: win32_port.h:140
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define WIFEXITED(w)
Definition: win32_port.h:137
#define ereport(elevel,...)
Definition: elog.h:144
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:824
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
Definition: pgstat.c:4247
#define WIFSIGNALED(w)
Definition: win32_port.h:138
#define WEXITSTATUS(w)
Definition: win32_port.h:139
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5701 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5702 {
5703  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5705 }
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:132
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:133

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 5999 of file postmaster.c.

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

6000 {
6001 #define MAX_BGWORKERS_TO_LAUNCH 100
6002  int num_launched = 0;
6003  TimestampTz now = 0;
6004  slist_mutable_iter iter;
6005 
6006  /*
6007  * During crash recovery, we have no need to be called until the state
6008  * transition out of recovery.
6009  */
6010  if (FatalError)
6011  {
6012  StartWorkerNeeded = false;
6013  HaveCrashedWorker = false;
6014  return;
6015  }
6016 
6017  /* Don't need to be called again unless we find a reason for it below */
6018  StartWorkerNeeded = false;
6019  HaveCrashedWorker = false;
6020 
6022  {
6023  RegisteredBgWorker *rw;
6024 
6025  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
6026 
6027  /* ignore if already running */
6028  if (rw->rw_pid != 0)
6029  continue;
6030 
6031  /* if marked for death, clean up and remove from list */
6032  if (rw->rw_terminate)
6033  {
6034  ForgetBackgroundWorker(&iter);
6035  continue;
6036  }
6037 
6038  /*
6039  * If this worker has crashed previously, maybe it needs to be
6040  * restarted (unless on registration it specified it doesn't want to
6041  * be restarted at all). Check how long ago did a crash last happen.
6042  * If the last crash is too recent, don't start it right away; let it
6043  * be restarted once enough time has passed.
6044  */
6045  if (rw->rw_crashed_at != 0)
6046  {
6048  {
6049  int notify_pid;
6050 
6051  notify_pid = rw->rw_worker.bgw_notify_pid;
6052 
6053  ForgetBackgroundWorker(&iter);
6054 
6055  /* Report worker is gone now. */
6056  if (notify_pid != 0)
6057  kill(notify_pid, SIGUSR1);
6058 
6059  continue;
6060  }
6061 
6062  /* read system time only when needed */
6063  if (now == 0)
6064  now = GetCurrentTimestamp();
6065 
6067  rw->rw_worker.bgw_restart_time * 1000))
6068  {
6069  /* Set flag to remember that we have workers to start later */
6070  HaveCrashedWorker = true;
6071  continue;
6072  }
6073  }
6074 
6076  {
6077  /* reset crash time before trying to start worker */
6078  rw->rw_crashed_at = 0;
6079 
6080  /*
6081  * Try to start the worker.
6082  *
6083  * On failure, give up processing workers for now, but set
6084  * StartWorkerNeeded so we'll come back here on the next iteration
6085  * of ServerLoop to try again. (We don't want to wait, because
6086  * there might be additional ready-to-run workers.) We could set
6087  * HaveCrashedWorker as well, since this worker is now marked
6088  * crashed, but there's no need because the next run of this
6089  * function will do that.
6090  */
6091  if (!do_start_bgworker(rw))
6092  {
6093  StartWorkerNeeded = true;
6094  return;
6095  }
6096 
6097  /*
6098  * If we've launched as many workers as allowed, quit, but have
6099  * ServerLoop call us again to look for additional ready-to-run
6100  * workers. There might not be any, but we'll find out the next
6101  * time we run.
6102  */
6103  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
6104  {
6105  StartWorkerNeeded = true;
6106  return;
6107  }
6108  }
6109  }
6110 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:367
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5891
#define SIGUSR1
Definition: win32_port.h:165
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int64 TimestampTz
Definition: timestamp.h:39
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:94
#define kill(pid, sig)
Definition: win32_port.h:426
static bool FatalError
Definition: postmaster.c:279
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1673
static volatile bool HaveCrashedWorker
Definition: postmaster.c:368
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:411
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5799
#define MAX_BGWORKERS_TO_LAUNCH
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
pid_t bgw_notify_pid
Definition: bgworker.h:99
BackgroundWorker rw_worker
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5642 of file postmaster.c.

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

Referenced by ServerLoop(), and sigusr1_handler().

5643 {
5644  if (WalReceiverPID == 0 &&
5645  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5647  Shutdown == NoShutdown)
5648  {
5650  if (WalReceiverPID != 0)
5651  WalReceiverRequested = false;
5652  /* else leave the flag set, so we'll try again later */
5653  }
5654 }
static pid_t WalReceiverPID
Definition: postmaster.c:254
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:364
static int Shutdown
Definition: postmaster.c:277
static PMState pmState
Definition: postmaster.c:341
#define NoShutdown
Definition: postmaster.c:272
#define StartWalReceiver()
Definition: postmaster.c:545

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2756 of file postmaster.c.

References AbortStartTime, AddToDataDirLockFile(), AutoVacPID, BACKEND_TYPE_AUTOVAC, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, BgWriterPID, BlockSig, 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_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_READONLY, pmState, PostmasterStateMachine(), Shutdown, signal_child(), SignalSomeChildren(), SIGQUIT, SmartShutdown, StartupPID, TerminateChildren(), UnBlockSig, WalReceiverPID, and WalWriterPID.

Referenced by PostmasterMain().

2757 {
2758  int save_errno = errno;
2759 
2760  /*
2761  * We rely on the signal mechanism to have blocked all signals ... except
2762  * on Windows, which lacks sigaction(), so we have to do it manually.
2763  */
2764 #ifdef WIN32
2765  PG_SETMASK(&BlockSig);
2766 #endif
2767 
2768  ereport(DEBUG2,
2769  (errmsg_internal("postmaster received signal %d",
2770  postgres_signal_arg)));
2771 
2772  switch (postgres_signal_arg)
2773  {
2774  case SIGTERM:
2775 
2776  /*
2777  * Smart Shutdown:
2778  *
2779  * Wait for children to end their work, then shut down.
2780  */
2781  if (Shutdown >= SmartShutdown)
2782  break;
2784  ereport(LOG,
2785  (errmsg("received smart shutdown request")));
2786 
2787  /* Report status */
2789 #ifdef USE_SYSTEMD
2790  sd_notify(0, "STOPPING=1");
2791 #endif
2792 
2793  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2795  {
2796  /* autovac workers are told to shut down immediately */
2797  /* and bgworkers too; does this need tweaking? */
2798  SignalSomeChildren(SIGTERM,
2800  /* and the autovac launcher too */
2801  if (AutoVacPID != 0)
2802  signal_child(AutoVacPID, SIGTERM);
2803  /* and the bgwriter too */
2804  if (BgWriterPID != 0)
2805  signal_child(BgWriterPID, SIGTERM);
2806  /* and the walwriter too */
2807  if (WalWriterPID != 0)
2808  signal_child(WalWriterPID, SIGTERM);
2809 
2810  /*
2811  * If we're in recovery, we can't kill the startup process
2812  * right away, because at present doing so does not release
2813  * its locks. We might want to change this in a future
2814  * release. For the time being, the PM_WAIT_READONLY state
2815  * indicates that we're waiting for the regular (read only)
2816  * backends to die off; once they do, we'll kill the startup
2817  * and walreceiver processes.
2818  */
2819  pmState = (pmState == PM_RUN) ?
2821  }
2822 
2823  /*
2824  * Now wait for online backup mode to end and backends to exit. If
2825  * that is already the case, PostmasterStateMachine will take the
2826  * next step.
2827  */
2829  break;
2830 
2831  case SIGINT:
2832 
2833  /*
2834  * Fast Shutdown:
2835  *
2836  * Abort all children with SIGTERM (rollback active transactions
2837  * and exit) and shut down when they are gone.
2838  */
2839  if (Shutdown >= FastShutdown)
2840  break;
2842  ereport(LOG,
2843  (errmsg("received fast shutdown request")));
2844 
2845  /* Report status */
2847 #ifdef USE_SYSTEMD
2848  sd_notify(0, "STOPPING=1");
2849 #endif
2850 
2851  if (StartupPID != 0)
2852  signal_child(StartupPID, SIGTERM);
2853  if (BgWriterPID != 0)
2854  signal_child(BgWriterPID, SIGTERM);
2855  if (WalReceiverPID != 0)
2856  signal_child(WalReceiverPID, SIGTERM);
2857  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2858  {
2860 
2861  /*
2862  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2863  * and/or checkpointer should be active in this state; we just
2864  * signaled the first four, and we don't want to kill
2865  * checkpointer yet.
2866  */
2868  }
2869  else if (pmState == PM_RUN ||
2870  pmState == PM_WAIT_BACKUP ||
2874  {
2875  ereport(LOG,
2876  (errmsg("aborting any active transactions")));
2877  /* shut down all backends and workers */
2878  SignalSomeChildren(SIGTERM,
2881  /* and the autovac launcher too */
2882  if (AutoVacPID != 0)
2883  signal_child(AutoVacPID, SIGTERM);
2884  /* and the walwriter too */
2885  if (WalWriterPID != 0)
2886  signal_child(WalWriterPID, SIGTERM);
2888  }
2889 
2890  /*
2891  * Now wait for backends to exit. If there are none,
2892  * PostmasterStateMachine will take the next step.
2893  */
2895  break;
2896 
2897  case SIGQUIT:
2898 
2899  /*
2900  * Immediate Shutdown:
2901  *
2902  * abort all children with SIGQUIT, wait for them to exit,
2903  * terminate remaining ones with SIGKILL, then exit without
2904  * attempt to properly shut down the data base system.
2905  */
2906  if (Shutdown >= ImmediateShutdown)
2907  break;
2909  ereport(LOG,
2910  (errmsg("received immediate shutdown request")));
2911 
2912  /* Report status */
2914 #ifdef USE_SYSTEMD
2915  sd_notify(0, "STOPPING=1");
2916 #endif
2917 
2920 
2921  /* set stopwatch for them to die */
2922  AbortStartTime = time(NULL);
2923 
2924  /*
2925  * Now wait for backends to exit. If there are none,
2926  * PostmasterStateMachine will take the next step.
2927  */
2929  break;
2930  }
2931 
2932 #ifdef WIN32
2934 #endif
2935 
2936  errno = save_errno;
2937 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3794
#define SIGQUIT
Definition: win32_port.h:154
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1301
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4070
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define LOG
Definition: elog.h:26
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:146
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:277
static pid_t BgWriterPID
Definition: postmaster.c:251
static pid_t StartupPID
Definition: postmaster.c:250
#define SmartShutdown
Definition: postmaster.c:273
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4114
#define FastShutdown
Definition: postmaster.c:274
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4044
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:341
#define ImmediateShutdown
Definition: postmaster.c:275
#define ereport(elevel,...)
Definition: elog.h:144
static pid_t WalWriterPID
Definition: postmaster.c:253
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
static pid_t AutoVacPID
Definition: postmaster.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
static time_t AbortStartTime
Definition: postmaster.c:345

◆ PostmasterMain()

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

Definition at line 567 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), DEBUG3, DestNone, dummy_handler(), elog, enable_bonjour, EnableSSL, environ, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, ExtraOptions, FATAL, fprintf, free, get_stats_option_name(), GetConfigOption(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), i, InitializeGUCOptions(), InitializeMaxBackends(), 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, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, PM_STATUS_STARTING, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal_pm(), process_shared_preload_libraries(), 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, snprintf, SplitDirectoriesString(), SplitGUCList(), 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().

568 {
569  int opt;
570  int status;
571  char *userDoption = NULL;
572  bool listen_addr_saved = false;
573  int i;
574  char *output_config_variable = NULL;
575 
577 
579 
581 
582  /*
583  * We should not be creating any files or directories before we check the
584  * data directory (see checkDataDir()), but just in case set the umask to
585  * the most restrictive (owner-only) permissions.
586  *
587  * checkDataDir() will reset the umask based on the data directory
588  * permissions.
589  */
590  umask(PG_MODE_MASK_OWNER);
591 
592  /*
593  * By default, palloc() requests in the postmaster will be allocated in
594  * the PostmasterContext, which is space that can be recycled by backends.
595  * Allocated data that needs to be available to backends should be
596  * allocated in TopMemoryContext.
597  */
599  "Postmaster",
602 
603  /* Initialize paths to installation files */
604  getInstallationPaths(argv[0]);
605 
606  /*
607  * Set up signal handlers for the postmaster process.
608  *
609  * In the postmaster, we use pqsignal_pm() rather than pqsignal() (which
610  * is used by all child processes and client processes). That has a
611  * couple of special behaviors:
612  *
613  * 1. Except on Windows, we tell sigaction() to block all signals for the
614  * duration of the signal handler. This is faster than our old approach
615  * of blocking/unblocking explicitly in the signal handler, and it should
616  * also prevent excessive stack consumption if signals arrive quickly.
617  *
618  * 2. We do not set the SA_RESTART flag. This is because signals will be
619  * blocked at all times except when ServerLoop is waiting for something to
620  * happen, and during that window, we want signals to exit the select(2)
621  * wait so that ServerLoop can respond if anything interesting happened.
622  * On some platforms, signals marked SA_RESTART would not cause the
623  * select() wait to end.
624  *
625  * Child processes will generally want SA_RESTART, so pqsignal() sets that
626  * flag. We expect children to set up their own handlers before
627  * unblocking signals.
628  *
629  * CAUTION: when changing this list, check for side-effects on the signal
630  * handling setup of child processes. See tcop/postgres.c,
631  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
632  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
633  * postmaster/syslogger.c, postmaster/bgworker.c and
634  * postmaster/checkpointer.c.
635  */
636  pqinitmask();
638 
639  pqsignal_pm(SIGHUP, SIGHUP_handler); /* reread config file and have
640  * children do same */
641  pqsignal_pm(SIGINT, pmdie); /* send SIGTERM and shut down */
642  pqsignal_pm(SIGQUIT, pmdie); /* send SIGQUIT and die */
643  pqsignal_pm(SIGTERM, pmdie); /* wait for children and shut down */
644  pqsignal_pm(SIGALRM, SIG_IGN); /* ignored */
645  pqsignal_pm(SIGPIPE, SIG_IGN); /* ignored */
646  pqsignal_pm(SIGUSR1, sigusr1_handler); /* message from child process */
647  pqsignal_pm(SIGUSR2, dummy_handler); /* unused, reserve for children */
648  pqsignal_pm(SIGCHLD, reaper); /* handle child termination */
649 
650  /*
651  * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
652  * ignore those signals in a postmaster environment, so that there is no
653  * risk of a child process freezing up due to writing to stderr. But for
654  * a standalone backend, their default handling is reasonable. Hence, all
655  * child processes should just allow the inherited settings to stand.
656  */
657 #ifdef SIGTTIN
658  pqsignal_pm(SIGTTIN, SIG_IGN); /* ignored */
659 #endif
660 #ifdef SIGTTOU
661  pqsignal_pm(SIGTTOU, SIG_IGN); /* ignored */
662 #endif
663 
664  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
665 #ifdef SIGXFSZ
666  pqsignal_pm(SIGXFSZ, SIG_IGN); /* ignored */
667 #endif
668 
669  /*
670  * Options setup
671  */
673 
674  opterr = 1;
675 
676  /*
677  * Parse command-line options. CAUTION: keep this in sync with
678  * tcop/postgres.c (the option sets should not conflict) and with the
679  * common help() function in main/main.c.
680  */
681  while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
682  {
683  switch (opt)
684  {
685  case 'B':
686  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
687  break;
688 
689  case 'b':
690  /* Undocumented flag used for binary upgrades */
691  IsBinaryUpgrade = true;
692  break;
693 
694  case 'C':
695  output_config_variable = strdup(optarg);
696  break;
697 
698  case 'D':
699  userDoption = strdup(optarg);
700  break;
701 
702  case 'd':
704  break;
705 
706  case 'E':
707  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
708  break;
709 
710  case 'e':
711  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
712  break;
713 
714  case 'F':
715  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
716  break;
717 
718  case 'f':
720  {
721  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
722  progname, optarg);
723  ExitPostmaster(1);
724  }
725  break;
726 
727  case 'h':
728  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
729  break;
730 
731  case 'i':
732  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
733  break;
734 
735  case 'j':
736  /* only used by interactive backend */
737  break;
738 
739  case 'k':
740  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
741  break;
742 
743  case 'l':
744  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
745  break;
746 
747  case 'N':
748  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
749  break;
750 
751  case 'n':
752  /* Don't reinit shared mem after abnormal exit */
753  Reinit = false;
754  break;
755 
756  case 'O':
757  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
758  break;
759 
760  case 'o':
761  /* Other options to pass to the backend on the command line */
763  sizeof(ExtraOptions) - strlen(ExtraOptions),
764  " %s", optarg);
765  break;
766 
767  case 'P':
768  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
769  break;
770 
771  case 'p':
773  break;
774 
775  case 'r':
776  /* only used by single-user backend */
777  break;
778 
779  case 'S':
781  break;
782 
783  case 's':
784  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
785  break;
786 
787  case 'T':
788 
789  /*
790  * In the event that some backend dumps core, send SIGSTOP,
791  * rather than SIGQUIT, to all its peers. This lets the wily
792  * post_hacker collect core dumps from everyone.
793  */
794  SendStop = true;
795  break;
796 
797  case 't':
798  {
799  const char *tmp = get_stats_option_name(optarg);
800 
801  if (tmp)
802  {
804  }
805  else
806  {
807  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
808  progname, optarg);
809  ExitPostmaster(1);
810  }
811  break;
812  }
813 
814  case 'W':
815  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
816  break;
817 
818  case 'c':
819  case '-':
820  {
821  char *name,
822  *value;
823 
824  ParseLongOption(optarg, &name, &value);
825  if (!value)
826  {
827  if (opt == '-')
828  ereport(ERROR,
829  (errcode(ERRCODE_SYNTAX_ERROR),
830  errmsg("--%s requires a value",
831  optarg)));
832  else
833  ereport(ERROR,
834  (errcode(ERRCODE_SYNTAX_ERROR),
835  errmsg("-c %s requires a value",
836  optarg)));
837  }
838 
840  free(name);
841  if (value)
842  free(value);
843  break;
844  }
845 
846  default:
847  write_stderr("Try \"%s --help\" for more information.\n",
848  progname);
849  ExitPostmaster(1);
850  }
851  }
852 
853  /*
854  * Postmaster accepts no non-option switch arguments.
855  */
856  if (optind < argc)
857  {
858  write_stderr("%s: invalid argument: \"%s\"\n",
859  progname, argv[optind]);
860  write_stderr("Try \"%s --help\" for more information.\n",
861  progname);
862  ExitPostmaster(1);
863  }
864 
865  /*
866  * Locate the proper configuration files and data directory, and read
867  * postgresql.conf for the first time.
868  */
869  if (!SelectConfigFiles(userDoption, progname))
870  ExitPostmaster(2);
871 
872  if (output_config_variable != NULL)
873  {
874  /*
875  * "-C guc" was specified, so print GUC's value and exit. No extra
876  * permission check is needed because the user is reading inside the
877  * data dir.
878  */
879  const char *config_val = GetConfigOption(output_config_variable,
880  false, false);
881 
882  puts(config_val ? config_val : "");
883  ExitPostmaster(0);
884  }
885 
886  /* Verify that DataDir looks reasonable */
887  checkDataDir();
888 
889  /* Check that pg_control exists */
891 
892  /* And switch working directory into it */
893  ChangeToDataDir();
894 
895  /*
896  * Check for invalid combinations of GUC settings.
897  */
899  {
900  write_stderr("%s: superuser_reserved_connections (%d) must be less than max_connections (%d)\n",
901  progname,
903  ExitPostmaster(1);
904  }
906  ereport(ERROR,
907  (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
909  ereport(ERROR,
910  (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
911 
912  /*
913  * Other one-time internal sanity checks can go here, if they are fast.
914  * (Put any slow processing further down, after postmaster.pid creation.)
915  */
916  if (!CheckDateTokenTables())
917  {
918  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
919  ExitPostmaster(1);
920  }
921 
922  /*
923  * Now that we are done processing the postmaster arguments, reset
924  * getopt(3) library so that it will work correctly in subprocesses.
925  */
926  optind = 1;
927 #ifdef HAVE_INT_OPTRESET
928  optreset = 1; /* some systems need this too */
929 #endif
930 
931  /* For debugging: display postmaster environment */
932  {
933  extern char **environ;
934  char **p;
935 
936  ereport(DEBUG3,
937  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
938  progname)));
939  ereport(DEBUG3,
940  (errmsg_internal("-----------------------------------------")));
941  for (p = environ; *p; ++p)
942  ereport(DEBUG3,
943  (errmsg_internal("\t%s", *p)));
944  ereport(DEBUG3,
945  (errmsg_internal("-----------------------------------------")));
946  }
947 
948  /*
949  * Create lockfile for data directory.
950  *
951  * We want to do this before we try to grab the input sockets, because the
952  * data directory interlock is more reliable than the socket-file
953  * interlock (thanks to whoever decided to put socket files in /tmp :-().
954  * For the same reason, it's best to grab the TCP socket(s) before the
955  * Unix socket(s).
956  *
957  * Also note that this internally sets up the on_proc_exit function that
958  * is responsible for removing both data directory and socket lockfiles;
959  * so it must happen before opening sockets so that at exit, the socket
960  * lockfiles go away after CloseServerPorts runs.
961  */
962  CreateDataDirLockFile(true);
963 
964  /*
965  * Read the control file (for error checking and config info).
966  *
967  * Since we verify the control file's CRC, this has a useful side effect
968  * on machines where we need a run-time test for CRC support instructions.
969  * The postmaster will do the test once at startup, and then its child
970  * processes will inherit the correct function pointer and not need to
971  * repeat the test.
972  */
974 
975  /*
976  * Register the apply launcher. Since it registers a background worker,
977  * it needs to be called before InitializeMaxBackends(), and it's probably
978  * a good idea to call it before any modules had chance to take the
979  * background worker slots.
980  */
982 
983  /*
984  * process any libraries that should be preloaded at postmaster start
985  */
987 
988  /*
989  * Initialize SSL library, if specified.
990  */
991 #ifdef USE_SSL
992  if (EnableSSL)
993  {
994  (void) secure_initialize(true);
995  LoadedSSL = true;
996  }
997 #endif
998 
999  /*
1000  * Now that loadable modules have had their chance to register background
1001  * workers, calculate MaxBackends.
1002  */
1004 
1005  /*
1006  * Set up shared memory and semaphores.
1007  */
1008  reset_shared();
1009 
1010  /*
1011  * Estimate number of openable files. This must happen after setting up
1012  * semaphores, because on some platforms semaphores count as open files.
1013  */
1014  set_max_safe_fds();
1015 
1016  /*
1017  * Set reference point for stack-depth checking.
1018  */
1019  set_stack_base();
1020 
1021  /*
1022  * Initialize pipe (or process handle on Windows) that allows children to
1023  * wake up from sleep on postmaster death.
1024  */
1026 
1027 #ifdef WIN32
1028 
1029  /*
1030  * Initialize I/O completion port used to deliver list of dead children.
1031  */
1032  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1033  if (win32ChildQueue == NULL)
1034  ereport(FATAL,
1035  (errmsg("could not create I/O completion port for child queue")));
1036 #endif
1037 
1038 #ifdef EXEC_BACKEND
1039  /* Write out nondefault GUC settings for child processes to use */
1040  write_nondefault_variables(PGC_POSTMASTER);
1041 
1042  /*
1043  * Clean out the temp directory used to transmit parameters to child
1044  * processes (see internal_forkexec, below). We must do this before
1045  * launching any child processes, else we have a race condition: we could
1046  * remove a parameter file before the child can read it. It should be
1047  * safe to do so now, because we verified earlier that there are no
1048  * conflicting Postgres processes in this data directory.
1049  */
1051 #endif
1052 
1053  /*
1054  * Forcibly remove the files signaling a standby promotion request.
1055  * Otherwise, the existence of those files triggers a promotion too early,
1056  * whether a user wants that or not.
1057  *
1058  * This removal of files is usually unnecessary because they can exist
1059  * only during a few moments during a standby promotion. However there is
1060  * a race condition: if pg_ctl promote is executed and creates the files
1061  * during a promotion, the files can stay around even after the server is
1062  * brought up to new master. Then, if new standby starts by using the
1063  * backup taken from that master, the files can exist at the server
1064  * startup and should be removed in order to avoid an unexpected
1065  * promotion.
1066  *
1067  * Note that promotion signal files need to be removed before the startup
1068  * process is invoked. Because, after that, they can be used by
1069  * postmaster's SIGUSR1 signal handler.
1070  */
1072 
1073  /* Do the same for logrotate signal file */
1075 
1076  /* Remove any outdated file holding the current log filenames. */
1077  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1078  ereport(LOG,
1080  errmsg("could not remove file \"%s\": %m",
1082 
1083  /*
1084  * If enabled, start up syslogger collection subprocess
1085  */
1087 
1088  /*
1089  * Reset whereToSendOutput from DestDebug (its starting state) to
1090  * DestNone. This stops ereport from sending log messages to stderr unless
1091  * Log_destination permits. We don't do this until the postmaster is
1092  * fully launched, since startup failures may as well be reported to
1093  * stderr.
1094  *
1095  * If we are in fact disabling logging to stderr, first emit a log message
1096  * saying so, to provide a breadcrumb trail for users who may not remember
1097  * that their logging is configured to go somewhere else.
1098  */
1100  ereport(LOG,
1101  (errmsg("ending log output to stderr"),
1102  errhint("Future log output will go to log destination \"%s\".",
1104 
1106 
1107  /*
1108  * Report server startup in log. While we could emit this much earlier,
1109  * it seems best to do so after starting the log collector, if we intend
1110  * to use one.
1111  */
1112  ereport(LOG,
1113  (errmsg("starting %s", PG_VERSION_STR)));
1114 
1115  /*
1116  * Establish input sockets.
1117  *
1118  * First, mark them all closed, and set up an on_proc_exit function that's
1119  * charged with closing the sockets again at postmaster shutdown.
1120  */
1121  for (i = 0; i < MAXLISTEN; i++)
1123 
1125 
1126  if (ListenAddresses)
1127  {
1128  char *rawstring;
1129  List *elemlist;
1130  ListCell *l;
1131  int success = 0;
1132 
1133  /* Need a modifiable copy of ListenAddresses */
1134  rawstring = pstrdup(ListenAddresses);
1135 
1136  /* Parse string into list of hostnames */
1137  if (!SplitGUCList(rawstring, ',', &elemlist))
1138  {
1139  /* syntax error in list */
1140  ereport(FATAL,
1141  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1142  errmsg("invalid list syntax in parameter \"%s\"",
1143  "listen_addresses")));
1144  }
1145 
1146  foreach(l, elemlist)
1147  {
1148  char *curhost = (char *) lfirst(l);
1149 
1150  if (strcmp(curhost, "*") == 0)
1151  status = StreamServerPort(AF_UNSPEC, NULL,
1152  (unsigned short) PostPortNumber,
1153  NULL,
1155  else
1156  status = StreamServerPort(AF_UNSPEC, curhost,
1157  (unsigned short) PostPortNumber,
1158  NULL,
1159  ListenSocket, MAXLISTEN);
1160 
1161  if (status == STATUS_OK)
1162  {
1163  success++;
1164  /* record the first successful host addr in lockfile */
1165  if (!listen_addr_saved)
1166  {
1168  listen_addr_saved = true;
1169  }
1170  }
1171  else
1172  ereport(WARNING,
1173  (errmsg("could not create listen socket for \"%s\"",
1174  curhost)));
1175  }
1176 
1177  if (!success && elemlist != NIL)
1178  ereport(FATAL,
1179  (errmsg("could not create any TCP/IP sockets")));
1180 
1181  list_free(elemlist);
1182  pfree(rawstring);
1183  }
1184 
1185 #ifdef USE_BONJOUR
1186  /* Register for Bonjour only if we opened TCP socket(s) */
1187  if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
1188  {
1189  DNSServiceErrorType err;
1190 
1191  /*
1192  * We pass 0 for interface_index, which will result in registering on
1193  * all "applicable" interfaces. It's not entirely clear from the
1194  * DNS-SD docs whether this would be appropriate if we have bound to
1195  * just a subset of the available network interfaces.
1196  */
1197  err = DNSServiceRegister(&bonjour_sdref,
1198  0,
1199  0,
1200  bonjour_name,
1201  "_postgresql._tcp.",
1202  NULL,
1203  NULL,
1205  0,
1206  NULL,
1207  NULL,
1208  NULL);
1209  if (err != kDNSServiceErr_NoError)
1210  elog(LOG, "DNSServiceRegister() failed: error code %ld",
1211  (long) err);
1212 
1213  /*
1214  * We don't bother to read the mDNS daemon's reply, and we expect that
1215  * it will automatically terminate our registration when the socket is
1216  * closed at postmaster termination. So there's nothing more to be
1217  * done here. However, the bonjour_sdref is kept around so that
1218  * forked children can close their copies of the socket.
1219  */
1220  }
1221 #endif
1222 
1223 #ifdef HAVE_UNIX_SOCKETS
1225  {
1226  char *rawstring;
1227  List *elemlist;
1228  ListCell *l;
1229  int success = 0;
1230 
1231  /* Need a modifiable copy of Unix_socket_directories */
1232  rawstring = pstrdup(Unix_socket_directories);
1233 
1234  /* Parse string into list of directories */
1235  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1236  {
1237  /* syntax error in list */
1238  ereport(FATAL,
1239  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1240  errmsg("invalid list syntax in parameter \"%s\"",
1241  "unix_socket_directories")));
1242  }
1243 
1244  foreach(l, elemlist)
1245  {
1246  char *socketdir = (char *) lfirst(l);
1247 
1248  status = StreamServerPort(AF_UNIX, NULL,
1249  (unsigned short) PostPortNumber,
1250  socketdir,
1251  ListenSocket, MAXLISTEN);
1252 
1253  if (status == STATUS_OK)
1254  {
1255  success++;
1256  /* record the first successful Unix socket in lockfile */
1257  if (success == 1)
1259  }
1260  else
1261  ereport(WARNING,
1262  (errmsg("could not create Unix-domain socket in directory \"%s\"",
1263  socketdir)));
1264  }
1265 
1266  if (!success && elemlist != NIL)
1267  ereport(FATAL,
1268  (errmsg("could not create any Unix-domain sockets")));
1269 
1270  list_free_deep(elemlist);
1271  pfree(rawstring);
1272  }
1273 #endif
1274 
1275  /*
1276  * check that we have some socket to listen on
1277  */
1278  if (ListenSocket[0] == PGINVALID_SOCKET)
1279  ereport(FATAL,
1280  (errmsg("no socket created for listening")));
1281 
1282  /*
1283  * If no valid TCP ports, write an empty line for listen address,
1284  * indicating the Unix socket must be used. Note that this line is not
1285  * added to the lock file until there is a socket backing it.
1286  */
1287  if (!listen_addr_saved)
1289 
1290  /*
1291  * Record postmaster options. We delay this till now to avoid recording
1292  * bogus options (eg, unusable port number).
1293  */
1294  if (!CreateOptsFile(argc, argv, my_exec_path))
1295  ExitPostmaster(1);
1296 
1297  /*
1298  * Write the external PID file if requested
1299  */
1300  if (external_pid_file)
1301  {
1302  FILE *fpidfile = fopen(external_pid_file, "w");
1303 
1304  if (fpidfile)
1305  {
1306  fprintf(fpidfile, "%d\n", MyProcPid);
1307  fclose(fpidfile);
1308 
1309  /* Make PID file world readable */
1310  if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1311  write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1313  }
1314  else
1315  write_stderr("%s: could not write external PID file \"%s\": %s\n",
1317 
1319  }
1320 
1321  /*
1322  * Remove old temporary files. At this point there can be no other
1323  * Postgres processes running in this directory, so this should be safe.
1324  */
1326 
1327  /*
1328  * Initialize stats collection subsystem (this does NOT start the
1329  * collector process!)
1330  */
1331  pgstat_init();
1332 
1333  /*
1334  * Initialize the autovacuum subsystem (again, no process start yet)
1335  */
1336  autovac_init();
1337 
1338  /*
1339  * Load configuration files for client authentication.
1340  */
1341  if (!load_hba())
1342  {
1343  /*
1344  * It makes no sense to continue if we fail to load the HBA file,
1345  * since there is no way to connect to the database in this case.
1346  */
1347  ereport(FATAL,
1348  (errmsg("could not load pg_hba.conf")));
1349  }
1350  if (!load_ident())
1351  {
1352  /*
1353  * We can start up without the IDENT file, although it means that you
1354  * cannot log in using any of the authentication methods that need a
1355  * user name mapping. load_ident() already logged the details of error
1356  * to the log.
1357  */
1358  }
1359 
1360 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1361 
1362  /*
1363  * On macOS, libintl replaces setlocale() with a version that calls
1364  * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1365  * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1366  * the process multithreaded. The postmaster calls sigprocmask() and
1367  * calls fork() without an immediate exec(), both of which have undefined
1368  * behavior in a multithreaded program. A multithreaded postmaster is the
1369  * normal case on Windows, which offers neither fork() nor sigprocmask().
1370  */
1371  if (pthread_is_threaded_np() != 0)
1372  ereport(FATAL,
1373  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1374  errmsg("postmaster became multithreaded during startup"),
1375  errhint("Set the LC_ALL environment variable to a valid locale.")));
1376 #endif
1377 
1378  /*
1379  * Remember postmaster startup time
1380  */
1382 
1383  /*
1384  * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1385  * see what's happening.
1386  */
1388 
1389  /*
1390  * We're ready to rock and roll...
1391  */
1393  Assert(StartupPID != 0);
1395  pmState = PM_STARTUP;
1396 
1397  /* Some workers may be scheduled to start now */
1399 
1400  status = ServerLoop();
1401 
1402  /*
1403  * ServerLoop probably shouldn't ever return, but if it does, close down.
1404  */
1405  ExitPostmaster(status != STATUS_OK);
1406 
1407  abort(); /* not reached */
1408 }
int StreamServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
Definition: pqcomm.c:328
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3259
int secure_initialize(bool isServerStart)
Definition: be-secure.c:77
#define NIL
Definition: pg_list.h:65
bool IsPostmasterEnvironment
Definition: globals.c:108
bool EnableSSL
Definition: postmaster.c:236
#define SIGQUIT
Definition: win32_port.h:154
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
#define S_IRGRP
Definition: win32_port.h:272
#define AllocSetContextCreate
Definition: memutils.h:170
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1451
int MyProcPid
Definition: globals.c:40
int errhint(const char *fmt,...)
Definition: elog.c:1071
#define StartupDataBase()
Definition: postmaster.c:541
static void reset_shared(void)
Definition: postmaster.c:2657
#define DEBUG3
Definition: elog.h:23
#define SIGUSR1
Definition: win32_port.h:165
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1301
#define SIGCHLD
Definition: win32_port.h:163
int wal_level
Definition: xlog.c:106
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define pg_hton16(x)
Definition: pg_bswap.h:120
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:5372
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:10500
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3436
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define write_stderr(str)
Definition: parallel.c:186
#define S_IROTH
Definition: win32_port.h:284
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:5661
bool CheckDateTokenTables(void)
Definition: datetime.c:4423
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:7709
#define PG_TEMP_FILES_DIR
Definition: pg_checksums.c:58
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:95
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3478
int SysLogger_Start(void)
Definition: syslogger.c:540
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3407
void checkDataDir(void)
Definition: miscinit.c:274
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
#define LOG
Definition: elog.h:26
void InitProcessGlobals(void)
Definition: postmaster.c:2623
const char * progname
Definition: pg_standby.c:36
#define fprintf
Definition: port.h:197
void list_free_deep(List *list)
Definition: list.c:1390
char * Unix_socket_directories
Definition: postmaster.c:200
bool IsBinaryUpgrade
Definition: globals.c:110
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool load_ident(void)
Definition: hba.c:2977
void autovac_init(void)
Definition: autovacuum.c:3281
void pqinitmask(void)
Definition: pqsignal.c:41
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1415
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3813
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:6602
#define PM_STATUS_STARTING
Definition: pidfile.h:51
void pfree(void *pointer)
Definition: mcxt.c:1056
int optind
Definition: getopt.c:50
#define S_IWUSR
Definition: win32_port.h:263
#define ERROR
Definition: elog.h:43
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1245
static pid_t StartupPID
Definition: postmaster.c:250
int PostPortNumber
Definition: postmaster.c:197
static void checkControlFile(void)
Definition: postmaster.c:1516
int ReservedBackends
Definition: postmaster.c:214
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5139
#define FATAL
Definition: elog.h:52
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: pidfile.h:41
char * external_pid_file
Definition: guc.c:555
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
Definition: dest.h:89
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7685
bool load_hba(void)
Definition: hba.c:2183
char * bonjour_name
Definition: postmaster.c:246
int XLogArchiveMode
Definition: xlog.c:94
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3057
int errcode_for_file_access(void)
Definition: elog.c:633
static pid_t SysLoggerPID
Definition: postmaster.c:258
#define SIGHUP
Definition: win32_port.h:153
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5033
void ChangeToDataDir(void)
Definition: miscinit.c:388
int opterr
Definition: getopt.c:49
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1463
char * Log_destination_string
Definition: elog.c:111
char * ListenAddresses
Definition: postmaster.c:203
#define STATUS_OK
Definition: c.h:1133
MemoryContext TopMemoryContext
Definition: mcxt.c:44
static void pmdie(SIGNAL_ARGS)
Definition: postmaster.c:2756
static void SIGHUP_handler(SIGNAL_ARGS)
Definition: postmaster.c:2674
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: pidfile.h:42
bool enable_bonjour
Definition: postmaster.c:245
void RemovePromoteSignalFiles(void)
Definition: xlog.c:12639
int max_wal_senders
Definition: walsender.c:121
#define SIG_IGN
Definition: win32_port.h:150
pid_t PostmasterPid
Definition: globals.c:95
#define WARNING
Definition: elog.h:40
pqsigfunc pqsignal_pm(int signo, pqsigfunc func)
Definition: pqsignal.c:118
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
sigset_t BlockSig
Definition: pqsignal.c:22
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
static PMState pmState
Definition: postmaster.c:341
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5537
void ApplyLauncherRegister(void)
Definition: launcher.c:763
#define PGINVALID_SOCKET
Definition: port.h:33
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
int MaxConnections
Definition: globals.c:132
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1551
TimestampTz PgStartTime
Definition: timestamp.c:50
#define LOG_DESTINATION_STDERR
Definition: elog.h:418
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
static bool Reinit
Definition: postmaster.c:232
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:223
static int ServerLoop(void)
Definition: postmaster.c:1643
#define Assert(condition)
Definition: c.h:738
#define lfirst(lc)
Definition: pg_list.h:190
void RemovePgTempFiles(void)
Definition: fd.c:2998
static void reaper(SIGNAL_ARGS)
Definition: postmaster.c:2943
void InitializeMaxBackends(void)
Definition: postinit.c:526
#define strerror
Definition: port.h:206
#define SIGALRM
Definition: win32_port.h:159
const char * name
Definition: encode.c:561
#define S_IRUSR
Definition: win32_port.h:260
static const char * userDoption
Definition: postgres.c:157
void set_max_safe_fds(void)
Definition: fd.c:940
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * optarg
Definition: getopt.c:52
void list_free(List *list)
Definition: list.c:1376
#define elog(elevel,...)
Definition: elog.h:214
int i
static void sigusr1_handler(SIGNAL_ARGS)
Definition: postmaster.c:5172
void pgstat_init(void)
Definition: pgstat.c:379
int Log_destination
Definition: elog.c:110
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3934
char ** environ
CommandDest whereToSendOutput
Definition: postgres.c:91
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
static bool success
Definition: initdb.c:161
static int SendStop
Definition: postmaster.c:233
void process_shared_preload_libraries(void)
Definition: miscinit.c:1629
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
Definition: pg_list.h:50
#define snprintf
Definition: port.h:193
#define MAXLISTEN
Definition: postmaster.c:217
MemoryContext PostmasterContext
Definition: mcxt.c:46
static void maybe_start_bgworkers(void)
Definition: postmaster.c:5999
void InitializeGUCOptions(void)
Definition: guc.c:5315

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6118 of file postmaster.c.

References AllocateFile(), Assert, AuxiliaryProcs, bkend::bgworker_notify, bkend::child_slot, closesocket, dlist_iter::cur, DataDir, generate_unaccent_rules::dest, dlist_container, dlist_foreach, bkend::elem, ereport, errmsg(), errmsg_internal(), ExtraOptions, first_syslogger_file_time, free, FreeFile(), i, IsBinaryUpgrade, sort-test::key, ListenSocket, LOG, MainLWLockArray, max_safe_fds, MaxBackends, MaxLivePostmasterChildren(), MAXPGPATH, mul_size(), my_exec_path, MyCancelKey, MyPMChildSlot, NamedLWLockTrancheArray, NamedLWLockTrancheRequests, PG_BINARY_R, pg_queue_signal(), PGINVALID_SOCKET, PgReloadTime, PgStartTime, pgStatSock, pgwin32_create_signal_listener(), pgwin32_initial_signal_pipe, bkend::pid, pkglib_path, PMSignalState, postmaster_alive_fds, PostmasterPid, PreparedXactProcs, ProcGlobal, ProcStructLock, redirection_done, ReserveExternalFD(), SetDataDir(), ShmemAlloc(), ShmemLock, ShmemProtectiveRegion, ShmemVariableCache, SIGCHLD, Port::sock, SpinlockSemaArray, strerror, strlcpy(), syslogPipe, UsedShmemSegAddr, UsedShmemSegID, and write_stderr.

Referenced by BackgroundWorkerStateChange().

6119 {
6120  dlist_iter iter;
6121  Backend *bp;
6122 
6123  dlist_foreach(iter, &BackendList)
6124  {
6125  bp = dlist_container(Backend, elem, iter.cur);
6126  if (bp->pid == pid)
6127  {
6128  bp->bgworker_notify = true;
6129  return true;
6130  }
6131  }
6132  return false;
6133 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:182
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:186
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:171

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3794 of file postmaster.c.

References AbortStartTime, Assert, AutoVacPID, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WORKER, BackupInProgress(), BgWriterPID, CancelBackup(), CheckpointerPID, CountChildren(), dlist_is_empty(), ereport, errmsg(), ExitPostmaster(), FatalError, ImmediateShutdown, LocalProcessControlFile(), LOG, NoShutdown, PgArchPID, PgStatPID, PM_NO_CHILDREN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_DEAD_END, PM_WAIT_READONLY, pmState, ReachedNormalRunning, reset_shared(), ResetBackgroundWorkerCrashTimes(), restart_after_crash, shmem_exit(), Shutdown, signal_child(), SignalChildren, SIGQUIT, SIGUSR2, StartCheckpointer, STARTUP_CRASHED, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

Referenced by pmdie(), reaper(), and sigusr1_handler().

3795 {
3796  if (pmState == PM_WAIT_BACKUP)
3797  {
3798  /*
3799  * PM_WAIT_BACKUP state ends when online backup mode is not active.
3800  */
3801  if (!BackupInProgress())
3803  }
3804 
3805  if (pmState == PM_WAIT_READONLY)
3806  {
3807  /*
3808  * PM_WAIT_READONLY state ends when we have no regular backends that
3809  * have been started during recovery. We kill the startup and
3810  * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3811  * we might like to kill these processes first and then wait for
3812  * backends to die off, but that doesn't work at present because
3813  * killing the startup process doesn't release its locks.
3814  */
3816  {
3817  if (StartupPID != 0)
3818  signal_child(StartupPID, SIGTERM);
3819  if (WalReceiverPID != 0)
3820  signal_child(WalReceiverPID, SIGTERM);
3822  }
3823  }
3824 
3825  /*
3826  * If we are in a state-machine state that implies waiting for backends to
3827  * exit, see if they're all gone, and change state if so.
3828  */
3829  if (pmState == PM_WAIT_BACKENDS)
3830  {
3831  /*
3832  * PM_WAIT_BACKENDS state ends when we have no regular backends
3833  * (including autovac workers), no bgworkers (including unconnected
3834  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3835  * doing crash recovery or an immediate shutdown then we expect the
3836  * checkpointer to exit as well, otherwise not. The archiver, stats,
3837  * and syslogger processes are disregarded since they are not
3838  * connected to shared memory; we also disregard dead_end children
3839  * here. Walsenders are also disregarded, they will be terminated
3840  * later after writing the checkpoint record, like the archiver
3841  * process.
3842  */
3844  StartupPID == 0 &&
3845  WalReceiverPID == 0 &&
3846  BgWriterPID == 0 &&
3847  (CheckpointerPID == 0 ||
3849  WalWriterPID == 0 &&
3850  AutoVacPID == 0)
3851  {
3853  {
3854  /*
3855  * Start waiting for dead_end children to die. This state
3856  * change causes ServerLoop to stop creating new ones.
3857  */
3859 
3860  /*
3861  * We already SIGQUIT'd the archiver and stats processes, if
3862  * any, when we started immediate shutdown or entered
3863  * FatalError state.
3864  */
3865  }
3866  else
3867  {
3868  /*
3869  * If we get here, we are proceeding with normal shutdown. All
3870  * the regular children are gone, and it's time to tell the
3871  * checkpointer to do a shutdown checkpoint.
3872  */
3874  /* Start the checkpointer if not running */
3875  if (CheckpointerPID == 0)
3877  /* And tell it to shut down */
3878  if (CheckpointerPID != 0)
3879  {
3881  pmState = PM_SHUTDOWN;
3882  }
3883  else
3884  {
3885  /*
3886  * If we failed to fork a checkpointer, just shut down.
3887  * Any required cleanup will happen at next restart. We
3888  * set FatalError so that an "abnormal shutdown" message
3889  * gets logged when we exit.
3890  */
3891  FatalError = true;
3893 
3894  /* Kill the walsenders, archiver and stats collector too */
3896  if (PgArchPID != 0)
3898  if (PgStatPID != 0)
3900  }
3901  }
3902  }
3903  }
3904 
3905  if (pmState == PM_SHUTDOWN_2)
3906  {
3907  /*
3908  * PM_SHUTDOWN_2 state ends when there's no other children than
3909  * dead_end children left. There shouldn't be any regular backends
3910  * left by now anyway; what we're really waiting for is walsenders and
3911  * archiver.
3912  */
3913  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3914  {
3916  }
3917  }
3918 
3919  if (pmState == PM_WAIT_DEAD_END)
3920  {
3921  /*
3922  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3923  * (ie, no dead_end children remain), and the archiver and stats
3924  * collector are gone too.
3925  *
3926  * The reason we wait for those two is to protect them against a new
3927  * postmaster starting conflicting subprocesses; this isn't an
3928  * ironclad protection, but it at least helps in the
3929  * shutdown-and-immediately-restart scenario. Note that they have
3930  * already been sent appropriate shutdown signals, either during a
3931  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3932  * FatalError processing.
3933  */
3934  if (dlist_is_empty(&BackendList) &&
3935  PgArchPID == 0 && PgStatPID == 0)
3936  {
3937  /* These other guys should be dead already */
3938  Assert(StartupPID == 0);
3939  Assert(WalReceiverPID == 0);
3940  Assert(BgWriterPID == 0);
3941  Assert(CheckpointerPID == 0);
3942  Assert(WalWriterPID == 0);
3943  Assert(AutoVacPID == 0);
3944  /* syslogger is not considered here */
3946  }
3947  }
3948 
3949  /*
3950  * If we've been told to shut down, we exit as soon as there are no
3951  * remaining children. If there was a crash, cleanup will occur at the
3952  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3953  * crash before exiting, but that seems unwise if we are quitting because
3954  * we got SIGTERM from init --- there may well not be time for recovery
3955  * before init decides to SIGKILL us.)
3956  *
3957  * Note that the syslogger continues to run. It will exit when it sees
3958  * EOF on its input pipe, which happens when there are no more upstream
3959  * processes.
3960  */
3962  {
3963  if (FatalError)
3964  {
3965  ereport(LOG, (errmsg("abnormal database system shutdown")));
3966  ExitPostmaster(1);
3967  }
3968  else
3969  {
3970  /*
3971  * Terminate exclusive backup mode to avoid recovery after a clean
3972  * fast shutdown. Since an exclusive backup can only be taken
3973  * during normal running (and not, for example, while running
3974  * under Hot Standby) it only makes sense to do this if we reached
3975  * normal running. If we're still in recovery, the backup file is
3976  * one we're recovering *from*, and we must keep it around so that
3977  * recovery restarts from the right place.
3978  */
3980  CancelBackup();
3981 
3982  /* Normal exit from the postmaster is here */
3983  ExitPostmaster(0);
3984  }
3985  }
3986 
3987  /*
3988  * If the startup process failed, or the user does not want an automatic
3989  * restart after backend crashes, wait for all non-syslogger children to
3990  * exit, and then exit postmaster. We don't try to reinitialize when the
3991  * startup process fails, because more than likely it will just fail again
3992  * and we will keep trying forever.
3993  */
3994  if (pmState == PM_NO_CHILDREN &&
3996  ExitPostmaster(1);
3997 
3998  /*
3999  * If we need to recover from a crash, wait for all non-syslogger children
4000  * to exit, then reset shmem and StartupDataBase.
4001  */
4002  if (FatalError && pmState == PM_NO_CHILDREN)
4003  {
4004  ereport(LOG,
4005  (errmsg("all server processes terminated; reinitializing")));
4006 
4007  /* allow background workers to immediately restart */
4009 
4010  shmem_exit(1);
4011 
4012  /* re-read control file into local memory */
4014 
4015  reset_shared();
4016 
4018  Assert(StartupPID != 0);
4020  pmState = PM_STARTUP;
4021  /* crash recovery started, reset SIGKILL flag */
4022  AbortStartTime = 0;
4023  }
4024 }
void CancelBackup(void)
Definition: xlog.c:11785
#define SIGQUIT
Definition: win32_port.h:154
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define StartupDataBase()
Definition: postmaster.c:541
static void reset_shared(void)
Definition: postmaster.c:2657
static pid_t PgStatPID
Definition: postmaster.c:257
static pid_t CheckpointerPID
Definition: postmaster.c:252
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool FatalError
Definition: postmaster.c:279
void shmem_exit(int code)
Definition: ipc.c:224
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define SIGUSR2
Definition: win32_port.h:166
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11765
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:514
#define SignalChildren(sig)
Definition: postmaster.c:418
static int Shutdown
Definition: postmaster.c:277
static pid_t BgWriterPID
Definition: postmaster.c:251
#define StartCheckpointer()
Definition: postmaster.c:543
static int CountChildren(int target)
Definition: postmaster.c:5401
static pid_t StartupPID
Definition: postmaster.c:250
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5139
bool restart_after_crash
Definition: postmaster.c:247
static dlist_head BackendList
Definition: postmaster.c:186
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5033
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4044
static PMState pmState
Definition: postmaster.c:341
#define BACKEND_TYPE_WORKER
Definition: postmaster.c:151
#define ImmediateShutdown
Definition: postmaster.c:275
#define ereport(elevel,...)
Definition: elog.h:144
static pid_t WalWriterPID
Definition: postmaster.c:253
#define Assert(condition)
Definition: c.h:738
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:272
static pid_t AutoVacPID
Definition: postmaster.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:824
static bool ReachedNormalRunning
Definition: postmaster.c:350
static time_t AbortStartTime
Definition: postmaster.c:345
static pid_t PgArchPID
Definition: postmaster.c:256

◆ processCancelRequest()

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

Definition at line 2368 of file postmaster.c.

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

Referenced by ProcessStartupPacket().

2369 {
2370  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2371  int backendPID;
2372  int32 cancelAuthCode;
2373  Backend *bp;
2374 
2375 #ifndef EXEC_BACKEND
2376  dlist_iter iter;
2377 #else
2378  int i;
2379 #endif
2380 
2381  backendPID = (int) pg_ntoh32(canc->backendPID);
2382  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2383 
2384  /*
2385  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2386  * longer access the postmaster's own backend list, and must rely on the
2387  * duplicate array in shared memory.
2388  */
2389 #ifndef EXEC_BACKEND
2390  dlist_foreach(iter, &BackendList)
2391  {
2392  bp = dlist_container(Backend, elem, iter.cur);
2393 #else
2394  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2395  {
2396  bp = (Backend *) &ShmemBackendArray[i];
2397 #endif
2398  if (bp->pid == backendPID)
2399  {
2400  if (bp->cancel_key == cancelAuthCode)
2401  {
2402  /* Found a match; signal that backend to cancel current op */
2403  ereport(DEBUG2,
2404  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2405  backendPID)));
2406  signal_child(bp->pid, SIGINT);
2407  }
2408  else
2409  /* Right PID, wrong key: no way, Jose */
2410  ereport(LOG,
2411  (errmsg("wrong key in cancel request for process %d",
2412  backendPID)));
2413  return;
2414  }
2415 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2416  }
2417 #else
2418  }
2419 #endif
2420 
2421  /* No matching backend */
2422  ereport(LOG,
2423  (errmsg("PID %d in cancel request did not match any process",
2424  backendPID)));
2425 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
uint32 cancelAuthCode
Definition: pqcomm.h:197
#define LOG
Definition: elog.h:26
signed int int32
Definition: c.h:355
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
uint32 backendPID
Definition: pqcomm.h:196
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static dlist_head BackendList
Definition: postmaster.c:186
#define DEBUG2
Definition: elog.h:24
int32 cancel_key
Definition: postmaster.c:172
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4044
dlist_node * cur
Definition: ilist.h:161
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5701
pid_t pid
Definition: postmaster.c:171
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i

◆ ProcessStartupPacket()