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

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */
 
#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */
 
#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */
 
#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */
 
#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */
 
#define MAXLISTEN   64
 
#define NoShutdown   0
 
#define SmartShutdown   1
 
#define FastShutdown   2
 
#define ImmediateShutdown   3
 
#define SIGKILL_CHILDREN_AFTER_SECS   5
 
#define SignalChildren(sig)   SignalSomeChildren(sig, BACKEND_TYPE_ALL)
 
#define PgArchStartupAllowed()
 
#define StartupDataBase()   StartChildProcess(StartupProcess)
 
#define StartArchiver()   StartChildProcess(ArchiverProcess)
 
#define StartBackgroundWriter()   StartChildProcess(BgWriterProcess)
 
#define StartCheckpointer()   StartChildProcess(CheckpointerProcess)
 
#define StartWalWriter()   StartChildProcess(WalWriterProcess)
 
#define StartWalReceiver()   StartChildProcess(WalReceiverProcess)
 
#define EXIT_STATUS_0(st)   ((st) == 0)
 
#define EXIT_STATUS_1(st)   (WIFEXITED(st) && WEXITSTATUS(st) == 1)
 
#define EXIT_STATUS_3(st)   (WIFEXITED(st) && WEXITSTATUS(st) == 3)
 
#define OPTS_FILE   "postmaster.opts"
 
#define MAX_BGWORKERS_TO_LAUNCH   100
 

Typedefs

typedef struct bkend Backend
 

Enumerations

enum  StartupStatusEnum { STARTUP_NOT_RUNNING, STARTUP_RUNNING, STARTUP_SIGNALED, STARTUP_CRASHED }
 
enum  PMState {
  PM_INIT, PM_STARTUP, PM_RECOVERY, PM_HOT_STANDBY,
  PM_RUN, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_SHUTDOWN,
  PM_SHUTDOWN_2, PM_WAIT_DEAD_END, PM_NO_CHILDREN
}
 
enum  ConnsAllowedState { ALLOW_ALL_CONNS, ALLOW_SUPERUSER_CONNS, ALLOW_NO_CONNS }
 

Functions

static void CloseServerPorts (int status, Datum arg)
 
static void unlink_external_pid_file (int status, Datum arg)
 
static void getInstallationPaths (const char *argv0)
 
static void checkControlFile (void)
 
static PortConnCreate (int serverFd)
 
static void ConnFree (Port *port)
 
static void reset_shared (void)
 
static void SIGHUP_handler (SIGNAL_ARGS)
 
static void pmdie (SIGNAL_ARGS)
 
static void reaper (SIGNAL_ARGS)
 
static void sigusr1_handler (SIGNAL_ARGS)
 
static void process_startup_packet_die (SIGNAL_ARGS)
 
static void dummy_handler (SIGNAL_ARGS)
 
static void StartupPacketTimeoutHandler (void)
 
static void CleanupBackend (int pid, int exitstatus)
 
static bool CleanupBackgroundWorker (int pid, int exitstatus)
 
static void HandleChildCrash (int pid, int exitstatus, const char *procname)
 
static void LogChildExit (int lev, const char *procname, int pid, int exitstatus)
 
static void PostmasterStateMachine (void)
 
static void BackendInitialize (Port *port)
 
static void BackendRun (Port *port) pg_attribute_noreturn()
 
static void ExitPostmaster (int status) pg_attribute_noreturn()
 
static int ServerLoop (void)
 
static int BackendStartup (Port *port)
 
static int ProcessStartupPacket (Port *port, bool ssl_done, bool gss_done)
 
static void SendNegotiateProtocolVersion (List *unrecognized_protocol_options)
 
static void processCancelRequest (Port *port, void *pkt)
 
static int initMasks (fd_set *rmask)
 
static void report_fork_failure_to_client (Port *port, int errnum)
 
static CAC_state canAcceptConnections (int backend_type)
 
static bool RandomCancelKey (int32 *cancel_key)
 
static void signal_child (pid_t pid, int signal)
 
static bool SignalSomeChildren (int signal, int targets)
 
static void TerminateChildren (int signal)
 
static int CountChildren (int target)
 
static bool assign_backendlist_entry (RegisteredBgWorker *rw)
 
static void maybe_start_bgworkers (void)
 
static bool CreateOptsFile (int argc, char *argv[], char *fullprogname)
 
static pid_t StartChildProcess (AuxProcType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
void PostmasterMain (int argc, char *argv[])
 
static void DetermineSleepTime (struct timeval *timeout)
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
int MaxLivePostmasterChildren (void)
 
void BackgroundWorkerInitializeConnection (const char *dbname, const char *username, uint32 flags)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid, uint32 flags)
 
void BackgroundWorkerBlockSignals (void)
 
void BackgroundWorkerUnblockSignals (void)
 
static bool do_start_bgworker (RegisteredBgWorker *rw)
 
static bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

static dlist_head BackendList = DLIST_STATIC_INIT(BackendList)
 
BackgroundWorkerMyBgworkerEntry = NULL
 
int PostPortNumber
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int ReservedBackends
 
static pgsocket ListenSocket [MAXLISTEN]
 
static bool Reinit = true
 
static int SendStop = false
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
bool remove_temp_files_after_crash = true
 
static pid_t StartupPID = 0
 
static pid_t BgWriterPID = 0
 
static pid_t CheckpointerPID = 0
 
static pid_t WalWriterPID = 0
 
static pid_t WalReceiverPID = 0
 
static pid_t AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t 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 ConnsAllowedState connsAllowed = ALLOW_ALL_CONNS
 
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 147 of file postmaster.c.

Referenced by StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 149 of file postmaster.c.

Referenced by assign_backendlist_entry(), canAcceptConnections(), and HandleChildCrash().

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 148 of file postmaster.c.

Referenced by CountChildren(), PostmasterStateMachine(), and SignalSomeChildren().

◆ EXIT_STATUS_0

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

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

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 273 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 274 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:158
static PMState pmState
Definition: postmaster.c:338
#define XLogArchivingActive()
Definition: xlog.h:155
bool PgArchCanRestart(void)
Definition: pgarch.c:148

Definition at line 447 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 360 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 430 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 272 of file postmaster.c.

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

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 555 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 556 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 557 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 554 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 559 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 558 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

Typedef Documentation

◆ Backend

typedef struct bkend Backend

Enumeration Type Documentation

◆ ConnsAllowedState

Enumerator
ALLOW_ALL_CONNS 
ALLOW_SUPERUSER_CONNS 
ALLOW_NO_CONNS 

Definition at line 346 of file postmaster.c.

347 {
348  ALLOW_ALL_CONNS, /* normal not-shutting-down state */
349  ALLOW_SUPERUSER_CONNS, /* only superusers can connect */
350  ALLOW_NO_CONNS /* no new connections allowed, period */
ConnsAllowedState
Definition: postmaster.c:346

◆ PMState

enum PMState
Enumerator
PM_INIT 
PM_STARTUP 
PM_RECOVERY 
PM_HOT_STANDBY 
PM_RUN 
PM_STOP_BACKENDS 
PM_WAIT_BACKENDS 
PM_SHUTDOWN 
PM_SHUTDOWN_2 
PM_WAIT_DEAD_END 
PM_NO_CHILDREN 

Definition at line 321 of file postmaster.c.

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 260 of file postmaster.c.

261 {
264  STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
StartupStatusEnum
Definition: postmaster.c:260

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5952 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().

5953 {
5954  Backend *bn;
5955 
5956  /*
5957  * Check that database state allows another connection. Currently the
5958  * only possible failure is CAC_TOOMANY, so we just log an error message
5959  * based on that rather than checking the error code precisely.
5960  */
5962  {
5963  ereport(LOG,
5964  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5965  errmsg("no slot available for new worker process")));
5966  return false;
5967  }
5968 
5969  /*
5970  * Compute the cancel key that will be assigned to this session. We
5971  * probably don't need cancel keys for background workers, but we'd better
5972  * have something random in the field to prevent unfriendly people from
5973  * sending cancels to them.
5974  */
5976  {
5977  ereport(LOG,
5978  (errcode(ERRCODE_INTERNAL_ERROR),
5979  errmsg("could not generate random cancel key")));
5980  return false;
5981  }
5982 
5983  bn = malloc(sizeof(Backend));
5984  if (bn == NULL)
5985  {
5986  ereport(LOG,
5987  (errcode(ERRCODE_OUT_OF_MEMORY),
5988  errmsg("out of memory")));
5989  return false;
5990  }
5991 
5992  bn->cancel_key = MyCancelKey;
5995  bn->dead_end = false;
5996  bn->bgworker_notify = false;
5997 
5998  rw->rw_backend = bn;
5999  rw->rw_child_slot = bn->child_slot;
6000 
6001  return true;
6002 }
struct bkend * rw_backend
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2499
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:185
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:219
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:47
int32 cancel_key
Definition: postmaster.c:181
bool dead_end
Definition: postmaster.c:184
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:149
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5402
int child_slot
Definition: postmaster.c:182
int bkend_type
Definition: postmaster.c:183
#define ereport(elevel,...)
Definition: elog.h:157
int MyPMChildSlot
Definition: globals.c:48
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4372 of file postmaster.c.

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

Referenced by BackendRun(), and BackendStartup().

4373 {
4374  int status;
4375  int ret;
4376  char remote_host[NI_MAXHOST];
4377  char remote_port[NI_MAXSERV];
4378  StringInfoData ps_data;
4379 
4380  /* Save port etc. for ps status */
4381  MyProcPort = port;
4382 
4383  /* Tell fd.c about the long-lived FD associated with the port */
4385 
4386  /*
4387  * PreAuthDelay is a debugging aid for investigating problems in the
4388  * authentication cycle: it can be set in postgresql.conf to allow time to
4389  * attach to the newly-forked backend with a debugger. (See also
4390  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4391  * is not honored until after authentication.)
4392  */
4393  if (PreAuthDelay > 0)
4394  pg_usleep(PreAuthDelay * 1000000L);
4395 
4396  /* This flag will remain set until InitPostgres finishes authentication */
4397  ClientAuthInProgress = true; /* limit visibility of log messages */
4398 
4399  /* set these to empty in case they are needed before we set them up */
4400  port->remote_host = "";
4401  port->remote_port = "";
4402 
4403  /*
4404  * Initialize libpq and enable reporting of ereport errors to the client.
4405  * Must do this now because authentication uses libpq to send messages.
4406  */
4407  pq_init(); /* initialize libpq to talk to client */
4408  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4409 
4410  /*
4411  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4412  * to collect the startup packet; while SIGQUIT results in _exit(2).
4413  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4414  * cleanly if a buggy client fails to send the packet promptly.
4415  *
4416  * Exiting with _exit(1) is only possible because we have not yet touched
4417  * shared memory; therefore no outside-the-process state needs to get
4418  * cleaned up.
4419  */
4421  /* SIGQUIT handler was already set up by InitPostmasterChild */
4422  InitializeTimeouts(); /* establishes SIGALRM handler */
4424 
4425  /*
4426  * Get the remote host name and port for logging and status display.
4427  */
4428  remote_host[0] = '\0';
4429  remote_port[0] = '\0';
4430  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4431  remote_host, sizeof(remote_host),
4432  remote_port, sizeof(remote_port),
4433  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4434  ereport(WARNING,
4435  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4436  gai_strerror(ret))));
4437 
4438  /*
4439  * Save remote_host and remote_port in port structure (after this, they
4440  * will appear in log_line_prefix data for log messages).
4441  */
4442  port->remote_host = strdup(remote_host);
4443  port->remote_port = strdup(remote_port);
4444 
4445  /* And now we can issue the Log_connections message, if wanted */
4446  if (Log_connections)
4447  {
4448  if (remote_port[0])
4449  ereport(LOG,
4450  (errmsg("connection received: host=%s port=%s",
4451  remote_host,
4452  remote_port)));
4453  else
4454  ereport(LOG,
4455  (errmsg("connection received: host=%s",
4456  remote_host)));
4457  }
4458 
4459  /*
4460  * If we did a reverse lookup to name, we might as well save the results
4461  * rather than possibly repeating the lookup during authentication.
4462  *
4463  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4464  * get nothing useful for a client without an rDNS entry. Therefore, we
4465  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4466  * it into remote_hostname if so. (This test is conservative and might
4467  * sometimes classify a hostname as numeric, but an error in that
4468  * direction is safe; it only results in a possible extra lookup.)
4469  */
4470  if (log_hostname &&
4471  ret == 0 &&
4472  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4473  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4474  port->remote_hostname = strdup(remote_host);
4475 
4476  /*
4477  * Ready to begin client interaction. We will give up and _exit(1) after
4478  * a time delay, so that a broken client can't hog a connection
4479  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4480  * against the time limit.
4481  *
4482  * Note: AuthenticationTimeout is applied here while waiting for the
4483  * startup packet, and then again in InitPostgres for the duration of any
4484  * authentication operations. So a hostile client could tie up the
4485  * process for nearly twice AuthenticationTimeout before we kick him off.
4486  *
4487  * Note: because PostgresMain will call InitializeTimeouts again, the
4488  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4489  * since we never use it again after this function.
4490  */
4493 
4494  /*
4495  * Receive the startup packet (which might turn out to be a cancel request
4496  * packet).
4497  */
4498  status = ProcessStartupPacket(port, false, false);
4499 
4500  /*
4501  * Disable the timeout, and prevent SIGTERM again.
4502  */
4504  PG_SETMASK(&BlockSig);
4505 
4506  /*
4507  * As a safety check that nothing in startup has yet performed
4508  * shared-memory modifications that would need to be undone if we had
4509  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4510  * handlers have been registered yet. (This isn't terribly bulletproof,
4511  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4512  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4513  * handlers unfortunately, since pq_init() already registered one.)
4514  */
4516 
4517  /*
4518  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4519  * already did any appropriate error reporting.
4520  */
4521  if (status != STATUS_OK)
4522  proc_exit(0);
4523 
4524  /*
4525  * Now that we have the user and database name, we can set the process
4526  * title for ps. It's good to do this as early as possible in startup.
4527  */
4528  initStringInfo(&ps_data);
4529  if (am_walsender)
4531  appendStringInfo(&ps_data, "%s ", port->user_name);
4532  if (!am_walsender)
4533  appendStringInfo(&ps_data, "%s ", port->database_name);
4534  appendStringInfo(&ps_data, "%s", port->remote_host);
4535  if (port->remote_port[0] != '\0')
4536  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4537 
4538  init_ps_display(ps_data.data);
4539  pfree(ps_data.data);
4540 
4541  set_ps_display("initializing");
4542 }
void InitializeTimeouts(void)
Definition: timeout.c:435
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
struct Port * MyProcPort
Definition: globals.c:46
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:249
struct sockaddr_storage addr
Definition: pqcomm.h:64
void proc_exit(int code)
Definition: ipc.c:104
char * remote_port
Definition: libpq-be.h:137
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:240
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define gai_strerror
Definition: getaddrinfo.h:146
int AuthenticationTimeout
Definition: postmaster.c:237
void set_ps_display(const char *activity)
Definition: ps_status.c:349
char * remote_hostname
Definition: libpq-be.h:133
bool ClientAuthInProgress
Definition: postmaster.c:364
SockAddr raddr
Definition: libpq-be.h:131
bool am_walsender
Definition: walsender.c:115
void pg_usleep(long microsec)
Definition: signal.c:53
void pq_init(void)
Definition: pqcomm.c:176
void pfree(void *pointer)
Definition: mcxt.c:1169
#define NI_MAXHOST
Definition: getaddrinfo.h:88
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void ReserveExternalFD(void)
Definition: fd.c:1210
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:146
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define STATUS_OK
Definition: c.h:1170
bool log_hostname
Definition: postmaster.c:239
static int port
Definition: pg_regress.c:92
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:2001
sigset_t BlockSig
Definition: pqsignal.c:22
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
#define ereport(elevel,...)
Definition: elog.h:157
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:469
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:524
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
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5368
sigset_t StartupBlockSig
Definition: pqsignal.c:22
void check_on_shmem_exit_lists_are_empty(void)
Definition: ipc.c:428
int PreAuthDelay
Definition: postmaster.c:236
char * remote_host
Definition: libpq-be.h:132
int errmsg(const char *fmt,...)
Definition: elog.c:909
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5392
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:621
CommandDest whereToSendOutput
Definition: postgres.c:92
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
char * database_name
Definition: libpq-be.h:145

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4552 of file postmaster.c.

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

Referenced by BackendStartup().

4553 {
4554  /*
4555  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4556  * just yet, though, because InitPostgres will need the HBA data.)
4557  */
4559 
4560  PostgresMain(port->database_name, port->user_name);
4561 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4015
char * user_name
Definition: libpq-be.h:146
MemoryContext TopMemoryContext
Definition: mcxt.c:48
char * database_name
Definition: libpq-be.h:145

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4211 of file postmaster.c.

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

Referenced by ServerLoop().

4212 {
4213  Backend *bn; /* for backend cleanup */
4214  pid_t pid;
4215 
4216  /*
4217  * Create backend data structure. Better before the fork() so we can
4218  * handle failure cleanly.
4219  */
4220  bn = (Backend *) malloc(sizeof(Backend));
4221  if (!bn)
4222  {
4223  ereport(LOG,
4224  (errcode(ERRCODE_OUT_OF_MEMORY),
4225  errmsg("out of memory")));
4226  return STATUS_ERROR;
4227  }
4228 
4229  /*
4230  * Compute the cancel key that will be assigned to this backend. The
4231  * backend will have its own copy in the forked-off process' value of
4232  * MyCancelKey, so that it can transmit the key to the frontend.
4233  */
4235  {
4236  free(bn);
4237  ereport(LOG,
4238  (errcode(ERRCODE_INTERNAL_ERROR),
4239  errmsg("could not generate random cancel key")));
4240  return STATUS_ERROR;
4241  }
4242 
4243  bn->cancel_key = MyCancelKey;
4244 
4245  /* Pass down canAcceptConnections state */
4247  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4249 
4250  /*
4251  * Unless it's a dead_end child, assign it a child slot number
4252  */
4253  if (!bn->dead_end)
4255  else
4256  bn->child_slot = 0;
4257 
4258  /* Hasn't asked to be notified about any bgworkers yet */
4259  bn->bgworker_notify = false;
4260 
4261 #ifdef EXEC_BACKEND
4262  pid = backend_forkexec(port);
4263 #else /* !EXEC_BACKEND */
4264  pid = fork_process();
4265  if (pid == 0) /* child */
4266  {
4267  free(bn);
4268 
4269  /* Detangle from postmaster */
4271 
4272  /* Close the postmaster's sockets */
4273  ClosePostmasterPorts(false);
4274 
4275  /* Perform additional initialization and collect startup packet */
4276  BackendInitialize(port);
4277 
4278  /*
4279  * Create a per-backend PGPROC struct in shared memory. We must do
4280  * this before we can use LWLocks. In the !EXEC_BACKEND case (here)
4281  * this could be delayed a bit further, but EXEC_BACKEND needs to do
4282  * stuff with LWLocks before PostgresMain(), so we do it here as well
4283  * for symmetry.
4284  */
4285  InitProcess();
4286 
4287  /* And run the backend */
4288  BackendRun(port);
4289  }
4290 #endif /* EXEC_BACKEND */
4291 
4292  if (pid < 0)
4293  {
4294  /* in parent, fork failed */
4295  int save_errno = errno;
4296 
4297  if (!bn->dead_end)
4299  free(bn);
4300  errno = save_errno;
4301  ereport(LOG,
4302  (errmsg("could not fork new process for connection: %m")));
4303  report_fork_failure_to_client(port, save_errno);
4304  return STATUS_ERROR;
4305  }
4306 
4307  /* in parent, successful fork */
4308  ereport(DEBUG2,
4309  (errmsg_internal("forked new backend, pid=%d socket=%d",
4310  (int) pid, (int) port->sock)));
4311 
4312  /*
4313  * Everything's been successful, it's safe to add this backend to our list
4314  * of backends.
4315  */
4316  bn->pid = pid;
4317  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4319 
4320 #ifdef EXEC_BACKEND
4321  if (!bn->dead_end)
4322  ShmemBackendArrayAdd(bn);
4323 #endif
4324 
4325  return STATUS_OK;
4326 }
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2499
CAC_state canAcceptConnections
Definition: libpq-be.h:138
void InitPostmasterChild(void)
Definition: miscinit.c:94
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:4552
pid_t fork_process(void)
Definition: fork_process.c:29
int errcode(int sqlerrcode)
Definition: elog.c:698
#define STATUS_ERROR
Definition: c.h:1171
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:146
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:186
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2612
pgsocket sock
Definition: libpq-be.h:127
bool bgworker_notify
Definition: postmaster.c:185
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:219
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:47
static dlist_head BackendList
Definition: postmaster.c:189
#define DEBUG2
Definition: elog.h:24
void InitProcess(void)
Definition: proc.c:303
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4337
int32 cancel_key
Definition: postmaster.c:181
bool dead_end
Definition: postmaster.c:184
#define STATUS_OK
Definition: c.h:1170
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5402
int child_slot
Definition: postmaster.c:182
int bkend_type
Definition: postmaster.c:183
#define ereport(elevel,...)
Definition: elog.h:157
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
pid_t pid
Definition: postmaster.c:180
int MyPMChildSlot
Definition: globals.c:48
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void BackendInitialize(Port *port)
Definition: postmaster.c:4372

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5775 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5776 {
5777  PG_SETMASK(&BlockSig);
5778 }
#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 5729 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().

5730 {
5732 
5733  /* XXX is this the right errcode? */
5735  ereport(FATAL,
5736  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5737  errmsg("database connection requirement not indicated during registration")));
5738 
5740 
5741  /* it had better not gotten out of "init" mode yet */
5742  if (!IsInitProcessingMode())
5743  ereport(ERROR,
5744  (errmsg("invalid processing mode in background worker")));
5746 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define ERROR
Definition: elog.h:46
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:155
#define FATAL
Definition: elog.h:49
const char * username
Definition: pgbench.c:282
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:572
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
char * dbname
Definition: streamutil.c:51
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define IsInitProcessingMode()
Definition: miscadmin.h:407

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5752 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().

5753 {
5755 
5756  /* XXX is this the right errcode? */
5758  ereport(FATAL,
5759  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5760  errmsg("database connection requirement not indicated during registration")));
5761 
5762  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5763 
5764  /* it had better not gotten out of "init" mode yet */
5765  if (!IsInitProcessingMode())
5766  ereport(ERROR,
5767  (errmsg("invalid processing mode in background worker")));
5769 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define ERROR
Definition: elog.h:46
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:155
#define FATAL
Definition: elog.h:49
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:572
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define IsInitProcessingMode()
Definition: miscadmin.h:407

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5909 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_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, and pmState.

Referenced by maybe_start_bgworkers().

5910 {
5911  switch (pmState)
5912  {
5913  case PM_NO_CHILDREN:
5914  case PM_WAIT_DEAD_END:
5915  case PM_SHUTDOWN_2:
5916  case PM_SHUTDOWN:
5917  case PM_WAIT_BACKENDS:
5918  case PM_STOP_BACKENDS:
5919  break;
5920 
5921  case PM_RUN:
5923  return true;
5924  /* fall through */
5925 
5926  case PM_HOT_STANDBY:
5928  return true;
5929  /* fall through */
5930 
5931  case PM_RECOVERY:
5932  case PM_STARTUP:
5933  case PM_INIT:
5935  return true;
5936  /* fall through */
5937 
5938  }
5939 
5940  return false;
5941 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:338

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 2499 of file postmaster.c.

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

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

2500 {
2501  CAC_state result = CAC_OK;
2502 
2503  /*
2504  * Can't start backends when in startup/shutdown/inconsistent recovery
2505  * state. We treat autovac workers the same as user backends for this
2506  * purpose. However, bgworkers are excluded from this test; we expect
2507  * bgworker_should_start_now() decided whether the DB state allows them.
2508  */
2509  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2510  backend_type != BACKEND_TYPE_BGWORKER)
2511  {
2512  if (Shutdown > NoShutdown)
2513  return CAC_SHUTDOWN; /* shutdown is pending */
2514  else if (!FatalError && pmState == PM_STARTUP)
2515  return CAC_STARTUP; /* normal startup */
2516  else if (!FatalError && pmState == PM_RECOVERY)
2517  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2518  * state */
2519  else
2520  return CAC_RECOVERY; /* else must be crash recovery */
2521  }
2522 
2523  /*
2524  * "Smart shutdown" restrictions are applied only to normal connections,
2525  * not to autovac workers or bgworkers. When only superusers can connect,
2526  * we return CAC_SUPERUSER to indicate that superuserness must be checked
2527  * later. Note that neither CAC_OK nor CAC_SUPERUSER can safely be
2528  * returned until we have checked for too many children.
2529  */
2530  if (connsAllowed != ALLOW_ALL_CONNS &&
2531  backend_type == BACKEND_TYPE_NORMAL)
2532  {
2534  result = CAC_SUPERUSER; /* allow superusers only */
2535  else
2536  return CAC_SHUTDOWN; /* shutdown is pending */
2537  }
2538 
2539  /*
2540  * Don't start too many children.
2541  *
2542  * We allow more connections here than we can have backends because some
2543  * might still be authenticating; they might fail auth, or some existing
2544  * backend might exit before the auth cycle is completed. The exact
2545  * MaxBackends limit is enforced when a new backend tries to join the
2546  * shared-inval backend array.
2547  *
2548  * The limit here must match the sizes of the per-child-process arrays;
2549  * see comments for MaxLivePostmasterChildren().
2550  */
2552  result = CAC_TOOMANY;
2553 
2554  return result;
2555 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:150
static bool FatalError
Definition: postmaster.c:278
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:146
static int Shutdown
Definition: postmaster.c:276
static int CountChildren(int target)
Definition: postmaster.c:5412
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:149
static PMState pmState
Definition: postmaster.c:338
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5719
static ConnsAllowedState connsAllowed
Definition: postmaster.c:353
#define NoShutdown
Definition: postmaster.c:271
CAC_state
Definition: libpq-be.h:71

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1590 of file postmaster.c.

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

Referenced by PostmasterMain().

1591 {
1592  char path[MAXPGPATH];
1593  FILE *fp;
1594 
1595  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1596 
1597  fp = AllocateFile(path, PG_BINARY_R);
1598  if (fp == NULL)
1599  {
1600  write_stderr("%s: could not find the database system\n"
1601  "Expected to find it in the directory \"%s\",\n"
1602  "but could not open file \"%s\": %s\n",
1603  progname, DataDir, path, strerror(errno));
1604  ExitPostmaster(2);
1605  }
1606  FreeFile(fp);
1607 }
const char * progname
Definition: main.c:46
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1273
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5156
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2459
#define strerror
Definition: port.h:230
int FreeFile(FILE *file)
Definition: fd.c:2658
char * DataDir
Definition: globals.c:65
#define snprintf
Definition: port.h:217

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

Definition at line 3405 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().

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3310 of file postmaster.c.

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

Referenced by reaper().

3312 {
3313  char namebuf[MAXPGPATH];
3314  slist_mutable_iter iter;
3315 
3317  {
3318  RegisteredBgWorker *rw;
3319 
3320  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3321 
3322  if (rw->rw_pid != pid)
3323  continue;
3324 
3325 #ifdef WIN32
3326  /* see CleanupBackend */
3327  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3328  exitstatus = 0;
3329 #endif
3330 
3331  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3332  rw->rw_worker.bgw_type);
3333 
3334 
3335  if (!EXIT_STATUS_0(exitstatus))
3336  {
3337  /* Record timestamp, so we know when to restart the worker. */
3339  }
3340  else
3341  {
3342  /* Zero exit status means terminate */
3343  rw->rw_crashed_at = 0;
3344  rw->rw_terminate = true;
3345  }
3346 
3347  /*
3348  * Additionally, just like a backend, any exit status other than 0 or
3349  * 1 is considered a crash and causes a system-wide restart.
3350  */
3351  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3352  {
3353  HandleChildCrash(pid, exitstatus, namebuf);
3354  return true;
3355  }
3356 
3357  /*
3358  * We must release the postmaster child slot. If the worker failed to
3359  * do so, it did not clean up after itself, requiring a crash-restart
3360  * cycle.
3361  */
3363  {
3364  HandleChildCrash(pid, exitstatus, namebuf);
3365  return true;
3366  }
3367 
3368  /* Get it out of the BackendList and clear out remaining data */
3369  dlist_delete(&rw->rw_backend->elem);
3370 #ifdef EXEC_BACKEND
3371  ShmemBackendArrayRemove(rw->rw_backend);
3372 #endif
3373 
3374  /*
3375  * It's possible that this background worker started some OTHER
3376  * background worker and asked to be notified when that worker started
3377  * or stopped. If so, cancel any notifications destined for the
3378  * now-dead backend.
3379  */
3380  if (rw->rw_backend->bgworker_notify)
3382  free(rw->rw_backend);
3383  rw->rw_backend = NULL;
3384  rw->rw_pid = 0;
3385  rw->rw_child_slot = 0;
3386  ReportBackgroundWorkerExit(&iter); /* report child death */
3387 
3388  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3389  namebuf, pid, exitstatus);
3390 
3391  return true;
3392  }
3393 
3394  return false;
3395 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
slist_node * cur
Definition: ilist.h:241
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:480
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:186
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:514
bool bgworker_notify
Definition: postmaster.c:185
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:735
#define EXIT_STATUS_1(st)
Definition: postmaster.c:563
#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:693
#define free(a)
Definition: header.h:65
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3489
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3742
BackgroundWorker rw_worker
#define snprintf
Definition: port.h:217
#define _(x)
Definition: elog.c:89
#define EXIT_STATUS_0(st)
Definition: postmaster.c:562

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2612 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(), pgstat_start(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

2613 {
2614  int i;
2615 
2616 #ifndef WIN32
2617 
2618  /*
2619  * Close the write end of postmaster death watch pipe. It's important to
2620  * do this as early as possible, so that if postmaster dies, others won't
2621  * think that it's still running because we're holding the pipe open.
2622  */
2624  ereport(FATAL,
2626  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2628  /* Notify fd.c that we released one pipe FD. */
2630 #endif
2631 
2632  /*
2633  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2634  * so we don't call ReleaseExternalFD() here.
2635  */
2636  for (i = 0; i < MAXLISTEN; i++)
2637  {
2638  if (ListenSocket[i] != PGINVALID_SOCKET)
2639  {
2642  }
2643  }
2644 
2645  /*
2646  * If using syslogger, close the read side of the pipe. We don't bother
2647  * tracking this in fd.c, either.
2648  */
2649  if (!am_syslogger)
2650  {
2651 #ifndef WIN32
2652  if (syslogPipe[0] >= 0)
2653  close(syslogPipe[0]);
2654  syslogPipe[0] = -1;
2655 #else
2656  if (syslogPipe[0])
2657  CloseHandle(syslogPipe[0]);
2658  syslogPipe[0] = 0;
2659 #endif
2660  }
2661 
2662 #ifdef USE_BONJOUR
2663  /* If using Bonjour, close the connection to the mDNS daemon */
2664  if (bonjour_sdref)
2665  close(DNSServiceRefSockFD(bonjour_sdref));
2666 #endif
2667 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:850
#define FATAL
Definition: elog.h:49
#define POSTMASTER_FD_OWN
Definition: postmaster.h:45
int errcode_for_file_access(void)
Definition: elog.c:721
int postmaster_alive_fds[2]
Definition: postmaster.c:571
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:221
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void ReleaseExternalFD(void)
Definition: fd.c:1228
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:220
int syslogPipe[2]
Definition: syslogger.c:115

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1488 of file postmaster.c.

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

Referenced by PostmasterMain().

1489 {
1490  int i;
1491 
1492  /*
1493  * First, explicitly close all the socket FDs. We used to just let this
1494  * happen implicitly at postmaster exit, but it's better to close them
1495  * before we remove the postmaster.pid lockfile; otherwise there's a race
1496  * condition if a new postmaster wants to re-use the TCP port number.
1497  */
1498  for (i = 0; i < MAXLISTEN; i++)
1499  {
1500  if (ListenSocket[i] != PGINVALID_SOCKET)
1501  {
1504  }
1505  }
1506 
1507  /*
1508  * Next, remove any filesystem entries for Unix sockets. To avoid race
1509  * conditions against incoming postmasters, this must happen after closing
1510  * the sockets and before removing lock files.
1511  */
1513 
1514  /*
1515  * We don't do anything about socket lock files here; those will be
1516  * removed in a later on_proc_exit callback.
1517  */
1518 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:850
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:221
#define PGINVALID_SOCKET
Definition: port.h:33
int i
void RemoveSocketFiles(void)
Definition: pqcomm.c:883
#define MAXLISTEN
Definition: postmaster.c:220

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2564 of file postmaster.c.

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

Referenced by ServerLoop().

2565 {
2566  Port *port;
2567 
2568  if (!(port = (Port *) calloc(1, sizeof(Port))))
2569  {
2570  ereport(LOG,
2571  (errcode(ERRCODE_OUT_OF_MEMORY),
2572  errmsg("out of memory")));
2573  ExitPostmaster(1);
2574  }
2575 
2576  if (StreamConnection(serverFd, port) != STATUS_OK)
2577  {
2578  if (port->sock != PGINVALID_SOCKET)
2579  StreamClose(port->sock);
2580  ConnFree(port);
2581  return NULL;
2582  }
2583 
2584  return port;
2585 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:850
static void ConnFree(Port *port)
Definition: postmaster.c:2595
int errcode(int sqlerrcode)
Definition: elog.c:698
Definition: libpq-be.h:125
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:716
pgsocket sock
Definition: libpq-be.h:127
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5156
#define STATUS_OK
Definition: c.h:1170
static int port
Definition: pg_regress.c:92
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2595 of file postmaster.c.

References free.

Referenced by ConnCreate(), and ServerLoop().

2596 {
2597  free(conn);
2598 }
PGconn * conn
Definition: streamutil.c:54
#define free(a)
Definition: header.h:65

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5412 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().

5413 {
5414  dlist_iter iter;
5415  int cnt = 0;
5416 
5417  dlist_foreach(iter, &BackendList)
5418  {
5419  Backend *bp = dlist_container(Backend, elem, iter.cur);
5420 
5421  if (bp->dead_end)
5422  continue;
5423 
5424  /*
5425  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5426  * it first and avoid touching shared memory for every child.
5427  */
5428  if (target != BACKEND_TYPE_ALL)
5429  {
5430  /*
5431  * Assign bkend_type for any recently announced WAL Sender
5432  * processes.
5433  */
5434  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5437 
5438  if (!(target & bp->bkend_type))
5439  continue;
5440  }
5441 
5442  cnt++;
5443  }
5444  return cnt;
5445 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:150
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:146
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
static dlist_head BackendList
Definition: postmaster.c:189
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:148
bool dead_end
Definition: postmaster.c:184
int child_slot
Definition: postmaster.c:182
int bkend_type
Definition: postmaster.c:183
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:275

◆ CreateOptsFile()

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

Definition at line 5675 of file postmaster.c.

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

Referenced by PostmasterMain().

5676 {
5677  FILE *fp;
5678  int i;
5679 
5680 #define OPTS_FILE "postmaster.opts"
5681 
5682  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5683  {
5684  ereport(LOG,
5686  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5687  return false;
5688  }
5689 
5690  fprintf(fp, "%s", fullprogname);
5691  for (i = 1; i < argc; i++)
5692  fprintf(fp, " \"%s\"", argv[i]);
5693  fputs("\n", fp);
5694 
5695  if (fclose(fp))
5696  {
5697  ereport(LOG,
5699  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5700  return false;
5701  }
5702 
5703  return true;
5704 }
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:221
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1619 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().

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

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5817 of file postmaster.c.

References Assert, assign_backendlist_entry(), BackgroundWorker::bgw_name, ClosePostmasterPorts(), DEBUG1, dlist_push_head(), bkend::elem, ereport, errmsg(), errmsg_internal(), 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().

5818 {
5819  pid_t worker_pid;
5820 
5821  Assert(rw->rw_pid == 0);
5822 
5823  /*
5824  * Allocate and assign the Backend element. Note we must do this before
5825  * forking, so that we can handle failures (out of memory or child-process
5826  * slots) cleanly.
5827  *
5828  * Treat failure as though the worker had crashed. That way, the
5829  * postmaster will wait a bit before attempting to start it again; if we
5830  * tried again right away, most likely we'd find ourselves hitting the
5831  * same resource-exhaustion condition.
5832  */
5833  if (!assign_backendlist_entry(rw))
5834  {
5836  return false;
5837  }
5838 
5839  ereport(DEBUG1,
5840  (errmsg_internal("starting background worker process \"%s\"",
5841  rw->rw_worker.bgw_name)));
5842 
5843 #ifdef EXEC_BACKEND
5844  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5845 #else
5846  switch ((worker_pid = fork_process()))
5847 #endif
5848  {
5849  case -1:
5850  /* in postmaster, fork failed ... */
5851  ereport(LOG,
5852  (errmsg("could not fork worker process: %m")));
5853  /* undo what assign_backendlist_entry did */
5855  rw->rw_child_slot = 0;
5856  free(rw->rw_backend);
5857  rw->rw_backend = NULL;
5858  /* mark entry as crashed, so we'll try again later */
5860  break;
5861 
5862 #ifndef EXEC_BACKEND
5863  case 0:
5864  /* in postmaster child ... */
5866 
5867  /* Close the postmaster's sockets */
5868  ClosePostmasterPorts(false);
5869 
5870  /*
5871  * Before blowing away PostmasterContext, save this bgworker's
5872  * data where it can find it.
5873  */
5876  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5877 
5878  /* Release postmaster's working memory context */
5881  PostmasterContext = NULL;
5882 
5884 
5885  exit(1); /* should not get here */
5886  break;
5887 #endif
5888  default:
5889  /* in postmaster, fork successful ... */
5890  rw->rw_pid = worker_pid;
5891  rw->rw_backend->pid = rw->rw_pid;
5893  /* add new worker to lists of backends */
5895 #ifdef EXEC_BACKEND
5896  ShmemBackendArrayAdd(rw->rw_backend);
5897 #endif
5898  return true;
5899  }
5900 
5901  return false;
5902 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:94
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
pid_t fork_process(void)
Definition: fork_process.c:29
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:186
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2612
void StartBackgroundWorker(void)
Definition: bgworker.c:741
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5952
static dlist_head BackendList
Definition: postmaster.c:189
MemoryContext TopMemoryContext
Definition: mcxt.c:48
#define ereport(elevel,...)
Definition: elog.h:157
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
#define Assert(condition)
Definition: c.h:804
pid_t pid
Definition: postmaster.c:180
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:50

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5383 of file postmaster.c.

Referenced by PostmasterMain().

5384 {
5385 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5156 of file postmaster.c.

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

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

5157 {
5158 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5159 
5160  /*
5161  * There is no known cause for a postmaster to become multithreaded after
5162  * startup. Recheck to account for the possibility of unknown causes.
5163  * This message uses LOG level, because an unclean shutdown at this point
5164  * would usually not look much different from a clean shutdown.
5165  */
5166  if (pthread_is_threaded_np() != 0)
5167  ereport(LOG,
5168  (errcode(ERRCODE_INTERNAL_ERROR),
5169  errmsg_internal("postmaster became multithreaded"),
5170  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5171 #endif
5172 
5173  /* should cleanup shared memory and kill all backends */
5174 
5175  /*
5176  * Not sure of the semantics here. When the Postmaster dies, should the
5177  * backends all be killed? probably not.
5178  *
5179  * MUST -- vadim 05-10-1999
5180  */
5181 
5182  proc_exit(status);
5183 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1536 of file postmaster.c.

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

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

◆ HandleChildCrash()

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

Definition at line 3489 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_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_CRASH, pmState, ReleasePostmasterChildSlot(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_pid, SendStop, SetQuitSignalReason(), Shutdown, signal_child(), SIGQUIT, SIGSTOP, slist_container, slist_foreach, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1959 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6617 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().

6618 {
6619 #ifndef WIN32
6620 
6621  /*
6622  * Create a pipe. Postmaster holds the write end of the pipe open
6623  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6624  * the read file descriptor to select() to wake up in case postmaster
6625  * dies, or check for postmaster death with a (read() == 0). Children must
6626  * close the write end as soon as possible after forking, because EOF
6627  * won't be signaled in the read end until all processes have closed the
6628  * write fd. That is taken care of in ClosePostmasterPorts().
6629  */
6631  if (pipe(postmaster_alive_fds) < 0)
6632  ereport(FATAL,
6634  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6635 
6636  /* Notify fd.c that we've eaten two FDs for the pipe. */
6639 
6640  /*
6641  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6642  * call.
6643  */
6644  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6645  ereport(FATAL,
6647  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6648 #else
6649 
6650  /*
6651  * On Windows, we use a process handle for the same purpose.
6652  */
6653  if (DuplicateHandle(GetCurrentProcess(),
6654  GetCurrentProcess(),
6655  GetCurrentProcess(),
6656  &PostmasterHandle,
6657  0,
6658  TRUE,
6659  DUPLICATE_SAME_ACCESS) == 0)
6660  ereport(FATAL,
6661  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6662  GetLastError())));
6663 #endif /* WIN32 */
6664 }
int MyProcPid
Definition: globals.c:43
#define FATAL
Definition: elog.h:49
void ReserveExternalFD(void)
Definition: fd.c:1210
int errcode_for_file_access(void)
Definition: elog.c:721
int errcode_for_socket_access(void)
Definition: elog.c:792
pid_t PostmasterPid
Definition: globals.c:98
int postmaster_alive_fds[2]
Definition: postmaster.c:571
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Assert(condition)
Definition: c.h:804
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:43

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2676 of file postmaster.c.

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

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

2677 {
2678  unsigned int rseed;
2679 
2680  MyProcPid = getpid();
2683 
2684  /*
2685  * Set a different seed for random() in every process. We want something
2686  * unpredictable, so if possible, use high-quality random bits for the
2687  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2688  */
2689  if (!pg_strong_random(&rseed, sizeof(rseed)))
2690  {
2691  /*
2692  * Since PIDs and timestamps tend to change more frequently in their
2693  * least significant bits, shift the timestamp left to allow a larger
2694  * total number of seeds in a given time period. Since that would
2695  * leave only 20 bits of the timestamp that cycle every ~1 second,
2696  * also mix in some higher bits.
2697  */
2698  rseed = ((uint64) MyProcPid) ^
2699  ((uint64) MyStartTimestamp << 12) ^
2700  ((uint64) MyStartTimestamp >> 20);
2701  }
2702  srandom(rseed);
2703 }
int MyProcPid
Definition: globals.c:43
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
pg_time_t MyStartTime
Definition: globals.c:44
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1754
TimestampTz MyStartTimestamp
Definition: globals.c:45
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 3742 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().

3743 {
3744  /*
3745  * size of activity_buffer is arbitrary, but set equal to default
3746  * track_activity_query_size
3747  */
3748  char activity_buffer[1024];
3749  const char *activity = NULL;
3750 
3751  if (!EXIT_STATUS_0(exitstatus))
3752  activity = pgstat_get_crashed_backend_activity(pid,
3753  activity_buffer,
3754  sizeof(activity_buffer));
3755 
3756  if (WIFEXITED(exitstatus))
3757  ereport(lev,
3758 
3759  /*------
3760  translator: %s is a noun phrase describing a child process, such as
3761  "server process" */
3762  (errmsg("%s (PID %d) exited with exit code %d",
3763  procname, pid, WEXITSTATUS(exitstatus)),
3764  activity ? errdetail("Failed process was running: %s", activity) : 0));
3765  else if (WIFSIGNALED(exitstatus))
3766  {
3767 #if defined(WIN32)
3768  ereport(lev,
3769 
3770  /*------
3771  translator: %s is a noun phrase describing a child process, such as
3772  "server process" */
3773  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3774  procname, pid, WTERMSIG(exitstatus)),
3775  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3776  activity ? errdetail("Failed process was running: %s", activity) : 0));
3777 #else
3778  ereport(lev,
3779 
3780  /*------
3781  translator: %s is a noun phrase describing a child process, such as
3782  "server process" */
3783  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3784  procname, pid, WTERMSIG(exitstatus),
3785  pg_strsignal(WTERMSIG(exitstatus))),
3786  activity ? errdetail("Failed process was running: %s", activity) : 0));
3787 #endif
3788  }
3789  else
3790  ereport(lev,
3791 
3792  /*------
3793  translator: %s is a noun phrase describing a child process, such as
3794  "server process" */
3795  (errmsg("%s (PID %d) exited with unrecognized status %d",
3796  procname, pid, exitstatus),
3797  activity ? errdetail("Failed process was running: %s", activity) : 0));
3798 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define WTERMSIG(w)
Definition: win32_port.h:154
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define WIFEXITED(w)
Definition: win32_port.h:151
#define ereport(elevel,...)
Definition: elog.h:157
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define WIFSIGNALED(w)
Definition: win32_port.h:152
#define WEXITSTATUS(w)
Definition: win32_port.h:153
#define EXIT_STATUS_0(st)
Definition: postmaster.c:562

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5719 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5720 {
5721  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5723 }
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:136
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:137

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 6016 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().

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5656 of file postmaster.c.

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

Referenced by ServerLoop(), and sigusr1_handler().

5657 {
5658  if (WalReceiverPID == 0 &&
5659  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5660  pmState == PM_HOT_STANDBY) &&
5662  {
5664  if (WalReceiverPID != 0)
5665  WalReceiverRequested = false;
5666  /* else leave the flag set, so we'll try again later */
5667  }
5668 }
static pid_t WalReceiverPID
Definition: postmaster.c:253
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:376
static int Shutdown
Definition: postmaster.c:276
#define SmartShutdown
Definition: postmaster.c:272
static PMState pmState
Definition: postmaster.c:338
#define StartWalReceiver()
Definition: postmaster.c:559

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2809 of file postmaster.c.

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

Referenced by PostmasterMain().

2810 {
2811  int save_errno = errno;
2812 
2813  /*
2814  * We rely on the signal mechanism to have blocked all signals ... except
2815  * on Windows, which lacks sigaction(), so we have to do it manually.
2816  */
2817 #ifdef WIN32
2818  PG_SETMASK(&BlockSig);
2819 #endif
2820 
2821  ereport(DEBUG2,
2822  (errmsg_internal("postmaster received signal %d",
2823  postgres_signal_arg)));
2824 
2825  switch (postgres_signal_arg)
2826  {
2827  case SIGTERM:
2828 
2829  /*
2830  * Smart Shutdown:
2831  *
2832  * Wait for children to end their work, then shut down.
2833  */
2834  if (Shutdown >= SmartShutdown)
2835  break;
2837  ereport(LOG,
2838  (errmsg("received smart shutdown request")));
2839 
2840  /* Report status */
2842 #ifdef USE_SYSTEMD
2843  sd_notify(0, "STOPPING=1");
2844 #endif
2845 
2846  /*
2847  * If we reached normal running, we have to wait for any online
2848  * backup mode to end; otherwise go straight to waiting for client
2849  * backends to exit. (The difference is that in the former state,
2850  * we'll still let in new superuser clients, so that somebody can
2851  * end the online backup mode.) If already in PM_STOP_BACKENDS or
2852  * a later state, do not change it.
2853  */
2854  if (pmState == PM_RUN)
2856  else if (pmState == PM_HOT_STANDBY)
2858  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2859  {
2860  /* There should be no clients, so proceed to stop children */
2862  }
2863 
2864  /*
2865  * Now wait for online backup mode to end and backends to exit. If
2866  * that is already the case, PostmasterStateMachine will take the
2867  * next step.
2868  */
2870  break;
2871 
2872  case SIGINT:
2873 
2874  /*
2875  * Fast Shutdown:
2876  *
2877  * Abort all children with SIGTERM (rollback active transactions
2878  * and exit) and shut down when they are gone.
2879  */
2880  if (Shutdown >= FastShutdown)
2881  break;
2883  ereport(LOG,
2884  (errmsg("received fast shutdown request")));
2885 
2886  /* Report status */
2888 #ifdef USE_SYSTEMD
2889  sd_notify(0, "STOPPING=1");
2890 #endif
2891 
2892  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2893  {
2894  /* Just shut down background processes silently */
2896  }
2897  else if (pmState == PM_RUN ||
2899  {
2900  /* Report that we're about to zap live client sessions */
2901  ereport(LOG,
2902  (errmsg("aborting any active transactions")));
2904  }
2905 
2906  /*
2907  * PostmasterStateMachine will issue any necessary signals, or
2908  * take the next step if no child processes need to be killed.
2909  */
2911  break;
2912 
2913  case SIGQUIT:
2914 
2915  /*
2916  * Immediate Shutdown:
2917  *
2918  * abort all children with SIGQUIT, wait for them to exit,
2919  * terminate remaining ones with SIGKILL, then exit without
2920  * attempt to properly shut down the data base system.
2921  */
2922  if (Shutdown >= ImmediateShutdown)
2923  break;
2925  ereport(LOG,
2926  (errmsg("received immediate shutdown request")));
2927 
2928  /* Report status */
2930 #ifdef USE_SYSTEMD
2931  sd_notify(0, "STOPPING=1");
2932 #endif
2933 
2934  /* tell children to shut down ASAP */
2938 
2939  /* set stopwatch for them to die */
2940  AbortStartTime = time(NULL);
2941 
2942  /*
2943  * Now wait for backends to exit. If there are none,
2944  * PostmasterStateMachine will take the next step.
2945  */
2947  break;
2948  }
2949 
2950 #ifdef WIN32
2952 #endif
2953 
2954  errno = save_errno;
2955 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3807
#define SIGQUIT
Definition: win32_port.h:168
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1348
#define LOG
Definition: elog.h:26
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:276
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:190
#define SmartShutdown
Definition: postmaster.c:272
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4178
#define FastShutdown
Definition: postmaster.c:273
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:338
#define ImmediateShutdown
Definition: postmaster.c:274
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static ConnsAllowedState connsAllowed
Definition: postmaster.c:353
int errmsg(const char *fmt,...)
Definition: elog.c:909
#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:357

◆ PostmasterMain()

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

Definition at line 581 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BgWriterPID, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPID, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), DEBUG3, DestNone, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, free, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, i, InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), 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(), pgwin32_signal_initialize(), 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, SplitDirectoriesString(), SplitGUCList(), StartBackgroundWriter, StartCheckpointer, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror, success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6135 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(), 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, query_id_enabled, redirection_done, ReserveExternalFD(), SetDataDir(), ShmemAlloc(), ShmemLock, ShmemProtectiveRegion, ShmemVariableCache, SIGCHLD, Port::sock, SpinlockSemaArray, strerror, strlcpy(), syslogPipe, UsedShmemSegAddr, UsedShmemSegID, and write_stderr.

Referenced by BackgroundWorkerStateChange().

6136 {
6137  dlist_iter iter;
6138  Backend *bp;
6139 
6140  dlist_foreach(iter, &BackendList)
6141  {
6142  bp = dlist_container(Backend, elem, iter.cur);
6143  if (bp->pid == pid)
6144  {
6145  bp->bgworker_notify = true;
6146  return true;
6147  }
6148  }
6149  return false;
6150 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
bool bgworker_notify
Definition: postmaster.c:185
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
static dlist_head BackendList
Definition: postmaster.c:189
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:180

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3807 of file postmaster.c.

References AbortStartTime, ALLOW_NO_CONNS, ALLOW_SUPERUSER_CONNS, Assert, AutoVacPID, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackupInProgress(), BgWriterPID, CancelBackup(), CheckpointerPID, connsAllowed, CountChildren(), dlist_is_empty(), ereport, errmsg(), ExitPostmaster(), FatalError, ForgetUnstartedBackgroundWorkers(), ImmediateShutdown, LocalProcessControlFile(), LOG, NoShutdown, PgArchPID, PgStatPID, PM_HOT_STANDBY, PM_NO_CHILDREN, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, pmState, ReachedNormalRunning, remove_temp_files_after_crash, RemovePgTempFiles(), reset_shared(), ResetBackgroundWorkerCrashTimes(), restart_after_crash, shmem_exit(), Shutdown, signal_child(), SignalChildren, SignalSomeChildren(), SIGQUIT, SIGUSR2, StartCheckpointer, STARTUP_CRASHED, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

3808 {
3809  /* If we're doing a smart shutdown, try to advance that state. */
3810  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3811  {
3813  {
3814  /*
3815  * ALLOW_SUPERUSER_CONNS state ends as soon as online backup mode
3816  * is not active.
3817  */
3818  if (!BackupInProgress())
3820  }
3821 
3823  {
3824  /*
3825  * ALLOW_NO_CONNS state ends when we have no normal client
3826  * backends running. Then we're ready to stop other children.
3827  */
3830  }
3831  }
3832 
3833  /*
3834  * If we're ready to do so, signal child processes to shut down. (This
3835  * isn't a persistent state, but treating it as a distinct pmState allows
3836  * us to share this code across multiple shutdown code paths.)
3837  */
3838  if (pmState == PM_STOP_BACKENDS)
3839  {
3840  /*
3841  * Forget any pending requests for background workers, since we're no
3842  * longer willing to launch any new workers. (If additional requests
3843  * arrive, BackgroundWorkerStateChange will reject them.)
3844  */
3846 
3847  /* Signal all backend children except walsenders */
3848  SignalSomeChildren(SIGTERM,
3850  /* and the autovac launcher too */
3851  if (AutoVacPID != 0)
3852  signal_child(AutoVacPID, SIGTERM);
3853  /* and the bgwriter too */
3854  if (BgWriterPID != 0)
3855  signal_child(BgWriterPID, SIGTERM);
3856  /* and the walwriter too */
3857  if (WalWriterPID != 0)
3858  signal_child(WalWriterPID, SIGTERM);
3859  /* If we're in recovery, also stop startup and walreceiver procs */
3860  if (StartupPID != 0)
3861  signal_child(StartupPID, SIGTERM);
3862  if (WalReceiverPID != 0)
3863  signal_child(WalReceiverPID, SIGTERM);
3864  /* checkpointer, archiver, stats, and syslogger may continue for now */
3865 
3866  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3868  }
3869 
3870  /*
3871  * If we are in a state-machine state that implies waiting for backends to
3872  * exit, see if they're all gone, and change state if so.
3873  */
3874  if (pmState == PM_WAIT_BACKENDS)
3875  {
3876  /*
3877  * PM_WAIT_BACKENDS state ends when we have no regular backends
3878  * (including autovac workers), no bgworkers (including unconnected
3879  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3880  * doing crash recovery or an immediate shutdown then we expect the
3881  * checkpointer to exit as well, otherwise not. The stats and
3882  * syslogger processes are disregarded since they are not connected to
3883  * shared memory; we also disregard dead_end children here. Walsenders
3884  * and archiver are also disregarded, they will be terminated later
3885  * after writing the checkpoint record.
3886  */
3888  StartupPID == 0 &&
3889  WalReceiverPID == 0 &&
3890  BgWriterPID == 0 &&
3891  (CheckpointerPID == 0 ||
3893  WalWriterPID == 0 &&
3894  AutoVacPID == 0)
3895  {
3897  {
3898  /*
3899  * Start waiting for dead_end children to die. This state
3900  * change causes ServerLoop to stop creating new ones.
3901  */
3903 
3904  /*
3905  * We already SIGQUIT'd the archiver and stats processes, if
3906  * any, when we started immediate shutdown or entered
3907  * FatalError state.
3908  */
3909  }
3910  else
3911  {
3912  /*
3913  * If we get here, we are proceeding with normal shutdown. All
3914  * the regular children are gone, and it's time to tell the
3915  * checkpointer to do a shutdown checkpoint.
3916  */
3918  /* Start the checkpointer if not running */
3919  if (CheckpointerPID == 0)
3921  /* And tell it to shut down */
3922  if (CheckpointerPID != 0)
3923  {
3925  pmState = PM_SHUTDOWN;
3926  }
3927  else
3928  {
3929  /*
3930  * If we failed to fork a checkpointer, just shut down.
3931  * Any required cleanup will happen at next restart. We
3932  * set FatalError so that an "abnormal shutdown" message
3933  * gets logged when we exit.
3934  */
3935  FatalError = true;
3937 
3938  /* Kill the walsenders, archiver and stats collector too */
3940  if (PgArchPID != 0)
3942  if (PgStatPID != 0)
3944  }
3945  }
3946  }
3947  }
3948 
3949  if (pmState == PM_SHUTDOWN_2)
3950  {
3951  /*
3952  * PM_SHUTDOWN_2 state ends when there's no other children than
3953  * dead_end children left. There shouldn't be any regular backends
3954  * left by now anyway; what we're really waiting for is walsenders and
3955  * archiver.
3956  */
3957  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3958  {
3960  }
3961  }
3962 
3963  if (pmState == PM_WAIT_DEAD_END)
3964  {
3965  /*
3966  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3967  * (ie, no dead_end children remain), and the archiver and stats
3968  * collector are gone too.
3969  *
3970  * The reason we wait for those two is to protect them against a new
3971  * postmaster starting conflicting subprocesses; this isn't an
3972  * ironclad protection, but it at least helps in the
3973  * shutdown-and-immediately-restart scenario. Note that they have
3974  * already been sent appropriate shutdown signals, either during a
3975  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3976  * FatalError processing.
3977  */
3978  if (dlist_is_empty(&BackendList) &&
3979  PgArchPID == 0 && PgStatPID == 0)
3980  {
3981  /* These other guys should be dead already */
3982  Assert(StartupPID == 0);
3983  Assert(WalReceiverPID == 0);
3984  Assert(BgWriterPID == 0);
3985  Assert(CheckpointerPID == 0);
3986  Assert(WalWriterPID == 0);
3987  Assert(AutoVacPID == 0);
3988  /* syslogger is not considered here */
3990  }
3991  }
3992 
3993  /*
3994  * If we've been told to shut down, we exit as soon as there are no
3995  * remaining children. If there was a crash, cleanup will occur at the
3996  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3997  * crash before exiting, but that seems unwise if we are quitting because
3998  * we got SIGTERM from init --- there may well not be time for recovery
3999  * before init decides to SIGKILL us.)
4000  *
4001  * Note that the syslogger continues to run. It will exit when it sees
4002  * EOF on its input pipe, which happens when there are no more upstream
4003  * processes.
4004  */
4006  {
4007  if (FatalError)
4008  {
4009  ereport(LOG, (errmsg("abnormal database system shutdown")));
4010  ExitPostmaster(1);
4011  }
4012  else
4013  {
4014  /*
4015  * Terminate exclusive backup mode to avoid recovery after a clean
4016  * fast shutdown. Since an exclusive backup can only be taken
4017  * during normal running (and not, for example, while running
4018  * under Hot Standby) it only makes sense to do this if we reached
4019  * normal running. If we're still in recovery, the backup file is
4020  * one we're recovering *from*, and we must keep it around so that
4021  * recovery restarts from the right place.
4022  */
4024  CancelBackup();
4025 
4026  /*
4027  * Normal exit from the postmaster is here. We don't need to log
4028  * anything here, since the UnlinkLockFiles proc_exit callback
4029  * will do so, and that should be the last user-visible action.
4030  */
4031  ExitPostmaster(0);
4032  }
4033  }
4034 
4035  /*
4036  * If the startup process failed, or the user does not want an automatic
4037  * restart after backend crashes, wait for all non-syslogger children to
4038  * exit, and then exit postmaster. We don't try to reinitialize when the
4039  * startup process fails, because more than likely it will just fail again
4040  * and we will keep trying forever.
4041  */
4042  if (pmState == PM_NO_CHILDREN)
4043  {
4045  {
4046  ereport(LOG,
4047  (errmsg("shutting down due to startup process failure")));
4048  ExitPostmaster(1);
4049  }
4050  if (!restart_after_crash)
4051  {
4052  ereport(LOG,
4053  (errmsg("shutting down because restart_after_crash is off")));
4054  ExitPostmaster(1);
4055  }
4056  }
4057 
4058  /*
4059  * If we need to recover from a crash, wait for all non-syslogger children
4060  * to exit, then reset shmem and StartupDataBase.
4061  */
4062  if (FatalError && pmState == PM_NO_CHILDREN)
4063  {
4064  ereport(LOG,
4065  (errmsg("all server processes terminated; reinitializing")));
4066 
4067  /* remove leftover temporary files after a crash */
4070 
4071  /* allow background workers to immediately restart */
4073 
4074  shmem_exit(1);
4075 
4076  /* re-read control file into local memory */
4078 
4079  reset_shared();
4080 
4082  Assert(StartupPID != 0);
4084  pmState = PM_STARTUP;
4085  /* crash recovery started, reset SIGKILL flag */
4086  AbortStartTime = 0;
4087  }
4088 }
void CancelBackup(void)
Definition: xlog.c:12258
#define SIGQUIT
Definition: win32_port.h:168
static StartupStatusEnum StartupStatus
Definition: postmaster.c:268
#define BACKEND_TYPE_ALL
Definition: postmaster.c:150
#define StartupDataBase()
Definition: postmaster.c:554
static void reset_shared(void)
Definition: postmaster.c:2710
static pid_t PgStatPID
Definition: postmaster.c:256
static pid_t CheckpointerPID
Definition: postmaster.c:251
static pid_t WalReceiverPID
Definition: postmaster.c:253
static bool FatalError
Definition: postmaster.c:278
void shmem_exit(int code)
Definition: ipc.c:224
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4134
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:146
#define SIGUSR2
Definition: win32_port.h:180
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:12238
bool remove_temp_files_after_crash
Definition: postmaster.c:246
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:579
#define SignalChildren(sig)
Definition: postmaster.c:430
static int Shutdown
Definition: postmaster.c:276
static pid_t BgWriterPID
Definition: postmaster.c:250
#define StartCheckpointer()
Definition: postmaster.c:557
static int CountChildren(int target)
Definition: postmaster.c:5412
static pid_t StartupPID
Definition: postmaster.c:249
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5156
bool restart_after_crash
Definition: postmaster.c:245
static dlist_head BackendList
Definition: postmaster.c:189
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:148
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5118
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4108
static PMState pmState
Definition: postmaster.c:338
#define ImmediateShutdown
Definition: postmaster.c:274
#define ereport(elevel,...)
Definition: elog.h:157
static pid_t WalWriterPID
Definition: postmaster.c:252
#define Assert(condition)
Definition: c.h:804
static ConnsAllowedState connsAllowed
Definition: postmaster.c:353
void RemovePgTempFiles(void)
Definition: fd.c:3150
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:271
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:541
static pid_t AutoVacPID
Definition: postmaster.c:254
int errmsg(const char *fmt,...)
Definition: elog.c:909
static bool ReachedNormalRunning
Definition: postmaster.c:362
static time_t AbortStartTime
Definition: postmaster.c:357
static pid_t PgArchPID
Definition: postmaster.c:255

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5368 of file postmaster.c.

Referenced by BackendInitialize().

5369 {
5370  _exit(1);
5371 }

◆ processCancelRequest()

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

Definition at line 2433 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().

2434 {
2435  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2436  int backendPID;
2437  int32 cancelAuthCode;
2438  Backend *bp;
2439 
2440 #ifndef EXEC_BACKEND
2441  dlist_iter iter;
2442 #else
2443  int i;
2444 #endif
2445 
2446  backendPID = (int) pg_ntoh32(canc->backendPID);
2447  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2448 
2449  /*
2450  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2451  * longer access the postmaster's own backend list, and must rely on the
2452  * duplicate array in shared memory.
2453  */
2454 #ifndef EXEC_BACKEND
2455  dlist_foreach(iter, &BackendList)
2456  {
2457  bp = dlist_container(Backend, elem, iter.cur);
2458 #else
2459  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2460  {
2461  bp = (Backend *) &ShmemBackendArray[i];
2462 #endif
2463  if (bp->pid == backendPID)
2464  {
2465  if (bp->cancel_key == cancelAuthCode)
2466  {
2467  /* Found a match; signal that backend to cancel current op */
2468  ereport(DEBUG2,
2469  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2470  backendPID)));
2471  signal_child(bp->pid, SIGINT);
2472  }
2473  else
2474  /* Right PID, wrong key: no way, Jose */
2475  ereport(LOG,
2476  (errmsg("wrong key in cancel request for process %d",
2477  backendPID)));
2478  return;
2479  }
2480 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2481  }
2482 #else
2483  }
2484 #endif
2485 
2486  /* No matching backend */
2487  ereport(LOG,
2488  (errmsg("PID %d in cancel request did not match any process",
2489  backendPID)));
2490 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
uint32 cancelAuthCode
Definition: pqcomm.h:183
#define LOG