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 557 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 558 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 559 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 271 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 272 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:336
#define XLogArchivingActive()
Definition: xlog.h:180

Definition at line 445 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 358 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 428 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 270 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 551 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 552 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 550 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 554 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 258 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

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

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

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

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

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4450 of file postmaster.c.

References AllocateFile(), Assert, AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), av, BackendInitialize(), checkDataDir(), ClosePostmasterPorts(), CreateSharedMemoryAndSemaphores(), Port::database_name, DestNone, elog, EnableSSL, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), FATAL, fork_process(), FreeFile(), i, InitAuxiliaryProcess(), InitializeGUCOptions(), InitPostmasterChild(), InitProcess(), InitShmemAccess(), IsBackgroundWorker, IsPostmasterEnvironment, lengthof, LocalProcessControlFile(), LOG, MakePGDirectory(), malloc, MAXPGPATH, MemoryContextSwitchTo(), MyProcPid, PG_BINARY_W, PG_TEMP_FILE_PREFIX, PG_TEMP_FILES_DIR, 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().

4451 {
4452  char *av[2];
4453  const int ac = 1;
4454 
4455  av[0] = "postgres";
4456  av[1] = NULL;
4457 
4458  /*
4459  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4460  * just yet, though, because InitPostgres will need the HBA data.)
4461  */
4463 
4464  PostgresMain(ac, av, port->database_name, port->user_name);
4465 }
struct @11::@12 av[32]
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3771
char * user_name
Definition: libpq-be.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * database_name
Definition: libpq-be.h:140

◆ BackendStartup()

static int BackendStartup ( Port port)
static

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

4119 {
4120  Backend *bn; /* for backend cleanup */
4121  pid_t pid;
4122 
4123  /*
4124  * Create backend data structure. Better before the fork() so we can
4125  * handle failure cleanly.
4126  */
4127  bn = (Backend *) malloc(sizeof(Backend));
4128  if (!bn)
4129  {
4130  ereport(LOG,
4131  (errcode(ERRCODE_OUT_OF_MEMORY),
4132  errmsg("out of memory")));
4133  return STATUS_ERROR;
4134  }
4135 
4136  /*
4137  * Compute the cancel key that will be assigned to this backend. The
4138  * backend will have its own copy in the forked-off process' value of
4139  * MyCancelKey, so that it can transmit the key to the frontend.
4140  */
4142  {
4143  free(bn);
4144  ereport(LOG,
4145  (errcode(ERRCODE_INTERNAL_ERROR),
4146  errmsg("could not generate random cancel key")));
4147  return STATUS_ERROR;
4148  }
4149 
4150  bn->cancel_key = MyCancelKey;
4151 
4152  /* Pass down canAcceptConnections state */
4154  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4156 
4157  /*
4158  * Unless it's a dead_end child, assign it a child slot number
4159  */
4160  if (!bn->dead_end)
4162  else
4163  bn->child_slot = 0;
4164 
4165  /* Hasn't asked to be notified about any bgworkers yet */
4166  bn->bgworker_notify = false;
4167 
4168 #ifdef EXEC_BACKEND
4169  pid = backend_forkexec(port);
4170 #else /* !EXEC_BACKEND */
4171  pid = fork_process();
4172  if (pid == 0) /* child */
4173  {
4174  free(bn);
4175 
4176  /* Detangle from postmaster */
4178 
4179  /* Close the postmaster's sockets */
4180  ClosePostmasterPorts(false);
4181 
4182  /* Perform additional initialization and collect startup packet */
4183  BackendInitialize(port);
4184 
4185  /* And run the backend */
4186  BackendRun(port);
4187  }
4188 #endif /* EXEC_BACKEND */
4189 
4190  if (pid < 0)
4191  {
4192  /* in parent, fork failed */
4193  int save_errno = errno;
4194 
4195  if (!bn->dead_end)
4197  free(bn);
4198  errno = save_errno;
4199  ereport(LOG,
4200  (errmsg("could not fork new process for connection: %m")));
4201  report_fork_failure_to_client(port, save_errno);
4202  return STATUS_ERROR;
4203  }
4204 
4205  /* in parent, successful fork */
4206  ereport(DEBUG2,
4207  (errmsg_internal("forked new backend, pid=%d socket=%d",
4208  (int) pid, (int) port->sock)));
4209 
4210  /*
4211  * Everything's been successful, it's safe to add this backend to our list
4212  * of backends.
4213  */
4214  bn->pid = pid;
4215  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4217 
4218 #ifdef EXEC_BACKEND
4219  if (!bn->dead_end)
4220  ShmemBackendArrayAdd(bn);
4221 #endif
4222 
4223  return STATUS_OK;
4224 }
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2420
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:4450
pid_t fork_process(void)
Definition: fork_process.c:29
int errcode(int sqlerrcode)
Definition: elog.c:694
#define STATUS_ERROR
Definition: c.h:1171
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#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:2532
pgsocket sock
Definition: libpq-be.h:122
bool bgworker_notify
Definition: postmaster.c:184
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:219
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:45
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:4235
int32 cancel_key
Definition: postmaster.c:180
bool dead_end
Definition: postmaster.c:183
#define STATUS_OK
Definition: c.h:1170
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5335
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:992
pid_t pid
Definition: postmaster.c:179
int MyPMChildSlot
Definition: globals.c:46
int errmsg(const char *fmt,...)
Definition: elog.c:905
static void BackendInitialize(Port *port)
Definition: postmaster.c:4270

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5705 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5706 {
5707  PG_SETMASK(&BlockSig);
5708 }
#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 5659 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().

5660 {
5662 
5663  /* XXX is this the right errcode? */
5665  ereport(FATAL,
5666  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5667  errmsg("database connection requirement not indicated during registration")));
5668 
5670 
5671  /* it had better not gotten out of "init" mode yet */
5672  if (!IsInitProcessingMode())
5673  ereport(ERROR,
5674  (errmsg("invalid processing mode in background worker")));
5676 }
int errcode(int sqlerrcode)
Definition: elog.c:694
#define SetProcessingMode(mode)
Definition: miscadmin.h:400
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define ERROR
Definition: elog.h:45
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:54
const char * username
Definition: pgbench.c:246
#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:579
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:51
int errmsg(const char *fmt,...)
Definition: elog.c:905
#define IsInitProcessingMode()
Definition: miscadmin.h:395

◆ BackgroundWorkerInitializeConnectionByOid()

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

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

5683 {
5685 
5686  /* XXX is this the right errcode? */
5688  ereport(FATAL,
5689  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5690  errmsg("database connection requirement not indicated during registration")));
5691 
5692  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5693 
5694  /* it had better not gotten out of "init" mode yet */
5695  if (!IsInitProcessingMode())
5696  ereport(ERROR,
5697  (errmsg("invalid processing mode in background worker")));
5699 }
int errcode(int sqlerrcode)
Definition: elog.c:694
#define SetProcessingMode(mode)
Definition: miscadmin.h:400
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define ERROR
Definition: elog.h:45
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:54
#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:579
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:905
#define IsInitProcessingMode()
Definition: miscadmin.h:395

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

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

5840 {
5841  switch (pmState)
5842  {
5843  case PM_NO_CHILDREN:
5844  case PM_WAIT_DEAD_END:
5845  case PM_SHUTDOWN_2:
5846  case PM_SHUTDOWN:
5847  case PM_WAIT_BACKENDS:
5848  case PM_STOP_BACKENDS:
5849  break;
5850 
5851  case PM_RUN:
5853  return true;
5854  /* fall through */
5855 
5856  case PM_HOT_STANDBY:
5858  return true;
5859  /* fall through */
5860 
5861  case PM_RECOVERY:
5862  case PM_STARTUP:
5863  case PM_INIT:
5865  return true;
5866  /* fall through */
5867 
5868  }
5869 
5870  return false;
5871 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:336

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

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

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

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1523 of file postmaster.c.

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

Referenced by PostmasterMain().

1524 {
1525  char path[MAXPGPATH];
1526  FILE *fp;
1527 
1528  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1529 
1530  fp = AllocateFile(path, PG_BINARY_R);
1531  if (fp == NULL)
1532  {
1533  write_stderr("%s: could not find the database system\n"
1534  "Expected to find it in the directory \"%s\",\n"
1535  "but could not open file \"%s\": %s\n",
1536  progname, DataDir, path, strerror(errno));
1537  ExitPostmaster(2);
1538  }
1539  FreeFile(fp);
1540 }
const char * progname
Definition: main.c:46
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1273
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5070
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2354
#define strerror
Definition: port.h:229
int FreeFile(FILE *file)
Definition: fd.c:2553
char * DataDir
Definition: globals.c:63
#define snprintf
Definition: port.h:216

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

3330 {
3331  dlist_mutable_iter iter;
3332 
3333  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3334 
3335  /*
3336  * If a backend dies in an ugly way then we must signal all other backends
3337  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3338  * assume everything is all right and proceed to remove the backend from
3339  * the active backend list.
3340  */
3341 
3342 #ifdef WIN32
3343 
3344  /*
3345  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3346  * since that sometimes happens under load when the process fails to start
3347  * properly (long before it starts using shared memory). Microsoft reports
3348  * it is related to mutex failure:
3349  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3350  */
3351  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3352  {
3353  LogChildExit(LOG, _("server process"), pid, exitstatus);
3354  exitstatus = 0;
3355  }
3356 #endif
3357 
3358  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3359  {
3360  HandleChildCrash(pid, exitstatus, _("server process"));
3361  return;
3362  }
3363 
3365  {
3366  Backend *bp = dlist_container(Backend, elem, iter.cur);
3367 
3368  if (bp->pid == pid)
3369  {
3370  if (!bp->dead_end)
3371  {
3373  {
3374  /*
3375  * Uh-oh, the child failed to clean itself up. Treat as a
3376  * crash after all.
3377  */
3378  HandleChildCrash(pid, exitstatus, _("server process"));
3379  return;
3380  }
3381 #ifdef EXEC_BACKEND
3382  ShmemBackendArrayRemove(bp);
3383 #endif
3384  }
3385  if (bp->bgworker_notify)
3386  {
3387  /*
3388  * This backend may have been slated to receive SIGUSR1 when
3389  * some background worker started or stopped. Cancel those
3390  * notifications, as we don't want to signal PIDs that are not
3391  * PostgreSQL backends. This gets skipped in the (probably
3392  * very common) case where the backend has never requested any
3393  * such notifications.
3394  */
3396  }
3397  dlist_delete(iter.cur);
3398  free(bp);
3399  break;
3400  }
3401  }
3402 }
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define LOG
Definition: elog.h:26
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:503
bool bgworker_notify
Definition: postmaster.c:184
#define EXIT_STATUS_1(st)
Definition: postmaster.c:558
#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:3412
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3668
#define _(x)
Definition: elog.c:89
#define EXIT_STATUS_0(st)
Definition: postmaster.c:557

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

3230 {
3231  char namebuf[MAXPGPATH];
3232  slist_mutable_iter iter;
3233 
3235  {
3236  RegisteredBgWorker *rw;
3237 
3238  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3239 
3240  if (rw->rw_pid != pid)
3241  continue;
3242 
3243 #ifdef WIN32
3244  /* see CleanupBackend */
3245  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3246  exitstatus = 0;
3247 #endif
3248 
3249  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3250  rw->rw_worker.bgw_type);
3251 
3252 
3253  if (!EXIT_STATUS_0(exitstatus))
3254  {
3255  /* Record timestamp, so we know when to restart the worker. */
3257  }
3258  else
3259  {
3260  /* Zero exit status means terminate */
3261  rw->rw_crashed_at = 0;
3262  rw->rw_terminate = true;
3263  }
3264 
3265  /*
3266  * Additionally, for shared-memory-connected workers, just like a
3267  * backend, any exit status other than 0 or 1 is considered a crash
3268  * and causes a system-wide restart.
3269  */
3270  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3271  {
3272  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3273  {
3274  HandleChildCrash(pid, exitstatus, namebuf);
3275  return true;
3276  }
3277  }
3278 
3279  /*
3280  * We must release the postmaster child slot whether this worker is
3281  * connected to shared memory or not, but we only treat it as a crash
3282  * if it is in fact connected.
3283  */
3286  {
3287  HandleChildCrash(pid, exitstatus, namebuf);
3288  return true;
3289  }
3290 
3291  /* Get it out of the BackendList and clear out remaining data */
3292  dlist_delete(&rw->rw_backend->elem);
3293 #ifdef EXEC_BACKEND
3294  ShmemBackendArrayRemove(rw->rw_backend);
3295 #endif
3296 
3297  /*
3298  * It's possible that this background worker started some OTHER
3299  * background worker and asked to be notified when that worker started
3300  * or stopped. If so, cancel any notifications destined for the
3301  * now-dead backend.
3302  */
3303  if (rw->rw_backend->bgworker_notify)
3305  free(rw->rw_backend);
3306  rw->rw_backend = NULL;
3307  rw->rw_pid = 0;
3308  rw->rw_child_slot = 0;
3309  ReportBackgroundWorkerExit(&iter); /* report child death */
3310 
3311  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3312  namebuf, pid, exitstatus);
3313 
3314  return true;
3315  }
3316 
3317  return false;
3318 }
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:469
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#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:503
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:558
#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:3412
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3668
BackgroundWorker rw_worker
#define snprintf
Definition: port.h:216
#define _(x)
Definition: elog.c:89
#define EXIT_STATUS_0(st)
Definition: postmaster.c:557

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

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

2533 {
2534  int i;
2535 
2536 #ifndef WIN32
2537 
2538  /*
2539  * Close the write end of postmaster death watch pipe. It's important to
2540  * do this as early as possible, so that if postmaster dies, others won't
2541  * think that it's still running because we're holding the pipe open.
2542  */
2544  ereport(FATAL,
2546  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2548  /* Notify fd.c that we released one pipe FD. */
2550 #endif
2551 
2552  /*
2553  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2554  * so we don't call ReleaseExternalFD() here.
2555  */
2556  for (i = 0; i < MAXLISTEN; i++)
2557  {
2558  if (ListenSocket[i] != PGINVALID_SOCKET)
2559  {
2562  }
2563  }
2564 
2565  /*
2566  * If using syslogger, close the read side of the pipe. We don't bother
2567  * tracking this in fd.c, either.
2568  */
2569  if (!am_syslogger)
2570  {
2571 #ifndef WIN32
2572  if (syslogPipe[0] >= 0)
2573  close(syslogPipe[0]);
2574  syslogPipe[0] = -1;
2575 #else
2576  if (syslogPipe[0])
2577  CloseHandle(syslogPipe[0]);
2578  syslogPipe[0] = 0;
2579 #endif
2580  }
2581 
2582 #ifdef USE_BONJOUR
2583  /* If using Bonjour, close the connection to the mDNS daemon */
2584  if (bonjour_sdref)
2585  close(DNSServiceRefSockFD(bonjour_sdref));
2586 #endif
2587 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
#define FATAL
Definition: elog.h:54
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:717
int postmaster_alive_fds[2]
Definition: postmaster.c:566
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:992
void ReleaseExternalFD(void)
Definition: fd.c:1129
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 1421 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2484 of file postmaster.c.

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

Referenced by ServerLoop().

2485 {
2486  Port *port;
2487 
2488  if (!(port = (Port *) calloc(1, sizeof(Port))))
2489  {
2490  ereport(LOG,
2491  (errcode(ERRCODE_OUT_OF_MEMORY),
2492  errmsg("out of memory")));
2493  ExitPostmaster(1);
2494  }
2495 
2496  if (StreamConnection(serverFd, port) != STATUS_OK)
2497  {
2498  if (port->sock != PGINVALID_SOCKET)
2499  StreamClose(port->sock);
2500  ConnFree(port);
2501  return NULL;
2502  }
2503 
2504  return port;
2505 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
static void ConnFree(Port *port)
Definition: postmaster.c:2515
int errcode(int sqlerrcode)
Definition: elog.c:694
Definition: libpq-be.h:120
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:711
pgsocket sock
Definition: libpq-be.h:122
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5070
#define STATUS_OK
Definition: c.h:1170
static int port
Definition: pg_regress.c:92
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:905

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2515 of file postmaster.c.

References free.

Referenced by ConnCreate(), and ServerLoop().

2516 {
2517  free(conn);
2518 }
PGconn * conn
Definition: streamutil.c:54
#define free(a)
Definition: header.h:65

◆ CountChildren()

static int CountChildren ( int  target)
static

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

5346 {
5347  dlist_iter iter;
5348  int cnt = 0;
5349 
5350  dlist_foreach(iter, &BackendList)
5351  {
5352  Backend *bp = dlist_container(Backend, elem, iter.cur);
5353 
5354  if (bp->dead_end)
5355  continue;
5356 
5357  /*
5358  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5359  * it first and avoid touching shared memory for every child.
5360  */
5361  if (target != BACKEND_TYPE_ALL)
5362  {
5363  /*
5364  * Assign bkend_type for any recently announced WAL Sender
5365  * processes.
5366  */
5367  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5370 
5371  if (!(target & bp->bkend_type))
5372  continue;
5373  }
5374 
5375  cnt++;
5376  }
5377  return cnt;
5378 }
#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:275

◆ CreateOptsFile()

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

Definition at line 5605 of file postmaster.c.

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

Referenced by PostmasterMain().

5606 {
5607  FILE *fp;
5608  int i;
5609 
5610 #define OPTS_FILE "postmaster.opts"
5611 
5612  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5613  {
5614  ereport(LOG,
5616  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5617  return false;
5618  }
5619 
5620  fprintf(fp, "%s", fullprogname);
5621  for (i = 1; i < argc; i++)
5622  fprintf(fp, " \"%s\"", argv[i]);
5623  fputs("\n", fp);
5624 
5625  if (fclose(fp))
5626  {
5627  ereport(LOG,
5629  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5630  return false;
5631  }
5632 
5633  return true;
5634 }
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:220
int errcode_for_file_access(void)
Definition: elog.c:717
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:905
int i
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

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

1553 {
1554  TimestampTz next_wakeup = 0;
1555 
1556  /*
1557  * Normal case: either there are no background workers at all, or we're in
1558  * a shutdown sequence (during which we ignore bgworkers altogether).
1559  */
1560  if (Shutdown > NoShutdown ||
1562  {
1563  if (AbortStartTime != 0)
1564  {
1565  /* time left to abort; clamp to 0 in case it already expired */
1566  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1567  (time(NULL) - AbortStartTime);
1568  timeout->tv_sec = Max(timeout->tv_sec, 0);
1569  timeout->tv_usec = 0;
1570  }
1571  else
1572  {
1573  timeout->tv_sec = 60;
1574  timeout->tv_usec = 0;
1575  }
1576  return;
1577  }
1578 
1579  if (StartWorkerNeeded)
1580  {
1581  timeout->tv_sec = 0;
1582  timeout->tv_usec = 0;
1583  return;
1584  }
1585 
1586  if (HaveCrashedWorker)
1587  {
1588  slist_mutable_iter siter;
1589 
1590  /*
1591  * When there are crashed bgworkers, we sleep just long enough that
1592  * they are restarted when they request to be. Scan the list to
1593  * determine the minimum of all wakeup times according to most recent
1594  * crash time and requested restart interval.
1595  */
1597  {
1598  RegisteredBgWorker *rw;
1599  TimestampTz this_wakeup;
1600 
1601  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1602 
1603  if (rw->rw_crashed_at == 0)
1604  continue;
1605 
1607  || rw->rw_terminate)
1608  {
1609  ForgetBackgroundWorker(&siter);
1610  continue;
1611  }
1612 
1613  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1614  1000L * rw->rw_worker.bgw_restart_time);
1615  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1616  next_wakeup = this_wakeup;
1617  }
1618  }
1619 
1620  if (next_wakeup != 0)
1621  {
1622  long secs;
1623  int microsecs;
1624 
1626  &secs, &microsecs);
1627  timeout->tv_sec = secs;
1628  timeout->tv_usec = microsecs;
1629 
1630  /* Ensure we don't exceed one minute */
1631  if (timeout->tv_sec > 60)
1632  {
1633  timeout->tv_sec = 60;
1634  timeout->tv_usec = 0;
1635  }
1636  }
1637  else
1638  {
1639  timeout->tv_sec = 60;
1640  timeout->tv_usec = 0;
1641  }
1642 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:377
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:378
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
static int Shutdown
Definition: postmaster.c:274
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:422
#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:358
#define Max(x, y)
Definition: c.h:980
#define NoShutdown
Definition: postmaster.c:269
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:355

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5747 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

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

Referenced by PostmasterMain().

5317 {
5318 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5070 of file postmaster.c.

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

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

5071 {
5072 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5073 
5074  /*
5075  * There is no known cause for a postmaster to become multithreaded after
5076  * startup. Recheck to account for the possibility of unknown causes.
5077  * This message uses LOG level, because an unclean shutdown at this point
5078  * would usually not look much different from a clean shutdown.
5079  */
5080  if (pthread_is_threaded_np() != 0)
5081  ereport(LOG,
5082  (errcode(ERRCODE_INTERNAL_ERROR),
5083  errmsg_internal("postmaster became multithreaded"),
5084  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5085 #endif
5086 
5087  /* should cleanup shared memory and kill all backends */
5088 
5089  /*
5090  * Not sure of the semantics here. When the Postmaster dies, should the
5091  * backends all be killed? probably not.
5092  *
5093  * MUST -- vadim 05-10-1999
5094  */
5095 
5096  proc_exit(status);
5097 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:694
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:1038
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
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 1469 of file postmaster.c.

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

Referenced by PostmasterMain().

1470 {
1471  DIR *pdir;
1472 
1473  /* Locate the postgres executable itself */
1474  if (find_my_exec(argv0, my_exec_path) < 0)
1475  ereport(FATAL,
1476  (errmsg("%s: could not locate my own executable path", argv0)));
1477 
1478 #ifdef EXEC_BACKEND
1479  /* Locate executable backend before we change working directory */
1480  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1481  postgres_exec_path) < 0)
1482  ereport(FATAL,
1483  (errmsg("%s: could not locate matching postgres executable",
1484  argv0)));
1485 #endif
1486 
1487  /*
1488  * Locate the pkglib directory --- this has to be set early in case we try
1489  * to load any modules from it in response to postgresql.conf entries.
1490  */
1492 
1493  /*
1494  * Verify that there's a readable directory there; otherwise the Postgres
1495  * installation is incomplete or corrupt. (A typical cause of this
1496  * failure is that the postgres executable has been moved or hardlinked to
1497  * some directory that's not a sibling of the installation lib/
1498  * directory.)
1499  */
1500  pdir = AllocateDir(pkglib_path);
1501  if (pdir == NULL)
1502  ereport(ERROR,
1504  errmsg("could not open directory \"%s\": %m",
1505  pkglib_path),
1506  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1507  my_exec_path)));
1508  FreeDir(pdir);
1509 
1510  /*
1511  * XXX is it worth similarly checking the share/ directory? If the lib/
1512  * directory is there, then share/ probably is too.
1513  */
1514 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:322
static char * argv0
Definition: pg_ctl.c:97
int errhint(const char *fmt,...)
Definition: elog.c:1152
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:45
#define FATAL
Definition: elog.h:54
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:127
int errcode_for_file_access(void)
Definition: elog.c:717
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2615
char my_exec_path[MAXPGPATH]
Definition: globals.c:73
#define PG_BACKEND_VERSIONSTR
Definition: port.h:135
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:905
char pkglib_path[MAXPGPATH]
Definition: globals.c:74
int FreeDir(DIR *dir)
Definition: fd.c:2733

◆ HandleChildCrash()

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

Definition at line 3412 of file postmaster.c.

References AbortStartTime, allow_immediate_pgstat_restart(), AutoVacPID, BACKEND_TYPE_BGWORKER, BackgroundWorkerList, BgWriterPID, bkend::bkend_type, CheckpointerPID, bkend::child_slot, dlist_mutable_iter::cur, slist_iter::cur, bkend::dead_end, DEBUG2, dlist_container, dlist_delete(), dlist_foreach_modify, bkend::elem, ereport, errmsg(), errmsg_internal(), FatalError, free, ImmediateShutdown, LOG, LogChildExit(), PgArchPID, PgStatPID, bkend::pid, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_CRASH, pmState, ReleasePostmasterChildSlot(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_pid, SendStop, SetQuitSignalReason(), Shutdown, signal_child(), SIGQUIT, SIGSTOP, slist_container, slist_foreach, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

3413 {
3414  dlist_mutable_iter iter;
3415  slist_iter siter;
3416  Backend *bp;
3417  bool take_action;
3418 
3419  /*
3420  * We only log messages and send signals if this is the first process
3421  * crash and we're not doing an immediate shutdown; otherwise, we're only
3422  * here to update postmaster's idea of live processes. If we have already
3423  * signaled children, nonzero exit status is to be expected, so don't
3424  * clutter log.
3425  */
3426  take_action = !FatalError && Shutdown != ImmediateShutdown;
3427 
3428  if (take_action)
3429  {
3430  LogChildExit(LOG, procname, pid, exitstatus);
3431  ereport(LOG,
3432  (errmsg("terminating any other active server processes")));
3434  }
3435 
3436  /* Process background workers. */
3438  {
3439  RegisteredBgWorker *rw;
3440 
3441  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3442  if (rw->rw_pid == 0)
3443  continue; /* not running */
3444  if (rw->rw_pid == pid)
3445  {
3446  /*
3447  * Found entry for freshly-dead worker, so remove it.
3448  */
3450  dlist_delete(&rw->rw_backend->elem);
3451 #ifdef EXEC_BACKEND
3452  ShmemBackendArrayRemove(rw->rw_backend);
3453 #endif
3454  free(rw->rw_backend);
3455  rw->rw_backend = NULL;
3456  rw->rw_pid = 0;
3457  rw->rw_child_slot = 0;
3458  /* don't reset crashed_at */
3459  /* don't report child stop, either */
3460  /* Keep looping so we can signal remaining workers */
3461  }
3462  else
3463  {
3464  /*
3465  * This worker is still alive. Unless we did so already, tell it
3466  * to commit hara-kiri.
3467  *
3468  * SIGQUIT is the special signal that says exit without proc_exit
3469  * and let the user know what's going on. But if SendStop is set
3470  * (-s on command line), then we send SIGSTOP instead, so that we
3471  * can get core dumps from all backends by hand.
3472  */
3473  if (take_action)
3474  {
3475  ereport(DEBUG2,
3476  (errmsg_internal("sending %s to process %d",
3477  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3478  (int) rw->rw_pid)));
3480  }
3481  }
3482  }
3483 
3484  /* Process regular backends */
3486  {
3487  bp = dlist_container(Backend, elem, iter.cur);
3488 
3489  if (bp->pid == pid)
3490  {
3491  /*
3492  * Found entry for freshly-dead backend, so remove it.
3493  */
3494  if (!bp->dead_end)
3495  {
3497 #ifdef EXEC_BACKEND
3498  ShmemBackendArrayRemove(bp);
3499 #endif
3500  }
3501  dlist_delete(iter.cur);
3502  free(bp);
3503  /* Keep looping so we can signal remaining backends */
3504  }
3505  else
3506  {
3507  /*
3508  * This backend is still alive. Unless we did so already, tell it
3509  * to commit hara-kiri.
3510  *
3511  * SIGQUIT is the special signal that says exit without proc_exit
3512  * and let the user know what's going on. But if SendStop is set
3513  * (-s on command line), then we send SIGSTOP instead, so that we
3514  * can get core dumps from all backends by hand.
3515  *
3516  * We could exclude dead_end children here, but at least in the
3517  * SIGSTOP case it seems better to include them.
3518  *
3519  * Background workers were already processed above; ignore them
3520  * here.
3521  */
3522  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3523  continue;
3524 
3525  if (take_action)
3526  {
3527  ereport(DEBUG2,
3528  (errmsg_internal("sending %s to process %d",
3529  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3530  (int) bp->pid)));
3531  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3532  }
3533  }
3534  }
3535 
3536  /* Take care of the startup process too */
3537  if (pid == StartupPID)
3538  {
3539  StartupPID = 0;
3540  /* Caller adjusts StartupStatus, so don't touch it here */
3541  }
3542  else if (StartupPID != 0 && take_action)
3543  {
3544  ereport(DEBUG2,
3545  (errmsg_internal("sending %s to process %d",
3546  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3547  (int) StartupPID)));
3550  }
3551 
3552  /* Take care of the bgwriter too */
3553  if (pid == BgWriterPID)
3554  BgWriterPID = 0;
3555  else if (BgWriterPID != 0 && take_action)
3556  {
3557  ereport(DEBUG2,
3558  (errmsg_internal("sending %s to process %d",
3559  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3560  (int) BgWriterPID)));
3562  }
3563 
3564  /* Take care of the checkpointer too */
3565  if (pid == CheckpointerPID)
3566  CheckpointerPID = 0;
3567  else if (CheckpointerPID != 0 && take_action)
3568  {
3569  ereport(DEBUG2,
3570  (errmsg_internal("sending %s to process %d",
3571  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3572  (int) CheckpointerPID)));
3574  }
3575 
3576  /* Take care of the walwriter too */
3577  if (pid == WalWriterPID)
3578  WalWriterPID = 0;
3579  else if (WalWriterPID != 0 && take_action)
3580  {
3581  ereport(DEBUG2,
3582  (errmsg_internal("sending %s to process %d",
3583  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3584  (int) WalWriterPID)));
3586  }
3587 
3588  /* Take care of the walreceiver too */
3589  if (pid == WalReceiverPID)
3590  WalReceiverPID = 0;
3591  else if (WalReceiverPID != 0 && take_action)
3592  {
3593  ereport(DEBUG2,
3594  (errmsg_internal("sending %s to process %d",
3595  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3596  (int) WalReceiverPID)));
3598  }
3599 
3600  /* Take care of the autovacuum launcher too */
3601  if (pid == AutoVacPID)
3602  AutoVacPID = 0;
3603  else if (AutoVacPID != 0 && take_action)
3604  {
3605  ereport(DEBUG2,
3606  (errmsg_internal("sending %s to process %d",
3607  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3608  (int) AutoVacPID)));
3610  }
3611 
3612  /*
3613  * Force a power-cycle of the pgarch process too. (This isn't absolutely
3614  * necessary, but it seems like a good idea for robustness, and it
3615  * simplifies the state-machine logic in the case where a shutdown request
3616  * arrives during crash processing.)
3617  */
3618  if (PgArchPID != 0 && take_action)
3619  {
3620  ereport(DEBUG2,
3621  (errmsg_internal("sending %s to process %d",
3622  "SIGQUIT",
3623  (int) PgArchPID)));
3625  }
3626 
3627  /*
3628  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3629  * necessary, but it seems like a good idea for robustness, and it
3630  * simplifies the state-machine logic in the case where a shutdown request
3631  * arrives during crash processing.)
3632  */
3633  if (PgStatPID != 0 && take_action)
3634  {
3635  ereport(DEBUG2,
3636  (errmsg_internal("sending %s to process %d",
3637  "SIGQUIT",
3638  (int) PgStatPID)));
3641  }
3642 
3643  /* We do NOT restart the syslogger */
3644 
3645  if (Shutdown != ImmediateShutdown)
3646  FatalError = true;
3647 
3648  /* We now transit into a state of waiting for children to die */
3649  if (pmState == PM_RECOVERY ||
3650  pmState == PM_HOT_STANDBY ||
3651  pmState == PM_RUN ||
3653  pmState == PM_SHUTDOWN)
3655 
3656  /*
3657  * .. and if this doesn't happen quickly enough, now the clock is ticking
3658  * for us to kill them without mercy.
3659  */
3660  if (AbortStartTime == 0)
3661  AbortStartTime = time(NULL);
3662 }
struct bkend * rw_backend
#define SIGQUIT
Definition: win32_port.h:160
static StartupStatusEnum StartupStatus
Definition: postmaster.c:266
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static pid_t PgStatPID
Definition: postmaster.c:254
slist_node * cur
Definition: ilist.h:226
static pid_t CheckpointerPID
Definition: postmaster.c:249
static pid_t WalReceiverPID
Definition: postmaster.c:251
static bool FatalError
Definition: postmaster.c:276
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#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:274
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static pid_t BgWriterPID
Definition: postmaster.c:248
static pid_t StartupPID
Definition: postmaster.c:247
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:190
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:4015
#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:336
#define ImmediateShutdown
Definition: postmaster.c:272
#define ereport(elevel,...)
Definition: elog.h:155
#define free(a)
Definition: header.h:65
static pid_t WalWriterPID
Definition: postmaster.c:250
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
pid_t pid
Definition: postmaster.c:179
static pid_t AutoVacPID
Definition: postmaster.c:252
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
int errmsg(const char *fmt,...)
Definition: elog.c:905
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3668
static int SendStop
Definition: postmaster.c:230
static time_t AbortStartTime
Definition: postmaster.c:355
void allow_immediate_pgstat_restart(void)
Definition: pgstat.c:844
static pid_t PgArchPID
Definition: postmaster.c:253

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1892 of file postmaster.c.

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

Referenced by ServerLoop().

1893 {
1894  int maxsock = -1;
1895  int i;
1896 
1897  FD_ZERO(rmask);
1898 
1899  for (i = 0; i < MAXLISTEN; i++)
1900  {
1901  int fd = ListenSocket[i];
1902 
1903  if (fd == PGINVALID_SOCKET)
1904  break;
1905  FD_SET(fd, rmask);
1906 
1907  if (fd > maxsock)
1908  maxsock = fd;
1909  }
1910 
1911  return maxsock + 1;
1912 }
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 6545 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().

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

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2596 of file postmaster.c.

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

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

2597 {
2598  unsigned int rseed;
2599 
2600  MyProcPid = getpid();
2603 
2604  /*
2605  * Set a different seed for random() in every process. We want something
2606  * unpredictable, so if possible, use high-quality random bits for the
2607  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2608  */
2609  if (!pg_strong_random(&rseed, sizeof(rseed)))
2610  {
2611  /*
2612  * Since PIDs and timestamps tend to change more frequently in their
2613  * least significant bits, shift the timestamp left to allow a larger
2614  * total number of seeds in a given time period. Since that would
2615  * leave only 20 bits of the timestamp that cycle every ~1 second,
2616  * also mix in some higher bits.
2617  */
2618  rseed = ((uint64) MyProcPid) ^
2619  ((uint64) MyStartTimestamp << 12) ^
2620  ((uint64) MyStartTimestamp >> 20);
2621  }
2622  srandom(rseed);
2623 }
int MyProcPid
Definition: globals.c:41
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
pg_time_t MyStartTime
Definition: globals.c:42
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1752
TimestampTz MyStartTimestamp
Definition: globals.c:43
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 3668 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().

3669 {
3670  /*
3671  * size of activity_buffer is arbitrary, but set equal to default
3672  * track_activity_query_size
3673  */
3674  char activity_buffer[1024];
3675  const char *activity = NULL;
3676 
3677  if (!EXIT_STATUS_0(exitstatus))
3678  activity = pgstat_get_crashed_backend_activity(pid,
3679  activity_buffer,
3680  sizeof(activity_buffer));
3681 
3682  if (WIFEXITED(exitstatus))
3683  ereport(lev,
3684 
3685  /*------
3686  translator: %s is a noun phrase describing a child process, such as
3687  "server process" */
3688  (errmsg("%s (PID %d) exited with exit code %d",
3689  procname, pid, WEXITSTATUS(exitstatus)),
3690  activity ? errdetail("Failed process was running: %s", activity) : 0));
3691  else if (WIFSIGNALED(exitstatus))
3692  {
3693 #if defined(WIN32)
3694  ereport(lev,
3695 
3696  /*------
3697  translator: %s is a noun phrase describing a child process, such as
3698  "server process" */
3699  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3700  procname, pid, WTERMSIG(exitstatus)),
3701  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3702  activity ? errdetail("Failed process was running: %s", activity) : 0));
3703 #else
3704  ereport(lev,
3705 
3706  /*------
3707  translator: %s is a noun phrase describing a child process, such as
3708  "server process" */
3709  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3710  procname, pid, WTERMSIG(exitstatus),
3711  pg_strsignal(WTERMSIG(exitstatus))),
3712  activity ? errdetail("Failed process was running: %s", activity) : 0));
3713 #endif
3714  }
3715  else
3716  ereport(lev,
3717 
3718  /*------
3719  translator: %s is a noun phrase describing a child process, such as
3720  "server process" */
3721  (errmsg("%s (PID %d) exited with unrecognized status %d",
3722  procname, pid, exitstatus),
3723  activity ? errdetail("Failed process was running: %s", activity) : 0));
3724 }
int errhint(const char *fmt,...)
Definition: elog.c:1152
#define WTERMSIG(w)
Definition: win32_port.h:146
int errdetail(const char *fmt,...)
Definition: elog.c:1038
#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:905
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
Definition: pgstat.c:4509
#define WIFSIGNALED(w)
Definition: win32_port.h:144
#define WEXITSTATUS(w)
Definition: win32_port.h:145
#define EXIT_STATUS_0(st)
Definition: postmaster.c:557

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5649 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5650 {
5651  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5653 }
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:134
int autovacuum_max_workers
Definition: autovacuum.c:115
int max_worker_processes
Definition: globals.c:135

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

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

5587 {
5588  if (WalReceiverPID == 0 &&
5589  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5590  pmState == PM_HOT_STANDBY) &&
5592  {
5594  if (WalReceiverPID != 0)
5595  WalReceiverRequested = false;
5596  /* else leave the flag set, so we'll try again later */
5597  }
5598 }
static pid_t WalReceiverPID
Definition: postmaster.c:251
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:374
static int Shutdown
Definition: postmaster.c:274
#define SmartShutdown
Definition: postmaster.c:270
static PMState pmState
Definition: postmaster.c:336
#define StartWalReceiver()
Definition: postmaster.c:554

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2729 of file postmaster.c.

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

Referenced by PostmasterMain().

2730 {
2731  int save_errno = errno;
2732 
2733  /*
2734  * We rely on the signal mechanism to have blocked all signals ... except
2735  * on Windows, which lacks sigaction(), so we have to do it manually.
2736  */
2737 #ifdef WIN32
2738  PG_SETMASK(&BlockSig);
2739 #endif
2740 
2741  ereport(DEBUG2,
2742  (errmsg_internal("postmaster received signal %d",
2743  postgres_signal_arg)));
2744 
2745  switch (postgres_signal_arg)
2746  {
2747  case SIGTERM:
2748 
2749  /*
2750  * Smart Shutdown:
2751  *
2752  * Wait for children to end their work, then shut down.
2753  */
2754  if (Shutdown >= SmartShutdown)
2755  break;
2757  ereport(LOG,
2758  (errmsg("received smart shutdown request")));
2759 
2760  /* Report status */
2762 #ifdef USE_SYSTEMD
2763  sd_notify(0, "STOPPING=1");
2764 #endif
2765 
2766  /*
2767  * If we reached normal running, we have to wait for any online
2768  * backup mode to end; otherwise go straight to waiting for client
2769  * backends to exit. (The difference is that in the former state,
2770  * we'll still let in new superuser clients, so that somebody can
2771  * end the online backup mode.) If already in PM_STOP_BACKENDS or
2772  * a later state, do not change it.
2773  */
2774  if (pmState == PM_RUN)
2776  else if (pmState == PM_HOT_STANDBY)
2778  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2779  {
2780  /* There should be no clients, so proceed to stop children */
2782  }
2783 
2784  /*
2785  * Now wait for online backup mode to end and backends to exit. If
2786  * that is already the case, PostmasterStateMachine will take the
2787  * next step.
2788  */
2790  break;
2791 
2792  case SIGINT:
2793 
2794  /*
2795  * Fast Shutdown:
2796  *
2797  * Abort all children with SIGTERM (rollback active transactions
2798  * and exit) and shut down when they are gone.
2799  */
2800  if (Shutdown >= FastShutdown)
2801  break;
2803  ereport(LOG,
2804  (errmsg("received fast shutdown request")));
2805 
2806  /* Report status */
2808 #ifdef USE_SYSTEMD
2809  sd_notify(0, "STOPPING=1");
2810 #endif
2811 
2812  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2813  {
2814  /* Just shut down background processes silently */
2816  }
2817  else if (pmState == PM_RUN ||
2819  {
2820  /* Report that we're about to zap live client sessions */
2821  ereport(LOG,
2822  (errmsg("aborting any active transactions")));
2824  }
2825 
2826  /*
2827  * PostmasterStateMachine will issue any necessary signals, or
2828  * take the next step if no child processes need to be killed.
2829  */
2831  break;
2832 
2833  case SIGQUIT:
2834 
2835  /*
2836  * Immediate Shutdown:
2837  *
2838  * abort all children with SIGQUIT, wait for them to exit,
2839  * terminate remaining ones with SIGKILL, then exit without
2840  * attempt to properly shut down the data base system.
2841  */
2842  if (Shutdown >= ImmediateShutdown)
2843  break;
2845  ereport(LOG,
2846  (errmsg("received immediate shutdown request")));
2847 
2848  /* Report status */
2850 #ifdef USE_SYSTEMD
2851  sd_notify(0, "STOPPING=1");
2852 #endif
2853 
2854  /* tell children to shut down ASAP */
2858 
2859  /* set stopwatch for them to die */
2860  AbortStartTime = time(NULL);
2861 
2862  /*
2863  * Now wait for backends to exit. If there are none,
2864  * PostmasterStateMachine will take the next step.
2865  */
2867  break;
2868  }
2869 
2870 #ifdef WIN32
2872 #endif
2873 
2874  errno = save_errno;
2875 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3733
#define SIGQUIT
Definition: win32_port.h:160
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1331
#define LOG
Definition: elog.h:26
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:274
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:190
#define SmartShutdown
Definition: postmaster.c:270
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4085
#define FastShutdown
Definition: postmaster.c:271
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:336
#define ImmediateShutdown
Definition: postmaster.c:272
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
static ConnsAllowedState connsAllowed
Definition: postmaster.c:351
int errmsg(const char *fmt,...)
Definition: elog.c:905
#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:355

◆ PostmasterMain()

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

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

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

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

6066 {
6067  dlist_iter iter;
6068  Backend *bp;
6069 
6070  dlist_foreach(iter, &BackendList)
6071  {
6072  bp = dlist_container(Backend, elem, iter.cur);
6073  if (bp->pid == pid)
6074  {
6075  bp->bgworker_notify = true;
6076  return true;
6077  }
6078  }
6079  return false;
6080 }
#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 3733 of file postmaster.c.

References AbortStartTime, ALLOW_NO_CONNS, ALLOW_SUPERUSER_CONNS, Assert, AutoVacPID, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackupInProgress(), BgWriterPID, CancelBackup(), CheckpointerPID, connsAllowed, CountChildren(), dlist_is_empty(), ereport, errmsg(), ExitPostmaster(), FatalError, ForgetUnstartedBackgroundWorkers(), ImmediateShutdown, LocalProcessControlFile(), LOG, NoShutdown, PgArchPID, PgStatPID, PM_HOT_STANDBY, PM_NO_CHILDREN, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, pmState, ReachedNormalRunning, 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().

3734 {
3735  /* If we're doing a smart shutdown, try to advance that state. */
3736  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3737  {
3739  {
3740  /*
3741  * ALLOW_SUPERUSER_CONNS state ends as soon as online backup mode
3742  * is not active.
3743  */
3744  if (!BackupInProgress())
3746  }
3747 
3749  {
3750  /*
3751  * ALLOW_NO_CONNS state ends when we have no normal client
3752  * backends running. Then we're ready to stop other children.
3753  */
3756  }
3757  }
3758 
3759  /*
3760  * If we're ready to do so, signal child processes to shut down. (This
3761  * isn't a persistent state, but treating it as a distinct pmState allows
3762  * us to share this code across multiple shutdown code paths.)
3763  */
3764  if (pmState == PM_STOP_BACKENDS)
3765  {
3766  /*
3767  * Forget any pending requests for background workers, since we're no
3768  * longer willing to launch any new workers. (If additional requests
3769  * arrive, BackgroundWorkerStateChange will reject them.)
3770  */
3772 
3773  /* Signal all backend children except walsenders */
3774  SignalSomeChildren(SIGTERM,
3776  /* and the autovac launcher too */
3777  if (AutoVacPID != 0)
3778  signal_child(AutoVacPID, SIGTERM);
3779  /* and the bgwriter too */
3780  if (BgWriterPID != 0)
3781  signal_child(BgWriterPID, SIGTERM);
3782  /* and the walwriter too */
3783  if (WalWriterPID != 0)
3784  signal_child(WalWriterPID, SIGTERM);
3785  /* If we're in recovery, also stop startup and walreceiver procs */
3786  if (StartupPID != 0)
3787  signal_child(StartupPID, SIGTERM);
3788  if (WalReceiverPID != 0)
3789  signal_child(WalReceiverPID, SIGTERM);
3790  /* checkpointer, archiver, stats, and syslogger may continue for now */
3791 
3792  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3794  }
3795 
3796  /*
3797  * If we are in a state-machine state that implies waiting for backends to
3798  * exit, see if they're all gone, and change state if so.
3799  */
3800  if (pmState == PM_WAIT_BACKENDS)
3801  {
3802  /*
3803  * PM_WAIT_BACKENDS state ends when we have no regular backends
3804  * (including autovac workers), no bgworkers (including unconnected
3805  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3806  * doing crash recovery or an immediate shutdown then we expect the
3807  * checkpointer to exit as well, otherwise not. The archiver, stats,
3808  * and syslogger processes are disregarded since they are not
3809  * connected to shared memory; we also disregard dead_end children
3810  * here. Walsenders are also disregarded, they will be terminated
3811  * later after writing the checkpoint record, like the archiver
3812  * process.
3813  */
3815  StartupPID == 0 &&
3816  WalReceiverPID == 0 &&
3817  BgWriterPID == 0 &&
3818  (CheckpointerPID == 0 ||
3820  WalWriterPID == 0 &&
3821  AutoVacPID == 0)
3822  {
3824  {
3825  /*
3826  * Start waiting for dead_end children to die. This state
3827  * change causes ServerLoop to stop creating new ones.
3828  */
3830 
3831  /*
3832  * We already SIGQUIT'd the archiver and stats processes, if
3833  * any, when we started immediate shutdown or entered
3834  * FatalError state.
3835  */
3836  }
3837  else
3838  {
3839  /*
3840  * If we get here, we are proceeding with normal shutdown. All
3841  * the regular children are gone, and it's time to tell the
3842  * checkpointer to do a shutdown checkpoint.
3843  */
3845  /* Start the checkpointer if not running */
3846  if (CheckpointerPID == 0)
3848  /* And tell it to shut down */
3849  if (CheckpointerPID != 0)
3850  {
3852  pmState = PM_SHUTDOWN;
3853  }
3854  else
3855  {
3856  /*
3857  * If we failed to fork a checkpointer, just shut down.
3858  * Any required cleanup will happen at next restart. We
3859  * set FatalError so that an "abnormal shutdown" message
3860  * gets logged when we exit.
3861  */
3862  FatalError = true;
3864 
3865  /* Kill the walsenders, archiver and stats collector too */
3867  if (PgArchPID != 0)
3869  if (PgStatPID != 0)
3871  }
3872  }
3873  }
3874  }
3875 
3876  if (pmState == PM_SHUTDOWN_2)
3877  {
3878  /*
3879  * PM_SHUTDOWN_2 state ends when there's no other children than
3880  * dead_end children left. There shouldn't be any regular backends
3881  * left by now anyway; what we're really waiting for is walsenders and
3882  * archiver.
3883  */
3884  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3885  {
3887  }
3888  }
3889 
3890  if (pmState == PM_WAIT_DEAD_END)
3891  {
3892  /*
3893  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3894  * (ie, no dead_end children remain), and the archiver and stats
3895  * collector are gone too.
3896  *
3897  * The reason we wait for those two is to protect them against a new
3898  * postmaster starting conflicting subprocesses; this isn't an
3899  * ironclad protection, but it at least helps in the
3900  * shutdown-and-immediately-restart scenario. Note that they have
3901  * already been sent appropriate shutdown signals, either during a
3902  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3903  * FatalError processing.
3904  */
3905  if (dlist_is_empty(&BackendList) &&
3906  PgArchPID == 0 && PgStatPID == 0)
3907  {
3908  /* These other guys should be dead already */
3909  Assert(StartupPID == 0);
3910  Assert(WalReceiverPID == 0);
3911  Assert(BgWriterPID == 0);
3912  Assert(CheckpointerPID == 0);
3913  Assert(WalWriterPID == 0);
3914  Assert(AutoVacPID == 0);
3915  /* syslogger is not considered here */
3917  }
3918  }
3919 
3920  /*
3921  * If we've been told to shut down, we exit as soon as there are no
3922  * remaining children. If there was a crash, cleanup will occur at the
3923  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3924  * crash before exiting, but that seems unwise if we are quitting because
3925  * we got SIGTERM from init --- there may well not be time for recovery
3926  * before init decides to SIGKILL us.)
3927  *
3928  * Note that the syslogger continues to run. It will exit when it sees
3929  * EOF on its input pipe, which happens when there are no more upstream
3930  * processes.
3931  */
3933  {
3934  if (FatalError)
3935  {
3936  ereport(LOG, (errmsg("abnormal database system shutdown")));
3937  ExitPostmaster(1);
3938  }
3939  else
3940  {
3941  /*
3942  * Terminate exclusive backup mode to avoid recovery after a clean
3943  * fast shutdown. Since an exclusive backup can only be taken
3944  * during normal running (and not, for example, while running
3945  * under Hot Standby) it only makes sense to do this if we reached
3946  * normal running. If we're still in recovery, the backup file is
3947  * one we're recovering *from*, and we must keep it around so that
3948  * recovery restarts from the right place.
3949  */
3951  CancelBackup();
3952 
3953  /* Normal exit from the postmaster is here */
3954  ExitPostmaster(0);
3955  }
3956  }
3957 
3958  /*
3959  * If the startup process failed, or the user does not want an automatic
3960  * restart after backend crashes, wait for all non-syslogger children to
3961  * exit, and then exit postmaster. We don't try to reinitialize when the
3962  * startup process fails, because more than likely it will just fail again
3963  * and we will keep trying forever.
3964  */
3965  if (pmState == PM_NO_CHILDREN &&
3967  ExitPostmaster(1);
3968 
3969  /*
3970  * If we need to recover from a crash, wait for all non-syslogger children
3971  * to exit, then reset shmem and StartupDataBase.
3972  */
3973  if (FatalError && pmState == PM_NO_CHILDREN)
3974  {
3975  ereport(LOG,
3976  (errmsg("all server processes terminated; reinitializing")));
3977 
3978  /* allow background workers to immediately restart */
3980 
3981  shmem_exit(1);
3982 
3983  /* re-read control file into local memory */
3985 
3986  reset_shared();
3987 
3989  Assert(StartupPID != 0);
3991  pmState = PM_STARTUP;
3992  /* crash recovery started, reset SIGKILL flag */
3993  AbortStartTime = 0;
3994  }
3995 }
void CancelBackup(void)
Definition: xlog.c:11912
#define SIGQUIT
Definition: win32_port.h:160
static StartupStatusEnum StartupStatus
Definition: postmaster.c:266
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define StartupDataBase()
Definition: postmaster.c:550
static void reset_shared(void)
Definition: postmaster.c:2630
static pid_t PgStatPID
Definition: postmaster.c:254
static pid_t CheckpointerPID
Definition: postmaster.c:249
static pid_t WalReceiverPID
Definition: postmaster.c:251
static bool FatalError
Definition: postmaster.c:276
void shmem_exit(int code)
Definition: ipc.c:224
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4041
#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:11892
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:568
#define SignalChildren(sig)
Definition: postmaster.c:428
static int Shutdown
Definition: postmaster.c:274
static pid_t BgWriterPID
Definition: postmaster.c:248
#define StartCheckpointer()
Definition: postmaster.c:552
static int CountChildren(int target)
Definition: postmaster.c:5345
static pid_t StartupPID
Definition: postmaster.c:247
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5070
bool restart_after_crash
Definition: postmaster.c:244
static dlist_head BackendList
Definition: postmaster.c:188
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5051
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4015
static PMState pmState
Definition: postmaster.c:336
#define ImmediateShutdown
Definition: postmaster.c:272
#define ereport(elevel,...)
Definition: elog.h:155
static pid_t WalWriterPID
Definition: postmaster.c:250
#define Assert(condition)
Definition: c.h:804
static ConnsAllowedState connsAllowed
Definition: postmaster.c:351
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:269
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:530
static pid_t AutoVacPID
Definition: postmaster.c:252
int errmsg(const char *fmt,...)
Definition: elog.c:905
static bool ReachedNormalRunning
Definition: postmaster.c:360
static time_t AbortStartTime
Definition: postmaster.c:355
static pid_t PgArchPID
Definition: postmaster.c:253

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5301 of file postmaster.c.

Referenced by BackendInitialize().

5302 {
5303  _exit(1);
5304 }

◆ processCancelRequest()

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

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

2355 {
2356  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2357  int backendPID;
2358  int32 cancelAuthCode;
2359  Backend *bp;
2360 
2361 #ifndef EXEC_BACKEND
2362  dlist_iter iter;
2363 #else
2364  int i;
2365 #endif
2366 
2367  backendPID = (int) pg_ntoh32(canc->backendPID);
2368  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2369 
2370  /*
2371  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2372  * longer access the postmaster's own backend list, and must rely on the
2373  * duplicate array in shared memory.
2374  */
2375 #ifndef EXEC_BACKEND
2376  dlist_foreach(iter, &BackendList)
2377  {
2378  bp = dlist_container(Backend, elem, iter.cur);
2379 #else
2380  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2381  {
2382  bp = (Backend *) &ShmemBackendArray[i];
2383 #endif
2384  if (bp->pid == backendPID)
2385  {
2386  if (bp->cancel_key == cancelAuthCode)
2387  {
2388  /* Found a match; signal that backend to cancel current op */
2389  ereport(DEBUG2,
2390  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2391  backendPID)));
2392  signal_child(bp->pid, SIGINT);
2393  }
2394  else
2395  /* Right PID, wrong key: no way, Jose */
2396  ereport(LOG,
2397  (errmsg("wrong key in cancel request for process %d",
2398  backendPID)));
2399  return;
2400  }
2401 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2402  }
2403 #else
2404  }
2405 #endif
2406 
2407  /* No matching backend */
2408  ereport(LOG,
2409  (errmsg("PID %d in cancel request did not match any process",
2410  backendPID)));
2411 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
uint32 cancelAuthCode
Definition: pqcomm.h:183
#define LOG
Definition: elog.h:26
signed int int32
Definition: c.h:429
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
uint32 backendPID
Definition: pqcomm.h:182
#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:4015
dlist_node * cur
Definition: ilist.h:161
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:992
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5649
pid_t pid
Definition: postmaster.c:179
int errmsg(const char *fmt,...)
Definition: elog.c:905
int i

◆ ProcessStartupPacket()

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

Definition at line 1934 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, 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, palloc(), 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, and Port::user_name.

Referenced by BackendInitialize().

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