PostgreSQL Source Code  git master
postmaster.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <sys/param.h>
#include <netdb.h>
#include <limits.h>
#include "access/transam.h"
#include "access/xlog.h"
#include "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
}
 
enum  ConnsAllowedState { ALLOW_ALL_CONNS , ALLOW_SUPERUSER_CONNS , ALLOW_NO_CONNS }
 

Functions

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

Variables

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

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

Definition at line 151 of file postmaster.c.

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 148 of file postmaster.c.

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 150 of file postmaster.c.

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

Definition at line 147 of file postmaster.c.

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 149 of file postmaster.c.

◆ EXIT_STATUS_0

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

Definition at line 563 of file postmaster.c.

◆ EXIT_STATUS_1

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

Definition at line 564 of file postmaster.c.

◆ EXIT_STATUS_3

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

Definition at line 565 of file postmaster.c.

◆ FastShutdown

#define FastShutdown   2

Definition at line 274 of file postmaster.c.

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 275 of file postmaster.c.

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

◆ MAXLISTEN

#define MAXLISTEN   64

Definition at line 221 of file postmaster.c.

◆ NoShutdown

#define NoShutdown   0

Definition at line 272 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:328
@ PM_HOT_STANDBY
Definition: postmaster.c:327
@ PM_RECOVERY
Definition: postmaster.c:326
static PMState pmState
Definition: postmaster.c:339
#define XLogArchivingActive()
Definition: xlog.h:153
#define XLogArchivingAlways()
Definition: xlog.h:156

Definition at line 448 of file postmaster.c.

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 361 of file postmaster.c.

◆ SignalChildren

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

Definition at line 431 of file postmaster.c.

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 273 of file postmaster.c.

◆ StartArchiver

#define StartArchiver ( )    StartChildProcess(ArchiverProcess)

Definition at line 556 of file postmaster.c.

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 557 of file postmaster.c.

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 558 of file postmaster.c.

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 555 of file postmaster.c.

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 560 of file postmaster.c.

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 559 of file postmaster.c.

Typedef Documentation

◆ Backend

typedef struct bkend Backend

Enumeration Type Documentation

◆ ConnsAllowedState

Enumerator
ALLOW_ALL_CONNS 
ALLOW_SUPERUSER_CONNS 
ALLOW_NO_CONNS 

Definition at line 347 of file postmaster.c.

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

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 261 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5986 of file postmaster.c.

5987 {
5988  Backend *bn;
5989 
5990  /*
5991  * Check that database state allows another connection. Currently the
5992  * only possible failure is CAC_TOOMANY, so we just log an error message
5993  * based on that rather than checking the error code precisely.
5994  */
5996  {
5997  ereport(LOG,
5998  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
5999  errmsg("no slot available for new worker process")));
6000  return false;
6001  }
6002 
6003  /*
6004  * Compute the cancel key that will be assigned to this session. We
6005  * probably don't need cancel keys for background workers, but we'd better
6006  * have something random in the field to prevent unfriendly people from
6007  * sending cancels to them.
6008  */
6010  {
6011  ereport(LOG,
6012  (errcode(ERRCODE_INTERNAL_ERROR),
6013  errmsg("could not generate random cancel key")));
6014  return false;
6015  }
6016 
6017  bn = malloc(sizeof(Backend));
6018  if (bn == NULL)
6019  {
6020  ereport(LOG,
6021  (errcode(ERRCODE_OUT_OF_MEMORY),
6022  errmsg("out of memory")));
6023  return false;
6024  }
6025 
6026  bn->cancel_key = MyCancelKey;
6029  bn->dead_end = false;
6030  bn->bgworker_notify = false;
6031 
6032  rw->rw_backend = bn;
6033  rw->rw_child_slot = bn->child_slot;
6034 
6035  return true;
6036 }
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define LOG
Definition: elog.h:25
#define ereport(elevel,...)
Definition: elog.h:143
int32 MyCancelKey
Definition: globals.c:47
int MyPMChildSlot
Definition: globals.c:48
#define malloc(a)
Definition: header.h:50
@ CAC_OK
Definition: libpq-be.h:73
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:219
static CAC_state canAcceptConnections(int backend_type)
Definition: postmaster.c:2524
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:150
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5436
struct bkend * rw_backend
bool bgworker_notify
Definition: postmaster.c:186
int bkend_type
Definition: postmaster.c:184
bool dead_end
Definition: postmaster.c:185
int32 cancel_key
Definition: postmaster.c:182
int child_slot
Definition: postmaster.c:183

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

4407 {
4408  int status;
4409  int ret;
4410  char remote_host[NI_MAXHOST];
4411  char remote_port[NI_MAXSERV];
4412  StringInfoData ps_data;
4413 
4414  /* Save port etc. for ps status */
4415  MyProcPort = port;
4416 
4417  /* Tell fd.c about the long-lived FD associated with the port */
4419 
4420  /*
4421  * PreAuthDelay is a debugging aid for investigating problems in the
4422  * authentication cycle: it can be set in postgresql.conf to allow time to
4423  * attach to the newly-forked backend with a debugger. (See also
4424  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4425  * is not honored until after authentication.)
4426  */
4427  if (PreAuthDelay > 0)
4428  pg_usleep(PreAuthDelay * 1000000L);
4429 
4430  /* This flag will remain set until InitPostgres finishes authentication */
4431  ClientAuthInProgress = true; /* limit visibility of log messages */
4432 
4433  /* set these to empty in case they are needed before we set them up */
4434  port->remote_host = "";
4435  port->remote_port = "";
4436 
4437  /*
4438  * Initialize libpq and enable reporting of ereport errors to the client.
4439  * Must do this now because authentication uses libpq to send messages.
4440  */
4441  pq_init(); /* initialize libpq to talk to client */
4442  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4443 
4444  /*
4445  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
4446  * to collect the startup packet; while SIGQUIT results in _exit(2).
4447  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
4448  * cleanly if a buggy client fails to send the packet promptly.
4449  *
4450  * Exiting with _exit(1) is only possible because we have not yet touched
4451  * shared memory; therefore no outside-the-process state needs to get
4452  * cleaned up.
4453  */
4455  /* SIGQUIT handler was already set up by InitPostmasterChild */
4456  InitializeTimeouts(); /* establishes SIGALRM handler */
4458 
4459  /*
4460  * Get the remote host name and port for logging and status display.
4461  */
4462  remote_host[0] = '\0';
4463  remote_port[0] = '\0';
4464  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4465  remote_host, sizeof(remote_host),
4466  remote_port, sizeof(remote_port),
4467  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4468  ereport(WARNING,
4469  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4470  gai_strerror(ret))));
4471 
4472  /*
4473  * Save remote_host and remote_port in port structure (after this, they
4474  * will appear in log_line_prefix data for log messages).
4475  */
4476  port->remote_host = strdup(remote_host);
4477  port->remote_port = strdup(remote_port);
4478 
4479  /* And now we can issue the Log_connections message, if wanted */
4480  if (Log_connections)
4481  {
4482  if (remote_port[0])
4483  ereport(LOG,
4484  (errmsg("connection received: host=%s port=%s",
4485  remote_host,
4486  remote_port)));
4487  else
4488  ereport(LOG,
4489  (errmsg("connection received: host=%s",
4490  remote_host)));
4491  }
4492 
4493  /*
4494  * If we did a reverse lookup to name, we might as well save the results
4495  * rather than possibly repeating the lookup during authentication.
4496  *
4497  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4498  * get nothing useful for a client without an rDNS entry. Therefore, we
4499  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4500  * it into remote_hostname if so. (This test is conservative and might
4501  * sometimes classify a hostname as numeric, but an error in that
4502  * direction is safe; it only results in a possible extra lookup.)
4503  */
4504  if (log_hostname &&
4505  ret == 0 &&
4506  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4507  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4508  port->remote_hostname = strdup(remote_host);
4509 
4510  /*
4511  * Ready to begin client interaction. We will give up and _exit(1) after
4512  * a time delay, so that a broken client can't hog a connection
4513  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4514  * against the time limit.
4515  *
4516  * Note: AuthenticationTimeout is applied here while waiting for the
4517  * startup packet, and then again in InitPostgres for the duration of any
4518  * authentication operations. So a hostile client could tie up the
4519  * process for nearly twice AuthenticationTimeout before we kick him off.
4520  *
4521  * Note: because PostgresMain will call InitializeTimeouts again, the
4522  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4523  * since we never use it again after this function.
4524  */
4527 
4528  /*
4529  * Receive the startup packet (which might turn out to be a cancel request
4530  * packet).
4531  */
4532  status = ProcessStartupPacket(port, false, false);
4533 
4534  /*
4535  * Disable the timeout, and prevent SIGTERM again.
4536  */
4538  PG_SETMASK(&BlockSig);
4539 
4540  /*
4541  * As a safety check that nothing in startup has yet performed
4542  * shared-memory modifications that would need to be undone if we had
4543  * exited through SIGTERM or timeout above, check that no on_shmem_exit
4544  * handlers have been registered yet. (This isn't terribly bulletproof,
4545  * since someone might misuse an on_proc_exit handler for shmem cleanup,
4546  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
4547  * handlers unfortunately, since pq_init() already registered one.)
4548  */
4550 
4551  /*
4552  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4553  * already did any appropriate error reporting.
4554  */
4555  if (status != STATUS_OK)
4556  proc_exit(0);
4557 
4558  /*
4559  * Now that we have the user and database name, we can set the process
4560  * title for ps. It's good to do this as early as possible in startup.
4561  */
4562  initStringInfo(&ps_data);
4563  if (am_walsender)
4565  appendStringInfo(&ps_data, "%s ", port->user_name);
4566  if (!am_walsender)
4567  appendStringInfo(&ps_data, "%s ", port->database_name);
4568  appendStringInfo(&ps_data, "%s", port->remote_host);
4569  if (port->remote_port[0] != '\0')
4570  appendStringInfo(&ps_data, "(%s)", port->remote_port);
4571 
4572  init_ps_display(ps_data.data);
4573  pfree(ps_data.data);
4574 
4575  set_ps_display("initializing");
4576 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
#define STATUS_OK
Definition: c.h:1167
@ DestRemote
Definition: dest.h:91
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define WARNING
Definition: elog.h:30
void ReserveExternalFD(void)
Definition: fd.c:1212
#define gai_strerror
Definition: getaddrinfo.h:146
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define NI_MAXSERV
Definition: getaddrinfo.h:91
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
struct Port * MyProcPort
Definition: globals.c:46
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
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:1169
@ B_WAL_SENDER
Definition: miscadmin.h:334
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:249
static int port
Definition: pg_regress.c:92
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
CommandDest whereToSendOutput
Definition: postgres.c:93
int PreAuthDelay
Definition: postmaster.c:237
bool log_hostname
Definition: postmaster.c:240
static void process_startup_packet_die(SIGNAL_ARGS)
Definition: postmaster.c:5402
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5426
bool Log_connections
Definition: postmaster.c:241
bool ClientAuthInProgress
Definition: postmaster.c:365
int AuthenticationTimeout
Definition: postmaster.c:238
static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
Definition: postmaster.c:2002
void pq_init(void)
Definition: pqcomm.c:176
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void set_ps_display(const char *activity)
Definition: ps_status.c:349
void pg_usleep(long microsec)
Definition: signal.c:53
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:551
void InitializeTimeouts(void)
Definition: timeout.c:461
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:676
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:496
@ STARTUP_PACKET_TIMEOUT
Definition: timeout.h:26
bool am_walsender
Definition: walsender.c:115

References am_walsender, appendStringInfo(), 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(), gai_strerror, GetBackendTypeDesc(), init_ps_display(), InitializeTimeouts(), initStringInfo(), LOG, Log_connections, log_hostname, MyProcPort, NI_MAXHOST, NI_MAXSERV, NI_NUMERICHOST, NI_NUMERICSERV, pfree(), pg_getnameinfo_all(), PG_SETMASK, pg_usleep(), port, pq_init(), pqsignal(), PreAuthDelay, proc_exit(), process_startup_packet_die(), ProcessStartupPacket(), 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 4586 of file postmaster.c.

4587 {
4588  /*
4589  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4590  * just yet, though, because InitPostgres will need the HBA data.)
4591  */
4593 
4594  PostgresMain(port->database_name, port->user_name);
4595 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4016

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

Referenced by BackendStartup().

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4245 of file postmaster.c.

4246 {
4247  Backend *bn; /* for backend cleanup */
4248  pid_t pid;
4249 
4250  /*
4251  * Create backend data structure. Better before the fork() so we can
4252  * handle failure cleanly.
4253  */
4254  bn = (Backend *) malloc(sizeof(Backend));
4255  if (!bn)
4256  {
4257  ereport(LOG,
4258  (errcode(ERRCODE_OUT_OF_MEMORY),
4259  errmsg("out of memory")));
4260  return STATUS_ERROR;
4261  }
4262 
4263  /*
4264  * Compute the cancel key that will be assigned to this backend. The
4265  * backend will have its own copy in the forked-off process' value of
4266  * MyCancelKey, so that it can transmit the key to the frontend.
4267  */
4269  {
4270  free(bn);
4271  ereport(LOG,
4272  (errcode(ERRCODE_INTERNAL_ERROR),
4273  errmsg("could not generate random cancel key")));
4274  return STATUS_ERROR;
4275  }
4276 
4277  bn->cancel_key = MyCancelKey;
4278 
4279  /* Pass down canAcceptConnections state */
4280  port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL);
4281  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4282  port->canAcceptConnections != CAC_SUPERUSER);
4283 
4284  /*
4285  * Unless it's a dead_end child, assign it a child slot number
4286  */
4287  if (!bn->dead_end)
4289  else
4290  bn->child_slot = 0;
4291 
4292  /* Hasn't asked to be notified about any bgworkers yet */
4293  bn->bgworker_notify = false;
4294 
4295 #ifdef EXEC_BACKEND
4296  pid = backend_forkexec(port);
4297 #else /* !EXEC_BACKEND */
4298  pid = fork_process();
4299  if (pid == 0) /* child */
4300  {
4301  free(bn);
4302 
4303  /* Detangle from postmaster */
4305 
4306  /* Close the postmaster's sockets */
4307  ClosePostmasterPorts(false);
4308 
4309  /* Perform additional initialization and collect startup packet */
4311 
4312  /*
4313  * Create a per-backend PGPROC struct in shared memory. We must do
4314  * this before we can use LWLocks. In the !EXEC_BACKEND case (here)
4315  * this could be delayed a bit further, but EXEC_BACKEND needs to do
4316  * stuff with LWLocks before PostgresMain(), so we do it here as well
4317  * for symmetry.
4318  */
4319  InitProcess();
4320 
4321  /* And run the backend */
4322  BackendRun(port);
4323  }
4324 #endif /* EXEC_BACKEND */
4325 
4326  if (pid < 0)
4327  {
4328  /* in parent, fork failed */
4329  int save_errno = errno;
4330 
4331  if (!bn->dead_end)
4333  free(bn);
4334  errno = save_errno;
4335  ereport(LOG,
4336  (errmsg("could not fork new process for connection: %m")));
4337  report_fork_failure_to_client(port, save_errno);
4338  return STATUS_ERROR;
4339  }
4340 
4341  /* in parent, successful fork */
4342  ereport(DEBUG2,
4343  (errmsg_internal("forked new backend, pid=%d socket=%d",
4344  (int) pid, (int) port->sock)));
4345 
4346  /*
4347  * Everything's been successful, it's safe to add this backend to our list
4348  * of backends.
4349  */
4350  bn->pid = pid;
4351  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4353 
4354 #ifdef EXEC_BACKEND
4355  if (!bn->dead_end)
4356  ShmemBackendArrayAdd(bn);
4357 #endif
4358 
4359  return STATUS_OK;
4360 }
#define STATUS_ERROR
Definition: c.h:1168
#define DEBUG2
Definition: elog.h:23
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:300
@ CAC_SUPERUSER
Definition: libpq-be.h:79
void InitPostmasterChild(void)
Definition: miscinit.c:94
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:253
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:147
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4586
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2637
static void BackendInitialize(Port *port)
Definition: postmaster.c:4406
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4371
static dlist_head BackendList
Definition: postmaster.c:190
void InitProcess(void)
Definition: proc.c:301
dlist_node elem
Definition: postmaster.c:187
pid_t pid
Definition: postmaster.c:181

References AssignPostmasterChildSlot(), BACKEND_TYPE_NORMAL, BackendInitialize(), BackendList, BackendRun(), bkend::bgworker_notify, bkend::bkend_type, CAC_OK, CAC_SUPERUSER, 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 5809 of file postmaster.c.

5810 {
5811  PG_SETMASK(&BlockSig);
5812 }

References BlockSig, and PG_SETMASK.

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5763 of file postmaster.c.

5764 {
5766 
5767  /* XXX is this the right errcode? */
5769  ereport(FATAL,
5770  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5771  errmsg("database connection requirement not indicated during registration")));
5772 
5774 
5775  /* it had better not gotten out of "init" mode yet */
5776  if (!IsInitProcessingMode())
5777  ereport(ERROR,
5778  (errmsg("invalid processing mode in background worker")));
5780 }
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:155
#define FATAL
Definition: elog.h:35
#define ERROR
Definition: elog.h:33
@ NormalProcessing
Definition: miscadmin.h:401
#define IsInitProcessingMode()
Definition: miscadmin.h:407
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
const char * username
Definition: pgbench.c:282
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:578
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:196
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 5786 of file postmaster.c.

5787 {
5789 
5790  /* XXX is this the right errcode? */
5792  ereport(FATAL,
5793  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5794  errmsg("database connection requirement not indicated during registration")));
5795 
5796  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5797 
5798  /* it had better not gotten out of "init" mode yet */
5799  if (!IsInitProcessingMode())
5800  ereport(ERROR,
5801  (errmsg("invalid processing mode in background worker")));
5803 }

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

5944 {
5945  switch (pmState)
5946  {
5947  case PM_NO_CHILDREN:
5948  case PM_WAIT_DEAD_END:
5949  case PM_SHUTDOWN_2:
5950  case PM_SHUTDOWN:
5951  case PM_WAIT_BACKENDS:
5952  case PM_STOP_BACKENDS:
5953  break;
5954 
5955  case PM_RUN:
5957  return true;
5958  /* fall through */
5959 
5960  case PM_HOT_STANDBY:
5962  return true;
5963  /* fall through */
5964 
5965  case PM_RECOVERY:
5966  case PM_STARTUP:
5967  case PM_INIT:
5969  return true;
5970  /* fall through */
5971 
5972  }
5973 
5974  return false;
5975 }
@ 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:99

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

2525 {
2526  CAC_state result = CAC_OK;
2527 
2528  /*
2529  * Can't start backends when in startup/shutdown/inconsistent recovery
2530  * state. We treat autovac workers the same as user backends for this
2531  * purpose. However, bgworkers are excluded from this test; we expect
2532  * bgworker_should_start_now() decided whether the DB state allows them.
2533  */
2534  if (pmState != PM_RUN && pmState != PM_HOT_STANDBY &&
2535  backend_type != BACKEND_TYPE_BGWORKER)
2536  {
2537  if (Shutdown > NoShutdown)
2538  return CAC_SHUTDOWN; /* shutdown is pending */
2539  else if (!FatalError && pmState == PM_STARTUP)
2540  return CAC_STARTUP; /* normal startup */
2541  else if (!FatalError && pmState == PM_RECOVERY)
2542  return CAC_NOTCONSISTENT; /* not yet at consistent recovery
2543  * state */
2544  else
2545  return CAC_RECOVERY; /* else must be crash recovery */
2546  }
2547 
2548  /*
2549  * "Smart shutdown" restrictions are applied only to normal connections,
2550  * not to autovac workers or bgworkers. When only superusers can connect,
2551  * we return CAC_SUPERUSER to indicate that superuserness must be checked
2552  * later. Note that neither CAC_OK nor CAC_SUPERUSER can safely be
2553  * returned until we have checked for too many children.
2554  */
2555  if (connsAllowed != ALLOW_ALL_CONNS &&
2556  backend_type == BACKEND_TYPE_NORMAL)
2557  {
2559  result = CAC_SUPERUSER; /* allow superusers only */
2560  else
2561  return CAC_SHUTDOWN; /* shutdown is pending */
2562  }
2563 
2564  /*
2565  * Don't start too many children.
2566  *
2567  * We allow more connections here than we can have backends because some
2568  * might still be authenticating; they might fail auth, or some existing
2569  * backend might exit before the auth cycle is completed. The exact
2570  * MaxBackends limit is enforced when a new backend tries to join the
2571  * shared-inval backend array.
2572  *
2573  * The limit here must match the sizes of the per-child-process arrays;
2574  * see comments for MaxLivePostmasterChildren().
2575  */
2577  result = CAC_TOOMANY;
2578 
2579  return result;
2580 }
CAC_state
Definition: libpq-be.h:72
@ CAC_TOOMANY
Definition: libpq-be.h:78
@ CAC_RECOVERY
Definition: libpq-be.h:76
@ CAC_NOTCONSISTENT
Definition: libpq-be.h:77
@ CAC_STARTUP
Definition: libpq-be.h:74
@ CAC_SHUTDOWN
Definition: libpq-be.h:75
static int Shutdown
Definition: postmaster.c:277
#define BACKEND_TYPE_ALL
Definition: postmaster.c:151
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5753
#define NoShutdown
Definition: postmaster.c:272
static bool FatalError
Definition: postmaster.c:279
static int CountChildren(int target)
Definition: postmaster.c:5446
static ConnsAllowedState connsAllowed
Definition: postmaster.c:354

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

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

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1591 of file postmaster.c.

1592 {
1593  char path[MAXPGPATH];
1594  FILE *fp;
1595 
1596  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1597 
1598  fp = AllocateFile(path, PG_BINARY_R);
1599  if (fp == NULL)
1600  {
1601  write_stderr("%s: could not find the database system\n"
1602  "Expected to find it in the directory \"%s\",\n"
1603  "but could not open file \"%s\": %s\n",
1604  progname, DataDir, path, strerror(errno));
1605  ExitPostmaster(2);
1606  }
1607  FreeFile(fp);
1608 }
#define write_stderr(str)
Definition: parallel.c:186
#define PG_BINARY_R
Definition: c.h:1270
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2461
int FreeFile(FILE *file)
Definition: fd.c:2660
char * DataDir
Definition: globals.c:65
const char * progname
Definition: main.c:46
#define MAXPGPATH
#define strerror
Definition: port.h:238
#define snprintf
Definition: port.h:225
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5190

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

3441 {
3442  dlist_mutable_iter iter;
3443 
3444  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3445 
3446  /*
3447  * If a backend dies in an ugly way then we must signal all other backends
3448  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3449  * assume everything is all right and proceed to remove the backend from
3450  * the active backend list.
3451  */
3452 
3453 #ifdef WIN32
3454 
3455  /*
3456  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3457  * since that sometimes happens under load when the process fails to start
3458  * properly (long before it starts using shared memory). Microsoft reports
3459  * it is related to mutex failure:
3460  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3461  */
3462  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3463  {
3464  LogChildExit(LOG, _("server process"), pid, exitstatus);
3465  exitstatus = 0;
3466  }
3467 #endif
3468 
3469  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3470  {
3471  HandleChildCrash(pid, exitstatus, _("server process"));
3472  return;
3473  }
3474 
3476  {
3477  Backend *bp = dlist_container(Backend, elem, iter.cur);
3478 
3479  if (bp->pid == pid)
3480  {
3481  if (!bp->dead_end)
3482  {
3484  {
3485  /*
3486  * Uh-oh, the child failed to clean itself up. Treat as a
3487  * crash after all.
3488  */
3489  HandleChildCrash(pid, exitstatus, _("server process"));
3490  return;
3491  }
3492 #ifdef EXEC_BACKEND
3493  ShmemBackendArrayRemove(bp);
3494 #endif
3495  }
3496  if (bp->bgworker_notify)
3497  {
3498  /*
3499  * This backend may have been slated to receive SIGUSR1 when
3500  * some background worker started or stopped. Cancel those
3501  * notifications, as we don't want to signal PIDs that are not
3502  * PostgreSQL backends. This gets skipped in the (probably
3503  * very common) case where the backend has never requested any
3504  * such notifications.
3505  */
3507  }
3508  dlist_delete(iter.cur);
3509  free(bp);
3510  break;
3511  }
3512  }
3513 }
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:514
#define _(x)
Definition: elog.c:89
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:543
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3776
#define EXIT_STATUS_1(st)
Definition: postmaster.c:564
#define EXIT_STATUS_0(st)
Definition: postmaster.c:563
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3523
dlist_node * cur
Definition: ilist.h:180

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

3346 {
3347  char namebuf[MAXPGPATH];
3348  slist_mutable_iter iter;
3349 
3351  {
3352  RegisteredBgWorker *rw;
3353 
3354  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3355 
3356  if (rw->rw_pid != pid)
3357  continue;
3358 
3359 #ifdef WIN32
3360  /* see CleanupBackend */
3361  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3362  exitstatus = 0;
3363 #endif
3364 
3365  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3366  rw->rw_worker.bgw_type);
3367 
3368 
3369  if (!EXIT_STATUS_0(exitstatus))
3370  {
3371  /* Record timestamp, so we know when to restart the worker. */
3373  }
3374  else
3375  {
3376  /* Zero exit status means terminate */
3377  rw->rw_crashed_at = 0;
3378  rw->rw_terminate = true;
3379  }
3380 
3381  /*
3382  * Additionally, just like a backend, any exit status other than 0 or
3383  * 1 is considered a crash and causes a system-wide restart.
3384  */
3385  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3386  {
3387  HandleChildCrash(pid, exitstatus, namebuf);
3388  return true;
3389  }
3390 
3391  /*
3392  * We must release the postmaster child slot. If the worker failed to
3393  * do so, it did not clean up after itself, requiring a crash-restart
3394  * cycle.
3395  */
3397  {
3398  HandleChildCrash(pid, exitstatus, namebuf);
3399  return true;
3400  }
3401 
3402  /* Get it out of the BackendList and clear out remaining data */
3403  dlist_delete(&rw->rw_backend->elem);
3404 #ifdef EXEC_BACKEND
3405  ShmemBackendArrayRemove(rw->rw_backend);
3406 #endif
3407 
3408  /*
3409  * It's possible that this background worker started some OTHER
3410  * background worker and asked to be notified when that worker started
3411  * or stopped. If so, cancel any notifications destined for the
3412  * now-dead backend.
3413  */
3414  if (rw->rw_backend->bgworker_notify)
3416  free(rw->rw_backend);
3417  rw->rw_backend = NULL;
3418  rw->rw_pid = 0;
3419  rw->rw_child_slot = 0;
3420  ReportBackgroundWorkerExit(&iter); /* report child death */
3421 
3422  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3423  namebuf, pid, exitstatus);
3424 
3425  return true;
3426  }
3427 
3428  return false;
3429 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
slist_head BackgroundWorkerList
Definition: bgworker.c:42
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:480
#define DEBUG1
Definition: elog.h:24
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:735
#define slist_container(type, membername, ptr)
Definition: ilist.h:693
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BackgroundWorker rw_worker
slist_node * cur
Definition: ilist.h:241

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

2638 {
2639  int i;
2640 
2641 #ifndef WIN32
2642 
2643  /*
2644  * Close the write end of postmaster death watch pipe. It's important to
2645  * do this as early as possible, so that if postmaster dies, others won't
2646  * think that it's still running because we're holding the pipe open.
2647  */
2649  ereport(FATAL,
2651  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2653  /* Notify fd.c that we released one pipe FD. */
2655 #endif
2656 
2657  /*
2658  * Close the postmaster's listen sockets. These aren't tracked by fd.c,
2659  * so we don't call ReleaseExternalFD() here.
2660  */
2661  for (i = 0; i < MAXLISTEN; i++)
2662  {
2664  {
2667  }
2668  }
2669 
2670  /*
2671  * If using syslogger, close the read side of the pipe. We don't bother
2672  * tracking this in fd.c, either.
2673  */
2674  if (!am_syslogger)
2675  {
2676 #ifndef WIN32
2677  if (syslogPipe[0] >= 0)
2678  close(syslogPipe[0]);
2679  syslogPipe[0] = -1;
2680 #else
2681  if (syslogPipe[0])
2682  CloseHandle(syslogPipe[0]);
2683  syslogPipe[0] = 0;
2684 #endif
2685  }
2686 
2687 #ifdef USE_BONJOUR
2688  /* If using Bonjour, close the connection to the mDNS daemon */
2689  if (bonjour_sdref)
2690  close(DNSServiceRefSockFD(bonjour_sdref));
2691 #endif
2692 }
int errcode_for_file_access(void)
Definition: elog.c:716
void ReleaseExternalFD(void)
Definition: fd.c:1230
#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:572
#define MAXLISTEN
Definition: postmaster.c:221
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:222
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
void StreamClose(pgsocket sock)
Definition: pqcomm.c:865
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(), pgstat_start(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1489 of file postmaster.c.

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

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

Referenced by PostmasterMain().

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2589 of file postmaster.c.

2590 {
2591  Port *port;
2592 
2593  if (!(port = (Port *) calloc(1, sizeof(Port))))
2594  {
2595  ereport(LOG,
2596  (errcode(ERRCODE_OUT_OF_MEMORY),
2597  errmsg("out of memory")));
2598  ExitPostmaster(1);
2599  }
2600 
2601  if (StreamConnection(serverFd, port) != STATUS_OK)
2602  {
2603  if (port->sock != PGINVALID_SOCKET)
2604  StreamClose(port->sock);
2605  ConnFree(port);
2606  return NULL;
2607  }
2608 
2609  return port;
2610 }
#define calloc(a, b)
Definition: header.h:55
static void ConnFree(Port *port)
Definition: postmaster.c:2620
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:731
Definition: libpq-be.h:126

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

2621 {
2622  free(conn);
2623 }
PGconn * conn
Definition: streamutil.c:54

References conn, and free.

Referenced by ConnCreate(), and ServerLoop().

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5446 of file postmaster.c.

5447 {
5448  dlist_iter iter;
5449  int cnt = 0;
5450 
5451  dlist_foreach(iter, &BackendList)
5452  {
5453  Backend *bp = dlist_container(Backend, elem, iter.cur);
5454 
5455  if (bp->dead_end)
5456  continue;
5457 
5458  /*
5459  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5460  * it first and avoid touching shared memory for every child.
5461  */
5462  if (target != BACKEND_TYPE_ALL)
5463  {
5464  /*
5465  * Assign bkend_type for any recently announced WAL Sender
5466  * processes.
5467  */
5468  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5471 
5472  if (!(target & bp->bkend_type))
5473  continue;
5474  }
5475 
5476  cnt++;
5477  }
5478  return cnt;
5479 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:275
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:149
dlist_node * cur
Definition: ilist.h:161

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

5710 {
5711  FILE *fp;
5712  int i;
5713 
5714 #define OPTS_FILE "postmaster.opts"
5715 
5716  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5717  {
5718  ereport(LOG,
5720  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
5721  return false;
5722  }
5723 
5724  fprintf(fp, "%s", fullprogname);
5725  for (i = 1; i < argc; i++)
5726  fprintf(fp, " \"%s\"", argv[i]);
5727  fputs("\n", fp);
5728 
5729  if (fclose(fp))
5730  {
5731  ereport(LOG,
5733  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
5734  return false;
5735  }
5736 
5737  return true;
5738 }
#define fprintf
Definition: port.h:229
#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 1620 of file postmaster.c.

1621 {
1622  TimestampTz next_wakeup = 0;
1623 
1624  /*
1625  * Normal case: either there are no background workers at all, or we're in
1626  * a shutdown sequence (during which we ignore bgworkers altogether).
1627  */
1628  if (Shutdown > NoShutdown ||
1630  {
1631  if (AbortStartTime != 0)
1632  {
1633  /* time left to abort; clamp to 0 in case it already expired */
1634  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1635  (time(NULL) - AbortStartTime);
1636  timeout->tv_sec = Max(timeout->tv_sec, 0);
1637  timeout->tv_usec = 0;
1638  }
1639  else
1640  {
1641  timeout->tv_sec = 60;
1642  timeout->tv_usec = 0;
1643  }
1644  return;
1645  }
1646 
1647  if (StartWorkerNeeded)
1648  {
1649  timeout->tv_sec = 0;
1650  timeout->tv_usec = 0;
1651  return;
1652  }
1653 
1654  if (HaveCrashedWorker)
1655  {
1656  slist_mutable_iter siter;
1657 
1658  /*
1659  * When there are crashed bgworkers, we sleep just long enough that
1660  * they are restarted when they request to be. Scan the list to
1661  * determine the minimum of all wakeup times according to most recent
1662  * crash time and requested restart interval.
1663  */
1665  {
1666  RegisteredBgWorker *rw;
1667  TimestampTz this_wakeup;
1668 
1669  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1670 
1671  if (rw->rw_crashed_at == 0)
1672  continue;
1673 
1675  || rw->rw_terminate)
1676  {
1677  ForgetBackgroundWorker(&siter);
1678  continue;
1679  }
1680 
1681  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1682  1000L * rw->rw_worker.bgw_restart_time);
1683  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1684  next_wakeup = this_wakeup;
1685  }
1686  }
1687 
1688  if (next_wakeup != 0)
1689  {
1690  long secs;
1691  int microsecs;
1692 
1694  &secs, &microsecs);
1695  timeout->tv_sec = secs;
1696  timeout->tv_usec = microsecs;
1697 
1698  /* Ensure we don't exceed one minute */
1699  if (timeout->tv_sec > 60)
1700  {
1701  timeout->tv_sec = 60;
1702  timeout->tv_usec = 0;
1703  }
1704  }
1705  else
1706  {
1707  timeout->tv_sec = 60;
1708  timeout->tv_usec = 0;
1709  }
1710 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1656
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:980
int64 TimestampTz
Definition: timestamp.h:39
static time_t AbortStartTime
Definition: postmaster.c:358
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:361
static volatile bool HaveCrashedWorker
Definition: postmaster.c:381
static volatile bool StartWorkerNeeded
Definition: postmaster.c:380
int bgw_restart_time
Definition: bgworker.h:95
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56

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

5852 {
5853  pid_t worker_pid;
5854 
5855  Assert(rw->rw_pid == 0);
5856 
5857  /*
5858  * Allocate and assign the Backend element. Note we must do this before
5859  * forking, so that we can handle failures (out of memory or child-process
5860  * slots) cleanly.
5861  *
5862  * Treat failure as though the worker had crashed. That way, the
5863  * postmaster will wait a bit before attempting to start it again; if we
5864  * tried again right away, most likely we'd find ourselves hitting the
5865  * same resource-exhaustion condition.
5866  */
5867  if (!assign_backendlist_entry(rw))
5868  {
5870  return false;
5871  }
5872 
5873  ereport(DEBUG1,
5874  (errmsg_internal("starting background worker process \"%s\"",
5875  rw->rw_worker.bgw_name)));
5876 
5877 #ifdef EXEC_BACKEND
5878  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5879 #else
5880  switch ((worker_pid = fork_process()))
5881 #endif
5882  {
5883  case -1:
5884  /* in postmaster, fork failed ... */
5885  ereport(LOG,
5886  (errmsg("could not fork worker process: %m")));
5887  /* undo what assign_backendlist_entry did */
5889  rw->rw_child_slot = 0;
5890  free(rw->rw_backend);
5891  rw->rw_backend = NULL;
5892  /* mark entry as crashed, so we'll try again later */
5894  break;
5895 
5896 #ifndef EXEC_BACKEND
5897  case 0:
5898  /* in postmaster child ... */
5900 
5901  /* Close the postmaster's sockets */
5902  ClosePostmasterPorts(false);
5903 
5904  /*
5905  * Before blowing away PostmasterContext, save this bgworker's
5906  * data where it can find it.
5907  */
5910  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5911 
5912  /* Release postmaster's working memory context */
5915  PostmasterContext = NULL;
5916 
5918 
5919  exit(1); /* should not get here */
5920  break;
5921 #endif
5922  default:
5923  /* in postmaster, fork successful ... */
5924  rw->rw_pid = worker_pid;
5925  rw->rw_backend->pid = rw->rw_pid;
5927  /* add new worker to lists of backends */
5929 #ifdef EXEC_BACKEND
5930  ShmemBackendArrayAdd(rw->rw_backend);
5931 #endif
5932  return true;
5933  }
5934 
5935  return false;
5936 }
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:863
MemoryContext PostmasterContext
Definition: mcxt.c:50
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5986
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 5417 of file postmaster.c.

5418 {
5419 }

Referenced by PostmasterMain().

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5190 of file postmaster.c.

5191 {
5192 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5193 
5194  /*
5195  * There is no known cause for a postmaster to become multithreaded after
5196  * startup. Recheck to account for the possibility of unknown causes.
5197  * This message uses LOG level, because an unclean shutdown at this point
5198  * would usually not look much different from a clean shutdown.
5199  */
5200  if (pthread_is_threaded_np() != 0)
5201  ereport(LOG,
5202  (errcode(ERRCODE_INTERNAL_ERROR),
5203  errmsg_internal("postmaster became multithreaded"),
5204  errdetail("Please report this to <%s>.", PACKAGE_BUGREPORT)));
5205 #endif
5206 
5207  /* should cleanup shared memory and kill all backends */
5208 
5209  /*
5210  * Not sure of the semantics here. When the Postmaster dies, should the
5211  * backends all be killed? probably not.
5212  *
5213  * MUST -- vadim 05-10-1999
5214  */
5215 
5216  proc_exit(status);
5217 }
int errdetail(const char *fmt,...)
Definition: elog.c:1037

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

1538 {
1539  DIR *pdir;
1540 
1541  /* Locate the postgres executable itself */
1542  if (find_my_exec(argv0, my_exec_path) < 0)
1543  ereport(FATAL,
1544  (errmsg("%s: could not locate my own executable path", argv0)));
1545 
1546 #ifdef EXEC_BACKEND
1547  /* Locate executable backend before we change working directory */
1548  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1549  postgres_exec_path) < 0)
1550  ereport(FATAL,
1551  (errmsg("%s: could not locate matching postgres executable",
1552  argv0)));
1553 #endif
1554 
1555  /*
1556  * Locate the pkglib directory --- this has to be set early in case we try
1557  * to load any modules from it in response to postgresql.conf entries.
1558  */
1560 
1561  /*
1562  * Verify that there's a readable directory there; otherwise the Postgres
1563  * installation is incomplete or corrupt. (A typical cause of this
1564  * failure is that the postgres executable has been moved or hardlinked to
1565  * some directory that's not a sibling of the installation lib/
1566  * directory.)
1567  */
1568  pdir = AllocateDir(pkglib_path);
1569  if (pdir == NULL)
1570  ereport(ERROR,
1572  errmsg("could not open directory \"%s\": %m",
1573  pkglib_path),
1574  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1575  my_exec_path)));
1576  FreeDir(pdir);
1577 
1578  /*
1579  * XXX is it worth similarly checking the share/ directory? If the lib/
1580  * directory is there, then share/ probably is too.
1581  */
1582 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:135
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:330
int errhint(const char *fmt,...)
Definition: elog.c:1151
int FreeDir(DIR *dir)
Definition: fd.c:2840
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2722
char pkglib_path[MAXPGPATH]
Definition: globals.c:76
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
static char * argv0
Definition: pg_ctl.c:97
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
#define PG_BACKEND_VERSIONSTR
Definition: port.h:139
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 3523 of file postmaster.c.

3524 {
3525  dlist_mutable_iter iter;
3526  slist_iter siter;
3527  Backend *bp;
3528  bool take_action;
3529 
3530  /*
3531  * We only log messages and send signals if this is the first process
3532  * crash and we're not doing an immediate shutdown; otherwise, we're only
3533  * here to update postmaster's idea of live processes. If we have already
3534  * signaled children, nonzero exit status is to be expected, so don't
3535  * clutter log.
3536  */
3537  take_action = !FatalError && Shutdown != ImmediateShutdown;
3538 
3539  if (take_action)
3540  {
3541  LogChildExit(LOG, procname, pid, exitstatus);
3542  ereport(LOG,
3543  (errmsg("terminating any other active server processes")));
3545  }
3546 
3547  /* Process background workers. */
3549  {
3550  RegisteredBgWorker *rw;
3551 
3552  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3553  if (rw->rw_pid == 0)
3554  continue; /* not running */
3555  if (rw->rw_pid == pid)
3556  {
3557  /*
3558  * Found entry for freshly-dead worker, so remove it.
3559  */
3561  dlist_delete(&rw->rw_backend->elem);
3562 #ifdef EXEC_BACKEND
3563  ShmemBackendArrayRemove(rw->rw_backend);
3564 #endif
3565  free(rw->rw_backend);
3566  rw->rw_backend = NULL;
3567  rw->rw_pid = 0;
3568  rw->rw_child_slot = 0;
3569  /* don't reset crashed_at */
3570  /* don't report child stop, either */
3571  /* Keep looping so we can signal remaining workers */
3572  }
3573  else
3574  {
3575  /*
3576  * This worker is still alive. Unless we did so already, tell it
3577  * to commit hara-kiri.
3578  *
3579  * SIGQUIT is the special signal that says exit without proc_exit
3580  * and let the user know what's going on. But if SendStop is set
3581  * (-T on command line), then we send SIGSTOP instead, so that we
3582  * can get core dumps from all backends by hand.
3583  */
3584  if (take_action)
3585  {
3586  ereport(DEBUG2,
3587  (errmsg_internal("sending %s to process %d",
3588  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3589  (int) rw->rw_pid)));
3591  }
3592  }
3593  }
3594 
3595  /* Process regular backends */
3597  {
3598  bp = dlist_container(Backend, elem, iter.cur);
3599 
3600  if (bp->pid == pid)
3601  {
3602  /*
3603  * Found entry for freshly-dead backend, so remove it.
3604  */
3605  if (!bp->dead_end)
3606  {
3608 #ifdef EXEC_BACKEND
3609  ShmemBackendArrayRemove(bp);
3610 #endif
3611  }
3612  dlist_delete(iter.cur);
3613  free(bp);
3614  /* Keep looping so we can signal remaining backends */
3615  }
3616  else
3617  {
3618  /*
3619  * This backend is still alive. Unless we did so already, tell it
3620  * to commit hara-kiri.
3621  *
3622  * SIGQUIT is the special signal that says exit without proc_exit
3623  * and let the user know what's going on. But if SendStop is set
3624  * (-T on command line), then we send SIGSTOP instead, so that we
3625  * can get core dumps from all backends by hand.
3626  *
3627  * We could exclude dead_end children here, but at least in the
3628  * SIGSTOP case it seems better to include them.
3629  *
3630  * Background workers were already processed above; ignore them
3631  * here.
3632  */
3633  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3634  continue;
3635 
3636  if (take_action)
3637  {
3638  ereport(DEBUG2,
3639  (errmsg_internal("sending %s to process %d",
3640  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3641  (int) bp->pid)));
3642  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3643  }
3644  }
3645  }
3646 
3647  /* Take care of the startup process too */
3648  if (pid == StartupPID)
3649  {
3650  StartupPID = 0;
3651  /* Caller adjusts StartupStatus, so don't touch it here */
3652  }
3653  else if (StartupPID != 0 && take_action)
3654  {
3655  ereport(DEBUG2,
3656  (errmsg_internal("sending %s to process %d",
3657  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3658  (int) StartupPID)));
3661  }
3662 
3663  /* Take care of the bgwriter too */
3664  if (pid == BgWriterPID)
3665  BgWriterPID = 0;
3666  else if (BgWriterPID != 0 && take_action)
3667  {
3668  ereport(DEBUG2,
3669  (errmsg_internal("sending %s to process %d",
3670  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3671  (int) BgWriterPID)));
3673  }
3674 
3675  /* Take care of the checkpointer too */
3676  if (pid == CheckpointerPID)
3677  CheckpointerPID = 0;
3678  else if (CheckpointerPID != 0 && take_action)
3679  {
3680  ereport(DEBUG2,
3681  (errmsg_internal("sending %s to process %d",
3682  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3683  (int) CheckpointerPID)));
3685  }
3686 
3687  /* Take care of the walwriter too */
3688  if (pid == WalWriterPID)
3689  WalWriterPID = 0;
3690  else if (WalWriterPID != 0 && take_action)
3691  {
3692  ereport(DEBUG2,
3693  (errmsg_internal("sending %s to process %d",
3694  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3695  (int) WalWriterPID)));
3697  }
3698 
3699  /* Take care of the walreceiver too */
3700  if (pid == WalReceiverPID)
3701  WalReceiverPID = 0;
3702  else if (WalReceiverPID != 0 && take_action)
3703  {
3704  ereport(DEBUG2,
3705  (errmsg_internal("sending %s to process %d",
3706  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3707  (int) WalReceiverPID)));
3709  }
3710 
3711  /* Take care of the autovacuum launcher too */
3712  if (pid == AutoVacPID)
3713  AutoVacPID = 0;
3714  else if (AutoVacPID != 0 && take_action)
3715  {
3716  ereport(DEBUG2,
3717  (errmsg_internal("sending %s to process %d",
3718  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3719  (int) AutoVacPID)));
3721  }
3722 
3723  /* Take care of the archiver too */
3724  if (pid == PgArchPID)
3725  PgArchPID = 0;
3726  else if (PgArchPID != 0 && take_action)
3727  {
3728  ereport(DEBUG2,
3729  (errmsg_internal("sending %s to process %d",
3730  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3731  (int) PgArchPID)));
3733  }
3734 
3735  /*
3736  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3737  * necessary, but it seems like a good idea for robustness, and it
3738  * simplifies the state-machine logic in the case where a shutdown request
3739  * arrives during crash processing.)
3740  */
3741  if (PgStatPID != 0 && take_action)
3742  {
3743  ereport(DEBUG2,
3744  (errmsg_internal("sending %s to process %d",
3745  "SIGQUIT",
3746  (int) PgStatPID)));
3749  }
3750 
3751  /* We do NOT restart the syslogger */
3752 
3753  if (Shutdown != ImmediateShutdown)
3754  FatalError = true;
3755 
3756  /* We now transit into a state of waiting for children to die */
3757  if (pmState == PM_RECOVERY ||
3758  pmState == PM_HOT_STANDBY ||
3759  pmState == PM_RUN ||
3761  pmState == PM_SHUTDOWN)
3763 
3764  /*
3765  * .. and if this doesn't happen quickly enough, now the clock is ticking
3766  * for us to kill them without mercy.
3767  */
3768  if (AbortStartTime == 0)
3769  AbortStartTime = time(NULL);
3770 }
#define slist_foreach(iter, lhead)
Definition: ilist.h:719
void allow_immediate_pgstat_restart(void)
Definition: pgstat.c:835
void SetQuitSignalReason(QuitSignalReason reason)
Definition: pmsignal.c:190
@ PMQUIT_FOR_CRASH
Definition: pmsignal.h:53
static pid_t WalReceiverPID
Definition: postmaster.c:254
static pid_t PgArchPID
Definition: postmaster.c:256
#define ImmediateShutdown
Definition: postmaster.c:275
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:4142
static pid_t PgStatPID
Definition: postmaster.c:257
static pid_t AutoVacPID
Definition: postmaster.c:255
static int SendStop
Definition: postmaster.c:232
static pid_t CheckpointerPID
Definition: postmaster.c:252
static pid_t BgWriterPID
Definition: postmaster.c:251
static pid_t WalWriterPID
Definition: postmaster.c:253
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
static pid_t StartupPID
Definition: postmaster.c:250
slist_node * cur
Definition: ilist.h:226
#define SIGSTOP
Definition: win32_port.h:174
#define SIGQUIT
Definition: win32_port.h:168

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

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

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1960 of file postmaster.c.

1961 {
1962  int maxsock = -1;
1963  int i;
1964 
1965  FD_ZERO(rmask);
1966 
1967  for (i = 0; i < MAXLISTEN; i++)
1968  {
1969  int fd = ListenSocket[i];
1970 
1971  if (fd == PGINVALID_SOCKET)
1972  break;
1973  FD_SET(fd, rmask);
1974 
1975  if (fd > maxsock)
1976  maxsock = fd;
1977  }
1978 
1979  return maxsock + 1;
1980 }
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 6651 of file postmaster.c.

6652 {
6653 #ifndef WIN32
6654 
6655  /*
6656  * Create a pipe. Postmaster holds the write end of the pipe open
6657  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6658  * the read file descriptor to select() to wake up in case postmaster
6659  * dies, or check for postmaster death with a (read() == 0). Children must
6660  * close the write end as soon as possible after forking, because EOF
6661  * won't be signaled in the read end until all processes have closed the
6662  * write fd. That is taken care of in ClosePostmasterPorts().
6663  */
6665  if (pipe(postmaster_alive_fds) < 0)
6666  ereport(FATAL,
6668  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6669 
6670  /* Notify fd.c that we've eaten two FDs for the pipe. */
6673 
6674  /*
6675  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6676  * call.
6677  */
6678  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6679  ereport(FATAL,
6681  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6682 #else
6683 
6684  /*
6685  * On Windows, we use a process handle for the same purpose.
6686  */
6687  if (DuplicateHandle(GetCurrentProcess(),
6688  GetCurrentProcess(),
6689  GetCurrentProcess(),
6690  &PostmasterHandle,
6691  0,
6692  TRUE,
6693  DUPLICATE_SAME_ACCESS) == 0)
6694  ereport(FATAL,
6695  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6696  GetLastError())));
6697 #endif /* WIN32 */
6698 }
int errcode_for_socket_access(void)
Definition: elog.c:787
pid_t PostmasterPid
Definition: globals.c:98
int MyProcPid
Definition: globals.c:43
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:43

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

2702 {
2703  MyProcPid = getpid();
2706 
2707  /*
2708  * Set a different global seed in every process. We want something
2709  * unpredictable, so if possible, use high-quality random bits for the
2710  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2711  */
2713  {
2714  uint64 rseed;
2715 
2716  /*
2717  * Since PIDs and timestamps tend to change more frequently in their
2718  * least significant bits, shift the timestamp left to allow a larger
2719  * total number of seeds in a given time period. Since that would
2720  * leave only 20 bits of the timestamp that cycle every ~1 second,
2721  * also mix in some higher bits.
2722  */
2723  rseed = ((uint64) MyProcPid) ^
2724  ((uint64) MyStartTimestamp << 12) ^
2725  ((uint64) MyStartTimestamp >> 20);
2726 
2728  }
2729 
2730  /*
2731  * Also make sure that we've set a good seed for random(3). Use of that
2732  * is deprecated in core Postgres, but extensions might use it.
2733  */
2734 #ifndef WIN32
2736 #endif
2737 }
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1754
#define unlikely(x)
Definition: c.h:273
TimestampTz MyStartTimestamp
Definition: globals.c:45
pg_time_t MyStartTime
Definition: globals.c:44
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 3776 of file postmaster.c.

3777 {
3778  /*
3779  * size of activity_buffer is arbitrary, but set equal to default
3780  * track_activity_query_size
3781  */
3782  char activity_buffer[1024];
3783  const char *activity = NULL;
3784 
3785  if (!EXIT_STATUS_0(exitstatus))
3786  activity = pgstat_get_crashed_backend_activity(pid,
3787  activity_buffer,
3788  sizeof(activity_buffer));
3789 
3790  if (WIFEXITED(exitstatus))
3791  ereport(lev,
3792 
3793  /*------
3794  translator: %s is a noun phrase describing a child process, such as
3795  "server process" */
3796  (errmsg("%s (PID %d) exited with exit code %d",
3797  procname, pid, WEXITSTATUS(exitstatus)),
3798  activity ? errdetail("Failed process was running: %s", activity) : 0));
3799  else if (WIFSIGNALED(exitstatus))
3800  {
3801 #if defined(WIN32)
3802  ereport(lev,
3803 
3804  /*------
3805  translator: %s is a noun phrase describing a child process, such as
3806  "server process" */
3807  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3808  procname, pid, WTERMSIG(exitstatus)),
3809  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3810  activity ? errdetail("Failed process was running: %s", activity) : 0));
3811 #else
3812  ereport(lev,
3813 
3814  /*------
3815  translator: %s is a noun phrase describing a child process, such as
3816  "server process" */
3817  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3818  procname, pid, WTERMSIG(exitstatus),
3819  pg_strsignal(WTERMSIG(exitstatus))),
3820  activity ? errdetail("Failed process was running: %s", activity) : 0));
3821 #endif
3822  }
3823  else
3824  ereport(lev,
3825 
3826  /*------
3827  translator: %s is a noun phrase describing a child process, such as
3828  "server process" */
3829  (errmsg("%s (PID %d) exited with unrecognized status %d",
3830  procname, pid, exitstatus),
3831  activity ? errdetail("Failed process was running: %s", activity) : 0));
3832 }
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:151
#define WIFSIGNALED(w)
Definition: win32_port.h:152
#define WTERMSIG(w)
Definition: win32_port.h:154
#define WEXITSTATUS(w)
Definition: win32_port.h:153

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

5754 {
5755  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5757 }
int autovacuum_max_workers
Definition: autovacuum.c:115
int MaxConnections
Definition: globals.c:136
int max_worker_processes
Definition: globals.c:137
int max_wal_senders
Definition: walsender.c:121

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 6050 of file postmaster.c.

6051 {
6052 #define MAX_BGWORKERS_TO_LAUNCH 100
6053  int num_launched = 0;
6054  TimestampTz now = 0;
6055  slist_mutable_iter iter;
6056 
6057  /*
6058  * During crash recovery, we have no need to be called until the state
6059  * transition out of recovery.
6060  */
6061  if (FatalError)
6062  {
6063  StartWorkerNeeded = false;
6064  HaveCrashedWorker = false;
6065  return;
6066  }
6067 
6068  /* Don't need to be called again unless we find a reason for it below */
6069  StartWorkerNeeded = false;
6070  HaveCrashedWorker = false;
6071 
6073  {
6074  RegisteredBgWorker *rw;
6075 
6076  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
6077 
6078  /* ignore if already running */
6079  if (rw->rw_pid != 0)
6080  continue;
6081 
6082  /* if marked for death, clean up and remove from list */
6083  if (rw->rw_terminate)
6084  {
6085  ForgetBackgroundWorker(&iter);
6086  continue;
6087  }
6088 
6089  /*
6090  * If this worker has crashed previously, maybe it needs to be
6091  * restarted (unless on registration it specified it doesn't want to
6092  * be restarted at all). Check how long ago did a crash last happen.
6093  * If the last crash is too recent, don't start it right away; let it
6094  * be restarted once enough time has passed.
6095  */
6096  if (rw->rw_crashed_at != 0)
6097  {
6099  {
6100  int notify_pid;
6101 
6102  notify_pid = rw->rw_worker.bgw_notify_pid;
6103 
6104  ForgetBackgroundWorker(&iter);
6105 
6106  /* Report worker is gone now. */
6107  if (notify_pid != 0)
6108  kill(notify_pid, SIGUSR1);
6109 
6110  continue;
6111  }
6112 
6113  /* read system time only when needed */
6114  if (now == 0)
6116 
6118  rw->rw_worker.bgw_restart_time * 1000))
6119  {
6120  /* Set flag to remember that we have workers to start later */
6121  HaveCrashedWorker = true;
6122  continue;
6123  }
6124  }
6125 
6127  {
6128  /* reset crash time before trying to start worker */
6129  rw->rw_crashed_at = 0;
6130 
6131  /*
6132  * Try to start the worker.
6133  *
6134  * On failure, give up processing workers for now, but set
6135  * StartWorkerNeeded so we'll come back here on the next iteration
6136  * of ServerLoop to try again. (We don't want to wait, because
6137  * there might be additional ready-to-run workers.) We could set
6138  * HaveCrashedWorker as well, since this worker is now marked
6139  * crashed, but there's no need because the next run of this
6140  * function will do that.
6141  */
6142  if (!do_start_bgworker(rw))
6143  {
6144  StartWorkerNeeded = true;
6145  return;
6146  }
6147 
6148  /*
6149  * If we've launched as many workers as allowed, quit, but have
6150  * ServerLoop call us again to look for additional ready-to-run
6151  * workers. There might not be any, but we'll find out the next
6152  * time we run.
6153  */
6154  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
6155  {
6156  StartWorkerNeeded = true;
6157  return;
6158  }
6159  }
6160  }
6161 }
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5851
#define MAX_BGWORKERS_TO_LAUNCH
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5943
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:464
#define SIGUSR1
Definition: win32_port.h:179

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

5691 {
5692  if (WalReceiverPID == 0 &&
5693  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5694  pmState == PM_HOT_STANDBY) &&
5696  {
5698  if (WalReceiverPID != 0)
5699  WalReceiverRequested = false;
5700  /* else leave the flag set, so we'll try again later */
5701  }
5702 }
#define SmartShutdown
Definition: postmaster.c:273
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:377
#define StartWalReceiver()
Definition: postmaster.c:560

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

2844 {
2845  int save_errno = errno;
2846 
2847  /*
2848  * We rely on the signal mechanism to have blocked all signals ... except
2849  * on Windows, which lacks sigaction(), so we have to do it manually.
2850  */
2851 #ifdef WIN32
2852  PG_SETMASK(&BlockSig);
2853 #endif
2854 
2855  ereport(DEBUG2,
2856  (errmsg_internal("postmaster received signal %d",
2857  postgres_signal_arg)));
2858 
2859  switch (postgres_signal_arg)
2860  {
2861  case SIGTERM:
2862 
2863  /*
2864  * Smart Shutdown:
2865  *
2866  * Wait for children to end their work, then shut down.
2867  */
2868  if (Shutdown >= SmartShutdown)
2869  break;
2871  ereport(LOG,
2872  (errmsg("received smart shutdown request")));
2873 
2874  /* Report status */
2876 #ifdef USE_SYSTEMD
2877  sd_notify(0, "STOPPING=1");
2878 #endif
2879 
2880  /*
2881  * If we reached normal running, we have to wait for any online
2882  * backup mode to end; otherwise go straight to waiting for client
2883  * backends to exit. (The difference is that in the former state,
2884  * we'll still let in new superuser clients, so that somebody can
2885  * end the online backup mode.) If already in PM_STOP_BACKENDS or
2886  * a later state, do not change it.
2887  */
2888  if (pmState == PM_RUN)
2890  else if (pmState == PM_HOT_STANDBY)
2892  else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2893  {
2894  /* There should be no clients, so proceed to stop children */
2896  }
2897 
2898  /*
2899  * Now wait for online backup mode to end and backends to exit. If
2900  * that is already the case, PostmasterStateMachine will take the
2901  * next step.
2902  */
2904  break;
2905 
2906  case SIGINT:
2907 
2908  /*
2909  * Fast Shutdown:
2910  *
2911  * Abort all children with SIGTERM (rollback active transactions
2912  * and exit) and shut down when they are gone.
2913  */
2914  if (Shutdown >= FastShutdown)
2915  break;
2917  ereport(LOG,
2918  (errmsg("received fast shutdown request")));
2919 
2920  /* Report status */
2922 #ifdef USE_SYSTEMD
2923  sd_notify(0, "STOPPING=1");
2924 #endif
2925 
2926  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2927  {
2928  /* Just shut down background processes silently */
2930  }
2931  else if (pmState == PM_RUN ||
2933  {
2934  /* Report that we're about to zap live client sessions */
2935  ereport(LOG,
2936  (errmsg("aborting any active transactions")));
2938  }
2939 
2940  /*
2941  * PostmasterStateMachine will issue any necessary signals, or
2942  * take the next step if no child processes need to be killed.
2943  */
2945  break;
2946 
2947  case SIGQUIT:
2948 
2949  /*
2950  * Immediate Shutdown:
2951  *
2952  * abort all children with SIGQUIT, wait for them to exit,
2953  * terminate remaining ones with SIGKILL, then exit without
2954  * attempt to properly shut down the data base system.
2955  */
2956  if (Shutdown >= ImmediateShutdown)
2957  break;
2959  ereport(LOG,
2960  (errmsg("received immediate shutdown request")));
2961 
2962  /* Report status */
2964 #ifdef USE_SYSTEMD
2965  sd_notify(0, "STOPPING=1");
2966 #endif
2967 
2968  /* tell children to shut down ASAP */
2972 
2973  /* set stopwatch for them to die */
2974  AbortStartTime = time(NULL);
2975 
2976  /*
2977  * Now wait for backends to exit. If there are none,
2978  * PostmasterStateMachine will take the next step.
2979  */
2981  break;
2982  }
2983 
2984 #ifdef WIN32
2986 #endif
2987 
2988  errno = save_errno;
2989 }
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1348
#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:3841
static void TerminateChildren(int signal)
Definition: postmaster.c:4212
#define FastShutdown
Definition: postmaster.c:274

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

Referenced by PostmasterMain().

◆ PostmasterMain()

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

Definition at line 582 of file postmaster.c.

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

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

6170 {
6171  dlist_iter iter;
6172  Backend *bp;
6173 
6174  dlist_foreach(iter, &BackendList)
6175  {
6176  bp = dlist_container(Backend, elem, iter.cur);
6177  if (bp->pid == pid)
6178  {
6179  bp->bgworker_notify = true;
6180  return true;
6181  }
6182  }
6183  return false;
6184 }

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

3842 {
3843  /* If we're doing a smart shutdown, try to advance that state. */
3844  if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
3845  {
3847  {
3848  /*
3849  * ALLOW_SUPERUSER_CONNS state ends as soon as online backup mode
3850  * is not active.
3851  */
3852  if (!BackupInProgress())
3854  }
3855 
3857  {
3858  /*
3859  * ALLOW_NO_CONNS state ends when we have no normal client
3860  * backends running. Then we're ready to stop other children.
3861  */
3864  }
3865  }
3866 
3867  /*
3868  * If we're ready to do so, signal child processes to shut down. (This
3869  * isn't a persistent state, but treating it as a distinct pmState allows
3870  * us to share this code across multiple shutdown code paths.)
3871  */
3872  if (pmState == PM_STOP_BACKENDS)
3873  {
3874  /*
3875  * Forget any pending requests for background workers, since we're no
3876  * longer willing to launch any new workers. (If additional requests
3877  * arrive, BackgroundWorkerStateChange will reject them.)
3878  */
3880 
3881  /* Signal all backend children except walsenders */
3882  SignalSomeChildren(SIGTERM,
3884  /* and the autovac launcher too */
3885  if (AutoVacPID != 0)
3886  signal_child(AutoVacPID, SIGTERM);
3887  /* and the bgwriter too */
3888  if (BgWriterPID != 0)
3889  signal_child(BgWriterPID, SIGTERM);
3890  /* and the walwriter too */
3891  if (WalWriterPID != 0)
3892  signal_child(WalWriterPID, SIGTERM);
3893  /* If we're in recovery, also stop startup and walreceiver procs */
3894  if (StartupPID != 0)
3895  signal_child(StartupPID, SIGTERM);
3896  if (WalReceiverPID != 0)
3897  signal_child(WalReceiverPID, SIGTERM);
3898  /* checkpointer, archiver, stats, and syslogger may continue for now */
3899 
3900  /* Now transition to PM_WAIT_BACKENDS state to wait for them to die */
3902  }
3903 
3904  /*
3905  * If we are in a state-machine state that implies waiting for backends to
3906  * exit, see if they're all gone, and change state if so.
3907  */
3908  if (pmState == PM_WAIT_BACKENDS)
3909  {
3910  /*
3911  * PM_WAIT_BACKENDS state ends when we have no regular backends
3912  * (including autovac workers), no bgworkers (including unconnected
3913  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3914  * doing crash recovery or an immediate shutdown then we expect the
3915  * checkpointer to exit as well, otherwise not. The stats and
3916  * syslogger processes are disregarded since they are not connected to
3917  * shared memory; we also disregard dead_end children here. Walsenders
3918  * and archiver are also disregarded, they will be terminated later
3919  * after writing the checkpoint record.
3920  */
3922  StartupPID == 0 &&
3923  WalReceiverPID == 0 &&
3924  BgWriterPID == 0 &&
3925  (CheckpointerPID == 0 ||
3927  WalWriterPID == 0 &&
3928  AutoVacPID == 0)
3929  {
3931  {
3932  /*
3933  * Start waiting for dead_end children to die. This state
3934  * change causes ServerLoop to stop creating new ones.
3935  */
3937 
3938  /*
3939  * We already SIGQUIT'd the archiver and stats processes, if
3940  * any, when we started immediate shutdown or entered
3941  * FatalError state.
3942  */
3943  }
3944  else
3945  {
3946  /*
3947  * If we get here, we are proceeding with normal shutdown. All
3948  * the regular children are gone, and it's time to tell the
3949  * checkpointer to do a shutdown checkpoint.
3950  */
3952  /* Start the checkpointer if not running */
3953  if (CheckpointerPID == 0)
3955  /* And tell it to shut down */
3956  if (CheckpointerPID != 0)
3957  {
3959  pmState = PM_SHUTDOWN;
3960  }
3961  else
3962  {
3963  /*
3964  * If we failed to fork a checkpointer, just shut down.
3965  * Any required cleanup will happen at next restart. We
3966  * set FatalError so that an "abnormal shutdown" message
3967  * gets logged when we exit.
3968  */
3969  FatalError = true;
3971 
3972  /* Kill the walsenders, archiver and stats collector too */
3974  if (PgArchPID != 0)
3976  if (PgStatPID != 0)
3978  }
3979  }
3980  }
3981  }
3982 
3983  if (pmState == PM_SHUTDOWN_2)
3984  {
3985  /*
3986  * PM_SHUTDOWN_2 state ends when there's no other children than
3987  * dead_end children left. There shouldn't be any regular backends
3988  * left by now anyway; what we're really waiting for is walsenders and
3989  * archiver.
3990  */
3991  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3992  {
3994  }
3995  }
3996 
3997  if (pmState == PM_WAIT_DEAD_END)
3998  {
3999  /*
4000  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
4001  * (ie, no dead_end children remain), and the archiver and stats
4002  * collector are gone too.
4003  *
4004  * The reason we wait for those two is to protect them against a new
4005  * postmaster starting conflicting subprocesses; this isn't an
4006  * ironclad protection, but it at least helps in the
4007  * shutdown-and-immediately-restart scenario. Note that they have
4008  * already been sent appropriate shutdown signals, either during a
4009  * normal state transition leading up to PM_WAIT_DEAD_END, or during
4010  * FatalError processing.
4011  */
4012  if (dlist_is_empty(&BackendList) &&
4013  PgArchPID == 0 && PgStatPID == 0)
4014  {
4015  /* These other guys should be dead already */
4016  Assert(StartupPID == 0);
4017  Assert(WalReceiverPID == 0);
4018  Assert(BgWriterPID == 0);
4019  Assert(CheckpointerPID == 0);
4020  Assert(WalWriterPID == 0);
4021  Assert(AutoVacPID == 0);
4022  /* syslogger is not considered here */
4024  }
4025  }
4026 
4027  /*
4028  * If we've been told to shut down, we exit as soon as there are no
4029  * remaining children. If there was a crash, cleanup will occur at the
4030  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
4031  * crash before exiting, but that seems unwise if we are quitting because
4032  * we got SIGTERM from init --- there may well not be time for recovery
4033  * before init decides to SIGKILL us.)
4034  *
4035  * Note that the syslogger continues to run. It will exit when it sees
4036  * EOF on its input pipe, which happens when there are no more upstream
4037  * processes.
4038  */
4040  {
4041  if (FatalError)
4042  {
4043  ereport(LOG, (errmsg("abnormal database system shutdown")));
4044  ExitPostmaster(1);
4045  }
4046  else
4047  {
4048  /*
4049  * Terminate exclusive backup mode to avoid recovery after a clean
4050  * fast shutdown. Since an exclusive backup can only be taken
4051  * during normal running (and not, for example, while running
4052  * under Hot Standby) it only makes sense to do this if we reached
4053  * normal running. If we're still in recovery, the backup file is
4054  * one we're recovering *from*, and we must keep it around so that
4055  * recovery restarts from the right place.
4056  */
4058  CancelBackup();
4059 
4060  /*
4061  * Normal exit from the postmaster is here. We don't need to log
4062  * anything here, since the UnlinkLockFiles proc_exit callback
4063  * will do so, and that should be the last user-visible action.
4064  */
4065  ExitPostmaster(0);
4066  }
4067  }
4068 
4069  /*
4070  * If the startup process failed, or the user does not want an automatic
4071  * restart after backend crashes, wait for all non-syslogger children to
4072  * exit, and then exit postmaster. We don't try to reinitialize when the
4073  * startup process fails, because more than likely it will just fail again
4074  * and we will keep trying forever.
4075  */
4076  if (pmState == PM_NO_CHILDREN)
4077  {
4079  {
4080  ereport(LOG,
4081  (errmsg("shutting down due to startup process failure")));
4082  ExitPostmaster(1);
4083  }
4084  if (!restart_after_crash)
4085  {
4086  ereport(LOG,
4087  (errmsg("shutting down because restart_after_crash is off")));
4088  ExitPostmaster(1);
4089  }
4090  }
4091 
4092  /*
4093  * If we need to recover from a crash, wait for all non-syslogger children
4094  * to exit, then reset shmem and StartupDataBase.
4095  */
4096  if (FatalError && pmState == PM_NO_CHILDREN)
4097  {
4098  ereport(LOG,
4099  (errmsg("all server processes terminated; reinitializing")));
4100 
4101  /* remove leftover temporary files after a crash */
4104 
4105  /* allow background workers to immediately restart */
4107 
4108  shmem_exit(1);
4109 
4110  /* re-read control file into local memory */
4112 
4113  reset_shared();
4114 
4116  Assert(StartupPID != 0);
4118  pmState = PM_STARTUP;
4119  /* crash recovery started, reset SIGKILL flag */
4120  AbortStartTime = 0;
4121  }
4122 }
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:289
void shmem_exit(int code)
Definition: ipc.c:224
bool remove_temp_files_after_crash
Definition: postmaster.c:247
bool restart_after_crash
Definition: postmaster.c:246
#define SignalChildren(sig)
Definition: postmaster.c:431
static bool ReachedNormalRunning
Definition: postmaster.c:363
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:4168
bool BackupInProgress(void)
Definition: xlog.c:12285
void CancelBackup(void)
Definition: xlog.c:12305

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

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

◆ process_startup_packet_die()

static void process_startup_packet_die ( SIGNAL_ARGS  )
static

Definition at line 5402 of file postmaster.c.

5403 {
5404  _exit(1);
5405 }

Referenced by BackendInitialize().

◆ processCancelRequest()

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

Definition at line 2458 of file postmaster.c.

2459 {
2460  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2461  int backendPID;
2462  int32 cancelAuthCode;
2463  Backend *bp;
2464 
2465 #ifndef EXEC_BACKEND
2466  dlist_iter iter;
2467 #else
2468  int i;
2469 #endif
2470 
2471  backendPID = (int) pg_ntoh32(canc->backendPID);
2472  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2473 
2474  /*
2475  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2476  * longer access the postmaster's own backend list, and must rely on the
2477  * duplicate array in shared memory.
2478  */
2479 #ifndef EXEC_BACKEND
2480  dlist_foreach(iter, &BackendList)
2481  {
2482  bp = dlist_container(Backend, elem, iter.cur);
2483 #else
2484  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2485  {
2486  bp = (Backend *) &ShmemBackendArray[i];
2487 #endif
2488  if (bp->pid == backendPID)
2489  {
2490  if (bp->cancel_key == cancelAuthCode)
2491  {
2492  /* Found a match; signal that backend to cancel current op */
2493  ereport(DEBUG2,
2494  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2495  backendPID)));
2496  signal_child(bp->pid, SIGINT);
2497  }
2498  else
2499  /* Right PID, wrong key: no way, Jose */
2500  ereport(LOG,
2501  (errmsg("wrong key in cancel request for process %d",
2502  backendPID)));
2503  return;
2504  }
2505 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2506  }
2507 #else
2508  }
2509 #endif
2510 
2511  /* No matching backend */
2512  ereport(LOG,
2513  (errmsg("PID %d in cancel request did not match any process",
2514  backendPID)));
2515 }
signed int int32
Definition: c.h:429
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
uint32 backendPID
Definition: pqcomm.h:182
uint32 cancelAuthCode
Definition: pqcomm.h:183

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

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

References am_db_walsender, am_walsender, B_BACKEND, B_WAL_SENDER, buf, CAC_NOTCONSISTENT, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_SUPERUSER, 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, IS_AF_UNIX, 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 5436 of file postmaster.c.

5437 {
5438  return pg_strong_random(cancel_key, sizeof(int32));
5439 }
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 2995 of file postmaster.c.

2996 {
2997  int save_errno = errno;
2998  int pid; /* process id of dead child process */
2999  int exitstatus; /* its exit status */
3000 
3001  /*
3002  * We rely on the signal mechanism to have blocked all signals ... except
3003  * on Windows, which lacks sigaction(), so we have to do it manually.
3004  */
3005 #ifdef WIN32
3006  PG_SETMASK(&BlockSig);
3007 #endif
3008 
3009  ereport(DEBUG4,
3010  (errmsg_internal("reaping dead processes")));
3011 
3012  while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
3013  {
3014  /*
3015  * Check if this child was a startup process.
3016  */
3017  if (pid == StartupPID)
3018  {
3019  StartupPID = 0;
3020 
3021  /*
3022  * Startup process exited in response to a shutdown request (or it
3023  * completed normally regardless of the shutdown request).
3024  */
3025  if (Shutdown > NoShutdown &&
3026  (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
3027  {
3030  /* PostmasterStateMachine logic does the rest */
3031  continue;
3032  }
3033 
3034  if (EXIT_STATUS_3(exitstatus))
3035  {
3036  ereport(LOG,
3037  (errmsg("shutdown at recovery target")));
3040  TerminateChildren(SIGTERM);
3042  /* PostmasterStateMachine logic does the rest */
3043  continue;
3044  }
3045 
3046  /*
3047  * Unexpected exit of startup process (including FATAL exit)
3048  * during PM_STARTUP is treated as catastrophic. There are no
3049  * other processes running yet, so we can just exit.
3050  */
3051  if (pmState == PM_STARTUP &&
3053  !EXIT_STATUS_0(exitstatus))
3054  {
3055  LogChildExit(LOG, _("startup process"),
3056  pid, exitstatus);
3057  ereport(LOG,
3058  (errmsg("aborting startup due to startup process failure")));
3059  ExitPostmaster(1);
3060  }
3061 
3062  /*
3063  * After PM_STARTUP, any unexpected exit (including FATAL exit) of
3064  * the startup process is catastrophic, so kill other children,
3065  * and set StartupStatus so we don't try to reinitialize after
3066  * they're gone. Exception: if StartupStatus is STARTUP_SIGNALED,
3067  * then we previously sent the startup process a SIGQUIT; so
3068  * that's probably the reason it died, and we do want to try to
3069  * restart in that case.
3070  *
3071  * This stanza also handles the case where we sent a SIGQUIT
3072  * during PM_STARTUP due to some dead_end child crashing: in that
3073  * situation, if the startup process dies on the SIGQUIT, we need
3074  * to transition to PM_WAIT_BACKENDS state which will allow
3075  * PostmasterStateMachine to restart the startup process. (On the
3076  * other hand, the startup process might complete normally, if we
3077  * were too late with the SIGQUIT. In that case we'll fall
3078  * through and commence normal operations.)
3079  */
3080  if (!EXIT_STATUS_0(exitstatus))
3081  {
3083  {
3085  if (pmState == PM_STARTUP)
3087  }
3088  else
3090  HandleChildCrash(pid, exitstatus,
3091  _("startup process"));
3092  continue;
3093  }
3094 
3095  /*
3096  * Startup succeeded, commence normal operations
3097  */
3099  FatalError = false;
3100  AbortStartTime = 0;
3101  ReachedNormalRunning = true;
3102  pmState = PM_RUN;
3104 
3105  /*
3106  * Crank up the background tasks, if we didn't do that already
3107  * when we entered consistent recovery state. It doesn't matter
3108  * if this fails, we'll just try again later.
3109  */
3110  if (CheckpointerPID == 0)
3112  if (BgWriterPID == 0)
3114  if (WalWriterPID == 0)
3116 
3117  /*
3118  * Likewise, start other special children as needed. In a restart
3119  * situation, some of them may be alive already.
3120  */
3123  if (PgArchStartupAllowed() && PgArchPID == 0)
3125  if (PgStatPID == 0)
3126  PgStatPID = pgstat_start();
3127 
3128  /* workers may be scheduled to start now */
3130 
3131  /* at this point we are really open for business */
3132  ereport(LOG,
3133  (errmsg("database system is ready to accept connections")));
3134 
3135  /* Report status */
3137 #ifdef USE_SYSTEMD
3138  sd_notify(0, "READY=1");
3139 #endif
3140 
3141  continue;
3142  }
3143 
3144  /*
3145  * Was it the bgwriter? Normal exit can be ignored; we'll start a new
3146  * one at the next iteration of the postmaster's main loop, if
3147  * necessary. Any other exit condition is treated as a crash.
3148  */
3149  if (pid == BgWriterPID)
3150  {
3151  BgWriterPID = 0;
3152  if (!EXIT_STATUS_0(exitstatus))
3153  HandleChildCrash(pid, exitstatus,
3154  _("background writer process"));
3155  continue;
3156  }
3157 
3158  /*
3159  * Was it the checkpointer?
3160  */
3161  if (pid == CheckpointerPID)
3162  {
3163  CheckpointerPID = 0;
3164  if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
3165  {
3166  /*
3167  * OK, we saw normal exit of the checkpointer after it's been
3168