PostgreSQL Source Code  git master
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/transam.h"
#include "access/xlog.h"
#include "bootstrap/bootstrap.h"
#include "catalog/pg_control.h"
#include "common/file_perm.h"
#include "common/ip.h"
#include "common/string.h"
#include "lib/ilist.h"
#include "libpq/auth.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/fork_process.h"
#include "postmaster/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 char ExtraOptions [MAXPGPATH]
 
static bool Reinit = true
 
static int SendStop = false
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
static pid_t StartupPID = 0
 
static pid_t BgWriterPID = 0
 
static pid_t CheckpointerPID = 0
 
static pid_t WalWriterPID = 0
 
static pid_t WalReceiverPID = 0
 
static pid_t AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t PgStatPID = 0
 
static pid_t SysLoggerPID = 0
 
static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING
 
static int Shutdown = NoShutdown
 
static bool FatalError = false
 
static PMState pmState = PM_INIT
 
static ConnsAllowedState connsAllowed = ALLOW_ALL_CONNS
 
static time_t AbortStartTime = 0
 
static bool ReachedNormalRunning = false
 
bool ClientAuthInProgress = false
 
bool redirection_done = false
 
static volatile sig_atomic_t start_autovac_launcher = false
 
static volatile bool avlauncher_needs_signal = false
 
static volatile sig_atomic_t WalReceiverRequested = false
 
static volatile bool StartWorkerNeeded = true
 
static volatile bool HaveCrashedWorker = false
 
int postmaster_alive_fds [2] = {-1, -1}
 

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

#define BACKEND_TYPE_ALL   0x000F /* OR of all the above */

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 147 of file postmaster.c.

Referenced by StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 149 of file postmaster.c.

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

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 148 of file postmaster.c.

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

◆ EXIT_STATUS_0

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

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

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 277 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

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

Definition at line 451 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 364 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 434 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 276 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 558 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 559 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 557 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 561 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

351 {
352  ALLOW_ALL_CONNS, /* normal not-shutting-down state */
353  ALLOW_SUPERUSER_CONNS, /* only superusers can connect */
354  ALLOW_NO_CONNS /* no new connections allowed, period */
ConnsAllowedState
Definition: postmaster.c:350

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 264 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

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

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

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

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

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4490 of file postmaster.c.

References AllocateFile(), Assert, AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), av, BackendInitialize(), calloc, checkDataDir(), ClosePostmasterPorts(), CreateSharedMemoryAndSemaphores(), Port::database_name, DEBUG3, DestNone, elog, EnableSSL, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ExtraOptions, FATAL, fork_process(), FreeFile(), Port::gss, i, InitAuxiliaryProcess(), InitializeGUCOptions(), InitPostmasterChild(), InitProcess(), InitShmemAccess(), IsBackgroundWorker, IsPostmasterEnvironment, lengthof, LocalProcessControlFile(), LOG, MakePGDirectory(), malloc, MAXPGPATH, MemoryContextAlloc(), MemoryContextSwitchTo(), MyProcPid, PG_BINARY_W, pg_split_opts(), 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(), progname, secure_initialize(), snprintf, sprintf, StartBackgroundWorker(), SysLoggerMain(), TopMemoryContext, UsedShmemSegAddr, Port::user_name, and whereToSendOutput.

Referenced by BackendStartup().

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

◆ BackendStartup()

static int BackendStartup ( Port port)
static

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

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

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5782 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5783 {
5784  PG_SETMASK(&BlockSig);
5785 }
#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 5736 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().

5737 {
5739 
5740  /* XXX is this the right errcode? */
5742  ereport(FATAL,
5743  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5744  errmsg("database connection requirement not indicated during registration")));
5745 
5747 
5748  /* it had better not gotten out of "init" mode yet */
5749  if (!IsInitProcessingMode())
5750  ereport(ERROR,
5751  (errmsg("invalid processing mode in background worker")));
5753 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define SetProcessingMode(mode)
Definition: miscadmin.h:399
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
static char * username
Definition: initdb.c:134
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:51
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define IsInitProcessingMode()
Definition: miscadmin.h:394

◆ BackgroundWorkerInitializeConnectionByOid()

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

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

5760 {
5762 
5763  /* XXX is this the right errcode? */
5765  ereport(FATAL,
5766  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5767  errmsg("database connection requirement not indicated during registration")));
5768 
5769  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5770 
5771  /* it had better not gotten out of "init" mode yet */
5772  if (!IsInitProcessingMode())
5773  ereport(ERROR,
5774  (errmsg("invalid processing mode in background worker")));
5776 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define SetProcessingMode(mode)
Definition: miscadmin.h:399
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define IsInitProcessingMode()
Definition: miscadmin.h:394

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

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

5917 {
5918  switch (pmState)
5919  {
5920  case PM_NO_CHILDREN:
5921  case PM_WAIT_DEAD_END:
5922  case PM_SHUTDOWN_2:
5923  case PM_SHUTDOWN:
5924  case PM_WAIT_BACKENDS:
5925  case PM_STOP_BACKENDS:
5926  break;
5927 
5928  case PM_RUN:
5930  return true;
5931  /* fall through */
5932 
5933  case PM_HOT_STANDBY:
5935  return true;
5936  /* fall through */
5937 
5938  case PM_RECOVERY:
5939  case PM_STARTUP:
5940  case PM_INIT:
5942  return true;
5943  /* fall through */
5944 
5945  }
5946 
5947  return false;
5948 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:342

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

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

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

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1531 of file postmaster.c.

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

Referenced by PostmasterMain().

1532 {
1533  char path[MAXPGPATH];
1534  FILE *fp;
1535 
1536  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1537 
1538  fp = AllocateFile(path, PG_BINARY_R);
1539  if (fp == NULL)
1540  {
1541  write_stderr("%s: could not find the database system\n"
1542  "Expected to find it in the directory \"%s\",\n"
1543  "but could not open file \"%s\": %s\n",
1544  progname, DataDir, path, strerror(errno));
1545  ExitPostmaster(2);
1546  }
1547  FreeFile(fp);
1548 }
#define write_stderr(str)
Definition: parallel.c:186
const char * progname
Definition: pg_standby.c:36
#define PG_BINARY_R
Definition: c.h:1213
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5153
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
#define strerror
Definition: port.h:206
int FreeFile(FILE *file)
Definition: fd.c:2521
char * DataDir
Definition: globals.c:62
#define snprintf
Definition: port.h:193

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

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

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

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

2582 {
2583  int i;
2584 
2585 #ifndef WIN32
2586 
2587  /*
2588  * Close the write end of postmaster death watch pipe. It's important to
2589  * do this as early as possible, so that if postmaster dies, others won't
2590  * think that it's still running because we're holding the pipe open.
2591  */
2593  ereport(FATAL,
2595  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2597  /* Notify fd.c that we released one pipe FD. */
2599 #endif
2600 
2601  /*
2602  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2603  * so we don't call ReleaseExternalFD() here.
2604  */
2605  for (i = 0; i < MAXLISTEN; i++)
2606  {
2607  if (ListenSocket[i] != PGINVALID_SOCKET)
2608  {
2611  }
2612  }
2613 
2614  /*
2615  * If using syslogger, close the read side of the pipe. We don't bother
2616  * tracking this in fd.c, either.
2617  */
2618  if (!am_syslogger)
2619  {
2620 #ifndef WIN32
2621  if (syslogPipe[0] >= 0)
2622  close(syslogPipe[0]);
2623  syslogPipe[0] = -1;
2624 #else
2625  if (syslogPipe[0])
2626  CloseHandle(syslogPipe[0]);
2627  syslogPipe[0] = 0;
2628 #endif
2629  }
2630 
2631 #ifdef USE_BONJOUR
2632  /* If using Bonjour, close the connection to the mDNS daemon */
2633  if (bonjour_sdref)
2634  close(DNSServiceRefSockFD(bonjour_sdref));
2635 #endif
2636 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:843
#define FATAL
Definition: elog.h:52
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:633
int postmaster_alive_fds[2]
Definition: postmaster.c:573
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:221
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
void ReleaseExternalFD(void)
Definition: fd.c:1101
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:220
int syslogPipe[2]
Definition: syslogger.c:113

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1430 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2515 of file postmaster.c.

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

Referenced by ServerLoop().

2516 {
2517  Port *port;
2518 
2519  if (!(port = (Port *) calloc(1, sizeof(Port))))
2520  {
2521  ereport(LOG,
2522  (errcode(ERRCODE_OUT_OF_MEMORY),
2523  errmsg("out of memory")));
2524  ExitPostmaster(1);
2525  }
2526 
2527  if (StreamConnection(serverFd, port) != STATUS_OK)
2528  {
2529  if (port->sock != PGINVALID_SOCKET)
2530  StreamClose(port->sock);
2531  ConnFree(port);
2532  return NULL;
2533  }
2534 
2535  /*
2536  * Allocate GSSAPI specific state struct
2537  */
2538 #ifndef EXEC_BACKEND
2539 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2540  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2541  if (!port->gss)
2542  {
2543  ereport(LOG,
2544  (errcode(ERRCODE_OUT_OF_MEMORY),
2545  errmsg("out of memory")));
2546  ExitPostmaster(1);
2547  }
2548 #endif
2549 #endif
2550 
2551  return port;
2552 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:843
static void ConnFree(Port *port)
Definition: postmaster.c:2559
int errcode(int sqlerrcode)
Definition: elog.c:610
Definition: libpq-be.h:120
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:714
pgsocket sock
Definition: libpq-be.h:122
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5153
#define STATUS_OK
Definition: c.h:1111
static int port
Definition: pg_regress.c:92
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:144
void * gss
Definition: libpq-be.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2559 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2560 {
2561 #ifdef USE_SSL
2562  secure_close(conn);
2563 #endif
2564  if (conn->gss)
2565  free(conn->gss);
2566  free(conn);
2567 }
PGconn * conn
Definition: streamutil.c:54
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:133

◆ CountChildren()

static int CountChildren ( int  target)
static

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

5427 {
5428  dlist_iter iter;
5429  int cnt = 0;
5430 
5431  dlist_foreach(iter, &BackendList)
5432  {
5433  Backend *bp = dlist_container(Backend, elem, iter.cur);
5434 
5435  if (bp->dead_end)
5436  continue;
5437 
5438  /*
5439  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5440  * it first and avoid touching shared memory for every child.
5441  */
5442  if (target != BACKEND_TYPE_ALL)
5443  {
5444  /*
5445  * Assign bkend_type for any recently announced WAL Sender
5446  * processes.
5447  */
5448  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5451 
5452  if (!(target & bp->bkend_type))
5453  continue;
5454  }
5455 
5456  cnt++;
5457  }
5458  return cnt;
5459 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:150
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:146
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:189
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:148
bool dead_end
Definition: postmaster.c:184
int child_slot
Definition: postmaster.c:182
int bkend_type
Definition: postmaster.c:183
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:240

◆ CreateOptsFile()

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

Definition at line 5686 of file postmaster.c.

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

Referenced by PostmasterMain().

5687 {
5688  FILE *fp;
5689  int i;
5690 
5691 #define OPTS_FILE "postmaster.opts"
5692 
5693  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5694  {
5695  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5696  return false;
5697  }
5698 
5699  fprintf(fp, "%s", fullprogname);
5700  for (i = 1; i < argc; i++)
5701  fprintf(fp, " \"%s\"", argv[i]);
5702  fputs("\n", fp);
5703 
5704  if (fclose(fp))
5705  {
5706  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5707  return false;
5708  }
5709 
5710  return true;
5711 }
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:197
#define elog(elevel,...)
Definition: elog.h:214
int i
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

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

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

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5824 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

5825 {
5826  pid_t worker_pid;
5827 
5828  Assert(rw->rw_pid == 0);
5829 
5830  /*
5831  * Allocate and assign the Backend element. Note we must do this before
5832  * forking, so that we can handle failures (out of memory or child-process
5833  * slots) cleanly.
5834  *
5835  * Treat failure as though the worker had crashed. That way, the
5836  * postmaster will wait a bit before attempting to start it again; if we
5837  * tried again right away, most likely we'd find ourselves hitting the
5838  * same resource-exhaustion condition.
5839  */
5840  if (!assign_backendlist_entry(rw))
5841  {
5843  return false;
5844  }
5845 
5846  ereport(DEBUG1,
5847  (errmsg("starting background worker process \"%s\"",
5848  rw->rw_worker.bgw_name)));
5849 
5850 #ifdef EXEC_BACKEND
5851  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5852 #else
5853  switch ((worker_pid = fork_process()))
5854 #endif
5855  {
5856  case -1:
5857  /* in postmaster, fork failed ... */
5858  ereport(LOG,
5859  (errmsg("could not fork worker process: %m")));
5860  /* undo what assign_backendlist_entry did */
5862  rw->rw_child_slot = 0;
5863  free(rw->rw_backend);
5864  rw->rw_backend = NULL;
5865  /* mark entry as crashed, so we'll try again later */
5867  break;
5868 
5869 #ifndef EXEC_BACKEND
5870  case 0:
5871  /* in postmaster child ... */
5873 
5874  /* Close the postmaster's sockets */
5875  ClosePostmasterPorts(false);
5876 
5877  /*
5878  * Before blowing away PostmasterContext, save this bgworker's
5879  * data where it can find it.
5880  */
5883  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5884 
5885  /* Release postmaster's working memory context */
5888  PostmasterContext = NULL;
5889 
5891 
5892  exit(1); /* should not get here */
5893  break;
5894 #endif
5895  default:
5896  /* in postmaster, fork successful ... */
5897  rw->rw_pid = worker_pid;
5898  rw->rw_backend->pid = rw->rw_pid;
5900  /* add new worker to lists of backends */
5902 #ifdef EXEC_BACKEND
5903  ShmemBackendArrayAdd(rw->rw_backend);
5904 #endif
5905  return true;
5906  }
5907 
5908  return false;
5909 }
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:1574
pid_t fork_process(void)
Definition: fork_process.c:32
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:186
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2581
void StartBackgroundWorker(void)
Definition: bgworker.c:680
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:439
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5959
static dlist_head BackendList
Definition: postmaster.c:189
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define ereport(elevel,...)
Definition: elog.h:144
#define free(a)
Definition: header.h:65
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:745
pid_t pid
Definition: postmaster.c:180
int errmsg(const char *fmt,...)
Definition: elog.c:824
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 5397 of file postmaster.c.

Referenced by PostmasterMain().

5398 {
5399 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5153 of file postmaster.c.

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

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

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1478 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ HandleChildCrash()

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

Definition at line 3459 of file postmaster.c.

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

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1900 of file postmaster.c.

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

Referenced by ServerLoop().

1901 {
1902  int maxsock = -1;
1903  int i;
1904 
1905  FD_ZERO(rmask);
1906 
1907  for (i = 0; i < MAXLISTEN; i++)
1908  {
1909  int fd = ListenSocket[i];
1910 
1911  if (fd == PGINVALID_SOCKET)
1912  break;
1913  FD_SET(fd, rmask);
1914 
1915  if (fd > maxsock)
1916  maxsock = fd;
1917  }
1918 
1919  return maxsock + 1;
1920 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:221
#define PGINVALID_SOCKET
Definition: port.h:33
int i
#define MAXLISTEN
Definition: postmaster.c:220

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

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

6627 {
6628 #ifndef WIN32
6629 
6630  /*
6631  * Create a pipe. Postmaster holds the write end of the pipe open
6632  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6633  * the read file descriptor to select() to wake up in case postmaster
6634  * dies, or check for postmaster death with a (read() == 0). Children must
6635  * close the write end as soon as possible after forking, because EOF
6636  * won't be signaled in the read end until all processes have closed the
6637  * write fd. That is taken care of in ClosePostmasterPorts().
6638  */
6640  if (pipe(postmaster_alive_fds) < 0)
6641  ereport(FATAL,
6643  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6644 
6645  /* Notify fd.c that we've eaten two FDs for the pipe. */
6648 
6649  /*
6650  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6651  * call.
6652  */
6653  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6654  ereport(FATAL,
6656  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6657 #else
6658 
6659  /*
6660  * On Windows, we use a process handle for the same purpose.
6661  */
6662  if (DuplicateHandle(GetCurrentProcess(),
6663  GetCurrentProcess(),
6664  GetCurrentProcess(),
6665  &PostmasterHandle,
6666  0,
6667  TRUE,
6668  DUPLICATE_SAME_ACCESS) == 0)
6669  ereport(FATAL,
6670  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6671  GetLastError())));
6672 #endif /* WIN32 */
6673 }
int MyProcPid
Definition: globals.c:40
#define FATAL
Definition: elog.h:52
void ReserveExternalFD(void)
Definition: fd.c:1083
int errcode_for_file_access(void)
Definition: elog.c:633
int errcode_for_socket_access(void)
Definition: elog.c:704
pid_t PostmasterPid
Definition: globals.c:95
int postmaster_alive_fds[2]
Definition: postmaster.c:573
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
#define Assert(condition)
Definition: c.h:745
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2645 of file postmaster.c.

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

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

2646 {
2647  unsigned int rseed;
2648 
2649  MyProcPid = getpid();
2652 
2653  /*
2654  * Set a different seed for random() in every process. We want something
2655  * unpredictable, so if possible, use high-quality random bits for the
2656  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2657  */
2658  if (!pg_strong_random(&rseed, sizeof(rseed)))
2659  {
2660  /*
2661  * Since PIDs and timestamps tend to change more frequently in their
2662  * least significant bits, shift the timestamp left to allow a larger
2663  * total number of seeds in a given time period. Since that would
2664  * leave only 20 bits of the timestamp that cycle every ~1 second,
2665  * also mix in some higher bits.
2666  */
2667  rseed = ((uint64) MyProcPid) ^
2668  ((uint64) MyStartTimestamp << 12) ^
2669  ((uint64) MyStartTimestamp >> 20);
2670  }
2671  srandom(rseed);
2672 }
int MyProcPid
Definition: globals.c:40
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
pg_time_t MyStartTime
Definition: globals.c:41
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1716
TimestampTz MyStartTimestamp
Definition: globals.c:42
bool pg_strong_random(void *buf, size_t len)
void srandom(unsigned int seed)
Definition: srandom.c:22

◆ LogChildExit()

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

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

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

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5726 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

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

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

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

5668 {
5669  if (WalReceiverPID == 0 &&
5670  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5671  pmState == PM_HOT_STANDBY) &&
5673  {
5675  if (WalReceiverPID != 0)
5676  WalReceiverRequested = false;
5677  /* else leave the flag set, so we'll try again later */
5678  }
5679 }
static pid_t WalReceiverPID
Definition: postmaster.c:257
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:380
static int Shutdown
Definition: postmaster.c:280
#define SmartShutdown
Definition: postmaster.c:276
static PMState pmState
Definition: postmaster.c:342
#define StartWalReceiver()
Definition: postmaster.c:561

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2778 of file postmaster.c.

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

Referenced by PostmasterMain().

2779 {
2780  int save_errno = errno;
2781 
2782  /*
2783  * We rely on the signal mechanism to have blocked all signals ... except
2784  * on Windows, which lacks sigaction(), so we have to do it manually.
2785  */
2786 #ifdef WIN32
2787  PG_SETMASK(&BlockSig);
2788 #endif
2789 
2790  ereport(DEBUG2,
2791  (errmsg_internal("postmaster received signal %d",
2792  postgres_signal_arg)));
2793 
2794  switch (postgres_signal_arg)
2795  {
2796  case SIGTERM:
2797 
2798  /*
2799  * Smart Shutdown:
2800  *
2801  * Wait for children to end their work, then shut down.
2802  */
2803  if (Shutdown >= SmartShutdown)
2804  break;
2806  ereport(LOG,
2807  (errmsg("received smart shutdown request")));
2808 
2809  /* Report status */
2811 #ifdef USE_SYSTEMD
2812  sd_notify(0, "STOPPING=1");
2813 #endif
2814 
2815  /*
2816  * If we reached normal running, we have to wait for any online
2817  * backup mode to end; otherwise go straight to waiting for client
2818  * backends to exit. (The difference is that in the former state,
2819  * we'll still let in new superuser clients, so that somebody can
2820  * end the online backup mode.) If already in PM_STOP_BACKENDS or
2821  * a later state, do not change it.
2822  */
2823  if (pmState == PM_RUN)
2825  else if (pmState == PM_HOT_STANDBY)
2827  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2828  {
2829  /* There should be no clients, so proceed to stop children */
2831  }
2832 
2833  /*
2834  * Now wait for online backup mode to end and backends to exit. If
2835  * that is already the case, PostmasterStateMachine will take the
2836  * next step.
2837  */
2839  break;
2840 
2841  case SIGINT:
2842 
2843  /*
2844  * Fast Shutdown:
2845  *
2846  * Abort all children with SIGTERM (rollback active transactions
2847  * and exit) and shut down when they are gone.
2848  */
2849  if (Shutdown >= FastShutdown)
2850  break;
2852  ereport(LOG,
2853  (errmsg("received fast shutdown request")));
2854 
2855  /* Report status */
2857 #ifdef USE_SYSTEMD
2858  sd_notify(0, "STOPPING=1");
2859 #endif
2860 
2861  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2862  {
2863  /* Just shut down background processes silently */
2865  }
2866  else if (pmState == PM_RUN ||
2868  {
2869  /* Report that we're about to zap live client sessions */
2870  ereport(LOG,
2871  (errmsg("aborting any active transactions")));
2873  }
2874 
2875  /*
2876  * PostmasterStateMachine will issue any necessary signals, or
2877  * take the next step if no child processes need to be killed.
2878  */
2880  break;
2881 
2882  case SIGQUIT:
2883 
2884  /*
2885  * Immediate Shutdown:
2886  *
2887  * abort all children with SIGQUIT, wait for them to exit,
2888  * terminate remaining ones with SIGKILL, then exit without
2889  * attempt to properly shut down the data base system.
2890  */
2891  if (Shutdown >= ImmediateShutdown)
2892  break;
2894  ereport(LOG,
2895  (errmsg("received immediate shutdown request")));
2896 
2897  /* Report status */
2899 #ifdef USE_SYSTEMD
2900  sd_notify(0, "STOPPING=1");
2901 #endif
2902 
2905 
2906  /* set stopwatch for them to die */
2907  AbortStartTime = time(NULL);
2908 
2909  /*
2910  * Now wait for backends to exit. If there are none,
2911  * PostmasterStateMachine will take the next step.
2912  */
2914  break;
2915  }
2916 
2917 #ifdef WIN32
2919 #endif
2920 
2921  errno = save_errno;
2922 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3779
#define SIGQUIT
Definition: win32_port.h:154
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1329
#define LOG
Definition: elog.h:26
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:280
#define SmartShutdown
Definition: postmaster.c:276
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4124
#define FastShutdown
Definition: postmaster.c:277
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:342
#define ImmediateShutdown
Definition: postmaster.c:278
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
static ConnsAllowedState connsAllowed
Definition: postmaster.c:357
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
static time_t AbortStartTime
Definition: postmaster.c:361

◆ PostmasterMain()

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

Definition at line 583 of file postmaster.c.

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

Referenced by main().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6142 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

6143 {
6144  dlist_iter iter;
6145  Backend *bp;
6146 
6147  dlist_foreach(iter, &BackendList)
6148  {
6149  bp = dlist_container(Backend, elem, iter.cur);
6150  if (bp->pid == pid)
6151  {
6152  bp->bgworker_notify = true;
6153  return true;
6154  }
6155  }
6156  return false;
6157 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:185
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:189
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:180

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3779 of file postmaster.c.

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

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

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

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5382 of file postmaster.c.

Referenced by BackendInitialize().

5383 {
5384  _exit(1);
5385 }

◆ processCancelRequest()

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

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

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

◆ ProcessStartupPacket()