PostgreSQL Source Code  git master
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/transam.h"
#include "access/xlog.h"
#include "bootstrap/bootstrap.h"
#include "catalog/pg_control.h"
#include "common/file_perm.h"
#include "common/ip.h"
#include "common/string.h"
#include "lib/ilist.h"
#include "libpq/auth.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/fork_process.h"
#include "postmaster/interrupt.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "replication/logicallauncher.h"
#include "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/ps_status.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */
 
#define BACKEND_TYPE_AUTOVAC   0x0002 /* autovacuum worker process */
 
#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */
 
#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */
 
#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */
 
#define MAXLISTEN   64
 
#define NoShutdown   0
 
#define SmartShutdown   1
 
#define FastShutdown   2
 
#define ImmediateShutdown   3
 
#define SIGKILL_CHILDREN_AFTER_SECS   5
 
#define SignalChildren(sig)   SignalSomeChildren(sig, BACKEND_TYPE_ALL)
 
#define PgArchStartupAllowed()
 
#define StartupDataBase()   StartChildProcess(StartupProcess)
 
#define 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
 
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 146 of file postmaster.c.

Referenced by StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

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

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

◆ EXIT_STATUS_0

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

Definition at line 556 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 557 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 558 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 270 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 271 of file postmaster.c.

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

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

Referenced by maybe_start_bgworkers().

◆ MAXLISTEN

#define MAXLISTEN   64

◆ NoShutdown

#define NoShutdown   0

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

Referenced by CreateOptsFile().

◆ PgArchStartupAllowed

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

Definition at line 444 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 357 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 427 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 269 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 550 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 551 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 549 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 553 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 257 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

5907 {
5908  Backend *bn;
5909 
5910  /*
5911  * Check that database state allows another connection. Currently the
5912  * only possible failure is CAC_TOOMANY, so we just log an error message
5913  * based on that rather than checking the error code precisely.
5914  */
5916  {
5917  ereport(LOG,
5918  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5919  errmsg("no slot available for new worker process")));
5920  return false;
5921  }
5922 
5923  /*
5924  * Compute the cancel key that will be assigned to this session. We
5925  * probably don't need cancel keys for background workers, but we'd better
5926  * have something random in the field to prevent unfriendly people from
5927  * sending cancels to them.
5928  */
5930  {
5931  ereport(LOG,
5932  (errcode(ERRCODE_INTERNAL_ERROR),
5933  errmsg("could not generate random cancel key")));
5934  return false;
5935  }
5936 
5937  bn = malloc(sizeof(Backend));
5938  if (bn == NULL)
5939  {
5940  ereport(LOG,
5941  (errcode(ERRCODE_OUT_OF_MEMORY),
5942  errmsg("out of memory")));
5943  return false;
5944  }
5945 
5946  bn->cancel_key = MyCancelKey;
5949  bn->dead_end = false;
5950  bn->bgworker_notify = false;
5951 
5952  rw->rw_backend = bn;
5953  rw->rw_child_slot = bn->child_slot;
5954 
5955  return true;
5956 }
struct bkend * rw_backend
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2436
int errcode(int sqlerrcode)
Definition: elog.c:691
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:184
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:184
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:44
int32 cancel_key
Definition: postmaster.c:180
bool dead_end
Definition: postmaster.c:183
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5363
int child_slot
Definition: postmaster.c:181
int bkend_type
Definition: postmaster.c:182
#define ereport(elevel,...)
Definition: elog.h:155
int MyPMChildSlot
Definition: globals.c:45
int errmsg(const char *fmt,...)
Definition: elog.c:902

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

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

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

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4474 of file postmaster.c.

References AllocateFile(), Assert, AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), av, BackendInitialize(), calloc, checkDataDir(), ClosePostmasterPorts(), CreateSharedMemoryAndSemaphores(), Port::database_name, DestNone, elog, EnableSSL, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), FATAL, fork_process(), FreeFile(), Port::gss, 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, PgArchiverMain(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), PgstatCollectorMain(), pgwin32_ReserveSharedMemoryRegion(), pgwin32_signal_initialize(), bkend::pid, port, PostgresMain(), process_shared_preload_libraries(), secure_initialize(), snprintf, sprintf, StartBackgroundWorker(), SysLoggerMain(), TopMemoryContext, UsedShmemSegAddr, Port::user_name, and whereToSendOutput.

Referenced by BackendStartup().

4475 {
4476  char *av[2];
4477  const int ac = 1;
4478 
4479  av[0] = "postgres";
4480  av[1] = NULL;
4481 
4482  /*
4483  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4484  * just yet, though, because InitPostgres will need the HBA data.)
4485  */
4487 
4488  PostgresMain(ac, av, port->database_name, port->user_name);
4489 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3773
char * user_name
Definition: libpq-be.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
struct @17::@18 av[32]
char * database_name
Definition: libpq-be.h:140

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4142 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(), LOG, malloc, MyCancelKey, MyPMChildSlot, bkend::pid, RandomCancelKey(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), Port::sock, STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

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

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5729 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5730 {
5731  PG_SETMASK(&BlockSig);
5732 }
#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 5683 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().

5684 {
5686 
5687  /* XXX is this the right errcode? */
5689  ereport(FATAL,
5690  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5691  errmsg("database connection requirement not indicated during registration")));
5692 
5694 
5695  /* it had better not gotten out of "init" mode yet */
5696  if (!IsInitProcessingMode())
5697  ereport(ERROR,
5698  (errmsg("invalid processing mode in background worker")));
5700 }
int errcode(int sqlerrcode)
Definition: elog.c:691
#define SetProcessingMode(mode)
Definition: miscadmin.h:399
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
static char * username
Definition: initdb.c:134
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:155
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:589
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:51
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define IsInitProcessingMode()
Definition: miscadmin.h:394

◆ BackgroundWorkerInitializeConnectionByOid()

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

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

5707 {
5709 
5710  /* XXX is this the right errcode? */
5712  ereport(FATAL,
5713  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5714  errmsg("database connection requirement not indicated during registration")));
5715 
5716  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5717 
5718  /* it had better not gotten out of "init" mode yet */
5719  if (!IsInitProcessingMode())
5720  ereport(ERROR,
5721  (errmsg("invalid processing mode in background worker")));
5723 }
int errcode(int sqlerrcode)
Definition: elog.c:691
#define SetProcessingMode(mode)
Definition: miscadmin.h:399
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
#define ereport(elevel,...)
Definition: elog.h:155
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:589
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define IsInitProcessingMode()
Definition: miscadmin.h:394

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

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

5864 {
5865  switch (pmState)
5866  {
5867  case PM_NO_CHILDREN:
5868  case PM_WAIT_DEAD_END:
5869  case PM_SHUTDOWN_2:
5870  case PM_SHUTDOWN:
5871  case PM_WAIT_BACKENDS:
5872  case PM_STOP_BACKENDS:
5873  break;
5874 
5875  case PM_RUN:
5877  return true;
5878  /* fall through */
5879 
5880  case PM_HOT_STANDBY:
5882  return true;
5883  /* fall through */
5884 
5885  case PM_RECOVERY:
5886  case PM_STARTUP:
5887  case PM_INIT:
5889  return true;
5890  /* fall through */
5891 
5892  }
5893 
5894  return false;
5895 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:335

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 2436 of file postmaster.c.

References ALLOW_ALL_CONNS, ALLOW_SUPERUSER_CONNS, BACKEND_TYPE_ALL, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, 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().

2437 {
2438  CAC_state result = CAC_OK;
2439 
2440  /*
2441  * Can't start backends when in startup/shutdown/inconsistent recovery
2442  * state. We treat autovac workers the same as user backends for this
2443  * purpose. However, bgworkers are excluded from this test; we expect
2444  * bgworker_should_start_now() decided whether the DB state allows them.
2445  */
2446  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2447  backend_type != BACKEND_TYPE_BGWORKER)
2448  {
2449  if (Shutdown > NoShutdown)
2450  return CAC_SHUTDOWN; /* shutdown is pending */
2451  else if (!FatalError &&
2452  (pmState == PM_STARTUP ||
2453  pmState == PM_RECOVERY))
2454  return CAC_STARTUP; /* normal startup */
2455  else
2456  return CAC_RECOVERY; /* else must be crash recovery */
2457  }
2458 
2459  /*
2460  * "Smart shutdown" restrictions are applied only to normal connections,
2461  * not to autovac workers or bgworkers. When only superusers can connect,
2462  * we return CAC_SUPERUSER to indicate that superuserness must be checked
2463  * later. Note that neither CAC_OK nor CAC_SUPERUSER can safely be
2464  * returned until we have checked for too many children.
2465  */
2466  if (connsAllowed != ALLOW_ALL_CONNS &&
2467  backend_type == BACKEND_TYPE_NORMAL)
2468  {
2470  result = CAC_SUPERUSER; /* allow superusers only */
2471  else
2472  return CAC_SHUTDOWN; /* shutdown is pending */
2473  }
2474 
2475  /*
2476  * Don't start too many children.
2477  *
2478  * We allow more connections here than we can have backends because some
2479  * might still be authenticating; they might fail auth, or some existing
2480  * backend might exit before the auth cycle is completed. The exact
2481  * MaxBackends limit is enforced when a new backend tries to join the
2482  * shared-inval backend array.
2483  *
2484  * The limit here must match the sizes of the per-child-process arrays;
2485  * see comments for MaxLivePostmasterChildren().
2486  */
2488  result = CAC_TOOMANY;
2489 
2490  return result;
2491 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
static bool FatalError
Definition: postmaster.c:275
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
static int Shutdown
Definition: postmaster.c:273
static int CountChildren(int target)
Definition: postmaster.c:5373
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static PMState pmState
Definition: postmaster.c:335
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5673
static ConnsAllowedState connsAllowed
Definition: postmaster.c:350
#define NoShutdown
Definition: postmaster.c:268
CAC_state
Definition: libpq-be.h:71

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1516 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3260 of file postmaster.c.

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

Referenced by reaper().

3262 {
3263  char namebuf[MAXPGPATH];
3264  slist_mutable_iter iter;
3265 
3267  {
3268  RegisteredBgWorker *rw;
3269 
3270  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3271 
3272  if (rw->rw_pid != pid)
3273  continue;
3274 
3275 #ifdef WIN32
3276  /* see CleanupBackend */
3277  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3278  exitstatus = 0;
3279 #endif
3280 
3281  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3282  rw->rw_worker.bgw_type);
3283 
3284 
3285  if (!EXIT_STATUS_0(exitstatus))
3286  {
3287  /* Record timestamp, so we know when to restart the worker. */
3289  }
3290  else
3291  {
3292  /* Zero exit status means terminate */
3293  rw->rw_crashed_at = 0;
3294  rw->rw_terminate = true;
3295  }
3296 
3297  /*
3298  * Additionally, for shared-memory-connected workers, just like a
3299  * backend, any exit status other than 0 or 1 is considered a crash
3300  * and causes a system-wide restart.
3301  */
3302  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3303  {
3304  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3305  {
3306  HandleChildCrash(pid, exitstatus, namebuf);
3307  return true;
3308  }
3309  }
3310 
3311  /*
3312  * We must release the postmaster child slot whether this worker is
3313  * connected to shared memory or not, but we only treat it as a crash
3314  * if it is in fact connected.
3315  */
3318  {
3319  HandleChildCrash(pid, exitstatus, namebuf);
3320  return true;
3321  }
3322 
3323  /* Get it out of the BackendList and clear out remaining data */
3324  dlist_delete(&rw->rw_backend->elem);
3325 #ifdef EXEC_BACKEND
3326  ShmemBackendArrayRemove(rw->rw_backend);
3327 #endif
3328 
3329  /*
3330  * It's possible that this background worker started some OTHER
3331  * background worker and asked to be notified when that worker started
3332  * or stopped. If so, cancel any notifications destined for the
3333  * now-dead backend.
3334  */
3335  if (rw->rw_backend->bgworker_notify)
3337  free(rw->rw_backend);
3338  rw->rw_backend = NULL;
3339  rw->rw_pid = 0;
3340  rw->rw_child_slot = 0;
3341  ReportBackgroundWorkerExit(&iter); /* report child death */
3342 
3343  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3344  namebuf, pid, exitstatus);
3345 
3346  return true;
3347  }
3348 
3349  return false;
3350 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
slist_node * cur
Definition: ilist.h:241
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:458
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:185
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:492
bool bgworker_notify
Definition: postmaster.c:184
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
#define EXIT_STATUS_1(st)
Definition: postmaster.c:557
#define MAXPGPATH
slist_head BackgroundWorkerList
Definition: bgworker.c:42
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define free(a)
Definition: header.h:65
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3444
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3699
BackgroundWorker rw_worker
#define snprintf
Definition: port.h:215
#define _(x)
Definition: elog.c:88
#define EXIT_STATUS_0(st)
Definition: postmaster.c:556

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2566 of file postmaster.c.

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

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

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

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1415 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2500 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2544 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2545 {
2546 #ifdef USE_SSL
2547  secure_close(conn);
2548 #endif
2549  if (conn->gss)
2550  free(conn->gss);
2551  free(conn);
2552 }
PGconn * conn
Definition: streamutil.c:54
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:133

◆ CountChildren()

static int CountChildren ( int  target)
static

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

5374 {
5375  dlist_iter iter;
5376  int cnt = 0;
5377 
5378  dlist_foreach(iter, &BackendList)
5379  {
5380  Backend *bp = dlist_container(Backend, elem, iter.cur);
5381 
5382  if (bp->dead_end)
5383  continue;
5384 
5385  /*
5386  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5387  * it first and avoid touching shared memory for every child.
5388  */
5389  if (target != BACKEND_TYPE_ALL)
5390  {
5391  /*
5392  * Assign bkend_type for any recently announced WAL Sender
5393  * processes.
5394  */
5395  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5398 
5399  if (!(target & bp->bkend_type))
5400  continue;
5401  }
5402 
5403  cnt++;
5404  }
5405  return cnt;
5406 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:188
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
bool dead_end
Definition: postmaster.c:183
int child_slot
Definition: postmaster.c:181
int bkend_type
Definition: postmaster.c:182
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:240

◆ CreateOptsFile()

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

Definition at line 5633 of file postmaster.c.

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

Referenced by PostmasterMain().

5634 {
5635  FILE *fp;
5636  int i;
5637 
5638 #define OPTS_FILE "postmaster.opts"
5639 
5640  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5641  {
5642  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5643  return false;
5644  }
5645 
5646  fprintf(fp, "%s", fullprogname);
5647  for (i = 1; i < argc; i++)
5648  fprintf(fp, " \"%s\"", argv[i]);
5649  fputs("\n", fp);
5650 
5651  if (fclose(fp))
5652  {
5653  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5654  return false;
5655  }
5656 
5657  return true;
5658 }
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:219
#define elog(elevel,...)
Definition: elog.h:228
int i
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1545 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5771 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

5772 {
5773  pid_t worker_pid;
5774 
5775  Assert(rw->rw_pid == 0);
5776 
5777  /*
5778  * Allocate and assign the Backend element. Note we must do this before
5779  * forking, so that we can handle failures (out of memory or child-process
5780  * slots) cleanly.
5781  *
5782  * Treat failure as though the worker had crashed. That way, the
5783  * postmaster will wait a bit before attempting to start it again; if we
5784  * tried again right away, most likely we'd find ourselves hitting the
5785  * same resource-exhaustion condition.
5786  */
5787  if (!assign_backendlist_entry(rw))
5788  {
5790  return false;
5791  }
5792 
5793  ereport(DEBUG1,
5794  (errmsg("starting background worker process \"%s\"",
5795  rw->rw_worker.bgw_name)));
5796 
5797 #ifdef EXEC_BACKEND
5798  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5799 #else
5800  switch ((worker_pid = fork_process()))
5801 #endif
5802  {
5803  case -1:
5804  /* in postmaster, fork failed ... */
5805  ereport(LOG,
5806  (errmsg("could not fork worker process: %m")));
5807  /* undo what assign_backendlist_entry did */
5809  rw->rw_child_slot = 0;
5810  free(rw->rw_backend);
5811  rw->rw_backend = NULL;
5812  /* mark entry as crashed, so we'll try again later */
5814  break;
5815 
5816 #ifndef EXEC_BACKEND
5817  case 0:
5818  /* in postmaster child ... */
5820 
5821  /* Close the postmaster's sockets */
5822  ClosePostmasterPorts(false);
5823 
5824  /*
5825  * Before blowing away PostmasterContext, save this bgworker's
5826  * data where it can find it.
5827  */
5830  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5831 
5832  /* Release postmaster's working memory context */
5835  PostmasterContext = NULL;
5836 
5838 
5839  exit(1); /* should not get here */
5840  break;
5841 #endif
5842  default:
5843  /* in postmaster, fork successful ... */
5844  rw->rw_pid = worker_pid;
5845  rw->rw_backend->pid = rw->rw_pid;
5847  /* add new worker to lists of backends */
5849 #ifdef EXEC_BACKEND
5850  ShmemBackendArrayAdd(rw->rw_backend);
5851 #endif
5852  return true;
5853  }
5854 
5855  return false;
5856 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:93
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
pid_t fork_process(void)
Definition: fork_process.c:29
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:185
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2566
void StartBackgroundWorker(void)
Definition: bgworker.c:680
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:439
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5906
static dlist_head BackendList
Definition: postmaster.c:188
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define ereport(elevel,...)
Definition: elog.h:155
#define free(a)
Definition: header.h:65
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:800
pid_t pid
Definition: postmaster.c:179
int errmsg(const char *fmt,...)
Definition: elog.c:902
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:46

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5344 of file postmaster.c.

Referenced by PostmasterMain().

5345 {
5346 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5100 of file postmaster.c.

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

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

5101 {
5102 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5103 
5104  /*
5105  * There is no known cause for a postmaster to become multithreaded after
5106  * startup. Recheck to account for the possibility of unknown causes.
5107  * This message uses LOG level, because an unclean shutdown at this point
5108  * would usually not look much different from a clean shutdown.
5109  */
5110  if (pthread_is_threaded_np() != 0)
5111  ereport(LOG,
5112  (errcode(ERRCODE_INTERNAL_ERROR),
5113  errmsg_internal("postmaster became multithreaded"),
5114  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5115 #endif
5116 
5117  /* should cleanup shared memory and kill all backends */
5118 
5119  /*
5120  * Not sure of the semantics here. When the Postmaster dies, should the
5121  * backends all be killed? probably not.
5122  *
5123  * MUST -- vadim 05-10-1999
5124  */
5125 
5126  proc_exit(status);
5127 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:691
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:1035
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:989
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 1463 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ HandleChildCrash()

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

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

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1885 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

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

6570 {
6571 #ifndef WIN32
6572 
6573  /*
6574  * Create a pipe. Postmaster holds the write end of the pipe open
6575  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6576  * the read file descriptor to select() to wake up in case postmaster
6577  * dies, or check for postmaster death with a (read() == 0). Children must
6578  * close the write end as soon as possible after forking, because EOF
6579  * won't be signaled in the read end until all processes have closed the
6580  * write fd. That is taken care of in ClosePostmasterPorts().
6581  */
6583  if (pipe(postmaster_alive_fds) < 0)
6584  ereport(FATAL,
6586  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6587 
6588  /* Notify fd.c that we've eaten two FDs for the pipe. */
6591 
6592  /*
6593  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6594  * call.
6595  */
6596  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6597  ereport(FATAL,
6599  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6600 #else
6601 
6602  /*
6603  * On Windows, we use a process handle for the same purpose.
6604  */
6605  if (DuplicateHandle(GetCurrentProcess(),
6606  GetCurrentProcess(),
6607  GetCurrentProcess(),
6608  &PostmasterHandle,
6609  0,
6610  TRUE,
6611  DUPLICATE_SAME_ACCESS) == 0)
6612  ereport(FATAL,
6613  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6614  GetLastError())));
6615 #endif /* WIN32 */
6616 }
int MyProcPid
Definition: globals.c:40
#define FATAL
Definition: elog.h:52
void ReserveExternalFD(void)
Definition: fd.c:1083
int errcode_for_file_access(void)
Definition: elog.c:714
int errcode_for_socket_access(void)
Definition: elog.c:785
pid_t PostmasterPid
Definition: globals.c:95
int postmaster_alive_fds[2]
Definition: postmaster.c:565
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:989
#define Assert(condition)
Definition: c.h:800
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2630 of file postmaster.c.

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

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

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

◆ LogChildExit()

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

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

3700 {
3701  /*
3702  * size of activity_buffer is arbitrary, but set equal to default
3703  * track_activity_query_size
3704  */
3705  char activity_buffer[1024];
3706  const char *activity = NULL;
3707 
3708  if (!EXIT_STATUS_0(exitstatus))
3709  activity = pgstat_get_crashed_backend_activity(pid,
3710  activity_buffer,
3711  sizeof(activity_buffer));
3712 
3713  if (WIFEXITED(exitstatus))
3714  ereport(lev,
3715 
3716  /*------
3717  translator: %s is a noun phrase describing a child process, such as
3718  "server process" */
3719  (errmsg("%s (PID %d) exited with exit code %d",
3720  procname, pid, WEXITSTATUS(exitstatus)),
3721  activity ? errdetail("Failed process was running: %s", activity) : 0));
3722  else if (WIFSIGNALED(exitstatus))
3723  {
3724 #if defined(WIN32)
3725  ereport(lev,
3726 
3727  /*------
3728  translator: %s is a noun phrase describing a child process, such as
3729  "server process" */
3730  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3731  procname, pid, WTERMSIG(exitstatus)),
3732  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3733  activity ? errdetail("Failed process was running: %s", activity) : 0));
3734 #else
3735  ereport(lev,
3736 
3737  /*------
3738  translator: %s is a noun phrase describing a child process, such as
3739  "server process" */
3740  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3741  procname, pid, WTERMSIG(exitstatus),
3742  pg_strsignal(WTERMSIG(exitstatus))),
3743  activity ? errdetail("Failed process was running: %s", activity) : 0));
3744 #endif
3745  }
3746  else
3747  ereport(lev,
3748 
3749  /*------
3750  translator: %s is a noun phrase describing a child process, such as
3751  "server process" */
3752  (errmsg("%s (PID %d) exited with unrecognized status %d",
3753  procname, pid, exitstatus),
3754  activity ? errdetail("Failed process was running: %s", activity) : 0));
3755 }
int errhint(const char *fmt,...)
Definition: elog.c:1149
#define WTERMSIG(w)
Definition: win32_port.h:146
int errdetail(const char *fmt,...)
Definition: elog.c:1035
#define WIFEXITED(w)
Definition: win32_port.h:143
#define ereport(elevel,...)
Definition: elog.h:155
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:902
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
Definition: pgstat.c:4408
#define WIFSIGNALED(w)
Definition: win32_port.h:144
#define WEXITSTATUS(w)
Definition: win32_port.h:145
#define EXIT_STATUS_0(st)
Definition: postmaster.c:556

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5673 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5674 {
5675  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5677 }
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:133
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:134

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

5971 {
5972 #define MAX_BGWORKERS_TO_LAUNCH 100
5973  int num_launched = 0;
5974  TimestampTz now = 0;
5975  slist_mutable_iter iter;
5976 
5977  /*
5978  * During crash recovery, we have no need to be called until the state
5979  * transition out of recovery.
5980  */
5981  if (FatalError)
5982  {
5983  StartWorkerNeeded = false;
5984  HaveCrashedWorker = false;
5985  return;
5986  }
5987 
5988  /* Don't need to be called again unless we find a reason for it below */
5989  StartWorkerNeeded = false;
5990  HaveCrashedWorker = false;
5991 
5993  {
5994  RegisteredBgWorker *rw;
5995 
5996  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5997 
5998  /* ignore if already running */
5999  if (rw->rw_pid != 0)
6000  continue;
6001 
6002  /* if marked for death, clean up and remove from list */
6003  if (rw->rw_terminate)
6004  {
6005  ForgetBackgroundWorker(&iter);
6006  continue;
6007  }
6008 
6009  /*
6010  * If this worker has crashed previously, maybe it needs to be
6011  * restarted (unless on registration it specified it doesn't want to
6012  * be restarted at all). Check how long ago did a crash last happen.
6013  * If the last crash is too recent, don't start it right away; let it
6014  * be restarted once enough time has passed.
6015  */
6016  if (rw->rw_crashed_at != 0)
6017  {
6019  {
6020  int notify_pid;
6021 
6022  notify_pid = rw->rw_worker.bgw_notify_pid;
6023 
6024  ForgetBackgroundWorker(&iter);
6025 
6026  /* Report worker is gone now. */
6027  if (notify_pid != 0)
6028  kill(notify_pid, SIGUSR1);
6029 
6030  continue;
6031  }
6032 
6033  /* read system time only when needed */
6034  if (now == 0)
6035  now = GetCurrentTimestamp();
6036 
6038  rw->rw_worker.bgw_restart_time * 1000))
6039  {
6040  /* Set flag to remember that we have workers to start later */
6041  HaveCrashedWorker = true;
6042  continue;
6043  }
6044  }
6045 
6047  {
6048  /* reset crash time before trying to start worker */
6049  rw->rw_crashed_at = 0;
6050 
6051  /*
6052  * Try to start the worker.
6053  *
6054  * On failure, give up processing workers for now, but set
6055  * StartWorkerNeeded so we'll come back here on the next iteration
6056  * of ServerLoop to try again. (We don't want to wait, because
6057  * there might be additional ready-to-run workers.) We could set
6058  * HaveCrashedWorker as well, since this worker is now marked
6059  * crashed, but there's no need because the next run of this
6060  * function will do that.
6061  */
6062  if (!do_start_bgworker(rw))
6063  {
6064  StartWorkerNeeded = true;
6065  return;
6066  }
6067 
6068  /*
6069  * If we've launched as many workers as allowed, quit, but have
6070  * ServerLoop call us again to look for additional ready-to-run
6071  * workers. There might not be any, but we'll find out the next
6072  * time we run.
6073  */
6074  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
6075  {
6076  StartWorkerNeeded = true;
6077  return;
6078  }
6079  }
6080  }
6081 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:376
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5863
#define SIGUSR1
Definition: win32_port.h:171
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
int64 TimestampTz
Definition: timestamp.h:39
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:94
#define kill(pid, sig)
Definition: win32_port.h:454
static bool FatalError
Definition: postmaster.c:275
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1709
static volatile bool HaveCrashedWorker
Definition: postmaster.c:377
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:411
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5771
#define MAX_BGWORKERS_TO_LAUNCH
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
pid_t bgw_notify_pid
Definition: bgworker.h:99
BackgroundWorker rw_worker
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

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

5615 {
5616  if (WalReceiverPID == 0 &&
5617  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5618  pmState == PM_HOT_STANDBY) &&
5620  {
5622  if (WalReceiverPID != 0)
5623  WalReceiverRequested = false;
5624  /* else leave the flag set, so we'll try again later */
5625  }
5626 }
static pid_t WalReceiverPID
Definition: postmaster.c:250
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:373
static int Shutdown
Definition: postmaster.c:273
#define SmartShutdown
Definition: postmaster.c:269
static PMState pmState
Definition: postmaster.c:335
#define StartWalReceiver()
Definition: postmaster.c:553

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2763 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, pmState, PostmasterStateMachine(), Shutdown, SIGQUIT, SmartShutdown, TerminateChildren(), and UnBlockSig.

Referenced by PostmasterMain().

2764 {
2765  int save_errno = errno;
2766 
2767  /*
2768  * We rely on the signal mechanism to have blocked all signals ... except
2769  * on Windows, which lacks sigaction(), so we have to do it manually.
2770  */
2771 #ifdef WIN32
2772  PG_SETMASK(&BlockSig);
2773 #endif
2774 
2775  ereport(DEBUG2,
2776  (errmsg_internal("postmaster received signal %d",
2777  postgres_signal_arg)));
2778 
2779  switch (postgres_signal_arg)
2780  {
2781  case SIGTERM:
2782 
2783  /*
2784  * Smart Shutdown:
2785  *
2786  * Wait for children to end their work, then shut down.
2787  */
2788  if (Shutdown >= SmartShutdown)
2789  break;
2791  ereport(LOG,
2792  (errmsg("received smart shutdown request")));
2793 
2794  /* Report status */
2796 #ifdef USE_SYSTEMD
2797  sd_notify(0, "STOPPING=1");
2798 #endif
2799 
2800  /*
2801  * If we reached normal running, we have to wait for any online
2802  * backup mode to end; otherwise go straight to waiting for client
2803  * backends to exit. (The difference is that in the former state,
2804  * we'll still let in new superuser clients, so that somebody can
2805  * end the online backup mode.) If already in PM_STOP_BACKENDS or
2806  * a later state, do not change it.
2807  */
2808  if (pmState == PM_RUN)
2810  else if (pmState == PM_HOT_STANDBY)
2812  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2813  {
2814  /* There should be no clients, so proceed to stop children */
2816  }
2817 
2818  /*
2819  * Now wait for online backup mode to end and backends to exit. If
2820  * that is already the case, PostmasterStateMachine will take the
2821  * next step.
2822  */
2824  break;
2825 
2826  case SIGINT:
2827 
2828  /*
2829  * Fast Shutdown:
2830  *
2831  * Abort all children with SIGTERM (rollback active transactions
2832  * and exit) and shut down when they are gone.
2833  */
2834  if (Shutdown >= FastShutdown)
2835  break;
2837  ereport(LOG,
2838  (errmsg("received fast shutdown request")));
2839 
2840  /* Report status */
2842 #ifdef USE_SYSTEMD
2843  sd_notify(0, "STOPPING=1");
2844 #endif
2845 
2846  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2847  {
2848  /* Just shut down background processes silently */
2850  }
2851  else if (pmState == PM_RUN ||
2853  {
2854  /* Report that we're about to zap live client sessions */
2855  ereport(LOG,
2856  (errmsg("aborting any active transactions")));
2858  }
2859 
2860  /*
2861  * PostmasterStateMachine will issue any necessary signals, or
2862  * take the next step if no child processes need to be killed.
2863  */
2865  break;
2866 
2867  case SIGQUIT:
2868 
2869  /*
2870  * Immediate Shutdown:
2871  *
2872  * abort all children with SIGQUIT, wait for them to exit,
2873  * terminate remaining ones with SIGKILL, then exit without
2874  * attempt to properly shut down the data base system.
2875  */
2876  if (Shutdown >= ImmediateShutdown)
2877  break;
2879  ereport(LOG,
2880  (errmsg("received immediate shutdown request")));
2881 
2882  /* Report status */
2884 #ifdef USE_SYSTEMD
2885  sd_notify(0, "STOPPING=1");
2886 #endif
2887 
2890 
2891  /* set stopwatch for them to die */
2892  AbortStartTime = time(NULL);
2893 
2894  /*
2895  * Now wait for backends to exit. If there are none,
2896  * PostmasterStateMachine will take the next step.
2897  */
2899  break;
2900  }
2901 
2902 #ifdef WIN32
2904 #endif
2905 
2906  errno = save_errno;
2907 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3764
#define SIGQUIT
Definition: win32_port.h:160
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1329
#define LOG
Definition: elog.h:26
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:273
#define SmartShutdown
Definition: postmaster.c:269
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4109
#define FastShutdown
Definition: postmaster.c:270
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:335
#define ImmediateShutdown
Definition: postmaster.c:271
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:989
static ConnsAllowedState connsAllowed
Definition: postmaster.c:350
int errmsg(const char *fmt,...)
Definition: elog.c:902
#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:354

◆ PostmasterMain()

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

Definition at line 575 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), DEBUG3, DestNone, dummy_handler(), elog, enable_bonjour, EnableSSL, environ, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, free, get_stats_option_name(), GetConfigOption(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), i, InitializeGUCOptions(), InitializeMaxBackends(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenSocket, load_hba(), load_ident(), LocalProcessControlFile(), LOCK_FILE_LINE_LISTEN_ADDR, LOCK_FILE_LINE_PM_STATUS, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, LOG_METAINFO_DATAFILE, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworkers(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, name, NIL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_SETMASK, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, PM_STATUS_STARTING, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal_pm(), process_shared_preload_libraries(), progname, pstrdup(), reaper(), Reinit, RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedBackends, reset_shared(), S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), SendStop, ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGHUP_handler(), SIGPIPE, SIGQUIT, SIGUSR1, sigusr1_handler(), SIGUSR2, SplitDirectoriesString(), SplitGUCList(), STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror, success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

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

Referenced by BackgroundWorkerStateChange().

6090 {
6091  dlist_iter iter;
6092  Backend *bp;
6093 
6094  dlist_foreach(iter, &BackendList)
6095  {
6096  bp = dlist_container(Backend, elem, iter.cur);
6097  if (bp->pid == pid)
6098  {
6099  bp->bgworker_notify = true;
6100  return true;
6101  }
6102  }
6103  return false;
6104 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:184
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:188
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:179

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

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

3765 {
3766  /* If we're doing a smart shutdown, try to advance that state. */
3767  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3768  {
3770  {
3771  /*
3772  * ALLOW_SUPERUSER_CONNS state ends as soon as online backup mode
3773  * is not active.
3774  */
3775  if (!BackupInProgress())
3777  }
3778 
3780  {
3781  /*
3782  * ALLOW_NO_CONNS state ends when we have no normal client
3783  * backends running. Then we're ready to stop other children.
3784  */
3787  }
3788  }
3789 
3790  /*
3791  * If we're ready to do so, signal child processes to shut down. (This
3792  * isn't a persistent state, but treating it as a distinct pmState allows
3793  * us to share this code across multiple shutdown code paths.)
3794  */
3795  if (pmState == PM_STOP_BACKENDS)
3796  {
3797  /* Signal all backend children except walsenders */
3798  SignalSomeChildren(SIGTERM,
3800  /* and the autovac launcher too */
3801  if (AutoVacPID != 0)
3802  signal_child(AutoVacPID, SIGTERM);
3803  /* and the bgwriter too */
3804  if (BgWriterPID != 0)
3805  signal_child(BgWriterPID, SIGTERM);
3806  /* and the walwriter too */
3807  if (WalWriterPID != 0)
3808  signal_child(WalWriterPID, SIGTERM);
3809  /* If we're in recovery, also stop startup and walreceiver procs */
3810  if (StartupPID != 0)
3811  signal_child(StartupPID, SIGTERM);
3812  if (WalReceiverPID != 0)
3813  signal_child(WalReceiverPID, SIGTERM);
3814  /* checkpointer, archiver, stats, and syslogger may continue for now */
3815 
3816  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3818  }
3819 
3820  /*
3821  * If we are in a state-machine state that implies waiting for backends to
3822  * exit, see if they're all gone, and change state if so.
3823  */
3824  if (pmState == PM_WAIT_BACKENDS)
3825  {
3826  /*
3827  * PM_WAIT_BACKENDS state ends when we have no regular backends
3828  * (including autovac workers), no bgworkers (including unconnected
3829  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3830  * doing crash recovery or an immediate shutdown then we expect the
3831  * checkpointer to exit as well, otherwise not. The archiver, stats,
3832  * and syslogger processes are disregarded since they are not
3833  * connected to shared memory; we also disregard dead_end children
3834  * here. Walsenders are also disregarded, they will be terminated
3835  * later after writing the checkpoint record, like the archiver
3836  * process.
3837  */
3839  StartupPID == 0 &&
3840  WalReceiverPID == 0 &&
3841  BgWriterPID == 0 &&
3842  (CheckpointerPID == 0 ||
3844  WalWriterPID == 0 &&
3845  AutoVacPID == 0)
3846  {
3848  {
3849  /*
3850  * Start waiting for dead_end children to die. This state
3851  * change causes ServerLoop to stop creating new ones.
3852  */
3854 
3855  /*
3856  * We already SIGQUIT'd the archiver and stats processes, if
3857  * any, when we started immediate shutdown or entered
3858  * FatalError state.
3859  */
3860  }
3861  else
3862  {
3863  /*
3864  * If we get here, we are proceeding with normal shutdown. All
3865  * the regular children are gone, and it's time to tell the
3866  * checkpointer to do a shutdown checkpoint.
3867  */
3869  /* Start the checkpointer if not running */
3870  if (CheckpointerPID == 0)
3872  /* And tell it to shut down */
3873  if (CheckpointerPID != 0)
3874  {
3876  pmState = PM_SHUTDOWN;
3877  }
3878  else
3879  {
3880  /*
3881  * If we failed to fork a checkpointer, just shut down.
3882  * Any required cleanup will happen at next restart. We
3883  * set FatalError so that an "abnormal shutdown" message
3884  * gets logged when we exit.
3885  */
3886  FatalError = true;
3888 
3889  /* Kill the walsenders, archiver and stats collector too */
3891  if (PgArchPID != 0)
3893  if (PgStatPID != 0)
3895  }
3896  }
3897  }
3898  }
3899 
3900  if (pmState == PM_SHUTDOWN_2)
3901  {
3902  /*
3903  * PM_SHUTDOWN_2 state ends when there's no other children than
3904  * dead_end children left. There shouldn't be any regular backends
3905  * left by now anyway; what we're really waiting for is walsenders and
3906  * archiver.
3907  */
3908  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3909  {
3911  }
3912  }
3913 
3914  if (pmState == PM_WAIT_DEAD_END)
3915  {
3916  /*
3917  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3918  * (ie, no dead_end children remain), and the archiver and stats
3919  * collector are gone too.
3920  *
3921  * The reason we wait for those two is to protect them against a new
3922  * postmaster starting conflicting subprocesses; this isn't an
3923  * ironclad protection, but it at least helps in the
3924  * shutdown-and-immediately-restart scenario. Note that they have
3925  * already been sent appropriate shutdown signals, either during a
3926  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3927  * FatalError processing.
3928  */
3929  if (dlist_is_empty(&BackendList) &&
3930  PgArchPID == 0 && PgStatPID == 0)
3931  {
3932  /* These other guys should be dead already */
3933  Assert(StartupPID == 0);
3934  Assert(WalReceiverPID == 0);
3935  Assert(BgWriterPID == 0);
3936  Assert(CheckpointerPID == 0);
3937  Assert(WalWriterPID == 0);
3938  Assert(AutoVacPID == 0);
3939  /* syslogger is not considered here */
3941  }
3942  }
3943 
3944  /*
3945  * If we've been told to shut down, we exit as soon as there are no
3946  * remaining children. If there was a crash, cleanup will occur at the
3947  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3948  * crash before exiting, but that seems unwise if we are quitting because
3949  * we got SIGTERM from init --- there may well not be time for recovery
3950  * before init decides to SIGKILL us.)
3951  *
3952  * Note that the syslogger continues to run. It will exit when it sees
3953  * EOF on its input pipe, which happens when there are no more upstream
3954  * processes.
3955  */
3957  {
3958  if (FatalError)
3959  {
3960  ereport(LOG, (errmsg("abnormal database system shutdown")));
3961  ExitPostmaster(1);
3962  }
3963  else
3964  {
3965  /*
3966  * Terminate exclusive backup mode to avoid recovery after a clean
3967  * fast shutdown. Since an exclusive backup can only be taken
3968  * during normal running (and not, for example, while running
3969  * under Hot Standby) it only makes sense to do this if we reached
3970  * normal running. If we're still in recovery, the backup file is
3971  * one we're recovering *from*, and we must keep it around so that
3972  * recovery restarts from the right place.
3973  */
3975  CancelBackup();
3976 
3977  /* Normal exit from the postmaster is here */
3978  ExitPostmaster(0);
3979  }
3980  }
3981 
3982  /*
3983  * If the startup process failed, or the user does not want an automatic
3984  * restart after backend crashes, wait for all non-syslogger children to
3985  * exit, and then exit postmaster. We don't try to reinitialize when the
3986  * startup process fails, because more than likely it will just fail again
3987  * and we will keep trying forever.
3988  */
3989  if (pmState == PM_NO_CHILDREN &&
3991  ExitPostmaster(1);
3992 
3993  /*
3994  * If we need to recover from a crash, wait for all non-syslogger children
3995  * to exit, then reset shmem and StartupDataBase.
3996  */
3997  if (FatalError && pmState == PM_NO_CHILDREN)
3998  {
3999  ereport(LOG,
4000  (errmsg("all server processes terminated; reinitializing")));
4001 
4002  /* allow background workers to immediately restart */
4004 
4005  shmem_exit(1);
4006 
4007  /* re-read control file into local memory */
4009 
4010  reset_shared();
4011 
4013  Assert(StartupPID != 0);
4015  pmState = PM_STARTUP;
4016  /* crash recovery started, reset SIGKILL flag */
4017  AbortStartTime = 0;
4018  }
4019 }
void CancelBackup(void)
Definition: xlog.c:11797
#define SIGQUIT
Definition: win32_port.h:160
static StartupStatusEnum StartupStatus
Definition: postmaster.c:265
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define StartupDataBase()
Definition: postmaster.c:549
static void reset_shared(void)
Definition: postmaster.c:2664
static pid_t PgStatPID
Definition: postmaster.c:253
static pid_t CheckpointerPID
Definition: postmaster.c:248
static pid_t WalReceiverPID
Definition: postmaster.c:250
static bool FatalError
Definition: postmaster.c:275
void shmem_exit(int code)
Definition: ipc.c:224
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4065
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define SIGUSR2
Definition: win32_port.h:172
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11777
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:514
#define SignalChildren(sig)
Definition: postmaster.c:427
static int Shutdown
Definition: postmaster.c:273
static pid_t BgWriterPID
Definition: postmaster.c:247
#define StartCheckpointer()
Definition: postmaster.c:551
static int CountChildren(int target)
Definition: postmaster.c:5373
static pid_t StartupPID
Definition: postmaster.c:246
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5100
bool restart_after_crash
Definition: postmaster.c:243
static dlist_head BackendList
Definition: postmaster.c:188
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5033
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4039
static PMState pmState
Definition: postmaster.c:335
#define ImmediateShutdown
Definition: postmaster.c:271
#define ereport(elevel,...)
Definition: elog.h:155
static pid_t WalWriterPID
Definition: postmaster.c:249
#define Assert(condition)
Definition: c.h:800
static ConnsAllowedState connsAllowed
Definition: postmaster.c:350
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:268
static pid_t AutoVacPID
Definition: postmaster.c:251
int errmsg(const char *fmt,...)
Definition: elog.c:902
static bool ReachedNormalRunning
Definition: postmaster.c:359
static time_t AbortStartTime
Definition: postmaster.c:354
static pid_t PgArchPID
Definition: postmaster.c:252

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5329 of file postmaster.c.

Referenced by BackendInitialize().

5330 {
5331  _exit(1);
5332 }

◆ processCancelRequest()

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

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

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

◆ ProcessStartupPacket()

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

Definition at line 1927 of file postmaster.c.

References SockAddr::addr, am_db_walsender, am_walsender, Port::application_name, B_BACKEND, B_WAL_SENDER, buf, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_SUPERUSER, CAC_TOOMANY, Port::canAcceptConnections, CANCEL_REQUEST_CODE, Port::cmdline_options, COMMERROR, StartupPacket::database, Port::database_name, Db_user_namespace, EINTR, ereport, errcode(), ERRCODE_CANNOT_CONNECT_NOW, errcode_for_socket_access(), errhint(), errmsg(), FATAL, FrontendProtocol, Port::guc_options, IS_AF_UNIX, Port::laddr, lappend(), MAX_STARTUP_PACKET_LENGTH, MemoryContextSwitchTo(), MyBackendType, NAMEDATALEN, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, NIL, StartupPacket::options, palloc0(), parse_bool(), pg_clean_ascii(), pg_ntoh32, PG_PROTOCOL_EARLIEST, PG_PROTOCOL_LATEST, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, pq_endmsgread(), pq_getbytes(), pq_startmsgread(), processCancelRequest(), Port::proto, psprintf(), pstrdup(), secure_open_gssapi(), secure_open_server(), send, SendNegotiateProtocolVersion(), Port::sock, STATUS_ERROR, STATUS_OK, TopMemoryContext, StartupPacket::user, and Port::user_name.

Referenced by BackendInitialize().

1928 {
1929  int32 len;
1930  void *buf;
1931  ProtocolVersion proto;
1932  MemoryContext oldcontext;
1933 
1934  pq_startmsgread();
1935 
1936  /*
1937  * Grab the first byte of the length word separately, so that we can tell
1938  * whether we have no data at all or an incomplete packet. (This might
1939  * sound inefficient, but it's not really, because of buffering in
1940  * pqcomm.c.)
1941  */
1942  if (pq_getbytes((char *) &len, 1) == EOF)
1943  {
1944  /*
1945  * If we get no data at all, don't clutter the log with a complaint;
1946  * such cases often occur for legitimate reasons. An example is that
1947  * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
1948  * client didn't like our response, it'll probably just drop the
1949  * connection. Service-monitoring software also often just opens and
1950  * closes a connection without sending anything. (So do port
1951  * scanners, which may be less benign, but it's not really our job to
1952  * notice those.)
1953  */
1954  return STATUS_ERROR;
1955  }
1956 
1957  if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
1958  {
1959  /* Got a partial length word, so bleat about that */
1960  if (!ssl_done && !gss_done)
1962  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1963  errmsg("incomplete startup packet")));
1964  return STATUS_ERROR;
1965  }
1966 
1967  len = pg_ntoh32(len);
1968  len -= 4;
1969 
1970  if (len < (int32) sizeof(ProtocolVersion) ||
1972  {
1974  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1975  errmsg("invalid length of startup packet")));
1976  return STATUS_ERROR;
1977  }
1978 
1979  /*
1980  * Allocate at least the size of an old-style startup packet, plus one
1981  * extra byte, and make sure all are zeroes. This ensures we will have
1982  * null termination of all strings, in both fixed- and variable-length
1983