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 "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/dynamic_loader.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/ps_status.h"
#include "utils/timeout.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 SSLdone)
 
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)
 
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
 
static unsigned int random_seed = 0
 
static struct timeval random_start_time
 
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 145 of file postmaster.c.

Referenced by pmdie(), and StartAutovacuumWorker().

◆ BACKEND_TYPE_BGWORKER

#define BACKEND_TYPE_BGWORKER   0x0008 /* bgworker process */

Definition at line 147 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 146 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 150 of file postmaster.c.

Referenced by PostmasterStateMachine().

◆ EXIT_STATUS_0

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

Definition at line 556 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 557 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 558 of file postmaster.c.

Referenced by reaper().

◆ FastShutdown

#define FastShutdown   2

Definition at line 273 of file postmaster.c.

Referenced by pmdie().

◆ ImmediateShutdown

#define ImmediateShutdown   3

Definition at line 274 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:138
static PMState pmState
Definition: postmaster.c:340
#define XLogArchivingActive()
Definition: xlog.h:135

Definition at line 444 of file postmaster.c.

Referenced by reaper(), and ServerLoop().

◆ SIGKILL_CHILDREN_AFTER_SECS

#define SIGKILL_CHILDREN_AFTER_SECS   5

Definition at line 347 of file postmaster.c.

Referenced by DetermineSleepTime(), and ServerLoop().

◆ SignalChildren

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

Definition at line 427 of file postmaster.c.

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

◆ SmartShutdown

#define SmartShutdown   1

Definition at line 272 of file postmaster.c.

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

◆ StartBackgroundWriter

#define StartBackgroundWriter ( )    StartChildProcess(BgWriterProcess)

Definition at line 550 of file postmaster.c.

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

◆ StartCheckpointer

#define StartCheckpointer ( )    StartChildProcess(CheckpointerProcess)

Definition at line 551 of file postmaster.c.

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

◆ StartupDataBase

#define StartupDataBase ( )    StartChildProcess(StartupProcess)

Definition at line 549 of file postmaster.c.

Referenced by PostmasterMain(), and PostmasterStateMachine().

◆ StartWalReceiver

#define StartWalReceiver ( )    StartChildProcess(WalReceiverProcess)

Definition at line 553 of file postmaster.c.

Referenced by MaybeStartWalReceiver().

◆ StartWalWriter

#define StartWalWriter ( )    StartChildProcess(WalWriterProcess)

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

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

◆ StartupStatusEnum

Enumerator
STARTUP_NOT_RUNNING 
STARTUP_RUNNING 
STARTUP_SIGNALED 
STARTUP_CRASHED 

Definition at line 260 of file postmaster.c.

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

Function Documentation

◆ assign_backendlist_entry()

static bool assign_backendlist_entry ( RegisteredBgWorker rw)
static

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

5761 {
5762  Backend *bn;
5763 
5764  /*
5765  * Compute the cancel key that will be assigned to this session. We
5766  * probably don't need cancel keys for background workers, but we'd better
5767  * have something random in the field to prevent unfriendly people from
5768  * sending cancels to them.
5769  */
5771  {
5772  ereport(LOG,
5773  (errcode(ERRCODE_INTERNAL_ERROR),
5774  errmsg("could not generate random cancel key")));
5775  return false;
5776  }
5777 
5778  bn = malloc(sizeof(Backend));
5779  if (bn == NULL)
5780  {
5781  ereport(LOG,
5782  (errcode(ERRCODE_OUT_OF_MEMORY),
5783  errmsg("out of memory")));
5784  return false;
5785  }
5786 
5787  bn->cancel_key = MyCancelKey;
5790  bn->dead_end = false;
5791  bn->bgworker_notify = false;
5792 
5793  rw->rw_backend = bn;
5794  rw->rw_child_slot = bn->child_slot;
5795 
5796  return true;
5797 }
struct bkend * rw_backend
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
bool bgworker_notify
Definition: postmaster.c:181
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:151
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:45
int32 cancel_key
Definition: postmaster.c:171
bool dead_end
Definition: postmaster.c:180
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:147
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5196
int child_slot
Definition: postmaster.c:172
int bkend_type
Definition: postmaster.c:179
int MyPMChildSlot
Definition: globals.c:46
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ BackendInitialize()

static void BackendInitialize ( Port port)
static

Definition at line 4107 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, GetCurrentTimestamp(), init_ps_display(), InitializeTimeouts(), LOG, Log_connections, log_hostname, MyProcPort, MyStartTime, 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, Port::SessionStartTime, SIGQUIT, snprintf(), startup_die(), STARTUP_PACKET_TIMEOUT, StartupBlockSig, StartupPacketTimeoutHandler(), status(), STATUS_OK, timestamptz_to_time_t(), update_process_title, Port::user_name, WARNING, and whereToSendOutput.

Referenced by BackendRun(), and BackendStartup().

4108 {
4109  int status;
4110  int ret;
4111  char remote_host[NI_MAXHOST];
4112  char remote_port[NI_MAXSERV];
4113  char remote_ps_data[NI_MAXHOST];
4114 
4115  /* Save port etc. for ps status */
4116  MyProcPort = port;
4117 
4118  /*
4119  * PreAuthDelay is a debugging aid for investigating problems in the
4120  * authentication cycle: it can be set in postgresql.conf to allow time to
4121  * attach to the newly-forked backend with a debugger. (See also
4122  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
4123  * is not honored until after authentication.)
4124  */
4125  if (PreAuthDelay > 0)
4126  pg_usleep(PreAuthDelay * 1000000L);
4127 
4128  /* This flag will remain set until InitPostgres finishes authentication */
4129  ClientAuthInProgress = true; /* limit visibility of log messages */
4130 
4131  /* save process start time */
4134 
4135  /* set these to empty in case they are needed before we set them up */
4136  port->remote_host = "";
4137  port->remote_port = "";
4138 
4139  /*
4140  * Initialize libpq and enable reporting of ereport errors to the client.
4141  * Must do this now because authentication uses libpq to send messages.
4142  */
4143  pq_init(); /* initialize libpq to talk to client */
4144  whereToSendOutput = DestRemote; /* now safe to ereport to client */
4145 
4146  /*
4147  * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
4148  * timeout while trying to collect the startup packet. Otherwise the
4149  * postmaster cannot shutdown the database FAST or IMMED cleanly if a
4150  * buggy client fails to send the packet promptly. XXX it follows that
4151  * the remainder of this function must tolerate losing control at any
4152  * instant. Likewise, any pg_on_exit_callback registered before or during
4153  * this function must be prepared to execute at any instant between here
4154  * and the end of this function. Furthermore, affected callbacks execute
4155  * partially or not at all when a second exit-inducing signal arrives
4156  * after proc_exit_prepare() decrements on_proc_exit_index. (Thanks to
4157  * that mechanic, callbacks need not anticipate more than one call.) This
4158  * is fragile; it ought to instead follow the norm of handling interrupts
4159  * at selected, safe opportunities.
4160  */
4161  pqsignal(SIGTERM, startup_die);
4163  InitializeTimeouts(); /* establishes SIGALRM handler */
4165 
4166  /*
4167  * Get the remote host name and port for logging and status display.
4168  */
4169  remote_host[0] = '\0';
4170  remote_port[0] = '\0';
4171  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
4172  remote_host, sizeof(remote_host),
4173  remote_port, sizeof(remote_port),
4174  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
4175  ereport(WARNING,
4176  (errmsg_internal("pg_getnameinfo_all() failed: %s",
4177  gai_strerror(ret))));
4178  if (remote_port[0] == '\0')
4179  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
4180  else
4181  snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
4182 
4183  /*
4184  * Save remote_host and remote_port in port structure (after this, they
4185  * will appear in log_line_prefix data for log messages).
4186  */
4187  port->remote_host = strdup(remote_host);
4188  port->remote_port = strdup(remote_port);
4189 
4190  /* And now we can issue the Log_connections message, if wanted */
4191  if (Log_connections)
4192  {
4193  if (remote_port[0])
4194  ereport(LOG,
4195  (errmsg("connection received: host=%s port=%s",
4196  remote_host,
4197  remote_port)));
4198  else
4199  ereport(LOG,
4200  (errmsg("connection received: host=%s",
4201  remote_host)));
4202  }
4203 
4204  /*
4205  * If we did a reverse lookup to name, we might as well save the results
4206  * rather than possibly repeating the lookup during authentication.
4207  *
4208  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
4209  * get nothing useful for a client without an rDNS entry. Therefore, we
4210  * must check whether we got a numeric IPv4 or IPv6 address, and not save
4211  * it into remote_hostname if so. (This test is conservative and might
4212  * sometimes classify a hostname as numeric, but an error in that
4213  * direction is safe; it only results in a possible extra lookup.)
4214  */
4215  if (log_hostname &&
4216  ret == 0 &&
4217  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
4218  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
4219  port->remote_hostname = strdup(remote_host);
4220 
4221  /*
4222  * Ready to begin client interaction. We will give up and exit(1) after a
4223  * time delay, so that a broken client can't hog a connection
4224  * indefinitely. PreAuthDelay and any DNS interactions above don't count
4225  * against the time limit.
4226  *
4227  * Note: AuthenticationTimeout is applied here while waiting for the
4228  * startup packet, and then again in InitPostgres for the duration of any
4229  * authentication operations. So a hostile client could tie up the
4230  * process for nearly twice AuthenticationTimeout before we kick him off.
4231  *
4232  * Note: because PostgresMain will call InitializeTimeouts again, the
4233  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
4234  * since we never use it again after this function.
4235  */
4238 
4239  /*
4240  * Receive the startup packet (which might turn out to be a cancel request
4241  * packet).
4242  */
4243  status = ProcessStartupPacket(port, false);
4244 
4245  /*
4246  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
4247  * already did any appropriate error reporting.
4248  */
4249  if (status != STATUS_OK)
4250  proc_exit(0);
4251 
4252  /*
4253  * Now that we have the user and database name, we can set the process
4254  * title for ps. It's good to do this as early as possible in startup.
4255  *
4256  * For a walsender, the ps display is set in the following form:
4257  *
4258  * postgres: walsender <user> <host> <activity>
4259  *
4260  * To achieve that, we pass "walsender" as username and username as dbname
4261  * to init_ps_display(). XXX: should add a new variant of
4262  * init_ps_display() to avoid abusing the parameters like this.
4263  */
4264  if (am_walsender)
4266  update_process_title ? "authentication" : "");
4267  else
4268  init_ps_display(port->user_name, port->database_name, remote_ps_data,
4269  update_process_title ? "authentication" : "");
4270 
4271  /*
4272  * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
4273  */
4275  PG_SETMASK(&BlockSig);
4276 }
void InitializeTimeouts(void)
Definition: timeout.c:340
#define SIGQUIT
Definition: win32_port.h:164
static void startup_die(SIGNAL_ARGS)
Definition: postmaster.c:5162
#define NI_NUMERICHOST
Definition: getaddrinfo.h:78
struct Port * MyProcPort
Definition: globals.c:44
bool update_process_title
Definition: ps_status.c:35
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
const char * pgstat_get_backend_desc(BackendType backendType)
Definition: pgstat.c:4099
pg_time_t MyStartTime
Definition: globals.c:43
struct sockaddr_storage addr
Definition: pqcomm.h:64
void proc_exit(int code)
Definition: ipc.c:104
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
char * remote_port
Definition: libpq-be.h:128
#define LOG
Definition: elog.h:26
bool Log_connections
Definition: postmaster.c:241
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
#define gai_strerror
Definition: getaddrinfo.h:146
int AuthenticationTimeout
Definition: postmaster.c:238
char * remote_hostname
Definition: libpq-be.h:124
bool ClientAuthInProgress
Definition: postmaster.c:351
SockAddr raddr
Definition: libpq-be.h:122
bool am_walsender
Definition: walsender.c:115
void pg_usleep(long microsec)
Definition: signal.c:53
void pq_init(void)
Definition: pqcomm.c:194
#define NI_MAXHOST
Definition: getaddrinfo.h:88
TimestampTz SessionStartTime
Definition: libpq-be.h:151
#define NI_MAXSERV
Definition: getaddrinfo.h:91
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1692
char * user_name
Definition: libpq-be.h:137
ACCEPT_TYPE_ARG3 salen
Definition: pqcomm.h:65
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:1008
bool log_hostname
Definition: postmaster.c:240
static int port
Definition: pg_regress.c:90
#define WARNING
Definition: elog.h:40
static int ProcessStartupPacket(Port *port, bool SSLdone)
Definition: postmaster.c:1889
sigset_t BlockSig
Definition: pqsignal.c:22
#define NI_NUMERICSERV
Definition: getaddrinfo.h:81
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:373
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
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:237
char * remote_host
Definition: libpq-be.h:123
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void StartupPacketTimeoutHandler(void)
Definition: postmaster.c:5186
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:525
CommandDest whereToSendOutput
Definition: postgres.c:89
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
char * database_name
Definition: libpq-be.h:136
void init_ps_display(const char *username, const char *dbname, const char *host_info, const char *initial_str)
Definition: ps_status.c:244

◆ BackendRun()

static void BackendRun ( Port port)
static

Definition at line 4287 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, random_seed, random_start_time, RegisterWaitForSingleObject(), secure_initialize(), Port::SessionStartTime, set_stack_base(), snprintf(), srandom(), StartBackgroundWorker(), SysLoggerMain(), TimestampDifference(), TopMemoryContext, TRUE, UsedShmemSegAddr, Port::user_name, and whereToSendOutput.

Referenced by BackendStartup().

4288 {
4289  char **av;
4290  int maxac;
4291  int ac;
4292  long secs;
4293  int usecs;
4294  int i;
4295 
4296  /*
4297  * Don't want backend to be able to see the postmaster random number
4298  * generator state. We have to clobber the static random_seed *and* start
4299  * a new random sequence in the random() library function.
4300  */
4301 #ifndef HAVE_STRONG_RANDOM
4302  random_seed = 0;
4303  random_start_time.tv_usec = 0;
4304 #endif
4305  /* slightly hacky way to convert timestamptz into integers */
4306  TimestampDifference(0, port->SessionStartTime, &secs, &usecs);
4307  srandom((unsigned int) (MyProcPid ^ (usecs << 12) ^ secs));
4308 
4309  /*
4310  * Now, build the argv vector that will be given to PostgresMain.
4311  *
4312  * The maximum possible number of commandline arguments that could come
4313  * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
4314  * pg_split_opts().
4315  */
4316  maxac = 2; /* for fixed args supplied below */
4317  maxac += (strlen(ExtraOptions) + 1) / 2;
4318 
4319  av = (char **) MemoryContextAlloc(TopMemoryContext,
4320  maxac * sizeof(char *));
4321  ac = 0;
4322 
4323  av[ac++] = "postgres";
4324 
4325  /*
4326  * Pass any backend switches specified with -o on the postmaster's own
4327  * command line. We assume these are secure.
4328  */
4329  pg_split_opts(av, &ac, ExtraOptions);
4330 
4331  av[ac] = NULL;
4332 
4333  Assert(ac < maxac);
4334 
4335  /*
4336  * Debug: print arguments being passed to backend
4337  */
4338  ereport(DEBUG3,
4339  (errmsg_internal("%s child[%d]: starting with (",
4340  progname, (int) getpid())));
4341  for (i = 0; i < ac; ++i)
4342  ereport(DEBUG3,
4343  (errmsg_internal("\t%s", av[i])));
4344  ereport(DEBUG3,
4345  (errmsg_internal(")")));
4346 
4347  /*
4348  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
4349  * just yet, though, because InitPostgres will need the HBA data.)
4350  */
4352 
4353  PostgresMain(ac, av, port->database_name, port->user_name);
4354 }
int MyProcPid
Definition: globals.c:42
#define DEBUG3
Definition: elog.h:23
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
const char * progname
Definition: pg_standby.c:37
static unsigned int random_seed
Definition: postmaster.c:375
TimestampTz SessionStartTime
Definition: libpq-be.h:151
void PostgresMain(int argc, char *argv[], const char *dbname, const char *username)
Definition: postgres.c:3620
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition: postinit.c:443
char * user_name
Definition: libpq-be.h:137
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:44
struct @18::@19 av[32]
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static char ExtraOptions[MAXPGPATH]
Definition: postmaster.c:222
#define Assert(condition)
Definition: c.h:699
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i
void srandom(unsigned int seed)
Definition: srandom.c:22
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
char * database_name
Definition: libpq-be.h:136
static struct timeval random_start_time
Definition: postmaster.c:376

◆ BackendStartup()

static int BackendStartup ( Port port)
static

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

3958 {
3959  Backend *bn; /* for backend cleanup */
3960  pid_t pid;
3961 
3962  /*
3963  * Create backend data structure. Better before the fork() so we can
3964  * handle failure cleanly.
3965  */
3966  bn = (Backend *) malloc(sizeof(Backend));
3967  if (!bn)
3968  {
3969  ereport(LOG,
3970  (errcode(ERRCODE_OUT_OF_MEMORY),
3971  errmsg("out of memory")));
3972  return STATUS_ERROR;
3973  }
3974 
3975  /*
3976  * Compute the cancel key that will be assigned to this backend. The
3977  * backend will have its own copy in the forked-off process' value of
3978  * MyCancelKey, so that it can transmit the key to the frontend.
3979  */
3981  {
3982  free(bn);
3983  ereport(LOG,
3984  (errcode(ERRCODE_INTERNAL_ERROR),
3985  errmsg("could not generate random cancel key")));
3986  return STATUS_ERROR;
3987  }
3988 
3989  bn->cancel_key = MyCancelKey;
3990 
3991  /* Pass down canAcceptConnections state */
3993  bn->dead_end = (port->canAcceptConnections != CAC_OK &&
3995 
3996  /*
3997  * Unless it's a dead_end child, assign it a child slot number
3998  */
3999  if (!bn->dead_end)
4001  else
4002  bn->child_slot = 0;
4003 
4004  /* Hasn't asked to be notified about any bgworkers yet */
4005  bn->bgworker_notify = false;
4006 
4007 #ifdef EXEC_BACKEND
4008  pid = backend_forkexec(port);
4009 #else /* !EXEC_BACKEND */
4010  pid = fork_process();
4011  if (pid == 0) /* child */
4012  {
4013  free(bn);
4014 
4015  /* Detangle from postmaster */
4017 
4018  /* Close the postmaster's sockets */
4019  ClosePostmasterPorts(false);
4020 
4021  /* Perform additional initialization and collect startup packet */
4022  BackendInitialize(port);
4023 
4024  /* And run the backend */
4025  BackendRun(port);
4026  }
4027 #endif /* EXEC_BACKEND */
4028 
4029  if (pid < 0)
4030  {
4031  /* in parent, fork failed */
4032  int save_errno = errno;
4033 
4034  if (!bn->dead_end)
4036  free(bn);
4037  errno = save_errno;
4038  ereport(LOG,
4039  (errmsg("could not fork new process for connection: %m")));
4040  report_fork_failure_to_client(port, save_errno);
4041  return STATUS_ERROR;
4042  }
4043 
4044  /* in parent, successful fork */
4045  ereport(DEBUG2,
4046  (errmsg_internal("forked new backend, pid=%d socket=%d",
4047  (int) pid, (int) port->sock)));
4048 
4049  /*
4050  * Everything's been successful, it's safe to add this backend to our list
4051  * of backends.
4052  */
4053  bn->pid = pid;
4054  bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */
4056 
4057 #ifdef EXEC_BACKEND
4058  if (!bn->dead_end)
4059  ShmemBackendArrayAdd(bn);
4060 #endif
4061 
4062  return STATUS_OK;
4063 }
CAC_state canAcceptConnections
Definition: libpq-be.h:129
void InitPostmasterChild(void)
Definition: miscinit.c:271
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:4287
pid_t fork_process(void)
Definition: fork_process.c:31
int errcode(int sqlerrcode)
Definition: elog.c:575
#define STATUS_ERROR
Definition: c.h:1009
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:144
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:182
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2440
pgsocket sock
Definition: libpq-be.h:118
bool bgworker_notify
Definition: postmaster.c:181
int AssignPostmasterChildSlot(void)
Definition: pmsignal.c:151
#define malloc(a)
Definition: header.h:50
int32 MyCancelKey
Definition: globals.c:45
static dlist_head BackendList
Definition: postmaster.c:185
#define DEBUG2
Definition: elog.h:24
static void report_fork_failure_to_client(Port *port, int errnum)
Definition: postmaster.c:4074
int32 cancel_key
Definition: postmaster.c:171
bool dead_end
Definition: postmaster.c:180
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:1008
static bool RandomCancelKey(int32 *cancel_key)
Definition: postmaster.c:5196
int child_slot
Definition: postmaster.c:172
int bkend_type
Definition: postmaster.c:179
#define free(a)
Definition: header.h:65
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
pid_t pid
Definition: postmaster.c:170
int MyPMChildSlot
Definition: globals.c:46
int errmsg(const char *fmt,...)
Definition: elog.c:797
static CAC_state canAcceptConnections(void)
Definition: postmaster.c:2318
static void BackendInitialize(Port *port)
Definition: postmaster.c:4107

◆ BackgroundWorkerBlockSignals()

void BackgroundWorkerBlockSignals ( void  )

Definition at line 5583 of file postmaster.c.

References BlockSig, and PG_SETMASK.

5584 {
5585  PG_SETMASK(&BlockSig);
5586 }
#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 5537 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().

5538 {
5540 
5541  /* XXX is this the right errcode? */
5543  ereport(FATAL,
5544  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5545  errmsg("database connection requirement not indicated during registration")));
5546 
5548 
5549  /* it had better not gotten out of "init" mode yet */
5550  if (!IsInitProcessingMode())
5551  ereport(ERROR,
5552  (errmsg("invalid processing mode in background worker")));
5554 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:378
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:191
#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:122
static char * username
Definition: initdb.c:132
#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:565
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
char * dbname
Definition: streamutil.c:51
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsInitProcessingMode()
Definition: miscadmin.h:373

◆ BackgroundWorkerInitializeConnectionByOid()

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

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

5561 {
5563 
5564  /* XXX is this the right errcode? */
5566  ereport(FATAL,
5567  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5568  errmsg("database connection requirement not indicated during registration")));
5569 
5570  InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
5571 
5572  /* it had better not gotten out of "init" mode yet */
5573  if (!IsInitProcessingMode())
5574  ereport(ERROR,
5575  (errmsg("invalid processing mode in background worker")));
5577 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SetProcessingMode(mode)
Definition: miscadmin.h:378
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:191
#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:122
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:565
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define IsInitProcessingMode()
Definition: miscadmin.h:373

◆ BackgroundWorkerUnblockSignals()

void BackgroundWorkerUnblockSignals ( void  )

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

5590 {
5592 }
#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 5716 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().

5717 {
5718  switch (pmState)
5719  {
5720  case PM_NO_CHILDREN:
5721  case PM_WAIT_DEAD_END:
5722  case PM_SHUTDOWN_2:
5723  case PM_SHUTDOWN:
5724  case PM_WAIT_BACKENDS:
5725  case PM_WAIT_READONLY:
5726  case PM_WAIT_BACKUP:
5727  break;
5728 
5729  case PM_RUN:
5731  return true;
5732  /* fall through */
5733 
5734  case PM_HOT_STANDBY:
5736  return true;
5737  /* fall through */
5738 
5739  case PM_RECOVERY:
5740  case PM_STARTUP:
5741  case PM_INIT:
5743  return true;
5744  /* fall through */
5745 
5746  }
5747 
5748  return false;
5749 }
static time_t start_time
Definition: pg_ctl.c:96
static PMState pmState
Definition: postmaster.c:340

◆ canAcceptConnections()

static CAC_state canAcceptConnections ( void  )
static

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

2319 {
2320  CAC_state result = CAC_OK;
2321 
2322  /*
2323  * Can't start backends when in startup/shutdown/inconsistent recovery
2324  * state.
2325  *
2326  * In state PM_WAIT_BACKUP only superusers can connect (this must be
2327  * allowed so that a superuser can end online backup mode); we return
2328  * CAC_WAITBACKUP code to indicate that this must be checked later. Note
2329  * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
2330  * have checked for too many children.
2331  */
2332  if (pmState != PM_RUN)
2333  {
2334  if (pmState == PM_WAIT_BACKUP)
2335  result = CAC_WAITBACKUP; /* allow superusers only */
2336  else if (Shutdown > NoShutdown)
2337  return CAC_SHUTDOWN; /* shutdown is pending */
2338  else if (!FatalError &&
2339  (pmState == PM_STARTUP ||
2340  pmState == PM_RECOVERY))
2341  return CAC_STARTUP; /* normal startup */
2342  else if (!FatalError &&
2344  result = CAC_OK; /* connection OK during hot standby */
2345  else
2346  return CAC_RECOVERY; /* else must be crash recovery */
2347  }
2348 
2349  /*
2350  * Don't start too many children.
2351  *
2352  * We allow more connections than we can have backends here because some
2353  * might still be authenticating; they might fail auth, or some existing
2354  * backend might exit before the auth cycle is completed. The exact
2355  * MaxBackends limit is enforced when a new backend tries to join the
2356  * shared-inval backend array.
2357  *
2358  * The limit here must match the sizes of the per-child-process arrays;
2359  * see comments for MaxLivePostmasterChildren().
2360  */
2362  result = CAC_TOOMANY;
2363 
2364  return result;
2365 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:148
static bool FatalError
Definition: postmaster.c:278
static int Shutdown
Definition: postmaster.c:276
static int CountChildren(int target)
Definition: postmaster.c:5237
static PMState pmState
Definition: postmaster.c:340
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5527
#define NoShutdown
Definition: postmaster.c:271
CAC_state
Definition: libpq-be.h:71

◆ checkControlFile()

static void checkControlFile ( void  )
static

Definition at line 1487 of file postmaster.c.

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

Referenced by PostmasterMain().

1488 {
1489  char path[MAXPGPATH];
1490  FILE *fp;
1491 
1492  snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
1493 
1494  fp = AllocateFile(path, PG_BINARY_R);
1495  if (fp == NULL)
1496  {
1497  write_stderr("%s: could not find the database system\n"
1498  "Expected to find it in the directory \"%s\",\n"
1499  "but could not open file \"%s\": %s\n",
1500  progname, DataDir, path, strerror(errno));
1501  ExitPostmaster(2);
1502  }
1503  FreeFile(fp);
1504 }
#define write_stderr(str)
Definition: parallel.c:182
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
const char * progname
Definition: pg_standby.c:37
#define PG_BINARY_R
Definition: c.h:1082
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:4968
#define MAXPGPATH
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2346
int FreeFile(FILE *file)
Definition: fd.c:2538
const char * strerror(int errnum)
Definition: strerror.c:19
char * DataDir
Definition: globals.c:63

◆ CleanupBackend()

static void CleanupBackend ( int  pid,
int  exitstatus 
)
static

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

3189 {
3190  dlist_mutable_iter iter;
3191 
3192  LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
3193 
3194  /*
3195  * If a backend dies in an ugly way then we must signal all other backends
3196  * to quickdie. If exit status is zero (normal) or one (FATAL exit), we
3197  * assume everything is all right and proceed to remove the backend from
3198  * the active backend list.
3199  */
3200 
3201 #ifdef WIN32
3202 
3203  /*
3204  * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
3205  * since that sometimes happens under load when the process fails to start
3206  * properly (long before it starts using shared memory). Microsoft reports
3207  * it is related to mutex failure:
3208  * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
3209  */
3210  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3211  {
3212  LogChildExit(LOG, _("server process"), pid, exitstatus);
3213  exitstatus = 0;
3214  }
3215 #endif
3216 
3217  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3218  {
3219  HandleChildCrash(pid, exitstatus, _("server process"));
3220  return;
3221  }
3222 
3224  {
3225  Backend *bp = dlist_container(Backend, elem, iter.cur);
3226 
3227  if (bp->pid == pid)
3228  {
3229  if (!bp->dead_end)
3230  {
3232  {
3233  /*
3234  * Uh-oh, the child failed to clean itself up. Treat as a
3235  * crash after all.
3236  */
3237  HandleChildCrash(pid, exitstatus, _("server process"));
3238  return;
3239  }
3240 #ifdef EXEC_BACKEND
3241  ShmemBackendArrayRemove(bp);
3242 #endif
3243  }
3244  if (bp->bgworker_notify)
3245  {
3246  /*
3247  * This backend may have been slated to receive SIGUSR1 when
3248  * some background worker started or stopped. Cancel those
3249  * notifications, as we don't want to signal PIDs that are not
3250  * PostgreSQL backends. This gets skipped in the (probably
3251  * very common) case where the backend has never requested any
3252  * such notifications.
3253  */
3255  }
3256  dlist_delete(iter.cur);
3257  free(bp);
3258  break;
3259  }
3260  }
3261 }
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:493
bool bgworker_notify
Definition: postmaster.c:181
#define EXIT_STATUS_1(st)
Definition: postmaster.c:557
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:185
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:180
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int child_slot
Definition: postmaster.c:172
#define free(a)
Definition: header.h:65
pid_t pid
Definition: postmaster.c:170
static void HandleChildCrash(int pid, int exitstatus, const char *procname)
Definition: postmaster.c:3271
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3527
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:556

◆ CleanupBackgroundWorker()

static bool CleanupBackgroundWorker ( int  pid,
int  exitstatus 
)
static

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

3089 {
3090  char namebuf[MAXPGPATH];
3091  slist_mutable_iter iter;
3092 
3094  {
3095  RegisteredBgWorker *rw;
3096 
3097  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
3098 
3099  if (rw->rw_pid != pid)
3100  continue;
3101 
3102 #ifdef WIN32
3103  /* see CleanupBackend */
3104  if (exitstatus == ERROR_WAIT_NO_CHILDREN)
3105  exitstatus = 0;
3106 #endif
3107 
3108  snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
3109  rw->rw_worker.bgw_type);
3110 
3111 
3112  if (!EXIT_STATUS_0(exitstatus))
3113  {
3114  /* Record timestamp, so we know when to restart the worker. */
3116  }
3117  else
3118  {
3119  /* Zero exit status means terminate */
3120  rw->rw_crashed_at = 0;
3121  rw->rw_terminate = true;
3122  }
3123 
3124  /*
3125  * Additionally, for shared-memory-connected workers, just like a
3126  * backend, any exit status other than 0 or 1 is considered a crash
3127  * and causes a system-wide restart.
3128  */
3129  if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
3130  {
3131  if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
3132  {
3133  HandleChildCrash(pid, exitstatus, namebuf);
3134  return true;
3135  }
3136  }
3137 
3138  /*
3139  * We must release the postmaster child slot whether this worker is
3140  * connected to shared memory or not, but we only treat it as a crash
3141  * if it is in fact connected.
3142  */
3145  {
3146  HandleChildCrash(pid, exitstatus, namebuf);
3147  return true;
3148  }
3149 
3150  /* Get it out of the BackendList and clear out remaining data */
3151  dlist_delete(&rw->rw_backend->elem);
3152 #ifdef EXEC_BACKEND
3153  ShmemBackendArrayRemove(rw->rw_backend);
3154 #endif
3155 
3156  /*
3157  * It's possible that this background worker started some OTHER
3158  * background worker and asked to be notified when that worker started
3159  * or stopped. If so, cancel any notifications destined for the
3160  * now-dead backend.
3161  */
3162  if (rw->rw_backend->bgworker_notify)
3164  free(rw->rw_backend);
3165  rw->rw_backend = NULL;
3166  rw->rw_pid = 0;
3167  rw->rw_child_slot = 0;
3168  ReportBackgroundWorkerExit(&iter); /* report child death */
3169 
3170  LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
3171  namebuf, pid, exitstatus);
3172 
3173  return true;
3174  }
3175 
3176  return false;
3177 }
struct bkend * rw_backend
#define DEBUG1
Definition: elog.h:25
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
slist_node * cur
Definition: ilist.h:241
void ReportBackgroundWorkerExit(slist_mutable_iter *cur)
Definition: bgworker.c:459
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:182
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
void BackgroundWorkerStopNotifications(pid_t pid)
Definition: bgworker.c:493
bool bgworker_notify
Definition: postmaster.c:181
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
#define EXIT_STATUS_1(st)
Definition: postmaster.c:557
#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:3271
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3527
BackgroundWorker rw_worker
#define _(x)
Definition: elog.c:84
#define EXIT_STATUS_0(st)
Definition: postmaster.c:556

◆ ClosePostmasterPorts()

void ClosePostmasterPorts ( bool  am_syslogger)

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

2441 {
2442  int i;
2443 
2444 #ifndef WIN32
2445 
2446  /*
2447  * Close the write end of postmaster death watch pipe. It's important to
2448  * do this as early as possible, so that if postmaster dies, others won't
2449  * think that it's still running because we're holding the pipe open.
2450  */
2452  ereport(FATAL,
2454  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
2456 #endif
2457 
2458  /* Close the listen sockets */
2459  for (i = 0; i < MAXLISTEN; i++)
2460  {
2461  if (ListenSocket[i] != PGINVALID_SOCKET)
2462  {
2465  }
2466  }
2467 
2468  /* If using syslogger, close the read side of the pipe */
2469  if (!am_syslogger)
2470  {
2471 #ifndef WIN32
2472  if (syslogPipe[0] >= 0)
2473  close(syslogPipe[0]);
2474  syslogPipe[0] = -1;
2475 #else
2476  if (syslogPipe[0])
2477  CloseHandle(syslogPipe[0]);
2478  syslogPipe[0] = 0;
2479 #endif
2480  }
2481 
2482 #ifdef USE_BONJOUR
2483  /* If using Bonjour, close the connection to the mDNS daemon */
2484  if (bonjour_sdref)
2485  close(DNSServiceRefSockFD(bonjour_sdref));
2486 #endif
2487 }
void StreamClose(pgsocket sock)
Definition: pqcomm.c:844
#define FATAL
Definition: elog.h:52
bool am_syslogger
Definition: syslogger.c:75
#define POSTMASTER_FD_OWN
Definition: postmaster.h:44
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int postmaster_alive_fds[2]
Definition: postmaster.c:565
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:217
#define PGINVALID_SOCKET
Definition: port.h:33
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int i
#define close(a)
Definition: win32.h:12
#define MAXLISTEN
Definition: postmaster.c:216
int syslogPipe[2]
Definition: syslogger.c:113

◆ CloseServerPorts()

static void CloseServerPorts ( int  status,
Datum  arg 
)
static

Definition at line 1386 of file postmaster.c.

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

Referenced by PostmasterMain().

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

◆ ConnCreate()

static Port * ConnCreate ( int  serverFd)
static

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

2375 {
2376  Port *port;
2377 
2378  if (!(port = (Port *) calloc(1, sizeof(Port))))
2379  {
2380  ereport(LOG,
2381  (errcode(ERRCODE_OUT_OF_MEMORY),
2382  errmsg("out of memory")));
2383  ExitPostmaster(1);
2384  }
2385 
2386  if (StreamConnection(serverFd, port) != STATUS_OK)
2387  {
2388  if (port->sock != PGINVALID_SOCKET)
2389  StreamClose(port->sock);
2390  ConnFree(port);
2391  return NULL;
2392  }
2393 
2394  /*
2395  * Allocate GSSAPI specific state struct
2396  */
2397 #ifndef EXEC_BACKEND
2398 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2399  port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
2400  if (!port->gss)
2401  {
2402  ereport(LOG,
2403  (errcode(ERRCODE_OUT_OF_MEMORY),
2404  errmsg("out of memory")));
2405  ExitPostmaster(1);
2406  }
2407 #endif
2408 #endif
2409 
2410  return port;
2411 }
#define calloc(a, b)
Definition: header.h:55
void StreamClose(pgsocket sock)
Definition: pqcomm.c:844
static void ConnFree(Port *port)
Definition: postmaster.c:2418
int errcode(int sqlerrcode)
Definition: elog.c:575
Definition: libpq-be.h:116
#define LOG
Definition: elog.h:26
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:716
pgsocket sock
Definition: libpq-be.h:118
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:4968
#define ereport(elevel, rest)
Definition: elog.h:122
#define STATUS_OK
Definition: c.h:1008
static int port
Definition: pg_regress.c:90
#define PGINVALID_SOCKET
Definition: port.h:33
void * gss
Definition: libpq-be.h:175
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ ConnFree()

static void ConnFree ( Port port)
static

Definition at line 2418 of file postmaster.c.

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

Referenced by ConnCreate(), and ServerLoop().

2419 {
2420 #ifdef USE_SSL
2421  secure_close(conn);
2422 #endif
2423  if (conn->gss)
2424  free(conn->gss);
2425  free(conn);
2426 }
PGconn * conn
Definition: streamutil.c:55
#define free(a)
Definition: header.h:65
void secure_close(Port *port)
Definition: be-secure.c:130

◆ CountChildren()

static int CountChildren ( int  target)
static

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

5238 {
5239  dlist_iter iter;
5240  int cnt = 0;
5241 
5242  dlist_foreach(iter, &BackendList)
5243  {
5244  Backend *bp = dlist_container(Backend, elem, iter.cur);
5245 
5246  if (bp->dead_end)
5247  continue;
5248 
5249  /*
5250  * Since target == BACKEND_TYPE_ALL is the most common case, we test
5251  * it first and avoid touching shared memory for every child.
5252  */
5253  if (target != BACKEND_TYPE_ALL)
5254  {
5255  /*
5256  * Assign bkend_type for any recently announced WAL Sender
5257  * processes.
5258  */
5259  if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
5262 
5263  if (!(target & bp->bkend_type))
5264  continue;
5265  }
5266 
5267  cnt++;
5268  }
5269  return cnt;
5270 }
#define BACKEND_TYPE_ALL
Definition: postmaster.c:148
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:144
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:185
#define BACKEND_TYPE_WALSND
Definition: postmaster.c:146
bool dead_end
Definition: postmaster.c:180
int child_slot
Definition: postmaster.c:172
int bkend_type
Definition: postmaster.c:179
dlist_node * cur
Definition: ilist.h:161
bool IsPostmasterChildWalSender(int slot)
Definition: pmsignal.c:207

◆ CreateOptsFile()

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

Definition at line 5487 of file postmaster.c.

References elog, i, LOG, and OPTS_FILE.

Referenced by PostmasterMain().

5488 {
5489  FILE *fp;
5490  int i;
5491 
5492 #define OPTS_FILE "postmaster.opts"
5493 
5494  if ((fp = fopen(OPTS_FILE, "w")) == NULL)
5495  {
5496  elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
5497  return false;
5498  }
5499 
5500  fprintf(fp, "%s", fullprogname);
5501  for (i = 1; i < argc; i++)
5502  fprintf(fp, " \"%s\"", argv[i]);
5503  fputs("\n", fp);
5504 
5505  if (fclose(fp))
5506  {
5507  elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
5508  return false;
5509  }
5510 
5511  return true;
5512 }
#define LOG
Definition: elog.h:26
int i
#define elog
Definition: elog.h:219
#define OPTS_FILE

◆ DetermineSleepTime()

static void DetermineSleepTime ( struct timeval *  timeout)
static

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

1517 {
1518  TimestampTz next_wakeup = 0;
1519 
1520  /*
1521  * Normal case: either there are no background workers at all, or we're in
1522  * a shutdown sequence (during which we ignore bgworkers altogether).
1523  */
1524  if (Shutdown > NoShutdown ||
1526  {
1527  if (AbortStartTime != 0)
1528  {
1529  /* time left to abort; clamp to 0 in case it already expired */
1530  timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
1531  (time(NULL) - AbortStartTime);
1532  timeout->tv_sec = Max(timeout->tv_sec, 0);
1533  timeout->tv_usec = 0;
1534  }
1535  else
1536  {
1537  timeout->tv_sec = 60;
1538  timeout->tv_usec = 0;
1539  }
1540  return;
1541  }
1542 
1543  if (StartWorkerNeeded)
1544  {
1545  timeout->tv_sec = 0;
1546  timeout->tv_usec = 0;
1547  return;
1548  }
1549 
1550  if (HaveCrashedWorker)
1551  {
1552  slist_mutable_iter siter;
1553 
1554  /*
1555  * When there are crashed bgworkers, we sleep just long enough that
1556  * they are restarted when they request to be. Scan the list to
1557  * determine the minimum of all wakeup times according to most recent
1558  * crash time and requested restart interval.
1559  */
1561  {
1562  RegisteredBgWorker *rw;
1563  TimestampTz this_wakeup;
1564 
1565  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
1566 
1567  if (rw->rw_crashed_at == 0)
1568  continue;
1569 
1571  || rw->rw_terminate)
1572  {
1573  ForgetBackgroundWorker(&siter);
1574  continue;
1575  }
1576 
1577  this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
1578  1000L * rw->rw_worker.bgw_restart_time);
1579  if (next_wakeup == 0 || this_wakeup < next_wakeup)
1580  next_wakeup = this_wakeup;
1581  }
1582  }
1583 
1584  if (next_wakeup != 0)
1585  {
1586  long secs;
1587  int microsecs;
1588 
1590  &secs, &microsecs);
1591  timeout->tv_sec = secs;
1592  timeout->tv_usec = microsecs;
1593 
1594  /* Ensure we don't exceed one minute */
1595  if (timeout->tv_sec > 60)
1596  {
1597  timeout->tv_sec = 60;
1598  timeout->tv_usec = 0;
1599  }
1600  }
1601  else
1602  {
1603  timeout->tv_sec = 60;
1604  timeout->tv_usec = 0;
1605  }
1606 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:366
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
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:367
#define slist_foreach_modify(iter, lhead)
Definition: ilist.h:716
static int Shutdown
Definition: postmaster.c:276
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:347
#define Max(x, y)
Definition: c.h:851
#define NoShutdown
Definition: postmaster.c:271
BackgroundWorker rw_worker
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
static time_t AbortStartTime
Definition: postmaster.c:344

◆ do_start_bgworker()

static bool do_start_bgworker ( RegisteredBgWorker rw)
static

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

5626 {
5627  pid_t worker_pid;
5628 
5629  Assert(rw->rw_pid == 0);
5630 
5631  /*
5632  * Allocate and assign the Backend element. Note we must do this before
5633  * forking, so that we can handle out of memory properly.
5634  *
5635  * Treat failure as though the worker had crashed. That way, the
5636  * postmaster will wait a bit before attempting to start it again; if it
5637  * tried again right away, most likely it'd find itself repeating the
5638  * out-of-memory or fork failure condition.
5639  */
5640  if (!assign_backendlist_entry(rw))
5641  {
5643  return false;
5644  }
5645 
5646  ereport(DEBUG1,
5647  (errmsg("starting background worker process \"%s\"",
5648  rw->rw_worker.bgw_name)));
5649 
5650 #ifdef EXEC_BACKEND
5651  switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
5652 #else
5653  switch ((worker_pid = fork_process()))
5654 #endif
5655  {
5656  case -1:
5657  /* in postmaster, fork failed ... */
5658  ereport(LOG,
5659  (errmsg("could not fork worker process: %m")));
5660  /* undo what assign_backendlist_entry did */
5662  rw->rw_child_slot = 0;
5663  free(rw->rw_backend);
5664  rw->rw_backend = NULL;
5665  /* mark entry as crashed, so we'll try again later */
5667  break;
5668 
5669 #ifndef EXEC_BACKEND
5670  case 0:
5671  /* in postmaster child ... */
5673 
5674  /* Close the postmaster's sockets */
5675  ClosePostmasterPorts(false);
5676 
5677  /*
5678  * Before blowing away PostmasterContext, save this bgworker's
5679  * data where it can find it.
5680  */
5683  memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
5684 
5685  /* Release postmaster's working memory context */
5688  PostmasterContext = NULL;
5689 
5691 
5692  exit(1); /* should not get here */
5693  break;
5694 #endif
5695  default:
5696  /* in postmaster, fork successful ... */
5697  rw->rw_pid = worker_pid;
5698  rw->rw_backend->pid = rw->rw_pid;
5700  /* add new worker to lists of backends */
5702 #ifdef EXEC_BACKEND
5703  ShmemBackendArrayAdd(rw->rw_backend);
5704 #endif
5705  return true;
5706  }
5707 
5708  return false;
5709 }
struct bkend * rw_backend
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define DEBUG1
Definition: elog.h:25
void InitPostmasterChild(void)
Definition: miscinit.c:271
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
pid_t fork_process(void)
Definition: fork_process.c:31
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:191
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:182
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2440
void StartBackgroundWorker(void)
Definition: bgworker.c:708
void ReportBackgroundWorkerPID(RegisteredBgWorker *rw)
Definition: bgworker.c:440
static bool assign_backendlist_entry(RegisteredBgWorker *rw)
Definition: postmaster.c:5760
static dlist_head BackendList
Definition: postmaster.c:185
#define ereport(elevel, rest)
Definition: elog.h:122
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:699
pid_t pid
Definition: postmaster.c:170
int errmsg(const char *fmt,...)
Definition: elog.c:797
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 5177 of file postmaster.c.

Referenced by PostmasterMain().

5178 {
5179 }

◆ ExitPostmaster()

static void ExitPostmaster ( int  status)
static

Definition at line 4968 of file postmaster.c.

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

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

4969 {
4970 #ifdef HAVE_PTHREAD_IS_THREADED_NP
4971 
4972  /*
4973  * There is no known cause for a postmaster to become multithreaded after
4974  * startup. Recheck to account for the possibility of unknown causes.
4975  * This message uses LOG level, because an unclean shutdown at this point
4976  * would usually not look much different from a clean shutdown.
4977  */
4978  if (pthread_is_threaded_np() != 0)
4979  ereport(LOG,
4980  (errcode(ERRCODE_INTERNAL_ERROR),
4981  errmsg_internal("postmaster became multithreaded"),
4982  errdetail("Please report this to <pgsql-bugs@postgresql.org>.")));
4983 #endif
4984 
4985  /* should cleanup shared memory and kill all backends */
4986 
4987  /*
4988  * Not sure of the semantics here. When the Postmaster dies, should the
4989  * backends all be killed? probably not.
4990  *
4991  * MUST -- vadim 05-10-1999
4992  */
4993 
4994  proc_exit(status);
4995 }
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225

◆ getInstallationPaths()

static void getInstallationPaths ( const char *  argv0)
static

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

1435 {
1436  DIR *pdir;
1437 
1438  /* Locate the postgres executable itself */
1439  if (find_my_exec(argv0, my_exec_path) < 0)
1440  elog(FATAL, "%s: could not locate my own executable path", argv0);
1441 
1442 #ifdef EXEC_BACKEND
1443  /* Locate executable backend before we change working directory */
1444  if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
1445  postgres_exec_path) < 0)
1446  ereport(FATAL,
1447  (errmsg("%s: could not locate matching postgres executable",
1448  argv0)));
1449 #endif
1450 
1451  /*
1452  * Locate the pkglib directory --- this has to be set early in case we try
1453  * to load any modules from it in response to postgresql.conf entries.
1454  */
1456 
1457  /*
1458  * Verify that there's a readable directory there; otherwise the Postgres
1459  * installation is incomplete or corrupt. (A typical cause of this
1460  * failure is that the postgres executable has been moved or hardlinked to
1461  * some directory that's not a sibling of the installation lib/
1462  * directory.)
1463  */
1464  pdir = AllocateDir(pkglib_path);
1465  if (pdir == NULL)
1466  ereport(ERROR,
1468  errmsg("could not open directory \"%s\": %m",
1469  pkglib_path),
1470  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
1471  my_exec_path)));
1472  FreeDir(pdir);
1473 
1474  /*
1475  * XXX is it worth similarly checking the share/ directory? If the lib/
1476  * directory is there, then share/ probably is too.
1477  */
1478 }
int find_other_exec(const char *argv0, const char *target, const char *versionstr, char *retpath)
Definition: exec.c:307
static char * argv0
Definition: pg_ctl.c:94
int errhint(const char *fmt,...)
Definition: elog.c:987
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:119
int errcode_for_file_access(void)
Definition: elog.c:598
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2600
#define ereport(elevel, rest)
Definition: elog.h:122
char my_exec_path[MAXPGPATH]
Definition: globals.c:73
#define PG_BACKEND_VERSIONSTR
Definition: port.h:111
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
char pkglib_path[MAXPGPATH]
Definition: globals.c:74
int FreeDir(DIR *dir)
Definition: fd.c:2718

◆ HandleChildCrash()

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

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

3272 {
3273  dlist_mutable_iter iter;
3274  slist_iter siter;
3275  Backend *bp;
3276  bool take_action;
3277 
3278  /*
3279  * We only log messages and send signals if this is the first process
3280  * crash and we're not doing an immediate shutdown; otherwise, we're only
3281  * here to update postmaster's idea of live processes. If we have already
3282  * signalled children, nonzero exit status is to be expected, so don't
3283  * clutter log.
3284  */
3285  take_action = !FatalError && Shutdown != ImmediateShutdown;
3286 
3287  if (take_action)
3288  {
3289  LogChildExit(LOG, procname, pid, exitstatus);
3290  ereport(LOG,
3291  (errmsg("terminating any other active server processes")));
3292  }
3293 
3294  /* Process background workers. */
3296  {
3297  RegisteredBgWorker *rw;
3298 
3299  rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
3300  if (rw->rw_pid == 0)
3301  continue; /* not running */
3302  if (rw->rw_pid == pid)
3303  {
3304  /*
3305  * Found entry for freshly-dead worker, so remove it.
3306  */
3308  dlist_delete(&rw->rw_backend->elem);
3309 #ifdef EXEC_BACKEND
3310  ShmemBackendArrayRemove(rw->rw_backend);
3311 #endif
3312  free(rw->rw_backend);
3313  rw->rw_backend = NULL;
3314  rw->rw_pid = 0;
3315  rw->rw_child_slot = 0;
3316  /* don't reset crashed_at */
3317  /* don't report child stop, either */
3318  /* Keep looping so we can signal remaining workers */
3319  }
3320  else
3321  {
3322  /*
3323  * This worker is still alive. Unless we did so already, tell it
3324  * to commit hara-kiri.
3325  *
3326  * SIGQUIT is the special signal that says exit without proc_exit
3327  * and let the user know what's going on. But if SendStop is set
3328  * (-s on command line), then we send SIGSTOP instead, so that we
3329  * can get core dumps from all backends by hand.
3330  */
3331  if (take_action)
3332  {
3333  ereport(DEBUG2,
3334  (errmsg_internal("sending %s to process %d",
3335  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3336  (int) rw->rw_pid)));
3338  }
3339  }
3340  }
3341 
3342  /* Process regular backends */
3344  {
3345  bp = dlist_container(Backend, elem, iter.cur);
3346 
3347  if (bp->pid == pid)
3348  {
3349  /*
3350  * Found entry for freshly-dead backend, so remove it.
3351  */
3352  if (!bp->dead_end)
3353  {
3355 #ifdef EXEC_BACKEND
3356  ShmemBackendArrayRemove(bp);
3357 #endif
3358  }
3359  dlist_delete(iter.cur);
3360  free(bp);
3361  /* Keep looping so we can signal remaining backends */
3362  }
3363  else
3364  {
3365  /*
3366  * This backend is still alive. Unless we did so already, tell it
3367  * to commit hara-kiri.
3368  *
3369  * SIGQUIT is the special signal that says exit without proc_exit
3370  * and let the user know what's going on. But if SendStop is set
3371  * (-s on command line), then we send SIGSTOP instead, so that we
3372  * can get core dumps from all backends by hand.
3373  *
3374  * We could exclude dead_end children here, but at least in the
3375  * SIGSTOP case it seems better to include them.
3376  *
3377  * Background workers were already processed above; ignore them
3378  * here.
3379  */
3380  if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
3381  continue;
3382 
3383  if (take_action)
3384  {
3385  ereport(DEBUG2,
3386  (errmsg_internal("sending %s to process %d",
3387  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3388  (int) bp->pid)));
3389  signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
3390  }
3391  }
3392  }
3393 
3394  /* Take care of the startup process too */
3395  if (pid == StartupPID)
3396  {
3397  StartupPID = 0;
3399  }
3400  else if (StartupPID != 0 && take_action)
3401  {
3402  ereport(DEBUG2,
3403  (errmsg_internal("sending %s to process %d",
3404  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3405  (int) StartupPID)));
3408  }
3409 
3410  /* Take care of the bgwriter too */
3411  if (pid == BgWriterPID)
3412  BgWriterPID = 0;
3413  else if (BgWriterPID != 0 && take_action)
3414  {
3415  ereport(DEBUG2,
3416  (errmsg_internal("sending %s to process %d",
3417  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3418  (int) BgWriterPID)));
3420  }
3421 
3422  /* Take care of the checkpointer too */
3423  if (pid == CheckpointerPID)
3424  CheckpointerPID = 0;
3425  else if (CheckpointerPID != 0 && take_action)
3426  {
3427  ereport(DEBUG2,
3428  (errmsg_internal("sending %s to process %d",
3429  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3430  (int) CheckpointerPID)));
3432  }
3433 
3434  /* Take care of the walwriter too */
3435  if (pid == WalWriterPID)
3436  WalWriterPID = 0;
3437  else if (WalWriterPID != 0 && take_action)
3438  {
3439  ereport(DEBUG2,
3440  (errmsg_internal("sending %s to process %d",
3441  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3442  (int) WalWriterPID)));
3444  }
3445 
3446  /* Take care of the walreceiver too */
3447  if (pid == WalReceiverPID)
3448  WalReceiverPID = 0;
3449  else if (WalReceiverPID != 0 && take_action)
3450  {
3451  ereport(DEBUG2,
3452  (errmsg_internal("sending %s to process %d",
3453  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3454  (int) WalReceiverPID)));
3456  }
3457 
3458  /* Take care of the autovacuum launcher too */
3459  if (pid == AutoVacPID)
3460  AutoVacPID = 0;
3461  else if (AutoVacPID != 0 && take_action)
3462  {
3463  ereport(DEBUG2,
3464  (errmsg_internal("sending %s to process %d",
3465  (SendStop ? "SIGSTOP" : "SIGQUIT"),
3466  (int) AutoVacPID)));
3468  }
3469 
3470  /*
3471  * Force a power-cycle of the pgarch process too. (This isn't absolutely
3472  * necessary, but it seems like a good idea for robustness, and it
3473  * simplifies the state-machine logic in the case where a shutdown request
3474  * arrives during crash processing.)
3475  */
3476  if (PgArchPID != 0 && take_action)
3477  {
3478  ereport(DEBUG2,
3479  (errmsg_internal("sending %s to process %d",
3480  "SIGQUIT",
3481  (int) PgArchPID)));
3483  }
3484 
3485  /*
3486  * Force a power-cycle of the pgstat process too. (This isn't absolutely
3487  * necessary, but it seems like a good idea for robustness, and it
3488  * simplifies the state-machine logic in the case where a shutdown request
3489  * arrives during crash processing.)
3490  */
3491  if (PgStatPID != 0 && take_action)
3492  {
3493  ereport(DEBUG2,
3494  (errmsg_internal("sending %s to process %d",
3495  "SIGQUIT",
3496  (int) PgStatPID)));
3499  }
3500 
3501  /* We do NOT restart the syslogger */
3502 
3503  if (Shutdown != ImmediateShutdown)
3504  FatalError = true;
3505 
3506  /* We now transit into a state of waiting for children to die */
3507  if (pmState == PM_RECOVERY ||
3508  pmState == PM_HOT_STANDBY ||
3509  pmState == PM_RUN ||
3510  pmState == PM_WAIT_BACKUP ||
3512  pmState == PM_SHUTDOWN)
3514 
3515  /*
3516  * .. and if this doesn't happen quickly enough, now the clock is ticking
3517  * for us to kill them without mercy.
3518  */
3519  if (AbortStartTime == 0)
3520  AbortStartTime = time(NULL);
3521 }
struct bkend * rw_backend
#define SIGQUIT
Definition: win32_port.h:164
static StartupStatusEnum StartupStatus
Definition: postmaster.c:268
dlist_node * cur
Definition: ilist.h:180
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static pid_t PgStatPID
Definition: postmaster.c:256
slist_node * cur
Definition: ilist.h:226
static pid_t CheckpointerPID
Definition: postmaster.c:251
static pid_t WalReceiverPID
Definition: postmaster.c:253
static bool FatalError
Definition: postmaster.c:278
bool ReleasePostmasterChildSlot(int slot)
Definition: pmsignal.c:185
#define LOG
Definition: elog.h:26
dlist_node elem
Definition: postmaster.c:182
#define SIGSTOP
Definition: win32_port.h:170
static int Shutdown
Definition: postmaster.c:276
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static pid_t BgWriterPID
Definition: postmaster.c:250
static pid_t StartupPID
Definition: postmaster.c:249
static dlist_head BackendList
Definition: postmaster.c:185
slist_head BackgroundWorkerList
Definition: bgworker.c:43
#define DEBUG2
Definition: elog.h:24
bool dead_end
Definition: postmaster.c:180
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3854
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:147
int child_slot
Definition: postmaster.c:172
int bkend_type
Definition: postmaster.c:179
#define slist_container(type, membername, ptr)
Definition: ilist.h:674
static PMState pmState
Definition: postmaster.c:340
#define ImmediateShutdown
Definition: postmaster.c:274
#define free(a)
Definition: header.h:65
static pid_t WalWriterPID
Definition: postmaster.c:252
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
pid_t pid
Definition: postmaster.c:170
static pid_t AutoVacPID
Definition: postmaster.c:254
#define slist_foreach(iter, lhead)
Definition: ilist.h:700
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void LogChildExit(int lev, const char *procname, int pid, int exitstatus)
Definition: postmaster.c:3527
static int SendStop
Definition: postmaster.c:232
static time_t AbortStartTime
Definition: postmaster.c:344
void allow_immediate_pgstat_restart(void)
Definition: pgstat.c:790
static pid_t PgArchPID
Definition: postmaster.c:255

◆ initMasks()

static int initMasks ( fd_set *  rmask)
static

Definition at line 1854 of file postmaster.c.

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

Referenced by ServerLoop().

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

◆ InitPostmasterDeathWatchHandle()

static void InitPostmasterDeathWatchHandle ( void  )
static

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

6395 {
6396 #ifndef WIN32
6397 
6398  /*
6399  * Create a pipe. Postmaster holds the write end of the pipe open
6400  * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
6401  * the read file descriptor to select() to wake up in case postmaster
6402  * dies, or check for postmaster death with a (read() == 0). Children must
6403  * close the write end as soon as possible after forking, because EOF
6404  * won't be signaled in the read end until all processes have closed the
6405  * write fd. That is taken care of in ClosePostmasterPorts().
6406  */
6408  if (pipe(postmaster_alive_fds) < 0)
6409  ereport(FATAL,
6411  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
6412 
6413  /*
6414  * Set O_NONBLOCK to allow testing for the fd's presence with a read()
6415  * call.
6416  */
6417  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
6418  ereport(FATAL,
6420  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
6421 #else
6422 
6423  /*
6424  * On Windows, we use a process handle for the same purpose.
6425  */
6426  if (DuplicateHandle(GetCurrentProcess(),
6427  GetCurrentProcess(),
6428  GetCurrentProcess(),
6429  &PostmasterHandle,
6430  0,
6431  TRUE,
6432  DUPLICATE_SAME_ACCESS) == 0)
6433  ereport(FATAL,
6434  (errmsg_internal("could not duplicate postmaster handle: error code %lu",
6435  GetLastError())));
6436 #endif /* WIN32 */
6437 }
#define TRUE
Definition: ecpglib.h:35
int MyProcPid
Definition: globals.c:42
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int errcode_for_socket_access(void)
Definition: elog.c:669
pid_t PostmasterPid
Definition: globals.c:96
int postmaster_alive_fds[2]
Definition: postmaster.c:565
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
#define Assert(condition)
Definition: c.h:699
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:42

◆ LogChildExit()

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

Definition at line 3527 of file postmaster.c.

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

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

3528 {
3529  /*
3530  * size of activity_buffer is arbitrary, but set equal to default
3531  * track_activity_query_size
3532  */
3533  char activity_buffer[1024];
3534  const char *activity = NULL;
3535 
3536  if (!EXIT_STATUS_0(exitstatus))
3537  activity = pgstat_get_crashed_backend_activity(pid,
3538  activity_buffer,
3539  sizeof(activity_buffer));
3540 
3541  if (WIFEXITED(exitstatus))
3542  ereport(lev,
3543 
3544  /*------
3545  translator: %s is a noun phrase describing a child process, such as
3546  "server process" */
3547  (errmsg("%s (PID %d) exited with exit code %d",
3548  procname, pid, WEXITSTATUS(exitstatus)),
3549  activity ? errdetail("Failed process was running: %s", activity) : 0));
3550  else if (WIFSIGNALED(exitstatus))
3551 #if defined(WIN32)
3552  ereport(lev,
3553 
3554  /*------
3555  translator: %s is a noun phrase describing a child process, such as
3556  "server process" */
3557  (errmsg("%s (PID %d) was terminated by exception 0x%X",
3558  procname, pid, WTERMSIG(exitstatus)),
3559  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
3560  activity ? errdetail("Failed process was running: %s", activity) : 0));
3561 #elif defined(HAVE_DECL_SYS_SIGLIST) && HAVE_DECL_SYS_SIGLIST
3562  ereport(lev,
3563 
3564  /*------
3565  translator: %s is a noun phrase describing a child process, such as
3566  "server process" */
3567  (errmsg("%s (PID %d) was terminated by signal %d: %s",
3568  procname, pid, WTERMSIG(exitstatus),
3569  WTERMSIG(exitstatus) < NSIG ?
3570  sys_siglist[WTERMSIG(exitstatus)] : "(unknown)"),
3571  activity ? errdetail("Failed process was running: %s", activity) : 0));
3572 #else
3573  ereport(lev,
3574 
3575  /*------
3576  translator: %s is a noun phrase describing a child process, such as
3577  "server process" */
3578  (errmsg("%s (PID %d) was terminated by signal %d",
3579  procname, pid, WTERMSIG(exitstatus)),
3580  activity ? errdetail("Failed process was running: %s", activity) : 0));
3581 #endif
3582  else
3583  ereport(lev,
3584 
3585  /*------
3586  translator: %s is a noun phrase describing a child process, such as
3587  "server process" */
3588  (errmsg("%s (PID %d) exited with unrecognized status %d",
3589  procname, pid, exitstatus),
3590  activity ? errdetail("Failed process was running: %s", activity) : 0));
3591 }
int errhint(const char *fmt,...)
Definition: elog.c:987
#define WTERMSIG(w)
Definition: win32_port.h:150
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define WIFEXITED(w)
Definition: win32_port.h:147
int errmsg(const char *fmt,...)
Definition: elog.c:797
const char * pgstat_get_crashed_backend_activity(int pid, char *buffer, int buflen)
Definition: pgstat.c:4040
#define WIFSIGNALED(w)
Definition: win32_port.h:148
#define WEXITSTATUS(w)
Definition: win32_port.h:149
#define EXIT_STATUS_0(st)
Definition: postmaster.c:556

◆ MaxLivePostmasterChildren()

int MaxLivePostmasterChildren ( void  )

Definition at line 5527 of file postmaster.c.

References autovacuum_max_workers, max_worker_processes, and MaxConnections.

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

5528 {
5529  return 2 * (MaxConnections + autovacuum_max_workers + 1 +
5531 }
int MaxConnections
Definition: globals.c:133
int autovacuum_max_workers
Definition: autovacuum.c:114
int max_worker_processes
Definition: globals.c:134

◆ maybe_start_bgworkers()

static void maybe_start_bgworkers ( void  )
static

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

5812 {
5813 #define MAX_BGWORKERS_TO_LAUNCH 100
5814  int num_launched = 0;
5815  TimestampTz now = 0;
5816  slist_mutable_iter iter;
5817 
5818  /*
5819  * During crash recovery, we have no need to be called until the state
5820  * transition out of recovery.
5821  */
5822  if (FatalError)
5823  {
5824  StartWorkerNeeded = false;
5825  HaveCrashedWorker = false;
5826  return;
5827  }
5828 
5829  /* Don't need to be called again unless we find a reason for it below */
5830  StartWorkerNeeded = false;
5831  HaveCrashedWorker = false;
5832 
5834  {
5835  RegisteredBgWorker *rw;
5836 
5837  rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
5838 
5839  /* ignore if already running */
5840  if (rw->rw_pid != 0)
5841  continue;
5842 
5843  /* if marked for death, clean up and remove from list */
5844  if (rw->rw_terminate)
5845  {
5846  ForgetBackgroundWorker(&iter);
5847  continue;
5848  }
5849 
5850  /*
5851  * If this worker has crashed previously, maybe it needs to be
5852  * restarted (unless on registration it specified it doesn't want to
5853  * be restarted at all). Check how long ago did a crash last happen.
5854  * If the last crash is too recent, don't start it right away; let it
5855  * be restarted once enough time has passed.
5856  */
5857  if (rw->rw_crashed_at != 0)
5858  {
5860  {
5861  int notify_pid;
5862 
5863  notify_pid = rw->rw_worker.bgw_notify_pid;
5864 
5865  ForgetBackgroundWorker(&iter);
5866 
5867  /* Report worker is gone now. */
5868  if (notify_pid != 0)
5869  kill(notify_pid, SIGUSR1);
5870 
5871  continue;
5872  }
5873 
5874  /* read system time only when needed */
5875  if (now == 0)
5876  now = GetCurrentTimestamp();
5877 
5879  rw->rw_worker.bgw_restart_time * 1000))
5880  {
5881  /* Set flag to remember that we have workers to start later */
5882  HaveCrashedWorker = true;
5883  continue;
5884  }
5885  }
5886 
5888  {
5889  /* reset crash time before trying to start worker */
5890  rw->rw_crashed_at = 0;
5891 
5892  /*
5893  * Try to start the worker.
5894  *
5895  * On failure, give up processing workers for now, but set
5896  * StartWorkerNeeded so we'll come back here on the next iteration
5897  * of ServerLoop to try again. (We don't want to wait, because
5898  * there might be additional ready-to-run workers.) We could set
5899  * HaveCrashedWorker as well, since this worker is now marked
5900  * crashed, but there's no need because the next run of this
5901  * function will do that.
5902  */
5903  if (!do_start_bgworker(rw))
5904  {
5905  StartWorkerNeeded = true;
5906  return;
5907  }
5908 
5909  /*
5910  * If we've launched as many workers as allowed, quit, but have
5911  * ServerLoop call us again to look for additional ready-to-run
5912  * workers. There might not be any, but we'll find out the next
5913  * time we run.
5914  */
5915  if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
5916  {
5917  StartWorkerNeeded = true;
5918  return;
5919  }
5920  }
5921  }
5922 }
static volatile bool StartWorkerNeeded
Definition: postmaster.c:366
static bool bgworker_should_start_now(BgWorkerStartTime start_time)
Definition: postmaster.c:5716
#define SIGUSR1
Definition: win32_port.h:177
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
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:437
static bool FatalError
Definition: postmaster.c:278
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
static volatile bool HaveCrashedWorker
Definition: postmaster.c:367
#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:5625
#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:1534

◆ MaybeStartWalReceiver()

static void MaybeStartWalReceiver ( void  )
static

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

5471 {
5472  if (WalReceiverPID == 0 &&
5473  (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
5475  Shutdown == NoShutdown)
5476  {
5478  WalReceiverRequested = false;
5479  }
5480 }
static pid_t WalReceiverPID
Definition: postmaster.c:253
static volatile sig_atomic_t WalReceiverRequested
Definition: postmaster.c:363
static int Shutdown
Definition: postmaster.c:276
static PMState pmState
Definition: postmaster.c:340
#define NoShutdown
Definition: postmaster.c:271
#define StartWalReceiver()
Definition: postmaster.c:553

◆ pmdie()

static void pmdie ( SIGNAL_ARGS  )
static

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

2586 {
2587  int save_errno = errno;
2588 
2589  PG_SETMASK(&BlockSig);
2590 
2591  ereport(DEBUG2,
2592  (errmsg_internal("postmaster received signal %d",
2593  postgres_signal_arg)));
2594 
2595  switch (postgres_signal_arg)
2596  {
2597  case SIGTERM:
2598 
2599  /*
2600  * Smart Shutdown:
2601  *
2602  * Wait for children to end their work, then shut down.
2603  */
2604  if (Shutdown >= SmartShutdown)
2605  break;
2607  ereport(LOG,
2608  (errmsg("received smart shutdown request")));
2609 
2610  /* Report status */
2612 #ifdef USE_SYSTEMD
2613  sd_notify(0, "STOPPING=1");
2614 #endif
2615 
2616  if (pmState == PM_RUN || pmState == PM_RECOVERY ||
2618  {
2619  /* autovac workers are told to shut down immediately */
2620  /* and bgworkers too; does this need tweaking? */
2621  SignalSomeChildren(SIGTERM,
2623  /* and the autovac launcher too */
2624  if (AutoVacPID != 0)
2625  signal_child(AutoVacPID, SIGTERM);
2626  /* and the bgwriter too */
2627  if (BgWriterPID != 0)
2628  signal_child(BgWriterPID, SIGTERM);
2629  /* and the walwriter too */
2630  if (WalWriterPID != 0)
2631  signal_child(WalWriterPID, SIGTERM);
2632 
2633  /*
2634  * If we're in recovery, we can't kill the startup process
2635  * right away, because at present doing so does not release
2636  * its locks. We might want to change this in a future
2637  * release. For the time being, the PM_WAIT_READONLY state
2638  * indicates that we're waiting for the regular (read only)
2639  * backends to die off; once they do, we'll kill the startup
2640  * and walreceiver processes.
2641  */
2642  pmState = (pmState == PM_RUN) ?
2644  }
2645 
2646  /*
2647  * Now wait for online backup mode to end and backends to exit. If
2648  * that is already the case, PostmasterStateMachine will take the
2649  * next step.
2650  */
2652  break;
2653 
2654  case SIGINT:
2655 
2656  /*
2657  * Fast Shutdown:
2658  *
2659  * Abort all children with SIGTERM (rollback active transactions
2660  * and exit) and shut down when they are gone.
2661  */
2662  if (Shutdown >= FastShutdown)
2663  break;
2665  ereport(LOG,
2666  (errmsg("received fast shutdown request")));
2667 
2668  /* Report status */
2670 #ifdef USE_SYSTEMD
2671  sd_notify(0, "STOPPING=1");
2672 #endif
2673 
2674  if (StartupPID != 0)
2675  signal_child(StartupPID, SIGTERM);
2676  if (BgWriterPID != 0)
2677  signal_child(BgWriterPID, SIGTERM);
2678  if (WalReceiverPID != 0)
2679  signal_child(WalReceiverPID, SIGTERM);
2680  if (pmState == PM_RECOVERY)
2681  {
2683 
2684  /*
2685  * Only startup, bgwriter, walreceiver, possibly bgworkers,
2686  * and/or checkpointer should be active in this state; we just
2687  * signaled the first four, and we don't want to kill
2688  * checkpointer yet.
2689  */
2691  }
2692  else if (pmState == PM_RUN ||
2693  pmState == PM_WAIT_BACKUP ||
2697  {
2698  ereport(LOG,
2699  (errmsg("aborting any active transactions")));
2700  /* shut down all backends and workers */
2701  SignalSomeChildren(SIGTERM,
2704  /* and the autovac launcher too */
2705  if (AutoVacPID != 0)
2706  signal_child(AutoVacPID, SIGTERM);
2707  /* and the walwriter too */
2708  if (WalWriterPID != 0)
2709  signal_child(WalWriterPID, SIGTERM);
2711  }
2712 
2713  /*
2714  * Now wait for backends to exit. If there are none,
2715  * PostmasterStateMachine will take the next step.
2716  */
2718  break;
2719 
2720  case SIGQUIT:
2721 
2722  /*
2723  * Immediate Shutdown:
2724  *
2725  * abort all children with SIGQUIT, wait for them to exit,
2726  * terminate remaining ones with SIGKILL, then exit without
2727  * attempt to properly shut down the data base system.
2728  */
2729  if (Shutdown >= ImmediateShutdown)
2730  break;
2732  ereport(LOG,
2733  (errmsg("received immediate shutdown request")));
2734 
2735  /* Report status */
2737 #ifdef USE_SYSTEMD
2738  sd_notify(0, "STOPPING=1");
2739 #endif
2740 
2743 
2744  /* set stopwatch for them to die */
2745  AbortStartTime = time(NULL);
2746 
2747  /*
2748  * Now wait for backends to exit. If there are none,
2749  * PostmasterStateMachine will take the next step.
2750  */
2752  break;
2753  }
2754 
2756 
2757  errno = save_errno;
2758 }
static void PostmasterStateMachine(void)
Definition: postmaster.c:3600
#define SIGQUIT
Definition: win32_port.h:164
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1250
static pid_t WalReceiverPID
Definition: postmaster.c:253
static bool SignalSomeChildren(int signal, int targets)
Definition: postmaster.c:3880
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:144
#define LOG
Definition: elog.h:26
#define BACKEND_TYPE_AUTOVAC
Definition: postmaster.c:145
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
static int Shutdown
Definition: postmaster.c:276
static pid_t BgWriterPID
Definition: postmaster.c:250
static pid_t StartupPID
Definition: postmaster.c:249
#define SmartShutdown
Definition: postmaster.c:272
#define DEBUG2
Definition: elog.h:24
static void TerminateChildren(int signal)
Definition: postmaster.c:3924
#define FastShutdown
Definition: postmaster.c:273
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3854
#define ereport(elevel, rest)
Definition: elog.h:122
#define BACKEND_TYPE_BGWORKER
Definition: postmaster.c:147
sigset_t BlockSig
Definition: pqsignal.c:22
static PMState pmState
Definition: postmaster.c:340
#define ImmediateShutdown
Definition: postmaster.c:274
static pid_t WalWriterPID
Definition: postmaster.c:252
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static pid_t AutoVacPID
Definition: postmaster.c:254
int errmsg(const char *fmt,...)
Definition: elog.c:797
#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:344

◆ PostmasterMain()

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

Definition at line 575 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, free, get_stats_option_name(), GetConfigOption(), GetCurrentTimestamp(), getInstallationPaths(), getopt(), gettimeofday(), i, InitializeGUCOptions(), InitializeMaxBackends(), InitPostmasterDeathWatchHandle(), 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, MyStartTime, 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(), random_start_time, reaper(), Reinit, 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, SIGTTIN, SIGTTOU, SIGUSR1, sigusr1_handler(), SIGUSR2, snprintf(), SplitDirectoriesString(), SplitIdentifierString(), srandom(), 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().

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

◆ PostmasterMarkPIDForWorkerNotify()

bool PostmasterMarkPIDForWorkerNotify ( int  pid)

Definition at line 5930 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, 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, ShmemVariableCache, SIGCHLD, Port::sock, SpinlockSemaArray, strerror(), strlcpy(), syslogPipe, TRUE, UsedShmemSegAddr, UsedShmemSegID, and write_stderr.

Referenced by BackgroundWorkerStateChange().

5931 {
5932  dlist_iter iter;
5933  Backend *bp;
5934 
5935  dlist_foreach(iter, &BackendList)
5936  {
5937  bp = dlist_container(Backend, elem, iter.cur);
5938  if (bp->pid == pid)
5939  {
5940  bp->bgworker_notify = true;
5941  return true;
5942  }
5943  }
5944  return false;
5945 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
bool bgworker_notify
Definition: postmaster.c:181
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
static dlist_head BackendList
Definition: postmaster.c:185
dlist_node * cur
Definition: ilist.h:161
pid_t pid
Definition: postmaster.c:170

◆ PostmasterStateMachine()

static void PostmasterStateMachine ( void  )
static

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

3601 {
3602  if (pmState == PM_WAIT_BACKUP)
3603  {
3604  /*
3605  * PM_WAIT_BACKUP state ends when online backup mode is not active.
3606  */
3607  if (!BackupInProgress())
3609  }
3610 
3611  if (pmState == PM_WAIT_READONLY)
3612  {
3613  /*
3614  * PM_WAIT_READONLY state ends when we have no regular backends that
3615  * have been started during recovery. We kill the startup and
3616  * walreceiver processes and transition to PM_WAIT_BACKENDS. Ideally,
3617  * we might like to kill these processes first and then wait for
3618  * backends to die off, but that doesn't work at present because
3619  * killing the startup process doesn't release its locks.
3620  */
3622  {
3623  if (StartupPID != 0)
3624  signal_child(StartupPID, SIGTERM);
3625  if (WalReceiverPID != 0)
3626  signal_child(WalReceiverPID, SIGTERM);
3628  }
3629  }
3630 
3631  /*
3632  * If we are in a state-machine state that implies waiting for backends to
3633  * exit, see if they're all gone, and change state if so.
3634  */
3635  if (pmState == PM_WAIT_BACKENDS)
3636  {
3637  /*
3638  * PM_WAIT_BACKENDS state ends when we have no regular backends
3639  * (including autovac workers), no bgworkers (including unconnected
3640  * ones), and no walwriter, autovac launcher or bgwriter. If we are
3641  * doing crash recovery or an immediate shutdown then we expect the
3642  * checkpointer to exit as well, otherwise not. The archiver, stats,
3643  * and syslogger processes are disregarded since they are not
3644  * connected to shared memory; we also disregard dead_end children
3645  * here. Walsenders are also disregarded, they will be terminated
3646  * later after writing the checkpoint record, like the archiver
3647  * process.
3648  */
3650  StartupPID == 0 &&
3651  WalReceiverPID == 0 &&
3652  BgWriterPID == 0 &&
3653  (CheckpointerPID == 0 ||
3655  WalWriterPID == 0 &&
3656  AutoVacPID == 0)
3657  {
3659  {
3660  /*
3661  * Start waiting for dead_end children to die. This state
3662  * change causes ServerLoop to stop creating new ones.
3663  */
3665 
3666  /*
3667  * We already SIGQUIT'd the archiver and stats processes, if
3668  * any, when we started immediate shutdown or entered
3669  * FatalError state.
3670  */
3671  }
3672  else
3673  {
3674  /*
3675  * If we get here, we are proceeding with normal shutdown. All
3676  * the regular children are gone, and it's time to tell the
3677  * checkpointer to do a shutdown checkpoint.
3678  */
3680  /* Start the checkpointer if not running */
3681  if (CheckpointerPID == 0)
3683  /* And tell it to shut down */
3684  if (CheckpointerPID != 0)
3685  {
3687  pmState = PM_SHUTDOWN;
3688  }
3689  else
3690  {
3691  /*
3692  * If we failed to fork a checkpointer, just shut down.
3693  * Any required cleanup will happen at next restart. We
3694  * set FatalError so that an "abnormal shutdown" message
3695  * gets logged when we exit.
3696  */
3697  FatalError = true;
3699 
3700  /* Kill the walsenders, archiver and stats collector too */
3702  if (PgArchPID != 0)
3704  if (PgStatPID != 0)
3706  }
3707  }
3708  }
3709  }
3710 
3711  if (pmState == PM_SHUTDOWN_2)
3712  {
3713  /*
3714  * PM_SHUTDOWN_2 state ends when there's no other children than
3715  * dead_end children left. There shouldn't be any regular backends
3716  * left by now anyway; what we're really waiting for is walsenders and
3717  * archiver.
3718  *
3719  * Walreceiver should normally be dead by now, but not when a fast
3720  * shutdown is performed during recovery.
3721  */
3722  if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0 &&
3723  WalReceiverPID == 0)
3724  {
3726  }
3727  }
3728 
3729  if (pmState == PM_WAIT_DEAD_END)
3730  {
3731  /*
3732  * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
3733  * (ie, no dead_end children remain), and the archiver and stats
3734  * collector are gone too.
3735  *
3736  * The reason we wait for those two is to protect them against a new
3737  * postmaster starting conflicting subprocesses; this isn't an
3738  * ironclad protection, but it at least helps in the
3739  * shutdown-and-immediately-restart scenario. Note that they have
3740  * already been sent appropriate shutdown signals, either during a
3741  * normal state transition leading up to PM_WAIT_DEAD_END, or during
3742  * FatalError processing.
3743  */
3744  if (dlist_is_empty(&BackendList) &&
3745  PgArchPID == 0 && PgStatPID == 0)
3746  {
3747  /* These other guys should be dead already */
3748  Assert(StartupPID == 0);
3749  Assert(WalReceiverPID == 0);
3750  Assert(BgWriterPID == 0);
3751  Assert(CheckpointerPID == 0);
3752  Assert(WalWriterPID == 0);
3753  Assert(AutoVacPID == 0);
3754  /* syslogger is not considered here */
3756  }
3757  }
3758 
3759  /*
3760  * If we've been told to shut down, we exit as soon as there are no
3761  * remaining children. If there was a crash, cleanup will occur at the
3762  * next startup. (Before PostgreSQL 8.3, we tried to recover from the
3763  * crash before exiting, but that seems unwise if we are quitting because
3764  * we got SIGTERM from init --- there may well not be time for recovery
3765  * before init decides to SIGKILL us.)
3766  *
3767  * Note that the syslogger continues to run. It will exit when it sees
3768  * EOF on its input pipe, which happens when there are no more upstream
3769  * processes.
3770  */
3772  {
3773  if (FatalError)
3774  {
3775  ereport(LOG, (errmsg("abnormal database system shutdown")));
3776  ExitPostmaster(1);
3777  }
3778  else
3779  {
3780  /*
3781  * Terminate exclusive backup mode to avoid recovery after a clean
3782  * fast shutdown. Since an exclusive backup can only be taken
3783  * during normal running (and not, for example, while running
3784  * under Hot Standby) it only makes sense to do this if we reached
3785  * normal running. If we're still in recovery, the backup file is
3786  * one we're recovering *from*, and we must keep it around so that
3787  * recovery restarts from the right place.
3788  */
3790  CancelBackup();
3791 
3792  /* Normal exit from the postmaster is here */
3793  ExitPostmaster(0);
3794  }
3795  }
3796 
3797  /*
3798  * If the startup process failed, or the user does not want an automatic
3799  * restart after backend crashes, wait for all non-syslogger children to
3800  * exit, and then exit postmaster. We don't try to reinitialize when the
3801  * startup process fails, because more than likely it will just fail again
3802  * and we will keep trying forever.
3803  */
3804  if (pmState == PM_NO_CHILDREN &&
3806  ExitPostmaster(1);
3807 
3808  /*
3809  * If we need to recover from a crash, wait for all non-syslogger children
3810  * to exit, then reset shmem and StartupDataBase.
3811  */
3812  if (FatalError && pmState == PM_NO_CHILDREN)
3813  {
3814  ereport(LOG,
3815  (errmsg("all server processes terminated; reinitializing")));
3816 
3817  /* allow background workers to immediately restart */
3819 
3820  shmem_exit(1);
3821 
3822  /* re-read control file into local memory */
3824 
3826 
3828  Assert(StartupPID != 0);
3830  pmState = PM_STARTUP;
3831  /* crash recovery started, reset SIGKILL flag */
3832  AbortStartTime = 0;
3833  }
3834 }
void CancelBackup(void)
Definition: xlog.c:11499
#define SIGQUIT
Definition: win32_port.h:164
static StartupStatusEnum StartupStatus
Definition: postmaster.c:268
#define BACKEND_TYPE_ALL
Definition: postmaster.c:148
#define StartupDataBase()
Definition: postmaster.c:549
static pid_t PgStatPID
Definition: postmaster.c:256
static pid_t CheckpointerPID
Definition: postmaster.c:251
static pid_t WalReceiverPID
Definition: postmaster.c:253
static bool FatalError
Definition: postmaster.c:278
void shmem_exit(int code)
Definition: ipc.c:224
#define BACKEND_TYPE_NORMAL
Definition: postmaster.c:144
#define SIGUSR2
Definition: win32_port.h:178
#define LOG
Definition: elog.h:26
bool BackupInProgress(void)
Definition: xlog.c:11479
void ResetBackgroundWorkerCrashTimes(void)
Definition: bgworker.c:515
#define SignalChildren(sig)
Definition: postmaster.c:427
static int Shutdown
Definition: postmaster.c:276
static pid_t BgWriterPID
Definition: postmaster.c:250
#define StartCheckpointer()
Definition: postmaster.c:551
static int CountChildren(int target)
Definition: postmaster.c:5237
static pid_t StartupPID
Definition: postmaster.c:249
int PostPortNumber
Definition: postmaster.c:196
static void ExitPostmaster(int status) pg_attribute_noreturn()
Definition: postmaster.c:4968
bool restart_after_crash
Definition: postmaster.c:246
static dlist_head BackendList
Definition: postmaster.c:185
void LocalProcessControlFile(bool reset)
Definition: xlog.c:4851
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3854
#define ereport(elevel, rest)
Definition: elog.h:122
static PMState pmState
Definition: postmaster.c:340
#define BACKEND_TYPE_WORKER
Definition: postmaster.c:150
#define ImmediateShutdown
Definition: postmaster.c:274
static void reset_shared(int port)
Definition: postmaster.c:2494
static pid_t WalWriterPID
Definition: postmaster.c:252
#define Assert(condition)
Definition: c.h:699
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
#define NoShutdown
Definition: postmaster.c:271
static pid_t AutoVacPID
Definition: postmaster.c:254
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool ReachedNormalRunning
Definition: postmaster.c:349
static time_t AbortStartTime
Definition: postmaster.c:344
static pid_t PgArchPID
Definition: postmaster.c:255

◆ processCancelRequest()

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

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

2260 {
2261  CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
2262  int backendPID;
2263  int32 cancelAuthCode;
2264  Backend *bp;
2265 
2266 #ifndef EXEC_BACKEND
2267  dlist_iter iter;
2268 #else
2269  int i;
2270 #endif
2271 
2272  backendPID = (int) pg_ntoh32(canc->backendPID);
2273  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
2274 
2275  /*
2276  * See if we have a matching backend. In the EXEC_BACKEND case, we can no
2277  * longer access the postmaster's own backend list, and must rely on the
2278  * duplicate array in shared memory.
2279  */
2280 #ifndef EXEC_BACKEND
2281  dlist_foreach(iter, &BackendList)
2282  {
2283  bp = dlist_container(Backend, elem, iter.cur);
2284 #else
2285  for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
2286  {
2287  bp = (Backend *) &ShmemBackendArray[i];
2288 #endif
2289  if (bp->pid == backendPID)
2290  {
2291  if (bp->cancel_key == cancelAuthCode)
2292  {
2293  /* Found a match; signal that backend to cancel current op */
2294  ereport(DEBUG2,
2295  (errmsg_internal("processing cancel request: sending SIGINT to process %d",
2296  backendPID)));
2297  signal_child(bp->pid, SIGINT);
2298  }
2299  else
2300  /* Right PID, wrong key: no way, Jose */
2301  ereport(LOG,
2302  (errmsg("wrong key in cancel request for process %d",
2303  backendPID)));
2304  return;
2305  }
2306  }
2307 
2308  /* No matching backend */
2309  ereport(LOG,
2310  (errmsg("PID %d in cancel request did not match any process",
2311  backendPID)));
2312 }
#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:313
#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:185
#define DEBUG2
Definition: elog.h:24
int32 cancel_key
Definition: postmaster.c:171
static void signal_child(pid_t pid, int signal)
Definition: postmaster.c:3854
#define ereport(elevel, rest)
Definition: elog.h:122
dlist_node * cur
Definition: ilist.h:161
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int MaxLivePostmasterChildren(void)
Definition: postmaster.c:5527
pid_t pid
Definition: postmaster.c:170
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i

◆ ProcessStartupPacket()

static int ProcessStartupPacket ( Port port,
bool  SSLdone 
)
static

Definition at line 1889 of file postmaster.c.

References SockAddr::addr, am_db_walsender, am_walsender, 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_SSL_CODE, NIL, StartupPacket::options, palloc0(), parse_bool(), 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_server(), send, SendNegotiateProtocolVersion(), Port::sock, STATUS_ERROR, STATUS_OK, TopMemoryContext, StartupPacket::user, and Port::user_name.

Referenced by BackendInitialize().

1890 {
1891  int32 len;
1892  void *buf;
1893  ProtocolVersion proto;
1894  MemoryContext oldcontext;
1895 
1896  pq_startmsgread();
1897  if (pq_getbytes((char *) &len, 4) == EOF)
1898  {
1899  /*
1900  * EOF after SSLdone probably means the client didn't like our
1901  * response to NEGOTIATE_SSL_CODE. That's not an error condition, so
1902  * don't clutter the log with a complaint.
1903  */
1904  if (!SSLdone)
1906  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1907  errmsg("incomplete startup packet")));
1908  return STATUS_ERROR;
1909  }
1910 
1911  len = pg_ntoh32(len);
1912  len -= 4;
1913 
1914  if (len < (int32) sizeof(ProtocolVersion) ||
1916  {
1918  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1919  errmsg("invalid length of startup packet")));
1920  return STATUS_ERROR;
1921  }
1922 
1923  /*
1924  * Allocate at least the size of an old-style startup packet, plus one
1925  * extra byte, and make sure all are zeroes. This ensures we will have
1926  * null termination of all strings, in both fixed- and variable-length
1927  * packet layouts.
1928  */
1929  if (len <= (int32) sizeof(StartupPacket))
1930  buf = palloc0(sizeof(StartupPacket) + 1);
1931  else
1932  buf = palloc0(len + 1);
1933 
1934  if (pq_getbytes(buf, len) == EOF)
1935  {
1937  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1938  errmsg("incomplete startup packet")));
1939  return STATUS_ERROR;
1940  }
1941  pq_endmsgread();
1942 
1943  /*
1944  * The first field is either a protocol version number or a special
1945  * request code.
1946  */
1947  port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
1948 
1949  if (proto == CANCEL_REQUEST_CODE)
1950  {
1951  processCancelRequest(port, buf);
1952  /* Not really an error, but we don't want to proceed further */