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/select.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/transam.h"
#include "access/xlog.h"
#include "access/xlogrecovery.h"
#include "catalog/pg_control.h"
#include "common/file_perm.h"
#include "common/ip.h"
#include "common/pg_prng.h"
#include "common/string.h"
#include "lib/ilist.h"
#include "libpq/auth.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "libpq/pqsignal.h"
#include "pg_getopt.h"
#include "pgstat.h"
#include "port/pg_bswap.h"
#include "postmaster/autovacuum.h"
#include "postmaster/auxprocess.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/fork_process.h"
#include "postmaster/interrupt.h"
#include "postmaster/pgarch.h"
#include "postmaster/postmaster.h"
#include "postmaster/syslogger.h"
#include "replication/logicallauncher.h"
#include "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/ps_status.h"
#include "utils/queryjumble.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "utils/varlena.h"
Include dependency graph for postmaster.c:

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

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

Typedefs

typedef struct bkend Backend
 

Enumerations

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

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 SIGHUP_handler (SIGNAL_ARGS)
 
static void pmdie (SIGNAL_ARGS)
 
static void reaper (SIGNAL_ARGS)
 
static void sigusr1_handler (SIGNAL_ARGS)
 
static void process_startup_packet_die (SIGNAL_ARGS)
 
static void dummy_handler (SIGNAL_ARGS)
 
static void StartupPacketTimeoutHandler (void)
 
static void CleanupBackend (int pid, int exitstatus)
 
static bool CleanupBackgroundWorker (int pid, int exitstatus)
 
static void HandleChildCrash (int pid, int exitstatus, const char *procname)
 
static void LogChildExit (int lev, const char *procname, int pid, int exitstatus)
 
static void PostmasterStateMachine (void)
 
static void BackendInitialize (Port *port)
 
static void BackendRun (Port *port) pg_attribute_noreturn()
 
static void ExitPostmaster (int status) pg_attribute_noreturn()
 
static int ServerLoop (void)
 
static int BackendStartup (Port *port)
 
static int ProcessStartupPacket (Port *port, bool ssl_done, bool gss_done)
 
static void SendNegotiateProtocolVersion (List *unrecognized_protocol_options)
 
static void processCancelRequest (Port *port, void *pkt)
 
static int initMasks (fd_set *rmask)
 
static void report_fork_failure_to_client (Port *port, int errnum)
 
static CAC_state canAcceptConnections (int backend_type)
 
static bool RandomCancelKey (int32 *cancel_key)
 
static void signal_child (pid_t pid, int signal)
 
static 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 (AuxProcType type)
 
static void StartAutovacuumWorker (void)
 
static void MaybeStartWalReceiver (void)
 
static void InitPostmasterDeathWatchHandle (void)
 
void PostmasterMain (int argc, char *argv[])
 
static void DetermineSleepTime (struct timeval *timeout)
 
void ClosePostmasterPorts (bool am_syslogger)
 
void InitProcessGlobals (void)
 
int MaxLivePostmasterChildren (void)
 
void BackgroundWorkerInitializeConnection (const char *dbname, const char *username, uint32 flags)
 
void BackgroundWorkerInitializeConnectionByOid (Oid dboid, Oid useroid, uint32 flags)
 
void BackgroundWorkerBlockSignals (void)
 
void BackgroundWorkerUnblockSignals (void)
 
static bool do_start_bgworker (RegisteredBgWorker *rw)
 
static bool bgworker_should_start_now (BgWorkerStartTime start_time)
 
bool PostmasterMarkPIDForWorkerNotify (int pid)
 

Variables

static dlist_head BackendList = DLIST_STATIC_INIT(BackendList)
 
BackgroundWorkerMyBgworkerEntry = NULL
 
int PostPortNumber = DEF_PGPORT
 
char * Unix_socket_directories
 
char * ListenAddresses
 
int ReservedBackends
 
static pgsocket ListenSocket [MAXLISTEN]
 
bool EnableSSL = false
 
int PreAuthDelay = 0
 
int AuthenticationTimeout = 60
 
bool log_hostname
 
bool Log_connections = false
 
bool Db_user_namespace = false
 
bool enable_bonjour = false
 
char * bonjour_name
 
bool restart_after_crash = true
 
bool remove_temp_files_after_crash = true
 
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 AutoVacPID = 0
 
static pid_t PgArchPID = 0
 
static pid_t SysLoggerPID = 0
 
static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING
 
static int Shutdown = NoShutdown
 
static bool FatalError = false
 
static PMState pmState = PM_INIT
 
static bool connsAllowed = true
 
static time_t AbortStartTime = 0
 
static bool ReachedNormalRunning = false
 
bool ClientAuthInProgress = false
 
bool redirection_done = false
 
static volatile sig_atomic_t start_autovac_launcher = false
 
static volatile bool avlauncher_needs_signal = false
 
static volatile sig_atomic_t WalReceiverRequested = false
 
static volatile bool StartWorkerNeeded = true
 
static volatile bool HaveCrashedWorker = false
 
int postmaster_alive_fds [2] = {-1, -1}
 

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

Definition at line 149 of file postmaster.c.

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 146 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 148 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 145 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 147 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 544 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 545 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 546 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 263 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 264 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 219 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 261 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:317
@ PM_HOT_STANDBY
Definition: postmaster.c:316
@ PM_RECOVERY
Definition: postmaster.c:315
static PMState pmState
Definition: postmaster.c:328
#define XLogArchivingActive()
Definition: xlog.h:94
#define XLogArchivingAlways()
Definition: xlog.h:97

Definition at line 430 of file postmaster.c.

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 343 of file postmaster.c.

◆ SignalChildren

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

Definition at line 413 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 262 of file postmaster.c.

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 537 of file postmaster.c.

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 538 of file postmaster.c.

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 539 of file postmaster.c.

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 536 of file postmaster.c.

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 541 of file postmaster.c.

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

312 {
313  PM_INIT, /* postmaster starting */
314  PM_STARTUP, /* waiting for startup subprocess */
315  PM_RECOVERY, /* in archive recovery mode */
316  PM_HOT_STANDBY, /* in hot standby mode */
317  PM_RUN, /* normal "database is alive" state */
318  PM_STOP_BACKENDS, /* need to stop remaining backends */
319  PM_WAIT_BACKENDS, /* waiting for live backends to exit */
320  PM_SHUTDOWN, /* waiting for checkpointer to do shutdown
321  * ckpt */
322  PM_SHUTDOWN_2, /* waiting for archiver and walsenders to
323  * finish */
324  PM_WAIT_DEAD_END, /* waiting for dead_end children to exit */
325  PM_NO_CHILDREN /* all important children have exited */
326 } PMState;
PMState
Definition: postmaster.c:312
@ PM_WAIT_DEAD_END
Definition: postmaster.c:324
@ PM_NO_CHILDREN
Definition: postmaster.c:325
@ PM_WAIT_BACKENDS
Definition: postmaster.c:319
@ PM_SHUTDOWN
Definition: postmaster.c:320
@ PM_STOP_BACKENDS
Definition: postmaster.c:318
@ PM_SHUTDOWN_2
Definition: postmaster.c:322
@ PM_INIT
Definition: postmaster.c:313
@ PM_STARTUP
Definition: postmaster.c:314

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 250 of file postmaster.c.

251 {
254  STARTUP_SIGNALED, /* we sent it a SIGQUIT or SIGKILL */
StartupStatusEnum
Definition: postmaster.c:251
@ STARTUP_SIGNALED
Definition: postmaster.c:254
@ STARTUP_CRASHED
Definition: postmaster.c:255
@ STARTUP_NOT_RUNNING
Definition: postmaster.c:252
@ STARTUP_RUNNING
Definition: postmaster.c:253

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5771 of file postmaster.c.

5772 {
5773  Backend *bn;
5774 
5775  /*
5776  * Check that database state allows another connection. Currently the
5777  * only possible failure is CAC_TOOMANY, so we just log an error message
5778  * based on that rather than checking the error code precisely.
5779  */
5781  {
5782  ereport(LOG,
5783  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5784  errmsg("no slot available for new worker process")));
5785  return false;
5786  }
5787 
5788  /*
5789  * Compute the cancel key that will be assigned to this session. We
5790  * probably don't need cancel keys for background workers, but we'd better
5791  * have something random in the field to prevent unfriendly people from
5792  * sending cancels to them.
5793  */
5795  {
5796  ereport(LOG,
5797  (errcode(ERRCODE_INTERNAL_ERROR),
5798  errmsg("could not generate random cancel key")));
5799  return false;
5800  }
5801 
5802  bn = malloc(sizeof(Backend));
5803  if (bn == NULL)
5804  {
5805  ereport(LOG,
5806  (errcode(ERRCODE_OUT_OF_MEMORY),
5807  errmsg("out of memory")));
5808  return false;
5809  }
5810 
5811  bn->cancel_key = MyCancelKey;
5814  bn->dead_end = false;
5815  bn->bgworker_notify = false;
5816 
5817  rw->rw_backend = bn;
5818  rw->rw_child_slot = bn->child_slot;
5819 
5820  return true;
5821 }
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define LOG
Definition: elog.h:27
#define ereport(elevel,...)
Definition: elog.h:145
int32 MyCancelKey
Definition: globals.c:48
int MyPMChildSlot
Definition: globals.c:49
#define malloc(a)
Definition: header.h:50
@ CAC_OK
Definition: libpq-be.h:63
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:247
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2504
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5214
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:184
int bkend_type
Definition: postmaster.c:182
bool dead_end
Definition: postmaster.c:183
int32 cancel_key
Definition: postmaster.c:180
int child_slot
Definition: postmaster.c:181

References AssignPostmasterChildSlot(), BACKEND_TYPE_BGWORKER, bkend::bgworker_notify, bkend::bkend_type, CAC_OK, canAcceptConnections(), bkend::cancel_key, bkend::child_slot, bkend::dead_end, ereport, errcode(), errmsg(), LOG, malloc, MyCancelKey, MyPMChildSlot, RandomCancelKey(), RegisteredBgWorker::rw_backend, and RegisteredBgWorker::rw_child_slot.

Referenced by do_start_bgworker().

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4208 of file postmaster.c.

4209 {
4210  int status;
4211  int ret;
4212  char remote_host[NI_MAXHOST];
4213  char remote_port[NI_MAXSERV];
4214  StringInfoData ps_data;
4215 
4216  /* Save port etc. for ps status */
4217  MyProcPort = port;
4218 
4219  /* Tell fd.c about the long-lived FD associated with the port */
4221 
4222  /*
4223  * PreAuthDelay is a debugging aid for investigating problems in the
4224  * authentication cycle: it can be set in postgresql.conf to allow time to
4225  * attach to the newly-forked backend with a debugger. (See also
4226  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4227  * is not honored until after authentication.)
4228  */
4229  if (PreAuthDelay > 0)
4230  pg_usleep(PreAuthDelay * 1000000L);
4231 
4232  /* This flag will remain set until InitPostgres finishes authentication */
4233  ClientAuthInProgress = true; /* limit visibility of log messages */
4234 
4235  /* set these to empty in case they are needed before we set them up */
4236  port->remote_host = "";
4237  port->remote_port = "";
4238 
4239  /*
4240  * Initialize libpq and enable reporting of ereport errors to the client.
4241  * Must do this now because authentication uses libpq to send messages.
4242  */
4243  pq_init(); /* initialize libpq to talk to client */
4244  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4245 
4246  /*
4247  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4248  * to collect the startup packet; while SIGQUIT results in _exit(2).
4249  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4250  * cleanly if a buggy client fails to send the packet promptly.
4251  *
4252  * Exiting with _exit(1) is only possible because we have not yet touched
4253  * shared memory; therefore no outside-the-process state needs to get
4254  * cleaned up.
4255  */
4257  /* SIGQUIT handler was already set up by InitPostmasterChild */
4258  InitializeTimeouts(); /* establishes SIGALRM handler */
4260 
4261  /*
4262  * Get the remote host name and port for logging and status display.
4263  */
4264  remote_host[0] = '\0';
4265  remote_port[0] = '\0';
4266  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4267  remote_host, sizeof(remote_host),
4268  remote_port, sizeof(remote_port),
4269  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4270  ereport(WARNING,
4271  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4272  gai_strerror(ret))));
4273 
4274  /*
4275  * Save remote_host and remote_port in port structure (after this, they
4276  * will appear in log_line_prefix data for log messages).
4277  */
4278  port->remote_host = strdup(remote_host);
4279  port->remote_port = strdup(remote_port);
4280 
4281  /* And now we can issue the Log_connections message, if wanted */
4282  if (Log_connections)
4283  {
4284  if (remote_port[0])
4285  ereport(LOG,
4286  (errmsg("connection received: host=%s port=%s",
4287  remote_host,
4288  remote_port)));
4289  else
4290  ereport(LOG,
4291  (errmsg("connection received: host=%s",
4292  remote_host)));
4293  }
4294 
4295  /*
4296  * If we did a reverse lookup to name, we might as well save the results
4297  * rather than possibly repeating the lookup during authentication.
4298  *
4299  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4300  * get nothing useful for a client without an rDNS entry. Therefore, we
4301  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4302  * it into remote_hostname if so. (This test is conservative and might
4303  * sometimes classify a hostname as numeric, but an error in that
4304  * direction is safe; it only results in a possible extra lookup.)
4305  */
4306  if (log_hostname &&
4307  ret == 0 &&
4308  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4309  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4310  port->remote_hostname = strdup(remote_host);
4311 
4312  /*
4313  * Ready to begin client interaction. We will give up and _exit(1) after
4314  * a time delay, so that a broken client can't hog a connection
4315  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4316  * against the time limit.
4317  *
4318  * Note: AuthenticationTimeout is applied here while waiting for the
4319  * startup packet, and then again in InitPostgres for the duration of any
4320  * authentication operations. So a hostile client could tie up the
4321  * process for nearly twice AuthenticationTimeout before we kick him off.
4322  *
4323  * Note: because PostgresMain will call InitializeTimeouts again, the
4324  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4325  * since we never use it again after this function.
4326  */
4329 
4330  /*
4331  * Receive the startup packet (which might turn out to be a cancel request
4332  * packet).
4333  */
4334  status = ProcessStartupPacket(port, false, false);
4335 
4336  /*
4337  * Disable the timeout, and prevent SIGTERM again.
4338  */
4340  PG_SETMASK(&BlockSig);
4341 
4342  /*
4343  * As a safety check that nothing in startup has yet performed
4344  * shared-memory modifications that would need to be undone if we had
4345  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4346  * handlers have been registered yet. (This isn't terribly bulletproof,
4347  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4348  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4349  * handlers unfortunately, since pq_init() already registered one.)
4350  */
4352 
4353  /*
4354  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4355  * already did any appropriate error reporting.
4356  */
4357  if (status != STATUS_OK)
4358  proc_exit(0);
4359 
4360  /*
4361  * Now that we have the user and database name, we can set the process
4362  * title for ps. It's good to do this as early as possible in startup.
4363  */
4364  initStringInfo(&ps_data);
4365  if (am_walsender)
4367  appendStringInfo(&ps_data, "%s ", port->user_name);
4368  if (port->database_name[0] != '\0')
4369  appendStringInfo(&ps_data, "%s ", port->database_name);
4370  appendStringInfoString(&ps_data, port->remote_host);
4371  if (port->remote_port[0] != '\0')
4372  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4373 
4374  init_ps_display(ps_data.data);
4375  pfree(ps_data.data);
4376 
4377  set_ps_display("initializing");
4378 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
#define STATUS_OK
Definition: c.h:1108
@ DestRemote
Definition: dest.h:91
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
#define WARNING
Definition: elog.h:32
void ReserveExternalFD(void)
Definition: fd.c:1134
struct Port * MyProcPort
Definition: globals.c:47
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:428
void proc_exit(int code)
Definition: ipc.c:104
void pfree(void *pointer)
Definition: mcxt.c:1306
@ B_WAL_SENDER
Definition: miscadmin.h:330
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:251
static int port
Definition: pg_regress.c:90
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
pqsigfunc pqsignal(int signo, pqsigfunc func)
CommandDest whereToSendOutput
Definition: postgres.c:85
int PreAuthDelay
Definition: postmaster.c:225
bool log_hostname
Definition: postmaster.c:228
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5180
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5204
bool Log_connections
Definition: postmaster.c:229
bool ClientAuthInProgress
Definition: postmaster.c:347
int AuthenticationTimeout
Definition: postmaster.c:226
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:1989
void pq_init(void)
Definition: pqcomm.c:172
#define PG_SETMASK(mask)
Definition: pqsignal.h:18
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:251
void set_ps_display(const char *activity)
Definition: ps_status.c:342
void pg_usleep(long microsec)
Definition: signal.c:53
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:564
void InitializeTimeouts(void)
Definition: timeout.c:474
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:689
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:509
@ STARTUP_PACKET_TIMEOUT
Definition: timeout.h:26
bool am_walsender
Definition: walsender.c:116

References am_walsender, appendStringInfo(), appendStringInfoString(), AuthenticationTimeout, B_WAL_SENDER, BlockSig, check_on_shmem_exit_lists_are_empty(), ClientAuthInProgress, StringInfoData::data, DestRemote, disable_timeout(), enable_timeout_after(), ereport, errmsg(), errmsg_internal(), GetBackendTypeDesc(), init_ps_display(), InitializeTimeouts(), initStringInfo(), LOG, Log_connections, log_hostname, MyProcPort, pfree(), pg_getnameinfo_all(), PG_SETMASK, 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(), STATUS_OK, WARNING, and whereToSendOutput.

Referenced by BackendStartup().

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4388 of file postmaster.c.

4389 {
4390  /*
4391  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4392  * just yet, though, because InitPostgres will need the HBA data.)
4393  */
4395 
4396  PostgresMain(port->database_name, port->user_name);
4397 }
MemoryContext TopMemoryContext
Definition: mcxt.c:130
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4044

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

Referenced by BackendStartup().

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4048 of file postmaster.c.

4049 {
4050  Backend *bn; /* for backend cleanup */
4051  pid_t pid;
4052 
4053  /*
4054  * Create backend data structure. Better before the fork() so we can
4055  * handle failure cleanly.
4056  */
4057  bn = (Backend *) malloc(sizeof(Backend));
4058  if (!bn)
4059  {
4060  ereport(LOG,
4061  (errcode(ERRCODE_OUT_OF_MEMORY),
4062  errmsg("out of memory")));
4063  return STATUS_ERROR;
4064  }
4065 
4066  /*
4067  * Compute the cancel key that will be assigned to this backend. The
4068  * backend will have its own copy in the forked-off process' value of
4069  * MyCancelKey, so that it can transmit the key to the frontend.
4070  */
4072  {
4073  free(bn);
4074  ereport(LOG,
4075  (errcode(ERRCODE_INTERNAL_ERROR),
4076  errmsg("could not generate random cancel key")));
4077  return STATUS_ERROR;
4078  }
4079 
4080  bn->cancel_key = MyCancelKey;
4081 
4082  /* Pass down canAcceptConnections state */
4083  port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL);
4084  bn->dead_end = (port->canAcceptConnections != CAC_OK);
4085 
4086  /*
4087  * Unless it's a dead_end child, assign it a child slot number
4088  */
4089  if (!bn->dead_end)
4091  else
4092  bn->child_slot = 0;
4093 
4094  /* Hasn't asked to be notified about any bgworkers yet */
4095  bn->bgworker_notify = false;
4096 
4097 #ifdef EXEC_BACKEND
4098  pid = backend_forkexec(port);
4099 #else /* !EXEC_BACKEND */
4100  pid = fork_process();
4101  if (pid == 0) /* child */
4102  {
4103  free(bn);
4104 
4105  /* Detangle from postmaster */
4107 
4108  /* Close the postmaster's sockets */
4109  ClosePostmasterPorts(false);
4110 
4111  /* Perform additional initialization and collect startup packet */
4113 
4114  /*
4115  * Create a per-backend PGPROC struct in shared memory. We must do
4116  * this before we can use LWLocks. In the !EXEC_BACKEND case (here)
4117  * this could be delayed a bit further, but EXEC_BACKEND needs to do
4118  * stuff with LWLocks before PostgresMain(), so we do it here as well
4119  * for symmetry.
4120  */
4121  InitProcess();
4122 
4123  /* And run the backend */
4124  BackendRun(port);
4125  }
4126 #endif /* EXEC_BACKEND */
4127 
4128  if (pid < 0)
4129  {
4130  /* in parent, fork failed */
4131  int save_errno = errno;
4132 
4133  if (!bn->dead_end)
4135  free(bn);
4136  errno = save_errno;
4137  ereport(LOG,
4138  (errmsg("could not fork new process for connection: %m")));
4139  report_fork_failure_to_client(port, save_errno);
4140  return STATUS_ERROR;
4141  }
4142 
4143  /* in parent, successful fork */
4144  ereport(DEBUG2,
4145  (errmsg_internal("forked new backend, pid=%d socket=%d",
4146  (int) pid, (int) port->sock)));
4147 
4148  /*
4149  * Everything's been successful, it's safe to add this backend to our list
4150  * of backends.
4151  */
4152  bn->pid = pid;
4153  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4155 
4156 #ifdef EXEC_BACKEND
4157  if (!bn->dead_end)
4158  ShmemBackendArrayAdd(bn);
4159 #endif
4160 
4161  return STATUS_OK;
4162 }
#define STATUS_ERROR
Definition: c.h:1109
#define DEBUG2
Definition: elog.h:25
pid_t fork_process(void)
Definition: fork_process.c:29
#define free(a)
Definition: header.h:65
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:336
void InitPostmasterChild(void)
Definition: miscinit.c:95
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:284
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4388
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2608
static void BackendInitialize(Port *port)
Definition: postmaster.c:4208
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4173
static dlist_head BackendList
Definition: postmaster.c:188
void InitProcess(void)
Definition: proc.c:301
dlist_node elem
Definition: postmaster.c:185
pid_t pid
Definition: postmaster.c:179

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(), free, InitPostmasterChild(), InitProcess(), LOG, malloc, MyCancelKey, MyPMChildSlot, 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 5595 of file postmaster.c.

5596 {
5597  PG_SETMASK(&BlockSig);
5598 }

References BlockSig, and PG_SETMASK.

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5541 of file postmaster.c.

5542 {
5544 
5545  /* XXX is this the right errcode? */
5547  ereport(FATAL,
5548  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5549  errmsg("database connection requirement not indicated during registration")));
5550 
5551  InitPostgres(dbname, InvalidOid, /* database to connect to */
5552  username, InvalidOid, /* role to connect as */
5553  false, /* never honor session_preload_libraries */
5554  (flags & BGWORKER_BYPASS_ALLOWCONN) != 0, /* ignore datallowconn? */
5555  NULL); /* no out_dbname */
5556 
5557  /* it had better not gotten out of "init" mode yet */
5558  if (!IsInitProcessingMode())
5559  ereport(ERROR,
5560  (errmsg("invalid processing mode in background worker")));
5562 }
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:155
#define FATAL
Definition: elog.h:37
#define ERROR
Definition: elog.h:35
@ NormalProcessing
Definition: miscadmin.h:397
#define IsInitProcessingMode()
Definition: miscadmin.h:403
#define SetProcessingMode(mode)
Definition: miscadmin.h:408
const char * username
Definition: pgbench.c:305
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bool load_session_libraries, bool override_allow_connections, char *out_dbname)
Definition: postinit.c:712
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:194
char * dbname
Definition: streamutil.c:51

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

Referenced by ApplyLauncherMain().

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5568 of file postmaster.c.

5569 {
5571 
5572  /* XXX is this the right errcode? */
5574  ereport(FATAL,
5575  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5576  errmsg("database connection requirement not indicated during registration")));
5577 
5578  InitPostgres(NULL, dboid, /* database to connect to */
5579  NULL, useroid, /* role to connect as */
5580  false, /* never honor session_preload_libraries */
5581  (flags & BGWORKER_BYPASS_ALLOWCONN) != 0, /* ignore datallowconn? */
5582  NULL); /* no out_dbname */
5583 
5584  /* it had better not gotten out of "init" mode yet */
5585  if (!IsInitProcessingMode())
5586  ereport(ERROR,
5587  (errmsg("invalid processing mode in background worker")));
5589 }

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

Referenced by ApplyWorkerMain(), autoprewarm_database_main(), and ParallelWorkerMain().

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5729 of file postmaster.c.

5730 {
5731  switch (pmState)
5732  {
5733  case PM_NO_CHILDREN:
5734  case PM_WAIT_DEAD_END:
5735  case PM_SHUTDOWN_2:
5736  case PM_SHUTDOWN:
5737  case PM_WAIT_BACKENDS:
5738  case PM_STOP_BACKENDS:
5739  break;
5740 
5741  case PM_RUN:
5743  return true;
5744  /* fall through */
5745 
5746  case PM_HOT_STANDBY:
5748  return true;
5749  /* fall through */
5750 
5751  case PM_RECOVERY:
5752  case PM_STARTUP:
5753  case PM_INIT:
5755  return true;
5756  /* fall through */
5757  }
5758 
5759  return false;
5760 }
@ 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 2504 of file postmaster.c.

2505 {
2506  CAC_state result = CAC_OK;
2507 
2508  /*
2509  * Can't start backends when in startup/shutdown/inconsistent recovery
2510  * state. We treat autovac workers the same as user backends for this
2511  * purpose. However, bgworkers are excluded from this test; we expect
2512  * bgworker_should_start_now() decided whether the DB state allows them.
2513  */
2514  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2515  backend_type != BACKEND_TYPE_BGWORKER)
2516  {
2517  if (Shutdown > NoShutdown)
2518  return CAC_SHUTDOWN; /* shutdown is pending */
2519  else if (!FatalError && pmState == PM_STARTUP)
2520  return CAC_STARTUP; /* normal startup */
2521  else if (!FatalError && pmState == PM_RECOVERY)
2522  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2523  * state */
2524  else
2525  return CAC_RECOVERY; /* else must be crash recovery */
2526  }
2527 
2528  /*
2529  * "Smart shutdown" restrictions are applied only to normal connections,
2530  * not to autovac workers or bgworkers.
2531  */
2532  if (!connsAllowed && backend_type == BACKEND_TYPE_NORMAL)
2533  return CAC_SHUTDOWN; /* shutdown is pending */
2534 
2535  /*
2536  * Don't start too many children.
2537  *
2538  * We allow more connections here than we can have backends because some
2539  * might still be authenticating; they might fail auth, or some existing
2540  * backend might exit before the auth cycle is completed. The exact
2541  * MaxBackends limit is enforced when a new backend tries to join the
2542  * shared-inval backend array.
2543  *
2544  * The limit here must match the sizes of the per-child-process arrays;
2545  * see comments for MaxLivePostmasterChildren().
2546  */
2548  result = CAC_TOOMANY;
2549 
2550  return result;
2551 }
CAC_state
Definition: libpq-be.h:62
@ 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
static bool connsAllowed
Definition: postmaster.c:336
static int Shutdown
Definition: postmaster.c:266
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5531
#define NoShutdown
Definition: postmaster.c:261
static bool FatalError
Definition: postmaster.c:268
static int CountChildren(int target)
Definition: postmaster.c:5224

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:1211
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2383
int FreeFile(FILE *file)
Definition: fd.c:2581
char * DataDir
Definition: globals.c:66
const char * progname
Definition: main.c:45
#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:4986

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

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

Referenced by reaper().

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3230 of file postmaster.c.

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

Referenced by reaper().

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2608 of file postmaster.c.

2609 {
2610  int i;
2611 
2612 #ifndef WIN32
2613 
2614  /*
2615  * Close the write end of postmaster death watch pipe. It's important to
2616  * do this as early as possible, so that if postmaster dies, others won't
2617  * think that it's still running because we're holding the pipe open.
2618  */
2620  ereport(FATAL,
2622  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2624  /* Notify fd.c that we released one pipe FD. */
2626 #endif
2627 
2628  /*
2629  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2630  * so we don't call ReleaseExternalFD() here.
2631  */
2632  for (i = 0; i < MAXLISTEN; i++)
2633  {
2635  {
2638  }
2639  }
2640 
2641  /*
2642  * If using syslogger, close the read side of the pipe. We don't bother
2643  * tracking this in fd.c, either.
2644  */
2645  if (!am_syslogger)
2646  {
2647 #ifndef WIN32
2648  if (syslogPipe[0] >= 0)
2649  close(syslogPipe[0]);
2650  syslogPipe[0] = -1;
2651 #else
2652  if (syslogPipe[0])
2653  CloseHandle(syslogPipe[0]);
2654  syslogPipe[0] = 0;
2655 #endif
2656  }
2657 
2658 #ifdef USE_BONJOUR
2659  /* If using Bonjour, close the connection to the mDNS daemon */
2660  if (bonjour_sdref)
2661  close(DNSServiceRefSockFD(bonjour_sdref));
2662 #endif
2663 }
int errcode_for_file_access(void)
Definition: elog.c:718
void ReleaseExternalFD(void)
Definition: fd.c:1152
#define close(a)
Definition: win32.h:12
int i
Definition: isn.c:73
#define PGINVALID_SOCKET
Definition: port.h:31
int postmaster_alive_fds[2]
Definition: postmaster.c:553
#define MAXLISTEN
Definition: postmaster.c:219
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:220
#define POSTMASTER_FD_OWN
Definition: postmaster.h:46
void StreamClose(pgsocket sock)
Definition: pqcomm.c:826
int syslogPipe[2]
Definition: syslogger.c:117

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

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

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1478 of file postmaster.c.

1479 {
1480  int i;
1481 
1482  /*
1483  * First, explicitly close all the socket FDs. We used to just let this
1484  * happen implicitly at postmaster exit, but it's better to close them
1485  * before we remove the postmaster.pid lockfile; otherwise there's a race
1486  * condition if a new postmaster wants to re-use the TCP port number.
1487  */
1488  for (i = 0; i < MAXLISTEN; i++)
1489  {
1491  {
1494  }
1495  }
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:859

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

Referenced by PostmasterMain().

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2560 of file postmaster.c.

2561 {
2562  Port *port;
2563 
2564  if (!(port = (Port *) calloc(1, sizeof(Port))))
2565  {
2566  ereport(LOG,
2567  (errcode(ERRCODE_OUT_OF_MEMORY),
2568  errmsg("out of memory")));
2569  ExitPostmaster(1);
2570  }
2571 
2572  if (StreamConnection(serverFd, port) != STATUS_OK)
2573  {
2574  if (port->sock != PGINVALID_SOCKET)
2575  StreamClose(port->sock);
2576  ConnFree(port);
2577  return NULL;
2578  }
2579 
2580  return port;
2581 }
#define calloc(a, b)
Definition: header.h:55
static void ConnFree(Port *port)
Definition: postmaster.c:2591
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:692
Definition: libpq-be.h:146

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

2592 {
2593  free(port);
2594 }

References free, and port.

Referenced by ConnCreate(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5224 of file postmaster.c.

5225 {
5226  dlist_iter iter;
5227  int cnt = 0;
5228 
5229  dlist_foreach(iter, &BackendList)
5230  {
5231  Backend *bp = dlist_container(Backend, elem, iter.cur);
5232 
5233  if (bp->dead_end)
5234  continue;
5235 
5236  /*
5237  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5238  * it first and avoid touching shared memory for every child.
5239  */
5240  if (target != BACKEND_TYPE_ALL)
5241  {
5242  /*
5243  * Assign bkend_type for any recently announced WAL Sender
5244  * processes.
5245  */
5246  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5249 
5250  if (!(target & bp->bkend_type))
5251  continue;
5252  }
5253 
5254  cnt++;
5255  }
5256  return cnt;
5257 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:573
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:307
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
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 5487 of file postmaster.c.

5488 {
5489  FILE *fp;
5490  int i;
5491 
5492 #define OPTS_FILE "postmaster.opts"
5493 
5494  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5495  {
5496  ereport(LOG,
5498  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5499  return false;
5500  }
5501 
5502  fprintf(fp, "%s", fullprogname);
5503  for (i = 1; i < argc; i++)
5504  fprintf(fp, " \"%s\"", argv[i]);
5505  fputs("\n", fp);
5506 
5507  if (fclose(fp))
5508  {
5509  ereport(LOG,
5511  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5512  return false;
5513  }
5514 
5515  return true;
5516 }
#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 void DetermineSleepTime ( struct timeval *  timeout)
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  /* time left to abort; clamp to 0 in case it already expired */
1623  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1624  (time(NULL) - AbortStartTime);
1625  timeout->tv_sec = Max(timeout->tv_sec, 0);
1626  timeout->tv_usec = 0;
1627  }
1628  else
1629  {
1630  timeout->tv_sec = 60;
1631  timeout->tv_usec = 0;
1632  }
1633  return;
1634  }
1635 
1636  if (StartWorkerNeeded)
1637  {
1638  timeout->tv_sec = 0;
1639  timeout->tv_usec = 0;
1640  return;
1641  }
1642 
1643  if (HaveCrashedWorker)
1644  {
1645  slist_mutable_iter siter;
1646 
1647  /*
1648  * When there are crashed bgworkers, we sleep just long enough that
1649  * they are restarted when they request to be. Scan the list to
1650  * determine the minimum of all wakeup times according to most recent
1651  * crash time and requested restart interval.
1652  */
1654  {
1655  RegisteredBgWorker *rw;
1656  TimestampTz this_wakeup;
1657 
1658  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1659 
1660  if (rw->rw_crashed_at == 0)
1661  continue;
1662 
1664  || rw->rw_terminate)
1665  {
1666  ForgetBackgroundWorker(&siter);
1667  continue;
1668  }
1669 
1670  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1671  1000L * rw->rw_worker.bgw_restart_time);
1672  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1673  next_wakeup = this_wakeup;
1674  }
1675  }
1676 
1677  if (next_wakeup != 0)
1678  {
1679  long secs;
1680  int microsecs;
1681 
1683  &secs, &microsecs);
1684  timeout->tv_sec = secs;
1685  timeout->tv_usec = microsecs;
1686 
1687  /* Ensure we don't exceed one minute */
1688  if (timeout->tv_sec > 60)
1689  {
1690  timeout->tv_sec = 60;
1691  timeout->tv_usec = 0;
1692  }
1693  }
1694  else
1695  {
1696  timeout->tv_sec = 60;
1697  timeout->tv_usec = 0;
1698  }
1699 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1664
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:426
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
#define Max(x, y)
Definition: c.h:931
int64 TimestampTz
Definition: timestamp.h:39
static time_t AbortStartTime
Definition: postmaster.c:340
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:343
static volatile bool HaveCrashedWorker
Definition: postmaster.c:363
static volatile bool StartWorkerNeeded
Definition: postmaster.c:362
int bgw_restart_time
Definition: bgworker.h:95
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:84

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

Referenced by ServerLoop().

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5637 of file postmaster.c.

5638 {
5639  pid_t worker_pid;
5640 
5641  Assert(rw->rw_pid == 0);
5642 
5643  /*
5644  * Allocate and assign the Backend element. Note we must do this before
5645  * forking, so that we can handle failures (out of memory or child-process
5646  * slots) cleanly.
5647  *
5648  * Treat failure as though the worker had crashed. That way, the
5649  * postmaster will wait a bit before attempting to start it again; if we
5650  * tried again right away, most likely we'd find ourselves hitting the
5651  * same resource-exhaustion condition.
5652  */
5653  if (!assign_backendlist_entry(rw))
5654  {
5656  return false;
5657  }
5658 
5659  ereport(DEBUG1,
5660  (errmsg_internal("starting background worker process \"%s\"",
5661  rw->rw_worker.bgw_name)));
5662 
5663 #ifdef EXEC_BACKEND
5664  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5665 #else
5666  switch ((worker_pid = fork_process()))
5667 #endif
5668  {
5669  case -1:
5670  /* in postmaster, fork failed ... */
5671  ereport(LOG,
5672  (errmsg("could not fork worker process: %m")));
5673  /* undo what assign_backendlist_entry did */
5675  rw->rw_child_slot = 0;
5676  free(rw->rw_backend);
5677  rw->rw_backend = NULL;
5678  /* mark entry as crashed, so we'll try again later */
5680  break;
5681 
5682 #ifndef EXEC_BACKEND
5683  case 0:
5684  /* in postmaster child ... */
5686 
5687  /* Close the postmaster's sockets */
5688  ClosePostmasterPorts(false);
5689 
5690  /*
5691  * Before blowing away PostmasterContext, save this bgworker's
5692  * data where it can find it.
5693  */
5696  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5697 
5698  /* Release postmaster's working memory context */
5701  PostmasterContext = NULL;
5702 
5704 
5705  exit(1); /* should not get here */
5706  break;
5707 #endif
5708  default:
5709  /* in postmaster, fork successful ... */
5710  rw->rw_pid = worker_pid;
5711  rw->rw_backend->pid = rw->rw_pid;
5713  /* add new worker to lists of backends */
5715 #ifdef EXEC_BACKEND
5716  ShmemBackendArrayAdd(rw->rw_backend);
5717 #endif
5718  return true;
5719  }
5720 
5721  return false;
5722 }
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:461
void StartBackgroundWorker(void)
Definition: bgworker.c:741
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
MemoryContext PostmasterContext
Definition: mcxt.c:132
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5771
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91

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

Referenced by maybe_start_bgworkers().

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5195 of file postmaster.c.

5196 {
5197 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 4986 of file postmaster.c.

4987 {
4988 #ifdef HAVE_PTHREAD_IS_THREADED_NP
4989 
4990  /*
4991  * There is no known cause for a postmaster to become multithreaded after
4992  * startup. Recheck to account for the possibility of unknown causes.
4993  * This message uses LOG level, because an unclean shutdown at this point
4994  * would usually not look much different from a clean shutdown.
4995  */
4996  if (pthread_is_threaded_np() != 0)
4997  ereport(LOG,
4998  (errcode(ERRCODE_INTERNAL_ERROR),
4999  errmsg_internal("postmaster became multithreaded"),
5000  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5001 #endif
5002 
5003  /* should cleanup shared memory and kill all backends */
5004 
5005  /*
5006  * Not sure of the semantics here. When the Postmaster dies, should the
5007  * backends all be killed? probably not.
5008  *
5009  * MUST -- vadim 05-10-1999
5010  */
5011 
5012  proc_exit(status);
5013 }
int errdetail(const char *fmt,...)
Definition: elog.c:1039

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

Referenced by checkControlFile(), ConnCreate(), PostmasterMain(), PostmasterStateMachine(), reaper(), 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  * XXX is it worth similarly checking the share/ directory? If the lib/
1569  * directory is there, then share/ probably is too.
1570  */
1571 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:152
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:351
int errhint(const char *fmt,...)
Definition: elog.c:1153
int FreeDir(DIR *dir)
Definition: fd.c:2761
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2643
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
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().

◆ HandleChildCrash()

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

Definition at line 3409 of file postmaster.c.

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1947 of file postmaster.c.

1948 {
1949  int maxsock = -1;
1950  int i;
1951 
1952  FD_ZERO(rmask);
1953 
1954  for (i = 0; i < MAXLISTEN; i++)
1955  {
1956  int fd = ListenSocket[i];
1957 
1958  if (fd == PGINVALID_SOCKET)
1959  break;
1960  FD_SET(fd, rmask);
1961 
1962  if (fd > maxsock)
1963  maxsock = fd;
1964  }
1965 
1966  return maxsock + 1;
1967 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105

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

Referenced by ServerLoop().

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6430 of file postmaster.c.

6431 {
6432 #ifndef WIN32
6433 
6434  /*
6435  * Create a pipe. Postmaster holds the write end of the pipe open
6436  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6437  * the read file descriptor to select() to wake up in case postmaster
6438  * dies, or check for postmaster death with a (read() == 0). Children must
6439  * close the write end as soon as possible after forking, because EOF
6440  * won't be signaled in the read end until all processes have closed the
6441  * write fd. That is taken care of in ClosePostmasterPorts().
6442  */
6444  if (pipe(postmaster_alive_fds) < 0)
6445  ereport(FATAL,
6447  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6448 
6449  /* Notify fd.c that we've eaten two FDs for the pipe. */
6452 
6453  /*
6454  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6455  * call.
6456  */
6457  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6458  ereport(FATAL,
6460  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6461 #else
6462 
6463  /*
6464  * On Windows, we use a process handle for the same purpose.
6465  */
6466  if (DuplicateHandle(GetCurrentProcess(),
6467  GetCurrentProcess(),
6468  GetCurrentProcess(),
6469  &PostmasterHandle,
6470  0,
6471  TRUE,
6472  DUPLICATE_SAME_ACCESS) == 0)
6473  ereport(FATAL,
6474  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6475  GetLastError())));
6476 #endif /* WIN32 */
6477 }
int errcode_for_socket_access(void)
Definition: elog.c:789
pid_t PostmasterPid
Definition: globals.c:99
int MyProcPid
Definition: globals.c:44
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:45

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

2673 {
2674  MyProcPid = getpid();
2677 
2678  /*
2679  * Set a different global seed in every process. We want something
2680  * unpredictable, so if possible, use high-quality random bits for the
2681  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2682  */
2684  {
2685  uint64 rseed;
2686 
2687  /*
2688  * Since PIDs and timestamps tend to change more frequently in their
2689  * least significant bits, shift the timestamp left to allow a larger
2690  * total number of seeds in a given time period. Since that would
2691  * leave only 20 bits of the timestamp that cycle every ~1 second,
2692  * also mix in some higher bits.
2693  */
2694  rseed = ((uint64) MyProcPid) ^
2695  ((uint64) MyStartTimestamp << 12) ^
2696  ((uint64) MyStartTimestamp >> 20);
2697 
2699  }
2700 
2701  /*
2702  * Also make sure that we've set a good seed for random(3). Use of that
2703  * is deprecated in core Postgres, but extensions might use it.
2704  */
2705 #ifndef WIN32
2707 #endif
2708 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1762
#define unlikely(x)
Definition: c.h:295
TimestampTz MyStartTimestamp
Definition: globals.c:46
pg_time_t MyStartTime
Definition: globals.c:45
uint32 pg_prng_uint32(pg_prng_state *state)
Definition: pg_prng.c:185
void pg_prng_seed(pg_prng_state *state, uint64 seed)
Definition: pg_prng.c:83
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:28
#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 3584 of file postmaster.c.

3585 {
3586  /*
3587  * size of activity_buffer is arbitrary, but set equal to default
3588  * track_activity_query_size
3589  */
3590  char activity_buffer[1024];
3591  const char *activity = NULL;
3592 
3593  if (!EXIT_STATUS_0(exitstatus))
3594  activity = pgstat_get_crashed_backend_activity(pid,
3595  activity_buffer,
3596  sizeof(activity_buffer));
3597 
3598  if (WIFEXITED(exitstatus))
3599  ereport(lev,
3600 
3601  /*------
3602  translator: %s is a noun phrase describing a child process, such as
3603  "server process" */
3604  (errmsg("%s (PID %d) exited with exit code %d",
3605  procname, pid, WEXITSTATUS(exitstatus)),
3606  activity ? errdetail("Failed process was running: %s", activity) : 0));
3607  else if (WIFSIGNALED(exitstatus))
3608  {
3609 #if defined(WIN32)
3610  ereport(lev,
3611 
3612  /*------
3613  translator: %s is a noun phrase describing a child process, such as
3614  "server process" */
3615  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3616  procname, pid, WTERMSIG(exitstatus)),
3617  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3618  activity ? errdetail("Failed process was running: %s", activity) : 0));
3619 #else
3620  ereport(lev,
3621 
3622  /*------
3623  translator: %s is a noun phrase describing a child process, such as
3624  "server process" */
3625  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3626  procname, pid, WTERMSIG(exitstatus),
3627  pg_strsignal(WTERMSIG(exitstatus))),
3628  activity ? errdetail("Failed process was running: %s", activity) : 0));
3629 #endif
3630  }
3631  else
3632  ereport(lev,
3633 
3634  /*------
3635  translator: %s is a noun phrase describing a child process, such as
3636  "server process" */
3637  (errmsg("%s (PID %d) exited with unrecognized status %d",
3638  procname, pid, exitstatus),
3639  activity ? errdetail("Failed process was running: %s", activity) : 0));
3640 }
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:42
#define WIFEXITED(w)
Definition: win32_port.h:160
#define WIFSIGNALED(w)
Definition: win32_port.h:161
#define WTERMSIG(w)
Definition: win32_port.h:163
#define WEXITSTATUS(w)
Definition: win32_port.h:162

References ereport, errdetail(), errhint(), errmsg(), EXIT_STATUS_0, pg_strsignal(), pgstat_get_crashed_backend_activity(), WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

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

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5531 of file postmaster.c.

5532 {
5533  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5535 }
int autovacuum_max_workers
Definition: autovacuum.c:117
int MaxConnections
Definition: globals.c:137
int max_worker_processes
Definition: globals.c:138
int max_wal_senders
Definition: walsender.c:122

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

5836 {
5837 #define MAX_BGWORKERS_TO_LAUNCH 100
5838  int num_launched = 0;
5839  TimestampTz now = 0;
5840  slist_mutable_iter iter;
5841 
5842  /*
5843  * During crash recovery, we have no need to be called until the state
5844  * transition out of recovery.
5845  */
5846  if (FatalError)
5847  {
5848  StartWorkerNeeded = false;
5849  HaveCrashedWorker = false;
5850  return;
5851  }
5852 
5853  /* Don't need to be called again unless we find a reason for it below */
5854  StartWorkerNeeded = false;
5855  HaveCrashedWorker = false;
5856 
5858  {
5859  RegisteredBgWorker *rw;
5860 
5861  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5862 
5863  /* ignore if already running */
5864  if (rw->rw_pid != 0)
5865  continue;
5866 
5867  /* if marked for death, clean up and remove from list */
5868  if (rw->rw_terminate)
5869  {
5870  ForgetBackgroundWorker(&iter);
5871  continue;
5872  }
5873 
5874  /*
5875  * If this worker has crashed previously, maybe it needs to be
5876  * restarted (unless on registration it specified it doesn't want to
5877  * be restarted at all). Check how long ago did a crash last happen.
5878  * If the last crash is too recent, don't start it right away; let it
5879  * be restarted once enough time has passed.
5880  */
5881  if (rw->rw_crashed_at != 0)
5882  {
5884  {
5885  int notify_pid;
5886 
5887  notify_pid = rw->rw_worker.bgw_notify_pid;
5888 
5889  ForgetBackgroundWorker(&iter);
5890 
5891  /* Report worker is gone now. */
5892  if (notify_pid != 0)
5893  kill(notify_pid, SIGUSR1);
5894 
5895  continue;
5896  }
5897 
5898  /* read system time only when needed */
5899  if (now == 0)
5901 
5903  rw->rw_worker.bgw_restart_time * 1000))
5904  {
5905  /* Set flag to remember that we have workers to start later */
5906  HaveCrashedWorker = true;
5907  continue;
5908  }
5909  }
5910 
5912  {
5913  /* reset crash time before trying to start worker */
5914  rw->rw_crashed_at = 0;
5915 
5916  /*
5917  * Try to start the worker.
5918  *
5919  * On failure, give up processing workers for now, but set
5920  * StartWorkerNeeded so we'll come back here on the next iteration
5921  * of ServerLoop to try again. (We don't want to wait, because
5922  * there might be additional ready-to-run workers.) We could set
5923  * HaveCrashedWorker as well, since this worker is now marked
5924  * crashed, but there's no need because the next run of this
5925  * function will do that.
5926  */
5927  if (!do_start_bgworker(rw))
5928  {
5929  StartWorkerNeeded = true;
5930  return;
5931  }
5932 
5933  /*
5934  * If we've launched as many workers as allowed, quit, but have
5935  * ServerLoop call us again to look for additional ready-to-run
5936  * workers. There might not be any, but we'll find out the next
5937  * time we run.
5938  */
5939  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5940  {
5941  StartWorkerNeeded = true;
5942  return;
5943  }
5944  }
5945  }
5946 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1719
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1537
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5637
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5729
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:482
#define SIGUSR1
Definition: win32_port.h:188

References BackgroundWorkerList, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, bgworker_should_start_now(), slist_mutable_iter::cur, do_start_bgworker(), FatalError, ForgetBackgroundWorker(), GetCurrentTimestamp(), HaveCrashedWorker, kill, MAX_BGWORKERS_TO_LAUNCH, now(), RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, SIGUSR1, slist_container, slist_foreach_modify, StartWorkerNeeded, and TimestampDifferenceExceeds().

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

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5468 of file postmaster.c.

5469 {
5470  if (WalReceiverPID == 0 &&
5471  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5472  pmState == PM_HOT_STANDBY) &&
5474  {
5476  if (WalReceiverPID != 0)
5477  WalReceiverRequested = false;
5478  /* else leave the flag set, so we'll try again later */
5479  }
5480 }
#define SmartShutdown
Definition: postmaster.c:262
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:359
#define StartWalReceiver()
Definition: postmaster.c:541

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

Referenced by ServerLoop(), and sigusr1_handler().

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2783 of file postmaster.c.

2784 {
2785  int save_errno = errno;
2786 
2787  ereport(DEBUG2,
2788  (errmsg_internal("postmaster received signal %d",
2789  postgres_signal_arg)));
2790 
2791  switch (postgres_signal_arg)
2792  {
2793  case SIGTERM:
2794 
2795  /*
2796  * Smart Shutdown:
2797  *
2798  * Wait for children to end their work, then shut down.
2799  */
2800  if (Shutdown >= SmartShutdown)
2801  break;
2803  ereport(LOG,
2804  (errmsg("received smart shutdown request")));
2805 
2806  /* Report status */
2808 #ifdef USE_SYSTEMD
2809  sd_notify(0, "STOPPING=1");
2810 #endif
2811 
2812  /*
2813  * If we reached normal running, we go straight to waiting for
2814  * client backends to exit. If already in PM_STOP_BACKENDS or a
2815  * later state, do not change it.
2816  */
2817  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
2818  connsAllowed = false;
2819  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2820  {
2821  /* There should be no clients, so proceed to stop children */
2823  }
2824 
2825  /*
2826  * Now wait for online backup mode to end and backends to exit. If
2827  * that is already the case, PostmasterStateMachine will take the
2828  * next step.
2829  */
2831  break;
2832 
2833  case SIGINT:
2834 
2835  /*
2836  * Fast Shutdown:
2837  *
2838  * Abort all children with SIGTERM (rollback active transactions
2839  * and exit) and shut down when they are gone.
2840  */
2841  if (Shutdown >= FastShutdown)
2842  break;
2844  ereport(LOG,
2845  (errmsg("received fast shutdown request")));
2846 
2847  /* Report status */
2849 #ifdef USE_SYSTEMD
2850  sd_notify(0, "STOPPING=1");
2851 #endif
2852 
2853  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2854  {
2855  /* Just shut down background processes silently */
2857  }
2858  else if (pmState == PM_RUN ||
2860  {
2861  /* Report that we're about to zap live client sessions */
2862  ereport(LOG,
2863  (errmsg("aborting any active transactions")));
2865  }
2866 
2867  /*
2868  * PostmasterStateMachine will issue any necessary signals, or
2869  * take the next step if no child processes need to be killed.
2870  */
2872  break;
2873 
2874  case SIGQUIT:
2875 
2876  /*
2877  * Immediate Shutdown:
2878  *
2879  * abort all children with SIGQUIT, wait for them to exit,
2880  * terminate remaining ones with SIGKILL, then exit without
2881  * attempt to properly shut down the data base system.
2882  */
2883  if (Shutdown >= ImmediateShutdown)
2884  break;
2886  ereport(LOG,
2887  (errmsg("received immediate shutdown request")));
2888 
2889  /* Report status */
2891 #ifdef USE_SYSTEMD
2892  sd_notify(0, "STOPPING=1");
2893 #endif
2894 
2895  /* tell children to shut down ASAP */
2896  /* (note we don't apply send_abort_for_crash here) */
2900 
2901  /* set stopwatch for them to die */
2902  AbortStartTime = time(NULL);
2903 
2904  /*
2905  * Now wait for backends to exit. If there are none,
2906  * PostmasterStateMachine will take the next step.
2907  */
2909  break;
2910  }
2911 
2912  errno = save_errno;
2913 }
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1498
#define PM_STATUS_STOPPING
Definition: pidfile.h:52
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:44
@ PMQUIT_FOR_STOP
Definition: pmsignal.h:54
static void PostmasterStateMachine(void)
Definition: postmaster.c:3649
static void TerminateChildren(int signal)
Definition: postmaster.c:4017
#define FastShutdown
Definition: postmaster.c:263
#define SIGQUIT
Definition: win32_port.h:177

References AbortStartTime, AddToDataDirLockFile(), connsAllowed, DEBUG2, ereport, errmsg(), errmsg_internal(), FastShutdown, ImmediateShutdown, LOCK_FILE_LINE_PM_STATUS, LOG, 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 PostmasterMain().

◆ PostmasterMain()

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

Definition at line 563 of file postmaster.c.

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

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert(), autovac_init(), BgWriterPID, BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CheckpointerPID, CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), CreateSharedMemoryAndSemaphores(), DEBUG3, DestNone, dummy_handler(), enable_bonjour, EnableSSL, environ, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, FATAL, fprintf, get_stats_option_name(), GetConfigOption(), GetConfigOptionFlags(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), GUC_RUNTIME_COMPUTED, HbaFileName, i, InitializeGUCOptions(), InitializeMaxBackends(), InitializeShmemGUCs(), InitializeWalConsistencyChecking(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenSocket, load_hba(), load_ident(), LocalProcessControlFile(), LOCK_FILE_LINE_LISTEN_ADDR, LOCK_FILE_LINE_PM_STATUS, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, LOG_METAINFO_DATAFILE, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworkers(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, name, NIL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_SETMASK, PG_TEMP_FILES_DIR, PGC_POSTMASTER, PGC_S_ARGV, PGC_S_OVERRIDE, PGC_SUSET, PGINVALID_SOCKET, PgStartTime, pgwin32_signal_initialize(), PM_STARTUP, PM_STATUS_STARTING, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal_pm(), process_shared_preload_libraries(), process_shmem_requests(), progname, pstrdup(), reaper(), RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePgTempFilesInDir(), RemovePromoteSignalFiles(), ReservedBackends, 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, SIGHUP_handler(), SIGPIPE, SIGQUIT, SIGUSR1, sigusr1_handler(), SIGUSR2, SplitDirectoriesString(), SplitGUCList(), StartBackgroundWriter, StartCheckpointer, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror, success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 5954 of file postmaster.c.

5955 {
5956  dlist_iter iter;
5957  Backend *bp;
5958 
5959  dlist_foreach(iter, &BackendList)
5960  {
5961  bp = dlist_container(Backend, elem, iter.cur);
5962  if (bp->pid == pid)
5963  {
5964  bp->bgworker_notify = true;
5965  return true;
5966  }
5967  }
5968  return false;
5969 }

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

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

References AbortStartTime, Assert(), AutoVacPID, BACKEND_TYPE_ALL, BACKEND_TYPE_NORMAL, BACKEND_TYPE_WALSND, BackendList, BgWriterPID, CheckpointerPID, 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, StartCheckpointer, STARTUP_CRASHED, STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, WalReceiverPID, and WalWriterPID.

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

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5180 of file postmaster.c.

5181 {
5182  _exit(1);
5183 }

Referenced by BackendInitialize().

◆ processCancelRequest()

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

Definition at line 2438 of file postmaster.c.

2439 {
2440  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2441  int backendPID;
2442  int32 cancelAuthCode;
2443  Backend *bp;
2444 
2445 #ifndef EXEC_BACKEND
2446  dlist_iter iter;
2447 #else
2448  int i;
2449 #endif
2450 
2451  backendPID = (int) pg_ntoh32(canc->backendPID);
2452  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2453 
2454  /*
2455  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2456  * longer access the postmaster's own backend list, and must rely on the
2457  * duplicate array in shared memory.
2458  */
2459 #ifndef EXEC_BACKEND
2460  dlist_foreach(iter, &BackendList)
2461  {
2462  bp = dlist_container(Backend, elem, iter.cur);
2463 #else
2464  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2465  {
2466  bp = (Backend *) &ShmemBackendArray[i];
2467 #endif
2468  if (bp->pid == backendPID)
2469  {
2470  if (bp->cancel_key == cancelAuthCode)
2471  {
2472  /* Found a match; signal that backend to cancel current op */
2473  ereport(DEBUG2,
2474  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2475  backendPID)));
2476  signal_child(bp->pid, SIGINT);
2477  }
2478  else
2479  /* Right PID, wrong key: no way, Jose */
2480  ereport(LOG,
2481  (errmsg("wrong key in cancel request for process %d",
2482  backendPID)));
2483  return;
2484  }
2485 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2486  }
2487 #else
2488  }
2489 #endif
2490 
2491  /* No matching backend */
2492  ereport(LOG,
2493  (errmsg("PID %d in cancel request did not match any process",
2494  backendPID)));
2495 }
signed int int32
Definition: c.h:430
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
uint32 backendPID
Definition: pqcomm.h:144
uint32 cancelAuthCode
Definition: pqcomm.h:145

References BackendList, CancelRequestPacket::backendPID, bkend::cancel_key, CancelRequestPacket::cancelAuthCode, dlist_iter::cur, DEBUG2, dlist_container, dlist_foreach, ereport, errmsg(), errmsg_internal(), i, LOG, MaxLivePostmasterChildren(), pg_ntoh32, bkend::pid, and signal_child().

Referenced by ProcessStartupPacket().

◆ ProcessStartupPacket()

static int ProcessStartupPacket ( Port port,
bool  ssl_done,
bool  gss_done 
)
static

Definition at line 1989 of file postmaster.c.

1990 {
1991  int32 len;
1992  char *buf;
1993  ProtocolVersion proto;
1994  MemoryContext oldcontext;
1995 
1996  pq_startmsgread();
1997 
1998  /*
1999  * Grab the first byte of the length word separately, so that we can tell
2000  * whether we have no data at all or an incomplete packet. (This might
2001  * sound inefficient, but it's not really, because of buffering in
2002  * pqcomm.c.)
2003  */
2004  if (pq_getbytes((char *) &len, 1) == EOF)
2005  {
2006  /*
2007  * If we get no data at all, don't clutter the log with a complaint;
2008  * such cases often occur for legitimate reasons. An example is that
2009  * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
2010  * client didn't like our response, it'll probably just drop the
2011  * connection. Service-monitoring software also often just opens and
2012  * closes a connection without sending anything. (So do port
2013  * scanners, which may be less benign, but it's not really our job to
2014  * notice those.)
2015  */
2016  return STATUS_ERROR;
2017  }
2018 
2019  if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
2020  {
2021  /* Got a partial length word, so bleat about that */
2022  if (!ssl_done && !gss_done)
2024  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2025  errmsg("incomplete startup packet")));
2026  return STATUS_ERROR;
2027  }
2028 
2029  len = pg_ntoh32(len);
2030  len -= 4;
2031 
2032  if (len < (int32) sizeof(ProtocolVersion) ||
2034  {
2036  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2037  errmsg("invalid length of startup packet")));
2038  return STATUS_ERROR;
2039  }
2040 
2041  /*
2042  * Allocate space to hold the startup packet, plus one extra byte that's
2043  * initialized to be zero. This ensures we will have null termination of
2044  * all strings inside the packet.
2045  */
2046  buf = palloc(len + 1);
2047  buf[len] = '\0';
2048 
2049  if (pq_getbytes(buf, len) == EOF)
2050  {
2052  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2053  errmsg("incomplete startup packet")));
2054  return STATUS_ERROR;
2055  }
2056  pq_endmsgread();
2057 
2058  /*
2059  * The first field is either a protocol version number or a special
2060  * request code.
2061  */
2062  port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
2063 
2064  if (proto == CANCEL_REQUEST_CODE)
2065  {
2067  /* Not really an error, but we don't want to proceed further */
2068  return STATUS_ERROR;
2069  }
2070 
2071  if (proto == NEGOTIATE_SSL_CODE && !ssl_done)
2072  {
2073  char SSLok;
2074 
2075 #ifdef USE_SSL
2076  /* No SSL when disabled or on Unix sockets */
2077  if (!LoadedSSL || port->laddr.addr.ss_family == AF_UNIX)
2078  SSLok = 'N';
2079  else
2080  SSLok = 'S'; /* Support for SSL */
2081 #else
2082  SSLok = 'N'; /* No support for SSL */
2083 #endif
2084 
2085 retry1:
2086  if (send(port->sock, &SSLok, 1, 0) != 1)
2087  {
2088  if (errno == EINTR)
2089  goto retry1; /* if interrupted, just retry */
2092  errmsg("failed to send SSL negotiation response: %m")));
2093  return STATUS_ERROR; /* close the connection */
2094  }
2095 
2096 #ifdef USE_SSL
2097  if (SSLok == 'S' && secure_open_server(port) == -1)
2098  return STATUS_ERROR;
2099 #endif
2100 
2101  /*
2102  * At this point we should have no data already buffered. If we do,
2103  * it was received before we performed the SSL handshake, so it wasn't
2104  * encrypted and indeed may have been injected by a man-in-the-middle.
2105  * We report this case to the client.
2106  */
2107  if (pq_buffer_has_data())
2108  ereport(FATAL,
2109  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2110  errmsg("received unencrypted data after SSL request"),
2111  errdetail("This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.")));
2112 
2113  /*
2114  * regular startup packet, cancel, etc packet should follow, but not
2115  * another SSL negotiation request, and a GSS request should only
2116  * follow if SSL was rejected (client may negotiate in either order)
2117  */
2118  return ProcessStartupPacket(port, true, SSLok == 'S');
2119  }
2120  else if (proto == NEGOTIATE_GSS_CODE && !gss_done)
2121  {
2122  char GSSok = 'N';
2123 
2124 #ifdef ENABLE_GSS
2125  /* No GSSAPI encryption when on Unix socket */
2126  if (port->laddr.addr.ss_family != AF_UNIX)
2127  GSSok = 'G';
2128 #endif
2129 
2130  while (send(port->sock, &GSSok, 1, 0) != 1)
2131  {
2132  if (errno == EINTR)
2133  continue;
2136  errmsg("failed to send GSSAPI negotiation response: %m")));
2137  return STATUS_ERROR; /* close the connection */
2138  }
2139 
2140 #ifdef ENABLE_GSS
2141  if (GSSok == 'G' && secure_open_gssapi(port) == -1)
2142  return STATUS_ERROR;
2143 #endif
2144 
2145  /*
2146  * At this point we should have no data already buffered. If we do,
2147  * it was received before we performed the GSS handshake, so it wasn't
2148  * encrypted and indeed may have been injected by a man-in-the-middle.
2149  * We report this case to the client.
2150  */
2151  if (pq_buffer_has_data())
2152  ereport(FATAL,
2153  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2154  errmsg("received unencrypted data after GSSAPI encryption request"),
2155  errdetail("This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.")));
2156 
2157  /*
2158  * regular startup packet, cancel, etc packet should follow, but not
2159  * another GSS negotiation request, and an SSL request should only
2160  * follow if GSS was rejected (client may negotiate in either order)
2161  */
2162  return ProcessStartupPacket(port, GSSok == 'G', true);
2163  }
2164 
2165  /* Could add additional special packet types here */
2166 
2167  /*
2168  * Set FrontendProtocol now so that ereport() knows what format to send if
2169  * we fail during startup.
2170  */
2171  FrontendProtocol = proto;
2172 
2173  /* Check that the major protocol version is in range. */
2176  ereport(FATAL,
2177  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2178  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
2179  PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
2183 
2184  /*
2185  * Now fetch parameters out of startup packet and save them into the Port
2186  * structure. All data structures attached to the Port struct must be
2187  * allocated in TopMemoryContext so that they will remain available in a
2188  * running backend (even after PostmasterContext is destroyed). We need
2189  * not worry about leaking this storage on failure, since we aren't in the
2190  * postmaster process anymore.
2191  */
2193 
2194  /* Handle protocol version 3 startup packet */
2195  {
2196  int32 offset = sizeof(ProtocolVersion);
2197  List *unrecognized_protocol_options = NIL;
2198 
2199  /*
2200  * Scan packet body for name/option pairs. We can assume any string
2201  * beginning within the packet body is null-terminated, thanks to
2202  * zeroing extra byte above.
2203  */
2204  port->guc_options = NIL;
2205 
2206  while (offset < len)
2207  {
2208  char *nameptr = buf + offset;
2209  int32 valoffset;
2210  char *valptr;
2211 
2212  if (*nameptr == '\0')
2213  break; /* found packet terminator */
2214  valoffset = offset + strlen(nameptr) + 1;
2215  if (valoffset >= len)
2216  break; /* missing value, will complain below */
2217  valptr = buf + valoffset;
2218 
2219  if (strcmp(nameptr, "database") == 0)
2220  port->database_name = pstrdup(valptr);
2221  else if (strcmp(nameptr, "user") == 0)
2222  port->user_name = pstrdup(valptr);
2223  else if (strcmp(nameptr, "options") == 0)
2224  port->cmdline_options = pstrdup(valptr);
2225  else if (strcmp(nameptr, "replication") == 0)
2226  {
2227  /*
2228  * Due to backward compatibility concerns the replication
2229  * parameter is a hybrid beast which allows the value to be
2230  * either boolean or the string 'database'. The latter
2231  * connects to a specific database which is e.g. required for
2232  * logical decoding while.
2233  */
2234  if (strcmp(valptr, "database") == 0)
2235  {
2236  am_walsender = true;
2237  am_db_walsender = true;
2238  }
2239  else if (!parse_bool(valptr, &am_walsender))
2240  ereport(FATAL,
2241  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2242  errmsg("invalid value for parameter \"%s\": \"%s\"",
2243  "replication",
2244  valptr),
2245  errhint("Valid values are: \"false\", 0, \"true\", 1, \"database\".")));
2246  }
2247  else if (strncmp(nameptr, "_pq_.", 5) == 0)
2248  {
2249  /*
2250  * Any option beginning with _pq_. is reserved for use as a
2251  * protocol-level option, but at present no such options are
2252  * defined.
2253  */
2254  unrecognized_protocol_options =
2255  lappend(unrecognized_protocol_options, pstrdup(nameptr));
2256  }
2257  else
2258  {
2259  /* Assume it's a generic GUC option */
2260  port->guc_options = lappend(port->guc_options,
2261  pstrdup(nameptr));
2262  port->guc_options = lappend(port->guc_options,
2263  pstrdup(valptr));
2264 
2265  /*
2266  * Copy application_name to port if we come across it. This
2267  * is done so we can log the application_name in the
2268  * connection authorization message. Note that the GUC would
2269  * be used but we haven't gone through GUC setup yet.
2270  */
2271  if (strcmp(nameptr, "application_name") == 0)
2272  {
2273  port->application_name = pg_clean_ascii(valptr, 0);
2274  }
2275  }
2276  offset = valoffset + strlen(valptr) + 1;
2277  }
2278 
2279  /*
2280  * If we didn't find a packet terminator exactly at the end of the
2281  * given packet length, complain.
2282  */
2283  if (offset != len - 1)
2284  ereport(FATAL,
2285  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2286  errmsg("invalid startup packet layout: expected terminator as last byte")));
2287 
2288  /*
2289  * If the client requested a newer protocol version or if the client
2290  * requested any protocol options we didn't recognize, let them know
2291  * the newest minor protocol version we do support and the names of
2292  * any unrecognized options.
2293  */
2295  unrecognized_protocol_options != NIL)
2296  SendNegotiateProtocolVersion(unrecognized_protocol_options);
2297  }
2298 
2299  /* Check a user name was given. */
2300  if (port->user_name == NULL || port->user_name[0] == '\0')
2301  ereport(FATAL,
2302  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
2303  errmsg("no PostgreSQL user name specified in startup packet")));
2304 
2305  /* The database defaults to the user name. */
2306  if (port->database_name == NULL || port->database_name[0] == '\0')
2307  port->database_name = pstrdup(port->user_name);
2308 
2309  if (Db_user_namespace)
2310  {
2311  /*
2312  * If user@, it is a global user, remove '@'. We only want to do this
2313  * if there is an '@' at the end and no earlier in the user string or
2314  * they may fake as a local user of another database attaching to this
2315  * database.
2316  */
2317  if (strchr(port->user_name, '@') ==
2318  port->user_name + strlen(port->user_name) - 1)
2319  *strchr(port->user_name, '@') = '\0';
2320  else
2321  {
2322  /* Append '@' and dbname */
2323  port->user_name = psprintf("%s@%s", port->user_name, port->database_name);
2324  }
2325  }
2326 
2327  /*
2328  * Truncate given database and user names to length of a Postgres name.
2329  * This avoids lookup failures when overlength names are given.
2330  */
2331  if (strlen(port->database_name) >= NAMEDATALEN)
2332  port->database_name[NAMEDATALEN - 1] = '\0';
2333  if (strlen(port->user_name) >= NAMEDATALEN)
2334  port->user_name[NAMEDATALEN - 1] = '\0';
2335 
2336  if (am_walsender)
2338  else
2340 
2341  /*
2342  * Normal walsender backends, e.g. for streaming replication, are not
2343  * connected to a particular database. But walsenders used for logical
2344  * replication need to connect to a specific database. We allow streaming
2345  * replication commands to be issued even if connected to a database as it
2346  * can make sense to first make a basebackup and then stream changes
2347  * starting from that.
2348  */
2349  if (am_walsender && !am_db_walsender)
2350  port->database_name[0] = '\0';
2351 
2352  /*
2353  * Done putting stuff in TopMemoryContext.
2354  */
2355  MemoryContextSwitchTo(oldcontext);
2356 
2357  /*
2358  * If we're going to reject the connection due to database state, say so
2359  * now instead of wasting cycles on an authentication exchange. (This also
2360  * allows a pg_ping utility to be written.)
2361  */
2362  switch (port->canAcceptConnections)
2363  {
2364  case CAC_STARTUP:
2365  ereport(FATAL,
2367  errmsg("the database system is starting up")));
2368  break;
2369  case CAC_NOTCONSISTENT:
2370  if (EnableHotStandby)
2371  ereport(FATAL,
2373  errmsg("the database system is not yet accepting connections"),
2374  errdetail("Consistent recovery state has not been yet reached.")));
2375  else
2376  ereport(FATAL,
2378  errmsg("the database system is not accepting connections"),
2379  errdetail("Hot standby mode is disabled.")));
2380  break;
2381  case CAC_SHUTDOWN:
2382  ereport(FATAL,
2384  errmsg("the database system is shutting down")));
2385  break;
2386  case CAC_RECOVERY:
2387  ereport(FATAL,
2389  errmsg("the database system is in recovery mode")));
2390  break;
2391  case CAC_TOOMANY:
2392  ereport(FATAL,
2393  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
2394  errmsg("sorry, too many clients already")));
2395  break;
2396  case CAC_OK:
2397  break;
2398  }
2399 
2400  return STATUS_OK;
2401 }
ssize_t secure_open_gssapi(Port *port)
int secure_open_server(Port *port)
Definition: be-secure.c:113
bool parse_bool(const char *value, bool *result)
Definition: bool.c:30
#define COMMERROR
Definition: elog.h:29
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:93
ProtocolVersion FrontendProtocol
Definition: globals.c:28
List * lappend(List *list, void *datum)
Definition: list.c:338
void * palloc(Size size)
Definition: mcxt.c:1199
@ B_BACKEND
Definition: miscadmin.h:322
BackendType MyBackendType
Definition: miscinit.c:63
#define NAMEDATALEN
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
bool Db_user_namespace
Definition: postmaster.c:230
static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options)
Definition: postmaster.c:2417
static void processCancelRequest(Port *port, void *pkt)
Definition: postmaster.c:2438
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1064
void pq_endmsgread(void)
Definition: pqcomm.c:1164
bool pq_buffer_has_data(void)
Definition: pqcomm.c:1127
void pq_startmsgread(void)
Definition: pqcomm.c:1140
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:75
#define PG_PROTOCOL_EARLIEST
Definition: pqcomm.h:84
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:138
#define MAX_STARTUP_PACKET_LENGTH
Definition: pqcomm.h:108
#define PG_PROTOCOL_LATEST
Definition: pqcomm.h:85
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:154
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:153
uint32 ProtocolVersion
Definition: pqcomm.h:87
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:76
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
char * pg_clean_ascii(const char *str, int alloc_flags)
Definition: string.c:86
bool am_db_walsender
Definition: walsender.c:119
#define EINTR
Definition: win32_port.h:369
#define send(s, buf, len, flags)
Definition: win32_port.h:494
bool EnableHotStandby
Definition: xlog.c:124

References am_db_walsender, am_walsender, B_BACKEND, B_WAL_SENDER, buf, CAC_NOTCONSISTENT, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_TOOMANY, CANCEL_REQUEST_CODE, COMMERROR, Db_user_namespace, EINTR, EnableHotStandby, ereport, errcode(), ERRCODE_CANNOT_CONNECT_NOW, errcode_for_socket_access(), errdetail(), errhint(), errmsg(), FATAL, FrontendProtocol, lappend(), len, MAX_STARTUP_PACKET_LENGTH, MemoryContextSwitchTo(), MyBackendType, NAMEDATALEN, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, NIL, palloc(), parse_bool(), pg_clean_ascii(), pg_ntoh32, PG_PROTOCOL_EARLIEST, PG_PROTOCOL_LATEST, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, port, pq_buffer_has_data(), pq_endmsgread(), pq_getbytes(), pq_startmsgread(), processCancelRequest(), psprintf(), pstrdup(), secure_open_gssapi(), secure_open_server(), send, SendNegotiateProtocolVersion(), STATUS_ERROR, STATUS_OK, and TopMemoryContext.

Referenced by BackendInitialize().

◆ RandomCancelKey()

static bool RandomCancelKey ( int32 cancel_key)
static

Definition at line 5214 of file postmaster.c.

5215 {
5216  return pg_strong_random(cancel_key, sizeof(int32));
5217 }
bool pg_strong_random(void *buf, size_t len)

References pg_strong_random().

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

◆ reaper()

static void reaper ( SIGNAL_ARGS  )
static

Definition at line 2919 of file postmaster.c.

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

References _, AbortStartTime, AddToDataDirLockFile(), Assert(), AutoVacPID, AutoVacuumingActive(), 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(), NoShutdown, 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, SmartShutdown, StartArchiver, StartAutoVacLauncher(), StartBackgroundWriter, StartCheckpointer, STARTUP_CRASHED, STARTUP_NOT_RUNNING, STARTUP_SIGNALED, StartupPID, StartupStatus, StartWalWriter, SysLogger_Start(), SysLoggerPID, TerminateChildren(), WalReceiverPID, and WalWriterPID.

Referenced by PostmasterMain().

◆ report_fork_failure_to_client()

static void report_fork_failure_to_client ( Port port,
int  errnum 
)
static

Definition at line 4173 of file postmaster.c.

4174 {
4175  char buffer[1000];
4176  int rc;
4177 
4178  /* Format the error message packet (always V2 protocol) */
4179  snprintf(buffer, sizeof(buffer), "E%s%s\n",
4180  _("could not fork new process for connection: "),
4181  strerror(errnum));
4182 
4183  /* Set port to non-blocking. Don't do send() if this fails */
4184  if (!pg_set_noblock(port->sock))
4185  return;
4186 
4187  /* We'll retry after EINTR, but ignore all other failures */
4188  do
4189  {
4190  rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
4191  } while (rc < 0 && errno == EINTR);
4192 }
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25

References _, EINTR, pg_set_noblock(), port, send, snprintf, and strerror.

Referenced by BackendStartup().

◆ SendNegotiateProtocolVersion()

static void SendNegotiateProtocolVersion ( List unrecognized_protocol_options)
static