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/xlog.h"
#include "access/xlogrecovery.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/ip.h"
#include "common/pg_prng.h"
#include "common/string.h"
#include "lib/ilist.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/auxprocess.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/fork_process.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "postmaster/walsummarizer.h"
#include "replication/logicallauncher.h"
#include "replication/slotsync.h"
#include "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/ps_status.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

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

Typedefs

typedef struct bkend Backend
 

Enumerations

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

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 handle_pm_pmsignal_signal (SIGNAL_ARGS)
 
static void handle_pm_child_exit_signal (SIGNAL_ARGS)
 
static void handle_pm_reload_request_signal (SIGNAL_ARGS)
 
static void handle_pm_shutdown_request_signal (SIGNAL_ARGS)
 
static void process_pm_pmsignal (void)
 
static void process_pm_child_exit (void)
 
static void process_pm_reload_request (void)
 
static void process_pm_shutdown_request (void)
 
static void process_startup_packet_die (SIGNAL_ARGS)
 
static void dummy_handler (SIGNAL_ARGS)
 
static void StartupPacketTimeoutHandler (void)
 
static void CleanupBackend (int pid, int exitstatus)
 
static bool CleanupBackgroundWorker (int pid, int exitstatus)
 
static void HandleChildCrash (int pid, int exitstatus, const char *procname)
 
static void LogChildExit (int lev, const char *procname, int pid, int exitstatus)
 
static void PostmasterStateMachine (void)
 
static void BackendInitialize (Port *port)
 
static void BackendRun (Port *port) pg_attribute_noreturn()
 
static void ExitPostmaster (int status) pg_attribute_noreturn()
 
static int ServerLoop (void)
 
static int BackendStartup (Port *port)
 
static int ProcessStartupPacket (Port *port, bool ssl_done, bool gss_done)
 
static void SendNegotiateProtocolVersion (List *unrecognized_protocol_options)
 
static void processCancelRequest (Port *port, void *pkt)
 
static 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 void sigquit_child (pid_t pid)
 
static bool SignalSomeChildren (int signal, int target)
 
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 (BackendType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void MaybeStartWalSummarizer (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
static void MaybeStartSlotSyncWorker (void)
 
void PostmasterMain (int argc, char *argv[])
 
static int DetermineSleepTime (void)
 
static void ConfigurePostmasterWaitSet (bool accept_connections)
 
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 = DEF_PGPORT
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int SuperuserReservedConnections
 
int ReservedConnections
 
static int NumListenSockets = 0
 
static pgsocketListenSockets = NULL
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
bool remove_temp_files_after_crash = true
 
bool send_abort_for_crash = false
 
bool send_abort_for_kill = false
 
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 WalSummarizerPID = 0
 
static pid_t AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t SysLoggerPID = 0
 
static pid_t SlotSyncWorkerPID = 0
 
static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING
 
static int Shutdown = NoShutdown
 
static bool FatalError = false
 
static PMState pmState = PM_INIT
 
static bool connsAllowed = true
 
static time_t AbortStartTime = 0
 
static bool ReachedNormalRunning = false
 
bool ClientAuthInProgress = false
 
bool redirection_done = false
 
static bool start_autovac_launcher = false
 
static bool avlauncher_needs_signal = false
 
static bool WalReceiverRequested = false
 
static bool StartWorkerNeeded = true
 
static bool HaveCrashedWorker = false
 
static volatile sig_atomic_t pending_pm_pmsignal
 
static volatile sig_atomic_t pending_pm_child_exit
 
static volatile sig_atomic_t pending_pm_reload_request
 
static volatile sig_atomic_t pending_pm_shutdown_request
 
static volatile sig_atomic_t pending_pm_fast_shutdown_request
 
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
 
static WaitEventSetpm_wait_set
 
int postmaster_alive_fds [2] = {-1, -1}
 

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

Definition at line 147 of file postmaster.c.

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 144 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 146 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 143 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 145 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 566 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 567 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 568 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 273 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 274 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 227 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 271 of file postmaster.c.

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
bool PgArchCanRestart(void)
Definition: pgarch.c:189
@ PM_RUN
Definition: postmaster.c:327
@ PM_HOT_STANDBY
Definition: postmaster.c:326
@ PM_RECOVERY
Definition: postmaster.c:325
static PMState pmState
Definition: postmaster.c:338
#define XLogArchivingActive()
Definition: xlog.h:97
#define XLogArchivingAlways()
Definition: xlog.h:100

Definition at line 456 of file postmaster.c.

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 353 of file postmaster.c.

◆ SignalChildren

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

Definition at line 437 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 272 of file postmaster.c.

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_STOP_BACKENDS 
PM_WAIT_BACKENDS 
PM_SHUTDOWN 
PM_SHUTDOWN_2 
PM_WAIT_DEAD_END 
PM_NO_CHILDREN 

Definition at line 321 of file postmaster.c.

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 260 of file postmaster.c.

261 {
264  STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
StartupStatusEnum
Definition: postmaster.c:261
@ STARTUP_SIGNALED
Definition: postmaster.c:264
@ STARTUP_CRASHED
Definition: postmaster.c:265
@ STARTUP_NOT_RUNNING
Definition: postmaster.c:262
@ STARTUP_RUNNING
Definition: postmaster.c:263

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5858 of file postmaster.c.

5859 {
5860  Backend *bn;
5861 
5862  /*
5863  * Check that database state allows another connection. Currently the
5864  * only possible failure is CAC_TOOMANY, so we just log an error message
5865  * based on that rather than checking the error code precisely.
5866  */
5868  {
5869  ereport(LOG,
5870  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5871  errmsg("no slot available for new worker process")));
5872  return false;
5873  }
5874 
5875  /*
5876  * Compute the cancel key that will be assigned to this session. We
5877  * probably don't need cancel keys for background workers, but we'd better
5878  * have something random in the field to prevent unfriendly people from
5879  * sending cancels to them.
5880  */
5882  {
5883  ereport(LOG,
5884  (errcode(ERRCODE_INTERNAL_ERROR),
5885  errmsg("could not generate random cancel key")));
5886  return false;
5887  }
5888 
5889  bn = palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM);
5890  if (bn == NULL)
5891  {
5892  ereport(LOG,
5893  (errcode(ERRCODE_OUT_OF_MEMORY),
5894  errmsg("out of memory")));
5895  return false;
5896  }
5897 
5898  bn->cancel_key = MyCancelKey;
5901  bn->dead_end = false;
5902  bn->bgworker_notify = false;
5903 
5904  rw->rw_backend = bn;
5905  rw->rw_child_slot = bn->child_slot;
5906 
5907  return true;
5908 }
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
#define MCXT_ALLOC_NO_OOM
Definition: fe_memutils.h:17
int32 MyCancelKey
Definition: globals.c:49
int MyPMChildSlot
Definition: globals.c:50
@ CAC_OK
Definition: libpq-be.h:63
void * palloc_extended(Size size, int flags)
Definition: mcxt.c:1248
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:247
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2396
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:146
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5255
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:182
int bkend_type
Definition: postmaster.c:180
bool dead_end
Definition: postmaster.c:181
int32 cancel_key
Definition: postmaster.c:178
int child_slot
Definition: postmaster.c:179

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, MCXT_ALLOC_NO_OOM, MyCancelKey, MyPMChildSlot, palloc_extended(), RandomCancelKey(), RegisteredBgWorker::rw_backend, and RegisteredBgWorker::rw_child_slot.

Referenced by do_start_bgworker().

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4235 of file postmaster.c.

4236 {
4237  int status;
4238  int ret;
4239  char remote_host[NI_MAXHOST];
4240  char remote_port[NI_MAXSERV];
4241  StringInfoData ps_data;
4242 
4243  /* Save port etc. for ps status */
4244  MyProcPort = port;
4245 
4246  /* Tell fd.c about the long-lived FD associated with the port */
4248 
4249  /*
4250  * PreAuthDelay is a debugging aid for investigating problems in the
4251  * authentication cycle: it can be set in postgresql.conf to allow time to
4252  * attach to the newly-forked backend with a debugger. (See also
4253  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4254  * is not honored until after authentication.)
4255  */
4256  if (PreAuthDelay > 0)
4257  pg_usleep(PreAuthDelay * 1000000L);
4258 
4259  /* This flag will remain set until InitPostgres finishes authentication */
4260  ClientAuthInProgress = true; /* limit visibility of log messages */
4261 
4262  /* set these to empty in case they are needed before we set them up */
4263  port->remote_host = "";
4264  port->remote_port = "";
4265 
4266  /*
4267  * Initialize libpq and enable reporting of ereport errors to the client.
4268  * Must do this now because authentication uses libpq to send messages.
4269  */
4270  pq_init(); /* initialize libpq to talk to client */
4271  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4272 
4273  /*
4274  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4275  * to collect the startup packet; while SIGQUIT results in _exit(2).
4276  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4277  * cleanly if a buggy client fails to send the packet promptly.
4278  *
4279  * Exiting with _exit(1) is only possible because we have not yet touched
4280  * shared memory; therefore no outside-the-process state needs to get
4281  * cleaned up.
4282  */
4284  /* SIGQUIT handler was already set up by InitPostmasterChild */
4285  InitializeTimeouts(); /* establishes SIGALRM handler */
4286  sigprocmask(SIG_SETMASK, &StartupBlockSig, NULL);
4287 
4288  /*
4289  * Get the remote host name and port for logging and status display.
4290  */
4291  remote_host[0] = '\0';
4292  remote_port[0] = '\0';
4293  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4294  remote_host, sizeof(remote_host),
4295  remote_port, sizeof(remote_port),
4296  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4297  ereport(WARNING,
4298  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4299  gai_strerror(ret))));
4300 
4301  /*
4302  * Save remote_host and remote_port in port structure (after this, they
4303  * will appear in log_line_prefix data for log messages).
4304  */
4305  port->remote_host = strdup(remote_host);
4306  port->remote_port = strdup(remote_port);
4307 
4308  /* And now we can issue the Log_connections message, if wanted */
4309  if (Log_connections)
4310  {
4311  if (remote_port[0])
4312  ereport(LOG,
4313  (errmsg("connection received: host=%s port=%s",
4314  remote_host,
4315  remote_port)));
4316  else
4317  ereport(LOG,
4318  (errmsg("connection received: host=%s",
4319  remote_host)));
4320  }
4321 
4322  /*
4323  * If we did a reverse lookup to name, we might as well save the results
4324  * rather than possibly repeating the lookup during authentication.
4325  *
4326  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4327  * get nothing useful for a client without an rDNS entry. Therefore, we
4328  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4329  * it into remote_hostname if so. (This test is conservative and might
4330  * sometimes classify a hostname as numeric, but an error in that
4331  * direction is safe; it only results in a possible extra lookup.)
4332  */
4333  if (log_hostname &&
4334  ret == 0 &&
4335  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4336  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4337  port->remote_hostname = strdup(remote_host);
4338 
4339  /*
4340  * Ready to begin client interaction. We will give up and _exit(1) after
4341  * a time delay, so that a broken client can't hog a connection
4342  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4343  * against the time limit.
4344  *
4345  * Note: AuthenticationTimeout is applied here while waiting for the
4346  * startup packet, and then again in InitPostgres for the duration of any
4347  * authentication operations. So a hostile client could tie up the
4348  * process for nearly twice AuthenticationTimeout before we kick him off.
4349  *
4350  * Note: because PostgresMain will call InitializeTimeouts again, the
4351  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4352  * since we never use it again after this function.
4353  */
4356 
4357  /*
4358  * Receive the startup packet (which might turn out to be a cancel request
4359  * packet).
4360  */
4361  status = ProcessStartupPacket(port, false, false);
4362 
4363  /*
4364  * If we're going to reject the connection due to database state, say so
4365  * now instead of wasting cycles on an authentication exchange. (This also
4366  * allows a pg_ping utility to be written.)
4367  */
4368  if (status == STATUS_OK)
4369  {
4370  switch (port->canAcceptConnections)
4371  {
4372  case CAC_STARTUP:
4373  ereport(FATAL,
4375  errmsg("the database system is starting up")));
4376  break;
4377  case CAC_NOTCONSISTENT:
4378  if (EnableHotStandby)
4379  ereport(FATAL,
4381  errmsg("the database system is not yet accepting connections"),
4382  errdetail("Consistent recovery state has not been yet reached.")));
4383  else
4384  ereport(FATAL,
4386  errmsg("the database system is not accepting connections"),
4387  errdetail("Hot standby mode is disabled.")));
4388  break;
4389  case CAC_SHUTDOWN:
4390  ereport(FATAL,
4392  errmsg("the database system is shutting down")));
4393  break;
4394  case CAC_RECOVERY:
4395  ereport(FATAL,
4397  errmsg("the database system is in recovery mode")));
4398  break;
4399  case CAC_TOOMANY:
4400  ereport(FATAL,
4401  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
4402  errmsg("sorry, too many clients already")));
4403  break;
4404  case CAC_OK:
4405  break;
4406  }
4407  }
4408 
4409  /*
4410  * Disable the timeout, and prevent SIGTERM again.
4411  */
4413  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
4414 
4415  /*
4416  * As a safety check that nothing in startup has yet performed
4417  * shared-memory modifications that would need to be undone if we had
4418  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4419  * handlers have been registered yet. (This isn't terribly bulletproof,
4420  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4421  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4422  * handlers unfortunately, since pq_init() already registered one.)
4423  */
4425 
4426  /*
4427  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4428  * already did any appropriate error reporting.
4429  */
4430  if (status != STATUS_OK)
4431  proc_exit(0);
4432 
4433  /*
4434  * Now that we have the user and database name, we can set the process
4435  * title for ps. It's good to do this as early as possible in startup.
4436  */
4437  initStringInfo(&ps_data);
4438  if (am_walsender)
4440  appendStringInfo(&ps_data, "%s ", port->user_name);
4441  if (port->database_name[0] != '\0')
4442  appendStringInfo(&ps_data, "%s ", port->database_name);
4443  appendStringInfoString(&ps_data, port->remote_host);
4444  if (port->remote_port[0] != '\0')
4445  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4446 
4447  init_ps_display(ps_data.data);
4448  pfree(ps_data.data);
4449 
4450  set_ps_display("initializing");
4451 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
#define STATUS_OK
Definition: c.h:1156
@ DestRemote
Definition: dest.h:89
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
int errdetail(const char *fmt,...)
Definition: elog.c:1205
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
void ReserveExternalFD(void)
Definition: fd.c:1221
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:91
struct Port * MyProcPort
Definition: globals.c:48
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
void check_on_shmem_exit_lists_are_empty(void)
Definition: ipc.c:432
void proc_exit(int code)
Definition: ipc.c:104
@ CAC_TOOMANY
Definition: libpq-be.h:68
@ CAC_RECOVERY
Definition: libpq-be.h:66
@ CAC_NOTCONSISTENT
Definition: libpq-be.h:67
@ CAC_STARTUP
Definition: libpq-be.h:64
@ CAC_SHUTDOWN
Definition: libpq-be.h:65
void pfree(void *pointer)
Definition: mcxt.c:1401
@ B_WAL_SENDER
Definition: miscadmin.h:339
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:263
static int port
Definition: pg_regress.c:116
pqsigfunc pqsignal(int signo, pqsigfunc func)
CommandDest whereToSendOutput
Definition: postgres.c:89
int PreAuthDelay
Definition: postmaster.c:234
bool log_hostname
Definition: postmaster.c:237
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5221
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5245
bool Log_connections
Definition: postmaster.c:238
bool ClientAuthInProgress
Definition: postmaster.c:357
int AuthenticationTimeout
Definition: postmaster.c:235
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:1944
void pq_init(void)
Definition: pqcomm.c:172
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:240
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
void pg_usleep(long microsec)
Definition: signal.c:53
const char * gai_strerror(int ecode)
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
void InitializeTimeouts(void)
Definition: timeout.c:470
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:505
@ STARTUP_PACKET_TIMEOUT
Definition: timeout.h:26
bool am_walsender
Definition: walsender.c:115
bool EnableHotStandby
Definition: xlog.c:121

References am_walsender, appendStringInfo(), appendStringInfoString(), AuthenticationTimeout, B_WAL_SENDER, BlockSig, CAC_NOTCONSISTENT, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_TOOMANY, check_on_shmem_exit_lists_are_empty(), ClientAuthInProgress, StringInfoData::data, DestRemote, disable_timeout(), enable_timeout_after(), EnableHotStandby, ereport, errcode(), ERRCODE_CANNOT_CONNECT_NOW, errdetail(), errmsg(), errmsg_internal(), FATAL, gai_strerror(), GetBackendTypeDesc(), init_ps_display(), InitializeTimeouts(), initStringInfo(), LOG, Log_connections, log_hostname, MyProcPort, pfree(), pg_getnameinfo_all(), pg_usleep(), port, pq_init(), pqsignal(), PreAuthDelay, proc_exit(), process_startup_packet_die(), ProcessStartupPacket(), RegisterTimeout(), ReserveExternalFD(), set_ps_display(), STARTUP_PACKET_TIMEOUT, StartupBlockSig, StartupPacketTimeoutHandler(), STATUS_OK, WARNING, and whereToSendOutput.

Referenced by BackendStartup().

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4461 of file postmaster.c.

4462 {
4463  /*
4464  * Create a per-backend PGPROC struct in shared memory. We must do this
4465  * before we can use LWLocks or access any shared memory.
4466  */
4467  InitProcess();
4468 
4469  /*
4470  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4471  * just yet, though, because InitPostgres will need the HBA data.)
4472  */
4474 
4475  PostgresMain(port->database_name, port->user_name);
4476 }
MemoryContext TopMemoryContext
Definition: mcxt.c:137
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4144
void InitProcess(void)
Definition: proc.c:296

References InitProcess(), MemoryContextSwitchTo(), port, PostgresMain(), and TopMemoryContext.

Referenced by BackendStartup().

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4086 of file postmaster.c.

4087 {
4088  Backend *bn; /* for backend cleanup */
4089  pid_t pid;
4090 
4091  /*
4092  * Create backend data structure. Better before the fork() so we can
4093  * handle failure cleanly.
4094  */
4095  bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM);
4096  if (!bn)
4097  {
4098  ereport(LOG,
4099  (errcode(ERRCODE_OUT_OF_MEMORY),
4100  errmsg("out of memory")));
4101  return STATUS_ERROR;
4102  }
4103 
4104  /*
4105  * Compute the cancel key that will be assigned to this backend. The
4106  * backend will have its own copy in the forked-off process' value of
4107  * MyCancelKey, so that it can transmit the key to the frontend.
4108  */
4110  {
4111  pfree(bn);
4112  ereport(LOG,
4113  (errcode(ERRCODE_INTERNAL_ERROR),
4114  errmsg("could not generate random cancel key")));
4115  return STATUS_ERROR;
4116  }
4117 
4118  bn->cancel_key = MyCancelKey;
4119 
4120  /* Pass down canAcceptConnections state */
4121  port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL);
4122  bn->dead_end = (port->canAcceptConnections != CAC_OK);
4123 
4124  /*
4125  * Unless it's a dead_end child, assign it a child slot number
4126  */
4127  if (!bn->dead_end)
4129  else
4130  bn->child_slot = 0;
4131 
4132  /* Hasn't asked to be notified about any bgworkers yet */
4133  bn->bgworker_notify = false;
4134 
4135 #ifdef EXEC_BACKEND
4136  pid = backend_forkexec(port);
4137 #else /* !EXEC_BACKEND */
4138  pid = fork_process();
4139  if (pid == 0) /* child */
4140  {
4141  /* Detangle from postmaster */
4143 
4144  /* Close the postmaster's sockets */
4145  ClosePostmasterPorts(false);
4146 
4147  /* Perform additional initialization and collect startup packet */
4149 
4150  /* And run the backend */
4151  BackendRun(port);
4152  }
4153 #endif /* EXEC_BACKEND */
4154 
4155  if (pid < 0)
4156  {
4157  /* in parent, fork failed */
4158  int save_errno = errno;
4159 
4160  if (!bn->dead_end)
4162  pfree(bn);
4163  errno = save_errno;
4164  ereport(LOG,
4165  (errmsg("could not fork new process for connection: %m")));
4166  report_fork_failure_to_client(port, save_errno);
4167  return STATUS_ERROR;
4168  }
4169 
4170  /* in parent, successful fork */
4171  ereport(DEBUG2,
4172  (errmsg_internal("forked new backend, pid=%d socket=%d",
4173  (int) pid, (int) port->sock)));
4174 
4175  /*
4176  * Everything's been successful, it's safe to add this backend to our list
4177  * of backends.
4178  */
4179  bn->pid = pid;
4180  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4182 
4183 #ifdef EXEC_BACKEND
4184  if (!bn->dead_end)
4185  ShmemBackendArrayAdd(bn);
4186 #endif
4187 
4188  return STATUS_OK;
4189 }
#define STATUS_ERROR
Definition: c.h:1157
#define DEBUG2
Definition: elog.h:29
pid_t fork_process(void)
Definition: fork_process.c:32
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
void InitPostmasterChild(void)
Definition: miscinit.c:95
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:284
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:143
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4461
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2500
static void BackendInitialize(Port *port)
Definition: postmaster.c:4235
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4200
static dlist_head BackendList
Definition: postmaster.c:186
dlist_node elem
Definition: postmaster.c:183
pid_t pid
Definition: postmaster.c:177

References AssignPostmasterChildSlot(), BACKEND_TYPE_NORMAL, BackendInitialize(), BackendList, BackendRun(), bkend::bgworker_notify, bkend::bkend_type, CAC_OK, canAcceptConnections(), bkend::cancel_key, bkend::child_slot, ClosePostmasterPorts(), bkend::dead_end, DEBUG2, dlist_push_head(), bkend::elem, ereport, errcode(), errmsg(), errmsg_internal(), fork_process(), InitPostmasterChild(), LOG, MCXT_ALLOC_NO_OOM, MyCancelKey, MyPMChildSlot, palloc_extended(), pfree(), bkend::pid, port, RandomCancelKey(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5685 of file postmaster.c.

5686 {
5687  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
5688 }

References BlockSig.

◆ BackgroundWorkerInitializeConnection()

void BackgroundWorkerInitializeConnection ( const char *  dbname,
const char *  username,
uint32  flags 
)

Definition at line 5617 of file postmaster.c.

5618 {
5620  bits32 init_flags = 0; /* never honor session_preload_libraries */
5621 
5622  /* ignore datallowconn? */
5623  if (flags & BGWORKER_BYPASS_ALLOWCONN)
5624  init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
5625  /* ignore rolcanlogin? */
5626  if (flags & BGWORKER_BYPASS_ROLELOGINCHECK)
5627  init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
5628 
5629  /* XXX is this the right errcode? */
5631  ereport(FATAL,
5632  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5633  errmsg("database connection requirement not indicated during registration")));
5634 
5635  InitPostgres(dbname, InvalidOid, /* database to connect to */
5636  username, InvalidOid, /* role to connect as */
5637  init_flags,
5638  NULL); /* no out_dbname */
5639 
5640  /* it had better not gotten out of "init" mode yet */
5641  if (!IsInitProcessingMode())
5642  ereport(ERROR,
5643  (errmsg("invalid processing mode in background worker")));
5645 }
#define BGWORKER_BYPASS_ROLELOGINCHECK
Definition: bgworker.h:157
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:156
uint32 bits32
Definition: c.h:502
#define ERROR
Definition: elog.h:39
@ NormalProcessing
Definition: miscadmin.h:446
#define IsInitProcessingMode()
Definition: miscadmin.h:452
#define SetProcessingMode(mode)
Definition: miscadmin.h:457
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition: miscadmin.h:475
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition: miscadmin.h:474
const char * username
Definition: pgbench.c:296
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:720
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
char * dbname
Definition: streamutil.c:51

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, dbname, ereport, errcode(), errmsg(), ERROR, FATAL, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitPostgres(), InvalidOid, IsInitProcessingMode, MyBgworkerEntry, NormalProcessing, SetProcessingMode, and username.

Referenced by ApplyLauncherMain(), and worker_spi_main().

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5651 of file postmaster.c.

5652 {
5654  bits32 init_flags = 0; /* never honor session_preload_libraries */
5655 
5656  /* ignore datallowconn? */
5657  if (flags & BGWORKER_BYPASS_ALLOWCONN)
5658  init_flags |= INIT_PG_OVERRIDE_ALLOW_CONNS;
5659  /* ignore rolcanlogin? */
5660  if (flags & BGWORKER_BYPASS_ROLELOGINCHECK)
5661  init_flags |= INIT_PG_OVERRIDE_ROLE_LOGIN;
5662 
5663  /* XXX is this the right errcode? */
5665  ereport(FATAL,
5666  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5667  errmsg("database connection requirement not indicated during registration")));
5668 
5669  InitPostgres(NULL, dboid, /* database to connect to */
5670  NULL, useroid, /* role to connect as */
5671  init_flags,
5672  NULL); /* no out_dbname */
5673 
5674  /* it had better not gotten out of "init" mode yet */
5675  if (!IsInitProcessingMode())
5676  ereport(ERROR,
5677  (errmsg("invalid processing mode in background worker")));
5679 }

References BackgroundWorker::bgw_flags, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_BYPASS_ALLOWCONN, BGWORKER_BYPASS_ROLELOGINCHECK, ereport, errcode(), errmsg(), ERROR, FATAL, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitPostgres(), IsInitProcessingMode, MyBgworkerEntry, NormalProcessing, and SetProcessingMode.

Referenced by autoprewarm_database_main(), InitializeLogRepWorker(), ParallelWorkerMain(), and worker_spi_main().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5691 of file postmaster.c.

5692 {
5693  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5694 }
sigset_t UnBlockSig
Definition: pqsignal.c:22

References UnBlockSig.

Referenced by ApplyLauncherMain(), autoprewarm_database_main(), autoprewarm_main(), BackgroundWorkerMain(), ParallelApplyWorkerMain(), ParallelWorkerMain(), SetupApplyOrSyncWorker(), test_shm_mq_main(), and worker_spi_main().

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5816 of file postmaster.c.

5817 {
5818  switch (pmState)
5819  {
5820  case PM_NO_CHILDREN:
5821  case PM_WAIT_DEAD_END:
5822  case PM_SHUTDOWN_2:
5823  case PM_SHUTDOWN:
5824  case PM_WAIT_BACKENDS:
5825  case PM_STOP_BACKENDS:
5826  break;
5827 
5828  case PM_RUN:
5830  return true;
5831  /* fall through */
5832 
5833  case PM_HOT_STANDBY:
5835  return true;
5836  /* fall through */
5837 
5838  case PM_RECOVERY:
5839  case PM_STARTUP:
5840  case PM_INIT:
5842  return true;
5843  /* fall through */
5844  }
5845 
5846  return false;
5847 }
@ BgWorkerStart_RecoveryFinished
Definition: bgworker.h:81
@ BgWorkerStart_ConsistentState
Definition: bgworker.h:80
@ BgWorkerStart_PostmasterStart
Definition: bgworker.h:79
static time_t start_time
Definition: pg_ctl.c:94

References BgWorkerStart_ConsistentState, BgWorkerStart_PostmasterStart, BgWorkerStart_RecoveryFinished, PM_HOT_STANDBY, PM_INIT, PM_NO_CHILDREN, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, pmState, and start_time.

Referenced by maybe_start_bgworkers().

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( int  backend_type)
static

Definition at line 2396 of file postmaster.c.

2397 {
2398  CAC_state result = CAC_OK;
2399 
2400  /*
2401  * Can't start backends when in startup/shutdown/inconsistent recovery
2402  * state. We treat autovac workers the same as user backends for this
2403  * purpose. However, bgworkers are excluded from this test; we expect
2404  * bgworker_should_start_now() decided whether the DB state allows them.
2405  */
2406  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2407  backend_type != BACKEND_TYPE_BGWORKER)
2408  {
2409  if (Shutdown > NoShutdown)
2410  return CAC_SHUTDOWN; /* shutdown is pending */
2411  else if (!FatalError && pmState == PM_STARTUP)
2412  return CAC_STARTUP; /* normal startup */
2413  else if (!FatalError && pmState == PM_RECOVERY)
2414  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2415  * state */
2416  else
2417  return CAC_RECOVERY; /* else must be crash recovery */
2418  }
2419 
2420  /*
2421  * "Smart shutdown" restrictions are applied only to normal connections,
2422  * not to autovac workers or bgworkers.
2423  */
2424  if (!connsAllowed && backend_type == BACKEND_TYPE_NORMAL)
2425  return CAC_SHUTDOWN; /* shutdown is pending */
2426 
2427  /*
2428  * Don't start too many children.
2429  *
2430  * We allow more connections here than we can have backends because some
2431  * might still be authenticating; they might fail auth, or some existing
2432  * backend might exit before the auth cycle is completed. The exact
2433  * MaxBackends limit is enforced when a new backend tries to join the
2434  * shared-inval backend array.
2435  *
2436  * The limit here must match the sizes of the per-child-process arrays;
2437  * see comments for MaxLivePostmasterChildren().
2438  */
2440  result = CAC_TOOMANY;
2441 
2442  return result;
2443 }
CAC_state
Definition: libpq-be.h:62
static bool connsAllowed
Definition: postmaster.c:346
static int Shutdown
Definition: postmaster.c:276
#define BACKEND_TYPE_ALL
Definition: postmaster.c:147
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5607
#define NoShutdown
Definition: postmaster.c:271
static bool FatalError
Definition: postmaster.c:278
static int CountChildren(int target)
Definition: postmaster.c:5265

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

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

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1580 of file postmaster.c.

1581 {
1582  char path[MAXPGPATH];
1583  FILE *fp;
1584 
1585  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1586 
1587  fp = AllocateFile(path, PG_BINARY_R);
1588  if (fp == NULL)
1589  {
1590  write_stderr("%s: could not find the database system\n"
1591  "Expected to find it in the directory \"%s\",\n"
1592  "but could not open file \"%s\": %s\n",
1593  progname, DataDir, path, strerror(errno));
1594  ExitPostmaster(2);
1595  }
1596  FreeFile(fp);
1597 }
#define write_stderr(str)
Definition: parallel.c:184
#define PG_BINARY_R
Definition: c.h:1262
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2583
int FreeFile(FILE *file)
Definition: fd.c:2781
char * DataDir
Definition: globals.c:67
const char * progname
Definition: main.c:44
#define MAXPGPATH
#define strerror
Definition: port.h:251
#define snprintf
Definition: port.h:238
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5025

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

Referenced by PostmasterMain().

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

Definition at line 3332 of file postmaster.c.

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

References _, BackendList, BackgroundWorkerStopNotifications(), bkend::bgworker_notify, bkend::child_slot, dlist_mutable_iter::cur, bkend::dead_end, DEBUG2, dlist_container, dlist_delete(), dlist_foreach_modify, EXIT_STATUS_0, EXIT_STATUS_1, HandleChildCrash(), LOG, LogChildExit(), pfree(), bkend::pid, and ReleasePostmasterChildSlot().

Referenced by process_pm_child_exit().

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3237 of file postmaster.c.

3239 {
3240  char namebuf[MAXPGPATH];
3241  slist_mutable_iter iter;
3242 
3244  {
3245  RegisteredBgWorker *rw;
3246 
3247  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3248 
3249  if (rw->rw_pid != pid)
3250  continue;
3251 
3252 #ifdef WIN32
3253  /* see CleanupBackend */
3254  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3255  exitstatus = 0;
3256 #endif
3257 
3258  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3259  rw->rw_worker.bgw_type);
3260 
3261 
3262  if (!EXIT_STATUS_0(exitstatus))
3263  {
3264  /* Record timestamp, so we know when to restart the worker. */
3266  }
3267  else
3268  {
3269  /* Zero exit status means terminate */
3270  rw->rw_crashed_at = 0;
3271  rw->rw_terminate = true;
3272  }
3273 
3274  /*
3275  * Additionally, just like a backend, any exit status other than 0 or
3276  * 1 is considered a crash and causes a system-wide restart.
3277  */
3278  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3279  {
3280  HandleChildCrash(pid, exitstatus, namebuf);
3281  return true;
3282  }
3283 
3284  /*
3285  * We must release the postmaster child slot. If the worker failed to
3286  * do so, it did not clean up after itself, requiring a crash-restart
3287  * cycle.
3288  */
3290  {
3291  HandleChildCrash(pid, exitstatus, namebuf);
3292  return true;
3293  }
3294 
3295  /* Get it out of the BackendList and clear out remaining data */
3296  dlist_delete(&rw->rw_backend->elem);
3297 #ifdef EXEC_BACKEND
3298  ShmemBackendArrayRemove(rw->rw_backend);
3299 #endif
3300 
3301  /*
3302  * It's possible that this background worker started some OTHER
3303  * background worker and asked to be notified when that worker started
3304  * or stopped. If so, cancel any notifications destined for the
3305  * now-dead backend.
3306  */
3307  if (rw->rw_backend->bgworker_notify)
3309  pfree(rw->rw_backend);
3310  rw->rw_backend = NULL;
3311  rw->rw_pid = 0;
3312  rw->rw_child_slot = 0;
3313  ReportBackgroundWorkerExit(&iter); /* report child death */
3314 
3315  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3316  namebuf, pid, exitstatus);
3317 
3318  return true;
3319  }
3320 
3321  return false;
3322 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
slist_head BackgroundWorkerList
Definition: bgworker.c:40
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:486
#define DEBUG1
Definition: elog.h:30
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:1148
#define slist_container(type, membername, ptr)
Definition: ilist.h:1106
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BackgroundWorker rw_worker
slist_node * cur
Definition: ilist.h:274

References _, BackgroundWorkerList, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_type, bkend::bgworker_notify, slist_mutable_iter::cur, DEBUG1, dlist_delete(), bkend::elem, EXIT_STATUS_0, EXIT_STATUS_1, GetCurrentTimestamp(), HandleChildCrash(), LOG, LogChildExit(), MAXPGPATH, pfree(), 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 process_pm_child_exit().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2500 of file postmaster.c.

2501 {
2502  /* Release resources held by the postmaster's WaitEventSet. */
2503  if (pm_wait_set)
2504  {
2506  pm_wait_set = NULL;
2507  }
2508 
2509 #ifndef WIN32
2510 
2511  /*
2512  * Close the write end of postmaster death watch pipe. It's important to
2513  * do this as early as possible, so that if postmaster dies, others won't
2514  * think that it's still running because we're holding the pipe open.
2515  */
2517  ereport(FATAL,
2519  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2521  /* Notify fd.c that we released one pipe FD. */
2523 #endif
2524 
2525  /*
2526  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2527  * so we don't call ReleaseExternalFD() here.
2528  *
2529  * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
2530  * EXEC_BACKEND mode.
2531  */
2532 #ifndef EXEC_BACKEND
2533  if (ListenSockets)
2534  {
2535  for (int i = 0; i < NumListenSockets; i++)
2538  }
2539  NumListenSockets = 0;
2540  ListenSockets = NULL;
2541 #endif
2542 
2543  /*
2544  * If using syslogger, close the read side of the pipe. We don't bother
2545  * tracking this in fd.c, either.
2546  */
2547  if (!am_syslogger)
2548  {
2549 #ifndef WIN32
2550  if (syslogPipe[0] >= 0)
2551  close(syslogPipe[0]);
2552  syslogPipe[0] = -1;
2553 #else
2554  if (syslogPipe[0])
2555  CloseHandle(syslogPipe[0]);
2556  syslogPipe[0] = 0;
2557 #endif
2558  }
2559 
2560 #ifdef USE_BONJOUR
2561  /* If using Bonjour, close the connection to the mDNS daemon */
2562  if (bonjour_sdref)
2563  close(DNSServiceRefSockFD(bonjour_sdref));
2564 #endif
2565 }
int errcode_for_file_access(void)
Definition: elog.c:882
void ReleaseExternalFD(void)
Definition: fd.c:1239
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
void FreeWaitEventSetAfterFork(WaitEventSet *set)
Definition: latch.c:917
static pgsocket * ListenSockets
Definition: postmaster.c:229
static int NumListenSockets
Definition: postmaster.c:228
int postmaster_alive_fds[2]
Definition: postmaster.c:575
static WaitEventSet * pm_wait_set
Definition: postmaster.c:384
#define POSTMASTER_FD_OWN
Definition: postmaster.h:47
void StreamClose(pgsocket sock)
Definition: pqcomm.c:831
int syslogPipe[2]
Definition: syslogger.c:116

References close, ereport, errcode_for_file_access(), errmsg_internal(), FATAL, FreeWaitEventSetAfterFork(), i, ListenSockets, NumListenSockets, pfree(), pm_wait_set, postmaster_alive_fds, POSTMASTER_FD_OWN, ReleaseExternalFD(), StreamClose(), and syslogPipe.

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

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1483 of file postmaster.c.

1484 {
1485  int i;
1486 
1487  /*
1488  * First, explicitly close all the socket FDs. We used to just let this
1489  * happen implicitly at postmaster exit, but it's better to close them
1490  * before we remove the postmaster.pid lockfile; otherwise there's a race
1491  * condition if a new postmaster wants to re-use the TCP port number.
1492  */
1493  for (i = 0; i < NumListenSockets; i++)
1495  NumListenSockets = 0;
1496 
1497  /*
1498  * Next, remove any filesystem entries for Unix sockets. To avoid race
1499  * conditions against incoming postmasters, this must happen after closing
1500  * the sockets and before removing lock files.
1501  */
1503 
1504  /*
1505  * We don't do anything about socket lock files here; those will be
1506  * removed in a later on_proc_exit callback.
1507  */
1508 }
void RemoveSocketFiles(void)
Definition: pqcomm.c:865

References i, ListenSockets, NumListenSockets, RemoveSocketFiles(), and StreamClose().

Referenced by PostmasterMain().

◆ ConfigurePostmasterWaitSet()

static void ConfigurePostmasterWaitSet ( bool  accept_connections)
static

Definition at line 1694 of file postmaster.c.

1695 {
1696  if (pm_wait_set)
1698  pm_wait_set = NULL;
1699 
1701  accept_connections ? (1 + NumListenSockets) : 1);
1703  NULL);
1704 
1705  if (accept_connections)
1706  {
1707  for (int i = 0; i < NumListenSockets; i++)
1709  NULL, NULL);
1710  }
1711 }
struct Latch * MyLatch
Definition: globals.c:59
WaitEventSet * CreateWaitEventSet(ResourceOwner resowner, int nevents)
Definition: latch.c:751
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:963
void FreeWaitEventSet(WaitEventSet *set)
Definition: latch.c:874
#define WL_SOCKET_ACCEPT
Definition: latch.h:144
#define WL_LATCH_SET
Definition: latch.h:127
#define PGINVALID_SOCKET
Definition: port.h:31

References AddWaitEventToSet(), CreateWaitEventSet(), FreeWaitEventSet(), i, ListenSockets, MyLatch, NumListenSockets, PGINVALID_SOCKET, pm_wait_set, WL_LATCH_SET, and WL_SOCKET_ACCEPT.

Referenced by PostmasterStateMachine(), and ServerLoop().

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2452 of file postmaster.c.

2453 {
2454  Port *port;
2455 
2456  if (!(port = (Port *) calloc(1, sizeof(Port))))
2457  {
2458  ereport(LOG,
2459  (errcode(ERRCODE_OUT_OF_MEMORY),
2460  errmsg("out of memory")));
2461  ExitPostmaster(1);
2462  }
2463 
2464  if (StreamConnection(serverFd, port) != STATUS_OK)
2465  {
2466  if (port->sock != PGINVALID_SOCKET)
2467  StreamClose(port->sock);
2468  ConnFree(port);
2469  return NULL;
2470  }
2471 
2472  return port;
2473 }
#define calloc(a, b)
Definition: header.h:55
static void ConnFree(Port *port)
Definition: postmaster.c:2483
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:697
Definition: libpq-be.h:147

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

Referenced by ServerLoop().

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2483 of file postmaster.c.

2484 {
2485  free(port);
2486 }
#define free(a)
Definition: header.h:65

References free, and port.

Referenced by ConnCreate(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5265 of file postmaster.c.

5266 {
5267  dlist_iter iter;
5268  int cnt = 0;
5269 
5270  dlist_foreach(iter, &BackendList)
5271  {
5272  Backend *bp = dlist_container(Backend, elem, iter.cur);
5273 
5274  if (bp->dead_end)
5275  continue;
5276 
5277  /*
5278  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5279  * it first and avoid touching shared memory for every child.
5280  */
5281  if (target != BACKEND_TYPE_ALL)
5282  {
5283  /*
5284  * Assign bkend_type for any recently announced WAL Sender
5285  * processes.
5286  */
5287  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5290 
5291  if (!(target & bp->bkend_type))
5292  continue;
5293  }
5294 
5295  cnt++;
5296  }
5297  return cnt;
5298 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:307
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:145
dlist_node * cur
Definition: ilist.h:179

References BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, bkend::bkend_type, bkend::child_slot, dlist_iter::cur, bkend::dead_end, dlist_container, dlist_foreach, and IsPostmasterChildWalSender().

Referenced by canAcceptConnections(), and PostmasterStateMachine().

◆ CreateOptsFile()

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

Definition at line 5563 of file postmaster.c.

5564 {
5565  FILE *fp;
5566  int i;
5567 
5568 #define OPTS_FILE "postmaster.opts"
5569 
5570  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5571  {
5572  ereport(LOG,
5574  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5575  return false;
5576  }
5577 
5578  fprintf(fp, "%s", fullprogname);
5579  for (i = 1; i < argc; i++)
5580  fprintf(fp, " \"%s\"", argv[i]);
5581  fputs("\n", fp);
5582 
5583  if (fclose(fp))
5584  {
5585  ereport(LOG,
5587  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5588  return false;
5589  }
5590 
5591  return true;
5592 }
#define fprintf
Definition: port.h:242
#define OPTS_FILE

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

Referenced by PostmasterMain().

◆ DetermineSleepTime()

static int DetermineSleepTime ( void  )
static

Definition at line 1609 of file postmaster.c.

1610 {
1611  TimestampTz next_wakeup = 0;
1612 
1613  /*
1614  * Normal case: either there are no background workers at all, or we're in
1615  * a shutdown sequence (during which we ignore bgworkers altogether).
1616  */
1617  if (Shutdown > NoShutdown ||
1619  {
1620  if (AbortStartTime != 0)
1621  {
1622  int seconds;
1623 
1624  /* time left to abort; clamp to 0 in case it already expired */
1625  seconds = SIGKILL_CHILDREN_AFTER_SECS -
1626  (time(NULL) - AbortStartTime);
1627 
1628  return Max(seconds * 1000, 0);
1629  }
1630  else
1631  return 60 * 1000;
1632  }
1633 
1634  if (StartWorkerNeeded)
1635  return 0;
1636 
1637  if (HaveCrashedWorker)
1638  {
1639  slist_mutable_iter siter;
1640 
1641  /*
1642  * When there are crashed bgworkers, we sleep just long enough that
1643  * they are restarted when they request to be. Scan the list to
1644  * determine the minimum of all wakeup times according to most recent
1645  * crash time and requested restart interval.
1646  */
1648  {
1649  RegisteredBgWorker *rw;
1650  TimestampTz this_wakeup;
1651 
1652  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1653 
1654  if (rw->rw_crashed_at == 0)
1655  continue;
1656 
1658  || rw->rw_terminate)
1659  {
1660  ForgetBackgroundWorker(&siter);
1661  continue;
1662  }
1663 
1664  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1665  1000L * rw->rw_worker.bgw_restart_time);
1666  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1667  next_wakeup = this_wakeup;
1668  }
1669  }
1670 
1671  if (next_wakeup != 0)
1672  {
1673  int ms;
1674 
1675  /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
1677  next_wakeup);
1678  return Min(60 * 1000, ms);
1679  }
1680 
1681  return 60 * 1000;
1682 }
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1766
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:432
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Min(x, y)
Definition: c.h:991
#define Max(x, y)
Definition: c.h:985
int64 TimestampTz
Definition: timestamp.h:39
static bool HaveCrashedWorker
Definition: postmaster.c:373
static time_t AbortStartTime
Definition: postmaster.c:350
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:353
static bool StartWorkerNeeded
Definition: postmaster.c:372
int bgw_restart_time
Definition: bgworker.h:95
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85

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

Referenced by ServerLoop().

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5724 of file postmaster.c.

5725 {
5726  pid_t worker_pid;
5727 
5728  Assert(rw->rw_pid == 0);
5729 
5730  /*
5731  * Allocate and assign the Backend element. Note we must do this before
5732  * forking, so that we can handle failures (out of memory or child-process
5733  * slots) cleanly.
5734  *
5735  * Treat failure as though the worker had crashed. That way, the
5736  * postmaster will wait a bit before attempting to start it again; if we
5737  * tried again right away, most likely we'd find ourselves hitting the
5738  * same resource-exhaustion condition.
5739  */
5740  if (!assign_backendlist_entry(rw))
5741  {
5743  return false;
5744  }
5745 
5746  ereport(DEBUG1,
5747  (errmsg_internal("starting background worker process \"%s\"",
5748  rw->rw_worker.bgw_name)));
5749 
5750 #ifdef EXEC_BACKEND
5751  switch ((worker_pid = bgworker_forkexec(&rw->rw_worker)))
5752 #else
5753  switch ((worker_pid = fork_process()))
5754 #endif
5755  {
5756  case -1:
5757  /* in postmaster, fork failed ... */
5758  ereport(LOG,
5759  (errmsg("could not fork worker process: %m")));
5760  /* undo what assign_backendlist_entry did */
5762  rw->rw_child_slot = 0;
5763  pfree(rw->rw_backend);
5764  rw->rw_backend = NULL;
5765  /* mark entry as crashed, so we'll try again later */
5767  break;
5768 
5769 #ifndef EXEC_BACKEND
5770  case 0:
5771  /* in postmaster child ... */
5773 
5774  /* Close the postmaster's sockets */
5775  ClosePostmasterPorts(false);
5776 
5777  /*
5778  * Before blowing away PostmasterContext, save this bgworker's
5779  * data where it can find it.
5780  */
5783  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5784 
5785  /* Release postmaster's working memory context */
5788  PostmasterContext = NULL;
5789 
5791 
5792  exit(1); /* should not get here */
5793  break;
5794 #endif
5795  default:
5796  /* in postmaster, fork successful ... */
5797  rw->rw_pid = worker_pid;
5798  rw->rw_backend->pid = rw->rw_pid;
5800  /* add new worker to lists of backends */
5802 #ifdef EXEC_BACKEND
5803  ShmemBackendArrayAdd(rw->rw_backend);
5804 #endif
5805  return true;
5806  }
5807 
5808  return false;
5809 }
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:467
void BackgroundWorkerMain(void)
Definition: bgworker.c:723
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1062
MemoryContext PostmasterContext
Definition: mcxt.c:139
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:399
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5858
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91

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

Referenced by maybe_start_bgworkers().

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5236 of file postmaster.c.

5237 {
5238 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5025 of file postmaster.c.

5026 {
5027 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5028 
5029  /*
5030  * There is no known cause for a postmaster to become multithreaded after
5031  * startup. Recheck to account for the possibility of unknown causes.
5032  * This message uses LOG level, because an unclean shutdown at this point
5033  * would usually not look much different from a clean shutdown.
5034  */
5035  if (pthread_is_threaded_np() != 0)
5036  ereport(LOG,
5037  (errcode(ERRCODE_INTERNAL_ERROR),
5038  errmsg_internal("postmaster became multithreaded"),
5039  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5040 #endif
5041 
5042  /* should cleanup shared memory and kill all backends */
5043 
5044  /*
5045  * Not sure of the semantics here. When the Postmaster dies, should the
5046  * backends all be killed? probably not.
5047  *
5048  * MUST -- vadim 05-10-1999
5049  */
5050 
5051  proc_exit(status);
5052 }

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

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

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1526 of file postmaster.c.

1527 {
1528  DIR *pdir;
1529 
1530  /* Locate the postgres executable itself */
1531  if (find_my_exec(argv0, my_exec_path) < 0)
1532  ereport(FATAL,
1533  (errmsg("%s: could not locate my own executable path", argv0)));
1534 
1535 #ifdef EXEC_BACKEND
1536  /* Locate executable backend before we change working directory */
1537  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1538  postgres_exec_path) < 0)
1539  ereport(FATAL,
1540  (errmsg("%s: could not locate matching postgres executable",
1541  argv0)));
1542 #endif
1543 
1544  /*
1545  * Locate the pkglib directory --- this has to be set early in case we try
1546  * to load any modules from it in response to postgresql.conf entries.
1547  */
1549 
1550  /*
1551  * Verify that there's a readable directory there; otherwise the Postgres
1552  * installation is incomplete or corrupt. (A typical cause of this
1553  * failure is that the postgres executable has been moved or hardlinked to
1554  * some directory that's not a sibling of the installation lib/
1555  * directory.)
1556  */
1557  pdir = AllocateDir(pkglib_path);
1558  if (pdir == NULL)
1559  ereport(ERROR,
1561  errmsg("could not open directory \"%s\": %m",
1562  pkglib_path),
1563  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1564  my_exec_path)));
1565  FreeDir(pdir);
1566 
1567  /*
1568  * It's not worth checking the share/ directory. If the lib/ directory is
1569  * there, then share/ probably is too.
1570  */
1571 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:329
int errhint(const char *fmt,...)
Definition: elog.c:1319
int FreeDir(DIR *dir)
Definition: fd.c:2961
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2843
char pkglib_path[MAXPGPATH]
Definition: globals.c:78
char my_exec_path[MAXPGPATH]
Definition: globals.c:77
static char * argv0
Definition: pg_ctl.c:92
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879
#define PG_BACKEND_VERSIONSTR
Definition: port.h:143
Definition: dirent.c:26

References AllocateDir(), argv0, 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().

◆ handle_pm_child_exit_signal()

static void handle_pm_child_exit_signal ( SIGNAL_ARGS  )
static

Definition at line 2885 of file postmaster.c.

2886 {
2887  pending_pm_child_exit = true;
2888  SetLatch(MyLatch);
2889 }
void SetLatch(Latch *latch)
Definition: latch.c:632
static volatile sig_atomic_t pending_pm_child_exit
Definition: postmaster.c:377

References MyLatch, pending_pm_child_exit, and SetLatch().

Referenced by PostmasterMain().

◆ handle_pm_pmsignal_signal()

static void handle_pm_pmsignal_signal ( SIGNAL_ARGS  )
static

Definition at line 2617 of file postmaster.c.

2618 {
2619  pending_pm_pmsignal = true;
2620  SetLatch(MyLatch);
2621 }
static volatile sig_atomic_t pending_pm_pmsignal
Definition: postmaster.c:376

References MyLatch, pending_pm_pmsignal, and SetLatch().

Referenced by PostmasterMain().

◆ handle_pm_reload_request_signal()

static void handle_pm_reload_request_signal ( SIGNAL_ARGS  )
static

Definition at line 2627 of file postmaster.c.

2628 {
2630  SetLatch(MyLatch);
2631 }
static volatile sig_atomic_t pending_pm_reload_request
Definition: postmaster.c:378

References MyLatch, pending_pm_reload_request, and SetLatch().

Referenced by PostmasterMain().

◆ handle_pm_shutdown_request_signal()

static void handle_pm_shutdown_request_signal ( SIGNAL_ARGS  )
static

Definition at line 2710 of file postmaster.c.

2711 {
2712  switch (postgres_signal_arg)
2713  {
2714  case SIGTERM:
2715  /* smart is implied if the other two flags aren't set */
2717  break;
2718  case SIGINT:
2721  break;
2722  case SIGQUIT:
2725  break;
2726  }
2727  SetLatch(MyLatch);
2728 }
static volatile sig_atomic_t pending_pm_fast_shutdown_request
Definition: postmaster.c:380
static volatile sig_atomic_t pending_pm_shutdown_request
Definition: postmaster.c:379
static volatile sig_atomic_t pending_pm_immediate_shutdown_request
Definition: postmaster.c:381
#define SIGQUIT
Definition: win32_port.h:169

References MyLatch, pending_pm_fast_shutdown_request, pending_pm_immediate_shutdown_request, pending_pm_shutdown_request, SetLatch(), and SIGQUIT.

Referenced by PostmasterMain().

◆ HandleChildCrash()

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

Definition at line 3416 of file postmaster.c.

3417 {
3418  dlist_mutable_iter iter;
3419  slist_iter siter;
3420  Backend *bp;
3421  bool take_action;
3422 
3423  /*
3424  * We only log messages and send signals if this is the first process
3425  * crash and we're not doing an immediate shutdown; otherwise, we're only
3426  * here to update postmaster's idea of live processes. If we have already
3427  * signaled children, nonzero exit status is to be expected, so don't
3428  * clutter log.
3429  */
3430  take_action = !FatalError && Shutdown != ImmediateShutdown;
3431 
3432  if (take_action)
3433  {
3434  LogChildExit(LOG, procname, pid, exitstatus);
3435  ereport(LOG,
3436  (errmsg("terminating any other active server processes")));
3438  }
3439 
3440  /* Process background workers. */
3442  {
3443  RegisteredBgWorker *rw;
3444 
3445  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3446  if (rw->rw_pid == 0)
3447  continue; /* not running */
3448  if (rw->rw_pid == pid)
3449  {
3450  /*
3451  * Found entry for freshly-dead worker, so remove it.
3452  */
3454  dlist_delete(&rw->rw_backend->elem);
3455 #ifdef EXEC_BACKEND
3456  ShmemBackendArrayRemove(rw->rw_backend);
3457 #endif
3458  pfree(rw->rw_backend);
3459  rw->rw_backend = NULL;
3460  rw->rw_pid = 0;
3461  rw->rw_child_slot = 0;
3462  /* don't reset crashed_at */
3463  /* don't report child stop, either */
3464  /* Keep looping so we can signal remaining workers */
3465  }
3466  else
3467  {
3468  /*
3469  * This worker is still alive. Unless we did so already, tell it
3470  * to commit hara-kiri.
3471  */
3472  if (take_action)
3473  sigquit_child(rw->rw_pid);
3474  }
3475  }
3476 
3477  /* Process regular backends */
3479  {
3480  bp = dlist_container(Backend, elem, iter.cur);
3481 
3482  if (bp->pid == pid)
3483  {
3484  /*
3485  * Found entry for freshly-dead backend, so remove it.
3486  */
3487  if (!bp->dead_end)
3488  {
3490 #ifdef EXEC_BACKEND
3491  ShmemBackendArrayRemove(bp);
3492 #endif
3493  }
3494  dlist_delete(iter.cur);
3495  pfree(bp);
3496  /* Keep looping so we can signal remaining backends */
3497  }
3498  else
3499  {
3500  /*
3501  * This backend is still alive. Unless we did so already, tell it
3502  * to commit hara-kiri.
3503  *
3504  * We could exclude dead_end children here, but at least when
3505  * sending SIGABRT it seems better to include them.
3506  *
3507  * Background workers were already processed above; ignore them
3508  * here.
3509  */
3510  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3511  continue;
3512 
3513  if (take_action)
3514  sigquit_child(bp->pid);
3515  }
3516  }
3517 
3518  /* Take care of the startup process too */
3519  if (pid == StartupPID)
3520  {
3521  StartupPID = 0;
3522  /* Caller adjusts StartupStatus, so don't touch it here */
3523  }
3524  else if (StartupPID != 0 && take_action)
3525  {
3528  }
3529 
3530  /* Take care of the bgwriter too */
3531  if (pid == BgWriterPID)
3532  BgWriterPID = 0;
3533  else if (BgWriterPID != 0 && take_action)
3535 
3536  /* Take care of the checkpointer too */
3537  if (pid == CheckpointerPID)
3538  CheckpointerPID = 0;
3539  else if (CheckpointerPID != 0 && take_action)
3541 
3542  /* Take care of the walwriter too */
3543  if (pid == WalWriterPID)
3544  WalWriterPID = 0;
3545  else if (WalWriterPID != 0 && take_action)
3547 
3548  /* Take care of the walreceiver too */
3549  if (pid == WalReceiverPID)
3550  WalReceiverPID = 0;
3551  else if (WalReceiverPID != 0 && take_action)
3553 
3554  /* Take care of the walsummarizer too */
3555  if (pid == WalSummarizerPID)
3556  WalSummarizerPID = 0;
3557  else if (WalSummarizerPID != 0 && take_action)
3559 
3560  /* Take care of the autovacuum launcher too */
3561  if (pid == AutoVacPID)
3562  AutoVacPID = 0;
3563  else if (AutoVacPID != 0 && take_action)
3565 
3566  /* Take care of the archiver too */
3567  if (pid == PgArchPID)
3568  PgArchPID = 0;
3569  else if (PgArchPID != 0 && take_action)
3571 
3572  /* Take care of the slot sync worker too */
3573  if (pid == SlotSyncWorkerPID)
3574  SlotSyncWorkerPID = 0;
3575  else if (SlotSyncWorkerPID != 0 && take_action)
3577 
3578  /* We do NOT restart the syslogger */
3579 
3580  if (Shutdown != ImmediateShutdown)
3581  FatalError = true;
3582 
3583  /* We now transit into a state of waiting for children to die */
3584  if (pmState == PM_RECOVERY ||
3585  pmState == PM_HOT_STANDBY ||
3586  pmState == PM_RUN ||
3588  pmState == PM_SHUTDOWN)
3590 
3591  /*
3592  * .. and if this doesn't happen quickly enough, now the clock is ticking
3593  * for us to kill them without mercy.
3594  */
3595  if (AbortStartTime == 0)
3596  AbortStartTime = time(NULL);
3597 }
#define slist_foreach(iter, lhead)
Definition: ilist.h:1132
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:218
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
static pid_t WalReceiverPID
Definition: postmaster.c:252
static pid_t PgArchPID
Definition: postmaster.c:255
#define ImmediateShutdown
Definition: postmaster.c:274
static pid_t AutoVacPID
Definition: postmaster.c:254
static pid_t SlotSyncWorkerPID
Definition: postmaster.c:257
static pid_t CheckpointerPID
Definition: postmaster.c:250
static pid_t BgWriterPID
Definition: postmaster.c:249
static pid_t WalWriterPID
Definition: postmaster.c:251
static StartupStatusEnum StartupStatus
Definition: postmaster.c:268
static pid_t WalSummarizerPID
Definition: postmaster.c:253
static void sigquit_child(pid_t pid)
Definition: postmaster.c:3993
static pid_t StartupPID
Definition: postmaster.c:248
slist_node * cur
Definition: ilist.h:259

References AbortStartTime, AutoVacPID, BACKEND_TYPE_BGWORKER, BackendList, BackgroundWorkerList, BgWriterPID, bkend::bkend_type, CheckpointerPID, bkend::child_slot, dlist_mutable_iter::cur, slist_iter::cur, bkend::dead_end, dlist_container, dlist_delete(), dlist_foreach_modify, bkend::elem, ereport, errmsg(), FatalError, ImmediateShutdown, LOG, LogChildExit(), pfree(), PgArchPID, bkend::pid, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_SHUTDOWN, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_CRASH, pmState, ReleasePostmasterChildSlot(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_pid, SetQuitSignalReason(), Shutdown, sigquit_child(), slist_container, slist_foreach, SlotSyncWorkerPID, STARTUP_SIGNALED, StartupPID, StartupStatus, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6556 of file postmaster.c.

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

References Assert(), ereport, errcode_for_file_access(), errcode_for_socket_access(), errmsg_internal(), FATAL, MyProcPid, postmaster_alive_fds, POSTMASTER_FD_WATCH, PostmasterPid, and ReserveExternalFD().

Referenced by PostmasterMain().

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2574 of file postmaster.c.

2575 {
2576  MyProcPid = getpid();
2579 
2580  /*
2581  * Set a different global seed in every process. We want something
2582  * unpredictable, so if possible, use high-quality random bits for the
2583  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2584  */
2586  {
2587  uint64 rseed;
2588 
2589  /*
2590  * Since PIDs and timestamps tend to change more frequently in their
2591  * least significant bits, shift the timestamp left to allow a larger
2592  * total number of seeds in a given time period. Since that would
2593  * leave only 20 bits of the timestamp that cycle every ~1 second,
2594  * also mix in some higher bits.
2595  */
2596  rseed = ((uint64) MyProcPid) ^
2597  ((uint64) MyStartTimestamp << 12) ^
2598  ((uint64) MyStartTimestamp >> 20);
2599 
2601  }
2602 
2603  /*
2604  * Also make sure that we've set a good seed for random(3). Use of that
2605  * is deprecated in core Postgres, but extensions might use it.
2606  */
2607 #ifndef WIN32
2609 #endif
2610 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1833
#define unlikely(x)
Definition: c.h:298
TimestampTz MyStartTimestamp
Definition: globals.c:47
pg_time_t MyStartTime
Definition: globals.c:46
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:191
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:89
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define pg_prng_strong_seed(state)
Definition: pg_prng.h:46

References GetCurrentTimestamp(), MyProcPid, MyStartTime, MyStartTimestamp, pg_global_prng_state, pg_prng_seed(), pg_prng_strong_seed, pg_prng_uint32(), timestamptz_to_time_t(), and unlikely.

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

◆ LogChildExit()

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

Definition at line 3603 of file postmaster.c.

3604 {
3605  /*
3606  * size of activity_buffer is arbitrary, but set equal to default
3607  * track_activity_query_size
3608  */
3609  char activity_buffer[1024];
3610  const char *activity = NULL;
3611 
3612  if (!EXIT_STATUS_0(exitstatus))
3613  activity = pgstat_get_crashed_backend_activity(pid,
3614  activity_buffer,
3615  sizeof(activity_buffer));
3616 
3617  if (WIFEXITED(exitstatus))
3618  ereport(lev,
3619 
3620  /*------
3621  translator: %s is a noun phrase describing a child process, such as
3622  "server process" */
3623  (errmsg("%s (PID %d) exited with exit code %d",
3624  procname, pid, WEXITSTATUS(exitstatus)),
3625  activity ? errdetail("Failed process was running: %s", activity) : 0));
3626  else if (WIFSIGNALED(exitstatus))
3627  {
3628 #if defined(WIN32)
3629  ereport(lev,
3630 
3631  /*------
3632  translator: %s is a noun phrase describing a child process, such as
3633  "server process" */
3634  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3635  procname, pid, WTERMSIG(exitstatus)),
3636  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3637  activity ? errdetail("Failed process was running: %s", activity) : 0));
3638 #else
3639  ereport(lev,
3640 
3641  /*------
3642  translator: %s is a noun phrase describing a child process, such as
3643  "server process" */
3644  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3645  procname, pid, WTERMSIG(exitstatus),
3646  pg_strsignal(WTERMSIG(exitstatus))),
3647  activity ? errdetail("Failed process was running: %s", activity) : 0));
3648 #endif
3649  }
3650  else
3651  ereport(lev,
3652 
3653  /*------
3654  translator: %s is a noun phrase describing a child process, such as
3655  "server process" */
3656  (errmsg("%s (PID %d) exited with unrecognized status %d",
3657  procname, pid, exitstatus),
3658  activity ? errdetail("Failed process was running: %s", activity) : 0));
3659 }
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:39
#define WIFEXITED(w)
Definition: win32_port.h:152
#define WIFSIGNALED(w)
Definition: win32_port.h:153
#define WTERMSIG(w)
Definition: win32_port.h:155
#define WEXITSTATUS(w)
Definition: win32_port.h:154

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 process_pm_child_exit().

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5607 of file postmaster.c.

5608 {
5609  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5611 }
int autovacuum_max_workers
Definition: autovacuum.c:117
int MaxConnections
Definition: globals.c:139
int max_worker_processes
Definition: globals.c:140
int max_wal_senders
Definition: walsender.c:121

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 5922 of file postmaster.c.

5923 {
5924 #define MAX_BGWORKERS_TO_LAUNCH 100
5925  int num_launched = 0;
5926  TimestampTz now = 0;
5927  slist_mutable_iter iter;
5928 
5929  /*
5930  * During crash recovery, we have no need to be called until the state
5931  * transition out of recovery.
5932  */
5933  if (FatalError)
5934  {
5935  StartWorkerNeeded = false;
5936  HaveCrashedWorker = false;
5937  return;
5938  }
5939 
5940  /* Don't need to be called again unless we find a reason for it below */
5941  StartWorkerNeeded = false;
5942  HaveCrashedWorker = false;
5943 
5945  {
5946  RegisteredBgWorker *rw;
5947 
5948  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5949 
5950  /* ignore if already running */
5951  if (rw->rw_pid != 0)
5952  continue;
5953 
5954  /* if marked for death, clean up and remove from list */
5955  if (rw->rw_terminate)
5956  {
5957  ForgetBackgroundWorker(&iter);
5958  continue;
5959  }
5960 
5961  /*
5962  * If this worker has crashed previously, maybe it needs to be
5963  * restarted (unless on registration it specified it doesn't want to
5964  * be restarted at all). Check how long ago did a crash last happen.
5965  * If the last crash is too recent, don't start it right away; let it
5966  * be restarted once enough time has passed.
5967  */
5968  if (rw->rw_crashed_at != 0)
5969  {
5971  {
5972  int notify_pid;
5973 
5974  notify_pid = rw->rw_worker.bgw_notify_pid;
5975 
5976  ForgetBackgroundWorker(&iter);
5977 
5978  /* Report worker is gone now. */
5979  if (notify_pid != 0)
5980  kill(notify_pid, SIGUSR1);
5981 
5982  continue;
5983  }
5984 
5985  /* read system time only when needed */
5986  if (now == 0)
5988 
5990  rw->rw_worker.bgw_restart_time * 1000))
5991  {
5992  /* Set flag to remember that we have workers to start later */
5993  HaveCrashedWorker = true;
5994  continue;
5995  }
5996  }
5997 
5999  {
6000  /* reset crash time before trying to start worker */
6001  rw->rw_crashed_at = 0;
6002 
6003  /*
6004  * Try to start the worker.
6005  *
6006  * On failure, give up processing workers for now, but set
6007  * StartWorkerNeeded so we'll come back here on the next iteration
6008  * of ServerLoop to try again. (We don't want to wait, because
6009  * there might be additional ready-to-run workers.) We could set
6010  * HaveCrashedWorker as well, since this worker is now marked
6011  * crashed, but there's no need because the next run of this
6012  * function will do that.
6013  */
6014  if (!do_start_bgworker(rw))
6015  {
6016  StartWorkerNeeded = true;
6017  return;
6018  }
6019 
6020  /*
6021  * If we've launched as many workers as allowed, quit, but have
6022  * ServerLoop call us again to look for additional ready-to-run
6023  * workers. There might not be any, but we'll find out the next
6024  * time we run.
6025  */
6026  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
6027  {
6028  StartWorkerNeeded = true;
6029  return;
6030  }
6031  }
6032  }
6033 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1790
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5724
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5816
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
pid_t bgw_notify_pid
Definition: bgworker.h:100
#define kill(pid, sig)
Definition: win32_port.h:485
#define SIGUSR1
Definition: win32_port.h:180

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(), process_pm_child_exit(), process_pm_pmsignal(), and ServerLoop().

◆ MaybeStartSlotSyncWorker()

static void MaybeStartSlotSyncWorker ( void  )
static

Definition at line 5551 of file postmaster.c.

5552 {
5553  if (SlotSyncWorkerPID == 0 && pmState == PM_HOT_STANDBY &&
5557 }
#define SmartShutdown
Definition: postmaster.c:272
int StartSlotSyncWorker(void)
Definition: slotsync.c:1296
bool sync_replication_slots
Definition: slotsync.c:101
bool SlotSyncWorkerCanRestart(void)
Definition: slotsync.c:1411
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:915

References LOG, PM_HOT_STANDBY, pmState, Shutdown, SlotSyncWorkerCanRestart(), SlotSyncWorkerPID, SmartShutdown, StartSlotSyncWorker(), sync_replication_slots, and ValidateSlotSyncParams().

Referenced by process_pm_child_exit(), and ServerLoop().

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5513 of file postmaster.c.

5514 {
5515  if (WalReceiverPID == 0 &&
5516  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5517  pmState == PM_HOT_STANDBY) &&
5519  {
5521  if (WalReceiverPID != 0)
5522  WalReceiverRequested = false;
5523  /* else leave the flag set, so we'll try again later */
5524  }
5525 }
@ B_WAL_RECEIVER
Definition: miscadmin.h:356
static pid_t StartChildProcess(BackendType type)
Definition: postmaster.c:5311
static bool WalReceiverRequested
Definition: postmaster.c:369

References B_WAL_RECEIVER, PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, pmState, Shutdown, SmartShutdown, StartChildProcess(), WalReceiverPID, and WalReceiverRequested.

Referenced by process_pm_pmsignal(), and ServerLoop().

◆ MaybeStartWalSummarizer()

static void MaybeStartWalSummarizer ( void  )
static

Definition at line 5532 of file postmaster.c.

5533 {
5534  if (summarize_wal && WalSummarizerPID == 0 &&
5535  (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
5538 }
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:357
bool summarize_wal

References B_WAL_SUMMARIZER, PM_HOT_STANDBY, PM_RUN, pmState, Shutdown, SmartShutdown, StartChildProcess(), summarize_wal, and WalSummarizerPID.

Referenced by process_pm_child_exit(), and ServerLoop().

◆ PostmasterMain()

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

Definition at line 585 of file postmaster.c.

586 {
587  int opt;
588  int status;
589  char *userDoption = NULL;
590  bool listen_addr_saved = false;
591  char *output_config_variable = NULL;
592 
594 
596 
598 
599  /*
600  * Start our win32 signal implementation
601  */
602 #ifdef WIN32
604 #endif
605 
606  /*
607  * We should not be creating any files or directories before we check the
608  * data directory (see checkDataDir()), but just in case set the umask to
609  * the most restrictive (owner-only) permissions.
610  *
611  * checkDataDir() will reset the umask based on the data directory
612  * permissions.
613  */
614  umask(PG_MODE_MASK_OWNER);
615 
616  /*
617  * By default, palloc() requests in the postmaster will be allocated in
618  * the PostmasterContext, which is space that can be recycled by backends.
619  * Allocated data that needs to be available to backends should be
620  * allocated in TopMemoryContext.
621  */
623  "Postmaster",
626 
627  /* Initialize paths to installation files */
628  getInstallationPaths(argv[0]);
629 
630  /*
631  * Set up signal handlers for the postmaster process.
632  *
633  * CAUTION: when changing this list, check for side-effects on the signal
634  * handling setup of child processes. See tcop/postgres.c,
635  * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
636  * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
637  * postmaster/bgworker.c and postmaster/checkpointer.c.
638  */
639  pqinitmask();
640  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
641 
646  pqsignal(SIGALRM, SIG_IGN); /* ignored */
647  pqsignal(SIGPIPE, SIG_IGN); /* ignored */
649  pqsignal(SIGUSR2, dummy_handler); /* unused, reserve for children */
651 
652  /* This may configure SIGURG, depending on platform. */
655 
656  /*
657  * No other place in Postgres should touch SIGTTIN/SIGTTOU handling. We
658  * ignore those signals in a postmaster environment, so that there is no
659  * risk of a child process freezing up due to writing to stderr. But for
660  * a standalone backend, their default handling is reasonable. Hence, all
661  * child processes should just allow the inherited settings to stand.
662  */
663 #ifdef SIGTTIN
664  pqsignal(SIGTTIN, SIG_IGN); /* ignored */
665 #endif
666 #ifdef SIGTTOU
667  pqsignal(SIGTTOU, SIG_IGN); /* ignored */
668 #endif
669 
670  /* ignore SIGXFSZ, so that ulimit violations work like disk full */
671 #ifdef SIGXFSZ
672  pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
673 #endif
674 
675  /* Begin accepting signals. */
676  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
677 
678  /*
679  * Options setup
680  */
682 
683  opterr = 1;
684 
685  /*
686  * Parse command-line options. CAUTION: keep this in sync with
687  * tcop/postgres.c (the option sets should not conflict) and with the
688  * common help() function in main/main.c.
689  */
690  while ((opt = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:")) != -1)
691  {
692  switch (opt)
693  {
694  case 'B':
695  SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
696  break;
697 
698  case 'b':
699  /* Undocumented flag used for binary upgrades */
700  IsBinaryUpgrade = true;
701  break;
702 
703  case 'C':
704  output_config_variable = strdup(optarg);
705  break;
706 
707  case 'c':
708  case '-':
709  {
710  char *name,
711  *value;
712 
714  if (!value)
715  {
716  if (opt == '-')
717  ereport(ERROR,
718  (errcode(ERRCODE_SYNTAX_ERROR),
719  errmsg("--%s requires a value",
720  optarg)));
721  else
722  ereport(ERROR,
723  (errcode(ERRCODE_SYNTAX_ERROR),
724  errmsg("-c %s requires a value",
725  optarg)));
726  }
727 
729  pfree(name);
730  pfree(value);
731  break;
732  }
733 
734  case 'D':
735  userDoption = strdup(optarg);
736  break;
737 
738  case 'd':
740  break;
741 
742  case 'E':
743  SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
744  break;
745 
746  case 'e':
747  SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
748  break;
749 
750  case 'F':
751  SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
752  break;
753 
754  case 'f':
756  {
757  write_stderr("%s: invalid argument for option -f: \"%s\"\n",
758  progname, optarg);
759  ExitPostmaster(1);
760  }
761  break;
762 
763  case 'h':
764  SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
765  break;
766 
767  case 'i':
768  SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
769  break;
770 
771  case 'j':
772  /* only used by interactive backend */
773  break;
774 
775  case 'k':
776  SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
777  break;
778 
779  case 'l':
780  SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
781  break;
782 
783  case 'N':
784  SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
785  break;
786 
787  case 'O':
788  SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
789  break;
790 
791  case 'P':
792  SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
793  break;
794 
795  case 'p':
797  break;
798 
799  case 'r':
800  /* only used by single-user backend */
801  break;
802 
803  case 'S':
805  break;
806 
807  case 's':
808  SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
809  break;
810 
811  case 'T':
812 
813  /*
814  * This option used to be defined as sending SIGSTOP after a
815  * backend crash, but sending SIGABRT seems more useful.
816  */
817  SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
818  break;
819 
820  case 't':
821  {
822  const char *tmp = get_stats_option_name(optarg);
823 
824  if (tmp)
825  {
827  }
828  else
829  {
830  write_stderr("%s: invalid argument for option -t: \"%s\"\n",
831  progname, optarg);
832  ExitPostmaster(1);
833  }
834  break;
835  }
836 
837  case 'W':
838  SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
839  break;
840 
841  default:
842  write_stderr("Try \"%s --help\" for more information.\n",
843  progname);
844  ExitPostmaster(1);
845  }
846  }
847 
848  /*
849  * Postmaster accepts no non-option switch arguments.
850  */
851  if (optind < argc)
852  {
853  write_stderr("%s: invalid argument: \"%s\"\n",
854  progname, argv[optind]);
855  write_stderr("Try \"%s --help\" for more information.\n",
856  progname);
857  ExitPostmaster(1);
858  }
859 
860  /*
861  * Locate the proper configuration files and data directory, and read
862  * postgresql.conf for the first time.
863  */
865  ExitPostmaster(2);
866 
867  if (output_config_variable != NULL)
868  {
869  /*
870  * If this is a runtime-computed GUC, it hasn't yet been initialized,
871  * and the present value is not useful. However, this is a convenient
872  * place to print the value for most GUCs because it is safe to run
873  * postmaster startup to this point even if the server is already
874  * running. For the handful of runtime-computed GUCs that we cannot
875  * provide meaningful values for yet, we wait until later in
876  * postmaster startup to print the value. We won't be able to use -C
877  * on running servers for those GUCs, but using this option now would
878  * lead to incorrect results for them.
879  */
880  int flags = GetConfigOptionFlags(output_config_variable, true);
881 
882  if ((flags & GUC_RUNTIME_COMPUTED) == 0)
883  {
884  /*
885  * "-C guc" was specified, so print GUC's value and exit. No
886  * extra permission check is needed because the user is reading
887  * inside the data dir.
888  */
889  const char *config_val = GetConfigOption(output_config_variable,
890  false, false);
891 
892  puts(config_val ? config_val : "");
893  ExitPostmaster(0);
894  }
895 
896  /*
897  * A runtime-computed GUC will be printed later on. As we initialize
898  * a server startup sequence, silence any log messages that may show
899  * up in the output generated. FATAL and more severe messages are
900  * useful to show, even if one would only expect at least PANIC. LOG
901  * entries are hidden.
902  */
903  SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
905  }
906 
907  /* Verify that DataDir looks reasonable */
908  checkDataDir();
909 
910  /* Check that pg_control exists */
912 
913  /* And switch working directory into it */
914  ChangeToDataDir();
915 
916  /*
917  * Check for invalid combinations of GUC settings.
918  */
920  {
921  write_stderr("%s: superuser_reserved_connections (%d) plus reserved_connections (%d) must be less than max_connections (%d)\n",
922  progname,
925  ExitPostmaster(1);
926  }
928  ereport(ERROR,
929  (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
931  ereport(ERROR,
932  (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
934  ereport(ERROR,
935  (errmsg("WAL cannot be summarized when wal_level is \"minimal\"")));
936 
937  /*
938  * Other one-time internal sanity checks can go here, if they are fast.
939  * (Put any slow processing further down, after postmaster.pid creation.)
940  */
941  if (!CheckDateTokenTables())
942  {
943  write_stderr("%s: invalid datetoken tables, please fix\n", progname);
944  ExitPostmaster(1);
945  }
946 
947  /*
948  * Now that we are done processing the postmaster arguments, reset
949  * getopt(3) library so that it will work correctly in subprocesses.
950  */
951  optind = 1;
952 #ifdef HAVE_INT_OPTRESET
953  optreset = 1; /* some systems need this too */
954 #endif
955 
956  /* For debugging: display postmaster environment */
957  {
958  extern char **environ;
959  char **p;
960 
961  ereport(DEBUG3,
962  (errmsg_internal("%s: PostmasterMain: initial environment dump:",
963  progname)));
964  ereport(DEBUG3,
965  (errmsg_internal("-----------------------------------------")));
966  for (p = environ; *p; ++p)
967  ereport(DEBUG3,
968  (errmsg_internal("\t%s", *p)));
969  ereport(DEBUG3,
970  (errmsg_internal("-----------------------------------------")));
971  }
972 
973  /*
974  * Create lockfile for data directory.
975  *
976  * We want to do this before we try to grab the input sockets, because the
977  * data directory interlock is more reliable than the socket-file
978  * interlock (thanks to whoever decided to put socket files in /tmp :-().
979  * For the same reason, it's best to grab the TCP socket(s) before the
980  * Unix socket(s).
981  *
982  * Also note that this internally sets up the on_proc_exit function that
983  * is responsible for removing both data directory and socket lockfiles;
984  * so it must happen before opening sockets so that at exit, the socket
985  * lockfiles go away after CloseServerPorts runs.
986  */
987  CreateDataDirLockFile(true);
988 
989  /*
990  * Read the control file (for error checking and config info).
991  *
992  * Since we verify the control file's CRC, this has a useful side effect
993  * on machines where we need a run-time test for CRC support instructions.
994  * The postmaster will do the test once at startup, and then its child
995  * processes will inherit the correct function pointer and not need to
996  * repeat the test.
997  */
999 
1000  /*
1001  * Register the apply launcher. It's probably a good idea to call this
1002  * before any modules had a chance to take the background worker slots.
1003  */
1005 
1006  /*
1007  * process any libraries that should be preloaded at postmaster start
1008  */
1010 
1011  /*
1012  * Initialize SSL library, if specified.
1013  */
1014 #ifdef USE_SSL
1015  if (EnableSSL)
1016  {
1017  (void) secure_initialize(true);
1018  LoadedSSL = true;
1019  }
1020 #endif
1021 
1022  /*
1023  * Now that loadable modules have had their chance to alter any GUCs,
1024  * calculate MaxBackends.
1025  */
1027 
1028  /*
1029  * Give preloaded libraries a chance to request additional shared memory.
1030  */
1032 
1033  /*
1034  * Now that loadable modules have had their chance to request additional
1035  * shared memory, determine the value of any runtime-computed GUCs that
1036  * depend on the amount of shared memory required.
1037  */
1039 
1040  /*
1041  * Now that modules have been loaded, we can process any custom resource
1042  * managers specified in the wal_consistency_checking GUC.
1043  */
1045 
1046  /*
1047  * If -C was specified with a runtime-computed GUC, we held off printing
1048  * the value earlier, as the GUC was not yet initialized. We handle -C
1049  * for most GUCs before we lock the data directory so that the option may
1050  * be used on a running server. However, a handful of GUCs are runtime-
1051  * computed and do not have meaningful values until after locking the data
1052  * directory, and we cannot safely calculate their values earlier on a
1053  * running server. At this point, such GUCs should be properly
1054  * initialized, and we haven't yet set up shared memory, so this is a good
1055  * time to handle the -C option for these special GUCs.
1056  */
1057  if (output_config_variable != NULL)
1058  {
1059  const char *config_val = GetConfigOption(output_config_variable,
1060  false, false);
1061 
1062  puts(config_val ? config_val : "");
1063  ExitPostmaster(0);
1064  }
1065 
1066  /*
1067  * Set up shared memory and semaphores.
1068  *
1069  * Note: if using SysV shmem and/or semas, each postmaster startup will
1070  * normally choose the same IPC keys. This helps ensure that we will
1071  * clean up dead IPC objects if the postmaster crashes and is restarted.
1072  */
1074 
1075  /*
1076  * Estimate number of openable files. This must happen after setting up
1077  * semaphores, because on some platforms semaphores count as open files.
1078  */
1079  set_max_safe_fds();
1080 
1081  /*
1082  * Set reference point for stack-depth checking.
1083  */
1084  (void) set_stack_base();
1085 
1086  /*
1087  * Initialize pipe (or process handle on Windows) that allows children to
1088  * wake up from sleep on postmaster death.
1089  */
1091 
1092 #ifdef WIN32
1093 
1094  /*
1095  * Initialize I/O completion port used to deliver list of dead children.
1096  */
1097  win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
1098  if (win32ChildQueue == NULL)
1099  ereport(FATAL,
1100  (errmsg("could not create I/O completion port for child queue")));
1101 #endif
1102 
1103 #ifdef EXEC_BACKEND
1104  /* Write out nondefault GUC settings for child processes to use */
1105  write_nondefault_variables(PGC_POSTMASTER);
1106 
1107  /*
1108  * Clean out the temp directory used to transmit parameters to child
1109  * processes (see internal_forkexec, below). We must do this before
1110  * launching any child processes, else we have a race condition: we could
1111  * remove a parameter file before the child can read it. It should be
1112  * safe to do so now, because we verified earlier that there are no
1113  * conflicting Postgres processes in this data directory.
1114  */
1116 #endif
1117 
1118  /*
1119  * Forcibly remove the files signaling a standby promotion request.
1120  * Otherwise, the existence of those files triggers a promotion too early,
1121  * whether a user wants that or not.
1122  *
1123  * This removal of files is usually unnecessary because they can exist
1124  * only during a few moments during a standby promotion. However there is
1125  * a race condition: if pg_ctl promote is executed and creates the files
1126  * during a promotion, the files can stay around even after the server is
1127  * brought up to be the primary. Then, if a new standby starts by using
1128  * the backup taken from the new primary, the files can exist at server
1129  * startup and must be removed in order to avoid an unexpected promotion.
1130  *
1131  * Note that promotion signal files need to be removed before the startup
1132  * process is invoked. Because, after that, they can be used by
1133  * postmaster's SIGUSR1 signal handler.
1134  */
1136 
1137  /* Do the same for logrotate signal file */
1139 
1140  /* Remove any outdated file holding the current log filenames. */
1141  if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
1142  ereport(LOG,
1144  errmsg("could not remove file \"%s\": %m",
1146 
1147  /*
1148  * If enabled, start up syslogger collection subprocess
1149  */
1151 
1152  /*
1153  * Reset whereToSendOutput from DestDebug (its starting state) to
1154  * DestNone. This stops ereport from sending log messages to stderr unless
1155  * Log_destination permits. We don't do this until the postmaster is
1156  * fully launched, since startup failures may as well be reported to
1157  * stderr.
1158  *
1159  * If we are in fact disabling logging to stderr, first emit a log message
1160  * saying so, to provide a breadcrumb trail for users who may not remember
1161  * that their logging is configured to go somewhere else.
1162  */
1164  ereport(LOG,
1165  (errmsg("ending log output to stderr"),
1166  errhint("Future log output will go to log destination \"%s\".",
1168 
1170 
1171  /*
1172  * Report server startup in log. While we could emit this much earlier,
1173  * it seems best to do so after starting the log collector, if we intend
1174  * to use one.
1175  */
1176  ereport(LOG,
1177  (errmsg("starting %s", PG_VERSION_STR)));
1178 
1179  /*
1180  * Establish input sockets.
1181  *
1182  * First set up an on_proc_exit function that's charged with closing the
1183  * sockets again at postmaster shutdown.
1184  */
1185  ListenSockets = palloc(MAXLISTEN * sizeof(pgsocket));
1187 
1188  if (ListenAddresses)
1189  {
1190  char *rawstring;
1191  List *elemlist;
1192  ListCell *l;
1193  int success = 0;
1194 
1195  /* Need a modifiable copy of ListenAddresses */
1196  rawstring = pstrdup(ListenAddresses);
1197 
1198  /* Parse string into list of hostnames */
1199  if (!SplitGUCList(rawstring, ',', &elemlist))
1200  {
1201  /* syntax error in list */
1202  ereport(FATAL,
1203  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1204  errmsg("invalid list syntax in parameter \"%s\"",
1205  "listen_addresses")));
1206  }
1207 
1208  foreach(l, elemlist)
1209  {
1210  char *curhost = (char *) lfirst(l);
1211 
1212  if (strcmp(curhost, "*") == 0)
1213  status = StreamServerPort(AF_UNSPEC, NULL,
1214  (unsigned short) PostPortNumber,
1215  NULL,
1216  ListenSockets,
1218  MAXLISTEN);
1219  else
1220  status = StreamServerPort(AF_UNSPEC, curhost,
1221  (unsigned short) PostPortNumber,
1222  NULL,
1223  ListenSockets,
1225  MAXLISTEN);
1226 
1227  if (status == STATUS_OK)
1228  {
1229  success++;
1230  /* record the first successful host addr in lockfile */
1231  if (!listen_addr_saved)
1232  {
1234  listen_addr_saved = true;
1235  }
1236  }
1237  else
1238  ereport(WARNING,
1239  (errmsg("could not create listen socket for \"%s\"",
1240  curhost)));
1241  }
1242 
1243  if (!success && elemlist != NIL)
1244  ereport(FATAL,
1245  (errmsg("could not create any TCP/IP sockets")));
1246 
1247  list_free(elemlist);
1248  pfree(rawstring);
1249  }
1250 
1251 #ifdef USE_BONJOUR
1252  /* Register for Bonjour only if we opened TCP socket(s) */
1253  if (enable_bonjour && NumListenSockets > 0)
1254  {
1255  DNSServiceErrorType err;
1256 
1257  /*
1258  * We pass 0 for interface_index, which will result in registering on
1259  * all "applicable" interfaces. It's not entirely clear from the
1260  * DNS-SD docs whether this would be appropriate if we have bound to
1261  * just a subset of the available network interfaces.
1262  */
1263  err = DNSServiceRegister(&bonjour_sdref,
1264  0,
1265  0,
1266  bonjour_name,
1267  "_postgresql._tcp.",
1268  NULL,
1269  NULL,
1271  0,
1272  NULL,
1273  NULL,
1274  NULL);
1275  if (err != kDNSServiceErr_NoError)
1276  ereport(LOG,
1277  (errmsg("DNSServiceRegister() failed: error code %ld",
1278  (long) err)));
1279 
1280  /*
1281  * We don't bother to read the mDNS daemon's reply, and we expect that
1282  * it will automatically terminate our registration when the socket is
1283  * closed at postmaster termination. So there's nothing more to be
1284  * done here. However, the bonjour_sdref is kept around so that
1285  * forked children can close their copies of the socket.
1286  */
1287  }
1288 #endif
1289 
1291  {
1292  char *rawstring;
1293  List *elemlist;
1294  ListCell *l;
1295  int success = 0;
1296 
1297  /* Need a modifiable copy of Unix_socket_directories */
1298  rawstring = pstrdup(Unix_socket_directories);
1299 
1300  /* Parse string into list of directories */
1301  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1302  {
1303  /* syntax error in list */
1304  ereport(FATAL,
1305  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1306  errmsg("invalid list syntax in parameter \"%s\"",
1307  "unix_socket_directories")));
1308  }
1309 
1310  foreach(l, elemlist)
1311  {
1312  char *socketdir = (char *) lfirst(l);
1313 
1314  status = StreamServerPort(AF_UNIX, NULL,
1315  (unsigned short) PostPortNumber,
1316  socketdir,
1317  ListenSockets,
1319  MAXLISTEN);
1320 
1321  if (status == STATUS_OK)
1322  {
1323  success++;
1324  /* record the first successful Unix socket in lockfile */
1325  if (success == 1)
1327  }
1328  else
1329  ereport(WARNING,
1330  (errmsg("could not create Unix-domain socket in directory \"%s\"",
1331  socketdir)));
1332  }
1333 
1334  if (!success && elemlist != NIL)
1335  ereport(FATAL,
1336  (errmsg("could not create any Unix-domain sockets")));
1337 
1338  list_free_deep(elemlist);
1339  pfree(rawstring);
1340  }
1341 
1342  /*
1343  * check that we have some socket to listen on
1344  */
1345  if (NumListenSockets == 0)
1346  ereport(FATAL,
1347  (errmsg("no socket created for listening")));
1348 
1349  /*
1350  * If no valid TCP ports, write an empty line for listen address,
1351  * indicating the Unix socket must be used. Note that this line is not
1352  * added to the lock file until there is a socket backing it.
1353  */
1354  if (!listen_addr_saved)
1356 
1357  /*
1358  * Record postmaster options. We delay this till now to avoid recording
1359  * bogus options (eg, unusable port number).
1360  */
1361  if (!CreateOptsFile(argc, argv, my_exec_path))
1362  ExitPostmaster(1);
1363 
1364  /*
1365  * Write the external PID file if requested
1366  */
1367  if (external_pid_file)
1368  {
1369  FILE *fpidfile = fopen(external_pid_file, "w");
1370 
1371  if (fpidfile)
1372  {
1373  fprintf(fpidfile, "%d\n", MyProcPid);
1374  fclose(fpidfile);
1375 
1376  /* Make PID file world readable */
1377  if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
1378  write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
1380  }
1381  else
1382  write_stderr("%s: could not write external PID file \"%s\": %s\n",
1384 
1386  }
1387 
1388  /*
1389  * Remove old temporary files. At this point there can be no other
1390  * Postgres processes running in this directory, so this should be safe.
1391  */
1393 
1394  /*
1395  * Initialize the autovacuum subsystem (again, no process start yet)
1396  */
1397  autovac_init();
1398 
1399  /*
1400  * Load configuration files for client authentication.
1401  */
1402  if (!load_hba())
1403  {
1404  /*
1405  * It makes no sense to continue if we fail to load the HBA file,
1406  * since there is no way to connect to the database in this case.
1407  */
1408  ereport(FATAL,
1409  /* translator: %s is a configuration file */
1410  (errmsg("could not load %s", HbaFileName)));
1411  }
1412  if (!load_ident())
1413  {
1414  /*
1415  * We can start up without the IDENT file, although it means that you
1416  * cannot log in using any of the authentication methods that need a
1417  * user name mapping. load_ident() already logged the details of error
1418  * to the log.
1419  */
1420  }
1421 
1422 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1423 
1424  /*
1425  * On macOS, libintl replaces setlocale() with a version that calls
1426  * CFLocaleCopyCurrent() when its second argument is "" and every relevant
1427  * environment variable is unset or empty. CFLocaleCopyCurrent() makes
1428  * the process multithreaded. The postmaster calls sigprocmask() and
1429  * calls fork() without an immediate exec(), both of which have undefined
1430  * behavior in a multithreaded program. A multithreaded postmaster is the
1431  * normal case on Windows, which offers neither fork() nor sigprocmask().
1432  */
1433  if (pthread_is_threaded_np() != 0)
1434  ereport(FATAL,
1435  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1436  errmsg("postmaster became multithreaded during startup"),
1437  errhint("Set the LC_ALL environment variable to a valid locale.")));
1438 #endif
1439 
1440  /*
1441  * Remember postmaster startup time
1442  */
1444 
1445  /*
1446  * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
1447  * see what's happening.
1448  */
1450 
1451  /* Start bgwriter and checkpointer so they can help with recovery */
1452  if (CheckpointerPID == 0)
1454  if (BgWriterPID == 0)
1456 
1457  /*
1458  * We're ready to rock and roll...
1459  */
1461  Assert(StartupPID != 0);
1463  pmState = PM_STARTUP;
1464 
1465  /* Some workers may be scheduled to start now */
1467 
1468  status = ServerLoop();
1469 
1470  /*
1471  * ServerLoop probably shouldn't ever return, but if it does, close down.
1472  */
1473  ExitPostmaster(status != STATUS_OK);
1474 
1475  abort(); /* not reached */
1476 }
void autovac_init(void)
Definition: autovacuum.c:3338
void pqinitmask(void)
Definition: pqsignal.c:41
bool CheckDateTokenTables(void)
Definition: datetime.c:4800
TimestampTz PgStartTime
Definition: timestamp.c:52
int secure_initialize(bool isServerStart)
Definition: be-secure.c:73
@ DestNone
Definition: dest.h:87
int Log_destination
Definition: elog.c:112
char * Log_destination_string
Definition: elog.c:113
#define DEBUG3
Definition: elog.h:28
#define LOG_DESTINATION_STDERR
Definition: elog.h:492
void err(int eval, const char *fmt,...)
Definition: err.c:43
void RemovePgTempFilesInDir(const char *tmpdirname, bool missing_ok, bool unlink_all)
Definition: fd.c:3333
void RemovePgTempFiles(void)
Definition: fd.c:3274
void set_max_safe_fds(void)
Definition: fd.c:1044
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
#define PG_TEMP_FILES_DIR
Definition: file_utils.h:62
bool IsBinaryUpgrade
Definition: globals.c:117
bool IsPostmasterEnvironment
Definition: globals.c:115
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4257
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition: guc.c:1780
void ParseLongOption(const char *string, char **name, char **value)
Definition: guc.c:6288
void InitializeGUCOptions(void)
Definition: guc.c:1526
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4280
int GetConfigOptionFlags(const char *name, bool missing_ok)
Definition: guc.c:4377
#define GUC_RUNTIME_COMPUTED
Definition: guc.h:225
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_S_ARGV
Definition: guc.h:113
@ PGC_SUSET
Definition: guc.h:74
@ PGC_POSTMASTER
Definition: guc.h:70
char * HbaFileName
Definition: guc_tables.c:540
char * external_pid_file
Definition: guc_tables.c:542
bool load_ident(void)
Definition: hba.c:2959
bool load_hba(void)
Definition: hba.c:2583
static struct @149 value
static bool success
Definition: initdb.c:184
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void InitializeShmemGUCs(void)
Definition: ipci.c:369
void CreateSharedMemoryAndSemaphores(void)
Definition: ipci.c:199
void InitializeLatchSupport(void)
Definition: latch.c:232
void ApplyLauncherRegister(void)
Definition: launcher.c:918
void list_free(List *list)
Definition: list.c:1546
void list_free_deep(List *list)
Definition: list.c:1560
char * pstrdup(const char *in)
Definition: mcxt.c:1576
void * palloc(Size size)
Definition: mcxt.c:1197
#define AllocSetContextCreate
Definition: memutils.h:128
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:152
@ B_CHECKPOINTER
Definition: miscadmin.h:354
@ B_STARTUP
Definition: miscadmin.h:355
@ B_BG_WRITER
Definition: miscadmin.h:353
void ChangeToDataDir(void)
Definition: miscinit.c:454
void process_shmem_requests(void)
Definition: miscinit.c:1871
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1511
void InitProcessLocalLatch(void)
Definition: miscinit.c:241
void process_shared_preload_libraries(void)
Definition: miscinit.c:1843
void checkDataDir(void)
Definition: miscinit.c:341
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1455
#define pg_hton16(x)
Definition: pg_bswap.h:120
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT int opterr
Definition: getopt.c:49
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:71
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define PM_STATUS_STARTING
Definition: pidfile.h:51
#define LOCK_FILE_LINE_LISTEN_ADDR
Definition: pidfile.h:42
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
#define LOCK_FILE_LINE_SOCKET_DIR
Definition: pidfile.h:41
int pgsocket
Definition: port.h:29
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition: postgres.c:3671
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition: postgres.c:3700
static const char * userDoption
Definition: postgres.c:160
const char * get_stats_option_name(const char *arg)
Definition: postgres.c:3742
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3473
void InitializeMaxBackends(void)
Definition: postinit.c:559
static void handle_pm_shutdown_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2710
static void maybe_start_bgworkers(void)
Definition: postmaster.c:5922
static void CloseServerPorts(int status, Datum arg)
Definition: postmaster.c:1483
static void InitPostmasterDeathWatchHandle(void)
Definition: postmaster.c:6556
void InitProcessGlobals(void)
Definition: postmaster.c:2574
static void handle_pm_reload_request_signal(SIGNAL_ARGS)
Definition: postmaster.c:2627
static int ServerLoop(void)
Definition: postmaster.c:1717
int PostPortNumber
Definition: postmaster.c:197
static void checkControlFile(void)
Definition: postmaster.c:1580
bool enable_bonjour
Definition: postmaster.c:240
int ReservedConnections
Definition: postmaster.c:224
static void handle_pm_pmsignal_signal(SIGNAL_ARGS)
Definition: postmaster.c:2617
char * Unix_socket_directories
Definition: postmaster.c:200
static bool CreateOptsFile(int argc, char *argv[], char *fullprogname)
Definition: postmaster.c:5563
static void handle_pm_child_exit_signal(SIGNAL_ARGS)
Definition: postmaster.c:2885
static void getInstallationPaths(const char *argv0)
Definition: postmaster.c:1526
static void unlink_external_pid_file(int status, Datum arg)
Definition: postmaster.c:1514
#define MAXLISTEN
Definition: postmaster.c:227
static void dummy_handler(SIGNAL_ARGS)
Definition: postmaster.c:5236
bool EnableSSL
Definition: postmaster.c:232
char * ListenAddresses
Definition: postmaster.c:203
int SuperuserReservedConnections
Definition: postmaster.c:223
char * bonjour_name
Definition: postmaster.c:241
static pid_t SysLoggerPID
Definition: postmaster.c:256
int StreamServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSockets[], int *NumListenSockets, int MaxListen)
Definition: pqcomm.c:322
char ** environ
void pgwin32_signal_initialize(void)
Definition: signal.c:79
Definition: pg_list.h:54
void RemoveLogrotateSignalFiles(void)
Definition: syslogger.c:1635
int SysLogger_Start(void)
Definition: syslogger.c:566
#define LOG_METAINFO_DATAFILE
Definition: syslogger.h:100
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3583
bool SplitGUCList(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3704
const char * name
#define S_IROTH
Definition: win32_port.h:313
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define S_IRGRP
Definition: win32_port.h:301
#define SIGPIPE
Definition: win32_port.h:173
#define S_IRUSR
Definition: win32_port.h:289
#define SIGALRM
Definition: win32_port.h:174
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
#define S_IWUSR
Definition: win32_port.h:292
int XLogArchiveMode
Definition: xlog.c:119
int wal_level
Definition: xlog.c:131
void InitializeWalConsistencyChecking(void)
Definition: xlog.c:4674
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4736
@ ARCHIVE_MODE_OFF
Definition: xlog.h:63
@ WAL_LEVEL_MINIMAL
Definition: xlog.h:72
void RemovePromoteSignalFiles(void)

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert(), autovac_init(), B_BG_WRITER, B_CHECKPOINTER, B_STARTUP, BgWriterPID, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPID, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), DEBUG3, DestNone, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, err(), errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), HbaFileName, InitializeGUCOptions(), InitializeLatchSupport(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), InitProcessLocalLatch(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenSockets, 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, NumListenSockets, on_proc_exit(), optarg, opterr, optind, palloc(), ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGC_S_OVERRIDE, PGC_SUSET, PgStartTime, pgwin32_signal_initialize(), PM_STARTUP, PM_STATUS_STARTING, pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), process_shared_preload_libraries(), process_shmem_requests(), progname, pstrdup(), RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedConnections, S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartChildProcess(), STARTUP_RUNNING, StartupPID, StartupStatus, STATUS_OK, StreamServerPort(), strerror, success, summarize_wal, SuperuserReservedConnections, SysLogger_Start(), SysLoggerPID, TopMemoryContext, UnBlockSig, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6041 of file postmaster.c.

6042 {
6043  dlist_iter iter;
6044  Backend *bp;
6045 
6046  dlist_foreach(iter, &BackendList)
6047  {
6048  bp = dlist_container(Backend, elem, iter.cur);
6049  if (bp->pid == pid)
6050  {
6051  bp->bgworker_notify = true;
6052  return true;
6053  }
6054  }
6055  return false;
6056 }

References BackendList, bkend::bgworker_notify, dlist_iter::cur, dlist_container, dlist_foreach, and bkend::pid.

Referenced by BackgroundWorkerStateChange().

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3669 of file postmaster.c.

3670 {
3671  /* If we're doing a smart shutdown, try to advance that state. */
3672  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3673  {
3674  if (!connsAllowed)
3675  {
3676  /*
3677  * This state ends when we have no normal client backends running.
3678  * Then we're ready to stop other children.
3679  */
3682  }
3683  }
3684 
3685  /*
3686  * If we're ready to do so, signal child processes to shut down. (This
3687  * isn't a persistent state, but treating it as a distinct pmState allows
3688  * us to share this code across multiple shutdown code paths.)
3689  */
3690  if (pmState == PM_STOP_BACKENDS)
3691  {
3692  /*
3693  * Forget any pending requests for background workers, since we're no
3694  * longer willing to launch any new workers. (If additional requests
3695  * arrive, BackgroundWorkerStateChange will reject them.)
3696  */
3698 
3699  /* Signal all backend children except walsenders */
3700  SignalSomeChildren(SIGTERM,
3702  /* and the autovac launcher too */
3703  if (AutoVacPID != 0)
3704  signal_child(AutoVacPID, SIGTERM);
3705  /* and the bgwriter too */
3706  if (BgWriterPID != 0)
3707  signal_child(BgWriterPID, SIGTERM);
3708  /* and the walwriter too */
3709  if (WalWriterPID != 0)
3710  signal_child(WalWriterPID, SIGTERM);
3711  /* If we're in recovery, also stop startup and walreceiver procs */
3712  if (StartupPID != 0)
3713  signal_child(StartupPID, SIGTERM);
3714  if (WalReceiverPID != 0)
3715  signal_child(WalReceiverPID, SIGTERM);
3716  if (WalSummarizerPID != 0)
3717  signal_child(WalSummarizerPID, SIGTERM);
3718  if (SlotSyncWorkerPID != 0)
3719  signal_child(SlotSyncWorkerPID, SIGTERM);
3720  /* checkpointer, archiver, stats, and syslogger may continue for now */
3721 
3722  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3724  }
3725 
3726  /*
3727  * If we are in a state-machine state that implies waiting for backends to
3728  * exit, see if they're all gone, and change state if so.
3729  */
3730  if (pmState == PM_WAIT_BACKENDS)
3731  {
3732  /*
3733  * PM_WAIT_BACKENDS state ends when we have no regular backends
3734  * (including autovac workers), no bgworkers (including unconnected
3735  * ones), and no walwriter, autovac launcher, bgwriter or slot sync
3736  * worker. If we are doing crash recovery or an immediate shutdown
3737  * then we expect the checkpointer to exit as well, otherwise not. The
3738  * stats and syslogger processes are disregarded since they are not
3739  * connected to shared memory; we also disregard dead_end children
3740  * here. Walsenders and archiver are also disregarded, they will be
3741  * terminated later after writing the checkpoint record.
3742  */
3744  StartupPID == 0 &&
3745  WalReceiverPID == 0 &&
3746  WalSummarizerPID == 0 &&
3747  BgWriterPID == 0 &&
3748  (CheckpointerPID == 0 ||
3750  WalWriterPID == 0 &&
3751  AutoVacPID == 0 &&
3752  SlotSyncWorkerPID == 0)
3753  {
3755  {
3756  /*
3757  * Start waiting for dead_end children to die. This state
3758  * change causes ServerLoop to stop creating new ones.
3759  */
3761 
3762  /*
3763  * We already SIGQUIT'd the archiver and stats processes, if
3764  * any, when we started immediate shutdown or entered
3765  * FatalError state.
3766  */
3767  }
3768  else
3769  {
3770  /*
3771  * If we get here, we are proceeding with normal shutdown. All
3772  * the regular children are gone, and it's time to tell the
3773  * checkpointer to do a shutdown checkpoint.
3774  */
3776  /* Start the checkpointer if not running */
3777  if (CheckpointerPID == 0)
3779  /* And tell it to shut down */
3780  if (CheckpointerPID != 0)
3781  {
3783  pmState = PM_SHUTDOWN;
3784  }
3785  else
3786  {
3787  /*
3788  * If we failed to fork a checkpointer, just shut down.
3789  * Any required cleanup will happen at next restart. We
3790  * set FatalError so that an "abnormal shutdown" message
3791  * gets logged when we exit.
3792  *
3793  * We don't consult send_abort_for_crash here, as it's
3794  * unlikely that dumping cores would illuminate the reason
3795  * for checkpointer fork failure.
3796  */
3797  FatalError = true;
3799 
3800  /* Kill the walsenders and archiver too */
3802  if (PgArchPID != 0)
3804  }
3805  }
3806  }
3807  }
3808 
3809  if (pmState == PM_SHUTDOWN_2)
3810  {
3811  /*
3812  * PM_SHUTDOWN_2 state ends when there's no other children than
3813  * dead_end children left. There shouldn't be any regular backends
3814  * left by now anyway; what we're really waiting for is walsenders and
3815  * archiver.
3816  */
3817  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3818  {
3820  }
3821  }
3822 
3823  if (pmState == PM_WAIT_DEAD_END)
3824  {
3825  /* Don't allow any new socket connection events. */
3827 
3828  /*
3829  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3830  * (ie, no dead_end children remain), and the archiver is gone too.
3831  *
3832  * The reason we wait for those two is to protect them against a new
3833  * postmaster starting conflicting subprocesses; this isn't an
3834  * ironclad protection, but it at least helps in the
3835  * shutdown-and-immediately-restart scenario. Note that they have
3836  * already been sent appropriate shutdown signals, either during a
3837  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3838  * FatalError processing.
3839  */
3840  if (dlist_is_empty(&BackendList) && PgArchPID == 0)
3841  {
3842  /* These other guys should be dead already */
3843  Assert(StartupPID == 0);
3844  Assert(WalReceiverPID == 0);
3845  Assert(WalSummarizerPID == 0);
3846  Assert(BgWriterPID == 0);
3847  Assert(CheckpointerPID == 0);
3848  Assert(WalWriterPID == 0);
3849  Assert(AutoVacPID == 0);
3850  Assert(SlotSyncWorkerPID == 0);
3851  /* syslogger is not considered here */
3853  }
3854  }
3855 
3856  /*
3857  * If we've been told to shut down, we exit as soon as there are no
3858  * remaining children. If there was a crash, cleanup will occur at the
3859  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3860  * crash before exiting, but that seems unwise if we are quitting because
3861  * we got SIGTERM from init --- there may well not be time for recovery
3862  * before init decides to SIGKILL us.)
3863  *
3864  * Note that the syslogger continues to run. It will exit when it sees
3865  * EOF on its input pipe, which happens when there are no more upstream
3866  * processes.
3867  */
3869  {
3870  if (FatalError)
3871  {
3872  ereport(LOG, (errmsg("abnormal database system shutdown")));
3873  ExitPostmaster(1);
3874  }
3875  else
3876  {
3877  /*
3878  * Normal exit from the postmaster is here. We don't need to log
3879  * anything here, since the UnlinkLockFiles proc_exit callback
3880  * will do so, and that should be the last user-visible action.
3881  */
3882  ExitPostmaster(0);
3883  }
3884  }
3885 
3886  /*
3887  * If the startup process failed, or the user does not want an automatic
3888  * restart after backend crashes, wait for all non-syslogger children to
3889  * exit, and then exit postmaster. We don't try to reinitialize when the
3890  * startup process fails, because more than likely it will just fail again
3891  * and we will keep trying forever.
3892  */
3893  if (pmState == PM_NO_CHILDREN)
3894  {
3896  {
3897  ereport(LOG,
3898  (errmsg("shutting down due to startup process failure")));
3899  ExitPostmaster(1);
3900  }
3901  if (!restart_after_crash)
3902  {
3903  ereport(LOG,
3904  (errmsg("shutting down because restart_after_crash is off")));
3905  ExitPostmaster(1);
3906  }
3907  }
3908 
3909  /*
3910  * If we need to recover from a crash, wait for all non-syslogger children
3911  * to exit, then reset shmem and start the startup process.
3912  */
3913  if (FatalError && pmState == PM_NO_CHILDREN)
3914  {
3915  ereport(LOG,
3916  (errmsg("all server processes terminated; reinitializing")));
3917 
3918  /* remove leftover temporary files after a crash */
3921 
3922  /* allow background workers to immediately restart */
3924 
3925  shmem_exit(1);
3926 
3927  /* re-read control file into local memory */
3929 
3930  /* re-create shared memory and semaphores */
3932 
3934  Assert(StartupPID != 0);
3936  pmState = PM_STARTUP;
3937  /* crash recovery started, reset SIGKILL flag */
3938  AbortStartTime = 0;
3939 
3940  /* start accepting server socket connection events again */
3942  }
3943 }
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:585
void ForgetUnstartedBackgroundWorkers(void)
Definition: bgworker.c:547
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
void shmem_exit(int code)
Definition: ipc.c:228
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3963
bool remove_temp_files_after_crash
Definition: postmaster.c:243
bool restart_after_crash
Definition: postmaster.c:242
#define SignalChildren(sig)
Definition: postmaster.c:437
static bool SignalSomeChildren(int signal, int target)
Definition: postmaster.c:4007
static void ConfigurePostmasterWaitSet(bool accept_connections)
Definition: postmaster.c:1694

References AbortStartTime, Assert(), AutoVacPID, B_CHECKPOINTER, B_STARTUP, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, BgWriterPID, CheckpointerPID, ConfigurePostmasterWaitSet(), connsAllowed, CountChildren(), CreateSharedMemoryAndSemaphores(), dlist_is_empty(), ereport, errmsg(), ExitPostmaster(), FatalError, ForgetUnstartedBackgroundWorkers(), ImmediateShutdown, LocalProcessControlFile(), LOG, NoShutdown, PgArchPID, PM_HOT_STANDBY, PM_NO_CHILDREN, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PM_WAIT_DEAD_END, pmState, remove_temp_files_after_crash, RemovePgTempFiles(), ResetBackgroundWorkerCrashTimes(), restart_after_crash, shmem_exit(), Shutdown, signal_child(), SignalChildren, SignalSomeChildren(), SIGQUIT, SIGUSR2, SlotSyncWorkerPID, StartChildProcess(), STARTUP_CRASHED, STARTUP_RUNNING, StartupPID, StartupStatus, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

Referenced by process_pm_child_exit(), process_pm_pmsignal(), and process_pm_shutdown_request().

◆ process_pm_child_exit()

static void process_pm_child_exit ( void  )
static

Definition at line 2895 of file postmaster.c.

2896 {
2897  int pid; /* process id of dead child process */
2898  int exitstatus; /* its exit status */
2899 
2900  pending_pm_child_exit = false;
2901 
2902  ereport(DEBUG4,
2903  (errmsg_internal("reaping dead processes")));
2904 
2905  while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
2906  {
2907  /*
2908  * Check if this child was a startup process.
2909  */
2910  if (pid == StartupPID)
2911  {
2912  StartupPID = 0;
2913 
2914  /*
2915  * Startup process exited in response to a shutdown request (or it
2916  * completed normally regardless of the shutdown request).
2917  */
2918  if (Shutdown > NoShutdown &&
2919  (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
2920  {
2923  /* PostmasterStateMachine logic does the rest */
2924  continue;
2925  }
2926 
2927  if (EXIT_STATUS_3(exitstatus))
2928  {
2929  ereport(LOG,
2930  (errmsg("shutdown at recovery target")));
2933  TerminateChildren(SIGTERM);
2935  /* PostmasterStateMachine logic does the rest */
2936  continue;
2937  }
2938 
2939  /*
2940  * Unexpected exit of startup process (including FATAL exit)
2941  * during PM_STARTUP is treated as catastrophic. There are no
2942  * other processes running yet, so we can just exit.
2943  */
2944  if (pmState == PM_STARTUP &&
2946  !EXIT_STATUS_0(exitstatus))
2947  {
2948  LogChildExit(LOG, _("startup process"),
2949  pid, exitstatus);
2950  ereport(LOG,
2951  (errmsg("aborting startup due to startup process failure")));
2952  ExitPostmaster(1);
2953  }
2954 
2955  /*
2956  * After PM_STARTUP, any unexpected exit (including FATAL exit) of
2957  * the startup process is catastrophic, so kill other children,
2958  * and set StartupStatus so we don't try to reinitialize after
2959  * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
2960  * then we previously sent the startup process a SIGQUIT; so
2961  * that's probably the reason it died, and we do want to try to
2962  * restart in that case.
2963  *
2964  * This stanza also handles the case where we sent a SIGQUIT
2965  * during PM_STARTUP due to some dead_end child crashing: in that
2966  * situation, if the startup process dies on the SIGQUIT, we need
2967  * to transition to PM_WAIT_BACKENDS state which will allow
2968  * PostmasterStateMachine to restart the startup process. (On the
2969  * other hand, the startup process might complete normally, if we
2970  * were too late with the SIGQUIT. In that case we'll fall
2971  * through and commence normal operations.)
2972  */
2973  if (!EXIT_STATUS_0(exitstatus))
2974  {
2976  {
2978  if (pmState == PM_STARTUP)
2980  }
2981  else
2983  HandleChildCrash(pid, exitstatus,
2984  _("startup process"));
2985  continue;
2986  }
2987 
2988  /*
2989  * Startup succeeded, commence normal operations
2990  */
2992  FatalError = false;
2993  AbortStartTime = 0;
2994  ReachedNormalRunning = true;
2995  pmState = PM_RUN;
2996  connsAllowed = true;
2997 
2998  /*
2999  * Crank up the background tasks, if we didn't do that already
3000  * when we entered consistent recovery state. It doesn't matter
3001  * if this fails, we'll just try again later.
3002  */
3003  if (CheckpointerPID == 0)
3005  if (BgWriterPID == 0)
3007  if (WalWriterPID == 0)
3010 
3011  /*
3012  * Likewise, start other special children as needed. In a restart
3013  * situation, some of them may be alive already.
3014  */
3017  if (PgArchStartupAllowed() && PgArchPID == 0)
3020 
3021  /* workers may be scheduled to start now */
3023 
3024  /* at this point we are really open for business */
3025  ereport(LOG,
3026  (errmsg("database system is ready to accept connections")));
3027 
3028  /* Report status */
3030 #ifdef USE_SYSTEMD
3031  sd_notify(0, "READY=1");
3032 #endif
3033 
3034  continue;
3035  }
3036 
3037  /*
3038  * Was it the bgwriter? Normal exit can be ignored; we'll start a new
3039  * one at the next iteration of the postmaster's main loop, if
3040  * necessary. Any other exit condition is treated as a crash.
3041  */
3042  if (pid == BgWriterPID)
3043  {
3044  BgWriterPID = 0;
3045  if (!EXIT_STATUS_0(exitstatus))
3046  HandleChildCrash(pid, exitstatus,
3047  _("background writer process"));
3048  continue;
3049  }
3050 
3051  /*
3052  * Was it the checkpointer?
3053  */
3054  if (pid == CheckpointerPID)
3055  {
3056  CheckpointerPID = 0;
3057  if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
3058  {
3059  /*
3060  * OK, we saw normal exit of the checkpointer after it's been
3061  * told to shut down. We expect that it wrote a shutdown
3062  * checkpoint. (If for some reason it didn't, recovery will
3063  * occur on next postmaster start.)
3064  *
3065  * At this point we should have no normal backend children
3066  * left (else we'd not be in PM_SHUTDOWN state) but we might
3067  * have dead_end children to wait for.
3068  *
3069  * If we have an archiver subprocess, tell it to do a last
3070  * archive cycle and quit. Likewise, if we have walsender
3071  * processes, tell them to send any remaining WAL and quit.
3072  */
3074 
3075  /* Waken archiver for the last time */
3076  if (PgArchPID != 0)
3078 
3079  /*
3080  * Waken walsenders for the last time. No regular backends
3081  * should be around anymore.
3082  */
3084 
3086  }
3087  else
3088  {
3089  /*
3090  * Any unexpected exit of the checkpointer (including FATAL
3091  * exit) is treated as a crash.
3092  */
3093  HandleChildCrash(pid, exitstatus,
3094  _("checkpointer process"));
3095  }
3096 
3097  continue;
3098  }
3099 
3100  /*
3101  * Was it the wal writer? Normal exit can be ignored; we'll start a
3102  * new one at the next iteration of the postmaster's main loop, if
3103  * necessary. Any other exit condition is treated as a crash.
3104  */
3105  if (pid == WalWriterPID)
3106  {
3107  WalWriterPID = 0;
3108  if (!EXIT_STATUS_0(exitstatus))
3109  HandleChildCrash(pid, exitstatus,
3110  _("WAL writer process"));
3111  continue;
3112  }
3113 
3114  /*
3115  * Was it the wal receiver? If exit status is zero (normal) or one
3116  * (FATAL exit), we assume everything is all right just like normal
3117  * backends. (If we need a new wal receiver, we'll start one at the
3118  * next iteration of the postmaster's main loop.)
3119  */
3120  if (pid == WalReceiverPID)
3121  {
3122  WalReceiverPID = 0;
3123  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3124  HandleChildCrash(pid, exitstatus,
3125  _("WAL receiver process"));
3126  continue;
3127  }
3128 
3129  /*
3130  * Was it the wal summarizer? Normal exit can be ignored; we'll start
3131  * a new one at the next iteration of the postmaster's main loop, if
3132  * necessary. Any other exit condition is treated as a crash.
3133  */
3134  if (pid == WalSummarizerPID)
3135  {
3136  WalSummarizerPID = 0;
3137  if (!EXIT_STATUS_0(exitstatus))
3138  HandleChildCrash(pid, exitstatus,
3139  _("WAL summarizer process"));
3140  continue;
3141  }
3142 
3143  /*
3144  * Was it the autovacuum launcher? Normal exit can be ignored; we'll
3145  * start a new one at the next iteration of the postmaster's main
3146  * loop, if necessary. Any other exit condition is treated as a
3147  * crash.
3148  */
3149  if (pid == AutoVacPID)
3150  {
3151  AutoVacPID = 0;
3152  if (!EXIT_STATUS_0(exitstatus))
3153  HandleChildCrash(pid, exitstatus,
3154  _("autovacuum launcher process"));
3155  continue;
3156  }
3157 
3158  /*
3159  * Was it the archiver? If exit status is zero (normal) or one (FATAL
3160  * exit), we assume everything is all right just like normal backends
3161  * and just try to restart a new one so that we immediately retry
3162  * archiving remaining files. (If fail, we'll try again in future
3163  * cycles of the postmaster's main loop.) Unless we were waiting for
3164  * it to shut down; don't restart it in that case, and
3165  * PostmasterStateMachine() will advance to the next shutdown step.
3166  */
3167  if (pid == PgArchPID)
3168  {
3169  PgArchPID = 0;
3170  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3171  HandleChildCrash(pid, exitstatus,
3172  _("archiver process"));
3173  if (PgArchStartupAllowed())
3175  continue;
3176  }
3177 
3178  /* Was it the system logger? If so, try to start a new one */
3179  if (pid == SysLoggerPID)
3180  {
3181  SysLoggerPID = 0;
3182  /* for safety's sake, launch new logger *first* */
3184  if (!EXIT_STATUS_0(exitstatus))
3185  LogChildExit(LOG, _("system logger process"),
3186  pid, exitstatus);
3187  continue;
3188  }
3189 
3190  /*
3191  * Was it the slot sync worker? Normal exit or FATAL exit can be
3192  * ignored (FATAL can be caused by libpqwalreceiver on receiving
3193  * shutdown request by the startup process during promotion); we'll
3194  * start a new one at the next iteration of the postmaster's main
3195  * loop, if necessary. Any other exit condition is treated as a crash.
3196  */
3197  if (pid == SlotSyncWorkerPID)
3198  {
3199  SlotSyncWorkerPID = 0;
3200  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3201  HandleChildCrash(pid, exitstatus,
3202  _("slot sync worker process"));
3203  continue;
3204  }
3205 
3206  /* Was it one of our background workers? */
3207  if (CleanupBackgroundWorker(pid, exitstatus))
3208  {
3209  /* have it be restarted */
3210  HaveCrashedWorker = true;
3211  continue;
3212  }
3213 
3214  /*
3215  * Else do standard backend child cleanup.
3216  */
3217  CleanupBackend(pid, exitstatus);
3218  } /* loop over pending child-death reports */
3219 
3220  /*
3221  * After cleaning out the SIGCHLD queue, see if we have any state changes
3222  * or actions to make.
3223  */
3225 }
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3284
int StartAutoVacLauncher(void)
#define DEBUG4
Definition: elog.h:27
@ B_WAL_WRITER
Definition: miscadmin.h:358
@ B_ARCHIVER
Definition: miscadmin.h:352
#define PM_STATUS_READY
Definition: pidfile.h:53
static bool CleanupBackgroundWorker(int pid, int exitstatus)
Definition: postmaster.c:3237
static void MaybeStartWalSummarizer(void)
Definition: postmaster.c:5532
static void PostmasterStateMachine(void)
Definition: postmaster.c:3669
static void TerminateChildren(int signal)
Definition: postmaster.c:4051
static void MaybeStartSlotSyncWorker(void)
Definition: postmaster.c:5551
#define PgArchStartupAllowed()
Definition: postmaster.c:456
static bool ReachedNormalRunning
Definition: postmaster.c:355
static void CleanupBackend(int pid, int exitstatus)
Definition: postmaster.c:3332
#define EXIT_STATUS_3(st)
Definition: postmaster.c:568

References _, AbortStartTime, AddToDataDirLockFile(), Assert(), AutoVacPID, AutoVacuumingActive(), B_ARCHIVER, B_BG_WRITER, B_CHECKPOINTER, B_WAL_WRITER, BgWriterPID, CheckpointerPID, CleanupBackend(), CleanupBackgroundWorker(), connsAllowed, DEBUG4, ereport, errmsg(), errmsg_internal(), EXIT_STATUS_0, EXIT_STATUS_1, EXIT_STATUS_3, ExitPostmaster(), FatalError, HandleChildCrash(), HaveCrashedWorker, IsBinaryUpgrade, LOCK_FILE_LINE_PM_STATUS, LOG, LogChildExit(), Max, maybe_start_bgworkers(), MaybeStartSlotSyncWorker(), MaybeStartWalSummarizer(), NoShutdown, pending_pm_child_exit, PgArchPID, PgArchStartupAllowed, PM_RUN, PM_SHUTDOWN, PM_SHUTDOWN_2, PM_STARTUP, PM_STATUS_READY, PM_WAIT_BACKENDS, pmState, PostmasterStateMachine(), ReachedNormalRunning, Shutdown, signal_child(), SignalChildren, SIGUSR2, SlotSyncWorkerPID, SmartShutdown, StartAutoVacLauncher(), StartChildProcess(), STARTUP_CRASHED, STARTUP_NOT_RUNNING, STARTUP_SIGNALED, StartupPID, StartupStatus, SysLogger_Start(), SysLoggerPID, TerminateChildren(), WalReceiverPID, WalSummarizerPID, and WalWriterPID.

Referenced by ServerLoop().

◆ process_pm_pmsignal()

static void process_pm_pmsignal ( void  )
static

Definition at line 5059 of file postmaster.c.

5060 {
5061  pending_pm_pmsignal = false;
5062 
5063  ereport(DEBUG2,
5064  (errmsg_internal("postmaster received pmsignal signal")));
5065 
5066  /*
5067  * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
5068  * unexpected states. If the startup process quickly starts up, completes
5069  * recovery, exits, we might process the death of the startup process
5070  * first. We don't want to go back to recovery in that case.
5071  */
5074  {
5075  /* WAL redo has started. We're out of reinitialization. */
5076  FatalError = false;
5077  AbortStartTime = 0;
5078 
5079  /*
5080  * Start the archiver if we're responsible for (re-)archiving received
5081  * files.
5082  */
5083  Assert(PgArchPID == 0);
5084  if (XLogArchivingAlways())
5086 
5087  /*
5088  * If we aren't planning to enter hot standby mode later, treat
5089  * RECOVERY_STARTED as meaning we're out of startup, and report status
5090  * accordingly.
5091  */
5092  if (!EnableHotStandby)
5093  {
5095 #ifdef USE_SYSTEMD
5096  sd_notify(0, "READY=1");
5097 #endif
5098  }
5099 
5100  pmState = PM_RECOVERY;
5101  }
5102 
5105  {
5106  ereport(LOG,
5107  (errmsg("database system is ready to accept read-only connections")));
5108 
5109  /* Report status */
5111 #ifdef USE_SYSTEMD
5112  sd_notify(0, "READY=1");
5113 #endif
5114 
5116  connsAllowed = true;
5117 
5118  /* Some workers may be scheduled to start now */
5119  StartWorkerNeeded = true;
5120  }
5121 
5122  /* Process background worker state changes. */
5124  {
5125  /* Accept new worker requests only if not stopping. */
5127  StartWorkerNeeded = true;
5128  }
5129 
5132 
5133  /* Tell syslogger to rotate logfile if requested */
5134  if (SysLoggerPID != 0)
5135  {
5136  if (CheckLogrotateSignal())
5137  {
5140  }
5142  {
5144  }
5145  }
5146 
5149  {
5150  /*
5151  * Start one iteration of the autovacuum daemon, even if autovacuuming
5152  * is nominally not enabled. This is so we can have an active defense
5153  * against transaction ID wraparound. We set a flag for the main loop
5154  * to do it rather than trying to do it here --- this is because the
5155  * autovac process itself may send the signal, and we want to handle
5156  * that by launching another iteration as soon as the current one
5157  * completes.
5158  */
5159  start_autovac_launcher = true;
5160  }
5161 
5164  {
5165  /* The autovacuum launcher wants us to start a worker process. */
5167  }
5168 
5170  {
5171  /* Startup Process wants us to start the walreceiver process. */
5172  /* Start immediately if possible, else remember request for later. */
5173  WalReceiverRequested = true;
5175  }
5176 
5177  /*
5178  * Try to advance postmaster's state machine, if a child requests it.
5179  *
5180  * Be careful about the order of this action relative to this function's
5181  * other actions. Generally, this should be after other actions, in case
5182  * they have effects PostmasterStateMachine would need to know about.
5183  * However, we should do it before the CheckPromoteSignal step, which
5184  * cannot have any (immediate) effect on the state machine, but does
5185  * depend on what state we're in now.
5186  */
5188  {
5190  }
5191 
5192  if (StartupPID != 0 &&
5193  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5194  pmState == PM_HOT_STANDBY) &&
5196  {
5197  /*
5198  * Tell startup process to finish recovery.
5199  *
5200  * Leave the promote signal file in place and let the Startup process
5201  * do the unlink.
5202  */
5204  }
5205 }
void BackgroundWorkerStateChange(bool allow_new_workers)
Definition: bgworker.c:246
#define PM_STATUS_STANDBY
Definition: pidfile.h:54
bool CheckPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:198
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition: pmsignal.h:39
@ PMSIGNAL_RECOVERY_STARTED
Definition: pmsignal.h:35
@ PMSIGNAL_START_WALRECEIVER
Definition: pmsignal.h:41
@ PMSIGNAL_START_AUTOVAC_LAUNCHER
Definition: pmsignal.h:38
@ PMSIGNAL_BEGIN_HOT_STANDBY
Definition: pmsignal.h:36
@ PMSIGNAL_BACKGROUND_WORKER_CHANGE
Definition: pmsignal.h:40
@ PMSIGNAL_ROTATE_LOGFILE
Definition: pmsignal.h:37
@ PMSIGNAL_ADVANCE_STATE_MACHINE
Definition: pmsignal.h:42
static void MaybeStartWalReceiver(void)
Definition: postmaster.c:5513
static bool start_autovac_launcher
Definition: postmaster.c:363
static void StartAutovacuumWorker(void)
Definition: postmaster.c:5422
bool CheckLogrotateSignal(void)
Definition: syslogger.c:1621
bool CheckPromoteSignal(void)

References AbortStartTime, AddToDataDirLockFile(), Assert(), B_ARCHIVER, BackgroundWorkerStateChange(), CheckLogrotateSignal(), CheckPostmasterSignal(), CheckPromoteSignal(), connsAllowed, DEBUG2, EnableHotStandby, ereport, errmsg(), errmsg_internal(), FatalError, HaveCrashedWorker, LOCK_FILE_LINE_PM_STATUS, LOG, maybe_start_bgworkers(), MaybeStartWalReceiver(), NoShutdown, pending_pm_pmsignal, PgArchPID, PM_HOT_STANDBY, PM_RECOVERY, PM_STARTUP, PM_STATUS_READY, PM_STATUS_STANDBY, PM_STOP_BACKENDS, PMSIGNAL_ADVANCE_STATE_MACHINE, PMSIGNAL_BACKGROUND_WORKER_CHANGE, PMSIGNAL_BEGIN_HOT_STANDBY, PMSIGNAL_RECOVERY_STARTED, PMSIGNAL_ROTATE_LOGFILE, PMSIGNAL_START_AUTOVAC_LAUNCHER, PMSIGNAL_START_AUTOVAC_WORKER, PMSIGNAL_START_WALRECEIVER, pmState, PostmasterStateMachine(), RemoveLogrotateSignalFiles(), Shutdown, signal_child(), SIGUSR1, SIGUSR2, SmartShutdown, start_autovac_launcher, StartAutovacuumWorker(), StartChildProcess(), StartupPID, StartWorkerNeeded, SysLoggerPID, WalReceiverRequested, and XLogArchivingAlways.

Referenced by ServerLoop().

◆ process_pm_reload_request()

static void process_pm_reload_request ( void  )
static

Definition at line 2637 of file postmaster.c.

2638 {
2639  pending_pm_reload_request = false;
2640 
2641  ereport(DEBUG2,
2642  (errmsg_internal("postmaster received reload request signal")));
2643 
2644  if (Shutdown <= SmartShutdown)
2645  {
2646  ereport(LOG,
2647  (errmsg("received SIGHUP, reloading configuration files")));
2650  if (StartupPID != 0)
2652  if (BgWriterPID != 0)
2654  if (CheckpointerPID != 0)
2656  if (WalWriterPID != 0)
2658  if (WalReceiverPID != 0)
2660  if (WalSummarizerPID != 0)
2662  if (AutoVacPID != 0)
2664  if (PgArchPID != 0)
2666  if (SysLoggerPID != 0)
2668  if (SlotSyncWorkerPID != 0)
2670 
2671  /* Reload authentication config files too */
2672  if (!load_hba())
2673  ereport(LOG,
2674  /* translator: %s is a configuration file */
2675  (errmsg("%s was not reloaded", HbaFileName)));
2676 
2677  if (!load_ident())
2678  ereport(LOG,
2679  (errmsg("%s was not reloaded", IdentFileName)));
2680 
2681 #ifdef USE_SSL
2682  /* Reload SSL configuration as well */
2683  if (EnableSSL)
2684  {
2685  if (secure_initialize(false) == 0)
2686  LoadedSSL = true;
2687  else
2688  ereport(LOG,
2689  (errmsg("SSL configuration was not reloaded")));
2690  }
2691  else
2692  {
2693  secure_destroy();
2694  LoadedSSL = false;
2695  }
2696 #endif
2697 
2698 #ifdef EXEC_BACKEND
2699  /* Update the starting-point file for future children */
2700  write_nondefault_variables(PGC_SIGHUP);
2701 #endif
2702  }
2703 }
void secure_destroy(void)
Definition: be-secure.c:86
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
char * IdentFileName
Definition: guc_tables.c:541

References AutoVacPID, BgWriterPID, CheckpointerPID, DEBUG2, EnableSSL, ereport, errmsg(), errmsg_internal(), HbaFileName, IdentFileName, load_hba(), load_ident(), LOG, pending_pm_reload_request, PgArchPID, PGC_SIGHUP, ProcessConfigFile(), secure_destroy(), secure_initialize(), Shutdown, SIGHUP, signal_child(), SignalChildren, SlotSyncWorkerPID, SmartShutdown, StartupPID, SysLoggerPID, WalReceiverPID, WalSummarizerPID, and WalWriterPID.

Referenced by ServerLoop().

◆ process_pm_shutdown_request()

static void process_pm_shutdown_request ( void  )
static

Definition at line 2734 of file postmaster.c.

2735 {
2736  int mode;
2737 
2738  ereport(DEBUG2,
2739  (errmsg_internal("postmaster received shutdown request signal")));
2740 
2742 
2743  /*
2744  * If more than one shutdown request signal arrived since the last server
2745  * loop, take the one that is the most immediate. That matches the
2746  * priority that would apply if we processed them one by one in any order.
2747  */
2749  {
2753  }
2755  {
2757  mode = FastShutdown;
2758  }
2759  else
2760  mode = SmartShutdown;
2761 
2762  switch (mode)
2763  {
2764  case SmartShutdown:
2765 
2766  /*
2767  * Smart Shutdown:
2768  *
2769  * Wait for children to end their work, then shut down.
2770  */
2771  if (Shutdown >= SmartShutdown)
2772  break;
2774  ereport(LOG,
2775  (errmsg("received smart shutdown request")));
2776 
2777  /* Report status */
2779 #ifdef USE_SYSTEMD
2780  sd_notify(0, "STOPPING=1");
2781 #endif
2782 
2783  /*
2784  * If we reached normal running, we go straight to waiting for
2785  * client backends to exit. If already in PM_STOP_BACKENDS or a
2786  * later state, do not change it.
2787  */
2788  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2789  connsAllowed = false;
2790  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2791  {
2792  /* There should be no clients, so proceed to stop children */
2794  }
2795 
2796  /*
2797  * Now wait for online backup mode to end and backends to exit. If
2798  * that is already the case, PostmasterStateMachine will take the
2799  * next step.
2800  */
2802  break;
2803 
2804  case FastShutdown:
2805 
2806  /*
2807  * Fast Shutdown:
2808  *
2809  * Abort all children with SIGTERM (rollback active transactions
2810  * and exit) and shut down when they are gone.
2811  */
2812  if (Shutdown >= FastShutdown)
2813  break;
2815  ereport(LOG,
2816  (errmsg("received fast shutdown request")));
2817 
2818  /* Report status */
2820 #ifdef USE_SYSTEMD
2821  sd_notify(0, "STOPPING=1");
2822 #endif
2823 
2824  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2825  {
2826  /* Just shut down background processes silently */
2828  }
2829  else if (pmState == PM_RUN ||
2831  {
2832  /* Report that we're about to zap live client sessions */
2833  ereport(LOG,
2834  (errmsg("aborting any active transactions")));
2836  }
2837 
2838  /*
2839  * PostmasterStateMachine will issue any necessary signals, or
2840  * take the next step if no child processes need to be killed.
2841  */
2843  break;
2844 
2845  case ImmediateShutdown:
2846 
2847  /*
2848  * Immediate Shutdown:
2849  *
2850  * abort all children with SIGQUIT, wait for them to exit,
2851  * terminate remaining ones with SIGKILL, then exit without
2852  * attempt to properly shut down the data base system.
2853  */
2854  if (Shutdown >= ImmediateShutdown)
2855  break;
2857  ereport(LOG,
2858  (errmsg("received immediate shutdown request")));
2859 
2860  /* Report status */
2862 #ifdef USE_SYSTEMD
2863  sd_notify(0, "STOPPING=1");
2864 #endif
2865 
2866  /* tell children to shut down ASAP */
2867  /* (note we don't apply send_abort_for_crash here) */
2871 
2872  /* set stopwatch for them to die */
2873  AbortStartTime = time(NULL);
2874 
2875  /*
2876  * Now wait for backends to exit. If there are none,
2877  * PostmasterStateMachine will take the next step.
2878  */
2880  break;
2881  }
2882 }
static PgChecksumMode mode
Definition: pg_checksums.c:56
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
#define FastShutdown
Definition: postmaster.c:273

References AbortStartTime, AddToDataDirLockFile(), connsAllowed, DEBUG2, ereport, errmsg(), errmsg_internal(), FastShutdown, ImmediateShutdown, LOCK_FILE_LINE_PM_STATUS, LOG, mode, pending_pm_fast_shutdown_request, pending_pm_immediate_shutdown_request, pending_pm_shutdown_request, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_STATUS_STOPPING, PM_STOP_BACKENDS, PM_WAIT_BACKENDS, PMQUIT_FOR_STOP, pmState, PostmasterStateMachine(), SetQuitSignalReason(), Shutdown, SIGQUIT, SmartShutdown, and TerminateChildren().

Referenced by ServerLoop().

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5221 of file postmaster.c.

5222 {
5223  _exit(1);
5224 }

Referenced by BackendInitialize().

◆ processCancelRequest()

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

Definition at line 2330 of file postmaster.c.

2331 {
2332  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2333  int backendPID;
2334  int32 cancelAuthCode;
2335  Backend *bp;
2336 
2337 #ifndef EXEC_BACKEND
2338  dlist_iter iter;
2339 #else
2340  int i;
2341 #endif
2342 
2343  backendPID = (int) pg_ntoh32(canc->backendPID);
2344  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2345 
2346  /*
2347  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2348  * longer access the postmaster's own backend list, and must rely on the
2349  * duplicate array in shared memory.
2350  */
2351 #ifndef EXEC_BACKEND