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/queryjumble.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

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

Typedefs

typedef struct bkend Backend
 

Enumerations

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

Functions

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

Variables

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

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 147 of file postmaster.c.

Referenced by StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 149 of file postmaster.c.

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

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 148 of file postmaster.c.

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

◆ EXIT_STATUS_0

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

Definition at line 562 of file postmaster.c.

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

◆ EXIT_STATUS_1

#define EXIT_STATUS_1 (   st)    (WIFEXITED(st) && WEXITSTATUS(st) == 1)

Definition at line 563 of file postmaster.c.

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

◆ EXIT_STATUS_3

#define EXIT_STATUS_3 (   st)    (WIFEXITED(st) && WEXITSTATUS(st) == 3)

Definition at line 564 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 273 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 274 of file postmaster.c.

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

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

Referenced by maybe_start_bgworkers().

◆ MAXLISTEN

#define MAXLISTEN   64

◆ NoShutdown

#define NoShutdown   0

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

Referenced by CreateOptsFile().

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
#define XLogArchivingAlways()
Definition: xlog.h:200
static PMState pmState
Definition: postmaster.c:338
#define XLogArchivingActive()
Definition: xlog.h:197
bool PgArchCanRestart(void)
Definition: pgarch.c:148

Definition at line 447 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 360 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 430 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 272 of file postmaster.c.

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

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 555 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 556 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 557 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 554 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 559 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 558 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

Typedef Documentation

◆ Backend

typedef struct bkend Backend

Enumeration Type Documentation

◆ ConnsAllowedState

Enumerator
ALLOW_ALL_CONNS 
ALLOW_SUPERUSER_CONNS 
ALLOW_NO_CONNS 

Definition at line 346 of file postmaster.c.

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

◆ PMState

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

Definition at line 321 of file postmaster.c.

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 260 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

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

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

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

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

4493 {
4494  char *av[2];
4495  const int ac = 1;
4496 
4497  av[0] = "postgres";
4498  av[1] = NULL;
4499 
4500  /*
4501  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4502  * just yet, though, because InitPostgres will need the HBA data.)
4503  */
4505 
4506  PostgresMain(ac, av, port->database_name, port->user_name);
4507 }
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 4160 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().

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

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5734 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5735 {
5736  PG_SETMASK(&BlockSig);
5737 }
#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 5688 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().

5689 {
5691 
5692  /* XXX is this the right errcode? */
5694  ereport(FATAL,
5695  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5696  errmsg("database connection requirement not indicated during registration")));
5697 
5699 
5700  /* it had better not gotten out of "init" mode yet */
5701  if (!IsInitProcessingMode())
5702  ereport(ERROR,
5703  (errmsg("invalid processing mode in background worker")));
5705 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define ERROR
Definition: elog.h:46
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:49
const char * username
Definition: pgbench.c:282
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c: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 5711 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().

5712 {
5714 
5715  /* XXX is this the right errcode? */
5717  ereport(FATAL,
5718  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5719  errmsg("database connection requirement not indicated during registration")));
5720 
5721  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5722 
5723  /* it had better not gotten out of "init" mode yet */
5724  if (!IsInitProcessingMode())
5725  ereport(ERROR,
5726  (errmsg("invalid processing mode in background worker")));
5728 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
#define ERROR
Definition: elog.h:46
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h: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 5868 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().

5869 {
5870  switch (pmState)
5871  {
5872  case PM_NO_CHILDREN:
5873  case PM_WAIT_DEAD_END:
5874  case PM_SHUTDOWN_2:
5875  case PM_SHUTDOWN:
5876  case PM_WAIT_BACKENDS:
5877  case PM_STOP_BACKENDS:
5878  break;
5879 
5880  case PM_RUN:
5882  return true;
5883  /* fall through */
5884 
5885  case PM_HOT_STANDBY:
5887  return true;
5888  /* fall through */
5889 
5890  case PM_RECOVERY:
5891  case PM_STARTUP:
5892  case PM_INIT:
5894  return true;
5895  /* fall through */
5896 
5897  }
5898 
5899  return false;
5900 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:338

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

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

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

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1534 of file postmaster.c.

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

Referenced by PostmasterMain().

1535 {
1536  char path[MAXPGPATH];
1537  FILE *fp;
1538 
1539  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1540 
1541  fp = AllocateFile(path, PG_BINARY_R);
1542  if (fp == NULL)
1543  {
1544  write_stderr("%s: could not find the database system\n"
1545  "Expected to find it in the directory \"%s\",\n"
1546  "but could not open file \"%s\": %s\n",
1547  progname, DataDir, path, strerror(errno));
1548  ExitPostmaster(2);
1549  }
1550  FreeFile(fp);
1551 }
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:5106
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2417
#define strerror
Definition: port.h:229
int FreeFile(FILE *file)
Definition: fd.c:2616
char * DataDir
Definition: globals.c:65
#define snprintf
Definition: port.h:216

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

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

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

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

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

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1432 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

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

2509 {
2510  Port *port;
2511 
2512  if (!(port = (Port *) calloc(1, sizeof(Port))))
2513  {
2514  ereport(LOG,
2515  (errcode(ERRCODE_OUT_OF_MEMORY),
2516  errmsg("out of memory")));
2517  ExitPostmaster(1);
2518  }
2519 
2520  if (StreamConnection(serverFd, port) != STATUS_OK)
2521  {
2522  if (port->sock != PGINVALID_SOCKET)
2523  StreamClose(port->sock);
2524  ConnFree(port);
2525  return NULL;
2526  }
2527 
2528  return port;
2529 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:850
static void ConnFree(Port *port)
Definition: postmaster.c:2539
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:5106
#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 2539 of file postmaster.c.

References free.

Referenced by ConnCreate(), and ServerLoop().

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

◆ CountChildren()

static int CountChildren ( int  target)
static

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

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

◆ CreateOptsFile()

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

Definition at line 5634 of file postmaster.c.

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

Referenced by PostmasterMain().

5635 {
5636  FILE *fp;
5637  int i;
5638 
5639 #define OPTS_FILE "postmaster.opts"
5640 
5641  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5642  {
5643  ereport(LOG,
5645  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5646  return false;
5647  }
5648 
5649  fprintf(fp, "%s", fullprogname);
5650  for (i = 1; i < argc; i++)
5651  fprintf(fp, " \"%s\"", argv[i]);
5652  fputs("\n", fp);
5653 
5654  if (fclose(fp))
5655  {
5656  ereport(LOG,
5658  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5659  return false;
5660  }
5661 
5662  return true;
5663 }
#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 1563 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().

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

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

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

5777 {
5778  pid_t worker_pid;
5779 
5780  Assert(rw->rw_pid == 0);
5781 
5782  /*
5783  * Allocate and assign the Backend element. Note we must do this before
5784  * forking, so that we can handle failures (out of memory or child-process
5785  * slots) cleanly.
5786  *
5787  * Treat failure as though the worker had crashed. That way, the
5788  * postmaster will wait a bit before attempting to start it again; if we
5789  * tried again right away, most likely we'd find ourselves hitting the
5790  * same resource-exhaustion condition.
5791  */
5792  if (!assign_backendlist_entry(rw))
5793  {
5795  return false;
5796  }
5797 
5798  ereport(DEBUG1,
5799  (errmsg_internal("starting background worker process \"%s\"",
5800  rw->rw_worker.bgw_name)));
5801 
5802 #ifdef EXEC_BACKEND
5803  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5804 #else
5805  switch ((worker_pid = fork_process()))
5806 #endif
5807  {
5808  case -1:
5809  /* in postmaster, fork failed ... */
5810  ereport(LOG,
5811  (errmsg("could not fork worker process: %m")));
5812  /* undo what assign_backendlist_entry did */
5814  rw->rw_child_slot = 0;
5815  free(rw->rw_backend);
5816  rw->rw_backend = NULL;
5817  /* mark entry as crashed, so we'll try again later */
5819  break;
5820 
5821 #ifndef EXEC_BACKEND
5822  case 0:
5823  /* in postmaster child ... */
5825 
5826  /* Close the postmaster's sockets */
5827  ClosePostmasterPorts(false);
5828 
5829  /*
5830  * Before blowing away PostmasterContext, save this bgworker's
5831  * data where it can find it.
5832  */
5835  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5836 
5837  /* Release postmaster's working memory context */
5840  PostmasterContext = NULL;
5841 
5843 
5844  exit(1); /* should not get here */
5845  break;
5846 #endif
5847  default:
5848  /* in postmaster, fork successful ... */
5849  rw->rw_pid = worker_pid;
5850  rw->rw_backend->pid = rw->rw_pid;
5852  /* add new worker to lists of backends */
5854 #ifdef EXEC_BACKEND
5855  ShmemBackendArrayAdd(rw->rw_backend);
5856 #endif
5857  return true;
5858  }
5859 
5860  return false;
5861 }
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:195
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:186
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2556
void StartBackgroundWorker(void)
Definition: bgworker.c:734
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5911
static dlist_head BackendList
Definition: postmaster.c:189
MemoryContext TopMemoryContext
Definition: mcxt.c:48
#define ereport(elevel,...)
Definition: elog.h:157
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:804
pid_t pid
Definition: postmaster.c:180
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:50

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5342 of file postmaster.c.

Referenced by PostmasterMain().

5343 {
5344 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5106 of file postmaster.c.

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

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

5107 {
5108 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5109 
5110  /*
5111  * There is no known cause for a postmaster to become multithreaded after
5112  * startup. Recheck to account for the possibility of unknown causes.
5113  * This message uses LOG level, because an unclean shutdown at this point
5114  * would usually not look much different from a clean shutdown.
5115  */
5116  if (pthread_is_threaded_np() != 0)
5117  ereport(LOG,
5118  (errcode(ERRCODE_INTERNAL_ERROR),
5119  errmsg_internal("postmaster became multithreaded"),
5120  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5121 #endif
5122 
5123  /* should cleanup shared memory and kill all backends */
5124 
5125  /*
5126  * Not sure of the semantics here. When the Postmaster dies, should the
5127  * backends all be killed? probably not.
5128  *
5129  * MUST -- vadim 05-10-1999
5130  */
5131 
5132  proc_exit(status);
5133 }
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 1480 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().

1481 {
1482  DIR *pdir;
1483 
1484  /* Locate the postgres executable itself */
1485  if (find_my_exec(argv0, my_exec_path) < 0)
1486  ereport(FATAL,
1487  (errmsg("%s: could not locate my own executable path", argv0)));
1488 
1489 #ifdef EXEC_BACKEND
1490  /* Locate executable backend before we change working directory */
1491  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1492  postgres_exec_path) < 0)
1493  ereport(FATAL,
1494  (errmsg("%s: could not locate matching postgres executable",
1495  argv0)));
1496 #endif
1497 
1498  /*
1499  * Locate the pkglib directory --- this has to be set early in case we try
1500  * to load any modules from it in response to postgresql.conf entries.
1501  */
1503 
1504  /*
1505  * Verify that there's a readable directory there; otherwise the Postgres
1506  * installation is incomplete or corrupt. (A typical cause of this
1507  * failure is that the postgres executable has been moved or hardlinked to
1508  * some directory that's not a sibling of the installation lib/
1509  * directory.)
1510  */
1511  pdir = AllocateDir(pkglib_path);
1512  if (pdir == NULL)
1513  ereport(ERROR,
1515  errmsg("could not open directory \"%s\": %m",
1516  pkglib_path),
1517  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1518  my_exec_path)));
1519  FreeDir(pdir);
1520 
1521  /*
1522  * XXX is it worth similarly checking the share/ directory? If the lib/
1523  * directory is there, then share/ probably is too.
1524  */
1525 }
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:2678
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:2796

◆ HandleChildCrash()

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

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1903 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

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

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

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2620 of file postmaster.c.

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

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

2621 {
2622  unsigned int rseed;
2623 
2624  MyProcPid = getpid();
2627 
2628  /*
2629  * Set a different seed for random() in every process. We want something
2630  * unpredictable, so if possible, use high-quality random bits for the
2631  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2632  */
2633  if (!pg_strong_random(&rseed, sizeof(rseed)))
2634  {
2635  /*
2636  * Since PIDs and timestamps tend to change more frequently in their
2637  * least significant bits, shift the timestamp left to allow a larger
2638  * total number of seeds in a given time period. Since that would
2639  * leave only 20 bits of the timestamp that cycle every ~1 second,
2640  * also mix in some higher bits.
2641  */
2642  rseed = ((uint64) MyProcPid) ^
2643  ((uint64) MyStartTimestamp << 12) ^
2644  ((uint64) MyStartTimestamp >> 20);
2645  }
2646  srandom(rseed);
2647 }
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 3691 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().

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

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5678 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5679 {
5680  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5682 }
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 5975 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().

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

5616 {
5617  if (WalReceiverPID == 0 &&
5618  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5619  pmState == PM_HOT_STANDBY) &&
5621  {
5623  if (WalReceiverPID != 0)
5624  WalReceiverRequested = false;
5625  /* else leave the flag set, so we'll try again later */
5626  }
5627 }
static pid_t WalReceiverPID
Definition: postmaster.c:253
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:376
static int Shutdown
Definition: postmaster.c:276
#define SmartShutdown
Definition: postmaster.c:272
static PMState pmState
Definition: postmaster.c:338
#define StartWalReceiver()
Definition: postmaster.c:559

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

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

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

◆ PostmasterMain()

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

Definition at line 581 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), 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().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6094 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

6095 {
6096  dlist_iter iter;
6097  Backend *bp;
6098 
6099  dlist_foreach(iter, &BackendList)
6100  {
6101  bp = dlist_container(Backend, elem, iter.cur);
6102  if (bp->pid == pid)
6103  {
6104  bp->bgworker_notify = true;
6105  return true;
6106  }
6107  }
6108  return false;
6109 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
bool bgworker_notify
Definition: postmaster.c:185
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
static dlist_head BackendList
Definition: postmaster.c:189
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:180

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

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

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

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5327 of file postmaster.c.

Referenced by BackendInitialize().

5328 {
5329  _exit(1);
5330 }

◆ processCancelRequest()

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

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

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

◆ ProcessStartupPacket()