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

Go to the source code of this file.

Data Structures

struct  bkend
 

Macros

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

Typedefs

typedef struct bkend Backend
 

Enumerations

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

Functions

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

Variables

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

Macro Definition Documentation

◆ BACKEND_TYPE_ALL

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

◆ BACKEND_TYPE_AUTOVAC

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

Definition at line 146 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 148 of file postmaster.c.

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

◆ BACKEND_TYPE_NORMAL

#define BACKEND_TYPE_NORMAL   0x0001 /* normal backend */

◆ BACKEND_TYPE_WALSND

#define BACKEND_TYPE_WALSND   0x0004 /* walsender process */

Definition at line 147 of file postmaster.c.

Referenced by CountChildren(), and SignalSomeChildren().

◆ BACKEND_TYPE_WORKER

#define BACKEND_TYPE_WORKER   (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)

Definition at line 151 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ EXIT_STATUS_0

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

Definition at line 548 of file postmaster.c.

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

◆ EXIT_STATUS_1

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

Definition at line 549 of file postmaster.c.

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

◆ EXIT_STATUS_3

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

Definition at line 550 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 274 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 275 of file postmaster.c.

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

◆ MAX_BGWORKERS_TO_LAUNCH

#define MAX_BGWORKERS_TO_LAUNCH   100

Referenced by maybe_start_bgworkers().

◆ MAXLISTEN

#define MAXLISTEN   64

◆ NoShutdown

#define NoShutdown   0

◆ OPTS_FILE

#define OPTS_FILE   "postmaster.opts"

Referenced by CreateOptsFile().

◆ PgArchStartupAllowed

#define PgArchStartupAllowed ( )
Value:
#define XLogArchivingAlways()
Definition: xlog.h:173
static PMState pmState
Definition: postmaster.c:341
#define XLogArchivingActive()
Definition: xlog.h:170

Definition at line 435 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 348 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 418 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 273 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 542 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 543 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 541 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 545 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

Definition at line 544 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

Typedef Documentation

◆ Backend

Enumeration Type Documentation

◆ PMState

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

Definition at line 323 of file postmaster.c.

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 261 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

Definition at line 5833 of file postmaster.c.

References AssignPostmasterChildSlot(), BACKEND_TYPE_BGWORKER, bkend::bgworker_notify, bkend::bkend_type, 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().

5834 {
5835  Backend *bn;
5836 
5837  /*
5838  * Compute the cancel key that will be assigned to this session. We
5839  * probably don't need cancel keys for background workers, but we'd better
5840  * have something random in the field to prevent unfriendly people from
5841  * sending cancels to them.
5842  */
5844  {
5845  ereport(LOG,
5846  (errcode(ERRCODE_INTERNAL_ERROR),
5847  errmsg("could not generate random cancel key")));
5848  return false;
5849  }
5850 
5851  bn = malloc(sizeof(Backend));
5852  if (bn == NULL)
5853  {
5854  ereport(LOG,
5855  (errcode(ERRCODE_OUT_OF_MEMORY),
5856  errmsg("out of memory")));
5857  return false;
5858  }
5859 
5860  bn->cancel_key = MyCancelKey;
5863  bn->dead_end = false;
5864  bn->bgworker_notify = false;
5865 
5866  rw->rw_backend = bn;
5867  rw->rw_child_slot = bn->child_slot;
5868 
5869  return true;
5870 }
struct bkend * rw_backend
int errcode(int sqlerrcode)
Definition: elog.c:570
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:182
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:184
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:44
int32 cancel_key
Definition: postmaster.c:172
bool dead_end
Definition: postmaster.c:181
#define ereport(elevel, rest)
Definition: elog.h:141
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5290
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
int MyPMChildSlot
Definition: globals.c:45
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4204 of file postmaster.c.

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

Referenced by BackendRun(), and BackendStartup().

4205 {
4206  int status;
4207  int ret;
4208  char remote_host[NI_MAXHOST];
4209  char remote_port[NI_MAXSERV];
4210  char remote_ps_data[NI_MAXHOST];
4211 
4212  /* Save port etc. for ps status */
4213  MyProcPort = port;
4214 
4215  /*
4216  * PreAuthDelay is a debugging aid for investigating problems in the
4217  * authentication cycle: it can be set in postgresql.conf to allow time to
4218  * attach to the newly-forked backend with a debugger. (See also
4219  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4220  * is not honored until after authentication.)
4221  */
4222  if (PreAuthDelay > 0)
4223  pg_usleep(PreAuthDelay * 1000000L);
4224 
4225  /* This flag will remain set until InitPostgres finishes authentication */
4226  ClientAuthInProgress = true; /* limit visibility of log messages */
4227 
4228  /* set these to empty in case they are needed before we set them up */
4229  port->remote_host = "";
4230  port->remote_port = "";
4231 
4232  /*
4233  * Initialize libpq and enable reporting of ereport errors to the client.
4234  * Must do this now because authentication uses libpq to send messages.
4235  */
4236  pq_init(); /* initialize libpq to talk to client */
4237  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4238 
4239  /*
4240  * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
4241  * timeout while trying to collect the startup packet. Otherwise the
4242  * postmaster cannot shutdown the database FAST or IMMED cleanly if a
4243  * buggy client fails to send the packet promptly. XXX it follows that
4244  * the remainder of this function must tolerate losing control at any
4245  * instant. Likewise, any pg_on_exit_callback registered before or during
4246  * this function must be prepared to execute at any instant between here
4247  * and the end of this function. Furthermore, affected callbacks execute
4248  * partially or not at all when a second exit-inducing signal arrives
4249  * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to
4250  * that mechanic, callbacks need not anticipate more than one call.) This
4251  * is fragile; it ought to instead follow the norm of handling interrupts
4252  * at selected, safe opportunities.
4253  */
4254  pqsignal(SIGTERM, startup_die);
4256  InitializeTimeouts(); /* establishes SIGALRM handler */
4258 
4259  /*
4260  * Get the remote host name and port for logging and status display.
4261  */
4262  remote_host[0] = '\0';
4263  remote_port[0] = '\0';
4264  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4265  remote_host, sizeof(remote_host),
4266  remote_port, sizeof(remote_port),
4267  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4268  ereport(WARNING,
4269  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4270  gai_strerror(ret))));
4271  if (remote_port[0] == '\0')
4272  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
4273  else
4274  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
4275 
4276  /*
4277  * Save remote_host and remote_port in port structure (after this, they
4278  * will appear in log_line_prefix data for log messages).
4279  */
4280  port->remote_host = strdup(remote_host);
4281  port->remote_port = strdup(remote_port);
4282 
4283  /* And now we can issue the Log_connections message, if wanted */
4284  if (Log_connections)
4285  {
4286  if (remote_port[0])
4287  ereport(LOG,
4288  (errmsg("connection received: host=%s port=%s",
4289  remote_host,
4290  remote_port)));
4291  else
4292  ereport(LOG,
4293  (errmsg("connection received: host=%s",
4294  remote_host)));
4295  }
4296 
4297  /*
4298  * If we did a reverse lookup to name, we might as well save the results
4299  * rather than possibly repeating the lookup during authentication.
4300  *
4301  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4302  * get nothing useful for a client without an rDNS entry. Therefore, we
4303  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4304  * it into remote_hostname if so. (This test is conservative and might
4305  * sometimes classify a hostname as numeric, but an error in that
4306  * direction is safe; it only results in a possible extra lookup.)
4307  */
4308  if (log_hostname &&
4309  ret == 0 &&
4310  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4311  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4312  port->remote_hostname = strdup(remote_host);
4313 
4314  /*
4315  * Ready to begin client interaction. We will give up and exit(1) after a
4316  * time delay, so that a broken client can't hog a connection
4317  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4318  * against the time limit.
4319  *
4320  * Note: AuthenticationTimeout is applied here while waiting for the
4321  * startup packet, and then again in InitPostgres for the duration of any
4322  * authentication operations. So a hostile client could tie up the
4323  * process for nearly twice AuthenticationTimeout before we kick him off.
4324  *
4325  * Note: because PostgresMain will call InitializeTimeouts again, the
4326  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4327  * since we never use it again after this function.
4328  */
4331 
4332  /*
4333  * Receive the startup packet (which might turn out to be a cancel request
4334  * packet).
4335  */
4336  status = ProcessStartupPacket(port, false);
4337 
4338  /*
4339  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4340  * already did any appropriate error reporting.
4341  */
4342  if (status != STATUS_OK)
4343  proc_exit(0);
4344 
4345  /*
4346  * Now that we have the user and database name, we can set the process
4347  * title for ps. It's good to do this as early as possible in startup.
4348  *
4349  * For a walsender, the ps display is set in the following form:
4350  *
4351  * postgres: walsender <user> <host> <activity>
4352  *
4353  * To achieve that, we pass "walsender" as username and username as dbname
4354  * to init_ps_display(). XXX: should add a new variant of
4355  * init_ps_display() to avoid abusing the parameters like this.
4356  */
4357  if (am_walsender)
4359  update_process_title ? "authentication" : "");
4360  else
4361  init_ps_display(port->user_name, port->database_name, remote_ps_data,
4362  update_process_title ? "authentication" : "");
4363 
4364  /*
4365  * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4366  */
4368  PG_SETMASK(&BlockSig);
4369 }
void InitializeTimeouts(void)
Definition: timeout.c:340
#define SIGQUIT
Definition: win32_port.h:164
static void startup_die(SIGNAL_ARGS)
Definition: postmaster.c:5256
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
struct Port * MyProcPort
Definition: globals.c:43
bool update_process_title
Definition: ps_status.c:35
static int ProcessStartupPacket(Port *port, bool secure_done)
Definition: postmaster.c:1898
const char * pgstat_get_backend_desc(BackendType backendType)
Definition: pgstat.c:4274
struct sockaddr_storage addr
Definition: pqcomm.h:64
void proc_exit(int code)
Definition: ipc.c:104
char * remote_port
Definition: libpq-be.h:132
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:242
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define gai_strerror
Definition: getaddrinfo.h:146
int AuthenticationTimeout
Definition: postmaster.c:239
char * remote_hostname
Definition: libpq-be.h:128
bool ClientAuthInProgress
Definition: postmaster.c:352
SockAddr raddr
Definition: libpq-be.h:126
bool am_walsender
Definition: walsender.c:114
void pg_usleep(long microsec)
Definition: signal.c:53
void pq_init(void)
Definition: pqcomm.c:194
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define NI_MAXSERV
Definition: getaddrinfo.h:91
char * user_name
Definition: libpq-be.h:141
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
bool log_hostname
Definition: postmaster.c:241
static int port
Definition: pg_regress.c:92
#define WARNING
Definition: elog.h:40
sigset_t BlockSig
Definition: pqsignal.c:22
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:373
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:428
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:122
sigset_t StartupBlockSig
Definition: pqsignal.c:22
int PreAuthDelay
Definition: postmaster.c:238
char * remote_host
Definition: libpq-be.h:127
int errmsg(const char *fmt,...)
Definition: elog.c:784
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5280
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
CommandDest whereToSendOutput
Definition: postgres.c:90
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
char * database_name
Definition: libpq-be.h:140
#define snprintf
Definition: port.h:192
void init_ps_display(const char *username, const char *dbname, const char *host_info, const char *initial_str)
Definition: ps_status.c:249

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4380 of file postmaster.c.

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

Referenced by BackendStartup().

4381 {
4382  char **av;
4383  int maxac;
4384  int ac;
4385  int i;
4386 
4387  /*
4388  * Now, build the argv vector that will be given to PostgresMain.
4389  *
4390  * The maximum possible number of commandline arguments that could come
4391  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4392  * pg_split_opts().
4393  */
4394  maxac = 2; /* for fixed args supplied below */
4395  maxac += (strlen(ExtraOptions) + 1) / 2;
4396 
4397  av = (char **) MemoryContextAlloc(TopMemoryContext,
4398  maxac * sizeof(char *));
4399  ac = 0;
4400 
4401  av[ac++] = "postgres";
4402 
4403  /*
4404  * Pass any backend switches specified with -o on the postmaster's own
4405  * command line. We assume these are secure.
4406  */
4407  pg_split_opts(av, &ac, ExtraOptions);
4408 
4409  av[ac] = NULL;
4410 
4411  Assert(ac < maxac);
4412 
4413  /*
4414  * Debug: print arguments being passed to backend
4415  */
4416  ereport(DEBUG3,
4417  (errmsg_internal("%s child[%d]: starting with (",
4418  progname, (int) getpid())));
4419  for (i = 0; i < ac; ++i)
4420  ereport(DEBUG3,
4421  (errmsg_internal("\t%s", av[i])));
4422  ereport(DEBUG3,
4423  (errmsg_internal(")")));
4424 
4425  /*
4426  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4427  * just yet, though, because InitPostgres will need the HBA data.)
4428  */
4430 
4431  PostgresMain(ac, av, port->database_name, port->user_name);
4432 }
#define DEBUG3
Definition: elog.h:23
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
const char * progname
Definition: pg_standby.c:37
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3727
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:469
char * user_name
Definition: libpq-be.h:141
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
struct @18::@19 av[32]
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:223
#define Assert(condition)
Definition: c.h:732
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i
char * database_name
Definition: libpq-be.h:140

◆ BackendStartup()

static int BackendStartup ( Port port)
static

Definition at line 4054 of file postmaster.c.

References AssignPostmasterChildSlot(), BACKEND_TYPE_NORMAL, BackendInitialize(), BackendRun(), bkend::bgworker_notify, bkend::bkend_type, CAC_OK, CAC_WAITBACKUP, Port::canAcceptConnections, canAcceptConnections(), bkend::cancel_key, bkend::child_slot, ClosePostmasterPorts(), bkend::dead_end, DEBUG2, dlist_push_head(), bkend::elem, ereport, errcode(), errmsg(), errmsg_internal(), fork_process(), free, InitPostmasterChild(), LOG, malloc, MyCancelKey, MyPMChildSlot, bkend::pid, RandomCancelKey(), ReleasePostmasterChildSlot(), report_fork_failure_to_client(), Port::sock, STATUS_ERROR, and STATUS_OK.

Referenced by ServerLoop().

4055 {
4056  Backend *bn; /* for backend cleanup */
4057  pid_t pid;
4058 
4059  /*
4060  * Create backend data structure. Better before the fork() so we can
4061  * handle failure cleanly.
4062  */
4063  bn = (Backend *) malloc(sizeof(Backend));
4064  if (!bn)
4065  {
4066  ereport(LOG,
4067  (errcode(ERRCODE_OUT_OF_MEMORY),
4068  errmsg("out of memory")));
4069  return STATUS_ERROR;
4070  }
4071 
4072  /*
4073  * Compute the cancel key that will be assigned to this backend. The
4074  * backend will have its own copy in the forked-off process' value of
4075  * MyCancelKey, so that it can transmit the key to the frontend.
4076  */
4078  {
4079  free(bn);
4080  ereport(LOG,
4081  (errcode(ERRCODE_INTERNAL_ERROR),
4082  errmsg("could not generate random cancel key")));
4083  return STATUS_ERROR;
4084  }
4085 
4086  bn->cancel_key = MyCancelKey;
4087 
4088  /* Pass down canAcceptConnections state */
4090  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
4092 
4093  /*
4094  * Unless it's a dead_end child, assign it a child slot number
4095  */
4096  if (!bn->dead_end)
4098  else
4099  bn->child_slot = 0;
4100 
4101  /* Hasn't asked to be notified about any bgworkers yet */
4102  bn->bgworker_notify = false;
4103 
4104 #ifdef EXEC_BACKEND
4105  pid = backend_forkexec(port);
4106 #else /* !EXEC_BACKEND */
4107  pid = fork_process();
4108  if (pid == 0) /* child */
4109  {
4110  free(bn);
4111 
4112  /* Detangle from postmaster */
4114 
4115  /* Close the postmaster's sockets */
4116  ClosePostmasterPorts(false);
4117 
4118  /* Perform additional initialization and collect startup packet */
4119  BackendInitialize(port);
4120 
4121  /* And run the backend */
4122  BackendRun(port);
4123  }
4124 #endif /* EXEC_BACKEND */
4125 
4126  if (pid < 0)
4127  {
4128  /* in parent, fork failed */
4129  int save_errno = errno;
4130 
4131  if (!bn->dead_end)
4133  free(bn);
4134  errno = save_errno;
4135  ereport(LOG,
4136  (errmsg("could not fork new process for connection: %m")));
4137  report_fork_failure_to_client(port, save_errno);
4138  return STATUS_ERROR;
4139  }
4140 
4141  /* in parent, successful fork */
4142  ereport(DEBUG2,
4143  (errmsg_internal("forked new backend, pid=%d socket=%d",
4144  (int) pid, (int) port->sock)));
4145 
4146  /*
4147  * Everything's been successful, it's safe to add this backend to our list
4148  * of backends.
4149  */
4150  bn->pid = pid;
4151  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4153 
4154 #ifdef EXEC_BACKEND
4155  if (!bn->dead_end)
4156  ShmemBackendArrayAdd(bn);
4157 #endif
4158 
4159  return STATUS_OK;
4160 }
CAC_state canAcceptConnections
Definition: libpq-be.h:133
void InitPostmasterChild(void)
Definition: miscinit.c:273
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
static void BackendRun(Port *port) pg_attribute_noreturn()
Definition: postmaster.c:4380
pid_t fork_process(void)
Definition: fork_process.c:31
int errcode(int sqlerrcode)
Definition: elog.c:570
#define STATUS_ERROR
Definition: c.h:1090
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2512
pgsocket sock
Definition: libpq-be.h:122
bool bgworker_notify
Definition: postmaster.c:182
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:184
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:44
static dlist_head BackendList
Definition: postmaster.c:186
#define DEBUG2
Definition: elog.h:24
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4171
int32 cancel_key
Definition: postmaster.c:172
bool dead_end
Definition: postmaster.c:181
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5290
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
pid_t pid
Definition: postmaster.c:171
int MyPMChildSlot
Definition: globals.c:45
int errmsg(const char *fmt,...)
Definition: elog.c:784
static CAC_state canAcceptConnections(void)
Definition: postmaster.c:2390
static void BackendInitialize(Port *port)
Definition: postmaster.c:4204

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5656 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5657 {
5658  PG_SETMASK(&BlockSig);
5659 }
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
sigset_t BlockSig
Definition: pqsignal.c:22

◆ BackgroundWorkerInitializeConnection()

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

Definition at line 5610 of file postmaster.c.

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

Referenced by ApplyLauncherMain(), and initialize_worker_spi().

5611 {
5613 
5614  /* XXX is this the right errcode? */
5616  ereport(FATAL,
5617  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5618  errmsg("database connection requirement not indicated during registration")));
5619 
5621 
5622  /* it had better not gotten out of "init" mode yet */
5623  if (!IsInitProcessingMode())
5624  ereport(ERROR,
5625  (errmsg("invalid processing mode in background worker")));
5627 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define SetProcessingMode(mode)
Definition: miscadmin.h:380
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:141
static char * username
Definition: initdb.c:133
#define InvalidOid
Definition: postgres_ext.h:36
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:592
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:52
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define IsInitProcessingMode()
Definition: miscadmin.h:375

◆ BackgroundWorkerInitializeConnectionByOid()

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

Definition at line 5633 of file postmaster.c.

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

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

5634 {
5636 
5637  /* XXX is this the right errcode? */
5639  ereport(FATAL,
5640  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5641  errmsg("database connection requirement not indicated during registration")));
5642 
5643  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5644 
5645  /* it had better not gotten out of "init" mode yet */
5646  if (!IsInitProcessingMode())
5647  ereport(ERROR,
5648  (errmsg("invalid processing mode in background worker")));
5650 }
int errcode(int sqlerrcode)
Definition: elog.c:570
#define SetProcessingMode(mode)
Definition: miscadmin.h:380
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
#define ERROR
Definition: elog.h:43
#define BGWORKER_BYPASS_ALLOWCONN
Definition: bgworker.h:154
#define FATAL
Definition: elog.h:52
#define ereport(elevel, rest)
Definition: elog.h:141
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:592
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define IsInitProcessingMode()
Definition: miscadmin.h:375

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

Definition at line 5662 of file postmaster.c.

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

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

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

◆ bgworker_should_start_now()

static bool bgworker_should_start_now ( BgWorkerStartTime  start_time)
static

Definition at line 5789 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

5790 {
5791  switch (pmState)
5792  {
5793  case PM_NO_CHILDREN:
5794  case PM_WAIT_DEAD_END:
5795  case PM_SHUTDOWN_2:
5796  case PM_SHUTDOWN:
5797  case PM_WAIT_BACKENDS:
5798  case PM_WAIT_READONLY:
5799  case PM_WAIT_BACKUP:
5800  break;
5801 
5802  case PM_RUN:
5804  return true;
5805  /* fall through */
5806 
5807  case PM_HOT_STANDBY:
5809  return true;
5810  /* fall through */
5811 
5812  case PM_RECOVERY:
5813  case PM_STARTUP:
5814  case PM_INIT:
5816  return true;
5817  /* fall through */
5818 
5819  }
5820 
5821  return false;
5822 }
static time_t start_time
Definition: pg_ctl.c:99
static PMState pmState
Definition: postmaster.c:341

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( void  )
static

Definition at line 2390 of file postmaster.c.

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

Referenced by BackendStartup(), and StartAutovacuumWorker().

2391 {
2392  CAC_state result = CAC_OK;
2393 
2394  /*
2395  * Can't start backends when in startup/shutdown/inconsistent recovery
2396  * state.
2397  *
2398  * In state PM_WAIT_BACKUP only superusers can connect (this must be
2399  * allowed so that a superuser can end online backup mode); we return
2400  * CAC_WAITBACKUP code to indicate that this must be checked later. Note
2401  * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
2402  * have checked for too many children.
2403  */
2404  if (pmState != PM_RUN)
2405  {
2406  if (pmState == PM_WAIT_BACKUP)
2407  result = CAC_WAITBACKUP; /* allow superusers only */
2408  else if (Shutdown > NoShutdown)
2409  return CAC_SHUTDOWN; /* shutdown is pending */
2410  else if (!FatalError &&
2411  (pmState == PM_STARTUP ||
2412  pmState == PM_RECOVERY))
2413  return CAC_STARTUP; /* normal startup */
2414  else if (!FatalError &&
2416  result = CAC_OK; /* connection OK during hot standby */
2417  else
2418  return CAC_RECOVERY; /* else must be crash recovery */
2419  }
2420 
2421  /*
2422  * Don't start too many children.
2423  *
2424  * We allow more connections than we can have backends here because some
2425  * might still be authenticating; they might fail auth, or some existing
2426  * backend might exit before the auth cycle is completed. The exact
2427  * MaxBackends limit is enforced when a new backend tries to join the
2428  * shared-inval backend array.
2429  *
2430  * The limit here must match the sizes of the per-child-process arrays;
2431  * see comments for MaxLivePostmasterChildren().
2432  */
2434  result = CAC_TOOMANY;
2435 
2436  return result;
2437 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
static bool FatalError
Definition: postmaster.c:279
static int Shutdown
Definition: postmaster.c:277
static int CountChildren(int target)
Definition: postmaster.c:5300
static PMState pmState
Definition: postmaster.c:341
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5600
#define NoShutdown
Definition: postmaster.c:272
CAC_state
Definition: libpq-be.h:71

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1493 of file postmaster.c.

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

Referenced by PostmasterMain().

1494 {
1495  char path[MAXPGPATH];
1496  FILE *fp;
1497 
1498  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1499 
1500  fp = AllocateFile(path, PG_BINARY_R);
1501  if (fp == NULL)
1502  {
1503  write_stderr("%s: could not find the database system\n"
1504  "Expected to find it in the directory \"%s\",\n"
1505  "but could not open file \"%s\": %s\n",
1506  progname, DataDir, path, strerror(errno));
1507  ExitPostmaster(2);
1508  }
1509  FreeFile(fp);
1510 }
#define write_stderr(str)
Definition: parallel.c:182
const char * progname
Definition: pg_standby.c:37
#define PG_BINARY_R
Definition: c.h:1193
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5046
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2207
#define strerror
Definition: port.h:205
int FreeFile(FILE *file)
Definition: fd.c:2406
char * DataDir
Definition: globals.c:62
#define snprintf
Definition: port.h:192

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

Definition at line 3296 of file postmaster.c.

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

Referenced by reaper().

3298 {
3299  dlist_mutable_iter iter;
3300 
3301  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3302 
3303  /*
3304  * If a backend dies in an ugly way then we must signal all other backends
3305  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3306  * assume everything is all right and proceed to remove the backend from
3307  * the active backend list.
3308  */
3309 
3310 #ifdef WIN32
3311 
3312  /*
3313  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3314  * since that sometimes happens under load when the process fails to start
3315  * properly (long before it starts using shared memory). Microsoft reports
3316  * it is related to mutex failure:
3317  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3318  */
3319  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3320  {
3321  LogChildExit(LOG, _("server process"), pid, exitstatus);
3322  exitstatus = 0;
3323  }
3324 #endif
3325 
3326  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3327  {
3328  HandleChildCrash(pid, exitstatus, _("server process"));
3329  return;
3330  }
3331 
3333  {
3334  Backend *bp = dlist_container(Backend, elem, iter.cur);
3335 
3336  if (bp->pid == pid)
3337  {
3338  if (!bp->dead_end)
3339  {
3341  {
3342  /*
3343  * Uh-oh, the child failed to clean itself up. Treat as a
3344  * crash after all.
3345  */
3346  HandleChildCrash(pid, exitstatus, _("server process"));
3347  return;
3348  }
3349 #ifdef EXEC_BACKEND
3350  ShmemBackendArrayRemove(bp);
3351 #endif
3352  }
3353  if (bp->bgworker_notify)
3354  {
3355  /*
3356  * This backend may have been slated to receive SIGUSR1 when
3357  * some background worker started or stopped. Cancel those
3358  * notifications, as we don't want to signal PIDs that are not
3359  * PostgreSQL backends. This gets skipped in the (probably
3360  * very common) case where the backend has never requested any
3361  * such notifications.
3362  */
3364  }
3365  dlist_delete(iter.cur);
3366  free(bp);
3367  break;
3368  }
3369  }
3370 }
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:493
bool bgworker_notify
Definition: postmaster.c:182
#define EXIT_STATUS_1(st)
Definition: postmaster.c:549
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:186
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:181
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int child_slot
Definition: postmaster.c:173
#define free(a)
Definition: header.h:65
pid_t pid
Definition: postmaster.c:171
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3380
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3636
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

Definition at line 3196 of file postmaster.c.

References _, BackgroundWorkerList, BackgroundWorkerStopNotifications(), BackgroundWorker::bgw_flags, BackgroundWorker::bgw_type, bkend::bgworker_notify, BGWORKER_SHMEM_ACCESS, slist_mutable_iter::cur, DEBUG1, dlist_delete(), bkend::elem, EXIT_STATUS_0, EXIT_STATUS_1, free, GetCurrentTimestamp(), HandleChildCrash(), LOG, LogChildExit(), MAXPGPATH, ReleasePostmasterChildSlot(), ReportBackgroundWorkerExit(), RegisteredBgWorker::rw_backend, RegisteredBgWorker::rw_child_slot, RegisteredBgWorker::rw_crashed_at, RegisteredBgWorker::rw_pid, RegisteredBgWorker::rw_terminate, RegisteredBgWorker::rw_worker, slist_container, slist_foreach_modify, and snprintf.

Referenced by reaper().

3198 {
3199  char namebuf[MAXPGPATH];
3200  slist_mutable_iter iter;
3201 
3203  {
3204  RegisteredBgWorker *rw;
3205 
3206  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3207 
3208  if (rw->rw_pid != pid)
3209  continue;
3210 
3211 #ifdef WIN32
3212  /* see CleanupBackend */
3213  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3214  exitstatus = 0;
3215 #endif
3216 
3217  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3218  rw->rw_worker.bgw_type);
3219 
3220 
3221  if (!EXIT_STATUS_0(exitstatus))
3222  {
3223  /* Record timestamp, so we know when to restart the worker. */
3225  }
3226  else
3227  {
3228  /* Zero exit status means terminate */
3229  rw->rw_crashed_at = 0;
3230  rw->rw_terminate = true;
3231  }
3232 
3233  /*
3234  * Additionally, for shared-memory-connected workers, just like a
3235  * backend, any exit status other than 0 or 1 is considered a crash
3236  * and causes a system-wide restart.
3237  */
3238  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3239  {
3240  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3241  {
3242  HandleChildCrash(pid, exitstatus, namebuf);
3243  return true;
3244  }
3245  }
3246 
3247  /*
3248  * We must release the postmaster child slot whether this worker is
3249  * connected to shared memory or not, but we only treat it as a crash
3250  * if it is in fact connected.
3251  */
3254  {
3255  HandleChildCrash(pid, exitstatus, namebuf);
3256  return true;
3257  }
3258 
3259  /* Get it out of the BackendList and clear out remaining data */
3260  dlist_delete(&rw->rw_backend->elem);
3261 #ifdef EXEC_BACKEND
3262  ShmemBackendArrayRemove(rw->rw_backend);
3263 #endif
3264 
3265  /*
3266  * It's possible that this background worker started some OTHER
3267  * background worker and asked to be notified when that worker started
3268  * or stopped. If so, cancel any notifications destined for the
3269  * now-dead backend.
3270  */
3271  if (rw->rw_backend->bgworker_notify)
3273  free(rw->rw_backend);
3274  rw->rw_backend = NULL;
3275  rw->rw_pid = 0;
3276  rw->rw_child_slot = 0;
3277  ReportBackgroundWorkerExit(&iter); /* report child death */
3278 
3279  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3280  namebuf, pid, exitstatus);
3281 
3282  return true;
3283  }
3284 
3285  return false;
3286 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
slist_node * cur
Definition: ilist.h:241
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:459
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:493
bool bgworker_notify
Definition: postmaster.c:182
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
#define EXIT_STATUS_1(st)
Definition: postmaster.c:549
#define MAXPGPATH
slist_head BackgroundWorkerList
Definition: bgworker.c:43
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define free(a)
Definition: header.h:65
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3380
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3636
BackgroundWorker rw_worker
#define snprintf
Definition: port.h:192
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

Definition at line 2512 of file postmaster.c.

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

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

2513 {
2514  int i;
2515 
2516 #ifndef WIN32
2517 
2518  /*
2519  * Close the write end of postmaster death watch pipe. It's important to
2520  * do this as early as possible, so that if postmaster dies, others won't
2521  * think that it's still running because we're holding the pipe open.
2522  */
2524  ereport(FATAL,
2526  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2528 #endif
2529 
2530  /* Close the listen sockets */
2531  for (i = 0; i < MAXLISTEN; i++)
2532  {
2533  if (ListenSocket[i] != PGINVALID_SOCKET)
2534  {
2537  }
2538  }
2539 
2540  /* If using syslogger, close the read side of the pipe */
2541  if (!am_syslogger)
2542  {
2543 #ifndef WIN32
2544  if (syslogPipe[0] >= 0)
2545  close(syslogPipe[0]);
2546  syslogPipe[0] = -1;
2547 #else
2548  if (syslogPipe[0])
2549  CloseHandle(syslogPipe[0]);
2550  syslogPipe[0] = 0;
2551 #endif
2552  }
2553 
2554 #ifdef USE_BONJOUR
2555  /* If using Bonjour, close the connection to the mDNS daemon */
2556  if (bonjour_sdref)
2557  close(DNSServiceRefSockFD(bonjour_sdref));
2558 #endif
2559 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
#define FATAL
Definition: elog.h:52
bool am_syslogger
Definition: syslogger.c:80
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
int postmaster_alive_fds[2]
Definition: postmaster.c:557
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:217
int syslogPipe[2]
Definition: syslogger.c:118

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1392 of file postmaster.c.

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

Referenced by PostmasterMain().

1393 {
1394  int i;
1395 
1396  /*
1397  * First, explicitly close all the socket FDs. We used to just let this
1398  * happen implicitly at postmaster exit, but it's better to close them
1399  * before we remove the postmaster.pid lockfile; otherwise there's a race
1400  * condition if a new postmaster wants to re-use the TCP port number.
1401  */
1402  for (i = 0; i < MAXLISTEN; i++)
1403  {
1404  if (ListenSocket[i] != PGINVALID_SOCKET)
1405  {
1408  }
1409  }
1410 
1411  /*
1412  * Next, remove any filesystem entries for Unix sockets. To avoid race
1413  * conditions against incoming postmasters, this must happen after closing
1414  * the sockets and before removing lock files.
1415  */
1417 
1418  /*
1419  * We don't do anything about socket lock files here; those will be
1420  * removed in a later on_proc_exit callback.
1421  */
1422 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
int i
void RemoveSocketFiles(void)
Definition: pqcomm.c:890
#define MAXLISTEN
Definition: postmaster.c:217

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

Definition at line 2446 of file postmaster.c.

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

Referenced by ServerLoop().

2447 {
2448  Port *port;
2449 
2450  if (!(port = (Port *) calloc(1, sizeof(Port))))
2451  {
2452  ereport(LOG,
2453  (errcode(ERRCODE_OUT_OF_MEMORY),
2454  errmsg("out of memory")));
2455  ExitPostmaster(1);
2456  }
2457 
2458  if (StreamConnection(serverFd, port) != STATUS_OK)
2459  {
2460  if (port->sock != PGINVALID_SOCKET)
2461  StreamClose(port->sock);
2462  ConnFree(port);
2463  return NULL;
2464  }
2465 
2466  /*
2467  * Allocate GSSAPI specific state struct
2468  */
2469 #ifndef EXEC_BACKEND
2470 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2471  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2472  if (!port->gss)
2473  {
2474  ereport(LOG,
2475  (errcode(ERRCODE_OUT_OF_MEMORY),
2476  errmsg("out of memory")));
2477  ExitPostmaster(1);
2478  }
2479 #endif
2480 #endif
2481 
2482  return port;
2483 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:845
static void ConnFree(Port *port)
Definition: postmaster.c:2490
int errcode(int sqlerrcode)
Definition: elog.c:570
Definition: libpq-be.h:120
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:716
pgsocket sock
Definition: libpq-be.h:122
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5046
#define ereport(elevel, rest)
Definition: elog.h:141
#define STATUS_OK
Definition: c.h:1089
static int port
Definition: pg_regress.c:92
#define PGINVALID_SOCKET
Definition: port.h:33
void * gss
Definition: libpq-be.h:184
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2490 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2491 {
2492 #ifdef USE_SSL
2493  secure_close(conn);
2494 #endif
2495  if (conn->gss)
2496  free(conn->gss);
2497  free(conn);
2498 }
PGconn * conn
Definition: streamutil.c:56
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:134

◆ CountChildren()

static int CountChildren ( int  target)
static

Definition at line 5300 of file postmaster.c.

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

Referenced by canAcceptConnections(), and PostmasterStateMachine().

5301 {
5302  dlist_iter iter;
5303  int cnt = 0;
5304 
5305  dlist_foreach(iter, &BackendList)
5306  {
5307  Backend *bp = dlist_container(Backend, elem, iter.cur);
5308 
5309  if (bp->dead_end)
5310  continue;
5311 
5312  /*
5313  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5314  * it first and avoid touching shared memory for every child.
5315  */
5316  if (target != BACKEND_TYPE_ALL)
5317  {
5318  /*
5319  * Assign bkend_type for any recently announced WAL Sender
5320  * processes.
5321  */
5322  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5325 
5326  if (!(target & bp->bkend_type))
5327  continue;
5328  }
5329 
5330  cnt++;
5331  }
5332  return cnt;
5333 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:186
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:147
bool dead_end
Definition: postmaster.c:181
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:240

◆ CreateOptsFile()

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

Definition at line 5560 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

Definition at line 1522 of file postmaster.c.

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

Referenced by ServerLoop().

1523 {
1524  TimestampTz next_wakeup = 0;
1525 
1526  /*
1527  * Normal case: either there are no background workers at all, or we're in
1528  * a shutdown sequence (during which we ignore bgworkers altogether).
1529  */
1530  if (Shutdown > NoShutdown ||
1532  {
1533  if (AbortStartTime != 0)
1534  {
1535  /* time left to abort; clamp to 0 in case it already expired */
1536  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1537  (time(NULL) - AbortStartTime);
1538  timeout->tv_sec = Max(timeout->tv_sec, 0);
1539  timeout->tv_usec = 0;
1540  }
1541  else
1542  {
1543  timeout->tv_sec = 60;
1544  timeout->tv_usec = 0;
1545  }
1546  return;
1547  }
1548 
1549  if (StartWorkerNeeded)
1550  {
1551  timeout->tv_sec = 0;
1552  timeout->tv_usec = 0;
1553  return;
1554  }
1555 
1556  if (HaveCrashedWorker)
1557  {
1558  slist_mutable_iter siter;
1559 
1560  /*
1561  * When there are crashed bgworkers, we sleep just long enough that
1562  * they are restarted when they request to be. Scan the list to
1563  * determine the minimum of all wakeup times according to most recent
1564  * crash time and requested restart interval.
1565  */
1567  {
1568  RegisteredBgWorker *rw;
1569  TimestampTz this_wakeup;
1570 
1571  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1572 
1573  if (rw->rw_crashed_at == 0)
1574  continue;
1575 
1577  || rw->rw_terminate)
1578  {
1579  ForgetBackgroundWorker(&siter);
1580  continue;
1581  }
1582 
1583  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1584  1000L * rw->rw_worker.bgw_restart_time);
1585  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1586  next_wakeup = this_wakeup;
1587  }
1588  }
1589 
1590  if (next_wakeup != 0)
1591  {
1592  long secs;
1593  int microsecs;
1594 
1596  &secs, &microsecs);
1597  timeout->tv_sec = secs;
1598  timeout->tv_usec = microsecs;
1599 
1600  /* Ensure we don't exceed one minute */
1601  if (timeout->tv_sec > 60)
1602  {
1603  timeout->tv_sec = 60;
1604  timeout->tv_usec = 0;
1605  }
1606  }
1607  else
1608  {
1609  timeout->tv_sec = 60;
1610  timeout->tv_usec = 0;
1611  }
1612 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:367
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:94
static volatile bool HaveCrashedWorker
Definition: postmaster.c:368
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
static int Shutdown
Definition: postmaster.c:277
slist_head BackgroundWorkerList
Definition: bgworker.c:43
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:412
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define SIGKILL_CHILDREN_AFTER_SECS
Definition: postmaster.c:348
#define Max(x, y)
Definition: c.h:898
#define NoShutdown
Definition: postmaster.c:272
BackgroundWorker rw_worker
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1643
static time_t AbortStartTime
Definition: postmaster.c:345

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

Definition at line 5698 of file postmaster.c.

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

Referenced by maybe_start_bgworkers().

5699 {
5700  pid_t worker_pid;
5701 
5702  Assert(rw->rw_pid == 0);
5703 
5704  /*
5705  * Allocate and assign the Backend element. Note we must do this before
5706  * forking, so that we can handle out of memory properly.
5707  *
5708  * Treat failure as though the worker had crashed. That way, the
5709  * postmaster will wait a bit before attempting to start it again; if it
5710  * tried again right away, most likely it'd find itself repeating the
5711  * out-of-memory or fork failure condition.
5712  */
5713  if (!assign_backendlist_entry(rw))
5714  {
5716  return false;
5717  }
5718 
5719  ereport(DEBUG1,
5720  (errmsg("starting background worker process \"%s\"",
5721  rw->rw_worker.bgw_name)));
5722 
5723 #ifdef EXEC_BACKEND
5724  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5725 #else
5726  switch ((worker_pid = fork_process()))
5727 #endif
5728  {
5729  case -1:
5730  /* in postmaster, fork failed ... */
5731  ereport(LOG,
5732  (errmsg("could not fork worker process: %m")));
5733  /* undo what assign_backendlist_entry did */
5735  rw->rw_child_slot = 0;
5736  free(rw->rw_backend);
5737  rw->rw_backend = NULL;
5738  /* mark entry as crashed, so we'll try again later */
5740  break;
5741 
5742 #ifndef EXEC_BACKEND
5743  case 0:
5744  /* in postmaster child ... */
5746 
5747  /* Close the postmaster's sockets */
5748  ClosePostmasterPorts(false);
5749 
5750  /*
5751  * Before blowing away PostmasterContext, save this bgworker's
5752  * data where it can find it.
5753  */
5756  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5757 
5758  /* Release postmaster's working memory context */
5761  PostmasterContext = NULL;
5762 
5764 
5765  exit(1); /* should not get here */
5766  break;
5767 #endif
5768  default:
5769  /* in postmaster, fork successful ... */
5770  rw->rw_pid = worker_pid;
5771  rw->rw_backend->pid = rw->rw_pid;
5773  /* add new worker to lists of backends */
5775 #ifdef EXEC_BACKEND
5776  ShmemBackendArrayAdd(rw->rw_backend);
5777 #endif
5778  return true;
5779  }
5780 
5781  return false;
5782 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:273
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
pid_t fork_process(void)
Definition: fork_process.c:31
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:192
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2512
void StartBackgroundWorker(void)
Definition: bgworker.c:701
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:440
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5833
static dlist_head BackendList
Definition: postmaster.c:186
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define free(a)
Definition: header.h:65
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:732
pid_t pid
Definition: postmaster.c:171
int errmsg(const char *fmt,...)
Definition: elog.c:784
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
BackgroundWorker rw_worker
MemoryContext PostmasterContext
Definition: mcxt.c:46

◆ dummy_handler()

static void dummy_handler ( SIGNAL_ARGS  )
static

Definition at line 5271 of file postmaster.c.

Referenced by PostmasterMain().

5272 {
5273 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 5046 of file postmaster.c.

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

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

5047 {
5048 #ifdef HAVE_PTHREAD_IS_THREADED_NP
5049 
5050  /*
5051  * There is no known cause for a postmaster to become multithreaded after
5052  * startup. Recheck to account for the possibility of unknown causes.
5053  * This message uses LOG level, because an unclean shutdown at this point
5054  * would usually not look much different from a clean shutdown.
5055  */
5056  if (pthread_is_threaded_np() != 0)
5057  ereport(LOG,
5058  (errcode(ERRCODE_INTERNAL_ERROR),
5059  errmsg_internal("postmaster became multithreaded"),
5060  errdetail("Please report this to <pgsql-bugs@lists.postgresql.org>.")));
5061 #endif
5062 
5063  /* should cleanup shared memory and kill all backends */
5064 
5065  /*
5066  * Not sure of the semantics here. When the Postmaster dies, should the
5067  * backends all be killed? probably not.
5068  *
5069  * MUST -- vadim 05-10-1999
5070  */
5071 
5072  proc_exit(status);
5073 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:570
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

Definition at line 1440 of file postmaster.c.

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

Referenced by PostmasterMain().

1441 {
1442  DIR *pdir;
1443 
1444  /* Locate the postgres executable itself */
1445  if (find_my_exec(argv0, my_exec_path) < 0)
1446  elog(FATAL, "%s: could not locate my own executable path", argv0);
1447 
1448 #ifdef EXEC_BACKEND
1449  /* Locate executable backend before we change working directory */
1450  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1451  postgres_exec_path) < 0)
1452  ereport(FATAL,
1453  (errmsg("%s: could not locate matching postgres executable",
1454  argv0)));
1455 #endif
1456 
1457  /*
1458  * Locate the pkglib directory --- this has to be set early in case we try
1459  * to load any modules from it in response to postgresql.conf entries.
1460  */
1462 
1463  /*
1464  * Verify that there's a readable directory there; otherwise the Postgres
1465  * installation is incomplete or corrupt. (A typical cause of this
1466  * failure is that the postgres executable has been moved or hardlinked to
1467  * some directory that's not a sibling of the installation lib/
1468  * directory.)
1469  */
1470  pdir = AllocateDir(pkglib_path);
1471  if (pdir == NULL)
1472  ereport(ERROR,
1474  errmsg("could not open directory \"%s\": %m",
1475  pkglib_path),
1476  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1477  my_exec_path)));
1478  FreeDir(pdir);
1479 
1480  /*
1481  * XXX is it worth similarly checking the share/ directory? If the lib/
1482  * directory is there, then share/ probably is too.
1483  */
1484 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:324
static char * argv0
Definition: pg_ctl.c:97
int errhint(const char *fmt,...)
Definition: elog.c:974
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:129
int errcode_for_file_access(void)
Definition: elog.c:593
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2468
#define ereport(elevel, rest)
Definition: elog.h:141
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
#define PG_BACKEND_VERSIONSTR
Definition: port.h:111
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
char pkglib_path[MAXPGPATH]
Definition: globals.c:73
int FreeDir(DIR *dir)
Definition: fd.c:2586

◆ HandleChildCrash()

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

Definition at line 3380 of file postmaster.c.

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

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

3381 {
3382  dlist_mutable_iter iter;
3383  slist_iter siter;
3384  Backend *bp;
3385  bool take_action;
3386 
3387  /*
3388  * We only log messages and send signals if this is the first process
3389  * crash and we're not doing an immediate shutdown; otherwise, we're only
3390  * here to update postmaster's idea of live processes. If we have already
3391  * signalled children, nonzero exit status is to be expected, so don't
3392  * clutter log.
3393  */
3394  take_action = !FatalError && Shutdown != ImmediateShutdown;
3395 
3396  if (take_action)
3397  {
3398  LogChildExit(LOG, procname, pid, exitstatus);
3399  ereport(LOG,
3400  (errmsg("terminating any other active server processes")));
3401  }
3402 
3403  /* Process background workers. */
3405  {
3406  RegisteredBgWorker *rw;
3407 
3408  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3409  if (rw->rw_pid == 0)
3410  continue; /* not running */
3411  if (rw->rw_pid == pid)
3412  {
3413  /*
3414  * Found entry for freshly-dead worker, so remove it.
3415  */
3417  dlist_delete(&rw->rw_backend->elem);
3418 #ifdef EXEC_BACKEND
3419  ShmemBackendArrayRemove(rw->rw_backend);
3420 #endif
3421  free(rw->rw_backend);
3422  rw->rw_backend = NULL;
3423  rw->rw_pid = 0;
3424  rw->rw_child_slot = 0;
3425  /* don't reset crashed_at */
3426  /* don't report child stop, either */
3427  /* Keep looping so we can signal remaining workers */
3428  }
3429  else
3430  {
3431  /*
3432  * This worker is still alive. Unless we did so already, tell it
3433  * to commit hara-kiri.
3434  *
3435  * SIGQUIT is the special signal that says exit without proc_exit
3436  * and let the user know what's going on. But if SendStop is set
3437  * (-s on command line), then we send SIGSTOP instead, so that we
3438  * can get core dumps from all backends by hand.
3439  */
3440  if (take_action)
3441  {
3442  ereport(DEBUG2,
3443  (errmsg_internal("sending %s to process %d",
3444  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3445  (int) rw->rw_pid)));
3447  }
3448  }
3449  }
3450 
3451  /* Process regular backends */
3453  {
3454  bp = dlist_container(Backend, elem, iter.cur);
3455 
3456  if (bp->pid == pid)
3457  {
3458  /*
3459  * Found entry for freshly-dead backend, so remove it.
3460  */
3461  if (!bp->dead_end)
3462  {
3464 #ifdef EXEC_BACKEND
3465  ShmemBackendArrayRemove(bp);
3466 #endif
3467  }
3468  dlist_delete(iter.cur);
3469  free(bp);
3470  /* Keep looping so we can signal remaining backends */
3471  }
3472  else
3473  {
3474  /*
3475  * This backend is still alive. Unless we did so already, tell it
3476  * to commit hara-kiri.
3477  *
3478  * SIGQUIT is the special signal that says exit without proc_exit
3479  * and let the user know what's going on. But if SendStop is set
3480  * (-s on command line), then we send SIGSTOP instead, so that we
3481  * can get core dumps from all backends by hand.
3482  *
3483  * We could exclude dead_end children here, but at least in the
3484  * SIGSTOP case it seems better to include them.
3485  *
3486  * Background workers were already processed above; ignore them
3487  * here.
3488  */
3489  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3490  continue;
3491 
3492  if (take_action)
3493  {
3494  ereport(DEBUG2,
3495  (errmsg_internal("sending %s to process %d",
3496  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3497  (int) bp->pid)));
3498  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3499  }
3500  }
3501  }
3502 
3503  /* Take care of the startup process too */
3504  if (pid == StartupPID)
3505  {
3506  StartupPID = 0;
3508  }
3509  else if (StartupPID != 0 && take_action)
3510  {
3511  ereport(DEBUG2,
3512  (errmsg_internal("sending %s to process %d",
3513  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3514  (int) StartupPID)));
3517  }
3518 
3519  /* Take care of the bgwriter too */
3520  if (pid == BgWriterPID)
3521  BgWriterPID = 0;
3522  else if (BgWriterPID != 0 && take_action)
3523  {
3524  ereport(DEBUG2,
3525  (errmsg_internal("sending %s to process %d",
3526  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3527  (int) BgWriterPID)));
3529  }
3530 
3531  /* Take care of the checkpointer too */
3532  if (pid == CheckpointerPID)
3533  CheckpointerPID = 0;
3534  else if (CheckpointerPID != 0 && take_action)
3535  {
3536  ereport(DEBUG2,
3537  (errmsg_internal("sending %s to process %d",
3538  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3539  (int) CheckpointerPID)));
3541  }
3542 
3543  /* Take care of the walwriter too */
3544  if (pid == WalWriterPID)
3545  WalWriterPID = 0;
3546  else if (WalWriterPID != 0 && take_action)
3547  {
3548  ereport(DEBUG2,
3549  (errmsg_internal("sending %s to process %d",
3550  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3551  (int) WalWriterPID)));
3553  }
3554 
3555  /* Take care of the walreceiver too */
3556  if (pid == WalReceiverPID)
3557  WalReceiverPID = 0;
3558  else if (WalReceiverPID != 0 && take_action)
3559  {
3560  ereport(DEBUG2,
3561  (errmsg_internal("sending %s to process %d",
3562  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3563  (int) WalReceiverPID)));
3565  }
3566 
3567  /* Take care of the autovacuum launcher too */
3568  if (pid == AutoVacPID)
3569  AutoVacPID = 0;
3570  else if (AutoVacPID != 0 && take_action)
3571  {
3572  ereport(DEBUG2,
3573  (errmsg_internal("sending %s to process %d",
3574  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3575  (int) AutoVacPID)));
3577  }
3578 
3579  /*
3580  * Force a power-cycle of the pgarch process too. (This isn't absolutely
3581  * necessary, but it seems like a good idea for robustness, and it
3582  * simplifies the state-machine logic in the case where a shutdown request
3583  * arrives during crash processing.)
3584  */
3585  if (PgArchPID != 0 && take_action)
3586  {
3587  ereport(DEBUG2,
3588  (errmsg_internal("sending %s to process %d",
3589  "SIGQUIT",
3590  (int) PgArchPID)));
3592  }
3593 
3594  /*
3595  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3596  * necessary, but it seems like a good idea for robustness, and it
3597  * simplifies the state-machine logic in the case where a shutdown request
3598  * arrives during crash processing.)
3599  */
3600  if (PgStatPID != 0 && take_action)
3601  {
3602  ereport(DEBUG2,
3603  (errmsg_internal("sending %s to process %d",
3604  "SIGQUIT",
3605  (int) PgStatPID)));
3608  }
3609 
3610  /* We do NOT restart the syslogger */
3611 
3612  if (Shutdown != ImmediateShutdown)
3613  FatalError = true;
3614 
3615  /* We now transit into a state of waiting for children to die */
3616  if (pmState == PM_RECOVERY ||
3617  pmState == PM_HOT_STANDBY ||
3618  pmState == PM_RUN ||
3619  pmState == PM_WAIT_BACKUP ||
3621  pmState == PM_SHUTDOWN)
3623 
3624  /*
3625  * .. and if this doesn't happen quickly enough, now the clock is ticking
3626  * for us to kill them without mercy.
3627  */
3628  if (AbortStartTime == 0)
3629  AbortStartTime = time(NULL);
3630 }
struct bkend * rw_backend
#define SIGQUIT
Definition: win32_port.h:164
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static pid_t PgStatPID
Definition: postmaster.c:257
slist_node * cur
Definition: ilist.h:226
static pid_t CheckpointerPID
Definition: postmaster.c:252
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool FatalError
Definition: postmaster.c:279
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:218
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:183
#define SIGSTOP
Definition: win32_port.h:170
static int Shutdown
Definition: postmaster.c:277
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static pid_t BgWriterPID
Definition: postmaster.c:251
static pid_t StartupPID
Definition: postmaster.c:250
static dlist_head BackendList
Definition: postmaster.c:186
slist_head BackgroundWorkerList
Definition: bgworker.c:43
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:181
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3951
#define ereport(elevel, rest)
Definition: elog.h:141
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
int child_slot
Definition: postmaster.c:173
int bkend_type
Definition: postmaster.c:180
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
static PMState pmState
Definition: postmaster.c:341
#define ImmediateShutdown
Definition: postmaster.c:275
#define free(a)
Definition: header.h:65
static pid_t WalWriterPID
Definition: postmaster.c:253
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
pid_t pid
Definition: postmaster.c:171
static pid_t AutoVacPID
Definition: postmaster.c:255
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
int errmsg(const char *fmt,...)
Definition: elog.c:784
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3636
static int SendStop
Definition: postmaster.c:233
static time_t AbortStartTime
Definition: postmaster.c:345
void allow_immediate_pgstat_restart(void)
Definition: pgstat.c:791
static pid_t PgArchPID
Definition: postmaster.c:256

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1860 of file postmaster.c.

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

Referenced by ServerLoop().

1861 {
1862  int maxsock = -1;
1863  int i;
1864 
1865  FD_ZERO(rmask);
1866 
1867  for (i = 0; i < MAXLISTEN; i++)
1868  {
1869  int fd = ListenSocket[i];
1870 
1871  if (fd == PGINVALID_SOCKET)
1872  break;
1873  FD_SET(fd, rmask);
1874 
1875  if (fd > maxsock)
1876  maxsock = fd;
1877  }
1878 
1879  return maxsock + 1;
1880 }
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:218
#define PGINVALID_SOCKET
Definition: port.h:33
int i
#define MAXLISTEN
Definition: postmaster.c:217

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

Definition at line 6473 of file postmaster.c.

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

Referenced by PostmasterMain().

6474 {
6475 #ifndef WIN32
6476 
6477  /*
6478  * Create a pipe. Postmaster holds the write end of the pipe open
6479  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6480  * the read file descriptor to select() to wake up in case postmaster
6481  * dies, or check for postmaster death with a (read() == 0). Children must
6482  * close the write end as soon as possible after forking, because EOF
6483  * won't be signaled in the read end until all processes have closed the
6484  * write fd. That is taken care of in ClosePostmasterPorts().
6485  */
6487  if (pipe(postmaster_alive_fds) < 0)
6488  ereport(FATAL,
6490  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6491 
6492  /*
6493  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6494  * call.
6495  */
6496  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6497  ereport(FATAL,
6499  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6500 #else
6501 
6502  /*
6503  * On Windows, we use a process handle for the same purpose.
6504  */
6505  if (DuplicateHandle(GetCurrentProcess(),
6506  GetCurrentProcess(),
6507  GetCurrentProcess(),
6508  &PostmasterHandle,
6509  0,
6510  TRUE,
6511  DUPLICATE_SAME_ACCESS) == 0)
6512  ereport(FATAL,
6513  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6514  GetLastError())));
6515 #endif /* WIN32 */
6516 }
#define TRUE
Definition: ecpglib.h:35
int MyProcPid
Definition: globals.c:40
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
int errcode_for_socket_access(void)
Definition: elog.c:664
pid_t PostmasterPid
Definition: globals.c:95
int postmaster_alive_fds[2]
Definition: postmaster.c:557
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
#define Assert(condition)
Definition: c.h:732
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42

◆ InitProcessGlobals()

void InitProcessGlobals ( void  )

Definition at line 2568 of file postmaster.c.

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

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

2569 {
2570  unsigned int rseed;
2571 
2572  MyProcPid = getpid();
2575 
2576  /*
2577  * Set a different seed for random() in every process. We want something
2578  * unpredictable, so if possible, use high-quality random bits for the
2579  * seed. Otherwise, fall back to a seed based on timestamp and PID.
2580  */
2581  if (!pg_strong_random(&rseed, sizeof(rseed)))
2582  {
2583  /*
2584  * Since PIDs and timestamps tend to change more frequently in their
2585  * least significant bits, shift the timestamp left to allow a larger
2586  * total number of seeds in a given time period. Since that would
2587  * leave only 20 bits of the timestamp that cycle every ~1 second,
2588  * also mix in some higher bits.
2589  */
2590  rseed = ((uint64) MyProcPid) ^
2591  ((uint64) MyStartTimestamp << 12) ^
2592  ((uint64) MyStartTimestamp >> 20);
2593  }
2594  srandom(rseed);
2595 }
int MyProcPid
Definition: globals.c:40
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
pg_time_t MyStartTime
Definition: globals.c:41
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1711
TimestampTz MyStartTimestamp
Definition: globals.c:42
bool pg_strong_random(void *buf, size_t len)
void srandom(unsigned int seed)
Definition: srandom.c:22

◆ LogChildExit()

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

Definition at line 3636 of file postmaster.c.

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

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

3637 {
3638  /*
3639  * size of activity_buffer is arbitrary, but set equal to default
3640  * track_activity_query_size
3641  */
3642  char activity_buffer[1024];
3643  const char *activity = NULL;
3644 
3645  if (!EXIT_STATUS_0(exitstatus))
3646  activity = pgstat_get_crashed_backend_activity(pid,
3647  activity_buffer,
3648  sizeof(activity_buffer));
3649 
3650  if (WIFEXITED(exitstatus))
3651  ereport(lev,
3652 
3653  /*------
3654  translator: %s is a noun phrase describing a child process, such as
3655  "server process" */
3656  (errmsg("%s (PID %d) exited with exit code %d",
3657  procname, pid, WEXITSTATUS(exitstatus)),
3658  activity ? errdetail("Failed process was running: %s", activity) : 0));
3659  else if (WIFSIGNALED(exitstatus))
3660  {
3661 #if defined(WIN32)
3662  ereport(lev,
3663 
3664  /*------
3665  translator: %s is a noun phrase describing a child process, such as
3666  "server process" */
3667  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3668  procname, pid, WTERMSIG(exitstatus)),
3669  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3670  activity ? errdetail("Failed process was running: %s", activity) : 0));
3671 #else
3672  ereport(lev,
3673 
3674  /*------
3675  translator: %s is a noun phrase describing a child process, such as
3676  "server process" */
3677  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3678  procname, pid, WTERMSIG(exitstatus),
3679  pg_strsignal(WTERMSIG(exitstatus))),
3680  activity ? errdetail("Failed process was running: %s", activity) : 0));
3681 #endif
3682  }
3683  else
3684  ereport(lev,
3685 
3686  /*------
3687  translator: %s is a noun phrase describing a child process, such as
3688  "server process" */
3689  (errmsg("%s (PID %d) exited with unrecognized status %d",
3690  procname, pid, exitstatus),
3691  activity ? errdetail("Failed process was running: %s", activity) : 0));
3692 }
int errhint(const char *fmt,...)
Definition: elog.c:974
#define WTERMSIG(w)
Definition: win32_port.h:150
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
#define WIFEXITED(w)
Definition: win32_port.h:147
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:37
int errmsg(const char *fmt,...)
Definition: elog.c:784
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
Definition: pgstat.c:4215
#define WIFSIGNALED(w)
Definition: win32_port.h:148
#define WEXITSTATUS(w)
Definition: win32_port.h:149
#define EXIT_STATUS_0(st)
Definition: postmaster.c:548

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5600 of file postmaster.c.

References autovacuum_max_workers, max_wal_senders, max_worker_processes, and MaxConnections.

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

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

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

Definition at line 5884 of file postmaster.c.

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

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

5885 {
5886 #define MAX_BGWORKERS_TO_LAUNCH 100
5887  int num_launched = 0;
5888  TimestampTz now = 0;
5889  slist_mutable_iter iter;
5890 
5891  /*
5892  * During crash recovery, we have no need to be called until the state
5893  * transition out of recovery.
5894  */
5895  if (FatalError)
5896  {
5897  StartWorkerNeeded = false;
5898  HaveCrashedWorker = false;
5899  return;
5900  }
5901 
5902  /* Don't need to be called again unless we find a reason for it below */
5903  StartWorkerNeeded = false;
5904  HaveCrashedWorker = false;
5905 
5907  {
5908  RegisteredBgWorker *rw;
5909 
5910  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5911 
5912  /* ignore if already running */
5913  if (rw->rw_pid != 0)
5914  continue;
5915 
5916  /* if marked for death, clean up and remove from list */
5917  if (rw->rw_terminate)
5918  {
5919  ForgetBackgroundWorker(&iter);
5920  continue;
5921  }
5922 
5923  /*
5924  * If this worker has crashed previously, maybe it needs to be
5925  * restarted (unless on registration it specified it doesn't want to
5926  * be restarted at all). Check how long ago did a crash last happen.
5927  * If the last crash is too recent, don't start it right away; let it
5928  * be restarted once enough time has passed.
5929  */
5930  if (rw->rw_crashed_at != 0)
5931  {
5933  {
5934  int notify_pid;
5935 
5936  notify_pid = rw->rw_worker.bgw_notify_pid;
5937 
5938  ForgetBackgroundWorker(&iter);
5939 
5940  /* Report worker is gone now. */
5941  if (notify_pid != 0)
5942  kill(notify_pid, SIGUSR1);
5943 
5944  continue;
5945  }
5946 
5947  /* read system time only when needed */
5948  if (now == 0)
5949  now = GetCurrentTimestamp();
5950 
5952  rw->rw_worker.bgw_restart_time * 1000))
5953  {
5954  /* Set flag to remember that we have workers to start later */
5955  HaveCrashedWorker = true;
5956  continue;
5957  }
5958  }
5959 
5961  {
5962  /* reset crash time before trying to start worker */
5963  rw->rw_crashed_at = 0;
5964 
5965  /*
5966  * Try to start the worker.
5967  *
5968  * On failure, give up processing workers for now, but set
5969  * StartWorkerNeeded so we'll come back here on the next iteration
5970  * of ServerLoop to try again. (We don't want to wait, because
5971  * there might be additional ready-to-run workers.) We could set
5972  * HaveCrashedWorker as well, since this worker is now marked
5973  * crashed, but there's no need because the next run of this
5974  * function will do that.
5975  */
5976  if (!do_start_bgworker(rw))
5977  {
5978  StartWorkerNeeded = true;
5979  return;
5980  }
5981 
5982  /*
5983  * If we've launched as many workers as allowed, quit, but have
5984  * ServerLoop call us again to look for additional ready-to-run
5985  * workers. There might not be any, but we'll find out the next
5986  * time we run.
5987  */
5988  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5989  {
5990  StartWorkerNeeded = true;
5991  return;
5992  }
5993  }
5994  }
5995 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:367
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5789
#define SIGUSR1
Definition: win32_port.h:175
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
slist_node * cur
Definition: ilist.h:241
int bgw_restart_time
Definition: bgworker.h:94
#define kill(pid, sig)
Definition: win32_port.h:435
static bool FatalError
Definition: postmaster.c:279
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1668
static volatile bool HaveCrashedWorker
Definition: postmaster.c:368
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
slist_head BackgroundWorkerList
Definition: bgworker.c:43
void ForgetBackgroundWorker(slist_mutable_iter *cur)
Definition: bgworker.c:412
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
static bool do_start_bgworker(RegisteredBgWorker *rw)
Definition: postmaster.c:5698
#define MAX_BGWORKERS_TO_LAUNCH
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
pid_t bgw_notify_pid
Definition: bgworker.h:99
BackgroundWorker rw_worker
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

Definition at line 5541 of file postmaster.c.

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

Referenced by ServerLoop(), and sigusr1_handler().

5542 {
5543  if (WalReceiverPID == 0 &&
5544  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5546  Shutdown == NoShutdown)
5547  {
5549  if (WalReceiverPID != 0)
5550  WalReceiverRequested = false;
5551  /* else leave the flag set, so we'll try again later */
5552  }
5553 }
static pid_t WalReceiverPID
Definition: postmaster.c:254
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:364
static int Shutdown
Definition: postmaster.c:277
static PMState pmState
Definition: postmaster.c:341
#define NoShutdown
Definition: postmaster.c:272
#define StartWalReceiver()
Definition: postmaster.c:545

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

Definition at line 2694 of file postmaster.c.

References AbortStartTime, AddToDataDirLockFile(), AutoVacPID, BACKEND_TYPE_AUTOVAC, BACKEND_TYPE_BGWORKER, BACKEND_TYPE_NORMAL, BgWriterPID, BlockSig, DEBUG2, ereport, errmsg(), errmsg_internal(), FastShutdown, ImmediateShutdown, LOCK_FILE_LINE_PM_STATUS, LOG, PG_SETMASK, PM_HOT_STANDBY, PM_RECOVERY, PM_RUN, PM_STARTUP, PM_STATUS_STOPPING, PM_WAIT_BACKENDS, PM_WAIT_BACKUP, PM_WAIT_READONLY, pmState, PostmasterStateMachine(), Shutdown, signal_child(), SignalSomeChildren(), SIGQUIT, SmartShutdown, StartupPID, TerminateChildren(), UnBlockSig, WalReceiverPID, and WalWriterPID.

Referenced by PostmasterMain().

2695 {
2696  int save_errno = errno;
2697 
2698  PG_SETMASK(&BlockSig);
2699 
2700  ereport(DEBUG2,
2701  (errmsg_internal("postmaster received signal %d",
2702  postgres_signal_arg)));
2703 
2704  switch (postgres_signal_arg)
2705  {
2706  case SIGTERM:
2707 
2708  /*
2709  * Smart Shutdown:
2710  *
2711  * Wait for children to end their work, then shut down.
2712  */
2713  if (Shutdown >= SmartShutdown)
2714  break;
2716  ereport(LOG,
2717  (errmsg("received smart shutdown request")));
2718 
2719  /* Report status */
2721 #ifdef USE_SYSTEMD
2722  sd_notify(0, "STOPPING=1");
2723 #endif
2724 
2725  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2727  {
2728  /* autovac workers are told to shut down immediately */
2729  /* and bgworkers too; does this need tweaking? */
2730  SignalSomeChildren(SIGTERM,
2732  /* and the autovac launcher too */
2733  if (AutoVacPID != 0)
2734  signal_child(AutoVacPID, SIGTERM);
2735  /* and the bgwriter too */
2736  if (BgWriterPID != 0)
2737  signal_child(BgWriterPID, SIGTERM);
2738  /* and the walwriter too */
2739  if (WalWriterPID != 0)
2740  signal_child(WalWriterPID, SIGTERM);
2741 
2742  /*
2743  * If we're in recovery, we can't kill the startup process
2744  * right away, because at present doing so does not release
2745  * its locks. We might want to change this in a future
2746  * release. For the time being, the PM_WAIT_READONLY state
2747  * indicates that we're waiting for the regular (read only)
2748  * backends to die off; once they do, we'll kill the startup
2749  * and walreceiver processes.
2750  */
2751  pmState = (pmState == PM_RUN) ?
2753  }
2754 
2755  /*
2756  * Now wait for online backup mode to end and backends to exit. If
2757  * that is already the case, PostmasterStateMachine will take the
2758  * next step.
2759  */
2761  break;
2762 
2763  case SIGINT:
2764 
2765  /*
2766  * Fast Shutdown:
2767  *
2768  * Abort all children with SIGTERM (rollback active transactions
2769  * and exit) and shut down when they are gone.
2770  */
2771  if (Shutdown >= FastShutdown)
2772  break;
2774  ereport(LOG,
2775  (errmsg("received fast shutdown request")));
2776 
2777  /* Report status */
2779 #ifdef USE_SYSTEMD
2780  sd_notify(0, "STOPPING=1");
2781 #endif
2782 
2783  if (StartupPID != 0)
2784  signal_child(StartupPID, SIGTERM);
2785  if (BgWriterPID != 0)
2786  signal_child(BgWriterPID, SIGTERM);
2787  if (WalReceiverPID != 0)
2788  signal_child(WalReceiverPID, SIGTERM);
2789  if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
2790  {
2792 
2793  /*
2794  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2795  * and/or checkpointer should be active in this state; we just
2796  * signaled the first four, and we don't want to kill
2797  * checkpointer yet.
2798  */
2800  }
2801  else if (pmState == PM_RUN ||
2802  pmState == PM_WAIT_BACKUP ||
2806  {
2807  ereport(LOG,
2808  (errmsg("aborting any active transactions")));
2809  /* shut down all backends and workers */
2810  SignalSomeChildren(SIGTERM,
2813  /* and the autovac launcher too */
2814  if (AutoVacPID != 0)
2815  signal_child(AutoVacPID, SIGTERM);
2816  /* and the walwriter too */
2817  if (WalWriterPID != 0)
2818  signal_child(WalWriterPID, SIGTERM);
2820  }
2821 
2822  /*
2823  * Now wait for backends to exit. If there are none,
2824  * PostmasterStateMachine will take the next step.
2825  */
2827  break;
2828 
2829  case SIGQUIT:
2830 
2831  /*
2832  * Immediate Shutdown:
2833  *
2834  * abort all children with SIGQUIT, wait for them to exit,
2835  * terminate remaining ones with SIGKILL, then exit without
2836  * attempt to properly shut down the data base system.
2837  */
2838  if (Shutdown >= ImmediateShutdown)
2839  break;
2841  ereport(LOG,
2842  (errmsg("received immediate shutdown request")));
2843 
2844  /* Report status */
2846 #ifdef USE_SYSTEMD
2847  sd_notify(0, "STOPPING=1");
2848 #endif
2849 
2852 
2853  /* set stopwatch for them to die */
2854  AbortStartTime = time(NULL);
2855 
2856  /*
2857  * Now wait for backends to exit. If there are none,
2858  * PostmasterStateMachine will take the next step.
2859  */
2861  break;
2862  }
2863 
2865 
2866  errno = save_errno;
2867 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3701
#define SIGQUIT
Definition: win32_port.h:164
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1254
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:3977
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define LOG
Definition: elog.h:26
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:146
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:277
static pid_t BgWriterPID
Definition: postmaster.c:251
static pid_t StartupPID
Definition: postmaster.c:250
#define SmartShutdown
Definition: postmaster.c:273
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:4021
#define FastShutdown
Definition: postmaster.c:274
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3951
#define ereport(elevel, rest)
Definition: elog.h:141
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:148
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:341
#define ImmediateShutdown
Definition: postmaster.c:275
static pid_t WalWriterPID
Definition: postmaster.c:253
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
static pid_t AutoVacPID
Definition: postmaster.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define PM_STATUS_STOPPING
Definition: pidfile.h:51
#define LOCK_FILE_LINE_PM_STATUS
Definition: pidfile.h:43
static time_t AbortStartTime
Definition: postmaster.c:345

◆ PostmasterMain()

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

Definition at line 567 of file postmaster.c.

References AddToDataDirLockFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ApplyLauncherRegister(), ARCHIVE_MODE_OFF, Assert, autovac_init(), BlockSig, bonjour_name, ChangeToDataDir(), checkControlFile(), checkDataDir(), CheckDateTokenTables(), CloseServerPorts(), CreateDataDirLockFile(), CreateOptsFile(), DEBUG3, DestNone, dummy_handler(), elog, enable_bonjour, EnableSSL, environ, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExitPostmaster(), external_pid_file, ExtraOptions, FATAL, fprintf, free, get_stats_option_name(), GetConfigOption(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), i, InitializeGUCOptions(), InitializeMaxBackends(), InitPostmasterDeathWatchHandle(), InitProcessGlobals(), IsBinaryUpgrade, IsPostmasterEnvironment, lfirst, list_free(), list_free_deep(), ListenAddresses, ListenSocket, load_hba(), load_ident(), LocalProcessControlFile(), LOCK_FILE_LINE_LISTEN_ADDR, LOCK_FILE_LINE_PM_STATUS, LOCK_FILE_LINE_SOCKET_DIR, LOG, Log_destination, LOG_DESTINATION_STDERR, Log_destination_string, LOG_METAINFO_DATAFILE, max_wal_senders, MaxConnections, MAXLISTEN, maybe_start_bgworkers(), MemoryContextSwitchTo(), my_exec_path, MyProcPid, name, NIL, on_proc_exit(), optarg, opterr, optind, ParseLongOption(), pfree(), pg_hton16, PG_MODE_MASK_OWNER, PG_SETMASK, PGC_POSTMASTER, PGC_S_ARGV, PGINVALID_SOCKET, PgStartTime, pgstat_init(), PM_STARTUP, PM_STATUS_STARTING, pmdie(), pmState, PostmasterContext, PostmasterPid, PostPortNumber, pqinitmask(), pqsignal(), pqsignal_no_restart(), process_shared_preload_libraries(), progname, pstrdup(), reaper(), Reinit, RemoveLogrotateSignalFiles(), RemovePgTempFiles(), RemovePromoteSignalFiles(), ReservedBackends, reset_shared(), S_IRGRP, S_IROTH, S_IRUSR, S_IWUSR, secure_initialize(), SelectConfigFiles(), SendStop, ServerLoop(), set_debug_options(), set_max_safe_fds(), set_plan_disabling_options(), set_stack_base(), SetConfigOption(), SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SIGHUP_handler(), SIGPIPE, SIGQUIT, SIGUSR1, sigusr1_handler(), SIGUSR2, snprintf, SplitDirectoriesString(), SplitIdentifierString(), STARTUP_RUNNING, StartupDataBase, StartupPID, StartupStatus, status(), STATUS_OK, StreamServerPort(), strerror, success, SysLogger_Start(), SysLoggerPID, TopMemoryContext, Unix_socket_directories, unlink_external_pid_file(), userDoption, value, wal_level, WAL_LEVEL_MINIMAL, WARNING, whereToSendOutput, write_stderr, and XLogArchiveMode.

Referenced by main().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 6003 of file postmaster.c.

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

Referenced by BackgroundWorkerStateChange().

6004 {
6005  dlist_iter iter;
6006  Backend *bp;
6007 
6008  dlist_foreach(iter, &BackendList)
6009  {
6010  bp = dlist_container(Backend, elem, iter.cur);
6011  if (bp->pid == pid)
6012  {
6013  bp->bgworker_notify = true;
6014  return true;
6015  }
6016  }
6017  return false;
6018 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:182
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:186
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:171

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

Definition at line 3701 of file postmaster.c.

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

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

3702 {
3703  if (pmState == PM_WAIT_BACKUP)
3704  {
3705  /*
3706  * PM_WAIT_BACKUP state ends when online backup mode is not active.
3707  */
3708  if (!BackupInProgress())
3710  }
3711 
3712  if (pmState == PM_WAIT_READONLY)
3713  {
3714  /*
3715  * PM_WAIT_READONLY state ends when we have no regular backends that
3716  * have been started during recovery. We kill the startup and
3717  * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3718  * we might like to kill these processes first and then wait for
3719  * backends to die off, but that doesn't work at present because
3720  * killing the startup process doesn't release its locks.
3721  */
3723  {
3724  if (StartupPID != 0)
3725  signal_child(StartupPID, SIGTERM);
3726  if (WalReceiverPID != 0)
3727  signal_child(WalReceiverPID, SIGTERM);
3729  }
3730  }
3731 
3732  /*
3733  * If we are in a state-machine state that implies waiting for backends to
3734  * exit, see if they're all gone, and change state if so.
3735  */
3736  if (pmState == PM_WAIT_BACKENDS)
3737  {
3738  /*
3739  * PM_WAIT_BACKENDS state ends when we have no regular backends
3740  * (including autovac workers), no bgworkers (including unconnected
3741  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3742  * doing crash recovery or an immediate shutdown then we expect the
3743  * checkpointer to exit as well, otherwise not. The archiver, stats,
3744  * and syslogger processes are disregarded since they are not
3745  * connected to shared memory; we also disregard dead_end children
3746  * here. Walsenders are also disregarded, they will be terminated
3747  * later after writing the checkpoint record, like the archiver
3748  * process.
3749  */
3751  StartupPID == 0 &&
3752  WalReceiverPID == 0 &&
3753  BgWriterPID == 0 &&
3754  (CheckpointerPID == 0 ||
3756  WalWriterPID == 0 &&
3757  AutoVacPID == 0)
3758  {
3760  {
3761  /*
3762  * Start waiting for dead_end children to die. This state
3763  * change causes ServerLoop to stop creating new ones.
3764  */
3766 
3767  /*
3768  * We already SIGQUIT'd the archiver and stats processes, if
3769  * any, when we started immediate shutdown or entered
3770  * FatalError state.
3771  */
3772  }
3773  else
3774  {
3775  /*
3776  * If we get here, we are proceeding with normal shutdown. All
3777  * the regular children are gone, and it's time to tell the
3778  * checkpointer to do a shutdown checkpoint.
3779  */
3781  /* Start the checkpointer if not running */
3782  if (CheckpointerPID == 0)
3784  /* And tell it to shut down */
3785  if (CheckpointerPID != 0)
3786  {
3788  pmState = PM_SHUTDOWN;
3789  }
3790  else
3791  {
3792  /*
3793  * If we failed to fork a checkpointer, just shut down.
3794  * Any required cleanup will happen at next restart. We
3795  * set FatalError so that an "abnormal shutdown" message
3796  * gets logged when we exit.
3797  */
3798  FatalError = true;
3800 
3801  /* Kill the walsenders, archiver and stats collector too */
3803  if (PgArchPID != 0)
3805  if (PgStatPID != 0)
3807  }
3808  }
3809  }
3810  }
3811 
3812  if (pmState == PM_SHUTDOWN_2)
3813  {
3814  /*
3815  * PM_SHUTDOWN_2 state ends when there's no other children than
3816  * dead_end children left. There shouldn't be any regular backends
3817  * left by now anyway; what we're really waiting for is walsenders and
3818  * archiver.
3819  */
3820  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
3821  {
3823  }
3824  }
3825 
3826  if (pmState == PM_WAIT_DEAD_END)
3827  {
3828  /*
3829  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3830  * (ie, no dead_end children remain), and the archiver and stats
3831  * collector are gone too.
3832  *
3833  * The reason we wait for those two is to protect them against a new
3834  * postmaster starting conflicting subprocesses; this isn't an
3835  * ironclad protection, but it at least helps in the
3836  * shutdown-and-immediately-restart scenario. Note that they have
3837  * already been sent appropriate shutdown signals, either during a
3838  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3839  * FatalError processing.
3840  */
3841  if (dlist_is_empty(&BackendList) &&
3842  PgArchPID == 0 && PgStatPID == 0)
3843  {
3844  /* These other guys should be dead already */
3845  Assert(StartupPID == 0);
3846  Assert(WalReceiverPID == 0);
3847  Assert(BgWriterPID == 0);
3848  Assert(CheckpointerPID == 0);
3849  Assert(WalWriterPID == 0);
3850  Assert(AutoVacPID == 0);
3851  /* syslogger is not considered here */
3853  }
3854  }
3855 
3856  /*
3857  * If we've been told to shut down, we exit as soon as there are no
3858  * remaining children. If there was a crash, cleanup will occur at the
3859  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3860  * crash before exiting, but that seems unwise if we are quitting because
3861  * we got SIGTERM from init --- there may well not be time for recovery
3862  * before init decides to SIGKILL us.)
3863  *
3864  * Note that the syslogger continues to run. It will exit when it sees
3865  * EOF on its input pipe, which happens when there are no more upstream
3866  * processes.
3867  */
3869  {
3870  if (FatalError)
3871  {
3872  ereport(LOG, (errmsg("abnormal database system shutdown")));
3873  ExitPostmaster(1);
3874  }
3875  else
3876  {
3877  /*
3878  * Terminate exclusive backup mode to avoid recovery after a clean
3879  * fast shutdown. Since an exclusive backup can only be taken
3880  * during normal running (and not, for example, while running
3881  * under Hot Standby) it only makes sense to do this if we reached
3882  * normal running. If we're still in recovery, the backup file is
3883  * one we're recovering *from*, and we must keep it around so that
3884  * recovery restarts from the right place.
3885  */
3887  CancelBackup();
3888 
3889  /* Normal exit from the postmaster is here */
3890  ExitPostmaster(0);
3891  }
3892  }
3893 
3894  /*
3895  * If the startup process failed, or the user does not want an automatic
3896  * restart after backend crashes, wait for all non-syslogger children to
3897  * exit, and then exit postmaster. We don't try to reinitialize when the
3898  * startup process fails, because more than likely it will just fail again
3899  * and we will keep trying forever.
3900  */
3901  if (pmState == PM_NO_CHILDREN &&
3903  ExitPostmaster(1);
3904 
3905  /*
3906  * If we need to recover from a crash, wait for all non-syslogger children
3907  * to exit, then reset shmem and StartupDataBase.
3908  */
3909  if (FatalError && pmState == PM_NO_CHILDREN)
3910  {
3911  ereport(LOG,
3912  (errmsg("all server processes terminated; reinitializing")));
3913 
3914  /* allow background workers to immediately restart */
3916 
3917  shmem_exit(1);
3918 
3919  /* re-read control file into local memory */
3921 
3923 
3925  Assert(StartupPID != 0);
3927  pmState = PM_STARTUP;
3928  /* crash recovery started, reset SIGKILL flag */
3929  AbortStartTime = 0;
3930  }
3931 }
void CancelBackup(void)
Definition: xlog.c:11446
#define SIGQUIT
Definition: win32_port.h:164
static StartupStatusEnum StartupStatus
Definition: postmaster.c:269
#define BACKEND_TYPE_ALL
Definition: postmaster.c:149
#define StartupDataBase()
Definition: postmaster.c:541
static pid_t PgStatPID
Definition: postmaster.c:257
static pid_t CheckpointerPID
Definition: postmaster.c:252
static pid_t WalReceiverPID
Definition: postmaster.c:254
static bool FatalError
Definition: postmaster.c:279
void shmem_exit(int code)
Definition: ipc.c:224
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:145
#define SIGUSR2
Definition: win32_port.h:176
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11426
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:515
#define SignalChildren(sig)
Definition: postmaster.c:418
static int Shutdown
Definition: postmaster.c:277
static pid_t BgWriterPID
Definition: postmaster.c:251
#define StartCheckpointer()
Definition: postmaster.c:543
static int CountChildren(int target)
Definition: postmaster.c:5300
static pid_t StartupPID
Definition: postmaster.c:250
int PostPortNumber
Definition: postmaster.c:197
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:5046
bool restart_after_crash
Definition: postmaster.c:247
static dlist_head BackendList
Definition: postmaster.c:186
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4922
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3951
#define ereport(elevel, rest)
Definition: elog.h:141
static PMState pmState
Definition: postmaster.c:341
#define BACKEND_TYPE_WORKER
Definition: postmaster.c:151
#define ImmediateShutdown
Definition: postmaster.c:275
static void reset_shared(int port)
Definition: postmaster.c:2602
static pid_t WalWriterPID
Definition: postmaster.c:253
#define Assert(condition)
Definition: c.h:732
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:272
static pid_t AutoVacPID
Definition: postmaster.c:255
int errmsg(const char *fmt,...)
Definition: elog.c:784
static bool ReachedNormalRunning
Definition: postmaster.c:350
static time_t AbortStartTime
Definition: postmaster.c:345
static pid_t PgArchPID
Definition: postmaster.c:256

◆ processCancelRequest()

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

Definition at line 2327 of file postmaster.c.

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

Referenced by ProcessStartupPacket().

2328 {
2329  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2330  int backendPID;
2331  int32 cancelAuthCode;
2332  Backend *bp;
2333 
2334 #ifndef EXEC_BACKEND
2335  dlist_iter iter;
2336 #else
2337  int i;
2338 #endif
2339 
2340  backendPID = (int) pg_ntoh32(canc->backendPID);
2341  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2342 
2343  /*
2344  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2345  * longer access the postmaster's own backend list, and must rely on the
2346  * duplicate array in shared memory.
2347  */
2348 #ifndef EXEC_BACKEND
2349  dlist_foreach(iter, &BackendList)
2350  {
2351  bp = dlist_container(Backend, elem, iter.cur);
2352 #else
2353  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2354  {
2355  bp = (Backend *) &ShmemBackendArray[i];
2356 #endif
2357  if (bp->pid == backendPID)
2358  {
2359  if (bp->cancel_key == cancelAuthCode)
2360  {
2361  /* Found a match; signal that backend to cancel current op */
2362  ereport(DEBUG2,
2363  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2364  backendPID)));
2365  signal_child(bp->pid, SIGINT);
2366  }
2367  else
2368  /* Right PID, wrong key: no way, Jose */
2369  ereport(LOG,
2370  (errmsg("wrong key in cancel request for process %d",
2371  backendPID)));
2372  return;
2373  }
2374 #ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */
2375  }
2376 #else
2377  }
2378 #endif
2379 
2380  /* No matching backend */
2381  ereport(LOG,
2382  (errmsg("PID %d in cancel request did not match any process",
2383  backendPID)));
2384 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
uint32 cancelAuthCode
Definition: pqcomm.h:197
#define LOG
Definition: elog.h:26
signed int int32
Definition: c.h:346
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
uint32 backendPID
Definition: pqcomm.h:196
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static dlist_head BackendList
Definition: postmaster.c:186
#define DEBUG2
Definition: elog.h:24
int32 cancel_key
Definition: postmaster.c:172
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3951
#define ereport(elevel, rest)
Definition: elog.h:141
dlist_node * cur
Definition: ilist.h:161
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5600
pid_t pid
Definition: postmaster.c:171
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i

◆ ProcessStartupPacket()

static int ProcessStartupPacket ( Port port,
bool  secure_done 
)
static

Definition at line 1898 of file postmaster.c.

References SockAddr::addr, am_db_walsender, am_walsender, Port::application_name, buf, CAC_OK, CAC_RECOVERY, CAC_SHUTDOWN, CAC_STARTUP, CAC_TOOMANY, CAC_WAITBACKUP, Port::canAcceptConnections, CANCEL_REQUEST_CODE, Port::cmdline_options, COMMERROR, StartupPacket::database, Port::database_name, Db_user_namespace, EINTR, ereport, errcode(), ERRCODE_CANNOT_CONNECT_NOW, errcode_for_socket_access(), errhint(), errmsg(), FATAL, FrontendProtocol, Port::guc_options, IS_AF_UNIX, Port::laddr, lappend(), MAX_STARTUP_PACKET_LENGTH, MemoryContextSwitchTo(), NAMEDATALEN, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, NIL, StartupPacket::options, palloc0(), parse_bool(), pg_clean_ascii(), pg_ntoh32, PG_PROTOCOL_EARLIEST, PG_PROTOCOL_LATEST, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, pq_endmsgread(), pq_getbytes(), pq_startmsgread(), processCancelRequest(), Port::proto, psprintf(), pstrdup(), secure_open_gssapi(), secure_open_server(), send, SendNegotiateProtocolVersion(), Port::sock, STATUS_ERROR, STATUS_OK, TopMemoryContext, StartupPacket::user, and Port::user_name.

Referenced by BackendInitialize().

1899 {
1900  int32 len;
1901  void *buf;
1902  ProtocolVersion proto;
1903  MemoryContext oldcontext;
1904 
1905  pq_startmsgread();
1906 
1907  /*
1908  * Grab the first byte of the length word separately, so that we can tell
1909  * whether we have no data at all or an incomplete packet. (This might
1910  * sound inefficient, but it's not really, because of buffering in
1911  * pqcomm.c.)
1912  */
1913  if (pq_getbytes((char *) &len, 1) == EOF)
1914  {
1915  /*
1916  * If we get no data at all, don't clutter the log with a complaint;
1917  * such cases often occur for legitimate reasons. An example is that
1918  * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
1919  * client didn't like our response, it'll probably just drop the
1920  * connection. Service-monitoring software also often just opens and
1921  * closes a connection without sending anything. (So do port
1922  * scanners, which may be less benign, but it's not really our job to
1923  * notice those.)
1924  */
1925  return STATUS_ERROR;
1926  }
1927 
1928  if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
1929  {
1930  /* Got a partial length word, so bleat about that */
1931  if (!secure_done)
1933  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1934  errmsg("incomplete startup packet")));
1935  return STATUS_ERROR;
1936  }
1937 
1938  len = pg_ntoh32(len);
1939  len -= 4;
1940 
1941  if (len < (int32) sizeof(ProtocolVersion) ||
1943  {
1945  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1946  errmsg("invalid length of startup packet")));
1947  return STATUS_ERROR;
1948  }
1949 
1950  /*
1951  * Allocate at least the size of an old-style startup packet, plus one
1952  * extra byte, and make sure all are zeroes. This ensures we will have
1953  * null termination of all strings, in both fixed- and variable-length
1954  * packet layouts.
1955  */
1956  if (len <= (int32) sizeof(StartupPacket))
1957  buf =