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

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

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

Typedefs

typedef struct bkend Backend
 

Enumerations

enum  StartupStatusEnum { STARTUP_NOT_RUNNING, STARTUP_RUNNING, STARTUP_SIGNALED, STARTUP_CRASHED }
 
enum  PMState {
  PM_INIT, PM_STARTUP, PM_RECOVERY, PM_HOT_STANDBY,
  PM_RUN, PM_WAIT_BACKUP, PM_WAIT_READONLY, PM_WAIT_BACKENDS,
  PM_SHUTDOWN, PM_SHUTDOWN_2, PM_WAIT_DEAD_END, PM_NO_CHILDREN
}
 

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 startup_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 secure_done)
 
static void SendNegotiateProtocolVersion (List *unrecognized_protocol_options)
 
static void processCancelRequest (Port *port, void *pkt)
 
static int initMasks (fd_set *rmask)
 
static void report_fork_failure_to_client (Port *port, int errnum)
 
static CAC_state canAcceptConnections (int backend_type)
 
static bool RandomCancelKey (int32 *cancel_key)
 
static void signal_child (pid_t pid, int signal)
 
static bool SignalSomeChildren (int signal, int targets)
 
static void TerminateChildren (int signal)
 
static int CountChildren (int target)
 
static bool assign_backendlist_entry (RegisteredBgWorker *rw)
 
static void maybe_start_bgworkers (void)
 
static bool CreateOptsFile (int argc, char *argv[], char *fullprogname)
 
static pid_t StartChildProcess (AuxProcType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
void PostmasterMain (int argc, char *argv[])
 
static void DetermineSleepTime (struct timeval *timeout)
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
int MaxLivePostmasterChildren (void)
 
void BackgroundWorkerInitializeConnection (const char *dbname, const char *username, uint32 flags)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid, uint32 flags)
 
void BackgroundWorkerBlockSignals (void)
 
void BackgroundWorkerUnblockSignals (void)
 
static bool do_start_bgworker (RegisteredBgWorker *rw)
 
static bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

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

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 146 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 147 of file postmaster.c.

Referenced by CountChildren(), and SignalSomeChildren().

◆ BACKEND_TYPE_WORKER

#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)

Definition at line 151 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ EXIT_STATUS_0

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

Definition at line 548 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 549 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 550 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 274 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 275 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:173
static PMState pmState
Definition: postmaster.c:341
#define XLogArchivingActive()
Definition: xlog.h:170

Definition at line 435 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 348 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 418 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 273 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 542 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 543 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 541 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 545 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 544 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

Typedef Documentation

◆ Backend

typedef struct bkend Backend

Enumeration Type Documentation

◆ PMState

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

Definition at line 323 of file postmaster.c.

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 261 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

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

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4271 of file postmaster.c.

References SockAddr::addr, am_walsender, AuthenticationTimeout, B_WAL_SENDER, BlockSig, ClientAuthInProgress, Port::database_name, DestRemote, disable_timeout(), enable_timeout_after(), ereport, errmsg(), errmsg_internal(), gai_strerror, init_ps_display(), InitializeTimeouts(), LOG, Log_connections, log_hostname, MyProcPort, NI_MAXHOST, NI_MAXSERV, NI_NUMERICHOST, NI_NUMERICSERV, pg_getnameinfo_all(), PG_SETMASK, pg_usleep(), pgstat_get_backend_desc(), port, pq_init(), pqsignal(), PreAuthDelay, proc_exit(), ProcessStartupPacket(), Port::raddr, RegisterTimeout(), Port::remote_host, Port::remote_hostname, Port::remote_port, SockAddr::salen, SIGQUIT, snprintf, startup_die(), STARTUP_PACKET_TIMEOUT, StartupBlockSig, StartupPacketTimeoutHandler(), status(), STATUS_OK, update_process_title, Port::user_name, WARNING, and whereToSendOutput.

Referenced by BackendRun(), and BackendStartup().

4272 {
4273  int status;
4274  int ret;
4275  char remote_host[NI_MAXHOST];
4276  char remote_port[NI_MAXSERV];
4277  char remote_ps_data[NI_MAXHOST];
4278 
4279  /* Save port etc. for ps status */
4280  MyProcPort = port;
4281 
4282  /*
4283  * PreAuthDelay is a debugging aid for investigating problems in the
4284  * authentication cycle: it can be set in postgresql.conf to allow time to
4285  * attach to the newly-forked backend with a debugger. (See also
4286  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4287  * is not honored until after authentication.)
4288  */
4289  if (PreAuthDelay > 0)
4290  pg_usleep(PreAuthDelay * 1000000L);
4291 
4292  /* This flag will remain set until InitPostgres finishes authentication */
4293  ClientAuthInProgress = true; /* limit visibility of log messages */
4294 
4295  /* set these to empty in case they are needed before we set them up */
4296  port->remote_host = "";
4297  port->remote_port = "";
4298 
4299  /*
4300  * Initialize libpq and enable reporting of ereport errors to the client.
4301  * Must do this now because authentication uses libpq to send messages.
4302  */
4303  pq_init(); /* initialize libpq to talk to client */
4304  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4305 
4306  /*
4307  * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
4308  * timeout while trying to collect the startup packet. Otherwise the
4309  * postmaster cannot shutdown the database FAST or IMMED cleanly if a
4310  * buggy client fails to send the packet promptly. XXX it follows that
4311  * the remainder of this function must tolerate losing control at any
4312  * instant. Likewise, any pg_on_exit_callback registered before or during
4313  * this function must be prepared to execute at any instant between here
4314  * and the end of this function. Furthermore, affected callbacks execute
4315  * partially or not at all when a second exit-inducing signal arrives
4316  * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to
4317  * that mechanic, callbacks need not anticipate more than one call.) This
4318  * is fragile; it ought to instead follow the norm of handling interrupts
4319  * at selected, safe opportunities.
4320  */
4321  pqsignal(SIGTERM, startup_die);
4323  InitializeTimeouts(); /* establishes SIGALRM handler */
4325 
4326  /*
4327  * Get the remote host name and port for logging and status display.
4328  */
4329  remote_host[0] = '\0';
4330  remote_port[0] = '\0';
4331  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4332  remote_host, sizeof(remote_host),
4333  remote_port, sizeof(remote_port),
4334  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4335  ereport(WARNING,
4336  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4337  gai_strerror(ret))));
4338  if (remote_port[0] == '\0')
4339  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
4340  else
4341  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
4342 
4343  /*
4344  * Save remote_host and remote_port in port structure (after this, they
4345  * will appear in log_line_prefix data for log messages).
4346  */
4347  port->remote_host = strdup(remote_host);
4348  port->remote_port = strdup(remote_port);
4349 
4350  /* And now we can issue the Log_connections message, if wanted */
4351  if (Log_connections)
4352  {
4353  if (remote_port[0])
4354  ereport(LOG,
4355  (errmsg("connection received: host=%s port=%s",
4356  remote_host,
4357  remote_port)));
4358  else
4359  ereport(LOG,
4360  (errmsg("connection received: host=%s",
4361  remote_host)));
4362  }
4363 
4364  /*
4365  * If we did a reverse lookup to name, we might as well save the results
4366  * rather than possibly repeating the lookup during authentication.
4367  *
4368  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4369  * get nothing useful for a client without an rDNS entry. Therefore, we
4370  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4371  * it into remote_hostname if so. (This test is conservative and might
4372  * sometimes classify a hostname as numeric, but an error in that
4373  * direction is safe; it only results in a possible extra lookup.)
4374  */
4375  if (log_hostname &&
4376  ret == 0 &&
4377  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4378  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4379  port->remote_hostname = strdup(remote_host);
4380 
4381  /*
4382  * Ready to begin client interaction. We will give up and exit(1) after a
4383  * time delay, so that a broken client can't hog a connection
4384  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4385  * against the time limit.
4386  *
4387  * Note: AuthenticationTimeout is applied here while waiting for the
4388  * startup packet, and then again in InitPostgres for the duration of any
4389  * authentication operations. So a hostile client could tie up the
4390  * process for nearly twice AuthenticationTimeout before we kick him off.
4391  *
4392  * Note: because PostgresMain will call InitializeTimeouts again, the
4393  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4394  * since we never use it again after this function.
4395  */
4398 
4399  /*
4400  * Receive the startup packet (which might turn out to be a cancel request
4401  * packet).
4402  */
4403  status = ProcessStartupPacket(port, false);
4404 
4405  /*
4406  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4407  * already did any appropriate error reporting.
4408  */
4409  if (status != STATUS_OK)
4410  proc_exit(0);
4411 
4412  /*
4413  * Now that we have the user and database name, we can set the process
4414  * title for ps. It's good to do this as early as possible in startup.
4415  *
4416  * For a walsender, the ps display is set in the following form:
4417  *
4418  * postgres: walsender <user> <host> <activity>
4419  *
4420  * To achieve that, we pass "walsender" as username and username as dbname
4421  * to init_ps_display(). XXX: should add a new variant of
4422  * init_ps_display() to avoid abusing the parameters like this.
4423  */
4424  if (am_walsender)
4426  update_process_title ? "authentication" : "");
4427  else
4428  init_ps_display(port->user_name, port->database_name, remote_ps_data,
4429  update_process_title ? "authentication" : "");
4430 
4431  /*
4432  * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4433  */
4435  PG_SETMASK(&BlockSig);
4436 }
void InitializeTimeouts(void)
Definition: timeout.c:340
#define SIGQUIT
Definition: win32_port.h:155
static void startup_die(SIGNAL_ARGS)
Definition: postmaster.c:5331
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
struct Port * MyProcPort
Definition: globals.c:43
bool update_process_title
Definition: ps_status.c:35
static int ProcessStartupPacket(Port *port, bool secure_done)
Definition: postmaster.c:1921
const char * pgstat_get_backend_desc(BackendType backendType)
Definition: pgstat.c:4274
struct sockaddr_storage addr
Definition: pqcomm.h:64
void proc_exit(int code)
Definition: ipc.c:104
char * remote_port
Definition: libpq-be.h:132
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:242
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define gai_strerror
Definition: getaddrinfo.h:146
int AuthenticationTimeout
Definition: postmaster.c:239
char * remote_hostname
Definition: libpq-be.h:128
bool ClientAuthInProgress
Definition: postmaster.c:352
SockAddr raddr
Definition: libpq-be.h:126
bool am_walsender
Definition: walsender.c:114
void pg_usleep(long microsec)
Definition: signal.c:53
void pq_init(void)
Definition: pqcomm.c:194
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:141
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
bool log_hostname
Definition: postmaster.c:241
static int port
Definition: pg_regress.c:92
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:373
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
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
sigset_t StartupBlockSig
Definition: pqsignal.c:22
int PreAuthDelay
Definition: postmaster.c:238
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:784
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5355
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
CommandDest whereToSendOutput
Definition: postgres.c:90
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
char * database_name
Definition: libpq-be.h:140
#define snprintf
Definition: port.h:192
void init_ps_display(const char *username, const char *dbname, const char *host_info, const char *initial_str)
Definition: ps_status.c:249

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4447 of file postmaster.c.

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

Referenced by BackendStartup().

4448 {
4449  char **av;
4450  int maxac;
4451  int ac;
4452  int i;
4453 
4454  /*
4455  * Now, build the argv vector that will be given to PostgresMain.
4456  *
4457  * The maximum possible number of commandline arguments that could come
4458  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4459  * pg_split_opts().
4460  */
4461  maxac = 2; /* for fixed args supplied below */
4462  maxac += (strlen(ExtraOptions) + 1) / 2;
4463 
4464  av = (char **) MemoryContextAlloc(TopMemoryContext,
4465  maxac * sizeof(char *));
4466  ac = 0;
4467 
4468  av[ac++] = "postgres";
4469 
4470  /*
4471  * Pass any backend switches specified with -o on the postmaster's own
4472  * command line. We assume these are secure.
4473  */
4474  pg_split_opts(av, &ac, ExtraOptions);
4475 
4476  av[ac] = NULL;
4477 
4478  Assert(ac < maxac);
4479 
4480  /*
4481  * Debug: print arguments being passed to backend
4482  */
4483  ereport(DEBUG3,
4484  (errmsg_internal("%s child[%d]: starting with (",
4485  progname, (int) getpid())));
4486  for (i = 0; i < ac; ++i)
4487  ereport(DEBUG3,
4488  (errmsg_internal("\t%s", av[i])));
4489  ereport(DEBUG3,
4490  (errmsg_internal(")")));
4491 
4492  /*
4493  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4494  * just yet, though, because InitPostgres will need the HBA data.)
4495  */
4497 
4498  PostgresMain(ac, av, port->database_name, port->user_name);
4499 }
#define DEBUG3
Definition: elog.h:23
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
const char * progname
Definition: pg_standby.c:37
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3727
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:467
char * user_name
Definition: libpq-be.h:141
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
struct @18::@19 av[32]
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:223
#define Assert(condition)
Definition: c.h:732
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:796
int i
char * database_name
Definition: libpq-be.h:140

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4121 of file postmaster.c.

References AssignPostmasterChildSlot(), BACKEND_TYPE_NORMAL, BackendInitialize(), BackendRun(), bkend::bgworker_notify, bkend::bkend_type, CAC_OK, CAC_WAITBACKUP, 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().

4122 {
4123  Backend *bn; /* for backend cleanup */
4124  pid_t pid;
4125 
4126  /*
4127  * Create backend data structure. Better before the fork() so we can
4128  * handle failure cleanly.
4129  */
4130  bn = (Backend *) malloc(sizeof(Backend));
4131  if (!bn)
4132  {
4133  ereport(LOG,
4134  (errcode(ERRCODE_OUT_OF_MEMORY),
4135  errmsg("out of memory")));
4136  return STATUS_ERROR;
4137  }
4138 
4139  /*
4140  * Compute the cancel key that will be assigned to this backend. The
4141  * backend will have its own copy in the forked-off process' value of
4142  * MyCancelKey, so that it can transmit the key to the frontend.
4143  */
4145  {
4146  free(bn);
4147  ereport(LOG,
4148  (errcode(ERRCODE_INTERNAL_ERROR),
4149  errmsg("could not generate random cancel key")));
4150  return STATUS_ERROR;
4151  }
4152 
4153  bn->cancel_key = MyCancelKey;
4154 
4155  /* Pass down canAcceptConnections state */
4157  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4159 
4160  /*
4161  * Unless it's a dead_end child, assign it a child slot number
4162  */
4163  if (!bn->dead_end)
4165  else
4166  bn->child_slot = 0;
4167 
4168  /* Hasn't asked to be notified about any bgworkers yet */
4169  bn->bgworker_notify = false;
4170 
4171 #ifdef EXEC_BACKEND
4172  pid = backend_forkexec(port);
4173 #else /* !EXEC_BACKEND */
4174  pid = fork_process();
4175  if (pid == 0) /* child */
4176  {
4177  free(bn);
4178 
4179  /* Detangle from postmaster */
4181 
4182  /* Close the postmaster's sockets */
4183  ClosePostmasterPorts(false);
4184 
4185  /* Perform additional initialization and collect startup packet */
4186  BackendInitialize(port);
4187 
4188  /* And run the backend */
4189  BackendRun(port);
4190  }
4191 #endif /* EXEC_BACKEND */
4192 
4193  if (pid < 0)
4194  {
4195  /* in parent, fork failed */
4196  int save_errno = errno;
4197 
4198  if (!bn->dead_end)
4200  free(bn);
4201  errno = save_errno;
4202  ereport(LOG,
4203  (errmsg("could not fork new process for connection: %m")));
4204  report_fork_failure_to_client(port, save_errno);
4205  return STATUS_ERROR;
4206  }
4207 
4208  /* in parent, successful fork */
4209  ereport(DEBUG2,
4210  (errmsg_internal("forked new backend, pid=%d socket=%d",
4211  (int) pid, (int) port->sock)));
4212 
4213  /*
4214  * Everything's been successful, it's safe to add this backend to our list
4215  * of backends.
4216  */
4217  bn->pid = pid;
4218  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4220 
4221 #ifdef EXEC_BACKEND
4222  if (!bn->dead_end)
4223  ShmemBackendArrayAdd(bn);
4224 #endif
4225 
4226  return STATUS_OK;
4227 }
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2416
CAC_state canAcceptConnections
Definition: libpq-be.h:133
void InitPostmasterChild(void)
Definition: miscinit.c:273
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:4447
pid_t fork_process(void)
Definition: fork_process.c:31
int errcode(int sqlerrcode)
Definition: elog.c:570
#define STATUS_ERROR
Definition: c.h:1090
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2541
pgsocket sock
Definition: libpq-be.h:122
bool bgworker_notify
Definition: postmaster.c:182
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:184
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:44
static dlist_head BackendList
Definition: postmaster.c:186
#define DEBUG2
Definition: elog.h:24
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4238
int32 cancel_key
Definition: postmaster.c:172
bool dead_end
Definition: postmaster.c:181
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5365
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
pid_t pid
Definition: postmaster.c:171
int MyPMChildSlot
Definition: globals.c:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
static void BackendInitialize(Port *port)
Definition: postmaster.c:4271

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5731 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5732 {
5733  PG_SETMASK(&BlockSig);
5734 }
#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 5685 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().

5686 {
5688 
5689  /* XXX is this the right errcode? */
5691  ereport(FATAL,
5692  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5693  errmsg("database connection requirement not indicated during registration")));
5694 
5696 
5697  /* it had better not gotten out of "init" mode yet */
5698  if (!IsInitProcessingMode())
5699  ereport(ERROR,
5700  (errmsg("invalid processing mode in background worker")));
5702 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define SetProcessingMode(mode)
Definition: miscadmin.h:380
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:141
static char * username
Definition: initdb.c:133
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:52
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define IsInitProcessingMode()
Definition: miscadmin.h:375

◆ BackgroundWorkerInitializeConnectionByOid()

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

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

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

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5737 of file postmaster.c.

References Assert, av, lengthof, MAXPGPATH, PG_SETMASK, snprintf, and UnBlockSig.

Referenced by ApplyLauncherMain(), ApplyWorkerMain(), autoprewarm_database_main(), autoprewarm_main(), initialize_worker_spi(), ParallelWorkerMain(), and test_shm_mq_main().

5738 {
5740 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t UnBlockSig
Definition: pqsignal.c:22

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5865 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_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_DEAD_END, PM_WAIT_READONLY, and pmState.

Referenced by maybe_start_bgworkers().

5866 {
5867  switch (pmState)
5868  {
5869  case PM_NO_CHILDREN:
5870  case PM_WAIT_DEAD_END:
5871  case PM_SHUTDOWN_2:
5872  case PM_SHUTDOWN:
5873  case PM_WAIT_BACKENDS:
5874  case PM_WAIT_READONLY:
5875  case PM_WAIT_BACKUP:
5876  break;
5877 
5878  case PM_RUN:
5880  return true;
5881  /* fall through */
5882 
5883  case PM_HOT_STANDBY:
5885  return true;
5886  /* fall through */
5887 
5888  case PM_RECOVERY:
5889  case PM_STARTUP:
5890  case PM_INIT:
5892  return true;
5893  /* fall through */
5894 
5895  }
5896 
5897  return false;
5898 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:341

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 2416 of file postmaster.c.

References BACKEND_TYPE_ALL, BACKEND_TYPE_BGWORKER, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_TOOMANY, CAC_WAITBACKUP, CountChildren(), FatalError, MaxLivePostmasterChildren(), NoShutdown, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_WAIT_BACKUP, pmState, and Shutdown.

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

2417 {
2418  CAC_state result = CAC_OK;
2419 
2420  /*
2421  * Can't start backends when in startup/shutdown/inconsistent recovery
2422  * state. We treat autovac workers the same as user backends for this
2423  * purpose. However, bgworkers are excluded from this test; we expect
2424  * bgworker_should_start_now() decided whether the DB state allows them.
2425  *
2426  * In state PM_WAIT_BACKUP only superusers can connect (this must be
2427  * allowed so that a superuser can end online backup mode); we return
2428  * CAC_WAITBACKUP code to indicate that this must be checked later. Note
2429  * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
2430  * have checked for too many children.
2431  */
2432  if (pmState != PM_RUN &&
2433  backend_type != BACKEND_TYPE_BGWORKER)
2434  {
2435  if (pmState == PM_WAIT_BACKUP)
2436  result = CAC_WAITBACKUP; /* allow superusers only */
2437  else if (Shutdown > NoShutdown)
2438  return CAC_SHUTDOWN; /* shutdown is pending */
2439  else if (!FatalError &&
2440  (pmState == PM_STARTUP ||
2441  pmState == PM_RECOVERY))
2442  return CAC_STARTUP; /* normal startup */
2443  else if (!FatalError &&
2445  result = CAC_OK; /* connection OK during hot standby */
2446  else
2447  return CAC_RECOVERY; /* else must be crash recovery */
2448  }
2449 
2450  /*
2451  * Don't start too many children.
2452  *
2453  * We allow more connections here than we can have backends because some
2454  * might still be authenticating; they might fail auth, or some existing
2455  * backend might exit before the auth cycle is completed. The exact
2456  * MaxBackends limit is enforced when a new backend tries to join the
2457  * shared-inval backend array.
2458  *
2459  * The limit here must match the sizes of the per-child-process arrays;
2460  * see comments for MaxLivePostmasterChildren().
2461  */
2463  result = CAC_TOOMANY;
2464 
2465  return result;
2466 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
static bool FatalError
Definition: postmaster.c:279
static int Shutdown
Definition: postmaster.c:277
static int CountChildren(int target)
Definition: postmaster.c:5375
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static PMState pmState
Definition: postmaster.c:341
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5675
#define NoShutdown
Definition: postmaster.c:272
CAC_state
Definition: libpq-be.h:71

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1516 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

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

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

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

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2541 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, StreamClose(), and syslogPipe.

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

2542 {
2543  int i;
2544 
2545 #ifndef WIN32
2546 
2547  /*
2548  * Close the write end of postmaster death watch pipe. It's important to
2549  * do this as early as possible, so that if postmaster dies, others won't
2550  * think that it's still running because we're holding the pipe open.
2551  */
2553  ereport(FATAL,
2555  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2557 #endif
2558 
2559  /* Close the listen sockets */
2560  for (i = 0; i < MAXLISTEN; i++)
2561  {
2562  if (ListenSocket[i] != PGINVALID_SOCKET)
2563  {
2566  }
2567  }
2568 
2569  /* If using syslogger, close the read side of the pipe */
2570  if (!am_syslogger)
2571  {
2572 #ifndef WIN32
2573  if (syslogPipe[0] >= 0)
2574  close(syslogPipe[0]);
2575  syslogPipe[0] = -1;
2576 #else
2577  if (syslogPipe[0])
2578  CloseHandle(syslogPipe[0]);
2579  syslogPipe[0] = 0;
2580 #endif
2581  }
2582 
2583 #ifdef USE_BONJOUR
2584  /* If using Bonjour, close the connection to the mDNS daemon */
2585  if (bonjour_sdref)
2586  close(DNSServiceRefSockFD(bonjour_sdref));
2587 #endif
2588 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
#define FATAL
Definition: elog.h:52
bool am_syslogger
Definition: syslogger.c:80
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
int postmaster_alive_fds[2]
Definition: postmaster.c:557
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:217
int syslogPipe[2]
Definition: syslogger.c:118

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1415 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2475 of file postmaster.c.

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

Referenced by ServerLoop().

2476 {
2477  Port *port;
2478 
2479  if (!(port = (Port *) calloc(1, sizeof(Port))))
2480  {
2481  ereport(LOG,
2482  (errcode(ERRCODE_OUT_OF_MEMORY),
2483  errmsg("out of memory")));
2484  ExitPostmaster(1);
2485  }
2486 
2487  if (StreamConnection(serverFd, port) != STATUS_OK)
2488  {
2489  if (port->sock != PGINVALID_SOCKET)
2490  StreamClose(port->sock);
2491  ConnFree(port);
2492  return NULL;
2493  }
2494 
2495  /*
2496  * Allocate GSSAPI specific state struct
2497  */
2498 #ifndef EXEC_BACKEND
2499 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2500  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2501  if (!port->gss)
2502  {
2503  ereport(LOG,
2504  (errcode(ERRCODE_OUT_OF_MEMORY),
2505  errmsg("out of memory")));
2506  ExitPostmaster(1);
2507  }
2508 #endif
2509 #endif
2510 
2511  return port;
2512 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
static void ConnFree(Port *port)
Definition: postmaster.c:2519
int errcode(int sqlerrcode)
Definition: elog.c:570
Definition: libpq-be.h:120
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:716
pgsocket sock
Definition: libpq-be.h:122
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5113
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
static int port
Definition: pg_regress.c:92
#define PGINVALID_SOCKET
Definition: port.h:33
void * gss
Definition: libpq-be.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2519 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2520 {
2521 #ifdef USE_SSL
2522  secure_close(conn);
2523 #endif
2524  if (conn->gss)
2525  free(conn->gss);
2526  free(conn);
2527 }
PGconn * conn
Definition: streamutil.c:56
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:134

◆ CountChildren()

static int CountChildren ( int  target)
static

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

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

◆ CreateOptsFile()

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

Definition at line 5635 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1545 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5773 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

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

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5346 of file postmaster.c.

Referenced by PostmasterMain().

5347 {
5348 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5113 of file postmaster.c.

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

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

5114 {
5115 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5116 
5117  /*
5118  * There is no known cause for a postmaster to become multithreaded after
5119  * startup. Recheck to account for the possibility of unknown causes.
5120  * This message uses LOG level, because an unclean shutdown at this point
5121  * would usually not look much different from a clean shutdown.
5122  */
5123  if (pthread_is_threaded_np() != 0)
5124  ereport(LOG,
5125  (errcode(ERRCODE_INTERNAL_ERROR),
5126  errmsg_internal("postmaster became multithreaded"),
5127  errdetail("Please report this to <pgsql-bugs@lists.postgresql.org>.")));
5128 #endif
5129 
5130  /* should cleanup shared memory and kill all backends */
5131 
5132  /*
5133  * Not sure of the semantics here. When the Postmaster dies, should the
5134  * backends all be killed? probably not.
5135  *
5136  * MUST -- vadim 05-10-1999
5137  */
5138 
5139  proc_exit(status);
5140 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:570
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1463 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ HandleChildCrash()

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

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

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1883 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6562 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 TRUE.

Referenced by PostmasterMain().

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

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2597 of file postmaster.c.

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

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

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

◆ LogChildExit()

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

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

3704 {
3705  /*
3706  * size of activity_buffer is arbitrary, but set equal to default
3707  * track_activity_query_size
3708  */
3709  char activity_buffer[1024];
3710  const char *activity = NULL;
3711 
3712  if (!EXIT_STATUS_0(exitstatus))
3713  activity = pgstat_get_crashed_backend_activity(pid,
3714  activity_buffer,
3715  sizeof(activity_buffer));
3716 
3717  if (WIFEXITED(exitstatus))
3718  ereport(lev,
3719 
3720  /*------
3721  translator: %s is a noun phrase describing a child process, such as
3722  "server process" */
3723  (errmsg("%s (PID %d) exited with exit code %d",
3724  procname, pid, WEXITSTATUS(exitstatus)),
3725  activity ? errdetail("Failed process was running: %s", activity) : 0));
3726  else if (WIFSIGNALED(exitstatus))
3727  {
3728 #if defined(WIN32)
3729  ereport(lev,
3730 
3731  /*------
3732  translator: %s is a noun phrase describing a child process, such as
3733  "server process" */
3734  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3735  procname, pid, WTERMSIG(exitstatus)),
3736  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3737  activity ? errdetail("Failed process was running: %s", activity) : 0));
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) was terminated by signal %d: %s",
3745  procname, pid, WTERMSIG(exitstatus),
3746  pg_strsignal(WTERMSIG(exitstatus))),
3747  activity ? errdetail("Failed process was running: %s", activity) : 0));
3748 #endif
3749  }
3750  else
3751  ereport(lev,
3752 
3753  /*------
3754  translator: %s is a noun phrase describing a child process, such as
3755  "server process" */
3756  (errmsg("%s (PID %d) exited with unrecognized status %d",
3757  procname, pid, exitstatus),
3758  activity ? errdetail("Failed process was running: %s", activity) : 0));
3759 }
int errhint(const char *fmt,...)
Definition: elog.c:974
#define WTERMSIG(w)
Definition: win32_port.h:141
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
#define WIFEXITED(w)
Definition: win32_port.h:138
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:42
int errmsg(const char *fmt,...)
Definition: elog.c:784
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
Definition: pgstat.c:4215
#define WIFSIGNALED(w)
Definition: win32_port.h:139
#define WEXITSTATUS(w)
Definition: win32_port.h:140
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5675 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

5676 {
5677  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5679 }
int max_wal_senders
Definition: walsender.c:120
int MaxConnections
Definition: globals.c:132
int autovacuum_max_workers
Definition: autovacuum.c:114
int max_worker_processes
Definition: globals.c:133

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5616 of file postmaster.c.

References NoShutdown, PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, PM_WAIT_READONLY, pmState, Shutdown, StartWalReceiver, WalReceiverPID, and WalReceiverRequested.

Referenced by ServerLoop(), and sigusr1_handler().

5617 {
5618  if (WalReceiverPID == 0 &&
5619  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5621  Shutdown == NoShutdown)
5622  {
5624  if (WalReceiverPID != 0)
5625  WalReceiverRequested = false;
5626  /* else leave the flag set, so we'll try again later */
5627  }
5628 }
static pid_t WalReceiverPID
Definition: postmaster.c:254
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:364
static int Shutdown
Definition: postmaster.c:277
static PMState pmState
Definition: postmaster.c:341
#define NoShutdown
Definition: postmaster.c:272
#define StartWalReceiver()
Definition: postmaster.c:545

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2730 of file postmaster.c.

References AbortStartTime, AddToDataDirLockFile(), AutoVacPID, BACKEND_TYPE_AUTOVAC, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, BgWriterPID, BlockSig, 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_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_READONLY, pmState, PostmasterStateMachine(), Shutdown, signal_child(), SignalSomeChildren(), SIGQUIT, SmartShutdown, StartupPID, TerminateChildren(), UnBlockSig, WalReceiverPID, and WalWriterPID.

Referenced by PostmasterMain().

2731 {
2732  int save_errno = errno;
2733 
2734  /*
2735  * We rely on the signal mechanism to have blocked all signals ... except
2736  * on Windows, which lacks sigaction(), so we have to do it manually.
2737  */
2738 #ifdef WIN32
2739  PG_SETMASK(&BlockSig);
2740 #endif
2741 
2742  ereport(DEBUG2,
2743  (errmsg_internal("postmaster received signal %d",
2744  postgres_signal_arg)));
2745 
2746  switch (postgres_signal_arg)
2747  {
2748  case SIGTERM:
2749 
2750  /*
2751  * Smart Shutdown:
2752  *
2753  * Wait for children to end their work, then shut down.
2754  */
2755  if (Shutdown >= SmartShutdown)
2756  break;
2758  ereport(LOG,
2759  (errmsg("received smart shutdown request")));
2760 
2761  /* Report status */
2763 #ifdef USE_SYSTEMD
2764  sd_notify(0, "STOPPING=1");
2765 #endif
2766 
2767  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2769  {
2770  /* autovac workers are told to shut down immediately */
2771  /* and bgworkers too; does this need tweaking? */
2772  SignalSomeChildren(SIGTERM,
2774  /* and the autovac launcher too */
2775  if (AutoVacPID != 0)
2776  signal_child(AutoVacPID, SIGTERM);
2777  /* and the bgwriter too */
2778  if (BgWriterPID != 0)
2779  signal_child(BgWriterPID, SIGTERM);
2780  /* and the walwriter too */
2781  if (WalWriterPID != 0)
2782  signal_child(WalWriterPID, SIGTERM);
2783 
2784  /*
2785  * If we're in recovery, we can't kill the startup process
2786  * right away, because at present doing so does not release
2787  * its locks. We might want to change this in a future
2788  * release. For the time being, the PM_WAIT_READONLY state
2789  * indicates that we're waiting for the regular (read only)
2790  * backends to die off; once they do, we'll kill the startup
2791  * and walreceiver processes.
2792  */
2793  pmState = (pmState == PM_RUN) ?
2795  }
2796 
2797  /*
2798  * Now wait for online backup mode to end and backends to exit. If
2799  * that is already the case, PostmasterStateMachine will take the
2800  * next step.
2801  */
2803  break;
2804 
2805  case SIGINT:
2806 
2807  /*
2808  * Fast Shutdown:
2809  *
2810  * Abort all children with SIGTERM (rollback active transactions
2811  * and exit) and shut down when they are gone.
2812  */
2813  if (Shutdown >= FastShutdown)
2814  break;
2816  ereport(LOG,
2817  (errmsg("received fast shutdown request")));
2818 
2819  /* Report status */
2821 #ifdef USE_SYSTEMD
2822  sd_notify(0, "STOPPING=1");
2823 #endif
2824 
2825  if (StartupPID != 0)
2826  signal_child(StartupPID, SIGTERM);
2827  if (BgWriterPID != 0)
2828  signal_child(BgWriterPID, SIGTERM);
2829  if (WalReceiverPID != 0)
2830  signal_child(WalReceiverPID, SIGTERM);
2831  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2832  {
2834 
2835  /*
2836  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2837  * and/or checkpointer should be active in this state; we just
2838  * signaled the first four, and we don't want to kill
2839  * checkpointer yet.
2840  */
2842  }
2843  else if (pmState == PM_RUN ||
2844  pmState == PM_WAIT_BACKUP ||
2848  {
2849  ereport(LOG,
2850  (errmsg("aborting any active transactions")));
2851  /* shut down all backends and workers */
2852  SignalSomeChildren(SIGTERM,
2855  /* and the autovac launcher too */
2856  if (AutoVacPID != 0)
2857  signal_child(AutoVacPID, SIGTERM);
2858  /* and the walwriter too */
2859  if (WalWriterPID != 0)
2860  signal_child(WalWriterPID, SIGTERM);
2862  }
2863 
2864  /*
2865  * Now wait for backends to exit. If there are none,
2866  * PostmasterStateMachine will take the next step.
2867  */
2869  break;
2870 
2871  case SIGQUIT:
2872 
2873  /*
2874  * Immediate Shutdown:
2875  *
2876  * abort all children with SIGQUIT, wait for them to exit,
2877  * terminate remaining ones with SIGKILL, then exit without
2878  * attempt to properly shut down the data base system.
2879  */
2880  if (Shutdown >= ImmediateShutdown)
2881  break;
2883  ereport(LOG,
2884  (errmsg("received immediate shutdown request")));
2885 
2886  /* Report status */
2888 #ifdef USE_SYSTEMD
2889  sd_notify(0, "STOPPING=1");
2890 #endif
2891 
2894 
2895  /* set stopwatch for them to die */
2896  AbortStartTime = time(NULL);
2897 
2898  /*
2899  * Now wait for backends to exit. If there are none,
2900  * PostmasterStateMachine will take the next step.
2901  */
2903  break;
2904  }
2905 
2906 #ifdef WIN32
2908 #endif
2909 
2910  errno = save_errno;
2911 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3768
#define SIGQUIT
Definition: win32_port.h:155
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1254
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4044
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define LOG
Definition: elog.h:26
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:146
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:277
static pid_t BgWriterPID
Definition: postmaster.c:251
static pid_t StartupPID
Definition: postmaster.c:250
#define SmartShutdown
Definition: postmaster.c:273
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4088
#define FastShutdown
Definition: postmaster.c:274
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4018
#define ereport(elevel, rest)
Definition: elog.h:141
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:341
#define ImmediateShutdown
Definition: postmaster.c:275
static pid_t WalWriterPID
Definition: postmaster.c:253
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
static pid_t AutoVacPID
Definition: postmaster.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:784
#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:345

◆ PostmasterMain()

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

Definition at line 567 of file postmaster.c.

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

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6092 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

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

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3768 of file postmaster.c.

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

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

3769 {
3770  if (pmState == PM_WAIT_BACKUP)
3771  {
3772  /*
3773  * PM_WAIT_BACKUP state ends when online backup mode is not active.
3774  */
3775  if (!BackupInProgress())
3777  }
3778 
3779  if (pmState == PM_WAIT_READONLY)
3780  {
3781  /*
3782  * PM_WAIT_READONLY state ends when we have no regular backends that
3783  * have been started during recovery. We kill the startup and
3784  * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3785  * we might like to kill these processes first and then wait for
3786  * backends to die off, but that doesn't work at present because
3787  * killing the startup process doesn't release its locks.
3788  */
3790  {
3791  if (StartupPID != 0)
3792  signal_child(StartupPID, SIGTERM);
3793  if (WalReceiverPID != 0)
3794  signal_child(WalReceiverPID, SIGTERM);
3796  }
3797  }
3798 
3799  /*
3800  * If we are in a state-machine state that implies waiting for backends to
3801  * exit, see if they're all gone, and change state if so.
3802  */
3803  if (pmState == PM_WAIT_BACKENDS)
3804  {
3805  /*
3806  * PM_WAIT_BACKENDS state ends when we have no regular backends
3807  * (including autovac workers), no bgworkers (including unconnected
3808  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3809  * doing crash recovery or an immediate shutdown then we expect the
3810  * checkpointer to exit as well, otherwise not. The archiver, stats,
3811  * and syslogger processes are disregarded since they are not
3812  * connected to shared memory; we also disregard dead_end children
3813  * here. Walsenders are also disregarded, they will be terminated
3814  * later after writing the checkpoint record, like the archiver
3815  * process.
3816  */
3818  StartupPID == 0 &&
3819  WalReceiverPID == 0 &&
3820  BgWriterPID == 0 &&
3821  (CheckpointerPID == 0 ||
3823  WalWriterPID == 0 &&
3824  AutoVacPID == 0)
3825  {
3827  {
3828  /*
3829  * Start waiting for dead_end children to die. This state
3830  * change causes ServerLoop to stop creating new ones.
3831  */
3833 
3834  /*
3835  * We already SIGQUIT'd the archiver and stats processes, if
3836  * any, when we started immediate shutdown or entered
3837  * FatalError state.
3838  */
3839  }
3840  else
3841  {
3842  /*
3843  * If we get here, we are proceeding with normal shutdown. All
3844  * the regular children are gone, and it's time to tell the
3845  * checkpointer to do a shutdown checkpoint.
3846  */
3848  /* Start the checkpointer if not running */
3849  if (CheckpointerPID == 0)
3851  /* And tell it to shut down */
3852  if (CheckpointerPID != 0)
3853  {
3855  pmState = PM_SHUTDOWN;
3856  }
3857  else
3858  {
3859  /*
3860  * If we failed to fork a checkpointer, just shut down.
3861  * Any required cleanup will happen at next restart. We
3862  * set FatalError so that an "abnormal shutdown" message
3863  * gets logged when we exit.
3864  */
3865  FatalError = true;
3867 
3868  /* Kill the walsenders, archiver and stats collector too */
3870  if (PgArchPID != 0)
3872  if (PgStatPID != 0)
3874  }
3875  }
3876  }
3877  }
3878 
3879  if (pmState == PM_SHUTDOWN_2)
3880  {
3881  /*
3882  * PM_SHUTDOWN_2 state ends when there's no other children than
3883  * dead_end children left. There shouldn't be any regular backends
3884  * left by now anyway; what we're really waiting for is walsenders and
3885  * archiver.
3886  */
3887  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3888  {
3890  }
3891  }
3892 
3893  if (pmState == PM_WAIT_DEAD_END)
3894  {
3895  /*
3896  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3897  * (ie, no dead_end children remain), and the archiver and stats
3898  * collector are gone too.
3899  *
3900  * The reason we wait for those two is to protect them against a new
3901  * postmaster starting conflicting subprocesses; this isn't an
3902  * ironclad protection, but it at least helps in the
3903  * shutdown-and-immediately-restart scenario. Note that they have
3904  * already been sent appropriate shutdown signals, either during a
3905  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3906  * FatalError processing.
3907  */
3908  if (dlist_is_empty(&BackendList) &&
3909  PgArchPID == 0 && PgStatPID == 0)
3910  {
3911  /* These other guys should be dead already */
3912  Assert(StartupPID == 0);
3913  Assert(WalReceiverPID == 0);
3914  Assert(BgWriterPID == 0);
3915  Assert(CheckpointerPID == 0);
3916  Assert(WalWriterPID == 0);
3917  Assert(AutoVacPID == 0);
3918  /* syslogger is not considered here */
3920  }
3921  }
3922 
3923  /*
3924  * If we've been told to shut down, we exit as soon as there are no
3925  * remaining children. If there was a crash, cleanup will occur at the
3926  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3927  * crash before exiting, but that seems unwise if we are quitting because
3928  * we got SIGTERM from init --- there may well not be time for recovery
3929  * before init decides to SIGKILL us.)
3930  *
3931  * Note that the syslogger continues to run. It will exit when it sees
3932  * EOF on its input pipe, which happens when there are no more upstream
3933  * processes.
3934  */
3936  {
3937  if (FatalError)
3938  {
3939  ereport(LOG, (errmsg("abnormal database system shutdown")));
3940  ExitPostmaster(1);
3941  }
3942  else
3943  {
3944  /*
3945  * Terminate exclusive backup mode to avoid recovery after a clean
3946  * fast shutdown. Since an exclusive backup can only be taken
3947  * during normal running (and not, for example, while running
3948  * under Hot Standby) it only makes sense to do this if we reached
3949  * normal running. If we're still in recovery, the backup file is
3950  * one we're recovering *from*, and we must keep it around so that
3951  * recovery restarts from the right place.
3952  */
3954  CancelBackup();
3955 
3956  /* Normal exit from the postmaster is here */
3957  ExitPostmaster(0);
3958  }
3959  }
3960 
3961  /*
3962  * If the startup process failed, or the user does not want an automatic
3963  * restart after backend crashes, wait for all non-syslogger children to
3964  * exit, and then exit postmaster. We don't try to reinitialize when the
3965  * startup process fails, because more than likely it will just fail again
3966  * and we will keep trying forever.
3967  */
3968  if (pmState == PM_NO_CHILDREN &&
3970  ExitPostmaster(1);
3971 
3972  /*
3973  * If we need to recover from a crash, wait for all non-syslogger children
3974  * to exit, then reset shmem and StartupDataBase.
3975  */
3976  if (FatalError && pmState == PM_NO_CHILDREN)
3977  {
3978  ereport(LOG,
3979  (errmsg("all server processes terminated; reinitializing")));
3980 
3981  /* allow background workers to immediately restart */
3983 
3984  shmem_exit(1);
3985 
3986  /* re-read control file into local memory */
3988 
3989  reset_shared();
3990 
3992  Assert(StartupPID != 0);
3994  pmState = PM_STARTUP;
3995  /* crash recovery started, reset SIGKILL flag */
3996  AbortStartTime = 0;
3997  }
3998 }
void CancelBackup(void)
Definition: xlog.c:11465
#define SIGQUIT
Definition: win32_port.h:155
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define StartupDataBase()
Definition: postmaster.c:541
static void reset_shared(void)
Definition: postmaster.c:2631
static pid_t PgStatPID
Definition: postmaster.c:257
static pid_t CheckpointerPID
Definition: postmaster.c:252
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool FatalError
Definition: postmaster.c:279
void shmem_exit(int code)
Definition: ipc.c:224
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define SIGUSR2
Definition: win32_port.h:167
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11445
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:515
#define SignalChildren(sig)
Definition: postmaster.c:418
static int Shutdown
Definition: postmaster.c:277
static pid_t BgWriterPID
Definition: postmaster.c:251
#define StartCheckpointer()
Definition: postmaster.c:543
static int CountChildren(int target)
Definition: postmaster.c:5375
static pid_t StartupPID
Definition: postmaster.c:250
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5113
bool restart_after_crash
Definition: postmaster.c:247
static dlist_head BackendList
Definition: postmaster.c:186
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4922
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4018
#define ereport(elevel, rest)
Definition: elog.h:141
static PMState pmState
Definition: postmaster.c:341
#define BACKEND_TYPE_WORKER
Definition: postmaster.c:151
#define ImmediateShutdown
Definition: postmaster.c:275
static pid_t WalWriterPID
Definition: postmaster.c:253
#define Assert(condition)
Definition: c.h:732
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:272
static pid_t AutoVacPID
Definition: postmaster.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:784
static bool ReachedNormalRunning
Definition: postmaster.c:350
static time_t AbortStartTime
Definition: postmaster.c:345
static pid_t PgArchPID
Definition: postmaster.c:256

◆ processCancelRequest()

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

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

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

◆ ProcessStartupPacket()