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

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

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

Typedefs

typedef struct bkend Backend
 

Enumerations

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

Functions

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

Variables

static dlist_head BackendList = DLIST_STATIC_INIT(BackendList)
 
BackgroundWorkerMyBgworkerEntry = NULL
 
int PostPortNumber
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int ReservedBackends
 
static pgsocket ListenSocket [MAXLISTEN]
 
static bool Reinit = true
 
static int SendStop = false
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
bool remove_temp_files_after_crash = true
 
static pid_t StartupPID = 0
 
static pid_t BgWriterPID = 0
 
static pid_t CheckpointerPID = 0
 
static pid_t WalWriterPID = 0
 
static pid_t WalReceiverPID = 0
 
static pid_t AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t PgStatPID = 0
 
static pid_t SysLoggerPID = 0
 
static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING
 
static int Shutdown = NoShutdown
 
static bool FatalError = false
 
static PMState pmState = PM_INIT
 
static ConnsAllowedState connsAllowed = ALLOW_ALL_CONNS
 
static time_t AbortStartTime = 0
 
static bool ReachedNormalRunning = false
 
bool ClientAuthInProgress = false
 
bool redirection_done = false
 
static volatile sig_atomic_t start_autovac_launcher = false
 
static volatile bool avlauncher_needs_signal = false
 
static volatile sig_atomic_t WalReceiverRequested = false
 
static volatile bool StartWorkerNeeded = true
 
static volatile bool HaveCrashedWorker = false
 
int postmaster_alive_fds [2] = {-1, -1}
 

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 146 of file postmaster.c.

Referenced by StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 148 of file postmaster.c.

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

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 147 of file postmaster.c.

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

◆ EXIT_STATUS_0

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

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

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 272 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 273 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:192
static PMState pmState
Definition: postmaster.c:337
#define XLogArchivingActive()
Definition: xlog.h:189
bool PgArchCanRestart(void)
Definition: pgarch.c:147

Definition at line 446 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 359 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 429 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 271 of file postmaster.c.

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

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 553 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 554 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 555 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 552 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 557 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 259 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

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

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

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

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

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4475 of file postmaster.c.

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

Referenced by BackendStartup().

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

◆ BackendStartup()

static int BackendStartup ( Port port)
static

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

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

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5718 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5719 {
5720  PG_SETMASK(&BlockSig);
5721 }
#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 5672 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().

5673 {
5675 
5676  /* XXX is this the right errcode? */
5678  ereport(FATAL,
5679  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5680  errmsg("database connection requirement not indicated during registration")));
5681 
5683 
5684  /* it had better not gotten out of "init" mode yet */
5685  if (!IsInitProcessingMode())
5686  ereport(ERROR,
5687  (errmsg("invalid processing mode in background worker")));
5689 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define ERROR
Definition: elog.h:46
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:49
const char * username
Definition: pgbench.c:280
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:579
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:51
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define IsInitProcessingMode()
Definition: miscadmin.h:407

◆ BackgroundWorkerInitializeConnectionByOid()

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

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

5696 {
5698 
5699  /* XXX is this the right errcode? */
5701  ereport(FATAL,
5702  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5703  errmsg("database connection requirement not indicated during registration")));
5704 
5705  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5706 
5707  /* it had better not gotten out of "init" mode yet */
5708  if (!IsInitProcessingMode())
5709  ereport(ERROR,
5710  (errmsg("invalid processing mode in background worker")));
5712 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
#define ERROR
Definition: elog.h:46
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:49
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:579
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define IsInitProcessingMode()
Definition: miscadmin.h:407

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

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

5853 {
5854  switch (pmState)
5855  {
5856  case PM_NO_CHILDREN:
5857  case PM_WAIT_DEAD_END:
5858  case PM_SHUTDOWN_2:
5859  case PM_SHUTDOWN:
5860  case PM_WAIT_BACKENDS:
5861  case PM_STOP_BACKENDS:
5862  break;
5863 
5864  case PM_RUN:
5866  return true;
5867  /* fall through */
5868 
5869  case PM_HOT_STANDBY:
5871  return true;
5872  /* fall through */
5873 
5874  case PM_RECOVERY:
5875  case PM_STARTUP:
5876  case PM_INIT:
5878  return true;
5879  /* fall through */
5880 
5881  }
5882 
5883  return false;
5884 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:337

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 2441 of file postmaster.c.

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

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

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

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1532 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

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

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2554 of file postmaster.c.

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

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

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

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 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:850
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:220
#define PGINVALID_SOCKET
Definition: port.h:33
int i
void RemoveSocketFiles(void)
Definition: pqcomm.c:883
#define MAXLISTEN
Definition: postmaster.c:219

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2506 of file postmaster.c.

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

Referenced by ServerLoop().

2507 {
2508  Port *port;
2509 
2510  if (!(port = (Port *) calloc(1, sizeof(Port))))
2511  {
2512  ereport(LOG,
2513  (errcode(ERRCODE_OUT_OF_MEMORY),
2514  errmsg("out of memory")));
2515  ExitPostmaster(1);
2516  }
2517 
2518  if (StreamConnection(serverFd, port) != STATUS_OK)
2519  {
2520  if (port->sock != PGINVALID_SOCKET)
2521  StreamClose(port->sock);
2522  ConnFree(port);
2523  return NULL;
2524  }
2525 
2526  return port;
2527 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:850
static void ConnFree(Port *port)
Definition: postmaster.c:2537
int errcode(int sqlerrcode)
Definition: elog.c:698
Definition: libpq-be.h:125
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:716
pgsocket sock
Definition: libpq-be.h:127
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5089
#define STATUS_OK
Definition: c.h:1170
static int port
Definition: pg_regress.c:92
#define PGINVALID_SOCKET
Definition: port.h:33
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2537 of file postmaster.c.

References free.

Referenced by ConnCreate(), and ServerLoop().

2538 {
2539  free(conn);
2540 }
PGconn * conn
Definition: streamutil.c:54
#define free(a)
Definition: header.h:65

◆ CountChildren()

static int CountChildren ( int  target)
static

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

5355 {
5356  dlist_iter iter;
5357  int cnt = 0;
5358 
5359  dlist_foreach(iter, &BackendList)
5360  {
5361  Backend *bp = dlist_container(Backend, elem, iter.cur);
5362 
5363  if (bp->dead_end)
5364  continue;
5365 
5366  /*
5367  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5368  * it first and avoid touching shared memory for every child.
5369  */
5370  if (target != BACKEND_TYPE_ALL)
5371  {
5372  /*
5373  * Assign bkend_type for any recently announced WAL Sender
5374  * processes.
5375  */
5376  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5379 
5380  if (!(target & bp->bkend_type))
5381  continue;
5382  }
5383 
5384  cnt++;
5385  }
5386  return cnt;
5387 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
static dlist_head BackendList
Definition: postmaster.c:188
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
bool dead_end
Definition: postmaster.c:183
int child_slot
Definition: postmaster.c:181
int bkend_type
Definition: postmaster.c:182
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:275

◆ CreateOptsFile()

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

Definition at line 5618 of file postmaster.c.

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

Referenced by PostmasterMain().

5619 {
5620  FILE *fp;
5621  int i;
5622 
5623 #define OPTS_FILE "postmaster.opts"
5624 
5625  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5626  {
5627  ereport(LOG,
5629  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5630  return false;
5631  }
5632 
5633  fprintf(fp, "%s", fullprogname);
5634  for (i = 1; i < argc; i++)
5635  fprintf(fp, " \"%s\"", argv[i]);
5636  fputs("\n", fp);
5637 
5638  if (fclose(fp))
5639  {
5640  ereport(LOG,
5642  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5643  return false;
5644  }
5645 
5646  return true;
5647 }
#define LOG
Definition: elog.h:26
#define fprintf
Definition: port.h:220
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

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

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

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5760 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

5761 {
5762  pid_t worker_pid;
5763 
5764  Assert(rw->rw_pid == 0);
5765 
5766  /*
5767  * Allocate and assign the Backend element. Note we must do this before
5768  * forking, so that we can handle failures (out of memory or child-process
5769  * slots) cleanly.
5770  *
5771  * Treat failure as though the worker had crashed. That way, the
5772  * postmaster will wait a bit before attempting to start it again; if we
5773  * tried again right away, most likely we'd find ourselves hitting the
5774  * same resource-exhaustion condition.
5775  */
5776  if (!assign_backendlist_entry(rw))
5777  {
5779  return false;
5780  }
5781 
5782  ereport(DEBUG1,
5783  (errmsg_internal("starting background worker process \"%s\"",
5784  rw->rw_worker.bgw_name)));
5785 
5786 #ifdef EXEC_BACKEND
5787  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5788 #else
5789  switch ((worker_pid = fork_process()))
5790 #endif
5791  {
5792  case -1:
5793  /* in postmaster, fork failed ... */
5794  ereport(LOG,
5795  (errmsg("could not fork worker process: %m")));
5796  /* undo what assign_backendlist_entry did */
5798  rw->rw_child_slot = 0;
5799  free(rw->rw_backend);
5800  rw->rw_backend = NULL;
5801  /* mark entry as crashed, so we'll try again later */
5803  break;
5804 
5805 #ifndef EXEC_BACKEND
5806  case 0:
5807  /* in postmaster child ... */
5809 
5810  /* Close the postmaster's sockets */
5811  ClosePostmasterPorts(false);
5812 
5813  /*
5814  * Before blowing away PostmasterContext, save this bgworker's
5815  * data where it can find it.
5816  */
5819  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5820 
5821  /* Release postmaster's working memory context */
5824  PostmasterContext = NULL;
5825 
5827 
5828  exit(1); /* should not get here */
5829  break;
5830 #endif
5831  default:
5832  /* in postmaster, fork successful ... */
5833  rw->rw_pid = worker_pid;
5834  rw->rw_backend->pid = rw->rw_pid;
5836  /* add new worker to lists of backends */
5838 #ifdef EXEC_BACKEND
5839  ShmemBackendArrayAdd(rw->rw_backend);
5840 #endif
5841  return true;
5842  }
5843 
5844  return false;
5845 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#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:1580
pid_t fork_process(void)
Definition: fork_process.c:29
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:185
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2554
void StartBackgroundWorker(void)
Definition: bgworker.c:723
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:450
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5895
static dlist_head BackendList
Definition: postmaster.c:188
MemoryContext TopMemoryContext
Definition: mcxt.c:48
#define ereport(elevel,...)
Definition: elog.h:157
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:804
pid_t pid
Definition: postmaster.c:179
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:50

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5325 of file postmaster.c.

Referenced by PostmasterMain().

5326 {
5327 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5089 of file postmaster.c.

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

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

5090 {
5091 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5092 
5093  /*
5094  * There is no known cause for a postmaster to become multithreaded after
5095  * startup. Recheck to account for the possibility of unknown causes.
5096  * This message uses LOG level, because an unclean shutdown at this point
5097  * would usually not look much different from a clean shutdown.
5098  */
5099  if (pthread_is_threaded_np() != 0)
5100  ereport(LOG,
5101  (errcode(ERRCODE_INTERNAL_ERROR),
5102  errmsg_internal("postmaster became multithreaded"),
5103  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5104 #endif
5105 
5106  /* should cleanup shared memory and kill all backends */
5107 
5108  /*
5109  * Not sure of the semantics here. When the Postmaster dies, should the
5110  * backends all be killed? probably not.
5111  *
5112  * MUST -- vadim 05-10-1999
5113  */
5114 
5115  proc_exit(status);
5116 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1478 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ HandleChildCrash()

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

Definition at line 3436 of file postmaster.c.

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

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1901 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

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

6559 {
6560 #ifndef WIN32
6561 
6562  /*
6563  * Create a pipe. Postmaster holds the write end of the pipe open
6564  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6565  * the read file descriptor to select() to wake up in case postmaster
6566  * dies, or check for postmaster death with a (read() == 0). Children must
6567  * close the write end as soon as possible after forking, because EOF
6568  * won't be signaled in the read end until all processes have closed the
6569  * write fd. That is taken care of in ClosePostmasterPorts().
6570  */
6572  if (pipe(postmaster_alive_fds) < 0)
6573  ereport(FATAL,
6575  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6576 
6577  /* Notify fd.c that we've eaten two FDs for the pipe. */
6580 
6581  /*
6582  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6583  * call.
6584  */
6585  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6586  ereport(FATAL,
6588  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6589 #else
6590 
6591  /*
6592  * On Windows, we use a process handle for the same purpose.
6593  */
6594  if (DuplicateHandle(GetCurrentProcess(),
6595  GetCurrentProcess(),
6596  GetCurrentProcess(),
6597  &PostmasterHandle,
6598  0,
6599  TRUE,
6600  DUPLICATE_SAME_ACCESS) == 0)
6601  ereport(FATAL,
6602  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6603  GetLastError())));
6604 #endif /* WIN32 */
6605 }
int MyProcPid
Definition: globals.c:43
#define FATAL
Definition: elog.h:49
void ReserveExternalFD(void)
Definition: fd.c:1130
int errcode_for_file_access(void)
Definition: elog.c:721
int errcode_for_socket_access(void)
Definition: elog.c:792
pid_t PostmasterPid
Definition: globals.c:98
int postmaster_alive_fds[2]
Definition: postmaster.c:569
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Assert(condition)
Definition: c.h:804
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:43

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2618 of file postmaster.c.

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

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

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

◆ LogChildExit()

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

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

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

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5662 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5663 {
5664  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5666 }
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:136
int autovacuum_max_workers
Definition: autovacuum.c:116
int max_worker_processes
Definition: globals.c:137

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

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

5600 {
5601  if (WalReceiverPID == 0 &&
5602  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5603  pmState == PM_HOT_STANDBY) &&
5605  {
5607  if (WalReceiverPID != 0)
5608  WalReceiverRequested = false;
5609  /* else leave the flag set, so we'll try again later */
5610  }
5611 }
static pid_t WalReceiverPID
Definition: postmaster.c:252
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:375
static int Shutdown
Definition: postmaster.c:275
#define SmartShutdown
Definition: postmaster.c:271
static PMState pmState
Definition: postmaster.c:337
#define StartWalReceiver()
Definition: postmaster.c:557

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2751 of file postmaster.c.

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

Referenced by PostmasterMain().

2752 {
2753  int save_errno = errno;
2754 
2755  /*
2756  * We rely on the signal mechanism to have blocked all signals ... except
2757  * on Windows, which lacks sigaction(), so we have to do it manually.
2758  */
2759 #ifdef WIN32
2760  PG_SETMASK(&BlockSig);
2761 #endif
2762 
2763  ereport(DEBUG2,
2764  (errmsg_internal("postmaster received signal %d",
2765  postgres_signal_arg)));
2766 
2767  switch (postgres_signal_arg)
2768  {
2769  case SIGTERM:
2770 
2771  /*
2772  * Smart Shutdown:
2773  *
2774  * Wait for children to end their work, then shut down.
2775  */
2776  if (Shutdown >= SmartShutdown)
2777  break;
2779  ereport(LOG,
2780  (errmsg("received smart shutdown request")));
2781 
2782  /* Report status */
2784 #ifdef USE_SYSTEMD
2785  sd_notify(0, "STOPPING=1");
2786 #endif
2787 
2788  /*
2789  * If we reached normal running, we have to wait for any online
2790  * backup mode to end; otherwise go straight to waiting for client
2791  * backends to exit. (The difference is that in the former state,
2792  * we'll still let in new superuser clients, so that somebody can
2793  * end the online backup mode.) If already in PM_STOP_BACKENDS or
2794  * a later state, do not change it.
2795  */
2796  if (pmState == PM_RUN)
2798  else if (pmState == PM_HOT_STANDBY)
2800  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2801  {
2802  /* There should be no clients, so proceed to stop children */
2804  }
2805 
2806  /*
2807  * Now wait for online backup mode to end and backends to exit. If
2808  * that is already the case, PostmasterStateMachine will take the
2809  * next step.
2810  */
2812  break;
2813 
2814  case SIGINT:
2815 
2816  /*
2817  * Fast Shutdown:
2818  *
2819  * Abort all children with SIGTERM (rollback active transactions
2820  * and exit) and shut down when they are gone.
2821  */
2822  if (Shutdown >= FastShutdown)
2823  break;
2825  ereport(LOG,
2826  (errmsg("received fast shutdown request")));
2827 
2828  /* Report status */
2830 #ifdef USE_SYSTEMD
2831  sd_notify(0, "STOPPING=1");
2832 #endif
2833 
2834  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2835  {
2836  /* Just shut down background processes silently */
2838  }
2839  else if (pmState == PM_RUN ||
2841  {
2842  /* Report that we're about to zap live client sessions */
2843  ereport(LOG,
2844  (errmsg("aborting any active transactions")));
2846  }
2847 
2848  /*
2849  * PostmasterStateMachine will issue any necessary signals, or
2850  * take the next step if no child processes need to be killed.
2851  */
2853  break;
2854 
2855  case SIGQUIT:
2856 
2857  /*
2858  * Immediate Shutdown:
2859  *
2860  * abort all children with SIGQUIT, wait for them to exit,
2861  * terminate remaining ones with SIGKILL, then exit without
2862  * attempt to properly shut down the data base system.
2863  */
2864  if (Shutdown >= ImmediateShutdown)
2865  break;
2867  ereport(LOG,
2868  (errmsg("received immediate shutdown request")));
2869 
2870  /* Report status */
2872 #ifdef USE_SYSTEMD
2873  sd_notify(0, "STOPPING=1");
2874 #endif
2875 
2876  /* tell children to shut down ASAP */
2880 
2881  /* set stopwatch for them to die */
2882  AbortStartTime = time(NULL);
2883 
2884  /*
2885  * Now wait for backends to exit. If there are none,
2886  * PostmasterStateMachine will take the next step.
2887  */
2889  break;
2890  }
2891 
2892 #ifdef WIN32
2894 #endif
2895 
2896  errno = save_errno;
2897 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3754
#define SIGQUIT
Definition: win32_port.h:160
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1331
#define LOG
Definition: elog.h:26
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:275
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:190
#define SmartShutdown
Definition: postmaster.c:271
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4110
#define FastShutdown
Definition: postmaster.c:272
sigset_t UnBlockSig
Definition: pqsignal.c:22
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:337
#define ImmediateShutdown
Definition: postmaster.c:273
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static ConnsAllowedState connsAllowed
Definition: postmaster.c:352
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
static time_t AbortStartTime
Definition: postmaster.c:356

◆ PostmasterMain()

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

Definition at line 579 of file postmaster.c.

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

Referenced by main().

580 {
581  int opt;
582  int status;
583  char *userDoption = NULL;
584  bool listen_addr_saved = false;
585  int i;
586  char *output_config_variable = NULL;
587 
589 
591 
593 
594  /*
595  * We should not be creating any files or directories before we check the
596  * data directory (see checkDataDir()), but just in case set the umask to
597  * the most restrictive (owner-only) permissions.
598  *
599  * checkDataDir() will reset the umask based on the data directory
600  * permissions.
601  */
602  umask(PG_MODE_MASK_OWNER);
603 
604  /*
605  * By default, palloc() requests in the postmaster will be allocated in
606  * the PostmasterContext, which is space that can be recycled by backends.
607  * Allocated data that needs to be available to backends should be
608  * allocated in TopMemoryContext.
609  */
611  "Postmaster",
614 
615  /* Initialize paths to installation files */
616  getInstallationPaths(argv[0]);
617 
618  /*
619  * Set up signal handlers for the postmaster process.
620  *
621  * In the postmaster, we use pqsignal_pm() rather than pqsignal() (which
622  * is used by all child processes and client processes). That has a
623  * couple of special behaviors:
624  *
625  * 1. Except on Windows, we tell sigaction() to block all signals for the
626  * duration of the signal handler. This is faster than our old approach
627  * of blocking/unblocking explicitly in the signal handler, and it should
628  * also prevent excessive stack consumption if signals arrive quickly.
629  *
630  * 2. We do not set the SA_RESTART flag. This is because signals will be
631  * blocked at all times except when ServerLoop is waiting for something to
632  * happen, and during that window, we want signals to exit the select(2)
633  * wait so that ServerLoop can respond if anything interesting happened.
634  * On some platforms, signals marked SA_RESTART would not cause the
635  * select() wait to end.
636  *
637  * Child processes will generally want SA_RESTART, so pqsignal() sets that
638  * flag. We expect children to set up their own handlers before
639  * unblocking signals.
640  *
641  * CAUTION: when changing this list, check for side-effects on the signal
642  * handling setup of child processes. See tcop/postgres.c,
643  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
644  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
645  * postmaster/syslogger.c, postmaster/bgworker.c and
646  * postmaster/checkpointer.c.
647  */
648  pqinitmask();
650 
651  pqsignal_pm(SIGHUP, SIGHUP_handler); /* reread config file and have
652  * children do same */
653  pqsignal_pm(SIGINT, pmdie); /* send SIGTERM and shut down */
654  pqsignal_pm(SIGQUIT, pmdie); /* send SIGQUIT and die */
655  pqsignal_pm(SIGTERM, pmdie); /* wait for children and shut down */
656  pqsignal_pm(SIGALRM, SIG_IGN); /* ignored */
657  pqsignal_pm(SIGPIPE, SIG_IGN); /* ignored */
658  pqsignal_pm(SIGUSR1, sigusr1_handler); /* message from child process */
659  pqsignal_pm(SIGUSR2, dummy_handler); /* unused, reserve for children */
660  pqsignal_pm(SIGCHLD, reaper); /* handle child termination */
661 
662 #ifdef SIGURG
663 
664  /*
665  * Ignore SIGURG for now. Child processes may change this (see
666  * InitializeLatchSupport), but they will not receive any such signals
667  * until they wait on a latch.
668  */
669  pqsignal_pm(SIGURG, SIG_IGN); /* ignored */
670 #endif
671 
672  /*
673  * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
674  * ignore those signals in a postmaster environment, so that there is no
675  * risk of a child process freezing up due to writing to stderr. But for
676  * a standalone backend, their default handling is reasonable. Hence, all
677  * child processes should just allow the inherited settings to stand.
678  */
679 #ifdef SIGTTIN
680  pqsignal_pm(SIGTTIN, SIG_IGN); /* ignored */
681 #endif
682 #ifdef SIGTTOU
683  pqsignal_pm(SIGTTOU, SIG_IGN); /* ignored */
684 #endif
685 
686  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
687 #ifdef SIGXFSZ
688  pqsignal_pm(SIGXFSZ, SIG_IGN); /* ignored */
689 #endif
690 
691  /*
692  * Options setup
693  */
695 
696  opterr = 1;
697 
698  /*
699  * Parse command-line options. CAUTION: keep this in sync with
700  * tcop/postgres.c (the option sets should not conflict) and with the
701  * common help() function in main/main.c.
702  */
703  while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:W:-:")) != -1)
704  {
705  switch (opt)
706  {
707  case 'B':
708  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
709  break;
710 
711  case 'b':
712  /* Undocumented flag used for binary upgrades */
713  IsBinaryUpgrade = true;
714  break;
715 
716  case 'C':
717  output_config_variable = strdup(optarg);
718  break;
719 
720  case 'D':
721  userDoption = strdup(optarg);
722  break;
723 
724  case 'd':
726  break;
727 
728  case 'E':
729  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
730  break;
731 
732  case 'e':
733  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
734  break;
735 
736  case 'F':
737  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
738  break;
739 
740  case 'f':
742  {
743  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
744  progname, optarg);
745  ExitPostmaster(1);
746  }
747  break;
748 
749  case 'h':
750  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
751  break;
752 
753  case 'i':
754  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
755  break;
756 
757  case 'j':
758  /* only used by interactive backend */
759  break;
760 
761  case 'k':
762  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
763  break;
764 
765  case 'l':
766  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
767  break;
768 
769  case 'N':
770  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
771  break;
772 
773  case 'n':
774  /* Don't reinit shared mem after abnormal exit */
775  Reinit = false;
776  break;
777 
778  case 'O':
779  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
780  break;
781 
782  case 'P':
783  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
784  break;
785 
786  case 'p':
788  break;
789 
790  case 'r':
791  /* only used by single-user backend */
792  break;
793 
794  case 'S':
796  break;
797 
798  case 's':
799  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
800  break;
801 
802  case 'T':
803 
804  /*
805  * In the event that some backend dumps core, send SIGSTOP,
806  * rather than SIGQUIT, to all its peers. This lets the wily
807  * post_hacker collect core dumps from everyone.
808  */
809  SendStop = true;
810  break;
811 
812  case 't':
813  {
814  const char *tmp = get_stats_option_name(optarg);
815 
816  if (tmp)
817  {
819  }
820  else
821  {
822  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
823  progname, optarg);
824  ExitPostmaster(1);
825  }
826  break;
827  }
828 
829  case 'W':
830  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
831  break;
832 
833  case 'c':
834  case '-':
835  {
836  char *name,
837  *value;
838 
839  ParseLongOption(optarg, &name, &value);
840  if (!value)
841  {
842  if (opt == '-')
843  ereport(ERROR,
844  (errcode(ERRCODE_SYNTAX_ERROR),
845  errmsg("--%s requires a value",
846  optarg)));
847  else
848  ereport(ERROR,
849  (errcode(ERRCODE_SYNTAX_ERROR),
850  errmsg("-c %s requires a value",
851  optarg)));
852  }
853 
855  free(name);
856  if (value)
857  free(value);
858  break;
859  }
860 
861  default:
862  write_stderr("Try \"%s --help\" for more information.\n",
863  progname);
864  ExitPostmaster(1);
865  }
866  }
867 
868  /*
869  * Postmaster accepts no non-option switch arguments.
870  */
871  if (optind < argc)
872  {
873  write_stderr("%s: invalid argument: \"%s\"\n",
874  progname, argv[optind]);
875  write_stderr("Try \"%s --help\" for more information.\n",
876  progname);
877  ExitPostmaster(1);
878  }
879 
880  /*
881  * Locate the proper configuration files and data directory, and read
882  * postgresql.conf for the first time.
883  */
884  if (!SelectConfigFiles(userDoption, progname))
885  ExitPostmaster(2);
886 
887  if (output_config_variable != NULL)
888  {
889  /*
890  * "-C guc" was specified, so print GUC's value and exit. No extra
891  * permission check is needed because the user is reading inside the
892  * data dir.
893  */
894  const char *config_val = GetConfigOption(output_config_variable,
895  false, false);
896 
897  puts(config_val ? config_val : "");
898  ExitPostmaster(0);
899  }
900 
901  /* Verify that DataDir looks reasonable */
902  checkDataDir();
903 
904  /* Check that pg_control exists */
906 
907  /* And switch working directory into it */
908  ChangeToDataDir();
909 
910  /*
911  * Check for invalid combinations of GUC settings.
912  */
914  {
915  write_stderr("%s: superuser_reserved_connections (%d) must be less than max_connections (%d)\n",
916  progname,
918  ExitPostmaster(1);
919  }
921  ereport(ERROR,
922  (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
924  ereport(ERROR,
925  (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
926 
927  /*
928  * Other one-time internal sanity checks can go here, if they are fast.
929  * (Put any slow processing further down, after postmaster.pid creation.)
930  */
931  if (!CheckDateTokenTables())
932  {
933  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
934  ExitPostmaster(1);
935  }
936 
937  /*
938  * Now that we are done processing the postmaster arguments, reset
939  * getopt(3) library so that it will work correctly in subprocesses.
940  */
941  optind = 1;
942 #ifdef HAVE_INT_OPTRESET
943  optreset = 1; /* some systems need this too */
944 #endif
945 
946  /* For debugging: display postmaster environment */
947  {
948  extern char **environ;
949  char **p;
950 
951  ereport(DEBUG3,
952  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
953  progname)));
954  ereport(DEBUG3,
955  (errmsg_internal("-----------------------------------------")));
956  for (p = environ; *p; ++p)
957  ereport(DEBUG3,
958  (errmsg_internal("\t%s", *p)));
959  ereport(DEBUG3,
960  (errmsg_internal("-----------------------------------------")));
961  }
962 
963  /*
964  * Create lockfile for data directory.
965  *
966  * We want to do this before we try to grab the input sockets, because the
967  * data directory interlock is more reliable than the socket-file
968  * interlock (thanks to whoever decided to put socket files in /tmp :-().
969  * For the same reason, it's best to grab the TCP socket(s) before the
970  * Unix socket(s).
971  *
972  * Also note that this internally sets up the on_proc_exit function that
973  * is responsible for removing both data directory and socket lockfiles;
974  * so it must happen before opening sockets so that at exit, the socket
975  * lockfiles go away after CloseServerPorts runs.
976  */
977  CreateDataDirLockFile(true);
978 
979  /*
980  * Read the control file (for error checking and config info).
981  *
982  * Since we verify the control file's CRC, this has a useful side effect
983  * on machines where we need a run-time test for CRC support instructions.
984  * The postmaster will do the test once at startup, and then its child
985  * processes will inherit the correct function pointer and not need to
986  * repeat the test.
987  */
989 
990  /*
991  * Register the apply launcher. Since it registers a background worker,
992  * it needs to be called before InitializeMaxBackends(), and it's probably
993  * a good idea to call it before any modules had chance to take the
994  * background worker slots.
995  */
997 
998  /*
999  * process any libraries that should be preloaded at postmaster start
1000  */
1002 
1003  /*
1004  * Initialize SSL library, if specified.
1005  */
1006 #ifdef USE_SSL
1007  if (EnableSSL)
1008  {
1009  (void) secure_initialize(true);
1010  LoadedSSL = true;
1011  }
1012 #endif
1013 
1014  /*
1015  * Now that loadable modules have had their chance to register background
1016  * workers, calculate MaxBackends.
1017  */
1019 
1020  /*
1021  * Set up shared memory and semaphores.
1022  */
1023  reset_shared();
1024 
1025  /*
1026  * Estimate number of openable files. This must happen after setting up
1027  * semaphores, because on some platforms semaphores count as open files.
1028  */
1029  set_max_safe_fds();
1030 
1031  /*
1032  * Set reference point for stack-depth checking.
1033  */
1034  set_stack_base();
1035 
1036  /*
1037  * Initialize pipe (or process handle on Windows) that allows children to
1038  * wake up from sleep on postmaster death.
1039  */
1041 
1042 #ifdef WIN32
1043 
1044  /*
1045  * Initialize I/O completion port used to deliver list of dead children.
1046  */
1047  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1048  if (win32ChildQueue == NULL)
1049  ereport(FATAL,
1050  (errmsg("could not create I/O completion port for child queue")));
1051 #endif
1052 
1053 #ifdef EXEC_BACKEND
1054  /* Write out nondefault GUC settings for child processes to use */
1055  write_nondefault_variables(PGC_POSTMASTER);
1056 
1057  /*
1058  * Clean out the temp directory used to transmit parameters to child
1059  * processes (see internal_forkexec, below). We must do this before
1060  * launching any child processes, else we have a race condition: we could
1061  * remove a parameter file before the child can read it. It should be
1062  * safe to do so now, because we verified earlier that there are no
1063  * conflicting Postgres processes in this data directory.
1064  */
1066 #endif
1067 
1068  /*
1069  * Forcibly remove the files signaling a standby promotion request.
1070  * Otherwise, the existence of those files triggers a promotion too early,
1071  * whether a user wants that or not.
1072  *
1073  * This removal of files is usually unnecessary because they can exist
1074  * only during a few moments during a standby promotion. However there is
1075  * a race condition: if pg_ctl promote is executed and creates the files
1076  * during a promotion, the files can stay around even after the server is
1077  * brought up to be the primary. Then, if a new standby starts by using
1078  * the backup taken from the new primary, the files can exist at server
1079  * startup and must be removed in order to avoid an unexpected promotion.
1080  *
1081  * Note that promotion signal files need to be removed before the startup
1082  * process is invoked. Because, after that, they can be used by
1083  * postmaster's SIGUSR1 signal handler.
1084  */
1086 
1087  /* Do the same for logrotate signal file */
1089 
1090  /* Remove any outdated file holding the current log filenames. */
1091  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1092  ereport(LOG,
1094  errmsg("could not remove file \"%s\": %m",
1096 
1097  /*
1098  * If enabled, start up syslogger collection subprocess
1099  */
1101 
1102  /*
1103  * Reset whereToSendOutput from DestDebug (its starting state) to
1104  * DestNone. This stops ereport from sending log messages to stderr unless
1105  * Log_destination permits. We don't do this until the postmaster is
1106  * fully launched, since startup failures may as well be reported to
1107  * stderr.
1108  *
1109  * If we are in fact disabling logging to stderr, first emit a log message
1110  * saying so, to provide a breadcrumb trail for users who may not remember
1111  * that their logging is configured to go somewhere else.
1112  */
1114  ereport(LOG,
1115  (errmsg("ending log output to stderr"),
1116  errhint("Future log output will go to log destination \"%s\".",
1118 
1120 
1121  /*
1122  * Report server startup in log. While we could emit this much earlier,
1123  * it seems best to do so after starting the log collector, if we intend
1124  * to use one.
1125  */
1126  ereport(LOG,
1127  (errmsg("starting %s", PG_VERSION_STR)));
1128 
1129  /*
1130  * Establish input sockets.
1131  *
1132  * First, mark them all closed, and set up an on_proc_exit function that's
1133  * charged with closing the sockets again at postmaster shutdown.
1134  */
1135  for (i = 0; i < MAXLISTEN; i++)
1137 
1139 
1140  if (ListenAddresses)
1141  {
1142  char *rawstring;
1143  List *elemlist;
1144  ListCell *l;
1145  int success = 0;
1146 
1147  /* Need a modifiable copy of ListenAddresses */
1148  rawstring = pstrdup(ListenAddresses);
1149 
1150  /* Parse string into list of hostnames */
1151  if (!SplitGUCList(rawstring, ',', &elemlist))
1152  {
1153  /* syntax error in list */
1154  ereport(FATAL,
1155  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1156  errmsg("invalid list syntax in parameter \"%s\"",
1157  "listen_addresses")));
1158  }
1159 
1160  foreach(l, elemlist)
1161  {
1162  char *curhost = (char *) lfirst(l);
1163 
1164  if (strcmp(curhost, "*") == 0)
1165  status = StreamServerPort(AF_UNSPEC, NULL,
1166  (unsigned short) PostPortNumber,
1167  NULL,
1169  else
1170  status = StreamServerPort(AF_UNSPEC, curhost,
1171  (unsigned short) PostPortNumber,
1172  NULL,
1173  ListenSocket, MAXLISTEN);
1174 
1175  if (status == STATUS_OK)
1176  {
1177  success++;
1178  /* record the first successful host addr in lockfile */
1179  if (!listen_addr_saved)
1180  {
1182  listen_addr_saved = true;
1183  }
1184  }
1185  else
1186  ereport(WARNING,
1187  (errmsg("could not create listen socket for \"%s\"",
1188  curhost)));
1189  }
1190 
1191  if (!success && elemlist != NIL)
1192  ereport(FATAL,
1193  (errmsg("could not create any TCP/IP sockets")));
1194 
1195  list_free(elemlist);
1196  pfree(rawstring);
1197  }
1198 
1199 #ifdef USE_BONJOUR
1200  /* Register for Bonjour only if we opened TCP socket(s) */
1201  if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
1202  {
1203  DNSServiceErrorType err;
1204 
1205  /*
1206  * We pass 0 for interface_index, which will result in registering on
1207  * all "applicable" interfaces. It's not entirely clear from the
1208  * DNS-SD docs whether this would be appropriate if we have bound to
1209  * just a subset of the available network interfaces.
1210  */
1211  err = DNSServiceRegister(&bonjour_sdref,
1212  0,
1213  0,
1214  bonjour_name,
1215  "_postgresql._tcp.",
1216  NULL,
1217  NULL,
1219  0,
1220  NULL,
1221  NULL,
1222  NULL);
1223  if (err != kDNSServiceErr_NoError)
1224  ereport(LOG,
1225  (errmsg("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:318
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3416
int secure_initialize(bool isServerStart)
Definition: be-secure.c:78
#define NIL
Definition: pg_list.h:65
bool IsPostmasterEnvironment
Definition: globals.c:111
bool EnableSSL
Definition: postmaster.c:233
#define SIGQUIT
Definition: win32_port.h:160
static StartupStatusEnum StartupStatus
Definition: postmaster.c:267
#define S_IRGRP
Definition: win32_port.h:292
#define AllocSetContextCreate
Definition: memutils.h:173
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1466
int MyProcPid
Definition: globals.c:43
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define StartupDataBase()
Definition: postmaster.c:552
static void reset_shared(void)
Definition: postmaster.c:2652
const char * progname
Definition: main.c:46
static struct @142 value
#define DEBUG3
Definition: elog.h:23
#define SIGUSR1
Definition: win32_port.h:171
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1331
#define SIGCHLD
Definition: win32_port.h:169
int wal_level
Definition: xlog.c:108
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define pg_hton16(x)
Definition: pg_bswap.h:120
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:5325
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:10943
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3593
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define write_stderr(str)
Definition: parallel.c:186
#define S_IROTH
Definition: win32_port.h:304
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:5618
bool CheckDateTokenTables(void)
Definition: datetime.c:4469
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:8074
#define PG_TEMP_FILES_DIR
Definition: pg_checksums.c:58
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:95
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3635
int SysLogger_Start(void)
Definition: syslogger.c:540
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3564
void checkDataDir(void)
Definition: miscinit.c:304
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
#define LOG
Definition: elog.h:26
void InitProcessGlobals(void)
Definition: postmaster.c:2618
#define fprintf
Definition: port.h:220
void list_free_deep(List *list)
Definition: list.c:1405
char * Unix_socket_directories
Definition: postmaster.c:202
bool IsBinaryUpgrade
Definition: globals.c:113
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
bool load_ident(void)
Definition: hba.c:3023
void autovac_init(void)
Definition: autovacuum.c:3428
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:3880
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:6558
#define PM_STATUS_STARTING
Definition: pidfile.h:51
void pfree(void *pointer)
Definition: mcxt.c:1169
int optind
Definition: getopt.c:50
#define S_IWUSR
Definition: win32_port.h:283
#define ERROR
Definition: elog.h:46
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1275
static pid_t StartupPID
Definition: postmaster.c:248
int PostPortNumber
Definition: postmaster.c:199
static void checkControlFile(void)
Definition: postmaster.c:1532
int ReservedBackends
Definition: postmaster.c:216
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5089
#define FATAL
Definition: elog.h:49
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: pidfile.h:41
char * external_pid_file
Definition: guc.c:584
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
Definition: dest.h:89
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8050
bool load_hba(void)
Definition: hba.c:2229
char * bonjour_name
Definition: postmaster.c:243
int XLogArchiveMode
Definition: xlog.c:96
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3118
int errcode_for_file_access(void)
Definition: elog.c:721
static pid_t SysLoggerPID
Definition: postmaster.c:256
#define SIGHUP
Definition: win32_port.h:159
void LocalProcessControlFile(bool reset)
Definition: xlog.c:5076
void ChangeToDataDir(void)
Definition: miscinit.c:418
int opterr
Definition: getopt.c:49
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1478
char * Log_destination_string
Definition: elog.c:112
char * ListenAddresses
Definition: postmaster.c:205
#define STATUS_OK
Definition: c.h:1170
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static void pmdie(SIGNAL_ARGS)
Definition: postmaster.c:2751
static void SIGHUP_handler(SIGNAL_ARGS)
Definition: postmaster.c:2669
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: pidfile.h:42
bool enable_bonjour
Definition: postmaster.c:242
void RemovePromoteSignalFiles(void)
Definition: xlog.c:12876
int max_wal_senders
Definition: walsender.c:121
#define SIG_IGN
Definition: win32_port.h:156
pid_t PostmasterPid
Definition: globals.c:98
#define WARNING
Definition: elog.h:40
pqsigfunc pqsignal_pm(int signo, pqsigfunc func)
Definition: pqsignal.c:120
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
sigset_t BlockSig
Definition: pqsignal.c:22
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:220
static PMState pmState
Definition: postmaster.c:337
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:5789
void ApplyLauncherRegister(void)
Definition: launcher.c:702
#define PGINVALID_SOCKET
Definition: port.h:33
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
int MaxConnections
Definition: globals.c:136
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1551
TimestampTz PgStartTime
Definition: timestamp.c:52
#define LOG_DESTINATION_STDERR
Definition: elog.h:435
#define ereport(elevel,...)
Definition: elog.h:157
static bool Reinit
Definition: postmaster.c:229
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
static int ServerLoop(void)
Definition: postmaster.c:1659
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void RemovePgTempFiles(void)
Definition: fd.c:3059
static void reaper(SIGNAL_ARGS)
Definition: postmaster.c:2903
void InitializeMaxBackends(void)
Definition: postinit.c:515
#define strerror
Definition: port.h:229
#define SIGALRM
Definition: win32_port.h:165
const char * name
Definition: encode.c:515
#define S_IRUSR
Definition: win32_port.h:280
static const char * userDoption
Definition: postgres.c:172
void set_max_safe_fds(void)
Definition: fd.c:990
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * optarg
Definition: getopt.c:52
void list_free(List *list)
Definition: list.c:1391
int i
static void sigusr1_handler(SIGNAL_ARGS)
Definition: postmaster.c:5122
void pgstat_init(void)
Definition: pgstat.c:377
int Log_destination
Definition: elog.c:111
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:4001
char ** environ
CommandDest whereToSendOutput
Definition: postgres.c:92
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
static bool success
Definition: initdb.c:165
static int SendStop
Definition: postmaster.c:230
void process_shared_preload_libraries(void)
Definition: miscinit.c:1659
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
Definition: pg_list.h:50
#define MAXLISTEN
Definition: postmaster.c:219
MemoryContext PostmasterContext
Definition: mcxt.c:50
static void maybe_start_bgworkers(void)
Definition: postmaster.c:5959
void InitializeGUCOptions(void)
Definition: guc.c:5566

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6078 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

6079 {
6080  dlist_iter iter;
6081  Backend *bp;
6082 
6083  dlist_foreach(iter, &BackendList)
6084  {
6085  bp = dlist_container(Backend, elem, iter.cur);
6086  if (bp->pid == pid)
6087  {
6088  bp->bgworker_notify = true;
6089  return true;
6090  }
6091  }
6092  return false;
6093 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
bool bgworker_notify
Definition: postmaster.c:184
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
static dlist_head BackendList
Definition: postmaster.c:188
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:179

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3754 of file postmaster.c.

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

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

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

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5310 of file postmaster.c.

Referenced by BackendInitialize().

5311 {
5312  _exit(1);
5313 }

◆ processCancelRequest()

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

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

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

◆ ProcessStartupPacket()